@tinyactors/sxml 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,3 +1,492 @@
1
- # Temporary Holding Version
1
+ # @tinyactors/sxml
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ sxml for JavaScript, in Node.js and browsers. It is the sxml C library
4
+ compiled to WebAssembly, with a small TypeScript wrapper and no runtime
5
+ dependencies. It is one module, `sxml.wasm` (7.7 MB, 1.7 MB gzipped),
6
+ with everything sxml has: XML parsing, XPath 4.0 with the F&O 4.0 function
7
+ library, XQuery 4.0 with the Update Facility 3.0, XQuery and XPath Full
8
+ Text 3.0, XSLT 4.0, XSD 1.1 validation, Serialization 4.0, and every
9
+ optional feature except EXPath File, which reads files.
10
+
11
+ ```js
12
+ import { load } from '@tinyactors/sxml';
13
+
14
+ const sxml = await load();
15
+ const processor = sxml.createProcessor();
16
+
17
+ const book = processor.parse('<book><title>XPath</title><year>2026</year></book>');
18
+ const result = processor.evaluate('//title/string(), xs:integer(//year) + $n', {
19
+ context: book,
20
+ variables: { n: 1 },
21
+ });
22
+ result.toString(); // '"XPath"\n2.027e3', the adaptive method
23
+ ```
24
+
25
+ - [Loading](#loading)
26
+ - [Optional features](#optional-features)
27
+ - [Processors and values](#processors-and-values)
28
+ - [Output](#output)
29
+ - [XQuery](#xquery)
30
+ - [XSLT](#xslt)
31
+ - [XSD validation](#xsd-validation)
32
+ - [Code languages](#code-languages)
33
+ - [Resources](#resources)
34
+ - [Errors](#errors)
35
+ - [Memory](#memory)
36
+ - [API summary](#api-summary)
37
+ - [Development](#development)
38
+
39
+ ## Loading
40
+
41
+ `load()` loads `sxml.wasm`, next to the package's JavaScript. To load it
42
+ from elsewhere, pass `load({ wasm })` with a URL, a path, the bytes, a
43
+ `WebAssembly.Module` or a `fetch()` response:
44
+
45
+ ```js
46
+ const sxml = await load({ wasm: await fetch('/assets/sxml.wasm') });
47
+ ```
48
+
49
+ The package exports the module as `@tinyactors/sxml/sxml.wasm`;
50
+ `@tinyactors/sxml/sxml-full.wasm`, the name of the full module of earlier
51
+ builds, is the same file.
52
+
53
+ One loaded module serves any number of processors. `sxml.version` is the
54
+ library's version (`'0.2.0'`).
55
+
56
+ ## Optional features
57
+
58
+ Some parts of sxml are optional features: large tables and functions that
59
+ a processor may go without. The module has every one except EXPath File,
60
+ which reads files. `sxml.features` lists them, and `createProcessor({
61
+ features })` picks some of them (by default all). Without a feature, sxml behaves
62
+ as the specifications say a processor without it does: its functions do
63
+ not exist (`err:XPST0017`), or the specification's fallback applies.
64
+
65
+ | Feature | What it adds |
66
+ | --- | --- |
67
+ | `html` | `fn:parse-html` and `fn:html-doc`: HTML parsed as the HTML Living Standard says, in every encoding of the Encoding Standard |
68
+ | `invisible-xml` | `fn:invisible-xml`: Invisible XML grammars that turn text into XML |
69
+ | `xslt-transform` | `fn:transform`: run an XSLT stylesheet from XPath or XQuery |
70
+ | `expath-binary` | The EXPath Binary 4.0 functions, namespace `http://expath.org/ns/binary`, bound to the prefix `bin` |
71
+ | `full-text` | XQuery and XPath Full Text 3.0: `contains text` and score variables in XPath and XQuery, with stemming, stop words and thesauri |
72
+ | `dtd-validation` | The `dtd-validation` option of `fn:doc` and `fn:parse-xml` |
73
+ | `builtin-schemas` | The schemas that `fn:json-to-xml` with `validate`, the typed results of `fn:analyze-string`, and lax validation without an in-scope schema use |
74
+ | `source-code` | `sxml:parse-code` and `sxml:code-languages` (namespace `urn:sxml`): source code in JSON, JavaScript, TypeScript, TSX, Python, C, CSS, HTML, Go or Markdown as a document of its syntax tree, with highlights and code inside code, and any other tree-sitter language from its WebAssembly file (see [Code languages](#code-languages)) |
75
+ | `uca-collation` | UCA collation URIs (Unicode Collation Algorithm 16.0) over the DUCET, which the package ships; the CLDR root collation and the CLDR tailorings by language when the resolver gives their files (resource kind `'collation-data'`) |
76
+ | `timezone-database` | IANA time zone names in `fn:civil-timezone` and in the `$place` argument of `fn:format-dateTime` (resource kind `'timezone-data'`) |
77
+ | `localization` | Month and day names, calendars and number words in other languages in `fn:format-date`, `fn:format-integer` and `xsl:number` (resource kind `'locale-data'`) |
78
+ | `test` | Nothing: tests use it to check that a feature list reaches the processor |
79
+
80
+ `uca-collation`, `timezone-database` and `localization` read their
81
+ tables through the resolver (see [Resources](#resources)) when they are
82
+ first used. Without the tables they behave as a processor without the
83
+ feature does.
84
+
85
+ ## Processors and values
86
+
87
+ A processor holds names, types and values. Every value and expression
88
+ belongs to the processor that made it.
89
+
90
+ - `processor.parse(xml, { uri })` parses a document (a string, or bytes in
91
+ any encoding the document declares) and returns its document node.
92
+ - `processor.compile(expression, { variables, namespaces, baseUri })`
93
+ compiles an XPath 4.0 expression once. Its `evaluate({ context,
94
+ variables })` can run many times.
95
+ - `processor.evaluate(expression, options)` compiles and evaluates once.
96
+ - `processor.value(data)` converts JavaScript data to a value.
97
+
98
+ Variable names are NCNames or `Q{uri}local`. A value to bind is either a
99
+ value from this processor or JavaScript data. A string becomes an
100
+ `xs:string`. Other data becomes what `fn:parse-json` makes of its JSON:
101
+ objects are maps, arrays are arrays, numbers are `xs:double`, and `null` is
102
+ the empty sequence.
103
+
104
+ `namespaces` binds prefixes for the expression, besides the predeclared
105
+ ones (`xs`, `fn`, `map`, `array`, `math`, `err`, ...). A processor with
106
+ the `expath-binary` feature also binds `bin`, as the `sxml` command does;
107
+ `namespaces` may rebind it:
108
+
109
+ ```js
110
+ processor.evaluate('bin:hex("CAFE") => bin:to-octets()').toString(); // '202\n254'
111
+ processor.evaluate('//p:item', { context: document, namespaces: { p: 'urn:p' } });
112
+ ```
113
+
114
+ ## Output
115
+
116
+ `value.toString()` writes the value by the adaptive method of Serialization
117
+ 4.0. `value.serialize(options)` takes the parameters of `fn:serialize`, and
118
+ keys may be in camelCase:
119
+
120
+ ```js
121
+ book.serialize({ method: 'xml', indent: true, omitXmlDeclaration: false });
122
+ processor.evaluate('map { "a": [1, 2] }').serialize({ method: 'json' }); // '{"a":[1,2]}'
123
+ ```
124
+
125
+ ## Streaming
126
+
127
+ The methods that return a string hold the whole output twice: in the
128
+ module's memory, which grows to fit it and never shrinks, and as the
129
+ string. For large outputs, write to a sink instead (D294):
130
+
131
+ | Method | Writes |
132
+ | --- | --- |
133
+ | `value.serializeTo(sink, options)`, `processor.serializeTo(value, sink, options)` | What `serialize(options)` returns |
134
+ | `query.runTo(sink, options)`, `query.serializeTo(value, sink)` | What `run` and `serialize` return |
135
+ | `transform({ output: sink })` | The principal result, with delivery `'serialized'`; `output` is then undefined |
136
+ | `transform({ resultDocumentOutput: (uri) => sink })` | Each serialized `xsl:result-document`; `undefined` gathers it in `resultDocuments` as before |
137
+ | `putDocument.serializeTo(sink)` | What `putDocument.serialize()` returns |
138
+
139
+ A sink is a function `(chunk: Uint8Array) => void`, or an object with
140
+ `write(chunk)` and, optionally, `close()` (after the output is complete)
141
+ and `abort(reason)` (when the call fails, or a result document is
142
+ abandoned). The chunks are 64 KiB by default; set
143
+ `createProcessor({ outputChunkByteCount })` to change that. Each chunk is
144
+ the sink's own copy, and the buffer in the module is reused for the next
145
+ one. A sink must not use the processor. If a sink throws, the call stops
146
+ and rethrows the same exception.
147
+
148
+ ```js
149
+ import { writeSync } from 'node:fs';
150
+ query.runTo((chunk) => writeSync(fd, chunk));
151
+ ```
152
+
153
+ Chunks are cut at byte counts, not at characters. `textSink(onText)`
154
+ decodes UTF-8 with `TextDecoder` in stream mode, so a character whose
155
+ bytes two chunks share is given to `onText` once both have arrived. Use
156
+ it, or your own streaming decoder, rather than decoding each chunk alone.
157
+
158
+ **Backpressure.** An evaluation runs synchronously inside WebAssembly,
159
+ so a sink is called during the call and cannot make the evaluation wait.
160
+ A sink that consumes each chunk at once keeps memory bounded by one
161
+ chunk: `fs.writeSync`, a hash, a decoder feeding a parser, or
162
+ `postMessage` from a worker to a thread that reads concurrently. The
163
+ adapters `writableStreamSink(writableStream)` (await its `done`),
164
+ `nodeStreamSink(writable)` and `outputReadableStream((sink) => ...)`
165
+ queue the chunks in JavaScript memory until the call returns and the
166
+ event loop drains them. They still save the copy in the module's memory
167
+ and the string.
168
+
169
+ **Input.** A resolver may answer `'xml-document'` with a `ChunkSource`:
170
+ an iterable of `Uint8Array` or string chunks, such as a generator that
171
+ reads a file with `fs.readSync`. sxml reads it as it parses, and closes
172
+ it (`return()`) when done. A document that XSLT streams is never whole in
173
+ memory: `xsl:source-document streamable="yes"`, or the principal source
174
+ that `transform({ streamedSource: uri })` names, when the initial mode is
175
+ streamable. `fn:doc` and other uses read the chunks whole into the
176
+ module, but not into JavaScript. For the other kinds, the package joins
177
+ the chunks first. `Processor.parse` takes the whole text: the C API has
178
+ no public incremental parse (D233), so for a large document, evaluate
179
+ `doc($uri)` with a chunk source.
180
+
181
+ Measured with Node.js 22, for output of 108.7 MB (1.8 million elements;
182
+ module memory, peak JavaScript heap):
183
+
184
+ | Case | String API | Sink |
185
+ | --- | --- | --- |
186
+ | `value.serialize` / `serializeTo` (tree of 1.8 M elements) | 749 MB, 113 MB | 481 MB, 4 MB |
187
+ | `query.run` / `runTo` | 749 MB, 113 MB | 481 MB, 4 MB |
188
+ | `transform` from a template | 749 MB, 113 MB | 481 MB, 4 MB |
189
+ | `transform` with `streamedSource` (95 MB source) | 387 MB, 113 MB (source as a string) | 11 MB, 15 MB (chunk source) |
190
+
191
+ ## XQuery
192
+
193
+ `processor.compileQuery(text, { namespaces, baseUri })` compiles an XQuery
194
+ 4.0 main module once. Its `evaluate({ context, variables, updates,
195
+ messages })` returns a value, `serialize(value)` serializes a value with
196
+ the serialization parameters of the query's output declarations, and
197
+ `run(options)` does both. The variables are the external variables of the
198
+ prolog. A library module that the query imports is read through the
199
+ resolver, with kind `'xquery-module'`.
200
+
201
+ ```js
202
+ const sxml = await load();
203
+ const processor = sxml.createProcessor();
204
+
205
+ const books = processor.parse(`<books>
206
+ <book year="1999"><title>XSLT</title></book>
207
+ <book year="2026"><title>XQuery 4.0</title></book>
208
+ </books>`);
209
+ const query = processor.compileQuery(`
210
+ declare option output:method "json";
211
+ declare variable $min external := 0;
212
+ array { //book[@year >= $min] ! map { "title": string(title), "year": xs:integer(@year) } }`);
213
+ query.run({ context: books, variables: { min: 2000 } });
214
+ // '[{"title":"XQuery 4.0","year":2026}]'
215
+ ```
216
+
217
+ Full Text searches text with `contains text`:
218
+
219
+ ```js
220
+ processor.compileQuery('"Parsing large files" contains text "parse" using stemming').run();
221
+ // 'true'
222
+ ```
223
+
224
+ An updating query (the XQuery Update Facility 3.0) returns the empty
225
+ sequence, and `query.isUpdating` is `true`. sxml never changes a tree:
226
+ each tree that the query changes is built again as a new tree, and it
227
+ goes to `updates.updatedTree` with the original root. The documents that
228
+ `fn:put` stores go to `updates.putDocument`, with their URI and a
229
+ `serialize()`. Without a `putDocument`, `fn:put` raises `FOUP0002`.
230
+
231
+ ```js
232
+ const update = processor.compileQuery('insert node <book year="2027"><title>Next</title></book> into /books');
233
+ update.evaluate({
234
+ context: books,
235
+ updates: {
236
+ updatedTree: ({ original, updated }) => {
237
+ console.log(processor.evaluate('count(//book)', { context: updated }).toString());
238
+ // 3: the new tree; original, the books document, still has 2
239
+ },
240
+ },
241
+ });
242
+ ```
243
+
244
+ `fn:trace` and `fn:message` output goes to `messages`, a function that
245
+ receives each message after the evaluation, also when the evaluation
246
+ failed.
247
+
248
+ ## XSLT
249
+
250
+ `processor.compileStylesheet(text, { baseUri, staticParameters })` compiles
251
+ an XSLT 4.0 stylesheet once. The modules it includes and imports are read
252
+ through the resolver, with kind `'xslt-module'`, and the packages it uses
253
+ with kind `'xslt-package'`. Its `transform(options)` returns `{ output,
254
+ value, resultDocuments }`:
255
+
256
+ - `source` is the global context item. Templates are applied to it, in
257
+ `initialMode` (`'#unnamed'` selects the unnamed mode) or in the default
258
+ mode. To apply templates to something else, give `initialMatchSelection`.
259
+ - `initialTemplate` calls a named template instead. Without a source,
260
+ `xsl:initial-template` is called. `initialFunction` with `args` calls a
261
+ public stylesheet function.
262
+ - `parameters`, `templateParameters` and `tunnelParameters` bind the
263
+ parameters by name.
264
+ - `delivery` says how the principal result is delivered. With
265
+ `'serialized'` (the default), `output` is the result as the unnamed
266
+ `xsl:output` serializes it. With `'raw'`, `value` is the result as the
267
+ stylesheet made it, and with `'tree'` it is one document node.
268
+ `serialization` replaces the parameters of the `xsl:output`.
269
+ - `resultDocuments` has each `xsl:result-document`, with its URI resolved
270
+ against `baseOutputUri`. `resultDocumentDelivery` says how they are
271
+ delivered, in the same way as `delivery`.
272
+ - `messages` receives the `xsl:message` and `xsl:assert` output.
273
+ - `output` and `resultDocumentOutput` write the serialized results to
274
+ sinks a chunk at a time, and `streamedSource` names a principal source
275
+ to stream (see Streaming).
276
+
277
+ ```js
278
+ const stylesheet = processor.compileStylesheet(`
279
+ <xsl:stylesheet version="3.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
280
+ <xsl:output method="html" html-version="5"/>
281
+ <xsl:param name="heading" select="'Books'"/>
282
+ <xsl:template match="/books">
283
+ <h1><xsl:value-of select="$heading"/></h1>
284
+ <xsl:for-each select="book">
285
+ <xsl:result-document href="book{position()}.txt" method="text">
286
+ <xsl:value-of select="title"/>
287
+ </xsl:result-document>
288
+ </xsl:for-each>
289
+ </xsl:template>
290
+ </xsl:stylesheet>`);
291
+ const result = stylesheet.transform({
292
+ source: books,
293
+ parameters: { heading: 'Library' },
294
+ baseOutputUri: 'https://example.com/out/',
295
+ });
296
+ result.output; // '<h1>Library</h1>'
297
+ result.resultDocuments.map(({ uri, output }) => `${uri}: ${output}`);
298
+ // ['https://example.com/out/book1.txt: XSLT', 'https://example.com/out/book2.txt: XQuery 4.0']
299
+ ```
300
+
301
+ A stylesheet with `version="1.0"` runs with XSLT 1.0 behaviour, and
302
+ `exsl:node-set`, `exsl:object-type` and `exsl:document` of EXSLT Common
303
+ are available.
304
+
305
+ ## XSD validation
306
+
307
+ `processor.compileSchema(documents, { baseUri })` compiles an XSD 1.1 schema
308
+ from one or more schema documents. A document is its text, or `{ text,
309
+ uri }`, or `{ uri }` alone, which the resolver is asked for. The documents
310
+ that a schema document includes or imports are read through the resolver,
311
+ with kind `'schema-document'`. If the schema has errors, a `SchemaError` is
312
+ thrown, and its `reports` has every error.
313
+
314
+ `schema.validate(input, { mode, type, uri })` validates XML text, or a
315
+ document or element node. Text is parsed and validated in one pass, so
316
+ each report has a line and a column. The result is `{ validity, reports,
317
+ document }`. `validity` is `'valid'`, `'invalid'` or `'not-known'` (lax
318
+ validation of an element that has no declaration). An invalid document is
319
+ a result, not an exception. Unless the document is invalid, `document` is
320
+ the validated copy, and its elements and attributes have the types of the
321
+ schema. `type` validates the root against a named type of the schema.
322
+
323
+ ```js
324
+ const schema = processor.compileSchema(`
325
+ <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
326
+ <xs:element name="book">
327
+ <xs:complexType>
328
+ <xs:sequence><xs:element name="title" type="xs:string"/></xs:sequence>
329
+ <xs:attribute name="year" type="xs:gYear" use="required"/>
330
+ </xs:complexType>
331
+ </xs:element>
332
+ </xs:schema>`);
333
+ const report = schema.validate('<book year="soon">\n <author/>\n</book>', { uri: 'book.xml' });
334
+ report.validity; // 'invalid'
335
+ report.reports.map(({ lineNumber, columnNumber, code }) => `${lineNumber}:${columnNumber} ${code}`);
336
+ // ['1:7 cvc-datatype-valid.1.2.1', '2:3 cvc-complex-type.2.4']
337
+
338
+ const valid = schema.validate('<book year="2026"><title>XQuery 4.0</title></book>');
339
+ processor.evaluate('/book/@year instance of attribute(*, xs:gYear)', { context: valid.document }).toString();
340
+ // 'true()'
341
+ ```
342
+
343
+ ## Code languages
344
+
345
+ `sxml:parse-code` (the `source-code` feature; the prefix `sxml` is bound
346
+ to `urn:sxml`) parses a dozen languages built in. Any other tree-sitter
347
+ grammar can be loaded from its WebAssembly language file,
348
+ `tree-sitter-NAME.wasm`, as `tree-sitter build --wasm` writes it (many
349
+ grammar repositories ship it with their releases), together with the
350
+ texts of its queries:
351
+
352
+ ```js
353
+ const rust = await sxml.loadCodeLanguage({
354
+ wasm: await fetch('/grammars/tree-sitter-rust.wasm'),
355
+ highlights: await (await fetch('/grammars/rust/highlights.scm')).text(),
356
+ // locals, injections and injectionRegex are optional, as is name
357
+ });
358
+ rust.name; // 'rust', from the file's tree_sitter_rust()
359
+ const processor = sxml.createProcessor({ codeLanguages: [rust] });
360
+ processor.evaluate('sxml:parse-code("fn main() {}", "rust")//function_item/identifier ! string()');
361
+ ```
362
+
363
+ `loadCodeLanguage` links the file into the running `sxml.wasm`: the
364
+ file is a WebAssembly side module (its `dylink.0` section), which shares
365
+ the module's memory, function table, stack and C library, so sxml's
366
+ tree-sitter runs its lexer and external scanner directly. It then checks
367
+ the grammar's ABI (13 to 15, tree-sitter 0.20 and later) and that each
368
+ query fits the grammar, and rejects with an `Error` that says what is
369
+ wrong: a file without `dylink.0`, one that needs other WebAssembly
370
+ libraries, one whose scanner imports a C function outside tree-sitter's
371
+ list for language files (`malloc`, `calloc`, `realloc`, `free`, the
372
+ `mem*` and `str*` functions, `isw*`, `towlower`, `towupper`; `abort` and
373
+ `__assert_fail` trap), another ABI, a query that does not fit (with its
374
+ byte offset), or a bad name. A loaded language stays in memory as long
375
+ as its `Sxml` and can be given to any number of its processors; one with
376
+ the name of a built-in language replaces it there.
377
+
378
+ ## Resources
379
+
380
+ `fn:doc`, `fn:unparsed-text` and the other resource functions ask the
381
+ processor's resolver. The resolver gets `{ kind, uriReference,
382
+ absoluteUri }` and returns a string, bytes, or `undefined` when the
383
+ resource is not available. Nothing else is read.
384
+
385
+ ```js
386
+ const processor = sxml.createProcessor({
387
+ resolver: ({ kind, absoluteUri }) => files.get(absoluteUri),
388
+ });
389
+ processor.evaluate('doc("data.xml")//item', { baseUri: 'https://example.com/' });
390
+ ```
391
+
392
+ The kinds are `'xml-document'`, `'text'`, `'binary'`, `'collection'`,
393
+ `'uri-collection'`, `'external-entity'`, `'xquery-module'`,
394
+ `'xslt-module'`, `'xslt-package'` and `'schema-document'`, and three for
395
+ the tables of the optional features:
396
+
397
+ - `'timezone-data'`: a file of the IANA Time Zone Database. `absoluteUri`
398
+ is `urn:sxml:timezone-data:` followed by a zoneinfo path, such as
399
+ `Europe/Paris` (a TZif file) or `zone1970.tab`. Answer with the file's
400
+ bytes.
401
+ - `'collation-data'`: the collation table. Answer with the text of the
402
+ file that `absoluteUri` names, or `undefined`. When the resolver has no
403
+ answer, the package uses the DUCET (`allkeys.txt` of the Unicode
404
+ Collation Algorithm 16.0.0) that it ships next to the modules; to load
405
+ it from elsewhere, pass `load({ collationData })` with a URL, a path or
406
+ the bytes, or `false` for none.
407
+ - `'locale-data'`: a file of the Unicode CLDR. `absoluteUri` is
408
+ `urn:sxml:locale-data:` followed by a path below CLDR's `common/`
409
+ directory, such as `main/de.xml` or `supplemental/supplementalData.xml`.
410
+ Answer with the file's bytes. Without it, dates are formatted in
411
+ English after `[Language: en]`.
412
+
413
+ The resolver is called synchronously during an evaluation. If it throws,
414
+ the evaluation stops and the same exception is rethrown. For a large XML
415
+ document, it may answer with an iterable of chunks (see Streaming).
416
+
417
+ ## Errors
418
+
419
+ Failures throw an `SxmlError`. Its fields are `status`, for example
420
+ `'DYNAMIC_ERROR'`, and `code`, for example `'err:FOAR0001'`, also as
421
+ `codeNamespaceUri` and `codeLocalName`. It also has `description`,
422
+ `sourceName` (`'expression'`, `'query'`, or the URI of a module or
423
+ stylesheet), `lineNumber` and `columnNumber`.
424
+
425
+ ```js
426
+ try {
427
+ processor.evaluate('1 div 0');
428
+ } catch (error) {
429
+ error.code; // 'err:FOAR0001'
430
+ }
431
+ ```
432
+
433
+ ## The step limit
434
+
435
+ An evaluation stops with an error after a hundred million evaluation
436
+ steps, a few seconds of work, so a query or stylesheet that would loop
437
+ for hours does not hang the page or the server. Set
438
+ `createProcessor({ maximumEvaluationStepCount })` to a whole number to
439
+ raise or lower it (the C processor limit of the same name; 0 is the
440
+ default). A streamed document grants 500 steps more for each element it
441
+ reads, so a streamed transformation of a long input runs within the
442
+ default bound, while a loop that reads no more input still stops (D295).
443
+
444
+ ```js
445
+ const processor = sxml.createProcessor({ maximumEvaluationStepCount: 1_000_000_000 });
446
+ ```
447
+
448
+ ## Memory
449
+
450
+ Processors, expressions, queries, stylesheets, schemas and values own
451
+ memory inside the WebAssembly module. Call `dispose()` when you are done
452
+ with one. Anything not disposed is freed when it is garbage collected.
453
+ Disposing a processor also frees everything it made. The values that a
454
+ query or a transformation gives you (results, updated trees, result
455
+ documents) are yours to dispose.
456
+
457
+ ## API summary
458
+
459
+ | Name | Description |
460
+ | --- | --- |
461
+ | `load({ wasm, collationData })` | Loads a module; returns an `Sxml` |
462
+ | `Sxml.version`, `Sxml.features` | The library version and the module's optional features |
463
+ | `Sxml.createProcessor({ resolver, features, codeLanguages, outputChunkByteCount, maximumEvaluationStepCount })` | A new `Processor` |
464
+ | `Sxml.loadCodeLanguage({ wasm, name, highlights, locals, injections, injectionRegex })` | A `CodeLanguage` (`name`, `abiVersion`) from a tree-sitter WebAssembly language file |
465
+ | `Processor.parse(xml, { uri })` | A document node |
466
+ | `Processor.compile(expression, options)` | An `XPathExpression`, with `evaluate(options)` and `variables` |
467
+ | `Processor.evaluate(expression, options)` | Compiles and evaluates an XPath expression once |
468
+ | `Processor.compileQuery(text, options)` | An `XQuery`, with `evaluate`, `serialize`, `run` and `isUpdating` |
469
+ | `Processor.compileStylesheet(text, options)` | A `Stylesheet`, with `transform` |
470
+ | `Processor.compileSchema(documents, options)` | A `Schema`, with `validate` |
471
+ | `Processor.value(data)` | JavaScript data as a value |
472
+ | `Processor.serialize(value, options)` | The same as `value.serialize(options)` |
473
+ | `Value.toString()`, `Value.serialize(options)` | The value's text |
474
+ | `Value.serializeTo(sink, options)`, `Processor.serializeTo`, `XQuery.runTo`, `XQuery.serializeTo` | The same, written to an `OutputSink` a chunk at a time |
475
+ | `textSink`, `writableStreamSink`, `nodeStreamSink`, `outputReadableStream` | Sinks that decode text, or write to WHATWG and Node.js streams |
476
+ | `dispose()` | On each object: frees its memory |
477
+ | `SxmlError`, `SchemaError` | The errors that the package throws |
478
+
479
+ ## Development
480
+
481
+ The package lives in `bindings/javascript/` of the sxml repository. ctest
482
+ builds and tests it under the `wasm` preset:
483
+
484
+ ```sh
485
+ cmake --preset wasm && cmake --build --preset wasm && ctest --preset wasm -R javascript
486
+ # javascript/languages runs test/full.test.ts: XQuery, XSLT and XSD
487
+ npm ci --prefix bindings/javascript # adds the javascript/typecheck test
488
+ ```
489
+
490
+ `npm run build`, with `SXML_WASM_PATH` set to the built `sxml.wasm`,
491
+ writes `dist/` with the module and `allkeys.txt`. The steps for a release are in
492
+ `docs/RELEASE.md`.