@lanexio/parser
This page documents @lanexio/parser, the main entry point package that provides a unified API across all Lanexio™ Parser grammars: parse, createParser, register, and detectLanguage.
- Version: Stable
- Module name:
parser - Package:
@lanexio/parser - Import path:
@lanexio/parser - Layer: 6 (Entry)
- Runtime: Universal
- Module format: ESM
- Stability: Stable
- Primary use case: Unified parsing API across all grammar packs.
Layer contract
Section titled “Layer contract”When to use this module
Section titled “When to use this module”- You want a single
parse()function that auto-detects the grammar. - You want to register multiple grammars and switch between them by language, file extension, or MIME type.
- You want a single import instead of importing each grammar pack individually.
Module boundary
Section titled “Module boundary”| Boundary | Description |
|---|---|
| Inputs | string or Uint8Array (source bytes) + ParseOptions (language, filename, mimeType, detect, onUnknown, grammarOptions, convenience keys) |
| Outputs | LexTree |
| Side effects | register() mutates grammarRegistry. grammarRegistry is a shared global. |
| Determinism | Yes (same input + same registrations produce same tree) |
| External dependencies | @lanexio/parser-core, @lanexio/parser-wasm (imported lazily by createParser for WASM grammars) |
| Never-throw guarantee | Yes by default. parse(), LanexioParser.parse, reparse, and the stream methods return LexTree for every input. The single exception: parse() throws LanexioParseError only when no language resolves and onUnknown is set to "throw". createParser() throws LanexioParserError at construction time when grammar instantiation fails. |
| Security surface | None |
Installation
Section titled “Installation”-
Install the package.
Terminal window pnpm add @lanexio/parserTerminal window npm install @lanexio/parserTerminal window yarn add @lanexio/parser -
Import the named export.
import { parse, createParser, register } from '@lanexio/parser';
Peer dependencies
Section titled “Peer dependencies”| Requirement | Required | Layer | Notes |
|---|---|---|---|
@lanexio/parser-core | Yes | 1 | ^1.0.0 |
@lanexio/parser-wasm | Yes | 4 | WASM bridge; imported lazily by createParser only for WASM grammars |
| Grammar packages | No | 2 | Installed separately and registered before use |
Basic Usage
Section titled “Basic Usage”import { parse, register } from '@lanexio/parser';import { htmlRegistration } from '@lanexio/parser-grammar-html';
register(htmlRegistration);
const encoder = new TextEncoder();const tree = parse(encoder.encode('<p>Hello</p>'), { language: 'html' });
console.log(tree.nodeCount);Auto-detection
Section titled “Auto-detection”// Detects grammar from an explicit language, a filename extension, a MIME// type, or content sniffing, in that order.const tree = parse(encoder.encode('<p>Hello</p>'), { language: 'html' });const toml = parse(encoder.encode('key = "value"'), { filename: 'data.toml' });If no hint resolves, parse() returns an error LexTree by default
(onUnknown: "error"). Set onUnknown: "throw" to raise LanexioParseError
instead, or pass a fallback language name to parse that language.
Create a parser handle
Section titled “Create a parser handle”import { createParser } from '@lanexio/parser';import { htmlGrammar } from '@lanexio/parser-grammar-html';
// createParser is async: grammar instantiation can load a WASM bridge.const parser = await createParser(htmlGrammar);const tree = parser.parse(encoder.encode('<p>Hello</p>'));A LanexioParser handle also exposes reparse(previousTree, edit) for
incremental edits and createStream() for push-based streaming, both
never-throwing. createParser itself throws LanexioParserError only when
instantiation fails (for example a grammar/protocol mismatch), because that is
a construction-time configuration error, not a parse-path defect.
Exports
Section titled “Exports”| Export | Type | Description |
|---|---|---|
parse | (source: string | Uint8Array, options?: ParseOptions) => LexTree | Unified parse entry point. Never throws unless onUnknown: "throw" is set and no language resolves. |
createParser | (grammar: LanexioParserPureGrammar | wasmGrammar) => Promise<LanexioParser> | Async. Create a parser handle bound to one grammar (pure or WASM-backed). Throws LanexioParserError only when grammar instantiation fails. |
register | (registration: GrammarRegistration) => void | Register a grammar in the unified registry. |
detectLanguage | (source: string | Uint8Array, hints?: DetectionHints) => DetectionResult | Auto-detect the grammar language from source bytes and hints. |
normalizeLanguage | (name: string) => string | Normalize a language name or alias to its canonical form. |
actionableError | (code: string, context: Readonly<Record<string, string>>) => string | Build a human-readable, actionable message for an error code. |
KNOWN_GRAMMARS | readonly KnownGrammarEntry[] | Metadata for grammars the registry knows by name. |
LANEXIO_PARSER_PACKAGE_NAME | "@lanexio/parser" | Stable npm package name constant. |
grammarRegistry | GrammarRegistry | Shared global registry (re-exported from parser-core). |
LanexioParserError | class | Thrown by createParser at construction time (grammar_load_failed, protocol_mismatch). Carries code and optional cause. |
LanexioParserErrorCode | const object | { GrammarLoadFailed, ProtocolMismatch } construction error codes. |
LanexioParseError | class | Thrown only by parse() when onUnknown: "throw" is set and no language resolves. |
@lanexio/parser also re-exports the parser-core surface (LexTree,
LexNode, LexCursor, PROTOCOL_VERSION, applyEdit, createParseStream,
toyParse, LexToyKind, LexEditError, LexEditErrorCode, walk,
transform, createPipeline, pickParseMode, toValue,
registerValueExtractor, valueExtractorRegistry, and the related types).
Their exact signatures are documented on the
parser-core reference page.
Options
Section titled “Options”ParseOptions
Section titled “ParseOptions”| Field | Type | Required | Default | Description |
|---|---|---|---|---|
language | string | No | undefined | Language name or alias for grammar lookup (e.g., "html", "markdown", "tsql"). |
filename | string | No | undefined | Filename for extension-based detection (e.g., "config.json5"). |
mimeType | string | No | undefined | MIME type for MIME-based detection (e.g., "application/json"). |
detect | boolean | No | enabled only when no explicit hint resolves | Content sniffing on the source bytes. |
onUnknown | "error" | "throw" | string | No | "error" | What to do when no language resolves: return an error tree ("error"), throw LanexioParseError ("throw"), or treat the value as a fallback language name and parse it. |
grammarOptions | Record<string, unknown> | No | undefined | Grammar/dialect pass-through options bag forwarded to the resolved grammar. |
dialect | string | No | undefined | Grammar pass-through convenience key for the SQL grammar dialect (e.g., "postgres", "tsql"). Merged into grammarOptions.dialect when not already set. |
strict | boolean | No | undefined | Grammar pass-through convenience key for the strict-mode parsers (CSV/TSV, XML, TOML). Merged into grammarOptions.strict when not already set. |
validate | boolean | No | undefined | Grammar pass-through convenience key for XML DTD validation. Merged into grammarOptions.validate when not already set. |
clientBatch | "accept" | "reject" | "split" | No | undefined | Grammar pass-through convenience key for the SQL/TSQL client-batch boundary mode. Merged into grammarOptions.clientBatch when not already set. |
spec | "1.0" | "1.1" | No | undefined | Grammar pass-through convenience key for the TOML spec version. Merged into grammarOptions.spec when not already set. |
There is no grammar option: language resolution goes through the registry by
name, filename extension, MIME type, or content sniffing. Dialect languages
such as "tsql", "mssql", and "sqlserver" force the SQL grammar’s tsql
dialect.
dialect, strict, validate, clientBatch, and spec are grammar
pass-through convenience keys (ADR 0048). An explicit grammarOptions value
for the same key wins over the top-level key; when grammarOptions is absent a
top-level key synthesizes { grammarOptions: { key } }; when grammarOptions
is present the merged bag is a shallow copy and never mutates the caller’s
object. An explicit grammarOptions.mode still wins over the strict
convenience key at pickParseMode. The grammar-side semantics for each key are
documented on the grammar reference pages: spec on the TOML grammar,
validate on the XML grammar, and clientBatch on the SQL/TSQL grammar.
Return shape
Section titled “Return shape”| Property | Type | Description |
|---|---|---|
root | LexNode | Root node of the parsed tree. |
nodeCount | number | Total nodes in the tree. |
source | Uint8Array | Original parsed bytes. |
Exported types
Section titled “Exported types”| Type | Purpose | Notes |
|---|---|---|
ParseOptions | Options for parse() | { language?, filename?, mimeType?, detect?, onUnknown?, grammarOptions?, dialect?, strict?, validate?, clientBatch?, spec? } |
GrammarParseOptions | Grammar-facing option subset | Forwarded into grammarOptions during resolution |
LanexioParser | Parser handle returned by createParser | { grammar: string; protocolVersion: number; parse(input: string | Uint8Array): LexTree; reparse(previousTree, edit): LexTree; createStream(): LexParseStream } |
DetectionResult | Result of language detection | { language, confidence, candidates? } |
DetectionHints | Hints for language detection | { language?, filename?, mimeType?, detect? } |
DetectionResult | Result of language detection | Language and confidence |
DetectionHints | Hints for language detection | Extension, MIME type |
KnownGrammarEntry | Entry in KNOWN_GRAMMARS | Grammar metadata |
LexRange | Byte range | Re-export from parser-core |
LanexioParserPureGrammar | Grammar descriptor | Re-export from parser-core |
LexParseStream | Streaming parse interface | Re-export from parser-core |
GrammarRegistration | Grammar registration | Re-export from parser-core |
LexEdit | Edit descriptor | Re-export from parser-core |
Configuration and Extension
Section titled “Configuration and Extension”Grammar registration
Section titled “Grammar registration”Register grammars before calling parse(). The registry supports lookup by language name, file extension, and MIME type.
Known grammars
Section titled “Known grammars”KNOWN_GRAMMARS lists the pre-registered grammar metadata. This is a read-only list for reference.
Accessibility
Section titled “Accessibility”Accessibility requirements
Section titled “Accessibility requirements”- No direct accessibility surface. The main entry point dispatches to grammar-specific parsers. Consuming code is responsible for semantic rendering.
Accessibility checklist
Section titled “Accessibility checklist”| Concern | Status |
|---|---|
| Generated output semantics | Not applicable (dispatch layer) |
| ARIA attributes in serialized output | Not applicable |
| Semantic element round-trip | Not applicable |
Security
Section titled “Security”Security considerations
Section titled “Security considerations”- The unified
parse()function relies on auto-detection but never trusts input: malformed bytes produce an errorLexTree, and unresolved detection returns an error tree by default. parse(), the handle methods, and the stream methods never throw on input.LanexioParseErroris raised only when the caller opts in viaonUnknown: "throw", andLanexioParserErroris a construction-time signal fromcreateParser, not a parse-path failure.- Detection hints (
language,filename,mimeType) and anyonUnknownfallback string are treated as registry keys, never as code or file paths.
| Threat | Mitigation | Status |
|---|---|---|
| Malformed input byte sequence | All parse paths are never-throw; malformed input yields LexError nodes in the returned tree | Implemented |
| Unresolved language detection | Default onUnknown: "error" returns an error LexTree with an actionable message; only onUnknown: "throw" raises LanexioParseError | Implemented |
Companion packages
Section titled “Companion packages”| Package | Relationship | Layer | Notes |
|---|---|---|---|
@lanexio/parser-core | Requires | 1 | Core tree and protocol. Re-exported. |
@lanexio/parser-grammar-html | Dev dependency | 2 | Optional grammar. |
@lanexio/parser-grammar-markdown | Dev dependency | 2 | Optional grammar. |
@lanexio/parser-wasm | Requires | 4 | WASM bridge support. |
Changelog
Section titled “Changelog”| Version | Date | Status | Notable changes |
|---|---|---|---|
1.0.0 | 2026-05-29 | Current | Initial stable release. Apache-2.0. |
Migration notes
Section titled “Migration notes”- None.