@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/dist/index.js ADDED
@@ -0,0 +1,1687 @@
1
+ // sxml for JavaScript: XML parsing, XPath 4.0, XQuery 4.0, XSLT 4.0, XSD 1.1
2
+ // validation and serialization in Node.js and browsers, over sxml.wasm
3
+ // (docs/DECISIONS.md, D10, D138, D272).
4
+ //
5
+ // import { load } from '@tinyactors/sxml';
6
+ // const sxml = await load();
7
+ // const processor = sxml.createProcessor();
8
+ // const book = processor.parse('<book><title>XPath</title></book>');
9
+ // processor.evaluate('//title/string()', { context: book }).toString();
10
+ // // '"XPath"' (the adaptive method of Serialization 4.0)
11
+ //
12
+ // The one module has every language and every optional feature (D272):
13
+ // XQuery 4.0 (Processor.compileQuery), XSLT 4.0 (Processor.compileStylesheet)
14
+ // and XSD 1.1 validation (Processor.compileSchema) besides XPath.
15
+ //
16
+ // Every object that owns memory in the module (Processor, XPathExpression,
17
+ // XQuery, Stylesheet, Schema, Value) has dispose(); one that is never disposed is released when it is
18
+ // garbage collected (FinalizationRegistry). The C side is the shim in
19
+ // ../sxml_javascript.c; the word offsets below follow its structs.
20
+ import { linkLanguageModule } from "./linker.js";
21
+ import { ChunkReader, OutputRouter, readWhole, } from "./stream.js";
22
+ import { wasiImports } from "./wasi.js";
23
+ export { nodeStreamSink, outputReadableStream, textSink, writableStreamSink, } from "./stream.js";
24
+ // ----------------------------------------------------------------- Errors
25
+ /** A failure in sxml: a static, dynamic or type error of the expression
26
+ * (with its error code), a document that is not well-formed, a limit, or
27
+ * out of memory. */
28
+ export class SxmlError extends Error {
29
+ /** The status, such as 'DYNAMIC_ERROR' or 'MALFORMED_INPUT'. */
30
+ status;
31
+ /** The error code as prefix:local, such as 'err:FOAR0001'; '' when the
32
+ * status has none. */
33
+ code;
34
+ codeNamespaceUri;
35
+ codeLocalName;
36
+ description;
37
+ /** The module or document the location is in: 'expression', 'query',
38
+ * a module's URI; '' when unknown. */
39
+ sourceName;
40
+ lineNumber;
41
+ columnNumber;
42
+ constructor(fields) {
43
+ const code = fields.codeLocalName === ''
44
+ ? ''
45
+ : fields.codePrefix !== ''
46
+ ? `${fields.codePrefix}:${fields.codeLocalName}`
47
+ : fields.codeNamespaceUri !== ''
48
+ ? `Q{${fields.codeNamespaceUri}}${fields.codeLocalName}`
49
+ : fields.codeLocalName;
50
+ const where = fields.lineNumber > 0 ? `${fields.lineNumber}:${fields.columnNumber}: ` : '';
51
+ const what = fields.description !== '' ? fields.description : fields.status;
52
+ super(`${where}${code !== '' ? `${code}: ` : ''}${what}`);
53
+ this.name = 'SxmlError';
54
+ this.status = fields.status;
55
+ this.code = code;
56
+ this.codeNamespaceUri = fields.codeNamespaceUri;
57
+ this.codeLocalName = fields.codeLocalName;
58
+ this.description = fields.description;
59
+ this.sourceName = fields.sourceName ?? '';
60
+ this.lineNumber = fields.lineNumber;
61
+ this.columnNumber = fields.columnNumber;
62
+ }
63
+ }
64
+ /** A schema that does not compile: every error, with the first as the
65
+ * SxmlError's own code, description and location. */
66
+ export class SchemaError extends SxmlError {
67
+ reports;
68
+ constructor(error, reports) {
69
+ const prefix = /^([^:{}]+):/.exec(error.code)?.[1] ?? '';
70
+ super({ ...error, codePrefix: prefix });
71
+ this.name = 'SchemaError';
72
+ this.reports = Object.freeze(reports);
73
+ }
74
+ }
75
+ // sxml_status values the package itself returns from the resolver import.
76
+ const status_ok = 0;
77
+ const status_out_of_memory = 6;
78
+ const status_input_output_failed = 13;
79
+ const resource_kinds = [
80
+ 'xml-document',
81
+ 'text',
82
+ 'binary',
83
+ 'collection',
84
+ 'uri-collection',
85
+ 'xquery-module',
86
+ 'xslt-module',
87
+ 'xslt-package',
88
+ 'schema-document',
89
+ 'external-entity',
90
+ 'timezone-data',
91
+ 'collation-data',
92
+ 'locale-data',
93
+ ];
94
+ /** The URI the uca-collation feature asks for its DUCET by. */
95
+ const ducet_uri = 'http://www.unicode.org/Public/UCA/16.0.0/allkeys.txt';
96
+ const encoder = new TextEncoder();
97
+ const decoder = new TextDecoder();
98
+ /** A processor's C side and the handles made with it, so that destroying
99
+ * it releases them first (they could not outlive it in C). */
100
+ /** The conventional prefixes of the optional features' namespaces, bound
101
+ * for XPath and XQuery wherever the feature is present, as the sxml
102
+ * command binds them (EXPath Binary 4.0, 1.5; EXPath File 4.0, 1.7;
103
+ * D235): feature name, prefix, namespace URI. */
104
+ const featurePrefixes = [
105
+ ['expath-binary', 'bin', 'http://expath.org/ns/binary'],
106
+ ['source-code', 'sxml', 'urn:sxml'],
107
+ ['expath-file', 'file', 'http://expath.org/ns/file'],
108
+ ];
109
+ class ProcessorState {
110
+ module;
111
+ address;
112
+ resolver;
113
+ /** Handles not yet released: address to kind. */
114
+ live = new Map();
115
+ /** The exception the resolver threw during the current call. */
116
+ pendingException = undefined;
117
+ isInResolver = false;
118
+ /** Whether an output sink or chunk source is running (D294). */
119
+ isInSink = false;
120
+ /** The router of the current streaming call's output (D294). */
121
+ outputRouter = undefined;
122
+ /** The chunk sources the resolver delivered, by reader identifier. */
123
+ readers = new Map();
124
+ nextReaderIdentifier = 1;
125
+ /** ProcessorOptions.outputChunkByteCount. */
126
+ outputChunkByteCount = default_output_chunk_byte_count;
127
+ /** parse-json($json), compiled when first needed. */
128
+ jsonExpression = 0;
129
+ /** What sxml_javascript_processor_destroy found still allocated. */
130
+ leakedAllocationCount = 0;
131
+ /** The processor's sxml_source_code_language_view and its array, made
132
+ * with malloc, which must outlive it; 0 for none. */
133
+ codeLanguageView = 0;
134
+ /** The prefixes of the processor's features' namespaces (D235). */
135
+ featureNamespaces;
136
+ constructor(module, address, resolver, features) {
137
+ this.module = module;
138
+ this.address = address;
139
+ this.resolver = resolver;
140
+ const namespaces = {};
141
+ for (const [feature, prefix, uri] of featurePrefixes) {
142
+ if (features.includes(feature)) {
143
+ namespaces[prefix] = uri;
144
+ }
145
+ }
146
+ this.featureNamespaces = Object.freeze(namespaces);
147
+ }
148
+ /** The namespaces of a compilation: the features' prefixes, then the
149
+ * caller's, which may rebind them. */
150
+ staticNamespaces(namespaces) {
151
+ return Object.entries({ ...this.featureNamespaces, ...(namespaces ?? {}) });
152
+ }
153
+ releaseHandle(kind, address) {
154
+ if (this.address === 0 || !this.live.delete(address)) {
155
+ return;
156
+ }
157
+ this.destroyHandle(kind, address);
158
+ }
159
+ /** Releases a handle by its kind's export. */
160
+ destroyHandle(kind, address) {
161
+ const exports = this.module.exports;
162
+ switch (kind) {
163
+ case 'value':
164
+ exports.sxml_javascript_value_release(address);
165
+ break;
166
+ case 'expression':
167
+ exports.sxml_javascript_expression_destroy(address);
168
+ break;
169
+ case 'query':
170
+ exports.sxml_javascript_query_destroy?.(address);
171
+ break;
172
+ case 'stylesheet':
173
+ exports.sxml_javascript_stylesheet_destroy?.(address);
174
+ break;
175
+ case 'schema':
176
+ exports.sxml_javascript_schema_destroy?.(address);
177
+ break;
178
+ }
179
+ }
180
+ destroy() {
181
+ if (this.address === 0) {
182
+ return;
183
+ }
184
+ for (const [address, kind] of this.live) {
185
+ this.destroyHandle(kind, address);
186
+ }
187
+ this.live.clear();
188
+ if (this.jsonExpression !== 0) {
189
+ this.module.exports.sxml_javascript_expression_destroy(this.jsonExpression);
190
+ this.jsonExpression = 0;
191
+ }
192
+ this.module.processors.delete(this.address);
193
+ this.leakedAllocationCount = this.module.exports.sxml_javascript_processor_destroy(this.address);
194
+ this.address = 0;
195
+ if (this.codeLanguageView !== 0) {
196
+ this.module.exports.free(this.codeLanguageView);
197
+ this.codeLanguageView = 0;
198
+ }
199
+ }
200
+ }
201
+ /** Memory for one call's request: texts and words, released together. */
202
+ class Scratch {
203
+ state;
204
+ addresses = [];
205
+ constructor(state) {
206
+ this.state = state;
207
+ }
208
+ allocate(byteCount) {
209
+ const address = this.state.module.exports.sxml_javascript_allocate(this.state.address, byteCount);
210
+ if (address === 0) {
211
+ throw outOfMemory();
212
+ }
213
+ this.addresses.push(address);
214
+ return address;
215
+ }
216
+ /** Copies text (UTF-8) or bytes in; returns the two words of a byte
217
+ * view. */
218
+ view(content) {
219
+ const bytes = typeof content === 'string' ? encoder.encode(content) : content;
220
+ const address = this.allocate(bytes.byteLength);
221
+ this.state.module.bytes().set(bytes, address);
222
+ return [address, bytes.byteLength];
223
+ }
224
+ /** Writes 32-bit words; returns their address. */
225
+ words(words) {
226
+ const address = this.allocate(words.length * 4);
227
+ this.state.module.words().set(words, address / 4);
228
+ return address;
229
+ }
230
+ release() {
231
+ for (const address of this.addresses) {
232
+ this.state.module.exports.sxml_javascript_release(this.state.address, address);
233
+ }
234
+ this.addresses.length = 0;
235
+ }
236
+ }
237
+ function outOfMemory() {
238
+ return new SxmlError({
239
+ status: 'OUT_OF_MEMORY',
240
+ codeNamespaceUri: '',
241
+ codeLocalName: '',
242
+ codePrefix: '',
243
+ description: 'Out of memory',
244
+ lineNumber: 0,
245
+ columnNumber: 0,
246
+ });
247
+ }
248
+ function disposed(what) {
249
+ return new Error(`sxml: this ${what} has been disposed`);
250
+ }
251
+ /** sxml_javascript_side_result_kind. */
252
+ const side_result_updated_tree = 0;
253
+ const side_result_put_document = 1;
254
+ const side_result_result_document = 2;
255
+ const side_result_message = 3;
256
+ const side_result_schema_report = 4;
257
+ /** sxml_xslt_invocation_kind and sxml_xslt_result_delivery. */
258
+ const invocation_apply_templates = 0;
259
+ const invocation_call_template = 1;
260
+ const invocation_call_function = 2;
261
+ const result_deliveries = { raw: 1, tree: 2, serialized: 3 };
262
+ /** sxml_validity. */
263
+ const validities = ['valid', 'invalid', 'not-known'];
264
+ /** The four words of a name (sxml_javascript_name); '' gives none. */
265
+ function nameWords(scratch, name) {
266
+ if (name === undefined || name === '') {
267
+ return [0, 0, 0, 0];
268
+ }
269
+ const [namespaceUri, localName] = splitName(name);
270
+ return [...scratch.view(namespaceUri), ...scratch.view(localName)];
271
+ }
272
+ /** Splits an NCName or Q{uri}local into namespace URI and local name. */
273
+ function splitName(name) {
274
+ const match = /^Q\{([^{}]*)\}(.+)$/.exec(name);
275
+ return match === null ? ['', name] : [match[1] ?? '', match[2] ?? ''];
276
+ }
277
+ /** The loaded module: makes processors. One per page or process is enough;
278
+ * processors made from it are independent. */
279
+ export class Sxml {
280
+ /** @internal */
281
+ exports;
282
+ /** The library version, such as '0.2.0'. */
283
+ version;
284
+ /** The optional features of the module: all of them (D272; 'test' adds
285
+ * nothing, it checks that the list reaches the processor). */
286
+ features;
287
+ /** The DUCET served for 'collation-data' (LoadOptions.collationData).
288
+ * @internal */
289
+ collationData;
290
+ /** Processors by address, for the resolver import. @internal */
291
+ processors = new Map();
292
+ registry;
293
+ /** @internal Use load(). */
294
+ constructor(exports) {
295
+ this.exports = exports;
296
+ this.registry = new FinalizationRegistry((held) => {
297
+ if (held.kind === 'processor') {
298
+ held.processor.destroy();
299
+ }
300
+ else {
301
+ held.processor.releaseHandle(held.kind, held.address);
302
+ }
303
+ });
304
+ const versionAddress = exports.sxml_javascript_version_text();
305
+ const bytes = this.bytes();
306
+ let end = versionAddress;
307
+ while (bytes[end] !== 0) {
308
+ end += 1;
309
+ }
310
+ this.version = decoder.decode(bytes.subarray(versionAddress, end));
311
+ const features = [];
312
+ for (let index = 0; index < exports.sxml_javascript_feature_count(); index += 1) {
313
+ features.push(this.text(exports.sxml_javascript_feature_name_bytes(index), exports.sxml_javascript_feature_name_byte_count(index)));
314
+ }
315
+ this.features = Object.freeze(features);
316
+ }
317
+ /** The module's memory as bytes; a new view after every call, since
318
+ * memory may have grown. @internal */
319
+ bytes() {
320
+ return new Uint8Array(this.exports.memory.buffer);
321
+ }
322
+ /** @internal */
323
+ words() {
324
+ return new Uint32Array(this.exports.memory.buffer);
325
+ }
326
+ /** @internal */
327
+ text(address, byteCount) {
328
+ return decoder.decode(this.bytes().subarray(address, address + byteCount));
329
+ }
330
+ /** @internal */
331
+ track(owner, held) {
332
+ this.registry.register(owner, held, owner);
333
+ }
334
+ /** @internal */
335
+ untrack(owner) {
336
+ this.registry.unregister(owner);
337
+ }
338
+ createProcessor(options = {}) {
339
+ let featureMask = 0;
340
+ for (const name of options.features ?? this.features) {
341
+ const index = this.features.indexOf(name);
342
+ if (index < 0) {
343
+ throw new Error(`sxml: this module has no optional feature '${name}'`);
344
+ }
345
+ featureMask |= 1 << index;
346
+ }
347
+ const stepCount = options.maximumEvaluationStepCount ?? 0;
348
+ if (!Number.isSafeInteger(stepCount) || stepCount < 0) {
349
+ throw new RangeError('sxml: maximumEvaluationStepCount must be a whole number from 0 to 2^53 - 1');
350
+ }
351
+ const codeLanguageView = this.codeLanguageView(options.codeLanguages ?? []);
352
+ // sxml_javascript_processor_request (sxml_javascript.h): four words
353
+ // and the step count's two, low first.
354
+ const request = this.exports.malloc(processor_request_byte_count);
355
+ if (request === 0) {
356
+ if (codeLanguageView !== 0) {
357
+ this.exports.free(codeLanguageView);
358
+ }
359
+ throw outOfMemory();
360
+ }
361
+ this.words().set([options.failingAllocationNumber ?? 0, featureMask >>> 0, codeLanguageView, 0, stepCount % 2 ** 32, Math.floor(stepCount / 2 ** 32)], request / 4);
362
+ const address = this.exports.sxml_javascript_processor_create(request);
363
+ this.exports.free(request);
364
+ if (address === 0) {
365
+ if (codeLanguageView !== 0) {
366
+ this.exports.free(codeLanguageView);
367
+ }
368
+ throw outOfMemory();
369
+ }
370
+ const state = new ProcessorState(this, address, options.resolver, options.features ?? this.features);
371
+ state.codeLanguageView = codeLanguageView;
372
+ this.exports.sxml_javascript_set_byte_reader(address);
373
+ if (options.outputChunkByteCount !== undefined) {
374
+ if (!Number.isInteger(options.outputChunkByteCount) || options.outputChunkByteCount < 1) {
375
+ throw new RangeError('sxml: outputChunkByteCount must be a positive integer');
376
+ }
377
+ state.outputChunkByteCount = options.outputChunkByteCount;
378
+ }
379
+ this.processors.set(address, state);
380
+ const processor = new Processor(state);
381
+ this.track(processor, { processor: state, kind: 'processor', address });
382
+ return processor;
383
+ }
384
+ /**
385
+ * Loads a tree-sitter language file (tree-sitter-NAME.wasm, as
386
+ * `tree-sitter build --wasm` writes it) into this module for
387
+ * sxml:parse-code: links it into sxml.wasm (src/linker.ts) and checks
388
+ * its ABI and queries. Give it to processors with createProcessor({
389
+ * codeLanguages }). It stays loaded as long as this Sxml. Rejects with
390
+ * an Error that says what is wrong with the file, the name or a query.
391
+ */
392
+ async loadCodeLanguage(options) {
393
+ const exports = this.exports;
394
+ const module = await compileModule(options.wasm);
395
+ const functions = new Map();
396
+ for (const [name, value] of Object.entries(exports)) {
397
+ // The C library functions the build exports for external scanners
398
+ // (bindings/javascript/CMakeLists.txt); sxml's own are sxml_.
399
+ if (typeof value === 'function' && !name.startsWith('sxml_') && !name.startsWith('_')) {
400
+ functions.set(name, value);
401
+ }
402
+ }
403
+ const linked = await linkLanguageModule(module, {
404
+ memory: exports.memory,
405
+ table: exports.__indirect_function_table,
406
+ stackPointer: exports.__stack_pointer,
407
+ functions,
408
+ reserve: (byteCount, alignment) => {
409
+ const address = this.reserve(byteCount + alignment - 1);
410
+ const aligned = Math.ceil(address / alignment) * alignment;
411
+ this.bytes().fill(0, aligned, aligned + byteCount);
412
+ return aligned;
413
+ },
414
+ }, options.name);
415
+ const name = options.name ?? linked.functionName;
416
+ // sxml_source_code_language (processor.h): six byte views but the
417
+ // grammar, eleven words; the texts stay with the language.
418
+ const view = (text) => {
419
+ const bytes = encoder.encode(text ?? '');
420
+ const address = this.reserve(bytes.byteLength);
421
+ this.bytes().set(bytes, address);
422
+ return [address, bytes.byteLength];
423
+ };
424
+ const words = [
425
+ ...view(name),
426
+ linked.languageAddress,
427
+ ...view(options.highlights),
428
+ ...view(options.locals),
429
+ ...view(options.injections),
430
+ ...view(options.injectionRegex),
431
+ ];
432
+ const language = this.reserve(code_language_byte_count);
433
+ this.words().set(words, language / 4);
434
+ // sxml_source_code_language_report: problem, abi_version, byte_offset.
435
+ const report = this.reserve(12);
436
+ const status = exports.sxml_javascript_check_code_language(language, report);
437
+ const [problem = 0, abiVersion = 0, byteOffset = 0] = this.words().subarray(report / 4, report / 4 + 3);
438
+ exports.free(report);
439
+ if (status === status_out_of_memory) {
440
+ throw outOfMemory();
441
+ }
442
+ if (status !== status_ok) {
443
+ throw new Error(codeLanguageProblem(problem, { name, abiVersion, byteOffset }));
444
+ }
445
+ return new CodeLanguage(this, language, name, abiVersion);
446
+ }
447
+ /** malloc of sxml.wasm, for memory that outlives processors.
448
+ * @internal */
449
+ reserve(byteCount) {
450
+ const address = this.exports.malloc(Math.max(byteCount, 1));
451
+ if (address === 0) {
452
+ throw outOfMemory();
453
+ }
454
+ return address;
455
+ }
456
+ /** A processor's sxml_source_code_language_view: the view, then a copy
457
+ * of each language; 0 for none. @internal */
458
+ codeLanguageView(languages) {
459
+ if (languages.length === 0) {
460
+ return 0;
461
+ }
462
+ const names = new Set();
463
+ for (const language of languages) {
464
+ if (language.module !== this) {
465
+ throw new Error('sxml: this code language was loaded by another sxml module');
466
+ }
467
+ if (names.has(language.name)) {
468
+ throw new Error(`sxml: two code languages are named '${language.name}'`);
469
+ }
470
+ names.add(language.name);
471
+ }
472
+ const view = this.reserve(8 + languages.length * code_language_byte_count);
473
+ const bytes = this.bytes();
474
+ languages.forEach((language, index) => {
475
+ const at = view + 8 + index * code_language_byte_count;
476
+ bytes.copyWithin(at, language.address, language.address + code_language_byte_count);
477
+ });
478
+ this.words().set([view + 8, languages.length], view / 4);
479
+ return view;
480
+ }
481
+ /** The resolver import (sxml_javascript_host_resolve). @internal */
482
+ resolve(processorAddress, requestAddress, resourceAddress) {
483
+ const state = this.processors.get(processorAddress);
484
+ if (state === undefined) {
485
+ return status_ok;
486
+ }
487
+ const request = this.words().subarray(requestAddress / 4, requestAddress / 4 + 5);
488
+ const resourceRequest = {
489
+ kind: resource_kinds[request[0] ?? 0] ?? 'xml-document',
490
+ uriReference: this.text(request[1] ?? 0, request[2] ?? 0),
491
+ absoluteUri: this.text(request[3] ?? 0, request[4] ?? 0),
492
+ };
493
+ let answer;
494
+ if (state.resolver !== undefined) {
495
+ state.isInResolver = true;
496
+ try {
497
+ answer = state.resolver(resourceRequest);
498
+ }
499
+ catch (exception) {
500
+ state.pendingException = exception;
501
+ return status_input_output_failed;
502
+ }
503
+ finally {
504
+ state.isInResolver = false;
505
+ }
506
+ }
507
+ if ((answer === null || answer === undefined) &&
508
+ resourceRequest.kind === 'collation-data' &&
509
+ resourceRequest.absoluteUri === ducet_uri) {
510
+ answer = this.collationData;
511
+ }
512
+ if (answer === null || answer === undefined) {
513
+ return status_ok;
514
+ }
515
+ if (typeof answer !== 'string' && !(answer instanceof Uint8Array)) {
516
+ // A chunk source (D294): read as it is parsed for an XML document,
517
+ // whole for the other kinds.
518
+ if (resourceRequest.kind === 'xml-document') {
519
+ const identifier = state.nextReaderIdentifier;
520
+ state.nextReaderIdentifier += 1;
521
+ state.readers.set(identifier, new ChunkReader(answer));
522
+ this.words().set([resource_form_byte_reader, 0, 0, identifier], resourceAddress / 4);
523
+ return status_ok;
524
+ }
525
+ try {
526
+ state.isInResolver = true;
527
+ answer = readWhole(answer);
528
+ }
529
+ catch (exception) {
530
+ state.pendingException = exception;
531
+ return status_input_output_failed;
532
+ }
533
+ finally {
534
+ state.isInResolver = false;
535
+ }
536
+ }
537
+ const bytes = typeof answer === 'string' ? encoder.encode(answer) : answer;
538
+ const address = this.exports.sxml_javascript_allocate(processorAddress, bytes.byteLength);
539
+ if (address === 0) {
540
+ return status_out_of_memory;
541
+ }
542
+ this.bytes().set(bytes, address);
543
+ this.words().set([1, address, bytes.byteLength, 0], resourceAddress / 4);
544
+ return status_ok;
545
+ }
546
+ /** The import sxml_host.write (sxml_host_output_event: kind, bytes,
547
+ * is_abandoned). @internal */
548
+ write(processorAddress, eventAddress) {
549
+ const state = this.processors.get(processorAddress);
550
+ const router = state?.outputRouter;
551
+ if (state === undefined || router === undefined) {
552
+ return status_ok;
553
+ }
554
+ const [kind = 0, address = 0, byteCount = 0, isAbandoned = 0] = this.words().subarray(eventAddress / 4, eventAddress / 4 + 4);
555
+ state.isInSink = true;
556
+ try {
557
+ router.event(kind, this.bytes().subarray(address, address + byteCount), isAbandoned !== 0, () => this.text(address, byteCount));
558
+ return status_ok;
559
+ }
560
+ catch (exception) {
561
+ state.pendingException = exception;
562
+ return status_input_output_failed;
563
+ }
564
+ finally {
565
+ state.isInSink = false;
566
+ }
567
+ }
568
+ /** The import sxml_host.read (sxml_host_read_request: identifier,
569
+ * buffer, byte_count, is_end). @internal */
570
+ read(processorAddress, requestAddress) {
571
+ const state = this.processors.get(processorAddress);
572
+ const at = requestAddress / 4;
573
+ const [identifier = 0, buffer = 0, bufferByteCount = 0] = this.words().subarray(at, at + 3);
574
+ const reader = state?.readers.get(identifier);
575
+ if (state === undefined || reader === undefined) {
576
+ this.words().set([0, 1], at + 3);
577
+ return status_ok;
578
+ }
579
+ state.isInSink = true;
580
+ try {
581
+ const [byteCount, isEnd] = reader.read(this.bytes().subarray(buffer, buffer + bufferByteCount));
582
+ this.words().set([byteCount, isEnd ? 1 : 0], at + 3);
583
+ return status_ok;
584
+ }
585
+ catch (exception) {
586
+ state.pendingException = exception;
587
+ return status_input_output_failed;
588
+ }
589
+ finally {
590
+ state.isInSink = false;
591
+ }
592
+ }
593
+ /** The import sxml_host.release_reader. @internal */
594
+ releaseReader(processorAddress, identifier) {
595
+ const state = this.processors.get(processorAddress);
596
+ const reader = state?.readers.get(identifier);
597
+ if (state === undefined || reader === undefined) {
598
+ return;
599
+ }
600
+ state.readers.delete(identifier);
601
+ try {
602
+ reader.close();
603
+ }
604
+ catch (exception) {
605
+ state.pendingException ??= exception;
606
+ }
607
+ }
608
+ }
609
+ /** ProcessorOptions.outputChunkByteCount's default. */
610
+ const default_output_chunk_byte_count = 65536;
611
+ /** SXML_RESOURCE_FORM_BYTE_READER (include/sxml/processor.h). */
612
+ const resource_form_byte_reader = 4;
613
+ /** The size of sxml_source_code_language in sxml.wasm (checked by the
614
+ * shim, sxml_javascript_exports.c). */
615
+ const code_language_byte_count = 44;
616
+ /** sizeof(sxml_javascript_processor_request) on wasm32 (D295). */
617
+ const processor_request_byte_count = 24;
618
+ /** sxml_source_code_language_problem, as the sxml command words it
619
+ * (apps/sxml/code_languages.c). */
620
+ function codeLanguageProblem(problem, { name, abiVersion, byteOffset }) {
621
+ const queries = ['highlights', 'locals', 'injections'];
622
+ if (problem === 1) {
623
+ return `sxml: '${name}' is no language name (ASCII letters, digits, '_', '-', '+' and '.')`;
624
+ }
625
+ if (problem === 2) {
626
+ return `sxml: the grammar's ABI is ${abiVersion}; sxml reads 13 to 15`;
627
+ }
628
+ return `sxml: the ${queries[problem - 3] ?? 'highlights'} query does not fit the grammar at byte ${byteOffset}`;
629
+ }
630
+ /** A tree-sitter language loaded by Sxml.loadCodeLanguage, for
631
+ * createProcessor({ codeLanguages }). */
632
+ export class CodeLanguage {
633
+ /** @internal */
634
+ module;
635
+ /** @internal Its sxml_source_code_language in the module's memory. */
636
+ address;
637
+ /** Its name in sxml:parse-code. */
638
+ name;
639
+ /** The grammar's tree-sitter language ABI, 13 to 15. */
640
+ abiVersion;
641
+ /** @internal Use Sxml.loadCodeLanguage(). */
642
+ constructor(module, address, name, abiVersion) {
643
+ this.module = module;
644
+ this.address = address;
645
+ this.name = name;
646
+ this.abiVersion = abiVersion;
647
+ }
648
+ }
649
+ /** Loads and instantiates sxml.wasm. */
650
+ export async function load(options = {}) {
651
+ const module = await compileModule(options.wasm ?? new URL('./sxml.wasm', import.meta.url));
652
+ let sxml;
653
+ let memory;
654
+ const instance = await WebAssembly.instantiate(module, {
655
+ wasi_snapshot_preview1: wasiImports(module, () => {
656
+ if (memory === undefined) {
657
+ throw new Error('sxml.wasm called WASI before it was instantiated');
658
+ }
659
+ return memory;
660
+ }),
661
+ sxml_host: {
662
+ resolve: (processor, request, resource) => sxml === undefined ? status_ok : sxml.resolve(processor, request, resource),
663
+ write: (processor, event) => sxml === undefined ? status_ok : sxml.write(processor, event),
664
+ read: (processor, request) => sxml === undefined ? status_ok : sxml.read(processor, request),
665
+ release_reader: (processor, identifier) => sxml?.releaseReader(processor, identifier),
666
+ },
667
+ });
668
+ const exports = instance.exports;
669
+ if (typeof exports.sxml_javascript_query_compile !== 'function') {
670
+ // A module of an older package, without XQuery, XSLT and XSD.
671
+ throw new Error('sxml: this module is not the package\'s sxml.wasm');
672
+ }
673
+ memory = exports.memory;
674
+ exports._initialize();
675
+ sxml = new Sxml(exports);
676
+ if (sxml.features.includes('uca-collation') && options.collationData !== false) {
677
+ if (options.collationData === undefined) {
678
+ // The package's copy; without it the feature falls back (D213).
679
+ sxml.collationData = await readBytes(new URL('./allkeys.txt', import.meta.url)).catch(() => undefined);
680
+ }
681
+ else {
682
+ sxml.collationData = await readBytes(options.collationData);
683
+ }
684
+ }
685
+ return sxml;
686
+ }
687
+ /** The bytes of a URL, a path or a buffer. */
688
+ async function readBytes(source) {
689
+ if (source instanceof ArrayBuffer) {
690
+ return new Uint8Array(source);
691
+ }
692
+ if (ArrayBuffer.isView(source)) {
693
+ return new Uint8Array(source.buffer, source.byteOffset, source.byteLength);
694
+ }
695
+ const url = source instanceof URL ? source : new URL(source, import.meta.url);
696
+ if (url.protocol === 'file:') {
697
+ const { readFile } = await import('node:fs/promises');
698
+ return new Uint8Array(await readFile(url));
699
+ }
700
+ const response = await fetch(url);
701
+ if (!response.ok) {
702
+ throw new Error(`sxml: cannot fetch ${url.href} (${response.status})`);
703
+ }
704
+ return new Uint8Array(await response.arrayBuffer());
705
+ }
706
+ async function compileModule(source) {
707
+ if (source instanceof WebAssembly.Module) {
708
+ return source;
709
+ }
710
+ if (source instanceof ArrayBuffer || ArrayBuffer.isView(source)) {
711
+ return WebAssembly.compile(source);
712
+ }
713
+ if (typeof source === 'string' || source instanceof URL) {
714
+ const url = source instanceof URL ? source : new URL(source, import.meta.url);
715
+ if (url.protocol === 'file:') {
716
+ // Node.js: fetch() does not read files.
717
+ const { readFile } = await import('node:fs/promises');
718
+ return WebAssembly.compile(await readFile(url));
719
+ }
720
+ return compileResponse(fetch(url));
721
+ }
722
+ return compileResponse(source);
723
+ }
724
+ async function compileResponse(response) {
725
+ const resolved = await response;
726
+ if (!resolved.ok) {
727
+ throw new Error(`sxml: cannot fetch sxml.wasm (${resolved.status})`);
728
+ }
729
+ return WebAssembly.compile(await resolved.arrayBuffer());
730
+ }
731
+ // --------------------------------------------------------------- Processor
732
+ /** A processor (include/sxml/processor.h): its name pool, types and items.
733
+ * Values and expressions belong to the processor that made them. */
734
+ export class Processor {
735
+ state;
736
+ /** @internal Use Sxml.createProcessor(). */
737
+ constructor(state) {
738
+ this.state = state;
739
+ }
740
+ /** Parses an XML document and returns its document node. */
741
+ parse(xml, options = {}) {
742
+ const state = this.enter();
743
+ const scratch = new Scratch(state);
744
+ try {
745
+ const request = scratch.words([...scratch.view(xml), ...scratch.view(options.uri ?? '')]);
746
+ return this.adopt(state.module.exports.sxml_javascript_parse(state.address, request));
747
+ }
748
+ finally {
749
+ scratch.release();
750
+ }
751
+ }
752
+ /** Compiles an XPath 4.0 expression, for evaluating it many times. */
753
+ compile(expression, options = {}) {
754
+ const state = this.enter();
755
+ const variables = options.variables ?? [];
756
+ const address = this.compileAddress(expression, options, variables);
757
+ state.live.set(address, 'expression');
758
+ const compiled = new XPathExpression(this, address, variables);
759
+ state.module.track(compiled, { processor: state, kind: 'expression', address });
760
+ return compiled;
761
+ }
762
+ /** Compiles and evaluates an expression once; the variables are those
763
+ * options.variables names. */
764
+ evaluate(expression, options = {}) {
765
+ const compiled = this.compile(expression, {
766
+ ...options,
767
+ variables: Object.keys(options.variables ?? {}),
768
+ });
769
+ try {
770
+ return compiled.evaluate(options);
771
+ }
772
+ finally {
773
+ compiled.dispose();
774
+ }
775
+ }
776
+ /** Compiles an XQuery 4.0 main module, with the library modules it
777
+ * imports (the resolver is asked for them, kind 'xquery-module'), for
778
+ * evaluating it many times. */
779
+ compileQuery(query, options = {}) {
780
+ const exports = this.exports();
781
+ const state = this.enter();
782
+ const scratch = new Scratch(state);
783
+ let address;
784
+ try {
785
+ const namespaceWords = [];
786
+ for (const [prefix, uri] of state.staticNamespaces(options.namespaces)) {
787
+ namespaceWords.push(...scratch.view(prefix), ...scratch.view(uri));
788
+ }
789
+ const request = scratch.words([
790
+ ...scratch.view(query),
791
+ ...scratch.view(options.baseUri ?? ''),
792
+ namespaceWords.length > 0 ? scratch.words(namespaceWords) : 0,
793
+ namespaceWords.length / 4,
794
+ ]);
795
+ address = exports.sxml_javascript_query_compile(state.address, request);
796
+ if (address === 0) {
797
+ throw this.failure();
798
+ }
799
+ }
800
+ finally {
801
+ scratch.release();
802
+ }
803
+ const compiled = new XQuery(this, address, exports.sxml_javascript_query_is_updating(address) !== 0);
804
+ this.track(compiled, 'query', address);
805
+ return compiled;
806
+ }
807
+ /** Compiles an XSLT 4.0 stylesheet, with the modules it includes and
808
+ * imports (kind 'xslt-module') and the packages it uses (kind
809
+ * 'xslt-package'), for running it many times. */
810
+ compileStylesheet(stylesheet, options = {}) {
811
+ const exports = this.exports();
812
+ const state = this.enter();
813
+ const scratch = new Scratch(state);
814
+ const made = [];
815
+ let address;
816
+ try {
817
+ const request = scratch.words([
818
+ ...scratch.view(stylesheet),
819
+ ...scratch.view(options.baseUri ?? ''),
820
+ ...this.bindingWords(scratch, options.staticParameters, made),
821
+ ]);
822
+ address = exports.sxml_javascript_stylesheet_compile(state.address, request);
823
+ if (address === 0) {
824
+ throw this.failure();
825
+ }
826
+ }
827
+ finally {
828
+ scratch.release();
829
+ for (const value of made) {
830
+ value.dispose();
831
+ }
832
+ }
833
+ const compiled = new Stylesheet(this, address);
834
+ this.track(compiled, 'stylesheet', address);
835
+ return compiled;
836
+ }
837
+ /** Compiles an XSD 1.1 schema from one or more schema documents (a
838
+ * string is a document's text), with every document they include,
839
+ * import, redefine or override (the resolver is asked, kind
840
+ * 'schema-document'). Throws a SchemaError with every report when the
841
+ * schema has errors. */
842
+ compileSchema(documents, options = {}) {
843
+ const exports = this.exports();
844
+ const state = this.enter();
845
+ const address = exports.sxml_javascript_schema_create(state.address);
846
+ if (address === 0) {
847
+ throw outOfMemory();
848
+ }
849
+ const schema = new Schema(this, address);
850
+ this.track(schema, 'schema', address);
851
+ const scratch = new Scratch(state);
852
+ try {
853
+ const documentWords = [];
854
+ const list = Array.isArray(documents) ? documents : [documents];
855
+ for (const document of list) {
856
+ const { text, uri } = typeof document === 'string' ? { text: document, uri: '' } : document;
857
+ documentWords.push(...(text === undefined ? [0, 0] : scratch.view(text)), ...scratch.view(uri ?? ''));
858
+ }
859
+ const request = scratch.words([
860
+ documentWords.length > 0 ? scratch.words(documentWords) : 0,
861
+ list.length,
862
+ ...scratch.view(options.baseUri ?? ''),
863
+ 0,
864
+ 0,
865
+ ]);
866
+ const status = exports.sxml_javascript_schema_compile(address, request);
867
+ const reports = schemaReports(this.sideResults(request / 4 + 4));
868
+ if (status !== status_ok) {
869
+ const failure = this.failure();
870
+ throw failure instanceof SxmlError ? new SchemaError(failure, reports) : failure;
871
+ }
872
+ }
873
+ catch (exception) {
874
+ schema.dispose();
875
+ throw exception;
876
+ }
877
+ finally {
878
+ scratch.release();
879
+ }
880
+ return schema;
881
+ }
882
+ /** Converts JSON-like data to a value (see JsonData). */
883
+ value(data) {
884
+ if (data instanceof Value) {
885
+ return data;
886
+ }
887
+ const state = this.enter();
888
+ const scratch = new Scratch(state);
889
+ let text;
890
+ try {
891
+ const view = scratch.words(scratch.view(typeof data === 'string' ? data : JSON.stringify(data)));
892
+ text = this.adopt(state.module.exports.sxml_javascript_string(state.address, view));
893
+ }
894
+ finally {
895
+ scratch.release();
896
+ }
897
+ if (typeof data === 'string') {
898
+ return text;
899
+ }
900
+ try {
901
+ if (state.jsonExpression === 0) {
902
+ state.jsonExpression = this.compileAddress('parse-json($json)', {}, ['json']);
903
+ }
904
+ return this.evaluateAddress(state.jsonExpression, { variableValues: [text] });
905
+ }
906
+ finally {
907
+ text.dispose();
908
+ }
909
+ }
910
+ /** Serializes a value: by the adaptive method without options, else as
911
+ * fn:serialize with them (method xml unless they name another). */
912
+ serialize(value, options) {
913
+ this.enter();
914
+ this.check(value);
915
+ const optionsValue = this.serializationOptions(options);
916
+ try {
917
+ return this.serializeWith(value, optionsValue);
918
+ }
919
+ finally {
920
+ optionsValue?.dispose();
921
+ }
922
+ }
923
+ /** Serializes a value as serialize() does, writing the output to sink a
924
+ * chunk at a time instead of returning it (D294). */
925
+ serializeTo(value, sink, options) {
926
+ this.enter();
927
+ this.check(value);
928
+ const optionsValue = this.serializationOptions(options);
929
+ try {
930
+ this.serializeWith(value, optionsValue, sink);
931
+ }
932
+ finally {
933
+ optionsValue?.dispose();
934
+ }
935
+ }
936
+ /** Releases the processor and every value and expression made with it. */
937
+ dispose() {
938
+ this.state.module.untrack(this);
939
+ this.state.destroy();
940
+ }
941
+ /** The allocations the processor holds, for leak checks in tests; after
942
+ * dispose(), those that were left when it was destroyed (0 unless the
943
+ * package or sxml leaked). */
944
+ liveAllocationCount() {
945
+ if (this.state.address === 0) {
946
+ return this.state.leakedAllocationCount;
947
+ }
948
+ return this.state.module.exports.sxml_javascript_live_allocation_count(this.state.address);
949
+ }
950
+ // ----------------------------------------------------- For the package
951
+ /** @internal The state, checked usable. */
952
+ enter() {
953
+ if (this.state.address === 0) {
954
+ throw disposed('processor');
955
+ }
956
+ if (this.state.isInResolver) {
957
+ throw new Error('sxml: a resolver must not use its processor');
958
+ }
959
+ if (this.state.isInSink) {
960
+ throw new Error('sxml: an output sink or chunk source must not use its processor');
961
+ }
962
+ this.state.pendingException = undefined;
963
+ return this.state;
964
+ }
965
+ /** @internal Throws unless value belongs to this processor. */
966
+ check(value) {
967
+ if (value.processor !== this) {
968
+ throw new Error('sxml: the value belongs to another processor');
969
+ }
970
+ }
971
+ /** @internal Wraps the address an operation returned, or throws its
972
+ * failure. */
973
+ adopt(address) {
974
+ if (address === 0) {
975
+ throw this.failure();
976
+ }
977
+ this.state.live.set(address, 'value');
978
+ const value = new Value(this, address);
979
+ this.state.module.track(value, { processor: this.state, kind: 'value', address });
980
+ return value;
981
+ }
982
+ /** @internal Releases a value or expression made with this processor. */
983
+ releaseHandle(owner, kind, address) {
984
+ this.state.module.untrack(owner);
985
+ this.state.releaseHandle(kind, address);
986
+ }
987
+ /** @internal Compiles; returns the expression's address. */
988
+ compileAddress(expression, options, variables) {
989
+ const state = this.state;
990
+ const scratch = new Scratch(state);
991
+ try {
992
+ const namespaceWords = [];
993
+ for (const [prefix, uri] of state.staticNamespaces(options.namespaces)) {
994
+ namespaceWords.push(...scratch.view(prefix), ...scratch.view(uri));
995
+ }
996
+ const variableWords = [];
997
+ for (const name of variables) {
998
+ const [namespaceUri, localName] = splitName(name);
999
+ variableWords.push(...scratch.view(namespaceUri), ...scratch.view(localName));
1000
+ }
1001
+ const request = scratch.words([
1002
+ ...scratch.view(expression),
1003
+ ...scratch.view(options.baseUri ?? ''),
1004
+ namespaceWords.length > 0 ? scratch.words(namespaceWords) : 0,
1005
+ namespaceWords.length / 4,
1006
+ variableWords.length > 0 ? scratch.words(variableWords) : 0,
1007
+ variables.length,
1008
+ ]);
1009
+ const address = state.module.exports.sxml_javascript_compile(state.address, request);
1010
+ if (address === 0) {
1011
+ throw this.failure();
1012
+ }
1013
+ return address;
1014
+ }
1015
+ finally {
1016
+ scratch.release();
1017
+ }
1018
+ }
1019
+ /** @internal Evaluates the expression at address. */
1020
+ evaluateAddress(expression, request) {
1021
+ const state = this.enter();
1022
+ const scratch = new Scratch(state);
1023
+ try {
1024
+ const values = request.variableValues.map((value) => value?.address() ?? 0);
1025
+ const words = scratch.words([
1026
+ request.context?.address() ?? 0,
1027
+ values.length > 0 ? scratch.words(values) : 0,
1028
+ values.length,
1029
+ ]);
1030
+ return this.adopt(state.module.exports.sxml_javascript_evaluate(expression, words));
1031
+ }
1032
+ finally {
1033
+ scratch.release();
1034
+ }
1035
+ }
1036
+ /** @internal options as the map fn:serialize takes, keys in kebab
1037
+ * case; undefined for none. */
1038
+ serializationOptions(options) {
1039
+ if (options === undefined) {
1040
+ return undefined;
1041
+ }
1042
+ const parameters = {};
1043
+ for (const [key, parameter] of Object.entries(options)) {
1044
+ parameters[key.replace(/[A-Z]/g, (letter) => `-${letter.toLowerCase()}`)] = parameter;
1045
+ }
1046
+ return this.value(parameters);
1047
+ }
1048
+ serializeWith(value, options, sink) {
1049
+ const state = this.enter();
1050
+ const scratch = new Scratch(state);
1051
+ try {
1052
+ const request = scratch.words([value.address(), options?.address() ?? 0]);
1053
+ const status = this.streaming(new OutputRouter(sink), sink !== undefined, () => state.module.exports.sxml_javascript_serialize(state.address, request));
1054
+ if (status !== status_ok) {
1055
+ throw this.failure();
1056
+ }
1057
+ return sink === undefined ? this.output() : undefined;
1058
+ }
1059
+ finally {
1060
+ scratch.release();
1061
+ }
1062
+ }
1063
+ /** @internal Runs call, a call of the shim that serializes, with its
1064
+ * output written to router's sinks when streams is true (D294); ends
1065
+ * them as the call ends, failed when it returned failed (0 or a status
1066
+ * other than OK, as isFailure says) or threw. */
1067
+ streaming(router, streams, call, isFailure) {
1068
+ if (!streams) {
1069
+ return call();
1070
+ }
1071
+ const state = this.state;
1072
+ const exports = state.module.exports;
1073
+ exports.sxml_javascript_set_output(state.address, state.outputChunkByteCount);
1074
+ state.outputRouter = router;
1075
+ let result;
1076
+ try {
1077
+ result = call();
1078
+ }
1079
+ catch (exception) {
1080
+ router.finish(true, exception);
1081
+ throw exception;
1082
+ }
1083
+ finally {
1084
+ state.outputRouter = undefined;
1085
+ exports.sxml_javascript_set_output(state.address, 0);
1086
+ }
1087
+ const failed = isFailure !== undefined ? isFailure(result) : result !== status_ok;
1088
+ if (failed) {
1089
+ // The failure stays readable: failure() reads it, and the sinks are
1090
+ // aborted with it after the caller has.
1091
+ const reason = this.peekFailure();
1092
+ router.finish(true, reason);
1093
+ }
1094
+ else {
1095
+ router.finish(false);
1096
+ }
1097
+ return result;
1098
+ }
1099
+ /** @internal The last failure without taking the resolver's exception. */
1100
+ peekFailure() {
1101
+ if (this.state.pendingException !== undefined) {
1102
+ return this.state.pendingException;
1103
+ }
1104
+ return this.failureRecord();
1105
+ }
1106
+ /** @internal The text of the processor's last serialization. */
1107
+ output() {
1108
+ const module = this.state.module;
1109
+ const output = module.exports.sxml_javascript_output_of(this.state.address) / 4;
1110
+ const words = module.words();
1111
+ return module.text(words[output] ?? 0, words[output + 1] ?? 0);
1112
+ }
1113
+ /** @internal An input as a value of this processor; values it made are
1114
+ * pushed to made, for the caller to dispose. */
1115
+ input(data, made) {
1116
+ if (data instanceof Value) {
1117
+ this.check(data);
1118
+ return data;
1119
+ }
1120
+ const value = this.value(data);
1121
+ made.push(value);
1122
+ return value;
1123
+ }
1124
+ /** @internal The words of bindings (sxml_javascript_binding: name,
1125
+ * value), as a binding list's two words. */
1126
+ bindingWords(scratch, bindings, made) {
1127
+ const words = [];
1128
+ const entries = Object.entries(bindings ?? {});
1129
+ for (const [name, data] of entries) {
1130
+ words.push(...nameWords(scratch, name), this.input(data, made).address());
1131
+ }
1132
+ return [words.length > 0 ? scratch.words(words) : 0, entries.length];
1133
+ }
1134
+ /** @internal The module's exports. */
1135
+ exports() {
1136
+ return this.state.module.exports;
1137
+ }
1138
+ /** @internal Registers the handle of a compiled object. */
1139
+ track(owner, kind, address) {
1140
+ this.state.live.set(address, kind);
1141
+ this.state.module.track(owner, { processor: this.state, kind, address });
1142
+ }
1143
+ /** @internal Adopts a value handle that may be 0 (none). */
1144
+ adoptOptional(address) {
1145
+ return address === 0 ? undefined : this.adopt(address);
1146
+ }
1147
+ /** @internal The side results a call wrote at words[at], [at + 1]
1148
+ * (sxml_javascript_side_result_list), every value adopted. */
1149
+ sideResults(at) {
1150
+ const module = this.state.module;
1151
+ const list = module.words();
1152
+ const first = (list[at] ?? 0) / 4;
1153
+ const count = list[at + 1] ?? 0;
1154
+ const words = module.words().slice(first, first + count * 12);
1155
+ const results = [];
1156
+ for (let index = 0; index < count; index += 1) {
1157
+ const word = (offset) => words[index * 12 + offset] ?? 0;
1158
+ const text = (offset) => module.text(word(offset), word(offset + 1));
1159
+ results.push({
1160
+ kind: word(0),
1161
+ uri: text(1),
1162
+ text: text(3),
1163
+ code: text(5),
1164
+ // Every value is the package's now (sxml_javascript.h).
1165
+ first: this.adoptOptional(word(7)),
1166
+ second: this.adoptOptional(word(8)),
1167
+ lineNumber: word(9),
1168
+ columnNumber: word(10),
1169
+ isTerminating: word(11) !== 0,
1170
+ });
1171
+ }
1172
+ return results;
1173
+ }
1174
+ /** @internal Hands the MESSAGE side results to a callback. */
1175
+ deliverMessages(results, receive) {
1176
+ for (const result of results) {
1177
+ if (result.kind === side_result_message && receive !== undefined) {
1178
+ receive({
1179
+ text: result.text,
1180
+ code: result.code,
1181
+ isTerminating: result.isTerminating,
1182
+ sourceName: result.uri,
1183
+ lineNumber: result.lineNumber,
1184
+ columnNumber: result.columnNumber,
1185
+ });
1186
+ }
1187
+ }
1188
+ }
1189
+ /** @internal Whether the last operation failed: its error has a
1190
+ * status, or the resolver threw. */
1191
+ hasFailed() {
1192
+ const state = this.state;
1193
+ const at = state.module.exports.sxml_javascript_error_of(state.address) / 4;
1194
+ return state.pendingException !== undefined || (state.module.words()[at] ?? 0) !== 0;
1195
+ }
1196
+ /** @internal The last operation's failure, or the resolver's exception. */
1197
+ failure() {
1198
+ const state = this.state;
1199
+ if (state.pendingException !== undefined) {
1200
+ const exception = state.pendingException;
1201
+ state.pendingException = undefined;
1202
+ return exception;
1203
+ }
1204
+ return this.failureRecord();
1205
+ }
1206
+ /** @internal The processor's error as an SxmlError. */
1207
+ failureRecord() {
1208
+ const state = this.state;
1209
+ const module = state.module;
1210
+ const at = module.exports.sxml_javascript_error_of(state.address) / 4;
1211
+ const words = module.words().slice(at, at + 15);
1212
+ const word = (index) => words[index] ?? 0;
1213
+ const text = (index) => module.text(word(index), word(index + 1));
1214
+ return new SxmlError({
1215
+ status: text(1).replace(/^SXML_STATUS_/, ''),
1216
+ codeNamespaceUri: text(3),
1217
+ codeLocalName: text(5),
1218
+ codePrefix: text(7),
1219
+ description: text(9),
1220
+ sourceName: text(11),
1221
+ lineNumber: word(13),
1222
+ columnNumber: word(14),
1223
+ });
1224
+ }
1225
+ }
1226
+ // ------------------------------------------------------------ Expressions
1227
+ /** A compiled XPath 4.0 expression (include/sxml/xpath.h). */
1228
+ export class XPathExpression {
1229
+ processor;
1230
+ /** The external variables, in the order compile() was given them. */
1231
+ variables;
1232
+ handle;
1233
+ /** @internal Use Processor.compile(). */
1234
+ constructor(processor, address, variables) {
1235
+ this.processor = processor;
1236
+ this.handle = address;
1237
+ this.variables = [...variables];
1238
+ }
1239
+ /** Evaluates the expression; the result is a new value. */
1240
+ evaluate(options = {}) {
1241
+ if (this.handle === 0) {
1242
+ throw disposed('expression');
1243
+ }
1244
+ const made = [];
1245
+ const convert = (input) => {
1246
+ if (input === undefined) {
1247
+ return undefined;
1248
+ }
1249
+ if (input instanceof Value) {
1250
+ this.processor.check(input);
1251
+ return input;
1252
+ }
1253
+ const value = this.processor.value(input);
1254
+ made.push(value);
1255
+ return value;
1256
+ };
1257
+ try {
1258
+ const bindings = options.variables ?? {};
1259
+ return this.processor.evaluateAddress(this.handle, {
1260
+ context: convert(options.context),
1261
+ variableValues: this.variables.map((name) => Object.hasOwn(bindings, name) ? convert(bindings[name]) : undefined),
1262
+ });
1263
+ }
1264
+ finally {
1265
+ for (const value of made) {
1266
+ value.dispose();
1267
+ }
1268
+ }
1269
+ }
1270
+ dispose() {
1271
+ if (this.handle !== 0) {
1272
+ this.processor.releaseHandle(this, 'expression', this.handle);
1273
+ this.handle = 0;
1274
+ }
1275
+ }
1276
+ }
1277
+ // ---------------------------------------------------------------- XQuery
1278
+ /** A compiled XQuery 4.0 main module (include/sxml/xquery.h).
1279
+ * Processor.compileQuery makes it. */
1280
+ export class XQuery {
1281
+ processor;
1282
+ /** Whether its body is an updating expression (XQUF 3.0, 2.2): its
1283
+ * result is then empty and its changes go to options.updates. */
1284
+ isUpdating;
1285
+ handle;
1286
+ /** @internal Use Processor.compileQuery(). */
1287
+ constructor(processor, address, isUpdating) {
1288
+ this.processor = processor;
1289
+ this.handle = address;
1290
+ this.isUpdating = isUpdating;
1291
+ }
1292
+ /** Evaluates the query; the result is a new value. */
1293
+ evaluate(options = {}) {
1294
+ const processor = this.processor;
1295
+ const exports = processor.exports();
1296
+ const address = this.address();
1297
+ const state = processor.enter();
1298
+ const scratch = new Scratch(state);
1299
+ const made = [];
1300
+ let result = 0;
1301
+ let failure;
1302
+ let sideResults = [];
1303
+ try {
1304
+ const request = scratch.words([
1305
+ options.context === undefined ? 0 : processor.input(options.context, made).address(),
1306
+ ...processor.bindingWords(scratch, options.variables, made),
1307
+ options.updates?.putDocument === undefined ? 0 : 1,
1308
+ 0,
1309
+ 0,
1310
+ ]);
1311
+ result = exports.sxml_javascript_query_evaluate(address, request);
1312
+ // Read before a callback can use the processor.
1313
+ failure = result === 0 ? processor.failure() : undefined;
1314
+ sideResults = processor.sideResults(request / 4 + 4);
1315
+ }
1316
+ finally {
1317
+ scratch.release();
1318
+ for (const value of made) {
1319
+ value.dispose();
1320
+ }
1321
+ }
1322
+ const value = result === 0 ? undefined : processor.adopt(result);
1323
+ processor.deliverMessages(sideResults, options.messages);
1324
+ deliverUpdates(processor, sideResults, options.updates);
1325
+ if (value === undefined) {
1326
+ throw failure;
1327
+ }
1328
+ return value;
1329
+ }
1330
+ /** Serializes a value with the serialization parameters the query's
1331
+ * output declarations give (XQuery 4.0, 5.22: method xml unless they
1332
+ * name another). Value.serialize(options) uses options instead. */
1333
+ serialize(value) {
1334
+ this.serializeOutput(value, undefined);
1335
+ return this.processor.output();
1336
+ }
1337
+ /** Serializes a value as serialize() does, writing the output to sink a
1338
+ * chunk at a time instead of returning it (D294). */
1339
+ serializeTo(value, sink) {
1340
+ this.serializeOutput(value, sink);
1341
+ }
1342
+ /** Evaluates the query and serializes its result as serialize() does. */
1343
+ run(options = {}) {
1344
+ const result = this.evaluate(options);
1345
+ try {
1346
+ return this.serialize(result);
1347
+ }
1348
+ finally {
1349
+ result.dispose();
1350
+ }
1351
+ }
1352
+ /** Evaluates the query and writes its serialized result to sink a chunk
1353
+ * at a time, as serializeTo() does (D294). */
1354
+ runTo(sink, options = {}) {
1355
+ const result = this.evaluate(options);
1356
+ try {
1357
+ this.serializeTo(result, sink);
1358
+ }
1359
+ finally {
1360
+ result.dispose();
1361
+ }
1362
+ }
1363
+ serializeOutput(value, sink) {
1364
+ const processor = this.processor;
1365
+ const exports = processor.exports();
1366
+ processor.enter();
1367
+ processor.check(value);
1368
+ const address = this.address();
1369
+ const status = processor.streaming(new OutputRouter(sink), sink !== undefined, () => exports.sxml_javascript_query_serialize(address, value.address()));
1370
+ if (status !== status_ok) {
1371
+ throw processor.failure();
1372
+ }
1373
+ }
1374
+ dispose() {
1375
+ if (this.handle !== 0) {
1376
+ this.processor.releaseHandle(this, 'query', this.handle);
1377
+ this.handle = 0;
1378
+ }
1379
+ }
1380
+ address() {
1381
+ if (this.handle === 0) {
1382
+ throw disposed('query');
1383
+ }
1384
+ return this.handle;
1385
+ }
1386
+ }
1387
+ /** Hands UPDATED_TREE and PUT_DOCUMENT side results to the sink; disposes
1388
+ * what it does not take. */
1389
+ function deliverUpdates(processor, results, sink) {
1390
+ for (const result of results) {
1391
+ if (result.kind === side_result_updated_tree && result.first !== undefined && result.second !== undefined) {
1392
+ if (sink?.updatedTree !== undefined) {
1393
+ sink.updatedTree({ original: result.first, updated: result.second });
1394
+ }
1395
+ else {
1396
+ result.first.dispose();
1397
+ result.second.dispose();
1398
+ }
1399
+ }
1400
+ else if (result.kind === side_result_put_document && result.first !== undefined) {
1401
+ const node = result.first;
1402
+ const parameters = result.second;
1403
+ if (sink?.putDocument !== undefined) {
1404
+ sink.putDocument({
1405
+ uri: result.uri,
1406
+ node,
1407
+ parameters,
1408
+ serialize: () => {
1409
+ if (parameters !== undefined) {
1410
+ return processor.serializeWith(node, parameters);
1411
+ }
1412
+ const options = processor.value({});
1413
+ try {
1414
+ return processor.serializeWith(node, options);
1415
+ }
1416
+ finally {
1417
+ options.dispose();
1418
+ }
1419
+ },
1420
+ serializeTo: (sink) => {
1421
+ if (parameters !== undefined) {
1422
+ processor.serializeWith(node, parameters, sink);
1423
+ return;
1424
+ }
1425
+ const options = processor.value({});
1426
+ try {
1427
+ processor.serializeWith(node, options, sink);
1428
+ }
1429
+ finally {
1430
+ options.dispose();
1431
+ }
1432
+ },
1433
+ });
1434
+ }
1435
+ else {
1436
+ node.dispose();
1437
+ parameters?.dispose();
1438
+ }
1439
+ }
1440
+ }
1441
+ }
1442
+ // ------------------------------------------------------------------ XSLT
1443
+ /** A compiled XSLT 4.0 stylesheet (include/sxml/xslt.h).
1444
+ * Processor.compileStylesheet makes it. */
1445
+ export class Stylesheet {
1446
+ processor;
1447
+ handle;
1448
+ /** @internal Use Processor.compileStylesheet(). */
1449
+ constructor(processor, address) {
1450
+ this.processor = processor;
1451
+ this.handle = address;
1452
+ }
1453
+ /** Runs one transformation (XSLT 4.0, 2.3): applies templates to the
1454
+ * source, or calls options.initialTemplate or options.initialFunction. */
1455
+ transform(options = {}) {
1456
+ const processor = this.processor;
1457
+ const exports = processor.exports();
1458
+ const address = this.address();
1459
+ const state = processor.enter();
1460
+ const scratch = new Scratch(state);
1461
+ const made = [];
1462
+ const delivery = options.delivery ?? 'serialized';
1463
+ const resultDocumentDelivery = options.resultDocumentDelivery ?? 'serialized';
1464
+ if (options.output !== undefined && delivery !== 'serialized') {
1465
+ throw new Error("sxml: TransformOptions.output needs delivery 'serialized'");
1466
+ }
1467
+ if (options.streamedSource !== undefined &&
1468
+ (options.source !== undefined || options.initialMatchSelection !== undefined)) {
1469
+ throw new Error('sxml: TransformOptions.streamedSource is the initial match selection');
1470
+ }
1471
+ // With a sink, the serialized results are written in chunks (D294).
1472
+ const router = new OutputRouter(options.output, options.resultDocumentOutput);
1473
+ const streams = options.output !== undefined ||
1474
+ (options.resultDocumentOutput !== undefined && resultDocumentDelivery === 'serialized');
1475
+ let result = 0;
1476
+ let failure;
1477
+ let output;
1478
+ let sideResults = [];
1479
+ try {
1480
+ const input = (data) => data === undefined ? 0 : processor.input(data, made).address();
1481
+ const args = (options.args ?? []).map(input);
1482
+ const serialization = processor.serializationOptions(options.serialization);
1483
+ if (serialization !== undefined) {
1484
+ made.push(serialization);
1485
+ }
1486
+ const invocation = options.initialFunction !== undefined
1487
+ ? invocation_call_function
1488
+ : options.initialTemplate !== undefined ||
1489
+ (options.source === undefined &&
1490
+ options.initialMatchSelection === undefined &&
1491
+ options.streamedSource === undefined)
1492
+ ? invocation_call_template
1493
+ : invocation_apply_templates;
1494
+ const unnamedMode = options.initialMode === '#unnamed';
1495
+ const request = scratch.words([
1496
+ input(options.source),
1497
+ input(options.initialMatchSelection),
1498
+ ...processor.bindingWords(scratch, options.parameters, made),
1499
+ ...processor.bindingWords(scratch, options.templateParameters, made),
1500
+ ...processor.bindingWords(scratch, options.tunnelParameters, made),
1501
+ args.length > 0 ? scratch.words(args) : 0,
1502
+ args.length,
1503
+ ...scratch.view(options.baseOutputUri ?? ''),
1504
+ serialization?.address() ?? 0,
1505
+ ...nameWords(scratch, unnamedMode ? undefined : options.initialMode),
1506
+ ...nameWords(scratch, options.initialTemplate),
1507
+ ...nameWords(scratch, options.initialFunction),
1508
+ invocation,
1509
+ result_deliveries[delivery],
1510
+ result_deliveries[resultDocumentDelivery],
1511
+ unnamedMode ? 1 : 0,
1512
+ 0,
1513
+ 0,
1514
+ ...scratch.view(options.streamedSource ?? ''),
1515
+ ]);
1516
+ result = processor.streaming(router, streams, () => exports.sxml_javascript_stylesheet_transform(address, request), (made) => made === 0);
1517
+ // Read before a callback can use the processor.
1518
+ failure = result === 0 ? processor.failure() : undefined;
1519
+ if (result !== 0 && delivery === 'serialized' && options.output === undefined) {
1520
+ output = streams ? router.principalOutput() : processor.output();
1521
+ }
1522
+ sideResults = processor.sideResults(request / 4 + 29);
1523
+ }
1524
+ finally {
1525
+ scratch.release();
1526
+ for (const value of made) {
1527
+ value.dispose();
1528
+ }
1529
+ }
1530
+ const value = result === 0 ? undefined : processor.adopt(result);
1531
+ processor.deliverMessages(sideResults, options.messages);
1532
+ const resultDocuments = router.gathered.map((document) => ({
1533
+ uri: document.uri,
1534
+ output: document.output,
1535
+ value: undefined,
1536
+ }));
1537
+ for (const side of sideResults) {
1538
+ if (side.kind === side_result_result_document) {
1539
+ resultDocuments.push({
1540
+ uri: side.uri,
1541
+ output: side.first === undefined ? side.text : undefined,
1542
+ value: side.first,
1543
+ });
1544
+ }
1545
+ }
1546
+ if (value === undefined) {
1547
+ for (const document of resultDocuments) {
1548
+ document.value?.dispose();
1549
+ }
1550
+ throw failure;
1551
+ }
1552
+ if (delivery === 'serialized') {
1553
+ value.dispose();
1554
+ return { output, value: undefined, resultDocuments };
1555
+ }
1556
+ return { output: undefined, value, resultDocuments };
1557
+ }
1558
+ dispose() {
1559
+ if (this.handle !== 0) {
1560
+ this.processor.releaseHandle(this, 'stylesheet', this.handle);
1561
+ this.handle = 0;
1562
+ }
1563
+ }
1564
+ address() {
1565
+ if (this.handle === 0) {
1566
+ throw disposed('stylesheet');
1567
+ }
1568
+ return this.handle;
1569
+ }
1570
+ }
1571
+ // ------------------------------------------------------------------- XSD
1572
+ /** The SCHEMA_REPORT side results as reports. */
1573
+ function schemaReports(results) {
1574
+ return results
1575
+ .filter((result) => result.kind === side_result_schema_report)
1576
+ .map((result) => ({
1577
+ code: result.code,
1578
+ description: result.text,
1579
+ sourceName: result.uri,
1580
+ lineNumber: result.lineNumber,
1581
+ columnNumber: result.columnNumber,
1582
+ }));
1583
+ }
1584
+ /** A compiled XSD 1.1 schema (include/sxml/schema.h).
1585
+ * Processor.compileSchema makes it. */
1586
+ export class Schema {
1587
+ processor;
1588
+ handle;
1589
+ /** @internal Use Processor.compileSchema(). */
1590
+ constructor(processor, address) {
1591
+ this.processor = processor;
1592
+ this.handle = address;
1593
+ }
1594
+ /** Validates a document (XSD 1.1 Part 1, 5.2): XML text, parsed and
1595
+ * validated in one pass so that reports have its lines and columns, or
1596
+ * a document or element node of this processor. An invalid document is
1597
+ * not an exception: see the result's validity and reports. Text that
1598
+ * is not well-formed throws, as Processor.parse does. */
1599
+ validate(input, options = {}) {
1600
+ const processor = this.processor;
1601
+ const exports = processor.exports();
1602
+ const address = this.address();
1603
+ if (input instanceof Value) {
1604
+ processor.check(input);
1605
+ }
1606
+ const state = processor.enter();
1607
+ const scratch = new Scratch(state);
1608
+ let result = 0;
1609
+ let failure;
1610
+ let validity = 'invalid';
1611
+ let reports = [];
1612
+ try {
1613
+ const request = scratch.words([
1614
+ input instanceof Value ? input.address() : 0,
1615
+ ...(input instanceof Value ? [0, 0] : scratch.view(input)),
1616
+ ...scratch.view(options.uri ?? ''),
1617
+ options.mode === 'lax' ? 1 : 0,
1618
+ ...nameWords(scratch, options.type),
1619
+ 0,
1620
+ 0,
1621
+ 0,
1622
+ ]);
1623
+ result = exports.sxml_javascript_schema_validate(address, request);
1624
+ failure = result === 0 && processor.hasFailed() ? processor.failure() : undefined;
1625
+ validity = validities[state.module.words()[request / 4 + 10] ?? 1] ?? 'invalid';
1626
+ reports = schemaReports(processor.sideResults(request / 4 + 11));
1627
+ }
1628
+ finally {
1629
+ scratch.release();
1630
+ }
1631
+ if (failure !== undefined) {
1632
+ throw failure;
1633
+ }
1634
+ return { validity, reports, document: processor.adoptOptional(result) };
1635
+ }
1636
+ dispose() {
1637
+ if (this.handle !== 0) {
1638
+ this.processor.releaseHandle(this, 'schema', this.handle);
1639
+ this.handle = 0;
1640
+ }
1641
+ }
1642
+ address() {
1643
+ if (this.handle === 0) {
1644
+ throw disposed('schema');
1645
+ }
1646
+ return this.handle;
1647
+ }
1648
+ }
1649
+ // ----------------------------------------------------------------- Values
1650
+ /** An XDM value: a sequence of items in its processor (a parsed document,
1651
+ * an evaluation's result). */
1652
+ export class Value {
1653
+ processor;
1654
+ handle;
1655
+ /** @internal */
1656
+ constructor(processor, address) {
1657
+ this.processor = processor;
1658
+ this.handle = address;
1659
+ }
1660
+ /** @internal The handle, checked usable. */
1661
+ address() {
1662
+ if (this.handle === 0) {
1663
+ throw disposed('value');
1664
+ }
1665
+ return this.handle;
1666
+ }
1667
+ /** Serializes the value (Processor.serialize). */
1668
+ serialize(options) {
1669
+ return this.processor.serialize(this, options);
1670
+ }
1671
+ /** Serializes the value to sink a chunk at a time
1672
+ * (Processor.serializeTo). */
1673
+ serializeTo(sink, options) {
1674
+ this.processor.serializeTo(this, sink, options);
1675
+ }
1676
+ /** The value by the adaptive method: items one per line, strings
1677
+ * quoted, nodes as XML. */
1678
+ toString() {
1679
+ return this.processor.serialize(this);
1680
+ }
1681
+ dispose() {
1682
+ if (this.handle !== 0) {
1683
+ this.processor.releaseHandle(this, 'value', this.handle);
1684
+ this.handle = 0;
1685
+ }
1686
+ }
1687
+ }