@traq-flavored-markdown/sdk
v0.3.0
Published
traQ Markdown presets and processing, distributed as Rust, Wasm, Go and TypeScript.
Readme
SDK: traQ Markdown
This package assembles the Markdown grammar used by traQ and distributes it for Rust, WebAssembly, TypeScript, and Go. Rust owns grammar definitions, AST contracts, and validation; the SDK exposes the supported presets and host APIs.
- npm:
@traq-flavored-markdown/sdk - Go module:
github.com/traPtitech/traq-flavored-markdown/packages/sdk/go
This package combines the core, CommonMark, extensions, and traQ plugin layers for traQ.
The TypeScript createHtmlRenderer() renderer applies traQ display policy to CommonMark
nodes: raw HTML is escaped, links use a restricted scheme list (including
tel, sms, and geo), and rejected links display their escaped Markdown
source. The CommonMark plugin's createSpecHtmlRenderer() renderer is for specification output
and can emit unsafe HTML; it is not used for message display.
traQ's spacing syntax preserves additional blank lines with their source spans
and container structure. Empty quote visibility is a presentation choice: the
standard traQ renderer supplies a line break without inserting an AST node.
Links and both direct and reference images use CommonMark parsing. URL encoding
belongs to parsing; URL scheme and image domain restrictions belong to each
renderer. The standard traQ view displays HTTPS images from its allowed domains.
An image inside a link preserves the outer destination: an allowed image renders
inside that link, and a rejected image keeps its formatted label prefixed with ! inside it.
No nested image-URL link is created, and the image URL need not pass the link
policy when it is only replaced with text. The outer destination must still pass
the link policy. A rejected standalone image becomes a link to its image URL when
the link policy allows its nonempty URL, prefixed with !; otherwise only its
formatted label and ! remain. Descendant links and references retain their
labels without creating nested anchors. Displayed images use plain-text alt
attributes. Rejected ordinary links also keep their formatted labels.
These rules apply to both direct and reference images. Applications can
supply images.validate and links.validate independently. Explicit undefined
options use the same display defaults as omitted options.
Contents
| Location | Purpose |
| ----------------------------- | ------------------------------------------------------------- |
| crates/features | Typed feature bindings and profile membership |
| crates/grammar | Published grammar presets |
| crates/processing | traQ plain-text rendering, extraction, and embedding policies |
| crates/wasm | Wasm interface for the shipped grammar and processing APIs |
| typescript, go, scripts | Host bindings and generated contract types |
Build artifacts are written to dist/; generated TypeScript and Go sources are
committed and must be regenerated from their Rust contracts.
Parse Markdown
Create parsers for the presets your application supports. A runtime compiles Wasm once, then gives each parser and extractor an independent instance.
Browser TypeScript
import { loadRuntime, presets } from '@traq-flavored-markdown/sdk/browser'
const runtime = await loadRuntime()
const parser = runtime.createParser(presets.traq.v1)
const document = parser.parse('**hello** :stamp:')
const inline = parser.parseInline('**hello**')
parser.dispose()loadRuntime fetches the packaged Wasm once and retains its shared runtime for
the page. It deliberately exposes no runtime dispose; dispose individual
parsers, extractors, and plain-text renderers when they are no longer needed.
Read the validated tree through document.document and source utilities through
document.source. Use document.toMutable() for an independent editable draft.
Node payload types and external-input guards are exported by their plugin packages.
@traq-flavored-markdown/sdk/nodes exports the complete node-name catalog.
Bun and other TypeScript hosts
import { createRuntime, presets } from '@traq-flavored-markdown/sdk'
const runtime = await createRuntime(wasmBytes)
try {
const parser = runtime.createParser(presets.traq.v1)
const document = parser.parse('**hello** :stamp:')
const inline = parser.parseInline('**hello**')
} finally {
runtime.dispose()
}wasmBytes is a Uint8Array. With Bun, load
@traq-flavored-markdown/sdk/parser.wasm with Bun.file(...).bytes(). Supply
the bytes directly in hosts that do not use the browser entrypoint.
Go
import markdown "github.com/traPtitech/traq-flavored-markdown/packages/sdk/go"
runtime, err := markdown.NewBundledRuntime(ctx)
if err != nil { return err }
defer runtime.Close(ctx)
parser, err := runtime.NewParser(ctx, markdown.GrammarTraqV1)
if err != nil { return err }
defer parser.Close(ctx)
document, err := parser.Parse(ctx, "**hello** :stamp:")
if err != nil { return err }The Go module embeds the matching Wasm, so NewBundledRuntime works without a
separate artifact or npm package. Use NewRuntime(ctx, wasmBytes) when loading a
matching Wasm artifact yourself. The Go modules are tagged at the same
version as the npm packages; install the SDK with
go get github.com/traPtitech/traq-flavored-markdown/packages/sdk/[email protected]
for the first Go release, then use the matching version for later releases.
Parse and ParseInline return an immutable markdown.Document. Read nodes with
Children, Kind, Span, and DecodePayload; concrete payload types are
generated from Rust contracts. Calls to one parser are serialized. For
parallel parsing, create multiple parsers from the same runtime. Closing a
runtime closes all of its parsers, extractors, and renderers.
Pass the document to Extract and Render to reuse its validated snapshot.
Call ToMutable to edit a detached draft, then NewDocument to validate and own
the resulting tree and payloads. Invalid UTF-8,
missing wire fields, unordered or overlapping sibling spans, and spans that
split a UTF-8 character are rejected before consumers run. Source bytes,
including a leading BOM, CRLF, and NUL, are preserved.
Go failures expose *markdown.Error with a stable Code and optional
Resource, Path, Offset, Span, Phase, Rule, and PayloadType.
Use errors.As to inspect them.
Domain errors leave an instance usable; a Wasm trap or malformed response
closes that instance. A later call reports disposed.
The generated contract ID identifies ABI operations, request and response schemas, node contracts, presets, and limits. Source provenance and the binary digest are recorded separately, so a source-only refactor does not change the semantic contract ID. Build through the shared SDK pipeline to pair Wasm with the generated TypeScript and Go descriptors.
Render and extract a document
For parsing, extraction, and display plain text together, create a processor:
const processor = runtime.createProcessor(presets.traq.v1, {
origin: 'https://q.example.test',
whitespace: 'collapse'
})
const { document, extraction, plainText } =
processor.process('**hello** :stamp:')
processor.dispose()process and processInline parse once and run both consumers against the same
validated native document in one Wasm call. Go exposes the same path through
NewProcessor, Process, and ProcessInline. Independent parsers, extractors,
and plain-text renderers remain available for callers that only need one result.
The whitespace policy defaults to collapse; preserve keeps rendered spacing.
TypeScript parsing produces a ParsedDocument (DocumentContext<NodeVariant>)
that can be passed directly to other consumers;
none of them parses the Markdown source again. The TypeScript renderer works on
the host, while the Go plain-text renderer and extractors call the native Rust
implementation through the same runtime.
import '@traq-flavored-markdown/sdk/index.css'
import { messageRenderers } from '@traq-flavored-markdown/sdk/renderer'
const parser = runtime.createParser(presets.traq.v1)
const extractor = runtime.createExtractor({ origin: 'https://q.example.test' })
const view = messageRenderers({ origin: 'https://q.example.test' })
const document = parser.parse('**hello** !!secret!!')
const extraction = extractor.extract(document)
const prepared = view.prepare(document)
const rendered = prepared.standard()
const condensed = prepared.condensed()
const html = rendered.htmlmessageRenderers builds standard and condensed views. prepare(document)
reuses a validated owner, analyzes semantic links once, then derives presentation
plans for both views. prepared.analysis exposes the shared semantic result.
view.render(document) returns both results; individual
view.standard.render(document) and view.condensed.render(document) are also
available. Preparation also accepts an existing core DocumentContext.
Each result contains rawText, html, and cards; the extractor returns
source-preserving message text, references, attachment and citation IDs, and an
embedding plan. The two views apply presentation choices without rewriting the
parsed AST. Complete Rust, Go, and TypeScript programs are in
examples.
For direct HTML, createHtmlRenderer(options) returns a renderer. createHtmlPreset(options)
returns a preset for the core createRenderer() composition API. Both accept
third-party renderer plugins through plugins; configurePlugins can replace
built-in handlers by returning updated plugin values:
import { definitions } from '@traq-flavored-markdown/commonmark-plugin/nodes'
import { PluginDeclaration } from '@traq-flavored-markdown/core/definitions'
import { RenderPlugin } from '@traq-flavored-markdown/core/renderer'
import { createHtmlRenderer } from '@traq-flavored-markdown/sdk/renderer'
const annotation = new RenderPlugin(new PluginDeclaration('app')).withHandler(
'app::Annotation',
(_node, context) => context.renderChildren()
)
const view = createHtmlRenderer({
plugins: [annotation],
configurePlugins(plugins) {
return {
...plugins,
common: plugins.common.withReplacedHandler(
definitions.Strong,
(_node, context) => '<b>' + context.renderChildren() + '</b>'
)
}
}
})
const rendered = view.render(document)The renderer entrypoint accepts optional adapters and does not load Highlight.js
or KaTeX. Install highlight.js and katex, then explicitly select the bundled
adapters when needed:
import { withDefaultAdapters } from '@traq-flavored-markdown/sdk/adapters'
import { createHtmlRenderer } from '@traq-flavored-markdown/sdk/renderer'
const view = createHtmlRenderer(withDefaultAdapters())Custom code.highlight and math.render callbacks need neither dependency.
Without adapters, code and math preserve escaped source.
For browser display, import katex/dist/katex.min.css and a Highlight.js theme
alongside the SDK stylesheet when using those adapters.
RenderPlugin.withHandler() and RenderPlugin.withReplacedHandler() return new values. Keep the returned
plugin when composing a preset; existing plugins and presets are unchanged.
Built-in plugin groups are common, extensions, and traq. Generated node
definitions carry the node kind, payload validator, and child-structure contract,
so handlers infer their data types and invalid known nodes fail before rendering.
Custom nodes nested inside a known paragraph must use a definition with
role: 'inline' and extend the schema option independently of renderer plugins; see the core API guide for defineNode.
Applications can opt into schema.withUnknownNodes() to preserve unknown roots
and children of unconstrained parents; they use the escaped-source fallback
unless an application plugin handles them.
Display options are grouped by responsibility:
| Option | Purpose |
| ---------------------------------------------------------------------- | ------------------------------------------------------ |
| links.validate, links.attributes | Destination policy and anchor attributes |
| images.validate, images.domains | Markdown image destination policy |
| code.highlight | Optional trusted code HTML adapter |
| math.render, math.renderCondensed | Optional trusted math HTML adapter |
| references.resolve | Application reference labels, routes, and highlighting |
| stamps.resolve, stamps.validateUrl | Stamp lookup and resolved image policy |
| presentation.breaks, presentation.rawHtml, presentation.xhtmlOut | Line breaks, raw HTML, and void-tag style |
labels.file and labels.message replace resource-card link text independently
of URL classification. images.domains replaces the default HTTPS image domain
list; images.validate supplies a complete custom policy.
For example, references.resolve(reference) returns
{ href, label, highlight }, while stamps.resolve(stamp) returns
{ url, title }. Both may return undefined when unresolved. The renderer does
not know application stores or API endpoint layouts. Custom HTML adapters are
trusted code; escape document values before including them in generated HTML.
Direct rendering also supports repeated views with
const session = createHtmlRenderer().createSession(document). Call session.render(plan)
with roots, omittedNodes, childText, or rootSeparator to change presentation
without editing the source AST. A plan may reference original or snapshot nodes
from that document; foreign nodes are rejected before handlers run.
TypeScript runtime failures are MarkdownError values with code, operation,
and optional resource, path, offset, span, phase, rule, and
payloadType. Invalid requests and native
domain errors leave an instance reusable. A trap or malformed Wasm response
closes the instance; later calls report disposed. contract_mismatch identifies
an artifact whose semantic contract differs from the generated SDK. The original
wire details are also retained in cause.
runtime.createPlainTextRenderer() exposes native display plain text, independently of
host HTML. createExtractor() and createPlainTextRenderer() accept omitted options;
their origin defaults to an empty string. Card presentation uses the
ResourceCard type, resourceCardFromUrl(), and endsWithResourceCard() from
the renderer entrypoint. Reference embedding is a separate source-editing API.
The stylesheet shares stamp sizes through --tfm-stamp-normal-size,
--tfm-stamp-small-size, --tfm-stamp-large-size, and
--tfm-stamp-ex-large-size. Compact message views use the normal size for large
stamps and their effects. Animation keyframes use the tfm-stamp- prefix. Colors also use CSS properties,
including --tfm-link-color, --tfm-code-background-color, and
--tfm-spoiler-background-color. Plugin index.css exports provide standalone
markup behavior; SDK index.css composes those bases with the traQ theme.
Sass consumers can load styles/index with the Node package importer
(sass --pkg-importer=node) so plugin styles resolve through their package exports.
Editing source
parseWithSyntax and parseInlineWithSyntax return a ParsedSyntax containing
the usual immutable document and optional parser-owned source facts:
import { analyzeForEditing } from '@traq-flavored-markdown/sdk/editor'
const parsed = parser.parseWithSyntax('> **hello**')
const editing = analyzeForEditing(parsed)
const session = createHtmlRenderer().createSession(parsed.document)
const entry = editing.nodes.find(
entry => entry.node.kind === 'commonmark.strong'
)!
const html = session.render({ roots: [entry.node] })The document can be passed to renderers and extractors directly. Original-byte
facts are available through parsed.syntaxFor(node) and parsed.syntax;
foreign nodes are rejected. Facts and the accompanying AST are immutable owned
snapshots. The native Rust parser exposes the same path as parse_with_syntax
and parse_inline_with_syntax. Ordinary parsing skips syntax capture.
analyzeForEditing reuses the captured facts and returns nodes, lines, and
detached definition markers. All editing ranges use half-open UTF-16
{ from, to } coordinates into the original input string. Nodes retain their
original AST identity and envelope range for subtree rendering, plus separate
content and marker ranges. A content or marker may have multiple ranges across removed container
prefixes. Line contexts expose quote/list ancestry, actual prefixes, continuation
strings, list marker spelling, missing indentation, and block-literal status.
Prefix text preserves whole authored tabs and expresses partial tabs as spaces.
The SDK supplies no CSS classes, DOM decorations, selection state, or IME policy.
Repeated analysis of the same parsed snapshot reuses the result.
describeSource(editing) provides the built-in grammar's semantic source regions
for styles, links, literals, headings, images, stamps, tables, and line containers.
Each region retains its native node and separate content and syntax range
arrays. In particular, multiline content across quote/list prefixes remains
disjoint. This view omits a block's final line ending from its display envelope;
the original facts remain available in editing.nodes. It selects no DOM tags,
CSS classes, or visibility rules. Custom node kinds can be handled directly
through editing.nodes.
Line breaks and indentation can be planned without an editor framework:
import {
analyzeForEditing,
planIndent,
planLineBreak
} from '@traq-flavored-markdown/sdk/editor'
const source = '> 12. item'
const selection = { from: source.length, to: source.length }
const plan = planLineBreak(source, selection, {
analyze: text => analyzeForEditing(parser.parseWithSyntax(text))
})
// plan inserts "\n> 13. " and places the selection after that prefix.
// continueItem: true keeps the current list item (a soft line break).
const indentation = planIndent(source, { from: 0, to: source.length })Each immutable plan contains ordered, disjoint changes in the original
UTF-16 source and a selection in the resulting source. Apply changes from
last to first, or map their positions through the editor's transactions. A list
break may also return completion, including resulting prefix coordinates and
continuation/child spellings for editor-specific follow-up keys. CRLF/CR line
endings are preserved. Invalid ranges, including surrogate-pair interiors, throw
RangeError. Reference atoms, selection direction, Undo boundaries, composition,
and DOM updates belong to the integrating editor.
SourceText.utf16Offset(byteOffset) and byteOffset(utf16Offset) provide cached
coordinate conversion; invalid UTF-8 boundaries and positions inside surrogate
pairs are rejected. CRLF, NUL, and BOM remain in the original string. If an editor
projects reference chips to U+FFFC, parse that projected string for editing;
mapping chips to serialized message JSON remains an editor concern.
Grammar versions
Grammar versions identify the rules used to write a message. Store that value
with the source and create a parser for the stored version when reading it back.
Unknown versions fail rather than silently selecting a newer grammar.
In TypeScript, check a stored string with isGrammarPresetId(version) before passing it
to createParser; the guard narrows it to the generated GrammarPresetId type.
presets.traq.v1 and GrammarTraqV1 are generated from the Rust preset catalog.
Custom grammars are composed in Rust and published through that catalog; the
TypeScript and Go APIs intentionally do not mirror the Rust grammar builder.
The v1 grammar is currently unreleased; its APIs and behavior can still change
after explicit review. Released presets preserve their interpretation of stored
content, with behavior changes assigned a new version.
