Skip to content

@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.
  • 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.
BoundaryDescription
Inputsstring or Uint8Array (source bytes) + ParseOptions (language, filename, mimeType, detect, onUnknown, grammarOptions, convenience keys)
OutputsLexTree
Side effectsregister() mutates grammarRegistry. grammarRegistry is a shared global.
DeterminismYes (same input + same registrations produce same tree)
External dependencies@lanexio/parser-core, @lanexio/parser-wasm (imported lazily by createParser for WASM grammars)
Never-throw guaranteeYes 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 surfaceNone
  1. Install the package.

    Terminal window
    pnpm add @lanexio/parser
  2. Import the named export.

    import { parse, createParser, register } from '@lanexio/parser';
RequirementRequiredLayerNotes
@lanexio/parser-coreYes1^1.0.0
@lanexio/parser-wasmYes4WASM bridge; imported lazily by createParser only for WASM grammars
Grammar packagesNo2Installed separately and registered before use
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);
// 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.

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.

ExportTypeDescription
parse(source: string | Uint8Array, options?: ParseOptions) => LexTreeUnified 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) => voidRegister a grammar in the unified registry.
detectLanguage(source: string | Uint8Array, hints?: DetectionHints) => DetectionResultAuto-detect the grammar language from source bytes and hints.
normalizeLanguage(name: string) => stringNormalize a language name or alias to its canonical form.
actionableError(code: string, context: Readonly<Record<string, string>>) => stringBuild a human-readable, actionable message for an error code.
KNOWN_GRAMMARSreadonly KnownGrammarEntry[]Metadata for grammars the registry knows by name.
LANEXIO_PARSER_PACKAGE_NAME"@lanexio/parser"Stable npm package name constant.
grammarRegistryGrammarRegistryShared global registry (re-exported from parser-core).
LanexioParserErrorclassThrown by createParser at construction time (grammar_load_failed, protocol_mismatch). Carries code and optional cause.
LanexioParserErrorCodeconst object{ GrammarLoadFailed, ProtocolMismatch } construction error codes.
LanexioParseErrorclassThrown 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.

FieldTypeRequiredDefaultDescription
languagestringNoundefinedLanguage name or alias for grammar lookup (e.g., "html", "markdown", "tsql").
filenamestringNoundefinedFilename for extension-based detection (e.g., "config.json5").
mimeTypestringNoundefinedMIME type for MIME-based detection (e.g., "application/json").
detectbooleanNoenabled only when no explicit hint resolvesContent sniffing on the source bytes.
onUnknown"error" | "throw" | stringNo"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.
grammarOptionsRecord<string, unknown>NoundefinedGrammar/dialect pass-through options bag forwarded to the resolved grammar.
dialectstringNoundefinedGrammar pass-through convenience key for the SQL grammar dialect (e.g., "postgres", "tsql"). Merged into grammarOptions.dialect when not already set.
strictbooleanNoundefinedGrammar pass-through convenience key for the strict-mode parsers (CSV/TSV, XML, TOML). Merged into grammarOptions.strict when not already set.
validatebooleanNoundefinedGrammar pass-through convenience key for XML DTD validation. Merged into grammarOptions.validate when not already set.
clientBatch"accept" | "reject" | "split"NoundefinedGrammar 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"NoundefinedGrammar 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.

PropertyTypeDescription
rootLexNodeRoot node of the parsed tree.
nodeCountnumberTotal nodes in the tree.
sourceUint8ArrayOriginal parsed bytes.
TypePurposeNotes
ParseOptionsOptions for parse(){ language?, filename?, mimeType?, detect?, onUnknown?, grammarOptions?, dialect?, strict?, validate?, clientBatch?, spec? }
GrammarParseOptionsGrammar-facing option subsetForwarded into grammarOptions during resolution
LanexioParserParser handle returned by createParser{ grammar: string; protocolVersion: number; parse(input: string | Uint8Array): LexTree; reparse(previousTree, edit): LexTree; createStream(): LexParseStream }
DetectionResultResult of language detection{ language, confidence, candidates? }
DetectionHintsHints for language detection{ language?, filename?, mimeType?, detect? }
DetectionResultResult of language detectionLanguage and confidence
DetectionHintsHints for language detectionExtension, MIME type
KnownGrammarEntryEntry in KNOWN_GRAMMARSGrammar metadata
LexRangeByte rangeRe-export from parser-core
LanexioParserPureGrammarGrammar descriptorRe-export from parser-core
LexParseStreamStreaming parse interfaceRe-export from parser-core
GrammarRegistrationGrammar registrationRe-export from parser-core
LexEditEdit descriptorRe-export from parser-core

Register grammars before calling parse(). The registry supports lookup by language name, file extension, and MIME type.

KNOWN_GRAMMARS lists the pre-registered grammar metadata. This is a read-only list for reference.

  • No direct accessibility surface. The main entry point dispatches to grammar-specific parsers. Consuming code is responsible for semantic rendering.
ConcernStatus
Generated output semanticsNot applicable (dispatch layer)
ARIA attributes in serialized outputNot applicable
Semantic element round-tripNot applicable
  • The unified parse() function relies on auto-detection but never trusts input: malformed bytes produce an error LexTree, and unresolved detection returns an error tree by default.
  • parse(), the handle methods, and the stream methods never throw on input. LanexioParseError is raised only when the caller opts in via onUnknown: "throw", and LanexioParserError is a construction-time signal from createParser, not a parse-path failure.
  • Detection hints (language, filename, mimeType) and any onUnknown fallback string are treated as registry keys, never as code or file paths.
ThreatMitigationStatus
Malformed input byte sequenceAll parse paths are never-throw; malformed input yields LexError nodes in the returned treeImplemented
Unresolved language detectionDefault onUnknown: "error" returns an error LexTree with an actionable message; only onUnknown: "throw" raises LanexioParseErrorImplemented
PackageRelationshipLayerNotes
@lanexio/parser-coreRequires1Core tree and protocol. Re-exported.
@lanexio/parser-grammar-htmlDev dependency2Optional grammar.
@lanexio/parser-grammar-markdownDev dependency2Optional grammar.
@lanexio/parser-wasmRequires4WASM bridge support.
VersionDateStatusNotable changes
1.0.02026-05-29CurrentInitial stable release. Apache-2.0.
  • None.