xmljslib 1.0.2 → 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/index.cjs CHANGED
@@ -32,7 +32,8 @@ var index_exports = {};
32
32
  __export(index_exports, {
33
33
  WSDLTypeGenerator: () => WSDLTypeGenerator,
34
34
  XMLBuilder: () => XMLBuilder,
35
- XMLParser: () => XMLParser
35
+ XMLParser: () => XMLParser,
36
+ asArray: () => asArray
36
37
  });
37
38
  module.exports = __toCommonJS(index_exports);
38
39
 
@@ -63,13 +64,25 @@ function createXMLNode(value, attributes = {}, isLeaf = false) {
63
64
  if (!hasAttributes) {
64
65
  return parsedValue;
65
66
  }
66
- const targetObj = Object(parsedValue !== void 0 ? parsedValue : "");
67
+ const attributeValue = Object.prototype.hasOwnProperty.call(attributes, "value") ? parsePrimitive(attributes.value) : void 0;
68
+ const nodeValue = parsedValue !== void 0 ? parsedValue : attributeValue;
69
+ const targetObj = Object(nodeValue !== void 0 ? nodeValue : "");
67
70
  for (const [key, attrVal] of Object.entries(attributes)) {
71
+ if (key === "value") {
72
+ continue;
73
+ }
68
74
  targetObj[`$${key}`] = parsePrimitive(attrVal);
69
75
  }
76
+ Object.defineProperty(targetObj, "$value", {
77
+ value: nodeValue,
78
+ writable: true,
79
+ enumerable: true,
80
+ configurable: true
81
+ });
70
82
  return new Proxy(targetObj, {
71
83
  get(target, prop) {
72
84
  if (prop === "__isXMLNode") return true;
85
+ if (prop === "$value") return nodeValue;
73
86
  if (prop === "valueOf" || prop === Symbol.toPrimitive) {
74
87
  return () => parsedValue;
75
88
  }
@@ -156,10 +169,14 @@ var XMLParser = class _XMLParser {
156
169
  static parseTreeJSON(item) {
157
170
  const result = {};
158
171
  const node = {};
172
+ const attributeValue = Object.prototype.hasOwnProperty.call(item.attributes, "value") ? item.attributes.value : void 0;
173
+ node.$value = item.$value !== null ? item.$value : attributeValue ?? null;
159
174
  for (const attr of Object.keys(item.attributes)) {
175
+ if (attr === "value") {
176
+ continue;
177
+ }
160
178
  node[`$${attr}`] = item.attributes[attr];
161
179
  }
162
- node.$value = item.$value;
163
180
  for (const child of item.children) {
164
181
  const parsed = _XMLParser.parseTreeJSON(child);
165
182
  const childValue = parsed[child.tag];
@@ -294,7 +311,7 @@ var XMLParser = class _XMLParser {
294
311
  };
295
312
 
296
313
  // src/lib/wsdlTypeGenerator.ts
297
- var WSDLTypeGenerator = class {
314
+ var WSDLTypeGenerator = class _WSDLTypeGenerator {
298
315
  typeRegistry = /* @__PURE__ */ new Map();
299
316
  simpleTypeRegistry = /* @__PURE__ */ new Map();
300
317
  simpleTypeDocumentationRegistry = /* @__PURE__ */ new Map();
@@ -309,6 +326,40 @@ var WSDLTypeGenerator = class {
309
326
  globalElementRegistry = /* @__PURE__ */ new Map();
310
327
  baseUrl = "";
311
328
  loadedUrls = /* @__PURE__ */ new Set();
329
+ /**
330
+ * Пространства имён, объявленные в документе (`xmlns:*`).
331
+ * Используются и для автоподстановки префиксов, и для объявления `xmlns` в XML.
332
+ */
333
+ namespaceUriByPrefix = /* @__PURE__ */ new Map();
334
+ namespacePrefixByUri = /* @__PURE__ */ new Map();
335
+ /**
336
+ * Пространства имён элементов: локальное имя элемента -> префикс.
337
+ *
338
+ * Квалифицированные элементы хранятся в `qualifiedElements`,
339
+ * неквалифицированные — в `unqualifiedElements`, чтобы одноимённые элементы
340
+ * из разных схем не конфликтовали: квалифицированный всегда выигрывает.
341
+ */
342
+ qualifiedElements = /* @__PURE__ */ new Map();
343
+ unqualifiedElements = /* @__PURE__ */ new Set();
344
+ /**
345
+ * Имена элементов, объявленных в нескольких пространствах имён.
346
+ * Для таких элементов одного префикса «по имени» недостаточно —
347
+ * нужен контекст родителя.
348
+ */
349
+ ambiguousElements = /* @__PURE__ */ new Set();
350
+ /**
351
+ * Тип каждого элемента: имя элемента -> имя типа в реестре complexType.
352
+ * Нужен, чтобы знать состав дочерних элементов.
353
+ */
354
+ elementTypeRegistry = /* @__PURE__ */ new Map();
355
+ /**
356
+ * Пространства имён типов: имя complexType -> префикс.
357
+ */
358
+ typeNamespacePrefix = /* @__PURE__ */ new Map();
359
+ /**
360
+ * Пространство имён XML Schema. Не имеет отношения к данным сервиса.
361
+ */
362
+ static XML_SCHEMA_NAMESPACE = "http://www.w3.org/2001/XMLSchema";
312
363
  get complexTypeCount() {
313
364
  return this.typeRegistry.size;
314
365
  }
@@ -331,8 +382,17 @@ var WSDLTypeGenerator = class {
331
382
  this.messageRegistry.clear();
332
383
  this.globalElementRegistry.clear();
333
384
  this.loadedUrls.clear();
385
+ this.namespaceUriByPrefix.clear();
386
+ this.namespacePrefixByUri.clear();
387
+ this.qualifiedElements.clear();
388
+ this.unqualifiedElements.clear();
389
+ this.ambiguousElements.clear();
390
+ this.elementTypeRegistry.clear();
391
+ this.typeNamespacePrefix.clear();
334
392
  console.log("\u{1F4E6} \u041F\u0430\u0440\u0441\u0438\u043D\u0433 \u0441\u0442\u0440\u0443\u043A\u0442\u0443\u0440\u044B XML...");
335
393
  const wsdl = new XMLParser(xmlContent, config);
394
+ 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...");
395
+ this.collectNamespaceDeclarations(wsdl);
336
396
  console.log("\u{1F50D} \u0410\u043D\u0430\u043B\u0438\u0437 WSDL \u0441\u043E\u043E\u0431\u0449\u0435\u043D\u0438\u0439...");
337
397
  this.extractMessages(wsdl);
338
398
  console.log("\u{1F50D} \u0410\u043D\u0430\u043B\u0438\u0437 WSDL \u043E\u043F\u0435\u0440\u0430\u0446\u0438\u0439...");
@@ -375,6 +435,106 @@ var WSDLTypeGenerator = class {
375
435
  const primitive = typeof value.valueOf === "function" ? value.valueOf() : value;
376
436
  return String(primitive);
377
437
  }
438
+ /**
439
+ * Приводит значение узла к строке.
440
+ */
441
+ toPrimitiveString(value) {
442
+ if (value === null || value === void 0) {
443
+ return void 0;
444
+ }
445
+ const primitive = typeof value.valueOf === "function" ? value.valueOf() : value;
446
+ if (primitive === null || primitive === void 0) {
447
+ return void 0;
448
+ }
449
+ const text = String(primitive).trim();
450
+ return text.length > 0 ? text : void 0;
451
+ }
452
+ /**
453
+ * Регистрирует связь префикс <-> URI пространства имён.
454
+ * Первые объявления имеют приоритет: префикс не переопределяется.
455
+ */
456
+ registerNamespacePrefix(prefix, uri) {
457
+ if (!this.namespaceUriByPrefix.has(prefix)) {
458
+ this.namespaceUriByPrefix.set(prefix, uri);
459
+ }
460
+ if (!this.namespacePrefixByUri.has(uri)) {
461
+ this.namespacePrefixByUri.set(uri, prefix);
462
+ }
463
+ }
464
+ /**
465
+ * Собирает объявления пространств имён (`xmlns:*`) из всего документа.
466
+ */
467
+ collectNamespaceDeclarations(node) {
468
+ if (!node || typeof node !== "object") {
469
+ return;
470
+ }
471
+ if (Array.isArray(node)) {
472
+ for (const item of node) {
473
+ this.collectNamespaceDeclarations(item);
474
+ }
475
+ return;
476
+ }
477
+ for (const [key, value] of Object.entries(node)) {
478
+ if (key.startsWith("$xmlns:")) {
479
+ const prefix = key.slice("$xmlns:".length);
480
+ const uri = this.toPrimitiveString(value);
481
+ if (prefix && uri && uri !== _WSDLTypeGenerator.XML_SCHEMA_NAMESPACE) {
482
+ this.registerNamespacePrefix(prefix, uri);
483
+ }
484
+ }
485
+ this.collectNamespaceDeclarations(value);
486
+ }
487
+ }
488
+ /**
489
+ * Определяет префикс для URI пространства имён.
490
+ *
491
+ * Если префикс не объявлен в документе, подбирается свободный
492
+ * (`tns` или `ns1`, `ns2`, ...), чтобы префикс всегда можно было объявить.
493
+ */
494
+ resolveNamespacePrefix(uri) {
495
+ if (!uri) {
496
+ return void 0;
497
+ }
498
+ const declared = this.namespacePrefixByUri.get(uri);
499
+ if (declared) {
500
+ return declared;
501
+ }
502
+ if (!this.namespaceUriByPrefix.has("tns")) {
503
+ this.registerNamespacePrefix("tns", uri);
504
+ return "tns";
505
+ }
506
+ let index = 1;
507
+ while (this.namespaceUriByPrefix.has(`ns${index}`)) {
508
+ index++;
509
+ }
510
+ const prefix = `ns${index}`;
511
+ this.registerNamespacePrefix(prefix, uri);
512
+ return prefix;
513
+ }
514
+ /**
515
+ * Регистрирует пространство имён элемента.
516
+ *
517
+ * Квалифицированный элемент всегда выигрывает у неквалифицированного
518
+ * с тем же локальным именем.
519
+ */
520
+ registerElementNamespace(name, prefix) {
521
+ if (!name) {
522
+ return;
523
+ }
524
+ if (prefix) {
525
+ const known = this.qualifiedElements.get(name);
526
+ if (known === void 0) {
527
+ this.qualifiedElements.set(name, prefix);
528
+ } else if (known !== prefix) {
529
+ this.ambiguousElements.add(name);
530
+ }
531
+ this.unqualifiedElements.delete(name);
532
+ return;
533
+ }
534
+ if (!this.qualifiedElements.has(name)) {
535
+ this.unqualifiedElements.add(name);
536
+ }
537
+ }
378
538
  /**
379
539
  * Извлекает текст документации из XML-узла.
380
540
  *
@@ -612,6 +772,8 @@ ${indent} */
612
772
  if (!schema) {
613
773
  return;
614
774
  }
775
+ this.collectNamespaceDeclarations(schema);
776
+ const context = this.createSchemaContext(schema);
615
777
  for (const key of Object.keys(schema)) {
616
778
  const cleanKey = this.cleanPrefix(key);
617
779
  if (["import", "include"].includes(cleanKey)) {
@@ -633,7 +795,7 @@ ${indent} */
633
795
  if (!ct?.$name) {
634
796
  continue;
635
797
  }
636
- this.parseComplexType(ct.$name, ct);
798
+ this.parseComplexType(ct.$name, ct, context);
637
799
  }
638
800
  }
639
801
  for (const key of Object.keys(schema)) {
@@ -657,10 +819,51 @@ ${indent} */
657
819
  if (!element?.$name) {
658
820
  continue;
659
821
  }
660
- this.parseGlobalElement(element);
822
+ this.parseGlobalElement(element, context);
661
823
  }
662
824
  }
663
825
  }
826
+ /**
827
+ * Формирует контекст схемы: целевое пространство имён и правила квалификации.
828
+ */
829
+ createSchemaContext(schema) {
830
+ const targetNamespace = this.getAttribute(schema, "targetNamespace");
831
+ const formDefault = (this.getAttribute(schema, "elementFormDefault") ?? "unqualified").toLowerCase();
832
+ return {
833
+ targetNamespace,
834
+ prefix: this.resolveNamespacePrefix(targetNamespace),
835
+ elementFormDefault: formDefault === "qualified" ? "qualified" : "unqualified"
836
+ };
837
+ }
838
+ /**
839
+ * Определяет, принадлежит ли элемент целевому пространству имён.
840
+ *
841
+ * Локальные элементы подчиняются `elementFormDefault`,
842
+ * глобальные — всегда квалифицированы.
843
+ *
844
+ * Для ссылок (`ref="pfx:Name"`) берётся пространство имён,
845
+ * объявленное в самом документе, а не пространство текущей схемы.
846
+ */
847
+ resolveElementPrefix(element, context, isGlobal) {
848
+ const ref = this.getAttribute(element, "ref");
849
+ if (ref) {
850
+ const refPrefix = ref.includes(":") ? ref.split(":")[0] : "";
851
+ const uri = this.namespaceUriByPrefix.get(refPrefix);
852
+ const resolved = uri ? this.namespacePrefixByUri.get(uri) : void 0;
853
+ return resolved ?? context.prefix;
854
+ }
855
+ if (!context.prefix || !context.targetNamespace) {
856
+ return void 0;
857
+ }
858
+ if (isGlobal) {
859
+ return context.prefix;
860
+ }
861
+ const form = this.getAttribute(element, "form");
862
+ if (form) {
863
+ return form.toLowerCase() === "qualified" ? context.prefix : void 0;
864
+ }
865
+ return context.elementFormDefault === "qualified" ? context.prefix : void 0;
866
+ }
664
867
  /**
665
868
  * Регистрирует глобальный XSD element.
666
869
  *
@@ -672,11 +875,12 @@ ${indent} */
672
875
  *
673
876
  * FetchBooking -> FetchBookingRequest
674
877
  */
675
- parseGlobalElement(element) {
878
+ parseGlobalElement(element, context) {
676
879
  const name = element.$name;
677
880
  if (!name) {
678
881
  return;
679
882
  }
883
+ this.registerElementNamespace(name, this.resolveElementPrefix(element, context, true));
680
884
  let typeName;
681
885
  if (element.$type) {
682
886
  typeName = this.mapXSDTypeToTS(element.$type);
@@ -685,7 +889,7 @@ ${indent} */
685
889
  const inlineSimpleType = this.getChildNode(element, "simpleType");
686
890
  if (inlineComplexType) {
687
891
  typeName = `${name}Type`;
688
- this.parseComplexType(typeName, inlineComplexType);
892
+ this.parseComplexType(typeName, inlineComplexType, context);
689
893
  } else if (inlineSimpleType) {
690
894
  typeName = `${name}Type`;
691
895
  this.parseSimpleType(typeName, inlineSimpleType);
@@ -694,6 +898,7 @@ ${indent} */
694
898
  }
695
899
  }
696
900
  this.globalElementRegistry.set(name, typeName);
901
+ this.elementTypeRegistry.set(name, typeName);
697
902
  }
698
903
  /**
699
904
  * Загружает внешнюю XSD-схему.
@@ -762,13 +967,16 @@ ${indent} */
762
967
  /**
763
968
  * Разбирает XSD complexType.
764
969
  */
765
- parseComplexType(name, ctNode) {
970
+ parseComplexType(name, ctNode, context) {
766
971
  const complexType = {
767
972
  name,
768
973
  elements: [],
769
974
  attributes: [],
770
975
  documentation: this.extractDocumentation(ctNode)
771
976
  };
977
+ if (context.prefix) {
978
+ this.typeNamespacePrefix.set(name, context.prefix);
979
+ }
772
980
  let baseType;
773
981
  const findElementsAndAttributes = (node) => {
774
982
  if (!node || typeof node !== "object") {
@@ -796,23 +1004,28 @@ ${indent} */
796
1004
  if (!fieldName) {
797
1005
  continue;
798
1006
  }
1007
+ const elementName = this.cleanPrefix(fieldName);
1008
+ const elementNamespace = this.resolveElementPrefix(element, context, false);
1009
+ this.registerElementNamespace(elementName, elementNamespace);
799
1010
  const inlineComplexType = this.getChildNode(element, "complexType");
800
1011
  const inlineSimpleType = this.getChildNode(element, "simpleType");
801
1012
  let elementType = element.$type || element.$ref;
802
1013
  if (inlineComplexType) {
803
1014
  elementType = `${this.cleanPrefix(fieldName)}Type`;
804
- this.parseComplexType(elementType, inlineComplexType);
1015
+ this.parseComplexType(elementType, inlineComplexType, context);
805
1016
  } else if (inlineSimpleType) {
806
1017
  elementType = `${this.cleanPrefix(fieldName)}Type`;
807
1018
  this.parseSimpleType(elementType, inlineSimpleType);
808
1019
  }
1020
+ this.elementTypeRegistry.set(elementName, this.cleanPrefix(elementType || "string"));
809
1021
  complexType.elements.push({
810
- name: this.cleanPrefix(fieldName),
1022
+ name: elementName,
811
1023
  type: this.mapXSDTypeToTS(elementType || "string"),
812
1024
  isArray: element.$maxOccurs === "unbounded" || Number(element.$maxOccurs) > 1,
813
1025
  isOptional: element.$minOccurs === "0" || !element.$minOccurs,
814
1026
  attributes: this.extractAttributes(element),
815
- documentation: this.extractDocumentation(element)
1027
+ documentation: this.extractDocumentation(element),
1028
+ namespace: elementNamespace
816
1029
  });
817
1030
  }
818
1031
  }
@@ -986,18 +1199,22 @@ ${indent} */
986
1199
  for (const [name, complexType] of this.typeRegistry.entries()) {
987
1200
  code += this.formatDocumentation(complexType.documentation);
988
1201
  const baseType = complexType.base;
1202
+ const namespaceField = this.compileNamespaceField(complexType);
989
1203
  if (baseType && builtInPrimitives.includes(baseType)) {
990
- const attrsObj = complexType.attributes.length > 0 ? `{ ${complexType.attributes.map((attribute) => `${attribute.name}?: ${attribute.type}`).join("; ")} }` : "{}";
1204
+ const attrs = [...complexType.attributes.map((attribute) => `${attribute.name}?: ${attribute.type}`)];
1205
+ const namespaceAttribute = namespaceField.trim();
1206
+ if (namespaceAttribute) {
1207
+ attrs.push(namespaceAttribute);
1208
+ }
1209
+ const attrsObj = attrs.length > 0 ? `{ ${attrs.join("; ")} }` : "{}";
991
1210
  code += `export type ${name} = XMLLeaf<${baseType}, ${attrsObj}>;
992
1211
 
993
1212
  `;
994
1213
  continue;
995
1214
  }
996
- const extendsStr = baseType ? ` extends ${baseType}` : "";
997
- code += `export interface ${name}${extendsStr} {
998
- `;
1215
+ let fields = namespaceField;
999
1216
  for (const element of complexType.elements) {
1000
- code += this.formatDocumentation(element.documentation, " ");
1217
+ fields += this.formatDocumentation(element.documentation, " ");
1001
1218
  const optional = element.isOptional ? "?" : "";
1002
1219
  let type = element.type;
1003
1220
  const hasAttributes = element.attributes.length > 0;
@@ -1007,17 +1224,134 @@ ${indent} */
1007
1224
  type = isPrimitiveLike ? `XMLLeaf<${type}, ${attributesType}>` : `XMLBranch<${type}, ${attributesType}>`;
1008
1225
  }
1009
1226
  const finalType = element.isArray ? `canBeArray<${type}>` : type;
1010
- code += ` ${element.name}${optional}: ${finalType};
1227
+ fields += ` ${element.name}${optional}: ${finalType};
1011
1228
  `;
1012
1229
  }
1013
1230
  for (const attribute of complexType.attributes) {
1014
- code += this.formatDocumentation(attribute.documentation, " ");
1015
- code += ` ${attribute.name}?: ${attribute.type};
1231
+ fields += this.formatDocumentation(attribute.documentation, " ");
1232
+ fields += ` ${attribute.name}?: ${attribute.type};
1016
1233
  `;
1017
1234
  }
1018
- code += " [key: `$xmlns${string}`]: string | undefined;\n";
1019
- code += "}\n\n";
1235
+ const body = baseType ? `${baseType} & {
1236
+ ${fields}}` : `{
1237
+ ${fields}}`;
1238
+ code += `export type ${name} = XMLBranch<${body}>;
1239
+
1240
+ `;
1241
+ }
1242
+ code += this.compileNamespaceRegistry();
1243
+ return code;
1244
+ }
1245
+ /**
1246
+ * Поле `$namespace` для типа: префикс пространства имён, в котором объявлен тип.
1247
+ *
1248
+ * Поле пропускается, если в типе уже есть XSD-атрибут с именем `namespace`:
1249
+ * иначе возник бы конфликт имён.
1250
+ */
1251
+ compileNamespaceField(complexType) {
1252
+ const prefix = this.typeNamespacePrefix.get(complexType.name);
1253
+ if (!prefix) {
1254
+ return "";
1255
+ }
1256
+ if (complexType.attributes.some((attribute) => attribute.name === "$namespace")) {
1257
+ return "";
1258
+ }
1259
+ return ` $namespace?: '${prefix}';
1260
+ `;
1261
+ }
1262
+ /**
1263
+ * Генерирует реестр пространств имён для XMLBuilder.
1264
+ *
1265
+ * Реестр сопоставляет локальные имена элементов с префиксами пространств имён,
1266
+ * поэтому XMLBuilder может подставлять префиксы и объявлять `xmlns` автоматически.
1267
+ */
1268
+ compileNamespaceRegistry() {
1269
+ if (this.qualifiedElements.size === 0 && this.namespaceUriByPrefix.size === 0) {
1270
+ return "";
1020
1271
  }
1272
+ let code = "";
1273
+ code += "/**\n";
1274
+ 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";
1275
+ code += " *\n";
1276
+ 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";
1277
+ 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";
1278
+ code += " * \u0432 \u043A\u043E\u0440\u043D\u0435\u0432\u043E\u0439 \u044D\u043B\u0435\u043C\u0435\u043D\u0442:\n";
1279
+ code += " *\n";
1280
+ code += " * new XMLBuilder(request, { namespaces: XMLNamespaceRegistry }).toXML();\n";
1281
+ code += " */\n\n";
1282
+ code += "export const XMLNamespacePrefixes = {\n";
1283
+ for (const [prefix, uri] of this.namespaceUriByPrefix.entries()) {
1284
+ code += ` ${JSON.stringify(prefix)}: ${JSON.stringify(uri)},
1285
+ `;
1286
+ }
1287
+ code += "} as const;\n\n";
1288
+ code += "export const XMLNamespaceElements = {\n";
1289
+ for (const [element, prefix] of this.qualifiedElements.entries()) {
1290
+ code += ` ${JSON.stringify(element)}: ${JSON.stringify(prefix)},
1291
+ `;
1292
+ }
1293
+ code += "} as const;\n\n";
1294
+ const children = this.compileNamespaceChildren();
1295
+ if (children) {
1296
+ code += "/**\n";
1297
+ 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";
1298
+ code += " *\n";
1299
+ 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";
1300
+ 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";
1301
+ 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";
1302
+ code += " */\n\n";
1303
+ code += children;
1304
+ }
1305
+ code += "export const XMLNamespaceRegistry = {\n";
1306
+ code += " prefixes: XMLNamespacePrefixes,\n";
1307
+ code += " elements: XMLNamespaceElements,\n";
1308
+ if (children) {
1309
+ code += " children: XMLNamespaceChildren,\n";
1310
+ }
1311
+ code += "} as const;\n\n";
1312
+ return code;
1313
+ }
1314
+ /**
1315
+ * Собирает карту «родитель -> { дочерний элемент -> префикс }».
1316
+ *
1317
+ * В карту попадают только неоднозначные элементы — те, что объявлены
1318
+ * в нескольких пространствах имён. Для остальных достаточно общего реестра.
1319
+ */
1320
+ compileNamespaceChildren() {
1321
+ const children = {};
1322
+ for (const [elementName, typeName] of this.elementTypeRegistry.entries()) {
1323
+ const type = this.typeRegistry.get(typeName);
1324
+ if (!type) {
1325
+ continue;
1326
+ }
1327
+ const map = {};
1328
+ for (const element of type.elements) {
1329
+ if (!element.namespace) {
1330
+ continue;
1331
+ }
1332
+ if (!this.ambiguousElements.has(element.name)) {
1333
+ continue;
1334
+ }
1335
+ map[element.name] = element.namespace;
1336
+ }
1337
+ if (Object.keys(map).length > 0) {
1338
+ children[elementName] = map;
1339
+ }
1340
+ }
1341
+ if (Object.keys(children).length === 0) {
1342
+ return "";
1343
+ }
1344
+ let code = "export const XMLNamespaceChildren = {\n";
1345
+ for (const [parent, map] of Object.entries(children)) {
1346
+ code += ` ${JSON.stringify(parent)}: {
1347
+ `;
1348
+ for (const [child, prefix] of Object.entries(map)) {
1349
+ code += ` ${JSON.stringify(child)}: ${JSON.stringify(prefix)},
1350
+ `;
1351
+ }
1352
+ code += " },\n";
1353
+ }
1354
+ code += "} as const;\n\n";
1021
1355
  return code;
1022
1356
  }
1023
1357
  };
@@ -1038,12 +1372,17 @@ function getXMLValue(value) {
1038
1372
  function isXMLRecord(value) {
1039
1373
  return value !== null && typeof value === "object" && !Array.isArray(value);
1040
1374
  }
1041
- function getXMLAttributes(value) {
1375
+ function getXMLAttributes(value, ctx) {
1042
1376
  return Object.entries(value).filter(([key]) => key.startsWith("$") && key !== "$value" && key !== "$namespace").map(([key, attrValue]) => {
1043
1377
  const name = key.slice(1);
1044
1378
  if (!name || !/^[A-Za-z_][\w.:-]*$/.test(name)) {
1045
1379
  throw new Error(`Invalid XML attribute name: ${name}`);
1046
1380
  }
1381
+ if (key.startsWith("$xmlns:")) {
1382
+ ctx.declaredPrefixes.add(key.slice("$xmlns:".length));
1383
+ } else if (key === "$xmlns") {
1384
+ ctx.declaredPrefixes.add("");
1385
+ }
1047
1386
  if (attrValue === null || attrValue === void 0) {
1048
1387
  return "";
1049
1388
  }
@@ -1053,65 +1392,126 @@ function getXMLAttributes(value) {
1053
1392
  return ` ${name}="${escapeXMLAttribute(String(attrValue))}"`;
1054
1393
  }).join("");
1055
1394
  }
1056
- function serializeXMLElement(tag, value) {
1057
- if (!/^[A-Za-z_][\w.:-]*$/.test(tag)) {
1058
- throw new Error(`Invalid XML tag name: ${tag}`);
1395
+ function resolveElementPrefix(tag, value, ctx, parentTag) {
1396
+ if (isXMLRecord(value) && value.$namespace !== void 0) {
1397
+ const namespace = value.$namespace;
1398
+ if (typeof namespace !== "string" || namespace !== "" && !/^[A-Za-z_][\w.-]*$/.test(namespace)) {
1399
+ throw new Error(`Invalid XML namespace prefix: ${namespace}`);
1400
+ }
1401
+ return namespace;
1059
1402
  }
1060
- if (Array.isArray(value)) {
1061
- return value.map((item) => serializeXMLElement(tag, item)).join("");
1403
+ if (tag.includes(":")) {
1404
+ return void 0;
1062
1405
  }
1063
- const namespace = isXMLRecord(value) ? value.$namespace : void 0;
1064
- if (namespace !== void 0) {
1065
- if (typeof namespace !== "string" || !/^[A-Za-z_][\w.-]*$/.test(namespace)) {
1066
- throw new Error(`Invalid XML namespace prefix: ${namespace}`);
1406
+ const contextual = parentTag ? ctx.children[parentTag]?.[tag] : void 0;
1407
+ if (contextual !== void 0) {
1408
+ return contextual;
1409
+ }
1410
+ const mapped = ctx.elements[tag];
1411
+ return mapped === void 0 ? void 0 : mapped;
1412
+ }
1413
+ function buildNamespaceDeclarations(ctx) {
1414
+ let declarations = "";
1415
+ for (const prefix of ctx.usedPrefixes) {
1416
+ if (ctx.declaredPrefixes.has(prefix)) {
1417
+ continue;
1418
+ }
1419
+ const uri = ctx.prefixes[prefix];
1420
+ if (!uri) {
1421
+ continue;
1067
1422
  }
1068
- tag = `${namespace}:${tag}`;
1423
+ declarations += ` xmlns:${prefix}="${escapeXMLAttribute(uri)}"`;
1424
+ }
1425
+ return declarations;
1426
+ }
1427
+ function serializeElementParts(tag, value, ctx, parentTag) {
1428
+ if (!/^[A-Za-z_][\w.:-]*$/.test(tag)) {
1429
+ throw new Error(`Invalid XML tag name: ${tag}`);
1069
1430
  }
1431
+ const prefix = resolveElementPrefix(tag, value, ctx, parentTag);
1432
+ if (prefix) {
1433
+ ctx.usedPrefixes.add(prefix);
1434
+ }
1435
+ const tagName = prefix ? `${prefix}:${tag}` : tag;
1070
1436
  let attributes = "";
1071
1437
  let content = "";
1072
1438
  if (isXMLNode(value)) {
1073
- attributes = getXMLAttributes(value);
1439
+ attributes = getXMLAttributes(value, ctx);
1074
1440
  content = escapeXMLText(String(getXMLValue(value) ?? ""));
1075
1441
  } else if (isXMLRecord(value)) {
1076
- attributes = getXMLAttributes(value);
1442
+ attributes = getXMLAttributes(value, ctx);
1077
1443
  const children = Object.entries(value).filter(([key]) => !key.startsWith("$"));
1078
1444
  if (children.length > 0) {
1079
- content = children.map(([key, childValue]) => serializeXMLElement(key, childValue)).join("");
1445
+ content = children.map(([key, childValue]) => serializeXMLElement(key, childValue, ctx, tag)).join("");
1080
1446
  } else if (attributes) {
1081
1447
  const text = value.$value;
1082
1448
  content = text == null ? "" : escapeXMLText(String(text));
1083
1449
  } else if ("$value" in value) {
1084
- throw new Error(`XML element "${tag}": $value requires at least one attribute`);
1450
+ throw new Error(`XML element "${tagName}": $value requires at least one attribute`);
1085
1451
  }
1086
1452
  } else {
1087
1453
  content = value == null ? "" : escapeXMLText(String(value));
1088
1454
  }
1089
- if (!content) {
1090
- return `<${tag}${attributes}/>`;
1455
+ return { tagName, attributes, content };
1456
+ }
1457
+ function composeElement(parts) {
1458
+ if (!parts.content) {
1459
+ return `<${parts.tagName}${parts.attributes}/>`;
1460
+ }
1461
+ return `<${parts.tagName}${parts.attributes}>${parts.content}</${parts.tagName}>`;
1462
+ }
1463
+ function serializeXMLElement(tag, value, ctx, parentTag) {
1464
+ if (Array.isArray(value)) {
1465
+ return value.map((item) => serializeXMLElement(tag, item, ctx, parentTag)).join("");
1091
1466
  }
1092
- return `<${tag}${attributes}>${content}</${tag}>`;
1467
+ return composeElement(serializeElementParts(tag, value, ctx, parentTag));
1093
1468
  }
1094
1469
  var XMLBuilder = class {
1095
1470
  $input;
1096
- constructor(obj) {
1471
+ $options;
1472
+ constructor(obj, options = {}) {
1097
1473
  this.$input = obj;
1474
+ this.$options = options;
1098
1475
  }
1099
1476
  toXML(config = {}) {
1477
+ const options = { ...this.$options, ...config };
1478
+ const registry = options.namespaces ?? {};
1479
+ const ctx = {
1480
+ prefixes: registry.prefixes ?? {},
1481
+ elements: registry.elements ?? {},
1482
+ children: registry.children ?? {},
1483
+ usedPrefixes: /* @__PURE__ */ new Set(),
1484
+ declaredPrefixes: /* @__PURE__ */ new Set()
1485
+ };
1100
1486
  const entries = Object.entries(this.$input);
1101
1487
  if (entries.length !== 1) {
1102
1488
  throw new Error("XML must contain exactly one root element");
1103
1489
  }
1104
1490
  const [rootTag, rootValue] = entries[0];
1105
- const xml = serializeXMLElement(rootTag, rootValue);
1106
- if (config.declaration) {
1491
+ const rootParts = Array.isArray(rootValue) ? rootValue.map((item) => serializeElementParts(rootTag, item, ctx)) : [serializeElementParts(rootTag, rootValue, ctx)];
1492
+ const declarations = buildNamespaceDeclarations(ctx);
1493
+ if (rootParts.length > 0) {
1494
+ rootParts[0] = {
1495
+ ...rootParts[0],
1496
+ attributes: `${rootParts[0].attributes}${declarations}`
1497
+ };
1498
+ }
1499
+ const xml = rootParts.map((parts) => composeElement(parts)).join("");
1500
+ if (options.declaration) {
1107
1501
  return `<?xml version="1.0" encoding="UTF-8"?>${xml}`;
1108
1502
  }
1109
1503
  return xml;
1110
1504
  }
1111
1505
  };
1506
+
1507
+ // src/utils/asArray.ts
1508
+ var asArray = (value) => {
1509
+ return Array.isArray(value) ? value : [value];
1510
+ };
1112
1511
  // Annotate the CommonJS export names for ESM import in node:
1113
1512
  0 && (module.exports = {
1114
1513
  WSDLTypeGenerator,
1115
1514
  XMLBuilder,
1116
- XMLParser
1515
+ XMLParser,
1516
+ asArray
1117
1517
  });