@tinyactors/sxml 0.0.0-stage → 0.3.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 +601 -2
- package/dist/allkeys.txt +39435 -0
- package/dist/index.d.ts +679 -0
- package/dist/index.js +1990 -0
- package/dist/linker.d.ts +20 -0
- package/dist/linker.js +196 -0
- package/dist/stream.d.ts +45 -0
- package/dist/stream.js +259 -0
- package/dist/sxml.wasm +0 -0
- package/dist/wasi.d.ts +3 -0
- package/dist/wasi.js +55 -0
- package/package.json +36 -4
package/README.md
CHANGED
|
@@ -1,3 +1,602 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @tinyactors/sxml
|
|
2
2
|
|
|
3
|
-
|
|
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` | `tree-sitter:parse` and `tree-sitter:languages` (namespace `urn:sxml:tree-sitter`, prefix `tree-sitter`): 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
|
+
## Schematron validation
|
|
344
|
+
|
|
345
|
+
`processor.compileSchematron(schema, { phase, parameters, baseUri })`
|
|
346
|
+
compiles a Schematron schema (ISO/IEC 19757-3:2025): its text, `{ text,
|
|
347
|
+
uri }`, or `{ uri }`, which the resolver is asked for, as are the
|
|
348
|
+
documents its `include` and `extends href` elements name (kind
|
|
349
|
+
`'xml-document'`). `phase` is a phase id, `'#ALL'`, `'#ANY'` or
|
|
350
|
+
`'#DEFAULT'` (the default); `parameters` gives schema parameters their
|
|
351
|
+
values. If the schema has errors, a `SchemaError` is thrown with every
|
|
352
|
+
one in its `reports`, with codes such as `'schematron:syntax'` or
|
|
353
|
+
`'err:XPST0003'`. The schema's `title`, `schemaVersion`,
|
|
354
|
+
`schematronEdition`, `queryBinding` and `phase` are on the result, and
|
|
355
|
+
its `warnings`: reports with the code `'schematron:compatibility'` for
|
|
356
|
+
the deviations of real rule sets that are read as meant (a parameter
|
|
357
|
+
named twice in one pattern instance, a pattern's `let` read by another
|
|
358
|
+
pattern, a rule's `let` after its assertions).
|
|
359
|
+
|
|
360
|
+
`schematron.validate(input, { uri, firedRules, svrl })` checks XML text
|
|
361
|
+
(parsed with its locations) or a node and gives `{ valid, phase,
|
|
362
|
+
findings, svrl }`. Each finding has its `kind`, `id`, `role`, `flag`,
|
|
363
|
+
`severity`, `isError`, `message`, `diagnostics`, `properties`,
|
|
364
|
+
`patternId`, `test`, `path`, the `document` its node is in (the URI of
|
|
365
|
+
a subordinate document for a pattern with `documents`), the node's
|
|
366
|
+
`lineNumber` and `columnNumber` there,
|
|
367
|
+
and the assertion's `schemaLineNumber` and `schemaColumnNumber`. `valid`
|
|
368
|
+
is false when a finding is an error: its severity is `fatal` or
|
|
369
|
+
`error`, or without a severity its role or a flag is, or it has neither.
|
|
370
|
+
|
|
371
|
+
```js
|
|
372
|
+
const rules = processor.compileSchematron(`
|
|
373
|
+
<sch:schema xmlns:sch="http://purl.oclc.org/dsdl/schematron">
|
|
374
|
+
<sch:pattern>
|
|
375
|
+
<sch:rule context="line">
|
|
376
|
+
<sch:assert test="@quantity > 0" id="positive">A line orders at least one item.</sch:assert>
|
|
377
|
+
</sch:rule>
|
|
378
|
+
</sch:pattern>
|
|
379
|
+
</sch:schema>`);
|
|
380
|
+
const result = rules.validate('<order>\n<line quantity="0"/>\n</order>');
|
|
381
|
+
result.valid; // false
|
|
382
|
+
result.findings.map(({ id, lineNumber, message }) => `${lineNumber} ${id}: ${message}`);
|
|
383
|
+
// ['2 positive: A line orders at least one item.']
|
|
384
|
+
```
|
|
385
|
+
|
|
386
|
+
A stylesheet with errors also throws a `SchemaError` from
|
|
387
|
+
`compileStylesheet`, with every error in `reports`.
|
|
388
|
+
|
|
389
|
+
## EXI
|
|
390
|
+
|
|
391
|
+
`processor.encodeExi(node, options)` encodes a document or element node as
|
|
392
|
+
an EXI stream (Efficient XML Interchange 1.0) and returns its bytes as a
|
|
393
|
+
`Uint8Array`. `processor.parseExi(stream, options)` decodes a stream into a
|
|
394
|
+
new document and returns its document node, as `parse` does for XML text;
|
|
395
|
+
`options.uri` is its document URI. A stream that is not EXI throws an
|
|
396
|
+
`SxmlError` with status `'MALFORMED_INPUT'`.
|
|
397
|
+
|
|
398
|
+
The options are EXI's (section 5.4). Each option that is left out has its
|
|
399
|
+
default: bit-packed, nothing preserved, a document, no limits on the
|
|
400
|
+
string tables, and the built-in grammars.
|
|
401
|
+
|
|
402
|
+
- `alignment`: `'bit-packed'` (the default), `'byte-alignment'`,
|
|
403
|
+
`'pre-compression'` or `'compression'` (DEFLATE).
|
|
404
|
+
- `preserve`: a list of `'comments'`, `'pis'`, `'dtd'`, `'prefixes'` and
|
|
405
|
+
`'lexical-values'`. Without `'prefixes'`, the decoder names prefixes
|
|
406
|
+
`ns0`, `ns1` and so on.
|
|
407
|
+
- `fragment`, `strict`, `selfContained`: booleans.
|
|
408
|
+
- `blockSize`, `valueMaxLength`, `valuePartitionCapacity`: integers.
|
|
409
|
+
- `includeCookie`, `includeOptions`, `includeSchemaId` (encoding only):
|
|
410
|
+
the `$EXI` cookie, the options in the header, the schemaId among them.
|
|
411
|
+
- `canonical`, with `omitOptionsDocument` and `utcTime` (encoding only):
|
|
412
|
+
Canonical EXI, one stream for one document and one set of options.
|
|
413
|
+
- `selfContainedElements` (encoding only, with `selfContained`): the
|
|
414
|
+
names of the elements written so that each can be read on its own, an
|
|
415
|
+
NCName or `Q{uri}local` each.
|
|
416
|
+
- `schema`: a `Schema` of the same processor, for schema-informed grammars.
|
|
417
|
+
|
|
418
|
+
A stream whose header has no options is decoded with the options given to
|
|
419
|
+
`parseExi`, which must be the options that it was encoded with. An unknown
|
|
420
|
+
`alignment` or `preserve` item throws a `TypeError`; a count that is not an
|
|
421
|
+
integer from 0 to 2^32 - 1 throws a `RangeError`. In XPath and XQuery, the
|
|
422
|
+
functions `exi:serialize` and `exi:parse` do the same (the prefix `exi` is
|
|
423
|
+
bound to `urn:sxml:exi`).
|
|
424
|
+
|
|
425
|
+
```js
|
|
426
|
+
const order = processor.parse('<order id="A-1"><line sku="KB-104">2</line><!-- note --></order>');
|
|
427
|
+
const stream = processor.encodeExi(order, { alignment: 'byte-alignment', preserve: ['comments'] });
|
|
428
|
+
processor.parseExi(stream, { alignment: 'byte-alignment', preserve: ['comments'] })
|
|
429
|
+
.serialize({ method: 'xml', omitXmlDeclaration: true });
|
|
430
|
+
// '<order id="A-1"><line sku="KB-104">2</line><!-- note --></order>'
|
|
431
|
+
```
|
|
432
|
+
|
|
433
|
+
## Code languages
|
|
434
|
+
|
|
435
|
+
`tree-sitter:parse` (the `source-code` feature; the prefix `tree-sitter`
|
|
436
|
+
is bound to `urn:sxml:tree-sitter`, and `sxml`, of the `sxml:token`
|
|
437
|
+
elements, to `urn:sxml`) parses a dozen languages built in. Any other tree-sitter
|
|
438
|
+
grammar can be loaded from its WebAssembly language file,
|
|
439
|
+
`tree-sitter-NAME.wasm`, as `tree-sitter build --wasm` writes it (many
|
|
440
|
+
grammar repositories ship it with their releases), together with the
|
|
441
|
+
texts of its queries:
|
|
442
|
+
|
|
443
|
+
```js
|
|
444
|
+
const rust = await sxml.loadCodeLanguage({
|
|
445
|
+
wasm: await fetch('/grammars/tree-sitter-rust.wasm'),
|
|
446
|
+
highlights: await (await fetch('/grammars/rust/highlights.scm')).text(),
|
|
447
|
+
// locals, injections and injectionRegex are optional, as is name
|
|
448
|
+
});
|
|
449
|
+
rust.name; // 'rust', from the file's tree_sitter_rust()
|
|
450
|
+
const processor = sxml.createProcessor({ codeLanguages: [rust] });
|
|
451
|
+
processor.evaluate('tree-sitter:parse("fn main() {}", "rust")//function_item/identifier ! string()');
|
|
452
|
+
```
|
|
453
|
+
|
|
454
|
+
`loadCodeLanguage` links the file into the running `sxml.wasm`: the
|
|
455
|
+
file is a WebAssembly side module (its `dylink.0` section), which shares
|
|
456
|
+
the module's memory, function table, stack and C library, so sxml's
|
|
457
|
+
tree-sitter runs its lexer and external scanner directly. It then checks
|
|
458
|
+
the grammar's ABI (13 to 15, tree-sitter 0.20 and later) and that each
|
|
459
|
+
query fits the grammar, and rejects with an `Error` that says what is
|
|
460
|
+
wrong: a file without `dylink.0`, one that needs other WebAssembly
|
|
461
|
+
libraries, one whose scanner imports a C function outside tree-sitter's
|
|
462
|
+
list for language files (`malloc`, `calloc`, `realloc`, `free`, the
|
|
463
|
+
`mem*` and `str*` functions, `isw*`, `towlower`, `towupper`; `abort` and
|
|
464
|
+
`__assert_fail` trap), another ABI, a query that does not fit (with its
|
|
465
|
+
byte offset), or a bad name. A loaded language stays in memory as long
|
|
466
|
+
as its `Sxml` and can be given to any number of its processors; one with
|
|
467
|
+
the name of a built-in language replaces it there.
|
|
468
|
+
|
|
469
|
+
## Resources
|
|
470
|
+
|
|
471
|
+
`fn:doc`, `fn:unparsed-text` and the other resource functions ask the
|
|
472
|
+
processor's resolver. The resolver gets `{ kind, uriReference,
|
|
473
|
+
absoluteUri }` and returns a string, bytes, or `undefined` when the
|
|
474
|
+
resource is not available. Nothing else is read.
|
|
475
|
+
|
|
476
|
+
```js
|
|
477
|
+
const processor = sxml.createProcessor({
|
|
478
|
+
resolver: ({ kind, absoluteUri }) => files.get(absoluteUri),
|
|
479
|
+
});
|
|
480
|
+
processor.evaluate('doc("data.xml")//item', { baseUri: 'https://example.com/' });
|
|
481
|
+
```
|
|
482
|
+
|
|
483
|
+
The kinds are `'xml-document'`, `'text'`, `'binary'`, `'collection'`,
|
|
484
|
+
`'uri-collection'`, `'external-entity'`, `'xquery-module'`,
|
|
485
|
+
`'xslt-module'`, `'xslt-package'` and `'schema-document'`, and three for
|
|
486
|
+
the tables of the optional features:
|
|
487
|
+
|
|
488
|
+
- `'timezone-data'`: a file of the IANA Time Zone Database. `absoluteUri`
|
|
489
|
+
is `urn:sxml:timezone-data:` followed by a zoneinfo path, such as
|
|
490
|
+
`Europe/Paris` (a TZif file) or `zone1970.tab`. Answer with the file's
|
|
491
|
+
bytes.
|
|
492
|
+
- `'collation-data'`: the collation table. Answer with the text of the
|
|
493
|
+
file that `absoluteUri` names, or `undefined`. When the resolver has no
|
|
494
|
+
answer, the package uses the DUCET (`allkeys.txt` of the Unicode
|
|
495
|
+
Collation Algorithm 16.0.0) that it ships next to the modules; to load
|
|
496
|
+
it from elsewhere, pass `load({ collationData })` with a URL, a path or
|
|
497
|
+
the bytes, or `false` for none.
|
|
498
|
+
- `'locale-data'`: a file of the Unicode CLDR. `absoluteUri` is
|
|
499
|
+
`urn:sxml:locale-data:` followed by a path below CLDR's `common/`
|
|
500
|
+
directory, such as `main/de.xml` or `supplemental/supplementalData.xml`.
|
|
501
|
+
Answer with the file's bytes. Without it, dates are formatted in
|
|
502
|
+
English after `[Language: en]`.
|
|
503
|
+
|
|
504
|
+
The resolver is called synchronously during an evaluation. If it throws,
|
|
505
|
+
the evaluation stops and the same exception is rethrown. For a large XML
|
|
506
|
+
document, it may answer with an iterable of chunks (see Streaming).
|
|
507
|
+
|
|
508
|
+
## Errors
|
|
509
|
+
|
|
510
|
+
Failures throw an `SxmlError`. Its fields are `status`, for example
|
|
511
|
+
`'DYNAMIC_ERROR'`, and `code`, for example `'err:FOAR0001'`, also as
|
|
512
|
+
`codeNamespaceUri` and `codeLocalName`. It also has `description`,
|
|
513
|
+
`sourceName` (`'expression'`, `'query'`, or the URI of a module or
|
|
514
|
+
stylesheet), `lineNumber` and `columnNumber`.
|
|
515
|
+
|
|
516
|
+
```js
|
|
517
|
+
try {
|
|
518
|
+
processor.evaluate('1 div 0');
|
|
519
|
+
} catch (error) {
|
|
520
|
+
error.code; // 'err:FOAR0001'
|
|
521
|
+
}
|
|
522
|
+
```
|
|
523
|
+
|
|
524
|
+
## The step limit
|
|
525
|
+
|
|
526
|
+
An evaluation stops with an error after a hundred million evaluation
|
|
527
|
+
steps, a few seconds of work, so a query or stylesheet that would loop
|
|
528
|
+
for hours does not hang the page or the server. Set
|
|
529
|
+
`createProcessor({ maximumEvaluationStepCount })` to a whole number to
|
|
530
|
+
raise or lower it (the C processor limit of the same name; 0 is the
|
|
531
|
+
default). A streamed document grants 500 steps more for each element it
|
|
532
|
+
reads, so a streamed transformation of a long input runs within the
|
|
533
|
+
default bound, while a loop that reads no more input still stops (D295).
|
|
534
|
+
|
|
535
|
+
```js
|
|
536
|
+
const processor = sxml.createProcessor({ maximumEvaluationStepCount: 1_000_000_000 });
|
|
537
|
+
```
|
|
538
|
+
|
|
539
|
+
## Source locations
|
|
540
|
+
|
|
541
|
+
`fn:location` gives the line and column of a node of a parsed document
|
|
542
|
+
when the document kept them. `createProcessor({ locations })` decides
|
|
543
|
+
which do: `'automatic'` (the default) keeps them for a document parsed
|
|
544
|
+
before any program is compiled with the processor, and for the
|
|
545
|
+
documents of a program that can ask for them (it calls `fn:location`,
|
|
546
|
+
can look up functions with `fn:function-lookup`, `fn:transform` or
|
|
547
|
+
`xsl:evaluate`, or validates); `'always'` keeps them for every document;
|
|
548
|
+
`'never'` for none. They cost 32 bytes a node (D313, D318).
|
|
549
|
+
|
|
550
|
+
```js
|
|
551
|
+
const processor = sxml.createProcessor({ locations: 'always' });
|
|
552
|
+
const book = processor.parse('<book>\n <title>XPath</title>\n</book>');
|
|
553
|
+
processor.evaluate('location(//title)?line-number', { context: book }).toString(); // '2'
|
|
554
|
+
```
|
|
555
|
+
|
|
556
|
+
## Memory
|
|
557
|
+
|
|
558
|
+
Processors, expressions, queries, stylesheets, schemas and values own
|
|
559
|
+
memory inside the WebAssembly module. Call `dispose()` when you are done
|
|
560
|
+
with one. Anything not disposed is freed when it is garbage collected.
|
|
561
|
+
Disposing a processor also frees everything it made. The values that a
|
|
562
|
+
query or a transformation gives you (results, updated trees, result
|
|
563
|
+
documents) are yours to dispose.
|
|
564
|
+
|
|
565
|
+
## API summary
|
|
566
|
+
|
|
567
|
+
| Name | Description |
|
|
568
|
+
| --- | --- |
|
|
569
|
+
| `load({ wasm, collationData })` | Loads a module; returns an `Sxml` |
|
|
570
|
+
| `Sxml.version`, `Sxml.features` | The library version and the module's optional features |
|
|
571
|
+
| `Sxml.createProcessor({ resolver, features, codeLanguages, outputChunkByteCount, maximumEvaluationStepCount, locations })` | A new `Processor` |
|
|
572
|
+
| `Sxml.loadCodeLanguage({ wasm, name, highlights, locals, injections, injectionRegex })` | A `CodeLanguage` (`name`, `abiVersion`) from a tree-sitter WebAssembly language file |
|
|
573
|
+
| `Processor.parse(xml, { uri })` | A document node |
|
|
574
|
+
| `Processor.compile(expression, options)` | An `XPathExpression`, with `evaluate(options)` and `variables` |
|
|
575
|
+
| `Processor.evaluate(expression, options)` | Compiles and evaluates an XPath expression once |
|
|
576
|
+
| `Processor.compileQuery(text, options)` | An `XQuery`, with `evaluate`, `serialize`, `run` and `isUpdating` |
|
|
577
|
+
| `Processor.compileStylesheet(text, options)` | A `Stylesheet`, with `transform` |
|
|
578
|
+
| `Processor.compileSchema(documents, options)` | A `Schema`, with `validate` |
|
|
579
|
+
| `Processor.compileSchematron(schema, options)` | A `Schematron`, with `validate` and its `title`, `phase` and edition |
|
|
580
|
+
| `Processor.encodeExi(node, options)`, `Processor.parseExi(stream, options)` | An EXI stream of a node, and the document of a stream |
|
|
581
|
+
| `Processor.value(data)` | JavaScript data as a value |
|
|
582
|
+
| `Processor.serialize(value, options)` | The same as `value.serialize(options)` |
|
|
583
|
+
| `Value.toString()`, `Value.serialize(options)` | The value's text |
|
|
584
|
+
| `Value.serializeTo(sink, options)`, `Processor.serializeTo`, `XQuery.runTo`, `XQuery.serializeTo` | The same, written to an `OutputSink` a chunk at a time |
|
|
585
|
+
| `textSink`, `writableStreamSink`, `nodeStreamSink`, `outputReadableStream` | Sinks that decode text, or write to WHATWG and Node.js streams |
|
|
586
|
+
| `dispose()` | On each object: frees its memory |
|
|
587
|
+
| `SxmlError`, `SchemaError` | The errors that the package throws |
|
|
588
|
+
|
|
589
|
+
## Development
|
|
590
|
+
|
|
591
|
+
The package lives in `bindings/javascript/` of the sxml repository. ctest
|
|
592
|
+
builds and tests it under the `wasm` preset:
|
|
593
|
+
|
|
594
|
+
```sh
|
|
595
|
+
cmake --preset wasm && cmake --build --preset wasm && ctest --preset wasm -R javascript
|
|
596
|
+
# javascript/languages runs test/full.test.ts: XQuery, XSLT and XSD
|
|
597
|
+
npm ci --prefix bindings/javascript # adds the javascript/typecheck test
|
|
598
|
+
```
|
|
599
|
+
|
|
600
|
+
`npm run build`, with `SXML_WASM_PATH` set to the built `sxml.wasm`,
|
|
601
|
+
writes `dist/` with the module and `allkeys.txt`. The steps for a release are in
|
|
602
|
+
`docs/RELEASE.md`.
|