import type { DumpOptions } from 'js-yaml' import type MarkdownExit from 'markdown-exit/core' import type { Token } from 'markdown-exit/core' import type MarkdownIt from 'markdown-it' import type { AutoCloseOptions } from './auto-close.ts' // #region Utility Types /** * The `[keyof T] extends [never]` form (rather than `keyof T extends never`) * is the standard trick to prevent TS from distributing the check over a * union — we want to test "is T's keyset empty?" as one yes/no question. */ type Writable = [keyof T] extends [never] ? Record : T // #endregion Utility Types // #region MarkdownDocument /** * A text node in the Markdown AST. */ export type TextNode = string /** * Attributes bag on an element node (props + internal `$` meta). */ export type ElementNodeAttributes = { [key: string]: unknown $?: { line?: number html?: 0 | 1 block?: 0 | 1 /** Opening delimiter, when the syntax has more than one (`\(` or `\[` math) */ markup?: string /** * Set on links `heading-links` adds: `'wrap'` around the heading text, `'separate'` * before or after it. Markdown output leaves both out. */ permalink?: 'wrap' | 'separate' } } /** * A comment node in the Markdown AST (``). * @param null - Null tag marks a comment * @param ElementNodeAttributes - Comment attributes * @param string - Comment content */ export type CommentNode = [null, ElementNodeAttributes, string] /** * An element node in the Markdown AST: `[tag, attrs, ...children]`. */ export type ElementNode = [string, ElementNodeAttributes, ...Node[]] /** * A node in the Markdown AST — element, text, or comment. * * `ElementNode` | `TextNode` | `CommentNode` */ export type Node = ElementNode | TextNode | CommentNode /** * The Markdown document (parse output / AST root). * @param nodes - The nodes of the document * @param frontmatter - The frontmatter data which is the data at the top of the file * @param meta - The meta data of the document, it can be used to store additional data * * The `TMeta` and `TFrontmatter` type parameters allow `parse` / `createMarkdownParser` * to surface plugin-contributed keys with narrow types (see `MergePluginMeta`). */ export interface MarkdownDocument, TFrontmatter = Record> { nodes: Node[] frontmatter: TFrontmatter meta: TMeta } // #endregion // #region Renderer types and interfaces export interface ContextBase { /** * true if node is inside html scope */ html?: boolean /** * true if node is inside a list */ list?: boolean /** * number if node is inside an ordered list */ order?: number /** * @default '\n\n' */ blockSeparator: string /** * @default 'markdown/comark' */ format: 'markdown/comark' | 'markdown/html' | 'text/html' | 'text' /** * @default true */ removeLastStyle?: boolean /** * Maximum number of inline attributes before switching to YAML block syntax. * Set to 0 to always use YAML block syntax. * @default 3 */ maxInlineAttributes?: number /** * Default syntax for block attributes when attributes exceed `maxInlineAttributes`. * - `'codeblock'` — wraps attributes in a fenced YAML code block with `[props]` label * - `'frontmatter'` — wraps attributes in `---` delimiters (frontmatter style) * @default 'codeblock' */ blockAttributesStyle?: 'frontmatter' | 'codeblock' [key: string]: unknown } export interface CreateContext extends ContextBase { /** * user defined node handlers */ handlers: Record } export interface Context extends ContextBase { /** * user defined node handlers */ handlers: Record /** * The conditional handlers of the renderer */ conditionalHandlers: ConditionalNodeHandler[] } /** * The NodeHandler function * @param node - The node to render * @param state - The state of the renderer * @param parent - The parent node * @returns The rendered node */ export type NodeHandler = (node: ElementNode, state: State, parent?: ElementNode) => string | Promise /** * A node handler rule that pairs a match predicate with a handler function. * When `match` returns true for a node, the associated `handler` is used to render it. */ export type ConditionalNodeHandler = { match: (node: ElementNode) => boolean handler: NodeHandler } /** * The State of the renderer * @param handlers - The handlers of the renderer * @param context - The context of the renderer * @param flow - Render children of the node * @param one - Render a single node * @param applyContext - The applyContext of the renderer * @returns The state of the renderer */ export type State = { /** * Additional data to pass to the renderer nodes, can be used to pass pre-fetched data to the renderer nodes */ data: Record /** * Render context — `{ frontmatter, meta, data, props }` — used to * resolve `:prefixed` attributes that reference dot-paths in markdown. * `props` is scoped to the nearest enclosing element as it's mutated during * recursion. */ renderData: NodeRenderData /** * The context of the renderer */ context: Context /** * The handlers of the renderer */ handlers: Record /** * Render children of the node */ flow: (node: ElementNode, state: State, parent?: ElementNode) => Promise /** * Render a single node */ one: (node: Node, state: State, parent?: ElementNode, atLineStart?: boolean) => Promise /** * Render the input */ render: (input: Node[] | ElementNode) => Promise /** * Apply the context * @param edit - The edit to apply to the context * @returns The revert of the edit */ applyContext: (edit: Record) => Record /** * The depth of the node in the tree */ nodeDepthInTree?: number [key: string]: unknown } /** * The context of the renderer */ /** * Auto-generated heading id mode. `true` is an alias for `'flat'`. */ export type HeadingIdsOption = boolean | 'nested' | 'flat' export interface RendererOptions { /** * Additional node handlers to pass to the renderer */ components?: Record /** * Additional data to pass to the renderer nodes, can be used to pass pre-fetched data to the renderer nodes */ data?: Record /** * Change the tag or props of element nodes just before they render. * See {@link NodeTransform}. */ transformNode?: NodeTransform | readonly NodeTransform[] [key: string]: unknown } /** * What a {@link NodeTransform} receives for each element node. */ export interface NodeTransformContext { /** The tag the renderer will use: the node's own tag, or the one an earlier transform returned. */ tag: string /** * The props the renderer will use: the node's attributes with `:` bindings * resolved, or the props an earlier transform returned. Do not mutate them. */ props: Record /** The node as it is in the document, with its raw attributes. Do not mutate it. */ node: ElementNode /** The parent element node, if any. */ parent?: ElementNode /** The render context the node's bindings resolve against. `props` holds the parent's props. */ renderData: NodeRenderData } /** * A replacement tag and/or props for a node. Omitted fields keep their current value. */ export interface NodeTransformResult { /** * The tag to render instead. It is looked up like any tag: in `components`, * then `componentsManifest`, then as a native element. */ tag?: string /** The props to render with instead. They are final: `:` keys are not resolved again. */ props?: Record } /** * Runs for every element node right before a renderer renders it, and may * return a new tag and/or new props. It must be synchronous and must not * mutate its input. Return nothing to keep the node as it is. * * The returned tag and props are rendered as-is. They are not sanitized, and * the security plugin runs at parse time, so it doesn't apply to them either. * Validate anything the transform builds from untrusted data, such as URLs. */ export type NodeTransform = (context: NodeTransformContext) => NodeTransformResult | null | undefined | void /** * The options for rendering markdown */ export interface RenderMarkdownOptions extends RendererOptions { /** * Maximum number of inline attributes before switching to YAML block syntax. * Set to 0 to always use YAML block syntax. * @default 3 */ maxInlineAttributes?: number /** * Default syntax for block attributes when attributes exceed `maxInlineAttributes`. * - `'codeblock'` — wraps attributes in a fenced YAML code block with `[props]` label * - `'frontmatter'` — wraps attributes in `---` delimiters (frontmatter style) * @default 'codeblock' */ blockAttributesStyle?: 'frontmatter' | 'codeblock' /** * Options for YAML serialization of frontmatter (js-yaml DumpOptions). * Defaults: indent=2, lineWidth=-1. */ frontmatterOptions?: DumpOptions /** * The `headingIds` mode the document was parsed with. Heading ids equal to * the auto-generated one are implicit and omitted; any other id is written * as `{#id}`. With `false`, every heading id is written. * @default true */ headingIds?: HeadingIdsOption } export interface NodeRenderData { /* * Frontmatter data from the markdown file */ frontmatter: Record /** * Meta information from Comark Tree */ meta: Record /** * Additional data paased to rendere */ data: Record /** * Props from parent node */ props: Record } // #endregion export type MarkdownExitPlugin = (md: MarkdownExit) => void export type MarkdownItPlugin = (md: MarkdownIt) => void export type MarkdownItPluginWithOptions = (md: MarkdownIt, options: T) => void export interface ComarkParsePreState { markdown: string options: ParserOptions [key: string]: any } export interface ComarkParseTokensState extends ComarkParsePreState { tokens: Token[] } export interface ComarkParsePostState< TMeta = Record, TFrontmatter = Record, > extends ComarkParseTokensState { tree: MarkdownDocument [key: string]: any } /** * Minimal span handle — structural subset of OpenTelemetry's `Span`. * Call {@link ComarkSpan.end} when the timed work is done. */ export interface ComarkSpan { end(): void } /** * Options for starting a span — structural subset of OpenTelemetry `SpanOptions`. */ export interface ComarkSpanOptions { /** Optional attributes attached to the span (OTel `SpanOptions.attributes`). */ attributes?: Record } /** * Timing recorder for the parse pipeline. * * Structural subset of OpenTelemetry's `Tracer` (`startSpan` / * `startActiveSpan`), so you can pass an OTel tracer directly: * * ```ts * import { trace } from '@opentelemetry/api' * const parse = createMarkdownParser({ tracer: trace.getTracer('comark') }) * ``` * * Nested `startActiveSpan` calls form a parent → child hierarchy via the * active context (OTel) or an internal stack (simple recorders). Universal * by design — no Node-specific APIs — so it works in the browser too. * * Like OTel, callers must `span.end()` (including in `finally` / promise * settlement). See {@link ParserOptions.tracer}. */ export interface ComarkTracer { /** * Start a span without making it active. Call `span.end()` when done. * Compatible with OTel `Tracer.startSpan(name, options?)`. */ startSpan(name: string, options?: ComarkSpanOptions): ComarkSpan /** * Start a span, make it active for the duration of `fn`, and pass the span * as the first argument. Nested `startActiveSpan` / `startSpan` calls become * children. Compatible with OTel `Tracer.startActiveSpan` (name + fn, or * name + options + fn). The caller must `span.end()`. */ startActiveSpan(name: string, fn: (span: ComarkSpan) => T): T startActiveSpan(name: string, options: ComarkSpanOptions, fn: (span: ComarkSpan) => T): T } /** * A Comark plugin. * * `TMeta` / `TFrontmatter` are phantom type parameters that record what this * plugin contributes to `tree.meta` / `tree.frontmatter`. They are surfaced * only via the optional `__meta` / `__frontmatter` markers — implementations * never set these at runtime; they exist purely so the contribution survives * `ReturnType` inference and can be merged in `createMarkdownParser`. */ export type ComarkPlugin = { name: string markdownItPlugins?: Array markdownItPost?: (state: ComarkParseTokensState) => void pre?: (state: ComarkParsePreState) => Promise | void post?: (state: ComarkParsePostState, Writable>) => Promise | void /** Auto-close flags for syntax this plugin adds, applied when `autoClose` is `true`. */ autoClose?: Pick /** Phantom — used for type inference only. Never set at runtime. */ __meta?: TMeta /** Phantom — used for type inference only. Never set at runtime. */ __frontmatter?: TFrontmatter } export type ComarkPluginFactory = ( opts?: Options ) => ComarkPlugin // #region Plugin type inference helpers type PluginMetaOf

= P extends ComarkPlugin ? M : {} type PluginFrontmatterOf

= P extends ComarkPlugin ? F : {} /** * Walk a tuple of plugins and intersect their meta contributions. * Returns `{}` when the tuple is empty or when nothing was contributed. */ export type MergePluginMeta = TPlugins extends readonly [infer Head, ...infer Rest] ? PluginMetaOf & MergePluginMeta : {} /** * Walk a tuple of plugins and intersect their frontmatter contributions. */ export type MergePluginFrontmatter = TPlugins extends readonly [ infer Head, ...infer Rest, ] ? PluginFrontmatterOf & MergePluginFrontmatter : {} /** * When no plugin contributed meta keys, fall back to the permissive * `Record` (backwards-compatible). Otherwise, preserve narrow * keys and type unknown accesses as `unknown` (safer than `any`). */ export type ResolvedMeta = [keyof T] extends [never] ? Record : T & Record export type ResolvedFrontmatter = [keyof T] extends [never] ? Record : T & Record // #endregion export type ComponentManifest = (name: string) => unknown | Promise | undefined | null export interface ComarkContextProvider { components: Record componentManifest: ComponentManifest } /** * Rewrites incomplete markdown before Comark tokenizes it. * * In streaming mode, `markdown` is the unstable tail left after Comark reuses * stable nodes from the previous parse. Outside streaming mode, it is the full * input string. */ export type AutoCloseFunction = (markdown: string, streaming?: boolean) => string export interface ParserCoreOptions< TPlugins extends readonly ComarkPlugin[] = readonly ComarkPlugin[], > { /** * Whether to automatically unwrap single paragraphs in container components. * When enabled, if a container component (alert, card, callout, note, warning, tip, info) * has only a single paragraph child, the paragraph wrapper is removed and its children * become direct children of the container. This creates cleaner HTML output. * * @default true * @example * // With autoUnwrap: true (default) * // Text * * // With autoUnwrap: false * //

Text

*/ autoUnwrap?: boolean /** * Remove wrapper tags from the parsed tree, hoisting their children up in * place. Mirrors the MDC `unwrap` behaviour and is primarily used to strip * the `

` wrapper for single-line / inline rendering, e.g. * ``. * * - `true` — unwrap paragraphs (`p`) * - `string` — comma- or whitespace-separated tag names, e.g. `'p, h1'` or `'div p'` * - `string[]` — explicit list of tag names * - `'*'` — matches any tag * * Tags are applied sequentially: each tag descends one level into the result * of the previous one, so `'div p'` unwraps a `

` then the `

` inside * it. After unwrapping, adjacent text nodes are merged into a single string * (like MDC): `a\n\nb` becomes `ab`. * * @default false * @example * // With unwrap: 'p' * // Input: `Hello **world**` * // Nodes: ['Hello ', ['strong', {}, 'world']] (no

wrapper) */ unwrap?: boolean | string | string[] /** * Rewrites incomplete markdown before tokenization. The public parser turns * `autoClose: true` into this function; the core parser has no built-in closer. * The second argument is `true` when the parse was called with `{ streaming: true }`. * @default undefined */ autoClose?: AutoCloseFunction /** * How to auto-generate `id` attributes for `h1`–`h6` headings from their text content. * User-supplied `id` attributes are always preserved. * * - `true` / `'flat'` — slug of the heading's own text only * - `'nested'` — slug prefixed with the parent heading's id (h2+ parents) * - `false` — no auto-generated ids * * Ids are unique within a document: a duplicate gets a numeric suffix * (`options`, `options-1`, `options-2`, ...) in both modes, and a suffixed id * never collides with a heading whose own slug is already `options-1`. * * Generated ids keep Unicode letters, marks, decimal digits, and letter numbers * (`## Café` → `café`, `## 日本語` → `日本語`). Punctuation and symbols are dropped, * and a heading that slugifies to nothing (emoji, punctuation only) gets no id. * A leading ASCII digit is prefixed with `_`. * * @default true * @example * // ## Setup\n### Install * // 'flat' → ['h2', { id: 'setup' }, ...], ['h3', { id: 'install' }, ...] * // 'nested' → ['h2', { id: 'setup' }, ...], ['h3', { id: 'setup-install' }, ...] * // false → ['h2', {}, ...], ['h3', {}, ...] * * // # Café → ['h1', { id: 'café' }, 'Café'] * // # Hello {id="custom"} → ['h1', { id: 'custom' }, 'Hello'] (any mode, including false) */ headingIds?: HeadingIdsOption /** * Additional plugins to use. A plugin with the same name as a default plugin * replaces that default and runs, in user-defined order, after the remaining defaults. * Duplicate user plugins keep their first occurrence. * @default [] */ plugins?: TPlugins /** * Timing recorder for the parse pipeline — see {@link ComarkTracer}. * Structural subset of OpenTelemetry `Tracer`, so an OTel tracer works as-is: * `createMarkdownParser({ tracer: trace.getTracer('comark') })`. * * When provided, the full parse is a root `comark:parse` active span containing * child phases (`comark:autoclose`, `comark:tokenize`, `comark:nodes`) and plugin * hooks (`comark:pre:`, `comark:post:`). Nested active spans form * the hierarchy. No timing overhead when omitted. * @default undefined */ tracer?: ComarkTracer } export interface ParserOptions< TPlugins extends readonly ComarkPlugin[] = readonly ComarkPlugin[], > extends Omit, 'autoClose'> { /** * Whether to automatically close unclosed markdown and Comark components, * or a custom function that rewrites incomplete markdown before tokenization. * `true` (the default) runs the built-in auto-closer. `false` skips it. * A function is forwarded to the core parser as-is; its second argument is * `true` when the parse was called with `{ streaming: true }`. * @default true */ autoClose?: boolean | AutoCloseFunction /** * @deprecated Use `registerDefaultPlugins: false` and register plugins explicitly * (include `linkify()` from `comark/plugins/linkify` only when you need autolinks). * Setting this option logs a deprecation warning. It still takes precedence over * `registerDefaultPlugins`: `false` skips the default linkify plugin, `true` keeps it. */ linkify?: boolean /** * Whether to register the built-in default plugins * (`linkify`, `frontmatter`, `html`, `alert`, `task-list`, `components`, `attributes`). * Set `false` to parse plain markdown with only the plugins listed in `plugins`. * Without the components/attributes plugins, `autoClose` skips component fences and attribute braces. * @default true */ registerDefaultPlugins?: boolean } /** * Type signature for the options object passed to the Comark parser function returned by createMarkdownParser(). */ export type ComarkParseFnOptions = { streaming?: boolean } /** * Type signature for the async Comark parser function returned by createMarkdownParser(). * Accepts a markdown string and optional parsing options, and returns a Promise of MarkdownDocument. */ export type ComarkParseFn, TFrontmatter = Record> = ( markdown: string, opts?: ComarkParseFnOptions ) => Promise>