Skip to content

@lanexio/parser-core

This page documents @lanexio/parser-core, the foundational package that defines the shared buffer protocol, tree data structures, and parser host for all Lanexio Parser packages.

  • Version: Stable
  • Module name: parser-core
  • Package: @lanexio/parser-core
  • Import path: @lanexio/parser-core
  • Layer: 1 (Core)
  • Runtime: Universal (browser, server, edge worker, test runner)
  • Module format: ESM
  • Stability: Stable
  • Primary use case: Build and traverse zero-copy flat ASTs, register grammars, use core primitives.
  • You need to create, traverse, or modify a LexTree directly.
  • You want to use the grammar registry to manage multiple grammars.
  • You need to build a custom grammar or parser integration.
  • You need the incremental editing API (applyEdit, reparse) or streaming parse (createParseStream).
  • You want the shared buffer protocol constants for value-level interop.
BoundaryDescription
InputsUint8Array (source bytes for parse), or preconstructed buffers for tree manipulation
OutputsLexTree, LexNode, LexCursor, LexEdit results
Side effectsNone
DeterminismYes (same bytes and same protocol version produce same tree)
External dependenciesNone
Never-throw guaranteeYes for parse()
Security surfaceNone (no HTML output, no I/O)
  1. Install the package.

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

    import { parse, LexTree, LexNode, LexCursor } from '@lanexio/parser-core';

This package has no peer dependencies. It is the foundation that all other packages depend on.

import { parse, LexNode, LexCursor, LexTree } from '@lanexio/parser-core';
const encoder = new TextEncoder();
const bytes = encoder.encode('toy input');
const tree: LexTree = parse(bytes);
console.log(tree.nodeCount);
console.log(tree.root);
const tree = parse(encoder.encode('example'));
const cursor = tree.cursor();
do {
const node = cursor.current;
console.log('kind:', node.kind, 'range:', node.range);
} while (cursor.gotoFirstChild() || cursor.gotoNextSibling() || cursor.gotoParent());
ExportTypeDescription
parse(source: Uint8Array) => LexTreeParse toy-grammar bytes into a flat AST. Never throws.
LexTreeclassRoot handle for a zero-copy flat AST backed by a single ArrayBuffer.
LexNodeclassReference to a single 16-byte node within a LexTree.
LexCursorclassPreorder DFS cursor over a LexTree, backed by a node index stack.
PROTOCOL_VERSIONnumberCurrent shared buffer protocol version (value: 3).
LEX_TREE_MAGICnumberMagic number identifying a valid tree header.
LEX_TREE_VERSIONnumberCurrent tree layout version.
createLexErrorTree(source: Uint8Array) => LexTreeCreate a tree with a single root LexError node.
applyEdit(tree: LexTree, edit: LexEdit) => LexTreeApply a structural edit to a tree.
reparse(tree: LexTree, options?: ReparseOptions) => LexTreeIncrementally reparse after edits.
reparseWithStats(tree: LexTree, options?: ReparseOptions) => { tree: LexTree; stats: ReparseStats }Reparse and return performance statistics.
computeDirtyRegion(tree: LexTree, edit: LexEdit) => DirtyRegionCompute the byte range affected by an edit.
createParseStream() => LexParseStreamCreate a streaming push parser for chunked input.
grammarRegistryobjectGlobal registry for grammar registrations.
embedGuests(tree: LexTree, options: EmbedGuestsOptions) => LexTreeEmbed guest-language subtrees into host tree.
embedRegistryobjectRegistry for guest-language embeddings.
graftSubtree(target: LexTree, source: LexTree, targetIndex: number) => LexTreeGraft a source tree onto a target tree.
findParentIndex(tree: LexTree, childIndex: number) => numberFind the parent node index of a child.
fixSubtreeSizes(tree: LexTree) => LexTreeRecompute subtree sizes after manual edits.
rebaseRecords(records: Uint32Array, delta: number) => Uint32ArrayOffset all byte ranges in a node record array.
assertLossless(tree: LexTree) => voidAssert that the tree preserves all source bytes.
emitSource(tree: LexTree) => Uint8ArrayReconstruct the source bytes from the tree.
extractLeafRanges(tree: LexTree) => LeafRange[]Extract leaf-level source byte ranges.
countFalseHasError(tree: LexTree) => numberCount nodes with false-positive error flags.
countInvertedRanges(tree: LexTree) => numberCount nodes with start > end ranges.
assertWellFormed(tree: LexTree) => voidAssert all structural invariants hold.
LexEditErrorclassError thrown on invalid edits.
LexEditErrorCodeconst objectError code constants for edit failures.
LosslessErrorclassError thrown when lossless integrity check fails.
NODE_STRIDEnumberStride (in Uint32 slots) per node record.
SLOT_KINDnumberSlot index for node kind.
SLOT_FLAGSnumberSlot index for node flags.
SLOT_FIELDnumberSlot index for node field id.
SLOT_STARTnumberSlot index for byte range start.
SLOT_ENDnumberSlot index for byte range end.
SLOT_SIZEnumberSlot index for subtree size.
createTree(records: Uint32Array, source: Uint8Array) => LexTreeCreate a tree from raw node records.
createTreeFromUint32Array(records: Uint32Array, source: Uint8Array) => LexTreeCreate a tree from a Uint32Array buffer.
growNodeData(nd: Uint32Array, needed: number) => Uint32ArrayGrow the node data buffer.
writeTreeHeader(records: Uint32Array, nodeCount: number, sourceLength: number) => Uint32ArrayWrite the tree header into a record buffer.
createPendingNode() => PendingNodeCreate a pending node for tree construction.
LANEXIO_PARSER_CORE_PACKAGE_NAMEstringStable npm package name constant.
LexToyKindconst objectKind constants for the built-in toy grammar.
LexToyFieldconst objectField constants for the built-in toy grammar.

The core module accepts options through LexTreeOptions when constructing trees programmatically.

FieldTypeRequiredDefaultDescription
nodeCountnumberYes-Number of nodes in the tree.
sourceLengthnumberYes-Length of the source buffer in bytes.

The primary return value from parse() is LexTree:

PropertyTypeDescription
rootLexNodeRoot node of the flat AST.
nodeCountnumberTotal nodes in the tree.
sourceUint8ArrayOriginal parsed bytes.
cursor()() => LexCursorCreate a new preorder DFS cursor starting at root.
TypePurposeNotes
LexTreeOptionsOptions for programmatic tree constructionUsed by createTree
LexTreeMetadataMetadata stored in the tree headerInternal use
LexRange{ start: number; end: number } byte offset rangeUsed across all grammar APIs
LexEditStructural edit descriptorPassed to applyEdit
DirtyRegionByte range affected by an editReturned by computeDirtyRegion
ReparseOptionsOptions for incremental reparsePassed to reparse
ReparseStatsPerformance statistics from reparseReturned by reparseWithStats
ReuseOracleOracle for incremental node reuseUsed by grammar incremental modules
LexParseStreamStreaming push parser interfaceCreated by createParseStream
LexTreeValidationCodeValidation result codeProduced by integrity checks
LexTreeValidationErrorError from tree validationThrown on invalid tree structure
LeafRangeLeaf-level source rangeUsed by extractLeafRanges
LosslessDiagnosticsDiagnostic info from lossless checkReturned by lossless operations
PendingNodeNode pending insertionUsed during tree construction
LanexioParserPureGrammarPure-TS grammar descriptor interfaceUsed by grammar packages to register themselves
GrammarRegistrationFull grammar registration descriptorUsed with grammarRegistry
EmbedGuestsOptionsOptions for guest embeddingPassed to embedGuests
EmbedRuleGuest embedding ruleUsed in embed registry

The grammarRegistry manages grammar registrations globally. Register a grammar to make it available for auto-detection and unified parsing.

import { grammarRegistry } from '@lanexio/parser-core';
import { htmlRegistration } from '@lanexio/parser-grammar-html';
grammarRegistry.register(htmlRegistration);

embedGuests inserts guest-language subtrees (for example, a CSS block inside an HTML style element) into a host tree. The embedRegistry stores the embedding rules.

createParseStream creates a LexParseStream that accepts chunked input via push() and finalizes with end():

import { createParseStream } from '@lanexio/parser-core';
const stream = createParseStream();
stream.push(encoder.encode('chunk1 '));
stream.push(encoder.encode('chunk2'));
const tree = stream.end();
  • No direct accessibility surface. The core module produces flat AST data structures. Consuming code is responsible for rendering output with appropriate semantics.
ConcernStatus
Generated output semanticsNot applicable (core data structures only)
ARIA attributes in serialized outputNot applicable
Semantic element round-tripNot applicable
  • No direct security surface. The core module provides data structures and parsing infrastructure. All parse functions carry the never-throw guarantee.
  • The toy grammar (parse()) is not intended for untrusted input validation — it is a minimal reference implementation.
ThreatMitigationStatus
Malformed input byte sequencePanic-free guarantee: all inputs accepted, errors produce LexError AST nodesImplemented
PackageRelationshipLayerNotes
@lanexio/parser-grammar-htmlConsumes2HTML grammar built on core primitives
@lanexio/parser-grammar-markdownConsumes2Markdown grammar built on core primitives
@lanexio/parser-grammar-jsonConsumes2JSON grammar built on core primitives
@lanexio/parser-queryConsumes3Query engine operates on core LexTree
@lanexio/parserRe-exports6Entry point re-exporting core API
VersionDateStatusNotable changes
1.0.02026-05-29CurrentInitial stable release. Apache-2.0.
  • None. This is the initial stable release.