beresta 0.0.0-stage → 2.1.1

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.
Files changed (42) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +55 -2
  3. package/examples/demo.mts +49 -0
  4. package/lib/errors.js +59 -0
  5. package/lib/factory.js +50 -0
  6. package/lib/flags.js +49 -0
  7. package/lib/index.d.ts +228 -0
  8. package/lib/index.js +38 -0
  9. package/lib/internal/bytes.js +35 -0
  10. package/lib/internal/keys.js +24 -0
  11. package/lib/internal/mixin.js +30 -0
  12. package/lib/internal/native.js +83 -0
  13. package/lib/internal/release.js +44 -0
  14. package/lib/languages.js +70 -0
  15. package/lib/nodes/document.js +57 -0
  16. package/lib/nodes/document_content.js +48 -0
  17. package/lib/nodes/element.js +55 -0
  18. package/lib/nodes/element_attributes.js +38 -0
  19. package/lib/nodes/node.js +25 -0
  20. package/lib/nodes/node_base.js +58 -0
  21. package/lib/nodes/node_children.js +49 -0
  22. package/lib/nodes/node_content.js +47 -0
  23. package/lib/nodes/node_editing.js +48 -0
  24. package/lib/nodes/node_navigation.js +46 -0
  25. package/lib/nodes/node_structure.js +51 -0
  26. package/lib/nodes/registry.js +121 -0
  27. package/lib/nodes/wrapping.js +55 -0
  28. package/lib/schema/diagnostics.js +50 -0
  29. package/lib/schema/schema.js +66 -0
  30. package/lib/schema/schema_lifecycle.js +35 -0
  31. package/lib/schema/schema_streaming.js +45 -0
  32. package/lib/xpath/xpath.js +68 -0
  33. package/lib/xpath/xpath_context.js +33 -0
  34. package/lib/xpath/xpath_evaluation.js +69 -0
  35. package/lib/xpath/xpath_scalars.js +34 -0
  36. package/native/linux-aarch64/beresta.node +0 -0
  37. package/native/linux-x86_64/beresta.node +0 -0
  38. package/native/macos-aarch64/beresta.node +0 -0
  39. package/native/macos-x86_64/beresta.node +0 -0
  40. package/native/windows-aarch64/beresta.node +0 -0
  41. package/native/windows-x86_64/beresta.node +0 -0
  42. package/package.json +37 -4
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Beresta contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,56 @@
1
- # Temporary Holding Version
1
+ # Берёста для Node.js
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Быстрая XML-библиотека на C++17: DOM, XPath 1.0, XML Schema с `xs:key`/`xs:keyref`, DTD, восемь кодировок. Вызовы идут через собственный аддон Node-API: **нет ни npm-зависимостей, ни node-gyp, ни компиляции на машине пользователя**. Готовые типы TypeScript входят в пакет.
4
+
5
+ ```bash
6
+ npm install beresta
7
+ ```
8
+
9
+ ```js
10
+ const beresta = require('beresta');
11
+
12
+ using document = beresta.parse("<shop><item code='A1'>Чай</item></shop>");
13
+ const item = document.root.firstChild;
14
+ console.log(item.getAttribute('code'), item.text); // A1 Чай
15
+
16
+ using query = new beresta.XPath('//item[@code = $c]', { variables: { c: 'A1' } });
17
+ console.log(query.string(document)); // Чай
18
+ ```
19
+
20
+ `using` работает в Node.js 24+; в более ранних версиях вызывайте `document.close()` (если забыть, память освободит сборщик мусора).
21
+
22
+ Пакет из npm уже содержит аддоны для Windows (x64, arm64), Linux (x64, arm64; glibc 2.35+) и macOS (универсальный: Intel и Apple Silicon). Для браузера и Cloudflare Workers есть пакет [`beresta-wasm`](../wasm/README.md) с тем же API. Сборка из исходников: `make NODE=1` или `cmake -DBERESTA_BUILD_NODE=ON` в корне репозитория — аддон окажется в `native/<os>-<arch>/beresta.node`.
23
+
24
+ **Как получить скорость C++.** Каждый шаг ручного обхода (`firstChild`, `nextSibling`) — вызов через Node-API и объект-обёртка. Тяжёлую работу отдавайте ядру целиком:
25
+
26
+ ```js
27
+ using schema = beresta.Schema.fromFile('export.xsd');
28
+ const problems = schema.validateFile('export.xml'); // поток без дерева, хоть гигабайты
29
+ const prices = new beresta.XPath('//item/@price').selectValues(document); // строки без объектов-узлов
30
+ ```
31
+
32
+ Среди библиотек для Node.js с настоящим DOM, XPath и XSD «Берёста» быстрее всех, а потоковая проверка `validateFile` / `validateBytes` не строит дерево и отображает файл в память. Строка и столбец нарушений в `schema.validate(document)` — с флагом `ParseFlags.TRACK_LOCATIONS` при разборе.
33
+
34
+ ---
35
+
36
+ # Beresta for Node.js
37
+
38
+ A fast C++17 XML library: DOM, XPath 1.0, XML Schema with `xs:key`/`xs:keyref`, DTD, eight encodings. The calls go through an own Node-API addon: **no npm dependencies, no node-gyp, no compilation on the user's machine**. TypeScript types are included.
39
+
40
+ ```bash
41
+ npm install beresta
42
+ ```
43
+
44
+ `using` works in Node.js 24+; in earlier versions call `document.close()` (if you forget, the garbage collector frees the memory).
45
+
46
+ The npm package already contains the addons for Windows (x64, arm64), Linux (x64, arm64; glibc 2.35+) and macOS (universal: Intel and Apple Silicon). For a browser and Cloudflare Workers there is the [`beresta-wasm`](../wasm/README.md) package with the same API. Building from source: `make NODE=1` or `cmake -DBERESTA_BUILD_NODE=ON` in the repository root — the addon lands in `native/<os>-<arch>/beresta.node`.
47
+
48
+ **How to get C++ speed.** Every step of a manual walk (`firstChild`, `nextSibling`) is a call through Node-API and a wrapper object. Hand heavy work over to the core entirely:
49
+
50
+ ```js
51
+ using schema = beresta.Schema.fromFile('export.xsd');
52
+ const problems = schema.validateFile('export.xml'); // a stream without a tree, even gigabytes
53
+ const prices = new beresta.XPath('//item/@price').selectValues(document); // strings without node objects
54
+ ```
55
+
56
+ Among the Node.js libraries with a real DOM, XPath and XSD Beresta is the fastest, and streaming validation with `validateFile` / `validateBytes` builds no tree and maps the file into memory. The line and column of violations in `schema.validate(document)` come with the `ParseFlags.TRACK_LOCATIONS` parse flag.
@@ -0,0 +1,49 @@
1
+ /*
2
+ * Пример на TypeScript. Node.js 23.6+ запускает его без компилятора
3
+ * (встроенное удаление типов): node examples/demo.mts
4
+ * Типы берутся из lib/index.d.ts — редактор подсказывает методы, а
5
+ * опечатка в имени или неверный тип аргумента видны ещё до запуска.
6
+ *
7
+ * A TypeScript example. Node.js 23.6+ runs it without a compiler
8
+ * (built-in type stripping): node examples/demo.mts
9
+ * The types come from lib/index.d.ts — the editor suggests methods, and a
10
+ * typo in a name or a wrong argument type is visible before the run.
11
+ */
12
+
13
+ import { parse, createDocument, XPath, WriteFlags, BerestaError } from '../lib/index.js';
14
+ import type { XmlDocument, XmlElement } from '../lib/index.js';
15
+
16
+ // Сумма цен всех товаров через XPath / The sum of all item prices through XPath
17
+ function totalPrice(document: XmlDocument): number
18
+ {
19
+ using query = new XPath('sum(//item/@price)');
20
+
21
+ return query.number(document);
22
+ }
23
+
24
+ // Новый заказ, построенный цепочкой вызовов / A new order built with a chain of calls
25
+ function buildOrder(): string
26
+ {
27
+ using order = createDocument('order');
28
+ const item: XmlElement = order.root!.appendElement('item').setAttribute('qty', 2);
29
+
30
+ item.appendText('Мёд & орехи');
31
+ return order.toXml(WriteFlags.PRETTY);
32
+ }
33
+
34
+ {
35
+ using shop = parse("<shop><item price='120'>Чай</item><item price='80'>Кофе</item></shop>");
36
+
37
+ console.log('Сумма / Total:', totalPrice(shop));
38
+ console.log(buildOrder());
39
+ }
40
+
41
+ try
42
+ {
43
+ parse('<a><b></a>');
44
+ }
45
+ catch (error)
46
+ {
47
+ if (error instanceof BerestaError)
48
+ console.log(error.code, error.message);
49
+ }
package/lib/errors.js ADDED
@@ -0,0 +1,59 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * Ошибка «Берёсты». status — число beresta_status Си-интерфейса,
5
+ * code — имя кода (PARSE_ERROR, VALIDATION_ERROR...), одинаковое во всех
6
+ * языках, — по соглашению Node.js, как ENOENT у модуля fs. message — текст
7
+ * на текущем языке сообщений.
8
+ *
9
+ * A Beresta error. status is the beresta_status number of the C interface,
10
+ * code is the code name (PARSE_ERROR, VALIDATION_ERROR...), the same in all
11
+ * languages — by the Node.js convention, like ENOENT of the fs module. message
12
+ * is the text in the current message language.
13
+ */
14
+ class BerestaError extends Error
15
+ {
16
+ constructor(status, code, message)
17
+ {
18
+ super(message);
19
+ this.name = 'BerestaError';
20
+ this.status = status;
21
+ this.code = code;
22
+ }
23
+ }
24
+
25
+ /**
26
+ * Обращение к уже закрытому документу, выражению или схеме. Это ошибка
27
+ * программы, а не данных, поэтому у неё отдельный класс.
28
+ *
29
+ * An access to an already closed document, expression or schema. This is a
30
+ * program error, not a data error, so it has a separate class.
31
+ */
32
+ class BerestaClosedError extends Error
33
+ {
34
+ constructor(message)
35
+ {
36
+ super(message);
37
+ this.name = 'BerestaClosedError';
38
+ this.code = 'OBJECT_CLOSED';
39
+ }
40
+ }
41
+
42
+ /**
43
+ * Нативный аддон не найден или не загрузился. Текст двуязычный: каталог
44
+ * сообщений живёт в самом аддоне и до его загрузки недоступен.
45
+ *
46
+ * The native addon is not found or failed to load. The text is bilingual:
47
+ * the message catalog lives in the addon itself and is unavailable before it loads.
48
+ */
49
+ class BerestaLoadError extends Error
50
+ {
51
+ constructor(message)
52
+ {
53
+ super(message);
54
+ this.name = 'BerestaLoadError';
55
+ this.code = 'ADDON_NOT_LOADED';
56
+ }
57
+ }
58
+
59
+ module.exports = { BerestaError, BerestaClosedError, BerestaLoadError };
package/lib/factory.js ADDED
@@ -0,0 +1,50 @@
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 { XmlDocument } = require('./nodes/document.js');
7
+
8
+ // Дескриптор схемы из настроек или null (без проверки по схеме)
9
+ // The schema handle from the options or null (no schema validation)
10
+ function schemaHandle(options)
11
+ {
12
+ if (options.schema === undefined || options.schema === null)
13
+ return null;
14
+ return options.schema.handle;
15
+ }
16
+
17
+ /**
18
+ * Разбор XML. Строка кодируется в UTF-8; Buffer / Uint8Array передаются как
19
+ * есть — кодировку (UTF-16, windows-1251...) библиотека определит сама.
20
+ * options.flags — ParseFlags, options.schema — проверка по XML Schema.
21
+ *
22
+ * Parses XML. A string is encoded to UTF-8; a Buffer / Uint8Array is passed as
23
+ * is — the library detects the encoding (UTF-16, windows-1251...) itself.
24
+ * options.flags are ParseFlags, options.schema is validation against an XML Schema.
25
+ */
26
+ function parse(input, options = {})
27
+ {
28
+ const bytes = toBytes(input, 'parse');
29
+ const flags = options.flags ?? ParseFlags.DEFAULT;
30
+
31
+ return new XmlDocument(native.document_parse(bytes, flags, schemaHandle(options)));
32
+ }
33
+
34
+ /** Разбор файла; ParseFlags.FILE_RESOURCES разрешает внешние DTD рядом с ним.
35
+ * Parses a file; ParseFlags.FILE_RESOURCES allows external DTDs next to it. */
36
+ function parseFile(path, options = {})
37
+ {
38
+ const flags = options.flags ?? ParseFlags.DEFAULT;
39
+
40
+ return new XmlDocument(native.document_parse_file(String(path), flags, schemaHandle(options)));
41
+ }
42
+
43
+ /** Новый документ; rootName === null — без корневого элемента.
44
+ * A new document; rootName === null means without a root element. */
45
+ function createDocument(rootName = null)
46
+ {
47
+ return new XmlDocument(native.document_create(rootName));
48
+ }
49
+
50
+ module.exports = { parse, parseFile, createDocument };
package/lib/flags.js ADDED
@@ -0,0 +1,49 @@
1
+ 'use strict';
2
+
3
+ /*
4
+ * Флаги и перечисления Си-интерфейса (значения совпадают с beresta_c.h).
5
+ * Флаги объединяются оператором |:
6
+ * beresta.parse(xml, { flags: ParseFlags.DISCARD_COMMENTS | ParseFlags.VALIDATE_DTD })
7
+ * Объекты заморожены: опечатка в имени даёт undefined, а не тихую запись.
8
+ *
9
+ * Flags and enumerations of the C interface (the values match beresta_c.h).
10
+ * Flags are combined with the | operator:
11
+ * beresta.parse(xml, { flags: ParseFlags.DISCARD_COMMENTS | ParseFlags.VALIDATE_DTD })
12
+ * The objects are frozen: a typo in a name gives undefined, not a silent write.
13
+ */
14
+
15
+ // Флаги разбора BERESTA_PARSE_* / Parsing flags BERESTA_PARSE_*
16
+ const ParseFlags = Object.freeze({
17
+ DEFAULT: 0,
18
+ PRESERVE_WHITESPACE: 1 << 0,
19
+ DISCARD_COMMENTS: 1 << 1,
20
+ COALESCE_CDATA: 1 << 2,
21
+ VALIDATE_DTD: 1 << 3,
22
+ NO_NAMESPACES: 1 << 4,
23
+ XINCLUDE: 1 << 5,
24
+ FILE_RESOURCES: 1 << 6,
25
+ // Строка и столбец узлов: места нарушений в schema.validate(document)
26
+ // The line and column of nodes: the places of violations in schema.validate(document)
27
+ TRACK_LOCATIONS: 1 << 7
28
+ });
29
+
30
+ // Флаги вывода BERESTA_WRITE_*: по умолчанию — ни одного лишнего пробела
31
+ // Output flags BERESTA_WRITE_*: by default — not a single extra space
32
+ const WriteFlags = Object.freeze({
33
+ DEFAULT: 0,
34
+ PRETTY: 1 << 0,
35
+ DECLARATION: 1 << 1
36
+ });
37
+
38
+ // Тип узла (beresta_node_kind) / The node type (beresta_node_kind)
39
+ const NodeType = Object.freeze({
40
+ DOCUMENT: 0,
41
+ DOCUMENT_TYPE: 1,
42
+ ELEMENT: 2,
43
+ TEXT: 3,
44
+ CDATA_SECTION: 4,
45
+ COMMENT: 5,
46
+ PROCESSING_INSTRUCTION: 6
47
+ });
48
+
49
+ module.exports = { ParseFlags, WriteFlags, NodeType };
package/lib/index.d.ts ADDED
@@ -0,0 +1,228 @@
1
+ /*
2
+ * Типы TypeScript для «Берёсты» (Node.js). Пакет написан на JavaScript,
3
+ * а этот файл даёт редактору автодополнение, а компилятору — строгую
4
+ * проверку: дескрипторы, флаги и результаты XPath имеют точные типы.
5
+ *
6
+ * TypeScript types for Beresta (Node.js). The package is written in JavaScript,
7
+ * and this file gives the editor autocompletion and the compiler strict
8
+ * checking: handles, flags and XPath results have exact types.
9
+ */
10
+
11
+ /** Нативный дескриптор: адрес объекта в памяти библиотеки. / A native handle: an object address in the library memory. */
12
+ export type Handle = bigint;
13
+
14
+ /** Значение NodeType. / A NodeType value. */
15
+ export type NodeTypeValue = 0 | 1 | 2 | 3 | 4 | 5 | 6;
16
+
17
+ /** Флаги разбора (объединяются через |). / Parsing flags (combined with |). */
18
+ export declare const ParseFlags: {
19
+ readonly DEFAULT: 0;
20
+ readonly PRESERVE_WHITESPACE: 1;
21
+ readonly DISCARD_COMMENTS: 2;
22
+ readonly COALESCE_CDATA: 4;
23
+ readonly VALIDATE_DTD: 8;
24
+ readonly NO_NAMESPACES: 16;
25
+ readonly XINCLUDE: 32;
26
+ readonly FILE_RESOURCES: 64;
27
+ readonly TRACK_LOCATIONS: 128;
28
+ };
29
+
30
+ /** Флаги вывода; по умолчанию — ни одного лишнего пробела. / Output flags; by default — not a single extra space. */
31
+ export declare const WriteFlags: {
32
+ readonly DEFAULT: 0;
33
+ readonly PRETTY: 1;
34
+ readonly DECLARATION: 2;
35
+ };
36
+
37
+ /** Тип узла (порядок совпадает с beresta_node_kind). / The node type (the order matches beresta_node_kind). */
38
+ export declare const NodeType: {
39
+ readonly DOCUMENT: 0;
40
+ readonly DOCUMENT_TYPE: 1;
41
+ readonly ELEMENT: 2;
42
+ readonly TEXT: 3;
43
+ readonly CDATA_SECTION: 4;
44
+ readonly COMMENT: 5;
45
+ readonly PROCESSING_INSTRUCTION: 6;
46
+ };
47
+
48
+ /** Вход разбора: текст (UTF-8) или байты в любой поддерживаемой кодировке.
49
+ * The parse input: text (UTF-8) or bytes in any supported encoding. */
50
+ export type XmlInput = string | Uint8Array | ArrayBuffer;
51
+
52
+ /** Настройки разбора. / Parse options. */
53
+ export interface ParseOptions {
54
+ /** Флаги ParseFlags. / ParseFlags flags. */
55
+ flags?: number;
56
+ /** Проверка по XML Schema во время разбора. / Validation against an XML Schema during parsing. */
57
+ schema?: Schema | null;
58
+ }
59
+
60
+ /** Настройки записи в файл. / File writing options. */
61
+ export interface SaveOptions {
62
+ /** Флаги WriteFlags. / WriteFlags flags. */
63
+ flags?: number;
64
+ /** Кодировка результата, например "windows-1251" (по умолчанию UTF-8). / The output encoding, for example "windows-1251" (UTF-8 by default). */
65
+ encoding?: string | null;
66
+ }
67
+
68
+ /** Ошибка «Берёсты»: code одинаков во всех языках, message — на текущем.
69
+ * A Beresta error: code is the same in all languages, message is in the current one. */
70
+ export declare class BerestaError extends Error {
71
+ /** Число beresta_status. / The beresta_status number. */
72
+ readonly status: number;
73
+ /** Имя кода: PARSE_ERROR, VALIDATION_ERROR, INVALID_NAME... / The code name: PARSE_ERROR, VALIDATION_ERROR, INVALID_NAME... */
74
+ readonly code: string;
75
+ constructor(status: number, code: string, message: string);
76
+ }
77
+
78
+ /** Обращение к закрытому документу, выражению или схеме. / An access to a closed document, expression or schema. */
79
+ export declare class BerestaClosedError extends Error {
80
+ readonly code: 'OBJECT_CLOSED';
81
+ constructor(message: string);
82
+ }
83
+
84
+ /** Нативный аддон не найден или не загрузился. / The native addon is not found or failed to load. */
85
+ export declare class BerestaLoadError extends Error {
86
+ readonly code: 'ADDON_NOT_LOADED';
87
+ constructor(message: string);
88
+ }
89
+
90
+ /** Узел дерева документа. / A node of the document tree. */
91
+ export declare class XmlNode implements Iterable<XmlNode> {
92
+ protected constructor(document: XmlDocument | null, handle: Handle);
93
+ /** Нативный дескриптор; BerestaClosedError, если документ закрыт. / The native handle; BerestaClosedError if the document is closed. */
94
+ readonly handle: Handle;
95
+ /** Документ-владелец. / The owner document. */
96
+ readonly document: XmlDocument;
97
+ /** Тип узла. / The node type. */
98
+ readonly type: NodeTypeValue;
99
+ /** Имя по соглашению DOM: тег, цель PI, "#text"... / The name by the DOM convention: a tag, a PI target, "#text"... */
100
+ readonly name: string;
101
+ /** Текстовое содержимое; запись у элемента заменяет всех детей. / The text content; writing it on an element replaces all children. */
102
+ text: string;
103
+ readonly parent: XmlNode | null;
104
+ readonly firstChild: XmlNode | null;
105
+ readonly lastChild: XmlNode | null;
106
+ readonly nextSibling: XmlNode | null;
107
+ readonly previousSibling: XmlNode | null;
108
+ readonly childCount: number;
109
+ /** Снимок списка детей. / A snapshot of the child list. */
110
+ readonly children: XmlNode[];
111
+ /** Ребёнок по индексу; отрицательный — с конца. / A child by index; a negative one counts from the end. */
112
+ child(index: number): XmlNode | null;
113
+ [Symbol.iterator](): Iterator<XmlNode>;
114
+ /** Указывают ли обёртки на один узел. / Whether the wrappers point to the same node. */
115
+ isSameNode(other: unknown): boolean;
116
+ /** Сериализация с потомками. / Serialization with the descendants. */
117
+ toXml(flags?: number): string;
118
+ appendElement(name: string): XmlElement;
119
+ appendText(text: string): XmlNode;
120
+ appendComment(text: string): XmlNode;
121
+ appendCData(text: string): XmlNode;
122
+ appendProcessingInstruction(target: string, data?: string | null): XmlNode;
123
+ /** Удаление с потомками; обёртка становится недействительной. / Removal with the descendants; the wrapper becomes invalid. */
124
+ remove(): void;
125
+ /** Глубокая копия в конец детей parent. / A deep copy appended to the children of parent. */
126
+ copyTo<T extends XmlNode>(parent: XmlNode): T;
127
+ /** Перенос без копирования в конец детей parent (можно в другой документ); после него
128
+ * document — документ parent. Корень и сам документ переносить нельзя.
129
+ * A move without copying to the end of the children of parent (another document is allowed);
130
+ * after it document is the document of parent. The root and the document itself cannot be moved. */
131
+ moveTo(parent: XmlNode): void;
132
+ }
133
+
134
+ /** Элемент XML. / An XML element. */
135
+ export declare class XmlElement extends XmlNode {
136
+ readonly type: 2;
137
+ readonly localName: string;
138
+ readonly namespaceUri: string | null;
139
+ /** Снимок атрибутов в порядке документа. / A snapshot of the attributes in document order. */
140
+ readonly attributes: Record<string, string>;
141
+ getAttribute(name: string): string | null;
142
+ setAttribute(name: string, value: string | number | boolean): this;
143
+ hasAttribute(name: string): boolean;
144
+ removeAttribute(name: string): boolean;
145
+ }
146
+
147
+ /** XML-документ — владелец дерева; закрывается close() или `using`. / An XML document — the tree owner; closed with close() or `using`. */
148
+ export declare class XmlDocument extends XmlNode implements Disposable {
149
+ protected constructor(handle: Handle);
150
+ readonly type: 0;
151
+ readonly closed: boolean;
152
+ readonly root: XmlElement | null;
153
+ elementById(id: string): XmlElement | null;
154
+ /** Независимая копия; её тоже нужно закрыть. / An independent copy; it must be closed too. */
155
+ clone(): XmlDocument;
156
+ save(path: string, options?: SaveOptions): void;
157
+ close(): void;
158
+ [Symbol.dispose](): void;
159
+ }
160
+
161
+ /** Контекст выражения XPath. / An XPath expression context. */
162
+ export interface XPathOptions {
163
+ /** Префиксы для имён p:name. / Prefixes for p:name names. */
164
+ namespaces?: Record<string, string>;
165
+ /** Переменные $name. / The $name variables. */
166
+ variables?: Record<string, string | number>;
167
+ }
168
+
169
+ /** Скомпилированное выражение XPath 1.0. / A compiled XPath 1.0 expression. */
170
+ export declare class XPath implements Disposable {
171
+ constructor(expression: string, options?: XPathOptions);
172
+ readonly handle: Handle;
173
+ readonly closed: boolean;
174
+ bindNamespace(prefix: string, uri: string): this;
175
+ set(name: string, value: string | number | boolean): this;
176
+ /** Узлы результата (атрибуты — через selectValues). / The result nodes (attributes — through selectValues). */
177
+ select(context: XmlNode): XmlNode[];
178
+ selectValues(context: XmlNode): string[];
179
+ string(context: XmlNode): string;
180
+ number(context: XmlNode): number;
181
+ boolean(context: XmlNode): boolean;
182
+ close(): void;
183
+ [Symbol.dispose](): void;
184
+ }
185
+
186
+ /** Одно нарушение схемы. / One schema violation. */
187
+ export declare class Diagnostic {
188
+ private constructor();
189
+ /** Текст с путём к элементу. / The text with the element path. */
190
+ readonly message: string;
191
+ /** Строка в исходнике (0 — неизвестна). / The line in the source (0 — unknown). */
192
+ readonly line: number;
193
+ readonly column: number;
194
+ }
195
+
196
+ /** Загруженная XML Schema. / A loaded XML Schema. */
197
+ export declare class Schema implements Disposable {
198
+ private constructor(handle: Handle);
199
+ static fromString(input: XmlInput): Schema;
200
+ static fromFile(path: string): Schema;
201
+ readonly handle: Handle;
202
+ readonly closed: boolean;
203
+ validate(document: XmlDocument): Diagnostic[];
204
+ /** Потоковая проверка без дерева: память O(глубины), синтаксическая ошибка — исключение.
205
+ * Streaming validation without a tree: O(depth) memory, a syntax error is an exception. */
206
+ validateBytes(input: XmlInput, options?: { flags?: number }): Diagnostic[];
207
+ /** Потоковая проверка файла (файл отображается в память). / Streaming validation of a file (the file is mapped into memory). */
208
+ validateFile(path: string, options?: { flags?: number }): Diagnostic[];
209
+ close(): void;
210
+ [Symbol.dispose](): void;
211
+ }
212
+
213
+ /** Разбор XML. / Parses XML. */
214
+ export declare function parse(input: XmlInput, options?: ParseOptions): XmlDocument;
215
+ /** Разбор файла. / Parses a file. */
216
+ export declare function parseFile(path: string, options?: ParseOptions): XmlDocument;
217
+ /** Новый документ (null — без корня). / A new document (null — without a root). */
218
+ export declare function createDocument(rootName?: string | null): XmlDocument;
219
+ /** Версия нативной библиотеки. / The native library version. */
220
+ export declare function version(): string;
221
+ /** Платформа аддона, например "linux-x86_64". / The addon platform, for example "linux-x86_64". */
222
+ export declare function platformName(): string;
223
+ /** Смена языка сообщений для всего процесса. / Switches the message language for the whole process. */
224
+ export declare function setLanguage(code: string): void;
225
+ /** Код текущего языка. / The current language code. */
226
+ export declare function language(): string;
227
+ /** Все языки библиотеки. / All languages of the library. */
228
+ export declare function languages(): string[];
package/lib/index.js ADDED
@@ -0,0 +1,38 @@
1
+ 'use strict';
2
+
3
+ /*
4
+ * Берёста — быстрая XML-библиотека DOM на C++17 для Node.js.
5
+ * Вызовы идут через собственный аддон Node-API (без node-gyp и без
6
+ * npm-зависимостей): бинарник для своей платформы лежит в native/<os>-<arch>/.
7
+ *
8
+ * Beresta is a fast XML DOM library in C++17 for Node.js.
9
+ * The calls go through an own Node-API addon (without node-gyp and without
10
+ * npm dependencies): the binary for each platform lives in native/<os>-<arch>/.
11
+ */
12
+
13
+ const { native, platformName } = require('./internal/native.js');
14
+ const { BerestaError, BerestaClosedError, BerestaLoadError } = require('./errors.js');
15
+ const { ParseFlags, WriteFlags, NodeType } = require('./flags.js');
16
+ const { setLanguage, language, languages } = require('./languages.js');
17
+ const { XmlNode } = require('./nodes/node.js');
18
+ const { XmlElement } = require('./nodes/element.js');
19
+ const { XmlDocument } = require('./nodes/document.js');
20
+ const { parse, parseFile, createDocument } = require('./factory.js');
21
+ const { XPath } = require('./xpath/xpath.js');
22
+ const { Schema } = require('./schema/schema.js');
23
+ const { Diagnostic } = require('./schema/diagnostics.js');
24
+
25
+ // Версия нативной библиотеки, например "2.1.0" / The native library version, for example "2.1.0"
26
+ function version()
27
+ {
28
+ return native.version();
29
+ }
30
+
31
+ module.exports = {
32
+ version, platformName,
33
+ parse, parseFile, createDocument,
34
+ XmlNode, XmlElement, XmlDocument, XPath, Schema, Diagnostic,
35
+ ParseFlags, WriteFlags, NodeType,
36
+ setLanguage, language, languages,
37
+ BerestaError, BerestaClosedError, BerestaLoadError
38
+ };
@@ -0,0 +1,35 @@
1
+ 'use strict';
2
+
3
+ const { messageText, Messages } = require('../languages.js');
4
+
5
+ // Кодировщик для сред без Buffer (браузер, Workers) / An encoder for environments without Buffer (browser, Workers)
6
+ const encoder = new TextEncoder();
7
+
8
+ /*
9
+ * Вход разбора -> байты для аддона. Строка кодируется в UTF-8; Buffer и
10
+ * Uint8Array передаются как есть, без копирования, — кодировку (UTF-16,
11
+ * windows-1251...) ядро определит само по BOM и XML-декларации.
12
+ * ArrayBuffer оборачивается представлением Uint8Array (тоже без копии).
13
+ *
14
+ * The parse input -> bytes for the addon. A string is encoded to UTF-8; a Buffer
15
+ * and a Uint8Array are passed as is, without copying — the core detects the
16
+ * encoding (UTF-16, windows-1251...) itself by the BOM and the XML declaration.
17
+ * An ArrayBuffer is wrapped in a Uint8Array view (also without a copy).
18
+ */
19
+ function toBytes(input, functionName)
20
+ {
21
+ if (typeof input === 'string')
22
+ {
23
+ if (typeof Buffer !== 'undefined')
24
+ return Buffer.from(input, 'utf8');
25
+ return encoder.encode(input);
26
+ }
27
+ if (input instanceof Uint8Array)
28
+ return input;
29
+ if (input instanceof ArrayBuffer)
30
+ return new Uint8Array(input);
31
+ throw new TypeError(messageText(Messages.INVALID_ARGUMENT, 1, functionName,
32
+ 'string | Buffer | Uint8Array | ArrayBuffer'));
33
+ }
34
+
35
+ module.exports = { toBytes };
@@ -0,0 +1,24 @@
1
+ 'use strict';
2
+
3
+ /*
4
+ * Ключи внутренних полей объектов-обёрток. Символы вместо #приватных полей:
5
+ * методы примесей (mixin.js) определены в других классах, а доступ к
6
+ * #полю разрешён только внутри класса, который его объявил. Символ не
7
+ * виден в Object.keys и JSON, поэтому поля всё равно скрыты от пользователя.
8
+ *
9
+ * The keys of the internal fields of the wrapper objects. Symbols instead of
10
+ * #private fields: the mixin methods (mixin.js) are defined in other classes,
11
+ * and a #field is accessible only inside the class that declared it. A symbol
12
+ * is invisible in Object.keys and JSON, so the fields are still hidden from the user.
13
+ */
14
+
15
+ // Нативный дескриптор (BigInt; null после закрытия) / The native handle (BigInt; null after closing)
16
+ const HANDLE = Symbol('beresta.handle');
17
+
18
+ // Документ-владелец узла / The owner document of a node
19
+ const OWNER = Symbol('beresta.owner');
20
+
21
+ // Реестр обёрток узлов документа (см. nodes/registry.js) / The node wrapper registry of a document (see nodes/registry.js)
22
+ const REGISTRY = Symbol('beresta.registry');
23
+
24
+ module.exports = { HANDLE, OWNER, REGISTRY };
@@ -0,0 +1,30 @@
1
+ 'use strict';
2
+
3
+ /*
4
+ * Примеси (mixin): методы узла разнесены по небольшим классам по смыслу —
5
+ * содержимое, навигация, дети, изменение дерева. Это принцип разделения
6
+ * интерфейсов (ISP из SOLID): каждая часть отвечает за одну обязанность и
7
+ * читается отдельно, а итоговый класс лишь собирает их. JavaScript
8
+ * наследует только от одного класса, поэтому методы копируются в прототип
9
+ * вместе с геттерами и сеттерами (дескрипторы свойств, а не значения).
10
+ *
11
+ * Mixins: the node methods are split into small classes by meaning —
12
+ * content, navigation, children, tree changes. This is the interface
13
+ * segregation principle (ISP from SOLID): each part has one responsibility
14
+ * and reads separately, while the final class only combines them. JavaScript
15
+ * inherits from one class only, so the methods are copied into the prototype
16
+ * together with getters and setters (property descriptors, not values).
17
+ */
18
+ function applyMixins(target, ...sources)
19
+ {
20
+ for (const source of sources)
21
+ {
22
+ const descriptors = Object.getOwnPropertyDescriptors(source.prototype);
23
+
24
+ delete descriptors.constructor;
25
+ Object.defineProperties(target.prototype, descriptors);
26
+ }
27
+ return target;
28
+ }
29
+
30
+ module.exports = { applyMixins };