@cuadra-ai/uikit 0.1.15 → 0.1.16
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","sources":["../node_modules/lucide-react/dist/esm/shared/src/utils.js","../node_modules/lucide-react/dist/esm/defaultAttributes.js","../node_modules/lucide-react/dist/esm/Icon.js","../node_modules/lucide-react/dist/esm/createLucideIcon.js","../node_modules/lucide-react/dist/esm/icons/arrow-up.js","../node_modules/lucide-react/dist/esm/icons/check.js","../node_modules/lucide-react/dist/esm/icons/chevron-down.js","../node_modules/lucide-react/dist/esm/icons/contrast.js","../node_modules/lucide-react/dist/esm/icons/copy.js","../node_modules/lucide-react/dist/esm/icons/ellipsis-vertical.js","../node_modules/lucide-react/dist/esm/icons/loader-circle.js","../node_modules/lucide-react/dist/esm/icons/menu.js","../node_modules/lucide-react/dist/esm/icons/plus.js","../src/lib/cuadraChatClient.ts","../src/adapters/messageConverter.ts","../src/adapters/chatModelAdapter.ts","../src/adapters/threadListAdapter.tsx","../src/components/CuadraRuntimeProvider.tsx","../node_modules/ccount/index.js","../node_modules/micromark-util-character/index.js","../node_modules/mdast-util-find-and-replace/node_modules/escape-string-regexp/index.js","../node_modules/unist-util-is/lib/index.js","../node_modules/unist-util-visit-parents/lib/index.js","../node_modules/mdast-util-find-and-replace/lib/index.js","../node_modules/mdast-util-gfm-autolink-literal/lib/index.js","../node_modules/micromark-util-normalize-identifier/index.js","../node_modules/mdast-util-gfm-footnote/lib/index.js","../node_modules/mdast-util-gfm-strikethrough/lib/index.js","../node_modules/markdown-table/index.js","../node_modules/mdast-util-to-markdown/lib/handle/blockquote.js","../node_modules/mdast-util-to-markdown/lib/util/pattern-in-scope.js","../node_modules/mdast-util-to-markdown/lib/handle/break.js","../node_modules/longest-streak/index.js","../node_modules/mdast-util-to-markdown/lib/util/format-code-as-indented.js","../node_modules/mdast-util-to-markdown/lib/util/check-fence.js","../node_modules/mdast-util-to-markdown/lib/handle/code.js","../node_modules/mdast-util-to-markdown/lib/util/check-quote.js","../node_modules/mdast-util-to-markdown/lib/handle/definition.js","../node_modules/mdast-util-to-markdown/lib/util/check-emphasis.js","../node_modules/mdast-util-to-markdown/lib/util/encode-character-reference.js","../node_modules/micromark-util-classify-character/index.js","../node_modules/mdast-util-to-markdown/lib/util/encode-info.js","../node_modules/mdast-util-to-markdown/lib/handle/emphasis.js","../node_modules/unist-util-visit/lib/index.js","../node_modules/mdast-util-to-string/lib/index.js","../node_modules/mdast-util-to-markdown/lib/util/format-heading-as-setext.js","../node_modules/mdast-util-to-markdown/lib/handle/heading.js","../node_modules/mdast-util-to-markdown/lib/handle/html.js","../node_modules/mdast-util-to-markdown/lib/handle/image.js","../node_modules/mdast-util-to-markdown/lib/handle/image-reference.js","../node_modules/mdast-util-to-markdown/lib/handle/inline-code.js","../node_modules/mdast-util-to-markdown/lib/util/format-link-as-autolink.js","../node_modules/mdast-util-to-markdown/lib/handle/link.js","../node_modules/mdast-util-to-markdown/lib/handle/link-reference.js","../node_modules/mdast-util-to-markdown/lib/util/check-bullet.js","../node_modules/mdast-util-to-markdown/lib/util/check-bullet-other.js","../node_modules/mdast-util-to-markdown/lib/util/check-bullet-ordered.js","../node_modules/mdast-util-to-markdown/lib/util/check-rule.js","../node_modules/mdast-util-to-markdown/lib/handle/list.js","../node_modules/mdast-util-to-markdown/lib/util/check-list-item-indent.js","../node_modules/mdast-util-to-markdown/lib/handle/list-item.js","../node_modules/mdast-util-to-markdown/lib/handle/paragraph.js","../node_modules/mdast-util-phrasing/lib/index.js","../node_modules/mdast-util-to-markdown/lib/handle/root.js","../node_modules/mdast-util-to-markdown/lib/util/check-strong.js","../node_modules/mdast-util-to-markdown/lib/handle/strong.js","../node_modules/mdast-util-to-markdown/lib/handle/text.js","../node_modules/mdast-util-to-markdown/lib/util/check-rule-repetition.js","../node_modules/mdast-util-to-markdown/lib/handle/thematic-break.js","../node_modules/mdast-util-to-markdown/lib/handle/index.js","../node_modules/mdast-util-gfm-table/lib/index.js","../node_modules/mdast-util-gfm-task-list-item/lib/index.js","../node_modules/mdast-util-gfm/lib/index.js","../node_modules/micromark-util-chunked/index.js","../node_modules/micromark-util-combine-extensions/index.js","../node_modules/micromark-extension-gfm-autolink-literal/lib/syntax.js","../node_modules/micromark-util-resolve-all/index.js","../node_modules/micromark-factory-space/index.js","../node_modules/micromark-core-commonmark/lib/blank-line.js","../node_modules/micromark-extension-gfm-footnote/lib/syntax.js","../node_modules/micromark-extension-gfm-strikethrough/lib/syntax.js","../node_modules/micromark-extension-gfm-table/lib/edit-map.js","../node_modules/micromark-extension-gfm-table/lib/infer.js","../node_modules/micromark-extension-gfm-table/lib/syntax.js","../node_modules/micromark-extension-gfm-task-list-item/lib/syntax.js","../node_modules/micromark-extension-gfm/index.js","../node_modules/remark-gfm/lib/index.js","../src/utils/cn.ts","../src/components/MarkdownText.tsx","../src/components/FakeReasoningLoader.tsx","../src/components/SimpleThread.tsx","../src/components/SimpleThreadList.tsx","../src/widget/components/TexturedCard.tsx","../src/widget/components/ThemeToggle.tsx","../src/widget/components/ChatHeader.tsx","../src/widget/context/CuadraWidgetContext.tsx","../src/utils/useInjectStyles.ts","../src/components/WidgetContent.tsx","../src/components/CuadraChat.tsx"],"sourcesContent":["/**\n * @license lucide-react v0.555.0 - ISC\n *\n * This source code is licensed under the ISC license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nconst toKebabCase = (string) => string.replace(/([a-z0-9])([A-Z])/g, \"$1-$2\").toLowerCase();\nconst toCamelCase = (string) => string.replace(\n /^([A-Z])|[\\s-_]+(\\w)/g,\n (match, p1, p2) => p2 ? p2.toUpperCase() : p1.toLowerCase()\n);\nconst toPascalCase = (string) => {\n const camelCase = toCamelCase(string);\n return camelCase.charAt(0).toUpperCase() + camelCase.slice(1);\n};\nconst mergeClasses = (...classes) => classes.filter((className, index, array) => {\n return Boolean(className) && className.trim() !== \"\" && array.indexOf(className) === index;\n}).join(\" \").trim();\nconst hasA11yProp = (props) => {\n for (const prop in props) {\n if (prop.startsWith(\"aria-\") || prop === \"role\" || prop === \"title\") {\n return true;\n }\n }\n};\n\nexport { hasA11yProp, mergeClasses, toCamelCase, toKebabCase, toPascalCase };\n//# sourceMappingURL=utils.js.map\n","/**\n * @license lucide-react v0.555.0 - ISC\n *\n * This source code is licensed under the ISC license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nvar defaultAttributes = {\n xmlns: \"http://www.w3.org/2000/svg\",\n width: 24,\n height: 24,\n viewBox: \"0 0 24 24\",\n fill: \"none\",\n stroke: \"currentColor\",\n strokeWidth: 2,\n strokeLinecap: \"round\",\n strokeLinejoin: \"round\"\n};\n\nexport { defaultAttributes as default };\n//# sourceMappingURL=defaultAttributes.js.map\n","/**\n * @license lucide-react v0.555.0 - ISC\n *\n * This source code is licensed under the ISC license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport { forwardRef, createElement } from 'react';\nimport defaultAttributes from './defaultAttributes.js';\nimport { mergeClasses, hasA11yProp } from './shared/src/utils.js';\n\nconst Icon = forwardRef(\n ({\n color = \"currentColor\",\n size = 24,\n strokeWidth = 2,\n absoluteStrokeWidth,\n className = \"\",\n children,\n iconNode,\n ...rest\n }, ref) => createElement(\n \"svg\",\n {\n ref,\n ...defaultAttributes,\n width: size,\n height: size,\n stroke: color,\n strokeWidth: absoluteStrokeWidth ? Number(strokeWidth) * 24 / Number(size) : strokeWidth,\n className: mergeClasses(\"lucide\", className),\n ...!children && !hasA11yProp(rest) && { \"aria-hidden\": \"true\" },\n ...rest\n },\n [\n ...iconNode.map(([tag, attrs]) => createElement(tag, attrs)),\n ...Array.isArray(children) ? children : [children]\n ]\n )\n);\n\nexport { Icon as default };\n//# sourceMappingURL=Icon.js.map\n","/**\n * @license lucide-react v0.555.0 - ISC\n *\n * This source code is licensed under the ISC license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport { forwardRef, createElement } from 'react';\nimport { mergeClasses, toKebabCase, toPascalCase } from './shared/src/utils.js';\nimport Icon from './Icon.js';\n\nconst createLucideIcon = (iconName, iconNode) => {\n const Component = forwardRef(\n ({ className, ...props }, ref) => createElement(Icon, {\n ref,\n iconNode,\n className: mergeClasses(\n `lucide-${toKebabCase(toPascalCase(iconName))}`,\n `lucide-${iconName}`,\n className\n ),\n ...props\n })\n );\n Component.displayName = toPascalCase(iconName);\n return Component;\n};\n\nexport { createLucideIcon as default };\n//# sourceMappingURL=createLucideIcon.js.map\n","/**\n * @license lucide-react v0.555.0 - ISC\n *\n * This source code is licensed under the ISC license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport createLucideIcon from '../createLucideIcon.js';\n\nconst __iconNode = [\n [\"path\", { d: \"m5 12 7-7 7 7\", key: \"hav0vg\" }],\n [\"path\", { d: \"M12 19V5\", key: \"x0mq9r\" }]\n];\nconst ArrowUp = createLucideIcon(\"arrow-up\", __iconNode);\n\nexport { __iconNode, ArrowUp as default };\n//# sourceMappingURL=arrow-up.js.map\n","/**\n * @license lucide-react v0.555.0 - ISC\n *\n * This source code is licensed under the ISC license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport createLucideIcon from '../createLucideIcon.js';\n\nconst __iconNode = [[\"path\", { d: \"M20 6 9 17l-5-5\", key: \"1gmf2c\" }]];\nconst Check = createLucideIcon(\"check\", __iconNode);\n\nexport { __iconNode, Check as default };\n//# sourceMappingURL=check.js.map\n","/**\n * @license lucide-react v0.555.0 - ISC\n *\n * This source code is licensed under the ISC license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport createLucideIcon from '../createLucideIcon.js';\n\nconst __iconNode = [[\"path\", { d: \"m6 9 6 6 6-6\", key: \"qrunsl\" }]];\nconst ChevronDown = createLucideIcon(\"chevron-down\", __iconNode);\n\nexport { __iconNode, ChevronDown as default };\n//# sourceMappingURL=chevron-down.js.map\n","/**\n * @license lucide-react v0.555.0 - ISC\n *\n * This source code is licensed under the ISC license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport createLucideIcon from '../createLucideIcon.js';\n\nconst __iconNode = [\n [\"circle\", { cx: \"12\", cy: \"12\", r: \"10\", key: \"1mglay\" }],\n [\"path\", { d: \"M12 18a6 6 0 0 0 0-12v12z\", key: \"j4l70d\" }]\n];\nconst Contrast = createLucideIcon(\"contrast\", __iconNode);\n\nexport { __iconNode, Contrast as default };\n//# sourceMappingURL=contrast.js.map\n","/**\n * @license lucide-react v0.555.0 - ISC\n *\n * This source code is licensed under the ISC license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport createLucideIcon from '../createLucideIcon.js';\n\nconst __iconNode = [\n [\"rect\", { width: \"14\", height: \"14\", x: \"8\", y: \"8\", rx: \"2\", ry: \"2\", key: \"17jyea\" }],\n [\"path\", { d: \"M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2\", key: \"zix9uf\" }]\n];\nconst Copy = createLucideIcon(\"copy\", __iconNode);\n\nexport { __iconNode, Copy as default };\n//# sourceMappingURL=copy.js.map\n","/**\n * @license lucide-react v0.555.0 - ISC\n *\n * This source code is licensed under the ISC license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport createLucideIcon from '../createLucideIcon.js';\n\nconst __iconNode = [\n [\"circle\", { cx: \"12\", cy: \"12\", r: \"1\", key: \"41hilf\" }],\n [\"circle\", { cx: \"12\", cy: \"5\", r: \"1\", key: \"gxeob9\" }],\n [\"circle\", { cx: \"12\", cy: \"19\", r: \"1\", key: \"lyex9k\" }]\n];\nconst EllipsisVertical = createLucideIcon(\"ellipsis-vertical\", __iconNode);\n\nexport { __iconNode, EllipsisVertical as default };\n//# sourceMappingURL=ellipsis-vertical.js.map\n","/**\n * @license lucide-react v0.555.0 - ISC\n *\n * This source code is licensed under the ISC license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport createLucideIcon from '../createLucideIcon.js';\n\nconst __iconNode = [[\"path\", { d: \"M21 12a9 9 0 1 1-6.219-8.56\", key: \"13zald\" }]];\nconst LoaderCircle = createLucideIcon(\"loader-circle\", __iconNode);\n\nexport { __iconNode, LoaderCircle as default };\n//# sourceMappingURL=loader-circle.js.map\n","/**\n * @license lucide-react v0.555.0 - ISC\n *\n * This source code is licensed under the ISC license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport createLucideIcon from '../createLucideIcon.js';\n\nconst __iconNode = [\n [\"path\", { d: \"M4 5h16\", key: \"1tepv9\" }],\n [\"path\", { d: \"M4 12h16\", key: \"1lakjw\" }],\n [\"path\", { d: \"M4 19h16\", key: \"1djgab\" }]\n];\nconst Menu = createLucideIcon(\"menu\", __iconNode);\n\nexport { __iconNode, Menu as default };\n//# sourceMappingURL=menu.js.map\n","/**\n * @license lucide-react v0.555.0 - ISC\n *\n * This source code is licensed under the ISC license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport createLucideIcon from '../createLucideIcon.js';\n\nconst __iconNode = [\n [\"path\", { d: \"M5 12h14\", key: \"1ays0h\" }],\n [\"path\", { d: \"M12 5v14\", key: \"s699le\" }]\n];\nconst Plus = createLucideIcon(\"plus\", __iconNode);\n\nexport { __iconNode, Plus as default };\n//# sourceMappingURL=plus.js.map\n","import type {\n ChatOut,\n ChatRequest,\n ChatSummaryPage,\n ChatUpdate,\n ListChatsParams,\n ListModelsParams,\n ModelOut,\n ModelPage,\n} from '../types/cuadra';\n\n/**\n * SSE Chunk types for streaming responses\n */\nexport interface SSEChunk {\n type?: string;\n content?: string;\n chatId?: string;\n id?: string; // Chat/message ID\n delta?: string; // Delta content (incremental text)\n finished?: boolean; // Whether the stream is finished\n message?: {\n role: string;\n content: string;\n };\n usage?: {\n inputTokens: number;\n outputTokens: number;\n totalTokens: number;\n cost?: number | null;\n };\n done?: boolean;\n}\n\n/**\n * CuadraChatClient - API client for Cuadra AI REST API\n * Handles authentication, HTTP requests, and SSE streaming\n */\nexport class CuadraChatClient {\n private baseUrl: string;\n private sessionToken: string | null = null;\n private isProxyMode: boolean = false;\n\n constructor(baseUrl: string, sessionToken?: string, isProxyMode: boolean = false) {\n this.baseUrl = baseUrl.replace(/\\/$/, ''); // Remove trailing slash\n this.isProxyMode = isProxyMode;\n if (sessionToken) {\n this.sessionToken = sessionToken;\n }\n }\n\n /**\n * Set or update the session token\n */\n setSessionToken(token: string | null): void {\n this.sessionToken = token;\n }\n\n /**\n * Create or continue a chat with streaming support\n * Returns a ReadableStream for SSE parsing\n */\n private getUrl(endpoint: string): string {\n if (this.isProxyMode) {\n // Proxy mode: remove /v1 prefix\n const path = `${this.baseUrl}${endpoint.replace('/v1', '')}`;\n // If baseUrl is relative, return as-is; otherwise construct full URL\n if (path.startsWith('/') || path.startsWith('./')) {\n return path;\n }\n return path;\n }\n return `${this.baseUrl}${endpoint}`;\n }\n\n async createOrContinueChat(\n request: ChatRequest,\n abortSignal?: AbortSignal,\n ): Promise<ReadableStream<Uint8Array>> {\n const url = this.getUrl('/v1/chats');\n \n // Generate idempotency key for create operation\n const idempotencyKey = this.generateIdempotencyKey();\n \n const headers: Record<string, string> = {\n 'Content-Type': 'application/json',\n 'Idempotency-Key': idempotencyKey,\n };\n\n if (this.sessionToken) {\n headers['Authorization'] = `Bearer ${this.sessionToken}`;\n }\n\n // Ensure stream is true for streaming\n const body: ChatRequest = {\n ...request,\n stream: true,\n };\n\n const response = await fetch(url, {\n method: 'POST',\n headers,\n body: JSON.stringify(body),\n signal: abortSignal,\n });\n\n if (!response.ok) {\n const errorData = await response.json().catch(() => ({}));\n throw new Error(\n errorData.detail ||\n errorData.message ||\n `API error: ${response.status} ${response.statusText}`,\n );\n }\n\n if (!response.body) {\n throw new Error('Response body is null');\n }\n\n return response.body;\n }\n\n /**\n * Get a specific chat by ID\n */\n async getChat(chatId: string): Promise<ChatOut> {\n const url = this.getUrl(`/v1/chats/${chatId}`);\n const headers: Record<string, string> = {\n 'Content-Type': 'application/json',\n };\n\n if (this.sessionToken) {\n headers['Authorization'] = `Bearer ${this.sessionToken}`;\n }\n\n const response = await fetch(url, {\n method: 'GET',\n headers,\n });\n\n if (!response.ok) {\n const errorData = await response.json().catch(() => ({}));\n throw new Error(\n errorData.detail ||\n errorData.message ||\n `API error: ${response.status} ${response.statusText}`,\n );\n }\n\n return response.json();\n }\n\n /**\n * List chats with pagination\n */\n async listChats(params?: ListChatsParams): Promise<ChatSummaryPage> {\n const baseUrl = this.getUrl('/v1/chats');\n // Handle relative URLs (for proxy mode)\n const url = baseUrl.startsWith('/') || baseUrl.startsWith('./')\n ? new URL(baseUrl, window.location.origin)\n : new URL(baseUrl);\n \n if (params?.limit) {\n url.searchParams.set('limit', params.limit.toString());\n }\n if (params?.cursor) {\n url.searchParams.set('cursor', params.cursor);\n }\n if (params?.['expand[]']) {\n params['expand[]'].forEach((expand) => {\n url.searchParams.append('expand[]', expand);\n });\n }\n\n const headers: Record<string, string> = {\n 'Content-Type': 'application/json',\n };\n\n if (this.sessionToken) {\n headers['Authorization'] = `Bearer ${this.sessionToken}`;\n }\n\n const response = await fetch(url.toString(), {\n method: 'GET',\n headers,\n });\n\n if (!response.ok) {\n const errorData = await response.json().catch(() => ({}));\n throw new Error(\n errorData.detail ||\n errorData.message ||\n `API error: ${response.status} ${response.statusText}`,\n );\n }\n\n return response.json();\n }\n\n /**\n * Generate a UUID v4 idempotency key\n */\n private generateIdempotencyKey(): string {\n try {\n if (typeof crypto !== 'undefined' && crypto.randomUUID) {\n return crypto.randomUUID();\n }\n } catch {\n // Fallback to manual UUID v4 generation\n }\n // Fallback: Generate UUID v4 format manually\n const generateHex = (count: number): string => {\n return Array.from({ length: count }, () => Math.floor(Math.random() * 16).toString(16)).join('');\n };\n const generateVariant = (): string => {\n const variants = ['8', '9', 'a', 'b'];\n return variants[Math.floor(Math.random() * variants.length)];\n };\n return `${generateHex(8)}-${generateHex(4)}-4${generateHex(3)}-${generateVariant()}${generateHex(3)}-${generateHex(12)}`;\n }\n\n /**\n * Update a chat\n */\n async updateChat(chatId: string, update: ChatUpdate): Promise<ChatOut> {\n const endpoint = `/v1/chats/${chatId}`;\n const baseUrl = this.getUrl(endpoint);\n \n // Handle relative URLs (for proxy mode)\n const url = baseUrl.startsWith('/') || baseUrl.startsWith('./')\n ? new URL(baseUrl, window.location.origin)\n : new URL(baseUrl);\n \n // Generate idempotency key for update operation\n const idempotencyKey = this.generateIdempotencyKey();\n \n const headers: HeadersInit = {\n 'Content-Type': 'application/json',\n 'Idempotency-Key': idempotencyKey,\n };\n\n if (this.sessionToken) {\n (headers as Record<string, string>)['Authorization'] = `Bearer ${this.sessionToken}`;\n }\n\n const response = await fetch(url.toString(), {\n method: 'PATCH',\n headers,\n body: JSON.stringify(update),\n });\n\n if (!response.ok) {\n const errorText = await response.text();\n let errorData: { detail?: string; message?: string } = {};\n try {\n errorData = JSON.parse(errorText) as { detail?: string; message?: string };\n } catch {\n errorData = { detail: errorText };\n }\n throw new Error(\n errorData.detail ||\n errorData.message ||\n `API error: ${response.status} ${response.statusText}`,\n );\n }\n\n // Handle empty responses (e.g., 204 No Content)\n if (response.status === 204) {\n return {} as ChatOut;\n }\n\n const text = await response.text();\n if (!text) {\n return {} as ChatOut;\n }\n\n try {\n return JSON.parse(text);\n } catch {\n return {} as ChatOut;\n }\n }\n\n /**\n * Delete a chat\n */\n async deleteChat(chatId: string): Promise<void> {\n const endpoint = `/v1/chats/${chatId}`;\n const baseUrl = this.getUrl(endpoint);\n \n // Handle relative URLs (for proxy mode)\n const url = baseUrl.startsWith('/') || baseUrl.startsWith('./')\n ? new URL(baseUrl, window.location.origin)\n : new URL(baseUrl);\n \n // Generate idempotency key for delete operation\n const idempotencyKey = this.generateIdempotencyKey();\n \n const headers: HeadersInit = {\n 'Content-Type': 'application/json',\n 'Idempotency-Key': idempotencyKey,\n };\n\n if (this.sessionToken) {\n (headers as Record<string, string>)['Authorization'] = `Bearer ${this.sessionToken}`;\n }\n\n const response = await fetch(url.toString(), {\n method: 'DELETE',\n headers,\n });\n\n if (!response.ok) {\n const errorData = await response.json().catch(() => ({}));\n throw new Error(\n errorData.detail ||\n errorData.message ||\n `API error: ${response.status} ${response.statusText}`,\n );\n }\n }\n\n /**\n * List available models\n */\n async listModels(params?: ListModelsParams): Promise<ModelPage> {\n const baseUrl = this.getUrl('/v1/models');\n // Handle relative URLs (for proxy mode)\n const url = baseUrl.startsWith('/') || baseUrl.startsWith('./')\n ? new URL(baseUrl, window.location.origin)\n : new URL(baseUrl);\n \n if (params?.limit) {\n url.searchParams.set('limit', params.limit.toString());\n }\n if (params?.cursor) {\n url.searchParams.set('cursor', params.cursor);\n }\n if (params?.['expand[]']) {\n params['expand[]'].forEach((expand) => {\n url.searchParams.append('expand[]', expand);\n });\n }\n\n const headers: Record<string, string> = {\n 'Content-Type': 'application/json',\n };\n\n if (this.sessionToken) {\n headers['Authorization'] = `Bearer ${this.sessionToken}`;\n }\n\n const response = await fetch(url.toString(), {\n method: 'GET',\n headers,\n });\n\n if (!response.ok) {\n const errorData = await response.json().catch(() => ({}));\n throw new Error(\n errorData.detail ||\n errorData.message ||\n `API error: ${response.status} ${response.statusText}`,\n );\n }\n\n return response.json();\n }\n\n /**\n * Get a specific model by ID\n */\n async getModel(modelId: string): Promise<ModelOut> {\n const url = this.getUrl(`/v1/models/${modelId}`);\n const headers: Record<string, string> = {\n 'Content-Type': 'application/json',\n };\n\n if (this.sessionToken) {\n headers['Authorization'] = `Bearer ${this.sessionToken}`;\n }\n\n const response = await fetch(url, {\n method: 'GET',\n headers,\n });\n\n if (!response.ok) {\n const errorData = await response.json().catch(() => ({}));\n throw new Error(\n errorData.detail ||\n errorData.message ||\n `API error: ${response.status} ${response.statusText}`,\n );\n }\n\n return response.json();\n }\n}\n\n/**\n * Parse SSE stream into chunks\n */\nexport async function* parseSSEStream(\n stream: ReadableStream<Uint8Array>,\n abortSignal?: AbortSignal,\n): AsyncGenerator<SSEChunk> {\n const reader = stream.getReader();\n const decoder = new TextDecoder();\n let buffer = '';\n\n try {\n while (true) {\n if (abortSignal?.aborted) {\n reader.cancel();\n break;\n }\n\n const { done, value } = await reader.read();\n if (done) break;\n\n buffer += decoder.decode(value, { stream: true });\n const lines = buffer.split('\\n\\n');\n buffer = lines.pop() || '';\n\n for (const line of lines) {\n if (line.startsWith('data: ')) {\n const data = line.slice(6);\n if (data.trim() === '[DONE]') {\n yield { done: true };\n continue;\n }\n try {\n const parsed = JSON.parse(data);\n yield parsed;\n } catch {\n // Skip invalid JSON\n }\n }\n }\n }\n } finally {\n reader.releaseLock();\n }\n}\n\n","import type { ThreadMessage } from '@assistant-ui/react';\nimport type { MessageCreate } from '../types/cuadra';\n\n/**\n * Convert assistant-ui ThreadMessage to Cuadra API MessageCreate format\n */\nexport function convertToCuadraMessages(\n messages: readonly ThreadMessage[],\n): MessageCreate[] {\n return messages.map((msg) => {\n // Extract text content from assistant-ui message format\n let content = '';\n\n if (typeof msg.content === 'string') {\n content = msg.content;\n } else if (Array.isArray(msg.content)) {\n // Find text content in content array\n const textContent = msg.content.find((c) => c.type === 'text');\n if (\n textContent &&\n typeof textContent === 'object' &&\n 'text' in textContent\n ) {\n content = textContent.text as string;\n }\n }\n\n return {\n role: msg.role as 'system' | 'user' | 'assistant',\n content,\n };\n });\n}\n\n/**\n * Convert Cuadra API MessageOut to assistant-ui ThreadMessage format\n */\nexport function convertFromCuadraMessage(\n msg: {\n role: string;\n content: string;\n id: string;\n createdAt: string;\n },\n): ThreadMessage {\n return {\n id: msg.id,\n role: msg.role as 'user' | 'assistant' | 'system',\n content: [\n {\n type: 'text' as const,\n text: msg.content,\n },\n ],\n createdAt: new Date(msg.createdAt),\n metadata: {\n custom: {},\n },\n ...(msg.role === 'assistant' && {\n status: {\n type: 'complete' as const,\n reason: 'stop' as const,\n },\n metadata: {\n unstable_state: null,\n unstable_annotations: [],\n unstable_data: [],\n steps: [],\n custom: {},\n },\n }),\n ...(msg.role === 'user' && {\n attachments: [],\n }),\n } as ThreadMessage;\n}\n\n","import type { ChatModelAdapter, ChatModelRunOptions } from '@assistant-ui/react';\nimport { CuadraChatClient, parseSSEStream, type SSEChunk } from '../lib/cuadraChatClient';\nimport { convertToCuadraMessages } from './messageConverter';\n\nexport interface ChatModelAdapterOptions {\n modelId?: string | null; // Optional - backend can resolve model ID in proxy mode\n systemPrompt?: string;\n ephemeral?: boolean;\n onChatCreated?: (chatId: string) => void;\n onUserMessage?: () => void; // Called when a user message is sent\n onThreadIdUpdate?: (localThreadId: string, serverChatId: string) => void; // Called when chat ID is received to update thread mapping\n}\n\n/**\n * Creates a ChatModelAdapter for LocalRuntime that connects to Cuadra API\n * Handles streaming responses and converts between assistant-ui and API formats\n */\nexport function createChatModelAdapter(\n client: CuadraChatClient,\n options: ChatModelAdapterOptions,\n): ChatModelAdapter {\n const { modelId, systemPrompt, ephemeral, onChatCreated, onUserMessage, onThreadIdUpdate } = options;\n \n return {\n async *run(options: ChatModelRunOptions) {\n const { messages, abortSignal, context } = options;\n \n // Get current thread ID from context if available\n const currentThreadId = (context as { threadId?: string })?.threadId;\n\n onUserMessage?.();\n\n // Convert assistant-ui ThreadMessage format to API MessageCreate format\n const apiMessages = convertToCuadraMessages(messages);\n\n // Create request\n // Note: context.threadId might not exist in ModelContext, \n // thread ID is managed by the runtime\n // modelId is optional - backend can resolve it in proxy mode\n const request: {\n messages: typeof apiMessages;\n chatId: null;\n modelId?: string | null;\n systemPrompt?: string;\n ephemeral?: boolean;\n stream: boolean;\n } = {\n messages: apiMessages,\n chatId: null, // Thread ID will be set by runtime if needed\n systemPrompt,\n ephemeral,\n stream: true,\n };\n \n // Only include modelId if provided (backend may resolve it)\n if (modelId && modelId.trim() !== '') {\n request.modelId = modelId;\n }\n\n // Stream from API\n const stream = await client.createOrContinueChat(request, abortSignal);\n\n let accumulatedText = '';\n let chatId: string | undefined;\n\n // Parse SSE stream\n for await (const chunk of parseSSEStream(stream, abortSignal)) {\n // Check abort signal\n if (abortSignal?.aborted) {\n throw new Error('Request aborted');\n }\n\n // Handle chat ID from chunk\n const chunkId = (chunk as { id?: string }).id;\n if (chunkId && !chatId) {\n chatId = chunkId;\n onChatCreated?.(chunkId);\n \n // Update thread ID mapping if we have a current thread ID\n if (currentThreadId && onThreadIdUpdate) {\n onThreadIdUpdate(currentThreadId, chunkId);\n }\n }\n\n // Handle delta format (current API format: {\"id\": \"...\", \"delta\": \"...\", \"finished\": false})\n const delta = (chunk as { delta?: string }).delta;\n if (delta !== undefined && delta !== null) {\n accumulatedText += delta;\n }\n\n // Handle legacy formats for compatibility\n if (chunk.type === 'message' || chunk.content) {\n const content = chunk.content || '';\n accumulatedText += content;\n }\n\n // Handle message object format\n if (chunk.message) {\n accumulatedText += chunk.message.content || '';\n }\n\n // Handle tool calls (if API supports them in future)\n // Note: Current API schema doesn't include tools, but structure is ready\n if ((chunk as SSEChunk & { tool_calls?: unknown[] }).tool_calls) {\n // Process tool calls when API supports them\n // This is a placeholder for future implementation\n }\n\n // Check if finished\n const finished = (chunk as { finished?: boolean }).finished;\n if (finished) {\n // Stream is complete, yield final accumulated text\n if (accumulatedText) {\n yield {\n content: [{ type: 'text', text: accumulatedText }],\n };\n }\n break;\n }\n\n // Yield incremental updates as we receive deltas\n if (accumulatedText) {\n yield {\n content: [{ type: 'text', text: accumulatedText }],\n };\n }\n }\n\n // Final yield with accumulated text\n if (accumulatedText) {\n yield {\n content: [{ type: 'text', text: accumulatedText }],\n };\n }\n },\n };\n}\n\n","import type {\n unstable_RemoteThreadListAdapter as RemoteThreadListAdapter,\n ThreadMessage,\n ThreadHistoryAdapter,\n} from '@assistant-ui/react';\nimport { CuadraChatClient } from '../lib/cuadraChatClient';\nimport { convertFromCuadraMessage } from './messageConverter';\nimport React from 'react';\nimport { RuntimeAdapterProvider, useThreadListItem } from '@assistant-ui/react';\n\n/**\n * Store mapping of local thread IDs to server chat IDs\n * This is used to update remoteId when server chat ID is received\n */\nexport const localToRemoteIdMap = new Map<string, string>();\n\n/**\n * Creates a RemoteThreadListAdapter for LocalRuntime that connects to Cuadra API\n * Maps API chat format to assistant-ui thread format\n */\nexport function createThreadListAdapter(\n client: CuadraChatClient,\n onChatIdReceived?: (localThreadId: string, serverChatId: string) => void,\n): RemoteThreadListAdapter & {\n updateRemoteId: (localThreadId: string, serverChatId: string) => void;\n} {\n return {\n async list() {\n const all = [];\n const limit = 50;\n let cursor: string | undefined = undefined;\n let safety = 0;\n\n // Fetch all chats with pagination\n do {\n const response = await client.listChats({ limit, cursor });\n const items = response.items || [];\n\n if (Array.isArray(items) && items.length > 0) {\n all.push(...items);\n }\n\n cursor = response.nextCursor || undefined;\n safety++;\n } while (cursor && safety < 50);\n\n // Map to assistant-ui thread format\n // Filter out deleted chats and chats without IDs\n const threads = all\n .map((chat) => {\n const id = chat.id;\n // Skip if no ID or if deleted\n if (!id || chat.deletedAt) return null;\n\n return {\n status: 'regular' as const,\n remoteId: id,\n title: chat.title || 'New Chat',\n createdAt: chat.createdAt ? new Date(chat.createdAt) : new Date(),\n updatedAt: chat.updatedAt ? new Date(chat.updatedAt) : new Date(),\n };\n })\n .filter((t) => t !== null) as Array<{\n status: 'regular' | 'archived';\n remoteId: string;\n title?: string;\n createdAt: Date;\n updatedAt: Date;\n }>;\n\n return { threads };\n },\n\n async initialize(threadId: string) {\n // For LocalRuntime, threadId is already generated locally (e.g., __LOCALID_...)\n // Check if we have a server chat ID for this local thread ID\n const serverChatId = localToRemoteIdMap.get(threadId);\n const remoteId = serverChatId || threadId;\n\n return { remoteId, externalId: undefined };\n },\n\n async rename(remoteId: string, newTitle: string) {\n await client.updateChat(remoteId, { title: newTitle });\n },\n\n async archive(_remoteId: string) {\n // Cuadra API uses soft delete, which we can treat as archive\n // If API adds explicit archive support, implement here\n },\n\n async unarchive(_remoteId: string) {\n // If Cuadra supports unarchive, implement here\n // Currently not supported\n },\n\n async delete(remoteId: string) {\n await client.deleteChat(remoteId);\n },\n\n async generateTitle(_remoteId: string, _messages: readonly ThreadMessage[]) {\n // Title generation not yet supported by Cuadra API\n // Return empty stream\n return new ReadableStream();\n },\n\n async fetch(threadId: string) {\n try {\n const chat = await client.getChat(threadId);\n const id = chat.id || threadId;\n\n return {\n status: 'regular' as const,\n remoteId: id,\n title: chat.title || 'Chat',\n createdAt: chat.createdAt ? new Date(chat.createdAt) : new Date(),\n updatedAt: chat.updatedAt ? new Date(chat.updatedAt) : new Date(),\n };\n } catch {\n // Return default if fetch fails\n return {\n status: 'regular' as const,\n remoteId: threadId,\n createdAt: new Date(),\n updatedAt: new Date(),\n };\n }\n },\n\n // Add a method to update the remoteId mapping when chat ID is received\n updateRemoteId(localThreadId: string, serverChatId: string) {\n localToRemoteIdMap.set(localThreadId, serverChatId);\n onChatIdReceived?.(localThreadId, serverChatId);\n },\n\n // Provider component that adds thread-specific history adapter\n unstable_Provider: ({ children }: { children?: React.ReactNode }) => {\n const threadListItem = useThreadListItem();\n const remoteId = threadListItem?.remoteId;\n\n // Create thread-specific history adapter\n const history = React.useMemo<ThreadHistoryAdapter>(\n () => ({\n async load() {\n if (!remoteId) return { messages: [] } as any;\n\n try {\n // Fetch chat with messages expanded\n const chat = await client.getChat(remoteId);\n \n if (!chat.messages || chat.messages.length === 0) {\n return { messages: [] } as any;\n }\n\n // Convert API messages to assistant-ui format\n const messages = chat.messages.map((msg) => convertFromCuadraMessage(msg));\n\n return { messages } as any;\n } catch (error) {\n console.error('Failed to load messages for thread:', remoteId, error);\n return { messages: [] } as any;\n }\n },\n\n async append(message) {\n // Messages are automatically persisted by the API when sent\n // This method is called by the runtime but we don't need to do anything\n // since messages are already saved via the chat API\n // If you need to explicitly save messages, you could implement an API endpoint here\n },\n }),\n [remoteId, client],\n );\n\n const adapters = React.useMemo(() => ({ history }), [history]);\n\n return (\n <RuntimeAdapterProvider adapters={adapters}>\n {children}\n </RuntimeAdapterProvider>\n );\n },\n };\n}\n\n","import React, { useCallback, useEffect, useMemo, useState } from 'react';\nimport {\n AssistantRuntimeProvider,\n unstable_useRemoteThreadListRuntime,\n useLocalRuntime,\n} from '@assistant-ui/react';\nimport { CuadraChatClient } from '../lib/cuadraChatClient';\nimport { createChatModelAdapter } from '../adapters/chatModelAdapter';\nimport { createThreadListAdapter } from '../adapters/threadListAdapter';\n\nexport interface CuadraRuntimeProviderProps {\n children: React.ReactNode;\n baseUrl: string;\n sessionToken?: string | null;\n isProxyMode?: boolean; // If true, uses proxy URL patterns (removes /v1 prefix)\n\n // Mode selection\n mode?: 'singleChat' | 'multiChat'; // Default: 'multiChat'\n\n // Model configuration\n modelMode?: 'selector' | 'fixed'; // Default: 'fixed'\n modelId?: string; // Required if modelMode === 'fixed'\n onModelChange?: (modelId: string) => void; // Called when model changes (selector mode)\n\n // Chat configuration\n ephemeral?: boolean; // Default: false - creates temporary chats that auto-delete\n systemPrompt?: string;\n\n // Thread configuration\n initialThreadId?: string; // Load existing thread (multiChat mode)\n\n // Callbacks\n onError?: (error: Error) => void;\n onChatCreated?: (chatId: string) => void;\n onUserMessage?: () => void; // Called when a user message is sent\n onThreadIdUpdate?: (\n oldThreadId: string,\n newThreadId: string,\n ) => void; // Callback when thread ID is updated from local to server\n onChatsLoaded?: () => void; // Callback when chats/thread list is loaded\n}\n\n/**\n * Main provider component that sets up assistant-ui runtime with Cuadra API\n * Supports single/multi chat modes, fixed/selector model modes, and ephemeral chats\n */\nexport function CuadraRuntimeProvider({\n children,\n baseUrl,\n sessionToken,\n isProxyMode = false,\n mode = 'multiChat',\n modelId,\n onModelChange: _onModelChange,\n ephemeral = false,\n systemPrompt,\n initialThreadId,\n onError,\n onChatCreated,\n onUserMessage,\n onThreadIdUpdate,\n onChatsLoaded,\n}: CuadraRuntimeProviderProps) {\n // Create API client\n const client = useMemo(\n () => new CuadraChatClient(baseUrl, sessionToken || undefined, isProxyMode),\n [baseUrl, sessionToken, isProxyMode],\n );\n\n // Track selected model ID (syncs with prop)\n const [selectedModelId, setSelectedModelId] = useState<string | null>(modelId || null);\n\n // Sync selectedModelId with modelId prop\n useEffect(() => {\n if (modelId) {\n setSelectedModelId(modelId);\n }\n }, [modelId]);\n\n // Handle chat created callback\n const handleChatCreated = useCallback(\n (chatId: string) => {\n onChatCreated?.(chatId);\n },\n [onChatCreated],\n );\n\n // Handle thread ID update\n const handleThreadIdUpdate = useCallback(\n (oldId: string, newId: string) => {\n onThreadIdUpdate?.(oldId, newId);\n },\n [onThreadIdUpdate],\n );\n\n // For singleChat mode, create model adapter and use useLocalRuntime\n const modelAdapter = useMemo(() => {\n return createChatModelAdapter(client, {\n modelId: selectedModelId || undefined, // Pass undefined if not set (backend resolves it)\n systemPrompt,\n ephemeral,\n onChatCreated: handleChatCreated,\n onUserMessage,\n });\n }, [client, selectedModelId, systemPrompt, ephemeral, handleChatCreated, onUserMessage]);\n\n if (mode === 'singleChat') {\n return (\n <SingleChatProvider modelAdapter={modelAdapter}>\n {children}\n </SingleChatProvider>\n );\n }\n\n // For multiChat mode, use RemoteThreadListRuntime\n // Pass adapter options instead of the adapter itself so we can add thread ID update callback\n return (\n <MultiChatProvider\n client={client}\n modelAdapterOptions={{\n modelId: selectedModelId || undefined,\n systemPrompt,\n ephemeral,\n onChatCreated: handleChatCreated,\n onUserMessage,\n }}\n initialThreadId={initialThreadId}\n onChatsLoaded={onChatsLoaded}\n onThreadIdUpdate={handleThreadIdUpdate}\n onError={onError}\n >\n {children}\n </MultiChatProvider>\n );\n}\n\n/**\n * Internal provider for singleChat mode that ensures useLocalRuntime\n * is only used after component mount to prevent \"Resource updated before mount\" errors\n * \n * The key insight: We must always render AssistantRuntimeProvider so children can use\n * useThreadRuntime(), but we need to prevent useLocalRuntime from initializing during SSR.\n * Since hooks must be called unconditionally, we always call it but ensure the provider\n * is rendered so the context is available.\n */\nfunction SingleChatProvider({\n modelAdapter,\n children,\n}: {\n modelAdapter: ReturnType<typeof createChatModelAdapter>;\n children: React.ReactNode;\n}) {\n // Always call the hook (required by React rules of hooks)\n // The hook will be called during SSR, but the runtime's internal useLayoutEffect\n // should handle the mounting check internally\n const localRuntime = useLocalRuntime(modelAdapter);\n\n // Always render the provider so children can access runtime context via useThreadRuntime()\n // The runtime itself should handle SSR/hydration gracefully\n return (\n <AssistantRuntimeProvider runtime={localRuntime}>\n {children}\n </AssistantRuntimeProvider>\n );\n}\n\n/**\n * Internal provider for multiChat mode using RemoteThreadListRuntime\n */\nfunction MultiChatProvider({\n client,\n modelAdapterOptions,\n initialThreadId: _initialThreadId,\n onChatsLoaded,\n onThreadIdUpdate,\n onError: _onError,\n children,\n}: {\n client: CuadraChatClient;\n modelAdapterOptions: {\n modelId?: string | null;\n systemPrompt?: string;\n ephemeral?: boolean;\n onChatCreated?: (chatId: string) => void;\n onUserMessage?: () => void;\n };\n initialThreadId?: string;\n onChatsLoaded?: () => void;\n onThreadIdUpdate?: (oldId: string, newId: string) => void;\n onError?: (error: Error) => void;\n children: React.ReactNode;\n}) {\n // Create thread list adapter\n const threadListAdapter = useMemo(() => {\n return createThreadListAdapter(client, (localThreadId, serverChatId) => {\n onThreadIdUpdate?.(localThreadId, serverChatId);\n });\n }, [client, onThreadIdUpdate]);\n\n // Create a callback to update thread ID mapping when chat is created\n const handleThreadIdUpdateFromAdapter = useCallback(\n (localThreadId: string, serverChatId: string) => {\n // Update the adapter's remote ID mapping\n if (threadListAdapter.updateRemoteId) {\n threadListAdapter.updateRemoteId(localThreadId, serverChatId);\n }\n // Also call the prop callback\n onThreadIdUpdate?.(localThreadId, serverChatId);\n },\n [threadListAdapter, onThreadIdUpdate],\n );\n\n // Wrap list method to call onChatsLoaded\n const wrappedAdapter = useMemo(() => {\n return {\n ...threadListAdapter,\n async list() {\n const result = await threadListAdapter.list();\n // Call onChatsLoaded on initial load\n onChatsLoaded?.();\n return result;\n },\n };\n }, [threadListAdapter, onChatsLoaded]);\n\n // Expose adapter globally for external access (e.g., rename/delete)\n useEffect(() => {\n (window as Window & { __cuadraThreadListAdapter?: typeof wrappedAdapter }).__cuadraThreadListAdapter =\n wrappedAdapter;\n (window as Window & { __cuadraThreadListRuntime?: unknown }).__cuadraThreadListRuntime = null;\n }, [wrappedAdapter]);\n\n // Create model adapter with thread ID update callback for multiChat mode\n const modelAdapter = useMemo(() => {\n return createChatModelAdapter(client, {\n ...modelAdapterOptions,\n onThreadIdUpdate: handleThreadIdUpdateFromAdapter,\n });\n }, [client, modelAdapterOptions, handleThreadIdUpdateFromAdapter]);\n\n // Create runtime hook that uses the model adapter\n const runtimeHook = useCallback(() => {\n return useLocalRuntime(modelAdapter);\n }, [modelAdapter]);\n\n // Use RemoteThreadListRuntime hook\n const runtime = unstable_useRemoteThreadListRuntime({\n adapter: wrappedAdapter,\n runtimeHook,\n });\n\n // Expose runtime globally for external refresh\n useEffect(() => {\n (window as Window & { __cuadraThreadListRuntime?: typeof runtime }).__cuadraThreadListRuntime =\n runtime;\n }, [runtime]);\n\n return (\n <AssistantRuntimeProvider runtime={runtime}>{children}</AssistantRuntimeProvider>\n );\n}\n","/**\n * Count how often a character (or substring) is used in a string.\n *\n * @param {string} value\n * Value to search in.\n * @param {string} character\n * Character (or substring) to look for.\n * @return {number}\n * Number of times `character` occurred in `value`.\n */\nexport function ccount(value, character) {\n const source = String(value)\n\n if (typeof character !== 'string') {\n throw new TypeError('Expected character')\n }\n\n let count = 0\n let index = source.indexOf(character)\n\n while (index !== -1) {\n count++\n index = source.indexOf(character, index + character.length)\n }\n\n return count\n}\n","/**\n * @import {Code} from 'micromark-util-types'\n */\n\n/**\n * Check whether the character code represents an ASCII alpha (`a` through `z`,\n * case insensitive).\n *\n * An **ASCII alpha** is an ASCII upper alpha or ASCII lower alpha.\n *\n * An **ASCII upper alpha** is a character in the inclusive range U+0041 (`A`)\n * to U+005A (`Z`).\n *\n * An **ASCII lower alpha** is a character in the inclusive range U+0061 (`a`)\n * to U+007A (`z`).\n *\n * @param code\n * Code.\n * @returns {boolean}\n * Whether it matches.\n */\nexport const asciiAlpha = regexCheck(/[A-Za-z]/);\n\n/**\n * Check whether the character code represents an ASCII alphanumeric (`a`\n * through `z`, case insensitive, or `0` through `9`).\n *\n * An **ASCII alphanumeric** is an ASCII digit (see `asciiDigit`) or ASCII alpha\n * (see `asciiAlpha`).\n *\n * @param code\n * Code.\n * @returns {boolean}\n * Whether it matches.\n */\nexport const asciiAlphanumeric = regexCheck(/[\\dA-Za-z]/);\n\n/**\n * Check whether the character code represents an ASCII atext.\n *\n * atext is an ASCII alphanumeric (see `asciiAlphanumeric`), or a character in\n * the inclusive ranges U+0023 NUMBER SIGN (`#`) to U+0027 APOSTROPHE (`'`),\n * U+002A ASTERISK (`*`), U+002B PLUS SIGN (`+`), U+002D DASH (`-`), U+002F\n * SLASH (`/`), U+003D EQUALS TO (`=`), U+003F QUESTION MARK (`?`), U+005E\n * CARET (`^`) to U+0060 GRAVE ACCENT (`` ` ``), or U+007B LEFT CURLY BRACE\n * (`{`) to U+007E TILDE (`~`).\n *\n * See:\n * **\\[RFC5322]**:\n * [Internet Message Format](https://tools.ietf.org/html/rfc5322).\n * P. Resnick.\n * IETF.\n *\n * @param code\n * Code.\n * @returns {boolean}\n * Whether it matches.\n */\nexport const asciiAtext = regexCheck(/[#-'*+\\--9=?A-Z^-~]/);\n\n/**\n * Check whether a character code is an ASCII control character.\n *\n * An **ASCII control** is a character in the inclusive range U+0000 NULL (NUL)\n * to U+001F (US), or U+007F (DEL).\n *\n * @param {Code} code\n * Code.\n * @returns {boolean}\n * Whether it matches.\n */\nexport function asciiControl(code) {\n return (\n // Special whitespace codes (which have negative values), C0 and Control\n // character DEL\n code !== null && (code < 32 || code === 127)\n );\n}\n\n/**\n * Check whether the character code represents an ASCII digit (`0` through `9`).\n *\n * An **ASCII digit** is a character in the inclusive range U+0030 (`0`) to\n * U+0039 (`9`).\n *\n * @param code\n * Code.\n * @returns {boolean}\n * Whether it matches.\n */\nexport const asciiDigit = regexCheck(/\\d/);\n\n/**\n * Check whether the character code represents an ASCII hex digit (`a` through\n * `f`, case insensitive, or `0` through `9`).\n *\n * An **ASCII hex digit** is an ASCII digit (see `asciiDigit`), ASCII upper hex\n * digit, or an ASCII lower hex digit.\n *\n * An **ASCII upper hex digit** is a character in the inclusive range U+0041\n * (`A`) to U+0046 (`F`).\n *\n * An **ASCII lower hex digit** is a character in the inclusive range U+0061\n * (`a`) to U+0066 (`f`).\n *\n * @param code\n * Code.\n * @returns {boolean}\n * Whether it matches.\n */\nexport const asciiHexDigit = regexCheck(/[\\dA-Fa-f]/);\n\n/**\n * Check whether the character code represents ASCII punctuation.\n *\n * An **ASCII punctuation** is a character in the inclusive ranges U+0021\n * EXCLAMATION MARK (`!`) to U+002F SLASH (`/`), U+003A COLON (`:`) to U+0040 AT\n * SIGN (`@`), U+005B LEFT SQUARE BRACKET (`[`) to U+0060 GRAVE ACCENT\n * (`` ` ``), or U+007B LEFT CURLY BRACE (`{`) to U+007E TILDE (`~`).\n *\n * @param code\n * Code.\n * @returns {boolean}\n * Whether it matches.\n */\nexport const asciiPunctuation = regexCheck(/[!-/:-@[-`{-~]/);\n\n/**\n * Check whether a character code is a markdown line ending.\n *\n * A **markdown line ending** is the virtual characters M-0003 CARRIAGE RETURN\n * LINE FEED (CRLF), M-0004 LINE FEED (LF) and M-0005 CARRIAGE RETURN (CR).\n *\n * In micromark, the actual character U+000A LINE FEED (LF) and U+000D CARRIAGE\n * RETURN (CR) are replaced by these virtual characters depending on whether\n * they occurred together.\n *\n * @param {Code} code\n * Code.\n * @returns {boolean}\n * Whether it matches.\n */\nexport function markdownLineEnding(code) {\n return code !== null && code < -2;\n}\n\n/**\n * Check whether a character code is a markdown line ending (see\n * `markdownLineEnding`) or markdown space (see `markdownSpace`).\n *\n * @param {Code} code\n * Code.\n * @returns {boolean}\n * Whether it matches.\n */\nexport function markdownLineEndingOrSpace(code) {\n return code !== null && (code < 0 || code === 32);\n}\n\n/**\n * Check whether a character code is a markdown space.\n *\n * A **markdown space** is the concrete character U+0020 SPACE (SP) and the\n * virtual characters M-0001 VIRTUAL SPACE (VS) and M-0002 HORIZONTAL TAB (HT).\n *\n * In micromark, the actual character U+0009 CHARACTER TABULATION (HT) is\n * replaced by one M-0002 HORIZONTAL TAB (HT) and between 0 and 3 M-0001 VIRTUAL\n * SPACE (VS) characters, depending on the column at which the tab occurred.\n *\n * @param {Code} code\n * Code.\n * @returns {boolean}\n * Whether it matches.\n */\nexport function markdownSpace(code) {\n return code === -2 || code === -1 || code === 32;\n}\n\n// Size note: removing ASCII from the regex and using `asciiPunctuation` here\n// In fact adds to the bundle size.\n/**\n * Check whether the character code represents Unicode punctuation.\n *\n * A **Unicode punctuation** is a character in the Unicode `Pc` (Punctuation,\n * Connector), `Pd` (Punctuation, Dash), `Pe` (Punctuation, Close), `Pf`\n * (Punctuation, Final quote), `Pi` (Punctuation, Initial quote), `Po`\n * (Punctuation, Other), or `Ps` (Punctuation, Open) categories, or an ASCII\n * punctuation (see `asciiPunctuation`).\n *\n * See:\n * **\\[UNICODE]**:\n * [The Unicode Standard](https://www.unicode.org/versions/).\n * Unicode Consortium.\n *\n * @param code\n * Code.\n * @returns\n * Whether it matches.\n */\nexport const unicodePunctuation = regexCheck(/\\p{P}|\\p{S}/u);\n\n/**\n * Check whether the character code represents Unicode whitespace.\n *\n * Note that this does handle micromark specific markdown whitespace characters.\n * See `markdownLineEndingOrSpace` to check that.\n *\n * A **Unicode whitespace** is a character in the Unicode `Zs` (Separator,\n * Space) category, or U+0009 CHARACTER TABULATION (HT), U+000A LINE FEED (LF),\n * U+000C (FF), or U+000D CARRIAGE RETURN (CR) (**\\[UNICODE]**).\n *\n * See:\n * **\\[UNICODE]**:\n * [The Unicode Standard](https://www.unicode.org/versions/).\n * Unicode Consortium.\n *\n * @param code\n * Code.\n * @returns\n * Whether it matches.\n */\nexport const unicodeWhitespace = regexCheck(/\\s/);\n\n/**\n * Create a code check from a regex.\n *\n * @param {RegExp} regex\n * Expression.\n * @returns {(code: Code) => boolean}\n * Check.\n */\nfunction regexCheck(regex) {\n return check;\n\n /**\n * Check whether a code matches the bound regex.\n *\n * @param {Code} code\n * Character code.\n * @returns {boolean}\n * Whether the character code matches the bound regex.\n */\n function check(code) {\n return code !== null && code > -1 && regex.test(String.fromCharCode(code));\n }\n}","export default function escapeStringRegexp(string) {\n\tif (typeof string !== 'string') {\n\t\tthrow new TypeError('Expected a string');\n\t}\n\n\t// Escape characters with special meaning either inside or outside character sets.\n\t// Use a simple backslash escape when it’s always valid, and a `\\xnn` escape when the simpler form would be disallowed by Unicode patterns’ stricter grammar.\n\treturn string\n\t\t.replace(/[|\\\\{}()[\\]^$+*?.]/g, '\\\\$&')\n\t\t.replace(/-/g, '\\\\x2d');\n}\n","/**\n * @import {Node, Parent} from 'unist'\n */\n\n/**\n * @template Fn\n * @template Fallback\n * @typedef {Fn extends (value: any) => value is infer Thing ? Thing : Fallback} Predicate\n */\n\n/**\n * @callback Check\n * Check that an arbitrary value is a node.\n * @param {unknown} this\n * The given context.\n * @param {unknown} [node]\n * Anything (typically a node).\n * @param {number | null | undefined} [index]\n * The node’s position in its parent.\n * @param {Parent | null | undefined} [parent]\n * The node’s parent.\n * @returns {boolean}\n * Whether this is a node and passes a test.\n *\n * @typedef {Record<string, unknown> | Node} Props\n * Object to check for equivalence.\n *\n * Note: `Node` is included as it is common but is not indexable.\n *\n * @typedef {Array<Props | TestFunction | string> | ReadonlyArray<Props | TestFunction | string> | Props | TestFunction | string | null | undefined} Test\n * Check for an arbitrary node.\n *\n * @callback TestFunction\n * Check if a node passes a test.\n * @param {unknown} this\n * The given context.\n * @param {Node} node\n * A node.\n * @param {number | undefined} [index]\n * The node’s position in its parent.\n * @param {Parent | undefined} [parent]\n * The node’s parent.\n * @returns {boolean | undefined | void}\n * Whether this node passes the test.\n *\n * Note: `void` is included until TS sees no return as `undefined`.\n */\n\n/**\n * Check if `node` is a `Node` and whether it passes the given test.\n *\n * @param {unknown} node\n * Thing to check, typically `Node`.\n * @param {Test} test\n * A check for a specific node.\n * @param {number | null | undefined} index\n * The node’s position in its parent.\n * @param {Parent | null | undefined} parent\n * The node’s parent.\n * @param {unknown} context\n * Context object (`this`) to pass to `test` functions.\n * @returns {boolean}\n * Whether `node` is a node and passes a test.\n */\nexport const is =\n // Note: overloads in JSDoc can’t yet use different `@template`s.\n /**\n * @type {(\n * (<Condition extends ReadonlyArray<string>>(node: unknown, test: Condition, index?: number | null | undefined, parent?: Parent | null | undefined, context?: unknown) => node is Node & {type: Condition[number]}) &\n * (<Condition extends Array<string>>(node: unknown, test: Condition, index?: number | null | undefined, parent?: Parent | null | undefined, context?: unknown) => node is Node & {type: Condition[number]}) &\n * (<Condition extends string>(node: unknown, test: Condition, index?: number | null | undefined, parent?: Parent | null | undefined, context?: unknown) => node is Node & {type: Condition}) &\n * (<Condition extends Props>(node: unknown, test: Condition, index?: number | null | undefined, parent?: Parent | null | undefined, context?: unknown) => node is Node & Condition) &\n * (<Condition extends TestFunction>(node: unknown, test: Condition, index?: number | null | undefined, parent?: Parent | null | undefined, context?: unknown) => node is Node & Predicate<Condition, Node>) &\n * ((node?: null | undefined) => false) &\n * ((node: unknown, test?: null | undefined, index?: number | null | undefined, parent?: Parent | null | undefined, context?: unknown) => node is Node) &\n * ((node: unknown, test?: Test, index?: number | null | undefined, parent?: Parent | null | undefined, context?: unknown) => boolean)\n * )}\n */\n (\n /**\n * @param {unknown} [node]\n * @param {Test} [test]\n * @param {number | null | undefined} [index]\n * @param {Parent | null | undefined} [parent]\n * @param {unknown} [context]\n * @returns {boolean}\n */\n // eslint-disable-next-line max-params\n function (node, test, index, parent, context) {\n const check = convert(test)\n\n if (\n index !== undefined &&\n index !== null &&\n (typeof index !== 'number' ||\n index < 0 ||\n index === Number.POSITIVE_INFINITY)\n ) {\n throw new Error('Expected positive finite index')\n }\n\n if (\n parent !== undefined &&\n parent !== null &&\n (!is(parent) || !parent.children)\n ) {\n throw new Error('Expected parent node')\n }\n\n if (\n (parent === undefined || parent === null) !==\n (index === undefined || index === null)\n ) {\n throw new Error('Expected both parent and index')\n }\n\n return looksLikeANode(node)\n ? check.call(context, node, index, parent)\n : false\n }\n )\n\n/**\n * Generate an assertion from a test.\n *\n * Useful if you’re going to test many nodes, for example when creating a\n * utility where something else passes a compatible test.\n *\n * The created function is a bit faster because it expects valid input only:\n * a `node`, `index`, and `parent`.\n *\n * @param {Test} test\n * * when nullish, checks if `node` is a `Node`.\n * * when `string`, works like passing `(node) => node.type === test`.\n * * when `function` checks if function passed the node is true.\n * * when `object`, checks that all keys in test are in node, and that they have (strictly) equal values.\n * * when `array`, checks if any one of the subtests pass.\n * @returns {Check}\n * An assertion.\n */\nexport const convert =\n // Note: overloads in JSDoc can’t yet use different `@template`s.\n /**\n * @type {(\n * (<Condition extends string>(test: Condition) => (node: unknown, index?: number | null | undefined, parent?: Parent | null | undefined, context?: unknown) => node is Node & {type: Condition}) &\n * (<Condition extends Props>(test: Condition) => (node: unknown, index?: number | null | undefined, parent?: Parent | null | undefined, context?: unknown) => node is Node & Condition) &\n * (<Condition extends TestFunction>(test: Condition) => (node: unknown, index?: number | null | undefined, parent?: Parent | null | undefined, context?: unknown) => node is Node & Predicate<Condition, Node>) &\n * ((test?: null | undefined) => (node?: unknown, index?: number | null | undefined, parent?: Parent | null | undefined, context?: unknown) => node is Node) &\n * ((test?: Test) => Check)\n * )}\n */\n (\n /**\n * @param {Test} [test]\n * @returns {Check}\n */\n function (test) {\n if (test === null || test === undefined) {\n return ok\n }\n\n if (typeof test === 'function') {\n return castFactory(test)\n }\n\n if (typeof test === 'object') {\n return Array.isArray(test)\n ? anyFactory(test)\n : // Cast because `ReadonlyArray` goes into the above but `isArray`\n // narrows to `Array`.\n propertiesFactory(/** @type {Props} */ (test))\n }\n\n if (typeof test === 'string') {\n return typeFactory(test)\n }\n\n throw new Error('Expected function, string, or object as test')\n }\n )\n\n/**\n * @param {Array<Props | TestFunction | string>} tests\n * @returns {Check}\n */\nfunction anyFactory(tests) {\n /** @type {Array<Check>} */\n const checks = []\n let index = -1\n\n while (++index < tests.length) {\n checks[index] = convert(tests[index])\n }\n\n return castFactory(any)\n\n /**\n * @this {unknown}\n * @type {TestFunction}\n */\n function any(...parameters) {\n let index = -1\n\n while (++index < checks.length) {\n if (checks[index].apply(this, parameters)) return true\n }\n\n return false\n }\n}\n\n/**\n * Turn an object into a test for a node with a certain fields.\n *\n * @param {Props} check\n * @returns {Check}\n */\nfunction propertiesFactory(check) {\n const checkAsRecord = /** @type {Record<string, unknown>} */ (check)\n\n return castFactory(all)\n\n /**\n * @param {Node} node\n * @returns {boolean}\n */\n function all(node) {\n const nodeAsRecord = /** @type {Record<string, unknown>} */ (\n /** @type {unknown} */ (node)\n )\n\n /** @type {string} */\n let key\n\n for (key in check) {\n if (nodeAsRecord[key] !== checkAsRecord[key]) return false\n }\n\n return true\n }\n}\n\n/**\n * Turn a string into a test for a node with a certain type.\n *\n * @param {string} check\n * @returns {Check}\n */\nfunction typeFactory(check) {\n return castFactory(type)\n\n /**\n * @param {Node} node\n */\n function type(node) {\n return node && node.type === check\n }\n}\n\n/**\n * Turn a custom test into a test for a node that passes that test.\n *\n * @param {TestFunction} testFunction\n * @returns {Check}\n */\nfunction castFactory(testFunction) {\n return check\n\n /**\n * @this {unknown}\n * @type {Check}\n */\n function check(value, index, parent) {\n return Boolean(\n looksLikeANode(value) &&\n testFunction.call(\n this,\n value,\n typeof index === 'number' ? index : undefined,\n parent || undefined\n )\n )\n }\n}\n\nfunction ok() {\n return true\n}\n\n/**\n * @param {unknown} value\n * @returns {value is Node}\n */\nfunction looksLikeANode(value) {\n return value !== null && typeof value === 'object' && 'type' in value\n}\n","/**\n * @import {Node as UnistNode, Parent as UnistParent} from 'unist'\n */\n\n/**\n * @typedef {Exclude<import('unist-util-is').Test, undefined> | undefined} Test\n * Test from `unist-util-is`.\n *\n * Note: we have remove and add `undefined`, because otherwise when generating\n * automatic `.d.ts` files, TS tries to flatten paths from a local perspective,\n * which doesn’t work when publishing on npm.\n */\n\n/**\n * @typedef {(\n * Fn extends (value: any) => value is infer Thing\n * ? Thing\n * : Fallback\n * )} Predicate\n * Get the value of a type guard `Fn`.\n * @template Fn\n * Value; typically function that is a type guard (such as `(x): x is Y`).\n * @template Fallback\n * Value to yield if `Fn` is not a type guard.\n */\n\n/**\n * @typedef {(\n * Check extends null | undefined // No test.\n * ? Value\n * : Value extends {type: Check} // String (type) test.\n * ? Value\n * : Value extends Check // Partial test.\n * ? Value\n * : Check extends Function // Function test.\n * ? Predicate<Check, Value> extends Value\n * ? Predicate<Check, Value>\n * : never\n * : never // Some other test?\n * )} MatchesOne\n * Check whether a node matches a primitive check in the type system.\n * @template Value\n * Value; typically unist `Node`.\n * @template Check\n * Value; typically `unist-util-is`-compatible test, but not arrays.\n */\n\n/**\n * @typedef {(\n * Check extends ReadonlyArray<infer T>\n * ? MatchesOne<Value, T>\n * : Check extends Array<infer T>\n * ? MatchesOne<Value, T>\n * : MatchesOne<Value, Check>\n * )} Matches\n * Check whether a node matches a check in the type system.\n * @template Value\n * Value; typically unist `Node`.\n * @template Check\n * Value; typically `unist-util-is`-compatible test.\n */\n\n/**\n * @typedef {0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10} Uint\n * Number; capped reasonably.\n */\n\n/**\n * @typedef {I extends 0 ? 1 : I extends 1 ? 2 : I extends 2 ? 3 : I extends 3 ? 4 : I extends 4 ? 5 : I extends 5 ? 6 : I extends 6 ? 7 : I extends 7 ? 8 : I extends 8 ? 9 : 10} Increment\n * Increment a number in the type system.\n * @template {Uint} [I=0]\n * Index.\n */\n\n/**\n * @typedef {(\n * Node extends UnistParent\n * ? Node extends {children: Array<infer Children>}\n * ? Child extends Children ? Node : never\n * : never\n * : never\n * )} InternalParent\n * Collect nodes that can be parents of `Child`.\n * @template {UnistNode} Node\n * All node types in a tree.\n * @template {UnistNode} Child\n * Node to search for.\n */\n\n/**\n * @typedef {InternalParent<InclusiveDescendant<Tree>, Child>} Parent\n * Collect nodes in `Tree` that can be parents of `Child`.\n * @template {UnistNode} Tree\n * All node types in a tree.\n * @template {UnistNode} Child\n * Node to search for.\n */\n\n/**\n * @typedef {(\n * Depth extends Max\n * ? never\n * :\n * | InternalParent<Node, Child>\n * | InternalAncestor<Node, InternalParent<Node, Child>, Max, Increment<Depth>>\n * )} InternalAncestor\n * Collect nodes in `Tree` that can be ancestors of `Child`.\n * @template {UnistNode} Node\n * All node types in a tree.\n * @template {UnistNode} Child\n * Node to search for.\n * @template {Uint} [Max=10]\n * Max; searches up to this depth.\n * @template {Uint} [Depth=0]\n * Current depth.\n */\n\n/**\n * @typedef {InternalAncestor<InclusiveDescendant<Tree>, Child>} Ancestor\n * Collect nodes in `Tree` that can be ancestors of `Child`.\n * @template {UnistNode} Tree\n * All node types in a tree.\n * @template {UnistNode} Child\n * Node to search for.\n */\n\n/**\n * @typedef {(\n * Tree extends UnistParent\n * ? Depth extends Max\n * ? Tree\n * : Tree | InclusiveDescendant<Tree['children'][number], Max, Increment<Depth>>\n * : Tree\n * )} InclusiveDescendant\n * Collect all (inclusive) descendants of `Tree`.\n *\n * > 👉 **Note**: for performance reasons, this seems to be the fastest way to\n * > recurse without actually running into an infinite loop, which the\n * > previous version did.\n * >\n * > Practically, a max of `2` is typically enough assuming a `Root` is\n * > passed, but it doesn’t improve performance.\n * > It gets higher with `List > ListItem > Table > TableRow > TableCell`.\n * > Using up to `10` doesn’t hurt or help either.\n * @template {UnistNode} Tree\n * Tree type.\n * @template {Uint} [Max=10]\n * Max; searches up to this depth.\n * @template {Uint} [Depth=0]\n * Current depth.\n */\n\n/**\n * @typedef {'skip' | boolean} Action\n * Union of the action types.\n *\n * @typedef {number} Index\n * Move to the sibling at `index` next (after node itself is completely\n * traversed).\n *\n * Useful if mutating the tree, such as removing the node the visitor is\n * currently on, or any of its previous siblings.\n * Results less than 0 or greater than or equal to `children.length` stop\n * traversing the parent.\n *\n * @typedef {[(Action | null | undefined | void)?, (Index | null | undefined)?]} ActionTuple\n * List with one or two values, the first an action, the second an index.\n *\n * @typedef {Action | ActionTuple | Index | null | undefined | void} VisitorResult\n * Any value that can be returned from a visitor.\n */\n\n/**\n * @callback Visitor\n * Handle a node (matching `test`, if given).\n *\n * Visitors are free to transform `node`.\n * They can also transform the parent of node (the last of `ancestors`).\n *\n * Replacing `node` itself, if `SKIP` is not returned, still causes its\n * descendants to be walked (which is a bug).\n *\n * When adding or removing previous siblings of `node` (or next siblings, in\n * case of reverse), the `Visitor` should return a new `Index` to specify the\n * sibling to traverse after `node` is traversed.\n * Adding or removing next siblings of `node` (or previous siblings, in case\n * of reverse) is handled as expected without needing to return a new `Index`.\n *\n * Removing the children property of an ancestor still results in them being\n * traversed.\n * @param {Visited} node\n * Found node.\n * @param {Array<VisitedParents>} ancestors\n * Ancestors of `node`.\n * @returns {VisitorResult}\n * What to do next.\n *\n * An `Index` is treated as a tuple of `[CONTINUE, Index]`.\n * An `Action` is treated as a tuple of `[Action]`.\n *\n * Passing a tuple back only makes sense if the `Action` is `SKIP`.\n * When the `Action` is `EXIT`, that action can be returned.\n * When the `Action` is `CONTINUE`, `Index` can be returned.\n * @template {UnistNode} [Visited=UnistNode]\n * Visited node type.\n * @template {UnistParent} [VisitedParents=UnistParent]\n * Ancestor type.\n */\n\n/**\n * @typedef {Visitor<Matches<InclusiveDescendant<Tree>, Check>, Ancestor<Tree, Matches<InclusiveDescendant<Tree>, Check>>>} BuildVisitor\n * Build a typed `Visitor` function from a tree and a test.\n *\n * It will infer which values are passed as `node` and which as `parents`.\n * @template {UnistNode} [Tree=UnistNode]\n * Tree type.\n * @template {Test} [Check=Test]\n * Test type.\n */\n\nimport {convert} from 'unist-util-is'\nimport {color} from 'unist-util-visit-parents/do-not-use-color'\n\n/** @type {Readonly<ActionTuple>} */\nconst empty = []\n\n/**\n * Continue traversing as normal.\n */\nexport const CONTINUE = true\n\n/**\n * Stop traversing immediately.\n */\nexport const EXIT = false\n\n/**\n * Do not traverse this node’s children.\n */\nexport const SKIP = 'skip'\n\n/**\n * Visit nodes, with ancestral information.\n *\n * This algorithm performs *depth-first* *tree traversal* in *preorder*\n * (**NLR**) or if `reverse` is given, in *reverse preorder* (**NRL**).\n *\n * You can choose for which nodes `visitor` is called by passing a `test`.\n * For complex tests, you should test yourself in `visitor`, as it will be\n * faster and will have improved type information.\n *\n * Walking the tree is an intensive task.\n * Make use of the return values of the visitor when possible.\n * Instead of walking a tree multiple times, walk it once, use `unist-util-is`\n * to check if a node matches, and then perform different operations.\n *\n * You can change the tree.\n * See `Visitor` for more info.\n *\n * @overload\n * @param {Tree} tree\n * @param {Check} check\n * @param {BuildVisitor<Tree, Check>} visitor\n * @param {boolean | null | undefined} [reverse]\n * @returns {undefined}\n *\n * @overload\n * @param {Tree} tree\n * @param {BuildVisitor<Tree>} visitor\n * @param {boolean | null | undefined} [reverse]\n * @returns {undefined}\n *\n * @param {UnistNode} tree\n * Tree to traverse.\n * @param {Visitor | Test} test\n * `unist-util-is`-compatible test\n * @param {Visitor | boolean | null | undefined} [visitor]\n * Handle each node.\n * @param {boolean | null | undefined} [reverse]\n * Traverse in reverse preorder (NRL) instead of the default preorder (NLR).\n * @returns {undefined}\n * Nothing.\n *\n * @template {UnistNode} Tree\n * Node type.\n * @template {Test} Check\n * `unist-util-is`-compatible test.\n */\nexport function visitParents(tree, test, visitor, reverse) {\n /** @type {Test} */\n let check\n\n if (typeof test === 'function' && typeof visitor !== 'function') {\n reverse = visitor\n // @ts-expect-error no visitor given, so `visitor` is test.\n visitor = test\n } else {\n // @ts-expect-error visitor given, so `test` isn’t a visitor.\n check = test\n }\n\n const is = convert(check)\n const step = reverse ? -1 : 1\n\n factory(tree, undefined, [])()\n\n /**\n * @param {UnistNode} node\n * @param {number | undefined} index\n * @param {Array<UnistParent>} parents\n */\n function factory(node, index, parents) {\n const value = /** @type {Record<string, unknown>} */ (\n node && typeof node === 'object' ? node : {}\n )\n\n if (typeof value.type === 'string') {\n const name =\n // `hast`\n typeof value.tagName === 'string'\n ? value.tagName\n : // `xast`\n typeof value.name === 'string'\n ? value.name\n : undefined\n\n Object.defineProperty(visit, 'name', {\n value:\n 'node (' + color(node.type + (name ? '<' + name + '>' : '')) + ')'\n })\n }\n\n return visit\n\n function visit() {\n /** @type {Readonly<ActionTuple>} */\n let result = empty\n /** @type {Readonly<ActionTuple>} */\n let subresult\n /** @type {number} */\n let offset\n /** @type {Array<UnistParent>} */\n let grandparents\n\n if (!test || is(node, index, parents[parents.length - 1] || undefined)) {\n // @ts-expect-error: `visitor` is now a visitor.\n result = toResult(visitor(node, parents))\n\n if (result[0] === EXIT) {\n return result\n }\n }\n\n if ('children' in node && node.children) {\n const nodeAsParent = /** @type {UnistParent} */ (node)\n\n if (nodeAsParent.children && result[0] !== SKIP) {\n offset = (reverse ? nodeAsParent.children.length : -1) + step\n grandparents = parents.concat(nodeAsParent)\n\n while (offset > -1 && offset < nodeAsParent.children.length) {\n const child = nodeAsParent.children[offset]\n\n subresult = factory(child, offset, grandparents)()\n\n if (subresult[0] === EXIT) {\n return subresult\n }\n\n offset =\n typeof subresult[1] === 'number' ? subresult[1] : offset + step\n }\n }\n }\n\n return result\n }\n }\n}\n\n/**\n * Turn a return value into a clean result.\n *\n * @param {VisitorResult} value\n * Valid return values from visitors.\n * @returns {Readonly<ActionTuple>}\n * Clean result.\n */\nfunction toResult(value) {\n if (Array.isArray(value)) {\n return value\n }\n\n if (typeof value === 'number') {\n return [CONTINUE, value]\n }\n\n return value === null || value === undefined ? empty : [value]\n}\n","/**\n * @import {Nodes, Parents, PhrasingContent, Root, Text} from 'mdast'\n * @import {BuildVisitor, Test, VisitorResult} from 'unist-util-visit-parents'\n */\n\n/**\n * @typedef RegExpMatchObject\n * Info on the match.\n * @property {number} index\n * The index of the search at which the result was found.\n * @property {string} input\n * A copy of the search string in the text node.\n * @property {[...Array<Parents>, Text]} stack\n * All ancestors of the text node, where the last node is the text itself.\n *\n * @typedef {RegExp | string} Find\n * Pattern to find.\n *\n * Strings are escaped and then turned into global expressions.\n *\n * @typedef {Array<FindAndReplaceTuple>} FindAndReplaceList\n * Several find and replaces, in array form.\n *\n * @typedef {[Find, Replace?]} FindAndReplaceTuple\n * Find and replace in tuple form.\n *\n * @typedef {ReplaceFunction | string | null | undefined} Replace\n * Thing to replace with.\n *\n * @callback ReplaceFunction\n * Callback called when a search matches.\n * @param {...any} parameters\n * The parameters are the result of corresponding search expression:\n *\n * * `value` (`string`) — whole match\n * * `...capture` (`Array<string>`) — matches from regex capture groups\n * * `match` (`RegExpMatchObject`) — info on the match\n * @returns {Array<PhrasingContent> | PhrasingContent | string | false | null | undefined}\n * Thing to replace with.\n *\n * * when `null`, `undefined`, `''`, remove the match\n * * …or when `false`, do not replace at all\n * * …or when `string`, replace with a text node of that value\n * * …or when `Node` or `Array<Node>`, replace with those nodes\n *\n * @typedef {[RegExp, ReplaceFunction]} Pair\n * Normalized find and replace.\n *\n * @typedef {Array<Pair>} Pairs\n * All find and replaced.\n *\n * @typedef Options\n * Configuration.\n * @property {Test | null | undefined} [ignore]\n * Test for which nodes to ignore (optional).\n */\n\nimport escape from 'escape-string-regexp'\nimport {visitParents} from 'unist-util-visit-parents'\nimport {convert} from 'unist-util-is'\n\n/**\n * Find patterns in a tree and replace them.\n *\n * The algorithm searches the tree in *preorder* for complete values in `Text`\n * nodes.\n * Partial matches are not supported.\n *\n * @param {Nodes} tree\n * Tree to change.\n * @param {FindAndReplaceList | FindAndReplaceTuple} list\n * Patterns to find.\n * @param {Options | null | undefined} [options]\n * Configuration (when `find` is not `Find`).\n * @returns {undefined}\n * Nothing.\n */\nexport function findAndReplace(tree, list, options) {\n const settings = options || {}\n const ignored = convert(settings.ignore || [])\n const pairs = toPairs(list)\n let pairIndex = -1\n\n while (++pairIndex < pairs.length) {\n visitParents(tree, 'text', visitor)\n }\n\n /** @type {BuildVisitor<Root, 'text'>} */\n function visitor(node, parents) {\n let index = -1\n /** @type {Parents | undefined} */\n let grandparent\n\n while (++index < parents.length) {\n const parent = parents[index]\n /** @type {Array<Nodes> | undefined} */\n const siblings = grandparent ? grandparent.children : undefined\n\n if (\n ignored(\n parent,\n siblings ? siblings.indexOf(parent) : undefined,\n grandparent\n )\n ) {\n return\n }\n\n grandparent = parent\n }\n\n if (grandparent) {\n return handler(node, parents)\n }\n }\n\n /**\n * Handle a text node which is not in an ignored parent.\n *\n * @param {Text} node\n * Text node.\n * @param {Array<Parents>} parents\n * Parents.\n * @returns {VisitorResult}\n * Result.\n */\n function handler(node, parents) {\n const parent = parents[parents.length - 1]\n const find = pairs[pairIndex][0]\n const replace = pairs[pairIndex][1]\n let start = 0\n /** @type {Array<Nodes>} */\n const siblings = parent.children\n const index = siblings.indexOf(node)\n let change = false\n /** @type {Array<PhrasingContent>} */\n let nodes = []\n\n find.lastIndex = 0\n\n let match = find.exec(node.value)\n\n while (match) {\n const position = match.index\n /** @type {RegExpMatchObject} */\n const matchObject = {\n index: match.index,\n input: match.input,\n stack: [...parents, node]\n }\n let value = replace(...match, matchObject)\n\n if (typeof value === 'string') {\n value = value.length > 0 ? {type: 'text', value} : undefined\n }\n\n // It wasn’t a match after all.\n if (value === false) {\n // False acts as if there was no match.\n // So we need to reset `lastIndex`, which currently being at the end of\n // the current match, to the beginning.\n find.lastIndex = position + 1\n } else {\n if (start !== position) {\n nodes.push({\n type: 'text',\n value: node.value.slice(start, position)\n })\n }\n\n if (Array.isArray(value)) {\n nodes.push(...value)\n } else if (value) {\n nodes.push(value)\n }\n\n start = position + match[0].length\n change = true\n }\n\n if (!find.global) {\n break\n }\n\n match = find.exec(node.value)\n }\n\n if (change) {\n if (start < node.value.length) {\n nodes.push({type: 'text', value: node.value.slice(start)})\n }\n\n parent.children.splice(index, 1, ...nodes)\n } else {\n nodes = [node]\n }\n\n return index + nodes.length\n }\n}\n\n/**\n * Turn a tuple or a list of tuples into pairs.\n *\n * @param {FindAndReplaceList | FindAndReplaceTuple} tupleOrList\n * Schema.\n * @returns {Pairs}\n * Clean pairs.\n */\nfunction toPairs(tupleOrList) {\n /** @type {Pairs} */\n const result = []\n\n if (!Array.isArray(tupleOrList)) {\n throw new TypeError('Expected find and replace tuple or list of tuples')\n }\n\n /** @type {FindAndReplaceList} */\n // @ts-expect-error: correct.\n const list =\n !tupleOrList[0] || Array.isArray(tupleOrList[0])\n ? tupleOrList\n : [tupleOrList]\n\n let index = -1\n\n while (++index < list.length) {\n const tuple = list[index]\n result.push([toExpression(tuple[0]), toFunction(tuple[1])])\n }\n\n return result\n}\n\n/**\n * Turn a find into an expression.\n *\n * @param {Find} find\n * Find.\n * @returns {RegExp}\n * Expression.\n */\nfunction toExpression(find) {\n return typeof find === 'string' ? new RegExp(escape(find), 'g') : find\n}\n\n/**\n * Turn a replace into a function.\n *\n * @param {Replace} replace\n * Replace.\n * @returns {ReplaceFunction}\n * Function.\n */\nfunction toFunction(replace) {\n return typeof replace === 'function'\n ? replace\n : function () {\n return replace\n }\n}\n","/**\n * @import {RegExpMatchObject, ReplaceFunction} from 'mdast-util-find-and-replace'\n * @import {CompileContext, Extension as FromMarkdownExtension, Handle as FromMarkdownHandle, Transform as FromMarkdownTransform} from 'mdast-util-from-markdown'\n * @import {ConstructName, Options as ToMarkdownExtension} from 'mdast-util-to-markdown'\n * @import {Link, PhrasingContent} from 'mdast'\n */\n\nimport {ccount} from 'ccount'\nimport {ok as assert} from 'devlop'\nimport {unicodePunctuation, unicodeWhitespace} from 'micromark-util-character'\nimport {findAndReplace} from 'mdast-util-find-and-replace'\n\n/** @type {ConstructName} */\nconst inConstruct = 'phrasing'\n/** @type {Array<ConstructName>} */\nconst notInConstruct = ['autolink', 'link', 'image', 'label']\n\n/**\n * Create an extension for `mdast-util-from-markdown` to enable GFM autolink\n * literals in markdown.\n *\n * @returns {FromMarkdownExtension}\n * Extension for `mdast-util-to-markdown` to enable GFM autolink literals.\n */\nexport function gfmAutolinkLiteralFromMarkdown() {\n return {\n transforms: [transformGfmAutolinkLiterals],\n enter: {\n literalAutolink: enterLiteralAutolink,\n literalAutolinkEmail: enterLiteralAutolinkValue,\n literalAutolinkHttp: enterLiteralAutolinkValue,\n literalAutolinkWww: enterLiteralAutolinkValue\n },\n exit: {\n literalAutolink: exitLiteralAutolink,\n literalAutolinkEmail: exitLiteralAutolinkEmail,\n literalAutolinkHttp: exitLiteralAutolinkHttp,\n literalAutolinkWww: exitLiteralAutolinkWww\n }\n }\n}\n\n/**\n * Create an extension for `mdast-util-to-markdown` to enable GFM autolink\n * literals in markdown.\n *\n * @returns {ToMarkdownExtension}\n * Extension for `mdast-util-to-markdown` to enable GFM autolink literals.\n */\nexport function gfmAutolinkLiteralToMarkdown() {\n return {\n unsafe: [\n {\n character: '@',\n before: '[+\\\\-.\\\\w]',\n after: '[\\\\-.\\\\w]',\n inConstruct,\n notInConstruct\n },\n {\n character: '.',\n before: '[Ww]',\n after: '[\\\\-.\\\\w]',\n inConstruct,\n notInConstruct\n },\n {\n character: ':',\n before: '[ps]',\n after: '\\\\/',\n inConstruct,\n notInConstruct\n }\n ]\n }\n}\n\n/**\n * @this {CompileContext}\n * @type {FromMarkdownHandle}\n */\nfunction enterLiteralAutolink(token) {\n this.enter({type: 'link', title: null, url: '', children: []}, token)\n}\n\n/**\n * @this {CompileContext}\n * @type {FromMarkdownHandle}\n */\nfunction enterLiteralAutolinkValue(token) {\n this.config.enter.autolinkProtocol.call(this, token)\n}\n\n/**\n * @this {CompileContext}\n * @type {FromMarkdownHandle}\n */\nfunction exitLiteralAutolinkHttp(token) {\n this.config.exit.autolinkProtocol.call(this, token)\n}\n\n/**\n * @this {CompileContext}\n * @type {FromMarkdownHandle}\n */\nfunction exitLiteralAutolinkWww(token) {\n this.config.exit.data.call(this, token)\n const node = this.stack[this.stack.length - 1]\n assert(node.type === 'link')\n node.url = 'http://' + this.sliceSerialize(token)\n}\n\n/**\n * @this {CompileContext}\n * @type {FromMarkdownHandle}\n */\nfunction exitLiteralAutolinkEmail(token) {\n this.config.exit.autolinkEmail.call(this, token)\n}\n\n/**\n * @this {CompileContext}\n * @type {FromMarkdownHandle}\n */\nfunction exitLiteralAutolink(token) {\n this.exit(token)\n}\n\n/** @type {FromMarkdownTransform} */\nfunction transformGfmAutolinkLiterals(tree) {\n findAndReplace(\n tree,\n [\n [/(https?:\\/\\/|www(?=\\.))([-.\\w]+)([^ \\t\\r\\n]*)/gi, findUrl],\n [/(?<=^|\\s|\\p{P}|\\p{S})([-.\\w+]+)@([-\\w]+(?:\\.[-\\w]+)+)/gu, findEmail]\n ],\n {ignore: ['link', 'linkReference']}\n )\n}\n\n/**\n * @type {ReplaceFunction}\n * @param {string} _\n * @param {string} protocol\n * @param {string} domain\n * @param {string} path\n * @param {RegExpMatchObject} match\n * @returns {Array<PhrasingContent> | Link | false}\n */\n// eslint-disable-next-line max-params\nfunction findUrl(_, protocol, domain, path, match) {\n let prefix = ''\n\n // Not an expected previous character.\n if (!previous(match)) {\n return false\n }\n\n // Treat `www` as part of the domain.\n if (/^w/i.test(protocol)) {\n domain = protocol + domain\n protocol = ''\n prefix = 'http://'\n }\n\n if (!isCorrectDomain(domain)) {\n return false\n }\n\n const parts = splitUrl(domain + path)\n\n if (!parts[0]) return false\n\n /** @type {Link} */\n const result = {\n type: 'link',\n title: null,\n url: prefix + protocol + parts[0],\n children: [{type: 'text', value: protocol + parts[0]}]\n }\n\n if (parts[1]) {\n return [result, {type: 'text', value: parts[1]}]\n }\n\n return result\n}\n\n/**\n * @type {ReplaceFunction}\n * @param {string} _\n * @param {string} atext\n * @param {string} label\n * @param {RegExpMatchObject} match\n * @returns {Link | false}\n */\nfunction findEmail(_, atext, label, match) {\n if (\n // Not an expected previous character.\n !previous(match, true) ||\n // Label ends in not allowed character.\n /[-\\d_]$/.test(label)\n ) {\n return false\n }\n\n return {\n type: 'link',\n title: null,\n url: 'mailto:' + atext + '@' + label,\n children: [{type: 'text', value: atext + '@' + label}]\n }\n}\n\n/**\n * @param {string} domain\n * @returns {boolean}\n */\nfunction isCorrectDomain(domain) {\n const parts = domain.split('.')\n\n if (\n parts.length < 2 ||\n (parts[parts.length - 1] &&\n (/_/.test(parts[parts.length - 1]) ||\n !/[a-zA-Z\\d]/.test(parts[parts.length - 1]))) ||\n (parts[parts.length - 2] &&\n (/_/.test(parts[parts.length - 2]) ||\n !/[a-zA-Z\\d]/.test(parts[parts.length - 2])))\n ) {\n return false\n }\n\n return true\n}\n\n/**\n * @param {string} url\n * @returns {[string, string | undefined]}\n */\nfunction splitUrl(url) {\n const trailExec = /[!\"&'),.:;<>?\\]}]+$/.exec(url)\n\n if (!trailExec) {\n return [url, undefined]\n }\n\n url = url.slice(0, trailExec.index)\n\n let trail = trailExec[0]\n let closingParenIndex = trail.indexOf(')')\n const openingParens = ccount(url, '(')\n let closingParens = ccount(url, ')')\n\n while (closingParenIndex !== -1 && openingParens > closingParens) {\n url += trail.slice(0, closingParenIndex + 1)\n trail = trail.slice(closingParenIndex + 1)\n closingParenIndex = trail.indexOf(')')\n closingParens++\n }\n\n return [url, trail]\n}\n\n/**\n * @param {RegExpMatchObject} match\n * @param {boolean | null | undefined} [email=false]\n * @returns {boolean}\n */\nfunction previous(match, email) {\n const code = match.input.charCodeAt(match.index - 1)\n\n return (\n (match.index === 0 ||\n unicodeWhitespace(code) ||\n unicodePunctuation(code)) &&\n // If it’s an email, the previous character should not be a slash.\n (!email || code !== 47)\n )\n}\n","/**\n * Normalize an identifier (as found in references, definitions).\n *\n * Collapses markdown whitespace, trim, and then lower- and uppercase.\n *\n * Some characters are considered “uppercase”, such as U+03F4 (`ϴ`), but if their\n * lowercase counterpart (U+03B8 (`θ`)) is uppercased will result in a different\n * uppercase character (U+0398 (`Θ`)).\n * So, to get a canonical form, we perform both lower- and uppercase.\n *\n * Using uppercase last makes sure keys will never interact with default\n * prototypal values (such as `constructor`): nothing in the prototype of\n * `Object` is uppercase.\n *\n * @param {string} value\n * Identifier to normalize.\n * @returns {string}\n * Normalized identifier.\n */\nexport function normalizeIdentifier(value) {\n return value\n // Collapse markdown whitespace.\n .replace(/[\\t\\n\\r ]+/g, \" \")\n // Trim.\n .replace(/^ | $/g, '')\n // Some characters are considered “uppercase”, but if their lowercase\n // counterpart is uppercased will result in a different uppercase\n // character.\n // Hence, to get that form, we perform both lower- and uppercase.\n // Upper case makes sure keys will not interact with default prototypal\n // methods: no method is uppercase.\n .toLowerCase().toUpperCase();\n}","/**\n * @import {\n * CompileContext,\n * Extension as FromMarkdownExtension,\n * Handle as FromMarkdownHandle\n * } from 'mdast-util-from-markdown'\n * @import {ToMarkdownOptions} from 'mdast-util-gfm-footnote'\n * @import {\n * Handle as ToMarkdownHandle,\n * Map,\n * Options as ToMarkdownExtension\n * } from 'mdast-util-to-markdown'\n * @import {FootnoteDefinition, FootnoteReference} from 'mdast'\n */\n\nimport {ok as assert} from 'devlop'\nimport {normalizeIdentifier} from 'micromark-util-normalize-identifier'\n\nfootnoteReference.peek = footnoteReferencePeek\n\n/**\n * @this {CompileContext}\n * @type {FromMarkdownHandle}\n */\nfunction enterFootnoteCallString() {\n this.buffer()\n}\n\n/**\n * @this {CompileContext}\n * @type {FromMarkdownHandle}\n */\nfunction enterFootnoteCall(token) {\n this.enter({type: 'footnoteReference', identifier: '', label: ''}, token)\n}\n\n/**\n * @this {CompileContext}\n * @type {FromMarkdownHandle}\n */\nfunction enterFootnoteDefinitionLabelString() {\n this.buffer()\n}\n\n/**\n * @this {CompileContext}\n * @type {FromMarkdownHandle}\n */\nfunction enterFootnoteDefinition(token) {\n this.enter(\n {type: 'footnoteDefinition', identifier: '', label: '', children: []},\n token\n )\n}\n\n/**\n * @this {CompileContext}\n * @type {FromMarkdownHandle}\n */\nfunction exitFootnoteCallString(token) {\n const label = this.resume()\n const node = this.stack[this.stack.length - 1]\n assert(node.type === 'footnoteReference')\n node.identifier = normalizeIdentifier(\n this.sliceSerialize(token)\n ).toLowerCase()\n node.label = label\n}\n\n/**\n * @this {CompileContext}\n * @type {FromMarkdownHandle}\n */\nfunction exitFootnoteCall(token) {\n this.exit(token)\n}\n\n/**\n * @this {CompileContext}\n * @type {FromMarkdownHandle}\n */\nfunction exitFootnoteDefinitionLabelString(token) {\n const label = this.resume()\n const node = this.stack[this.stack.length - 1]\n assert(node.type === 'footnoteDefinition')\n node.identifier = normalizeIdentifier(\n this.sliceSerialize(token)\n ).toLowerCase()\n node.label = label\n}\n\n/**\n * @this {CompileContext}\n * @type {FromMarkdownHandle}\n */\nfunction exitFootnoteDefinition(token) {\n this.exit(token)\n}\n\n/** @type {ToMarkdownHandle} */\nfunction footnoteReferencePeek() {\n return '['\n}\n\n/**\n * @type {ToMarkdownHandle}\n * @param {FootnoteReference} node\n */\nfunction footnoteReference(node, _, state, info) {\n const tracker = state.createTracker(info)\n let value = tracker.move('[^')\n const exit = state.enter('footnoteReference')\n const subexit = state.enter('reference')\n value += tracker.move(\n state.safe(state.associationId(node), {after: ']', before: value})\n )\n subexit()\n exit()\n value += tracker.move(']')\n return value\n}\n\n/**\n * Create an extension for `mdast-util-from-markdown` to enable GFM footnotes\n * in markdown.\n *\n * @returns {FromMarkdownExtension}\n * Extension for `mdast-util-from-markdown`.\n */\nexport function gfmFootnoteFromMarkdown() {\n return {\n enter: {\n gfmFootnoteCallString: enterFootnoteCallString,\n gfmFootnoteCall: enterFootnoteCall,\n gfmFootnoteDefinitionLabelString: enterFootnoteDefinitionLabelString,\n gfmFootnoteDefinition: enterFootnoteDefinition\n },\n exit: {\n gfmFootnoteCallString: exitFootnoteCallString,\n gfmFootnoteCall: exitFootnoteCall,\n gfmFootnoteDefinitionLabelString: exitFootnoteDefinitionLabelString,\n gfmFootnoteDefinition: exitFootnoteDefinition\n }\n }\n}\n\n/**\n * Create an extension for `mdast-util-to-markdown` to enable GFM footnotes\n * in markdown.\n *\n * @param {ToMarkdownOptions | null | undefined} [options]\n * Configuration (optional).\n * @returns {ToMarkdownExtension}\n * Extension for `mdast-util-to-markdown`.\n */\nexport function gfmFootnoteToMarkdown(options) {\n // To do: next major: change default.\n let firstLineBlank = false\n\n if (options && options.firstLineBlank) {\n firstLineBlank = true\n }\n\n return {\n handlers: {footnoteDefinition, footnoteReference},\n // This is on by default already.\n unsafe: [{character: '[', inConstruct: ['label', 'phrasing', 'reference']}]\n }\n\n /**\n * @type {ToMarkdownHandle}\n * @param {FootnoteDefinition} node\n */\n function footnoteDefinition(node, _, state, info) {\n const tracker = state.createTracker(info)\n let value = tracker.move('[^')\n const exit = state.enter('footnoteDefinition')\n const subexit = state.enter('label')\n value += tracker.move(\n state.safe(state.associationId(node), {before: value, after: ']'})\n )\n subexit()\n\n value += tracker.move(']:')\n\n if (node.children && node.children.length > 0) {\n tracker.shift(4)\n\n value += tracker.move(\n (firstLineBlank ? '\\n' : ' ') +\n state.indentLines(\n state.containerFlow(node, tracker.current()),\n firstLineBlank ? mapAll : mapExceptFirst\n )\n )\n }\n\n exit()\n\n return value\n }\n}\n\n/** @type {Map} */\nfunction mapExceptFirst(line, index, blank) {\n return index === 0 ? line : mapAll(line, index, blank)\n}\n\n/** @type {Map} */\nfunction mapAll(line, index, blank) {\n return (blank ? '' : ' ') + line\n}\n","/**\n * @typedef {import('mdast').Delete} Delete\n *\n * @typedef {import('mdast-util-from-markdown').CompileContext} CompileContext\n * @typedef {import('mdast-util-from-markdown').Extension} FromMarkdownExtension\n * @typedef {import('mdast-util-from-markdown').Handle} FromMarkdownHandle\n *\n * @typedef {import('mdast-util-to-markdown').ConstructName} ConstructName\n * @typedef {import('mdast-util-to-markdown').Handle} ToMarkdownHandle\n * @typedef {import('mdast-util-to-markdown').Options} ToMarkdownExtension\n */\n\n/**\n * List of constructs that occur in phrasing (paragraphs, headings), but cannot\n * contain strikethrough.\n * So they sort of cancel each other out.\n * Note: could use a better name.\n *\n * Note: keep in sync with: <https://github.com/syntax-tree/mdast-util-to-markdown/blob/8ce8dbf/lib/unsafe.js#L14>\n *\n * @type {Array<ConstructName>}\n */\nconst constructsWithoutStrikethrough = [\n 'autolink',\n 'destinationLiteral',\n 'destinationRaw',\n 'reference',\n 'titleQuote',\n 'titleApostrophe'\n]\n\nhandleDelete.peek = peekDelete\n\n/**\n * Create an extension for `mdast-util-from-markdown` to enable GFM\n * strikethrough in markdown.\n *\n * @returns {FromMarkdownExtension}\n * Extension for `mdast-util-from-markdown` to enable GFM strikethrough.\n */\nexport function gfmStrikethroughFromMarkdown() {\n return {\n canContainEols: ['delete'],\n enter: {strikethrough: enterStrikethrough},\n exit: {strikethrough: exitStrikethrough}\n }\n}\n\n/**\n * Create an extension for `mdast-util-to-markdown` to enable GFM\n * strikethrough in markdown.\n *\n * @returns {ToMarkdownExtension}\n * Extension for `mdast-util-to-markdown` to enable GFM strikethrough.\n */\nexport function gfmStrikethroughToMarkdown() {\n return {\n unsafe: [\n {\n character: '~',\n inConstruct: 'phrasing',\n notInConstruct: constructsWithoutStrikethrough\n }\n ],\n handlers: {delete: handleDelete}\n }\n}\n\n/**\n * @this {CompileContext}\n * @type {FromMarkdownHandle}\n */\nfunction enterStrikethrough(token) {\n this.enter({type: 'delete', children: []}, token)\n}\n\n/**\n * @this {CompileContext}\n * @type {FromMarkdownHandle}\n */\nfunction exitStrikethrough(token) {\n this.exit(token)\n}\n\n/**\n * @type {ToMarkdownHandle}\n * @param {Delete} node\n */\nfunction handleDelete(node, _, state, info) {\n const tracker = state.createTracker(info)\n const exit = state.enter('strikethrough')\n let value = tracker.move('~~')\n value += state.containerPhrasing(node, {\n ...tracker.current(),\n before: value,\n after: '~'\n })\n value += tracker.move('~~')\n exit()\n return value\n}\n\n/** @type {ToMarkdownHandle} */\nfunction peekDelete() {\n return '~'\n}\n","// To do: next major: remove.\n/**\n * @typedef {Options} MarkdownTableOptions\n * Configuration.\n */\n\n/**\n * @typedef Options\n * Configuration.\n * @property {boolean | null | undefined} [alignDelimiters=true]\n * Whether to align the delimiters (default: `true`);\n * they are aligned by default:\n *\n * ```markdown\n * | Alpha | B |\n * | ----- | ----- |\n * | C | Delta |\n * ```\n *\n * Pass `false` to make them staggered:\n *\n * ```markdown\n * | Alpha | B |\n * | - | - |\n * | C | Delta |\n * ```\n * @property {ReadonlyArray<string | null | undefined> | string | null | undefined} [align]\n * How to align columns (default: `''`);\n * one style for all columns or styles for their respective columns;\n * each style is either `'l'` (left), `'r'` (right), or `'c'` (center);\n * other values are treated as `''`, which doesn’t place the colon in the\n * alignment row but does align left;\n * *only the lowercased first character is used, so `Right` is fine.*\n * @property {boolean | null | undefined} [delimiterEnd=true]\n * Whether to end each row with the delimiter (default: `true`).\n *\n * > 👉 **Note**: please don’t use this: it could create fragile structures\n * > that aren’t understandable to some markdown parsers.\n *\n * When `true`, there are ending delimiters:\n *\n * ```markdown\n * | Alpha | B |\n * | ----- | ----- |\n * | C | Delta |\n * ```\n *\n * When `false`, there are no ending delimiters:\n *\n * ```markdown\n * | Alpha | B\n * | ----- | -----\n * | C | Delta\n * ```\n * @property {boolean | null | undefined} [delimiterStart=true]\n * Whether to begin each row with the delimiter (default: `true`).\n *\n * > 👉 **Note**: please don’t use this: it could create fragile structures\n * > that aren’t understandable to some markdown parsers.\n *\n * When `true`, there are starting delimiters:\n *\n * ```markdown\n * | Alpha | B |\n * | ----- | ----- |\n * | C | Delta |\n * ```\n *\n * When `false`, there are no starting delimiters:\n *\n * ```markdown\n * Alpha | B |\n * ----- | ----- |\n * C | Delta |\n * ```\n * @property {boolean | null | undefined} [padding=true]\n * Whether to add a space of padding between delimiters and cells\n * (default: `true`).\n *\n * When `true`, there is padding:\n *\n * ```markdown\n * | Alpha | B |\n * | ----- | ----- |\n * | C | Delta |\n * ```\n *\n * When `false`, there is no padding:\n *\n * ```markdown\n * |Alpha|B |\n * |-----|-----|\n * |C |Delta|\n * ```\n * @property {((value: string) => number) | null | undefined} [stringLength]\n * Function to detect the length of table cell content (optional);\n * this is used when aligning the delimiters (`|`) between table cells;\n * full-width characters and emoji mess up delimiter alignment when viewing\n * the markdown source;\n * to fix this, you can pass this function,\n * which receives the cell content and returns its “visible” size;\n * note that what is and isn’t visible depends on where the text is displayed.\n *\n * Without such a function, the following:\n *\n * ```js\n * markdownTable([\n * ['Alpha', 'Bravo'],\n * ['中文', 'Charlie'],\n * ['👩❤️👩', 'Delta']\n * ])\n * ```\n *\n * Yields:\n *\n * ```markdown\n * | Alpha | Bravo |\n * | - | - |\n * | 中文 | Charlie |\n * | 👩❤️👩 | Delta |\n * ```\n *\n * With [`string-width`](https://github.com/sindresorhus/string-width):\n *\n * ```js\n * import stringWidth from 'string-width'\n *\n * markdownTable(\n * [\n * ['Alpha', 'Bravo'],\n * ['中文', 'Charlie'],\n * ['👩❤️👩', 'Delta']\n * ],\n * {stringLength: stringWidth}\n * )\n * ```\n *\n * Yields:\n *\n * ```markdown\n * | Alpha | Bravo |\n * | ----- | ------- |\n * | 中文 | Charlie |\n * | 👩❤️👩 | Delta |\n * ```\n */\n\n/**\n * @param {string} value\n * Cell value.\n * @returns {number}\n * Cell size.\n */\nfunction defaultStringLength(value) {\n return value.length\n}\n\n/**\n * Generate a markdown\n * ([GFM](https://docs.github.com/en/github/writing-on-github/working-with-advanced-formatting/organizing-information-with-tables))\n * table.\n *\n * @param {ReadonlyArray<ReadonlyArray<string | null | undefined>>} table\n * Table data (matrix of strings).\n * @param {Readonly<Options> | null | undefined} [options]\n * Configuration (optional).\n * @returns {string}\n * Result.\n */\nexport function markdownTable(table, options) {\n const settings = options || {}\n // To do: next major: change to spread.\n const align = (settings.align || []).concat()\n const stringLength = settings.stringLength || defaultStringLength\n /** @type {Array<number>} Character codes as symbols for alignment per column. */\n const alignments = []\n /** @type {Array<Array<string>>} Cells per row. */\n const cellMatrix = []\n /** @type {Array<Array<number>>} Sizes of each cell per row. */\n const sizeMatrix = []\n /** @type {Array<number>} */\n const longestCellByColumn = []\n let mostCellsPerRow = 0\n let rowIndex = -1\n\n // This is a superfluous loop if we don’t align delimiters, but otherwise we’d\n // do superfluous work when aligning, so optimize for aligning.\n while (++rowIndex < table.length) {\n /** @type {Array<string>} */\n const row = []\n /** @type {Array<number>} */\n const sizes = []\n let columnIndex = -1\n\n if (table[rowIndex].length > mostCellsPerRow) {\n mostCellsPerRow = table[rowIndex].length\n }\n\n while (++columnIndex < table[rowIndex].length) {\n const cell = serialize(table[rowIndex][columnIndex])\n\n if (settings.alignDelimiters !== false) {\n const size = stringLength(cell)\n sizes[columnIndex] = size\n\n if (\n longestCellByColumn[columnIndex] === undefined ||\n size > longestCellByColumn[columnIndex]\n ) {\n longestCellByColumn[columnIndex] = size\n }\n }\n\n row.push(cell)\n }\n\n cellMatrix[rowIndex] = row\n sizeMatrix[rowIndex] = sizes\n }\n\n // Figure out which alignments to use.\n let columnIndex = -1\n\n if (typeof align === 'object' && 'length' in align) {\n while (++columnIndex < mostCellsPerRow) {\n alignments[columnIndex] = toAlignment(align[columnIndex])\n }\n } else {\n const code = toAlignment(align)\n\n while (++columnIndex < mostCellsPerRow) {\n alignments[columnIndex] = code\n }\n }\n\n // Inject the alignment row.\n columnIndex = -1\n /** @type {Array<string>} */\n const row = []\n /** @type {Array<number>} */\n const sizes = []\n\n while (++columnIndex < mostCellsPerRow) {\n const code = alignments[columnIndex]\n let before = ''\n let after = ''\n\n if (code === 99 /* `c` */) {\n before = ':'\n after = ':'\n } else if (code === 108 /* `l` */) {\n before = ':'\n } else if (code === 114 /* `r` */) {\n after = ':'\n }\n\n // There *must* be at least one hyphen-minus in each alignment cell.\n let size =\n settings.alignDelimiters === false\n ? 1\n : Math.max(\n 1,\n longestCellByColumn[columnIndex] - before.length - after.length\n )\n\n const cell = before + '-'.repeat(size) + after\n\n if (settings.alignDelimiters !== false) {\n size = before.length + size + after.length\n\n if (size > longestCellByColumn[columnIndex]) {\n longestCellByColumn[columnIndex] = size\n }\n\n sizes[columnIndex] = size\n }\n\n row[columnIndex] = cell\n }\n\n // Inject the alignment row.\n cellMatrix.splice(1, 0, row)\n sizeMatrix.splice(1, 0, sizes)\n\n rowIndex = -1\n /** @type {Array<string>} */\n const lines = []\n\n while (++rowIndex < cellMatrix.length) {\n const row = cellMatrix[rowIndex]\n const sizes = sizeMatrix[rowIndex]\n columnIndex = -1\n /** @type {Array<string>} */\n const line = []\n\n while (++columnIndex < mostCellsPerRow) {\n const cell = row[columnIndex] || ''\n let before = ''\n let after = ''\n\n if (settings.alignDelimiters !== false) {\n const size =\n longestCellByColumn[columnIndex] - (sizes[columnIndex] || 0)\n const code = alignments[columnIndex]\n\n if (code === 114 /* `r` */) {\n before = ' '.repeat(size)\n } else if (code === 99 /* `c` */) {\n if (size % 2) {\n before = ' '.repeat(size / 2 + 0.5)\n after = ' '.repeat(size / 2 - 0.5)\n } else {\n before = ' '.repeat(size / 2)\n after = before\n }\n } else {\n after = ' '.repeat(size)\n }\n }\n\n if (settings.delimiterStart !== false && !columnIndex) {\n line.push('|')\n }\n\n if (\n settings.padding !== false &&\n // Don’t add the opening space if we’re not aligning and the cell is\n // empty: there will be a closing space.\n !(settings.alignDelimiters === false && cell === '') &&\n (settings.delimiterStart !== false || columnIndex)\n ) {\n line.push(' ')\n }\n\n if (settings.alignDelimiters !== false) {\n line.push(before)\n }\n\n line.push(cell)\n\n if (settings.alignDelimiters !== false) {\n line.push(after)\n }\n\n if (settings.padding !== false) {\n line.push(' ')\n }\n\n if (\n settings.delimiterEnd !== false ||\n columnIndex !== mostCellsPerRow - 1\n ) {\n line.push('|')\n }\n }\n\n lines.push(\n settings.delimiterEnd === false\n ? line.join('').replace(/ +$/, '')\n : line.join('')\n )\n }\n\n return lines.join('\\n')\n}\n\n/**\n * @param {string | null | undefined} [value]\n * Value to serialize.\n * @returns {string}\n * Result.\n */\nfunction serialize(value) {\n return value === null || value === undefined ? '' : String(value)\n}\n\n/**\n * @param {string | null | undefined} value\n * Value.\n * @returns {number}\n * Alignment.\n */\nfunction toAlignment(value) {\n const code = typeof value === 'string' ? value.codePointAt(0) : 0\n\n return code === 67 /* `C` */ || code === 99 /* `c` */\n ? 99 /* `c` */\n : code === 76 /* `L` */ || code === 108 /* `l` */\n ? 108 /* `l` */\n : code === 82 /* `R` */ || code === 114 /* `r` */\n ? 114 /* `r` */\n : 0\n}\n","/**\n * @import {Blockquote, Parents} from 'mdast'\n * @import {Info, Map, State} from 'mdast-util-to-markdown'\n */\n\n/**\n * @param {Blockquote} node\n * @param {Parents | undefined} _\n * @param {State} state\n * @param {Info} info\n * @returns {string}\n */\nexport function blockquote(node, _, state, info) {\n const exit = state.enter('blockquote')\n const tracker = state.createTracker(info)\n tracker.move('> ')\n tracker.shift(2)\n const value = state.indentLines(\n state.containerFlow(node, tracker.current()),\n map\n )\n exit()\n return value\n}\n\n/** @type {Map} */\nfunction map(line, _, blank) {\n return '>' + (blank ? '' : ' ') + line\n}\n","/**\n * @import {ConstructName, Unsafe} from 'mdast-util-to-markdown'\n */\n\n/**\n * @param {Array<ConstructName>} stack\n * @param {Unsafe} pattern\n * @returns {boolean}\n */\nexport function patternInScope(stack, pattern) {\n return (\n listInScope(stack, pattern.inConstruct, true) &&\n !listInScope(stack, pattern.notInConstruct, false)\n )\n}\n\n/**\n * @param {Array<ConstructName>} stack\n * @param {Unsafe['inConstruct']} list\n * @param {boolean} none\n * @returns {boolean}\n */\nfunction listInScope(stack, list, none) {\n if (typeof list === 'string') {\n list = [list]\n }\n\n if (!list || list.length === 0) {\n return none\n }\n\n let index = -1\n\n while (++index < list.length) {\n if (stack.includes(list[index])) {\n return true\n }\n }\n\n return false\n}\n","/**\n * @import {Break, Parents} from 'mdast'\n * @import {Info, State} from 'mdast-util-to-markdown'\n */\n\nimport {patternInScope} from '../util/pattern-in-scope.js'\n\n/**\n * @param {Break} _\n * @param {Parents | undefined} _1\n * @param {State} state\n * @param {Info} info\n * @returns {string}\n */\nexport function hardBreak(_, _1, state, info) {\n let index = -1\n\n while (++index < state.unsafe.length) {\n // If we can’t put eols in this construct (setext headings, tables), use a\n // space instead.\n if (\n state.unsafe[index].character === '\\n' &&\n patternInScope(state.stack, state.unsafe[index])\n ) {\n return /[ \\t]/.test(info.before) ? '' : ' '\n }\n }\n\n return '\\\\\\n'\n}\n","/**\n * Get the count of the longest repeating streak of `substring` in `value`.\n *\n * @param {string} value\n * Content to search in.\n * @param {string} substring\n * Substring to look for, typically one character.\n * @returns {number}\n * Count of most frequent adjacent `substring`s in `value`.\n */\nexport function longestStreak(value, substring) {\n const source = String(value)\n let index = source.indexOf(substring)\n let expected = index\n let count = 0\n let max = 0\n\n if (typeof substring !== 'string') {\n throw new TypeError('Expected substring')\n }\n\n while (index !== -1) {\n if (index === expected) {\n if (++count > max) {\n max = count\n }\n } else {\n count = 1\n }\n\n expected = index + substring.length\n index = source.indexOf(substring, expected)\n }\n\n return max\n}\n","/**\n * @import {State} from 'mdast-util-to-markdown'\n * @import {Code} from 'mdast'\n */\n\n/**\n * @param {Code} node\n * @param {State} state\n * @returns {boolean}\n */\nexport function formatCodeAsIndented(node, state) {\n return Boolean(\n state.options.fences === false &&\n node.value &&\n // If there’s no info…\n !node.lang &&\n // And there’s a non-whitespace character…\n /[^ \\r\\n]/.test(node.value) &&\n // And the value doesn’t start or end in a blank…\n !/^[\\t ]*(?:[\\r\\n]|$)|(?:^|[\\r\\n])[\\t ]*$/.test(node.value)\n )\n}\n","/**\n * @import {Options, State} from 'mdast-util-to-markdown'\n */\n\n/**\n * @param {State} state\n * @returns {Exclude<Options['fence'], null | undefined>}\n */\nexport function checkFence(state) {\n const marker = state.options.fence || '`'\n\n if (marker !== '`' && marker !== '~') {\n throw new Error(\n 'Cannot serialize code with `' +\n marker +\n '` for `options.fence`, expected `` ` `` or `~`'\n )\n }\n\n return marker\n}\n","/**\n * @import {Info, Map, State} from 'mdast-util-to-markdown'\n * @import {Code, Parents} from 'mdast'\n */\n\nimport {longestStreak} from 'longest-streak'\nimport {formatCodeAsIndented} from '../util/format-code-as-indented.js'\nimport {checkFence} from '../util/check-fence.js'\n\n/**\n * @param {Code} node\n * @param {Parents | undefined} _\n * @param {State} state\n * @param {Info} info\n * @returns {string}\n */\nexport function code(node, _, state, info) {\n const marker = checkFence(state)\n const raw = node.value || ''\n const suffix = marker === '`' ? 'GraveAccent' : 'Tilde'\n\n if (formatCodeAsIndented(node, state)) {\n const exit = state.enter('codeIndented')\n const value = state.indentLines(raw, map)\n exit()\n return value\n }\n\n const tracker = state.createTracker(info)\n const sequence = marker.repeat(Math.max(longestStreak(raw, marker) + 1, 3))\n const exit = state.enter('codeFenced')\n let value = tracker.move(sequence)\n\n if (node.lang) {\n const subexit = state.enter(`codeFencedLang${suffix}`)\n value += tracker.move(\n state.safe(node.lang, {\n before: value,\n after: ' ',\n encode: ['`'],\n ...tracker.current()\n })\n )\n subexit()\n }\n\n if (node.lang && node.meta) {\n const subexit = state.enter(`codeFencedMeta${suffix}`)\n value += tracker.move(' ')\n value += tracker.move(\n state.safe(node.meta, {\n before: value,\n after: '\\n',\n encode: ['`'],\n ...tracker.current()\n })\n )\n subexit()\n }\n\n value += tracker.move('\\n')\n\n if (raw) {\n value += tracker.move(raw + '\\n')\n }\n\n value += tracker.move(sequence)\n exit()\n return value\n}\n\n/** @type {Map} */\nfunction map(line, _, blank) {\n return (blank ? '' : ' ') + line\n}\n","/**\n * @import {Options, State} from 'mdast-util-to-markdown'\n */\n\n/**\n * @param {State} state\n * @returns {Exclude<Options['quote'], null | undefined>}\n */\nexport function checkQuote(state) {\n const marker = state.options.quote || '\"'\n\n if (marker !== '\"' && marker !== \"'\") {\n throw new Error(\n 'Cannot serialize title with `' +\n marker +\n '` for `options.quote`, expected `\"`, or `\\'`'\n )\n }\n\n return marker\n}\n","/**\n * @import {Info, State} from 'mdast-util-to-markdown'\n * @import {Definition, Parents} from 'mdast'\n */\n\nimport {checkQuote} from '../util/check-quote.js'\n\n/**\n * @param {Definition} node\n * @param {Parents | undefined} _\n * @param {State} state\n * @param {Info} info\n * @returns {string}\n */\nexport function definition(node, _, state, info) {\n const quote = checkQuote(state)\n const suffix = quote === '\"' ? 'Quote' : 'Apostrophe'\n const exit = state.enter('definition')\n let subexit = state.enter('label')\n const tracker = state.createTracker(info)\n let value = tracker.move('[')\n value += tracker.move(\n state.safe(state.associationId(node), {\n before: value,\n after: ']',\n ...tracker.current()\n })\n )\n value += tracker.move(']: ')\n\n subexit()\n\n if (\n // If there’s no url, or…\n !node.url ||\n // If there are control characters or whitespace.\n /[\\0- \\u007F]/.test(node.url)\n ) {\n subexit = state.enter('destinationLiteral')\n value += tracker.move('<')\n value += tracker.move(\n state.safe(node.url, {before: value, after: '>', ...tracker.current()})\n )\n value += tracker.move('>')\n } else {\n // No whitespace, raw is prettier.\n subexit = state.enter('destinationRaw')\n value += tracker.move(\n state.safe(node.url, {\n before: value,\n after: node.title ? ' ' : '\\n',\n ...tracker.current()\n })\n )\n }\n\n subexit()\n\n if (node.title) {\n subexit = state.enter(`title${suffix}`)\n value += tracker.move(' ' + quote)\n value += tracker.move(\n state.safe(node.title, {\n before: value,\n after: quote,\n ...tracker.current()\n })\n )\n value += tracker.move(quote)\n subexit()\n }\n\n exit()\n\n return value\n}\n","/**\n * @import {Options, State} from 'mdast-util-to-markdown'\n */\n\n/**\n * @param {State} state\n * @returns {Exclude<Options['emphasis'], null | undefined>}\n */\nexport function checkEmphasis(state) {\n const marker = state.options.emphasis || '*'\n\n if (marker !== '*' && marker !== '_') {\n throw new Error(\n 'Cannot serialize emphasis with `' +\n marker +\n '` for `options.emphasis`, expected `*`, or `_`'\n )\n }\n\n return marker\n}\n","/**\n * Encode a code point as a character reference.\n *\n * @param {number} code\n * Code point to encode.\n * @returns {string}\n * Encoded character reference.\n */\nexport function encodeCharacterReference(code) {\n return '&#x' + code.toString(16).toUpperCase() + ';'\n}\n","/**\n * @import {Code} from 'micromark-util-types'\n */\n\nimport { markdownLineEndingOrSpace, unicodePunctuation, unicodeWhitespace } from 'micromark-util-character';\n/**\n * Classify whether a code represents whitespace, punctuation, or something\n * else.\n *\n * Used for attention (emphasis, strong), whose sequences can open or close\n * based on the class of surrounding characters.\n *\n * > 👉 **Note**: eof (`null`) is seen as whitespace.\n *\n * @param {Code} code\n * Code.\n * @returns {typeof constants.characterGroupWhitespace | typeof constants.characterGroupPunctuation | undefined}\n * Group.\n */\nexport function classifyCharacter(code) {\n if (code === null || markdownLineEndingOrSpace(code) || unicodeWhitespace(code)) {\n return 1;\n }\n if (unicodePunctuation(code)) {\n return 2;\n }\n}","/**\n * @import {EncodeSides} from '../types.js'\n */\n\nimport {classifyCharacter} from 'micromark-util-classify-character'\n\n/**\n * Check whether to encode (as a character reference) the characters\n * surrounding an attention run.\n *\n * Which characters are around an attention run influence whether it works or\n * not.\n *\n * See <https://github.com/orgs/syntax-tree/discussions/60> for more info.\n * See this markdown in a particular renderer to see what works:\n *\n * ```markdown\n * | | A (letter inside) | B (punctuation inside) | C (whitespace inside) | D (nothing inside) |\n * | ----------------------- | ----------------- | ---------------------- | --------------------- | ------------------ |\n * | 1 (letter outside) | x*y*z | x*.*z | x* *z | x**z |\n * | 2 (punctuation outside) | .*y*. | .*.*. | .* *. | .**. |\n * | 3 (whitespace outside) | x *y* z | x *.* z | x * * z | x ** z |\n * | 4 (nothing outside) | *x* | *.* | * * | ** |\n * ```\n *\n * @param {number} outside\n * Code point on the outer side of the run.\n * @param {number} inside\n * Code point on the inner side of the run.\n * @param {'*' | '_'} marker\n * Marker of the run.\n * Underscores are handled more strictly (they form less often) than\n * asterisks.\n * @returns {EncodeSides}\n * Whether to encode characters.\n */\n// Important: punctuation must never be encoded.\n// Punctuation is solely used by markdown constructs.\n// And by encoding itself.\n// Encoding them will break constructs or double encode things.\nexport function encodeInfo(outside, inside, marker) {\n const outsideKind = classifyCharacter(outside)\n const insideKind = classifyCharacter(inside)\n\n // Letter outside:\n if (outsideKind === undefined) {\n return insideKind === undefined\n ? // Letter inside:\n // we have to encode *both* letters for `_` as it is looser.\n // it already forms for `*` (and GFMs `~`).\n marker === '_'\n ? {inside: true, outside: true}\n : {inside: false, outside: false}\n : insideKind === 1\n ? // Whitespace inside: encode both (letter, whitespace).\n {inside: true, outside: true}\n : // Punctuation inside: encode outer (letter)\n {inside: false, outside: true}\n }\n\n // Whitespace outside:\n if (outsideKind === 1) {\n return insideKind === undefined\n ? // Letter inside: already forms.\n {inside: false, outside: false}\n : insideKind === 1\n ? // Whitespace inside: encode both (whitespace).\n {inside: true, outside: true}\n : // Punctuation inside: already forms.\n {inside: false, outside: false}\n }\n\n // Punctuation outside:\n return insideKind === undefined\n ? // Letter inside: already forms.\n {inside: false, outside: false}\n : insideKind === 1\n ? // Whitespace inside: encode inner (whitespace).\n {inside: true, outside: false}\n : // Punctuation inside: already forms.\n {inside: false, outside: false}\n}\n","/**\n * @import {Info, State} from 'mdast-util-to-markdown'\n * @import {Emphasis, Parents} from 'mdast'\n */\n\nimport {checkEmphasis} from '../util/check-emphasis.js'\nimport {encodeCharacterReference} from '../util/encode-character-reference.js'\nimport {encodeInfo} from '../util/encode-info.js'\n\nemphasis.peek = emphasisPeek\n\n/**\n * @param {Emphasis} node\n * @param {Parents | undefined} _\n * @param {State} state\n * @param {Info} info\n * @returns {string}\n */\nexport function emphasis(node, _, state, info) {\n const marker = checkEmphasis(state)\n const exit = state.enter('emphasis')\n const tracker = state.createTracker(info)\n const before = tracker.move(marker)\n\n let between = tracker.move(\n state.containerPhrasing(node, {\n after: marker,\n before,\n ...tracker.current()\n })\n )\n const betweenHead = between.charCodeAt(0)\n const open = encodeInfo(\n info.before.charCodeAt(info.before.length - 1),\n betweenHead,\n marker\n )\n\n if (open.inside) {\n between = encodeCharacterReference(betweenHead) + between.slice(1)\n }\n\n const betweenTail = between.charCodeAt(between.length - 1)\n const close = encodeInfo(info.after.charCodeAt(0), betweenTail, marker)\n\n if (close.inside) {\n between = between.slice(0, -1) + encodeCharacterReference(betweenTail)\n }\n\n const after = tracker.move(marker)\n\n exit()\n\n state.attentionEncodeSurroundingInfo = {\n after: close.outside,\n before: open.outside\n }\n return before + between + after\n}\n\n/**\n * @param {Emphasis} _\n * @param {Parents | undefined} _1\n * @param {State} state\n * @returns {string}\n */\nfunction emphasisPeek(_, _1, state) {\n return state.options.emphasis || '*'\n}\n","/**\n * @typedef {import('unist').Node} UnistNode\n * @typedef {import('unist').Parent} UnistParent\n * @typedef {import('unist-util-visit-parents').VisitorResult} VisitorResult\n */\n\n/**\n * @typedef {Exclude<import('unist-util-is').Test, undefined> | undefined} Test\n * Test from `unist-util-is`.\n *\n * Note: we have remove and add `undefined`, because otherwise when generating\n * automatic `.d.ts` files, TS tries to flatten paths from a local perspective,\n * which doesn’t work when publishing on npm.\n */\n\n// To do: use types from `unist-util-visit-parents` when it’s released.\n\n/**\n * @typedef {(\n * Fn extends (value: any) => value is infer Thing\n * ? Thing\n * : Fallback\n * )} Predicate\n * Get the value of a type guard `Fn`.\n * @template Fn\n * Value; typically function that is a type guard (such as `(x): x is Y`).\n * @template Fallback\n * Value to yield if `Fn` is not a type guard.\n */\n\n/**\n * @typedef {(\n * Check extends null | undefined // No test.\n * ? Value\n * : Value extends {type: Check} // String (type) test.\n * ? Value\n * : Value extends Check // Partial test.\n * ? Value\n * : Check extends Function // Function test.\n * ? Predicate<Check, Value> extends Value\n * ? Predicate<Check, Value>\n * : never\n * : never // Some other test?\n * )} MatchesOne\n * Check whether a node matches a primitive check in the type system.\n * @template Value\n * Value; typically unist `Node`.\n * @template Check\n * Value; typically `unist-util-is`-compatible test, but not arrays.\n */\n\n/**\n * @typedef {(\n * Check extends Array<any>\n * ? MatchesOne<Value, Check[keyof Check]>\n * : MatchesOne<Value, Check>\n * )} Matches\n * Check whether a node matches a check in the type system.\n * @template Value\n * Value; typically unist `Node`.\n * @template Check\n * Value; typically `unist-util-is`-compatible test.\n */\n\n/**\n * @typedef {0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10} Uint\n * Number; capped reasonably.\n */\n\n/**\n * @typedef {I extends 0 ? 1 : I extends 1 ? 2 : I extends 2 ? 3 : I extends 3 ? 4 : I extends 4 ? 5 : I extends 5 ? 6 : I extends 6 ? 7 : I extends 7 ? 8 : I extends 8 ? 9 : 10} Increment\n * Increment a number in the type system.\n * @template {Uint} [I=0]\n * Index.\n */\n\n/**\n * @typedef {(\n * Node extends UnistParent\n * ? Node extends {children: Array<infer Children>}\n * ? Child extends Children ? Node : never\n * : never\n * : never\n * )} InternalParent\n * Collect nodes that can be parents of `Child`.\n * @template {UnistNode} Node\n * All node types in a tree.\n * @template {UnistNode} Child\n * Node to search for.\n */\n\n/**\n * @typedef {InternalParent<InclusiveDescendant<Tree>, Child>} Parent\n * Collect nodes in `Tree` that can be parents of `Child`.\n * @template {UnistNode} Tree\n * All node types in a tree.\n * @template {UnistNode} Child\n * Node to search for.\n */\n\n/**\n * @typedef {(\n * Depth extends Max\n * ? never\n * :\n * | InternalParent<Node, Child>\n * | InternalAncestor<Node, InternalParent<Node, Child>, Max, Increment<Depth>>\n * )} InternalAncestor\n * Collect nodes in `Tree` that can be ancestors of `Child`.\n * @template {UnistNode} Node\n * All node types in a tree.\n * @template {UnistNode} Child\n * Node to search for.\n * @template {Uint} [Max=10]\n * Max; searches up to this depth.\n * @template {Uint} [Depth=0]\n * Current depth.\n */\n\n/**\n * @typedef {(\n * Tree extends UnistParent\n * ? Depth extends Max\n * ? Tree\n * : Tree | InclusiveDescendant<Tree['children'][number], Max, Increment<Depth>>\n * : Tree\n * )} InclusiveDescendant\n * Collect all (inclusive) descendants of `Tree`.\n *\n * > 👉 **Note**: for performance reasons, this seems to be the fastest way to\n * > recurse without actually running into an infinite loop, which the\n * > previous version did.\n * >\n * > Practically, a max of `2` is typically enough assuming a `Root` is\n * > passed, but it doesn’t improve performance.\n * > It gets higher with `List > ListItem > Table > TableRow > TableCell`.\n * > Using up to `10` doesn’t hurt or help either.\n * @template {UnistNode} Tree\n * Tree type.\n * @template {Uint} [Max=10]\n * Max; searches up to this depth.\n * @template {Uint} [Depth=0]\n * Current depth.\n */\n\n/**\n * @callback Visitor\n * Handle a node (matching `test`, if given).\n *\n * Visitors are free to transform `node`.\n * They can also transform `parent`.\n *\n * Replacing `node` itself, if `SKIP` is not returned, still causes its\n * descendants to be walked (which is a bug).\n *\n * When adding or removing previous siblings of `node` (or next siblings, in\n * case of reverse), the `Visitor` should return a new `Index` to specify the\n * sibling to traverse after `node` is traversed.\n * Adding or removing next siblings of `node` (or previous siblings, in case\n * of reverse) is handled as expected without needing to return a new `Index`.\n *\n * Removing the children property of `parent` still results in them being\n * traversed.\n * @param {Visited} node\n * Found node.\n * @param {Visited extends UnistNode ? number | undefined : never} index\n * Index of `node` in `parent`.\n * @param {Ancestor extends UnistParent ? Ancestor | undefined : never} parent\n * Parent of `node`.\n * @returns {VisitorResult}\n * What to do next.\n *\n * An `Index` is treated as a tuple of `[CONTINUE, Index]`.\n * An `Action` is treated as a tuple of `[Action]`.\n *\n * Passing a tuple back only makes sense if the `Action` is `SKIP`.\n * When the `Action` is `EXIT`, that action can be returned.\n * When the `Action` is `CONTINUE`, `Index` can be returned.\n * @template {UnistNode} [Visited=UnistNode]\n * Visited node type.\n * @template {UnistParent} [Ancestor=UnistParent]\n * Ancestor type.\n */\n\n/**\n * @typedef {Visitor<Visited, Parent<Ancestor, Visited>>} BuildVisitorFromMatch\n * Build a typed `Visitor` function from a node and all possible parents.\n *\n * It will infer which values are passed as `node` and which as `parent`.\n * @template {UnistNode} Visited\n * Node type.\n * @template {UnistParent} Ancestor\n * Parent type.\n */\n\n/**\n * @typedef {(\n * BuildVisitorFromMatch<\n * Matches<Descendant, Check>,\n * Extract<Descendant, UnistParent>\n * >\n * )} BuildVisitorFromDescendants\n * Build a typed `Visitor` function from a list of descendants and a test.\n *\n * It will infer which values are passed as `node` and which as `parent`.\n * @template {UnistNode} Descendant\n * Node type.\n * @template {Test} Check\n * Test type.\n */\n\n/**\n * @typedef {(\n * BuildVisitorFromDescendants<\n * InclusiveDescendant<Tree>,\n * Check\n * >\n * )} BuildVisitor\n * Build a typed `Visitor` function from a tree and a test.\n *\n * It will infer which values are passed as `node` and which as `parent`.\n * @template {UnistNode} [Tree=UnistNode]\n * Node type.\n * @template {Test} [Check=Test]\n * Test type.\n */\n\nimport {visitParents} from 'unist-util-visit-parents'\n\nexport {CONTINUE, EXIT, SKIP} from 'unist-util-visit-parents'\n\n/**\n * Visit nodes.\n *\n * This algorithm performs *depth-first* *tree traversal* in *preorder*\n * (**NLR**) or if `reverse` is given, in *reverse preorder* (**NRL**).\n *\n * You can choose for which nodes `visitor` is called by passing a `test`.\n * For complex tests, you should test yourself in `visitor`, as it will be\n * faster and will have improved type information.\n *\n * Walking the tree is an intensive task.\n * Make use of the return values of the visitor when possible.\n * Instead of walking a tree multiple times, walk it once, use `unist-util-is`\n * to check if a node matches, and then perform different operations.\n *\n * You can change the tree.\n * See `Visitor` for more info.\n *\n * @overload\n * @param {Tree} tree\n * @param {Check} check\n * @param {BuildVisitor<Tree, Check>} visitor\n * @param {boolean | null | undefined} [reverse]\n * @returns {undefined}\n *\n * @overload\n * @param {Tree} tree\n * @param {BuildVisitor<Tree>} visitor\n * @param {boolean | null | undefined} [reverse]\n * @returns {undefined}\n *\n * @param {UnistNode} tree\n * Tree to traverse.\n * @param {Visitor | Test} testOrVisitor\n * `unist-util-is`-compatible test (optional, omit to pass a visitor).\n * @param {Visitor | boolean | null | undefined} [visitorOrReverse]\n * Handle each node (when test is omitted, pass `reverse`).\n * @param {boolean | null | undefined} [maybeReverse=false]\n * Traverse in reverse preorder (NRL) instead of the default preorder (NLR).\n * @returns {undefined}\n * Nothing.\n *\n * @template {UnistNode} Tree\n * Node type.\n * @template {Test} Check\n * `unist-util-is`-compatible test.\n */\nexport function visit(tree, testOrVisitor, visitorOrReverse, maybeReverse) {\n /** @type {boolean | null | undefined} */\n let reverse\n /** @type {Test} */\n let test\n /** @type {Visitor} */\n let visitor\n\n if (\n typeof testOrVisitor === 'function' &&\n typeof visitorOrReverse !== 'function'\n ) {\n test = undefined\n visitor = testOrVisitor\n reverse = visitorOrReverse\n } else {\n // @ts-expect-error: assume the overload with test was given.\n test = testOrVisitor\n // @ts-expect-error: assume the overload with test was given.\n visitor = visitorOrReverse\n reverse = maybeReverse\n }\n\n visitParents(tree, test, overload, reverse)\n\n /**\n * @param {UnistNode} node\n * @param {Array<UnistParent>} parents\n */\n function overload(node, parents) {\n const parent = parents[parents.length - 1]\n const index = parent ? parent.children.indexOf(node) : undefined\n return visitor(node, index, parent)\n }\n}\n","/**\n * @typedef {import('mdast').Nodes} Nodes\n *\n * @typedef Options\n * Configuration (optional).\n * @property {boolean | null | undefined} [includeImageAlt=true]\n * Whether to use `alt` for `image`s (default: `true`).\n * @property {boolean | null | undefined} [includeHtml=true]\n * Whether to use `value` of HTML (default: `true`).\n */\n\n/** @type {Options} */\nconst emptyOptions = {}\n\n/**\n * Get the text content of a node or list of nodes.\n *\n * Prefers the node’s plain-text fields, otherwise serializes its children,\n * and if the given value is an array, serialize the nodes in it.\n *\n * @param {unknown} [value]\n * Thing to serialize, typically `Node`.\n * @param {Options | null | undefined} [options]\n * Configuration (optional).\n * @returns {string}\n * Serialized `value`.\n */\nexport function toString(value, options) {\n const settings = options || emptyOptions\n const includeImageAlt =\n typeof settings.includeImageAlt === 'boolean'\n ? settings.includeImageAlt\n : true\n const includeHtml =\n typeof settings.includeHtml === 'boolean' ? settings.includeHtml : true\n\n return one(value, includeImageAlt, includeHtml)\n}\n\n/**\n * One node or several nodes.\n *\n * @param {unknown} value\n * Thing to serialize.\n * @param {boolean} includeImageAlt\n * Include image `alt`s.\n * @param {boolean} includeHtml\n * Include HTML.\n * @returns {string}\n * Serialized node.\n */\nfunction one(value, includeImageAlt, includeHtml) {\n if (node(value)) {\n if ('value' in value) {\n return value.type === 'html' && !includeHtml ? '' : value.value\n }\n\n if (includeImageAlt && 'alt' in value && value.alt) {\n return value.alt\n }\n\n if ('children' in value) {\n return all(value.children, includeImageAlt, includeHtml)\n }\n }\n\n if (Array.isArray(value)) {\n return all(value, includeImageAlt, includeHtml)\n }\n\n return ''\n}\n\n/**\n * Serialize a list of nodes.\n *\n * @param {Array<unknown>} values\n * Thing to serialize.\n * @param {boolean} includeImageAlt\n * Include image `alt`s.\n * @param {boolean} includeHtml\n * Include HTML.\n * @returns {string}\n * Serialized nodes.\n */\nfunction all(values, includeImageAlt, includeHtml) {\n /** @type {Array<string>} */\n const result = []\n let index = -1\n\n while (++index < values.length) {\n result[index] = one(values[index], includeImageAlt, includeHtml)\n }\n\n return result.join('')\n}\n\n/**\n * Check if `value` looks like a node.\n *\n * @param {unknown} value\n * Thing.\n * @returns {value is Nodes}\n * Whether `value` is a node.\n */\nfunction node(value) {\n return Boolean(value && typeof value === 'object')\n}\n","/**\n * @import {State} from 'mdast-util-to-markdown'\n * @import {Heading} from 'mdast'\n */\n\nimport {EXIT, visit} from 'unist-util-visit'\nimport {toString} from 'mdast-util-to-string'\n\n/**\n * @param {Heading} node\n * @param {State} state\n * @returns {boolean}\n */\nexport function formatHeadingAsSetext(node, state) {\n let literalWithBreak = false\n\n // Look for literals with a line break.\n // Note that this also\n visit(node, function (node) {\n if (\n ('value' in node && /\\r?\\n|\\r/.test(node.value)) ||\n node.type === 'break'\n ) {\n literalWithBreak = true\n return EXIT\n }\n })\n\n return Boolean(\n (!node.depth || node.depth < 3) &&\n toString(node) &&\n (state.options.setext || literalWithBreak)\n )\n}\n","/**\n * @import {Info, State} from 'mdast-util-to-markdown'\n * @import {Heading, Parents} from 'mdast'\n */\n\nimport {encodeCharacterReference} from '../util/encode-character-reference.js'\nimport {formatHeadingAsSetext} from '../util/format-heading-as-setext.js'\n\n/**\n * @param {Heading} node\n * @param {Parents | undefined} _\n * @param {State} state\n * @param {Info} info\n * @returns {string}\n */\nexport function heading(node, _, state, info) {\n const rank = Math.max(Math.min(6, node.depth || 1), 1)\n const tracker = state.createTracker(info)\n\n if (formatHeadingAsSetext(node, state)) {\n const exit = state.enter('headingSetext')\n const subexit = state.enter('phrasing')\n const value = state.containerPhrasing(node, {\n ...tracker.current(),\n before: '\\n',\n after: '\\n'\n })\n subexit()\n exit()\n\n return (\n value +\n '\\n' +\n (rank === 1 ? '=' : '-').repeat(\n // The whole size…\n value.length -\n // Minus the position of the character after the last EOL (or\n // 0 if there is none)…\n (Math.max(value.lastIndexOf('\\r'), value.lastIndexOf('\\n')) + 1)\n )\n )\n }\n\n const sequence = '#'.repeat(rank)\n const exit = state.enter('headingAtx')\n const subexit = state.enter('phrasing')\n\n // Note: for proper tracking, we should reset the output positions when there\n // is no content returned, because then the space is not output.\n // Practically, in that case, there is no content, so it doesn’t matter that\n // we’ve tracked one too many characters.\n tracker.move(sequence + ' ')\n\n let value = state.containerPhrasing(node, {\n before: '# ',\n after: '\\n',\n ...tracker.current()\n })\n\n if (/^[\\t ]/.test(value)) {\n // To do: what effect has the character reference on tracking?\n value = encodeCharacterReference(value.charCodeAt(0)) + value.slice(1)\n }\n\n value = value ? sequence + ' ' + value : sequence\n\n if (state.options.closeAtx) {\n value += ' ' + sequence\n }\n\n subexit()\n exit()\n\n return value\n}\n","/**\n * @import {Html} from 'mdast'\n */\n\nhtml.peek = htmlPeek\n\n/**\n * @param {Html} node\n * @returns {string}\n */\nexport function html(node) {\n return node.value || ''\n}\n\n/**\n * @returns {string}\n */\nfunction htmlPeek() {\n return '<'\n}\n","/**\n * @import {Info, State} from 'mdast-util-to-markdown'\n * @import {Image, Parents} from 'mdast'\n */\n\nimport {checkQuote} from '../util/check-quote.js'\n\nimage.peek = imagePeek\n\n/**\n * @param {Image} node\n * @param {Parents | undefined} _\n * @param {State} state\n * @param {Info} info\n * @returns {string}\n */\nexport function image(node, _, state, info) {\n const quote = checkQuote(state)\n const suffix = quote === '\"' ? 'Quote' : 'Apostrophe'\n const exit = state.enter('image')\n let subexit = state.enter('label')\n const tracker = state.createTracker(info)\n let value = tracker.move('![')\n value += tracker.move(\n state.safe(node.alt, {before: value, after: ']', ...tracker.current()})\n )\n value += tracker.move('](')\n\n subexit()\n\n if (\n // If there’s no url but there is a title…\n (!node.url && node.title) ||\n // If there are control characters or whitespace.\n /[\\0- \\u007F]/.test(node.url)\n ) {\n subexit = state.enter('destinationLiteral')\n value += tracker.move('<')\n value += tracker.move(\n state.safe(node.url, {before: value, after: '>', ...tracker.current()})\n )\n value += tracker.move('>')\n } else {\n // No whitespace, raw is prettier.\n subexit = state.enter('destinationRaw')\n value += tracker.move(\n state.safe(node.url, {\n before: value,\n after: node.title ? ' ' : ')',\n ...tracker.current()\n })\n )\n }\n\n subexit()\n\n if (node.title) {\n subexit = state.enter(`title${suffix}`)\n value += tracker.move(' ' + quote)\n value += tracker.move(\n state.safe(node.title, {\n before: value,\n after: quote,\n ...tracker.current()\n })\n )\n value += tracker.move(quote)\n subexit()\n }\n\n value += tracker.move(')')\n exit()\n\n return value\n}\n\n/**\n * @returns {string}\n */\nfunction imagePeek() {\n return '!'\n}\n","/**\n * @import {Info, State} from 'mdast-util-to-markdown'\n * @import {ImageReference, Parents} from 'mdast'\n */\n\nimageReference.peek = imageReferencePeek\n\n/**\n * @param {ImageReference} node\n * @param {Parents | undefined} _\n * @param {State} state\n * @param {Info} info\n * @returns {string}\n */\nexport function imageReference(node, _, state, info) {\n const type = node.referenceType\n const exit = state.enter('imageReference')\n let subexit = state.enter('label')\n const tracker = state.createTracker(info)\n let value = tracker.move('![')\n const alt = state.safe(node.alt, {\n before: value,\n after: ']',\n ...tracker.current()\n })\n value += tracker.move(alt + '][')\n\n subexit()\n // Hide the fact that we’re in phrasing, because escapes don’t work.\n const stack = state.stack\n state.stack = []\n subexit = state.enter('reference')\n // Note: for proper tracking, we should reset the output positions when we end\n // up making a `shortcut` reference, because then there is no brace output.\n // Practically, in that case, there is no content, so it doesn’t matter that\n // we’ve tracked one too many characters.\n const reference = state.safe(state.associationId(node), {\n before: value,\n after: ']',\n ...tracker.current()\n })\n subexit()\n state.stack = stack\n exit()\n\n if (type === 'full' || !alt || alt !== reference) {\n value += tracker.move(reference + ']')\n } else if (type === 'shortcut') {\n // Remove the unwanted `[`.\n value = value.slice(0, -1)\n } else {\n value += tracker.move(']')\n }\n\n return value\n}\n\n/**\n * @returns {string}\n */\nfunction imageReferencePeek() {\n return '!'\n}\n","/**\n * @import {State} from 'mdast-util-to-markdown'\n * @import {InlineCode, Parents} from 'mdast'\n */\n\ninlineCode.peek = inlineCodePeek\n\n/**\n * @param {InlineCode} node\n * @param {Parents | undefined} _\n * @param {State} state\n * @returns {string}\n */\nexport function inlineCode(node, _, state) {\n let value = node.value || ''\n let sequence = '`'\n let index = -1\n\n // If there is a single grave accent on its own in the code, use a fence of\n // two.\n // If there are two in a row, use one.\n while (new RegExp('(^|[^`])' + sequence + '([^`]|$)').test(value)) {\n sequence += '`'\n }\n\n // If this is not just spaces or eols (tabs don’t count), and either the\n // first or last character are a space, eol, or tick, then pad with spaces.\n if (\n /[^ \\r\\n]/.test(value) &&\n ((/^[ \\r\\n]/.test(value) && /[ \\r\\n]$/.test(value)) || /^`|`$/.test(value))\n ) {\n value = ' ' + value + ' '\n }\n\n // We have a potential problem: certain characters after eols could result in\n // blocks being seen.\n // For example, if someone injected the string `'\\n# b'`, then that would\n // result in an ATX heading.\n // We can’t escape characters in `inlineCode`, but because eols are\n // transformed to spaces when going from markdown to HTML anyway, we can swap\n // them out.\n while (++index < state.unsafe.length) {\n const pattern = state.unsafe[index]\n const expression = state.compilePattern(pattern)\n /** @type {RegExpExecArray | null} */\n let match\n\n // Only look for `atBreak`s.\n // Btw: note that `atBreak` patterns will always start the regex at LF or\n // CR.\n if (!pattern.atBreak) continue\n\n while ((match = expression.exec(value))) {\n let position = match.index\n\n // Support CRLF (patterns only look for one of the characters).\n if (\n value.charCodeAt(position) === 10 /* `\\n` */ &&\n value.charCodeAt(position - 1) === 13 /* `\\r` */\n ) {\n position--\n }\n\n value = value.slice(0, position) + ' ' + value.slice(match.index + 1)\n }\n }\n\n return sequence + value + sequence\n}\n\n/**\n * @returns {string}\n */\nfunction inlineCodePeek() {\n return '`'\n}\n","/**\n * @import {State} from 'mdast-util-to-markdown'\n * @import {Link} from 'mdast'\n */\n\nimport {toString} from 'mdast-util-to-string'\n\n/**\n * @param {Link} node\n * @param {State} state\n * @returns {boolean}\n */\nexport function formatLinkAsAutolink(node, state) {\n const raw = toString(node)\n\n return Boolean(\n !state.options.resourceLink &&\n // If there’s a url…\n node.url &&\n // And there’s a no title…\n !node.title &&\n // And the content of `node` is a single text node…\n node.children &&\n node.children.length === 1 &&\n node.children[0].type === 'text' &&\n // And if the url is the same as the content…\n (raw === node.url || 'mailto:' + raw === node.url) &&\n // And that starts w/ a protocol…\n /^[a-z][a-z+.-]+:/i.test(node.url) &&\n // And that doesn’t contain ASCII control codes (character escapes and\n // references don’t work), space, or angle brackets…\n !/[\\0- <>\\u007F]/.test(node.url)\n )\n}\n","/**\n * @import {Info, State} from 'mdast-util-to-markdown'\n * @import {Link, Parents} from 'mdast'\n * @import {Exit} from '../types.js'\n */\n\nimport {checkQuote} from '../util/check-quote.js'\nimport {formatLinkAsAutolink} from '../util/format-link-as-autolink.js'\n\nlink.peek = linkPeek\n\n/**\n * @param {Link} node\n * @param {Parents | undefined} _\n * @param {State} state\n * @param {Info} info\n * @returns {string}\n */\nexport function link(node, _, state, info) {\n const quote = checkQuote(state)\n const suffix = quote === '\"' ? 'Quote' : 'Apostrophe'\n const tracker = state.createTracker(info)\n /** @type {Exit} */\n let exit\n /** @type {Exit} */\n let subexit\n\n if (formatLinkAsAutolink(node, state)) {\n // Hide the fact that we’re in phrasing, because escapes don’t work.\n const stack = state.stack\n state.stack = []\n exit = state.enter('autolink')\n let value = tracker.move('<')\n value += tracker.move(\n state.containerPhrasing(node, {\n before: value,\n after: '>',\n ...tracker.current()\n })\n )\n value += tracker.move('>')\n exit()\n state.stack = stack\n return value\n }\n\n exit = state.enter('link')\n subexit = state.enter('label')\n let value = tracker.move('[')\n value += tracker.move(\n state.containerPhrasing(node, {\n before: value,\n after: '](',\n ...tracker.current()\n })\n )\n value += tracker.move('](')\n subexit()\n\n if (\n // If there’s no url but there is a title…\n (!node.url && node.title) ||\n // If there are control characters or whitespace.\n /[\\0- \\u007F]/.test(node.url)\n ) {\n subexit = state.enter('destinationLiteral')\n value += tracker.move('<')\n value += tracker.move(\n state.safe(node.url, {before: value, after: '>', ...tracker.current()})\n )\n value += tracker.move('>')\n } else {\n // No whitespace, raw is prettier.\n subexit = state.enter('destinationRaw')\n value += tracker.move(\n state.safe(node.url, {\n before: value,\n after: node.title ? ' ' : ')',\n ...tracker.current()\n })\n )\n }\n\n subexit()\n\n if (node.title) {\n subexit = state.enter(`title${suffix}`)\n value += tracker.move(' ' + quote)\n value += tracker.move(\n state.safe(node.title, {\n before: value,\n after: quote,\n ...tracker.current()\n })\n )\n value += tracker.move(quote)\n subexit()\n }\n\n value += tracker.move(')')\n\n exit()\n return value\n}\n\n/**\n * @param {Link} node\n * @param {Parents | undefined} _\n * @param {State} state\n * @returns {string}\n */\nfunction linkPeek(node, _, state) {\n return formatLinkAsAutolink(node, state) ? '<' : '['\n}\n","/**\n * @import {Info, State} from 'mdast-util-to-markdown'\n * @import {LinkReference, Parents} from 'mdast'\n */\n\nlinkReference.peek = linkReferencePeek\n\n/**\n * @param {LinkReference} node\n * @param {Parents | undefined} _\n * @param {State} state\n * @param {Info} info\n * @returns {string}\n */\nexport function linkReference(node, _, state, info) {\n const type = node.referenceType\n const exit = state.enter('linkReference')\n let subexit = state.enter('label')\n const tracker = state.createTracker(info)\n let value = tracker.move('[')\n const text = state.containerPhrasing(node, {\n before: value,\n after: ']',\n ...tracker.current()\n })\n value += tracker.move(text + '][')\n\n subexit()\n // Hide the fact that we’re in phrasing, because escapes don’t work.\n const stack = state.stack\n state.stack = []\n subexit = state.enter('reference')\n // Note: for proper tracking, we should reset the output positions when we end\n // up making a `shortcut` reference, because then there is no brace output.\n // Practically, in that case, there is no content, so it doesn’t matter that\n // we’ve tracked one too many characters.\n const reference = state.safe(state.associationId(node), {\n before: value,\n after: ']',\n ...tracker.current()\n })\n subexit()\n state.stack = stack\n exit()\n\n if (type === 'full' || !text || text !== reference) {\n value += tracker.move(reference + ']')\n } else if (type === 'shortcut') {\n // Remove the unwanted `[`.\n value = value.slice(0, -1)\n } else {\n value += tracker.move(']')\n }\n\n return value\n}\n\n/**\n * @returns {string}\n */\nfunction linkReferencePeek() {\n return '['\n}\n","/**\n * @import {Options, State} from 'mdast-util-to-markdown'\n */\n\n/**\n * @param {State} state\n * @returns {Exclude<Options['bullet'], null | undefined>}\n */\nexport function checkBullet(state) {\n const marker = state.options.bullet || '*'\n\n if (marker !== '*' && marker !== '+' && marker !== '-') {\n throw new Error(\n 'Cannot serialize items with `' +\n marker +\n '` for `options.bullet`, expected `*`, `+`, or `-`'\n )\n }\n\n return marker\n}\n","/**\n * @import {Options, State} from 'mdast-util-to-markdown'\n */\n\nimport {checkBullet} from './check-bullet.js'\n\n/**\n * @param {State} state\n * @returns {Exclude<Options['bullet'], null | undefined>}\n */\nexport function checkBulletOther(state) {\n const bullet = checkBullet(state)\n const bulletOther = state.options.bulletOther\n\n if (!bulletOther) {\n return bullet === '*' ? '-' : '*'\n }\n\n if (bulletOther !== '*' && bulletOther !== '+' && bulletOther !== '-') {\n throw new Error(\n 'Cannot serialize items with `' +\n bulletOther +\n '` for `options.bulletOther`, expected `*`, `+`, or `-`'\n )\n }\n\n if (bulletOther === bullet) {\n throw new Error(\n 'Expected `bullet` (`' +\n bullet +\n '`) and `bulletOther` (`' +\n bulletOther +\n '`) to be different'\n )\n }\n\n return bulletOther\n}\n","/**\n * @import {Options, State} from 'mdast-util-to-markdown'\n */\n\n/**\n * @param {State} state\n * @returns {Exclude<Options['bulletOrdered'], null | undefined>}\n */\nexport function checkBulletOrdered(state) {\n const marker = state.options.bulletOrdered || '.'\n\n if (marker !== '.' && marker !== ')') {\n throw new Error(\n 'Cannot serialize items with `' +\n marker +\n '` for `options.bulletOrdered`, expected `.` or `)`'\n )\n }\n\n return marker\n}\n","/**\n * @import {Options, State} from 'mdast-util-to-markdown'\n */\n\n/**\n * @param {State} state\n * @returns {Exclude<Options['rule'], null | undefined>}\n */\nexport function checkRule(state) {\n const marker = state.options.rule || '*'\n\n if (marker !== '*' && marker !== '-' && marker !== '_') {\n throw new Error(\n 'Cannot serialize rules with `' +\n marker +\n '` for `options.rule`, expected `*`, `-`, or `_`'\n )\n }\n\n return marker\n}\n","/**\n * @import {Info, State} from 'mdast-util-to-markdown'\n * @import {List, Parents} from 'mdast'\n */\n\nimport {checkBullet} from '../util/check-bullet.js'\nimport {checkBulletOther} from '../util/check-bullet-other.js'\nimport {checkBulletOrdered} from '../util/check-bullet-ordered.js'\nimport {checkRule} from '../util/check-rule.js'\n\n/**\n * @param {List} node\n * @param {Parents | undefined} parent\n * @param {State} state\n * @param {Info} info\n * @returns {string}\n */\nexport function list(node, parent, state, info) {\n const exit = state.enter('list')\n const bulletCurrent = state.bulletCurrent\n /** @type {string} */\n let bullet = node.ordered ? checkBulletOrdered(state) : checkBullet(state)\n /** @type {string} */\n const bulletOther = node.ordered\n ? bullet === '.'\n ? ')'\n : '.'\n : checkBulletOther(state)\n let useDifferentMarker =\n parent && state.bulletLastUsed ? bullet === state.bulletLastUsed : false\n\n if (!node.ordered) {\n const firstListItem = node.children ? node.children[0] : undefined\n\n // If there’s an empty first list item directly in two list items,\n // we have to use a different bullet:\n //\n // ```markdown\n // * - *\n // ```\n //\n // …because otherwise it would become one big thematic break.\n if (\n // Bullet could be used as a thematic break marker:\n (bullet === '*' || bullet === '-') &&\n // Empty first list item:\n firstListItem &&\n (!firstListItem.children || !firstListItem.children[0]) &&\n // Directly in two other list items:\n state.stack[state.stack.length - 1] === 'list' &&\n state.stack[state.stack.length - 2] === 'listItem' &&\n state.stack[state.stack.length - 3] === 'list' &&\n state.stack[state.stack.length - 4] === 'listItem' &&\n // That are each the first child.\n state.indexStack[state.indexStack.length - 1] === 0 &&\n state.indexStack[state.indexStack.length - 2] === 0 &&\n state.indexStack[state.indexStack.length - 3] === 0\n ) {\n useDifferentMarker = true\n }\n\n // If there’s a thematic break at the start of the first list item,\n // we have to use a different bullet:\n //\n // ```markdown\n // * ---\n // ```\n //\n // …because otherwise it would become one big thematic break.\n if (checkRule(state) === bullet && firstListItem) {\n let index = -1\n\n while (++index < node.children.length) {\n const item = node.children[index]\n\n if (\n item &&\n item.type === 'listItem' &&\n item.children &&\n item.children[0] &&\n item.children[0].type === 'thematicBreak'\n ) {\n useDifferentMarker = true\n break\n }\n }\n }\n }\n\n if (useDifferentMarker) {\n bullet = bulletOther\n }\n\n state.bulletCurrent = bullet\n const value = state.containerFlow(node, info)\n state.bulletLastUsed = bullet\n state.bulletCurrent = bulletCurrent\n exit()\n return value\n}\n","/**\n * @import {Options, State} from 'mdast-util-to-markdown'\n */\n\n/**\n * @param {State} state\n * @returns {Exclude<Options['listItemIndent'], null | undefined>}\n */\nexport function checkListItemIndent(state) {\n const style = state.options.listItemIndent || 'one'\n\n if (style !== 'tab' && style !== 'one' && style !== 'mixed') {\n throw new Error(\n 'Cannot serialize items with `' +\n style +\n '` for `options.listItemIndent`, expected `tab`, `one`, or `mixed`'\n )\n }\n\n return style\n}\n","/**\n * @import {Info, Map, State} from 'mdast-util-to-markdown'\n * @import {ListItem, Parents} from 'mdast'\n */\n\nimport {checkBullet} from '../util/check-bullet.js'\nimport {checkListItemIndent} from '../util/check-list-item-indent.js'\n\n/**\n * @param {ListItem} node\n * @param {Parents | undefined} parent\n * @param {State} state\n * @param {Info} info\n * @returns {string}\n */\nexport function listItem(node, parent, state, info) {\n const listItemIndent = checkListItemIndent(state)\n let bullet = state.bulletCurrent || checkBullet(state)\n\n // Add the marker value for ordered lists.\n if (parent && parent.type === 'list' && parent.ordered) {\n bullet =\n (typeof parent.start === 'number' && parent.start > -1\n ? parent.start\n : 1) +\n (state.options.incrementListMarker === false\n ? 0\n : parent.children.indexOf(node)) +\n bullet\n }\n\n let size = bullet.length + 1\n\n if (\n listItemIndent === 'tab' ||\n (listItemIndent === 'mixed' &&\n ((parent && parent.type === 'list' && parent.spread) || node.spread))\n ) {\n size = Math.ceil(size / 4) * 4\n }\n\n const tracker = state.createTracker(info)\n tracker.move(bullet + ' '.repeat(size - bullet.length))\n tracker.shift(size)\n const exit = state.enter('listItem')\n const value = state.indentLines(\n state.containerFlow(node, tracker.current()),\n map\n )\n exit()\n\n return value\n\n /** @type {Map} */\n function map(line, index, blank) {\n if (index) {\n return (blank ? '' : ' '.repeat(size)) + line\n }\n\n return (blank ? bullet : bullet + ' '.repeat(size - bullet.length)) + line\n }\n}\n","/**\n * @import {Info, State} from 'mdast-util-to-markdown'\n * @import {Paragraph, Parents} from 'mdast'\n */\n\n/**\n * @param {Paragraph} node\n * @param {Parents | undefined} _\n * @param {State} state\n * @param {Info} info\n * @returns {string}\n */\nexport function paragraph(node, _, state, info) {\n const exit = state.enter('paragraph')\n const subexit = state.enter('phrasing')\n const value = state.containerPhrasing(node, info)\n subexit()\n exit()\n return value\n}\n","/**\n * @typedef {import('mdast').Html} Html\n * @typedef {import('mdast').PhrasingContent} PhrasingContent\n */\n\nimport {convert} from 'unist-util-is'\n\n/**\n * Check if the given value is *phrasing content*.\n *\n * > 👉 **Note**: Excludes `html`, which can be both phrasing or flow.\n *\n * @param node\n * Thing to check, typically `Node`.\n * @returns\n * Whether `value` is phrasing content.\n */\n\nexport const phrasing =\n /** @type {(node?: unknown) => node is Exclude<PhrasingContent, Html>} */\n (\n convert([\n 'break',\n 'delete',\n 'emphasis',\n // To do: next major: removed since footnotes were added to GFM.\n 'footnote',\n 'footnoteReference',\n 'image',\n 'imageReference',\n 'inlineCode',\n // Enabled by `mdast-util-math`:\n 'inlineMath',\n 'link',\n 'linkReference',\n // Enabled by `mdast-util-mdx`:\n 'mdxJsxTextElement',\n // Enabled by `mdast-util-mdx`:\n 'mdxTextExpression',\n 'strong',\n 'text',\n // Enabled by `mdast-util-directive`:\n 'textDirective'\n ])\n )\n","/**\n * @import {Info, State} from 'mdast-util-to-markdown'\n * @import {Parents, Root} from 'mdast'\n */\n\nimport {phrasing} from 'mdast-util-phrasing'\n\n/**\n * @param {Root} node\n * @param {Parents | undefined} _\n * @param {State} state\n * @param {Info} info\n * @returns {string}\n */\nexport function root(node, _, state, info) {\n // Note: `html` nodes are ambiguous.\n const hasPhrasing = node.children.some(function (d) {\n return phrasing(d)\n })\n\n const container = hasPhrasing ? state.containerPhrasing : state.containerFlow\n return container.call(state, node, info)\n}\n","/**\n * @import {Options, State} from 'mdast-util-to-markdown'\n */\n\n/**\n * @param {State} state\n * @returns {Exclude<Options['strong'], null | undefined>}\n */\nexport function checkStrong(state) {\n const marker = state.options.strong || '*'\n\n if (marker !== '*' && marker !== '_') {\n throw new Error(\n 'Cannot serialize strong with `' +\n marker +\n '` for `options.strong`, expected `*`, or `_`'\n )\n }\n\n return marker\n}\n","/**\n * @import {Info, State} from 'mdast-util-to-markdown'\n * @import {Parents, Strong} from 'mdast'\n */\n\nimport {checkStrong} from '../util/check-strong.js'\nimport {encodeCharacterReference} from '../util/encode-character-reference.js'\nimport {encodeInfo} from '../util/encode-info.js'\n\nstrong.peek = strongPeek\n\n/**\n * @param {Strong} node\n * @param {Parents | undefined} _\n * @param {State} state\n * @param {Info} info\n * @returns {string}\n */\nexport function strong(node, _, state, info) {\n const marker = checkStrong(state)\n const exit = state.enter('strong')\n const tracker = state.createTracker(info)\n const before = tracker.move(marker + marker)\n\n let between = tracker.move(\n state.containerPhrasing(node, {\n after: marker,\n before,\n ...tracker.current()\n })\n )\n const betweenHead = between.charCodeAt(0)\n const open = encodeInfo(\n info.before.charCodeAt(info.before.length - 1),\n betweenHead,\n marker\n )\n\n if (open.inside) {\n between = encodeCharacterReference(betweenHead) + between.slice(1)\n }\n\n const betweenTail = between.charCodeAt(between.length - 1)\n const close = encodeInfo(info.after.charCodeAt(0), betweenTail, marker)\n\n if (close.inside) {\n between = between.slice(0, -1) + encodeCharacterReference(betweenTail)\n }\n\n const after = tracker.move(marker + marker)\n\n exit()\n\n state.attentionEncodeSurroundingInfo = {\n after: close.outside,\n before: open.outside\n }\n return before + between + after\n}\n\n/**\n * @param {Strong} _\n * @param {Parents | undefined} _1\n * @param {State} state\n * @returns {string}\n */\nfunction strongPeek(_, _1, state) {\n return state.options.strong || '*'\n}\n","/**\n * @import {Info, State} from 'mdast-util-to-markdown'\n * @import {Parents, Text} from 'mdast'\n */\n\n/**\n * @param {Text} node\n * @param {Parents | undefined} _\n * @param {State} state\n * @param {Info} info\n * @returns {string}\n */\nexport function text(node, _, state, info) {\n return state.safe(node.value, info)\n}\n","/**\n * @import {Options, State} from 'mdast-util-to-markdown'\n */\n\n/**\n * @param {State} state\n * @returns {Exclude<Options['ruleRepetition'], null | undefined>}\n */\nexport function checkRuleRepetition(state) {\n const repetition = state.options.ruleRepetition || 3\n\n if (repetition < 3) {\n throw new Error(\n 'Cannot serialize rules with repetition `' +\n repetition +\n '` for `options.ruleRepetition`, expected `3` or more'\n )\n }\n\n return repetition\n}\n","/**\n * @import {State} from 'mdast-util-to-markdown'\n * @import {Parents, ThematicBreak} from 'mdast'\n */\n\nimport {checkRuleRepetition} from '../util/check-rule-repetition.js'\nimport {checkRule} from '../util/check-rule.js'\n\n/**\n * @param {ThematicBreak} _\n * @param {Parents | undefined} _1\n * @param {State} state\n * @returns {string}\n */\nexport function thematicBreak(_, _1, state) {\n const value = (\n checkRule(state) + (state.options.ruleSpaces ? ' ' : '')\n ).repeat(checkRuleRepetition(state))\n\n return state.options.ruleSpaces ? value.slice(0, -1) : value\n}\n","import {blockquote} from './blockquote.js'\nimport {hardBreak} from './break.js'\nimport {code} from './code.js'\nimport {definition} from './definition.js'\nimport {emphasis} from './emphasis.js'\nimport {heading} from './heading.js'\nimport {html} from './html.js'\nimport {image} from './image.js'\nimport {imageReference} from './image-reference.js'\nimport {inlineCode} from './inline-code.js'\nimport {link} from './link.js'\nimport {linkReference} from './link-reference.js'\nimport {list} from './list.js'\nimport {listItem} from './list-item.js'\nimport {paragraph} from './paragraph.js'\nimport {root} from './root.js'\nimport {strong} from './strong.js'\nimport {text} from './text.js'\nimport {thematicBreak} from './thematic-break.js'\n\n/**\n * Default (CommonMark) handlers.\n */\nexport const handle = {\n blockquote,\n break: hardBreak,\n code,\n definition,\n emphasis,\n hardBreak,\n heading,\n html,\n image,\n imageReference,\n inlineCode,\n link,\n linkReference,\n list,\n listItem,\n paragraph,\n root,\n strong,\n text,\n thematicBreak\n}\n","/**\n * @typedef {import('mdast').InlineCode} InlineCode\n * @typedef {import('mdast').Table} Table\n * @typedef {import('mdast').TableCell} TableCell\n * @typedef {import('mdast').TableRow} TableRow\n *\n * @typedef {import('markdown-table').Options} MarkdownTableOptions\n *\n * @typedef {import('mdast-util-from-markdown').CompileContext} CompileContext\n * @typedef {import('mdast-util-from-markdown').Extension} FromMarkdownExtension\n * @typedef {import('mdast-util-from-markdown').Handle} FromMarkdownHandle\n *\n * @typedef {import('mdast-util-to-markdown').Options} ToMarkdownExtension\n * @typedef {import('mdast-util-to-markdown').Handle} ToMarkdownHandle\n * @typedef {import('mdast-util-to-markdown').State} State\n * @typedef {import('mdast-util-to-markdown').Info} Info\n */\n\n/**\n * @typedef Options\n * Configuration.\n * @property {boolean | null | undefined} [tableCellPadding=true]\n * Whether to add a space of padding between delimiters and cells (default:\n * `true`).\n * @property {boolean | null | undefined} [tablePipeAlign=true]\n * Whether to align the delimiters (default: `true`).\n * @property {MarkdownTableOptions['stringLength'] | null | undefined} [stringLength]\n * Function to detect the length of table cell content, used when aligning\n * the delimiters between cells (optional).\n */\n\nimport {ok as assert} from 'devlop'\nimport {markdownTable} from 'markdown-table'\nimport {defaultHandlers} from 'mdast-util-to-markdown'\n\n/**\n * Create an extension for `mdast-util-from-markdown` to enable GFM tables in\n * markdown.\n *\n * @returns {FromMarkdownExtension}\n * Extension for `mdast-util-from-markdown` to enable GFM tables.\n */\nexport function gfmTableFromMarkdown() {\n return {\n enter: {\n table: enterTable,\n tableData: enterCell,\n tableHeader: enterCell,\n tableRow: enterRow\n },\n exit: {\n codeText: exitCodeText,\n table: exitTable,\n tableData: exit,\n tableHeader: exit,\n tableRow: exit\n }\n }\n}\n\n/**\n * @this {CompileContext}\n * @type {FromMarkdownHandle}\n */\nfunction enterTable(token) {\n const align = token._align\n assert(align, 'expected `_align` on table')\n this.enter(\n {\n type: 'table',\n align: align.map(function (d) {\n return d === 'none' ? null : d\n }),\n children: []\n },\n token\n )\n this.data.inTable = true\n}\n\n/**\n * @this {CompileContext}\n * @type {FromMarkdownHandle}\n */\nfunction exitTable(token) {\n this.exit(token)\n this.data.inTable = undefined\n}\n\n/**\n * @this {CompileContext}\n * @type {FromMarkdownHandle}\n */\nfunction enterRow(token) {\n this.enter({type: 'tableRow', children: []}, token)\n}\n\n/**\n * @this {CompileContext}\n * @type {FromMarkdownHandle}\n */\nfunction exit(token) {\n this.exit(token)\n}\n\n/**\n * @this {CompileContext}\n * @type {FromMarkdownHandle}\n */\nfunction enterCell(token) {\n this.enter({type: 'tableCell', children: []}, token)\n}\n\n// Overwrite the default code text data handler to unescape escaped pipes when\n// they are in tables.\n/**\n * @this {CompileContext}\n * @type {FromMarkdownHandle}\n */\nfunction exitCodeText(token) {\n let value = this.resume()\n\n if (this.data.inTable) {\n value = value.replace(/\\\\([\\\\|])/g, replace)\n }\n\n const node = this.stack[this.stack.length - 1]\n assert(node.type === 'inlineCode')\n node.value = value\n this.exit(token)\n}\n\n/**\n * @param {string} $0\n * @param {string} $1\n * @returns {string}\n */\nfunction replace($0, $1) {\n // Pipes work, backslashes don’t (but can’t escape pipes).\n return $1 === '|' ? $1 : $0\n}\n\n/**\n * Create an extension for `mdast-util-to-markdown` to enable GFM tables in\n * markdown.\n *\n * @param {Options | null | undefined} [options]\n * Configuration.\n * @returns {ToMarkdownExtension}\n * Extension for `mdast-util-to-markdown` to enable GFM tables.\n */\nexport function gfmTableToMarkdown(options) {\n const settings = options || {}\n const padding = settings.tableCellPadding\n const alignDelimiters = settings.tablePipeAlign\n const stringLength = settings.stringLength\n const around = padding ? ' ' : '|'\n\n return {\n unsafe: [\n {character: '\\r', inConstruct: 'tableCell'},\n {character: '\\n', inConstruct: 'tableCell'},\n // A pipe, when followed by a tab or space (padding), or a dash or colon\n // (unpadded delimiter row), could result in a table.\n {atBreak: true, character: '|', after: '[\\t :-]'},\n // A pipe in a cell must be encoded.\n {character: '|', inConstruct: 'tableCell'},\n // A colon must be followed by a dash, in which case it could start a\n // delimiter row.\n {atBreak: true, character: ':', after: '-'},\n // A delimiter row can also start with a dash, when followed by more\n // dashes, a colon, or a pipe.\n // This is a stricter version than the built in check for lists, thematic\n // breaks, and setex heading underlines though:\n // <https://github.com/syntax-tree/mdast-util-to-markdown/blob/51a2038/lib/unsafe.js#L57>\n {atBreak: true, character: '-', after: '[:|-]'}\n ],\n handlers: {\n inlineCode: inlineCodeWithTable,\n table: handleTable,\n tableCell: handleTableCell,\n tableRow: handleTableRow\n }\n }\n\n /**\n * @type {ToMarkdownHandle}\n * @param {Table} node\n */\n function handleTable(node, _, state, info) {\n return serializeData(handleTableAsData(node, state, info), node.align)\n }\n\n /**\n * This function isn’t really used normally, because we handle rows at the\n * table level.\n * But, if someone passes in a table row, this ensures we make somewhat sense.\n *\n * @type {ToMarkdownHandle}\n * @param {TableRow} node\n */\n function handleTableRow(node, _, state, info) {\n const row = handleTableRowAsData(node, state, info)\n const value = serializeData([row])\n // `markdown-table` will always add an align row\n return value.slice(0, value.indexOf('\\n'))\n }\n\n /**\n * @type {ToMarkdownHandle}\n * @param {TableCell} node\n */\n function handleTableCell(node, _, state, info) {\n const exit = state.enter('tableCell')\n const subexit = state.enter('phrasing')\n const value = state.containerPhrasing(node, {\n ...info,\n before: around,\n after: around\n })\n subexit()\n exit()\n return value\n }\n\n /**\n * @param {Array<Array<string>>} matrix\n * @param {Array<string | null | undefined> | null | undefined} [align]\n */\n function serializeData(matrix, align) {\n return markdownTable(matrix, {\n align,\n // @ts-expect-error: `markdown-table` types should support `null`.\n alignDelimiters,\n // @ts-expect-error: `markdown-table` types should support `null`.\n padding,\n // @ts-expect-error: `markdown-table` types should support `null`.\n stringLength\n })\n }\n\n /**\n * @param {Table} node\n * @param {State} state\n * @param {Info} info\n */\n function handleTableAsData(node, state, info) {\n const children = node.children\n let index = -1\n /** @type {Array<Array<string>>} */\n const result = []\n const subexit = state.enter('table')\n\n while (++index < children.length) {\n result[index] = handleTableRowAsData(children[index], state, info)\n }\n\n subexit()\n\n return result\n }\n\n /**\n * @param {TableRow} node\n * @param {State} state\n * @param {Info} info\n */\n function handleTableRowAsData(node, state, info) {\n const children = node.children\n let index = -1\n /** @type {Array<string>} */\n const result = []\n const subexit = state.enter('tableRow')\n\n while (++index < children.length) {\n // Note: the positional info as used here is incorrect.\n // Making it correct would be impossible due to aligning cells?\n // And it would need copy/pasting `markdown-table` into this project.\n result[index] = handleTableCell(children[index], node, state, info)\n }\n\n subexit()\n\n return result\n }\n\n /**\n * @type {ToMarkdownHandle}\n * @param {InlineCode} node\n */\n function inlineCodeWithTable(node, parent, state) {\n let value = defaultHandlers.inlineCode(node, parent, state)\n\n if (state.stack.includes('tableCell')) {\n value = value.replace(/\\|/g, '\\\\$&')\n }\n\n return value\n }\n}\n","/**\n * @typedef {import('mdast').ListItem} ListItem\n * @typedef {import('mdast').Paragraph} Paragraph\n * @typedef {import('mdast-util-from-markdown').CompileContext} CompileContext\n * @typedef {import('mdast-util-from-markdown').Extension} FromMarkdownExtension\n * @typedef {import('mdast-util-from-markdown').Handle} FromMarkdownHandle\n * @typedef {import('mdast-util-to-markdown').Options} ToMarkdownExtension\n * @typedef {import('mdast-util-to-markdown').Handle} ToMarkdownHandle\n */\n\nimport {ok as assert} from 'devlop'\nimport {defaultHandlers} from 'mdast-util-to-markdown'\n\n/**\n * Create an extension for `mdast-util-from-markdown` to enable GFM task\n * list items in markdown.\n *\n * @returns {FromMarkdownExtension}\n * Extension for `mdast-util-from-markdown` to enable GFM task list items.\n */\nexport function gfmTaskListItemFromMarkdown() {\n return {\n exit: {\n taskListCheckValueChecked: exitCheck,\n taskListCheckValueUnchecked: exitCheck,\n paragraph: exitParagraphWithTaskListItem\n }\n }\n}\n\n/**\n * Create an extension for `mdast-util-to-markdown` to enable GFM task list\n * items in markdown.\n *\n * @returns {ToMarkdownExtension}\n * Extension for `mdast-util-to-markdown` to enable GFM task list items.\n */\nexport function gfmTaskListItemToMarkdown() {\n return {\n unsafe: [{atBreak: true, character: '-', after: '[:|-]'}],\n handlers: {listItem: listItemWithTaskListItem}\n }\n}\n\n/**\n * @this {CompileContext}\n * @type {FromMarkdownHandle}\n */\nfunction exitCheck(token) {\n // We’re always in a paragraph, in a list item.\n const node = this.stack[this.stack.length - 2]\n assert(node.type === 'listItem')\n node.checked = token.type === 'taskListCheckValueChecked'\n}\n\n/**\n * @this {CompileContext}\n * @type {FromMarkdownHandle}\n */\nfunction exitParagraphWithTaskListItem(token) {\n const parent = this.stack[this.stack.length - 2]\n\n if (\n parent &&\n parent.type === 'listItem' &&\n typeof parent.checked === 'boolean'\n ) {\n const node = this.stack[this.stack.length - 1]\n assert(node.type === 'paragraph')\n const head = node.children[0]\n\n if (head && head.type === 'text') {\n const siblings = parent.children\n let index = -1\n /** @type {Paragraph | undefined} */\n let firstParaghraph\n\n while (++index < siblings.length) {\n const sibling = siblings[index]\n if (sibling.type === 'paragraph') {\n firstParaghraph = sibling\n break\n }\n }\n\n if (firstParaghraph === node) {\n // Must start with a space or a tab.\n head.value = head.value.slice(1)\n\n if (head.value.length === 0) {\n node.children.shift()\n } else if (\n node.position &&\n head.position &&\n typeof head.position.start.offset === 'number'\n ) {\n head.position.start.column++\n head.position.start.offset++\n node.position.start = Object.assign({}, head.position.start)\n }\n }\n }\n }\n\n this.exit(token)\n}\n\n/**\n * @type {ToMarkdownHandle}\n * @param {ListItem} node\n */\nfunction listItemWithTaskListItem(node, parent, state, info) {\n const head = node.children[0]\n const checkable =\n typeof node.checked === 'boolean' && head && head.type === 'paragraph'\n const checkbox = '[' + (node.checked ? 'x' : ' ') + '] '\n const tracker = state.createTracker(info)\n\n if (checkable) {\n tracker.move(checkbox)\n }\n\n let value = defaultHandlers.listItem(node, parent, state, {\n ...info,\n ...tracker.current()\n })\n\n if (checkable) {\n value = value.replace(/^(?:[*+-]|\\d+\\.)([\\r\\n]| {1,3})/, check)\n }\n\n return value\n\n /**\n * @param {string} $0\n * @returns {string}\n */\n function check($0) {\n return $0 + checkbox\n }\n}\n","/**\n * @import {Extension as FromMarkdownExtension} from 'mdast-util-from-markdown'\n * @import {Options} from 'mdast-util-gfm'\n * @import {Options as ToMarkdownExtension} from 'mdast-util-to-markdown'\n */\n\nimport {\n gfmAutolinkLiteralFromMarkdown,\n gfmAutolinkLiteralToMarkdown\n} from 'mdast-util-gfm-autolink-literal'\nimport {\n gfmFootnoteFromMarkdown,\n gfmFootnoteToMarkdown\n} from 'mdast-util-gfm-footnote'\nimport {\n gfmStrikethroughFromMarkdown,\n gfmStrikethroughToMarkdown\n} from 'mdast-util-gfm-strikethrough'\nimport {gfmTableFromMarkdown, gfmTableToMarkdown} from 'mdast-util-gfm-table'\nimport {\n gfmTaskListItemFromMarkdown,\n gfmTaskListItemToMarkdown\n} from 'mdast-util-gfm-task-list-item'\n\n/**\n * Create an extension for `mdast-util-from-markdown` to enable GFM (autolink\n * literals, footnotes, strikethrough, tables, tasklists).\n *\n * @returns {Array<FromMarkdownExtension>}\n * Extension for `mdast-util-from-markdown` to enable GFM (autolink literals,\n * footnotes, strikethrough, tables, tasklists).\n */\nexport function gfmFromMarkdown() {\n return [\n gfmAutolinkLiteralFromMarkdown(),\n gfmFootnoteFromMarkdown(),\n gfmStrikethroughFromMarkdown(),\n gfmTableFromMarkdown(),\n gfmTaskListItemFromMarkdown()\n ]\n}\n\n/**\n * Create an extension for `mdast-util-to-markdown` to enable GFM (autolink\n * literals, footnotes, strikethrough, tables, tasklists).\n *\n * @param {Options | null | undefined} [options]\n * Configuration (optional).\n * @returns {ToMarkdownExtension}\n * Extension for `mdast-util-to-markdown` to enable GFM (autolink literals,\n * footnotes, strikethrough, tables, tasklists).\n */\nexport function gfmToMarkdown(options) {\n return {\n extensions: [\n gfmAutolinkLiteralToMarkdown(),\n gfmFootnoteToMarkdown(options),\n gfmStrikethroughToMarkdown(),\n gfmTableToMarkdown(options),\n gfmTaskListItemToMarkdown()\n ]\n }\n}\n","/**\n * Like `Array#splice`, but smarter for giant arrays.\n *\n * `Array#splice` takes all items to be inserted as individual argument which\n * causes a stack overflow in V8 when trying to insert 100k items for instance.\n *\n * Otherwise, this does not return the removed items, and takes `items` as an\n * array instead of rest parameters.\n *\n * @template {unknown} T\n * Item type.\n * @param {Array<T>} list\n * List to operate on.\n * @param {number} start\n * Index to remove/insert at (can be negative).\n * @param {number} remove\n * Number of items to remove.\n * @param {Array<T>} items\n * Items to inject into `list`.\n * @returns {undefined}\n * Nothing.\n */\nexport function splice(list, start, remove, items) {\n const end = list.length;\n let chunkStart = 0;\n /** @type {Array<unknown>} */\n let parameters;\n\n // Make start between zero and `end` (included).\n if (start < 0) {\n start = -start > end ? 0 : end + start;\n } else {\n start = start > end ? end : start;\n }\n remove = remove > 0 ? remove : 0;\n\n // No need to chunk the items if there’s only a couple (10k) items.\n if (items.length < 10000) {\n parameters = Array.from(items);\n parameters.unshift(start, remove);\n // @ts-expect-error Hush, it’s fine.\n list.splice(...parameters);\n } else {\n // Delete `remove` items starting from `start`\n if (remove) list.splice(start, remove);\n\n // Insert the items in chunks to not cause stack overflows.\n while (chunkStart < items.length) {\n parameters = items.slice(chunkStart, chunkStart + 10000);\n parameters.unshift(start, 0);\n // @ts-expect-error Hush, it’s fine.\n list.splice(...parameters);\n chunkStart += 10000;\n start += 10000;\n }\n }\n}\n\n/**\n * Append `items` (an array) at the end of `list` (another array).\n * When `list` was empty, returns `items` instead.\n *\n * This prevents a potentially expensive operation when `list` is empty,\n * and adds items in batches to prevent V8 from hanging.\n *\n * @template {unknown} T\n * Item type.\n * @param {Array<T>} list\n * List to operate on.\n * @param {Array<T>} items\n * Items to add to `list`.\n * @returns {Array<T>}\n * Either `list` or `items`.\n */\nexport function push(list, items) {\n if (list.length > 0) {\n splice(list, list.length, 0, items);\n return list;\n }\n return items;\n}","/**\n * @import {\n * Extension,\n * Handles,\n * HtmlExtension,\n * NormalizedExtension\n * } from 'micromark-util-types'\n */\n\nimport {splice} from 'micromark-util-chunked'\n\nconst hasOwnProperty = {}.hasOwnProperty\n\n/**\n * Combine multiple syntax extensions into one.\n *\n * @param {ReadonlyArray<Extension>} extensions\n * List of syntax extensions.\n * @returns {NormalizedExtension}\n * A single combined extension.\n */\nexport function combineExtensions(extensions) {\n /** @type {NormalizedExtension} */\n const all = {}\n let index = -1\n\n while (++index < extensions.length) {\n syntaxExtension(all, extensions[index])\n }\n\n return all\n}\n\n/**\n * Merge `extension` into `all`.\n *\n * @param {NormalizedExtension} all\n * Extension to merge into.\n * @param {Extension} extension\n * Extension to merge.\n * @returns {undefined}\n * Nothing.\n */\nfunction syntaxExtension(all, extension) {\n /** @type {keyof Extension} */\n let hook\n\n for (hook in extension) {\n const maybe = hasOwnProperty.call(all, hook) ? all[hook] : undefined\n /** @type {Record<string, unknown>} */\n const left = maybe || (all[hook] = {})\n /** @type {Record<string, unknown> | undefined} */\n const right = extension[hook]\n /** @type {string} */\n let code\n\n if (right) {\n for (code in right) {\n if (!hasOwnProperty.call(left, code)) left[code] = []\n const value = right[code]\n constructs(\n // @ts-expect-error Looks like a list.\n left[code],\n Array.isArray(value) ? value : value ? [value] : []\n )\n }\n }\n }\n}\n\n/**\n * Merge `list` into `existing` (both lists of constructs).\n * Mutates `existing`.\n *\n * @param {Array<unknown>} existing\n * List of constructs to merge into.\n * @param {Array<unknown>} list\n * List of constructs to merge.\n * @returns {undefined}\n * Nothing.\n */\nfunction constructs(existing, list) {\n let index = -1\n /** @type {Array<unknown>} */\n const before = []\n\n while (++index < list.length) {\n // @ts-expect-error Looks like an object.\n ;(list[index].add === 'after' ? existing : before).push(list[index])\n }\n\n splice(existing, 0, 0, before)\n}\n\n/**\n * Combine multiple HTML extensions into one.\n *\n * @param {ReadonlyArray<HtmlExtension>} htmlExtensions\n * List of HTML extensions.\n * @returns {HtmlExtension}\n * Single combined HTML extension.\n */\nexport function combineHtmlExtensions(htmlExtensions) {\n /** @type {HtmlExtension} */\n const handlers = {}\n let index = -1\n\n while (++index < htmlExtensions.length) {\n htmlExtension(handlers, htmlExtensions[index])\n }\n\n return handlers\n}\n\n/**\n * Merge `extension` into `all`.\n *\n * @param {HtmlExtension} all\n * Extension to merge into.\n * @param {HtmlExtension} extension\n * Extension to merge.\n * @returns {undefined}\n * Nothing.\n */\nfunction htmlExtension(all, extension) {\n /** @type {keyof HtmlExtension} */\n let hook\n\n for (hook in extension) {\n const maybe = hasOwnProperty.call(all, hook) ? all[hook] : undefined\n const left = maybe || (all[hook] = {})\n const right = extension[hook]\n /** @type {keyof Handles} */\n let type\n\n if (right) {\n for (type in right) {\n // @ts-expect-error assume document vs regular handler are managed correctly.\n left[type] = right[type]\n }\n }\n }\n}\n","/**\n * @import {Code, ConstructRecord, Event, Extension, Previous, State, TokenizeContext, Tokenizer} from 'micromark-util-types'\n */\n\nimport { asciiAlpha, asciiAlphanumeric, asciiControl, markdownLineEndingOrSpace, unicodePunctuation, unicodeWhitespace } from 'micromark-util-character';\nconst wwwPrefix = {\n tokenize: tokenizeWwwPrefix,\n partial: true\n};\nconst domain = {\n tokenize: tokenizeDomain,\n partial: true\n};\nconst path = {\n tokenize: tokenizePath,\n partial: true\n};\nconst trail = {\n tokenize: tokenizeTrail,\n partial: true\n};\nconst emailDomainDotTrail = {\n tokenize: tokenizeEmailDomainDotTrail,\n partial: true\n};\nconst wwwAutolink = {\n name: 'wwwAutolink',\n tokenize: tokenizeWwwAutolink,\n previous: previousWww\n};\nconst protocolAutolink = {\n name: 'protocolAutolink',\n tokenize: tokenizeProtocolAutolink,\n previous: previousProtocol\n};\nconst emailAutolink = {\n name: 'emailAutolink',\n tokenize: tokenizeEmailAutolink,\n previous: previousEmail\n};\n\n/** @type {ConstructRecord} */\nconst text = {};\n\n/**\n * Create an extension for `micromark` to support GitHub autolink literal\n * syntax.\n *\n * @returns {Extension}\n * Extension for `micromark` that can be passed in `extensions` to enable GFM\n * autolink literal syntax.\n */\nexport function gfmAutolinkLiteral() {\n return {\n text\n };\n}\n\n/** @type {Code} */\nlet code = 48;\n\n// Add alphanumerics.\nwhile (code < 123) {\n text[code] = emailAutolink;\n code++;\n if (code === 58) code = 65;else if (code === 91) code = 97;\n}\ntext[43] = emailAutolink;\ntext[45] = emailAutolink;\ntext[46] = emailAutolink;\ntext[95] = emailAutolink;\ntext[72] = [emailAutolink, protocolAutolink];\ntext[104] = [emailAutolink, protocolAutolink];\ntext[87] = [emailAutolink, wwwAutolink];\ntext[119] = [emailAutolink, wwwAutolink];\n\n// To do: perform email autolink literals on events, afterwards.\n// That’s where `markdown-rs` and `cmark-gfm` perform it.\n// It should look for `@`, then for atext backwards, and then for a label\n// forwards.\n// To do: `mailto:`, `xmpp:` protocol as prefix.\n\n/**\n * Email autolink literal.\n *\n * ```markdown\n * > | a contact@example.org b\n * ^^^^^^^^^^^^^^^^^^^\n * ```\n *\n * @this {TokenizeContext}\n * @type {Tokenizer}\n */\nfunction tokenizeEmailAutolink(effects, ok, nok) {\n const self = this;\n /** @type {boolean | undefined} */\n let dot;\n /** @type {boolean} */\n let data;\n return start;\n\n /**\n * Start of email autolink literal.\n *\n * ```markdown\n * > | a contact@example.org b\n * ^\n * ```\n *\n * @type {State}\n */\n function start(code) {\n if (!gfmAtext(code) || !previousEmail.call(self, self.previous) || previousUnbalanced(self.events)) {\n return nok(code);\n }\n effects.enter('literalAutolink');\n effects.enter('literalAutolinkEmail');\n return atext(code);\n }\n\n /**\n * In email atext.\n *\n * ```markdown\n * > | a contact@example.org b\n * ^\n * ```\n *\n * @type {State}\n */\n function atext(code) {\n if (gfmAtext(code)) {\n effects.consume(code);\n return atext;\n }\n if (code === 64) {\n effects.consume(code);\n return emailDomain;\n }\n return nok(code);\n }\n\n /**\n * In email domain.\n *\n * The reference code is a bit overly complex as it handles the `@`, of which\n * there may be just one.\n * Source: <https://github.com/github/cmark-gfm/blob/ef1cfcb/extensions/autolink.c#L318>\n *\n * ```markdown\n * > | a contact@example.org b\n * ^\n * ```\n *\n * @type {State}\n */\n function emailDomain(code) {\n // Dot followed by alphanumerical (not `-` or `_`).\n if (code === 46) {\n return effects.check(emailDomainDotTrail, emailDomainAfter, emailDomainDot)(code);\n }\n\n // Alphanumerical, `-`, and `_`.\n if (code === 45 || code === 95 || asciiAlphanumeric(code)) {\n data = true;\n effects.consume(code);\n return emailDomain;\n }\n\n // To do: `/` if xmpp.\n\n // Note: normally we’d truncate trailing punctuation from the link.\n // However, email autolink literals cannot contain any of those markers,\n // except for `.`, but that can only occur if it isn’t trailing.\n // So we can ignore truncating!\n return emailDomainAfter(code);\n }\n\n /**\n * In email domain, on dot that is not a trail.\n *\n * ```markdown\n * > | a contact@example.org b\n * ^\n * ```\n *\n * @type {State}\n */\n function emailDomainDot(code) {\n effects.consume(code);\n dot = true;\n return emailDomain;\n }\n\n /**\n * After email domain.\n *\n * ```markdown\n * > | a contact@example.org b\n * ^\n * ```\n *\n * @type {State}\n */\n function emailDomainAfter(code) {\n // Domain must not be empty, must include a dot, and must end in alphabetical.\n // Source: <https://github.com/github/cmark-gfm/blob/ef1cfcb/extensions/autolink.c#L332>.\n if (data && dot && asciiAlpha(self.previous)) {\n effects.exit('literalAutolinkEmail');\n effects.exit('literalAutolink');\n return ok(code);\n }\n return nok(code);\n }\n}\n\n/**\n * `www` autolink literal.\n *\n * ```markdown\n * > | a www.example.org b\n * ^^^^^^^^^^^^^^^\n * ```\n *\n * @this {TokenizeContext}\n * @type {Tokenizer}\n */\nfunction tokenizeWwwAutolink(effects, ok, nok) {\n const self = this;\n return wwwStart;\n\n /**\n * Start of www autolink literal.\n *\n * ```markdown\n * > | www.example.com/a?b#c\n * ^\n * ```\n *\n * @type {State}\n */\n function wwwStart(code) {\n if (code !== 87 && code !== 119 || !previousWww.call(self, self.previous) || previousUnbalanced(self.events)) {\n return nok(code);\n }\n effects.enter('literalAutolink');\n effects.enter('literalAutolinkWww');\n // Note: we *check*, so we can discard the `www.` we parsed.\n // If it worked, we consider it as a part of the domain.\n return effects.check(wwwPrefix, effects.attempt(domain, effects.attempt(path, wwwAfter), nok), nok)(code);\n }\n\n /**\n * After a www autolink literal.\n *\n * ```markdown\n * > | www.example.com/a?b#c\n * ^\n * ```\n *\n * @type {State}\n */\n function wwwAfter(code) {\n effects.exit('literalAutolinkWww');\n effects.exit('literalAutolink');\n return ok(code);\n }\n}\n\n/**\n * Protocol autolink literal.\n *\n * ```markdown\n * > | a https://example.org b\n * ^^^^^^^^^^^^^^^^^^^\n * ```\n *\n * @this {TokenizeContext}\n * @type {Tokenizer}\n */\nfunction tokenizeProtocolAutolink(effects, ok, nok) {\n const self = this;\n let buffer = '';\n let seen = false;\n return protocolStart;\n\n /**\n * Start of protocol autolink literal.\n *\n * ```markdown\n * > | https://example.com/a?b#c\n * ^\n * ```\n *\n * @type {State}\n */\n function protocolStart(code) {\n if ((code === 72 || code === 104) && previousProtocol.call(self, self.previous) && !previousUnbalanced(self.events)) {\n effects.enter('literalAutolink');\n effects.enter('literalAutolinkHttp');\n buffer += String.fromCodePoint(code);\n effects.consume(code);\n return protocolPrefixInside;\n }\n return nok(code);\n }\n\n /**\n * In protocol.\n *\n * ```markdown\n * > | https://example.com/a?b#c\n * ^^^^^\n * ```\n *\n * @type {State}\n */\n function protocolPrefixInside(code) {\n // `5` is size of `https`\n if (asciiAlpha(code) && buffer.length < 5) {\n // @ts-expect-error: definitely number.\n buffer += String.fromCodePoint(code);\n effects.consume(code);\n return protocolPrefixInside;\n }\n if (code === 58) {\n const protocol = buffer.toLowerCase();\n if (protocol === 'http' || protocol === 'https') {\n effects.consume(code);\n return protocolSlashesInside;\n }\n }\n return nok(code);\n }\n\n /**\n * In slashes.\n *\n * ```markdown\n * > | https://example.com/a?b#c\n * ^^\n * ```\n *\n * @type {State}\n */\n function protocolSlashesInside(code) {\n if (code === 47) {\n effects.consume(code);\n if (seen) {\n return afterProtocol;\n }\n seen = true;\n return protocolSlashesInside;\n }\n return nok(code);\n }\n\n /**\n * After protocol, before domain.\n *\n * ```markdown\n * > | https://example.com/a?b#c\n * ^\n * ```\n *\n * @type {State}\n */\n function afterProtocol(code) {\n // To do: this is different from `markdown-rs`:\n // https://github.com/wooorm/markdown-rs/blob/b3a921c761309ae00a51fe348d8a43adbc54b518/src/construct/gfm_autolink_literal.rs#L172-L182\n return code === null || asciiControl(code) || markdownLineEndingOrSpace(code) || unicodeWhitespace(code) || unicodePunctuation(code) ? nok(code) : effects.attempt(domain, effects.attempt(path, protocolAfter), nok)(code);\n }\n\n /**\n * After a protocol autolink literal.\n *\n * ```markdown\n * > | https://example.com/a?b#c\n * ^\n * ```\n *\n * @type {State}\n */\n function protocolAfter(code) {\n effects.exit('literalAutolinkHttp');\n effects.exit('literalAutolink');\n return ok(code);\n }\n}\n\n/**\n * `www` prefix.\n *\n * ```markdown\n * > | a www.example.org b\n * ^^^^\n * ```\n *\n * @this {TokenizeContext}\n * @type {Tokenizer}\n */\nfunction tokenizeWwwPrefix(effects, ok, nok) {\n let size = 0;\n return wwwPrefixInside;\n\n /**\n * In www prefix.\n *\n * ```markdown\n * > | www.example.com\n * ^^^^\n * ```\n *\n * @type {State}\n */\n function wwwPrefixInside(code) {\n if ((code === 87 || code === 119) && size < 3) {\n size++;\n effects.consume(code);\n return wwwPrefixInside;\n }\n if (code === 46 && size === 3) {\n effects.consume(code);\n return wwwPrefixAfter;\n }\n return nok(code);\n }\n\n /**\n * After www prefix.\n *\n * ```markdown\n * > | www.example.com\n * ^\n * ```\n *\n * @type {State}\n */\n function wwwPrefixAfter(code) {\n // If there is *anything*, we can link.\n return code === null ? nok(code) : ok(code);\n }\n}\n\n/**\n * Domain.\n *\n * ```markdown\n * > | a https://example.org b\n * ^^^^^^^^^^^\n * ```\n *\n * @this {TokenizeContext}\n * @type {Tokenizer}\n */\nfunction tokenizeDomain(effects, ok, nok) {\n /** @type {boolean | undefined} */\n let underscoreInLastSegment;\n /** @type {boolean | undefined} */\n let underscoreInLastLastSegment;\n /** @type {boolean | undefined} */\n let seen;\n return domainInside;\n\n /**\n * In domain.\n *\n * ```markdown\n * > | https://example.com/a\n * ^^^^^^^^^^^\n * ```\n *\n * @type {State}\n */\n function domainInside(code) {\n // Check whether this marker, which is a trailing punctuation\n // marker, optionally followed by more trailing markers, and then\n // followed by an end.\n if (code === 46 || code === 95) {\n return effects.check(trail, domainAfter, domainAtPunctuation)(code);\n }\n\n // GH documents that only alphanumerics (other than `-`, `.`, and `_`) can\n // occur, which sounds like ASCII only, but they also support `www.點看.com`,\n // so that’s Unicode.\n // Instead of some new production for Unicode alphanumerics, markdown\n // already has that for Unicode punctuation and whitespace, so use those.\n // Source: <https://github.com/github/cmark-gfm/blob/ef1cfcb/extensions/autolink.c#L12>.\n if (code === null || markdownLineEndingOrSpace(code) || unicodeWhitespace(code) || code !== 45 && unicodePunctuation(code)) {\n return domainAfter(code);\n }\n seen = true;\n effects.consume(code);\n return domainInside;\n }\n\n /**\n * In domain, at potential trailing punctuation, that was not trailing.\n *\n * ```markdown\n * > | https://example.com\n * ^\n * ```\n *\n * @type {State}\n */\n function domainAtPunctuation(code) {\n // There is an underscore in the last segment of the domain\n if (code === 95) {\n underscoreInLastSegment = true;\n }\n // Otherwise, it’s a `.`: save the last segment underscore in the\n // penultimate segment slot.\n else {\n underscoreInLastLastSegment = underscoreInLastSegment;\n underscoreInLastSegment = undefined;\n }\n effects.consume(code);\n return domainInside;\n }\n\n /**\n * After domain.\n *\n * ```markdown\n * > | https://example.com/a\n * ^\n * ```\n *\n * @type {State} */\n function domainAfter(code) {\n // Note: that’s GH says a dot is needed, but it’s not true:\n // <https://github.com/github/cmark-gfm/issues/279>\n if (underscoreInLastLastSegment || underscoreInLastSegment || !seen) {\n return nok(code);\n }\n return ok(code);\n }\n}\n\n/**\n * Path.\n *\n * ```markdown\n * > | a https://example.org/stuff b\n * ^^^^^^\n * ```\n *\n * @this {TokenizeContext}\n * @type {Tokenizer}\n */\nfunction tokenizePath(effects, ok) {\n let sizeOpen = 0;\n let sizeClose = 0;\n return pathInside;\n\n /**\n * In path.\n *\n * ```markdown\n * > | https://example.com/a\n * ^^\n * ```\n *\n * @type {State}\n */\n function pathInside(code) {\n if (code === 40) {\n sizeOpen++;\n effects.consume(code);\n return pathInside;\n }\n\n // To do: `markdown-rs` also needs this.\n // If this is a paren, and there are less closings than openings,\n // we don’t check for a trail.\n if (code === 41 && sizeClose < sizeOpen) {\n return pathAtPunctuation(code);\n }\n\n // Check whether this trailing punctuation marker is optionally\n // followed by more trailing markers, and then followed\n // by an end.\n if (code === 33 || code === 34 || code === 38 || code === 39 || code === 41 || code === 42 || code === 44 || code === 46 || code === 58 || code === 59 || code === 60 || code === 63 || code === 93 || code === 95 || code === 126) {\n return effects.check(trail, ok, pathAtPunctuation)(code);\n }\n if (code === null || markdownLineEndingOrSpace(code) || unicodeWhitespace(code)) {\n return ok(code);\n }\n effects.consume(code);\n return pathInside;\n }\n\n /**\n * In path, at potential trailing punctuation, that was not trailing.\n *\n * ```markdown\n * > | https://example.com/a\"b\n * ^\n * ```\n *\n * @type {State}\n */\n function pathAtPunctuation(code) {\n // Count closing parens.\n if (code === 41) {\n sizeClose++;\n }\n effects.consume(code);\n return pathInside;\n }\n}\n\n/**\n * Trail.\n *\n * This calls `ok` if this *is* the trail, followed by an end, which means\n * the entire trail is not part of the link.\n * It calls `nok` if this *is* part of the link.\n *\n * ```markdown\n * > | https://example.com\").\n * ^^^\n * ```\n *\n * @this {TokenizeContext}\n * @type {Tokenizer}\n */\nfunction tokenizeTrail(effects, ok, nok) {\n return trail;\n\n /**\n * In trail of domain or path.\n *\n * ```markdown\n * > | https://example.com\").\n * ^\n * ```\n *\n * @type {State}\n */\n function trail(code) {\n // Regular trailing punctuation.\n if (code === 33 || code === 34 || code === 39 || code === 41 || code === 42 || code === 44 || code === 46 || code === 58 || code === 59 || code === 63 || code === 95 || code === 126) {\n effects.consume(code);\n return trail;\n }\n\n // `&` followed by one or more alphabeticals and then a `;`, is\n // as a whole considered as trailing punctuation.\n // In all other cases, it is considered as continuation of the URL.\n if (code === 38) {\n effects.consume(code);\n return trailCharacterReferenceStart;\n }\n\n // Needed because we allow literals after `[`, as we fix:\n // <https://github.com/github/cmark-gfm/issues/278>.\n // Check that it is not followed by `(` or `[`.\n if (code === 93) {\n effects.consume(code);\n return trailBracketAfter;\n }\n if (\n // `<` is an end.\n code === 60 ||\n // So is whitespace.\n code === null || markdownLineEndingOrSpace(code) || unicodeWhitespace(code)) {\n return ok(code);\n }\n return nok(code);\n }\n\n /**\n * In trail, after `]`.\n *\n * > 👉 **Note**: this deviates from `cmark-gfm` to fix a bug.\n * > See end of <https://github.com/github/cmark-gfm/issues/278> for more.\n *\n * ```markdown\n * > | https://example.com](\n * ^\n * ```\n *\n * @type {State}\n */\n function trailBracketAfter(code) {\n // Whitespace or something that could start a resource or reference is the end.\n // Switch back to trail otherwise.\n if (code === null || code === 40 || code === 91 || markdownLineEndingOrSpace(code) || unicodeWhitespace(code)) {\n return ok(code);\n }\n return trail(code);\n }\n\n /**\n * In character-reference like trail, after `&`.\n *\n * ```markdown\n * > | https://example.com&).\n * ^\n * ```\n *\n * @type {State}\n */\n function trailCharacterReferenceStart(code) {\n // When non-alpha, it’s not a trail.\n return asciiAlpha(code) ? trailCharacterReferenceInside(code) : nok(code);\n }\n\n /**\n * In character-reference like trail.\n *\n * ```markdown\n * > | https://example.com&).\n * ^\n * ```\n *\n * @type {State}\n */\n function trailCharacterReferenceInside(code) {\n // Switch back to trail if this is well-formed.\n if (code === 59) {\n effects.consume(code);\n return trail;\n }\n if (asciiAlpha(code)) {\n effects.consume(code);\n return trailCharacterReferenceInside;\n }\n\n // It’s not a trail.\n return nok(code);\n }\n}\n\n/**\n * Dot in email domain trail.\n *\n * This calls `ok` if this *is* the trail, followed by an end, which means\n * the trail is not part of the link.\n * It calls `nok` if this *is* part of the link.\n *\n * ```markdown\n * > | contact@example.org.\n * ^\n * ```\n *\n * @this {TokenizeContext}\n * @type {Tokenizer}\n */\nfunction tokenizeEmailDomainDotTrail(effects, ok, nok) {\n return start;\n\n /**\n * Dot.\n *\n * ```markdown\n * > | contact@example.org.\n * ^ ^\n * ```\n *\n * @type {State}\n */\n function start(code) {\n // Must be dot.\n effects.consume(code);\n return after;\n }\n\n /**\n * After dot.\n *\n * ```markdown\n * > | contact@example.org.\n * ^ ^\n * ```\n *\n * @type {State}\n */\n function after(code) {\n // Not a trail if alphanumeric.\n return asciiAlphanumeric(code) ? nok(code) : ok(code);\n }\n}\n\n/**\n * See:\n * <https://github.com/github/cmark-gfm/blob/ef1cfcb/extensions/autolink.c#L156>.\n *\n * @type {Previous}\n */\nfunction previousWww(code) {\n return code === null || code === 40 || code === 42 || code === 95 || code === 91 || code === 93 || code === 126 || markdownLineEndingOrSpace(code);\n}\n\n/**\n * See:\n * <https://github.com/github/cmark-gfm/blob/ef1cfcb/extensions/autolink.c#L214>.\n *\n * @type {Previous}\n */\nfunction previousProtocol(code) {\n return !asciiAlpha(code);\n}\n\n/**\n * @this {TokenizeContext}\n * @type {Previous}\n */\nfunction previousEmail(code) {\n // Do not allow a slash “inside” atext.\n // The reference code is a bit weird, but that’s what it results in.\n // Source: <https://github.com/github/cmark-gfm/blob/ef1cfcb/extensions/autolink.c#L307>.\n // Other than slash, every preceding character is allowed.\n return !(code === 47 || gfmAtext(code));\n}\n\n/**\n * @param {Code} code\n * @returns {boolean}\n */\nfunction gfmAtext(code) {\n return code === 43 || code === 45 || code === 46 || code === 95 || asciiAlphanumeric(code);\n}\n\n/**\n * @param {Array<Event>} events\n * @returns {boolean}\n */\nfunction previousUnbalanced(events) {\n let index = events.length;\n let result = false;\n while (index--) {\n const token = events[index][1];\n if ((token.type === 'labelLink' || token.type === 'labelImage') && !token._balanced) {\n result = true;\n break;\n }\n\n // If we’ve seen this token, and it was marked as not having any unbalanced\n // bracket before it, we can exit.\n if (token._gfmAutolinkLiteralWalkedInto) {\n result = false;\n break;\n }\n }\n if (events.length > 0 && !result) {\n // Mark the last token as “walked into” w/o finding\n // anything.\n events[events.length - 1][1]._gfmAutolinkLiteralWalkedInto = true;\n }\n return result;\n}","/**\n * @import {Event, Resolver, TokenizeContext} from 'micromark-util-types'\n */\n\n/**\n * Call all `resolveAll`s.\n *\n * @param {ReadonlyArray<{resolveAll?: Resolver | undefined}>} constructs\n * List of constructs, optionally with `resolveAll`s.\n * @param {Array<Event>} events\n * List of events.\n * @param {TokenizeContext} context\n * Context used by `tokenize`.\n * @returns {Array<Event>}\n * Changed events.\n */\nexport function resolveAll(constructs, events, context) {\n /** @type {Array<Resolver>} */\n const called = []\n let index = -1\n\n while (++index < constructs.length) {\n const resolve = constructs[index].resolveAll\n\n if (resolve && !called.includes(resolve)) {\n events = resolve(events, context)\n called.push(resolve)\n }\n }\n\n return events\n}\n","/**\n * @import {Effects, State, TokenType} from 'micromark-util-types'\n */\n\nimport { markdownSpace } from 'micromark-util-character';\n\n// To do: implement `spaceOrTab`, `spaceOrTabMinMax`, `spaceOrTabWithOptions`.\n\n/**\n * Parse spaces and tabs.\n *\n * There is no `nok` parameter:\n *\n * * spaces in markdown are often optional, in which case this factory can be\n * used and `ok` will be switched to whether spaces were found or not\n * * one line ending or space can be detected with `markdownSpace(code)` right\n * before using `factorySpace`\n *\n * ###### Examples\n *\n * Where `␉` represents a tab (plus how much it expands) and `␠` represents a\n * single space.\n *\n * ```markdown\n * ␉\n * ␠␠␠␠\n * ␉␠\n * ```\n *\n * @param {Effects} effects\n * Context.\n * @param {State} ok\n * State switched to when successful.\n * @param {TokenType} type\n * Type (`' \\t'`).\n * @param {number | undefined} [max=Infinity]\n * Max (exclusive).\n * @returns {State}\n * Start state.\n */\nexport function factorySpace(effects, ok, type, max) {\n const limit = max ? max - 1 : Number.POSITIVE_INFINITY;\n let size = 0;\n return start;\n\n /** @type {State} */\n function start(code) {\n if (markdownSpace(code)) {\n effects.enter(type);\n return prefix(code);\n }\n return ok(code);\n }\n\n /** @type {State} */\n function prefix(code) {\n if (markdownSpace(code) && size++ < limit) {\n effects.consume(code);\n return prefix;\n }\n effects.exit(type);\n return ok(code);\n }\n}","/**\n * @import {\n * Construct,\n * State,\n * TokenizeContext,\n * Tokenizer\n * } from 'micromark-util-types'\n */\n\nimport { factorySpace } from 'micromark-factory-space';\nimport { markdownLineEnding, markdownSpace } from 'micromark-util-character';\n/** @type {Construct} */\nexport const blankLine = {\n partial: true,\n tokenize: tokenizeBlankLine\n};\n\n/**\n * @this {TokenizeContext}\n * Context.\n * @type {Tokenizer}\n */\nfunction tokenizeBlankLine(effects, ok, nok) {\n return start;\n\n /**\n * Start of blank line.\n *\n * > 👉 **Note**: `␠` represents a space character.\n *\n * ```markdown\n * > | ␠␠␊\n * ^\n * > | ␊\n * ^\n * ```\n *\n * @type {State}\n */\n function start(code) {\n return markdownSpace(code) ? factorySpace(effects, after, \"linePrefix\")(code) : after(code);\n }\n\n /**\n * At eof/eol, after optional whitespace.\n *\n * > 👉 **Note**: `␠` represents a space character.\n *\n * ```markdown\n * > | ␠␠␊\n * ^\n * > | ␊\n * ^\n * ```\n *\n * @type {State}\n */\n function after(code) {\n return code === null || markdownLineEnding(code) ? ok(code) : nok(code);\n }\n}","/**\n * @import {Event, Exiter, Extension, Resolver, State, Token, TokenizeContext, Tokenizer} from 'micromark-util-types'\n */\n\nimport { blankLine } from 'micromark-core-commonmark';\nimport { factorySpace } from 'micromark-factory-space';\nimport { markdownLineEndingOrSpace } from 'micromark-util-character';\nimport { normalizeIdentifier } from 'micromark-util-normalize-identifier';\nconst indent = {\n tokenize: tokenizeIndent,\n partial: true\n};\n\n// To do: micromark should support a `_hiddenGfmFootnoteSupport`, which only\n// affects label start (image).\n// That will let us drop `tokenizePotentialGfmFootnote*`.\n// It currently has a `_hiddenFootnoteSupport`, which affects that and more.\n// That can be removed when `micromark-extension-footnote` is archived.\n\n/**\n * Create an extension for `micromark` to enable GFM footnote syntax.\n *\n * @returns {Extension}\n * Extension for `micromark` that can be passed in `extensions` to\n * enable GFM footnote syntax.\n */\nexport function gfmFootnote() {\n /** @type {Extension} */\n return {\n document: {\n [91]: {\n name: 'gfmFootnoteDefinition',\n tokenize: tokenizeDefinitionStart,\n continuation: {\n tokenize: tokenizeDefinitionContinuation\n },\n exit: gfmFootnoteDefinitionEnd\n }\n },\n text: {\n [91]: {\n name: 'gfmFootnoteCall',\n tokenize: tokenizeGfmFootnoteCall\n },\n [93]: {\n name: 'gfmPotentialFootnoteCall',\n add: 'after',\n tokenize: tokenizePotentialGfmFootnoteCall,\n resolveTo: resolveToPotentialGfmFootnoteCall\n }\n }\n };\n}\n\n// To do: remove after micromark update.\n/**\n * @this {TokenizeContext}\n * @type {Tokenizer}\n */\nfunction tokenizePotentialGfmFootnoteCall(effects, ok, nok) {\n const self = this;\n let index = self.events.length;\n const defined = self.parser.gfmFootnotes || (self.parser.gfmFootnotes = []);\n /** @type {Token} */\n let labelStart;\n\n // Find an opening.\n while (index--) {\n const token = self.events[index][1];\n if (token.type === \"labelImage\") {\n labelStart = token;\n break;\n }\n\n // Exit if we’ve walked far enough.\n if (token.type === 'gfmFootnoteCall' || token.type === \"labelLink\" || token.type === \"label\" || token.type === \"image\" || token.type === \"link\") {\n break;\n }\n }\n return start;\n\n /**\n * @type {State}\n */\n function start(code) {\n if (!labelStart || !labelStart._balanced) {\n return nok(code);\n }\n const id = normalizeIdentifier(self.sliceSerialize({\n start: labelStart.end,\n end: self.now()\n }));\n if (id.codePointAt(0) !== 94 || !defined.includes(id.slice(1))) {\n return nok(code);\n }\n effects.enter('gfmFootnoteCallLabelMarker');\n effects.consume(code);\n effects.exit('gfmFootnoteCallLabelMarker');\n return ok(code);\n }\n}\n\n// To do: remove after micromark update.\n/** @type {Resolver} */\nfunction resolveToPotentialGfmFootnoteCall(events, context) {\n let index = events.length;\n /** @type {Token | undefined} */\n let labelStart;\n\n // Find an opening.\n while (index--) {\n if (events[index][1].type === \"labelImage\" && events[index][0] === 'enter') {\n labelStart = events[index][1];\n break;\n }\n }\n // Change the `labelImageMarker` to a `data`.\n events[index + 1][1].type = \"data\";\n events[index + 3][1].type = 'gfmFootnoteCallLabelMarker';\n\n // The whole (without `!`):\n /** @type {Token} */\n const call = {\n type: 'gfmFootnoteCall',\n start: Object.assign({}, events[index + 3][1].start),\n end: Object.assign({}, events[events.length - 1][1].end)\n };\n // The `^` marker\n /** @type {Token} */\n const marker = {\n type: 'gfmFootnoteCallMarker',\n start: Object.assign({}, events[index + 3][1].end),\n end: Object.assign({}, events[index + 3][1].end)\n };\n // Increment the end 1 character.\n marker.end.column++;\n marker.end.offset++;\n marker.end._bufferIndex++;\n /** @type {Token} */\n const string = {\n type: 'gfmFootnoteCallString',\n start: Object.assign({}, marker.end),\n end: Object.assign({}, events[events.length - 1][1].start)\n };\n /** @type {Token} */\n const chunk = {\n type: \"chunkString\",\n contentType: 'string',\n start: Object.assign({}, string.start),\n end: Object.assign({}, string.end)\n };\n\n /** @type {Array<Event>} */\n const replacement = [\n // Take the `labelImageMarker` (now `data`, the `!`)\n events[index + 1], events[index + 2], ['enter', call, context],\n // The `[`\n events[index + 3], events[index + 4],\n // The `^`.\n ['enter', marker, context], ['exit', marker, context],\n // Everything in between.\n ['enter', string, context], ['enter', chunk, context], ['exit', chunk, context], ['exit', string, context],\n // The ending (`]`, properly parsed and labelled).\n events[events.length - 2], events[events.length - 1], ['exit', call, context]];\n events.splice(index, events.length - index + 1, ...replacement);\n return events;\n}\n\n/**\n * @this {TokenizeContext}\n * @type {Tokenizer}\n */\nfunction tokenizeGfmFootnoteCall(effects, ok, nok) {\n const self = this;\n const defined = self.parser.gfmFootnotes || (self.parser.gfmFootnotes = []);\n let size = 0;\n /** @type {boolean} */\n let data;\n\n // Note: the implementation of `markdown-rs` is different, because it houses\n // core *and* extensions in one project.\n // Therefore, it can include footnote logic inside `label-end`.\n // We can’t do that, but luckily, we can parse footnotes in a simpler way than\n // needed for labels.\n return start;\n\n /**\n * Start of footnote label.\n *\n * ```markdown\n * > | a [^b] c\n * ^\n * ```\n *\n * @type {State}\n */\n function start(code) {\n effects.enter('gfmFootnoteCall');\n effects.enter('gfmFootnoteCallLabelMarker');\n effects.consume(code);\n effects.exit('gfmFootnoteCallLabelMarker');\n return callStart;\n }\n\n /**\n * After `[`, at `^`.\n *\n * ```markdown\n * > | a [^b] c\n * ^\n * ```\n *\n * @type {State}\n */\n function callStart(code) {\n if (code !== 94) return nok(code);\n effects.enter('gfmFootnoteCallMarker');\n effects.consume(code);\n effects.exit('gfmFootnoteCallMarker');\n effects.enter('gfmFootnoteCallString');\n effects.enter('chunkString').contentType = 'string';\n return callData;\n }\n\n /**\n * In label.\n *\n * ```markdown\n * > | a [^b] c\n * ^\n * ```\n *\n * @type {State}\n */\n function callData(code) {\n if (\n // Too long.\n size > 999 ||\n // Closing brace with nothing.\n code === 93 && !data ||\n // Space or tab is not supported by GFM for some reason.\n // `\\n` and `[` not being supported makes sense.\n code === null || code === 91 || markdownLineEndingOrSpace(code)) {\n return nok(code);\n }\n if (code === 93) {\n effects.exit('chunkString');\n const token = effects.exit('gfmFootnoteCallString');\n if (!defined.includes(normalizeIdentifier(self.sliceSerialize(token)))) {\n return nok(code);\n }\n effects.enter('gfmFootnoteCallLabelMarker');\n effects.consume(code);\n effects.exit('gfmFootnoteCallLabelMarker');\n effects.exit('gfmFootnoteCall');\n return ok;\n }\n if (!markdownLineEndingOrSpace(code)) {\n data = true;\n }\n size++;\n effects.consume(code);\n return code === 92 ? callEscape : callData;\n }\n\n /**\n * On character after escape.\n *\n * ```markdown\n * > | a [^b\\c] d\n * ^\n * ```\n *\n * @type {State}\n */\n function callEscape(code) {\n if (code === 91 || code === 92 || code === 93) {\n effects.consume(code);\n size++;\n return callData;\n }\n return callData(code);\n }\n}\n\n/**\n * @this {TokenizeContext}\n * @type {Tokenizer}\n */\nfunction tokenizeDefinitionStart(effects, ok, nok) {\n const self = this;\n const defined = self.parser.gfmFootnotes || (self.parser.gfmFootnotes = []);\n /** @type {string} */\n let identifier;\n let size = 0;\n /** @type {boolean | undefined} */\n let data;\n return start;\n\n /**\n * Start of GFM footnote definition.\n *\n * ```markdown\n * > | [^a]: b\n * ^\n * ```\n *\n * @type {State}\n */\n function start(code) {\n effects.enter('gfmFootnoteDefinition')._container = true;\n effects.enter('gfmFootnoteDefinitionLabel');\n effects.enter('gfmFootnoteDefinitionLabelMarker');\n effects.consume(code);\n effects.exit('gfmFootnoteDefinitionLabelMarker');\n return labelAtMarker;\n }\n\n /**\n * In label, at caret.\n *\n * ```markdown\n * > | [^a]: b\n * ^\n * ```\n *\n * @type {State}\n */\n function labelAtMarker(code) {\n if (code === 94) {\n effects.enter('gfmFootnoteDefinitionMarker');\n effects.consume(code);\n effects.exit('gfmFootnoteDefinitionMarker');\n effects.enter('gfmFootnoteDefinitionLabelString');\n effects.enter('chunkString').contentType = 'string';\n return labelInside;\n }\n return nok(code);\n }\n\n /**\n * In label.\n *\n * > 👉 **Note**: `cmark-gfm` prevents whitespace from occurring in footnote\n * > definition labels.\n *\n * ```markdown\n * > | [^a]: b\n * ^\n * ```\n *\n * @type {State}\n */\n function labelInside(code) {\n if (\n // Too long.\n size > 999 ||\n // Closing brace with nothing.\n code === 93 && !data ||\n // Space or tab is not supported by GFM for some reason.\n // `\\n` and `[` not being supported makes sense.\n code === null || code === 91 || markdownLineEndingOrSpace(code)) {\n return nok(code);\n }\n if (code === 93) {\n effects.exit('chunkString');\n const token = effects.exit('gfmFootnoteDefinitionLabelString');\n identifier = normalizeIdentifier(self.sliceSerialize(token));\n effects.enter('gfmFootnoteDefinitionLabelMarker');\n effects.consume(code);\n effects.exit('gfmFootnoteDefinitionLabelMarker');\n effects.exit('gfmFootnoteDefinitionLabel');\n return labelAfter;\n }\n if (!markdownLineEndingOrSpace(code)) {\n data = true;\n }\n size++;\n effects.consume(code);\n return code === 92 ? labelEscape : labelInside;\n }\n\n /**\n * After `\\`, at a special character.\n *\n * > 👉 **Note**: `cmark-gfm` currently does not support escaped brackets:\n * > <https://github.com/github/cmark-gfm/issues/240>\n *\n * ```markdown\n * > | [^a\\*b]: c\n * ^\n * ```\n *\n * @type {State}\n */\n function labelEscape(code) {\n if (code === 91 || code === 92 || code === 93) {\n effects.consume(code);\n size++;\n return labelInside;\n }\n return labelInside(code);\n }\n\n /**\n * After definition label.\n *\n * ```markdown\n * > | [^a]: b\n * ^\n * ```\n *\n * @type {State}\n */\n function labelAfter(code) {\n if (code === 58) {\n effects.enter('definitionMarker');\n effects.consume(code);\n effects.exit('definitionMarker');\n if (!defined.includes(identifier)) {\n defined.push(identifier);\n }\n\n // Any whitespace after the marker is eaten, forming indented code\n // is not possible.\n // No space is also fine, just like a block quote marker.\n return factorySpace(effects, whitespaceAfter, 'gfmFootnoteDefinitionWhitespace');\n }\n return nok(code);\n }\n\n /**\n * After definition prefix.\n *\n * ```markdown\n * > | [^a]: b\n * ^\n * ```\n *\n * @type {State}\n */\n function whitespaceAfter(code) {\n // `markdown-rs` has a wrapping token for the prefix that is closed here.\n return ok(code);\n }\n}\n\n/**\n * @this {TokenizeContext}\n * @type {Tokenizer}\n */\nfunction tokenizeDefinitionContinuation(effects, ok, nok) {\n /// Start of footnote definition continuation.\n ///\n /// ```markdown\n /// | [^a]: b\n /// > | c\n /// ^\n /// ```\n //\n // Either a blank line, which is okay, or an indented thing.\n return effects.check(blankLine, ok, effects.attempt(indent, ok, nok));\n}\n\n/** @type {Exiter} */\nfunction gfmFootnoteDefinitionEnd(effects) {\n effects.exit('gfmFootnoteDefinition');\n}\n\n/**\n * @this {TokenizeContext}\n * @type {Tokenizer}\n */\nfunction tokenizeIndent(effects, ok, nok) {\n const self = this;\n return factorySpace(effects, afterPrefix, 'gfmFootnoteDefinitionIndent', 4 + 1);\n\n /**\n * @type {State}\n */\n function afterPrefix(code) {\n const tail = self.events[self.events.length - 1];\n return tail && tail[1].type === 'gfmFootnoteDefinitionIndent' && tail[2].sliceSerialize(tail[1], true).length === 4 ? ok(code) : nok(code);\n }\n}","/**\n * @import {Options} from 'micromark-extension-gfm-strikethrough'\n * @import {Event, Extension, Resolver, State, Token, TokenizeContext, Tokenizer} from 'micromark-util-types'\n */\n\nimport { splice } from 'micromark-util-chunked';\nimport { classifyCharacter } from 'micromark-util-classify-character';\nimport { resolveAll } from 'micromark-util-resolve-all';\n/**\n * Create an extension for `micromark` to enable GFM strikethrough syntax.\n *\n * @param {Options | null | undefined} [options={}]\n * Configuration.\n * @returns {Extension}\n * Extension for `micromark` that can be passed in `extensions`, to\n * enable GFM strikethrough syntax.\n */\nexport function gfmStrikethrough(options) {\n const options_ = options || {};\n let single = options_.singleTilde;\n const tokenizer = {\n name: 'strikethrough',\n tokenize: tokenizeStrikethrough,\n resolveAll: resolveAllStrikethrough\n };\n if (single === null || single === undefined) {\n single = true;\n }\n return {\n text: {\n [126]: tokenizer\n },\n insideSpan: {\n null: [tokenizer]\n },\n attentionMarkers: {\n null: [126]\n }\n };\n\n /**\n * Take events and resolve strikethrough.\n *\n * @type {Resolver}\n */\n function resolveAllStrikethrough(events, context) {\n let index = -1;\n\n // Walk through all events.\n while (++index < events.length) {\n // Find a token that can close.\n if (events[index][0] === 'enter' && events[index][1].type === 'strikethroughSequenceTemporary' && events[index][1]._close) {\n let open = index;\n\n // Now walk back to find an opener.\n while (open--) {\n // Find a token that can open the closer.\n if (events[open][0] === 'exit' && events[open][1].type === 'strikethroughSequenceTemporary' && events[open][1]._open &&\n // If the sizes are the same:\n events[index][1].end.offset - events[index][1].start.offset === events[open][1].end.offset - events[open][1].start.offset) {\n events[index][1].type = 'strikethroughSequence';\n events[open][1].type = 'strikethroughSequence';\n\n /** @type {Token} */\n const strikethrough = {\n type: 'strikethrough',\n start: Object.assign({}, events[open][1].start),\n end: Object.assign({}, events[index][1].end)\n };\n\n /** @type {Token} */\n const text = {\n type: 'strikethroughText',\n start: Object.assign({}, events[open][1].end),\n end: Object.assign({}, events[index][1].start)\n };\n\n // Opening.\n /** @type {Array<Event>} */\n const nextEvents = [['enter', strikethrough, context], ['enter', events[open][1], context], ['exit', events[open][1], context], ['enter', text, context]];\n const insideSpan = context.parser.constructs.insideSpan.null;\n if (insideSpan) {\n // Between.\n splice(nextEvents, nextEvents.length, 0, resolveAll(insideSpan, events.slice(open + 1, index), context));\n }\n\n // Closing.\n splice(nextEvents, nextEvents.length, 0, [['exit', text, context], ['enter', events[index][1], context], ['exit', events[index][1], context], ['exit', strikethrough, context]]);\n splice(events, open - 1, index - open + 3, nextEvents);\n index = open + nextEvents.length - 2;\n break;\n }\n }\n }\n }\n index = -1;\n while (++index < events.length) {\n if (events[index][1].type === 'strikethroughSequenceTemporary') {\n events[index][1].type = \"data\";\n }\n }\n return events;\n }\n\n /**\n * @this {TokenizeContext}\n * @type {Tokenizer}\n */\n function tokenizeStrikethrough(effects, ok, nok) {\n const previous = this.previous;\n const events = this.events;\n let size = 0;\n return start;\n\n /** @type {State} */\n function start(code) {\n if (previous === 126 && events[events.length - 1][1].type !== \"characterEscape\") {\n return nok(code);\n }\n effects.enter('strikethroughSequenceTemporary');\n return more(code);\n }\n\n /** @type {State} */\n function more(code) {\n const before = classifyCharacter(previous);\n if (code === 126) {\n // If this is the third marker, exit.\n if (size > 1) return nok(code);\n effects.consume(code);\n size++;\n return more;\n }\n if (size < 2 && !single) return nok(code);\n const token = effects.exit('strikethroughSequenceTemporary');\n const after = classifyCharacter(code);\n token._open = !after || after === 2 && Boolean(before);\n token._close = !before || before === 2 && Boolean(after);\n return ok(code);\n }\n }\n}","/**\n * @import {Event} from 'micromark-util-types'\n */\n\n// Port of `edit_map.rs` from `markdown-rs`.\n// This should move to `markdown-js` later.\n\n// Deal with several changes in events, batching them together.\n//\n// Preferably, changes should be kept to a minimum.\n// Sometimes, it’s needed to change the list of events, because parsing can be\n// messy, and it helps to expose a cleaner interface of events to the compiler\n// and other users.\n// It can also help to merge many adjacent similar events.\n// And, in other cases, it’s needed to parse subcontent: pass some events\n// through another tokenizer and inject the result.\n\n/**\n * @typedef {[number, number, Array<Event>]} Change\n * @typedef {[number, number, number]} Jump\n */\n\n/**\n * Tracks a bunch of edits.\n */\nexport class EditMap {\n /**\n * Create a new edit map.\n */\n constructor() {\n /**\n * Record of changes.\n *\n * @type {Array<Change>}\n */\n this.map = [];\n }\n\n /**\n * Create an edit: a remove and/or add at a certain place.\n *\n * @param {number} index\n * @param {number} remove\n * @param {Array<Event>} add\n * @returns {undefined}\n */\n add(index, remove, add) {\n addImplementation(this, index, remove, add);\n }\n\n // To do: add this when moving to `micromark`.\n // /**\n // * Create an edit: but insert `add` before existing additions.\n // *\n // * @param {number} index\n // * @param {number} remove\n // * @param {Array<Event>} add\n // * @returns {undefined}\n // */\n // addBefore(index, remove, add) {\n // addImplementation(this, index, remove, add, true)\n // }\n\n /**\n * Done, change the events.\n *\n * @param {Array<Event>} events\n * @returns {undefined}\n */\n consume(events) {\n this.map.sort(function (a, b) {\n return a[0] - b[0];\n });\n\n /* c8 ignore next 3 -- `resolve` is never called without tables, so without edits. */\n if (this.map.length === 0) {\n return;\n }\n\n // To do: if links are added in events, like they are in `markdown-rs`,\n // this is needed.\n // // Calculate jumps: where items in the current list move to.\n // /** @type {Array<Jump>} */\n // const jumps = []\n // let index = 0\n // let addAcc = 0\n // let removeAcc = 0\n // while (index < this.map.length) {\n // const [at, remove, add] = this.map[index]\n // removeAcc += remove\n // addAcc += add.length\n // jumps.push([at, removeAcc, addAcc])\n // index += 1\n // }\n //\n // . shiftLinks(events, jumps)\n\n let index = this.map.length;\n /** @type {Array<Array<Event>>} */\n const vecs = [];\n while (index > 0) {\n index -= 1;\n vecs.push(events.slice(this.map[index][0] + this.map[index][1]), this.map[index][2]);\n\n // Truncate rest.\n events.length = this.map[index][0];\n }\n vecs.push(events.slice());\n events.length = 0;\n let slice = vecs.pop();\n while (slice) {\n for (const element of slice) {\n events.push(element);\n }\n slice = vecs.pop();\n }\n\n // Truncate everything.\n this.map.length = 0;\n }\n}\n\n/**\n * Create an edit.\n *\n * @param {EditMap} editMap\n * @param {number} at\n * @param {number} remove\n * @param {Array<Event>} add\n * @returns {undefined}\n */\nfunction addImplementation(editMap, at, remove, add) {\n let index = 0;\n\n /* c8 ignore next 3 -- `resolve` is never called without tables, so without edits. */\n if (remove === 0 && add.length === 0) {\n return;\n }\n while (index < editMap.map.length) {\n if (editMap.map[index][0] === at) {\n editMap.map[index][1] += remove;\n\n // To do: before not used by tables, use when moving to micromark.\n // if (before) {\n // add.push(...editMap.map[index][2])\n // editMap.map[index][2] = add\n // } else {\n editMap.map[index][2].push(...add);\n // }\n\n return;\n }\n index += 1;\n }\n editMap.map.push([at, remove, add]);\n}\n\n// /**\n// * Shift `previous` and `next` links according to `jumps`.\n// *\n// * This fixes links in case there are events removed or added between them.\n// *\n// * @param {Array<Event>} events\n// * @param {Array<Jump>} jumps\n// */\n// function shiftLinks(events, jumps) {\n// let jumpIndex = 0\n// let index = 0\n// let add = 0\n// let rm = 0\n\n// while (index < events.length) {\n// const rmCurr = rm\n\n// while (jumpIndex < jumps.length && jumps[jumpIndex][0] <= index) {\n// add = jumps[jumpIndex][2]\n// rm = jumps[jumpIndex][1]\n// jumpIndex += 1\n// }\n\n// // Ignore items that will be removed.\n// if (rm > rmCurr) {\n// index += rm - rmCurr\n// } else {\n// // ?\n// // if let Some(link) = &events[index].link {\n// // if let Some(next) = link.next {\n// // events[next].link.as_mut().unwrap().previous = Some(index + add - rm);\n// // while jumpIndex < jumps.len() && jumps[jumpIndex].0 <= next {\n// // add = jumps[jumpIndex].2;\n// // rm = jumps[jumpIndex].1;\n// // jumpIndex += 1;\n// // }\n// // events[index].link.as_mut().unwrap().next = Some(next + add - rm);\n// // index = next;\n// // continue;\n// // }\n// // }\n// index += 1\n// }\n// }\n// }","/**\n * @import {Event} from 'micromark-util-types'\n */\n\n/**\n * @typedef {'center' | 'left' | 'none' | 'right'} Align\n */\n\n/**\n * Figure out the alignment of a GFM table.\n *\n * @param {Readonly<Array<Event>>} events\n * List of events.\n * @param {number} index\n * Table enter event.\n * @returns {Array<Align>}\n * List of aligns.\n */\nexport function gfmTableAlign(events, index) {\n let inDelimiterRow = false;\n /** @type {Array<Align>} */\n const align = [];\n while (index < events.length) {\n const event = events[index];\n if (inDelimiterRow) {\n if (event[0] === 'enter') {\n // Start of alignment value: set a new column.\n // To do: `markdown-rs` uses `tableDelimiterCellValue`.\n if (event[1].type === 'tableContent') {\n align.push(events[index + 1][1].type === 'tableDelimiterMarker' ? 'left' : 'none');\n }\n }\n // Exits:\n // End of alignment value: change the column.\n // To do: `markdown-rs` uses `tableDelimiterCellValue`.\n else if (event[1].type === 'tableContent') {\n if (events[index - 1][1].type === 'tableDelimiterMarker') {\n const alignIndex = align.length - 1;\n align[alignIndex] = align[alignIndex] === 'left' ? 'center' : 'right';\n }\n }\n // Done!\n else if (event[1].type === 'tableDelimiterRow') {\n break;\n }\n } else if (event[0] === 'enter' && event[1].type === 'tableDelimiterRow') {\n inDelimiterRow = true;\n }\n index += 1;\n }\n return align;\n}","/**\n * @import {Event, Extension, Point, Resolver, State, Token, TokenizeContext, Tokenizer} from 'micromark-util-types'\n */\n\n/**\n * @typedef {[number, number, number, number]} Range\n * Cell info.\n *\n * @typedef {0 | 1 | 2 | 3} RowKind\n * Where we are: `1` for head row, `2` for delimiter row, `3` for body row.\n */\n\nimport { factorySpace } from 'micromark-factory-space';\nimport { markdownLineEnding, markdownLineEndingOrSpace, markdownSpace } from 'micromark-util-character';\nimport { EditMap } from './edit-map.js';\nimport { gfmTableAlign } from './infer.js';\n\n/**\n * Create an HTML extension for `micromark` to support GitHub tables syntax.\n *\n * @returns {Extension}\n * Extension for `micromark` that can be passed in `extensions` to enable GFM\n * table syntax.\n */\nexport function gfmTable() {\n return {\n flow: {\n null: {\n name: 'table',\n tokenize: tokenizeTable,\n resolveAll: resolveTable\n }\n }\n };\n}\n\n/**\n * @this {TokenizeContext}\n * @type {Tokenizer}\n */\nfunction tokenizeTable(effects, ok, nok) {\n const self = this;\n let size = 0;\n let sizeB = 0;\n /** @type {boolean | undefined} */\n let seen;\n return start;\n\n /**\n * Start of a GFM table.\n *\n * If there is a valid table row or table head before, then we try to parse\n * another row.\n * Otherwise, we try to parse a head.\n *\n * ```markdown\n * > | | a |\n * ^\n * | | - |\n * > | | b |\n * ^\n * ```\n * @type {State}\n */\n function start(code) {\n let index = self.events.length - 1;\n while (index > -1) {\n const type = self.events[index][1].type;\n if (type === \"lineEnding\" ||\n // Note: markdown-rs uses `whitespace` instead of `linePrefix`\n type === \"linePrefix\") index--;else break;\n }\n const tail = index > -1 ? self.events[index][1].type : null;\n const next = tail === 'tableHead' || tail === 'tableRow' ? bodyRowStart : headRowBefore;\n\n // Don’t allow lazy body rows.\n if (next === bodyRowStart && self.parser.lazy[self.now().line]) {\n return nok(code);\n }\n return next(code);\n }\n\n /**\n * Before table head row.\n *\n * ```markdown\n * > | | a |\n * ^\n * | | - |\n * | | b |\n * ```\n *\n * @type {State}\n */\n function headRowBefore(code) {\n effects.enter('tableHead');\n effects.enter('tableRow');\n return headRowStart(code);\n }\n\n /**\n * Before table head row, after whitespace.\n *\n * ```markdown\n * > | | a |\n * ^\n * | | - |\n * | | b |\n * ```\n *\n * @type {State}\n */\n function headRowStart(code) {\n if (code === 124) {\n return headRowBreak(code);\n }\n\n // To do: micromark-js should let us parse our own whitespace in extensions,\n // like `markdown-rs`:\n //\n // ```js\n // // 4+ spaces.\n // if (markdownSpace(code)) {\n // return nok(code)\n // }\n // ```\n\n seen = true;\n // Count the first character, that isn’t a pipe, double.\n sizeB += 1;\n return headRowBreak(code);\n }\n\n /**\n * At break in table head row.\n *\n * ```markdown\n * > | | a |\n * ^\n * ^\n * ^\n * | | - |\n * | | b |\n * ```\n *\n * @type {State}\n */\n function headRowBreak(code) {\n if (code === null) {\n // Note: in `markdown-rs`, we need to reset, in `micromark-js` we don‘t.\n return nok(code);\n }\n if (markdownLineEnding(code)) {\n // If anything other than one pipe (ignoring whitespace) was used, it’s fine.\n if (sizeB > 1) {\n sizeB = 0;\n // To do: check if this works.\n // Feel free to interrupt:\n self.interrupt = true;\n effects.exit('tableRow');\n effects.enter(\"lineEnding\");\n effects.consume(code);\n effects.exit(\"lineEnding\");\n return headDelimiterStart;\n }\n\n // Note: in `markdown-rs`, we need to reset, in `micromark-js` we don‘t.\n return nok(code);\n }\n if (markdownSpace(code)) {\n // To do: check if this is fine.\n // effects.attempt(State::Next(StateName::GfmTableHeadRowBreak), State::Nok)\n // State::Retry(space_or_tab(tokenizer))\n return factorySpace(effects, headRowBreak, \"whitespace\")(code);\n }\n sizeB += 1;\n if (seen) {\n seen = false;\n // Header cell count.\n size += 1;\n }\n if (code === 124) {\n effects.enter('tableCellDivider');\n effects.consume(code);\n effects.exit('tableCellDivider');\n // Whether a delimiter was seen.\n seen = true;\n return headRowBreak;\n }\n\n // Anything else is cell data.\n effects.enter(\"data\");\n return headRowData(code);\n }\n\n /**\n * In table head row data.\n *\n * ```markdown\n * > | | a |\n * ^\n * | | - |\n * | | b |\n * ```\n *\n * @type {State}\n */\n function headRowData(code) {\n if (code === null || code === 124 || markdownLineEndingOrSpace(code)) {\n effects.exit(\"data\");\n return headRowBreak(code);\n }\n effects.consume(code);\n return code === 92 ? headRowEscape : headRowData;\n }\n\n /**\n * In table head row escape.\n *\n * ```markdown\n * > | | a\\-b |\n * ^\n * | | ---- |\n * | | c |\n * ```\n *\n * @type {State}\n */\n function headRowEscape(code) {\n if (code === 92 || code === 124) {\n effects.consume(code);\n return headRowData;\n }\n return headRowData(code);\n }\n\n /**\n * Before delimiter row.\n *\n * ```markdown\n * | | a |\n * > | | - |\n * ^\n * | | b |\n * ```\n *\n * @type {State}\n */\n function headDelimiterStart(code) {\n // Reset `interrupt`.\n self.interrupt = false;\n\n // Note: in `markdown-rs`, we need to handle piercing here too.\n if (self.parser.lazy[self.now().line]) {\n return nok(code);\n }\n effects.enter('tableDelimiterRow');\n // Track if we’ve seen a `:` or `|`.\n seen = false;\n if (markdownSpace(code)) {\n return factorySpace(effects, headDelimiterBefore, \"linePrefix\", self.parser.constructs.disable.null.includes('codeIndented') ? undefined : 4)(code);\n }\n return headDelimiterBefore(code);\n }\n\n /**\n * Before delimiter row, after optional whitespace.\n *\n * Reused when a `|` is found later, to parse another cell.\n *\n * ```markdown\n * | | a |\n * > | | - |\n * ^\n * | | b |\n * ```\n *\n * @type {State}\n */\n function headDelimiterBefore(code) {\n if (code === 45 || code === 58) {\n return headDelimiterValueBefore(code);\n }\n if (code === 124) {\n seen = true;\n // If we start with a pipe, we open a cell marker.\n effects.enter('tableCellDivider');\n effects.consume(code);\n effects.exit('tableCellDivider');\n return headDelimiterCellBefore;\n }\n\n // More whitespace / empty row not allowed at start.\n return headDelimiterNok(code);\n }\n\n /**\n * After `|`, before delimiter cell.\n *\n * ```markdown\n * | | a |\n * > | | - |\n * ^\n * ```\n *\n * @type {State}\n */\n function headDelimiterCellBefore(code) {\n if (markdownSpace(code)) {\n return factorySpace(effects, headDelimiterValueBefore, \"whitespace\")(code);\n }\n return headDelimiterValueBefore(code);\n }\n\n /**\n * Before delimiter cell value.\n *\n * ```markdown\n * | | a |\n * > | | - |\n * ^\n * ```\n *\n * @type {State}\n */\n function headDelimiterValueBefore(code) {\n // Align: left.\n if (code === 58) {\n sizeB += 1;\n seen = true;\n effects.enter('tableDelimiterMarker');\n effects.consume(code);\n effects.exit('tableDelimiterMarker');\n return headDelimiterLeftAlignmentAfter;\n }\n\n // Align: none.\n if (code === 45) {\n sizeB += 1;\n // To do: seems weird that this *isn’t* left aligned, but that state is used?\n return headDelimiterLeftAlignmentAfter(code);\n }\n if (code === null || markdownLineEnding(code)) {\n return headDelimiterCellAfter(code);\n }\n return headDelimiterNok(code);\n }\n\n /**\n * After delimiter cell left alignment marker.\n *\n * ```markdown\n * | | a |\n * > | | :- |\n * ^\n * ```\n *\n * @type {State}\n */\n function headDelimiterLeftAlignmentAfter(code) {\n if (code === 45) {\n effects.enter('tableDelimiterFiller');\n return headDelimiterFiller(code);\n }\n\n // Anything else is not ok after the left-align colon.\n return headDelimiterNok(code);\n }\n\n /**\n * In delimiter cell filler.\n *\n * ```markdown\n * | | a |\n * > | | - |\n * ^\n * ```\n *\n * @type {State}\n */\n function headDelimiterFiller(code) {\n if (code === 45) {\n effects.consume(code);\n return headDelimiterFiller;\n }\n\n // Align is `center` if it was `left`, `right` otherwise.\n if (code === 58) {\n seen = true;\n effects.exit('tableDelimiterFiller');\n effects.enter('tableDelimiterMarker');\n effects.consume(code);\n effects.exit('tableDelimiterMarker');\n return headDelimiterRightAlignmentAfter;\n }\n effects.exit('tableDelimiterFiller');\n return headDelimiterRightAlignmentAfter(code);\n }\n\n /**\n * After delimiter cell right alignment marker.\n *\n * ```markdown\n * | | a |\n * > | | -: |\n * ^\n * ```\n *\n * @type {State}\n */\n function headDelimiterRightAlignmentAfter(code) {\n if (markdownSpace(code)) {\n return factorySpace(effects, headDelimiterCellAfter, \"whitespace\")(code);\n }\n return headDelimiterCellAfter(code);\n }\n\n /**\n * After delimiter cell.\n *\n * ```markdown\n * | | a |\n * > | | -: |\n * ^\n * ```\n *\n * @type {State}\n */\n function headDelimiterCellAfter(code) {\n if (code === 124) {\n return headDelimiterBefore(code);\n }\n if (code === null || markdownLineEnding(code)) {\n // Exit when:\n // * there was no `:` or `|` at all (it’s a thematic break or setext\n // underline instead)\n // * the header cell count is not the delimiter cell count\n if (!seen || size !== sizeB) {\n return headDelimiterNok(code);\n }\n\n // Note: in markdown-rs`, a reset is needed here.\n effects.exit('tableDelimiterRow');\n effects.exit('tableHead');\n // To do: in `markdown-rs`, resolvers need to be registered manually.\n // effects.register_resolver(ResolveName::GfmTable)\n return ok(code);\n }\n return headDelimiterNok(code);\n }\n\n /**\n * In delimiter row, at a disallowed byte.\n *\n * ```markdown\n * | | a |\n * > | | x |\n * ^\n * ```\n *\n * @type {State}\n */\n function headDelimiterNok(code) {\n // Note: in `markdown-rs`, we need to reset, in `micromark-js` we don‘t.\n return nok(code);\n }\n\n /**\n * Before table body row.\n *\n * ```markdown\n * | | a |\n * | | - |\n * > | | b |\n * ^\n * ```\n *\n * @type {State}\n */\n function bodyRowStart(code) {\n // Note: in `markdown-rs` we need to manually take care of a prefix,\n // but in `micromark-js` that is done for us, so if we’re here, we’re\n // never at whitespace.\n effects.enter('tableRow');\n return bodyRowBreak(code);\n }\n\n /**\n * At break in table body row.\n *\n * ```markdown\n * | | a |\n * | | - |\n * > | | b |\n * ^\n * ^\n * ^\n * ```\n *\n * @type {State}\n */\n function bodyRowBreak(code) {\n if (code === 124) {\n effects.enter('tableCellDivider');\n effects.consume(code);\n effects.exit('tableCellDivider');\n return bodyRowBreak;\n }\n if (code === null || markdownLineEnding(code)) {\n effects.exit('tableRow');\n return ok(code);\n }\n if (markdownSpace(code)) {\n return factorySpace(effects, bodyRowBreak, \"whitespace\")(code);\n }\n\n // Anything else is cell content.\n effects.enter(\"data\");\n return bodyRowData(code);\n }\n\n /**\n * In table body row data.\n *\n * ```markdown\n * | | a |\n * | | - |\n * > | | b |\n * ^\n * ```\n *\n * @type {State}\n */\n function bodyRowData(code) {\n if (code === null || code === 124 || markdownLineEndingOrSpace(code)) {\n effects.exit(\"data\");\n return bodyRowBreak(code);\n }\n effects.consume(code);\n return code === 92 ? bodyRowEscape : bodyRowData;\n }\n\n /**\n * In table body row escape.\n *\n * ```markdown\n * | | a |\n * | | ---- |\n * > | | b\\-c |\n * ^\n * ```\n *\n * @type {State}\n */\n function bodyRowEscape(code) {\n if (code === 92 || code === 124) {\n effects.consume(code);\n return bodyRowData;\n }\n return bodyRowData(code);\n }\n}\n\n/** @type {Resolver} */\n\nfunction resolveTable(events, context) {\n let index = -1;\n let inFirstCellAwaitingPipe = true;\n /** @type {RowKind} */\n let rowKind = 0;\n /** @type {Range} */\n let lastCell = [0, 0, 0, 0];\n /** @type {Range} */\n let cell = [0, 0, 0, 0];\n let afterHeadAwaitingFirstBodyRow = false;\n let lastTableEnd = 0;\n /** @type {Token | undefined} */\n let currentTable;\n /** @type {Token | undefined} */\n let currentBody;\n /** @type {Token | undefined} */\n let currentCell;\n const map = new EditMap();\n while (++index < events.length) {\n const event = events[index];\n const token = event[1];\n if (event[0] === 'enter') {\n // Start of head.\n if (token.type === 'tableHead') {\n afterHeadAwaitingFirstBodyRow = false;\n\n // Inject previous (body end and) table end.\n if (lastTableEnd !== 0) {\n flushTableEnd(map, context, lastTableEnd, currentTable, currentBody);\n currentBody = undefined;\n lastTableEnd = 0;\n }\n\n // Inject table start.\n currentTable = {\n type: 'table',\n start: Object.assign({}, token.start),\n // Note: correct end is set later.\n end: Object.assign({}, token.end)\n };\n map.add(index, 0, [['enter', currentTable, context]]);\n } else if (token.type === 'tableRow' || token.type === 'tableDelimiterRow') {\n inFirstCellAwaitingPipe = true;\n currentCell = undefined;\n lastCell = [0, 0, 0, 0];\n cell = [0, index + 1, 0, 0];\n\n // Inject table body start.\n if (afterHeadAwaitingFirstBodyRow) {\n afterHeadAwaitingFirstBodyRow = false;\n currentBody = {\n type: 'tableBody',\n start: Object.assign({}, token.start),\n // Note: correct end is set later.\n end: Object.assign({}, token.end)\n };\n map.add(index, 0, [['enter', currentBody, context]]);\n }\n rowKind = token.type === 'tableDelimiterRow' ? 2 : currentBody ? 3 : 1;\n }\n // Cell data.\n else if (rowKind && (token.type === \"data\" || token.type === 'tableDelimiterMarker' || token.type === 'tableDelimiterFiller')) {\n inFirstCellAwaitingPipe = false;\n\n // First value in cell.\n if (cell[2] === 0) {\n if (lastCell[1] !== 0) {\n cell[0] = cell[1];\n currentCell = flushCell(map, context, lastCell, rowKind, undefined, currentCell);\n lastCell = [0, 0, 0, 0];\n }\n cell[2] = index;\n }\n } else if (token.type === 'tableCellDivider') {\n if (inFirstCellAwaitingPipe) {\n inFirstCellAwaitingPipe = false;\n } else {\n if (lastCell[1] !== 0) {\n cell[0] = cell[1];\n currentCell = flushCell(map, context, lastCell, rowKind, undefined, currentCell);\n }\n lastCell = cell;\n cell = [lastCell[1], index, 0, 0];\n }\n }\n }\n // Exit events.\n else if (token.type === 'tableHead') {\n afterHeadAwaitingFirstBodyRow = true;\n lastTableEnd = index;\n } else if (token.type === 'tableRow' || token.type === 'tableDelimiterRow') {\n lastTableEnd = index;\n if (lastCell[1] !== 0) {\n cell[0] = cell[1];\n currentCell = flushCell(map, context, lastCell, rowKind, index, currentCell);\n } else if (cell[1] !== 0) {\n currentCell = flushCell(map, context, cell, rowKind, index, currentCell);\n }\n rowKind = 0;\n } else if (rowKind && (token.type === \"data\" || token.type === 'tableDelimiterMarker' || token.type === 'tableDelimiterFiller')) {\n cell[3] = index;\n }\n }\n if (lastTableEnd !== 0) {\n flushTableEnd(map, context, lastTableEnd, currentTable, currentBody);\n }\n map.consume(context.events);\n\n // To do: move this into `html`, when events are exposed there.\n // That’s what `markdown-rs` does.\n // That needs updates to `mdast-util-gfm-table`.\n index = -1;\n while (++index < context.events.length) {\n const event = context.events[index];\n if (event[0] === 'enter' && event[1].type === 'table') {\n event[1]._align = gfmTableAlign(context.events, index);\n }\n }\n return events;\n}\n\n/**\n * Generate a cell.\n *\n * @param {EditMap} map\n * @param {Readonly<TokenizeContext>} context\n * @param {Readonly<Range>} range\n * @param {RowKind} rowKind\n * @param {number | undefined} rowEnd\n * @param {Token | undefined} previousCell\n * @returns {Token | undefined}\n */\n// eslint-disable-next-line max-params\nfunction flushCell(map, context, range, rowKind, rowEnd, previousCell) {\n // `markdown-rs` uses:\n // rowKind === 2 ? 'tableDelimiterCell' : 'tableCell'\n const groupName = rowKind === 1 ? 'tableHeader' : rowKind === 2 ? 'tableDelimiter' : 'tableData';\n // `markdown-rs` uses:\n // rowKind === 2 ? 'tableDelimiterCellValue' : 'tableCellText'\n const valueName = 'tableContent';\n\n // Insert an exit for the previous cell, if there is one.\n //\n // ```markdown\n // > | | aa | bb | cc |\n // ^-- exit\n // ^^^^-- this cell\n // ```\n if (range[0] !== 0) {\n previousCell.end = Object.assign({}, getPoint(context.events, range[0]));\n map.add(range[0], 0, [['exit', previousCell, context]]);\n }\n\n // Insert enter of this cell.\n //\n // ```markdown\n // > | | aa | bb | cc |\n // ^-- enter\n // ^^^^-- this cell\n // ```\n const now = getPoint(context.events, range[1]);\n previousCell = {\n type: groupName,\n start: Object.assign({}, now),\n // Note: correct end is set later.\n end: Object.assign({}, now)\n };\n map.add(range[1], 0, [['enter', previousCell, context]]);\n\n // Insert text start at first data start and end at last data end, and\n // remove events between.\n //\n // ```markdown\n // > | | aa | bb | cc |\n // ^-- enter\n // ^-- exit\n // ^^^^-- this cell\n // ```\n if (range[2] !== 0) {\n const relatedStart = getPoint(context.events, range[2]);\n const relatedEnd = getPoint(context.events, range[3]);\n /** @type {Token} */\n const valueToken = {\n type: valueName,\n start: Object.assign({}, relatedStart),\n end: Object.assign({}, relatedEnd)\n };\n map.add(range[2], 0, [['enter', valueToken, context]]);\n if (rowKind !== 2) {\n // Fix positional info on remaining events\n const start = context.events[range[2]];\n const end = context.events[range[3]];\n start[1].end = Object.assign({}, end[1].end);\n start[1].type = \"chunkText\";\n start[1].contentType = \"text\";\n\n // Remove if needed.\n if (range[3] > range[2] + 1) {\n const a = range[2] + 1;\n const b = range[3] - range[2] - 1;\n map.add(a, b, []);\n }\n }\n map.add(range[3] + 1, 0, [['exit', valueToken, context]]);\n }\n\n // Insert an exit for the last cell, if at the row end.\n //\n // ```markdown\n // > | | aa | bb | cc |\n // ^-- exit\n // ^^^^^^-- this cell (the last one contains two “between” parts)\n // ```\n if (rowEnd !== undefined) {\n previousCell.end = Object.assign({}, getPoint(context.events, rowEnd));\n map.add(rowEnd, 0, [['exit', previousCell, context]]);\n previousCell = undefined;\n }\n return previousCell;\n}\n\n/**\n * Generate table end (and table body end).\n *\n * @param {Readonly<EditMap>} map\n * @param {Readonly<TokenizeContext>} context\n * @param {number} index\n * @param {Token} table\n * @param {Token | undefined} tableBody\n */\n// eslint-disable-next-line max-params\nfunction flushTableEnd(map, context, index, table, tableBody) {\n /** @type {Array<Event>} */\n const exits = [];\n const related = getPoint(context.events, index);\n if (tableBody) {\n tableBody.end = Object.assign({}, related);\n exits.push(['exit', tableBody, context]);\n }\n table.end = Object.assign({}, related);\n exits.push(['exit', table, context]);\n map.add(index + 1, 0, exits);\n}\n\n/**\n * @param {Readonly<Array<Event>>} events\n * @param {number} index\n * @returns {Readonly<Point>}\n */\nfunction getPoint(events, index) {\n const event = events[index];\n const side = event[0] === 'enter' ? 'start' : 'end';\n return event[1][side];\n}","/**\n * @import {Extension, State, TokenizeContext, Tokenizer} from 'micromark-util-types'\n */\n\nimport { factorySpace } from 'micromark-factory-space';\nimport { markdownLineEnding, markdownLineEndingOrSpace, markdownSpace } from 'micromark-util-character';\nconst tasklistCheck = {\n name: 'tasklistCheck',\n tokenize: tokenizeTasklistCheck\n};\n\n/**\n * Create an HTML extension for `micromark` to support GFM task list items\n * syntax.\n *\n * @returns {Extension}\n * Extension for `micromark` that can be passed in `htmlExtensions` to\n * support GFM task list items when serializing to HTML.\n */\nexport function gfmTaskListItem() {\n return {\n text: {\n [91]: tasklistCheck\n }\n };\n}\n\n/**\n * @this {TokenizeContext}\n * @type {Tokenizer}\n */\nfunction tokenizeTasklistCheck(effects, ok, nok) {\n const self = this;\n return open;\n\n /**\n * At start of task list item check.\n *\n * ```markdown\n * > | * [x] y.\n * ^\n * ```\n *\n * @type {State}\n */\n function open(code) {\n if (\n // Exit if there’s stuff before.\n self.previous !== null ||\n // Exit if not in the first content that is the first child of a list\n // item.\n !self._gfmTasklistFirstContentOfListItem) {\n return nok(code);\n }\n effects.enter('taskListCheck');\n effects.enter('taskListCheckMarker');\n effects.consume(code);\n effects.exit('taskListCheckMarker');\n return inside;\n }\n\n /**\n * In task list item check.\n *\n * ```markdown\n * > | * [x] y.\n * ^\n * ```\n *\n * @type {State}\n */\n function inside(code) {\n // Currently we match how GH works in files.\n // To match how GH works in comments, use `markdownSpace` (`[\\t ]`) instead\n // of `markdownLineEndingOrSpace` (`[\\t\\n\\r ]`).\n if (markdownLineEndingOrSpace(code)) {\n effects.enter('taskListCheckValueUnchecked');\n effects.consume(code);\n effects.exit('taskListCheckValueUnchecked');\n return close;\n }\n if (code === 88 || code === 120) {\n effects.enter('taskListCheckValueChecked');\n effects.consume(code);\n effects.exit('taskListCheckValueChecked');\n return close;\n }\n return nok(code);\n }\n\n /**\n * At close of task list item check.\n *\n * ```markdown\n * > | * [x] y.\n * ^\n * ```\n *\n * @type {State}\n */\n function close(code) {\n if (code === 93) {\n effects.enter('taskListCheckMarker');\n effects.consume(code);\n effects.exit('taskListCheckMarker');\n effects.exit('taskListCheck');\n return after;\n }\n return nok(code);\n }\n\n /**\n * @type {State}\n */\n function after(code) {\n // EOL in paragraph means there must be something else after it.\n if (markdownLineEnding(code)) {\n return ok(code);\n }\n\n // Space or tab?\n // Check what comes after.\n if (markdownSpace(code)) {\n return effects.check({\n tokenize: spaceThenNonSpace\n }, ok, nok)(code);\n }\n\n // EOF, or non-whitespace, both wrong.\n return nok(code);\n }\n}\n\n/**\n * @this {TokenizeContext}\n * @type {Tokenizer}\n */\nfunction spaceThenNonSpace(effects, ok, nok) {\n return factorySpace(effects, after, \"whitespace\");\n\n /**\n * After whitespace, after task list item check.\n *\n * ```markdown\n * > | * [x] y.\n * ^\n * ```\n *\n * @type {State}\n */\n function after(code) {\n // EOF means there was nothing, so bad.\n // EOL means there’s content after it, so good.\n // Impossible to have more spaces.\n // Anything else is good.\n return code === null ? nok(code) : ok(code);\n }\n}","/**\n * @typedef {import('micromark-extension-gfm-footnote').HtmlOptions} HtmlOptions\n * @typedef {import('micromark-extension-gfm-strikethrough').Options} Options\n * @typedef {import('micromark-util-types').Extension} Extension\n * @typedef {import('micromark-util-types').HtmlExtension} HtmlExtension\n */\n\nimport {\n combineExtensions,\n combineHtmlExtensions\n} from 'micromark-util-combine-extensions'\nimport {\n gfmAutolinkLiteral,\n gfmAutolinkLiteralHtml\n} from 'micromark-extension-gfm-autolink-literal'\nimport {gfmFootnote, gfmFootnoteHtml} from 'micromark-extension-gfm-footnote'\nimport {\n gfmStrikethrough,\n gfmStrikethroughHtml\n} from 'micromark-extension-gfm-strikethrough'\nimport {gfmTable, gfmTableHtml} from 'micromark-extension-gfm-table'\nimport {gfmTagfilterHtml} from 'micromark-extension-gfm-tagfilter'\nimport {\n gfmTaskListItem,\n gfmTaskListItemHtml\n} from 'micromark-extension-gfm-task-list-item'\n\n/**\n * Create an extension for `micromark` to enable GFM syntax.\n *\n * @param {Options | null | undefined} [options]\n * Configuration (optional).\n *\n * Passed to `micromark-extens-gfm-strikethrough`.\n * @returns {Extension}\n * Extension for `micromark` that can be passed in `extensions` to enable GFM\n * syntax.\n */\nexport function gfm(options) {\n return combineExtensions([\n gfmAutolinkLiteral(),\n gfmFootnote(),\n gfmStrikethrough(options),\n gfmTable(),\n gfmTaskListItem()\n ])\n}\n\n/**\n * Create an extension for `micromark` to support GFM when serializing to HTML.\n *\n * @param {HtmlOptions | null | undefined} [options]\n * Configuration (optional).\n *\n * Passed to `micromark-extens-gfm-footnote`.\n * @returns {HtmlExtension}\n * Extension for `micromark` that can be passed in `htmlExtensions` to\n * support GFM when serializing to HTML.\n */\nexport function gfmHtml(options) {\n return combineHtmlExtensions([\n gfmAutolinkLiteralHtml(),\n gfmFootnoteHtml(options),\n gfmStrikethroughHtml(),\n gfmTableHtml(),\n gfmTagfilterHtml(),\n gfmTaskListItemHtml()\n ])\n}\n","/**\n * @import {Root} from 'mdast'\n * @import {Options} from 'remark-gfm'\n * @import {} from 'remark-parse'\n * @import {} from 'remark-stringify'\n * @import {Processor} from 'unified'\n */\n\nimport {gfmFromMarkdown, gfmToMarkdown} from 'mdast-util-gfm'\nimport {gfm} from 'micromark-extension-gfm'\n\n/** @type {Options} */\nconst emptyOptions = {}\n\n/**\n * Add support GFM (autolink literals, footnotes, strikethrough, tables,\n * tasklists).\n *\n * @param {Options | null | undefined} [options]\n * Configuration (optional).\n * @returns {undefined}\n * Nothing.\n */\nexport default function remarkGfm(options) {\n // @ts-expect-error: TS is wrong about `this`.\n // eslint-disable-next-line unicorn/no-this-assignment\n const self = /** @type {Processor<Root>} */ (this)\n const settings = options || emptyOptions\n const data = self.data()\n\n const micromarkExtensions =\n data.micromarkExtensions || (data.micromarkExtensions = [])\n const fromMarkdownExtensions =\n data.fromMarkdownExtensions || (data.fromMarkdownExtensions = [])\n const toMarkdownExtensions =\n data.toMarkdownExtensions || (data.toMarkdownExtensions = [])\n\n micromarkExtensions.push(gfm(settings))\n fromMarkdownExtensions.push(gfmFromMarkdown())\n toMarkdownExtensions.push(gfmToMarkdown(settings))\n}\n","export function cn(...classes: Array<string | false | null | undefined>): string {\n return classes.filter(Boolean).join(' ');\n}\n\n","'use client';\n\nimport '@assistant-ui/react-markdown/styles/dot.css';\n\nimport {\n type CodeHeaderProps,\n MarkdownTextPrimitive,\n unstable_memoizeMarkdownComponents as memoizeMarkdownComponents,\n useIsMarkdownCodeBlock,\n} from '@assistant-ui/react-markdown';\nimport remarkGfm from 'remark-gfm';\nimport { type FC, memo, useState } from 'react';\nimport { CheckIcon, CopyIcon } from 'lucide-react';\nimport { cn } from '../utils/cn';\n\ninterface MarkdownTextProps {\n content: string;\n}\n\nconst MarkdownTextImpl: FC<MarkdownTextProps> = ({ content }) => {\n return (\n <MarkdownTextPrimitive\n remarkPlugins={[remarkGfm]}\n className=\"cuadra-aui-md\"\n components={defaultComponents}\n {...({ children: content } as { children: string })}\n />\n );\n};\n\nexport const MarkdownText = memo(MarkdownTextImpl);\n\nconst CodeHeader: FC<CodeHeaderProps> = ({ language, code }) => {\n const { isCopied, copyToClipboard } = useCopyToClipboard();\n const onCopy = () => {\n if (!code || isCopied) return;\n copyToClipboard(code);\n };\n\n return (\n <div className=\"cuadra-flex cuadra-items-center cuadra-justify-between cuadra-gap-4 cuadra-mt-4 cuadra-rounded-t-lg cuadra-bg-muted/50 cuadra-border-b cuadra-border-border cuadra-px-4 cuadra-py-2 cuadra-text-sm cuadra-font-normal cuadra-text-foreground cuadra-font-brand\">\n <span className=\"cuadra-lowercase [&>span]:cuadra-text-xs cuadra-font-brand\">{language}</span>\n <button\n onClick={onCopy}\n className=\"cuadra-p-1 cuadra-rounded hover:cuadra-bg-muted cuadra-transition-colors\"\n aria-label=\"Copy code\"\n >\n {!isCopied && <CopyIcon className=\"cuadra-h-4 cuadra-w-4\" />}\n {isCopied && <CheckIcon className=\"cuadra-h-4 cuadra-w-4\" />}\n </button>\n </div>\n );\n};\n\nconst useCopyToClipboard = ({\n copiedDuration = 3000,\n}: {\n copiedDuration?: number;\n} = {}) => {\n const [isCopied, setIsCopied] = useState<boolean>(false);\n\n const copyToClipboard = (value: string) => {\n if (!value) return;\n\n navigator.clipboard.writeText(value).then(() => {\n setIsCopied(true);\n setTimeout(() => setIsCopied(false), copiedDuration);\n });\n };\n\n return { isCopied, copyToClipboard };\n};\n\nconst defaultComponents = memoizeMarkdownComponents({\n h1: ({ className, ...props }) => (\n <h1\n className={cn('cuadra-mb-6 cuadra-scroll-m-20 cuadra-text-2xl cuadra-font-normal cuadra-tracking-tight last:cuadra-mb-0 font-brand', className)}\n {...props}\n />\n ),\n h2: ({ className, ...props }) => (\n <h2\n className={cn(\n 'cuadra-mb-4 cuadra-mt-6 cuadra-scroll-m-20 cuadra-text-xl cuadra-font-normal cuadra-tracking-tight first:cuadra-mt-0 last:cuadra-mb-0 font-brand',\n className,\n )}\n {...props}\n />\n ),\n h3: ({ className, ...props }) => (\n <h3\n className={cn(\n 'cuadra-mb-3 cuadra-mt-5 cuadra-scroll-m-20 cuadra-text-lg cuadra-font-normal cuadra-tracking-tight first:cuadra-mt-0 last:cuadra-mb-0 font-brand',\n className,\n )}\n {...props}\n />\n ),\n h4: ({ className, ...props }) => (\n <h4\n className={cn(\n 'cuadra-mb-4 cuadra-mt-6 cuadra-scroll-m-20 cuadra-text-xl cuadra-font-normal cuadra-tracking-tight first:cuadra-mt-0 last:cuadra-mb-0 font-brand',\n className,\n )}\n {...props}\n />\n ),\n h5: ({ className, ...props }) => (\n <h5 className={cn('cuadra-my-4 cuadra-text-lg cuadra-font-normal first:cuadra-mt-0 last:cuadra-mb-0 font-brand', className)} {...props} />\n ),\n h6: ({ className, ...props }) => (\n <h6 className={cn('cuadra-my-4 cuadra-font-normal first:cuadra-mb-0 font-brand', className)} {...props} />\n ),\n p: ({ className, ...props }) => (\n <p className={cn('cuadra-mb-5 cuadra-mt-5 cuadra-leading-7 first:cuadra-mt-0 last:cuadra-mb-0 font-brand', className)} {...props} />\n ),\n a: ({ className, ...props }) => (\n <a\n className={cn('cuadra-text-primary cuadra-font-medium cuadra-underline cuadra-underline-offset-4 font-brand', className)}\n {...props}\n />\n ),\n blockquote: ({ className, ...props }) => (\n <blockquote className={cn('cuadra-border-l-2 cuadra-pl-6 cuadra-italic font-brand', className)} {...props} />\n ),\n ul: ({ className, ...props }) => (\n <ul className={cn('cuadra-my-5 cuadra-ml-6 cuadra-list-disc [&>li]:cuadra-mt-2 font-brand', className)} {...props} />\n ),\n ol: ({ className, ...props }) => (\n <ol className={cn('cuadra-my-5 cuadra-ml-6 cuadra-list-decimal [&>li]:cuadra-mt-2 font-brand', className)} {...props} />\n ),\n hr: ({ className, ...props }) => <hr className={cn('cuadra-my-5 cuadra-border-b', className)} {...props} />,\n table: ({ className, ...props }) => (\n <table\n className={cn('cuadra-my-5 cuadra-w-full cuadra-border-separate cuadra-border-spacing-0 cuadra-overflow-y-auto font-brand', className)}\n {...props}\n />\n ),\n th: ({ className, ...props }) => (\n <th\n className={cn(\n 'cuadra-bg-muted cuadra-px-4 cuadra-py-2 cuadra-text-left cuadra-font-normal first:cuadra-rounded-tl-lg last:cuadra-rounded-tr-lg [&[align=center]]:cuadra-text-center [&[align=right]]:cuadra-text-right font-brand',\n className,\n )}\n {...props}\n />\n ),\n td: ({ className, ...props }) => (\n <td\n className={cn(\n 'cuadra-border-b cuadra-border-l cuadra-px-4 cuadra-py-2 cuadra-text-left last:cuadra-border-r [&[align=center]]:cuadra-text-center [&[align=right]]:cuadra-text-right font-brand',\n className,\n )}\n {...props}\n />\n ),\n tr: ({ className, ...props }) => (\n <tr\n className={cn(\n 'cuadra-m-0 cuadra-border-b cuadra-p-0 first:cuadra-border-t [&:last-child>td:first-child]:cuadra-rounded-bl-lg [&:last-child>td:last-child]:cuadra-rounded-br-lg',\n className,\n )}\n {...props}\n />\n ),\n sup: ({ className, ...props }) => (\n <sup className={cn('[&>a]:cuadra-text-xs [&>a]:cuadra-no-underline font-brand', className)} {...props} />\n ),\n pre: ({ className, ...props }) => (\n <pre\n className={cn(\n 'cuadra-overflow-x-auto cuadra-rounded-b-lg !cuadra-rounded-t-none cuadra-bg-muted cuadra-p-4 cuadra-text-foreground font-brand',\n className,\n )}\n {...props}\n />\n ),\n code: function Code({ className, ...props }) {\n const isCodeBlock = useIsMarkdownCodeBlock();\n return (\n <code\n className={cn(!isCodeBlock && 'cuadra-bg-muted cuadra-rounded cuadra-border cuadra-font-normal font-brand', className)}\n {...props}\n />\n );\n },\n CodeHeader,\n});\n","import { useEffect, useState } from 'react';\n\nconst STEPS = [\n 'Sending question…',\n 'Understanding your need…',\n 'Scanning data…',\n 'Comparing results…',\n 'Composing answer…',\n];\n\nexport function FakeReasoningLoader({ active }: { active: boolean }) {\n const [index, setIndex] = useState(0);\n\n useEffect(() => {\n if (!active) {\n setIndex(0);\n return;\n }\n\n const id = window.setInterval(() => {\n setIndex((prev) => {\n // Once we reach the last step, stay there and stop advancing\n if (prev >= STEPS.length - 1) {\n window.clearInterval(id);\n return prev;\n }\n return prev + 1;\n });\n }, 2500);\n\n return () => window.clearInterval(id);\n }, [active]);\n\n if (!active) return null;\n\n return <span className=\"cuadra-text-xs cuadra-text-muted-foreground cuadra-font-brand\">Thinking… {STEPS[index]}</span>;\n}\n\n","import { ComposerPrimitive, MessagePrimitive, ThreadPrimitive, useAssistantApi, useThreadRuntime } from '@assistant-ui/react';\nimport { ArrowUpIcon, Loader2 } from 'lucide-react';\nimport { useEffect, useState } from 'react';\nimport { MarkdownText } from './MarkdownText';\nimport { FakeReasoningLoader } from './FakeReasoningLoader';\nimport '@assistant-ui/react-markdown/styles/dot.css';\n\nexport interface SimpleThreadProps {\n /** Welcome screen title */\n welcomeTitle?: string;\n /** Welcome screen subtitle */\n welcomeSubtitle?: string;\n /** Extra top padding for thread viewport (e.g., '1rem', '2rem') */\n extraTopPadding?: string;\n /** Suggestions to show in welcome screen */\n suggestions?: Array<{\n /** Suggestion prompt text */\n prompt: string;\n }>;\n /** Placeholder text for the input field */\n inputPlaceholder?: string;\n}\n\n/**\n * Simple Thread component wrapper\n * Provides a basic chat interface using assistant-ui primitives\n */\nexport function SimpleThread({\n welcomeTitle = 'Hi, how can I help you today?',\n welcomeSubtitle = 'Start exploring our platform and discover what you can build.',\n extraTopPadding,\n suggestions,\n inputPlaceholder = 'Type your message...',\n}: SimpleThreadProps = {}) {\n const thread = useThreadRuntime();\n const [isLoadingMessages, setIsLoadingMessages] = useState(false);\n const [currentThreadId, setCurrentThreadId] = useState<string | null>(null);\n const [hasAssistantContent, setHasAssistantContent] = useState(false);\n\n // Track thread changes and loading state by subscribing to store changes\n useEffect(() => {\n if (!thread) {\n setIsLoadingMessages(false);\n return;\n }\n\n try {\n // Access runtime store to track loading state\n interface RuntimeStore {\n getState?: () => {\n threadId?: string;\n messages?: unknown[];\n isLoadingHistory?: boolean;\n isRunning?: boolean;\n };\n subscribe?: (callback: (state: { threadId?: string; messages?: unknown[]; isLoadingHistory?: boolean; isRunning?: boolean }) => void) => () => void;\n }\n const runtimeStore = (thread as { store?: RuntimeStore })?.store;\n if (!runtimeStore) {\n setIsLoadingMessages(false);\n return;\n }\n\n // Subscribe to store changes\n const unsubscribe = runtimeStore.subscribe?.((state) => {\n const threadId = state?.threadId;\n const messages = (state?.messages || []) as Array<{\n role?: string;\n content?: Array<{ type?: string; text?: string }> | string;\n }>;\n const isLoadingHistory = state?.isLoadingHistory || false;\n const messageCount = messages.length;\n\n // Check if thread changed\n if (threadId && threadId !== currentThreadId) {\n setCurrentThreadId(threadId);\n }\n\n // Only show loading if:\n // 1. We're actively loading history\n // 2. We have no messages yet\n const shouldShowLoading = isLoadingHistory && messageCount === 0;\n setIsLoadingMessages(shouldShowLoading);\n\n // Detect when assistant has started sending visible content\n const hasAssistantWithText = messages.some(\n (m) =>\n m.role === 'assistant' &&\n !!m.content &&\n (Array.isArray(m.content)\n ? m.content.some((c) => (typeof c === 'object' && c?.text ? c.text.trim().length > 0 : false))\n : (typeof m.content === 'string' ? m.content.trim().length > 0 : false)),\n );\n setHasAssistantContent(hasAssistantWithText);\n });\n\n // Initial check\n const state = runtimeStore.getState?.();\n if (state) {\n const threadId = state?.threadId;\n const messages = (state?.messages || []) as Array<{\n role?: string;\n content?: Array<{ type?: string; text?: string }> | string;\n }>;\n const isLoadingHistory = state?.isLoadingHistory || false;\n const messageCount = messages.length;\n\n if (threadId && threadId !== currentThreadId) {\n setCurrentThreadId(threadId);\n }\n\n const shouldShowLoading = isLoadingHistory && messageCount === 0;\n setIsLoadingMessages(shouldShowLoading);\n\n // Detect when assistant has started sending visible content\n const hasAssistantWithText = messages.some(\n (m) =>\n m.role === 'assistant' &&\n !!m.content &&\n (Array.isArray(m.content)\n ? m.content.some((c) => (typeof c === 'object' && c?.text ? c.text.trim().length > 0 : false))\n : (typeof m.content === 'string' ? m.content.trim().length > 0 : false)),\n );\n setHasAssistantContent(hasAssistantWithText);\n }\n\n return () => {\n if (unsubscribe) {\n unsubscribe();\n }\n };\n } catch {\n setIsLoadingMessages(false);\n }\n }, [thread, currentThreadId]);\n\n return (\n <ThreadPrimitive.Root className=\"cuadra-bg-inherit cuadra-flex cuadra-flex-col cuadra-w-full cuadra-h-full\">\n <ThreadPrimitive.Viewport \n className=\"cuadra-w-full cuadra-bg-inherit cuadra-px-4 cuadra-flex-1 cuadra-min-h-0 cuadra-overflow-y-auto cuadra-relative scrollbar-thin cuadra-pt-4\"\n style={extraTopPadding ? { paddingTop: extraTopPadding } : undefined}\n >\n {isLoadingMessages ? (\n <div className=\"cuadra-absolute cuadra-inset-0 cuadra-flex cuadra-items-center cuadra-justify-center\">\n <div className=\"cuadra-flex cuadra-flex-col cuadra-items-center cuadra-gap-2\">\n <Loader2 className=\"cuadra-h-6 cuadra-w-6 cuadra-animate-spin cuadra-text-muted-foreground\" />\n <p className=\"cuadra-text-sm cuadra-text-muted-foreground font-brand\">Loading messages...</p>\n </div>\n </div>\n ) : (\n <>\n <ThreadPrimitive.Empty>\n <WelcomeScreen \n title={welcomeTitle}\n subtitle={welcomeSubtitle}\n suggestions={suggestions}\n />\n </ThreadPrimitive.Empty>\n <ThreadPrimitive.Messages\n components={{\n UserMessage: UserMessage,\n AssistantMessage: AssistantMessage,\n }}\n />\n <ThreadPrimitive.If running>\n {!hasAssistantContent && (\n <div className=\"cuadra-mt-2 cuadra-max-w-2xl\">\n <FakeReasoningLoader active />\n </div>\n )}\n </ThreadPrimitive.If>\n </>\n )}\n </ThreadPrimitive.Viewport>\n <div className=\"cuadra-w-full cuadra-mt-3 cuadra-border-t cuadra-border-border cuadra-pt-4\">\n <ComposerPrimitive.Root className=\"cuadra-relative !cuadra-relative cuadra-flex-1 cuadra-w-full\">\n <ComposerPrimitive.Input\n asChild\n >\n <textarea\n rows={3}\n placeholder={inputPlaceholder}\n className=\"cuadra-flex cuadra-min-h-[80px] cuadra-w-full cuadra-rounded-md cuadra-border cuadra-border-border cuadra-bg-background cuadra-px-3 cuadra-py-2 cuadra-text-base placeholder:cuadra-text-muted-foreground focus-visible:cuadra-outline-none disabled:cuadra-cursor-not-allowed disabled:cuadra-opacity-50 cuadra-resize-none cuadra-pr-10 font-brand\"\n style={{ paddingRight: '2.5rem', fontSize: '1rem', borderWidth: '1px' }}\n />\n </ComposerPrimitive.Input>\n <ComposerPrimitive.Send asChild>\n <button\n className=\"!cuadra-absolute !cuadra-bottom-2 !cuadra-right-2 cuadra-size-8 cuadra-rounded-md cuadra-shadow-sm hover:cuadra-opacity-90 disabled:cuadra-opacity-50 disabled:cuadra-cursor-not-allowed cuadra-flex cuadra-items-center cuadra-justify-center\"\n style={{ \n position: 'absolute', \n bottom: '0.5rem', \n right: '0.5rem',\n backgroundColor: 'var(--primary)',\n color: 'hsl(var(--primary-foreground))'\n }}\n aria-label=\"Send message\"\n type=\"button\"\n >\n <ArrowUpIcon className=\"cuadra-h-4 cuadra-w-4\" />\n </button>\n </ComposerPrimitive.Send>\n </ComposerPrimitive.Root>\n </div>\n </ThreadPrimitive.Root>\n );\n}\n\ninterface WelcomeScreenProps {\n title: string;\n subtitle: string;\n suggestions?: Array<{\n prompt: string;\n }>;\n}\n\n/**\n * Welcome screen component\n */\nfunction WelcomeScreen({ title, subtitle, suggestions }: WelcomeScreenProps) {\n const api = useAssistantApi();\n \n const handleSuggestionClick = async (prompt: string) => {\n try {\n // Use composer API to set text and send (same as normal send button)\n api.composer().setText(prompt);\n \n // Small delay to ensure text is set\n await new Promise(resolve => setTimeout(resolve, 10));\n \n api.composer().send();\n } catch (error) {\n // Silently handle errors - user can retry\n void error;\n }\n };\n\n return (\n <div className=\"cuadra-flex cuadra-flex-col cuadra-items-center cuadra-h-full cuadra-py-12 cuadra-px-4 cuadra-overflow-y-auto scrollbar-hide\">\n <div className=\"cuadra-text-center cuadra-max-w-3xl cuadra-w-full cuadra-flex cuadra-flex-col cuadra-items-center cuadra-justify-center cuadra-min-h-full\">\n <div className=\"cuadra-flex cuadra-flex-col cuadra-items-center cuadra-justify-center cuadra-mb-8\">\n <h2 className=\"cuadra-text-lg cuadra-font-normal cuadra-text-foreground cuadra-mb-2 font-brand\">\n {title}\n </h2>\n <p className=\"cuadra-text-muted-foreground font-brand\">\n {subtitle}\n </p>\n </div>\n {suggestions && suggestions.length > 0 && (\n <div className=\"cuadra-grid cuadra-grid-cols-2 cuadra-gap-2 cuadra-pb-4 cuadra-w-full cuadra-max-w-2xl\">\n {suggestions.map((suggestion, index) => (\n <button\n key={`suggestion-${index}`}\n type=\"button\"\n onClick={() => handleSuggestionClick(suggestion.prompt)}\n className=\"cuadra-w-full cuadra-text-center cuadra-px-4 cuadra-py-3 cuadra-rounded-lg cuadra-border cuadra-border-border cuadra-bg-background cuadra-text-sm font-brand cuadra-cursor-pointer focus:cuadra-outline-none focus:cuadra-ring-0\"\n style={{ borderWidth: '1px' }}\n >\n {suggestion.prompt}\n </button>\n ))}\n </div>\n )}\n </div>\n </div>\n );\n}\n\n/**\n * User message component\n */\nfunction UserMessage() {\n return (\n <MessagePrimitive.Root className=\"cuadra-grid cuadra-w-full cuadra-auto-rows-auto cuadra-grid-cols-[minmax(72px,1fr)_auto] cuadra-gap-y-2 cuadra-py-3 [&:where(>*)]:cuadra-col-start-2\">\n <div \n className=\"cuadra-bg-muted cuadra-text-foreground cuadra-col-start-2 cuadra-row-start-2 cuadra-max-w-[calc(42rem*0.8)] cuadra-break-words cuadra-rounded-3xl cuadra-border cuadra-border-border cuadra-px-5 cuadra-py-2.5 font-brand\"\n style={{ \n maxWidth: 'calc(42rem * 0.8)',\n borderRadius: '1.5rem',\n backgroundColor: 'hsl(var(--muted))',\n color: 'hsl(var(--foreground))',\n paddingLeft: '1.25rem',\n paddingRight: '1.25rem',\n paddingTop: '0.625rem',\n paddingBottom: '0.625rem',\n wordBreak: 'break-word',\n borderWidth: '1px'\n }}\n >\n <MessagePrimitive.Parts\n components={{\n Text: ({ text }) => <MarkdownText content={text || ''} />,\n }}\n />\n </div>\n </MessagePrimitive.Root>\n );\n}\n\n/**\n * Assistant message component\n */\nfunction AssistantMessage() {\n return (\n <MessagePrimitive.Root className=\"cuadra-relative cuadra-grid cuadra-w-full cuadra-grid-cols-[auto_auto_1fr] cuadra-grid-rows-[auto_1fr] cuadra-py-3\">\n <div \n className=\"cuadra-text-foreground cuadra-col-span-2 cuadra-col-start-2 cuadra-row-start-1 cuadra-my-1.5 cuadra-max-w-[90%] cuadra-break-words cuadra-leading-7 font-brand\"\n style={{ \n maxWidth: '90%',\n marginTop: '0.375rem',\n marginBottom: '0.375rem'\n }}\n >\n <MessagePrimitive.Parts\n components={{\n Text: ({ text }) => <MarkdownText content={text || ''} />,\n }}\n />\n </div>\n </MessagePrimitive.Root>\n );\n}\n","import { ThreadListItemPrimitive, ThreadListPrimitive, useThread, useThreadListItem } from '@assistant-ui/react';\nimport { MoreVertical, Plus } from 'lucide-react';\nimport { useEffect, useState } from 'react';\n\n/**\n * ThreadListItem component with rename and delete functionality\n */\nfunction ThreadListItem({ onThreadSelect }: { onThreadSelect?: () => void }) {\n const threadItem = useThreadListItem();\n const currentThread = useThread((state) => state.threadId);\n const [hoveredThreadId, setHoveredThreadId] = useState<string | null>(null);\n const isActive = threadItem?.id === currentThread;\n const isHovered = hoveredThreadId === threadItem?.id;\n\n // Per-thread state for rename\n const [isRenaming, setIsRenaming] = useState(false);\n const [nextTitle, setNextTitle] = useState(threadItem?.title || '');\n const [isMenuOpen, setIsMenuOpen] = useState(false);\n const [busy, setBusy] = useState(false);\n\n const handleRename = async () => {\n if (!threadItem?.remoteId || !nextTitle || nextTitle === threadItem.title) {\n setIsRenaming(false);\n return;\n }\n \n try {\n setBusy(true);\n const adapter = (window as Window & { __cuadraThreadListAdapter?: { rename?: (remoteId: string, newTitle: string) => Promise<void> } }).__cuadraThreadListAdapter;\n if (adapter && typeof adapter.rename === 'function') {\n await adapter.rename(threadItem.remoteId, nextTitle);\n }\n setIsRenaming(false);\n setIsMenuOpen(false);\n } catch {\n // Silently fail - error is already handled by the adapter\n setIsRenaming(false);\n setIsMenuOpen(false);\n } finally {\n setBusy(false);\n }\n };\n\n // Update nextTitle when threadItem.title changes (but not when renaming)\n useEffect(() => {\n if (threadItem?.title && !isRenaming) {\n setNextTitle(threadItem.title);\n }\n }, [threadItem?.title, isRenaming]);\n\n if (!threadItem) {\n return null;\n }\n\n return (\n <ThreadListItemPrimitive.Root\n className={`group cuadra-relative cuadra-flex cuadra-items-center cuadra-gap-3 cuadra-rounded-lg cuadra-transition-colors cuadra-cursor-pointer cuadra-border cuadra-mb-2 ${\n isActive\n ? 'cuadra-bg-muted cuadra-border-border'\n : 'cuadra-border-transparent hover:cuadra-bg-muted hover:cuadra-border-border'\n }`}\n style={{ marginBottom: '0.5rem' }}\n onMouseEnter={() => setHoveredThreadId(threadItem.id)}\n onMouseLeave={() => setHoveredThreadId(null)}\n >\n <ThreadListItemPrimitive.Trigger \n className=\"cuadra-p-3 cuadra-flex-1 cuadra-flex cuadra-items-center cuadra-justify-between cuadra-w-full cuadra-min-w-0 cuadra-cursor-pointer\"\n onClick={() => onThreadSelect?.()}\n >\n <div className=\"cuadra-flex cuadra-flex-col cuadra-min-w-0 cuadra-flex-1 cuadra-items-start cuadra-text-left\">\n {isRenaming ? (\n <input\n className=\"cuadra-flex cuadra-w-full cuadra-rounded-md cuadra-border cuadra-border-input cuadra-bg-background cuadra-px-3 cuadra-py-2 cuadra-text-sm placeholder:cuadra-text-muted-foreground focus-visible:cuadra-outline-none disabled:cuadra-cursor-not-allowed disabled:cuadra-opacity-50 font-brand\"\n value={nextTitle}\n onChange={(e) => setNextTitle(e.target.value)}\n onKeyDown={(e) => {\n if (e.key === 'Enter') {\n void handleRename();\n }\n if (e.key === 'Escape') {\n setIsRenaming(false);\n setNextTitle(threadItem.title || '');\n }\n }}\n disabled={busy}\n autoFocus\n onClick={(e) => e.stopPropagation()}\n />\n ) : (\n <>\n <span className=\"cuadra-text-sm cuadra-font-normal cuadra-text-foreground cuadra-truncate font-brand\">\n {(threadItem.title?.length || 0) > 60 \n ? `${threadItem.title?.slice(0, 60)}…` \n : threadItem.title || 'Chat'}\n </span>\n {((threadItem as unknown) as { updatedAt?: Date }).updatedAt && (\n <span className=\"cuadra-text-xs cuadra-text-muted-foreground cuadra-mt-1 font-brand\">\n {new Date(((threadItem as unknown) as { updatedAt: Date }).updatedAt).toLocaleDateString()}\n </span>\n )}\n </>\n )}\n </div>\n {/* Always reserve space for menu button to prevent layout shift */}\n <div className=\"cuadra-ml-2 cuadra-flex-shrink-0 cuadra-w-6 cuadra-h-6 cuadra-flex cuadra-items-center cuadra-justify-center\">\n {(isHovered || isActive || isMenuOpen) && (\n <div className=\"cuadra-relative\">\n <button\n className=\"cuadra-p-1 cuadra-rounded hover:cuadra-bg-background/50 cuadra-transition-colors\"\n onClick={(e) => {\n e.stopPropagation();\n setIsMenuOpen(!isMenuOpen);\n }}\n aria-label=\"Thread options\"\n >\n <MoreVertical className=\"cuadra-h-4 cuadra-w-4 cuadra-text-muted-foreground\" />\n </button>\n {isMenuOpen && (\n <>\n <div \n className=\"cuadra-fixed cuadra-inset-0 cuadra-z-40\" \n onClick={() => setIsMenuOpen(false)}\n />\n <div className=\"cuadra-absolute cuadra-right-0 cuadra-top-8 cuadra-z-50 cuadra-bg-background cuadra-border cuadra-border-border cuadra-rounded-lg cuadra-shadow-lg cuadra-min-w-[120px] cuadra-overflow-hidden\">\n {isRenaming ? (\n <button\n className=\"cuadra-w-full cuadra-px-3 cuadra-py-2 cuadra-text-sm cuadra-text-left hover:cuadra-bg-muted cuadra-transition-colors font-brand\"\n onClick={(e) => {\n e.stopPropagation();\n void handleRename();\n }}\n disabled={busy}\n >\n Save\n </button>\n ) : (\n <>\n <button\n className=\"cuadra-w-full cuadra-px-3 cuadra-py-2 cuadra-text-sm cuadra-text-left hover:cuadra-bg-muted cuadra-transition-colors font-brand\"\n onClick={(e) => {\n e.stopPropagation();\n setIsRenaming(true);\n setNextTitle(threadItem.title || '');\n setIsMenuOpen(false);\n }}\n >\n Rename\n </button>\n <div className=\"cuadra-border-t cuadra-border-border\" />\n <ThreadListItemPrimitive.Delete asChild>\n <button\n className=\"cuadra-w-full cuadra-px-3 cuadra-py-2 cuadra-text-sm cuadra-text-left cuadra-text-destructive hover:cuadra-bg-muted cuadra-transition-colors font-brand\"\n onClick={(e) => {\n e.stopPropagation();\n setIsMenuOpen(false);\n }}\n >\n Delete\n </button>\n </ThreadListItemPrimitive.Delete>\n </>\n )}\n </div>\n </>\n )}\n </div>\n )}\n </div>\n </ThreadListItemPrimitive.Trigger>\n </ThreadListItemPrimitive.Root>\n );\n}\n\n/**\n * Simple ThreadList component wrapper\n * Provides a basic thread list interface using assistant-ui primitives\n */\nexport function SimpleThreadList({ onThreadSelect }: { onThreadSelect?: () => void }) {\n\n return (\n <ThreadListPrimitive.Root className=\"!cuadra-border-r cuadra-border-border cuadra-flex cuadra-flex-col cuadra-bg-background cuadra-transition-all cuadra-duration-300 cuadra-ease-in-out cuadra-h-full cuadra-w-80\" style={{ borderRightWidth: '1px' }}>\n <div className=\"cuadra-border-b cuadra-border-border cuadra-flex cuadra-items-center cuadra-justify-between cuadra-transition-all cuadra-duration-300 cuadra-h-16 cuadra-px-4\">\n <h3 className=\"cuadra-text-sm cuadra-font-normal cuadra-text-foreground cuadra-text-nowrap font-brand\">Chat History</h3>\n </div>\n\n <div className=\"cuadra-flex-1 cuadra-overflow-y-auto cuadra-p-2 scrollbar-thin\">\n <ThreadListPrimitive.New\n className=\"group cuadra-relative cuadra-flex cuadra-items-center cuadra-gap-3 cuadra-p-3 cuadra-rounded-lg cuadra-cursor-pointer cuadra-transition-colors cuadra-border cuadra-border-transparent hover:cuadra-bg-muted hover:cuadra-border-border\"\n onClick={() => onThreadSelect?.()}\n >\n <div className=\"cuadra-flex-1 cuadra-min-w-0\">\n <div className=\"cuadra-flex cuadra-items-center cuadra-gap-2\">\n <Plus className=\"cuadra-h-4 cuadra-w-4 cuadra-text-muted-foreground\" />\n <h4 className=\"cuadra-text-sm cuadra-font-normal cuadra-text-foreground font-brand\">New Chat</h4>\n </div>\n </div>\n </ThreadListPrimitive.New>\n\n <div className=\"cuadra-my-2 cuadra-border-t cuadra-border-border\"></div>\n\n <ThreadListPrimitive.Items\n components={{\n ThreadListItem: (props) => <ThreadListItem {...props} onThreadSelect={onThreadSelect} />,\n }}\n />\n </div>\n </ThreadListPrimitive.Root>\n );\n}\n","import React from 'react';\n\nconst pulseKeyframes = `\n @keyframes rotate {\n 100% { transform: rotate(1turn); }\n }\n`;\n\ninterface TexturedCardProps {\n children: React.ReactNode;\n className?: string;\n paddingX?: string;\n paddingY?: string;\n borderSizePx?: number;\n style?: React.CSSProperties;\n contentStyle?: React.CSSProperties;\n rotating?: boolean;\n}\n\nexport const TexturedCard: React.FC<TexturedCardProps> = ({\n children,\n className = '',\n paddingX = 'px-0',\n paddingY = 'py-0',\n borderSizePx = 4,\n style,\n contentStyle,\n rotating = false,\n}) => {\n return (\n <>\n <style>{pulseKeyframes}</style>\n <div\n className={`cuadra-relative cuadra-bg-background md:cuadra-rounded-xl cuadra-overflow-hidden ${className}`}\n style={{ padding: borderSizePx, ...style }}\n >\n <div\n className=\"cuadra-absolute md:cuadra-rounded-xl\"\n style={\n rotating\n ? {\n left: '-100%',\n top: '-100%',\n width: '300%',\n height: '300%',\n backgroundImage: 'conic-gradient(#F4633A, #FF7A4D, #FF8C5C, #F4633A, #FF7A4D, #FF8C5C)',\n backgroundRepeat: 'no-repeat',\n backgroundSize: 'cover',\n backgroundPosition: 'center',\n animation: 'rotate 4s linear infinite',\n }\n : {\n backgroundImage: 'linear-gradient(to right, #F4633A, #FF7A4D, #FF8C5C, #F4633A)',\n backgroundSize: 'cover',\n backgroundPosition: 'center',\n backgroundRepeat: 'no-repeat',\n top: '0',\n left: '0',\n width: '100%',\n height: '100%',\n }\n }\n />\n <div\n className={`cuadra-relative cuadra-bg-background cuadra-h-full cuadra-z-10 cuadra-flex cuadra-flex-col cuadra-overflow-hidden ${paddingX} ${paddingY}`}\n style={{\n borderRadius: 'calc(0.75rem - 4px)',\n ...contentStyle,\n }}\n >\n {children}\n </div>\n </div>\n </>\n );\n};\n\n","import React, { useEffect, useState } from 'react';\nimport { Contrast } from 'lucide-react';\n\ninterface ThemeToggleProps {\n className?: string;\n theme?: 'light' | 'dark' | 'system';\n}\n\nexport const ThemeToggle: React.FC<ThemeToggleProps> = ({ className = '', theme: initialTheme = 'system' }) => {\n const getInitialTheme = (): 'light' | 'dark' => {\n if (typeof window === 'undefined') return 'light';\n \n if (initialTheme === 'system') {\n const saved = localStorage.getItem('theme') as 'light' | 'dark' | null;\n if (saved) return saved;\n if (window.matchMedia('(prefers-color-scheme: dark)').matches) return 'dark';\n return 'light';\n }\n \n return initialTheme;\n };\n\n const [theme, setTheme] = useState<'light' | 'dark'>(getInitialTheme);\n\n useEffect(() => {\n if (initialTheme !== 'system') {\n setTheme(initialTheme);\n }\n }, [initialTheme]);\n\n useEffect(() => {\n const root = document.documentElement;\n root.classList.remove('light', 'dark');\n root.classList.add(theme);\n if (initialTheme === 'system') {\n localStorage.setItem('theme', theme);\n }\n }, [theme, initialTheme]);\n\n const toggleTheme = () => {\n if (initialTheme === 'system') {\n setTheme((prev) => (prev === 'light' ? 'dark' : 'light'));\n }\n };\n\n return (\n <button\n type=\"button\"\n aria-label=\"Toggle theme\"\n onClick={toggleTheme}\n disabled={initialTheme !== 'system'}\n className={`cuadra-flex cuadra-items-center cuadra-justify-center cuadra-h-8 cuadra-w-8 cuadra-rounded-full cuadra-bg-muted hover:cuadra-bg-muted/80 cuadra-transition-colors disabled:cuadra-opacity-50 disabled:cuadra-cursor-not-allowed ${className}`}\n >\n <Contrast\n className={`cuadra-h-4 cuadra-w-4 cuadra-transition-colors ${theme === 'dark' ? 'cuadra-text-primary' : 'cuadra-text-gray-400'}`}\n />\n </button>\n );\n};\n\n","import React, { useEffect, useRef, useState } from 'react';\nimport { ChevronDown, Menu } from 'lucide-react';\nimport { ThemeToggle } from './ThemeToggle';\n\ninterface ChatHeaderProps {\n currentModel: string;\n models: Array<{ id: string; name: string }>;\n modelsLoading: boolean;\n modelsError?: Error | null;\n onModelChange: (model: string) => void;\n hideModelSelector?: boolean;\n showThemeToggle?: boolean;\n theme?: 'light' | 'dark' | 'system';\n onMobileMenuClick?: () => void;\n showMobileMenuButton?: boolean;\n}\n\nexport const ChatHeader: React.FC<ChatHeaderProps> = ({\n currentModel,\n models,\n modelsLoading,\n modelsError,\n onModelChange,\n hideModelSelector = false,\n showThemeToggle = true,\n theme = 'system',\n onMobileMenuClick,\n showMobileMenuButton = false,\n}) => {\n const [isOpen, setIsOpen] = useState(false);\n const selectRef = useRef<HTMLDivElement>(null);\n\n useEffect(() => {\n const handleClickOutside = (event: MouseEvent) => {\n if (selectRef.current && !selectRef.current.contains(event.target as Node)) {\n setIsOpen(false);\n }\n };\n\n if (isOpen) {\n document.addEventListener('mousedown', handleClickOutside);\n }\n\n return () => {\n document.removeEventListener('mousedown', handleClickOutside);\n };\n }, [isOpen]);\n\n const selectedModel = models.find((m) => m.id === currentModel);\n\n return (\n <div className=\"cuadra-h-16 cuadra-px-4 cuadra-border-b cuadra-border-border cuadra-flex cuadra-items-center cuadra-justify-between cuadra-bg-background\">\n <div className=\"cuadra-flex cuadra-items-center cuadra-gap-2\">\n {showMobileMenuButton && (\n <button\n type=\"button\"\n onClick={onMobileMenuClick}\n className=\"cuadra-flex cuadra-items-center cuadra-justify-center cuadra-h-8 cuadra-w-8 cuadra-rounded-full cuadra-bg-muted hover:cuadra-bg-muted/80 cuadra-transition-colors disabled:cuadra-opacity-50 disabled:cuadra-cursor-not-allowed md:cuadra-hidden\"\n aria-label=\"Toggle thread list\"\n >\n <Menu className=\"cuadra-h-4 cuadra-w-4 cuadra-text-foreground\" />\n </button>\n )}\n {showThemeToggle && (\n <div className=\"cuadra-flex cuadra-items-center cuadra-gap-2\">\n <ThemeToggle theme={theme} />\n </div>\n )}\n </div>\n <div className=\"cuadra-flex cuadra-items-center cuadra-gap-2 md:cuadra-ml-0 cuadra-ml-auto\">\n {!hideModelSelector && (\n <label className=\"cuadra-hidden md:cuadra-inline cuadra-text-sm cuadra-text-muted-foreground cuadra-font-brand\">Model</label>\n )}\n {hideModelSelector ? null : modelsLoading ? (\n <div className=\"cuadra-w-48 cuadra-rounded-md cuadra-border cuadra-border-border cuadra-px-3 cuadra-py-2 cuadra-bg-muted\">\n <span className=\"cuadra-text-muted-foreground cuadra-text-sm cuadra-font-brand\">Loading...</span>\n </div>\n ) : modelsError ? (\n <div className=\"cuadra-w-48 cuadra-rounded-md cuadra-border cuadra-border-destructive cuadra-px-3 cuadra-py-2 cuadra-bg-destructive/10\">\n <span className=\"cuadra-text-destructive cuadra-text-sm cuadra-font-brand\">Failed to load models</span>\n </div>\n ) : (\n <div ref={selectRef} className=\"cuadra-relative cuadra-w-48\">\n <button\n type=\"button\"\n onClick={() => setIsOpen(!isOpen)}\n disabled={modelsLoading || models.length === 0 || !!modelsError}\n className=\"cuadra-flex cuadra-h-10 cuadra-w-full cuadra-items-center cuadra-justify-between cuadra-rounded-md cuadra-border cuadra-border-input cuadra-bg-background cuadra-px-3 cuadra-py-2 cuadra-text-sm placeholder:cuadra-text-muted-foreground focus:cuadra-outline-none disabled:cuadra-cursor-not-allowed disabled:cuadra-opacity-50 cuadra-font-brand\"\n >\n <span className={selectedModel ? 'cuadra-text-foreground' : 'cuadra-text-muted-foreground'}>\n {selectedModel?.name || 'Select model'}\n </span>\n <ChevronDown className=\"cuadra-ml-2 cuadra-h-4 cuadra-w-4 cuadra-opacity-50\" />\n </button>\n {isOpen && models.length > 0 && (\n <div className=\"cuadra-absolute cuadra-z-50 cuadra-mt-1 cuadra-w-full cuadra-min-w-[8rem] cuadra-overflow-hidden cuadra-rounded-md glass-popover cuadra-text-popover-foreground cuadra-animate-in fade-in-80 cuadra-border cuadra-border-border cuadra-bg-popover cuadra-shadow-md\">\n <div className=\"cuadra-p-1\">\n {models.map((model) => (\n <button\n key={model.id}\n type=\"button\"\n onClick={() => {\n onModelChange(model.id);\n setIsOpen(false);\n }}\n className={`cuadra-relative cuadra-flex cuadra-w-full cuadra-cursor-pointer cuadra-select-none cuadra-items-center cuadra-rounded-sm cuadra-py-1.5 cuadra-pl-8 cuadra-pr-2 cuadra-text-sm cuadra-outline-none focus:cuadra-bg-secondary focus:cuadra-text-secondary-foreground font-brand cuadra-transition-colors ${\n currentModel === model.id\n ? 'cuadra-bg-secondary cuadra-text-secondary-foreground'\n : 'hover:cuadra-bg-secondary/50'\n }`}\n >\n {currentModel === model.id && (\n <span className=\"cuadra-absolute cuadra-left-2 cuadra-flex cuadra-h-3.5 cuadra-w-3.5 cuadra-items-center cuadra-justify-center\">\n <svg\n xmlns=\"http://www.w3.org/2000/svg\"\n width=\"16\"\n height=\"16\"\n fill=\"none\"\n viewBox=\"0 0 16 16\"\n >\n <path\n fill=\"currentColor\"\n fillRule=\"evenodd\"\n d=\"M6.47 10.03a.75.75 0 0 1-1.06-1.06l2-2a.75.75 0 0 1 1.06 0l2 2a.75.75 0 1 1-1.06 1.06L8 9.06l-1.53 1.53Z\"\n clipRule=\"evenodd\"\n />\n </svg>\n </span>\n )}\n <span>{model.name}</span>\n </button>\n ))}\n </div>\n </div>\n )}\n </div>\n )}\n </div>\n </div>\n );\n};\n\n","import React, { createContext, useContext } from 'react';\n\ninterface CuadraWidgetContextType {\n currentModelId: string | null;\n models: Array<{ id: string; name: string }>;\n modelsLoading: boolean;\n modelsError: Error | null;\n onModelChange: (modelId: string) => void;\n refetchModels: () => void;\n}\n\nconst CuadraWidgetContext = createContext<CuadraWidgetContextType | undefined>(undefined);\n\nexport const useCuadraWidgetContext = () => {\n const context = useContext(CuadraWidgetContext);\n if (!context) {\n throw new Error('useCuadraWidgetContext must be used within CuadraWidgetProvider');\n }\n return context;\n};\n\ninterface CuadraWidgetProviderProps {\n children: React.ReactNode;\n value: CuadraWidgetContextType;\n}\n\nexport const CuadraWidgetProvider: React.FC<CuadraWidgetProviderProps> = ({ children, value }) => {\n return (\n <CuadraWidgetContext.Provider value={value}>{children}</CuadraWidgetContext.Provider>\n );\n};\n\n","import { useEffect } from 'react';\n\n/**\n * Hook to inject uikit CSS styles into the DOM\n * \n * IMPORTANT: For the CSS to work, consumers must import it:\n * import '@cuadra-ai/uikit/styles';\n * \n * This hook provides a fallback that tries to inject styles if they're not already loaded.\n */\nexport function useInjectStyles(): void {\n useEffect(() => {\n // Check if styles already injected or if CSS is already loaded\n const existingStyle = document.querySelector('style[data-cuadra-uikit]');\n if (existingStyle) {\n return;\n }\n\n // Check if CSS classes are already available (styles might be loaded via import)\n const testEl = document.createElement('div');\n testEl.className = 'cuadra-flex';\n document.body.appendChild(testEl);\n const stylesLoaded = window.getComputedStyle(testEl).display === 'flex';\n document.body.removeChild(testEl);\n\n if (stylesLoaded) {\n // Styles are already loaded, no need to inject\n return;\n }\n\n // Styles not loaded - try to inject them\n // Note: This is a fallback. The proper way is to import '@cuadra-ai/uikit/styles'\n // Silently attempt to load styles - user should import '@cuadra-ai/uikit/styles'\n\n // Create a link element to load the CSS\n const link = document.createElement('link');\n link.setAttribute('data-cuadra-uikit', 'true');\n link.rel = 'stylesheet';\n link.type = 'text/css';\n \n // Try to find the CSS file\n // In development with file: protocol, try relative path\n // In production, it should be in node_modules\n const possiblePaths = [\n '/node_modules/@cuadra-ai/uikit/dist/uikit.css',\n new URL('../dist/uikit.css', import.meta.url).href,\n ];\n\n let loaded = false;\n for (const path of possiblePaths) {\n link.href = path;\n link.onload = () => {\n loaded = true;\n };\n link.onerror = () => {\n // Try next path\n };\n document.head.appendChild(link);\n if (loaded) break;\n }\n }, []);\n}\n\n","import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react';\nimport { createPortal } from 'react-dom';\nimport { Loader2 } from 'lucide-react';\nimport { CuadraRuntimeProvider } from './CuadraRuntimeProvider';\nimport { SimpleThread } from './SimpleThread';\nimport { SimpleThreadList } from './SimpleThreadList';\nimport { TexturedCard } from '../widget/components/TexturedCard';\nimport { ChatHeader } from '../widget/components/ChatHeader';\nimport { CuadraWidgetProvider } from '../widget/context/CuadraWidgetContext';\nimport { CuadraChatClient } from '../lib/cuadraChatClient';\nimport type { ModelPage } from '../types/cuadra';\nimport { useInjectStyles } from '../utils/useInjectStyles';\n\n// Export the config type for use in React components\nexport interface CuadraUIKitConfig {\n // API Configuration (choose one)\n /** Cuadra API base URL (e.g., 'https://api.cuadra.ai') */\n baseUrl?: string;\n /** Proxy URL for backend-handled authentication (e.g., '/api/chat') */\n proxyUrl?: string;\n \n // Authentication (optional if using proxyUrl)\n /** Bearer token for authentication (optional if backend handles auth) */\n sessionToken?: string | null;\n \n // Chat configuration\n /** Chat mode: single thread or multi-thread */\n mode?: 'singleChat' | 'multiChat';\n /** Model selection mode */\n modelMode?: 'selector' | 'fixed';\n /** Model ID (required if modelMode=\"fixed\") */\n modelId?: string;\n /** Callback when model changes (selector mode) */\n onModelChange?: (modelId: string) => void;\n /** Create temporary chats that auto-delete */\n ephemeral?: boolean;\n /** System prompt for the assistant */\n systemPrompt?: string;\n \n // Thread configuration\n /** Load existing thread (multiChat mode) */\n initialThreadId?: string;\n \n // UI Configuration\n /** Language/locale for i18n (e.g., 'en', 'es', 'fr') */\n language?: string;\n /** Welcome screen title */\n welcomeTitle?: string;\n /** Welcome screen subtitle */\n welcomeSubtitle?: string;\n /** Extra top padding for thread viewport (e.g., '1rem', '2rem') */\n extraTopPadding?: string;\n /** Suggestions to show in welcome screen */\n suggestions?: Array<{\n /** Suggestion prompt text */\n prompt: string;\n }>;\n /** Placeholder text for the input field */\n inputPlaceholder?: string;\n \n // Theme configuration\n /** Show theme toggle button */\n showThemeToggle?: boolean;\n /** Initial theme ('light' | 'dark' | 'system') */\n theme?: 'light' | 'dark' | 'system';\n \n // Container\n /** Container element ID (defaults to 'cuadra-chat') */\n containerId?: string;\n /** CSS classes to add to container element */\n containerClass?: string;\n \n // Callbacks\n /** Called when an error occurs */\n onError?: (error: Error) => void;\n /** Called when chat is created */\n onChatCreated?: (chatId: string) => void;\n /** Called when a user message is sent */\n onUserMessage?: () => void;\n /** Called when thread ID updates */\n onThreadIdUpdate?: (oldId: string, newId: string) => void;\n}\n\n/**\n * Main widget content component - shared between library and widget builds\n * This component does NOT use createRoot - it's a regular React component\n */\nexport const WidgetContent: React.FC<{ config: CuadraUIKitConfig }> = ({ config }) => {\n // Inject styles when component mounts\n useInjectStyles();\n\n const {\n baseUrl,\n proxyUrl,\n sessionToken,\n mode = 'multiChat',\n modelMode = 'fixed',\n modelId,\n onModelChange,\n ephemeral = false,\n systemPrompt,\n initialThreadId,\n welcomeTitle,\n welcomeSubtitle,\n extraTopPadding,\n suggestions,\n inputPlaceholder,\n showThemeToggle = true,\n theme: initialTheme = 'system',\n onError,\n onChatCreated,\n onUserMessage,\n onThreadIdUpdate,\n } = config;\n\n // Mobile sidebar state\n const [isMobileSidebarOpen, setIsMobileSidebarOpen] = useState(false);\n\n // Determine the actual baseUrl and proxy mode\n const actualBaseUrl = proxyUrl || baseUrl || '';\n const isProxyMode = !!proxyUrl;\n\n // Create client for fetching models\n const client = useMemo(\n () => new CuadraChatClient(actualBaseUrl, sessionToken || undefined, isProxyMode),\n [actualBaseUrl, sessionToken, isProxyMode],\n );\n\n // Models state (replacing react-query)\n const [modelsData, setModelsData] = useState<ModelPage | null>(null);\n const [modelsLoading, setModelsLoading] = useState(false);\n const [modelsError, setModelsError] = useState<Error | null>(null);\n \n // Chats loading state (for multiChat mode)\n const [chatsLoading, setChatsLoading] = useState(false);\n \n // Set chatsLoading to true initially for multiChat mode\n useEffect(() => {\n if (mode === 'multiChat') {\n setChatsLoading(true);\n }\n }, [mode]);\n\n // Fetch models function\n const fetchModels = useCallback(async () => {\n if (modelMode !== 'selector') return;\n \n setModelsLoading(true);\n setModelsError(null);\n try {\n const data = await client.listModels();\n setModelsData(data);\n } catch (error) {\n setModelsError(error instanceof Error ? error : new Error('Failed to load models'));\n } finally {\n setModelsLoading(false);\n }\n }, [client, modelMode]);\n\n // Initial fetch and refetch function\n useEffect(() => {\n if (modelMode === 'selector') {\n fetchModels();\n }\n }, [modelMode, fetchModels]);\n\n // Expose refetch function on window for external access\n useEffect(() => {\n if (typeof window !== 'undefined') {\n (window as Window & { __cuadraUIKitRefetchModels?: typeof fetchModels }).__cuadraUIKitRefetchModels = fetchModels;\n }\n return () => {\n if (typeof window !== 'undefined') {\n delete (window as Window & { __cuadraUIKitRefetchModels?: typeof fetchModels }).__cuadraUIKitRefetchModels;\n }\n };\n }, [fetchModels]);\n\n // Track current model ID\n const [currentModelId, setCurrentModelId] = useState<string | null>(\n modelMode === 'fixed' ? modelId || null : null,\n );\n \n // Track previous model ID to detect changes\n const prevModelIdRef = useRef<string | null>(currentModelId);\n\n // Handle model change\n const handleModelChange = useCallback(\n (newModelId: string) => {\n const prevModelId = prevModelIdRef.current;\n setCurrentModelId(newModelId);\n prevModelIdRef.current = newModelId;\n onModelChange?.(newModelId);\n \n // Create a new thread when model changes (if not initial load)\n if (prevModelId !== null && prevModelId !== newModelId && mode === 'multiChat') {\n // Access the runtime to create a new thread\n // Use setTimeout to ensure runtime is available after state update\n setTimeout(() => {\n const runtime = (window as Window & { \n __cuadraThreadListRuntime?: {\n threads?: {\n switchToNewThread?: () => Promise<void> | void;\n createThread?: () => Promise<void> | void;\n };\n switchToNewThread?: () => Promise<void> | void;\n } \n }).__cuadraThreadListRuntime;\n \n // Try multiple ways to create a new thread\n if (runtime?.threads?.switchToNewThread) {\n try {\n void runtime.threads.switchToNewThread();\n } catch (_error) {\n // Silently handle - user can manually create thread\n }\n } else if (runtime?.threads?.createThread) {\n try {\n void runtime.threads.createThread();\n } catch (_error) {\n // Silently handle - user can manually create thread\n }\n } else if (runtime?.switchToNewThread) {\n try {\n void runtime.switchToNewThread();\n } catch (_error) {\n // Silently handle - user can manually create thread\n }\n }\n }, 100);\n }\n },\n [onModelChange, mode],\n );\n\n // Auto-select first model when models are loaded\n useEffect(() => {\n if (\n modelMode === 'selector' &&\n modelsData?.items &&\n modelsData.items.length > 0 &&\n !currentModelId\n ) {\n const firstModel = modelsData.items[0];\n if (firstModel?.id) {\n const modelId = firstModel.id as string;\n setCurrentModelId(modelId);\n onModelChange?.(modelId);\n }\n }\n }, [modelMode, modelsData?.items, currentModelId, onModelChange]);\n\n // Don't render chat UI until we have a model selected (for selector mode)\n const hasModel = modelMode === 'fixed' ? !!modelId : !!currentModelId;\n\n // Prepare models for ChatHeader\n const models = useMemo(\n () =>\n (modelsData?.items || [])\n .filter((m) => m?.id && m?.displayName)\n .map((m) => ({ id: m.id as string, name: m.displayName as string })),\n [modelsData],\n );\n\n // Create widget context value\n const widgetContextValue = useMemo(\n () => ({\n currentModelId: currentModelId || '',\n models,\n modelsLoading,\n modelsError,\n onModelChange: handleModelChange,\n refetchModels: fetchModels,\n }),\n [currentModelId, models, modelsLoading, modelsError, handleModelChange, fetchModels],\n );\n\n // Determine if we're still loading (models and/or chats)\n const isLoading = \n (modelMode === 'selector' && modelsLoading) || \n (mode === 'multiChat' && chatsLoading);\n\n // Show loading state if we're still loading models or chats\n if (isLoading) {\n return (\n <CuadraWidgetProvider value={widgetContextValue}>\n <TexturedCard className=\"cuadra-h-full\" paddingX=\"cuadra-px-0\" paddingY=\"cuadra-py-0\">\n <div className=\"cuadra-flex cuadra-items-center cuadra-justify-center cuadra-h-full\">\n <Loader2 className=\"cuadra-h-6 cuadra-w-6 cuadra-animate-spin cuadra-text-muted-foreground\" />\n </div>\n </TexturedCard>\n </CuadraWidgetProvider>\n );\n }\n\n // Show error state if we need a model but don't have one\n if (modelMode === 'selector' && !hasModel && modelsError) {\n return (\n <CuadraWidgetProvider value={widgetContextValue}>\n <TexturedCard className=\"cuadra-h-full\" paddingX=\"cuadra-px-0\" paddingY=\"cuadra-py-0\">\n <div className=\"cuadra-flex cuadra-items-center cuadra-justify-center cuadra-h-full\">\n <div className=\"cuadra-flex cuadra-flex-col cuadra-items-center cuadra-gap-2\">\n <p className=\"cuadra-text-sm cuadra-text-destructive font-brand\">Failed to load models</p>\n </div>\n </div>\n </TexturedCard>\n </CuadraWidgetProvider>\n );\n }\n\n return (\n <div className=\"cuadra-uikit cuadra-h-full cuadra-w-full\" style={{ height: '100%', width: '100%' }}>\n <CuadraWidgetProvider value={widgetContextValue}>\n <CuadraRuntimeProvider\n baseUrl={isProxyMode ? actualBaseUrl : (baseUrl || actualBaseUrl)}\n sessionToken={sessionToken}\n isProxyMode={isProxyMode}\n mode={mode}\n modelMode={modelMode}\n modelId={currentModelId || modelId || undefined}\n onModelChange={handleModelChange}\n ephemeral={ephemeral}\n systemPrompt={systemPrompt}\n initialThreadId={initialThreadId}\n onError={onError}\n onChatCreated={onChatCreated}\n onUserMessage={onUserMessage}\n onThreadIdUpdate={onThreadIdUpdate}\n onChatsLoaded={() => {\n if (mode === 'multiChat') {\n setChatsLoading(false);\n }\n }}\n >\n <TexturedCard\n paddingX=\"cuadra-px-0\"\n paddingY=\"cuadra-py-0\"\n className={`cuadra-h-full ${config.containerClass || ''}`}\n borderSizePx={4}\n style={{ height: '100%' }}\n >\n <div className=\"cuadra-h-full cuadra-flex cuadra-relative\" style={{ height: '100%' }}>\n {mode === 'multiChat' ? (\n <>\n {/* Mobile sidebar overlay - portal for full height */}\n {isMobileSidebarOpen && typeof document !== 'undefined' && createPortal(\n <div\n className=\"cuadra-fixed cuadra-inset-0 cuadra-bg-black/50 cuadra-z-40 md:cuadra-hidden\"\n onClick={() => setIsMobileSidebarOpen(false)}\n />,\n document.body\n )}\n {/* Thread list sidebar - portal on mobile, relative on desktop */}\n {typeof document !== 'undefined' && (\n <>\n {/* Desktop: render inline */}\n <div\n className=\"cuadra-hidden md:cuadra-block !cuadra-border-r cuadra-border-border cuadra-flex cuadra-flex-col cuadra-bg-background cuadra-transition-all cuadra-duration-300 cuadra-ease-in-out cuadra-h-full cuadra-w-80 cuadra-relative\"\n style={{ borderRightWidth: '1px', height: '100%' }}\n >\n <SimpleThreadList onThreadSelect={() => setIsMobileSidebarOpen(false)} />\n </div>\n {/* Mobile: render as portal */}\n {isMobileSidebarOpen && createPortal(\n <div\n className=\"cuadra-block md:cuadra-hidden !cuadra-border-r cuadra-border-border cuadra-flex cuadra-flex-col cuadra-bg-background cuadra-transition-all cuadra-duration-300 cuadra-ease-in-out cuadra-h-screen cuadra-w-80 cuadra-fixed cuadra-z-50 cuadra-top-0 cuadra-left-0 cuadra-translate-x-0\"\n style={{ borderRightWidth: '1px' }}\n >\n <SimpleThreadList onThreadSelect={() => setIsMobileSidebarOpen(false)} />\n </div>,\n document.body\n )}\n </>\n )}\n <div className=\"cuadra-flex-1 cuadra-flex cuadra-flex-col\">\n {modelMode === 'selector' && (\n <ChatHeader\n currentModel={currentModelId || ''}\n models={models}\n modelsLoading={modelsLoading}\n modelsError={modelsError}\n onModelChange={handleModelChange}\n showThemeToggle={showThemeToggle}\n theme={initialTheme}\n onMobileMenuClick={() => setIsMobileSidebarOpen(!isMobileSidebarOpen)}\n showMobileMenuButton={mode === 'multiChat'}\n />\n )}\n <div className=\"cuadra-flex-1 cuadra-relative cuadra-min-h-0 cuadra-space-y-4 cuadra-p-4\">\n <SimpleThread \n welcomeTitle={welcomeTitle}\n welcomeSubtitle={welcomeSubtitle}\n extraTopPadding={extraTopPadding}\n suggestions={suggestions}\n inputPlaceholder={inputPlaceholder}\n />\n </div>\n </div>\n </>\n ) : (\n <div className=\"cuadra-flex-1 cuadra-flex cuadra-flex-col\">\n {modelMode === 'selector' && (\n <ChatHeader\n currentModel={currentModelId || ''}\n models={models}\n modelsLoading={modelsLoading}\n modelsError={modelsError}\n onModelChange={handleModelChange}\n showThemeToggle={showThemeToggle}\n theme={initialTheme}\n />\n )}\n <div className=\"cuadra-flex-1 cuadra-relative cuadra-min-h-0 cuadra-space-y-4 cuadra-p-4\">\n <SimpleThread \n welcomeTitle={welcomeTitle}\n welcomeSubtitle={welcomeSubtitle}\n extraTopPadding={extraTopPadding}\n suggestions={suggestions}\n />\n </div>\n </div>\n )}\n </div>\n </TexturedCard>\n </CuadraRuntimeProvider>\n </CuadraWidgetProvider>\n </div>\n );\n};\n\n","import { type CuadraUIKitConfig, WidgetContent } from './WidgetContent';\nimport type { CuadraRuntimeProviderProps } from './CuadraRuntimeProvider';\n\n// Props interface that matches CuadraRuntimeProviderProps but adds className and proxyUrl\nexport interface CuadraChatProps extends Omit<CuadraRuntimeProviderProps, 'children' | 'isProxyMode'> {\n /** Proxy URL for backend-handled authentication (e.g., '/api/chat' or 'http://localhost:3000') */\n proxyUrl?: string;\n /** Container className for styling */\n className?: string;\n /** Show theme toggle button */\n showThemeToggle?: boolean;\n /** Initial theme ('light' | 'dark' | 'system') */\n theme?: 'light' | 'dark' | 'system';\n /** Language/locale for i18n (e.g., 'en', 'es', 'fr') */\n language?: string;\n /** Welcome screen title */\n welcomeTitle?: string;\n /** Welcome screen subtitle */\n welcomeSubtitle?: string;\n /** Extra top padding for thread viewport (e.g., '1rem', '2rem') */\n extraTopPadding?: string;\n /** Suggestions to show in welcome screen */\n suggestions?: Array<{\n /** Suggestion prompt text */\n prompt: string;\n }>;\n /** Placeholder text for the input field */\n inputPlaceholder?: string;\n /** Called when a user message is sent */\n onUserMessage?: () => void;\n}\n\n/**\n * All-in-one Cuadra Chat component\n * \n * This component uses the widget implementation internally, ensuring\n * consistent styling and behavior with the widget version.\n */\nexport function CuadraChat(props: CuadraChatProps) {\n const config: CuadraUIKitConfig = {\n baseUrl: props.baseUrl,\n proxyUrl: props.proxyUrl,\n sessionToken: props.sessionToken || null,\n mode: props.mode || 'multiChat',\n modelMode: props.modelMode || 'fixed',\n modelId: props.modelId,\n onModelChange: props.onModelChange,\n ephemeral: props.ephemeral,\n systemPrompt: props.systemPrompt,\n initialThreadId: props.initialThreadId,\n language: props.language,\n welcomeTitle: props.welcomeTitle,\n welcomeSubtitle: props.welcomeSubtitle,\n extraTopPadding: props.extraTopPadding,\n suggestions: props.suggestions,\n inputPlaceholder: props.inputPlaceholder,\n onError: props.onError,\n onChatCreated: props.onChatCreated,\n onUserMessage: props.onUserMessage,\n onThreadIdUpdate: props.onThreadIdUpdate,\n showThemeToggle: props.showThemeToggle,\n theme: props.theme,\n containerClass: props.className,\n };\n\n return <WidgetContent config={config} />;\n}\n\n"],"names":["toKebabCase","string","toCamelCase","match","p1","p2","toPascalCase","camelCase","mergeClasses","classes","className","index","array","hasA11yProp","props","prop","defaultAttributes","Icon","forwardRef","color","size","strokeWidth","absoluteStrokeWidth","children","iconNode","rest","ref","createElement","tag","attrs","createLucideIcon","iconName","Component","__iconNode","ArrowUp","Check","ChevronDown","Contrast","Copy","EllipsisVertical","LoaderCircle","Menu","Plus","CuadraChatClient","baseUrl","sessionToken","isProxyMode","__publicField","token","endpoint","path","request","abortSignal","url","headers","body","response","errorData","chatId","params","expand","generateHex","count","generateVariant","variants","update","errorText","text","modelId","parseSSEStream","stream","reader","decoder","buffer","done","value","lines","line","data","convertToCuadraMessages","messages","msg","content","textContent","c","convertFromCuadraMessage","createChatModelAdapter","client","options","systemPrompt","ephemeral","onChatCreated","onUserMessage","onThreadIdUpdate","context","currentThreadId","accumulatedText","chunk","chunkId","delta","localToRemoteIdMap","createThreadListAdapter","onChatIdReceived","all","cursor","safety","items","chat","id","t","threadId","remoteId","newTitle","_remoteId","_messages","localThreadId","serverChatId","useThreadListItem","history","React","error","message","adapters","jsx","RuntimeAdapterProvider","CuadraRuntimeProvider","mode","_onModelChange","initialThreadId","onError","onChatsLoaded","useMemo","selectedModelId","setSelectedModelId","useState","useEffect","handleChatCreated","useCallback","handleThreadIdUpdate","oldId","newId","modelAdapter","SingleChatProvider","MultiChatProvider","localRuntime","useLocalRuntime","AssistantRuntimeProvider","modelAdapterOptions","_initialThreadId","_onError","threadListAdapter","handleThreadIdUpdateFromAdapter","wrappedAdapter","result","runtimeHook","runtime","unstable_useRemoteThreadListRuntime","ccount","character","source","asciiAlpha","regexCheck","asciiAlphanumeric","asciiControl","code","markdownLineEnding","markdownLineEndingOrSpace","markdownSpace","unicodePunctuation","unicodeWhitespace","regex","check","escapeStringRegexp","convert","test","ok","castFactory","anyFactory","propertiesFactory","typeFactory","tests","checks","any","parameters","checkAsRecord","node","nodeAsRecord","key","type","testFunction","parent","looksLikeANode","empty","CONTINUE","EXIT","SKIP","visitParents","tree","visitor","reverse","is","step","factory","parents","name","visit","subresult","offset","grandparents","toResult","nodeAsParent","child","findAndReplace","list","ignored","pairs","toPairs","pairIndex","grandparent","siblings","handler","find","replace","start","change","nodes","position","matchObject","tupleOrList","tuple","toExpression","toFunction","escape","inConstruct","notInConstruct","gfmAutolinkLiteralFromMarkdown","transformGfmAutolinkLiterals","enterLiteralAutolink","enterLiteralAutolinkValue","exitLiteralAutolink","exitLiteralAutolinkEmail","exitLiteralAutolinkHttp","exitLiteralAutolinkWww","gfmAutolinkLiteralToMarkdown","assert","findUrl","findEmail","_","protocol","domain","prefix","previous","isCorrectDomain","parts","splitUrl","atext","label","trailExec","trail","closingParenIndex","openingParens","closingParens","email","normalizeIdentifier","footnoteReference","footnoteReferencePeek","enterFootnoteCallString","enterFootnoteCall","enterFootnoteDefinitionLabelString","enterFootnoteDefinition","exitFootnoteCallString","exitFootnoteCall","exitFootnoteDefinitionLabelString","exitFootnoteDefinition","state","info","tracker","exit","subexit","gfmFootnoteFromMarkdown","gfmFootnoteToMarkdown","firstLineBlank","footnoteDefinition","mapAll","mapExceptFirst","blank","constructsWithoutStrikethrough","handleDelete","peekDelete","gfmStrikethroughFromMarkdown","enterStrikethrough","exitStrikethrough","gfmStrikethroughToMarkdown","defaultStringLength","markdownTable","table","settings","align","stringLength","alignments","cellMatrix","sizeMatrix","longestCellByColumn","mostCellsPerRow","rowIndex","row","sizes","columnIndex","cell","serialize","toAlignment","before","after","blockquote","map","patternInScope","stack","pattern","listInScope","none","hardBreak","_1","longestStreak","substring","expected","max","formatCodeAsIndented","checkFence","marker","raw","suffix","sequence","checkQuote","definition","quote","checkEmphasis","encodeCharacterReference","classifyCharacter","encodeInfo","outside","inside","outsideKind","insideKind","emphasis","emphasisPeek","between","betweenHead","open","betweenTail","close","testOrVisitor","visitorOrReverse","maybeReverse","overload","emptyOptions","toString","includeImageAlt","includeHtml","one","values","formatHeadingAsSetext","literalWithBreak","heading","rank","html","htmlPeek","image","imagePeek","imageReference","imageReferencePeek","alt","reference","inlineCode","inlineCodePeek","expression","formatLinkAsAutolink","link","linkPeek","linkReference","linkReferencePeek","checkBullet","checkBulletOther","bullet","bulletOther","checkBulletOrdered","checkRule","bulletCurrent","useDifferentMarker","firstListItem","item","checkListItemIndent","style","listItem","listItemIndent","paragraph","phrasing","root","d","checkStrong","strong","strongPeek","checkRuleRepetition","repetition","thematicBreak","handle","gfmTableFromMarkdown","enterTable","enterCell","enterRow","exitCodeText","exitTable","$0","$1","gfmTableToMarkdown","padding","alignDelimiters","around","inlineCodeWithTable","handleTable","handleTableCell","handleTableRow","serializeData","handleTableAsData","handleTableRowAsData","matrix","defaultHandlers","gfmTaskListItemFromMarkdown","exitCheck","exitParagraphWithTaskListItem","gfmTaskListItemToMarkdown","listItemWithTaskListItem","head","firstParaghraph","sibling","checkable","checkbox","gfmFromMarkdown","gfmToMarkdown","splice","remove","end","chunkStart","hasOwnProperty","combineExtensions","extensions","syntaxExtension","extension","hook","left","right","constructs","existing","wwwPrefix","tokenizeWwwPrefix","tokenizeDomain","tokenizePath","tokenizeTrail","emailDomainDotTrail","tokenizeEmailDomainDotTrail","wwwAutolink","tokenizeWwwAutolink","previousWww","protocolAutolink","tokenizeProtocolAutolink","previousProtocol","emailAutolink","tokenizeEmailAutolink","previousEmail","gfmAutolinkLiteral","effects","nok","self","dot","gfmAtext","previousUnbalanced","emailDomain","emailDomainAfter","emailDomainDot","wwwStart","wwwAfter","seen","protocolStart","protocolPrefixInside","protocolSlashesInside","afterProtocol","protocolAfter","wwwPrefixInside","wwwPrefixAfter","underscoreInLastSegment","underscoreInLastLastSegment","domainInside","domainAfter","domainAtPunctuation","sizeOpen","sizeClose","pathInside","pathAtPunctuation","trailCharacterReferenceStart","trailBracketAfter","trailCharacterReferenceInside","events","resolveAll","called","resolve","factorySpace","limit","blankLine","tokenizeBlankLine","indent","tokenizeIndent","gfmFootnote","tokenizeDefinitionStart","tokenizeDefinitionContinuation","gfmFootnoteDefinitionEnd","tokenizeGfmFootnoteCall","tokenizePotentialGfmFootnoteCall","resolveToPotentialGfmFootnoteCall","defined","labelStart","call","replacement","callStart","callData","callEscape","identifier","labelAtMarker","labelInside","labelAfter","labelEscape","whitespaceAfter","afterPrefix","tail","gfmStrikethrough","single","tokenizer","tokenizeStrikethrough","resolveAllStrikethrough","strikethrough","nextEvents","insideSpan","more","EditMap","add","addImplementation","a","b","vecs","slice","element","editMap","at","gfmTableAlign","inDelimiterRow","event","alignIndex","gfmTable","tokenizeTable","resolveTable","sizeB","next","bodyRowStart","headRowBefore","headRowStart","headRowBreak","headDelimiterStart","headRowData","headRowEscape","headDelimiterBefore","headDelimiterValueBefore","headDelimiterCellBefore","headDelimiterNok","headDelimiterLeftAlignmentAfter","headDelimiterCellAfter","headDelimiterFiller","headDelimiterRightAlignmentAfter","bodyRowBreak","bodyRowData","bodyRowEscape","inFirstCellAwaitingPipe","rowKind","lastCell","afterHeadAwaitingFirstBodyRow","lastTableEnd","currentTable","currentBody","currentCell","flushTableEnd","flushCell","range","rowEnd","previousCell","groupName","valueName","getPoint","now","relatedStart","relatedEnd","valueToken","tableBody","exits","related","side","tasklistCheck","tokenizeTasklistCheck","gfmTaskListItem","spaceThenNonSpace","gfm","remarkGfm","micromarkExtensions","fromMarkdownExtensions","toMarkdownExtensions","cn","MarkdownTextImpl","MarkdownTextPrimitive","defaultComponents","MarkdownText","memo","CodeHeader","language","isCopied","copyToClipboard","useCopyToClipboard","jsxs","CopyIcon","CheckIcon","copiedDuration","setIsCopied","memoizeMarkdownComponents","isCodeBlock","useIsMarkdownCodeBlock","STEPS","FakeReasoningLoader","active","setIndex","prev","SimpleThread","welcomeTitle","welcomeSubtitle","extraTopPadding","suggestions","inputPlaceholder","thread","useThreadRuntime","isLoadingMessages","setIsLoadingMessages","setCurrentThreadId","hasAssistantContent","setHasAssistantContent","runtimeStore","unsubscribe","isLoadingHistory","messageCount","hasAssistantWithText","m","ThreadPrimitive","Loader2","Fragment","WelcomeScreen","UserMessage","AssistantMessage","ComposerPrimitive","ArrowUpIcon","title","subtitle","api","useAssistantApi","handleSuggestionClick","prompt","suggestion","MessagePrimitive","ThreadListItem","onThreadSelect","threadItem","currentThread","useThread","hoveredThreadId","setHoveredThreadId","isActive","isHovered","isRenaming","setIsRenaming","nextTitle","setNextTitle","isMenuOpen","setIsMenuOpen","busy","setBusy","handleRename","adapter","ThreadListItemPrimitive","e","MoreVertical","SimpleThreadList","ThreadListPrimitive","pulseKeyframes","TexturedCard","paddingX","paddingY","borderSizePx","contentStyle","rotating","ThemeToggle","initialTheme","getInitialTheme","saved","theme","setTheme","ChatHeader","currentModel","models","modelsLoading","modelsError","onModelChange","hideModelSelector","showThemeToggle","onMobileMenuClick","showMobileMenuButton","isOpen","setIsOpen","selectRef","useRef","handleClickOutside","selectedModel","model","CuadraWidgetContext","createContext","CuadraWidgetProvider","useInjectStyles","testEl","stylesLoaded","possiblePaths","loaded","WidgetContent","config","proxyUrl","modelMode","isMobileSidebarOpen","setIsMobileSidebarOpen","actualBaseUrl","modelsData","setModelsData","setModelsLoading","setModelsError","chatsLoading","setChatsLoading","fetchModels","currentModelId","setCurrentModelId","prevModelIdRef","handleModelChange","newModel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,QAAAC,GAAgB;AACxC;","x_google_ignoreList":[0,1,2,3,4,5,6,7,8,9,10,11,12,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86]}
|
|
1
|
+
{"version":3,"file":"index.mjs","sources":["../node_modules/lucide-react/dist/esm/shared/src/utils.js","../node_modules/lucide-react/dist/esm/defaultAttributes.js","../node_modules/lucide-react/dist/esm/Icon.js","../node_modules/lucide-react/dist/esm/createLucideIcon.js","../node_modules/lucide-react/dist/esm/icons/arrow-up.js","../node_modules/lucide-react/dist/esm/icons/check.js","../node_modules/lucide-react/dist/esm/icons/chevron-down.js","../node_modules/lucide-react/dist/esm/icons/contrast.js","../node_modules/lucide-react/dist/esm/icons/copy.js","../node_modules/lucide-react/dist/esm/icons/ellipsis-vertical.js","../node_modules/lucide-react/dist/esm/icons/loader-circle.js","../node_modules/lucide-react/dist/esm/icons/menu.js","../node_modules/lucide-react/dist/esm/icons/plus.js","../src/lib/cuadraChatClient.ts","../src/adapters/messageConverter.ts","../src/adapters/chatModelAdapter.ts","../src/adapters/threadListAdapter.tsx","../src/components/CuadraRuntimeProvider.tsx","../node_modules/ccount/index.js","../node_modules/micromark-util-character/index.js","../node_modules/mdast-util-find-and-replace/node_modules/escape-string-regexp/index.js","../node_modules/unist-util-is/lib/index.js","../node_modules/unist-util-visit-parents/lib/index.js","../node_modules/mdast-util-find-and-replace/lib/index.js","../node_modules/mdast-util-gfm-autolink-literal/lib/index.js","../node_modules/micromark-util-normalize-identifier/index.js","../node_modules/mdast-util-gfm-footnote/lib/index.js","../node_modules/mdast-util-gfm-strikethrough/lib/index.js","../node_modules/markdown-table/index.js","../node_modules/mdast-util-to-markdown/lib/handle/blockquote.js","../node_modules/mdast-util-to-markdown/lib/util/pattern-in-scope.js","../node_modules/mdast-util-to-markdown/lib/handle/break.js","../node_modules/longest-streak/index.js","../node_modules/mdast-util-to-markdown/lib/util/format-code-as-indented.js","../node_modules/mdast-util-to-markdown/lib/util/check-fence.js","../node_modules/mdast-util-to-markdown/lib/handle/code.js","../node_modules/mdast-util-to-markdown/lib/util/check-quote.js","../node_modules/mdast-util-to-markdown/lib/handle/definition.js","../node_modules/mdast-util-to-markdown/lib/util/check-emphasis.js","../node_modules/mdast-util-to-markdown/lib/util/encode-character-reference.js","../node_modules/micromark-util-classify-character/index.js","../node_modules/mdast-util-to-markdown/lib/util/encode-info.js","../node_modules/mdast-util-to-markdown/lib/handle/emphasis.js","../node_modules/unist-util-visit/lib/index.js","../node_modules/mdast-util-to-string/lib/index.js","../node_modules/mdast-util-to-markdown/lib/util/format-heading-as-setext.js","../node_modules/mdast-util-to-markdown/lib/handle/heading.js","../node_modules/mdast-util-to-markdown/lib/handle/html.js","../node_modules/mdast-util-to-markdown/lib/handle/image.js","../node_modules/mdast-util-to-markdown/lib/handle/image-reference.js","../node_modules/mdast-util-to-markdown/lib/handle/inline-code.js","../node_modules/mdast-util-to-markdown/lib/util/format-link-as-autolink.js","../node_modules/mdast-util-to-markdown/lib/handle/link.js","../node_modules/mdast-util-to-markdown/lib/handle/link-reference.js","../node_modules/mdast-util-to-markdown/lib/util/check-bullet.js","../node_modules/mdast-util-to-markdown/lib/util/check-bullet-other.js","../node_modules/mdast-util-to-markdown/lib/util/check-bullet-ordered.js","../node_modules/mdast-util-to-markdown/lib/util/check-rule.js","../node_modules/mdast-util-to-markdown/lib/handle/list.js","../node_modules/mdast-util-to-markdown/lib/util/check-list-item-indent.js","../node_modules/mdast-util-to-markdown/lib/handle/list-item.js","../node_modules/mdast-util-to-markdown/lib/handle/paragraph.js","../node_modules/mdast-util-phrasing/lib/index.js","../node_modules/mdast-util-to-markdown/lib/handle/root.js","../node_modules/mdast-util-to-markdown/lib/util/check-strong.js","../node_modules/mdast-util-to-markdown/lib/handle/strong.js","../node_modules/mdast-util-to-markdown/lib/handle/text.js","../node_modules/mdast-util-to-markdown/lib/util/check-rule-repetition.js","../node_modules/mdast-util-to-markdown/lib/handle/thematic-break.js","../node_modules/mdast-util-to-markdown/lib/handle/index.js","../node_modules/mdast-util-gfm-table/lib/index.js","../node_modules/mdast-util-gfm-task-list-item/lib/index.js","../node_modules/mdast-util-gfm/lib/index.js","../node_modules/micromark-util-chunked/index.js","../node_modules/micromark-util-combine-extensions/index.js","../node_modules/micromark-extension-gfm-autolink-literal/lib/syntax.js","../node_modules/micromark-util-resolve-all/index.js","../node_modules/micromark-factory-space/index.js","../node_modules/micromark-core-commonmark/lib/blank-line.js","../node_modules/micromark-extension-gfm-footnote/lib/syntax.js","../node_modules/micromark-extension-gfm-strikethrough/lib/syntax.js","../node_modules/micromark-extension-gfm-table/lib/edit-map.js","../node_modules/micromark-extension-gfm-table/lib/infer.js","../node_modules/micromark-extension-gfm-table/lib/syntax.js","../node_modules/micromark-extension-gfm-task-list-item/lib/syntax.js","../node_modules/micromark-extension-gfm/index.js","../node_modules/remark-gfm/lib/index.js","../src/utils/cn.ts","../src/components/MarkdownText.tsx","../src/components/FakeReasoningLoader.tsx","../src/components/SimpleThread.tsx","../src/components/SimpleThreadList.tsx","../src/widget/components/TexturedCard.tsx","../src/widget/components/ThemeToggle.tsx","../src/widget/components/ChatHeader.tsx","../src/widget/context/CuadraWidgetContext.tsx","../src/utils/useInjectStyles.ts","../src/components/WidgetContent.tsx","../src/components/CuadraChat.tsx"],"sourcesContent":["/**\n * @license lucide-react v0.555.0 - ISC\n *\n * This source code is licensed under the ISC license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nconst toKebabCase = (string) => string.replace(/([a-z0-9])([A-Z])/g, \"$1-$2\").toLowerCase();\nconst toCamelCase = (string) => string.replace(\n /^([A-Z])|[\\s-_]+(\\w)/g,\n (match, p1, p2) => p2 ? p2.toUpperCase() : p1.toLowerCase()\n);\nconst toPascalCase = (string) => {\n const camelCase = toCamelCase(string);\n return camelCase.charAt(0).toUpperCase() + camelCase.slice(1);\n};\nconst mergeClasses = (...classes) => classes.filter((className, index, array) => {\n return Boolean(className) && className.trim() !== \"\" && array.indexOf(className) === index;\n}).join(\" \").trim();\nconst hasA11yProp = (props) => {\n for (const prop in props) {\n if (prop.startsWith(\"aria-\") || prop === \"role\" || prop === \"title\") {\n return true;\n }\n }\n};\n\nexport { hasA11yProp, mergeClasses, toCamelCase, toKebabCase, toPascalCase };\n//# sourceMappingURL=utils.js.map\n","/**\n * @license lucide-react v0.555.0 - ISC\n *\n * This source code is licensed under the ISC license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nvar defaultAttributes = {\n xmlns: \"http://www.w3.org/2000/svg\",\n width: 24,\n height: 24,\n viewBox: \"0 0 24 24\",\n fill: \"none\",\n stroke: \"currentColor\",\n strokeWidth: 2,\n strokeLinecap: \"round\",\n strokeLinejoin: \"round\"\n};\n\nexport { defaultAttributes as default };\n//# sourceMappingURL=defaultAttributes.js.map\n","/**\n * @license lucide-react v0.555.0 - ISC\n *\n * This source code is licensed under the ISC license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport { forwardRef, createElement } from 'react';\nimport defaultAttributes from './defaultAttributes.js';\nimport { mergeClasses, hasA11yProp } from './shared/src/utils.js';\n\nconst Icon = forwardRef(\n ({\n color = \"currentColor\",\n size = 24,\n strokeWidth = 2,\n absoluteStrokeWidth,\n className = \"\",\n children,\n iconNode,\n ...rest\n }, ref) => createElement(\n \"svg\",\n {\n ref,\n ...defaultAttributes,\n width: size,\n height: size,\n stroke: color,\n strokeWidth: absoluteStrokeWidth ? Number(strokeWidth) * 24 / Number(size) : strokeWidth,\n className: mergeClasses(\"lucide\", className),\n ...!children && !hasA11yProp(rest) && { \"aria-hidden\": \"true\" },\n ...rest\n },\n [\n ...iconNode.map(([tag, attrs]) => createElement(tag, attrs)),\n ...Array.isArray(children) ? children : [children]\n ]\n )\n);\n\nexport { Icon as default };\n//# sourceMappingURL=Icon.js.map\n","/**\n * @license lucide-react v0.555.0 - ISC\n *\n * This source code is licensed under the ISC license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport { forwardRef, createElement } from 'react';\nimport { mergeClasses, toKebabCase, toPascalCase } from './shared/src/utils.js';\nimport Icon from './Icon.js';\n\nconst createLucideIcon = (iconName, iconNode) => {\n const Component = forwardRef(\n ({ className, ...props }, ref) => createElement(Icon, {\n ref,\n iconNode,\n className: mergeClasses(\n `lucide-${toKebabCase(toPascalCase(iconName))}`,\n `lucide-${iconName}`,\n className\n ),\n ...props\n })\n );\n Component.displayName = toPascalCase(iconName);\n return Component;\n};\n\nexport { createLucideIcon as default };\n//# sourceMappingURL=createLucideIcon.js.map\n","/**\n * @license lucide-react v0.555.0 - ISC\n *\n * This source code is licensed under the ISC license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport createLucideIcon from '../createLucideIcon.js';\n\nconst __iconNode = [\n [\"path\", { d: \"m5 12 7-7 7 7\", key: \"hav0vg\" }],\n [\"path\", { d: \"M12 19V5\", key: \"x0mq9r\" }]\n];\nconst ArrowUp = createLucideIcon(\"arrow-up\", __iconNode);\n\nexport { __iconNode, ArrowUp as default };\n//# sourceMappingURL=arrow-up.js.map\n","/**\n * @license lucide-react v0.555.0 - ISC\n *\n * This source code is licensed under the ISC license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport createLucideIcon from '../createLucideIcon.js';\n\nconst __iconNode = [[\"path\", { d: \"M20 6 9 17l-5-5\", key: \"1gmf2c\" }]];\nconst Check = createLucideIcon(\"check\", __iconNode);\n\nexport { __iconNode, Check as default };\n//# sourceMappingURL=check.js.map\n","/**\n * @license lucide-react v0.555.0 - ISC\n *\n * This source code is licensed under the ISC license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport createLucideIcon from '../createLucideIcon.js';\n\nconst __iconNode = [[\"path\", { d: \"m6 9 6 6 6-6\", key: \"qrunsl\" }]];\nconst ChevronDown = createLucideIcon(\"chevron-down\", __iconNode);\n\nexport { __iconNode, ChevronDown as default };\n//# sourceMappingURL=chevron-down.js.map\n","/**\n * @license lucide-react v0.555.0 - ISC\n *\n * This source code is licensed under the ISC license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport createLucideIcon from '../createLucideIcon.js';\n\nconst __iconNode = [\n [\"circle\", { cx: \"12\", cy: \"12\", r: \"10\", key: \"1mglay\" }],\n [\"path\", { d: \"M12 18a6 6 0 0 0 0-12v12z\", key: \"j4l70d\" }]\n];\nconst Contrast = createLucideIcon(\"contrast\", __iconNode);\n\nexport { __iconNode, Contrast as default };\n//# sourceMappingURL=contrast.js.map\n","/**\n * @license lucide-react v0.555.0 - ISC\n *\n * This source code is licensed under the ISC license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport createLucideIcon from '../createLucideIcon.js';\n\nconst __iconNode = [\n [\"rect\", { width: \"14\", height: \"14\", x: \"8\", y: \"8\", rx: \"2\", ry: \"2\", key: \"17jyea\" }],\n [\"path\", { d: \"M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2\", key: \"zix9uf\" }]\n];\nconst Copy = createLucideIcon(\"copy\", __iconNode);\n\nexport { __iconNode, Copy as default };\n//# sourceMappingURL=copy.js.map\n","/**\n * @license lucide-react v0.555.0 - ISC\n *\n * This source code is licensed under the ISC license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport createLucideIcon from '../createLucideIcon.js';\n\nconst __iconNode = [\n [\"circle\", { cx: \"12\", cy: \"12\", r: \"1\", key: \"41hilf\" }],\n [\"circle\", { cx: \"12\", cy: \"5\", r: \"1\", key: \"gxeob9\" }],\n [\"circle\", { cx: \"12\", cy: \"19\", r: \"1\", key: \"lyex9k\" }]\n];\nconst EllipsisVertical = createLucideIcon(\"ellipsis-vertical\", __iconNode);\n\nexport { __iconNode, EllipsisVertical as default };\n//# sourceMappingURL=ellipsis-vertical.js.map\n","/**\n * @license lucide-react v0.555.0 - ISC\n *\n * This source code is licensed under the ISC license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport createLucideIcon from '../createLucideIcon.js';\n\nconst __iconNode = [[\"path\", { d: \"M21 12a9 9 0 1 1-6.219-8.56\", key: \"13zald\" }]];\nconst LoaderCircle = createLucideIcon(\"loader-circle\", __iconNode);\n\nexport { __iconNode, LoaderCircle as default };\n//# sourceMappingURL=loader-circle.js.map\n","/**\n * @license lucide-react v0.555.0 - ISC\n *\n * This source code is licensed under the ISC license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport createLucideIcon from '../createLucideIcon.js';\n\nconst __iconNode = [\n [\"path\", { d: \"M4 5h16\", key: \"1tepv9\" }],\n [\"path\", { d: \"M4 12h16\", key: \"1lakjw\" }],\n [\"path\", { d: \"M4 19h16\", key: \"1djgab\" }]\n];\nconst Menu = createLucideIcon(\"menu\", __iconNode);\n\nexport { __iconNode, Menu as default };\n//# sourceMappingURL=menu.js.map\n","/**\n * @license lucide-react v0.555.0 - ISC\n *\n * This source code is licensed under the ISC license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport createLucideIcon from '../createLucideIcon.js';\n\nconst __iconNode = [\n [\"path\", { d: \"M5 12h14\", key: \"1ays0h\" }],\n [\"path\", { d: \"M12 5v14\", key: \"s699le\" }]\n];\nconst Plus = createLucideIcon(\"plus\", __iconNode);\n\nexport { __iconNode, Plus as default };\n//# sourceMappingURL=plus.js.map\n","import type {\n ChatOut,\n ChatRequest,\n ChatSummaryPage,\n ChatUpdate,\n ListChatsParams,\n ListModelsParams,\n ModelOut,\n ModelPage,\n} from '../types/cuadra';\n\n/**\n * SSE Chunk types for streaming responses\n */\nexport interface SSEChunk {\n type?: string;\n content?: string;\n chatId?: string;\n id?: string; // Chat/message ID\n delta?: string; // Delta content (incremental text)\n finished?: boolean; // Whether the stream is finished\n message?: {\n role: string;\n content: string;\n };\n usage?: {\n inputTokens: number;\n outputTokens: number;\n totalTokens: number;\n cost?: number | null;\n };\n done?: boolean;\n}\n\n/**\n * CuadraChatClient - API client for Cuadra AI REST API\n * Handles authentication, HTTP requests, and SSE streaming\n */\nexport class CuadraChatClient {\n private baseUrl: string;\n private sessionToken: string | null = null;\n private isProxyMode: boolean = false;\n\n constructor(baseUrl: string, sessionToken?: string, isProxyMode: boolean = false) {\n this.baseUrl = baseUrl.replace(/\\/$/, ''); // Remove trailing slash\n this.isProxyMode = isProxyMode;\n if (sessionToken) {\n this.sessionToken = sessionToken;\n }\n }\n\n /**\n * Set or update the session token\n */\n setSessionToken(token: string | null): void {\n this.sessionToken = token;\n }\n\n /**\n * Create or continue a chat with streaming support\n * Returns a ReadableStream for SSE parsing\n */\n private getUrl(endpoint: string): string {\n if (this.isProxyMode) {\n // Proxy mode: remove /v1 prefix\n const path = `${this.baseUrl}${endpoint.replace('/v1', '')}`;\n // If baseUrl is relative, return as-is; otherwise construct full URL\n if (path.startsWith('/') || path.startsWith('./')) {\n return path;\n }\n return path;\n }\n return `${this.baseUrl}${endpoint}`;\n }\n\n async createOrContinueChat(\n request: ChatRequest,\n abortSignal?: AbortSignal,\n ): Promise<ReadableStream<Uint8Array>> {\n const url = this.getUrl('/v1/chats');\n \n // Generate idempotency key for create operation\n const idempotencyKey = this.generateIdempotencyKey();\n \n const headers: Record<string, string> = {\n 'Content-Type': 'application/json',\n 'Idempotency-Key': idempotencyKey,\n };\n\n if (this.sessionToken) {\n headers['Authorization'] = `Bearer ${this.sessionToken}`;\n }\n\n // Ensure stream is true for streaming\n const body: ChatRequest = {\n ...request,\n stream: true,\n };\n\n const response = await fetch(url, {\n method: 'POST',\n headers,\n body: JSON.stringify(body),\n signal: abortSignal,\n });\n\n if (!response.ok) {\n const errorData = await response.json().catch(() => ({}));\n throw new Error(\n errorData.detail ||\n errorData.message ||\n `API error: ${response.status} ${response.statusText}`,\n );\n }\n\n if (!response.body) {\n throw new Error('Response body is null');\n }\n\n return response.body;\n }\n\n /**\n * Get a specific chat by ID\n */\n async getChat(chatId: string): Promise<ChatOut> {\n const url = this.getUrl(`/v1/chats/${chatId}`);\n const headers: Record<string, string> = {\n 'Content-Type': 'application/json',\n };\n\n if (this.sessionToken) {\n headers['Authorization'] = `Bearer ${this.sessionToken}`;\n }\n\n const response = await fetch(url, {\n method: 'GET',\n headers,\n });\n\n if (!response.ok) {\n const errorData = await response.json().catch(() => ({}));\n throw new Error(\n errorData.detail ||\n errorData.message ||\n `API error: ${response.status} ${response.statusText}`,\n );\n }\n\n return response.json();\n }\n\n /**\n * List chats with pagination\n */\n async listChats(params?: ListChatsParams): Promise<ChatSummaryPage> {\n const baseUrl = this.getUrl('/v1/chats');\n // Handle relative URLs (for proxy mode)\n const url = baseUrl.startsWith('/') || baseUrl.startsWith('./')\n ? new URL(baseUrl, window.location.origin)\n : new URL(baseUrl);\n \n if (params?.limit) {\n url.searchParams.set('limit', params.limit.toString());\n }\n if (params?.cursor) {\n url.searchParams.set('cursor', params.cursor);\n }\n if (params?.['expand[]']) {\n params['expand[]'].forEach((expand) => {\n url.searchParams.append('expand[]', expand);\n });\n }\n\n const headers: Record<string, string> = {\n 'Content-Type': 'application/json',\n };\n\n if (this.sessionToken) {\n headers['Authorization'] = `Bearer ${this.sessionToken}`;\n }\n\n const response = await fetch(url.toString(), {\n method: 'GET',\n headers,\n });\n\n if (!response.ok) {\n const errorData = await response.json().catch(() => ({}));\n throw new Error(\n errorData.detail ||\n errorData.message ||\n `API error: ${response.status} ${response.statusText}`,\n );\n }\n\n return response.json();\n }\n\n /**\n * Generate a UUID v4 idempotency key\n */\n private generateIdempotencyKey(): string {\n try {\n if (typeof crypto !== 'undefined' && crypto.randomUUID) {\n return crypto.randomUUID();\n }\n } catch {\n // Fallback to manual UUID v4 generation\n }\n // Fallback: Generate UUID v4 format manually\n const generateHex = (count: number): string => {\n return Array.from({ length: count }, () => Math.floor(Math.random() * 16).toString(16)).join('');\n };\n const generateVariant = (): string => {\n const variants = ['8', '9', 'a', 'b'];\n return variants[Math.floor(Math.random() * variants.length)];\n };\n return `${generateHex(8)}-${generateHex(4)}-4${generateHex(3)}-${generateVariant()}${generateHex(3)}-${generateHex(12)}`;\n }\n\n /**\n * Update a chat\n */\n async updateChat(chatId: string, update: ChatUpdate): Promise<ChatOut> {\n const endpoint = `/v1/chats/${chatId}`;\n const baseUrl = this.getUrl(endpoint);\n \n // Handle relative URLs (for proxy mode)\n const url = baseUrl.startsWith('/') || baseUrl.startsWith('./')\n ? new URL(baseUrl, window.location.origin)\n : new URL(baseUrl);\n \n // Generate idempotency key for update operation\n const idempotencyKey = this.generateIdempotencyKey();\n \n const headers: HeadersInit = {\n 'Content-Type': 'application/json',\n 'Idempotency-Key': idempotencyKey,\n };\n\n if (this.sessionToken) {\n (headers as Record<string, string>)['Authorization'] = `Bearer ${this.sessionToken}`;\n }\n\n const response = await fetch(url.toString(), {\n method: 'PATCH',\n headers,\n body: JSON.stringify(update),\n });\n\n if (!response.ok) {\n const errorText = await response.text();\n let errorData: { detail?: string; message?: string } = {};\n try {\n errorData = JSON.parse(errorText) as { detail?: string; message?: string };\n } catch {\n errorData = { detail: errorText };\n }\n throw new Error(\n errorData.detail ||\n errorData.message ||\n `API error: ${response.status} ${response.statusText}`,\n );\n }\n\n // Handle empty responses (e.g., 204 No Content)\n if (response.status === 204) {\n return {} as ChatOut;\n }\n\n const text = await response.text();\n if (!text) {\n return {} as ChatOut;\n }\n\n try {\n return JSON.parse(text);\n } catch {\n return {} as ChatOut;\n }\n }\n\n /**\n * Delete a chat\n */\n async deleteChat(chatId: string): Promise<void> {\n const endpoint = `/v1/chats/${chatId}`;\n const baseUrl = this.getUrl(endpoint);\n \n // Handle relative URLs (for proxy mode)\n const url = baseUrl.startsWith('/') || baseUrl.startsWith('./')\n ? new URL(baseUrl, window.location.origin)\n : new URL(baseUrl);\n \n // Generate idempotency key for delete operation\n const idempotencyKey = this.generateIdempotencyKey();\n \n const headers: HeadersInit = {\n 'Content-Type': 'application/json',\n 'Idempotency-Key': idempotencyKey,\n };\n\n if (this.sessionToken) {\n (headers as Record<string, string>)['Authorization'] = `Bearer ${this.sessionToken}`;\n }\n\n const response = await fetch(url.toString(), {\n method: 'DELETE',\n headers,\n });\n\n if (!response.ok) {\n const errorData = await response.json().catch(() => ({}));\n throw new Error(\n errorData.detail ||\n errorData.message ||\n `API error: ${response.status} ${response.statusText}`,\n );\n }\n }\n\n /**\n * List available models\n */\n async listModels(params?: ListModelsParams): Promise<ModelPage> {\n const baseUrl = this.getUrl('/v1/models');\n // Handle relative URLs (for proxy mode)\n const url = baseUrl.startsWith('/') || baseUrl.startsWith('./')\n ? new URL(baseUrl, window.location.origin)\n : new URL(baseUrl);\n \n if (params?.limit) {\n url.searchParams.set('limit', params.limit.toString());\n }\n if (params?.cursor) {\n url.searchParams.set('cursor', params.cursor);\n }\n if (params?.['expand[]']) {\n params['expand[]'].forEach((expand) => {\n url.searchParams.append('expand[]', expand);\n });\n }\n\n const headers: Record<string, string> = {\n 'Content-Type': 'application/json',\n };\n\n if (this.sessionToken) {\n headers['Authorization'] = `Bearer ${this.sessionToken}`;\n }\n\n const response = await fetch(url.toString(), {\n method: 'GET',\n headers,\n });\n\n if (!response.ok) {\n const errorData = await response.json().catch(() => ({}));\n throw new Error(\n errorData.detail ||\n errorData.message ||\n `API error: ${response.status} ${response.statusText}`,\n );\n }\n\n return response.json();\n }\n\n /**\n * Get a specific model by ID\n */\n async getModel(modelId: string): Promise<ModelOut> {\n const url = this.getUrl(`/v1/models/${modelId}`);\n const headers: Record<string, string> = {\n 'Content-Type': 'application/json',\n };\n\n if (this.sessionToken) {\n headers['Authorization'] = `Bearer ${this.sessionToken}`;\n }\n\n const response = await fetch(url, {\n method: 'GET',\n headers,\n });\n\n if (!response.ok) {\n const errorData = await response.json().catch(() => ({}));\n throw new Error(\n errorData.detail ||\n errorData.message ||\n `API error: ${response.status} ${response.statusText}`,\n );\n }\n\n return response.json();\n }\n}\n\n/**\n * Parse SSE stream into chunks\n */\nexport async function* parseSSEStream(\n stream: ReadableStream<Uint8Array>,\n abortSignal?: AbortSignal,\n): AsyncGenerator<SSEChunk> {\n const reader = stream.getReader();\n const decoder = new TextDecoder();\n let buffer = '';\n\n try {\n while (true) {\n if (abortSignal?.aborted) {\n reader.cancel();\n break;\n }\n\n const { done, value } = await reader.read();\n if (done) break;\n\n buffer += decoder.decode(value, { stream: true });\n const lines = buffer.split('\\n\\n');\n buffer = lines.pop() || '';\n\n for (const line of lines) {\n if (line.startsWith('data: ')) {\n const data = line.slice(6);\n if (data.trim() === '[DONE]') {\n yield { done: true };\n continue;\n }\n try {\n const parsed = JSON.parse(data);\n yield parsed;\n } catch {\n // Skip invalid JSON\n }\n }\n }\n }\n } finally {\n reader.releaseLock();\n }\n}\n\n","import type { ThreadMessage } from '@assistant-ui/react';\nimport type { MessageCreate } from '../types/cuadra';\n\n/**\n * Convert assistant-ui ThreadMessage to Cuadra API MessageCreate format\n */\nexport function convertToCuadraMessages(\n messages: readonly ThreadMessage[],\n): MessageCreate[] {\n return messages.map((msg) => {\n // Extract text content from assistant-ui message format\n let content = '';\n\n if (typeof msg.content === 'string') {\n content = msg.content;\n } else if (Array.isArray(msg.content)) {\n // Find text content in content array\n const textContent = msg.content.find((c) => c.type === 'text');\n if (\n textContent &&\n typeof textContent === 'object' &&\n 'text' in textContent\n ) {\n content = textContent.text as string;\n }\n }\n\n return {\n role: msg.role as 'system' | 'user' | 'assistant',\n content,\n };\n });\n}\n\n/**\n * Convert Cuadra API MessageOut to assistant-ui ThreadMessage format\n */\nexport function convertFromCuadraMessage(\n msg: {\n role: string;\n content: string;\n id: string;\n createdAt: string;\n },\n): ThreadMessage {\n return {\n id: msg.id,\n role: msg.role as 'user' | 'assistant' | 'system',\n content: [\n {\n type: 'text' as const,\n text: msg.content,\n },\n ],\n createdAt: new Date(msg.createdAt),\n metadata: {\n custom: {},\n },\n ...(msg.role === 'assistant' && {\n status: {\n type: 'complete' as const,\n reason: 'stop' as const,\n },\n metadata: {\n unstable_state: null,\n unstable_annotations: [],\n unstable_data: [],\n steps: [],\n custom: {},\n },\n }),\n ...(msg.role === 'user' && {\n attachments: [],\n }),\n } as ThreadMessage;\n}\n\n","import type { ChatModelAdapter, ChatModelRunOptions } from '@assistant-ui/react';\nimport { CuadraChatClient, parseSSEStream, type SSEChunk } from '../lib/cuadraChatClient';\nimport { convertToCuadraMessages } from './messageConverter';\n\nexport interface ChatModelAdapterOptions {\n modelId?: string | null; // Optional - backend can resolve model ID in proxy mode\n systemPrompt?: string;\n ephemeral?: boolean;\n onChatCreated?: (chatId: string) => void;\n onUserMessage?: () => void; // Called when a user message is sent\n onThreadIdUpdate?: (localThreadId: string, serverChatId: string) => void; // Called when chat ID is received to update thread mapping\n}\n\n/**\n * Creates a ChatModelAdapter for LocalRuntime that connects to Cuadra API\n * Handles streaming responses and converts between assistant-ui and API formats\n */\nexport function createChatModelAdapter(\n client: CuadraChatClient,\n options: ChatModelAdapterOptions,\n): ChatModelAdapter {\n const { modelId, systemPrompt, ephemeral, onChatCreated, onUserMessage, onThreadIdUpdate } = options;\n \n return {\n async *run(options: ChatModelRunOptions) {\n const { messages, abortSignal, context } = options;\n \n // Get current thread ID from context if available\n const currentThreadId = (context as { threadId?: string })?.threadId;\n\n onUserMessage?.();\n\n // Convert assistant-ui ThreadMessage format to API MessageCreate format\n const apiMessages = convertToCuadraMessages(messages);\n\n // Create request\n // Note: context.threadId might not exist in ModelContext, \n // thread ID is managed by the runtime\n // modelId is optional - backend can resolve it in proxy mode\n const request: {\n messages: typeof apiMessages;\n chatId: null;\n modelId?: string | null;\n systemPrompt?: string;\n ephemeral?: boolean;\n stream: boolean;\n } = {\n messages: apiMessages,\n chatId: null, // Thread ID will be set by runtime if needed\n systemPrompt,\n ephemeral,\n stream: true,\n };\n \n // Only include modelId if provided (backend may resolve it)\n if (modelId && modelId.trim() !== '') {\n request.modelId = modelId;\n }\n\n // Stream from API\n const stream = await client.createOrContinueChat(request, abortSignal);\n\n let accumulatedText = '';\n let chatId: string | undefined;\n\n // Parse SSE stream\n for await (const chunk of parseSSEStream(stream, abortSignal)) {\n // Check abort signal\n if (abortSignal?.aborted) {\n throw new Error('Request aborted');\n }\n\n // Handle chat ID from chunk\n const chunkId = (chunk as { id?: string }).id;\n if (chunkId && !chatId) {\n chatId = chunkId;\n onChatCreated?.(chunkId);\n \n // Update thread ID mapping if we have a current thread ID\n if (currentThreadId && onThreadIdUpdate) {\n onThreadIdUpdate(currentThreadId, chunkId);\n }\n }\n\n // Handle delta format (current API format: {\"id\": \"...\", \"delta\": \"...\", \"finished\": false})\n const delta = (chunk as { delta?: string }).delta;\n if (delta !== undefined && delta !== null) {\n accumulatedText += delta;\n }\n\n // Handle legacy formats for compatibility\n if (chunk.type === 'message' || chunk.content) {\n const content = chunk.content || '';\n accumulatedText += content;\n }\n\n // Handle message object format\n if (chunk.message) {\n accumulatedText += chunk.message.content || '';\n }\n\n // Handle tool calls (if API supports them in future)\n // Note: Current API schema doesn't include tools, but structure is ready\n if ((chunk as SSEChunk & { tool_calls?: unknown[] }).tool_calls) {\n // Process tool calls when API supports them\n // This is a placeholder for future implementation\n }\n\n // Check if finished\n const finished = (chunk as { finished?: boolean }).finished;\n if (finished) {\n // Stream is complete, yield final accumulated text\n if (accumulatedText) {\n yield {\n content: [{ type: 'text', text: accumulatedText }],\n };\n }\n break;\n }\n\n // Yield incremental updates as we receive deltas\n if (accumulatedText) {\n yield {\n content: [{ type: 'text', text: accumulatedText }],\n };\n }\n }\n\n // Final yield with accumulated text\n if (accumulatedText) {\n yield {\n content: [{ type: 'text', text: accumulatedText }],\n };\n }\n },\n };\n}\n\n","import type {\n unstable_RemoteThreadListAdapter as RemoteThreadListAdapter,\n ThreadMessage,\n ThreadHistoryAdapter,\n} from '@assistant-ui/react';\nimport { CuadraChatClient } from '../lib/cuadraChatClient';\nimport { convertFromCuadraMessage } from './messageConverter';\nimport React from 'react';\nimport { RuntimeAdapterProvider, useThreadListItem } from '@assistant-ui/react';\n\n/**\n * Store mapping of local thread IDs to server chat IDs\n * This is used to update remoteId when server chat ID is received\n */\nexport const localToRemoteIdMap = new Map<string, string>();\n\n/**\n * Creates a RemoteThreadListAdapter for LocalRuntime that connects to Cuadra API\n * Maps API chat format to assistant-ui thread format\n */\nexport function createThreadListAdapter(\n client: CuadraChatClient,\n onChatIdReceived?: (localThreadId: string, serverChatId: string) => void,\n): RemoteThreadListAdapter & {\n updateRemoteId: (localThreadId: string, serverChatId: string) => void;\n} {\n return {\n async list() {\n const all = [];\n const limit = 50;\n let cursor: string | undefined = undefined;\n let safety = 0;\n\n // Fetch all chats with pagination\n do {\n const response = await client.listChats({ limit, cursor });\n const items = response.items || [];\n\n if (Array.isArray(items) && items.length > 0) {\n all.push(...items);\n }\n\n cursor = response.nextCursor || undefined;\n safety++;\n } while (cursor && safety < 50);\n\n // Map to assistant-ui thread format\n // Filter out deleted chats and chats without IDs\n const threads = all\n .map((chat) => {\n const id = chat.id;\n // Skip if no ID or if deleted\n if (!id || chat.deletedAt) return null;\n\n return {\n status: 'regular' as const,\n remoteId: id,\n title: chat.title || 'New Chat',\n createdAt: chat.createdAt ? new Date(chat.createdAt) : new Date(),\n updatedAt: chat.updatedAt ? new Date(chat.updatedAt) : new Date(),\n };\n })\n .filter((t) => t !== null) as Array<{\n status: 'regular' | 'archived';\n remoteId: string;\n title?: string;\n createdAt: Date;\n updatedAt: Date;\n }>;\n\n return { threads };\n },\n\n async initialize(threadId: string) {\n // For LocalRuntime, threadId is already generated locally (e.g., __LOCALID_...)\n // Check if we have a server chat ID for this local thread ID\n const serverChatId = localToRemoteIdMap.get(threadId);\n const remoteId = serverChatId || threadId;\n\n return { remoteId, externalId: undefined };\n },\n\n async rename(remoteId: string, newTitle: string) {\n await client.updateChat(remoteId, { title: newTitle });\n },\n\n async archive(_remoteId: string) {\n // Cuadra API uses soft delete, which we can treat as archive\n // If API adds explicit archive support, implement here\n },\n\n async unarchive(_remoteId: string) {\n // If Cuadra supports unarchive, implement here\n // Currently not supported\n },\n\n async delete(remoteId: string) {\n await client.deleteChat(remoteId);\n },\n\n async generateTitle(_remoteId: string, _messages: readonly ThreadMessage[]) {\n // Title generation not yet supported by Cuadra API\n // Return empty stream\n return new ReadableStream();\n },\n\n async fetch(threadId: string) {\n try {\n const chat = await client.getChat(threadId);\n const id = chat.id || threadId;\n\n return {\n status: 'regular' as const,\n remoteId: id,\n title: chat.title || 'Chat',\n createdAt: chat.createdAt ? new Date(chat.createdAt) : new Date(),\n updatedAt: chat.updatedAt ? new Date(chat.updatedAt) : new Date(),\n };\n } catch {\n // Return default if fetch fails\n return {\n status: 'regular' as const,\n remoteId: threadId,\n createdAt: new Date(),\n updatedAt: new Date(),\n };\n }\n },\n\n // Add a method to update the remoteId mapping when chat ID is received\n updateRemoteId(localThreadId: string, serverChatId: string) {\n localToRemoteIdMap.set(localThreadId, serverChatId);\n onChatIdReceived?.(localThreadId, serverChatId);\n },\n\n // Provider component that adds thread-specific history adapter\n unstable_Provider: ({ children }: { children?: React.ReactNode }) => {\n const threadListItem = useThreadListItem();\n const remoteId = threadListItem?.remoteId;\n\n // Create thread-specific history adapter\n const history = React.useMemo<ThreadHistoryAdapter>(\n () => ({\n async load() {\n if (!remoteId) return { messages: [] } as any;\n\n try {\n // Fetch chat with messages expanded\n const chat = await client.getChat(remoteId);\n \n if (!chat.messages || chat.messages.length === 0) {\n return { messages: [] } as any;\n }\n\n // Convert API messages to assistant-ui format\n const messages = chat.messages.map((msg) => convertFromCuadraMessage(msg));\n\n return { messages } as any;\n } catch (error) {\n console.error('Failed to load messages for thread:', remoteId, error);\n return { messages: [] } as any;\n }\n },\n\n async append(message) {\n // Messages are automatically persisted by the API when sent\n // This method is called by the runtime but we don't need to do anything\n // since messages are already saved via the chat API\n // If you need to explicitly save messages, you could implement an API endpoint here\n },\n }),\n [remoteId, client],\n );\n\n const adapters = React.useMemo(() => ({ history }), [history]);\n\n return (\n <RuntimeAdapterProvider adapters={adapters}>\n {children}\n </RuntimeAdapterProvider>\n );\n },\n };\n}\n\n","import React, { useCallback, useEffect, useMemo, useState } from 'react';\nimport {\n AssistantRuntimeProvider,\n unstable_useRemoteThreadListRuntime,\n useLocalRuntime,\n} from '@assistant-ui/react';\nimport { CuadraChatClient } from '../lib/cuadraChatClient';\nimport { createChatModelAdapter } from '../adapters/chatModelAdapter';\nimport { createThreadListAdapter } from '../adapters/threadListAdapter';\n\nexport interface CuadraRuntimeProviderProps {\n children: React.ReactNode;\n baseUrl: string;\n sessionToken?: string | null;\n isProxyMode?: boolean; // If true, uses proxy URL patterns (removes /v1 prefix)\n\n // Mode selection\n mode?: 'singleChat' | 'multiChat'; // Default: 'multiChat'\n\n // Model configuration\n modelMode?: 'selector' | 'fixed'; // Default: 'fixed'\n modelId?: string; // Required if modelMode === 'fixed'\n onModelChange?: (modelId: string) => void; // Called when model changes (selector mode)\n\n // Chat configuration\n ephemeral?: boolean; // Default: false - creates temporary chats that auto-delete\n systemPrompt?: string;\n\n // Thread configuration\n initialThreadId?: string; // Load existing thread (multiChat mode)\n\n // Callbacks\n onError?: (error: Error) => void;\n onChatCreated?: (chatId: string) => void;\n onUserMessage?: () => void; // Called when a user message is sent\n onThreadIdUpdate?: (\n oldThreadId: string,\n newThreadId: string,\n ) => void; // Callback when thread ID is updated from local to server\n onChatsLoaded?: () => void; // Callback when chats/thread list is loaded\n}\n\n/**\n * Main provider component that sets up assistant-ui runtime with Cuadra API\n * Supports single/multi chat modes, fixed/selector model modes, and ephemeral chats\n */\nexport function CuadraRuntimeProvider({\n children,\n baseUrl,\n sessionToken,\n isProxyMode = false,\n mode = 'multiChat',\n modelId,\n onModelChange: _onModelChange,\n ephemeral = false,\n systemPrompt,\n initialThreadId,\n onError,\n onChatCreated,\n onUserMessage,\n onThreadIdUpdate,\n onChatsLoaded,\n}: CuadraRuntimeProviderProps) {\n // Create API client\n const client = useMemo(\n () => new CuadraChatClient(baseUrl, sessionToken || undefined, isProxyMode),\n [baseUrl, sessionToken, isProxyMode],\n );\n\n // Track selected model ID (syncs with prop)\n const [selectedModelId, setSelectedModelId] = useState<string | null>(modelId || null);\n\n // Sync selectedModelId with modelId prop\n useEffect(() => {\n if (modelId) {\n setSelectedModelId(modelId);\n }\n }, [modelId]);\n\n // Handle chat created callback\n const handleChatCreated = useCallback(\n (chatId: string) => {\n onChatCreated?.(chatId);\n },\n [onChatCreated],\n );\n\n // Handle thread ID update\n const handleThreadIdUpdate = useCallback(\n (oldId: string, newId: string) => {\n onThreadIdUpdate?.(oldId, newId);\n },\n [onThreadIdUpdate],\n );\n\n // For singleChat mode, create model adapter and use useLocalRuntime\n const modelAdapter = useMemo(() => {\n return createChatModelAdapter(client, {\n modelId: selectedModelId || undefined, // Pass undefined if not set (backend resolves it)\n systemPrompt,\n ephemeral,\n onChatCreated: handleChatCreated,\n onUserMessage,\n });\n }, [client, selectedModelId, systemPrompt, ephemeral, handleChatCreated, onUserMessage]);\n\n if (mode === 'singleChat') {\n return (\n <SingleChatProvider modelAdapter={modelAdapter}>\n {children}\n </SingleChatProvider>\n );\n }\n\n // For multiChat mode, use RemoteThreadListRuntime\n // Pass adapter options instead of the adapter itself so we can add thread ID update callback\n return (\n <MultiChatProvider\n client={client}\n modelAdapterOptions={{\n modelId: selectedModelId || undefined,\n systemPrompt,\n ephemeral,\n onChatCreated: handleChatCreated,\n onUserMessage,\n }}\n initialThreadId={initialThreadId}\n onChatsLoaded={onChatsLoaded}\n onThreadIdUpdate={handleThreadIdUpdate}\n onError={onError}\n >\n {children}\n </MultiChatProvider>\n );\n}\n\n/**\n * Internal provider for singleChat mode using useLocalRuntime\n */\nfunction SingleChatProvider({\n modelAdapter,\n children,\n}: {\n modelAdapter: ReturnType<typeof createChatModelAdapter>;\n children: React.ReactNode;\n}) {\n // Always call the hook (required by React rules of hooks)\n const localRuntime = useLocalRuntime(modelAdapter);\n\n // Always render the provider so children can access runtime context via useThreadRuntime()\n return (\n <AssistantRuntimeProvider runtime={localRuntime}>\n {children}\n </AssistantRuntimeProvider>\n );\n}\n\n/**\n * Internal provider for multiChat mode using RemoteThreadListRuntime\n */\nfunction MultiChatProvider({\n client,\n modelAdapterOptions,\n initialThreadId: _initialThreadId,\n onChatsLoaded,\n onThreadIdUpdate,\n onError: _onError,\n children,\n}: {\n client: CuadraChatClient;\n modelAdapterOptions: {\n modelId?: string | null;\n systemPrompt?: string;\n ephemeral?: boolean;\n onChatCreated?: (chatId: string) => void;\n onUserMessage?: () => void;\n };\n initialThreadId?: string;\n onChatsLoaded?: () => void;\n onThreadIdUpdate?: (oldId: string, newId: string) => void;\n onError?: (error: Error) => void;\n children: React.ReactNode;\n}) {\n // Create thread list adapter\n const threadListAdapter = useMemo(() => {\n return createThreadListAdapter(client, (localThreadId, serverChatId) => {\n onThreadIdUpdate?.(localThreadId, serverChatId);\n });\n }, [client, onThreadIdUpdate]);\n\n // Create a callback to update thread ID mapping when chat is created\n const handleThreadIdUpdateFromAdapter = useCallback(\n (localThreadId: string, serverChatId: string) => {\n // Update the adapter's remote ID mapping\n if (threadListAdapter.updateRemoteId) {\n threadListAdapter.updateRemoteId(localThreadId, serverChatId);\n }\n // Also call the prop callback\n onThreadIdUpdate?.(localThreadId, serverChatId);\n },\n [threadListAdapter, onThreadIdUpdate],\n );\n\n // Wrap list method to call onChatsLoaded\n const wrappedAdapter = useMemo(() => {\n return {\n ...threadListAdapter,\n async list() {\n const result = await threadListAdapter.list();\n // Call onChatsLoaded on initial load\n onChatsLoaded?.();\n return result;\n },\n };\n }, [threadListAdapter, onChatsLoaded]);\n\n // Expose adapter globally for external access (e.g., rename/delete)\n useEffect(() => {\n (window as Window & { __cuadraThreadListAdapter?: typeof wrappedAdapter }).__cuadraThreadListAdapter =\n wrappedAdapter;\n (window as Window & { __cuadraThreadListRuntime?: unknown }).__cuadraThreadListRuntime = null;\n }, [wrappedAdapter]);\n\n // Create model adapter with thread ID update callback for multiChat mode\n const modelAdapter = useMemo(() => {\n return createChatModelAdapter(client, {\n ...modelAdapterOptions,\n onThreadIdUpdate: handleThreadIdUpdateFromAdapter,\n });\n }, [client, modelAdapterOptions, handleThreadIdUpdateFromAdapter]);\n\n // Create runtime hook that uses the model adapter\n const runtimeHook = useCallback(() => {\n return useLocalRuntime(modelAdapter);\n }, [modelAdapter]);\n\n // Use RemoteThreadListRuntime hook\n const runtime = unstable_useRemoteThreadListRuntime({\n adapter: wrappedAdapter,\n runtimeHook,\n });\n\n // Expose runtime globally for external refresh\n useEffect(() => {\n (window as Window & { __cuadraThreadListRuntime?: typeof runtime }).__cuadraThreadListRuntime =\n runtime;\n }, [runtime]);\n\n return (\n <AssistantRuntimeProvider runtime={runtime}>{children}</AssistantRuntimeProvider>\n );\n}\n","/**\n * Count how often a character (or substring) is used in a string.\n *\n * @param {string} value\n * Value to search in.\n * @param {string} character\n * Character (or substring) to look for.\n * @return {number}\n * Number of times `character` occurred in `value`.\n */\nexport function ccount(value, character) {\n const source = String(value)\n\n if (typeof character !== 'string') {\n throw new TypeError('Expected character')\n }\n\n let count = 0\n let index = source.indexOf(character)\n\n while (index !== -1) {\n count++\n index = source.indexOf(character, index + character.length)\n }\n\n return count\n}\n","/**\n * @import {Code} from 'micromark-util-types'\n */\n\n/**\n * Check whether the character code represents an ASCII alpha (`a` through `z`,\n * case insensitive).\n *\n * An **ASCII alpha** is an ASCII upper alpha or ASCII lower alpha.\n *\n * An **ASCII upper alpha** is a character in the inclusive range U+0041 (`A`)\n * to U+005A (`Z`).\n *\n * An **ASCII lower alpha** is a character in the inclusive range U+0061 (`a`)\n * to U+007A (`z`).\n *\n * @param code\n * Code.\n * @returns {boolean}\n * Whether it matches.\n */\nexport const asciiAlpha = regexCheck(/[A-Za-z]/);\n\n/**\n * Check whether the character code represents an ASCII alphanumeric (`a`\n * through `z`, case insensitive, or `0` through `9`).\n *\n * An **ASCII alphanumeric** is an ASCII digit (see `asciiDigit`) or ASCII alpha\n * (see `asciiAlpha`).\n *\n * @param code\n * Code.\n * @returns {boolean}\n * Whether it matches.\n */\nexport const asciiAlphanumeric = regexCheck(/[\\dA-Za-z]/);\n\n/**\n * Check whether the character code represents an ASCII atext.\n *\n * atext is an ASCII alphanumeric (see `asciiAlphanumeric`), or a character in\n * the inclusive ranges U+0023 NUMBER SIGN (`#`) to U+0027 APOSTROPHE (`'`),\n * U+002A ASTERISK (`*`), U+002B PLUS SIGN (`+`), U+002D DASH (`-`), U+002F\n * SLASH (`/`), U+003D EQUALS TO (`=`), U+003F QUESTION MARK (`?`), U+005E\n * CARET (`^`) to U+0060 GRAVE ACCENT (`` ` ``), or U+007B LEFT CURLY BRACE\n * (`{`) to U+007E TILDE (`~`).\n *\n * See:\n * **\\[RFC5322]**:\n * [Internet Message Format](https://tools.ietf.org/html/rfc5322).\n * P. Resnick.\n * IETF.\n *\n * @param code\n * Code.\n * @returns {boolean}\n * Whether it matches.\n */\nexport const asciiAtext = regexCheck(/[#-'*+\\--9=?A-Z^-~]/);\n\n/**\n * Check whether a character code is an ASCII control character.\n *\n * An **ASCII control** is a character in the inclusive range U+0000 NULL (NUL)\n * to U+001F (US), or U+007F (DEL).\n *\n * @param {Code} code\n * Code.\n * @returns {boolean}\n * Whether it matches.\n */\nexport function asciiControl(code) {\n return (\n // Special whitespace codes (which have negative values), C0 and Control\n // character DEL\n code !== null && (code < 32 || code === 127)\n );\n}\n\n/**\n * Check whether the character code represents an ASCII digit (`0` through `9`).\n *\n * An **ASCII digit** is a character in the inclusive range U+0030 (`0`) to\n * U+0039 (`9`).\n *\n * @param code\n * Code.\n * @returns {boolean}\n * Whether it matches.\n */\nexport const asciiDigit = regexCheck(/\\d/);\n\n/**\n * Check whether the character code represents an ASCII hex digit (`a` through\n * `f`, case insensitive, or `0` through `9`).\n *\n * An **ASCII hex digit** is an ASCII digit (see `asciiDigit`), ASCII upper hex\n * digit, or an ASCII lower hex digit.\n *\n * An **ASCII upper hex digit** is a character in the inclusive range U+0041\n * (`A`) to U+0046 (`F`).\n *\n * An **ASCII lower hex digit** is a character in the inclusive range U+0061\n * (`a`) to U+0066 (`f`).\n *\n * @param code\n * Code.\n * @returns {boolean}\n * Whether it matches.\n */\nexport const asciiHexDigit = regexCheck(/[\\dA-Fa-f]/);\n\n/**\n * Check whether the character code represents ASCII punctuation.\n *\n * An **ASCII punctuation** is a character in the inclusive ranges U+0021\n * EXCLAMATION MARK (`!`) to U+002F SLASH (`/`), U+003A COLON (`:`) to U+0040 AT\n * SIGN (`@`), U+005B LEFT SQUARE BRACKET (`[`) to U+0060 GRAVE ACCENT\n * (`` ` ``), or U+007B LEFT CURLY BRACE (`{`) to U+007E TILDE (`~`).\n *\n * @param code\n * Code.\n * @returns {boolean}\n * Whether it matches.\n */\nexport const asciiPunctuation = regexCheck(/[!-/:-@[-`{-~]/);\n\n/**\n * Check whether a character code is a markdown line ending.\n *\n * A **markdown line ending** is the virtual characters M-0003 CARRIAGE RETURN\n * LINE FEED (CRLF), M-0004 LINE FEED (LF) and M-0005 CARRIAGE RETURN (CR).\n *\n * In micromark, the actual character U+000A LINE FEED (LF) and U+000D CARRIAGE\n * RETURN (CR) are replaced by these virtual characters depending on whether\n * they occurred together.\n *\n * @param {Code} code\n * Code.\n * @returns {boolean}\n * Whether it matches.\n */\nexport function markdownLineEnding(code) {\n return code !== null && code < -2;\n}\n\n/**\n * Check whether a character code is a markdown line ending (see\n * `markdownLineEnding`) or markdown space (see `markdownSpace`).\n *\n * @param {Code} code\n * Code.\n * @returns {boolean}\n * Whether it matches.\n */\nexport function markdownLineEndingOrSpace(code) {\n return code !== null && (code < 0 || code === 32);\n}\n\n/**\n * Check whether a character code is a markdown space.\n *\n * A **markdown space** is the concrete character U+0020 SPACE (SP) and the\n * virtual characters M-0001 VIRTUAL SPACE (VS) and M-0002 HORIZONTAL TAB (HT).\n *\n * In micromark, the actual character U+0009 CHARACTER TABULATION (HT) is\n * replaced by one M-0002 HORIZONTAL TAB (HT) and between 0 and 3 M-0001 VIRTUAL\n * SPACE (VS) characters, depending on the column at which the tab occurred.\n *\n * @param {Code} code\n * Code.\n * @returns {boolean}\n * Whether it matches.\n */\nexport function markdownSpace(code) {\n return code === -2 || code === -1 || code === 32;\n}\n\n// Size note: removing ASCII from the regex and using `asciiPunctuation` here\n// In fact adds to the bundle size.\n/**\n * Check whether the character code represents Unicode punctuation.\n *\n * A **Unicode punctuation** is a character in the Unicode `Pc` (Punctuation,\n * Connector), `Pd` (Punctuation, Dash), `Pe` (Punctuation, Close), `Pf`\n * (Punctuation, Final quote), `Pi` (Punctuation, Initial quote), `Po`\n * (Punctuation, Other), or `Ps` (Punctuation, Open) categories, or an ASCII\n * punctuation (see `asciiPunctuation`).\n *\n * See:\n * **\\[UNICODE]**:\n * [The Unicode Standard](https://www.unicode.org/versions/).\n * Unicode Consortium.\n *\n * @param code\n * Code.\n * @returns\n * Whether it matches.\n */\nexport const unicodePunctuation = regexCheck(/\\p{P}|\\p{S}/u);\n\n/**\n * Check whether the character code represents Unicode whitespace.\n *\n * Note that this does handle micromark specific markdown whitespace characters.\n * See `markdownLineEndingOrSpace` to check that.\n *\n * A **Unicode whitespace** is a character in the Unicode `Zs` (Separator,\n * Space) category, or U+0009 CHARACTER TABULATION (HT), U+000A LINE FEED (LF),\n * U+000C (FF), or U+000D CARRIAGE RETURN (CR) (**\\[UNICODE]**).\n *\n * See:\n * **\\[UNICODE]**:\n * [The Unicode Standard](https://www.unicode.org/versions/).\n * Unicode Consortium.\n *\n * @param code\n * Code.\n * @returns\n * Whether it matches.\n */\nexport const unicodeWhitespace = regexCheck(/\\s/);\n\n/**\n * Create a code check from a regex.\n *\n * @param {RegExp} regex\n * Expression.\n * @returns {(code: Code) => boolean}\n * Check.\n */\nfunction regexCheck(regex) {\n return check;\n\n /**\n * Check whether a code matches the bound regex.\n *\n * @param {Code} code\n * Character code.\n * @returns {boolean}\n * Whether the character code matches the bound regex.\n */\n function check(code) {\n return code !== null && code > -1 && regex.test(String.fromCharCode(code));\n }\n}","export default function escapeStringRegexp(string) {\n\tif (typeof string !== 'string') {\n\t\tthrow new TypeError('Expected a string');\n\t}\n\n\t// Escape characters with special meaning either inside or outside character sets.\n\t// Use a simple backslash escape when it’s always valid, and a `\\xnn` escape when the simpler form would be disallowed by Unicode patterns’ stricter grammar.\n\treturn string\n\t\t.replace(/[|\\\\{}()[\\]^$+*?.]/g, '\\\\$&')\n\t\t.replace(/-/g, '\\\\x2d');\n}\n","/**\n * @import {Node, Parent} from 'unist'\n */\n\n/**\n * @template Fn\n * @template Fallback\n * @typedef {Fn extends (value: any) => value is infer Thing ? Thing : Fallback} Predicate\n */\n\n/**\n * @callback Check\n * Check that an arbitrary value is a node.\n * @param {unknown} this\n * The given context.\n * @param {unknown} [node]\n * Anything (typically a node).\n * @param {number | null | undefined} [index]\n * The node’s position in its parent.\n * @param {Parent | null | undefined} [parent]\n * The node’s parent.\n * @returns {boolean}\n * Whether this is a node and passes a test.\n *\n * @typedef {Record<string, unknown> | Node} Props\n * Object to check for equivalence.\n *\n * Note: `Node` is included as it is common but is not indexable.\n *\n * @typedef {Array<Props | TestFunction | string> | ReadonlyArray<Props | TestFunction | string> | Props | TestFunction | string | null | undefined} Test\n * Check for an arbitrary node.\n *\n * @callback TestFunction\n * Check if a node passes a test.\n * @param {unknown} this\n * The given context.\n * @param {Node} node\n * A node.\n * @param {number | undefined} [index]\n * The node’s position in its parent.\n * @param {Parent | undefined} [parent]\n * The node’s parent.\n * @returns {boolean | undefined | void}\n * Whether this node passes the test.\n *\n * Note: `void` is included until TS sees no return as `undefined`.\n */\n\n/**\n * Check if `node` is a `Node` and whether it passes the given test.\n *\n * @param {unknown} node\n * Thing to check, typically `Node`.\n * @param {Test} test\n * A check for a specific node.\n * @param {number | null | undefined} index\n * The node’s position in its parent.\n * @param {Parent | null | undefined} parent\n * The node’s parent.\n * @param {unknown} context\n * Context object (`this`) to pass to `test` functions.\n * @returns {boolean}\n * Whether `node` is a node and passes a test.\n */\nexport const is =\n // Note: overloads in JSDoc can’t yet use different `@template`s.\n /**\n * @type {(\n * (<Condition extends ReadonlyArray<string>>(node: unknown, test: Condition, index?: number | null | undefined, parent?: Parent | null | undefined, context?: unknown) => node is Node & {type: Condition[number]}) &\n * (<Condition extends Array<string>>(node: unknown, test: Condition, index?: number | null | undefined, parent?: Parent | null | undefined, context?: unknown) => node is Node & {type: Condition[number]}) &\n * (<Condition extends string>(node: unknown, test: Condition, index?: number | null | undefined, parent?: Parent | null | undefined, context?: unknown) => node is Node & {type: Condition}) &\n * (<Condition extends Props>(node: unknown, test: Condition, index?: number | null | undefined, parent?: Parent | null | undefined, context?: unknown) => node is Node & Condition) &\n * (<Condition extends TestFunction>(node: unknown, test: Condition, index?: number | null | undefined, parent?: Parent | null | undefined, context?: unknown) => node is Node & Predicate<Condition, Node>) &\n * ((node?: null | undefined) => false) &\n * ((node: unknown, test?: null | undefined, index?: number | null | undefined, parent?: Parent | null | undefined, context?: unknown) => node is Node) &\n * ((node: unknown, test?: Test, index?: number | null | undefined, parent?: Parent | null | undefined, context?: unknown) => boolean)\n * )}\n */\n (\n /**\n * @param {unknown} [node]\n * @param {Test} [test]\n * @param {number | null | undefined} [index]\n * @param {Parent | null | undefined} [parent]\n * @param {unknown} [context]\n * @returns {boolean}\n */\n // eslint-disable-next-line max-params\n function (node, test, index, parent, context) {\n const check = convert(test)\n\n if (\n index !== undefined &&\n index !== null &&\n (typeof index !== 'number' ||\n index < 0 ||\n index === Number.POSITIVE_INFINITY)\n ) {\n throw new Error('Expected positive finite index')\n }\n\n if (\n parent !== undefined &&\n parent !== null &&\n (!is(parent) || !parent.children)\n ) {\n throw new Error('Expected parent node')\n }\n\n if (\n (parent === undefined || parent === null) !==\n (index === undefined || index === null)\n ) {\n throw new Error('Expected both parent and index')\n }\n\n return looksLikeANode(node)\n ? check.call(context, node, index, parent)\n : false\n }\n )\n\n/**\n * Generate an assertion from a test.\n *\n * Useful if you’re going to test many nodes, for example when creating a\n * utility where something else passes a compatible test.\n *\n * The created function is a bit faster because it expects valid input only:\n * a `node`, `index`, and `parent`.\n *\n * @param {Test} test\n * * when nullish, checks if `node` is a `Node`.\n * * when `string`, works like passing `(node) => node.type === test`.\n * * when `function` checks if function passed the node is true.\n * * when `object`, checks that all keys in test are in node, and that they have (strictly) equal values.\n * * when `array`, checks if any one of the subtests pass.\n * @returns {Check}\n * An assertion.\n */\nexport const convert =\n // Note: overloads in JSDoc can’t yet use different `@template`s.\n /**\n * @type {(\n * (<Condition extends string>(test: Condition) => (node: unknown, index?: number | null | undefined, parent?: Parent | null | undefined, context?: unknown) => node is Node & {type: Condition}) &\n * (<Condition extends Props>(test: Condition) => (node: unknown, index?: number | null | undefined, parent?: Parent | null | undefined, context?: unknown) => node is Node & Condition) &\n * (<Condition extends TestFunction>(test: Condition) => (node: unknown, index?: number | null | undefined, parent?: Parent | null | undefined, context?: unknown) => node is Node & Predicate<Condition, Node>) &\n * ((test?: null | undefined) => (node?: unknown, index?: number | null | undefined, parent?: Parent | null | undefined, context?: unknown) => node is Node) &\n * ((test?: Test) => Check)\n * )}\n */\n (\n /**\n * @param {Test} [test]\n * @returns {Check}\n */\n function (test) {\n if (test === null || test === undefined) {\n return ok\n }\n\n if (typeof test === 'function') {\n return castFactory(test)\n }\n\n if (typeof test === 'object') {\n return Array.isArray(test)\n ? anyFactory(test)\n : // Cast because `ReadonlyArray` goes into the above but `isArray`\n // narrows to `Array`.\n propertiesFactory(/** @type {Props} */ (test))\n }\n\n if (typeof test === 'string') {\n return typeFactory(test)\n }\n\n throw new Error('Expected function, string, or object as test')\n }\n )\n\n/**\n * @param {Array<Props | TestFunction | string>} tests\n * @returns {Check}\n */\nfunction anyFactory(tests) {\n /** @type {Array<Check>} */\n const checks = []\n let index = -1\n\n while (++index < tests.length) {\n checks[index] = convert(tests[index])\n }\n\n return castFactory(any)\n\n /**\n * @this {unknown}\n * @type {TestFunction}\n */\n function any(...parameters) {\n let index = -1\n\n while (++index < checks.length) {\n if (checks[index].apply(this, parameters)) return true\n }\n\n return false\n }\n}\n\n/**\n * Turn an object into a test for a node with a certain fields.\n *\n * @param {Props} check\n * @returns {Check}\n */\nfunction propertiesFactory(check) {\n const checkAsRecord = /** @type {Record<string, unknown>} */ (check)\n\n return castFactory(all)\n\n /**\n * @param {Node} node\n * @returns {boolean}\n */\n function all(node) {\n const nodeAsRecord = /** @type {Record<string, unknown>} */ (\n /** @type {unknown} */ (node)\n )\n\n /** @type {string} */\n let key\n\n for (key in check) {\n if (nodeAsRecord[key] !== checkAsRecord[key]) return false\n }\n\n return true\n }\n}\n\n/**\n * Turn a string into a test for a node with a certain type.\n *\n * @param {string} check\n * @returns {Check}\n */\nfunction typeFactory(check) {\n return castFactory(type)\n\n /**\n * @param {Node} node\n */\n function type(node) {\n return node && node.type === check\n }\n}\n\n/**\n * Turn a custom test into a test for a node that passes that test.\n *\n * @param {TestFunction} testFunction\n * @returns {Check}\n */\nfunction castFactory(testFunction) {\n return check\n\n /**\n * @this {unknown}\n * @type {Check}\n */\n function check(value, index, parent) {\n return Boolean(\n looksLikeANode(value) &&\n testFunction.call(\n this,\n value,\n typeof index === 'number' ? index : undefined,\n parent || undefined\n )\n )\n }\n}\n\nfunction ok() {\n return true\n}\n\n/**\n * @param {unknown} value\n * @returns {value is Node}\n */\nfunction looksLikeANode(value) {\n return value !== null && typeof value === 'object' && 'type' in value\n}\n","/**\n * @import {Node as UnistNode, Parent as UnistParent} from 'unist'\n */\n\n/**\n * @typedef {Exclude<import('unist-util-is').Test, undefined> | undefined} Test\n * Test from `unist-util-is`.\n *\n * Note: we have remove and add `undefined`, because otherwise when generating\n * automatic `.d.ts` files, TS tries to flatten paths from a local perspective,\n * which doesn’t work when publishing on npm.\n */\n\n/**\n * @typedef {(\n * Fn extends (value: any) => value is infer Thing\n * ? Thing\n * : Fallback\n * )} Predicate\n * Get the value of a type guard `Fn`.\n * @template Fn\n * Value; typically function that is a type guard (such as `(x): x is Y`).\n * @template Fallback\n * Value to yield if `Fn` is not a type guard.\n */\n\n/**\n * @typedef {(\n * Check extends null | undefined // No test.\n * ? Value\n * : Value extends {type: Check} // String (type) test.\n * ? Value\n * : Value extends Check // Partial test.\n * ? Value\n * : Check extends Function // Function test.\n * ? Predicate<Check, Value> extends Value\n * ? Predicate<Check, Value>\n * : never\n * : never // Some other test?\n * )} MatchesOne\n * Check whether a node matches a primitive check in the type system.\n * @template Value\n * Value; typically unist `Node`.\n * @template Check\n * Value; typically `unist-util-is`-compatible test, but not arrays.\n */\n\n/**\n * @typedef {(\n * Check extends ReadonlyArray<infer T>\n * ? MatchesOne<Value, T>\n * : Check extends Array<infer T>\n * ? MatchesOne<Value, T>\n * : MatchesOne<Value, Check>\n * )} Matches\n * Check whether a node matches a check in the type system.\n * @template Value\n * Value; typically unist `Node`.\n * @template Check\n * Value; typically `unist-util-is`-compatible test.\n */\n\n/**\n * @typedef {0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10} Uint\n * Number; capped reasonably.\n */\n\n/**\n * @typedef {I extends 0 ? 1 : I extends 1 ? 2 : I extends 2 ? 3 : I extends 3 ? 4 : I extends 4 ? 5 : I extends 5 ? 6 : I extends 6 ? 7 : I extends 7 ? 8 : I extends 8 ? 9 : 10} Increment\n * Increment a number in the type system.\n * @template {Uint} [I=0]\n * Index.\n */\n\n/**\n * @typedef {(\n * Node extends UnistParent\n * ? Node extends {children: Array<infer Children>}\n * ? Child extends Children ? Node : never\n * : never\n * : never\n * )} InternalParent\n * Collect nodes that can be parents of `Child`.\n * @template {UnistNode} Node\n * All node types in a tree.\n * @template {UnistNode} Child\n * Node to search for.\n */\n\n/**\n * @typedef {InternalParent<InclusiveDescendant<Tree>, Child>} Parent\n * Collect nodes in `Tree` that can be parents of `Child`.\n * @template {UnistNode} Tree\n * All node types in a tree.\n * @template {UnistNode} Child\n * Node to search for.\n */\n\n/**\n * @typedef {(\n * Depth extends Max\n * ? never\n * :\n * | InternalParent<Node, Child>\n * | InternalAncestor<Node, InternalParent<Node, Child>, Max, Increment<Depth>>\n * )} InternalAncestor\n * Collect nodes in `Tree` that can be ancestors of `Child`.\n * @template {UnistNode} Node\n * All node types in a tree.\n * @template {UnistNode} Child\n * Node to search for.\n * @template {Uint} [Max=10]\n * Max; searches up to this depth.\n * @template {Uint} [Depth=0]\n * Current depth.\n */\n\n/**\n * @typedef {InternalAncestor<InclusiveDescendant<Tree>, Child>} Ancestor\n * Collect nodes in `Tree` that can be ancestors of `Child`.\n * @template {UnistNode} Tree\n * All node types in a tree.\n * @template {UnistNode} Child\n * Node to search for.\n */\n\n/**\n * @typedef {(\n * Tree extends UnistParent\n * ? Depth extends Max\n * ? Tree\n * : Tree | InclusiveDescendant<Tree['children'][number], Max, Increment<Depth>>\n * : Tree\n * )} InclusiveDescendant\n * Collect all (inclusive) descendants of `Tree`.\n *\n * > 👉 **Note**: for performance reasons, this seems to be the fastest way to\n * > recurse without actually running into an infinite loop, which the\n * > previous version did.\n * >\n * > Practically, a max of `2` is typically enough assuming a `Root` is\n * > passed, but it doesn’t improve performance.\n * > It gets higher with `List > ListItem > Table > TableRow > TableCell`.\n * > Using up to `10` doesn’t hurt or help either.\n * @template {UnistNode} Tree\n * Tree type.\n * @template {Uint} [Max=10]\n * Max; searches up to this depth.\n * @template {Uint} [Depth=0]\n * Current depth.\n */\n\n/**\n * @typedef {'skip' | boolean} Action\n * Union of the action types.\n *\n * @typedef {number} Index\n * Move to the sibling at `index` next (after node itself is completely\n * traversed).\n *\n * Useful if mutating the tree, such as removing the node the visitor is\n * currently on, or any of its previous siblings.\n * Results less than 0 or greater than or equal to `children.length` stop\n * traversing the parent.\n *\n * @typedef {[(Action | null | undefined | void)?, (Index | null | undefined)?]} ActionTuple\n * List with one or two values, the first an action, the second an index.\n *\n * @typedef {Action | ActionTuple | Index | null | undefined | void} VisitorResult\n * Any value that can be returned from a visitor.\n */\n\n/**\n * @callback Visitor\n * Handle a node (matching `test`, if given).\n *\n * Visitors are free to transform `node`.\n * They can also transform the parent of node (the last of `ancestors`).\n *\n * Replacing `node` itself, if `SKIP` is not returned, still causes its\n * descendants to be walked (which is a bug).\n *\n * When adding or removing previous siblings of `node` (or next siblings, in\n * case of reverse), the `Visitor` should return a new `Index` to specify the\n * sibling to traverse after `node` is traversed.\n * Adding or removing next siblings of `node` (or previous siblings, in case\n * of reverse) is handled as expected without needing to return a new `Index`.\n *\n * Removing the children property of an ancestor still results in them being\n * traversed.\n * @param {Visited} node\n * Found node.\n * @param {Array<VisitedParents>} ancestors\n * Ancestors of `node`.\n * @returns {VisitorResult}\n * What to do next.\n *\n * An `Index` is treated as a tuple of `[CONTINUE, Index]`.\n * An `Action` is treated as a tuple of `[Action]`.\n *\n * Passing a tuple back only makes sense if the `Action` is `SKIP`.\n * When the `Action` is `EXIT`, that action can be returned.\n * When the `Action` is `CONTINUE`, `Index` can be returned.\n * @template {UnistNode} [Visited=UnistNode]\n * Visited node type.\n * @template {UnistParent} [VisitedParents=UnistParent]\n * Ancestor type.\n */\n\n/**\n * @typedef {Visitor<Matches<InclusiveDescendant<Tree>, Check>, Ancestor<Tree, Matches<InclusiveDescendant<Tree>, Check>>>} BuildVisitor\n * Build a typed `Visitor` function from a tree and a test.\n *\n * It will infer which values are passed as `node` and which as `parents`.\n * @template {UnistNode} [Tree=UnistNode]\n * Tree type.\n * @template {Test} [Check=Test]\n * Test type.\n */\n\nimport {convert} from 'unist-util-is'\nimport {color} from 'unist-util-visit-parents/do-not-use-color'\n\n/** @type {Readonly<ActionTuple>} */\nconst empty = []\n\n/**\n * Continue traversing as normal.\n */\nexport const CONTINUE = true\n\n/**\n * Stop traversing immediately.\n */\nexport const EXIT = false\n\n/**\n * Do not traverse this node’s children.\n */\nexport const SKIP = 'skip'\n\n/**\n * Visit nodes, with ancestral information.\n *\n * This algorithm performs *depth-first* *tree traversal* in *preorder*\n * (**NLR**) or if `reverse` is given, in *reverse preorder* (**NRL**).\n *\n * You can choose for which nodes `visitor` is called by passing a `test`.\n * For complex tests, you should test yourself in `visitor`, as it will be\n * faster and will have improved type information.\n *\n * Walking the tree is an intensive task.\n * Make use of the return values of the visitor when possible.\n * Instead of walking a tree multiple times, walk it once, use `unist-util-is`\n * to check if a node matches, and then perform different operations.\n *\n * You can change the tree.\n * See `Visitor` for more info.\n *\n * @overload\n * @param {Tree} tree\n * @param {Check} check\n * @param {BuildVisitor<Tree, Check>} visitor\n * @param {boolean | null | undefined} [reverse]\n * @returns {undefined}\n *\n * @overload\n * @param {Tree} tree\n * @param {BuildVisitor<Tree>} visitor\n * @param {boolean | null | undefined} [reverse]\n * @returns {undefined}\n *\n * @param {UnistNode} tree\n * Tree to traverse.\n * @param {Visitor | Test} test\n * `unist-util-is`-compatible test\n * @param {Visitor | boolean | null | undefined} [visitor]\n * Handle each node.\n * @param {boolean | null | undefined} [reverse]\n * Traverse in reverse preorder (NRL) instead of the default preorder (NLR).\n * @returns {undefined}\n * Nothing.\n *\n * @template {UnistNode} Tree\n * Node type.\n * @template {Test} Check\n * `unist-util-is`-compatible test.\n */\nexport function visitParents(tree, test, visitor, reverse) {\n /** @type {Test} */\n let check\n\n if (typeof test === 'function' && typeof visitor !== 'function') {\n reverse = visitor\n // @ts-expect-error no visitor given, so `visitor` is test.\n visitor = test\n } else {\n // @ts-expect-error visitor given, so `test` isn’t a visitor.\n check = test\n }\n\n const is = convert(check)\n const step = reverse ? -1 : 1\n\n factory(tree, undefined, [])()\n\n /**\n * @param {UnistNode} node\n * @param {number | undefined} index\n * @param {Array<UnistParent>} parents\n */\n function factory(node, index, parents) {\n const value = /** @type {Record<string, unknown>} */ (\n node && typeof node === 'object' ? node : {}\n )\n\n if (typeof value.type === 'string') {\n const name =\n // `hast`\n typeof value.tagName === 'string'\n ? value.tagName\n : // `xast`\n typeof value.name === 'string'\n ? value.name\n : undefined\n\n Object.defineProperty(visit, 'name', {\n value:\n 'node (' + color(node.type + (name ? '<' + name + '>' : '')) + ')'\n })\n }\n\n return visit\n\n function visit() {\n /** @type {Readonly<ActionTuple>} */\n let result = empty\n /** @type {Readonly<ActionTuple>} */\n let subresult\n /** @type {number} */\n let offset\n /** @type {Array<UnistParent>} */\n let grandparents\n\n if (!test || is(node, index, parents[parents.length - 1] || undefined)) {\n // @ts-expect-error: `visitor` is now a visitor.\n result = toResult(visitor(node, parents))\n\n if (result[0] === EXIT) {\n return result\n }\n }\n\n if ('children' in node && node.children) {\n const nodeAsParent = /** @type {UnistParent} */ (node)\n\n if (nodeAsParent.children && result[0] !== SKIP) {\n offset = (reverse ? nodeAsParent.children.length : -1) + step\n grandparents = parents.concat(nodeAsParent)\n\n while (offset > -1 && offset < nodeAsParent.children.length) {\n const child = nodeAsParent.children[offset]\n\n subresult = factory(child, offset, grandparents)()\n\n if (subresult[0] === EXIT) {\n return subresult\n }\n\n offset =\n typeof subresult[1] === 'number' ? subresult[1] : offset + step\n }\n }\n }\n\n return result\n }\n }\n}\n\n/**\n * Turn a return value into a clean result.\n *\n * @param {VisitorResult} value\n * Valid return values from visitors.\n * @returns {Readonly<ActionTuple>}\n * Clean result.\n */\nfunction toResult(value) {\n if (Array.isArray(value)) {\n return value\n }\n\n if (typeof value === 'number') {\n return [CONTINUE, value]\n }\n\n return value === null || value === undefined ? empty : [value]\n}\n","/**\n * @import {Nodes, Parents, PhrasingContent, Root, Text} from 'mdast'\n * @import {BuildVisitor, Test, VisitorResult} from 'unist-util-visit-parents'\n */\n\n/**\n * @typedef RegExpMatchObject\n * Info on the match.\n * @property {number} index\n * The index of the search at which the result was found.\n * @property {string} input\n * A copy of the search string in the text node.\n * @property {[...Array<Parents>, Text]} stack\n * All ancestors of the text node, where the last node is the text itself.\n *\n * @typedef {RegExp | string} Find\n * Pattern to find.\n *\n * Strings are escaped and then turned into global expressions.\n *\n * @typedef {Array<FindAndReplaceTuple>} FindAndReplaceList\n * Several find and replaces, in array form.\n *\n * @typedef {[Find, Replace?]} FindAndReplaceTuple\n * Find and replace in tuple form.\n *\n * @typedef {ReplaceFunction | string | null | undefined} Replace\n * Thing to replace with.\n *\n * @callback ReplaceFunction\n * Callback called when a search matches.\n * @param {...any} parameters\n * The parameters are the result of corresponding search expression:\n *\n * * `value` (`string`) — whole match\n * * `...capture` (`Array<string>`) — matches from regex capture groups\n * * `match` (`RegExpMatchObject`) — info on the match\n * @returns {Array<PhrasingContent> | PhrasingContent | string | false | null | undefined}\n * Thing to replace with.\n *\n * * when `null`, `undefined`, `''`, remove the match\n * * …or when `false`, do not replace at all\n * * …or when `string`, replace with a text node of that value\n * * …or when `Node` or `Array<Node>`, replace with those nodes\n *\n * @typedef {[RegExp, ReplaceFunction]} Pair\n * Normalized find and replace.\n *\n * @typedef {Array<Pair>} Pairs\n * All find and replaced.\n *\n * @typedef Options\n * Configuration.\n * @property {Test | null | undefined} [ignore]\n * Test for which nodes to ignore (optional).\n */\n\nimport escape from 'escape-string-regexp'\nimport {visitParents} from 'unist-util-visit-parents'\nimport {convert} from 'unist-util-is'\n\n/**\n * Find patterns in a tree and replace them.\n *\n * The algorithm searches the tree in *preorder* for complete values in `Text`\n * nodes.\n * Partial matches are not supported.\n *\n * @param {Nodes} tree\n * Tree to change.\n * @param {FindAndReplaceList | FindAndReplaceTuple} list\n * Patterns to find.\n * @param {Options | null | undefined} [options]\n * Configuration (when `find` is not `Find`).\n * @returns {undefined}\n * Nothing.\n */\nexport function findAndReplace(tree, list, options) {\n const settings = options || {}\n const ignored = convert(settings.ignore || [])\n const pairs = toPairs(list)\n let pairIndex = -1\n\n while (++pairIndex < pairs.length) {\n visitParents(tree, 'text', visitor)\n }\n\n /** @type {BuildVisitor<Root, 'text'>} */\n function visitor(node, parents) {\n let index = -1\n /** @type {Parents | undefined} */\n let grandparent\n\n while (++index < parents.length) {\n const parent = parents[index]\n /** @type {Array<Nodes> | undefined} */\n const siblings = grandparent ? grandparent.children : undefined\n\n if (\n ignored(\n parent,\n siblings ? siblings.indexOf(parent) : undefined,\n grandparent\n )\n ) {\n return\n }\n\n grandparent = parent\n }\n\n if (grandparent) {\n return handler(node, parents)\n }\n }\n\n /**\n * Handle a text node which is not in an ignored parent.\n *\n * @param {Text} node\n * Text node.\n * @param {Array<Parents>} parents\n * Parents.\n * @returns {VisitorResult}\n * Result.\n */\n function handler(node, parents) {\n const parent = parents[parents.length - 1]\n const find = pairs[pairIndex][0]\n const replace = pairs[pairIndex][1]\n let start = 0\n /** @type {Array<Nodes>} */\n const siblings = parent.children\n const index = siblings.indexOf(node)\n let change = false\n /** @type {Array<PhrasingContent>} */\n let nodes = []\n\n find.lastIndex = 0\n\n let match = find.exec(node.value)\n\n while (match) {\n const position = match.index\n /** @type {RegExpMatchObject} */\n const matchObject = {\n index: match.index,\n input: match.input,\n stack: [...parents, node]\n }\n let value = replace(...match, matchObject)\n\n if (typeof value === 'string') {\n value = value.length > 0 ? {type: 'text', value} : undefined\n }\n\n // It wasn’t a match after all.\n if (value === false) {\n // False acts as if there was no match.\n // So we need to reset `lastIndex`, which currently being at the end of\n // the current match, to the beginning.\n find.lastIndex = position + 1\n } else {\n if (start !== position) {\n nodes.push({\n type: 'text',\n value: node.value.slice(start, position)\n })\n }\n\n if (Array.isArray(value)) {\n nodes.push(...value)\n } else if (value) {\n nodes.push(value)\n }\n\n start = position + match[0].length\n change = true\n }\n\n if (!find.global) {\n break\n }\n\n match = find.exec(node.value)\n }\n\n if (change) {\n if (start < node.value.length) {\n nodes.push({type: 'text', value: node.value.slice(start)})\n }\n\n parent.children.splice(index, 1, ...nodes)\n } else {\n nodes = [node]\n }\n\n return index + nodes.length\n }\n}\n\n/**\n * Turn a tuple or a list of tuples into pairs.\n *\n * @param {FindAndReplaceList | FindAndReplaceTuple} tupleOrList\n * Schema.\n * @returns {Pairs}\n * Clean pairs.\n */\nfunction toPairs(tupleOrList) {\n /** @type {Pairs} */\n const result = []\n\n if (!Array.isArray(tupleOrList)) {\n throw new TypeError('Expected find and replace tuple or list of tuples')\n }\n\n /** @type {FindAndReplaceList} */\n // @ts-expect-error: correct.\n const list =\n !tupleOrList[0] || Array.isArray(tupleOrList[0])\n ? tupleOrList\n : [tupleOrList]\n\n let index = -1\n\n while (++index < list.length) {\n const tuple = list[index]\n result.push([toExpression(tuple[0]), toFunction(tuple[1])])\n }\n\n return result\n}\n\n/**\n * Turn a find into an expression.\n *\n * @param {Find} find\n * Find.\n * @returns {RegExp}\n * Expression.\n */\nfunction toExpression(find) {\n return typeof find === 'string' ? new RegExp(escape(find), 'g') : find\n}\n\n/**\n * Turn a replace into a function.\n *\n * @param {Replace} replace\n * Replace.\n * @returns {ReplaceFunction}\n * Function.\n */\nfunction toFunction(replace) {\n return typeof replace === 'function'\n ? replace\n : function () {\n return replace\n }\n}\n","/**\n * @import {RegExpMatchObject, ReplaceFunction} from 'mdast-util-find-and-replace'\n * @import {CompileContext, Extension as FromMarkdownExtension, Handle as FromMarkdownHandle, Transform as FromMarkdownTransform} from 'mdast-util-from-markdown'\n * @import {ConstructName, Options as ToMarkdownExtension} from 'mdast-util-to-markdown'\n * @import {Link, PhrasingContent} from 'mdast'\n */\n\nimport {ccount} from 'ccount'\nimport {ok as assert} from 'devlop'\nimport {unicodePunctuation, unicodeWhitespace} from 'micromark-util-character'\nimport {findAndReplace} from 'mdast-util-find-and-replace'\n\n/** @type {ConstructName} */\nconst inConstruct = 'phrasing'\n/** @type {Array<ConstructName>} */\nconst notInConstruct = ['autolink', 'link', 'image', 'label']\n\n/**\n * Create an extension for `mdast-util-from-markdown` to enable GFM autolink\n * literals in markdown.\n *\n * @returns {FromMarkdownExtension}\n * Extension for `mdast-util-to-markdown` to enable GFM autolink literals.\n */\nexport function gfmAutolinkLiteralFromMarkdown() {\n return {\n transforms: [transformGfmAutolinkLiterals],\n enter: {\n literalAutolink: enterLiteralAutolink,\n literalAutolinkEmail: enterLiteralAutolinkValue,\n literalAutolinkHttp: enterLiteralAutolinkValue,\n literalAutolinkWww: enterLiteralAutolinkValue\n },\n exit: {\n literalAutolink: exitLiteralAutolink,\n literalAutolinkEmail: exitLiteralAutolinkEmail,\n literalAutolinkHttp: exitLiteralAutolinkHttp,\n literalAutolinkWww: exitLiteralAutolinkWww\n }\n }\n}\n\n/**\n * Create an extension for `mdast-util-to-markdown` to enable GFM autolink\n * literals in markdown.\n *\n * @returns {ToMarkdownExtension}\n * Extension for `mdast-util-to-markdown` to enable GFM autolink literals.\n */\nexport function gfmAutolinkLiteralToMarkdown() {\n return {\n unsafe: [\n {\n character: '@',\n before: '[+\\\\-.\\\\w]',\n after: '[\\\\-.\\\\w]',\n inConstruct,\n notInConstruct\n },\n {\n character: '.',\n before: '[Ww]',\n after: '[\\\\-.\\\\w]',\n inConstruct,\n notInConstruct\n },\n {\n character: ':',\n before: '[ps]',\n after: '\\\\/',\n inConstruct,\n notInConstruct\n }\n ]\n }\n}\n\n/**\n * @this {CompileContext}\n * @type {FromMarkdownHandle}\n */\nfunction enterLiteralAutolink(token) {\n this.enter({type: 'link', title: null, url: '', children: []}, token)\n}\n\n/**\n * @this {CompileContext}\n * @type {FromMarkdownHandle}\n */\nfunction enterLiteralAutolinkValue(token) {\n this.config.enter.autolinkProtocol.call(this, token)\n}\n\n/**\n * @this {CompileContext}\n * @type {FromMarkdownHandle}\n */\nfunction exitLiteralAutolinkHttp(token) {\n this.config.exit.autolinkProtocol.call(this, token)\n}\n\n/**\n * @this {CompileContext}\n * @type {FromMarkdownHandle}\n */\nfunction exitLiteralAutolinkWww(token) {\n this.config.exit.data.call(this, token)\n const node = this.stack[this.stack.length - 1]\n assert(node.type === 'link')\n node.url = 'http://' + this.sliceSerialize(token)\n}\n\n/**\n * @this {CompileContext}\n * @type {FromMarkdownHandle}\n */\nfunction exitLiteralAutolinkEmail(token) {\n this.config.exit.autolinkEmail.call(this, token)\n}\n\n/**\n * @this {CompileContext}\n * @type {FromMarkdownHandle}\n */\nfunction exitLiteralAutolink(token) {\n this.exit(token)\n}\n\n/** @type {FromMarkdownTransform} */\nfunction transformGfmAutolinkLiterals(tree) {\n findAndReplace(\n tree,\n [\n [/(https?:\\/\\/|www(?=\\.))([-.\\w]+)([^ \\t\\r\\n]*)/gi, findUrl],\n [/(?<=^|\\s|\\p{P}|\\p{S})([-.\\w+]+)@([-\\w]+(?:\\.[-\\w]+)+)/gu, findEmail]\n ],\n {ignore: ['link', 'linkReference']}\n )\n}\n\n/**\n * @type {ReplaceFunction}\n * @param {string} _\n * @param {string} protocol\n * @param {string} domain\n * @param {string} path\n * @param {RegExpMatchObject} match\n * @returns {Array<PhrasingContent> | Link | false}\n */\n// eslint-disable-next-line max-params\nfunction findUrl(_, protocol, domain, path, match) {\n let prefix = ''\n\n // Not an expected previous character.\n if (!previous(match)) {\n return false\n }\n\n // Treat `www` as part of the domain.\n if (/^w/i.test(protocol)) {\n domain = protocol + domain\n protocol = ''\n prefix = 'http://'\n }\n\n if (!isCorrectDomain(domain)) {\n return false\n }\n\n const parts = splitUrl(domain + path)\n\n if (!parts[0]) return false\n\n /** @type {Link} */\n const result = {\n type: 'link',\n title: null,\n url: prefix + protocol + parts[0],\n children: [{type: 'text', value: protocol + parts[0]}]\n }\n\n if (parts[1]) {\n return [result, {type: 'text', value: parts[1]}]\n }\n\n return result\n}\n\n/**\n * @type {ReplaceFunction}\n * @param {string} _\n * @param {string} atext\n * @param {string} label\n * @param {RegExpMatchObject} match\n * @returns {Link | false}\n */\nfunction findEmail(_, atext, label, match) {\n if (\n // Not an expected previous character.\n !previous(match, true) ||\n // Label ends in not allowed character.\n /[-\\d_]$/.test(label)\n ) {\n return false\n }\n\n return {\n type: 'link',\n title: null,\n url: 'mailto:' + atext + '@' + label,\n children: [{type: 'text', value: atext + '@' + label}]\n }\n}\n\n/**\n * @param {string} domain\n * @returns {boolean}\n */\nfunction isCorrectDomain(domain) {\n const parts = domain.split('.')\n\n if (\n parts.length < 2 ||\n (parts[parts.length - 1] &&\n (/_/.test(parts[parts.length - 1]) ||\n !/[a-zA-Z\\d]/.test(parts[parts.length - 1]))) ||\n (parts[parts.length - 2] &&\n (/_/.test(parts[parts.length - 2]) ||\n !/[a-zA-Z\\d]/.test(parts[parts.length - 2])))\n ) {\n return false\n }\n\n return true\n}\n\n/**\n * @param {string} url\n * @returns {[string, string | undefined]}\n */\nfunction splitUrl(url) {\n const trailExec = /[!\"&'),.:;<>?\\]}]+$/.exec(url)\n\n if (!trailExec) {\n return [url, undefined]\n }\n\n url = url.slice(0, trailExec.index)\n\n let trail = trailExec[0]\n let closingParenIndex = trail.indexOf(')')\n const openingParens = ccount(url, '(')\n let closingParens = ccount(url, ')')\n\n while (closingParenIndex !== -1 && openingParens > closingParens) {\n url += trail.slice(0, closingParenIndex + 1)\n trail = trail.slice(closingParenIndex + 1)\n closingParenIndex = trail.indexOf(')')\n closingParens++\n }\n\n return [url, trail]\n}\n\n/**\n * @param {RegExpMatchObject} match\n * @param {boolean | null | undefined} [email=false]\n * @returns {boolean}\n */\nfunction previous(match, email) {\n const code = match.input.charCodeAt(match.index - 1)\n\n return (\n (match.index === 0 ||\n unicodeWhitespace(code) ||\n unicodePunctuation(code)) &&\n // If it’s an email, the previous character should not be a slash.\n (!email || code !== 47)\n )\n}\n","/**\n * Normalize an identifier (as found in references, definitions).\n *\n * Collapses markdown whitespace, trim, and then lower- and uppercase.\n *\n * Some characters are considered “uppercase”, such as U+03F4 (`ϴ`), but if their\n * lowercase counterpart (U+03B8 (`θ`)) is uppercased will result in a different\n * uppercase character (U+0398 (`Θ`)).\n * So, to get a canonical form, we perform both lower- and uppercase.\n *\n * Using uppercase last makes sure keys will never interact with default\n * prototypal values (such as `constructor`): nothing in the prototype of\n * `Object` is uppercase.\n *\n * @param {string} value\n * Identifier to normalize.\n * @returns {string}\n * Normalized identifier.\n */\nexport function normalizeIdentifier(value) {\n return value\n // Collapse markdown whitespace.\n .replace(/[\\t\\n\\r ]+/g, \" \")\n // Trim.\n .replace(/^ | $/g, '')\n // Some characters are considered “uppercase”, but if their lowercase\n // counterpart is uppercased will result in a different uppercase\n // character.\n // Hence, to get that form, we perform both lower- and uppercase.\n // Upper case makes sure keys will not interact with default prototypal\n // methods: no method is uppercase.\n .toLowerCase().toUpperCase();\n}","/**\n * @import {\n * CompileContext,\n * Extension as FromMarkdownExtension,\n * Handle as FromMarkdownHandle\n * } from 'mdast-util-from-markdown'\n * @import {ToMarkdownOptions} from 'mdast-util-gfm-footnote'\n * @import {\n * Handle as ToMarkdownHandle,\n * Map,\n * Options as ToMarkdownExtension\n * } from 'mdast-util-to-markdown'\n * @import {FootnoteDefinition, FootnoteReference} from 'mdast'\n */\n\nimport {ok as assert} from 'devlop'\nimport {normalizeIdentifier} from 'micromark-util-normalize-identifier'\n\nfootnoteReference.peek = footnoteReferencePeek\n\n/**\n * @this {CompileContext}\n * @type {FromMarkdownHandle}\n */\nfunction enterFootnoteCallString() {\n this.buffer()\n}\n\n/**\n * @this {CompileContext}\n * @type {FromMarkdownHandle}\n */\nfunction enterFootnoteCall(token) {\n this.enter({type: 'footnoteReference', identifier: '', label: ''}, token)\n}\n\n/**\n * @this {CompileContext}\n * @type {FromMarkdownHandle}\n */\nfunction enterFootnoteDefinitionLabelString() {\n this.buffer()\n}\n\n/**\n * @this {CompileContext}\n * @type {FromMarkdownHandle}\n */\nfunction enterFootnoteDefinition(token) {\n this.enter(\n {type: 'footnoteDefinition', identifier: '', label: '', children: []},\n token\n )\n}\n\n/**\n * @this {CompileContext}\n * @type {FromMarkdownHandle}\n */\nfunction exitFootnoteCallString(token) {\n const label = this.resume()\n const node = this.stack[this.stack.length - 1]\n assert(node.type === 'footnoteReference')\n node.identifier = normalizeIdentifier(\n this.sliceSerialize(token)\n ).toLowerCase()\n node.label = label\n}\n\n/**\n * @this {CompileContext}\n * @type {FromMarkdownHandle}\n */\nfunction exitFootnoteCall(token) {\n this.exit(token)\n}\n\n/**\n * @this {CompileContext}\n * @type {FromMarkdownHandle}\n */\nfunction exitFootnoteDefinitionLabelString(token) {\n const label = this.resume()\n const node = this.stack[this.stack.length - 1]\n assert(node.type === 'footnoteDefinition')\n node.identifier = normalizeIdentifier(\n this.sliceSerialize(token)\n ).toLowerCase()\n node.label = label\n}\n\n/**\n * @this {CompileContext}\n * @type {FromMarkdownHandle}\n */\nfunction exitFootnoteDefinition(token) {\n this.exit(token)\n}\n\n/** @type {ToMarkdownHandle} */\nfunction footnoteReferencePeek() {\n return '['\n}\n\n/**\n * @type {ToMarkdownHandle}\n * @param {FootnoteReference} node\n */\nfunction footnoteReference(node, _, state, info) {\n const tracker = state.createTracker(info)\n let value = tracker.move('[^')\n const exit = state.enter('footnoteReference')\n const subexit = state.enter('reference')\n value += tracker.move(\n state.safe(state.associationId(node), {after: ']', before: value})\n )\n subexit()\n exit()\n value += tracker.move(']')\n return value\n}\n\n/**\n * Create an extension for `mdast-util-from-markdown` to enable GFM footnotes\n * in markdown.\n *\n * @returns {FromMarkdownExtension}\n * Extension for `mdast-util-from-markdown`.\n */\nexport function gfmFootnoteFromMarkdown() {\n return {\n enter: {\n gfmFootnoteCallString: enterFootnoteCallString,\n gfmFootnoteCall: enterFootnoteCall,\n gfmFootnoteDefinitionLabelString: enterFootnoteDefinitionLabelString,\n gfmFootnoteDefinition: enterFootnoteDefinition\n },\n exit: {\n gfmFootnoteCallString: exitFootnoteCallString,\n gfmFootnoteCall: exitFootnoteCall,\n gfmFootnoteDefinitionLabelString: exitFootnoteDefinitionLabelString,\n gfmFootnoteDefinition: exitFootnoteDefinition\n }\n }\n}\n\n/**\n * Create an extension for `mdast-util-to-markdown` to enable GFM footnotes\n * in markdown.\n *\n * @param {ToMarkdownOptions | null | undefined} [options]\n * Configuration (optional).\n * @returns {ToMarkdownExtension}\n * Extension for `mdast-util-to-markdown`.\n */\nexport function gfmFootnoteToMarkdown(options) {\n // To do: next major: change default.\n let firstLineBlank = false\n\n if (options && options.firstLineBlank) {\n firstLineBlank = true\n }\n\n return {\n handlers: {footnoteDefinition, footnoteReference},\n // This is on by default already.\n unsafe: [{character: '[', inConstruct: ['label', 'phrasing', 'reference']}]\n }\n\n /**\n * @type {ToMarkdownHandle}\n * @param {FootnoteDefinition} node\n */\n function footnoteDefinition(node, _, state, info) {\n const tracker = state.createTracker(info)\n let value = tracker.move('[^')\n const exit = state.enter('footnoteDefinition')\n const subexit = state.enter('label')\n value += tracker.move(\n state.safe(state.associationId(node), {before: value, after: ']'})\n )\n subexit()\n\n value += tracker.move(']:')\n\n if (node.children && node.children.length > 0) {\n tracker.shift(4)\n\n value += tracker.move(\n (firstLineBlank ? '\\n' : ' ') +\n state.indentLines(\n state.containerFlow(node, tracker.current()),\n firstLineBlank ? mapAll : mapExceptFirst\n )\n )\n }\n\n exit()\n\n return value\n }\n}\n\n/** @type {Map} */\nfunction mapExceptFirst(line, index, blank) {\n return index === 0 ? line : mapAll(line, index, blank)\n}\n\n/** @type {Map} */\nfunction mapAll(line, index, blank) {\n return (blank ? '' : ' ') + line\n}\n","/**\n * @typedef {import('mdast').Delete} Delete\n *\n * @typedef {import('mdast-util-from-markdown').CompileContext} CompileContext\n * @typedef {import('mdast-util-from-markdown').Extension} FromMarkdownExtension\n * @typedef {import('mdast-util-from-markdown').Handle} FromMarkdownHandle\n *\n * @typedef {import('mdast-util-to-markdown').ConstructName} ConstructName\n * @typedef {import('mdast-util-to-markdown').Handle} ToMarkdownHandle\n * @typedef {import('mdast-util-to-markdown').Options} ToMarkdownExtension\n */\n\n/**\n * List of constructs that occur in phrasing (paragraphs, headings), but cannot\n * contain strikethrough.\n * So they sort of cancel each other out.\n * Note: could use a better name.\n *\n * Note: keep in sync with: <https://github.com/syntax-tree/mdast-util-to-markdown/blob/8ce8dbf/lib/unsafe.js#L14>\n *\n * @type {Array<ConstructName>}\n */\nconst constructsWithoutStrikethrough = [\n 'autolink',\n 'destinationLiteral',\n 'destinationRaw',\n 'reference',\n 'titleQuote',\n 'titleApostrophe'\n]\n\nhandleDelete.peek = peekDelete\n\n/**\n * Create an extension for `mdast-util-from-markdown` to enable GFM\n * strikethrough in markdown.\n *\n * @returns {FromMarkdownExtension}\n * Extension for `mdast-util-from-markdown` to enable GFM strikethrough.\n */\nexport function gfmStrikethroughFromMarkdown() {\n return {\n canContainEols: ['delete'],\n enter: {strikethrough: enterStrikethrough},\n exit: {strikethrough: exitStrikethrough}\n }\n}\n\n/**\n * Create an extension for `mdast-util-to-markdown` to enable GFM\n * strikethrough in markdown.\n *\n * @returns {ToMarkdownExtension}\n * Extension for `mdast-util-to-markdown` to enable GFM strikethrough.\n */\nexport function gfmStrikethroughToMarkdown() {\n return {\n unsafe: [\n {\n character: '~',\n inConstruct: 'phrasing',\n notInConstruct: constructsWithoutStrikethrough\n }\n ],\n handlers: {delete: handleDelete}\n }\n}\n\n/**\n * @this {CompileContext}\n * @type {FromMarkdownHandle}\n */\nfunction enterStrikethrough(token) {\n this.enter({type: 'delete', children: []}, token)\n}\n\n/**\n * @this {CompileContext}\n * @type {FromMarkdownHandle}\n */\nfunction exitStrikethrough(token) {\n this.exit(token)\n}\n\n/**\n * @type {ToMarkdownHandle}\n * @param {Delete} node\n */\nfunction handleDelete(node, _, state, info) {\n const tracker = state.createTracker(info)\n const exit = state.enter('strikethrough')\n let value = tracker.move('~~')\n value += state.containerPhrasing(node, {\n ...tracker.current(),\n before: value,\n after: '~'\n })\n value += tracker.move('~~')\n exit()\n return value\n}\n\n/** @type {ToMarkdownHandle} */\nfunction peekDelete() {\n return '~'\n}\n","// To do: next major: remove.\n/**\n * @typedef {Options} MarkdownTableOptions\n * Configuration.\n */\n\n/**\n * @typedef Options\n * Configuration.\n * @property {boolean | null | undefined} [alignDelimiters=true]\n * Whether to align the delimiters (default: `true`);\n * they are aligned by default:\n *\n * ```markdown\n * | Alpha | B |\n * | ----- | ----- |\n * | C | Delta |\n * ```\n *\n * Pass `false` to make them staggered:\n *\n * ```markdown\n * | Alpha | B |\n * | - | - |\n * | C | Delta |\n * ```\n * @property {ReadonlyArray<string | null | undefined> | string | null | undefined} [align]\n * How to align columns (default: `''`);\n * one style for all columns or styles for their respective columns;\n * each style is either `'l'` (left), `'r'` (right), or `'c'` (center);\n * other values are treated as `''`, which doesn’t place the colon in the\n * alignment row but does align left;\n * *only the lowercased first character is used, so `Right` is fine.*\n * @property {boolean | null | undefined} [delimiterEnd=true]\n * Whether to end each row with the delimiter (default: `true`).\n *\n * > 👉 **Note**: please don’t use this: it could create fragile structures\n * > that aren’t understandable to some markdown parsers.\n *\n * When `true`, there are ending delimiters:\n *\n * ```markdown\n * | Alpha | B |\n * | ----- | ----- |\n * | C | Delta |\n * ```\n *\n * When `false`, there are no ending delimiters:\n *\n * ```markdown\n * | Alpha | B\n * | ----- | -----\n * | C | Delta\n * ```\n * @property {boolean | null | undefined} [delimiterStart=true]\n * Whether to begin each row with the delimiter (default: `true`).\n *\n * > 👉 **Note**: please don’t use this: it could create fragile structures\n * > that aren’t understandable to some markdown parsers.\n *\n * When `true`, there are starting delimiters:\n *\n * ```markdown\n * | Alpha | B |\n * | ----- | ----- |\n * | C | Delta |\n * ```\n *\n * When `false`, there are no starting delimiters:\n *\n * ```markdown\n * Alpha | B |\n * ----- | ----- |\n * C | Delta |\n * ```\n * @property {boolean | null | undefined} [padding=true]\n * Whether to add a space of padding between delimiters and cells\n * (default: `true`).\n *\n * When `true`, there is padding:\n *\n * ```markdown\n * | Alpha | B |\n * | ----- | ----- |\n * | C | Delta |\n * ```\n *\n * When `false`, there is no padding:\n *\n * ```markdown\n * |Alpha|B |\n * |-----|-----|\n * |C |Delta|\n * ```\n * @property {((value: string) => number) | null | undefined} [stringLength]\n * Function to detect the length of table cell content (optional);\n * this is used when aligning the delimiters (`|`) between table cells;\n * full-width characters and emoji mess up delimiter alignment when viewing\n * the markdown source;\n * to fix this, you can pass this function,\n * which receives the cell content and returns its “visible” size;\n * note that what is and isn’t visible depends on where the text is displayed.\n *\n * Without such a function, the following:\n *\n * ```js\n * markdownTable([\n * ['Alpha', 'Bravo'],\n * ['中文', 'Charlie'],\n * ['👩❤️👩', 'Delta']\n * ])\n * ```\n *\n * Yields:\n *\n * ```markdown\n * | Alpha | Bravo |\n * | - | - |\n * | 中文 | Charlie |\n * | 👩❤️👩 | Delta |\n * ```\n *\n * With [`string-width`](https://github.com/sindresorhus/string-width):\n *\n * ```js\n * import stringWidth from 'string-width'\n *\n * markdownTable(\n * [\n * ['Alpha', 'Bravo'],\n * ['中文', 'Charlie'],\n * ['👩❤️👩', 'Delta']\n * ],\n * {stringLength: stringWidth}\n * )\n * ```\n *\n * Yields:\n *\n * ```markdown\n * | Alpha | Bravo |\n * | ----- | ------- |\n * | 中文 | Charlie |\n * | 👩❤️👩 | Delta |\n * ```\n */\n\n/**\n * @param {string} value\n * Cell value.\n * @returns {number}\n * Cell size.\n */\nfunction defaultStringLength(value) {\n return value.length\n}\n\n/**\n * Generate a markdown\n * ([GFM](https://docs.github.com/en/github/writing-on-github/working-with-advanced-formatting/organizing-information-with-tables))\n * table.\n *\n * @param {ReadonlyArray<ReadonlyArray<string | null | undefined>>} table\n * Table data (matrix of strings).\n * @param {Readonly<Options> | null | undefined} [options]\n * Configuration (optional).\n * @returns {string}\n * Result.\n */\nexport function markdownTable(table, options) {\n const settings = options || {}\n // To do: next major: change to spread.\n const align = (settings.align || []).concat()\n const stringLength = settings.stringLength || defaultStringLength\n /** @type {Array<number>} Character codes as symbols for alignment per column. */\n const alignments = []\n /** @type {Array<Array<string>>} Cells per row. */\n const cellMatrix = []\n /** @type {Array<Array<number>>} Sizes of each cell per row. */\n const sizeMatrix = []\n /** @type {Array<number>} */\n const longestCellByColumn = []\n let mostCellsPerRow = 0\n let rowIndex = -1\n\n // This is a superfluous loop if we don’t align delimiters, but otherwise we’d\n // do superfluous work when aligning, so optimize for aligning.\n while (++rowIndex < table.length) {\n /** @type {Array<string>} */\n const row = []\n /** @type {Array<number>} */\n const sizes = []\n let columnIndex = -1\n\n if (table[rowIndex].length > mostCellsPerRow) {\n mostCellsPerRow = table[rowIndex].length\n }\n\n while (++columnIndex < table[rowIndex].length) {\n const cell = serialize(table[rowIndex][columnIndex])\n\n if (settings.alignDelimiters !== false) {\n const size = stringLength(cell)\n sizes[columnIndex] = size\n\n if (\n longestCellByColumn[columnIndex] === undefined ||\n size > longestCellByColumn[columnIndex]\n ) {\n longestCellByColumn[columnIndex] = size\n }\n }\n\n row.push(cell)\n }\n\n cellMatrix[rowIndex] = row\n sizeMatrix[rowIndex] = sizes\n }\n\n // Figure out which alignments to use.\n let columnIndex = -1\n\n if (typeof align === 'object' && 'length' in align) {\n while (++columnIndex < mostCellsPerRow) {\n alignments[columnIndex] = toAlignment(align[columnIndex])\n }\n } else {\n const code = toAlignment(align)\n\n while (++columnIndex < mostCellsPerRow) {\n alignments[columnIndex] = code\n }\n }\n\n // Inject the alignment row.\n columnIndex = -1\n /** @type {Array<string>} */\n const row = []\n /** @type {Array<number>} */\n const sizes = []\n\n while (++columnIndex < mostCellsPerRow) {\n const code = alignments[columnIndex]\n let before = ''\n let after = ''\n\n if (code === 99 /* `c` */) {\n before = ':'\n after = ':'\n } else if (code === 108 /* `l` */) {\n before = ':'\n } else if (code === 114 /* `r` */) {\n after = ':'\n }\n\n // There *must* be at least one hyphen-minus in each alignment cell.\n let size =\n settings.alignDelimiters === false\n ? 1\n : Math.max(\n 1,\n longestCellByColumn[columnIndex] - before.length - after.length\n )\n\n const cell = before + '-'.repeat(size) + after\n\n if (settings.alignDelimiters !== false) {\n size = before.length + size + after.length\n\n if (size > longestCellByColumn[columnIndex]) {\n longestCellByColumn[columnIndex] = size\n }\n\n sizes[columnIndex] = size\n }\n\n row[columnIndex] = cell\n }\n\n // Inject the alignment row.\n cellMatrix.splice(1, 0, row)\n sizeMatrix.splice(1, 0, sizes)\n\n rowIndex = -1\n /** @type {Array<string>} */\n const lines = []\n\n while (++rowIndex < cellMatrix.length) {\n const row = cellMatrix[rowIndex]\n const sizes = sizeMatrix[rowIndex]\n columnIndex = -1\n /** @type {Array<string>} */\n const line = []\n\n while (++columnIndex < mostCellsPerRow) {\n const cell = row[columnIndex] || ''\n let before = ''\n let after = ''\n\n if (settings.alignDelimiters !== false) {\n const size =\n longestCellByColumn[columnIndex] - (sizes[columnIndex] || 0)\n const code = alignments[columnIndex]\n\n if (code === 114 /* `r` */) {\n before = ' '.repeat(size)\n } else if (code === 99 /* `c` */) {\n if (size % 2) {\n before = ' '.repeat(size / 2 + 0.5)\n after = ' '.repeat(size / 2 - 0.5)\n } else {\n before = ' '.repeat(size / 2)\n after = before\n }\n } else {\n after = ' '.repeat(size)\n }\n }\n\n if (settings.delimiterStart !== false && !columnIndex) {\n line.push('|')\n }\n\n if (\n settings.padding !== false &&\n // Don’t add the opening space if we’re not aligning and the cell is\n // empty: there will be a closing space.\n !(settings.alignDelimiters === false && cell === '') &&\n (settings.delimiterStart !== false || columnIndex)\n ) {\n line.push(' ')\n }\n\n if (settings.alignDelimiters !== false) {\n line.push(before)\n }\n\n line.push(cell)\n\n if (settings.alignDelimiters !== false) {\n line.push(after)\n }\n\n if (settings.padding !== false) {\n line.push(' ')\n }\n\n if (\n settings.delimiterEnd !== false ||\n columnIndex !== mostCellsPerRow - 1\n ) {\n line.push('|')\n }\n }\n\n lines.push(\n settings.delimiterEnd === false\n ? line.join('').replace(/ +$/, '')\n : line.join('')\n )\n }\n\n return lines.join('\\n')\n}\n\n/**\n * @param {string | null | undefined} [value]\n * Value to serialize.\n * @returns {string}\n * Result.\n */\nfunction serialize(value) {\n return value === null || value === undefined ? '' : String(value)\n}\n\n/**\n * @param {string | null | undefined} value\n * Value.\n * @returns {number}\n * Alignment.\n */\nfunction toAlignment(value) {\n const code = typeof value === 'string' ? value.codePointAt(0) : 0\n\n return code === 67 /* `C` */ || code === 99 /* `c` */\n ? 99 /* `c` */\n : code === 76 /* `L` */ || code === 108 /* `l` */\n ? 108 /* `l` */\n : code === 82 /* `R` */ || code === 114 /* `r` */\n ? 114 /* `r` */\n : 0\n}\n","/**\n * @import {Blockquote, Parents} from 'mdast'\n * @import {Info, Map, State} from 'mdast-util-to-markdown'\n */\n\n/**\n * @param {Blockquote} node\n * @param {Parents | undefined} _\n * @param {State} state\n * @param {Info} info\n * @returns {string}\n */\nexport function blockquote(node, _, state, info) {\n const exit = state.enter('blockquote')\n const tracker = state.createTracker(info)\n tracker.move('> ')\n tracker.shift(2)\n const value = state.indentLines(\n state.containerFlow(node, tracker.current()),\n map\n )\n exit()\n return value\n}\n\n/** @type {Map} */\nfunction map(line, _, blank) {\n return '>' + (blank ? '' : ' ') + line\n}\n","/**\n * @import {ConstructName, Unsafe} from 'mdast-util-to-markdown'\n */\n\n/**\n * @param {Array<ConstructName>} stack\n * @param {Unsafe} pattern\n * @returns {boolean}\n */\nexport function patternInScope(stack, pattern) {\n return (\n listInScope(stack, pattern.inConstruct, true) &&\n !listInScope(stack, pattern.notInConstruct, false)\n )\n}\n\n/**\n * @param {Array<ConstructName>} stack\n * @param {Unsafe['inConstruct']} list\n * @param {boolean} none\n * @returns {boolean}\n */\nfunction listInScope(stack, list, none) {\n if (typeof list === 'string') {\n list = [list]\n }\n\n if (!list || list.length === 0) {\n return none\n }\n\n let index = -1\n\n while (++index < list.length) {\n if (stack.includes(list[index])) {\n return true\n }\n }\n\n return false\n}\n","/**\n * @import {Break, Parents} from 'mdast'\n * @import {Info, State} from 'mdast-util-to-markdown'\n */\n\nimport {patternInScope} from '../util/pattern-in-scope.js'\n\n/**\n * @param {Break} _\n * @param {Parents | undefined} _1\n * @param {State} state\n * @param {Info} info\n * @returns {string}\n */\nexport function hardBreak(_, _1, state, info) {\n let index = -1\n\n while (++index < state.unsafe.length) {\n // If we can’t put eols in this construct (setext headings, tables), use a\n // space instead.\n if (\n state.unsafe[index].character === '\\n' &&\n patternInScope(state.stack, state.unsafe[index])\n ) {\n return /[ \\t]/.test(info.before) ? '' : ' '\n }\n }\n\n return '\\\\\\n'\n}\n","/**\n * Get the count of the longest repeating streak of `substring` in `value`.\n *\n * @param {string} value\n * Content to search in.\n * @param {string} substring\n * Substring to look for, typically one character.\n * @returns {number}\n * Count of most frequent adjacent `substring`s in `value`.\n */\nexport function longestStreak(value, substring) {\n const source = String(value)\n let index = source.indexOf(substring)\n let expected = index\n let count = 0\n let max = 0\n\n if (typeof substring !== 'string') {\n throw new TypeError('Expected substring')\n }\n\n while (index !== -1) {\n if (index === expected) {\n if (++count > max) {\n max = count\n }\n } else {\n count = 1\n }\n\n expected = index + substring.length\n index = source.indexOf(substring, expected)\n }\n\n return max\n}\n","/**\n * @import {State} from 'mdast-util-to-markdown'\n * @import {Code} from 'mdast'\n */\n\n/**\n * @param {Code} node\n * @param {State} state\n * @returns {boolean}\n */\nexport function formatCodeAsIndented(node, state) {\n return Boolean(\n state.options.fences === false &&\n node.value &&\n // If there’s no info…\n !node.lang &&\n // And there’s a non-whitespace character…\n /[^ \\r\\n]/.test(node.value) &&\n // And the value doesn’t start or end in a blank…\n !/^[\\t ]*(?:[\\r\\n]|$)|(?:^|[\\r\\n])[\\t ]*$/.test(node.value)\n )\n}\n","/**\n * @import {Options, State} from 'mdast-util-to-markdown'\n */\n\n/**\n * @param {State} state\n * @returns {Exclude<Options['fence'], null | undefined>}\n */\nexport function checkFence(state) {\n const marker = state.options.fence || '`'\n\n if (marker !== '`' && marker !== '~') {\n throw new Error(\n 'Cannot serialize code with `' +\n marker +\n '` for `options.fence`, expected `` ` `` or `~`'\n )\n }\n\n return marker\n}\n","/**\n * @import {Info, Map, State} from 'mdast-util-to-markdown'\n * @import {Code, Parents} from 'mdast'\n */\n\nimport {longestStreak} from 'longest-streak'\nimport {formatCodeAsIndented} from '../util/format-code-as-indented.js'\nimport {checkFence} from '../util/check-fence.js'\n\n/**\n * @param {Code} node\n * @param {Parents | undefined} _\n * @param {State} state\n * @param {Info} info\n * @returns {string}\n */\nexport function code(node, _, state, info) {\n const marker = checkFence(state)\n const raw = node.value || ''\n const suffix = marker === '`' ? 'GraveAccent' : 'Tilde'\n\n if (formatCodeAsIndented(node, state)) {\n const exit = state.enter('codeIndented')\n const value = state.indentLines(raw, map)\n exit()\n return value\n }\n\n const tracker = state.createTracker(info)\n const sequence = marker.repeat(Math.max(longestStreak(raw, marker) + 1, 3))\n const exit = state.enter('codeFenced')\n let value = tracker.move(sequence)\n\n if (node.lang) {\n const subexit = state.enter(`codeFencedLang${suffix}`)\n value += tracker.move(\n state.safe(node.lang, {\n before: value,\n after: ' ',\n encode: ['`'],\n ...tracker.current()\n })\n )\n subexit()\n }\n\n if (node.lang && node.meta) {\n const subexit = state.enter(`codeFencedMeta${suffix}`)\n value += tracker.move(' ')\n value += tracker.move(\n state.safe(node.meta, {\n before: value,\n after: '\\n',\n encode: ['`'],\n ...tracker.current()\n })\n )\n subexit()\n }\n\n value += tracker.move('\\n')\n\n if (raw) {\n value += tracker.move(raw + '\\n')\n }\n\n value += tracker.move(sequence)\n exit()\n return value\n}\n\n/** @type {Map} */\nfunction map(line, _, blank) {\n return (blank ? '' : ' ') + line\n}\n","/**\n * @import {Options, State} from 'mdast-util-to-markdown'\n */\n\n/**\n * @param {State} state\n * @returns {Exclude<Options['quote'], null | undefined>}\n */\nexport function checkQuote(state) {\n const marker = state.options.quote || '\"'\n\n if (marker !== '\"' && marker !== \"'\") {\n throw new Error(\n 'Cannot serialize title with `' +\n marker +\n '` for `options.quote`, expected `\"`, or `\\'`'\n )\n }\n\n return marker\n}\n","/**\n * @import {Info, State} from 'mdast-util-to-markdown'\n * @import {Definition, Parents} from 'mdast'\n */\n\nimport {checkQuote} from '../util/check-quote.js'\n\n/**\n * @param {Definition} node\n * @param {Parents | undefined} _\n * @param {State} state\n * @param {Info} info\n * @returns {string}\n */\nexport function definition(node, _, state, info) {\n const quote = checkQuote(state)\n const suffix = quote === '\"' ? 'Quote' : 'Apostrophe'\n const exit = state.enter('definition')\n let subexit = state.enter('label')\n const tracker = state.createTracker(info)\n let value = tracker.move('[')\n value += tracker.move(\n state.safe(state.associationId(node), {\n before: value,\n after: ']',\n ...tracker.current()\n })\n )\n value += tracker.move(']: ')\n\n subexit()\n\n if (\n // If there’s no url, or…\n !node.url ||\n // If there are control characters or whitespace.\n /[\\0- \\u007F]/.test(node.url)\n ) {\n subexit = state.enter('destinationLiteral')\n value += tracker.move('<')\n value += tracker.move(\n state.safe(node.url, {before: value, after: '>', ...tracker.current()})\n )\n value += tracker.move('>')\n } else {\n // No whitespace, raw is prettier.\n subexit = state.enter('destinationRaw')\n value += tracker.move(\n state.safe(node.url, {\n before: value,\n after: node.title ? ' ' : '\\n',\n ...tracker.current()\n })\n )\n }\n\n subexit()\n\n if (node.title) {\n subexit = state.enter(`title${suffix}`)\n value += tracker.move(' ' + quote)\n value += tracker.move(\n state.safe(node.title, {\n before: value,\n after: quote,\n ...tracker.current()\n })\n )\n value += tracker.move(quote)\n subexit()\n }\n\n exit()\n\n return value\n}\n","/**\n * @import {Options, State} from 'mdast-util-to-markdown'\n */\n\n/**\n * @param {State} state\n * @returns {Exclude<Options['emphasis'], null | undefined>}\n */\nexport function checkEmphasis(state) {\n const marker = state.options.emphasis || '*'\n\n if (marker !== '*' && marker !== '_') {\n throw new Error(\n 'Cannot serialize emphasis with `' +\n marker +\n '` for `options.emphasis`, expected `*`, or `_`'\n )\n }\n\n return marker\n}\n","/**\n * Encode a code point as a character reference.\n *\n * @param {number} code\n * Code point to encode.\n * @returns {string}\n * Encoded character reference.\n */\nexport function encodeCharacterReference(code) {\n return '&#x' + code.toString(16).toUpperCase() + ';'\n}\n","/**\n * @import {Code} from 'micromark-util-types'\n */\n\nimport { markdownLineEndingOrSpace, unicodePunctuation, unicodeWhitespace } from 'micromark-util-character';\n/**\n * Classify whether a code represents whitespace, punctuation, or something\n * else.\n *\n * Used for attention (emphasis, strong), whose sequences can open or close\n * based on the class of surrounding characters.\n *\n * > 👉 **Note**: eof (`null`) is seen as whitespace.\n *\n * @param {Code} code\n * Code.\n * @returns {typeof constants.characterGroupWhitespace | typeof constants.characterGroupPunctuation | undefined}\n * Group.\n */\nexport function classifyCharacter(code) {\n if (code === null || markdownLineEndingOrSpace(code) || unicodeWhitespace(code)) {\n return 1;\n }\n if (unicodePunctuation(code)) {\n return 2;\n }\n}","/**\n * @import {EncodeSides} from '../types.js'\n */\n\nimport {classifyCharacter} from 'micromark-util-classify-character'\n\n/**\n * Check whether to encode (as a character reference) the characters\n * surrounding an attention run.\n *\n * Which characters are around an attention run influence whether it works or\n * not.\n *\n * See <https://github.com/orgs/syntax-tree/discussions/60> for more info.\n * See this markdown in a particular renderer to see what works:\n *\n * ```markdown\n * | | A (letter inside) | B (punctuation inside) | C (whitespace inside) | D (nothing inside) |\n * | ----------------------- | ----------------- | ---------------------- | --------------------- | ------------------ |\n * | 1 (letter outside) | x*y*z | x*.*z | x* *z | x**z |\n * | 2 (punctuation outside) | .*y*. | .*.*. | .* *. | .**. |\n * | 3 (whitespace outside) | x *y* z | x *.* z | x * * z | x ** z |\n * | 4 (nothing outside) | *x* | *.* | * * | ** |\n * ```\n *\n * @param {number} outside\n * Code point on the outer side of the run.\n * @param {number} inside\n * Code point on the inner side of the run.\n * @param {'*' | '_'} marker\n * Marker of the run.\n * Underscores are handled more strictly (they form less often) than\n * asterisks.\n * @returns {EncodeSides}\n * Whether to encode characters.\n */\n// Important: punctuation must never be encoded.\n// Punctuation is solely used by markdown constructs.\n// And by encoding itself.\n// Encoding them will break constructs or double encode things.\nexport function encodeInfo(outside, inside, marker) {\n const outsideKind = classifyCharacter(outside)\n const insideKind = classifyCharacter(inside)\n\n // Letter outside:\n if (outsideKind === undefined) {\n return insideKind === undefined\n ? // Letter inside:\n // we have to encode *both* letters for `_` as it is looser.\n // it already forms for `*` (and GFMs `~`).\n marker === '_'\n ? {inside: true, outside: true}\n : {inside: false, outside: false}\n : insideKind === 1\n ? // Whitespace inside: encode both (letter, whitespace).\n {inside: true, outside: true}\n : // Punctuation inside: encode outer (letter)\n {inside: false, outside: true}\n }\n\n // Whitespace outside:\n if (outsideKind === 1) {\n return insideKind === undefined\n ? // Letter inside: already forms.\n {inside: false, outside: false}\n : insideKind === 1\n ? // Whitespace inside: encode both (whitespace).\n {inside: true, outside: true}\n : // Punctuation inside: already forms.\n {inside: false, outside: false}\n }\n\n // Punctuation outside:\n return insideKind === undefined\n ? // Letter inside: already forms.\n {inside: false, outside: false}\n : insideKind === 1\n ? // Whitespace inside: encode inner (whitespace).\n {inside: true, outside: false}\n : // Punctuation inside: already forms.\n {inside: false, outside: false}\n}\n","/**\n * @import {Info, State} from 'mdast-util-to-markdown'\n * @import {Emphasis, Parents} from 'mdast'\n */\n\nimport {checkEmphasis} from '../util/check-emphasis.js'\nimport {encodeCharacterReference} from '../util/encode-character-reference.js'\nimport {encodeInfo} from '../util/encode-info.js'\n\nemphasis.peek = emphasisPeek\n\n/**\n * @param {Emphasis} node\n * @param {Parents | undefined} _\n * @param {State} state\n * @param {Info} info\n * @returns {string}\n */\nexport function emphasis(node, _, state, info) {\n const marker = checkEmphasis(state)\n const exit = state.enter('emphasis')\n const tracker = state.createTracker(info)\n const before = tracker.move(marker)\n\n let between = tracker.move(\n state.containerPhrasing(node, {\n after: marker,\n before,\n ...tracker.current()\n })\n )\n const betweenHead = between.charCodeAt(0)\n const open = encodeInfo(\n info.before.charCodeAt(info.before.length - 1),\n betweenHead,\n marker\n )\n\n if (open.inside) {\n between = encodeCharacterReference(betweenHead) + between.slice(1)\n }\n\n const betweenTail = between.charCodeAt(between.length - 1)\n const close = encodeInfo(info.after.charCodeAt(0), betweenTail, marker)\n\n if (close.inside) {\n between = between.slice(0, -1) + encodeCharacterReference(betweenTail)\n }\n\n const after = tracker.move(marker)\n\n exit()\n\n state.attentionEncodeSurroundingInfo = {\n after: close.outside,\n before: open.outside\n }\n return before + between + after\n}\n\n/**\n * @param {Emphasis} _\n * @param {Parents | undefined} _1\n * @param {State} state\n * @returns {string}\n */\nfunction emphasisPeek(_, _1, state) {\n return state.options.emphasis || '*'\n}\n","/**\n * @typedef {import('unist').Node} UnistNode\n * @typedef {import('unist').Parent} UnistParent\n * @typedef {import('unist-util-visit-parents').VisitorResult} VisitorResult\n */\n\n/**\n * @typedef {Exclude<import('unist-util-is').Test, undefined> | undefined} Test\n * Test from `unist-util-is`.\n *\n * Note: we have remove and add `undefined`, because otherwise when generating\n * automatic `.d.ts` files, TS tries to flatten paths from a local perspective,\n * which doesn’t work when publishing on npm.\n */\n\n// To do: use types from `unist-util-visit-parents` when it’s released.\n\n/**\n * @typedef {(\n * Fn extends (value: any) => value is infer Thing\n * ? Thing\n * : Fallback\n * )} Predicate\n * Get the value of a type guard `Fn`.\n * @template Fn\n * Value; typically function that is a type guard (such as `(x): x is Y`).\n * @template Fallback\n * Value to yield if `Fn` is not a type guard.\n */\n\n/**\n * @typedef {(\n * Check extends null | undefined // No test.\n * ? Value\n * : Value extends {type: Check} // String (type) test.\n * ? Value\n * : Value extends Check // Partial test.\n * ? Value\n * : Check extends Function // Function test.\n * ? Predicate<Check, Value> extends Value\n * ? Predicate<Check, Value>\n * : never\n * : never // Some other test?\n * )} MatchesOne\n * Check whether a node matches a primitive check in the type system.\n * @template Value\n * Value; typically unist `Node`.\n * @template Check\n * Value; typically `unist-util-is`-compatible test, but not arrays.\n */\n\n/**\n * @typedef {(\n * Check extends Array<any>\n * ? MatchesOne<Value, Check[keyof Check]>\n * : MatchesOne<Value, Check>\n * )} Matches\n * Check whether a node matches a check in the type system.\n * @template Value\n * Value; typically unist `Node`.\n * @template Check\n * Value; typically `unist-util-is`-compatible test.\n */\n\n/**\n * @typedef {0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10} Uint\n * Number; capped reasonably.\n */\n\n/**\n * @typedef {I extends 0 ? 1 : I extends 1 ? 2 : I extends 2 ? 3 : I extends 3 ? 4 : I extends 4 ? 5 : I extends 5 ? 6 : I extends 6 ? 7 : I extends 7 ? 8 : I extends 8 ? 9 : 10} Increment\n * Increment a number in the type system.\n * @template {Uint} [I=0]\n * Index.\n */\n\n/**\n * @typedef {(\n * Node extends UnistParent\n * ? Node extends {children: Array<infer Children>}\n * ? Child extends Children ? Node : never\n * : never\n * : never\n * )} InternalParent\n * Collect nodes that can be parents of `Child`.\n * @template {UnistNode} Node\n * All node types in a tree.\n * @template {UnistNode} Child\n * Node to search for.\n */\n\n/**\n * @typedef {InternalParent<InclusiveDescendant<Tree>, Child>} Parent\n * Collect nodes in `Tree` that can be parents of `Child`.\n * @template {UnistNode} Tree\n * All node types in a tree.\n * @template {UnistNode} Child\n * Node to search for.\n */\n\n/**\n * @typedef {(\n * Depth extends Max\n * ? never\n * :\n * | InternalParent<Node, Child>\n * | InternalAncestor<Node, InternalParent<Node, Child>, Max, Increment<Depth>>\n * )} InternalAncestor\n * Collect nodes in `Tree` that can be ancestors of `Child`.\n * @template {UnistNode} Node\n * All node types in a tree.\n * @template {UnistNode} Child\n * Node to search for.\n * @template {Uint} [Max=10]\n * Max; searches up to this depth.\n * @template {Uint} [Depth=0]\n * Current depth.\n */\n\n/**\n * @typedef {(\n * Tree extends UnistParent\n * ? Depth extends Max\n * ? Tree\n * : Tree | InclusiveDescendant<Tree['children'][number], Max, Increment<Depth>>\n * : Tree\n * )} InclusiveDescendant\n * Collect all (inclusive) descendants of `Tree`.\n *\n * > 👉 **Note**: for performance reasons, this seems to be the fastest way to\n * > recurse without actually running into an infinite loop, which the\n * > previous version did.\n * >\n * > Practically, a max of `2` is typically enough assuming a `Root` is\n * > passed, but it doesn’t improve performance.\n * > It gets higher with `List > ListItem > Table > TableRow > TableCell`.\n * > Using up to `10` doesn’t hurt or help either.\n * @template {UnistNode} Tree\n * Tree type.\n * @template {Uint} [Max=10]\n * Max; searches up to this depth.\n * @template {Uint} [Depth=0]\n * Current depth.\n */\n\n/**\n * @callback Visitor\n * Handle a node (matching `test`, if given).\n *\n * Visitors are free to transform `node`.\n * They can also transform `parent`.\n *\n * Replacing `node` itself, if `SKIP` is not returned, still causes its\n * descendants to be walked (which is a bug).\n *\n * When adding or removing previous siblings of `node` (or next siblings, in\n * case of reverse), the `Visitor` should return a new `Index` to specify the\n * sibling to traverse after `node` is traversed.\n * Adding or removing next siblings of `node` (or previous siblings, in case\n * of reverse) is handled as expected without needing to return a new `Index`.\n *\n * Removing the children property of `parent` still results in them being\n * traversed.\n * @param {Visited} node\n * Found node.\n * @param {Visited extends UnistNode ? number | undefined : never} index\n * Index of `node` in `parent`.\n * @param {Ancestor extends UnistParent ? Ancestor | undefined : never} parent\n * Parent of `node`.\n * @returns {VisitorResult}\n * What to do next.\n *\n * An `Index` is treated as a tuple of `[CONTINUE, Index]`.\n * An `Action` is treated as a tuple of `[Action]`.\n *\n * Passing a tuple back only makes sense if the `Action` is `SKIP`.\n * When the `Action` is `EXIT`, that action can be returned.\n * When the `Action` is `CONTINUE`, `Index` can be returned.\n * @template {UnistNode} [Visited=UnistNode]\n * Visited node type.\n * @template {UnistParent} [Ancestor=UnistParent]\n * Ancestor type.\n */\n\n/**\n * @typedef {Visitor<Visited, Parent<Ancestor, Visited>>} BuildVisitorFromMatch\n * Build a typed `Visitor` function from a node and all possible parents.\n *\n * It will infer which values are passed as `node` and which as `parent`.\n * @template {UnistNode} Visited\n * Node type.\n * @template {UnistParent} Ancestor\n * Parent type.\n */\n\n/**\n * @typedef {(\n * BuildVisitorFromMatch<\n * Matches<Descendant, Check>,\n * Extract<Descendant, UnistParent>\n * >\n * )} BuildVisitorFromDescendants\n * Build a typed `Visitor` function from a list of descendants and a test.\n *\n * It will infer which values are passed as `node` and which as `parent`.\n * @template {UnistNode} Descendant\n * Node type.\n * @template {Test} Check\n * Test type.\n */\n\n/**\n * @typedef {(\n * BuildVisitorFromDescendants<\n * InclusiveDescendant<Tree>,\n * Check\n * >\n * )} BuildVisitor\n * Build a typed `Visitor` function from a tree and a test.\n *\n * It will infer which values are passed as `node` and which as `parent`.\n * @template {UnistNode} [Tree=UnistNode]\n * Node type.\n * @template {Test} [Check=Test]\n * Test type.\n */\n\nimport {visitParents} from 'unist-util-visit-parents'\n\nexport {CONTINUE, EXIT, SKIP} from 'unist-util-visit-parents'\n\n/**\n * Visit nodes.\n *\n * This algorithm performs *depth-first* *tree traversal* in *preorder*\n * (**NLR**) or if `reverse` is given, in *reverse preorder* (**NRL**).\n *\n * You can choose for which nodes `visitor` is called by passing a `test`.\n * For complex tests, you should test yourself in `visitor`, as it will be\n * faster and will have improved type information.\n *\n * Walking the tree is an intensive task.\n * Make use of the return values of the visitor when possible.\n * Instead of walking a tree multiple times, walk it once, use `unist-util-is`\n * to check if a node matches, and then perform different operations.\n *\n * You can change the tree.\n * See `Visitor` for more info.\n *\n * @overload\n * @param {Tree} tree\n * @param {Check} check\n * @param {BuildVisitor<Tree, Check>} visitor\n * @param {boolean | null | undefined} [reverse]\n * @returns {undefined}\n *\n * @overload\n * @param {Tree} tree\n * @param {BuildVisitor<Tree>} visitor\n * @param {boolean | null | undefined} [reverse]\n * @returns {undefined}\n *\n * @param {UnistNode} tree\n * Tree to traverse.\n * @param {Visitor | Test} testOrVisitor\n * `unist-util-is`-compatible test (optional, omit to pass a visitor).\n * @param {Visitor | boolean | null | undefined} [visitorOrReverse]\n * Handle each node (when test is omitted, pass `reverse`).\n * @param {boolean | null | undefined} [maybeReverse=false]\n * Traverse in reverse preorder (NRL) instead of the default preorder (NLR).\n * @returns {undefined}\n * Nothing.\n *\n * @template {UnistNode} Tree\n * Node type.\n * @template {Test} Check\n * `unist-util-is`-compatible test.\n */\nexport function visit(tree, testOrVisitor, visitorOrReverse, maybeReverse) {\n /** @type {boolean | null | undefined} */\n let reverse\n /** @type {Test} */\n let test\n /** @type {Visitor} */\n let visitor\n\n if (\n typeof testOrVisitor === 'function' &&\n typeof visitorOrReverse !== 'function'\n ) {\n test = undefined\n visitor = testOrVisitor\n reverse = visitorOrReverse\n } else {\n // @ts-expect-error: assume the overload with test was given.\n test = testOrVisitor\n // @ts-expect-error: assume the overload with test was given.\n visitor = visitorOrReverse\n reverse = maybeReverse\n }\n\n visitParents(tree, test, overload, reverse)\n\n /**\n * @param {UnistNode} node\n * @param {Array<UnistParent>} parents\n */\n function overload(node, parents) {\n const parent = parents[parents.length - 1]\n const index = parent ? parent.children.indexOf(node) : undefined\n return visitor(node, index, parent)\n }\n}\n","/**\n * @typedef {import('mdast').Nodes} Nodes\n *\n * @typedef Options\n * Configuration (optional).\n * @property {boolean | null | undefined} [includeImageAlt=true]\n * Whether to use `alt` for `image`s (default: `true`).\n * @property {boolean | null | undefined} [includeHtml=true]\n * Whether to use `value` of HTML (default: `true`).\n */\n\n/** @type {Options} */\nconst emptyOptions = {}\n\n/**\n * Get the text content of a node or list of nodes.\n *\n * Prefers the node’s plain-text fields, otherwise serializes its children,\n * and if the given value is an array, serialize the nodes in it.\n *\n * @param {unknown} [value]\n * Thing to serialize, typically `Node`.\n * @param {Options | null | undefined} [options]\n * Configuration (optional).\n * @returns {string}\n * Serialized `value`.\n */\nexport function toString(value, options) {\n const settings = options || emptyOptions\n const includeImageAlt =\n typeof settings.includeImageAlt === 'boolean'\n ? settings.includeImageAlt\n : true\n const includeHtml =\n typeof settings.includeHtml === 'boolean' ? settings.includeHtml : true\n\n return one(value, includeImageAlt, includeHtml)\n}\n\n/**\n * One node or several nodes.\n *\n * @param {unknown} value\n * Thing to serialize.\n * @param {boolean} includeImageAlt\n * Include image `alt`s.\n * @param {boolean} includeHtml\n * Include HTML.\n * @returns {string}\n * Serialized node.\n */\nfunction one(value, includeImageAlt, includeHtml) {\n if (node(value)) {\n if ('value' in value) {\n return value.type === 'html' && !includeHtml ? '' : value.value\n }\n\n if (includeImageAlt && 'alt' in value && value.alt) {\n return value.alt\n }\n\n if ('children' in value) {\n return all(value.children, includeImageAlt, includeHtml)\n }\n }\n\n if (Array.isArray(value)) {\n return all(value, includeImageAlt, includeHtml)\n }\n\n return ''\n}\n\n/**\n * Serialize a list of nodes.\n *\n * @param {Array<unknown>} values\n * Thing to serialize.\n * @param {boolean} includeImageAlt\n * Include image `alt`s.\n * @param {boolean} includeHtml\n * Include HTML.\n * @returns {string}\n * Serialized nodes.\n */\nfunction all(values, includeImageAlt, includeHtml) {\n /** @type {Array<string>} */\n const result = []\n let index = -1\n\n while (++index < values.length) {\n result[index] = one(values[index], includeImageAlt, includeHtml)\n }\n\n return result.join('')\n}\n\n/**\n * Check if `value` looks like a node.\n *\n * @param {unknown} value\n * Thing.\n * @returns {value is Nodes}\n * Whether `value` is a node.\n */\nfunction node(value) {\n return Boolean(value && typeof value === 'object')\n}\n","/**\n * @import {State} from 'mdast-util-to-markdown'\n * @import {Heading} from 'mdast'\n */\n\nimport {EXIT, visit} from 'unist-util-visit'\nimport {toString} from 'mdast-util-to-string'\n\n/**\n * @param {Heading} node\n * @param {State} state\n * @returns {boolean}\n */\nexport function formatHeadingAsSetext(node, state) {\n let literalWithBreak = false\n\n // Look for literals with a line break.\n // Note that this also\n visit(node, function (node) {\n if (\n ('value' in node && /\\r?\\n|\\r/.test(node.value)) ||\n node.type === 'break'\n ) {\n literalWithBreak = true\n return EXIT\n }\n })\n\n return Boolean(\n (!node.depth || node.depth < 3) &&\n toString(node) &&\n (state.options.setext || literalWithBreak)\n )\n}\n","/**\n * @import {Info, State} from 'mdast-util-to-markdown'\n * @import {Heading, Parents} from 'mdast'\n */\n\nimport {encodeCharacterReference} from '../util/encode-character-reference.js'\nimport {formatHeadingAsSetext} from '../util/format-heading-as-setext.js'\n\n/**\n * @param {Heading} node\n * @param {Parents | undefined} _\n * @param {State} state\n * @param {Info} info\n * @returns {string}\n */\nexport function heading(node, _, state, info) {\n const rank = Math.max(Math.min(6, node.depth || 1), 1)\n const tracker = state.createTracker(info)\n\n if (formatHeadingAsSetext(node, state)) {\n const exit = state.enter('headingSetext')\n const subexit = state.enter('phrasing')\n const value = state.containerPhrasing(node, {\n ...tracker.current(),\n before: '\\n',\n after: '\\n'\n })\n subexit()\n exit()\n\n return (\n value +\n '\\n' +\n (rank === 1 ? '=' : '-').repeat(\n // The whole size…\n value.length -\n // Minus the position of the character after the last EOL (or\n // 0 if there is none)…\n (Math.max(value.lastIndexOf('\\r'), value.lastIndexOf('\\n')) + 1)\n )\n )\n }\n\n const sequence = '#'.repeat(rank)\n const exit = state.enter('headingAtx')\n const subexit = state.enter('phrasing')\n\n // Note: for proper tracking, we should reset the output positions when there\n // is no content returned, because then the space is not output.\n // Practically, in that case, there is no content, so it doesn’t matter that\n // we’ve tracked one too many characters.\n tracker.move(sequence + ' ')\n\n let value = state.containerPhrasing(node, {\n before: '# ',\n after: '\\n',\n ...tracker.current()\n })\n\n if (/^[\\t ]/.test(value)) {\n // To do: what effect has the character reference on tracking?\n value = encodeCharacterReference(value.charCodeAt(0)) + value.slice(1)\n }\n\n value = value ? sequence + ' ' + value : sequence\n\n if (state.options.closeAtx) {\n value += ' ' + sequence\n }\n\n subexit()\n exit()\n\n return value\n}\n","/**\n * @import {Html} from 'mdast'\n */\n\nhtml.peek = htmlPeek\n\n/**\n * @param {Html} node\n * @returns {string}\n */\nexport function html(node) {\n return node.value || ''\n}\n\n/**\n * @returns {string}\n */\nfunction htmlPeek() {\n return '<'\n}\n","/**\n * @import {Info, State} from 'mdast-util-to-markdown'\n * @import {Image, Parents} from 'mdast'\n */\n\nimport {checkQuote} from '../util/check-quote.js'\n\nimage.peek = imagePeek\n\n/**\n * @param {Image} node\n * @param {Parents | undefined} _\n * @param {State} state\n * @param {Info} info\n * @returns {string}\n */\nexport function image(node, _, state, info) {\n const quote = checkQuote(state)\n const suffix = quote === '\"' ? 'Quote' : 'Apostrophe'\n const exit = state.enter('image')\n let subexit = state.enter('label')\n const tracker = state.createTracker(info)\n let value = tracker.move('![')\n value += tracker.move(\n state.safe(node.alt, {before: value, after: ']', ...tracker.current()})\n )\n value += tracker.move('](')\n\n subexit()\n\n if (\n // If there’s no url but there is a title…\n (!node.url && node.title) ||\n // If there are control characters or whitespace.\n /[\\0- \\u007F]/.test(node.url)\n ) {\n subexit = state.enter('destinationLiteral')\n value += tracker.move('<')\n value += tracker.move(\n state.safe(node.url, {before: value, after: '>', ...tracker.current()})\n )\n value += tracker.move('>')\n } else {\n // No whitespace, raw is prettier.\n subexit = state.enter('destinationRaw')\n value += tracker.move(\n state.safe(node.url, {\n before: value,\n after: node.title ? ' ' : ')',\n ...tracker.current()\n })\n )\n }\n\n subexit()\n\n if (node.title) {\n subexit = state.enter(`title${suffix}`)\n value += tracker.move(' ' + quote)\n value += tracker.move(\n state.safe(node.title, {\n before: value,\n after: quote,\n ...tracker.current()\n })\n )\n value += tracker.move(quote)\n subexit()\n }\n\n value += tracker.move(')')\n exit()\n\n return value\n}\n\n/**\n * @returns {string}\n */\nfunction imagePeek() {\n return '!'\n}\n","/**\n * @import {Info, State} from 'mdast-util-to-markdown'\n * @import {ImageReference, Parents} from 'mdast'\n */\n\nimageReference.peek = imageReferencePeek\n\n/**\n * @param {ImageReference} node\n * @param {Parents | undefined} _\n * @param {State} state\n * @param {Info} info\n * @returns {string}\n */\nexport function imageReference(node, _, state, info) {\n const type = node.referenceType\n const exit = state.enter('imageReference')\n let subexit = state.enter('label')\n const tracker = state.createTracker(info)\n let value = tracker.move('![')\n const alt = state.safe(node.alt, {\n before: value,\n after: ']',\n ...tracker.current()\n })\n value += tracker.move(alt + '][')\n\n subexit()\n // Hide the fact that we’re in phrasing, because escapes don’t work.\n const stack = state.stack\n state.stack = []\n subexit = state.enter('reference')\n // Note: for proper tracking, we should reset the output positions when we end\n // up making a `shortcut` reference, because then there is no brace output.\n // Practically, in that case, there is no content, so it doesn’t matter that\n // we’ve tracked one too many characters.\n const reference = state.safe(state.associationId(node), {\n before: value,\n after: ']',\n ...tracker.current()\n })\n subexit()\n state.stack = stack\n exit()\n\n if (type === 'full' || !alt || alt !== reference) {\n value += tracker.move(reference + ']')\n } else if (type === 'shortcut') {\n // Remove the unwanted `[`.\n value = value.slice(0, -1)\n } else {\n value += tracker.move(']')\n }\n\n return value\n}\n\n/**\n * @returns {string}\n */\nfunction imageReferencePeek() {\n return '!'\n}\n","/**\n * @import {State} from 'mdast-util-to-markdown'\n * @import {InlineCode, Parents} from 'mdast'\n */\n\ninlineCode.peek = inlineCodePeek\n\n/**\n * @param {InlineCode} node\n * @param {Parents | undefined} _\n * @param {State} state\n * @returns {string}\n */\nexport function inlineCode(node, _, state) {\n let value = node.value || ''\n let sequence = '`'\n let index = -1\n\n // If there is a single grave accent on its own in the code, use a fence of\n // two.\n // If there are two in a row, use one.\n while (new RegExp('(^|[^`])' + sequence + '([^`]|$)').test(value)) {\n sequence += '`'\n }\n\n // If this is not just spaces or eols (tabs don’t count), and either the\n // first or last character are a space, eol, or tick, then pad with spaces.\n if (\n /[^ \\r\\n]/.test(value) &&\n ((/^[ \\r\\n]/.test(value) && /[ \\r\\n]$/.test(value)) || /^`|`$/.test(value))\n ) {\n value = ' ' + value + ' '\n }\n\n // We have a potential problem: certain characters after eols could result in\n // blocks being seen.\n // For example, if someone injected the string `'\\n# b'`, then that would\n // result in an ATX heading.\n // We can’t escape characters in `inlineCode`, but because eols are\n // transformed to spaces when going from markdown to HTML anyway, we can swap\n // them out.\n while (++index < state.unsafe.length) {\n const pattern = state.unsafe[index]\n const expression = state.compilePattern(pattern)\n /** @type {RegExpExecArray | null} */\n let match\n\n // Only look for `atBreak`s.\n // Btw: note that `atBreak` patterns will always start the regex at LF or\n // CR.\n if (!pattern.atBreak) continue\n\n while ((match = expression.exec(value))) {\n let position = match.index\n\n // Support CRLF (patterns only look for one of the characters).\n if (\n value.charCodeAt(position) === 10 /* `\\n` */ &&\n value.charCodeAt(position - 1) === 13 /* `\\r` */\n ) {\n position--\n }\n\n value = value.slice(0, position) + ' ' + value.slice(match.index + 1)\n }\n }\n\n return sequence + value + sequence\n}\n\n/**\n * @returns {string}\n */\nfunction inlineCodePeek() {\n return '`'\n}\n","/**\n * @import {State} from 'mdast-util-to-markdown'\n * @import {Link} from 'mdast'\n */\n\nimport {toString} from 'mdast-util-to-string'\n\n/**\n * @param {Link} node\n * @param {State} state\n * @returns {boolean}\n */\nexport function formatLinkAsAutolink(node, state) {\n const raw = toString(node)\n\n return Boolean(\n !state.options.resourceLink &&\n // If there’s a url…\n node.url &&\n // And there’s a no title…\n !node.title &&\n // And the content of `node` is a single text node…\n node.children &&\n node.children.length === 1 &&\n node.children[0].type === 'text' &&\n // And if the url is the same as the content…\n (raw === node.url || 'mailto:' + raw === node.url) &&\n // And that starts w/ a protocol…\n /^[a-z][a-z+.-]+:/i.test(node.url) &&\n // And that doesn’t contain ASCII control codes (character escapes and\n // references don’t work), space, or angle brackets…\n !/[\\0- <>\\u007F]/.test(node.url)\n )\n}\n","/**\n * @import {Info, State} from 'mdast-util-to-markdown'\n * @import {Link, Parents} from 'mdast'\n * @import {Exit} from '../types.js'\n */\n\nimport {checkQuote} from '../util/check-quote.js'\nimport {formatLinkAsAutolink} from '../util/format-link-as-autolink.js'\n\nlink.peek = linkPeek\n\n/**\n * @param {Link} node\n * @param {Parents | undefined} _\n * @param {State} state\n * @param {Info} info\n * @returns {string}\n */\nexport function link(node, _, state, info) {\n const quote = checkQuote(state)\n const suffix = quote === '\"' ? 'Quote' : 'Apostrophe'\n const tracker = state.createTracker(info)\n /** @type {Exit} */\n let exit\n /** @type {Exit} */\n let subexit\n\n if (formatLinkAsAutolink(node, state)) {\n // Hide the fact that we’re in phrasing, because escapes don’t work.\n const stack = state.stack\n state.stack = []\n exit = state.enter('autolink')\n let value = tracker.move('<')\n value += tracker.move(\n state.containerPhrasing(node, {\n before: value,\n after: '>',\n ...tracker.current()\n })\n )\n value += tracker.move('>')\n exit()\n state.stack = stack\n return value\n }\n\n exit = state.enter('link')\n subexit = state.enter('label')\n let value = tracker.move('[')\n value += tracker.move(\n state.containerPhrasing(node, {\n before: value,\n after: '](',\n ...tracker.current()\n })\n )\n value += tracker.move('](')\n subexit()\n\n if (\n // If there’s no url but there is a title…\n (!node.url && node.title) ||\n // If there are control characters or whitespace.\n /[\\0- \\u007F]/.test(node.url)\n ) {\n subexit = state.enter('destinationLiteral')\n value += tracker.move('<')\n value += tracker.move(\n state.safe(node.url, {before: value, after: '>', ...tracker.current()})\n )\n value += tracker.move('>')\n } else {\n // No whitespace, raw is prettier.\n subexit = state.enter('destinationRaw')\n value += tracker.move(\n state.safe(node.url, {\n before: value,\n after: node.title ? ' ' : ')',\n ...tracker.current()\n })\n )\n }\n\n subexit()\n\n if (node.title) {\n subexit = state.enter(`title${suffix}`)\n value += tracker.move(' ' + quote)\n value += tracker.move(\n state.safe(node.title, {\n before: value,\n after: quote,\n ...tracker.current()\n })\n )\n value += tracker.move(quote)\n subexit()\n }\n\n value += tracker.move(')')\n\n exit()\n return value\n}\n\n/**\n * @param {Link} node\n * @param {Parents | undefined} _\n * @param {State} state\n * @returns {string}\n */\nfunction linkPeek(node, _, state) {\n return formatLinkAsAutolink(node, state) ? '<' : '['\n}\n","/**\n * @import {Info, State} from 'mdast-util-to-markdown'\n * @import {LinkReference, Parents} from 'mdast'\n */\n\nlinkReference.peek = linkReferencePeek\n\n/**\n * @param {LinkReference} node\n * @param {Parents | undefined} _\n * @param {State} state\n * @param {Info} info\n * @returns {string}\n */\nexport function linkReference(node, _, state, info) {\n const type = node.referenceType\n const exit = state.enter('linkReference')\n let subexit = state.enter('label')\n const tracker = state.createTracker(info)\n let value = tracker.move('[')\n const text = state.containerPhrasing(node, {\n before: value,\n after: ']',\n ...tracker.current()\n })\n value += tracker.move(text + '][')\n\n subexit()\n // Hide the fact that we’re in phrasing, because escapes don’t work.\n const stack = state.stack\n state.stack = []\n subexit = state.enter('reference')\n // Note: for proper tracking, we should reset the output positions when we end\n // up making a `shortcut` reference, because then there is no brace output.\n // Practically, in that case, there is no content, so it doesn’t matter that\n // we’ve tracked one too many characters.\n const reference = state.safe(state.associationId(node), {\n before: value,\n after: ']',\n ...tracker.current()\n })\n subexit()\n state.stack = stack\n exit()\n\n if (type === 'full' || !text || text !== reference) {\n value += tracker.move(reference + ']')\n } else if (type === 'shortcut') {\n // Remove the unwanted `[`.\n value = value.slice(0, -1)\n } else {\n value += tracker.move(']')\n }\n\n return value\n}\n\n/**\n * @returns {string}\n */\nfunction linkReferencePeek() {\n return '['\n}\n","/**\n * @import {Options, State} from 'mdast-util-to-markdown'\n */\n\n/**\n * @param {State} state\n * @returns {Exclude<Options['bullet'], null | undefined>}\n */\nexport function checkBullet(state) {\n const marker = state.options.bullet || '*'\n\n if (marker !== '*' && marker !== '+' && marker !== '-') {\n throw new Error(\n 'Cannot serialize items with `' +\n marker +\n '` for `options.bullet`, expected `*`, `+`, or `-`'\n )\n }\n\n return marker\n}\n","/**\n * @import {Options, State} from 'mdast-util-to-markdown'\n */\n\nimport {checkBullet} from './check-bullet.js'\n\n/**\n * @param {State} state\n * @returns {Exclude<Options['bullet'], null | undefined>}\n */\nexport function checkBulletOther(state) {\n const bullet = checkBullet(state)\n const bulletOther = state.options.bulletOther\n\n if (!bulletOther) {\n return bullet === '*' ? '-' : '*'\n }\n\n if (bulletOther !== '*' && bulletOther !== '+' && bulletOther !== '-') {\n throw new Error(\n 'Cannot serialize items with `' +\n bulletOther +\n '` for `options.bulletOther`, expected `*`, `+`, or `-`'\n )\n }\n\n if (bulletOther === bullet) {\n throw new Error(\n 'Expected `bullet` (`' +\n bullet +\n '`) and `bulletOther` (`' +\n bulletOther +\n '`) to be different'\n )\n }\n\n return bulletOther\n}\n","/**\n * @import {Options, State} from 'mdast-util-to-markdown'\n */\n\n/**\n * @param {State} state\n * @returns {Exclude<Options['bulletOrdered'], null | undefined>}\n */\nexport function checkBulletOrdered(state) {\n const marker = state.options.bulletOrdered || '.'\n\n if (marker !== '.' && marker !== ')') {\n throw new Error(\n 'Cannot serialize items with `' +\n marker +\n '` for `options.bulletOrdered`, expected `.` or `)`'\n )\n }\n\n return marker\n}\n","/**\n * @import {Options, State} from 'mdast-util-to-markdown'\n */\n\n/**\n * @param {State} state\n * @returns {Exclude<Options['rule'], null | undefined>}\n */\nexport function checkRule(state) {\n const marker = state.options.rule || '*'\n\n if (marker !== '*' && marker !== '-' && marker !== '_') {\n throw new Error(\n 'Cannot serialize rules with `' +\n marker +\n '` for `options.rule`, expected `*`, `-`, or `_`'\n )\n }\n\n return marker\n}\n","/**\n * @import {Info, State} from 'mdast-util-to-markdown'\n * @import {List, Parents} from 'mdast'\n */\n\nimport {checkBullet} from '../util/check-bullet.js'\nimport {checkBulletOther} from '../util/check-bullet-other.js'\nimport {checkBulletOrdered} from '../util/check-bullet-ordered.js'\nimport {checkRule} from '../util/check-rule.js'\n\n/**\n * @param {List} node\n * @param {Parents | undefined} parent\n * @param {State} state\n * @param {Info} info\n * @returns {string}\n */\nexport function list(node, parent, state, info) {\n const exit = state.enter('list')\n const bulletCurrent = state.bulletCurrent\n /** @type {string} */\n let bullet = node.ordered ? checkBulletOrdered(state) : checkBullet(state)\n /** @type {string} */\n const bulletOther = node.ordered\n ? bullet === '.'\n ? ')'\n : '.'\n : checkBulletOther(state)\n let useDifferentMarker =\n parent && state.bulletLastUsed ? bullet === state.bulletLastUsed : false\n\n if (!node.ordered) {\n const firstListItem = node.children ? node.children[0] : undefined\n\n // If there’s an empty first list item directly in two list items,\n // we have to use a different bullet:\n //\n // ```markdown\n // * - *\n // ```\n //\n // …because otherwise it would become one big thematic break.\n if (\n // Bullet could be used as a thematic break marker:\n (bullet === '*' || bullet === '-') &&\n // Empty first list item:\n firstListItem &&\n (!firstListItem.children || !firstListItem.children[0]) &&\n // Directly in two other list items:\n state.stack[state.stack.length - 1] === 'list' &&\n state.stack[state.stack.length - 2] === 'listItem' &&\n state.stack[state.stack.length - 3] === 'list' &&\n state.stack[state.stack.length - 4] === 'listItem' &&\n // That are each the first child.\n state.indexStack[state.indexStack.length - 1] === 0 &&\n state.indexStack[state.indexStack.length - 2] === 0 &&\n state.indexStack[state.indexStack.length - 3] === 0\n ) {\n useDifferentMarker = true\n }\n\n // If there’s a thematic break at the start of the first list item,\n // we have to use a different bullet:\n //\n // ```markdown\n // * ---\n // ```\n //\n // …because otherwise it would become one big thematic break.\n if (checkRule(state) === bullet && firstListItem) {\n let index = -1\n\n while (++index < node.children.length) {\n const item = node.children[index]\n\n if (\n item &&\n item.type === 'listItem' &&\n item.children &&\n item.children[0] &&\n item.children[0].type === 'thematicBreak'\n ) {\n useDifferentMarker = true\n break\n }\n }\n }\n }\n\n if (useDifferentMarker) {\n bullet = bulletOther\n }\n\n state.bulletCurrent = bullet\n const value = state.containerFlow(node, info)\n state.bulletLastUsed = bullet\n state.bulletCurrent = bulletCurrent\n exit()\n return value\n}\n","/**\n * @import {Options, State} from 'mdast-util-to-markdown'\n */\n\n/**\n * @param {State} state\n * @returns {Exclude<Options['listItemIndent'], null | undefined>}\n */\nexport function checkListItemIndent(state) {\n const style = state.options.listItemIndent || 'one'\n\n if (style !== 'tab' && style !== 'one' && style !== 'mixed') {\n throw new Error(\n 'Cannot serialize items with `' +\n style +\n '` for `options.listItemIndent`, expected `tab`, `one`, or `mixed`'\n )\n }\n\n return style\n}\n","/**\n * @import {Info, Map, State} from 'mdast-util-to-markdown'\n * @import {ListItem, Parents} from 'mdast'\n */\n\nimport {checkBullet} from '../util/check-bullet.js'\nimport {checkListItemIndent} from '../util/check-list-item-indent.js'\n\n/**\n * @param {ListItem} node\n * @param {Parents | undefined} parent\n * @param {State} state\n * @param {Info} info\n * @returns {string}\n */\nexport function listItem(node, parent, state, info) {\n const listItemIndent = checkListItemIndent(state)\n let bullet = state.bulletCurrent || checkBullet(state)\n\n // Add the marker value for ordered lists.\n if (parent && parent.type === 'list' && parent.ordered) {\n bullet =\n (typeof parent.start === 'number' && parent.start > -1\n ? parent.start\n : 1) +\n (state.options.incrementListMarker === false\n ? 0\n : parent.children.indexOf(node)) +\n bullet\n }\n\n let size = bullet.length + 1\n\n if (\n listItemIndent === 'tab' ||\n (listItemIndent === 'mixed' &&\n ((parent && parent.type === 'list' && parent.spread) || node.spread))\n ) {\n size = Math.ceil(size / 4) * 4\n }\n\n const tracker = state.createTracker(info)\n tracker.move(bullet + ' '.repeat(size - bullet.length))\n tracker.shift(size)\n const exit = state.enter('listItem')\n const value = state.indentLines(\n state.containerFlow(node, tracker.current()),\n map\n )\n exit()\n\n return value\n\n /** @type {Map} */\n function map(line, index, blank) {\n if (index) {\n return (blank ? '' : ' '.repeat(size)) + line\n }\n\n return (blank ? bullet : bullet + ' '.repeat(size - bullet.length)) + line\n }\n}\n","/**\n * @import {Info, State} from 'mdast-util-to-markdown'\n * @import {Paragraph, Parents} from 'mdast'\n */\n\n/**\n * @param {Paragraph} node\n * @param {Parents | undefined} _\n * @param {State} state\n * @param {Info} info\n * @returns {string}\n */\nexport function paragraph(node, _, state, info) {\n const exit = state.enter('paragraph')\n const subexit = state.enter('phrasing')\n const value = state.containerPhrasing(node, info)\n subexit()\n exit()\n return value\n}\n","/**\n * @typedef {import('mdast').Html} Html\n * @typedef {import('mdast').PhrasingContent} PhrasingContent\n */\n\nimport {convert} from 'unist-util-is'\n\n/**\n * Check if the given value is *phrasing content*.\n *\n * > 👉 **Note**: Excludes `html`, which can be both phrasing or flow.\n *\n * @param node\n * Thing to check, typically `Node`.\n * @returns\n * Whether `value` is phrasing content.\n */\n\nexport const phrasing =\n /** @type {(node?: unknown) => node is Exclude<PhrasingContent, Html>} */\n (\n convert([\n 'break',\n 'delete',\n 'emphasis',\n // To do: next major: removed since footnotes were added to GFM.\n 'footnote',\n 'footnoteReference',\n 'image',\n 'imageReference',\n 'inlineCode',\n // Enabled by `mdast-util-math`:\n 'inlineMath',\n 'link',\n 'linkReference',\n // Enabled by `mdast-util-mdx`:\n 'mdxJsxTextElement',\n // Enabled by `mdast-util-mdx`:\n 'mdxTextExpression',\n 'strong',\n 'text',\n // Enabled by `mdast-util-directive`:\n 'textDirective'\n ])\n )\n","/**\n * @import {Info, State} from 'mdast-util-to-markdown'\n * @import {Parents, Root} from 'mdast'\n */\n\nimport {phrasing} from 'mdast-util-phrasing'\n\n/**\n * @param {Root} node\n * @param {Parents | undefined} _\n * @param {State} state\n * @param {Info} info\n * @returns {string}\n */\nexport function root(node, _, state, info) {\n // Note: `html` nodes are ambiguous.\n const hasPhrasing = node.children.some(function (d) {\n return phrasing(d)\n })\n\n const container = hasPhrasing ? state.containerPhrasing : state.containerFlow\n return container.call(state, node, info)\n}\n","/**\n * @import {Options, State} from 'mdast-util-to-markdown'\n */\n\n/**\n * @param {State} state\n * @returns {Exclude<Options['strong'], null | undefined>}\n */\nexport function checkStrong(state) {\n const marker = state.options.strong || '*'\n\n if (marker !== '*' && marker !== '_') {\n throw new Error(\n 'Cannot serialize strong with `' +\n marker +\n '` for `options.strong`, expected `*`, or `_`'\n )\n }\n\n return marker\n}\n","/**\n * @import {Info, State} from 'mdast-util-to-markdown'\n * @import {Parents, Strong} from 'mdast'\n */\n\nimport {checkStrong} from '../util/check-strong.js'\nimport {encodeCharacterReference} from '../util/encode-character-reference.js'\nimport {encodeInfo} from '../util/encode-info.js'\n\nstrong.peek = strongPeek\n\n/**\n * @param {Strong} node\n * @param {Parents | undefined} _\n * @param {State} state\n * @param {Info} info\n * @returns {string}\n */\nexport function strong(node, _, state, info) {\n const marker = checkStrong(state)\n const exit = state.enter('strong')\n const tracker = state.createTracker(info)\n const before = tracker.move(marker + marker)\n\n let between = tracker.move(\n state.containerPhrasing(node, {\n after: marker,\n before,\n ...tracker.current()\n })\n )\n const betweenHead = between.charCodeAt(0)\n const open = encodeInfo(\n info.before.charCodeAt(info.before.length - 1),\n betweenHead,\n marker\n )\n\n if (open.inside) {\n between = encodeCharacterReference(betweenHead) + between.slice(1)\n }\n\n const betweenTail = between.charCodeAt(between.length - 1)\n const close = encodeInfo(info.after.charCodeAt(0), betweenTail, marker)\n\n if (close.inside) {\n between = between.slice(0, -1) + encodeCharacterReference(betweenTail)\n }\n\n const after = tracker.move(marker + marker)\n\n exit()\n\n state.attentionEncodeSurroundingInfo = {\n after: close.outside,\n before: open.outside\n }\n return before + between + after\n}\n\n/**\n * @param {Strong} _\n * @param {Parents | undefined} _1\n * @param {State} state\n * @returns {string}\n */\nfunction strongPeek(_, _1, state) {\n return state.options.strong || '*'\n}\n","/**\n * @import {Info, State} from 'mdast-util-to-markdown'\n * @import {Parents, Text} from 'mdast'\n */\n\n/**\n * @param {Text} node\n * @param {Parents | undefined} _\n * @param {State} state\n * @param {Info} info\n * @returns {string}\n */\nexport function text(node, _, state, info) {\n return state.safe(node.value, info)\n}\n","/**\n * @import {Options, State} from 'mdast-util-to-markdown'\n */\n\n/**\n * @param {State} state\n * @returns {Exclude<Options['ruleRepetition'], null | undefined>}\n */\nexport function checkRuleRepetition(state) {\n const repetition = state.options.ruleRepetition || 3\n\n if (repetition < 3) {\n throw new Error(\n 'Cannot serialize rules with repetition `' +\n repetition +\n '` for `options.ruleRepetition`, expected `3` or more'\n )\n }\n\n return repetition\n}\n","/**\n * @import {State} from 'mdast-util-to-markdown'\n * @import {Parents, ThematicBreak} from 'mdast'\n */\n\nimport {checkRuleRepetition} from '../util/check-rule-repetition.js'\nimport {checkRule} from '../util/check-rule.js'\n\n/**\n * @param {ThematicBreak} _\n * @param {Parents | undefined} _1\n * @param {State} state\n * @returns {string}\n */\nexport function thematicBreak(_, _1, state) {\n const value = (\n checkRule(state) + (state.options.ruleSpaces ? ' ' : '')\n ).repeat(checkRuleRepetition(state))\n\n return state.options.ruleSpaces ? value.slice(0, -1) : value\n}\n","import {blockquote} from './blockquote.js'\nimport {hardBreak} from './break.js'\nimport {code} from './code.js'\nimport {definition} from './definition.js'\nimport {emphasis} from './emphasis.js'\nimport {heading} from './heading.js'\nimport {html} from './html.js'\nimport {image} from './image.js'\nimport {imageReference} from './image-reference.js'\nimport {inlineCode} from './inline-code.js'\nimport {link} from './link.js'\nimport {linkReference} from './link-reference.js'\nimport {list} from './list.js'\nimport {listItem} from './list-item.js'\nimport {paragraph} from './paragraph.js'\nimport {root} from './root.js'\nimport {strong} from './strong.js'\nimport {text} from './text.js'\nimport {thematicBreak} from './thematic-break.js'\n\n/**\n * Default (CommonMark) handlers.\n */\nexport const handle = {\n blockquote,\n break: hardBreak,\n code,\n definition,\n emphasis,\n hardBreak,\n heading,\n html,\n image,\n imageReference,\n inlineCode,\n link,\n linkReference,\n list,\n listItem,\n paragraph,\n root,\n strong,\n text,\n thematicBreak\n}\n","/**\n * @typedef {import('mdast').InlineCode} InlineCode\n * @typedef {import('mdast').Table} Table\n * @typedef {import('mdast').TableCell} TableCell\n * @typedef {import('mdast').TableRow} TableRow\n *\n * @typedef {import('markdown-table').Options} MarkdownTableOptions\n *\n * @typedef {import('mdast-util-from-markdown').CompileContext} CompileContext\n * @typedef {import('mdast-util-from-markdown').Extension} FromMarkdownExtension\n * @typedef {import('mdast-util-from-markdown').Handle} FromMarkdownHandle\n *\n * @typedef {import('mdast-util-to-markdown').Options} ToMarkdownExtension\n * @typedef {import('mdast-util-to-markdown').Handle} ToMarkdownHandle\n * @typedef {import('mdast-util-to-markdown').State} State\n * @typedef {import('mdast-util-to-markdown').Info} Info\n */\n\n/**\n * @typedef Options\n * Configuration.\n * @property {boolean | null | undefined} [tableCellPadding=true]\n * Whether to add a space of padding between delimiters and cells (default:\n * `true`).\n * @property {boolean | null | undefined} [tablePipeAlign=true]\n * Whether to align the delimiters (default: `true`).\n * @property {MarkdownTableOptions['stringLength'] | null | undefined} [stringLength]\n * Function to detect the length of table cell content, used when aligning\n * the delimiters between cells (optional).\n */\n\nimport {ok as assert} from 'devlop'\nimport {markdownTable} from 'markdown-table'\nimport {defaultHandlers} from 'mdast-util-to-markdown'\n\n/**\n * Create an extension for `mdast-util-from-markdown` to enable GFM tables in\n * markdown.\n *\n * @returns {FromMarkdownExtension}\n * Extension for `mdast-util-from-markdown` to enable GFM tables.\n */\nexport function gfmTableFromMarkdown() {\n return {\n enter: {\n table: enterTable,\n tableData: enterCell,\n tableHeader: enterCell,\n tableRow: enterRow\n },\n exit: {\n codeText: exitCodeText,\n table: exitTable,\n tableData: exit,\n tableHeader: exit,\n tableRow: exit\n }\n }\n}\n\n/**\n * @this {CompileContext}\n * @type {FromMarkdownHandle}\n */\nfunction enterTable(token) {\n const align = token._align\n assert(align, 'expected `_align` on table')\n this.enter(\n {\n type: 'table',\n align: align.map(function (d) {\n return d === 'none' ? null : d\n }),\n children: []\n },\n token\n )\n this.data.inTable = true\n}\n\n/**\n * @this {CompileContext}\n * @type {FromMarkdownHandle}\n */\nfunction exitTable(token) {\n this.exit(token)\n this.data.inTable = undefined\n}\n\n/**\n * @this {CompileContext}\n * @type {FromMarkdownHandle}\n */\nfunction enterRow(token) {\n this.enter({type: 'tableRow', children: []}, token)\n}\n\n/**\n * @this {CompileContext}\n * @type {FromMarkdownHandle}\n */\nfunction exit(token) {\n this.exit(token)\n}\n\n/**\n * @this {CompileContext}\n * @type {FromMarkdownHandle}\n */\nfunction enterCell(token) {\n this.enter({type: 'tableCell', children: []}, token)\n}\n\n// Overwrite the default code text data handler to unescape escaped pipes when\n// they are in tables.\n/**\n * @this {CompileContext}\n * @type {FromMarkdownHandle}\n */\nfunction exitCodeText(token) {\n let value = this.resume()\n\n if (this.data.inTable) {\n value = value.replace(/\\\\([\\\\|])/g, replace)\n }\n\n const node = this.stack[this.stack.length - 1]\n assert(node.type === 'inlineCode')\n node.value = value\n this.exit(token)\n}\n\n/**\n * @param {string} $0\n * @param {string} $1\n * @returns {string}\n */\nfunction replace($0, $1) {\n // Pipes work, backslashes don’t (but can’t escape pipes).\n return $1 === '|' ? $1 : $0\n}\n\n/**\n * Create an extension for `mdast-util-to-markdown` to enable GFM tables in\n * markdown.\n *\n * @param {Options | null | undefined} [options]\n * Configuration.\n * @returns {ToMarkdownExtension}\n * Extension for `mdast-util-to-markdown` to enable GFM tables.\n */\nexport function gfmTableToMarkdown(options) {\n const settings = options || {}\n const padding = settings.tableCellPadding\n const alignDelimiters = settings.tablePipeAlign\n const stringLength = settings.stringLength\n const around = padding ? ' ' : '|'\n\n return {\n unsafe: [\n {character: '\\r', inConstruct: 'tableCell'},\n {character: '\\n', inConstruct: 'tableCell'},\n // A pipe, when followed by a tab or space (padding), or a dash or colon\n // (unpadded delimiter row), could result in a table.\n {atBreak: true, character: '|', after: '[\\t :-]'},\n // A pipe in a cell must be encoded.\n {character: '|', inConstruct: 'tableCell'},\n // A colon must be followed by a dash, in which case it could start a\n // delimiter row.\n {atBreak: true, character: ':', after: '-'},\n // A delimiter row can also start with a dash, when followed by more\n // dashes, a colon, or a pipe.\n // This is a stricter version than the built in check for lists, thematic\n // breaks, and setex heading underlines though:\n // <https://github.com/syntax-tree/mdast-util-to-markdown/blob/51a2038/lib/unsafe.js#L57>\n {atBreak: true, character: '-', after: '[:|-]'}\n ],\n handlers: {\n inlineCode: inlineCodeWithTable,\n table: handleTable,\n tableCell: handleTableCell,\n tableRow: handleTableRow\n }\n }\n\n /**\n * @type {ToMarkdownHandle}\n * @param {Table} node\n */\n function handleTable(node, _, state, info) {\n return serializeData(handleTableAsData(node, state, info), node.align)\n }\n\n /**\n * This function isn’t really used normally, because we handle rows at the\n * table level.\n * But, if someone passes in a table row, this ensures we make somewhat sense.\n *\n * @type {ToMarkdownHandle}\n * @param {TableRow} node\n */\n function handleTableRow(node, _, state, info) {\n const row = handleTableRowAsData(node, state, info)\n const value = serializeData([row])\n // `markdown-table` will always add an align row\n return value.slice(0, value.indexOf('\\n'))\n }\n\n /**\n * @type {ToMarkdownHandle}\n * @param {TableCell} node\n */\n function handleTableCell(node, _, state, info) {\n const exit = state.enter('tableCell')\n const subexit = state.enter('phrasing')\n const value = state.containerPhrasing(node, {\n ...info,\n before: around,\n after: around\n })\n subexit()\n exit()\n return value\n }\n\n /**\n * @param {Array<Array<string>>} matrix\n * @param {Array<string | null | undefined> | null | undefined} [align]\n */\n function serializeData(matrix, align) {\n return markdownTable(matrix, {\n align,\n // @ts-expect-error: `markdown-table` types should support `null`.\n alignDelimiters,\n // @ts-expect-error: `markdown-table` types should support `null`.\n padding,\n // @ts-expect-error: `markdown-table` types should support `null`.\n stringLength\n })\n }\n\n /**\n * @param {Table} node\n * @param {State} state\n * @param {Info} info\n */\n function handleTableAsData(node, state, info) {\n const children = node.children\n let index = -1\n /** @type {Array<Array<string>>} */\n const result = []\n const subexit = state.enter('table')\n\n while (++index < children.length) {\n result[index] = handleTableRowAsData(children[index], state, info)\n }\n\n subexit()\n\n return result\n }\n\n /**\n * @param {TableRow} node\n * @param {State} state\n * @param {Info} info\n */\n function handleTableRowAsData(node, state, info) {\n const children = node.children\n let index = -1\n /** @type {Array<string>} */\n const result = []\n const subexit = state.enter('tableRow')\n\n while (++index < children.length) {\n // Note: the positional info as used here is incorrect.\n // Making it correct would be impossible due to aligning cells?\n // And it would need copy/pasting `markdown-table` into this project.\n result[index] = handleTableCell(children[index], node, state, info)\n }\n\n subexit()\n\n return result\n }\n\n /**\n * @type {ToMarkdownHandle}\n * @param {InlineCode} node\n */\n function inlineCodeWithTable(node, parent, state) {\n let value = defaultHandlers.inlineCode(node, parent, state)\n\n if (state.stack.includes('tableCell')) {\n value = value.replace(/\\|/g, '\\\\$&')\n }\n\n return value\n }\n}\n","/**\n * @typedef {import('mdast').ListItem} ListItem\n * @typedef {import('mdast').Paragraph} Paragraph\n * @typedef {import('mdast-util-from-markdown').CompileContext} CompileContext\n * @typedef {import('mdast-util-from-markdown').Extension} FromMarkdownExtension\n * @typedef {import('mdast-util-from-markdown').Handle} FromMarkdownHandle\n * @typedef {import('mdast-util-to-markdown').Options} ToMarkdownExtension\n * @typedef {import('mdast-util-to-markdown').Handle} ToMarkdownHandle\n */\n\nimport {ok as assert} from 'devlop'\nimport {defaultHandlers} from 'mdast-util-to-markdown'\n\n/**\n * Create an extension for `mdast-util-from-markdown` to enable GFM task\n * list items in markdown.\n *\n * @returns {FromMarkdownExtension}\n * Extension for `mdast-util-from-markdown` to enable GFM task list items.\n */\nexport function gfmTaskListItemFromMarkdown() {\n return {\n exit: {\n taskListCheckValueChecked: exitCheck,\n taskListCheckValueUnchecked: exitCheck,\n paragraph: exitParagraphWithTaskListItem\n }\n }\n}\n\n/**\n * Create an extension for `mdast-util-to-markdown` to enable GFM task list\n * items in markdown.\n *\n * @returns {ToMarkdownExtension}\n * Extension for `mdast-util-to-markdown` to enable GFM task list items.\n */\nexport function gfmTaskListItemToMarkdown() {\n return {\n unsafe: [{atBreak: true, character: '-', after: '[:|-]'}],\n handlers: {listItem: listItemWithTaskListItem}\n }\n}\n\n/**\n * @this {CompileContext}\n * @type {FromMarkdownHandle}\n */\nfunction exitCheck(token) {\n // We’re always in a paragraph, in a list item.\n const node = this.stack[this.stack.length - 2]\n assert(node.type === 'listItem')\n node.checked = token.type === 'taskListCheckValueChecked'\n}\n\n/**\n * @this {CompileContext}\n * @type {FromMarkdownHandle}\n */\nfunction exitParagraphWithTaskListItem(token) {\n const parent = this.stack[this.stack.length - 2]\n\n if (\n parent &&\n parent.type === 'listItem' &&\n typeof parent.checked === 'boolean'\n ) {\n const node = this.stack[this.stack.length - 1]\n assert(node.type === 'paragraph')\n const head = node.children[0]\n\n if (head && head.type === 'text') {\n const siblings = parent.children\n let index = -1\n /** @type {Paragraph | undefined} */\n let firstParaghraph\n\n while (++index < siblings.length) {\n const sibling = siblings[index]\n if (sibling.type === 'paragraph') {\n firstParaghraph = sibling\n break\n }\n }\n\n if (firstParaghraph === node) {\n // Must start with a space or a tab.\n head.value = head.value.slice(1)\n\n if (head.value.length === 0) {\n node.children.shift()\n } else if (\n node.position &&\n head.position &&\n typeof head.position.start.offset === 'number'\n ) {\n head.position.start.column++\n head.position.start.offset++\n node.position.start = Object.assign({}, head.position.start)\n }\n }\n }\n }\n\n this.exit(token)\n}\n\n/**\n * @type {ToMarkdownHandle}\n * @param {ListItem} node\n */\nfunction listItemWithTaskListItem(node, parent, state, info) {\n const head = node.children[0]\n const checkable =\n typeof node.checked === 'boolean' && head && head.type === 'paragraph'\n const checkbox = '[' + (node.checked ? 'x' : ' ') + '] '\n const tracker = state.createTracker(info)\n\n if (checkable) {\n tracker.move(checkbox)\n }\n\n let value = defaultHandlers.listItem(node, parent, state, {\n ...info,\n ...tracker.current()\n })\n\n if (checkable) {\n value = value.replace(/^(?:[*+-]|\\d+\\.)([\\r\\n]| {1,3})/, check)\n }\n\n return value\n\n /**\n * @param {string} $0\n * @returns {string}\n */\n function check($0) {\n return $0 + checkbox\n }\n}\n","/**\n * @import {Extension as FromMarkdownExtension} from 'mdast-util-from-markdown'\n * @import {Options} from 'mdast-util-gfm'\n * @import {Options as ToMarkdownExtension} from 'mdast-util-to-markdown'\n */\n\nimport {\n gfmAutolinkLiteralFromMarkdown,\n gfmAutolinkLiteralToMarkdown\n} from 'mdast-util-gfm-autolink-literal'\nimport {\n gfmFootnoteFromMarkdown,\n gfmFootnoteToMarkdown\n} from 'mdast-util-gfm-footnote'\nimport {\n gfmStrikethroughFromMarkdown,\n gfmStrikethroughToMarkdown\n} from 'mdast-util-gfm-strikethrough'\nimport {gfmTableFromMarkdown, gfmTableToMarkdown} from 'mdast-util-gfm-table'\nimport {\n gfmTaskListItemFromMarkdown,\n gfmTaskListItemToMarkdown\n} from 'mdast-util-gfm-task-list-item'\n\n/**\n * Create an extension for `mdast-util-from-markdown` to enable GFM (autolink\n * literals, footnotes, strikethrough, tables, tasklists).\n *\n * @returns {Array<FromMarkdownExtension>}\n * Extension for `mdast-util-from-markdown` to enable GFM (autolink literals,\n * footnotes, strikethrough, tables, tasklists).\n */\nexport function gfmFromMarkdown() {\n return [\n gfmAutolinkLiteralFromMarkdown(),\n gfmFootnoteFromMarkdown(),\n gfmStrikethroughFromMarkdown(),\n gfmTableFromMarkdown(),\n gfmTaskListItemFromMarkdown()\n ]\n}\n\n/**\n * Create an extension for `mdast-util-to-markdown` to enable GFM (autolink\n * literals, footnotes, strikethrough, tables, tasklists).\n *\n * @param {Options | null | undefined} [options]\n * Configuration (optional).\n * @returns {ToMarkdownExtension}\n * Extension for `mdast-util-to-markdown` to enable GFM (autolink literals,\n * footnotes, strikethrough, tables, tasklists).\n */\nexport function gfmToMarkdown(options) {\n return {\n extensions: [\n gfmAutolinkLiteralToMarkdown(),\n gfmFootnoteToMarkdown(options),\n gfmStrikethroughToMarkdown(),\n gfmTableToMarkdown(options),\n gfmTaskListItemToMarkdown()\n ]\n }\n}\n","/**\n * Like `Array#splice`, but smarter for giant arrays.\n *\n * `Array#splice` takes all items to be inserted as individual argument which\n * causes a stack overflow in V8 when trying to insert 100k items for instance.\n *\n * Otherwise, this does not return the removed items, and takes `items` as an\n * array instead of rest parameters.\n *\n * @template {unknown} T\n * Item type.\n * @param {Array<T>} list\n * List to operate on.\n * @param {number} start\n * Index to remove/insert at (can be negative).\n * @param {number} remove\n * Number of items to remove.\n * @param {Array<T>} items\n * Items to inject into `list`.\n * @returns {undefined}\n * Nothing.\n */\nexport function splice(list, start, remove, items) {\n const end = list.length;\n let chunkStart = 0;\n /** @type {Array<unknown>} */\n let parameters;\n\n // Make start between zero and `end` (included).\n if (start < 0) {\n start = -start > end ? 0 : end + start;\n } else {\n start = start > end ? end : start;\n }\n remove = remove > 0 ? remove : 0;\n\n // No need to chunk the items if there’s only a couple (10k) items.\n if (items.length < 10000) {\n parameters = Array.from(items);\n parameters.unshift(start, remove);\n // @ts-expect-error Hush, it’s fine.\n list.splice(...parameters);\n } else {\n // Delete `remove` items starting from `start`\n if (remove) list.splice(start, remove);\n\n // Insert the items in chunks to not cause stack overflows.\n while (chunkStart < items.length) {\n parameters = items.slice(chunkStart, chunkStart + 10000);\n parameters.unshift(start, 0);\n // @ts-expect-error Hush, it’s fine.\n list.splice(...parameters);\n chunkStart += 10000;\n start += 10000;\n }\n }\n}\n\n/**\n * Append `items` (an array) at the end of `list` (another array).\n * When `list` was empty, returns `items` instead.\n *\n * This prevents a potentially expensive operation when `list` is empty,\n * and adds items in batches to prevent V8 from hanging.\n *\n * @template {unknown} T\n * Item type.\n * @param {Array<T>} list\n * List to operate on.\n * @param {Array<T>} items\n * Items to add to `list`.\n * @returns {Array<T>}\n * Either `list` or `items`.\n */\nexport function push(list, items) {\n if (list.length > 0) {\n splice(list, list.length, 0, items);\n return list;\n }\n return items;\n}","/**\n * @import {\n * Extension,\n * Handles,\n * HtmlExtension,\n * NormalizedExtension\n * } from 'micromark-util-types'\n */\n\nimport {splice} from 'micromark-util-chunked'\n\nconst hasOwnProperty = {}.hasOwnProperty\n\n/**\n * Combine multiple syntax extensions into one.\n *\n * @param {ReadonlyArray<Extension>} extensions\n * List of syntax extensions.\n * @returns {NormalizedExtension}\n * A single combined extension.\n */\nexport function combineExtensions(extensions) {\n /** @type {NormalizedExtension} */\n const all = {}\n let index = -1\n\n while (++index < extensions.length) {\n syntaxExtension(all, extensions[index])\n }\n\n return all\n}\n\n/**\n * Merge `extension` into `all`.\n *\n * @param {NormalizedExtension} all\n * Extension to merge into.\n * @param {Extension} extension\n * Extension to merge.\n * @returns {undefined}\n * Nothing.\n */\nfunction syntaxExtension(all, extension) {\n /** @type {keyof Extension} */\n let hook\n\n for (hook in extension) {\n const maybe = hasOwnProperty.call(all, hook) ? all[hook] : undefined\n /** @type {Record<string, unknown>} */\n const left = maybe || (all[hook] = {})\n /** @type {Record<string, unknown> | undefined} */\n const right = extension[hook]\n /** @type {string} */\n let code\n\n if (right) {\n for (code in right) {\n if (!hasOwnProperty.call(left, code)) left[code] = []\n const value = right[code]\n constructs(\n // @ts-expect-error Looks like a list.\n left[code],\n Array.isArray(value) ? value : value ? [value] : []\n )\n }\n }\n }\n}\n\n/**\n * Merge `list` into `existing` (both lists of constructs).\n * Mutates `existing`.\n *\n * @param {Array<unknown>} existing\n * List of constructs to merge into.\n * @param {Array<unknown>} list\n * List of constructs to merge.\n * @returns {undefined}\n * Nothing.\n */\nfunction constructs(existing, list) {\n let index = -1\n /** @type {Array<unknown>} */\n const before = []\n\n while (++index < list.length) {\n // @ts-expect-error Looks like an object.\n ;(list[index].add === 'after' ? existing : before).push(list[index])\n }\n\n splice(existing, 0, 0, before)\n}\n\n/**\n * Combine multiple HTML extensions into one.\n *\n * @param {ReadonlyArray<HtmlExtension>} htmlExtensions\n * List of HTML extensions.\n * @returns {HtmlExtension}\n * Single combined HTML extension.\n */\nexport function combineHtmlExtensions(htmlExtensions) {\n /** @type {HtmlExtension} */\n const handlers = {}\n let index = -1\n\n while (++index < htmlExtensions.length) {\n htmlExtension(handlers, htmlExtensions[index])\n }\n\n return handlers\n}\n\n/**\n * Merge `extension` into `all`.\n *\n * @param {HtmlExtension} all\n * Extension to merge into.\n * @param {HtmlExtension} extension\n * Extension to merge.\n * @returns {undefined}\n * Nothing.\n */\nfunction htmlExtension(all, extension) {\n /** @type {keyof HtmlExtension} */\n let hook\n\n for (hook in extension) {\n const maybe = hasOwnProperty.call(all, hook) ? all[hook] : undefined\n const left = maybe || (all[hook] = {})\n const right = extension[hook]\n /** @type {keyof Handles} */\n let type\n\n if (right) {\n for (type in right) {\n // @ts-expect-error assume document vs regular handler are managed correctly.\n left[type] = right[type]\n }\n }\n }\n}\n","/**\n * @import {Code, ConstructRecord, Event, Extension, Previous, State, TokenizeContext, Tokenizer} from 'micromark-util-types'\n */\n\nimport { asciiAlpha, asciiAlphanumeric, asciiControl, markdownLineEndingOrSpace, unicodePunctuation, unicodeWhitespace } from 'micromark-util-character';\nconst wwwPrefix = {\n tokenize: tokenizeWwwPrefix,\n partial: true\n};\nconst domain = {\n tokenize: tokenizeDomain,\n partial: true\n};\nconst path = {\n tokenize: tokenizePath,\n partial: true\n};\nconst trail = {\n tokenize: tokenizeTrail,\n partial: true\n};\nconst emailDomainDotTrail = {\n tokenize: tokenizeEmailDomainDotTrail,\n partial: true\n};\nconst wwwAutolink = {\n name: 'wwwAutolink',\n tokenize: tokenizeWwwAutolink,\n previous: previousWww\n};\nconst protocolAutolink = {\n name: 'protocolAutolink',\n tokenize: tokenizeProtocolAutolink,\n previous: previousProtocol\n};\nconst emailAutolink = {\n name: 'emailAutolink',\n tokenize: tokenizeEmailAutolink,\n previous: previousEmail\n};\n\n/** @type {ConstructRecord} */\nconst text = {};\n\n/**\n * Create an extension for `micromark` to support GitHub autolink literal\n * syntax.\n *\n * @returns {Extension}\n * Extension for `micromark` that can be passed in `extensions` to enable GFM\n * autolink literal syntax.\n */\nexport function gfmAutolinkLiteral() {\n return {\n text\n };\n}\n\n/** @type {Code} */\nlet code = 48;\n\n// Add alphanumerics.\nwhile (code < 123) {\n text[code] = emailAutolink;\n code++;\n if (code === 58) code = 65;else if (code === 91) code = 97;\n}\ntext[43] = emailAutolink;\ntext[45] = emailAutolink;\ntext[46] = emailAutolink;\ntext[95] = emailAutolink;\ntext[72] = [emailAutolink, protocolAutolink];\ntext[104] = [emailAutolink, protocolAutolink];\ntext[87] = [emailAutolink, wwwAutolink];\ntext[119] = [emailAutolink, wwwAutolink];\n\n// To do: perform email autolink literals on events, afterwards.\n// That’s where `markdown-rs` and `cmark-gfm` perform it.\n// It should look for `@`, then for atext backwards, and then for a label\n// forwards.\n// To do: `mailto:`, `xmpp:` protocol as prefix.\n\n/**\n * Email autolink literal.\n *\n * ```markdown\n * > | a contact@example.org b\n * ^^^^^^^^^^^^^^^^^^^\n * ```\n *\n * @this {TokenizeContext}\n * @type {Tokenizer}\n */\nfunction tokenizeEmailAutolink(effects, ok, nok) {\n const self = this;\n /** @type {boolean | undefined} */\n let dot;\n /** @type {boolean} */\n let data;\n return start;\n\n /**\n * Start of email autolink literal.\n *\n * ```markdown\n * > | a contact@example.org b\n * ^\n * ```\n *\n * @type {State}\n */\n function start(code) {\n if (!gfmAtext(code) || !previousEmail.call(self, self.previous) || previousUnbalanced(self.events)) {\n return nok(code);\n }\n effects.enter('literalAutolink');\n effects.enter('literalAutolinkEmail');\n return atext(code);\n }\n\n /**\n * In email atext.\n *\n * ```markdown\n * > | a contact@example.org b\n * ^\n * ```\n *\n * @type {State}\n */\n function atext(code) {\n if (gfmAtext(code)) {\n effects.consume(code);\n return atext;\n }\n if (code === 64) {\n effects.consume(code);\n return emailDomain;\n }\n return nok(code);\n }\n\n /**\n * In email domain.\n *\n * The reference code is a bit overly complex as it handles the `@`, of which\n * there may be just one.\n * Source: <https://github.com/github/cmark-gfm/blob/ef1cfcb/extensions/autolink.c#L318>\n *\n * ```markdown\n * > | a contact@example.org b\n * ^\n * ```\n *\n * @type {State}\n */\n function emailDomain(code) {\n // Dot followed by alphanumerical (not `-` or `_`).\n if (code === 46) {\n return effects.check(emailDomainDotTrail, emailDomainAfter, emailDomainDot)(code);\n }\n\n // Alphanumerical, `-`, and `_`.\n if (code === 45 || code === 95 || asciiAlphanumeric(code)) {\n data = true;\n effects.consume(code);\n return emailDomain;\n }\n\n // To do: `/` if xmpp.\n\n // Note: normally we’d truncate trailing punctuation from the link.\n // However, email autolink literals cannot contain any of those markers,\n // except for `.`, but that can only occur if it isn’t trailing.\n // So we can ignore truncating!\n return emailDomainAfter(code);\n }\n\n /**\n * In email domain, on dot that is not a trail.\n *\n * ```markdown\n * > | a contact@example.org b\n * ^\n * ```\n *\n * @type {State}\n */\n function emailDomainDot(code) {\n effects.consume(code);\n dot = true;\n return emailDomain;\n }\n\n /**\n * After email domain.\n *\n * ```markdown\n * > | a contact@example.org b\n * ^\n * ```\n *\n * @type {State}\n */\n function emailDomainAfter(code) {\n // Domain must not be empty, must include a dot, and must end in alphabetical.\n // Source: <https://github.com/github/cmark-gfm/blob/ef1cfcb/extensions/autolink.c#L332>.\n if (data && dot && asciiAlpha(self.previous)) {\n effects.exit('literalAutolinkEmail');\n effects.exit('literalAutolink');\n return ok(code);\n }\n return nok(code);\n }\n}\n\n/**\n * `www` autolink literal.\n *\n * ```markdown\n * > | a www.example.org b\n * ^^^^^^^^^^^^^^^\n * ```\n *\n * @this {TokenizeContext}\n * @type {Tokenizer}\n */\nfunction tokenizeWwwAutolink(effects, ok, nok) {\n const self = this;\n return wwwStart;\n\n /**\n * Start of www autolink literal.\n *\n * ```markdown\n * > | www.example.com/a?b#c\n * ^\n * ```\n *\n * @type {State}\n */\n function wwwStart(code) {\n if (code !== 87 && code !== 119 || !previousWww.call(self, self.previous) || previousUnbalanced(self.events)) {\n return nok(code);\n }\n effects.enter('literalAutolink');\n effects.enter('literalAutolinkWww');\n // Note: we *check*, so we can discard the `www.` we parsed.\n // If it worked, we consider it as a part of the domain.\n return effects.check(wwwPrefix, effects.attempt(domain, effects.attempt(path, wwwAfter), nok), nok)(code);\n }\n\n /**\n * After a www autolink literal.\n *\n * ```markdown\n * > | www.example.com/a?b#c\n * ^\n * ```\n *\n * @type {State}\n */\n function wwwAfter(code) {\n effects.exit('literalAutolinkWww');\n effects.exit('literalAutolink');\n return ok(code);\n }\n}\n\n/**\n * Protocol autolink literal.\n *\n * ```markdown\n * > | a https://example.org b\n * ^^^^^^^^^^^^^^^^^^^\n * ```\n *\n * @this {TokenizeContext}\n * @type {Tokenizer}\n */\nfunction tokenizeProtocolAutolink(effects, ok, nok) {\n const self = this;\n let buffer = '';\n let seen = false;\n return protocolStart;\n\n /**\n * Start of protocol autolink literal.\n *\n * ```markdown\n * > | https://example.com/a?b#c\n * ^\n * ```\n *\n * @type {State}\n */\n function protocolStart(code) {\n if ((code === 72 || code === 104) && previousProtocol.call(self, self.previous) && !previousUnbalanced(self.events)) {\n effects.enter('literalAutolink');\n effects.enter('literalAutolinkHttp');\n buffer += String.fromCodePoint(code);\n effects.consume(code);\n return protocolPrefixInside;\n }\n return nok(code);\n }\n\n /**\n * In protocol.\n *\n * ```markdown\n * > | https://example.com/a?b#c\n * ^^^^^\n * ```\n *\n * @type {State}\n */\n function protocolPrefixInside(code) {\n // `5` is size of `https`\n if (asciiAlpha(code) && buffer.length < 5) {\n // @ts-expect-error: definitely number.\n buffer += String.fromCodePoint(code);\n effects.consume(code);\n return protocolPrefixInside;\n }\n if (code === 58) {\n const protocol = buffer.toLowerCase();\n if (protocol === 'http' || protocol === 'https') {\n effects.consume(code);\n return protocolSlashesInside;\n }\n }\n return nok(code);\n }\n\n /**\n * In slashes.\n *\n * ```markdown\n * > | https://example.com/a?b#c\n * ^^\n * ```\n *\n * @type {State}\n */\n function protocolSlashesInside(code) {\n if (code === 47) {\n effects.consume(code);\n if (seen) {\n return afterProtocol;\n }\n seen = true;\n return protocolSlashesInside;\n }\n return nok(code);\n }\n\n /**\n * After protocol, before domain.\n *\n * ```markdown\n * > | https://example.com/a?b#c\n * ^\n * ```\n *\n * @type {State}\n */\n function afterProtocol(code) {\n // To do: this is different from `markdown-rs`:\n // https://github.com/wooorm/markdown-rs/blob/b3a921c761309ae00a51fe348d8a43adbc54b518/src/construct/gfm_autolink_literal.rs#L172-L182\n return code === null || asciiControl(code) || markdownLineEndingOrSpace(code) || unicodeWhitespace(code) || unicodePunctuation(code) ? nok(code) : effects.attempt(domain, effects.attempt(path, protocolAfter), nok)(code);\n }\n\n /**\n * After a protocol autolink literal.\n *\n * ```markdown\n * > | https://example.com/a?b#c\n * ^\n * ```\n *\n * @type {State}\n */\n function protocolAfter(code) {\n effects.exit('literalAutolinkHttp');\n effects.exit('literalAutolink');\n return ok(code);\n }\n}\n\n/**\n * `www` prefix.\n *\n * ```markdown\n * > | a www.example.org b\n * ^^^^\n * ```\n *\n * @this {TokenizeContext}\n * @type {Tokenizer}\n */\nfunction tokenizeWwwPrefix(effects, ok, nok) {\n let size = 0;\n return wwwPrefixInside;\n\n /**\n * In www prefix.\n *\n * ```markdown\n * > | www.example.com\n * ^^^^\n * ```\n *\n * @type {State}\n */\n function wwwPrefixInside(code) {\n if ((code === 87 || code === 119) && size < 3) {\n size++;\n effects.consume(code);\n return wwwPrefixInside;\n }\n if (code === 46 && size === 3) {\n effects.consume(code);\n return wwwPrefixAfter;\n }\n return nok(code);\n }\n\n /**\n * After www prefix.\n *\n * ```markdown\n * > | www.example.com\n * ^\n * ```\n *\n * @type {State}\n */\n function wwwPrefixAfter(code) {\n // If there is *anything*, we can link.\n return code === null ? nok(code) : ok(code);\n }\n}\n\n/**\n * Domain.\n *\n * ```markdown\n * > | a https://example.org b\n * ^^^^^^^^^^^\n * ```\n *\n * @this {TokenizeContext}\n * @type {Tokenizer}\n */\nfunction tokenizeDomain(effects, ok, nok) {\n /** @type {boolean | undefined} */\n let underscoreInLastSegment;\n /** @type {boolean | undefined} */\n let underscoreInLastLastSegment;\n /** @type {boolean | undefined} */\n let seen;\n return domainInside;\n\n /**\n * In domain.\n *\n * ```markdown\n * > | https://example.com/a\n * ^^^^^^^^^^^\n * ```\n *\n * @type {State}\n */\n function domainInside(code) {\n // Check whether this marker, which is a trailing punctuation\n // marker, optionally followed by more trailing markers, and then\n // followed by an end.\n if (code === 46 || code === 95) {\n return effects.check(trail, domainAfter, domainAtPunctuation)(code);\n }\n\n // GH documents that only alphanumerics (other than `-`, `.`, and `_`) can\n // occur, which sounds like ASCII only, but they also support `www.點看.com`,\n // so that’s Unicode.\n // Instead of some new production for Unicode alphanumerics, markdown\n // already has that for Unicode punctuation and whitespace, so use those.\n // Source: <https://github.com/github/cmark-gfm/blob/ef1cfcb/extensions/autolink.c#L12>.\n if (code === null || markdownLineEndingOrSpace(code) || unicodeWhitespace(code) || code !== 45 && unicodePunctuation(code)) {\n return domainAfter(code);\n }\n seen = true;\n effects.consume(code);\n return domainInside;\n }\n\n /**\n * In domain, at potential trailing punctuation, that was not trailing.\n *\n * ```markdown\n * > | https://example.com\n * ^\n * ```\n *\n * @type {State}\n */\n function domainAtPunctuation(code) {\n // There is an underscore in the last segment of the domain\n if (code === 95) {\n underscoreInLastSegment = true;\n }\n // Otherwise, it’s a `.`: save the last segment underscore in the\n // penultimate segment slot.\n else {\n underscoreInLastLastSegment = underscoreInLastSegment;\n underscoreInLastSegment = undefined;\n }\n effects.consume(code);\n return domainInside;\n }\n\n /**\n * After domain.\n *\n * ```markdown\n * > | https://example.com/a\n * ^\n * ```\n *\n * @type {State} */\n function domainAfter(code) {\n // Note: that’s GH says a dot is needed, but it’s not true:\n // <https://github.com/github/cmark-gfm/issues/279>\n if (underscoreInLastLastSegment || underscoreInLastSegment || !seen) {\n return nok(code);\n }\n return ok(code);\n }\n}\n\n/**\n * Path.\n *\n * ```markdown\n * > | a https://example.org/stuff b\n * ^^^^^^\n * ```\n *\n * @this {TokenizeContext}\n * @type {Tokenizer}\n */\nfunction tokenizePath(effects, ok) {\n let sizeOpen = 0;\n let sizeClose = 0;\n return pathInside;\n\n /**\n * In path.\n *\n * ```markdown\n * > | https://example.com/a\n * ^^\n * ```\n *\n * @type {State}\n */\n function pathInside(code) {\n if (code === 40) {\n sizeOpen++;\n effects.consume(code);\n return pathInside;\n }\n\n // To do: `markdown-rs` also needs this.\n // If this is a paren, and there are less closings than openings,\n // we don’t check for a trail.\n if (code === 41 && sizeClose < sizeOpen) {\n return pathAtPunctuation(code);\n }\n\n // Check whether this trailing punctuation marker is optionally\n // followed by more trailing markers, and then followed\n // by an end.\n if (code === 33 || code === 34 || code === 38 || code === 39 || code === 41 || code === 42 || code === 44 || code === 46 || code === 58 || code === 59 || code === 60 || code === 63 || code === 93 || code === 95 || code === 126) {\n return effects.check(trail, ok, pathAtPunctuation)(code);\n }\n if (code === null || markdownLineEndingOrSpace(code) || unicodeWhitespace(code)) {\n return ok(code);\n }\n effects.consume(code);\n return pathInside;\n }\n\n /**\n * In path, at potential trailing punctuation, that was not trailing.\n *\n * ```markdown\n * > | https://example.com/a\"b\n * ^\n * ```\n *\n * @type {State}\n */\n function pathAtPunctuation(code) {\n // Count closing parens.\n if (code === 41) {\n sizeClose++;\n }\n effects.consume(code);\n return pathInside;\n }\n}\n\n/**\n * Trail.\n *\n * This calls `ok` if this *is* the trail, followed by an end, which means\n * the entire trail is not part of the link.\n * It calls `nok` if this *is* part of the link.\n *\n * ```markdown\n * > | https://example.com\").\n * ^^^\n * ```\n *\n * @this {TokenizeContext}\n * @type {Tokenizer}\n */\nfunction tokenizeTrail(effects, ok, nok) {\n return trail;\n\n /**\n * In trail of domain or path.\n *\n * ```markdown\n * > | https://example.com\").\n * ^\n * ```\n *\n * @type {State}\n */\n function trail(code) {\n // Regular trailing punctuation.\n if (code === 33 || code === 34 || code === 39 || code === 41 || code === 42 || code === 44 || code === 46 || code === 58 || code === 59 || code === 63 || code === 95 || code === 126) {\n effects.consume(code);\n return trail;\n }\n\n // `&` followed by one or more alphabeticals and then a `;`, is\n // as a whole considered as trailing punctuation.\n // In all other cases, it is considered as continuation of the URL.\n if (code === 38) {\n effects.consume(code);\n return trailCharacterReferenceStart;\n }\n\n // Needed because we allow literals after `[`, as we fix:\n // <https://github.com/github/cmark-gfm/issues/278>.\n // Check that it is not followed by `(` or `[`.\n if (code === 93) {\n effects.consume(code);\n return trailBracketAfter;\n }\n if (\n // `<` is an end.\n code === 60 ||\n // So is whitespace.\n code === null || markdownLineEndingOrSpace(code) || unicodeWhitespace(code)) {\n return ok(code);\n }\n return nok(code);\n }\n\n /**\n * In trail, after `]`.\n *\n * > 👉 **Note**: this deviates from `cmark-gfm` to fix a bug.\n * > See end of <https://github.com/github/cmark-gfm/issues/278> for more.\n *\n * ```markdown\n * > | https://example.com](\n * ^\n * ```\n *\n * @type {State}\n */\n function trailBracketAfter(code) {\n // Whitespace or something that could start a resource or reference is the end.\n // Switch back to trail otherwise.\n if (code === null || code === 40 || code === 91 || markdownLineEndingOrSpace(code) || unicodeWhitespace(code)) {\n return ok(code);\n }\n return trail(code);\n }\n\n /**\n * In character-reference like trail, after `&`.\n *\n * ```markdown\n * > | https://example.com&).\n * ^\n * ```\n *\n * @type {State}\n */\n function trailCharacterReferenceStart(code) {\n // When non-alpha, it’s not a trail.\n return asciiAlpha(code) ? trailCharacterReferenceInside(code) : nok(code);\n }\n\n /**\n * In character-reference like trail.\n *\n * ```markdown\n * > | https://example.com&).\n * ^\n * ```\n *\n * @type {State}\n */\n function trailCharacterReferenceInside(code) {\n // Switch back to trail if this is well-formed.\n if (code === 59) {\n effects.consume(code);\n return trail;\n }\n if (asciiAlpha(code)) {\n effects.consume(code);\n return trailCharacterReferenceInside;\n }\n\n // It’s not a trail.\n return nok(code);\n }\n}\n\n/**\n * Dot in email domain trail.\n *\n * This calls `ok` if this *is* the trail, followed by an end, which means\n * the trail is not part of the link.\n * It calls `nok` if this *is* part of the link.\n *\n * ```markdown\n * > | contact@example.org.\n * ^\n * ```\n *\n * @this {TokenizeContext}\n * @type {Tokenizer}\n */\nfunction tokenizeEmailDomainDotTrail(effects, ok, nok) {\n return start;\n\n /**\n * Dot.\n *\n * ```markdown\n * > | contact@example.org.\n * ^ ^\n * ```\n *\n * @type {State}\n */\n function start(code) {\n // Must be dot.\n effects.consume(code);\n return after;\n }\n\n /**\n * After dot.\n *\n * ```markdown\n * > | contact@example.org.\n * ^ ^\n * ```\n *\n * @type {State}\n */\n function after(code) {\n // Not a trail if alphanumeric.\n return asciiAlphanumeric(code) ? nok(code) : ok(code);\n }\n}\n\n/**\n * See:\n * <https://github.com/github/cmark-gfm/blob/ef1cfcb/extensions/autolink.c#L156>.\n *\n * @type {Previous}\n */\nfunction previousWww(code) {\n return code === null || code === 40 || code === 42 || code === 95 || code === 91 || code === 93 || code === 126 || markdownLineEndingOrSpace(code);\n}\n\n/**\n * See:\n * <https://github.com/github/cmark-gfm/blob/ef1cfcb/extensions/autolink.c#L214>.\n *\n * @type {Previous}\n */\nfunction previousProtocol(code) {\n return !asciiAlpha(code);\n}\n\n/**\n * @this {TokenizeContext}\n * @type {Previous}\n */\nfunction previousEmail(code) {\n // Do not allow a slash “inside” atext.\n // The reference code is a bit weird, but that’s what it results in.\n // Source: <https://github.com/github/cmark-gfm/blob/ef1cfcb/extensions/autolink.c#L307>.\n // Other than slash, every preceding character is allowed.\n return !(code === 47 || gfmAtext(code));\n}\n\n/**\n * @param {Code} code\n * @returns {boolean}\n */\nfunction gfmAtext(code) {\n return code === 43 || code === 45 || code === 46 || code === 95 || asciiAlphanumeric(code);\n}\n\n/**\n * @param {Array<Event>} events\n * @returns {boolean}\n */\nfunction previousUnbalanced(events) {\n let index = events.length;\n let result = false;\n while (index--) {\n const token = events[index][1];\n if ((token.type === 'labelLink' || token.type === 'labelImage') && !token._balanced) {\n result = true;\n break;\n }\n\n // If we’ve seen this token, and it was marked as not having any unbalanced\n // bracket before it, we can exit.\n if (token._gfmAutolinkLiteralWalkedInto) {\n result = false;\n break;\n }\n }\n if (events.length > 0 && !result) {\n // Mark the last token as “walked into” w/o finding\n // anything.\n events[events.length - 1][1]._gfmAutolinkLiteralWalkedInto = true;\n }\n return result;\n}","/**\n * @import {Event, Resolver, TokenizeContext} from 'micromark-util-types'\n */\n\n/**\n * Call all `resolveAll`s.\n *\n * @param {ReadonlyArray<{resolveAll?: Resolver | undefined}>} constructs\n * List of constructs, optionally with `resolveAll`s.\n * @param {Array<Event>} events\n * List of events.\n * @param {TokenizeContext} context\n * Context used by `tokenize`.\n * @returns {Array<Event>}\n * Changed events.\n */\nexport function resolveAll(constructs, events, context) {\n /** @type {Array<Resolver>} */\n const called = []\n let index = -1\n\n while (++index < constructs.length) {\n const resolve = constructs[index].resolveAll\n\n if (resolve && !called.includes(resolve)) {\n events = resolve(events, context)\n called.push(resolve)\n }\n }\n\n return events\n}\n","/**\n * @import {Effects, State, TokenType} from 'micromark-util-types'\n */\n\nimport { markdownSpace } from 'micromark-util-character';\n\n// To do: implement `spaceOrTab`, `spaceOrTabMinMax`, `spaceOrTabWithOptions`.\n\n/**\n * Parse spaces and tabs.\n *\n * There is no `nok` parameter:\n *\n * * spaces in markdown are often optional, in which case this factory can be\n * used and `ok` will be switched to whether spaces were found or not\n * * one line ending or space can be detected with `markdownSpace(code)` right\n * before using `factorySpace`\n *\n * ###### Examples\n *\n * Where `␉` represents a tab (plus how much it expands) and `␠` represents a\n * single space.\n *\n * ```markdown\n * ␉\n * ␠␠␠␠\n * ␉␠\n * ```\n *\n * @param {Effects} effects\n * Context.\n * @param {State} ok\n * State switched to when successful.\n * @param {TokenType} type\n * Type (`' \\t'`).\n * @param {number | undefined} [max=Infinity]\n * Max (exclusive).\n * @returns {State}\n * Start state.\n */\nexport function factorySpace(effects, ok, type, max) {\n const limit = max ? max - 1 : Number.POSITIVE_INFINITY;\n let size = 0;\n return start;\n\n /** @type {State} */\n function start(code) {\n if (markdownSpace(code)) {\n effects.enter(type);\n return prefix(code);\n }\n return ok(code);\n }\n\n /** @type {State} */\n function prefix(code) {\n if (markdownSpace(code) && size++ < limit) {\n effects.consume(code);\n return prefix;\n }\n effects.exit(type);\n return ok(code);\n }\n}","/**\n * @import {\n * Construct,\n * State,\n * TokenizeContext,\n * Tokenizer\n * } from 'micromark-util-types'\n */\n\nimport { factorySpace } from 'micromark-factory-space';\nimport { markdownLineEnding, markdownSpace } from 'micromark-util-character';\n/** @type {Construct} */\nexport const blankLine = {\n partial: true,\n tokenize: tokenizeBlankLine\n};\n\n/**\n * @this {TokenizeContext}\n * Context.\n * @type {Tokenizer}\n */\nfunction tokenizeBlankLine(effects, ok, nok) {\n return start;\n\n /**\n * Start of blank line.\n *\n * > 👉 **Note**: `␠` represents a space character.\n *\n * ```markdown\n * > | ␠␠␊\n * ^\n * > | ␊\n * ^\n * ```\n *\n * @type {State}\n */\n function start(code) {\n return markdownSpace(code) ? factorySpace(effects, after, \"linePrefix\")(code) : after(code);\n }\n\n /**\n * At eof/eol, after optional whitespace.\n *\n * > 👉 **Note**: `␠` represents a space character.\n *\n * ```markdown\n * > | ␠␠␊\n * ^\n * > | ␊\n * ^\n * ```\n *\n * @type {State}\n */\n function after(code) {\n return code === null || markdownLineEnding(code) ? ok(code) : nok(code);\n }\n}","/**\n * @import {Event, Exiter, Extension, Resolver, State, Token, TokenizeContext, Tokenizer} from 'micromark-util-types'\n */\n\nimport { blankLine } from 'micromark-core-commonmark';\nimport { factorySpace } from 'micromark-factory-space';\nimport { markdownLineEndingOrSpace } from 'micromark-util-character';\nimport { normalizeIdentifier } from 'micromark-util-normalize-identifier';\nconst indent = {\n tokenize: tokenizeIndent,\n partial: true\n};\n\n// To do: micromark should support a `_hiddenGfmFootnoteSupport`, which only\n// affects label start (image).\n// That will let us drop `tokenizePotentialGfmFootnote*`.\n// It currently has a `_hiddenFootnoteSupport`, which affects that and more.\n// That can be removed when `micromark-extension-footnote` is archived.\n\n/**\n * Create an extension for `micromark` to enable GFM footnote syntax.\n *\n * @returns {Extension}\n * Extension for `micromark` that can be passed in `extensions` to\n * enable GFM footnote syntax.\n */\nexport function gfmFootnote() {\n /** @type {Extension} */\n return {\n document: {\n [91]: {\n name: 'gfmFootnoteDefinition',\n tokenize: tokenizeDefinitionStart,\n continuation: {\n tokenize: tokenizeDefinitionContinuation\n },\n exit: gfmFootnoteDefinitionEnd\n }\n },\n text: {\n [91]: {\n name: 'gfmFootnoteCall',\n tokenize: tokenizeGfmFootnoteCall\n },\n [93]: {\n name: 'gfmPotentialFootnoteCall',\n add: 'after',\n tokenize: tokenizePotentialGfmFootnoteCall,\n resolveTo: resolveToPotentialGfmFootnoteCall\n }\n }\n };\n}\n\n// To do: remove after micromark update.\n/**\n * @this {TokenizeContext}\n * @type {Tokenizer}\n */\nfunction tokenizePotentialGfmFootnoteCall(effects, ok, nok) {\n const self = this;\n let index = self.events.length;\n const defined = self.parser.gfmFootnotes || (self.parser.gfmFootnotes = []);\n /** @type {Token} */\n let labelStart;\n\n // Find an opening.\n while (index--) {\n const token = self.events[index][1];\n if (token.type === \"labelImage\") {\n labelStart = token;\n break;\n }\n\n // Exit if we’ve walked far enough.\n if (token.type === 'gfmFootnoteCall' || token.type === \"labelLink\" || token.type === \"label\" || token.type === \"image\" || token.type === \"link\") {\n break;\n }\n }\n return start;\n\n /**\n * @type {State}\n */\n function start(code) {\n if (!labelStart || !labelStart._balanced) {\n return nok(code);\n }\n const id = normalizeIdentifier(self.sliceSerialize({\n start: labelStart.end,\n end: self.now()\n }));\n if (id.codePointAt(0) !== 94 || !defined.includes(id.slice(1))) {\n return nok(code);\n }\n effects.enter('gfmFootnoteCallLabelMarker');\n effects.consume(code);\n effects.exit('gfmFootnoteCallLabelMarker');\n return ok(code);\n }\n}\n\n// To do: remove after micromark update.\n/** @type {Resolver} */\nfunction resolveToPotentialGfmFootnoteCall(events, context) {\n let index = events.length;\n /** @type {Token | undefined} */\n let labelStart;\n\n // Find an opening.\n while (index--) {\n if (events[index][1].type === \"labelImage\" && events[index][0] === 'enter') {\n labelStart = events[index][1];\n break;\n }\n }\n // Change the `labelImageMarker` to a `data`.\n events[index + 1][1].type = \"data\";\n events[index + 3][1].type = 'gfmFootnoteCallLabelMarker';\n\n // The whole (without `!`):\n /** @type {Token} */\n const call = {\n type: 'gfmFootnoteCall',\n start: Object.assign({}, events[index + 3][1].start),\n end: Object.assign({}, events[events.length - 1][1].end)\n };\n // The `^` marker\n /** @type {Token} */\n const marker = {\n type: 'gfmFootnoteCallMarker',\n start: Object.assign({}, events[index + 3][1].end),\n end: Object.assign({}, events[index + 3][1].end)\n };\n // Increment the end 1 character.\n marker.end.column++;\n marker.end.offset++;\n marker.end._bufferIndex++;\n /** @type {Token} */\n const string = {\n type: 'gfmFootnoteCallString',\n start: Object.assign({}, marker.end),\n end: Object.assign({}, events[events.length - 1][1].start)\n };\n /** @type {Token} */\n const chunk = {\n type: \"chunkString\",\n contentType: 'string',\n start: Object.assign({}, string.start),\n end: Object.assign({}, string.end)\n };\n\n /** @type {Array<Event>} */\n const replacement = [\n // Take the `labelImageMarker` (now `data`, the `!`)\n events[index + 1], events[index + 2], ['enter', call, context],\n // The `[`\n events[index + 3], events[index + 4],\n // The `^`.\n ['enter', marker, context], ['exit', marker, context],\n // Everything in between.\n ['enter', string, context], ['enter', chunk, context], ['exit', chunk, context], ['exit', string, context],\n // The ending (`]`, properly parsed and labelled).\n events[events.length - 2], events[events.length - 1], ['exit', call, context]];\n events.splice(index, events.length - index + 1, ...replacement);\n return events;\n}\n\n/**\n * @this {TokenizeContext}\n * @type {Tokenizer}\n */\nfunction tokenizeGfmFootnoteCall(effects, ok, nok) {\n const self = this;\n const defined = self.parser.gfmFootnotes || (self.parser.gfmFootnotes = []);\n let size = 0;\n /** @type {boolean} */\n let data;\n\n // Note: the implementation of `markdown-rs` is different, because it houses\n // core *and* extensions in one project.\n // Therefore, it can include footnote logic inside `label-end`.\n // We can’t do that, but luckily, we can parse footnotes in a simpler way than\n // needed for labels.\n return start;\n\n /**\n * Start of footnote label.\n *\n * ```markdown\n * > | a [^b] c\n * ^\n * ```\n *\n * @type {State}\n */\n function start(code) {\n effects.enter('gfmFootnoteCall');\n effects.enter('gfmFootnoteCallLabelMarker');\n effects.consume(code);\n effects.exit('gfmFootnoteCallLabelMarker');\n return callStart;\n }\n\n /**\n * After `[`, at `^`.\n *\n * ```markdown\n * > | a [^b] c\n * ^\n * ```\n *\n * @type {State}\n */\n function callStart(code) {\n if (code !== 94) return nok(code);\n effects.enter('gfmFootnoteCallMarker');\n effects.consume(code);\n effects.exit('gfmFootnoteCallMarker');\n effects.enter('gfmFootnoteCallString');\n effects.enter('chunkString').contentType = 'string';\n return callData;\n }\n\n /**\n * In label.\n *\n * ```markdown\n * > | a [^b] c\n * ^\n * ```\n *\n * @type {State}\n */\n function callData(code) {\n if (\n // Too long.\n size > 999 ||\n // Closing brace with nothing.\n code === 93 && !data ||\n // Space or tab is not supported by GFM for some reason.\n // `\\n` and `[` not being supported makes sense.\n code === null || code === 91 || markdownLineEndingOrSpace(code)) {\n return nok(code);\n }\n if (code === 93) {\n effects.exit('chunkString');\n const token = effects.exit('gfmFootnoteCallString');\n if (!defined.includes(normalizeIdentifier(self.sliceSerialize(token)))) {\n return nok(code);\n }\n effects.enter('gfmFootnoteCallLabelMarker');\n effects.consume(code);\n effects.exit('gfmFootnoteCallLabelMarker');\n effects.exit('gfmFootnoteCall');\n return ok;\n }\n if (!markdownLineEndingOrSpace(code)) {\n data = true;\n }\n size++;\n effects.consume(code);\n return code === 92 ? callEscape : callData;\n }\n\n /**\n * On character after escape.\n *\n * ```markdown\n * > | a [^b\\c] d\n * ^\n * ```\n *\n * @type {State}\n */\n function callEscape(code) {\n if (code === 91 || code === 92 || code === 93) {\n effects.consume(code);\n size++;\n return callData;\n }\n return callData(code);\n }\n}\n\n/**\n * @this {TokenizeContext}\n * @type {Tokenizer}\n */\nfunction tokenizeDefinitionStart(effects, ok, nok) {\n const self = this;\n const defined = self.parser.gfmFootnotes || (self.parser.gfmFootnotes = []);\n /** @type {string} */\n let identifier;\n let size = 0;\n /** @type {boolean | undefined} */\n let data;\n return start;\n\n /**\n * Start of GFM footnote definition.\n *\n * ```markdown\n * > | [^a]: b\n * ^\n * ```\n *\n * @type {State}\n */\n function start(code) {\n effects.enter('gfmFootnoteDefinition')._container = true;\n effects.enter('gfmFootnoteDefinitionLabel');\n effects.enter('gfmFootnoteDefinitionLabelMarker');\n effects.consume(code);\n effects.exit('gfmFootnoteDefinitionLabelMarker');\n return labelAtMarker;\n }\n\n /**\n * In label, at caret.\n *\n * ```markdown\n * > | [^a]: b\n * ^\n * ```\n *\n * @type {State}\n */\n function labelAtMarker(code) {\n if (code === 94) {\n effects.enter('gfmFootnoteDefinitionMarker');\n effects.consume(code);\n effects.exit('gfmFootnoteDefinitionMarker');\n effects.enter('gfmFootnoteDefinitionLabelString');\n effects.enter('chunkString').contentType = 'string';\n return labelInside;\n }\n return nok(code);\n }\n\n /**\n * In label.\n *\n * > 👉 **Note**: `cmark-gfm` prevents whitespace from occurring in footnote\n * > definition labels.\n *\n * ```markdown\n * > | [^a]: b\n * ^\n * ```\n *\n * @type {State}\n */\n function labelInside(code) {\n if (\n // Too long.\n size > 999 ||\n // Closing brace with nothing.\n code === 93 && !data ||\n // Space or tab is not supported by GFM for some reason.\n // `\\n` and `[` not being supported makes sense.\n code === null || code === 91 || markdownLineEndingOrSpace(code)) {\n return nok(code);\n }\n if (code === 93) {\n effects.exit('chunkString');\n const token = effects.exit('gfmFootnoteDefinitionLabelString');\n identifier = normalizeIdentifier(self.sliceSerialize(token));\n effects.enter('gfmFootnoteDefinitionLabelMarker');\n effects.consume(code);\n effects.exit('gfmFootnoteDefinitionLabelMarker');\n effects.exit('gfmFootnoteDefinitionLabel');\n return labelAfter;\n }\n if (!markdownLineEndingOrSpace(code)) {\n data = true;\n }\n size++;\n effects.consume(code);\n return code === 92 ? labelEscape : labelInside;\n }\n\n /**\n * After `\\`, at a special character.\n *\n * > 👉 **Note**: `cmark-gfm` currently does not support escaped brackets:\n * > <https://github.com/github/cmark-gfm/issues/240>\n *\n * ```markdown\n * > | [^a\\*b]: c\n * ^\n * ```\n *\n * @type {State}\n */\n function labelEscape(code) {\n if (code === 91 || code === 92 || code === 93) {\n effects.consume(code);\n size++;\n return labelInside;\n }\n return labelInside(code);\n }\n\n /**\n * After definition label.\n *\n * ```markdown\n * > | [^a]: b\n * ^\n * ```\n *\n * @type {State}\n */\n function labelAfter(code) {\n if (code === 58) {\n effects.enter('definitionMarker');\n effects.consume(code);\n effects.exit('definitionMarker');\n if (!defined.includes(identifier)) {\n defined.push(identifier);\n }\n\n // Any whitespace after the marker is eaten, forming indented code\n // is not possible.\n // No space is also fine, just like a block quote marker.\n return factorySpace(effects, whitespaceAfter, 'gfmFootnoteDefinitionWhitespace');\n }\n return nok(code);\n }\n\n /**\n * After definition prefix.\n *\n * ```markdown\n * > | [^a]: b\n * ^\n * ```\n *\n * @type {State}\n */\n function whitespaceAfter(code) {\n // `markdown-rs` has a wrapping token for the prefix that is closed here.\n return ok(code);\n }\n}\n\n/**\n * @this {TokenizeContext}\n * @type {Tokenizer}\n */\nfunction tokenizeDefinitionContinuation(effects, ok, nok) {\n /// Start of footnote definition continuation.\n ///\n /// ```markdown\n /// | [^a]: b\n /// > | c\n /// ^\n /// ```\n //\n // Either a blank line, which is okay, or an indented thing.\n return effects.check(blankLine, ok, effects.attempt(indent, ok, nok));\n}\n\n/** @type {Exiter} */\nfunction gfmFootnoteDefinitionEnd(effects) {\n effects.exit('gfmFootnoteDefinition');\n}\n\n/**\n * @this {TokenizeContext}\n * @type {Tokenizer}\n */\nfunction tokenizeIndent(effects, ok, nok) {\n const self = this;\n return factorySpace(effects, afterPrefix, 'gfmFootnoteDefinitionIndent', 4 + 1);\n\n /**\n * @type {State}\n */\n function afterPrefix(code) {\n const tail = self.events[self.events.length - 1];\n return tail && tail[1].type === 'gfmFootnoteDefinitionIndent' && tail[2].sliceSerialize(tail[1], true).length === 4 ? ok(code) : nok(code);\n }\n}","/**\n * @import {Options} from 'micromark-extension-gfm-strikethrough'\n * @import {Event, Extension, Resolver, State, Token, TokenizeContext, Tokenizer} from 'micromark-util-types'\n */\n\nimport { splice } from 'micromark-util-chunked';\nimport { classifyCharacter } from 'micromark-util-classify-character';\nimport { resolveAll } from 'micromark-util-resolve-all';\n/**\n * Create an extension for `micromark` to enable GFM strikethrough syntax.\n *\n * @param {Options | null | undefined} [options={}]\n * Configuration.\n * @returns {Extension}\n * Extension for `micromark` that can be passed in `extensions`, to\n * enable GFM strikethrough syntax.\n */\nexport function gfmStrikethrough(options) {\n const options_ = options || {};\n let single = options_.singleTilde;\n const tokenizer = {\n name: 'strikethrough',\n tokenize: tokenizeStrikethrough,\n resolveAll: resolveAllStrikethrough\n };\n if (single === null || single === undefined) {\n single = true;\n }\n return {\n text: {\n [126]: tokenizer\n },\n insideSpan: {\n null: [tokenizer]\n },\n attentionMarkers: {\n null: [126]\n }\n };\n\n /**\n * Take events and resolve strikethrough.\n *\n * @type {Resolver}\n */\n function resolveAllStrikethrough(events, context) {\n let index = -1;\n\n // Walk through all events.\n while (++index < events.length) {\n // Find a token that can close.\n if (events[index][0] === 'enter' && events[index][1].type === 'strikethroughSequenceTemporary' && events[index][1]._close) {\n let open = index;\n\n // Now walk back to find an opener.\n while (open--) {\n // Find a token that can open the closer.\n if (events[open][0] === 'exit' && events[open][1].type === 'strikethroughSequenceTemporary' && events[open][1]._open &&\n // If the sizes are the same:\n events[index][1].end.offset - events[index][1].start.offset === events[open][1].end.offset - events[open][1].start.offset) {\n events[index][1].type = 'strikethroughSequence';\n events[open][1].type = 'strikethroughSequence';\n\n /** @type {Token} */\n const strikethrough = {\n type: 'strikethrough',\n start: Object.assign({}, events[open][1].start),\n end: Object.assign({}, events[index][1].end)\n };\n\n /** @type {Token} */\n const text = {\n type: 'strikethroughText',\n start: Object.assign({}, events[open][1].end),\n end: Object.assign({}, events[index][1].start)\n };\n\n // Opening.\n /** @type {Array<Event>} */\n const nextEvents = [['enter', strikethrough, context], ['enter', events[open][1], context], ['exit', events[open][1], context], ['enter', text, context]];\n const insideSpan = context.parser.constructs.insideSpan.null;\n if (insideSpan) {\n // Between.\n splice(nextEvents, nextEvents.length, 0, resolveAll(insideSpan, events.slice(open + 1, index), context));\n }\n\n // Closing.\n splice(nextEvents, nextEvents.length, 0, [['exit', text, context], ['enter', events[index][1], context], ['exit', events[index][1], context], ['exit', strikethrough, context]]);\n splice(events, open - 1, index - open + 3, nextEvents);\n index = open + nextEvents.length - 2;\n break;\n }\n }\n }\n }\n index = -1;\n while (++index < events.length) {\n if (events[index][1].type === 'strikethroughSequenceTemporary') {\n events[index][1].type = \"data\";\n }\n }\n return events;\n }\n\n /**\n * @this {TokenizeContext}\n * @type {Tokenizer}\n */\n function tokenizeStrikethrough(effects, ok, nok) {\n const previous = this.previous;\n const events = this.events;\n let size = 0;\n return start;\n\n /** @type {State} */\n function start(code) {\n if (previous === 126 && events[events.length - 1][1].type !== \"characterEscape\") {\n return nok(code);\n }\n effects.enter('strikethroughSequenceTemporary');\n return more(code);\n }\n\n /** @type {State} */\n function more(code) {\n const before = classifyCharacter(previous);\n if (code === 126) {\n // If this is the third marker, exit.\n if (size > 1) return nok(code);\n effects.consume(code);\n size++;\n return more;\n }\n if (size < 2 && !single) return nok(code);\n const token = effects.exit('strikethroughSequenceTemporary');\n const after = classifyCharacter(code);\n token._open = !after || after === 2 && Boolean(before);\n token._close = !before || before === 2 && Boolean(after);\n return ok(code);\n }\n }\n}","/**\n * @import {Event} from 'micromark-util-types'\n */\n\n// Port of `edit_map.rs` from `markdown-rs`.\n// This should move to `markdown-js` later.\n\n// Deal with several changes in events, batching them together.\n//\n// Preferably, changes should be kept to a minimum.\n// Sometimes, it’s needed to change the list of events, because parsing can be\n// messy, and it helps to expose a cleaner interface of events to the compiler\n// and other users.\n// It can also help to merge many adjacent similar events.\n// And, in other cases, it’s needed to parse subcontent: pass some events\n// through another tokenizer and inject the result.\n\n/**\n * @typedef {[number, number, Array<Event>]} Change\n * @typedef {[number, number, number]} Jump\n */\n\n/**\n * Tracks a bunch of edits.\n */\nexport class EditMap {\n /**\n * Create a new edit map.\n */\n constructor() {\n /**\n * Record of changes.\n *\n * @type {Array<Change>}\n */\n this.map = [];\n }\n\n /**\n * Create an edit: a remove and/or add at a certain place.\n *\n * @param {number} index\n * @param {number} remove\n * @param {Array<Event>} add\n * @returns {undefined}\n */\n add(index, remove, add) {\n addImplementation(this, index, remove, add);\n }\n\n // To do: add this when moving to `micromark`.\n // /**\n // * Create an edit: but insert `add` before existing additions.\n // *\n // * @param {number} index\n // * @param {number} remove\n // * @param {Array<Event>} add\n // * @returns {undefined}\n // */\n // addBefore(index, remove, add) {\n // addImplementation(this, index, remove, add, true)\n // }\n\n /**\n * Done, change the events.\n *\n * @param {Array<Event>} events\n * @returns {undefined}\n */\n consume(events) {\n this.map.sort(function (a, b) {\n return a[0] - b[0];\n });\n\n /* c8 ignore next 3 -- `resolve` is never called without tables, so without edits. */\n if (this.map.length === 0) {\n return;\n }\n\n // To do: if links are added in events, like they are in `markdown-rs`,\n // this is needed.\n // // Calculate jumps: where items in the current list move to.\n // /** @type {Array<Jump>} */\n // const jumps = []\n // let index = 0\n // let addAcc = 0\n // let removeAcc = 0\n // while (index < this.map.length) {\n // const [at, remove, add] = this.map[index]\n // removeAcc += remove\n // addAcc += add.length\n // jumps.push([at, removeAcc, addAcc])\n // index += 1\n // }\n //\n // . shiftLinks(events, jumps)\n\n let index = this.map.length;\n /** @type {Array<Array<Event>>} */\n const vecs = [];\n while (index > 0) {\n index -= 1;\n vecs.push(events.slice(this.map[index][0] + this.map[index][1]), this.map[index][2]);\n\n // Truncate rest.\n events.length = this.map[index][0];\n }\n vecs.push(events.slice());\n events.length = 0;\n let slice = vecs.pop();\n while (slice) {\n for (const element of slice) {\n events.push(element);\n }\n slice = vecs.pop();\n }\n\n // Truncate everything.\n this.map.length = 0;\n }\n}\n\n/**\n * Create an edit.\n *\n * @param {EditMap} editMap\n * @param {number} at\n * @param {number} remove\n * @param {Array<Event>} add\n * @returns {undefined}\n */\nfunction addImplementation(editMap, at, remove, add) {\n let index = 0;\n\n /* c8 ignore next 3 -- `resolve` is never called without tables, so without edits. */\n if (remove === 0 && add.length === 0) {\n return;\n }\n while (index < editMap.map.length) {\n if (editMap.map[index][0] === at) {\n editMap.map[index][1] += remove;\n\n // To do: before not used by tables, use when moving to micromark.\n // if (before) {\n // add.push(...editMap.map[index][2])\n // editMap.map[index][2] = add\n // } else {\n editMap.map[index][2].push(...add);\n // }\n\n return;\n }\n index += 1;\n }\n editMap.map.push([at, remove, add]);\n}\n\n// /**\n// * Shift `previous` and `next` links according to `jumps`.\n// *\n// * This fixes links in case there are events removed or added between them.\n// *\n// * @param {Array<Event>} events\n// * @param {Array<Jump>} jumps\n// */\n// function shiftLinks(events, jumps) {\n// let jumpIndex = 0\n// let index = 0\n// let add = 0\n// let rm = 0\n\n// while (index < events.length) {\n// const rmCurr = rm\n\n// while (jumpIndex < jumps.length && jumps[jumpIndex][0] <= index) {\n// add = jumps[jumpIndex][2]\n// rm = jumps[jumpIndex][1]\n// jumpIndex += 1\n// }\n\n// // Ignore items that will be removed.\n// if (rm > rmCurr) {\n// index += rm - rmCurr\n// } else {\n// // ?\n// // if let Some(link) = &events[index].link {\n// // if let Some(next) = link.next {\n// // events[next].link.as_mut().unwrap().previous = Some(index + add - rm);\n// // while jumpIndex < jumps.len() && jumps[jumpIndex].0 <= next {\n// // add = jumps[jumpIndex].2;\n// // rm = jumps[jumpIndex].1;\n// // jumpIndex += 1;\n// // }\n// // events[index].link.as_mut().unwrap().next = Some(next + add - rm);\n// // index = next;\n// // continue;\n// // }\n// // }\n// index += 1\n// }\n// }\n// }","/**\n * @import {Event} from 'micromark-util-types'\n */\n\n/**\n * @typedef {'center' | 'left' | 'none' | 'right'} Align\n */\n\n/**\n * Figure out the alignment of a GFM table.\n *\n * @param {Readonly<Array<Event>>} events\n * List of events.\n * @param {number} index\n * Table enter event.\n * @returns {Array<Align>}\n * List of aligns.\n */\nexport function gfmTableAlign(events, index) {\n let inDelimiterRow = false;\n /** @type {Array<Align>} */\n const align = [];\n while (index < events.length) {\n const event = events[index];\n if (inDelimiterRow) {\n if (event[0] === 'enter') {\n // Start of alignment value: set a new column.\n // To do: `markdown-rs` uses `tableDelimiterCellValue`.\n if (event[1].type === 'tableContent') {\n align.push(events[index + 1][1].type === 'tableDelimiterMarker' ? 'left' : 'none');\n }\n }\n // Exits:\n // End of alignment value: change the column.\n // To do: `markdown-rs` uses `tableDelimiterCellValue`.\n else if (event[1].type === 'tableContent') {\n if (events[index - 1][1].type === 'tableDelimiterMarker') {\n const alignIndex = align.length - 1;\n align[alignIndex] = align[alignIndex] === 'left' ? 'center' : 'right';\n }\n }\n // Done!\n else if (event[1].type === 'tableDelimiterRow') {\n break;\n }\n } else if (event[0] === 'enter' && event[1].type === 'tableDelimiterRow') {\n inDelimiterRow = true;\n }\n index += 1;\n }\n return align;\n}","/**\n * @import {Event, Extension, Point, Resolver, State, Token, TokenizeContext, Tokenizer} from 'micromark-util-types'\n */\n\n/**\n * @typedef {[number, number, number, number]} Range\n * Cell info.\n *\n * @typedef {0 | 1 | 2 | 3} RowKind\n * Where we are: `1` for head row, `2` for delimiter row, `3` for body row.\n */\n\nimport { factorySpace } from 'micromark-factory-space';\nimport { markdownLineEnding, markdownLineEndingOrSpace, markdownSpace } from 'micromark-util-character';\nimport { EditMap } from './edit-map.js';\nimport { gfmTableAlign } from './infer.js';\n\n/**\n * Create an HTML extension for `micromark` to support GitHub tables syntax.\n *\n * @returns {Extension}\n * Extension for `micromark` that can be passed in `extensions` to enable GFM\n * table syntax.\n */\nexport function gfmTable() {\n return {\n flow: {\n null: {\n name: 'table',\n tokenize: tokenizeTable,\n resolveAll: resolveTable\n }\n }\n };\n}\n\n/**\n * @this {TokenizeContext}\n * @type {Tokenizer}\n */\nfunction tokenizeTable(effects, ok, nok) {\n const self = this;\n let size = 0;\n let sizeB = 0;\n /** @type {boolean | undefined} */\n let seen;\n return start;\n\n /**\n * Start of a GFM table.\n *\n * If there is a valid table row or table head before, then we try to parse\n * another row.\n * Otherwise, we try to parse a head.\n *\n * ```markdown\n * > | | a |\n * ^\n * | | - |\n * > | | b |\n * ^\n * ```\n * @type {State}\n */\n function start(code) {\n let index = self.events.length - 1;\n while (index > -1) {\n const type = self.events[index][1].type;\n if (type === \"lineEnding\" ||\n // Note: markdown-rs uses `whitespace` instead of `linePrefix`\n type === \"linePrefix\") index--;else break;\n }\n const tail = index > -1 ? self.events[index][1].type : null;\n const next = tail === 'tableHead' || tail === 'tableRow' ? bodyRowStart : headRowBefore;\n\n // Don’t allow lazy body rows.\n if (next === bodyRowStart && self.parser.lazy[self.now().line]) {\n return nok(code);\n }\n return next(code);\n }\n\n /**\n * Before table head row.\n *\n * ```markdown\n * > | | a |\n * ^\n * | | - |\n * | | b |\n * ```\n *\n * @type {State}\n */\n function headRowBefore(code) {\n effects.enter('tableHead');\n effects.enter('tableRow');\n return headRowStart(code);\n }\n\n /**\n * Before table head row, after whitespace.\n *\n * ```markdown\n * > | | a |\n * ^\n * | | - |\n * | | b |\n * ```\n *\n * @type {State}\n */\n function headRowStart(code) {\n if (code === 124) {\n return headRowBreak(code);\n }\n\n // To do: micromark-js should let us parse our own whitespace in extensions,\n // like `markdown-rs`:\n //\n // ```js\n // // 4+ spaces.\n // if (markdownSpace(code)) {\n // return nok(code)\n // }\n // ```\n\n seen = true;\n // Count the first character, that isn’t a pipe, double.\n sizeB += 1;\n return headRowBreak(code);\n }\n\n /**\n * At break in table head row.\n *\n * ```markdown\n * > | | a |\n * ^\n * ^\n * ^\n * | | - |\n * | | b |\n * ```\n *\n * @type {State}\n */\n function headRowBreak(code) {\n if (code === null) {\n // Note: in `markdown-rs`, we need to reset, in `micromark-js` we don‘t.\n return nok(code);\n }\n if (markdownLineEnding(code)) {\n // If anything other than one pipe (ignoring whitespace) was used, it’s fine.\n if (sizeB > 1) {\n sizeB = 0;\n // To do: check if this works.\n // Feel free to interrupt:\n self.interrupt = true;\n effects.exit('tableRow');\n effects.enter(\"lineEnding\");\n effects.consume(code);\n effects.exit(\"lineEnding\");\n return headDelimiterStart;\n }\n\n // Note: in `markdown-rs`, we need to reset, in `micromark-js` we don‘t.\n return nok(code);\n }\n if (markdownSpace(code)) {\n // To do: check if this is fine.\n // effects.attempt(State::Next(StateName::GfmTableHeadRowBreak), State::Nok)\n // State::Retry(space_or_tab(tokenizer))\n return factorySpace(effects, headRowBreak, \"whitespace\")(code);\n }\n sizeB += 1;\n if (seen) {\n seen = false;\n // Header cell count.\n size += 1;\n }\n if (code === 124) {\n effects.enter('tableCellDivider');\n effects.consume(code);\n effects.exit('tableCellDivider');\n // Whether a delimiter was seen.\n seen = true;\n return headRowBreak;\n }\n\n // Anything else is cell data.\n effects.enter(\"data\");\n return headRowData(code);\n }\n\n /**\n * In table head row data.\n *\n * ```markdown\n * > | | a |\n * ^\n * | | - |\n * | | b |\n * ```\n *\n * @type {State}\n */\n function headRowData(code) {\n if (code === null || code === 124 || markdownLineEndingOrSpace(code)) {\n effects.exit(\"data\");\n return headRowBreak(code);\n }\n effects.consume(code);\n return code === 92 ? headRowEscape : headRowData;\n }\n\n /**\n * In table head row escape.\n *\n * ```markdown\n * > | | a\\-b |\n * ^\n * | | ---- |\n * | | c |\n * ```\n *\n * @type {State}\n */\n function headRowEscape(code) {\n if (code === 92 || code === 124) {\n effects.consume(code);\n return headRowData;\n }\n return headRowData(code);\n }\n\n /**\n * Before delimiter row.\n *\n * ```markdown\n * | | a |\n * > | | - |\n * ^\n * | | b |\n * ```\n *\n * @type {State}\n */\n function headDelimiterStart(code) {\n // Reset `interrupt`.\n self.interrupt = false;\n\n // Note: in `markdown-rs`, we need to handle piercing here too.\n if (self.parser.lazy[self.now().line]) {\n return nok(code);\n }\n effects.enter('tableDelimiterRow');\n // Track if we’ve seen a `:` or `|`.\n seen = false;\n if (markdownSpace(code)) {\n return factorySpace(effects, headDelimiterBefore, \"linePrefix\", self.parser.constructs.disable.null.includes('codeIndented') ? undefined : 4)(code);\n }\n return headDelimiterBefore(code);\n }\n\n /**\n * Before delimiter row, after optional whitespace.\n *\n * Reused when a `|` is found later, to parse another cell.\n *\n * ```markdown\n * | | a |\n * > | | - |\n * ^\n * | | b |\n * ```\n *\n * @type {State}\n */\n function headDelimiterBefore(code) {\n if (code === 45 || code === 58) {\n return headDelimiterValueBefore(code);\n }\n if (code === 124) {\n seen = true;\n // If we start with a pipe, we open a cell marker.\n effects.enter('tableCellDivider');\n effects.consume(code);\n effects.exit('tableCellDivider');\n return headDelimiterCellBefore;\n }\n\n // More whitespace / empty row not allowed at start.\n return headDelimiterNok(code);\n }\n\n /**\n * After `|`, before delimiter cell.\n *\n * ```markdown\n * | | a |\n * > | | - |\n * ^\n * ```\n *\n * @type {State}\n */\n function headDelimiterCellBefore(code) {\n if (markdownSpace(code)) {\n return factorySpace(effects, headDelimiterValueBefore, \"whitespace\")(code);\n }\n return headDelimiterValueBefore(code);\n }\n\n /**\n * Before delimiter cell value.\n *\n * ```markdown\n * | | a |\n * > | | - |\n * ^\n * ```\n *\n * @type {State}\n */\n function headDelimiterValueBefore(code) {\n // Align: left.\n if (code === 58) {\n sizeB += 1;\n seen = true;\n effects.enter('tableDelimiterMarker');\n effects.consume(code);\n effects.exit('tableDelimiterMarker');\n return headDelimiterLeftAlignmentAfter;\n }\n\n // Align: none.\n if (code === 45) {\n sizeB += 1;\n // To do: seems weird that this *isn’t* left aligned, but that state is used?\n return headDelimiterLeftAlignmentAfter(code);\n }\n if (code === null || markdownLineEnding(code)) {\n return headDelimiterCellAfter(code);\n }\n return headDelimiterNok(code);\n }\n\n /**\n * After delimiter cell left alignment marker.\n *\n * ```markdown\n * | | a |\n * > | | :- |\n * ^\n * ```\n *\n * @type {State}\n */\n function headDelimiterLeftAlignmentAfter(code) {\n if (code === 45) {\n effects.enter('tableDelimiterFiller');\n return headDelimiterFiller(code);\n }\n\n // Anything else is not ok after the left-align colon.\n return headDelimiterNok(code);\n }\n\n /**\n * In delimiter cell filler.\n *\n * ```markdown\n * | | a |\n * > | | - |\n * ^\n * ```\n *\n * @type {State}\n */\n function headDelimiterFiller(code) {\n if (code === 45) {\n effects.consume(code);\n return headDelimiterFiller;\n }\n\n // Align is `center` if it was `left`, `right` otherwise.\n if (code === 58) {\n seen = true;\n effects.exit('tableDelimiterFiller');\n effects.enter('tableDelimiterMarker');\n effects.consume(code);\n effects.exit('tableDelimiterMarker');\n return headDelimiterRightAlignmentAfter;\n }\n effects.exit('tableDelimiterFiller');\n return headDelimiterRightAlignmentAfter(code);\n }\n\n /**\n * After delimiter cell right alignment marker.\n *\n * ```markdown\n * | | a |\n * > | | -: |\n * ^\n * ```\n *\n * @type {State}\n */\n function headDelimiterRightAlignmentAfter(code) {\n if (markdownSpace(code)) {\n return factorySpace(effects, headDelimiterCellAfter, \"whitespace\")(code);\n }\n return headDelimiterCellAfter(code);\n }\n\n /**\n * After delimiter cell.\n *\n * ```markdown\n * | | a |\n * > | | -: |\n * ^\n * ```\n *\n * @type {State}\n */\n function headDelimiterCellAfter(code) {\n if (code === 124) {\n return headDelimiterBefore(code);\n }\n if (code === null || markdownLineEnding(code)) {\n // Exit when:\n // * there was no `:` or `|` at all (it’s a thematic break or setext\n // underline instead)\n // * the header cell count is not the delimiter cell count\n if (!seen || size !== sizeB) {\n return headDelimiterNok(code);\n }\n\n // Note: in markdown-rs`, a reset is needed here.\n effects.exit('tableDelimiterRow');\n effects.exit('tableHead');\n // To do: in `markdown-rs`, resolvers need to be registered manually.\n // effects.register_resolver(ResolveName::GfmTable)\n return ok(code);\n }\n return headDelimiterNok(code);\n }\n\n /**\n * In delimiter row, at a disallowed byte.\n *\n * ```markdown\n * | | a |\n * > | | x |\n * ^\n * ```\n *\n * @type {State}\n */\n function headDelimiterNok(code) {\n // Note: in `markdown-rs`, we need to reset, in `micromark-js` we don‘t.\n return nok(code);\n }\n\n /**\n * Before table body row.\n *\n * ```markdown\n * | | a |\n * | | - |\n * > | | b |\n * ^\n * ```\n *\n * @type {State}\n */\n function bodyRowStart(code) {\n // Note: in `markdown-rs` we need to manually take care of a prefix,\n // but in `micromark-js` that is done for us, so if we’re here, we’re\n // never at whitespace.\n effects.enter('tableRow');\n return bodyRowBreak(code);\n }\n\n /**\n * At break in table body row.\n *\n * ```markdown\n * | | a |\n * | | - |\n * > | | b |\n * ^\n * ^\n * ^\n * ```\n *\n * @type {State}\n */\n function bodyRowBreak(code) {\n if (code === 124) {\n effects.enter('tableCellDivider');\n effects.consume(code);\n effects.exit('tableCellDivider');\n return bodyRowBreak;\n }\n if (code === null || markdownLineEnding(code)) {\n effects.exit('tableRow');\n return ok(code);\n }\n if (markdownSpace(code)) {\n return factorySpace(effects, bodyRowBreak, \"whitespace\")(code);\n }\n\n // Anything else is cell content.\n effects.enter(\"data\");\n return bodyRowData(code);\n }\n\n /**\n * In table body row data.\n *\n * ```markdown\n * | | a |\n * | | - |\n * > | | b |\n * ^\n * ```\n *\n * @type {State}\n */\n function bodyRowData(code) {\n if (code === null || code === 124 || markdownLineEndingOrSpace(code)) {\n effects.exit(\"data\");\n return bodyRowBreak(code);\n }\n effects.consume(code);\n return code === 92 ? bodyRowEscape : bodyRowData;\n }\n\n /**\n * In table body row escape.\n *\n * ```markdown\n * | | a |\n * | | ---- |\n * > | | b\\-c |\n * ^\n * ```\n *\n * @type {State}\n */\n function bodyRowEscape(code) {\n if (code === 92 || code === 124) {\n effects.consume(code);\n return bodyRowData;\n }\n return bodyRowData(code);\n }\n}\n\n/** @type {Resolver} */\n\nfunction resolveTable(events, context) {\n let index = -1;\n let inFirstCellAwaitingPipe = true;\n /** @type {RowKind} */\n let rowKind = 0;\n /** @type {Range} */\n let lastCell = [0, 0, 0, 0];\n /** @type {Range} */\n let cell = [0, 0, 0, 0];\n let afterHeadAwaitingFirstBodyRow = false;\n let lastTableEnd = 0;\n /** @type {Token | undefined} */\n let currentTable;\n /** @type {Token | undefined} */\n let currentBody;\n /** @type {Token | undefined} */\n let currentCell;\n const map = new EditMap();\n while (++index < events.length) {\n const event = events[index];\n const token = event[1];\n if (event[0] === 'enter') {\n // Start of head.\n if (token.type === 'tableHead') {\n afterHeadAwaitingFirstBodyRow = false;\n\n // Inject previous (body end and) table end.\n if (lastTableEnd !== 0) {\n flushTableEnd(map, context, lastTableEnd, currentTable, currentBody);\n currentBody = undefined;\n lastTableEnd = 0;\n }\n\n // Inject table start.\n currentTable = {\n type: 'table',\n start: Object.assign({}, token.start),\n // Note: correct end is set later.\n end: Object.assign({}, token.end)\n };\n map.add(index, 0, [['enter', currentTable, context]]);\n } else if (token.type === 'tableRow' || token.type === 'tableDelimiterRow') {\n inFirstCellAwaitingPipe = true;\n currentCell = undefined;\n lastCell = [0, 0, 0, 0];\n cell = [0, index + 1, 0, 0];\n\n // Inject table body start.\n if (afterHeadAwaitingFirstBodyRow) {\n afterHeadAwaitingFirstBodyRow = false;\n currentBody = {\n type: 'tableBody',\n start: Object.assign({}, token.start),\n // Note: correct end is set later.\n end: Object.assign({}, token.end)\n };\n map.add(index, 0, [['enter', currentBody, context]]);\n }\n rowKind = token.type === 'tableDelimiterRow' ? 2 : currentBody ? 3 : 1;\n }\n // Cell data.\n else if (rowKind && (token.type === \"data\" || token.type === 'tableDelimiterMarker' || token.type === 'tableDelimiterFiller')) {\n inFirstCellAwaitingPipe = false;\n\n // First value in cell.\n if (cell[2] === 0) {\n if (lastCell[1] !== 0) {\n cell[0] = cell[1];\n currentCell = flushCell(map, context, lastCell, rowKind, undefined, currentCell);\n lastCell = [0, 0, 0, 0];\n }\n cell[2] = index;\n }\n } else if (token.type === 'tableCellDivider') {\n if (inFirstCellAwaitingPipe) {\n inFirstCellAwaitingPipe = false;\n } else {\n if (lastCell[1] !== 0) {\n cell[0] = cell[1];\n currentCell = flushCell(map, context, lastCell, rowKind, undefined, currentCell);\n }\n lastCell = cell;\n cell = [lastCell[1], index, 0, 0];\n }\n }\n }\n // Exit events.\n else if (token.type === 'tableHead') {\n afterHeadAwaitingFirstBodyRow = true;\n lastTableEnd = index;\n } else if (token.type === 'tableRow' || token.type === 'tableDelimiterRow') {\n lastTableEnd = index;\n if (lastCell[1] !== 0) {\n cell[0] = cell[1];\n currentCell = flushCell(map, context, lastCell, rowKind, index, currentCell);\n } else if (cell[1] !== 0) {\n currentCell = flushCell(map, context, cell, rowKind, index, currentCell);\n }\n rowKind = 0;\n } else if (rowKind && (token.type === \"data\" || token.type === 'tableDelimiterMarker' || token.type === 'tableDelimiterFiller')) {\n cell[3] = index;\n }\n }\n if (lastTableEnd !== 0) {\n flushTableEnd(map, context, lastTableEnd, currentTable, currentBody);\n }\n map.consume(context.events);\n\n // To do: move this into `html`, when events are exposed there.\n // That’s what `markdown-rs` does.\n // That needs updates to `mdast-util-gfm-table`.\n index = -1;\n while (++index < context.events.length) {\n const event = context.events[index];\n if (event[0] === 'enter' && event[1].type === 'table') {\n event[1]._align = gfmTableAlign(context.events, index);\n }\n }\n return events;\n}\n\n/**\n * Generate a cell.\n *\n * @param {EditMap} map\n * @param {Readonly<TokenizeContext>} context\n * @param {Readonly<Range>} range\n * @param {RowKind} rowKind\n * @param {number | undefined} rowEnd\n * @param {Token | undefined} previousCell\n * @returns {Token | undefined}\n */\n// eslint-disable-next-line max-params\nfunction flushCell(map, context, range, rowKind, rowEnd, previousCell) {\n // `markdown-rs` uses:\n // rowKind === 2 ? 'tableDelimiterCell' : 'tableCell'\n const groupName = rowKind === 1 ? 'tableHeader' : rowKind === 2 ? 'tableDelimiter' : 'tableData';\n // `markdown-rs` uses:\n // rowKind === 2 ? 'tableDelimiterCellValue' : 'tableCellText'\n const valueName = 'tableContent';\n\n // Insert an exit for the previous cell, if there is one.\n //\n // ```markdown\n // > | | aa | bb | cc |\n // ^-- exit\n // ^^^^-- this cell\n // ```\n if (range[0] !== 0) {\n previousCell.end = Object.assign({}, getPoint(context.events, range[0]));\n map.add(range[0], 0, [['exit', previousCell, context]]);\n }\n\n // Insert enter of this cell.\n //\n // ```markdown\n // > | | aa | bb | cc |\n // ^-- enter\n // ^^^^-- this cell\n // ```\n const now = getPoint(context.events, range[1]);\n previousCell = {\n type: groupName,\n start: Object.assign({}, now),\n // Note: correct end is set later.\n end: Object.assign({}, now)\n };\n map.add(range[1], 0, [['enter', previousCell, context]]);\n\n // Insert text start at first data start and end at last data end, and\n // remove events between.\n //\n // ```markdown\n // > | | aa | bb | cc |\n // ^-- enter\n // ^-- exit\n // ^^^^-- this cell\n // ```\n if (range[2] !== 0) {\n const relatedStart = getPoint(context.events, range[2]);\n const relatedEnd = getPoint(context.events, range[3]);\n /** @type {Token} */\n const valueToken = {\n type: valueName,\n start: Object.assign({}, relatedStart),\n end: Object.assign({}, relatedEnd)\n };\n map.add(range[2], 0, [['enter', valueToken, context]]);\n if (rowKind !== 2) {\n // Fix positional info on remaining events\n const start = context.events[range[2]];\n const end = context.events[range[3]];\n start[1].end = Object.assign({}, end[1].end);\n start[1].type = \"chunkText\";\n start[1].contentType = \"text\";\n\n // Remove if needed.\n if (range[3] > range[2] + 1) {\n const a = range[2] + 1;\n const b = range[3] - range[2] - 1;\n map.add(a, b, []);\n }\n }\n map.add(range[3] + 1, 0, [['exit', valueToken, context]]);\n }\n\n // Insert an exit for the last cell, if at the row end.\n //\n // ```markdown\n // > | | aa | bb | cc |\n // ^-- exit\n // ^^^^^^-- this cell (the last one contains two “between” parts)\n // ```\n if (rowEnd !== undefined) {\n previousCell.end = Object.assign({}, getPoint(context.events, rowEnd));\n map.add(rowEnd, 0, [['exit', previousCell, context]]);\n previousCell = undefined;\n }\n return previousCell;\n}\n\n/**\n * Generate table end (and table body end).\n *\n * @param {Readonly<EditMap>} map\n * @param {Readonly<TokenizeContext>} context\n * @param {number} index\n * @param {Token} table\n * @param {Token | undefined} tableBody\n */\n// eslint-disable-next-line max-params\nfunction flushTableEnd(map, context, index, table, tableBody) {\n /** @type {Array<Event>} */\n const exits = [];\n const related = getPoint(context.events, index);\n if (tableBody) {\n tableBody.end = Object.assign({}, related);\n exits.push(['exit', tableBody, context]);\n }\n table.end = Object.assign({}, related);\n exits.push(['exit', table, context]);\n map.add(index + 1, 0, exits);\n}\n\n/**\n * @param {Readonly<Array<Event>>} events\n * @param {number} index\n * @returns {Readonly<Point>}\n */\nfunction getPoint(events, index) {\n const event = events[index];\n const side = event[0] === 'enter' ? 'start' : 'end';\n return event[1][side];\n}","/**\n * @import {Extension, State, TokenizeContext, Tokenizer} from 'micromark-util-types'\n */\n\nimport { factorySpace } from 'micromark-factory-space';\nimport { markdownLineEnding, markdownLineEndingOrSpace, markdownSpace } from 'micromark-util-character';\nconst tasklistCheck = {\n name: 'tasklistCheck',\n tokenize: tokenizeTasklistCheck\n};\n\n/**\n * Create an HTML extension for `micromark` to support GFM task list items\n * syntax.\n *\n * @returns {Extension}\n * Extension for `micromark` that can be passed in `htmlExtensions` to\n * support GFM task list items when serializing to HTML.\n */\nexport function gfmTaskListItem() {\n return {\n text: {\n [91]: tasklistCheck\n }\n };\n}\n\n/**\n * @this {TokenizeContext}\n * @type {Tokenizer}\n */\nfunction tokenizeTasklistCheck(effects, ok, nok) {\n const self = this;\n return open;\n\n /**\n * At start of task list item check.\n *\n * ```markdown\n * > | * [x] y.\n * ^\n * ```\n *\n * @type {State}\n */\n function open(code) {\n if (\n // Exit if there’s stuff before.\n self.previous !== null ||\n // Exit if not in the first content that is the first child of a list\n // item.\n !self._gfmTasklistFirstContentOfListItem) {\n return nok(code);\n }\n effects.enter('taskListCheck');\n effects.enter('taskListCheckMarker');\n effects.consume(code);\n effects.exit('taskListCheckMarker');\n return inside;\n }\n\n /**\n * In task list item check.\n *\n * ```markdown\n * > | * [x] y.\n * ^\n * ```\n *\n * @type {State}\n */\n function inside(code) {\n // Currently we match how GH works in files.\n // To match how GH works in comments, use `markdownSpace` (`[\\t ]`) instead\n // of `markdownLineEndingOrSpace` (`[\\t\\n\\r ]`).\n if (markdownLineEndingOrSpace(code)) {\n effects.enter('taskListCheckValueUnchecked');\n effects.consume(code);\n effects.exit('taskListCheckValueUnchecked');\n return close;\n }\n if (code === 88 || code === 120) {\n effects.enter('taskListCheckValueChecked');\n effects.consume(code);\n effects.exit('taskListCheckValueChecked');\n return close;\n }\n return nok(code);\n }\n\n /**\n * At close of task list item check.\n *\n * ```markdown\n * > | * [x] y.\n * ^\n * ```\n *\n * @type {State}\n */\n function close(code) {\n if (code === 93) {\n effects.enter('taskListCheckMarker');\n effects.consume(code);\n effects.exit('taskListCheckMarker');\n effects.exit('taskListCheck');\n return after;\n }\n return nok(code);\n }\n\n /**\n * @type {State}\n */\n function after(code) {\n // EOL in paragraph means there must be something else after it.\n if (markdownLineEnding(code)) {\n return ok(code);\n }\n\n // Space or tab?\n // Check what comes after.\n if (markdownSpace(code)) {\n return effects.check({\n tokenize: spaceThenNonSpace\n }, ok, nok)(code);\n }\n\n // EOF, or non-whitespace, both wrong.\n return nok(code);\n }\n}\n\n/**\n * @this {TokenizeContext}\n * @type {Tokenizer}\n */\nfunction spaceThenNonSpace(effects, ok, nok) {\n return factorySpace(effects, after, \"whitespace\");\n\n /**\n * After whitespace, after task list item check.\n *\n * ```markdown\n * > | * [x] y.\n * ^\n * ```\n *\n * @type {State}\n */\n function after(code) {\n // EOF means there was nothing, so bad.\n // EOL means there’s content after it, so good.\n // Impossible to have more spaces.\n // Anything else is good.\n return code === null ? nok(code) : ok(code);\n }\n}","/**\n * @typedef {import('micromark-extension-gfm-footnote').HtmlOptions} HtmlOptions\n * @typedef {import('micromark-extension-gfm-strikethrough').Options} Options\n * @typedef {import('micromark-util-types').Extension} Extension\n * @typedef {import('micromark-util-types').HtmlExtension} HtmlExtension\n */\n\nimport {\n combineExtensions,\n combineHtmlExtensions\n} from 'micromark-util-combine-extensions'\nimport {\n gfmAutolinkLiteral,\n gfmAutolinkLiteralHtml\n} from 'micromark-extension-gfm-autolink-literal'\nimport {gfmFootnote, gfmFootnoteHtml} from 'micromark-extension-gfm-footnote'\nimport {\n gfmStrikethrough,\n gfmStrikethroughHtml\n} from 'micromark-extension-gfm-strikethrough'\nimport {gfmTable, gfmTableHtml} from 'micromark-extension-gfm-table'\nimport {gfmTagfilterHtml} from 'micromark-extension-gfm-tagfilter'\nimport {\n gfmTaskListItem,\n gfmTaskListItemHtml\n} from 'micromark-extension-gfm-task-list-item'\n\n/**\n * Create an extension for `micromark` to enable GFM syntax.\n *\n * @param {Options | null | undefined} [options]\n * Configuration (optional).\n *\n * Passed to `micromark-extens-gfm-strikethrough`.\n * @returns {Extension}\n * Extension for `micromark` that can be passed in `extensions` to enable GFM\n * syntax.\n */\nexport function gfm(options) {\n return combineExtensions([\n gfmAutolinkLiteral(),\n gfmFootnote(),\n gfmStrikethrough(options),\n gfmTable(),\n gfmTaskListItem()\n ])\n}\n\n/**\n * Create an extension for `micromark` to support GFM when serializing to HTML.\n *\n * @param {HtmlOptions | null | undefined} [options]\n * Configuration (optional).\n *\n * Passed to `micromark-extens-gfm-footnote`.\n * @returns {HtmlExtension}\n * Extension for `micromark` that can be passed in `htmlExtensions` to\n * support GFM when serializing to HTML.\n */\nexport function gfmHtml(options) {\n return combineHtmlExtensions([\n gfmAutolinkLiteralHtml(),\n gfmFootnoteHtml(options),\n gfmStrikethroughHtml(),\n gfmTableHtml(),\n gfmTagfilterHtml(),\n gfmTaskListItemHtml()\n ])\n}\n","/**\n * @import {Root} from 'mdast'\n * @import {Options} from 'remark-gfm'\n * @import {} from 'remark-parse'\n * @import {} from 'remark-stringify'\n * @import {Processor} from 'unified'\n */\n\nimport {gfmFromMarkdown, gfmToMarkdown} from 'mdast-util-gfm'\nimport {gfm} from 'micromark-extension-gfm'\n\n/** @type {Options} */\nconst emptyOptions = {}\n\n/**\n * Add support GFM (autolink literals, footnotes, strikethrough, tables,\n * tasklists).\n *\n * @param {Options | null | undefined} [options]\n * Configuration (optional).\n * @returns {undefined}\n * Nothing.\n */\nexport default function remarkGfm(options) {\n // @ts-expect-error: TS is wrong about `this`.\n // eslint-disable-next-line unicorn/no-this-assignment\n const self = /** @type {Processor<Root>} */ (this)\n const settings = options || emptyOptions\n const data = self.data()\n\n const micromarkExtensions =\n data.micromarkExtensions || (data.micromarkExtensions = [])\n const fromMarkdownExtensions =\n data.fromMarkdownExtensions || (data.fromMarkdownExtensions = [])\n const toMarkdownExtensions =\n data.toMarkdownExtensions || (data.toMarkdownExtensions = [])\n\n micromarkExtensions.push(gfm(settings))\n fromMarkdownExtensions.push(gfmFromMarkdown())\n toMarkdownExtensions.push(gfmToMarkdown(settings))\n}\n","export function cn(...classes: Array<string | false | null | undefined>): string {\n return classes.filter(Boolean).join(' ');\n}\n\n","'use client';\n\nimport '@assistant-ui/react-markdown/styles/dot.css';\n\nimport {\n type CodeHeaderProps,\n MarkdownTextPrimitive,\n unstable_memoizeMarkdownComponents as memoizeMarkdownComponents,\n useIsMarkdownCodeBlock,\n} from '@assistant-ui/react-markdown';\nimport remarkGfm from 'remark-gfm';\nimport { type FC, memo, useState } from 'react';\nimport { CheckIcon, CopyIcon } from 'lucide-react';\nimport { cn } from '../utils/cn';\n\ninterface MarkdownTextProps {\n content: string;\n}\n\nconst MarkdownTextImpl: FC<MarkdownTextProps> = ({ content }) => {\n return (\n <MarkdownTextPrimitive\n remarkPlugins={[remarkGfm]}\n className=\"cuadra-aui-md\"\n components={defaultComponents}\n {...({ children: content } as { children: string })}\n />\n );\n};\n\nexport const MarkdownText = memo(MarkdownTextImpl);\n\nconst CodeHeader: FC<CodeHeaderProps> = ({ language, code }) => {\n const { isCopied, copyToClipboard } = useCopyToClipboard();\n const onCopy = () => {\n if (!code || isCopied) return;\n copyToClipboard(code);\n };\n\n return (\n <div className=\"cuadra-flex cuadra-items-center cuadra-justify-between cuadra-gap-4 cuadra-mt-4 cuadra-rounded-t-lg cuadra-bg-muted/50 cuadra-border-b cuadra-border-border cuadra-px-4 cuadra-py-2 cuadra-text-sm cuadra-font-normal cuadra-text-foreground cuadra-font-brand\">\n <span className=\"cuadra-lowercase [&>span]:cuadra-text-xs cuadra-font-brand\">{language}</span>\n <button\n onClick={onCopy}\n className=\"cuadra-p-1 cuadra-rounded hover:cuadra-bg-muted cuadra-transition-colors\"\n aria-label=\"Copy code\"\n >\n {!isCopied && <CopyIcon className=\"cuadra-h-4 cuadra-w-4\" />}\n {isCopied && <CheckIcon className=\"cuadra-h-4 cuadra-w-4\" />}\n </button>\n </div>\n );\n};\n\nconst useCopyToClipboard = ({\n copiedDuration = 3000,\n}: {\n copiedDuration?: number;\n} = {}) => {\n const [isCopied, setIsCopied] = useState<boolean>(false);\n\n const copyToClipboard = (value: string) => {\n if (!value) return;\n\n navigator.clipboard.writeText(value).then(() => {\n setIsCopied(true);\n setTimeout(() => setIsCopied(false), copiedDuration);\n });\n };\n\n return { isCopied, copyToClipboard };\n};\n\nconst defaultComponents = memoizeMarkdownComponents({\n h1: ({ className, ...props }) => (\n <h1\n className={cn('cuadra-mb-6 cuadra-scroll-m-20 cuadra-text-2xl cuadra-font-normal cuadra-tracking-tight last:cuadra-mb-0 font-brand', className)}\n {...props}\n />\n ),\n h2: ({ className, ...props }) => (\n <h2\n className={cn(\n 'cuadra-mb-4 cuadra-mt-6 cuadra-scroll-m-20 cuadra-text-xl cuadra-font-normal cuadra-tracking-tight first:cuadra-mt-0 last:cuadra-mb-0 font-brand',\n className,\n )}\n {...props}\n />\n ),\n h3: ({ className, ...props }) => (\n <h3\n className={cn(\n 'cuadra-mb-3 cuadra-mt-5 cuadra-scroll-m-20 cuadra-text-lg cuadra-font-normal cuadra-tracking-tight first:cuadra-mt-0 last:cuadra-mb-0 font-brand',\n className,\n )}\n {...props}\n />\n ),\n h4: ({ className, ...props }) => (\n <h4\n className={cn(\n 'cuadra-mb-4 cuadra-mt-6 cuadra-scroll-m-20 cuadra-text-xl cuadra-font-normal cuadra-tracking-tight first:cuadra-mt-0 last:cuadra-mb-0 font-brand',\n className,\n )}\n {...props}\n />\n ),\n h5: ({ className, ...props }) => (\n <h5 className={cn('cuadra-my-4 cuadra-text-lg cuadra-font-normal first:cuadra-mt-0 last:cuadra-mb-0 font-brand', className)} {...props} />\n ),\n h6: ({ className, ...props }) => (\n <h6 className={cn('cuadra-my-4 cuadra-font-normal first:cuadra-mb-0 font-brand', className)} {...props} />\n ),\n p: ({ className, ...props }) => (\n <p className={cn('cuadra-mb-5 cuadra-mt-5 cuadra-leading-7 first:cuadra-mt-0 last:cuadra-mb-0 font-brand', className)} {...props} />\n ),\n a: ({ className, ...props }) => (\n <a\n className={cn('cuadra-text-primary cuadra-font-medium cuadra-underline cuadra-underline-offset-4 font-brand', className)}\n {...props}\n />\n ),\n blockquote: ({ className, ...props }) => (\n <blockquote className={cn('cuadra-border-l-2 cuadra-pl-6 cuadra-italic font-brand', className)} {...props} />\n ),\n ul: ({ className, ...props }) => (\n <ul className={cn('cuadra-my-5 cuadra-ml-6 cuadra-list-disc [&>li]:cuadra-mt-2 font-brand', className)} {...props} />\n ),\n ol: ({ className, ...props }) => (\n <ol className={cn('cuadra-my-5 cuadra-ml-6 cuadra-list-decimal [&>li]:cuadra-mt-2 font-brand', className)} {...props} />\n ),\n hr: ({ className, ...props }) => <hr className={cn('cuadra-my-5 cuadra-border-b', className)} {...props} />,\n table: ({ className, ...props }) => (\n <table\n className={cn('cuadra-my-5 cuadra-w-full cuadra-border-separate cuadra-border-spacing-0 cuadra-overflow-y-auto font-brand', className)}\n {...props}\n />\n ),\n th: ({ className, ...props }) => (\n <th\n className={cn(\n 'cuadra-bg-muted cuadra-px-4 cuadra-py-2 cuadra-text-left cuadra-font-normal first:cuadra-rounded-tl-lg last:cuadra-rounded-tr-lg [&[align=center]]:cuadra-text-center [&[align=right]]:cuadra-text-right font-brand',\n className,\n )}\n {...props}\n />\n ),\n td: ({ className, ...props }) => (\n <td\n className={cn(\n 'cuadra-border-b cuadra-border-l cuadra-px-4 cuadra-py-2 cuadra-text-left last:cuadra-border-r [&[align=center]]:cuadra-text-center [&[align=right]]:cuadra-text-right font-brand',\n className,\n )}\n {...props}\n />\n ),\n tr: ({ className, ...props }) => (\n <tr\n className={cn(\n 'cuadra-m-0 cuadra-border-b cuadra-p-0 first:cuadra-border-t [&:last-child>td:first-child]:cuadra-rounded-bl-lg [&:last-child>td:last-child]:cuadra-rounded-br-lg',\n className,\n )}\n {...props}\n />\n ),\n sup: ({ className, ...props }) => (\n <sup className={cn('[&>a]:cuadra-text-xs [&>a]:cuadra-no-underline font-brand', className)} {...props} />\n ),\n pre: ({ className, ...props }) => (\n <pre\n className={cn(\n 'cuadra-overflow-x-auto cuadra-rounded-b-lg !cuadra-rounded-t-none cuadra-bg-muted cuadra-p-4 cuadra-text-foreground font-brand',\n className,\n )}\n {...props}\n />\n ),\n code: function Code({ className, ...props }) {\n const isCodeBlock = useIsMarkdownCodeBlock();\n return (\n <code\n className={cn(!isCodeBlock && 'cuadra-bg-muted cuadra-rounded cuadra-border cuadra-font-normal font-brand', className)}\n {...props}\n />\n );\n },\n CodeHeader,\n});\n","import { useEffect, useState } from 'react';\n\nconst STEPS = [\n 'Sending question…',\n 'Understanding your need…',\n 'Scanning data…',\n 'Comparing results…',\n 'Composing answer…',\n];\n\nexport function FakeReasoningLoader({ active }: { active: boolean }) {\n const [index, setIndex] = useState(0);\n\n useEffect(() => {\n if (!active) {\n setIndex(0);\n return;\n }\n\n const id = window.setInterval(() => {\n setIndex((prev) => {\n // Once we reach the last step, stay there and stop advancing\n if (prev >= STEPS.length - 1) {\n window.clearInterval(id);\n return prev;\n }\n return prev + 1;\n });\n }, 2500);\n\n return () => window.clearInterval(id);\n }, [active]);\n\n if (!active) return null;\n\n return <span className=\"cuadra-text-xs cuadra-text-muted-foreground cuadra-font-brand\">Thinking… {STEPS[index]}</span>;\n}\n\n","import { ComposerPrimitive, MessagePrimitive, ThreadPrimitive, useAssistantApi, useThreadRuntime } from '@assistant-ui/react';\nimport { ArrowUpIcon, Loader2 } from 'lucide-react';\nimport { useEffect, useState } from 'react';\nimport { MarkdownText } from './MarkdownText';\nimport { FakeReasoningLoader } from './FakeReasoningLoader';\nimport '@assistant-ui/react-markdown/styles/dot.css';\n\nexport interface SimpleThreadProps {\n /** Welcome screen title */\n welcomeTitle?: string;\n /** Welcome screen subtitle */\n welcomeSubtitle?: string;\n /** Extra top padding for thread viewport (e.g., '1rem', '2rem') */\n extraTopPadding?: string;\n /** Suggestions to show in welcome screen */\n suggestions?: Array<{\n /** Suggestion prompt text */\n prompt: string;\n }>;\n /** Placeholder text for the input field */\n inputPlaceholder?: string;\n}\n\n/**\n * Simple Thread component wrapper\n * Provides a basic chat interface using assistant-ui primitives\n */\nexport function SimpleThread({\n welcomeTitle = 'Hi, how can I help you today?',\n welcomeSubtitle = 'Start exploring our platform and discover what you can build.',\n extraTopPadding,\n suggestions,\n inputPlaceholder = 'Type your message...',\n}: SimpleThreadProps = {}) {\n const thread = useThreadRuntime();\n const [isLoadingMessages, setIsLoadingMessages] = useState(false);\n const [currentThreadId, setCurrentThreadId] = useState<string | null>(null);\n const [hasAssistantContent, setHasAssistantContent] = useState(false);\n\n // Track thread changes and loading state by subscribing to store changes\n useEffect(() => {\n if (!thread) {\n setIsLoadingMessages(false);\n return;\n }\n\n try {\n // Access runtime store to track loading state\n interface RuntimeStore {\n getState?: () => {\n threadId?: string;\n messages?: unknown[];\n isLoadingHistory?: boolean;\n isRunning?: boolean;\n };\n subscribe?: (callback: (state: { threadId?: string; messages?: unknown[]; isLoadingHistory?: boolean; isRunning?: boolean }) => void) => () => void;\n }\n const runtimeStore = (thread as { store?: RuntimeStore })?.store;\n if (!runtimeStore) {\n setIsLoadingMessages(false);\n return;\n }\n\n // Subscribe to store changes\n const unsubscribe = runtimeStore.subscribe?.((state) => {\n const threadId = state?.threadId;\n const messages = (state?.messages || []) as Array<{\n role?: string;\n content?: Array<{ type?: string; text?: string }> | string;\n }>;\n const isLoadingHistory = state?.isLoadingHistory || false;\n const messageCount = messages.length;\n\n // Check if thread changed\n if (threadId && threadId !== currentThreadId) {\n setCurrentThreadId(threadId);\n }\n\n // Only show loading if:\n // 1. We're actively loading history\n // 2. We have no messages yet\n const shouldShowLoading = isLoadingHistory && messageCount === 0;\n setIsLoadingMessages(shouldShowLoading);\n\n // Detect when assistant has started sending visible content\n const hasAssistantWithText = messages.some(\n (m) =>\n m.role === 'assistant' &&\n !!m.content &&\n (Array.isArray(m.content)\n ? m.content.some((c) => (typeof c === 'object' && c?.text ? c.text.trim().length > 0 : false))\n : (typeof m.content === 'string' ? m.content.trim().length > 0 : false)),\n );\n setHasAssistantContent(hasAssistantWithText);\n });\n\n // Initial check\n const state = runtimeStore.getState?.();\n if (state) {\n const threadId = state?.threadId;\n const messages = (state?.messages || []) as Array<{\n role?: string;\n content?: Array<{ type?: string; text?: string }> | string;\n }>;\n const isLoadingHistory = state?.isLoadingHistory || false;\n const messageCount = messages.length;\n\n if (threadId && threadId !== currentThreadId) {\n setCurrentThreadId(threadId);\n }\n\n const shouldShowLoading = isLoadingHistory && messageCount === 0;\n setIsLoadingMessages(shouldShowLoading);\n\n // Detect when assistant has started sending visible content\n const hasAssistantWithText = messages.some(\n (m) =>\n m.role === 'assistant' &&\n !!m.content &&\n (Array.isArray(m.content)\n ? m.content.some((c) => (typeof c === 'object' && c?.text ? c.text.trim().length > 0 : false))\n : (typeof m.content === 'string' ? m.content.trim().length > 0 : false)),\n );\n setHasAssistantContent(hasAssistantWithText);\n }\n\n return () => {\n if (unsubscribe) {\n unsubscribe();\n }\n };\n } catch {\n setIsLoadingMessages(false);\n }\n }, [thread, currentThreadId]);\n\n return (\n <ThreadPrimitive.Root className=\"cuadra-bg-inherit cuadra-flex cuadra-flex-col cuadra-w-full cuadra-h-full\">\n <ThreadPrimitive.Viewport \n className=\"cuadra-w-full cuadra-bg-inherit cuadra-px-4 cuadra-flex-1 cuadra-min-h-0 cuadra-overflow-y-auto cuadra-relative scrollbar-thin cuadra-pt-4\"\n style={extraTopPadding ? { paddingTop: extraTopPadding } : undefined}\n >\n {isLoadingMessages ? (\n <div className=\"cuadra-absolute cuadra-inset-0 cuadra-flex cuadra-items-center cuadra-justify-center\">\n <div className=\"cuadra-flex cuadra-flex-col cuadra-items-center cuadra-gap-2\">\n <Loader2 className=\"cuadra-h-6 cuadra-w-6 cuadra-animate-spin cuadra-text-muted-foreground\" />\n <p className=\"cuadra-text-sm cuadra-text-muted-foreground font-brand\">Loading messages...</p>\n </div>\n </div>\n ) : (\n <>\n <ThreadPrimitive.Empty>\n <WelcomeScreen \n title={welcomeTitle}\n subtitle={welcomeSubtitle}\n suggestions={suggestions}\n />\n </ThreadPrimitive.Empty>\n <ThreadPrimitive.Messages\n components={{\n UserMessage: UserMessage,\n AssistantMessage: AssistantMessage,\n }}\n />\n <ThreadPrimitive.If running>\n {!hasAssistantContent && (\n <div className=\"cuadra-mt-2 cuadra-max-w-2xl\">\n <FakeReasoningLoader active />\n </div>\n )}\n </ThreadPrimitive.If>\n </>\n )}\n </ThreadPrimitive.Viewport>\n <div className=\"cuadra-w-full cuadra-mt-3 cuadra-border-t cuadra-border-border cuadra-pt-4\">\n <ComposerPrimitive.Root className=\"cuadra-relative !cuadra-relative cuadra-flex-1 cuadra-w-full\">\n <ComposerPrimitive.Input\n asChild\n >\n <textarea\n rows={3}\n placeholder={inputPlaceholder}\n className=\"cuadra-flex cuadra-min-h-[80px] cuadra-w-full cuadra-rounded-md cuadra-border cuadra-border-border cuadra-bg-background cuadra-px-3 cuadra-py-2 cuadra-text-base placeholder:cuadra-text-muted-foreground focus-visible:cuadra-outline-none disabled:cuadra-cursor-not-allowed disabled:cuadra-opacity-50 cuadra-resize-none cuadra-pr-10 font-brand\"\n style={{ paddingRight: '2.5rem', fontSize: '1rem', borderWidth: '1px' }}\n />\n </ComposerPrimitive.Input>\n <ComposerPrimitive.Send asChild>\n <button\n className=\"!cuadra-absolute !cuadra-bottom-2 !cuadra-right-2 cuadra-size-8 cuadra-rounded-md cuadra-shadow-sm hover:cuadra-opacity-90 disabled:cuadra-opacity-50 disabled:cuadra-cursor-not-allowed cuadra-flex cuadra-items-center cuadra-justify-center\"\n style={{ \n position: 'absolute', \n bottom: '0.5rem', \n right: '0.5rem',\n backgroundColor: 'var(--primary)',\n color: 'hsl(var(--primary-foreground))'\n }}\n aria-label=\"Send message\"\n type=\"button\"\n >\n <ArrowUpIcon className=\"cuadra-h-4 cuadra-w-4\" />\n </button>\n </ComposerPrimitive.Send>\n </ComposerPrimitive.Root>\n </div>\n </ThreadPrimitive.Root>\n );\n}\n\ninterface WelcomeScreenProps {\n title: string;\n subtitle: string;\n suggestions?: Array<{\n prompt: string;\n }>;\n}\n\n/**\n * Welcome screen component\n */\nfunction WelcomeScreen({ title, subtitle, suggestions }: WelcomeScreenProps) {\n const api = useAssistantApi();\n \n const handleSuggestionClick = async (prompt: string) => {\n try {\n // Use composer API to set text and send (same as normal send button)\n api.composer().setText(prompt);\n \n // Small delay to ensure text is set\n await new Promise(resolve => setTimeout(resolve, 10));\n \n api.composer().send();\n } catch (error) {\n // Silently handle errors - user can retry\n void error;\n }\n };\n\n return (\n <div className=\"cuadra-flex cuadra-flex-col cuadra-items-center cuadra-h-full cuadra-py-12 cuadra-px-4 cuadra-overflow-y-auto scrollbar-hide\">\n <div className=\"cuadra-text-center cuadra-max-w-3xl cuadra-w-full cuadra-flex cuadra-flex-col cuadra-items-center cuadra-justify-center cuadra-min-h-full\">\n <div className=\"cuadra-flex cuadra-flex-col cuadra-items-center cuadra-justify-center cuadra-mb-8\">\n <h2 className=\"cuadra-text-lg cuadra-font-normal cuadra-text-foreground cuadra-mb-2 font-brand\">\n {title}\n </h2>\n <p className=\"cuadra-text-muted-foreground font-brand\">\n {subtitle}\n </p>\n </div>\n {suggestions && suggestions.length > 0 && (\n <div className=\"cuadra-grid cuadra-grid-cols-2 cuadra-gap-2 cuadra-pb-4 cuadra-w-full cuadra-max-w-2xl\">\n {suggestions.map((suggestion, index) => (\n <button\n key={`suggestion-${index}`}\n type=\"button\"\n onClick={() => handleSuggestionClick(suggestion.prompt)}\n className=\"cuadra-w-full cuadra-text-center cuadra-px-4 cuadra-py-3 cuadra-rounded-lg cuadra-border cuadra-border-border cuadra-bg-background cuadra-text-sm font-brand cuadra-cursor-pointer focus:cuadra-outline-none focus:cuadra-ring-0\"\n style={{ borderWidth: '1px' }}\n >\n {suggestion.prompt}\n </button>\n ))}\n </div>\n )}\n </div>\n </div>\n );\n}\n\n/**\n * User message component\n */\nfunction UserMessage() {\n return (\n <MessagePrimitive.Root className=\"cuadra-grid cuadra-w-full cuadra-auto-rows-auto cuadra-grid-cols-[minmax(72px,1fr)_auto] cuadra-gap-y-2 cuadra-py-3 [&:where(>*)]:cuadra-col-start-2\">\n <div \n className=\"cuadra-bg-muted cuadra-text-foreground cuadra-col-start-2 cuadra-row-start-2 cuadra-max-w-[calc(42rem*0.8)] cuadra-break-words cuadra-rounded-3xl cuadra-border cuadra-border-border cuadra-px-5 cuadra-py-2.5 font-brand\"\n style={{ \n maxWidth: 'calc(42rem * 0.8)',\n borderRadius: '1.5rem',\n backgroundColor: 'hsl(var(--muted))',\n color: 'hsl(var(--foreground))',\n paddingLeft: '1.25rem',\n paddingRight: '1.25rem',\n paddingTop: '0.625rem',\n paddingBottom: '0.625rem',\n wordBreak: 'break-word',\n borderWidth: '1px'\n }}\n >\n <MessagePrimitive.Parts\n components={{\n Text: ({ text }) => <MarkdownText content={text || ''} />,\n }}\n />\n </div>\n </MessagePrimitive.Root>\n );\n}\n\n/**\n * Assistant message component\n */\nfunction AssistantMessage() {\n return (\n <MessagePrimitive.Root className=\"cuadra-relative cuadra-grid cuadra-w-full cuadra-grid-cols-[auto_auto_1fr] cuadra-grid-rows-[auto_1fr] cuadra-py-3\">\n <div \n className=\"cuadra-text-foreground cuadra-col-span-2 cuadra-col-start-2 cuadra-row-start-1 cuadra-my-1.5 cuadra-max-w-[90%] cuadra-break-words cuadra-leading-7 font-brand\"\n style={{ \n maxWidth: '90%',\n marginTop: '0.375rem',\n marginBottom: '0.375rem'\n }}\n >\n <MessagePrimitive.Parts\n components={{\n Text: ({ text }) => <MarkdownText content={text || ''} />,\n }}\n />\n </div>\n </MessagePrimitive.Root>\n );\n}\n","import { ThreadListItemPrimitive, ThreadListPrimitive, useThread, useThreadListItem } from '@assistant-ui/react';\nimport { MoreVertical, Plus } from 'lucide-react';\nimport { useEffect, useState } from 'react';\n\n/**\n * ThreadListItem component with rename and delete functionality\n */\nfunction ThreadListItem({ onThreadSelect }: { onThreadSelect?: () => void }) {\n const threadItem = useThreadListItem();\n const currentThread = useThread((state) => state.threadId);\n const [hoveredThreadId, setHoveredThreadId] = useState<string | null>(null);\n const isActive = threadItem?.id === currentThread;\n const isHovered = hoveredThreadId === threadItem?.id;\n\n // Per-thread state for rename\n const [isRenaming, setIsRenaming] = useState(false);\n const [nextTitle, setNextTitle] = useState(threadItem?.title || '');\n const [isMenuOpen, setIsMenuOpen] = useState(false);\n const [busy, setBusy] = useState(false);\n\n const handleRename = async () => {\n if (!threadItem?.remoteId || !nextTitle || nextTitle === threadItem.title) {\n setIsRenaming(false);\n return;\n }\n \n try {\n setBusy(true);\n const adapter = (window as Window & { __cuadraThreadListAdapter?: { rename?: (remoteId: string, newTitle: string) => Promise<void> } }).__cuadraThreadListAdapter;\n if (adapter && typeof adapter.rename === 'function') {\n await adapter.rename(threadItem.remoteId, nextTitle);\n }\n setIsRenaming(false);\n setIsMenuOpen(false);\n } catch {\n // Silently fail - error is already handled by the adapter\n setIsRenaming(false);\n setIsMenuOpen(false);\n } finally {\n setBusy(false);\n }\n };\n\n // Update nextTitle when threadItem.title changes (but not when renaming)\n useEffect(() => {\n if (threadItem?.title && !isRenaming) {\n setNextTitle(threadItem.title);\n }\n }, [threadItem?.title, isRenaming]);\n\n if (!threadItem) {\n return null;\n }\n\n return (\n <ThreadListItemPrimitive.Root\n className={`group cuadra-relative cuadra-flex cuadra-items-center cuadra-gap-3 cuadra-rounded-lg cuadra-transition-colors cuadra-cursor-pointer cuadra-border cuadra-mb-2 ${\n isActive\n ? 'cuadra-bg-muted cuadra-border-border'\n : 'cuadra-border-transparent hover:cuadra-bg-muted hover:cuadra-border-border'\n }`}\n style={{ marginBottom: '0.5rem' }}\n onMouseEnter={() => setHoveredThreadId(threadItem.id)}\n onMouseLeave={() => setHoveredThreadId(null)}\n >\n <ThreadListItemPrimitive.Trigger \n className=\"cuadra-p-3 cuadra-flex-1 cuadra-flex cuadra-items-center cuadra-justify-between cuadra-w-full cuadra-min-w-0 cuadra-cursor-pointer\"\n onClick={() => onThreadSelect?.()}\n >\n <div className=\"cuadra-flex cuadra-flex-col cuadra-min-w-0 cuadra-flex-1 cuadra-items-start cuadra-text-left\">\n {isRenaming ? (\n <input\n className=\"cuadra-flex cuadra-w-full cuadra-rounded-md cuadra-border cuadra-border-input cuadra-bg-background cuadra-px-3 cuadra-py-2 cuadra-text-sm placeholder:cuadra-text-muted-foreground focus-visible:cuadra-outline-none disabled:cuadra-cursor-not-allowed disabled:cuadra-opacity-50 font-brand\"\n value={nextTitle}\n onChange={(e) => setNextTitle(e.target.value)}\n onKeyDown={(e) => {\n if (e.key === 'Enter') {\n void handleRename();\n }\n if (e.key === 'Escape') {\n setIsRenaming(false);\n setNextTitle(threadItem.title || '');\n }\n }}\n disabled={busy}\n autoFocus\n onClick={(e) => e.stopPropagation()}\n />\n ) : (\n <>\n <span className=\"cuadra-text-sm cuadra-font-normal cuadra-text-foreground cuadra-truncate font-brand\">\n {(threadItem.title?.length || 0) > 60 \n ? `${threadItem.title?.slice(0, 60)}…` \n : threadItem.title || 'Chat'}\n </span>\n {((threadItem as unknown) as { updatedAt?: Date }).updatedAt && (\n <span className=\"cuadra-text-xs cuadra-text-muted-foreground cuadra-mt-1 font-brand\">\n {new Date(((threadItem as unknown) as { updatedAt: Date }).updatedAt).toLocaleDateString()}\n </span>\n )}\n </>\n )}\n </div>\n {/* Always reserve space for menu button to prevent layout shift */}\n <div className=\"cuadra-ml-2 cuadra-flex-shrink-0 cuadra-w-6 cuadra-h-6 cuadra-flex cuadra-items-center cuadra-justify-center\">\n {(isHovered || isActive || isMenuOpen) && (\n <div className=\"cuadra-relative\">\n <button\n className=\"cuadra-p-1 cuadra-rounded hover:cuadra-bg-background/50 cuadra-transition-colors\"\n onClick={(e) => {\n e.stopPropagation();\n setIsMenuOpen(!isMenuOpen);\n }}\n aria-label=\"Thread options\"\n >\n <MoreVertical className=\"cuadra-h-4 cuadra-w-4 cuadra-text-muted-foreground\" />\n </button>\n {isMenuOpen && (\n <>\n <div \n className=\"cuadra-fixed cuadra-inset-0 cuadra-z-40\" \n onClick={() => setIsMenuOpen(false)}\n />\n <div className=\"cuadra-absolute cuadra-right-0 cuadra-top-8 cuadra-z-50 cuadra-bg-background cuadra-border cuadra-border-border cuadra-rounded-lg cuadra-shadow-lg cuadra-min-w-[120px] cuadra-overflow-hidden\">\n {isRenaming ? (\n <button\n className=\"cuadra-w-full cuadra-px-3 cuadra-py-2 cuadra-text-sm cuadra-text-left hover:cuadra-bg-muted cuadra-transition-colors font-brand\"\n onClick={(e) => {\n e.stopPropagation();\n void handleRename();\n }}\n disabled={busy}\n >\n Save\n </button>\n ) : (\n <>\n <button\n className=\"cuadra-w-full cuadra-px-3 cuadra-py-2 cuadra-text-sm cuadra-text-left hover:cuadra-bg-muted cuadra-transition-colors font-brand\"\n onClick={(e) => {\n e.stopPropagation();\n setIsRenaming(true);\n setNextTitle(threadItem.title || '');\n setIsMenuOpen(false);\n }}\n >\n Rename\n </button>\n <div className=\"cuadra-border-t cuadra-border-border\" />\n <ThreadListItemPrimitive.Delete asChild>\n <button\n className=\"cuadra-w-full cuadra-px-3 cuadra-py-2 cuadra-text-sm cuadra-text-left cuadra-text-destructive hover:cuadra-bg-muted cuadra-transition-colors font-brand\"\n onClick={(e) => {\n e.stopPropagation();\n setIsMenuOpen(false);\n }}\n >\n Delete\n </button>\n </ThreadListItemPrimitive.Delete>\n </>\n )}\n </div>\n </>\n )}\n </div>\n )}\n </div>\n </ThreadListItemPrimitive.Trigger>\n </ThreadListItemPrimitive.Root>\n );\n}\n\n/**\n * Simple ThreadList component wrapper\n * Provides a basic thread list interface using assistant-ui primitives\n */\nexport function SimpleThreadList({ onThreadSelect }: { onThreadSelect?: () => void }) {\n\n return (\n <ThreadListPrimitive.Root className=\"!cuadra-border-r cuadra-border-border cuadra-flex cuadra-flex-col cuadra-bg-background cuadra-transition-all cuadra-duration-300 cuadra-ease-in-out cuadra-h-full cuadra-w-80\" style={{ borderRightWidth: '1px' }}>\n <div className=\"cuadra-border-b cuadra-border-border cuadra-flex cuadra-items-center cuadra-justify-between cuadra-transition-all cuadra-duration-300 cuadra-h-16 cuadra-px-4\">\n <h3 className=\"cuadra-text-sm cuadra-font-normal cuadra-text-foreground cuadra-text-nowrap font-brand\">Chat History</h3>\n </div>\n\n <div className=\"cuadra-flex-1 cuadra-overflow-y-auto cuadra-p-2 scrollbar-thin\">\n <ThreadListPrimitive.New\n className=\"group cuadra-relative cuadra-flex cuadra-items-center cuadra-gap-3 cuadra-p-3 cuadra-rounded-lg cuadra-cursor-pointer cuadra-transition-colors cuadra-border cuadra-border-transparent hover:cuadra-bg-muted hover:cuadra-border-border\"\n onClick={() => onThreadSelect?.()}\n >\n <div className=\"cuadra-flex-1 cuadra-min-w-0\">\n <div className=\"cuadra-flex cuadra-items-center cuadra-gap-2\">\n <Plus className=\"cuadra-h-4 cuadra-w-4 cuadra-text-muted-foreground\" />\n <h4 className=\"cuadra-text-sm cuadra-font-normal cuadra-text-foreground font-brand\">New Chat</h4>\n </div>\n </div>\n </ThreadListPrimitive.New>\n\n <div className=\"cuadra-my-2 cuadra-border-t cuadra-border-border\"></div>\n\n <ThreadListPrimitive.Items\n components={{\n ThreadListItem: (props) => <ThreadListItem {...props} onThreadSelect={onThreadSelect} />,\n }}\n />\n </div>\n </ThreadListPrimitive.Root>\n );\n}\n","import React from 'react';\n\nconst pulseKeyframes = `\n @keyframes rotate {\n 100% { transform: rotate(1turn); }\n }\n`;\n\ninterface TexturedCardProps {\n children: React.ReactNode;\n className?: string;\n paddingX?: string;\n paddingY?: string;\n borderSizePx?: number;\n style?: React.CSSProperties;\n contentStyle?: React.CSSProperties;\n rotating?: boolean;\n}\n\nexport const TexturedCard: React.FC<TexturedCardProps> = ({\n children,\n className = '',\n paddingX = 'px-0',\n paddingY = 'py-0',\n borderSizePx = 4,\n style,\n contentStyle,\n rotating = false,\n}) => {\n return (\n <>\n <style>{pulseKeyframes}</style>\n <div\n className={`cuadra-relative cuadra-bg-background md:cuadra-rounded-xl cuadra-overflow-hidden ${className}`}\n style={{ padding: borderSizePx, ...style }}\n >\n <div\n className=\"cuadra-absolute md:cuadra-rounded-xl\"\n style={\n rotating\n ? {\n left: '-100%',\n top: '-100%',\n width: '300%',\n height: '300%',\n backgroundImage: 'conic-gradient(#F4633A, #FF7A4D, #FF8C5C, #F4633A, #FF7A4D, #FF8C5C)',\n backgroundRepeat: 'no-repeat',\n backgroundSize: 'cover',\n backgroundPosition: 'center',\n animation: 'rotate 4s linear infinite',\n }\n : {\n backgroundImage: 'linear-gradient(to right, #F4633A, #FF7A4D, #FF8C5C, #F4633A)',\n backgroundSize: 'cover',\n backgroundPosition: 'center',\n backgroundRepeat: 'no-repeat',\n top: '0',\n left: '0',\n width: '100%',\n height: '100%',\n }\n }\n />\n <div\n className={`cuadra-relative cuadra-bg-background cuadra-h-full cuadra-z-10 cuadra-flex cuadra-flex-col cuadra-overflow-hidden ${paddingX} ${paddingY}`}\n style={{\n borderRadius: 'calc(0.75rem - 4px)',\n ...contentStyle,\n }}\n >\n {children}\n </div>\n </div>\n </>\n );\n};\n\n","import React, { useEffect, useState } from 'react';\nimport { Contrast } from 'lucide-react';\n\ninterface ThemeToggleProps {\n className?: string;\n theme?: 'light' | 'dark' | 'system';\n}\n\nexport const ThemeToggle: React.FC<ThemeToggleProps> = ({ className = '', theme: initialTheme = 'system' }) => {\n const getInitialTheme = (): 'light' | 'dark' => {\n if (typeof window === 'undefined') return 'light';\n \n if (initialTheme === 'system') {\n const saved = localStorage.getItem('theme') as 'light' | 'dark' | null;\n if (saved) return saved;\n if (window.matchMedia('(prefers-color-scheme: dark)').matches) return 'dark';\n return 'light';\n }\n \n return initialTheme;\n };\n\n const [theme, setTheme] = useState<'light' | 'dark'>(getInitialTheme);\n\n useEffect(() => {\n if (initialTheme !== 'system') {\n setTheme(initialTheme);\n }\n }, [initialTheme]);\n\n useEffect(() => {\n const root = document.documentElement;\n root.classList.remove('light', 'dark');\n root.classList.add(theme);\n if (initialTheme === 'system') {\n localStorage.setItem('theme', theme);\n }\n }, [theme, initialTheme]);\n\n const toggleTheme = () => {\n if (initialTheme === 'system') {\n setTheme((prev) => (prev === 'light' ? 'dark' : 'light'));\n }\n };\n\n return (\n <button\n type=\"button\"\n aria-label=\"Toggle theme\"\n onClick={toggleTheme}\n disabled={initialTheme !== 'system'}\n className={`cuadra-flex cuadra-items-center cuadra-justify-center cuadra-h-8 cuadra-w-8 cuadra-rounded-full cuadra-bg-muted hover:cuadra-bg-muted/80 cuadra-transition-colors disabled:cuadra-opacity-50 disabled:cuadra-cursor-not-allowed ${className}`}\n >\n <Contrast\n className={`cuadra-h-4 cuadra-w-4 cuadra-transition-colors ${theme === 'dark' ? 'cuadra-text-primary' : 'cuadra-text-gray-400'}`}\n />\n </button>\n );\n};\n\n","import React, { useEffect, useRef, useState } from 'react';\nimport { ChevronDown, Menu } from 'lucide-react';\nimport { ThemeToggle } from './ThemeToggle';\n\ninterface ChatHeaderProps {\n currentModel: string;\n models: Array<{ id: string; name: string }>;\n modelsLoading: boolean;\n modelsError?: Error | null;\n onModelChange: (model: string) => void;\n hideModelSelector?: boolean;\n showThemeToggle?: boolean;\n theme?: 'light' | 'dark' | 'system';\n onMobileMenuClick?: () => void;\n showMobileMenuButton?: boolean;\n}\n\nexport const ChatHeader: React.FC<ChatHeaderProps> = ({\n currentModel,\n models,\n modelsLoading,\n modelsError,\n onModelChange,\n hideModelSelector = false,\n showThemeToggle = true,\n theme = 'system',\n onMobileMenuClick,\n showMobileMenuButton = false,\n}) => {\n const [isOpen, setIsOpen] = useState(false);\n const selectRef = useRef<HTMLDivElement>(null);\n\n useEffect(() => {\n const handleClickOutside = (event: MouseEvent) => {\n if (selectRef.current && !selectRef.current.contains(event.target as Node)) {\n setIsOpen(false);\n }\n };\n\n if (isOpen) {\n document.addEventListener('mousedown', handleClickOutside);\n }\n\n return () => {\n document.removeEventListener('mousedown', handleClickOutside);\n };\n }, [isOpen]);\n\n const selectedModel = models.find((m) => m.id === currentModel);\n\n return (\n <div className=\"cuadra-h-16 cuadra-px-4 cuadra-border-b cuadra-border-border cuadra-flex cuadra-items-center cuadra-justify-between cuadra-bg-background\">\n <div className=\"cuadra-flex cuadra-items-center cuadra-gap-2\">\n {showMobileMenuButton && (\n <button\n type=\"button\"\n onClick={onMobileMenuClick}\n className=\"cuadra-flex cuadra-items-center cuadra-justify-center cuadra-h-8 cuadra-w-8 cuadra-rounded-full cuadra-bg-muted hover:cuadra-bg-muted/80 cuadra-transition-colors disabled:cuadra-opacity-50 disabled:cuadra-cursor-not-allowed md:cuadra-hidden\"\n aria-label=\"Toggle thread list\"\n >\n <Menu className=\"cuadra-h-4 cuadra-w-4 cuadra-text-foreground\" />\n </button>\n )}\n {showThemeToggle && (\n <div className=\"cuadra-flex cuadra-items-center cuadra-gap-2\">\n <ThemeToggle theme={theme} />\n </div>\n )}\n </div>\n <div className=\"cuadra-flex cuadra-items-center cuadra-gap-2 md:cuadra-ml-0 cuadra-ml-auto\">\n {!hideModelSelector && (\n <label className=\"cuadra-hidden md:cuadra-inline cuadra-text-sm cuadra-text-muted-foreground cuadra-font-brand\">Model</label>\n )}\n {hideModelSelector ? null : modelsLoading ? (\n <div className=\"cuadra-w-48 cuadra-rounded-md cuadra-border cuadra-border-border cuadra-px-3 cuadra-py-2 cuadra-bg-muted\">\n <span className=\"cuadra-text-muted-foreground cuadra-text-sm cuadra-font-brand\">Loading...</span>\n </div>\n ) : modelsError ? (\n <div className=\"cuadra-w-48 cuadra-rounded-md cuadra-border cuadra-border-destructive cuadra-px-3 cuadra-py-2 cuadra-bg-destructive/10\">\n <span className=\"cuadra-text-destructive cuadra-text-sm cuadra-font-brand\">Failed to load models</span>\n </div>\n ) : (\n <div ref={selectRef} className=\"cuadra-relative cuadra-w-48\">\n <button\n type=\"button\"\n onClick={() => setIsOpen(!isOpen)}\n disabled={modelsLoading || models.length === 0 || !!modelsError}\n className=\"cuadra-flex cuadra-h-10 cuadra-w-full cuadra-items-center cuadra-justify-between cuadra-rounded-md cuadra-border cuadra-border-input cuadra-bg-background cuadra-px-3 cuadra-py-2 cuadra-text-sm placeholder:cuadra-text-muted-foreground focus:cuadra-outline-none disabled:cuadra-cursor-not-allowed disabled:cuadra-opacity-50 cuadra-font-brand\"\n >\n <span className={selectedModel ? 'cuadra-text-foreground' : 'cuadra-text-muted-foreground'}>\n {selectedModel?.name || 'Select model'}\n </span>\n <ChevronDown className=\"cuadra-ml-2 cuadra-h-4 cuadra-w-4 cuadra-opacity-50\" />\n </button>\n {isOpen && models.length > 0 && (\n <div className=\"cuadra-absolute cuadra-z-50 cuadra-mt-1 cuadra-w-full cuadra-min-w-[8rem] cuadra-overflow-hidden cuadra-rounded-md glass-popover cuadra-text-popover-foreground cuadra-animate-in fade-in-80 cuadra-border cuadra-border-border cuadra-bg-popover cuadra-shadow-md\">\n <div className=\"cuadra-p-1\">\n {models.map((model) => (\n <button\n key={model.id}\n type=\"button\"\n onClick={() => {\n onModelChange(model.id);\n setIsOpen(false);\n }}\n className={`cuadra-relative cuadra-flex cuadra-w-full cuadra-cursor-pointer cuadra-select-none cuadra-items-center cuadra-rounded-sm cuadra-py-1.5 cuadra-pl-8 cuadra-pr-2 cuadra-text-sm cuadra-outline-none focus:cuadra-bg-secondary focus:cuadra-text-secondary-foreground font-brand cuadra-transition-colors ${\n currentModel === model.id\n ? 'cuadra-bg-secondary cuadra-text-secondary-foreground'\n : 'hover:cuadra-bg-secondary/50'\n }`}\n >\n {currentModel === model.id && (\n <span className=\"cuadra-absolute cuadra-left-2 cuadra-flex cuadra-h-3.5 cuadra-w-3.5 cuadra-items-center cuadra-justify-center\">\n <svg\n xmlns=\"http://www.w3.org/2000/svg\"\n width=\"16\"\n height=\"16\"\n fill=\"none\"\n viewBox=\"0 0 16 16\"\n >\n <path\n fill=\"currentColor\"\n fillRule=\"evenodd\"\n d=\"M6.47 10.03a.75.75 0 0 1-1.06-1.06l2-2a.75.75 0 0 1 1.06 0l2 2a.75.75 0 1 1-1.06 1.06L8 9.06l-1.53 1.53Z\"\n clipRule=\"evenodd\"\n />\n </svg>\n </span>\n )}\n <span>{model.name}</span>\n </button>\n ))}\n </div>\n </div>\n )}\n </div>\n )}\n </div>\n </div>\n );\n};\n\n","import React, { createContext, useContext } from 'react';\n\ninterface CuadraWidgetContextType {\n currentModelId: string | null;\n models: Array<{ id: string; name: string }>;\n modelsLoading: boolean;\n modelsError: Error | null;\n onModelChange: (modelId: string) => void;\n refetchModels: () => void;\n}\n\nconst CuadraWidgetContext = createContext<CuadraWidgetContextType | undefined>(undefined);\n\nexport const useCuadraWidgetContext = () => {\n const context = useContext(CuadraWidgetContext);\n if (!context) {\n throw new Error('useCuadraWidgetContext must be used within CuadraWidgetProvider');\n }\n return context;\n};\n\ninterface CuadraWidgetProviderProps {\n children: React.ReactNode;\n value: CuadraWidgetContextType;\n}\n\nexport const CuadraWidgetProvider: React.FC<CuadraWidgetProviderProps> = ({ children, value }) => {\n return (\n <CuadraWidgetContext.Provider value={value}>{children}</CuadraWidgetContext.Provider>\n );\n};\n\n","import { useEffect } from 'react';\n\n/**\n * Hook to inject uikit CSS styles into the DOM\n * \n * IMPORTANT: For the CSS to work, consumers must import it:\n * import '@cuadra-ai/uikit/styles';\n * \n * This hook provides a fallback that tries to inject styles if they're not already loaded.\n */\nexport function useInjectStyles(): void {\n useEffect(() => {\n // Check if styles already injected or if CSS is already loaded\n const existingStyle = document.querySelector('style[data-cuadra-uikit]');\n if (existingStyle) {\n return;\n }\n\n // Check if CSS classes are already available (styles might be loaded via import)\n const testEl = document.createElement('div');\n testEl.className = 'cuadra-flex';\n document.body.appendChild(testEl);\n const stylesLoaded = window.getComputedStyle(testEl).display === 'flex';\n document.body.removeChild(testEl);\n\n if (stylesLoaded) {\n // Styles are already loaded, no need to inject\n return;\n }\n\n // Styles not loaded - try to inject them\n // Note: This is a fallback. The proper way is to import '@cuadra-ai/uikit/styles'\n // Silently attempt to load styles - user should import '@cuadra-ai/uikit/styles'\n\n // Create a link element to load the CSS\n const link = document.createElement('link');\n link.setAttribute('data-cuadra-uikit', 'true');\n link.rel = 'stylesheet';\n link.type = 'text/css';\n \n // Try to find the CSS file\n // In development with file: protocol, try relative path\n // In production, it should be in node_modules\n const possiblePaths = [\n '/node_modules/@cuadra-ai/uikit/dist/uikit.css',\n new URL('../dist/uikit.css', import.meta.url).href,\n ];\n\n let loaded = false;\n for (const path of possiblePaths) {\n link.href = path;\n link.onload = () => {\n loaded = true;\n };\n link.onerror = () => {\n // Try next path\n };\n document.head.appendChild(link);\n if (loaded) break;\n }\n }, []);\n}\n\n","import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react';\nimport { createPortal } from 'react-dom';\nimport { Loader2 } from 'lucide-react';\nimport { CuadraRuntimeProvider } from './CuadraRuntimeProvider';\nimport { SimpleThread } from './SimpleThread';\nimport { SimpleThreadList } from './SimpleThreadList';\nimport { TexturedCard } from '../widget/components/TexturedCard';\nimport { ChatHeader } from '../widget/components/ChatHeader';\nimport { CuadraWidgetProvider } from '../widget/context/CuadraWidgetContext';\nimport { CuadraChatClient } from '../lib/cuadraChatClient';\nimport type { ModelPage } from '../types/cuadra';\nimport { useInjectStyles } from '../utils/useInjectStyles';\n\n// Export the config type for use in React components\nexport interface CuadraUIKitConfig {\n // API Configuration (choose one)\n /** Cuadra API base URL (e.g., 'https://api.cuadra.ai') */\n baseUrl?: string;\n /** Proxy URL for backend-handled authentication (e.g., '/api/chat') */\n proxyUrl?: string;\n \n // Authentication (optional if using proxyUrl)\n /** Bearer token for authentication (optional if backend handles auth) */\n sessionToken?: string | null;\n \n // Chat configuration\n /** Chat mode: single thread or multi-thread */\n mode?: 'singleChat' | 'multiChat';\n /** Model selection mode */\n modelMode?: 'selector' | 'fixed';\n /** Model ID (required if modelMode=\"fixed\") */\n modelId?: string;\n /** Callback when model changes (selector mode) */\n onModelChange?: (modelId: string) => void;\n /** Create temporary chats that auto-delete */\n ephemeral?: boolean;\n /** System prompt for the assistant */\n systemPrompt?: string;\n \n // Thread configuration\n /** Load existing thread (multiChat mode) */\n initialThreadId?: string;\n \n // UI Configuration\n /** Language/locale for i18n (e.g., 'en', 'es', 'fr') */\n language?: string;\n /** Welcome screen title */\n welcomeTitle?: string;\n /** Welcome screen subtitle */\n welcomeSubtitle?: string;\n /** Extra top padding for thread viewport (e.g., '1rem', '2rem') */\n extraTopPadding?: string;\n /** Suggestions to show in welcome screen */\n suggestions?: Array<{\n /** Suggestion prompt text */\n prompt: string;\n }>;\n /** Placeholder text for the input field */\n inputPlaceholder?: string;\n \n // Theme configuration\n /** Show theme toggle button */\n showThemeToggle?: boolean;\n /** Initial theme ('light' | 'dark' | 'system') */\n theme?: 'light' | 'dark' | 'system';\n \n // Container\n /** Container element ID (defaults to 'cuadra-chat') */\n containerId?: string;\n /** CSS classes to add to container element */\n containerClass?: string;\n \n // Callbacks\n /** Called when an error occurs */\n onError?: (error: Error) => void;\n /** Called when chat is created */\n onChatCreated?: (chatId: string) => void;\n /** Called when a user message is sent */\n onUserMessage?: () => void;\n /** Called when thread ID updates */\n onThreadIdUpdate?: (oldId: string, newId: string) => void;\n}\n\n/**\n * Main widget content component - shared between library and widget builds\n * This component does NOT use createRoot - it's a regular React component\n */\nexport const WidgetContent: React.FC<{ config: CuadraUIKitConfig }> = ({ config }) => {\n // Inject styles when component mounts\n useInjectStyles();\n\n const {\n baseUrl,\n proxyUrl,\n sessionToken,\n mode = 'multiChat',\n modelMode = 'fixed',\n modelId,\n onModelChange,\n ephemeral = false,\n systemPrompt,\n initialThreadId,\n welcomeTitle,\n welcomeSubtitle,\n extraTopPadding,\n suggestions,\n inputPlaceholder,\n showThemeToggle = true,\n theme: initialTheme = 'system',\n onError,\n onChatCreated,\n onUserMessage,\n onThreadIdUpdate,\n } = config;\n\n // Mobile sidebar state\n const [isMobileSidebarOpen, setIsMobileSidebarOpen] = useState(false);\n\n // Determine the actual baseUrl and proxy mode\n const actualBaseUrl = proxyUrl || baseUrl || '';\n const isProxyMode = !!proxyUrl;\n\n // Create client for fetching models\n const client = useMemo(\n () => new CuadraChatClient(actualBaseUrl, sessionToken || undefined, isProxyMode),\n [actualBaseUrl, sessionToken, isProxyMode],\n );\n\n // Models state (replacing react-query)\n const [modelsData, setModelsData] = useState<ModelPage | null>(null);\n const [modelsLoading, setModelsLoading] = useState(false);\n const [modelsError, setModelsError] = useState<Error | null>(null);\n \n // Chats loading state (for multiChat mode)\n const [chatsLoading, setChatsLoading] = useState(false);\n \n // Set chatsLoading to true initially for multiChat mode\n useEffect(() => {\n if (mode === 'multiChat') {\n setChatsLoading(true);\n }\n }, [mode]);\n\n // Fetch models function\n const fetchModels = useCallback(async () => {\n if (modelMode !== 'selector') return;\n \n setModelsLoading(true);\n setModelsError(null);\n try {\n const data = await client.listModels();\n setModelsData(data);\n } catch (error) {\n setModelsError(error instanceof Error ? error : new Error('Failed to load models'));\n } finally {\n setModelsLoading(false);\n }\n }, [client, modelMode]);\n\n // Initial fetch and refetch function\n useEffect(() => {\n if (modelMode === 'selector') {\n fetchModels();\n }\n }, [modelMode, fetchModels]);\n\n // Expose refetch function on window for external access\n useEffect(() => {\n if (typeof window !== 'undefined') {\n (window as Window & { __cuadraUIKitRefetchModels?: typeof fetchModels }).__cuadraUIKitRefetchModels = fetchModels;\n }\n return () => {\n if (typeof window !== 'undefined') {\n delete (window as Window & { __cuadraUIKitRefetchModels?: typeof fetchModels }).__cuadraUIKitRefetchModels;\n }\n };\n }, [fetchModels]);\n\n // Track current model ID\n const [currentModelId, setCurrentModelId] = useState<string | null>(\n modelMode === 'fixed' ? modelId || null : null,\n );\n \n // Track previous model ID to detect changes\n const prevModelIdRef = useRef<string | null>(currentModelId);\n\n // Handle model change\n const handleModelChange = useCallback(\n (newModelId: string) => {\n const prevModelId = prevModelIdRef.current;\n setCurrentModelId(newModelId);\n prevModelIdRef.current = newModelId;\n onModelChange?.(newModelId);\n \n // Create a new thread when model changes (if not initial load)\n if (prevModelId !== null && prevModelId !== newModelId && mode === 'multiChat') {\n // Access the runtime to create a new thread\n // Use setTimeout to ensure runtime is available after state update\n setTimeout(() => {\n const runtime = (window as Window & { \n __cuadraThreadListRuntime?: {\n threads?: {\n switchToNewThread?: () => Promise<void> | void;\n createThread?: () => Promise<void> | void;\n };\n switchToNewThread?: () => Promise<void> | void;\n } \n }).__cuadraThreadListRuntime;\n \n // Try multiple ways to create a new thread\n if (runtime?.threads?.switchToNewThread) {\n try {\n void runtime.threads.switchToNewThread();\n } catch (_error) {\n // Silently handle - user can manually create thread\n }\n } else if (runtime?.threads?.createThread) {\n try {\n void runtime.threads.createThread();\n } catch (_error) {\n // Silently handle - user can manually create thread\n }\n } else if (runtime?.switchToNewThread) {\n try {\n void runtime.switchToNewThread();\n } catch (_error) {\n // Silently handle - user can manually create thread\n }\n }\n }, 100);\n }\n },\n [onModelChange, mode],\n );\n\n // Auto-select first model when models are loaded\n useEffect(() => {\n if (\n modelMode === 'selector' &&\n modelsData?.items &&\n modelsData.items.length > 0 &&\n !currentModelId\n ) {\n const firstModel = modelsData.items[0];\n if (firstModel?.id) {\n const modelId = firstModel.id as string;\n setCurrentModelId(modelId);\n onModelChange?.(modelId);\n }\n }\n }, [modelMode, modelsData?.items, currentModelId, onModelChange]);\n\n // Don't render chat UI until we have a model selected (for selector mode)\n const hasModel = modelMode === 'fixed' ? !!modelId : !!currentModelId;\n\n // Prepare models for ChatHeader\n const models = useMemo(\n () =>\n (modelsData?.items || [])\n .filter((m) => m?.id && m?.displayName)\n .map((m) => ({ id: m.id as string, name: m.displayName as string })),\n [modelsData],\n );\n\n // Create widget context value\n const widgetContextValue = useMemo(\n () => ({\n currentModelId: currentModelId || '',\n models,\n modelsLoading,\n modelsError,\n onModelChange: handleModelChange,\n refetchModels: fetchModels,\n }),\n [currentModelId, models, modelsLoading, modelsError, handleModelChange, fetchModels],\n );\n\n // Determine if we're still loading (models and/or chats)\n const isLoading = \n (modelMode === 'selector' && modelsLoading) || \n (mode === 'multiChat' && chatsLoading);\n\n // Show loading state if we're still loading models or chats\n if (isLoading) {\n return (\n <CuadraWidgetProvider value={widgetContextValue}>\n <TexturedCard className=\"cuadra-h-full\" paddingX=\"cuadra-px-0\" paddingY=\"cuadra-py-0\">\n <div className=\"cuadra-flex cuadra-items-center cuadra-justify-center cuadra-h-full\">\n <Loader2 className=\"cuadra-h-6 cuadra-w-6 cuadra-animate-spin cuadra-text-muted-foreground\" />\n </div>\n </TexturedCard>\n </CuadraWidgetProvider>\n );\n }\n\n // Show error state if we need a model but don't have one\n if (modelMode === 'selector' && !hasModel && modelsError) {\n return (\n <CuadraWidgetProvider value={widgetContextValue}>\n <TexturedCard className=\"cuadra-h-full\" paddingX=\"cuadra-px-0\" paddingY=\"cuadra-py-0\">\n <div className=\"cuadra-flex cuadra-items-center cuadra-justify-center cuadra-h-full\">\n <div className=\"cuadra-flex cuadra-flex-col cuadra-items-center cuadra-gap-2\">\n <p className=\"cuadra-text-sm cuadra-text-destructive font-brand\">Failed to load models</p>\n </div>\n </div>\n </TexturedCard>\n </CuadraWidgetProvider>\n );\n }\n\n return (\n <div className=\"cuadra-uikit cuadra-h-full cuadra-w-full\" style={{ height: '100%', width: '100%' }}>\n <CuadraWidgetProvider value={widgetContextValue}>\n <CuadraRuntimeProvider\n baseUrl={isProxyMode ? actualBaseUrl : (baseUrl || actualBaseUrl)}\n sessionToken={sessionToken}\n isProxyMode={isProxyMode}\n mode={mode}\n modelMode={modelMode}\n modelId={currentModelId || modelId || undefined}\n onModelChange={handleModelChange}\n ephemeral={ephemeral}\n systemPrompt={systemPrompt}\n initialThreadId={initialThreadId}\n onError={onError}\n onChatCreated={onChatCreated}\n onUserMessage={onUserMessage}\n onThreadIdUpdate={onThreadIdUpdate}\n onChatsLoaded={() => {\n if (mode === 'multiChat') {\n setChatsLoading(false);\n }\n }}\n >\n <TexturedCard\n paddingX=\"cuadra-px-0\"\n paddingY=\"cuadra-py-0\"\n className={`cuadra-h-full ${config.containerClass || ''}`}\n borderSizePx={4}\n style={{ height: '100%' }}\n >\n <div className=\"cuadra-h-full cuadra-flex cuadra-relative\" style={{ height: '100%' }}>\n {mode === 'multiChat' ? (\n <>\n {/* Mobile sidebar overlay - portal for full height */}\n {isMobileSidebarOpen && typeof document !== 'undefined' && createPortal(\n <div\n className=\"cuadra-fixed cuadra-inset-0 cuadra-bg-black/50 cuadra-z-40 md:cuadra-hidden\"\n onClick={() => setIsMobileSidebarOpen(false)}\n />,\n document.body\n )}\n {/* Thread list sidebar - portal on mobile, relative on desktop */}\n {typeof document !== 'undefined' && (\n <>\n {/* Desktop: render inline */}\n <div\n className=\"cuadra-hidden md:cuadra-block !cuadra-border-r cuadra-border-border cuadra-flex cuadra-flex-col cuadra-bg-background cuadra-transition-all cuadra-duration-300 cuadra-ease-in-out cuadra-h-full cuadra-w-80 cuadra-relative\"\n style={{ borderRightWidth: '1px', height: '100%' }}\n >\n <SimpleThreadList onThreadSelect={() => setIsMobileSidebarOpen(false)} />\n </div>\n {/* Mobile: render as portal */}\n {isMobileSidebarOpen && createPortal(\n <div\n className=\"cuadra-block md:cuadra-hidden !cuadra-border-r cuadra-border-border cuadra-flex cuadra-flex-col cuadra-bg-background cuadra-transition-all cuadra-duration-300 cuadra-ease-in-out cuadra-h-screen cuadra-w-80 cuadra-fixed cuadra-z-50 cuadra-top-0 cuadra-left-0 cuadra-translate-x-0\"\n style={{ borderRightWidth: '1px' }}\n >\n <SimpleThreadList onThreadSelect={() => setIsMobileSidebarOpen(false)} />\n </div>,\n document.body\n )}\n </>\n )}\n <div className=\"cuadra-flex-1 cuadra-flex cuadra-flex-col\">\n {modelMode === 'selector' && (\n <ChatHeader\n currentModel={currentModelId || ''}\n models={models}\n modelsLoading={modelsLoading}\n modelsError={modelsError}\n onModelChange={handleModelChange}\n showThemeToggle={showThemeToggle}\n theme={initialTheme}\n onMobileMenuClick={() => setIsMobileSidebarOpen(!isMobileSidebarOpen)}\n showMobileMenuButton={mode === 'multiChat'}\n />\n )}\n <div className=\"cuadra-flex-1 cuadra-relative cuadra-min-h-0 cuadra-space-y-4 cuadra-p-4\">\n <SimpleThread \n welcomeTitle={welcomeTitle}\n welcomeSubtitle={welcomeSubtitle}\n extraTopPadding={extraTopPadding}\n suggestions={suggestions}\n inputPlaceholder={inputPlaceholder}\n />\n </div>\n </div>\n </>\n ) : (\n <div className=\"cuadra-flex-1 cuadra-flex cuadra-flex-col\">\n {modelMode === 'selector' && (\n <ChatHeader\n currentModel={currentModelId || ''}\n models={models}\n modelsLoading={modelsLoading}\n modelsError={modelsError}\n onModelChange={handleModelChange}\n showThemeToggle={showThemeToggle}\n theme={initialTheme}\n />\n )}\n <div className=\"cuadra-flex-1 cuadra-relative cuadra-min-h-0 cuadra-space-y-4 cuadra-p-4\">\n <SimpleThread \n welcomeTitle={welcomeTitle}\n welcomeSubtitle={welcomeSubtitle}\n extraTopPadding={extraTopPadding}\n suggestions={suggestions}\n />\n </div>\n </div>\n )}\n </div>\n </TexturedCard>\n </CuadraRuntimeProvider>\n </CuadraWidgetProvider>\n </div>\n );\n};\n\n","import { type CuadraUIKitConfig, WidgetContent } from './WidgetContent';\nimport type { CuadraRuntimeProviderProps } from './CuadraRuntimeProvider';\n\n// Props interface that matches CuadraRuntimeProviderProps but adds className and proxyUrl\nexport interface CuadraChatProps extends Omit<CuadraRuntimeProviderProps, 'children' | 'isProxyMode'> {\n /** Proxy URL for backend-handled authentication (e.g., '/api/chat' or 'http://localhost:3000') */\n proxyUrl?: string;\n /** Container className for styling */\n className?: string;\n /** Show theme toggle button */\n showThemeToggle?: boolean;\n /** Initial theme ('light' | 'dark' | 'system') */\n theme?: 'light' | 'dark' | 'system';\n /** Language/locale for i18n (e.g., 'en', 'es', 'fr') */\n language?: string;\n /** Welcome screen title */\n welcomeTitle?: string;\n /** Welcome screen subtitle */\n welcomeSubtitle?: string;\n /** Extra top padding for thread viewport (e.g., '1rem', '2rem') */\n extraTopPadding?: string;\n /** Suggestions to show in welcome screen */\n suggestions?: Array<{\n /** Suggestion prompt text */\n prompt: string;\n }>;\n /** Placeholder text for the input field */\n inputPlaceholder?: string;\n /** Called when a user message is sent */\n onUserMessage?: () => void;\n}\n\n/**\n * All-in-one Cuadra Chat component\n * \n * This component uses the widget implementation internally, ensuring\n * consistent styling and behavior with the widget version.\n */\nexport function CuadraChat(props: CuadraChatProps) {\n const config: CuadraUIKitConfig = {\n baseUrl: props.baseUrl,\n proxyUrl: props.proxyUrl,\n sessionToken: props.sessionToken || null,\n mode: props.mode || 'multiChat',\n modelMode: props.modelMode || 'fixed',\n modelId: props.modelId,\n onModelChange: props.onModelChange,\n ephemeral: props.ephemeral,\n systemPrompt: props.systemPrompt,\n initialThreadId: props.initialThreadId,\n language: props.language,\n welcomeTitle: props.welcomeTitle,\n welcomeSubtitle: props.welcomeSubtitle,\n extraTopPadding: props.extraTopPadding,\n suggestions: props.suggestions,\n inputPlaceholder: props.inputPlaceholder,\n onError: props.onError,\n onChatCreated: props.onChatCreated,\n onUserMessage: props.onUserMessage,\n onThreadIdUpdate: props.onThreadIdUpdate,\n showThemeToggle: props.showThemeToggle,\n theme: props.theme,\n containerClass: props.className,\n };\n\n return <WidgetContent config={config} />;\n}\n\n"],"names":["toKebabCase","string","toCamelCase","match","p1","p2","toPascalCase","camelCase","mergeClasses","classes","className","index","array","hasA11yProp","props","prop","defaultAttributes","Icon","forwardRef","color","size","strokeWidth","absoluteStrokeWidth","children","iconNode","rest","ref","createElement","tag","attrs","createLucideIcon","iconName","Component","__iconNode","ArrowUp","Check","ChevronDown","Contrast","Copy","EllipsisVertical","LoaderCircle","Menu","Plus","CuadraChatClient","baseUrl","sessionToken","isProxyMode","__publicField","token","endpoint","path","request","abortSignal","url","headers","body","response","errorData","chatId","params","expand","generateHex","count","generateVariant","variants","update","errorText","text","modelId","parseSSEStream","stream","reader","decoder","buffer","done","value","lines","line","data","convertToCuadraMessages","messages","msg","content","textContent","c","convertFromCuadraMessage","createChatModelAdapter","client","options","systemPrompt","ephemeral","onChatCreated","onUserMessage","onThreadIdUpdate","context","currentThreadId","accumulatedText","chunk","chunkId","delta","localToRemoteIdMap","createThreadListAdapter","onChatIdReceived","all","cursor","safety","items","chat","id","t","threadId","remoteId","newTitle","_remoteId","_messages","localThreadId","serverChatId","useThreadListItem","history","React","error","message","adapters","jsx","RuntimeAdapterProvider","CuadraRuntimeProvider","mode","_onModelChange","initialThreadId","onError","onChatsLoaded","useMemo","selectedModelId","setSelectedModelId","useState","useEffect","handleChatCreated","useCallback","handleThreadIdUpdate","oldId","newId","modelAdapter","SingleChatProvider","MultiChatProvider","localRuntime","useLocalRuntime","AssistantRuntimeProvider","modelAdapterOptions","_initialThreadId","_onError","threadListAdapter","handleThreadIdUpdateFromAdapter","wrappedAdapter","result","runtimeHook","runtime","unstable_useRemoteThreadListRuntime","ccount","character","source","asciiAlpha","regexCheck","asciiAlphanumeric","asciiControl","code","markdownLineEnding","markdownLineEndingOrSpace","markdownSpace","unicodePunctuation","unicodeWhitespace","regex","check","escapeStringRegexp","convert","test","ok","castFactory","anyFactory","propertiesFactory","typeFactory","tests","checks","any","parameters","checkAsRecord","node","nodeAsRecord","key","type","testFunction","parent","looksLikeANode","empty","CONTINUE","EXIT","SKIP","visitParents","tree","visitor","reverse","is","step","factory","parents","name","visit","subresult","offset","grandparents","toResult","nodeAsParent","child","findAndReplace","list","ignored","pairs","toPairs","pairIndex","grandparent","siblings","handler","find","replace","start","change","nodes","position","matchObject","tupleOrList","tuple","toExpression","toFunction","escape","inConstruct","notInConstruct","gfmAutolinkLiteralFromMarkdown","transformGfmAutolinkLiterals","enterLiteralAutolink","enterLiteralAutolinkValue","exitLiteralAutolink","exitLiteralAutolinkEmail","exitLiteralAutolinkHttp","exitLiteralAutolinkWww","gfmAutolinkLiteralToMarkdown","assert","findUrl","findEmail","_","protocol","domain","prefix","previous","isCorrectDomain","parts","splitUrl","atext","label","trailExec","trail","closingParenIndex","openingParens","closingParens","email","normalizeIdentifier","footnoteReference","footnoteReferencePeek","enterFootnoteCallString","enterFootnoteCall","enterFootnoteDefinitionLabelString","enterFootnoteDefinition","exitFootnoteCallString","exitFootnoteCall","exitFootnoteDefinitionLabelString","exitFootnoteDefinition","state","info","tracker","exit","subexit","gfmFootnoteFromMarkdown","gfmFootnoteToMarkdown","firstLineBlank","footnoteDefinition","mapAll","mapExceptFirst","blank","constructsWithoutStrikethrough","handleDelete","peekDelete","gfmStrikethroughFromMarkdown","enterStrikethrough","exitStrikethrough","gfmStrikethroughToMarkdown","defaultStringLength","markdownTable","table","settings","align","stringLength","alignments","cellMatrix","sizeMatrix","longestCellByColumn","mostCellsPerRow","rowIndex","row","sizes","columnIndex","cell","serialize","toAlignment","before","after","blockquote","map","patternInScope","stack","pattern","listInScope","none","hardBreak","_1","longestStreak","substring","expected","max","formatCodeAsIndented","checkFence","marker","raw","suffix","sequence","checkQuote","definition","quote","checkEmphasis","encodeCharacterReference","classifyCharacter","encodeInfo","outside","inside","outsideKind","insideKind","emphasis","emphasisPeek","between","betweenHead","open","betweenTail","close","testOrVisitor","visitorOrReverse","maybeReverse","overload","emptyOptions","toString","includeImageAlt","includeHtml","one","values","formatHeadingAsSetext","literalWithBreak","heading","rank","html","htmlPeek","image","imagePeek","imageReference","imageReferencePeek","alt","reference","inlineCode","inlineCodePeek","expression","formatLinkAsAutolink","link","linkPeek","linkReference","linkReferencePeek","checkBullet","checkBulletOther","bullet","bulletOther","checkBulletOrdered","checkRule","bulletCurrent","useDifferentMarker","firstListItem","item","checkListItemIndent","style","listItem","listItemIndent","paragraph","phrasing","root","d","checkStrong","strong","strongPeek","checkRuleRepetition","repetition","thematicBreak","handle","gfmTableFromMarkdown","enterTable","enterCell","enterRow","exitCodeText","exitTable","$0","$1","gfmTableToMarkdown","padding","alignDelimiters","around","inlineCodeWithTable","handleTable","handleTableCell","handleTableRow","serializeData","handleTableAsData","handleTableRowAsData","matrix","defaultHandlers","gfmTaskListItemFromMarkdown","exitCheck","exitParagraphWithTaskListItem","gfmTaskListItemToMarkdown","listItemWithTaskListItem","head","firstParaghraph","sibling","checkable","checkbox","gfmFromMarkdown","gfmToMarkdown","splice","remove","end","chunkStart","hasOwnProperty","combineExtensions","extensions","syntaxExtension","extension","hook","left","right","constructs","existing","wwwPrefix","tokenizeWwwPrefix","tokenizeDomain","tokenizePath","tokenizeTrail","emailDomainDotTrail","tokenizeEmailDomainDotTrail","wwwAutolink","tokenizeWwwAutolink","previousWww","protocolAutolink","tokenizeProtocolAutolink","previousProtocol","emailAutolink","tokenizeEmailAutolink","previousEmail","gfmAutolinkLiteral","effects","nok","self","dot","gfmAtext","previousUnbalanced","emailDomain","emailDomainAfter","emailDomainDot","wwwStart","wwwAfter","seen","protocolStart","protocolPrefixInside","protocolSlashesInside","afterProtocol","protocolAfter","wwwPrefixInside","wwwPrefixAfter","underscoreInLastSegment","underscoreInLastLastSegment","domainInside","domainAfter","domainAtPunctuation","sizeOpen","sizeClose","pathInside","pathAtPunctuation","trailCharacterReferenceStart","trailBracketAfter","trailCharacterReferenceInside","events","resolveAll","called","resolve","factorySpace","limit","blankLine","tokenizeBlankLine","indent","tokenizeIndent","gfmFootnote","tokenizeDefinitionStart","tokenizeDefinitionContinuation","gfmFootnoteDefinitionEnd","tokenizeGfmFootnoteCall","tokenizePotentialGfmFootnoteCall","resolveToPotentialGfmFootnoteCall","defined","labelStart","call","replacement","callStart","callData","callEscape","identifier","labelAtMarker","labelInside","labelAfter","labelEscape","whitespaceAfter","afterPrefix","tail","gfmStrikethrough","single","tokenizer","tokenizeStrikethrough","resolveAllStrikethrough","strikethrough","nextEvents","insideSpan","more","EditMap","add","addImplementation","a","b","vecs","slice","element","editMap","at","gfmTableAlign","inDelimiterRow","event","alignIndex","gfmTable","tokenizeTable","resolveTable","sizeB","next","bodyRowStart","headRowBefore","headRowStart","headRowBreak","headDelimiterStart","headRowData","headRowEscape","headDelimiterBefore","headDelimiterValueBefore","headDelimiterCellBefore","headDelimiterNok","headDelimiterLeftAlignmentAfter","headDelimiterCellAfter","headDelimiterFiller","headDelimiterRightAlignmentAfter","bodyRowBreak","bodyRowData","bodyRowEscape","inFirstCellAwaitingPipe","rowKind","lastCell","afterHeadAwaitingFirstBodyRow","lastTableEnd","currentTable","currentBody","currentCell","flushTableEnd","flushCell","range","rowEnd","previousCell","groupName","valueName","getPoint","now","relatedStart","relatedEnd","valueToken","tableBody","exits","related","side","tasklistCheck","tokenizeTasklistCheck","gfmTaskListItem","spaceThenNonSpace","gfm","remarkGfm","micromarkExtensions","fromMarkdownExtensions","toMarkdownExtensions","cn","MarkdownTextImpl","MarkdownTextPrimitive","defaultComponents","MarkdownText","memo","CodeHeader","language","isCopied","copyToClipboard","useCopyToClipboard","jsxs","CopyIcon","CheckIcon","copiedDuration","setIsCopied","memoizeMarkdownComponents","isCodeBlock","useIsMarkdownCodeBlock","STEPS","FakeReasoningLoader","active","setIndex","prev","SimpleThread","welcomeTitle","welcomeSubtitle","extraTopPadding","suggestions","inputPlaceholder","thread","useThreadRuntime","isLoadingMessages","setIsLoadingMessages","setCurrentThreadId","hasAssistantContent","setHasAssistantContent","runtimeStore","unsubscribe","isLoadingHistory","messageCount","hasAssistantWithText","m","ThreadPrimitive","Loader2","Fragment","WelcomeScreen","UserMessage","AssistantMessage","ComposerPrimitive","ArrowUpIcon","title","subtitle","api","useAssistantApi","handleSuggestionClick","prompt","suggestion","MessagePrimitive","ThreadListItem","onThreadSelect","threadItem","currentThread","useThread","hoveredThreadId","setHoveredThreadId","isActive","isHovered","isRenaming","setIsRenaming","nextTitle","setNextTitle","isMenuOpen","setIsMenuOpen","busy","setBusy","handleRename","adapter","ThreadListItemPrimitive","e","MoreVertical","SimpleThreadList","ThreadListPrimitive","pulseKeyframes","TexturedCard","paddingX","paddingY","borderSizePx","contentStyle","rotating","ThemeToggle","initialTheme","getInitialTheme","saved","theme","setTheme","ChatHeader","currentModel","models","modelsLoading","modelsError","onModelChange","hideModelSelector","showThemeToggle","onMobileMenuClick","showMobileMenuButton","isOpen","setIsOpen","selectRef","useRef","handleClickOutside","selectedModel","model","CuadraWidgetContext","createContext","CuadraWidgetProvider","useInjectStyles","testEl","stylesLoaded","possiblePaths","loaded","WidgetContent","config","proxyUrl","modelMode","isMobileSidebarOpen","setIsMobileSidebarOpen","actualBaseUrl","modelsData","setModelsData","setModelsLoading","setModelsError","chatsLoading","setChatsLoading","fetchModels","currentModelId","setCurrentModelId","prevModelIdRef","handleModelChange","newModelId","prevModelId","firstModel","hasModel","widgetContextValue","createPortal","CuadraChat"],"mappings":";;;;;;;;AAOA,MAAMA,KAAc,CAACC,MAAWA,EAAO,QAAQ,sBAAsB,OAAO,EAAE,YAAW,GACnFC,KAAc,CAACD,MAAWA,EAAO;AA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,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86]}
|