xmljslib 1.0.3 → 1.0.4
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/cli.js +354 -22
- package/dist/index.cjs +444 -45
- package/dist/index.d.cts +133 -2
- package/dist/index.d.ts +133 -2
- package/dist/index.js +442 -44
- package/package.json +63 -62
- package/readme.md +573 -466
- package/readme.ru.md +110 -3
package/dist/index.js
CHANGED
|
@@ -25,14 +25,25 @@ function createXMLNode(value, attributes = {}, isLeaf = false) {
|
|
|
25
25
|
if (!hasAttributes) {
|
|
26
26
|
return parsedValue;
|
|
27
27
|
}
|
|
28
|
-
const
|
|
28
|
+
const attributeValue = Object.prototype.hasOwnProperty.call(attributes, "value") ? parsePrimitive(attributes.value) : void 0;
|
|
29
|
+
const nodeValue = parsedValue !== void 0 ? parsedValue : attributeValue;
|
|
30
|
+
const targetObj = Object(nodeValue !== void 0 ? nodeValue : "");
|
|
29
31
|
for (const [key, attrVal] of Object.entries(attributes)) {
|
|
32
|
+
if (key === "value") {
|
|
33
|
+
continue;
|
|
34
|
+
}
|
|
30
35
|
targetObj[`$${key}`] = parsePrimitive(attrVal);
|
|
31
36
|
}
|
|
37
|
+
Object.defineProperty(targetObj, "$value", {
|
|
38
|
+
value: nodeValue,
|
|
39
|
+
writable: true,
|
|
40
|
+
enumerable: true,
|
|
41
|
+
configurable: true
|
|
42
|
+
});
|
|
32
43
|
return new Proxy(targetObj, {
|
|
33
44
|
get(target, prop) {
|
|
34
45
|
if (prop === "__isXMLNode") return true;
|
|
35
|
-
if (prop === "$value") return
|
|
46
|
+
if (prop === "$value") return nodeValue;
|
|
36
47
|
if (prop === "valueOf" || prop === Symbol.toPrimitive) {
|
|
37
48
|
return () => parsedValue;
|
|
38
49
|
}
|
|
@@ -119,10 +130,14 @@ var XMLParser = class _XMLParser {
|
|
|
119
130
|
static parseTreeJSON(item) {
|
|
120
131
|
const result = {};
|
|
121
132
|
const node = {};
|
|
133
|
+
const attributeValue = Object.prototype.hasOwnProperty.call(item.attributes, "value") ? item.attributes.value : void 0;
|
|
134
|
+
node.$value = item.$value !== null ? item.$value : attributeValue ?? null;
|
|
122
135
|
for (const attr of Object.keys(item.attributes)) {
|
|
136
|
+
if (attr === "value") {
|
|
137
|
+
continue;
|
|
138
|
+
}
|
|
123
139
|
node[`$${attr}`] = item.attributes[attr];
|
|
124
140
|
}
|
|
125
|
-
node.$value = item.$value;
|
|
126
141
|
for (const child of item.children) {
|
|
127
142
|
const parsed = _XMLParser.parseTreeJSON(child);
|
|
128
143
|
const childValue = parsed[child.tag];
|
|
@@ -257,7 +272,7 @@ var XMLParser = class _XMLParser {
|
|
|
257
272
|
};
|
|
258
273
|
|
|
259
274
|
// src/lib/wsdlTypeGenerator.ts
|
|
260
|
-
var WSDLTypeGenerator = class {
|
|
275
|
+
var WSDLTypeGenerator = class _WSDLTypeGenerator {
|
|
261
276
|
typeRegistry = /* @__PURE__ */ new Map();
|
|
262
277
|
simpleTypeRegistry = /* @__PURE__ */ new Map();
|
|
263
278
|
simpleTypeDocumentationRegistry = /* @__PURE__ */ new Map();
|
|
@@ -272,6 +287,40 @@ var WSDLTypeGenerator = class {
|
|
|
272
287
|
globalElementRegistry = /* @__PURE__ */ new Map();
|
|
273
288
|
baseUrl = "";
|
|
274
289
|
loadedUrls = /* @__PURE__ */ new Set();
|
|
290
|
+
/**
|
|
291
|
+
* Пространства имён, объявленные в документе (`xmlns:*`).
|
|
292
|
+
* Используются и для автоподстановки префиксов, и для объявления `xmlns` в XML.
|
|
293
|
+
*/
|
|
294
|
+
namespaceUriByPrefix = /* @__PURE__ */ new Map();
|
|
295
|
+
namespacePrefixByUri = /* @__PURE__ */ new Map();
|
|
296
|
+
/**
|
|
297
|
+
* Пространства имён элементов: локальное имя элемента -> префикс.
|
|
298
|
+
*
|
|
299
|
+
* Квалифицированные элементы хранятся в `qualifiedElements`,
|
|
300
|
+
* неквалифицированные — в `unqualifiedElements`, чтобы одноимённые элементы
|
|
301
|
+
* из разных схем не конфликтовали: квалифицированный всегда выигрывает.
|
|
302
|
+
*/
|
|
303
|
+
qualifiedElements = /* @__PURE__ */ new Map();
|
|
304
|
+
unqualifiedElements = /* @__PURE__ */ new Set();
|
|
305
|
+
/**
|
|
306
|
+
* Имена элементов, объявленных в нескольких пространствах имён.
|
|
307
|
+
* Для таких элементов одного префикса «по имени» недостаточно —
|
|
308
|
+
* нужен контекст родителя.
|
|
309
|
+
*/
|
|
310
|
+
ambiguousElements = /* @__PURE__ */ new Set();
|
|
311
|
+
/**
|
|
312
|
+
* Тип каждого элемента: имя элемента -> имя типа в реестре complexType.
|
|
313
|
+
* Нужен, чтобы знать состав дочерних элементов.
|
|
314
|
+
*/
|
|
315
|
+
elementTypeRegistry = /* @__PURE__ */ new Map();
|
|
316
|
+
/**
|
|
317
|
+
* Пространства имён типов: имя complexType -> префикс.
|
|
318
|
+
*/
|
|
319
|
+
typeNamespacePrefix = /* @__PURE__ */ new Map();
|
|
320
|
+
/**
|
|
321
|
+
* Пространство имён XML Schema. Не имеет отношения к данным сервиса.
|
|
322
|
+
*/
|
|
323
|
+
static XML_SCHEMA_NAMESPACE = "http://www.w3.org/2001/XMLSchema";
|
|
275
324
|
get complexTypeCount() {
|
|
276
325
|
return this.typeRegistry.size;
|
|
277
326
|
}
|
|
@@ -294,8 +343,17 @@ var WSDLTypeGenerator = class {
|
|
|
294
343
|
this.messageRegistry.clear();
|
|
295
344
|
this.globalElementRegistry.clear();
|
|
296
345
|
this.loadedUrls.clear();
|
|
346
|
+
this.namespaceUriByPrefix.clear();
|
|
347
|
+
this.namespacePrefixByUri.clear();
|
|
348
|
+
this.qualifiedElements.clear();
|
|
349
|
+
this.unqualifiedElements.clear();
|
|
350
|
+
this.ambiguousElements.clear();
|
|
351
|
+
this.elementTypeRegistry.clear();
|
|
352
|
+
this.typeNamespacePrefix.clear();
|
|
297
353
|
console.log("\u{1F4E6} \u041F\u0430\u0440\u0441\u0438\u043D\u0433 \u0441\u0442\u0440\u0443\u043A\u0442\u0443\u0440\u044B XML...");
|
|
298
354
|
const wsdl = new XMLParser(xmlContent, config);
|
|
355
|
+
console.log("\u{1F50D} \u0410\u043D\u0430\u043B\u0438\u0437 \u043E\u0431\u044A\u044F\u0432\u043B\u0435\u043D\u0438\u0439 \u043F\u0440\u043E\u0441\u0442\u0440\u0430\u043D\u0441\u0442\u0432 \u0438\u043C\u0451\u043D...");
|
|
356
|
+
this.collectNamespaceDeclarations(wsdl);
|
|
299
357
|
console.log("\u{1F50D} \u0410\u043D\u0430\u043B\u0438\u0437 WSDL \u0441\u043E\u043E\u0431\u0449\u0435\u043D\u0438\u0439...");
|
|
300
358
|
this.extractMessages(wsdl);
|
|
301
359
|
console.log("\u{1F50D} \u0410\u043D\u0430\u043B\u0438\u0437 WSDL \u043E\u043F\u0435\u0440\u0430\u0446\u0438\u0439...");
|
|
@@ -338,6 +396,106 @@ var WSDLTypeGenerator = class {
|
|
|
338
396
|
const primitive = typeof value.valueOf === "function" ? value.valueOf() : value;
|
|
339
397
|
return String(primitive);
|
|
340
398
|
}
|
|
399
|
+
/**
|
|
400
|
+
* Приводит значение узла к строке.
|
|
401
|
+
*/
|
|
402
|
+
toPrimitiveString(value) {
|
|
403
|
+
if (value === null || value === void 0) {
|
|
404
|
+
return void 0;
|
|
405
|
+
}
|
|
406
|
+
const primitive = typeof value.valueOf === "function" ? value.valueOf() : value;
|
|
407
|
+
if (primitive === null || primitive === void 0) {
|
|
408
|
+
return void 0;
|
|
409
|
+
}
|
|
410
|
+
const text = String(primitive).trim();
|
|
411
|
+
return text.length > 0 ? text : void 0;
|
|
412
|
+
}
|
|
413
|
+
/**
|
|
414
|
+
* Регистрирует связь префикс <-> URI пространства имён.
|
|
415
|
+
* Первые объявления имеют приоритет: префикс не переопределяется.
|
|
416
|
+
*/
|
|
417
|
+
registerNamespacePrefix(prefix, uri) {
|
|
418
|
+
if (!this.namespaceUriByPrefix.has(prefix)) {
|
|
419
|
+
this.namespaceUriByPrefix.set(prefix, uri);
|
|
420
|
+
}
|
|
421
|
+
if (!this.namespacePrefixByUri.has(uri)) {
|
|
422
|
+
this.namespacePrefixByUri.set(uri, prefix);
|
|
423
|
+
}
|
|
424
|
+
}
|
|
425
|
+
/**
|
|
426
|
+
* Собирает объявления пространств имён (`xmlns:*`) из всего документа.
|
|
427
|
+
*/
|
|
428
|
+
collectNamespaceDeclarations(node) {
|
|
429
|
+
if (!node || typeof node !== "object") {
|
|
430
|
+
return;
|
|
431
|
+
}
|
|
432
|
+
if (Array.isArray(node)) {
|
|
433
|
+
for (const item of node) {
|
|
434
|
+
this.collectNamespaceDeclarations(item);
|
|
435
|
+
}
|
|
436
|
+
return;
|
|
437
|
+
}
|
|
438
|
+
for (const [key, value] of Object.entries(node)) {
|
|
439
|
+
if (key.startsWith("$xmlns:")) {
|
|
440
|
+
const prefix = key.slice("$xmlns:".length);
|
|
441
|
+
const uri = this.toPrimitiveString(value);
|
|
442
|
+
if (prefix && uri && uri !== _WSDLTypeGenerator.XML_SCHEMA_NAMESPACE) {
|
|
443
|
+
this.registerNamespacePrefix(prefix, uri);
|
|
444
|
+
}
|
|
445
|
+
}
|
|
446
|
+
this.collectNamespaceDeclarations(value);
|
|
447
|
+
}
|
|
448
|
+
}
|
|
449
|
+
/**
|
|
450
|
+
* Определяет префикс для URI пространства имён.
|
|
451
|
+
*
|
|
452
|
+
* Если префикс не объявлен в документе, подбирается свободный
|
|
453
|
+
* (`tns` или `ns1`, `ns2`, ...), чтобы префикс всегда можно было объявить.
|
|
454
|
+
*/
|
|
455
|
+
resolveNamespacePrefix(uri) {
|
|
456
|
+
if (!uri) {
|
|
457
|
+
return void 0;
|
|
458
|
+
}
|
|
459
|
+
const declared = this.namespacePrefixByUri.get(uri);
|
|
460
|
+
if (declared) {
|
|
461
|
+
return declared;
|
|
462
|
+
}
|
|
463
|
+
if (!this.namespaceUriByPrefix.has("tns")) {
|
|
464
|
+
this.registerNamespacePrefix("tns", uri);
|
|
465
|
+
return "tns";
|
|
466
|
+
}
|
|
467
|
+
let index = 1;
|
|
468
|
+
while (this.namespaceUriByPrefix.has(`ns${index}`)) {
|
|
469
|
+
index++;
|
|
470
|
+
}
|
|
471
|
+
const prefix = `ns${index}`;
|
|
472
|
+
this.registerNamespacePrefix(prefix, uri);
|
|
473
|
+
return prefix;
|
|
474
|
+
}
|
|
475
|
+
/**
|
|
476
|
+
* Регистрирует пространство имён элемента.
|
|
477
|
+
*
|
|
478
|
+
* Квалифицированный элемент всегда выигрывает у неквалифицированного
|
|
479
|
+
* с тем же локальным именем.
|
|
480
|
+
*/
|
|
481
|
+
registerElementNamespace(name, prefix) {
|
|
482
|
+
if (!name) {
|
|
483
|
+
return;
|
|
484
|
+
}
|
|
485
|
+
if (prefix) {
|
|
486
|
+
const known = this.qualifiedElements.get(name);
|
|
487
|
+
if (known === void 0) {
|
|
488
|
+
this.qualifiedElements.set(name, prefix);
|
|
489
|
+
} else if (known !== prefix) {
|
|
490
|
+
this.ambiguousElements.add(name);
|
|
491
|
+
}
|
|
492
|
+
this.unqualifiedElements.delete(name);
|
|
493
|
+
return;
|
|
494
|
+
}
|
|
495
|
+
if (!this.qualifiedElements.has(name)) {
|
|
496
|
+
this.unqualifiedElements.add(name);
|
|
497
|
+
}
|
|
498
|
+
}
|
|
341
499
|
/**
|
|
342
500
|
* Извлекает текст документации из XML-узла.
|
|
343
501
|
*
|
|
@@ -575,6 +733,8 @@ ${indent} */
|
|
|
575
733
|
if (!schema) {
|
|
576
734
|
return;
|
|
577
735
|
}
|
|
736
|
+
this.collectNamespaceDeclarations(schema);
|
|
737
|
+
const context = this.createSchemaContext(schema);
|
|
578
738
|
for (const key of Object.keys(schema)) {
|
|
579
739
|
const cleanKey = this.cleanPrefix(key);
|
|
580
740
|
if (["import", "include"].includes(cleanKey)) {
|
|
@@ -596,7 +756,7 @@ ${indent} */
|
|
|
596
756
|
if (!ct?.$name) {
|
|
597
757
|
continue;
|
|
598
758
|
}
|
|
599
|
-
this.parseComplexType(ct.$name, ct);
|
|
759
|
+
this.parseComplexType(ct.$name, ct, context);
|
|
600
760
|
}
|
|
601
761
|
}
|
|
602
762
|
for (const key of Object.keys(schema)) {
|
|
@@ -620,10 +780,51 @@ ${indent} */
|
|
|
620
780
|
if (!element?.$name) {
|
|
621
781
|
continue;
|
|
622
782
|
}
|
|
623
|
-
this.parseGlobalElement(element);
|
|
783
|
+
this.parseGlobalElement(element, context);
|
|
624
784
|
}
|
|
625
785
|
}
|
|
626
786
|
}
|
|
787
|
+
/**
|
|
788
|
+
* Формирует контекст схемы: целевое пространство имён и правила квалификации.
|
|
789
|
+
*/
|
|
790
|
+
createSchemaContext(schema) {
|
|
791
|
+
const targetNamespace = this.getAttribute(schema, "targetNamespace");
|
|
792
|
+
const formDefault = (this.getAttribute(schema, "elementFormDefault") ?? "unqualified").toLowerCase();
|
|
793
|
+
return {
|
|
794
|
+
targetNamespace,
|
|
795
|
+
prefix: this.resolveNamespacePrefix(targetNamespace),
|
|
796
|
+
elementFormDefault: formDefault === "qualified" ? "qualified" : "unqualified"
|
|
797
|
+
};
|
|
798
|
+
}
|
|
799
|
+
/**
|
|
800
|
+
* Определяет, принадлежит ли элемент целевому пространству имён.
|
|
801
|
+
*
|
|
802
|
+
* Локальные элементы подчиняются `elementFormDefault`,
|
|
803
|
+
* глобальные — всегда квалифицированы.
|
|
804
|
+
*
|
|
805
|
+
* Для ссылок (`ref="pfx:Name"`) берётся пространство имён,
|
|
806
|
+
* объявленное в самом документе, а не пространство текущей схемы.
|
|
807
|
+
*/
|
|
808
|
+
resolveElementPrefix(element, context, isGlobal) {
|
|
809
|
+
const ref = this.getAttribute(element, "ref");
|
|
810
|
+
if (ref) {
|
|
811
|
+
const refPrefix = ref.includes(":") ? ref.split(":")[0] : "";
|
|
812
|
+
const uri = this.namespaceUriByPrefix.get(refPrefix);
|
|
813
|
+
const resolved = uri ? this.namespacePrefixByUri.get(uri) : void 0;
|
|
814
|
+
return resolved ?? context.prefix;
|
|
815
|
+
}
|
|
816
|
+
if (!context.prefix || !context.targetNamespace) {
|
|
817
|
+
return void 0;
|
|
818
|
+
}
|
|
819
|
+
if (isGlobal) {
|
|
820
|
+
return context.prefix;
|
|
821
|
+
}
|
|
822
|
+
const form = this.getAttribute(element, "form");
|
|
823
|
+
if (form) {
|
|
824
|
+
return form.toLowerCase() === "qualified" ? context.prefix : void 0;
|
|
825
|
+
}
|
|
826
|
+
return context.elementFormDefault === "qualified" ? context.prefix : void 0;
|
|
827
|
+
}
|
|
627
828
|
/**
|
|
628
829
|
* Регистрирует глобальный XSD element.
|
|
629
830
|
*
|
|
@@ -635,11 +836,12 @@ ${indent} */
|
|
|
635
836
|
*
|
|
636
837
|
* FetchBooking -> FetchBookingRequest
|
|
637
838
|
*/
|
|
638
|
-
parseGlobalElement(element) {
|
|
839
|
+
parseGlobalElement(element, context) {
|
|
639
840
|
const name = element.$name;
|
|
640
841
|
if (!name) {
|
|
641
842
|
return;
|
|
642
843
|
}
|
|
844
|
+
this.registerElementNamespace(name, this.resolveElementPrefix(element, context, true));
|
|
643
845
|
let typeName;
|
|
644
846
|
if (element.$type) {
|
|
645
847
|
typeName = this.mapXSDTypeToTS(element.$type);
|
|
@@ -648,7 +850,7 @@ ${indent} */
|
|
|
648
850
|
const inlineSimpleType = this.getChildNode(element, "simpleType");
|
|
649
851
|
if (inlineComplexType) {
|
|
650
852
|
typeName = `${name}Type`;
|
|
651
|
-
this.parseComplexType(typeName, inlineComplexType);
|
|
853
|
+
this.parseComplexType(typeName, inlineComplexType, context);
|
|
652
854
|
} else if (inlineSimpleType) {
|
|
653
855
|
typeName = `${name}Type`;
|
|
654
856
|
this.parseSimpleType(typeName, inlineSimpleType);
|
|
@@ -657,6 +859,7 @@ ${indent} */
|
|
|
657
859
|
}
|
|
658
860
|
}
|
|
659
861
|
this.globalElementRegistry.set(name, typeName);
|
|
862
|
+
this.elementTypeRegistry.set(name, typeName);
|
|
660
863
|
}
|
|
661
864
|
/**
|
|
662
865
|
* Загружает внешнюю XSD-схему.
|
|
@@ -725,13 +928,16 @@ ${indent} */
|
|
|
725
928
|
/**
|
|
726
929
|
* Разбирает XSD complexType.
|
|
727
930
|
*/
|
|
728
|
-
parseComplexType(name, ctNode) {
|
|
931
|
+
parseComplexType(name, ctNode, context) {
|
|
729
932
|
const complexType = {
|
|
730
933
|
name,
|
|
731
934
|
elements: [],
|
|
732
935
|
attributes: [],
|
|
733
936
|
documentation: this.extractDocumentation(ctNode)
|
|
734
937
|
};
|
|
938
|
+
if (context.prefix) {
|
|
939
|
+
this.typeNamespacePrefix.set(name, context.prefix);
|
|
940
|
+
}
|
|
735
941
|
let baseType;
|
|
736
942
|
const findElementsAndAttributes = (node) => {
|
|
737
943
|
if (!node || typeof node !== "object") {
|
|
@@ -759,23 +965,28 @@ ${indent} */
|
|
|
759
965
|
if (!fieldName) {
|
|
760
966
|
continue;
|
|
761
967
|
}
|
|
968
|
+
const elementName = this.cleanPrefix(fieldName);
|
|
969
|
+
const elementNamespace = this.resolveElementPrefix(element, context, false);
|
|
970
|
+
this.registerElementNamespace(elementName, elementNamespace);
|
|
762
971
|
const inlineComplexType = this.getChildNode(element, "complexType");
|
|
763
972
|
const inlineSimpleType = this.getChildNode(element, "simpleType");
|
|
764
973
|
let elementType = element.$type || element.$ref;
|
|
765
974
|
if (inlineComplexType) {
|
|
766
975
|
elementType = `${this.cleanPrefix(fieldName)}Type`;
|
|
767
|
-
this.parseComplexType(elementType, inlineComplexType);
|
|
976
|
+
this.parseComplexType(elementType, inlineComplexType, context);
|
|
768
977
|
} else if (inlineSimpleType) {
|
|
769
978
|
elementType = `${this.cleanPrefix(fieldName)}Type`;
|
|
770
979
|
this.parseSimpleType(elementType, inlineSimpleType);
|
|
771
980
|
}
|
|
981
|
+
this.elementTypeRegistry.set(elementName, this.cleanPrefix(elementType || "string"));
|
|
772
982
|
complexType.elements.push({
|
|
773
|
-
name:
|
|
983
|
+
name: elementName,
|
|
774
984
|
type: this.mapXSDTypeToTS(elementType || "string"),
|
|
775
985
|
isArray: element.$maxOccurs === "unbounded" || Number(element.$maxOccurs) > 1,
|
|
776
986
|
isOptional: element.$minOccurs === "0" || !element.$minOccurs,
|
|
777
987
|
attributes: this.extractAttributes(element),
|
|
778
|
-
documentation: this.extractDocumentation(element)
|
|
988
|
+
documentation: this.extractDocumentation(element),
|
|
989
|
+
namespace: elementNamespace
|
|
779
990
|
});
|
|
780
991
|
}
|
|
781
992
|
}
|
|
@@ -949,18 +1160,22 @@ ${indent} */
|
|
|
949
1160
|
for (const [name, complexType] of this.typeRegistry.entries()) {
|
|
950
1161
|
code += this.formatDocumentation(complexType.documentation);
|
|
951
1162
|
const baseType = complexType.base;
|
|
1163
|
+
const namespaceField = this.compileNamespaceField(complexType);
|
|
952
1164
|
if (baseType && builtInPrimitives.includes(baseType)) {
|
|
953
|
-
const
|
|
1165
|
+
const attrs = [...complexType.attributes.map((attribute) => `${attribute.name}?: ${attribute.type}`)];
|
|
1166
|
+
const namespaceAttribute = namespaceField.trim();
|
|
1167
|
+
if (namespaceAttribute) {
|
|
1168
|
+
attrs.push(namespaceAttribute);
|
|
1169
|
+
}
|
|
1170
|
+
const attrsObj = attrs.length > 0 ? `{ ${attrs.join("; ")} }` : "{}";
|
|
954
1171
|
code += `export type ${name} = XMLLeaf<${baseType}, ${attrsObj}>;
|
|
955
1172
|
|
|
956
1173
|
`;
|
|
957
1174
|
continue;
|
|
958
1175
|
}
|
|
959
|
-
|
|
960
|
-
code += `export interface ${name}${extendsStr} {
|
|
961
|
-
`;
|
|
1176
|
+
let fields = namespaceField;
|
|
962
1177
|
for (const element of complexType.elements) {
|
|
963
|
-
|
|
1178
|
+
fields += this.formatDocumentation(element.documentation, " ");
|
|
964
1179
|
const optional = element.isOptional ? "?" : "";
|
|
965
1180
|
let type = element.type;
|
|
966
1181
|
const hasAttributes = element.attributes.length > 0;
|
|
@@ -970,17 +1185,134 @@ ${indent} */
|
|
|
970
1185
|
type = isPrimitiveLike ? `XMLLeaf<${type}, ${attributesType}>` : `XMLBranch<${type}, ${attributesType}>`;
|
|
971
1186
|
}
|
|
972
1187
|
const finalType = element.isArray ? `canBeArray<${type}>` : type;
|
|
973
|
-
|
|
1188
|
+
fields += ` ${element.name}${optional}: ${finalType};
|
|
974
1189
|
`;
|
|
975
1190
|
}
|
|
976
1191
|
for (const attribute of complexType.attributes) {
|
|
977
|
-
|
|
978
|
-
|
|
1192
|
+
fields += this.formatDocumentation(attribute.documentation, " ");
|
|
1193
|
+
fields += ` ${attribute.name}?: ${attribute.type};
|
|
979
1194
|
`;
|
|
980
1195
|
}
|
|
981
|
-
|
|
982
|
-
|
|
1196
|
+
const body = baseType ? `${baseType} & {
|
|
1197
|
+
${fields}}` : `{
|
|
1198
|
+
${fields}}`;
|
|
1199
|
+
code += `export type ${name} = XMLBranch<${body}>;
|
|
1200
|
+
|
|
1201
|
+
`;
|
|
1202
|
+
}
|
|
1203
|
+
code += this.compileNamespaceRegistry();
|
|
1204
|
+
return code;
|
|
1205
|
+
}
|
|
1206
|
+
/**
|
|
1207
|
+
* Поле `$namespace` для типа: префикс пространства имён, в котором объявлен тип.
|
|
1208
|
+
*
|
|
1209
|
+
* Поле пропускается, если в типе уже есть XSD-атрибут с именем `namespace`:
|
|
1210
|
+
* иначе возник бы конфликт имён.
|
|
1211
|
+
*/
|
|
1212
|
+
compileNamespaceField(complexType) {
|
|
1213
|
+
const prefix = this.typeNamespacePrefix.get(complexType.name);
|
|
1214
|
+
if (!prefix) {
|
|
1215
|
+
return "";
|
|
1216
|
+
}
|
|
1217
|
+
if (complexType.attributes.some((attribute) => attribute.name === "$namespace")) {
|
|
1218
|
+
return "";
|
|
1219
|
+
}
|
|
1220
|
+
return ` $namespace?: '${prefix}';
|
|
1221
|
+
`;
|
|
1222
|
+
}
|
|
1223
|
+
/**
|
|
1224
|
+
* Генерирует реестр пространств имён для XMLBuilder.
|
|
1225
|
+
*
|
|
1226
|
+
* Реестр сопоставляет локальные имена элементов с префиксами пространств имён,
|
|
1227
|
+
* поэтому XMLBuilder может подставлять префиксы и объявлять `xmlns` автоматически.
|
|
1228
|
+
*/
|
|
1229
|
+
compileNamespaceRegistry() {
|
|
1230
|
+
if (this.qualifiedElements.size === 0 && this.namespaceUriByPrefix.size === 0) {
|
|
1231
|
+
return "";
|
|
983
1232
|
}
|
|
1233
|
+
let code = "";
|
|
1234
|
+
code += "/**\n";
|
|
1235
|
+
code += " * \u041F\u0420\u041E\u0421\u0422\u0420\u0410\u041D\u0421\u0422\u0412\u0410 \u0418\u041C\u0401\u041D, \u0418\u0417\u0412\u041B\u0415\u0427\u0401\u041D\u041D\u042B\u0415 \u0418\u0417 WSDL/XSD\n";
|
|
1236
|
+
code += " *\n";
|
|
1237
|
+
code += " * \u0420\u0435\u0435\u0441\u0442\u0440 \u043C\u043E\u0436\u043D\u043E \u043F\u0435\u0440\u0435\u0434\u0430\u0442\u044C \u0432 XMLBuilder, \u0438 \u0442\u043E\u0433\u0434\u0430 \u043F\u0440\u0435\u0444\u0438\u043A\u0441\u044B \u043F\u0440\u043E\u0441\u0442\u0440\u0430\u043D\u0441\u0442\u0432 \u0438\u043C\u0451\u043D\n";
|
|
1238
|
+
code += " * \u0431\u0443\u0434\u0443\u0442 \u043F\u043E\u0434\u0441\u0442\u0430\u0432\u043B\u044F\u0442\u044C\u0441\u044F \u0430\u0432\u0442\u043E\u043C\u0430\u0442\u0438\u0447\u0435\u0441\u043A\u0438, \u0430 \u043E\u0431\u044A\u044F\u0432\u043B\u0435\u043D\u0438\u044F `xmlns:*` \u2014 \u0434\u043E\u0431\u0430\u0432\u043B\u044F\u0442\u044C\u0441\u044F\n";
|
|
1239
|
+
code += " * \u0432 \u043A\u043E\u0440\u043D\u0435\u0432\u043E\u0439 \u044D\u043B\u0435\u043C\u0435\u043D\u0442:\n";
|
|
1240
|
+
code += " *\n";
|
|
1241
|
+
code += " * new XMLBuilder(request, { namespaces: XMLNamespaceRegistry }).toXML();\n";
|
|
1242
|
+
code += " */\n\n";
|
|
1243
|
+
code += "export const XMLNamespacePrefixes = {\n";
|
|
1244
|
+
for (const [prefix, uri] of this.namespaceUriByPrefix.entries()) {
|
|
1245
|
+
code += ` ${JSON.stringify(prefix)}: ${JSON.stringify(uri)},
|
|
1246
|
+
`;
|
|
1247
|
+
}
|
|
1248
|
+
code += "} as const;\n\n";
|
|
1249
|
+
code += "export const XMLNamespaceElements = {\n";
|
|
1250
|
+
for (const [element, prefix] of this.qualifiedElements.entries()) {
|
|
1251
|
+
code += ` ${JSON.stringify(element)}: ${JSON.stringify(prefix)},
|
|
1252
|
+
`;
|
|
1253
|
+
}
|
|
1254
|
+
code += "} as const;\n\n";
|
|
1255
|
+
const children = this.compileNamespaceChildren();
|
|
1256
|
+
if (children) {
|
|
1257
|
+
code += "/**\n";
|
|
1258
|
+
code += " * \u041F\u0440\u043E\u0441\u0442\u0440\u0430\u043D\u0441\u0442\u0432\u0430 \u0438\u043C\u0451\u043D \u0434\u043E\u0447\u0435\u0440\u043D\u0438\u0445 \u044D\u043B\u0435\u043C\u0435\u043D\u0442\u043E\u0432: \u0440\u043E\u0434\u0438\u0442\u0435\u043B\u044C -> { \u044D\u043B\u0435\u043C\u0435\u043D\u0442 -> \u043F\u0440\u0435\u0444\u0438\u043A\u0441 }.\n";
|
|
1259
|
+
code += " *\n";
|
|
1260
|
+
code += " * \u0417\u0430\u043F\u043E\u043B\u043D\u044F\u0435\u0442\u0441\u044F \u0434\u043B\u044F \u044D\u043B\u0435\u043C\u0435\u043D\u0442\u043E\u0432, \u043E\u0431\u044A\u044F\u0432\u043B\u0435\u043D\u043D\u044B\u0445 \u0441\u0440\u0430\u0437\u0443 \u0432 \u043D\u0435\u0441\u043A\u043E\u043B\u044C\u043A\u0438\u0445 \u043F\u0440\u043E\u0441\u0442\u0440\u0430\u043D\u0441\u0442\u0432\u0430\u0445 \u0438\u043C\u0451\u043D:\n";
|
|
1261
|
+
code += " * \u043F\u043E \u043E\u0434\u043D\u043E\u043C\u0443 \u0438\u043C\u0435\u043D\u0438 \u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430 \u043F\u0440\u0435\u0444\u0438\u043A\u0441 \u043E\u043F\u0440\u0435\u0434\u0435\u043B\u0438\u0442\u044C \u043E\u0434\u043D\u043E\u0437\u043D\u0430\u0447\u043D\u043E \u043D\u0435\u043B\u044C\u0437\u044F,\n";
|
|
1262
|
+
code += " * \u043F\u043E\u044D\u0442\u043E\u043C\u0443 \u0443\u0447\u0438\u0442\u044B\u0432\u0430\u0435\u0442\u0441\u044F \u043A\u043E\u043D\u0442\u0435\u043A\u0441\u0442 \u0440\u043E\u0434\u0438\u0442\u0435\u043B\u044F.\n";
|
|
1263
|
+
code += " */\n\n";
|
|
1264
|
+
code += children;
|
|
1265
|
+
}
|
|
1266
|
+
code += "export const XMLNamespaceRegistry = {\n";
|
|
1267
|
+
code += " prefixes: XMLNamespacePrefixes,\n";
|
|
1268
|
+
code += " elements: XMLNamespaceElements,\n";
|
|
1269
|
+
if (children) {
|
|
1270
|
+
code += " children: XMLNamespaceChildren,\n";
|
|
1271
|
+
}
|
|
1272
|
+
code += "} as const;\n\n";
|
|
1273
|
+
return code;
|
|
1274
|
+
}
|
|
1275
|
+
/**
|
|
1276
|
+
* Собирает карту «родитель -> { дочерний элемент -> префикс }».
|
|
1277
|
+
*
|
|
1278
|
+
* В карту попадают только неоднозначные элементы — те, что объявлены
|
|
1279
|
+
* в нескольких пространствах имён. Для остальных достаточно общего реестра.
|
|
1280
|
+
*/
|
|
1281
|
+
compileNamespaceChildren() {
|
|
1282
|
+
const children = {};
|
|
1283
|
+
for (const [elementName, typeName] of this.elementTypeRegistry.entries()) {
|
|
1284
|
+
const type = this.typeRegistry.get(typeName);
|
|
1285
|
+
if (!type) {
|
|
1286
|
+
continue;
|
|
1287
|
+
}
|
|
1288
|
+
const map = {};
|
|
1289
|
+
for (const element of type.elements) {
|
|
1290
|
+
if (!element.namespace) {
|
|
1291
|
+
continue;
|
|
1292
|
+
}
|
|
1293
|
+
if (!this.ambiguousElements.has(element.name)) {
|
|
1294
|
+
continue;
|
|
1295
|
+
}
|
|
1296
|
+
map[element.name] = element.namespace;
|
|
1297
|
+
}
|
|
1298
|
+
if (Object.keys(map).length > 0) {
|
|
1299
|
+
children[elementName] = map;
|
|
1300
|
+
}
|
|
1301
|
+
}
|
|
1302
|
+
if (Object.keys(children).length === 0) {
|
|
1303
|
+
return "";
|
|
1304
|
+
}
|
|
1305
|
+
let code = "export const XMLNamespaceChildren = {\n";
|
|
1306
|
+
for (const [parent, map] of Object.entries(children)) {
|
|
1307
|
+
code += ` ${JSON.stringify(parent)}: {
|
|
1308
|
+
`;
|
|
1309
|
+
for (const [child, prefix] of Object.entries(map)) {
|
|
1310
|
+
code += ` ${JSON.stringify(child)}: ${JSON.stringify(prefix)},
|
|
1311
|
+
`;
|
|
1312
|
+
}
|
|
1313
|
+
code += " },\n";
|
|
1314
|
+
}
|
|
1315
|
+
code += "} as const;\n\n";
|
|
984
1316
|
return code;
|
|
985
1317
|
}
|
|
986
1318
|
};
|
|
@@ -1001,12 +1333,17 @@ function getXMLValue(value) {
|
|
|
1001
1333
|
function isXMLRecord(value) {
|
|
1002
1334
|
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
1003
1335
|
}
|
|
1004
|
-
function getXMLAttributes(value) {
|
|
1336
|
+
function getXMLAttributes(value, ctx) {
|
|
1005
1337
|
return Object.entries(value).filter(([key]) => key.startsWith("$") && key !== "$value" && key !== "$namespace").map(([key, attrValue]) => {
|
|
1006
1338
|
const name = key.slice(1);
|
|
1007
1339
|
if (!name || !/^[A-Za-z_][\w.:-]*$/.test(name)) {
|
|
1008
1340
|
throw new Error(`Invalid XML attribute name: ${name}`);
|
|
1009
1341
|
}
|
|
1342
|
+
if (key.startsWith("$xmlns:")) {
|
|
1343
|
+
ctx.declaredPrefixes.add(key.slice("$xmlns:".length));
|
|
1344
|
+
} else if (key === "$xmlns") {
|
|
1345
|
+
ctx.declaredPrefixes.add("");
|
|
1346
|
+
}
|
|
1010
1347
|
if (attrValue === null || attrValue === void 0) {
|
|
1011
1348
|
return "";
|
|
1012
1349
|
}
|
|
@@ -1016,64 +1353,125 @@ function getXMLAttributes(value) {
|
|
|
1016
1353
|
return ` ${name}="${escapeXMLAttribute(String(attrValue))}"`;
|
|
1017
1354
|
}).join("");
|
|
1018
1355
|
}
|
|
1019
|
-
function
|
|
1020
|
-
if (
|
|
1021
|
-
|
|
1356
|
+
function resolveElementPrefix(tag, value, ctx, parentTag) {
|
|
1357
|
+
if (isXMLRecord(value) && value.$namespace !== void 0) {
|
|
1358
|
+
const namespace = value.$namespace;
|
|
1359
|
+
if (typeof namespace !== "string" || namespace !== "" && !/^[A-Za-z_][\w.-]*$/.test(namespace)) {
|
|
1360
|
+
throw new Error(`Invalid XML namespace prefix: ${namespace}`);
|
|
1361
|
+
}
|
|
1362
|
+
return namespace;
|
|
1022
1363
|
}
|
|
1023
|
-
if (
|
|
1024
|
-
return
|
|
1364
|
+
if (tag.includes(":")) {
|
|
1365
|
+
return void 0;
|
|
1025
1366
|
}
|
|
1026
|
-
const
|
|
1027
|
-
if (
|
|
1028
|
-
|
|
1029
|
-
|
|
1367
|
+
const contextual = parentTag ? ctx.children[parentTag]?.[tag] : void 0;
|
|
1368
|
+
if (contextual !== void 0) {
|
|
1369
|
+
return contextual;
|
|
1370
|
+
}
|
|
1371
|
+
const mapped = ctx.elements[tag];
|
|
1372
|
+
return mapped === void 0 ? void 0 : mapped;
|
|
1373
|
+
}
|
|
1374
|
+
function buildNamespaceDeclarations(ctx) {
|
|
1375
|
+
let declarations = "";
|
|
1376
|
+
for (const prefix of ctx.usedPrefixes) {
|
|
1377
|
+
if (ctx.declaredPrefixes.has(prefix)) {
|
|
1378
|
+
continue;
|
|
1379
|
+
}
|
|
1380
|
+
const uri = ctx.prefixes[prefix];
|
|
1381
|
+
if (!uri) {
|
|
1382
|
+
continue;
|
|
1030
1383
|
}
|
|
1031
|
-
|
|
1384
|
+
declarations += ` xmlns:${prefix}="${escapeXMLAttribute(uri)}"`;
|
|
1385
|
+
}
|
|
1386
|
+
return declarations;
|
|
1387
|
+
}
|
|
1388
|
+
function serializeElementParts(tag, value, ctx, parentTag) {
|
|
1389
|
+
if (!/^[A-Za-z_][\w.:-]*$/.test(tag)) {
|
|
1390
|
+
throw new Error(`Invalid XML tag name: ${tag}`);
|
|
1032
1391
|
}
|
|
1392
|
+
const prefix = resolveElementPrefix(tag, value, ctx, parentTag);
|
|
1393
|
+
if (prefix) {
|
|
1394
|
+
ctx.usedPrefixes.add(prefix);
|
|
1395
|
+
}
|
|
1396
|
+
const tagName = prefix ? `${prefix}:${tag}` : tag;
|
|
1033
1397
|
let attributes = "";
|
|
1034
1398
|
let content = "";
|
|
1035
1399
|
if (isXMLNode(value)) {
|
|
1036
|
-
attributes = getXMLAttributes(value);
|
|
1400
|
+
attributes = getXMLAttributes(value, ctx);
|
|
1037
1401
|
content = escapeXMLText(String(getXMLValue(value) ?? ""));
|
|
1038
1402
|
} else if (isXMLRecord(value)) {
|
|
1039
|
-
attributes = getXMLAttributes(value);
|
|
1403
|
+
attributes = getXMLAttributes(value, ctx);
|
|
1040
1404
|
const children = Object.entries(value).filter(([key]) => !key.startsWith("$"));
|
|
1041
1405
|
if (children.length > 0) {
|
|
1042
|
-
content = children.map(([key, childValue]) => serializeXMLElement(key, childValue)).join("");
|
|
1406
|
+
content = children.map(([key, childValue]) => serializeXMLElement(key, childValue, ctx, tag)).join("");
|
|
1043
1407
|
} else if (attributes) {
|
|
1044
1408
|
const text = value.$value;
|
|
1045
1409
|
content = text == null ? "" : escapeXMLText(String(text));
|
|
1046
1410
|
} else if ("$value" in value) {
|
|
1047
|
-
throw new Error(`XML element "${
|
|
1411
|
+
throw new Error(`XML element "${tagName}": $value requires at least one attribute`);
|
|
1048
1412
|
}
|
|
1049
1413
|
} else {
|
|
1050
1414
|
content = value == null ? "" : escapeXMLText(String(value));
|
|
1051
1415
|
}
|
|
1052
|
-
|
|
1053
|
-
|
|
1416
|
+
return { tagName, attributes, content };
|
|
1417
|
+
}
|
|
1418
|
+
function composeElement(parts) {
|
|
1419
|
+
if (!parts.content) {
|
|
1420
|
+
return `<${parts.tagName}${parts.attributes}/>`;
|
|
1421
|
+
}
|
|
1422
|
+
return `<${parts.tagName}${parts.attributes}>${parts.content}</${parts.tagName}>`;
|
|
1423
|
+
}
|
|
1424
|
+
function serializeXMLElement(tag, value, ctx, parentTag) {
|
|
1425
|
+
if (Array.isArray(value)) {
|
|
1426
|
+
return value.map((item) => serializeXMLElement(tag, item, ctx, parentTag)).join("");
|
|
1054
1427
|
}
|
|
1055
|
-
return
|
|
1428
|
+
return composeElement(serializeElementParts(tag, value, ctx, parentTag));
|
|
1056
1429
|
}
|
|
1057
1430
|
var XMLBuilder = class {
|
|
1058
1431
|
$input;
|
|
1059
|
-
|
|
1432
|
+
$options;
|
|
1433
|
+
constructor(obj, options = {}) {
|
|
1060
1434
|
this.$input = obj;
|
|
1435
|
+
this.$options = options;
|
|
1061
1436
|
}
|
|
1062
1437
|
toXML(config = {}) {
|
|
1438
|
+
const options = { ...this.$options, ...config };
|
|
1439
|
+
const registry = options.namespaces ?? {};
|
|
1440
|
+
const ctx = {
|
|
1441
|
+
prefixes: registry.prefixes ?? {},
|
|
1442
|
+
elements: registry.elements ?? {},
|
|
1443
|
+
children: registry.children ?? {},
|
|
1444
|
+
usedPrefixes: /* @__PURE__ */ new Set(),
|
|
1445
|
+
declaredPrefixes: /* @__PURE__ */ new Set()
|
|
1446
|
+
};
|
|
1063
1447
|
const entries = Object.entries(this.$input);
|
|
1064
1448
|
if (entries.length !== 1) {
|
|
1065
1449
|
throw new Error("XML must contain exactly one root element");
|
|
1066
1450
|
}
|
|
1067
1451
|
const [rootTag, rootValue] = entries[0];
|
|
1068
|
-
const
|
|
1069
|
-
|
|
1452
|
+
const rootParts = Array.isArray(rootValue) ? rootValue.map((item) => serializeElementParts(rootTag, item, ctx)) : [serializeElementParts(rootTag, rootValue, ctx)];
|
|
1453
|
+
const declarations = buildNamespaceDeclarations(ctx);
|
|
1454
|
+
if (rootParts.length > 0) {
|
|
1455
|
+
rootParts[0] = {
|
|
1456
|
+
...rootParts[0],
|
|
1457
|
+
attributes: `${rootParts[0].attributes}${declarations}`
|
|
1458
|
+
};
|
|
1459
|
+
}
|
|
1460
|
+
const xml = rootParts.map((parts) => composeElement(parts)).join("");
|
|
1461
|
+
if (options.declaration) {
|
|
1070
1462
|
return `<?xml version="1.0" encoding="UTF-8"?>${xml}`;
|
|
1071
1463
|
}
|
|
1072
1464
|
return xml;
|
|
1073
1465
|
}
|
|
1074
1466
|
};
|
|
1467
|
+
|
|
1468
|
+
// src/utils/asArray.ts
|
|
1469
|
+
var asArray = (value) => {
|
|
1470
|
+
return Array.isArray(value) ? value : [value];
|
|
1471
|
+
};
|
|
1075
1472
|
export {
|
|
1076
1473
|
WSDLTypeGenerator,
|
|
1077
1474
|
XMLBuilder,
|
|
1078
|
-
XMLParser
|
|
1475
|
+
XMLParser,
|
|
1476
|
+
asArray
|
|
1079
1477
|
};
|