beresta 0.0.0-stage → 2.1.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/LICENSE +21 -0
- package/README.md +55 -2
- package/examples/demo.mts +49 -0
- package/lib/errors.js +59 -0
- package/lib/factory.js +50 -0
- package/lib/flags.js +49 -0
- package/lib/index.d.ts +228 -0
- package/lib/index.js +38 -0
- package/lib/internal/bytes.js +35 -0
- package/lib/internal/keys.js +24 -0
- package/lib/internal/mixin.js +30 -0
- package/lib/internal/native.js +83 -0
- package/lib/internal/release.js +44 -0
- package/lib/languages.js +70 -0
- package/lib/nodes/document.js +57 -0
- package/lib/nodes/document_content.js +48 -0
- package/lib/nodes/element.js +55 -0
- package/lib/nodes/element_attributes.js +38 -0
- package/lib/nodes/node.js +25 -0
- package/lib/nodes/node_base.js +58 -0
- package/lib/nodes/node_children.js +49 -0
- package/lib/nodes/node_content.js +47 -0
- package/lib/nodes/node_editing.js +48 -0
- package/lib/nodes/node_navigation.js +46 -0
- package/lib/nodes/node_structure.js +51 -0
- package/lib/nodes/registry.js +121 -0
- package/lib/nodes/wrapping.js +55 -0
- package/lib/schema/diagnostics.js +50 -0
- package/lib/schema/schema.js +66 -0
- package/lib/schema/schema_lifecycle.js +35 -0
- package/lib/schema/schema_streaming.js +45 -0
- package/lib/xpath/xpath.js +68 -0
- package/lib/xpath/xpath_context.js +33 -0
- package/lib/xpath/xpath_evaluation.js +69 -0
- package/lib/xpath/xpath_scalars.js +34 -0
- package/native/linux-aarch64/beresta.node +0 -0
- package/native/linux-x86_64/beresta.node +0 -0
- package/native/macos-aarch64/beresta.node +0 -0
- package/native/macos-x86_64/beresta.node +0 -0
- package/native/windows-aarch64/beresta.node +0 -0
- package/native/windows-x86_64/beresta.node +0 -0
- package/package.json +37 -4
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const { native } = require('../internal/native.js');
|
|
4
|
+
const { REGISTRY } = require('../internal/keys.js');
|
|
5
|
+
const { wrap } = require('./wrapping.js');
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Примесь: удаление, копирование и перенос поддерева.
|
|
9
|
+
* Mixin: removing, copying and moving a subtree.
|
|
10
|
+
*/
|
|
11
|
+
class NodeStructure
|
|
12
|
+
{
|
|
13
|
+
/** Удаление узла с потомками. После вызова эта обёртка и обёртки потомков
|
|
14
|
+
* недействительны — обращаться к ним нельзя.
|
|
15
|
+
* Removes the node with its descendants. After the call this wrapper and the
|
|
16
|
+
* wrappers of its descendants are invalid — they must not be used. */
|
|
17
|
+
remove()
|
|
18
|
+
{
|
|
19
|
+
native.node_remove(this.handle);
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/** Глубокая копия в конец детей parent (можно в другой документ); возвращает копию.
|
|
23
|
+
* A deep copy appended to the children of parent (another document is allowed); returns the copy. */
|
|
24
|
+
copyTo(parent)
|
|
25
|
+
{
|
|
26
|
+
return wrap(parent.document, native.node_copy_to(this.handle, parent.handle));
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** Перенос (без копирования) в конец детей parent, в том числе в другой документ.
|
|
30
|
+
* Эта обёртка остаётся тем же узлом; после переноса её документ (OWNER) —
|
|
31
|
+
* parent.document, и закрытие прежнего документа узел не затрагивает. Обёртки
|
|
32
|
+
* потомков, полученные раньше, тоже переходят к новому документу. Корень
|
|
33
|
+
* документа и сам документ переносить нельзя (HIERARCHY_VIOLATION / INVALID_ARGUMENT).
|
|
34
|
+
* Moves the node (without copying) to the end of the children of parent, including
|
|
35
|
+
* into another document. This wrapper stays the same node; after the move its document
|
|
36
|
+
* (OWNER) is parent.document, and closing the former document does not affect the node.
|
|
37
|
+
* The wrappers of descendants obtained earlier move to the new document too. The
|
|
38
|
+
* document root and the document itself cannot be moved (HIERARCHY_VIOLATION / INVALID_ARGUMENT). */
|
|
39
|
+
moveTo(parent)
|
|
40
|
+
{
|
|
41
|
+
const source = this.document;
|
|
42
|
+
const target = parent.document;
|
|
43
|
+
const handle = this.handle;
|
|
44
|
+
|
|
45
|
+
native.node_move_to(handle, parent.handle);
|
|
46
|
+
if (source !== target)
|
|
47
|
+
source[REGISTRY].transfer(this, handle, target);
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
module.exports = { NodeStructure };
|
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const { native } = require('../internal/native.js');
|
|
4
|
+
const { OWNER, REGISTRY } = require('../internal/keys.js');
|
|
5
|
+
|
|
6
|
+
// Минимальный размер, с которого начинается чистка / The minimal size the sweep starts from
|
|
7
|
+
const MINIMAL_SWEEP_SIZE = 64;
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* Реестр обёрток одного документа: нативный дескриптор узла → его
|
|
11
|
+
* единственная обёртка (паттерн Identity Map). Зачем он нужен: при переносе
|
|
12
|
+
* узла в другой документ (moveTo) у ВСЕХ уже выданных обёрток этого узла и
|
|
13
|
+
* его потомков должен смениться документ-владелец (символ OWNER). Иначе
|
|
14
|
+
* обёртка, полученная до переноса, проверяла бы «жив ли документ» по
|
|
15
|
+
* старому документу и после закрытия нового обратилась бы к освобождённой
|
|
16
|
+
* памяти — процесс упал бы.
|
|
17
|
+
*
|
|
18
|
+
* Реестр хранит WeakRef и не продлевает жизнь обёрткам; записи умерших
|
|
19
|
+
* обёрток вычищаются, когда реестр вырастает вдвое. Запись об удалённом узле
|
|
20
|
+
* может пережить его (дескриптор достанется новому узлу), поэтому вместе
|
|
21
|
+
* с обёрткой хранится её вид — элемент или нет — и сверяется при поиске.
|
|
22
|
+
*
|
|
23
|
+
* The wrapper registry of one document: the native node handle → its only
|
|
24
|
+
* wrapper (the Identity Map pattern). Why it is needed: when a node is moved into
|
|
25
|
+
* another document (moveTo), ALL wrappers already handed out for this node and
|
|
26
|
+
* its descendants must change their owner document (the OWNER symbol). Otherwise
|
|
27
|
+
* a wrapper obtained before the move would check "is the document alive" against
|
|
28
|
+
* the old document and, after the new one is closed, would access freed memory —
|
|
29
|
+
* the process would crash.
|
|
30
|
+
*
|
|
31
|
+
* The registry keeps WeakRef and does not extend the life of wrappers; the entries
|
|
32
|
+
* of dead wrappers are swept out when the registry doubles. The entry of a removed
|
|
33
|
+
* node may outlive it (the handle goes to a new node), so the wrapper kind — an
|
|
34
|
+
* element or not — is kept with the wrapper and compared on lookup.
|
|
35
|
+
*/
|
|
36
|
+
class NodeRegistry
|
|
37
|
+
{
|
|
38
|
+
constructor()
|
|
39
|
+
{
|
|
40
|
+
this.wrappers = new Map();
|
|
41
|
+
this.sweepAt = MINIMAL_SWEEP_SIZE;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** Живая обёртка узла нужного вида или null. / A live wrapper of the node of the required kind or null. */
|
|
45
|
+
find(handle, element)
|
|
46
|
+
{
|
|
47
|
+
const entry = this.wrappers.get(handle);
|
|
48
|
+
|
|
49
|
+
if (entry === undefined || entry.element !== element)
|
|
50
|
+
return null;
|
|
51
|
+
const node = entry.ref.deref();
|
|
52
|
+
if (node === undefined)
|
|
53
|
+
return null;
|
|
54
|
+
return node;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** Запоминание обёртки; при достижении порога — чистка умерших записей
|
|
58
|
+
* (порог становится вдвое больше оставшегося, в среднем O(1) на вставку).
|
|
59
|
+
* Remembers a wrapper; on reaching the threshold the dead entries are swept
|
|
60
|
+
* (the threshold becomes twice the rest, O(1) per insertion on average). */
|
|
61
|
+
store(handle, node, element)
|
|
62
|
+
{
|
|
63
|
+
this.wrappers.set(handle, { ref: new WeakRef(node), element });
|
|
64
|
+
if (this.wrappers.size < this.sweepAt)
|
|
65
|
+
return;
|
|
66
|
+
for (const [key, entry] of this.wrappers)
|
|
67
|
+
{
|
|
68
|
+
if (entry.ref.deref() === undefined)
|
|
69
|
+
this.wrappers.delete(key);
|
|
70
|
+
}
|
|
71
|
+
this.sweepAt = Math.max(MINIMAL_SWEEP_SIZE, this.wrappers.size * 2);
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/** Передача обёрток перенесённого поддерева документу target (и самой
|
|
75
|
+
* обёртки moved). Узлы уже живут в target, поэтому обход нативного
|
|
76
|
+
* поддерева безопасен; обход итеративный (явный стек). Если в реестре нет
|
|
77
|
+
* никого, кроме корня поддерева, обходить потомков незачем.
|
|
78
|
+
* Hands the wrappers of the moved subtree over to the target document (and the
|
|
79
|
+
* moved wrapper itself). The nodes already live in target, so walking the native
|
|
80
|
+
* subtree is safe; the walk is iterative (an explicit stack). If the registry
|
|
81
|
+
* holds nobody but the subtree root, there is no need to walk the descendants. */
|
|
82
|
+
transfer(moved, root, target)
|
|
83
|
+
{
|
|
84
|
+
const deep = this.wrappers.size > 1;
|
|
85
|
+
const pending = [root];
|
|
86
|
+
|
|
87
|
+
moved[OWNER] = target;
|
|
88
|
+
while (pending.length > 0)
|
|
89
|
+
{
|
|
90
|
+
const current = pending.pop();
|
|
91
|
+
let child = null;
|
|
92
|
+
|
|
93
|
+
this.adopt(current, target);
|
|
94
|
+
if (deep)
|
|
95
|
+
child = native.node_first_child(current);
|
|
96
|
+
while (child !== null)
|
|
97
|
+
{
|
|
98
|
+
pending.push(child);
|
|
99
|
+
child = native.node_next_sibling(child);
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/** Передача одной обёртки (если она ещё жива) реестру документа target.
|
|
105
|
+
* Hands one wrapper (if it is still alive) over to the registry of the target document. */
|
|
106
|
+
adopt(handle, target)
|
|
107
|
+
{
|
|
108
|
+
const entry = this.wrappers.get(handle);
|
|
109
|
+
|
|
110
|
+
if (entry === undefined)
|
|
111
|
+
return;
|
|
112
|
+
this.wrappers.delete(handle);
|
|
113
|
+
const node = entry.ref.deref();
|
|
114
|
+
if (node === undefined)
|
|
115
|
+
return;
|
|
116
|
+
node[OWNER] = target;
|
|
117
|
+
target[REGISTRY].store(handle, node, entry.element);
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
module.exports = { NodeRegistry };
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
/*
|
|
4
|
+
* Фабрика объектов-обёрток для дескрипторов узлов (паттерн Factory Method).
|
|
5
|
+
* Си-интерфейс отдаёт «голый» дескриптор; по типу узла выбирается класс:
|
|
6
|
+
* XmlElement для элементов, сам документ для дескриптора документа,
|
|
7
|
+
* XmlNode для остальных узлов. Классы регистрируются из element.js:
|
|
8
|
+
* так нет циклического require между узлом, его примесями и фабрикой.
|
|
9
|
+
* Уже выданная живая обёртка того же узла возвращается повторно (реестр
|
|
10
|
+
* документа, паттерн Identity Map, см. registry.js): у узла одна обёртка.
|
|
11
|
+
*
|
|
12
|
+
* The factory of wrapper objects for node handles (the Factory Method pattern).
|
|
13
|
+
* The C interface returns a "bare" handle; the class is chosen by the node type:
|
|
14
|
+
* XmlElement for elements, the document itself for the document handle,
|
|
15
|
+
* XmlNode for other nodes. The classes are registered from element.js:
|
|
16
|
+
* so there is no circular require between a node, its mixins and the factory.
|
|
17
|
+
* A live wrapper already handed out for the same node is returned again (the
|
|
18
|
+
* document registry, the Identity Map pattern, see registry.js): one node, one wrapper.
|
|
19
|
+
*/
|
|
20
|
+
|
|
21
|
+
const { native } = require('../internal/native.js');
|
|
22
|
+
const { HANDLE, REGISTRY } = require('../internal/keys.js');
|
|
23
|
+
const { NodeType } = require('../flags.js');
|
|
24
|
+
|
|
25
|
+
// Зарегистрированные классы узлов / The registered node classes
|
|
26
|
+
const classes = { node: null, element: null };
|
|
27
|
+
|
|
28
|
+
// Регистрация классов (вызывается один раз из element.js) / Registers the classes (called once from element.js)
|
|
29
|
+
function registerNodeClasses(nodeClass, elementClass)
|
|
30
|
+
{
|
|
31
|
+
classes.node = nodeClass;
|
|
32
|
+
classes.element = elementClass;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
// Обёртка для дескриптора узла документа document (null -> null)
|
|
36
|
+
// A wrapper for a node handle of the document document (null -> null)
|
|
37
|
+
function wrap(document, handle)
|
|
38
|
+
{
|
|
39
|
+
if (handle === null)
|
|
40
|
+
return null;
|
|
41
|
+
if (handle === document[HANDLE])
|
|
42
|
+
return document;
|
|
43
|
+
const element = native.node_type(handle) === NodeType.ELEMENT;
|
|
44
|
+
let node = document[REGISTRY].find(handle, element);
|
|
45
|
+
if (node !== null)
|
|
46
|
+
return node;
|
|
47
|
+
if (element)
|
|
48
|
+
node = new classes.element(document, handle);
|
|
49
|
+
else
|
|
50
|
+
node = new classes.node(document, handle);
|
|
51
|
+
document[REGISTRY].store(handle, node, element);
|
|
52
|
+
return node;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
module.exports = { registerNodeClasses, wrap };
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const { native } = require('../internal/native.js');
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Одно нарушение схемы: текст начинается с пути к элементу
|
|
7
|
+
* ("/catalog/book[2]: ..."), line и column — место в исходнике (0 — неизвестно).
|
|
8
|
+
*
|
|
9
|
+
* One schema violation: the text starts with the element path
|
|
10
|
+
* ("/catalog/book[2]: ..."), line and column are the place in the source (0 — unknown).
|
|
11
|
+
*/
|
|
12
|
+
class Diagnostic
|
|
13
|
+
{
|
|
14
|
+
constructor(message, line, column)
|
|
15
|
+
{
|
|
16
|
+
this.message = message;
|
|
17
|
+
this.line = line;
|
|
18
|
+
this.column = column;
|
|
19
|
+
Object.freeze(this);
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/*
|
|
24
|
+
* Чтение нативного списка нарушений в массив; список освобождается в
|
|
25
|
+
* finally — даже если чтение прервало исключение.
|
|
26
|
+
*
|
|
27
|
+
* Reads the native list of violations into an array; the list is freed in
|
|
28
|
+
* finally — even if reading was interrupted by an exception.
|
|
29
|
+
*/
|
|
30
|
+
function readDiagnostics(list)
|
|
31
|
+
{
|
|
32
|
+
const result = [];
|
|
33
|
+
|
|
34
|
+
try
|
|
35
|
+
{
|
|
36
|
+
const count = native.diagnostics_count(list);
|
|
37
|
+
for (let index = 0; index < count; ++index)
|
|
38
|
+
{
|
|
39
|
+
result.push(new Diagnostic(native.diagnostics_message(list, index),
|
|
40
|
+
native.diagnostics_line(list, index), native.diagnostics_column(list, index)));
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
finally
|
|
44
|
+
{
|
|
45
|
+
native.diagnostics_free(list);
|
|
46
|
+
}
|
|
47
|
+
return result;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
module.exports = { Diagnostic, readDiagnostics };
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const { native } = require('../internal/native.js');
|
|
4
|
+
const { HANDLE } = require('../internal/keys.js');
|
|
5
|
+
const { track } = require('../internal/release.js');
|
|
6
|
+
const { toBytes } = require('../internal/bytes.js');
|
|
7
|
+
const { applyMixins } = require('../internal/mixin.js');
|
|
8
|
+
const { BerestaClosedError } = require('../errors.js');
|
|
9
|
+
const { messageText, Messages } = require('../languages.js');
|
|
10
|
+
const { readDiagnostics } = require('./diagnostics.js');
|
|
11
|
+
const { SchemaLifecycle } = require('./schema_lifecycle.js');
|
|
12
|
+
const { SchemaStreaming } = require('./schema_streaming.js');
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* Загруженная XML Schema. Неизменяема после загрузки: одну схему можно
|
|
16
|
+
* использовать для множества документов — и при разборе (parse с
|
|
17
|
+
* options.schema), и отдельной проверкой validate. Потоковая проверка без
|
|
18
|
+
* дерева — validateBytes / validateFile (schema_streaming.js).
|
|
19
|
+
*
|
|
20
|
+
* A loaded XML Schema. Immutable after loading: one schema can be used for
|
|
21
|
+
* many documents — both during parsing (parse with options.schema) and
|
|
22
|
+
* as a separate validate check. Streaming validation without a tree is
|
|
23
|
+
* validateBytes / validateFile (schema_streaming.js).
|
|
24
|
+
*/
|
|
25
|
+
class Schema
|
|
26
|
+
{
|
|
27
|
+
/** Создаётся фабриками fromString / fromFile. / Created by the fromString / fromFile factories. */
|
|
28
|
+
constructor(handle)
|
|
29
|
+
{
|
|
30
|
+
this[HANDLE] = handle;
|
|
31
|
+
track(this, 'schema_free', handle);
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** Схема из текста или байтов XSD (xs:include здесь недоступен — нет каталога).
|
|
35
|
+
* A schema from XSD text or bytes (xs:include is unavailable here — there is no directory). */
|
|
36
|
+
static fromString(input)
|
|
37
|
+
{
|
|
38
|
+
return new Schema(native.schema_load(toBytes(input, 'Schema.fromString')));
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** Схема из файла; xs:include / xs:import ищутся рядом с ним.
|
|
42
|
+
* A schema from a file; xs:include / xs:import are looked up next to it. */
|
|
43
|
+
static fromFile(path)
|
|
44
|
+
{
|
|
45
|
+
return new Schema(native.schema_load_file(String(path)));
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/** Дескриптор; BerestaClosedError, если схема уже закрыта. / The handle; BerestaClosedError if the schema is closed. */
|
|
49
|
+
get handle()
|
|
50
|
+
{
|
|
51
|
+
if (this[HANDLE] === null)
|
|
52
|
+
throw new BerestaClosedError(messageText(Messages.SCHEMA_CLOSED));
|
|
53
|
+
return this[HANDLE];
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** Все нарушения за один проход; пустой массив — документ корректен.
|
|
57
|
+
* All violations in one pass; an empty array means the document is valid. */
|
|
58
|
+
validate(document)
|
|
59
|
+
{
|
|
60
|
+
return readDiagnostics(native.schema_validate(this.handle, document.handle));
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
applyMixins(Schema, SchemaLifecycle, SchemaStreaming);
|
|
65
|
+
|
|
66
|
+
module.exports = { Schema };
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const { HANDLE } = require('../internal/keys.js');
|
|
4
|
+
const { release } = require('../internal/release.js');
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Примесь схемы: закрытие и поддержка `using`.
|
|
8
|
+
* A schema mixin: closing and `using` support.
|
|
9
|
+
*/
|
|
10
|
+
class SchemaLifecycle
|
|
11
|
+
{
|
|
12
|
+
/** true после close(). / true after close(). */
|
|
13
|
+
get closed()
|
|
14
|
+
{
|
|
15
|
+
return this[HANDLE] === null;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/** Освобождение нативной памяти; повторный вызов безопасен. / Releases the native memory; calling it again is safe. */
|
|
19
|
+
close()
|
|
20
|
+
{
|
|
21
|
+
if (this[HANDLE] === null)
|
|
22
|
+
return;
|
|
23
|
+
const handle = this[HANDLE];
|
|
24
|
+
this[HANDLE] = null;
|
|
25
|
+
release(this, 'schema_free', handle);
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/** Поддержка `using`. / Support for `using`. */
|
|
29
|
+
[Symbol.dispose]()
|
|
30
|
+
{
|
|
31
|
+
this.close();
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
module.exports = { SchemaLifecycle };
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const { native } = require('../internal/native.js');
|
|
4
|
+
const { toBytes } = require('../internal/bytes.js');
|
|
5
|
+
const { ParseFlags } = require('../flags.js');
|
|
6
|
+
const { readDiagnostics } = require('./diagnostics.js');
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* Примесь схемы: потоковая проверка без построения дерева (SAX + XSD внутри
|
|
10
|
+
* ядра). Память — O(глубины документа) плюс значения ID и таблицы ключей;
|
|
11
|
+
* файл отображается в память, а не копируется. Так проверяются выгрузки в
|
|
12
|
+
* гигабайты, и это быстрее, чем parse + validate: дерево не строится вовсе.
|
|
13
|
+
* Нарушения схемы возвращаются массивом, синтаксическая ошибка XML —
|
|
14
|
+
* исключение BerestaError (PARSE_ERROR).
|
|
15
|
+
*
|
|
16
|
+
* A schema mixin: streaming validation without building a tree (SAX + XSD inside
|
|
17
|
+
* the core). The memory is O(document depth) plus ID values and key tables;
|
|
18
|
+
* the file is mapped into memory, not copied. This is how exports of gigabytes
|
|
19
|
+
* are validated, and it is faster than parse + validate: no tree is built at all.
|
|
20
|
+
* Schema violations are returned as an array, an XML syntax error is a
|
|
21
|
+
* BerestaError (PARSE_ERROR).
|
|
22
|
+
*/
|
|
23
|
+
class SchemaStreaming
|
|
24
|
+
{
|
|
25
|
+
/** Проверка XML из памяти (строка, Buffer или Uint8Array); options.flags — ParseFlags.
|
|
26
|
+
* Validates XML from memory (a string, a Buffer or a Uint8Array); options.flags are ParseFlags. */
|
|
27
|
+
validateBytes(input, options = {})
|
|
28
|
+
{
|
|
29
|
+
const bytes = toBytes(input, 'Schema.validateBytes');
|
|
30
|
+
const flags = options.flags ?? ParseFlags.DEFAULT;
|
|
31
|
+
|
|
32
|
+
return readDiagnostics(native.schema_validate_bytes(bytes, flags, this.handle));
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** Проверка файла; ParseFlags.FILE_RESOURCES разрешает внешние DTD рядом с ним.
|
|
36
|
+
* Validates a file; ParseFlags.FILE_RESOURCES allows external DTDs next to it. */
|
|
37
|
+
validateFile(path, options = {})
|
|
38
|
+
{
|
|
39
|
+
const flags = options.flags ?? ParseFlags.DEFAULT;
|
|
40
|
+
|
|
41
|
+
return readDiagnostics(native.schema_validate_file(String(path), flags, this.handle));
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
module.exports = { SchemaStreaming };
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const { native } = require('../internal/native.js');
|
|
4
|
+
const { HANDLE } = require('../internal/keys.js');
|
|
5
|
+
const { track, release } = require('../internal/release.js');
|
|
6
|
+
const { applyMixins } = require('../internal/mixin.js');
|
|
7
|
+
const { BerestaClosedError } = require('../errors.js');
|
|
8
|
+
const { messageText, Messages } = require('../languages.js');
|
|
9
|
+
const { XPathContext } = require('./xpath_context.js');
|
|
10
|
+
const { XPathEvaluation } = require('./xpath_evaluation.js');
|
|
11
|
+
const { XPathScalars } = require('./xpath_scalars.js');
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* Скомпилированное выражение XPath 1.0. Компилируется один раз, вычисляется
|
|
15
|
+
* сколько угодно раз для разных узлов и документов. Префиксы и переменные
|
|
16
|
+
* задаются в конструкторе или позже (bindNamespace, set).
|
|
17
|
+
* new XPath('//s:item[@code = $c]', { namespaces: { s: 'urn:shop' }, variables: { c: 'B2' } })
|
|
18
|
+
*
|
|
19
|
+
* A compiled XPath 1.0 expression. It is compiled once and evaluated any number
|
|
20
|
+
* of times for different nodes and documents. Prefixes and variables are set
|
|
21
|
+
* in the constructor or later (bindNamespace, set).
|
|
22
|
+
*/
|
|
23
|
+
class XPath
|
|
24
|
+
{
|
|
25
|
+
constructor(expression, options = {})
|
|
26
|
+
{
|
|
27
|
+
this[HANDLE] = native.xpath_compile(expression);
|
|
28
|
+
track(this, 'xpath_free', this[HANDLE]);
|
|
29
|
+
for (const [prefix, uri] of Object.entries(options.namespaces ?? {}))
|
|
30
|
+
this.bindNamespace(prefix, uri);
|
|
31
|
+
for (const [name, value] of Object.entries(options.variables ?? {}))
|
|
32
|
+
this.set(name, value);
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** Дескриптор; BerestaClosedError, если выражение уже закрыто. / The handle; BerestaClosedError if the expression is closed. */
|
|
36
|
+
get handle()
|
|
37
|
+
{
|
|
38
|
+
if (this[HANDLE] === null)
|
|
39
|
+
throw new BerestaClosedError(messageText(Messages.XPATH_CLOSED));
|
|
40
|
+
return this[HANDLE];
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** true после close(). / true after close(). */
|
|
44
|
+
get closed()
|
|
45
|
+
{
|
|
46
|
+
return this[HANDLE] === null;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** Освобождение нативной памяти; повторный вызов безопасен. / Releases the native memory; calling it again is safe. */
|
|
50
|
+
close()
|
|
51
|
+
{
|
|
52
|
+
if (this[HANDLE] === null)
|
|
53
|
+
return;
|
|
54
|
+
const handle = this[HANDLE];
|
|
55
|
+
this[HANDLE] = null;
|
|
56
|
+
release(this, 'xpath_free', handle);
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** Поддержка `using`. / Support for `using`. */
|
|
60
|
+
[Symbol.dispose]()
|
|
61
|
+
{
|
|
62
|
+
this.close();
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
applyMixins(XPath, XPathContext, XPathEvaluation, XPathScalars);
|
|
67
|
+
|
|
68
|
+
module.exports = { XPath };
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const { native } = require('../internal/native.js');
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Примесь XPath: контекст выражения — префиксы пространств имён и
|
|
7
|
+
* переменные $name. Методы возвращают само выражение — удобно цепочкой.
|
|
8
|
+
*
|
|
9
|
+
* An XPath mixin: the expression context — namespace prefixes and $name
|
|
10
|
+
* variables. The methods return the expression itself — handy for chaining.
|
|
11
|
+
*/
|
|
12
|
+
class XPathContext
|
|
13
|
+
{
|
|
14
|
+
/** Префикс для имён p:name в выражении. / A prefix for p:name names in the expression. */
|
|
15
|
+
bindNamespace(prefix, uri)
|
|
16
|
+
{
|
|
17
|
+
native.xpath_bind_namespace(this.handle, prefix, uri);
|
|
18
|
+
return this;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/** Переменная $name: число остаётся числом, остальное становится строкой.
|
|
22
|
+
* The $name variable: a number stays a number, everything else becomes a string. */
|
|
23
|
+
set(name, value)
|
|
24
|
+
{
|
|
25
|
+
if (typeof value === 'number')
|
|
26
|
+
native.xpath_set_number(this.handle, name, value);
|
|
27
|
+
else
|
|
28
|
+
native.xpath_set_string(this.handle, name, String(value));
|
|
29
|
+
return this;
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
module.exports = { XPathContext };
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const { native } = require('../internal/native.js');
|
|
4
|
+
const { wrap } = require('../nodes/wrapping.js');
|
|
5
|
+
|
|
6
|
+
/*
|
|
7
|
+
* Результат beresta_xpath_select читается внутри одного вызова: элементы
|
|
8
|
+
* копируются в массив JavaScript, а нативный набор освобождается в finally —
|
|
9
|
+
* даже если чтение прервало исключение.
|
|
10
|
+
*
|
|
11
|
+
* The result of beresta_xpath_select is read within one call: the items are
|
|
12
|
+
* copied into a JavaScript array, and the native set is freed in finally —
|
|
13
|
+
* even if reading was interrupted by an exception.
|
|
14
|
+
*/
|
|
15
|
+
function readNodeSet(xpath, context, readValues)
|
|
16
|
+
{
|
|
17
|
+
const nodeset = native.xpath_select(xpath.handle, context.handle);
|
|
18
|
+
const result = [];
|
|
19
|
+
|
|
20
|
+
try
|
|
21
|
+
{
|
|
22
|
+
const size = native.nodeset_size(nodeset);
|
|
23
|
+
for (let index = 0; index < size; ++index)
|
|
24
|
+
{
|
|
25
|
+
if (readValues)
|
|
26
|
+
result.push(native.nodeset_value(nodeset, index));
|
|
27
|
+
else
|
|
28
|
+
appendNode(result, wrap(context.document, native.nodeset_node(nodeset, index)));
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
finally
|
|
32
|
+
{
|
|
33
|
+
native.nodeset_free(nodeset);
|
|
34
|
+
}
|
|
35
|
+
return result;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
// Узел попадает в результат, если это узел DOM (у атрибута узла нет)
|
|
39
|
+
// A node goes into the result if it is a DOM node (an attribute has no node)
|
|
40
|
+
function appendNode(result, node)
|
|
41
|
+
{
|
|
42
|
+
if (node !== null)
|
|
43
|
+
result.push(node);
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* Примесь XPath: вычисление относительно узла или документа.
|
|
48
|
+
* An XPath mixin: evaluation relative to a node or a document.
|
|
49
|
+
*/
|
|
50
|
+
class XPathEvaluation
|
|
51
|
+
{
|
|
52
|
+
/** Узлы результата в порядке документа. Атрибуты в DOM «Берёсты» — не узлы;
|
|
53
|
+
* их значения возвращает selectValues.
|
|
54
|
+
* The result nodes in document order. Attributes in the Beresta DOM are not nodes;
|
|
55
|
+
* selectValues returns their values. */
|
|
56
|
+
select(context)
|
|
57
|
+
{
|
|
58
|
+
return readNodeSet(this, context, false);
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** Строковые значения всех элементов результата, включая атрибуты.
|
|
62
|
+
* The string values of all result items, attributes included. */
|
|
63
|
+
selectValues(context)
|
|
64
|
+
{
|
|
65
|
+
return readNodeSet(this, context, true);
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
module.exports = { XPathEvaluation };
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const { native } = require('../internal/native.js');
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Примесь XPath: результат как строка, число или логическое значение —
|
|
7
|
+
* по правилам функций string(), number(), boolean() XPath 1.0.
|
|
8
|
+
*
|
|
9
|
+
* An XPath mixin: the result as a string, a number or a boolean —
|
|
10
|
+
* by the rules of the XPath 1.0 string(), number(), boolean() functions.
|
|
11
|
+
*/
|
|
12
|
+
class XPathScalars
|
|
13
|
+
{
|
|
14
|
+
/** Результат по правилам функции string(). / The result by the rules of the string() function. */
|
|
15
|
+
string(context)
|
|
16
|
+
{
|
|
17
|
+
return native.xpath_string(this.handle, context.handle);
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/** Результат по правилам функции number(); NaN — не ошибка, а законный ответ.
|
|
21
|
+
* The result by the rules of the number() function; NaN is not an error but a legitimate answer. */
|
|
22
|
+
number(context)
|
|
23
|
+
{
|
|
24
|
+
return native.xpath_number(this.handle, context.handle);
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** Результат по правилам функции boolean(). / The result by the rules of the boolean() function. */
|
|
28
|
+
boolean(context)
|
|
29
|
+
{
|
|
30
|
+
return native.xpath_boolean(this.handle, context.handle);
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
module.exports = { XPathScalars };
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|