@apiconvert/core 0.2.0 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (62) hide show
  1. package/README.md +60 -268
  2. package/dist/condition-expression-evaluator.d.ts +4 -0
  3. package/dist/condition-expression-evaluator.d.ts.map +1 -0
  4. package/dist/condition-expression-evaluator.js +63 -0
  5. package/dist/condition-expression-evaluator.js.map +1 -0
  6. package/dist/condition-expression-parser.d.ts +26 -0
  7. package/dist/condition-expression-parser.d.ts.map +1 -0
  8. package/dist/condition-expression-parser.js +191 -0
  9. package/dist/condition-expression-parser.js.map +1 -0
  10. package/dist/condition-expression-tokenizer.d.ts +3 -0
  11. package/dist/condition-expression-tokenizer.d.ts.map +1 -0
  12. package/dist/condition-expression-tokenizer.js +103 -0
  13. package/dist/condition-expression-tokenizer.js.map +1 -0
  14. package/dist/condition-expression-types.d.ts +29 -0
  15. package/dist/condition-expression-types.d.ts.map +1 -0
  16. package/dist/condition-expression-types.js +3 -0
  17. package/dist/condition-expression-types.js.map +1 -0
  18. package/dist/condition-expression.d.ts +9 -0
  19. package/dist/condition-expression.d.ts.map +1 -0
  20. package/dist/condition-expression.js +16 -0
  21. package/dist/condition-expression.js.map +1 -0
  22. package/dist/core-utils.d.ts +11 -0
  23. package/dist/core-utils.d.ts.map +1 -0
  24. package/dist/core-utils.js +126 -0
  25. package/dist/core-utils.js.map +1 -0
  26. package/dist/index.d.ts +5 -99
  27. package/dist/index.d.ts.map +1 -1
  28. package/dist/index.js +31 -729
  29. package/dist/index.js.map +1 -1
  30. package/dist/mapping-engine.d.ts +3 -0
  31. package/dist/mapping-engine.d.ts.map +1 -0
  32. package/dist/mapping-engine.js +18 -0
  33. package/dist/mapping-engine.js.map +1 -0
  34. package/dist/payload-converter.d.ts +7 -0
  35. package/dist/payload-converter.d.ts.map +1 -0
  36. package/dist/payload-converter.js +37 -0
  37. package/dist/payload-converter.js.map +1 -0
  38. package/dist/query-payload.d.ts +3 -0
  39. package/dist/query-payload.d.ts.map +1 -0
  40. package/dist/query-payload.js +183 -0
  41. package/dist/query-payload.js.map +1 -0
  42. package/dist/rule-executor.d.ts +3 -0
  43. package/dist/rule-executor.d.ts.map +1 -0
  44. package/dist/rule-executor.js +108 -0
  45. package/dist/rule-executor.js.map +1 -0
  46. package/dist/rules-normalizer.d.ts +3 -0
  47. package/dist/rules-normalizer.d.ts.map +1 -0
  48. package/dist/rules-normalizer.js +158 -0
  49. package/dist/rules-normalizer.js.map +1 -0
  50. package/dist/source-resolver.d.ts +4 -0
  51. package/dist/source-resolver.d.ts.map +1 -0
  52. package/dist/source-resolver.js +155 -0
  53. package/dist/source-resolver.js.map +1 -0
  54. package/dist/types.d.ts +97 -0
  55. package/dist/types.d.ts.map +1 -0
  56. package/dist/types.js +33 -0
  57. package/dist/types.js.map +1 -0
  58. package/dist/xml-payload.d.ts +3 -0
  59. package/dist/xml-payload.d.ts.map +1 -0
  60. package/dist/xml-payload.js +61 -0
  61. package/dist/xml-payload.js.map +1 -0
  62. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -1,144 +1,46 @@
1
1
  "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
2
16
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.rulesSchemaPath = exports.ConditionOperator = exports.MergeMode = exports.TransformType = exports.DataFormat = void 0;
4
- exports.normalizeConversionRules = normalizeConversionRules;
5
- exports.applyConversion = applyConversion;
6
- exports.parsePayload = parsePayload;
7
- exports.formatPayload = formatPayload;
17
+ exports.parsePayload = exports.normalizeConversionRules = exports.formatPayload = exports.applyConversion = void 0;
8
18
  exports.runConversionCase = runConversionCase;
9
- const fast_xml_parser_1 = require("fast-xml-parser");
10
- var DataFormat;
11
- (function (DataFormat) {
12
- DataFormat["Json"] = "json";
13
- DataFormat["Xml"] = "xml";
14
- DataFormat["Query"] = "query";
15
- })(DataFormat || (exports.DataFormat = DataFormat = {}));
16
- var TransformType;
17
- (function (TransformType) {
18
- TransformType["ToLowerCase"] = "toLowerCase";
19
- TransformType["ToUpperCase"] = "toUpperCase";
20
- TransformType["Number"] = "number";
21
- TransformType["Boolean"] = "boolean";
22
- TransformType["Concat"] = "concat";
23
- TransformType["Split"] = "split";
24
- })(TransformType || (exports.TransformType = TransformType = {}));
25
- var MergeMode;
26
- (function (MergeMode) {
27
- MergeMode["Concat"] = "concat";
28
- MergeMode["FirstNonEmpty"] = "firstNonEmpty";
29
- MergeMode["Array"] = "array";
30
- })(MergeMode || (exports.MergeMode = MergeMode = {}));
31
- var ConditionOperator;
32
- (function (ConditionOperator) {
33
- ConditionOperator["Exists"] = "exists";
34
- ConditionOperator["Equals"] = "equals";
35
- ConditionOperator["NotEquals"] = "notEquals";
36
- ConditionOperator["Includes"] = "includes";
37
- ConditionOperator["Gt"] = "gt";
38
- ConditionOperator["Lt"] = "lt";
39
- })(ConditionOperator || (exports.ConditionOperator = ConditionOperator = {}));
40
- exports.rulesSchemaPath = "/schemas/rules/rules.schema.json";
41
- function normalizeConversionRules(raw) {
42
- if (raw && typeof raw === "object" && !Array.isArray(raw)) {
43
- if (isConversionRules(raw)) {
44
- return normalizeRules(raw);
45
- }
46
- if (isLegacyConfig(raw)) {
47
- return normalizeLegacyRules(raw);
48
- }
49
- return emptyRules();
50
- }
51
- if (typeof raw === "string") {
52
- try {
53
- const parsed = JSON.parse(raw);
54
- return normalizeConversionRules(parsed);
55
- }
56
- catch {
57
- return emptyRules();
58
- }
59
- }
60
- return emptyRules();
61
- }
62
- function applyConversion(input, rawRules) {
63
- const rules = normalizeConversionRules(rawRules);
64
- const fieldMappings = rules.fieldMappings ?? [];
65
- const arrayMappings = rules.arrayMappings ?? [];
66
- if (fieldMappings.length === 0 && arrayMappings.length === 0) {
67
- return { output: input ?? {}, errors: [] };
68
- }
69
- const output = {};
70
- const errors = [];
71
- applyFieldMappings(input, null, fieldMappings, output, errors, "Field");
72
- arrayMappings.forEach((arrayRule, index) => {
73
- const value = resolvePathValue(input, null, arrayRule.inputPath ?? "");
74
- let items = Array.isArray(value) ? value : null;
75
- if (!items && arrayRule.coerceSingle && value != null) {
76
- items = [value];
77
- }
78
- if (!items) {
79
- errors.push(`Array ${index + 1}: input path did not resolve to an array (${arrayRule.inputPath}).`);
80
- return;
81
- }
82
- const mappedItems = [];
83
- items.forEach((item) => {
84
- const itemOutput = {};
85
- applyFieldMappings(input, item, arrayRule.itemMappings ?? [], itemOutput, errors, `Array ${index + 1} item`);
86
- mappedItems.push(itemOutput);
87
- });
88
- if (!arrayRule.outputPath || arrayRule.outputPath.trim().length === 0) {
89
- errors.push(`Array ${index + 1}: output path is required.`);
90
- return;
91
- }
92
- const outputPath = normalizeWritePath(arrayRule.outputPath);
93
- if (!outputPath || outputPath.trim().length === 0) {
94
- errors.push(`Array ${index + 1}: output path is required.`);
95
- return;
96
- }
97
- setValueByPath(output, outputPath, mappedItems);
98
- });
99
- return { output, errors };
100
- }
101
- function parsePayload(text, format) {
102
- try {
103
- switch (format) {
104
- case DataFormat.Xml:
105
- return { value: parseXml(text) };
106
- case DataFormat.Query:
107
- return { value: parseQueryString(text) };
108
- default:
109
- return { value: parseJson(text) };
110
- }
111
- }
112
- catch (error) {
113
- return { value: null, error: error instanceof Error ? error.message : String(error) };
114
- }
115
- }
116
- function formatPayload(value, format, pretty) {
117
- switch (format) {
118
- case DataFormat.Xml:
119
- return formatXml(value, pretty);
120
- case DataFormat.Query:
121
- return formatQueryString(value);
122
- default:
123
- return JSON.stringify(sanitizeForJson(value ?? {}), null, pretty ? 2 : 0);
124
- }
125
- }
19
+ const mapping_engine_1 = require("./mapping-engine");
20
+ Object.defineProperty(exports, "applyConversion", { enumerable: true, get: function () { return mapping_engine_1.applyConversion; } });
21
+ const payload_converter_1 = require("./payload-converter");
22
+ Object.defineProperty(exports, "formatPayload", { enumerable: true, get: function () { return payload_converter_1.formatPayload; } });
23
+ Object.defineProperty(exports, "parsePayload", { enumerable: true, get: function () { return payload_converter_1.parsePayload; } });
24
+ const rules_normalizer_1 = require("./rules-normalizer");
25
+ Object.defineProperty(exports, "normalizeConversionRules", { enumerable: true, get: function () { return rules_normalizer_1.normalizeConversionRules; } });
26
+ const types_1 = require("./types");
27
+ __exportStar(require("./types"), exports);
126
28
  async function runConversionCase(args) {
127
- const rules = normalizeConversionRules(args.rulesText);
29
+ const rules = (0, rules_normalizer_1.normalizeConversionRules)(args.rulesText);
128
30
  const inputFormat = extensionToFormat(args.inputExtension);
129
31
  const outputFormat = extensionToFormat(args.outputExtension);
130
32
  const inputValue = inputFormat ? parsePayloadOrThrow(args.inputText, inputFormat) : args.inputText;
131
- const result = applyConversion(inputValue, rules);
33
+ const result = (0, mapping_engine_1.applyConversion)(inputValue, rules);
132
34
  if (result.errors.length > 0) {
133
35
  throw new Error(`Conversion errors: ${result.errors.join("; ")}`);
134
36
  }
135
37
  if (!outputFormat) {
136
38
  return result.output == null ? "" : String(result.output);
137
39
  }
138
- return formatPayload(result.output, outputFormat, outputFormat === DataFormat.Xml);
40
+ return (0, payload_converter_1.formatPayload)(result.output, outputFormat, outputFormat === types_1.DataFormat.Xml);
139
41
  }
140
42
  function parsePayloadOrThrow(text, format) {
141
- const { value, error } = parsePayload(text, format);
43
+ const { value, error } = (0, payload_converter_1.parsePayload)(text, format);
142
44
  if (error) {
143
45
  throw new Error(error);
144
46
  }
@@ -147,611 +49,11 @@ function parsePayloadOrThrow(text, format) {
147
49
  function extensionToFormat(extension) {
148
50
  const ext = extension.toLowerCase();
149
51
  if (ext === "json")
150
- return DataFormat.Json;
52
+ return types_1.DataFormat.Json;
151
53
  if (ext === "xml")
152
- return DataFormat.Xml;
54
+ return types_1.DataFormat.Xml;
153
55
  if (ext === "txt")
154
- return DataFormat.Query;
56
+ return types_1.DataFormat.Query;
155
57
  return null;
156
58
  }
157
- function normalizeRules(rules) {
158
- return {
159
- version: rules.version ?? 2,
160
- inputFormat: rules.inputFormat ?? DataFormat.Json,
161
- outputFormat: rules.outputFormat ?? DataFormat.Json,
162
- fieldMappings: (rules.fieldMappings ?? []).map((rule) => ({
163
- outputPath: rule.outputPath,
164
- outputPaths: rule.outputPaths ?? [],
165
- source: rule.source ?? { type: "path" },
166
- defaultValue: rule.defaultValue ?? ""
167
- })),
168
- arrayMappings: (rules.arrayMappings ?? []).map((mapping) => ({
169
- inputPath: mapping.inputPath,
170
- outputPath: mapping.outputPath,
171
- coerceSingle: mapping.coerceSingle ?? false,
172
- itemMappings: (mapping.itemMappings ?? []).map((rule) => ({
173
- outputPath: rule.outputPath,
174
- outputPaths: rule.outputPaths ?? [],
175
- source: rule.source ?? { type: "path" },
176
- defaultValue: rule.defaultValue ?? ""
177
- }))
178
- }))
179
- };
180
- }
181
- function normalizeLegacyRules(legacy) {
182
- const rows = legacy.rows ?? [];
183
- const fieldMappings = rows.map((row) => {
184
- const sourceType = row.sourceType ?? "path";
185
- let source;
186
- if (sourceType === "constant") {
187
- source = { type: "constant", value: row.sourceValue ?? "" };
188
- }
189
- else if (sourceType === "transform") {
190
- source = {
191
- type: "transform",
192
- path: row.sourceValue ?? "",
193
- transform: row.transformType ?? TransformType.ToLowerCase
194
- };
195
- }
196
- else {
197
- source = { type: "path", path: row.sourceValue ?? "" };
198
- }
199
- return {
200
- outputPath: row.outputPath,
201
- source,
202
- defaultValue: row.defaultValue ?? ""
203
- };
204
- });
205
- return {
206
- version: 2,
207
- inputFormat: DataFormat.Json,
208
- outputFormat: DataFormat.Json,
209
- fieldMappings,
210
- arrayMappings: []
211
- };
212
- }
213
- function emptyRules() {
214
- return {
215
- version: 2,
216
- inputFormat: DataFormat.Json,
217
- outputFormat: DataFormat.Json,
218
- fieldMappings: [],
219
- arrayMappings: []
220
- };
221
- }
222
- function isConversionRules(value) {
223
- if (!value || typeof value !== "object" || Array.isArray(value)) {
224
- return false;
225
- }
226
- const record = value;
227
- return record.version === 2 || "fieldMappings" in record || "arrayMappings" in record;
228
- }
229
- function isLegacyConfig(value) {
230
- if (!value || typeof value !== "object" || Array.isArray(value)) {
231
- return false;
232
- }
233
- const record = value;
234
- return Array.isArray(record.rows);
235
- }
236
- function applyFieldMappings(root, item, mappings, output, errors, label) {
237
- mappings.forEach((rule, index) => {
238
- const writePaths = getWritePaths(rule);
239
- if (writePaths.length === 0) {
240
- errors.push(`${label} ${index + 1}: output path is required.`);
241
- return;
242
- }
243
- let value = resolveSourceValue(root, item, rule.source);
244
- if ((value == null || value === "") && rule.defaultValue) {
245
- value = parsePrimitive(rule.defaultValue);
246
- }
247
- writePaths.forEach((writePath) => {
248
- setValueByPath(output, writePath, value);
249
- });
250
- });
251
- }
252
- function resolveSourceValue(root, item, source) {
253
- switch (source.type) {
254
- case "constant":
255
- return parsePrimitive(source.value ?? "");
256
- case "path":
257
- return resolvePathValue(root, item, source.path ?? "");
258
- case "merge":
259
- return resolveMergeSourceValue(root, item, source);
260
- case "transform": {
261
- if (source.transform === TransformType.Concat) {
262
- const tokens = (source.path ?? "")
263
- .split(",")
264
- .map((token) => token.trim())
265
- .filter((token) => token.length > 0);
266
- let result = "";
267
- for (const token of tokens) {
268
- if (token.toLowerCase().startsWith("const:")) {
269
- result += token.slice("const:".length);
270
- continue;
271
- }
272
- const resolved = resolvePathValue(root, item, token);
273
- result += resolved == null ? "" : String(resolved);
274
- }
275
- return result;
276
- }
277
- if (source.transform === TransformType.Split) {
278
- const baseValue = resolvePathValue(root, item, source.path ?? "");
279
- if (baseValue == null) {
280
- return null;
281
- }
282
- const separator = source.separator ?? " ";
283
- if (separator.length === 0) {
284
- return null;
285
- }
286
- let tokenIndex = source.tokenIndex ?? 0;
287
- const trimAfterSplit = source.trimAfterSplit ?? true;
288
- const rawTokens = String(baseValue).split(separator).filter((token) => token.length > 0);
289
- const tokens = trimAfterSplit
290
- ? rawTokens.map((token) => token.trim()).filter((token) => token.length > 0)
291
- : rawTokens;
292
- if (tokenIndex < 0) {
293
- tokenIndex = tokens.length + tokenIndex;
294
- }
295
- if (tokenIndex < 0 || tokenIndex >= tokens.length) {
296
- return null;
297
- }
298
- return tokens[tokenIndex];
299
- }
300
- const baseValue = resolvePathValue(root, item, source.path ?? "");
301
- return resolveTransform(baseValue, source.transform ?? TransformType.ToLowerCase);
302
- }
303
- case "condition": {
304
- if (!source.condition) {
305
- return null;
306
- }
307
- const matched = evaluateCondition(root, item, source.condition);
308
- const resolved = matched ? source.trueValue : source.falseValue;
309
- return parsePrimitive(resolved ?? "");
310
- }
311
- default:
312
- return null;
313
- }
314
- }
315
- function resolveMergeSourceValue(root, item, source) {
316
- const values = (source.paths ?? [])
317
- .filter((path) => !!path && path.trim().length > 0)
318
- .map((path) => resolvePathValue(root, item, path));
319
- const mode = source.mergeMode ?? MergeMode.Concat;
320
- switch (mode) {
321
- case MergeMode.FirstNonEmpty:
322
- return values.find((value) => value != null && (typeof value !== "string" || value.length > 0)) ?? null;
323
- case MergeMode.Array:
324
- return values;
325
- default:
326
- return values.map((value) => (value == null ? "" : String(value))).join(source.separator ?? "");
327
- }
328
- }
329
- function resolvePathValue(root, item, path) {
330
- if (!path || path.trim().length === 0)
331
- return null;
332
- if (path === "$")
333
- return root;
334
- if (path.startsWith("$.", 0)) {
335
- return getValueByPath(root, path.slice(2));
336
- }
337
- if (path.startsWith("$[", 0)) {
338
- return getValueByPath(root, path.slice(1));
339
- }
340
- if (item != null) {
341
- return getValueByPath(item, path);
342
- }
343
- return getValueByPath(root, path);
344
- }
345
- function evaluateCondition(root, item, condition) {
346
- const value = resolvePathValue(root, item, condition.path);
347
- const compareValue = condition.value != null ? parsePrimitive(condition.value) : null;
348
- switch (condition.operator) {
349
- case ConditionOperator.Exists:
350
- return value != null;
351
- case ConditionOperator.Equals:
352
- return Object.is(value, compareValue);
353
- case ConditionOperator.NotEquals:
354
- return !Object.is(value, compareValue);
355
- case ConditionOperator.Includes:
356
- return includesValue(value, compareValue);
357
- case ConditionOperator.Gt:
358
- return toNumber(value) > toNumber(compareValue);
359
- case ConditionOperator.Lt:
360
- return toNumber(value) < toNumber(compareValue);
361
- default:
362
- return false;
363
- }
364
- }
365
- function includesValue(value, compareValue) {
366
- if (typeof value === "string" && typeof compareValue === "string") {
367
- return value.includes(compareValue);
368
- }
369
- if (Array.isArray(value)) {
370
- return value.some((item) => Object.is(item, compareValue));
371
- }
372
- return false;
373
- }
374
- function resolveTransform(value, transform) {
375
- switch (transform) {
376
- case TransformType.ToLowerCase:
377
- return typeof value === "string" ? value.toLowerCase() : value;
378
- case TransformType.ToUpperCase:
379
- return typeof value === "string" ? value.toUpperCase() : value;
380
- case TransformType.Number:
381
- return value == null || value === "" ? value : toNumber(value);
382
- case TransformType.Boolean:
383
- if (typeof value === "boolean")
384
- return value;
385
- if (typeof value === "string") {
386
- return ["true", "1", "yes", "y"].includes(value.toLowerCase());
387
- }
388
- return value != null;
389
- default:
390
- return value;
391
- }
392
- }
393
- function getValueByPath(input, path) {
394
- if (input == null || !path || path.trim().length === 0)
395
- return null;
396
- const parts = path.split(".").map((part) => part.trim());
397
- let current = input;
398
- for (const part of parts) {
399
- if (current == null)
400
- return null;
401
- const arrayMatch = part.match(/^(\w+)\[(\d+)\]$/);
402
- if (arrayMatch) {
403
- const key = arrayMatch[1];
404
- const index = Number.parseInt(arrayMatch[2], 10);
405
- if (!isRecord(current) || !(key in current))
406
- return null;
407
- const next = current[key];
408
- if (!Array.isArray(next) || index >= next.length)
409
- return null;
410
- current = next[index];
411
- continue;
412
- }
413
- if (/^\d+$/.test(part)) {
414
- const index = Number.parseInt(part, 10);
415
- if (!Array.isArray(current) || index >= current.length)
416
- return null;
417
- current = current[index];
418
- continue;
419
- }
420
- if (!isRecord(current) || !(part in current))
421
- return null;
422
- current = current[part];
423
- }
424
- return current;
425
- }
426
- function setValueByPath(target, path, value) {
427
- const parts = path.split(".").map((part) => part.trim());
428
- let current = target;
429
- for (let index = 0; index < parts.length; index += 1) {
430
- const part = parts[index];
431
- const isLast = index === parts.length - 1;
432
- if (isLast) {
433
- current[part] = value;
434
- return;
435
- }
436
- const next = current[part];
437
- if (!isRecord(next)) {
438
- current[part] = {};
439
- }
440
- current = current[part];
441
- }
442
- }
443
- function normalizeWritePath(path) {
444
- if (!path || path.trim().length === 0) {
445
- return path;
446
- }
447
- if (path.startsWith("$.", 0)) {
448
- return path.slice(2);
449
- }
450
- if (path === "$") {
451
- return "";
452
- }
453
- return path;
454
- }
455
- function getWritePaths(rule) {
456
- const paths = [];
457
- if (rule.outputPath && rule.outputPath.trim().length > 0) {
458
- paths.push(rule.outputPath);
459
- }
460
- (rule.outputPaths ?? []).forEach((path) => {
461
- if (path && path.trim().length > 0) {
462
- paths.push(path);
463
- }
464
- });
465
- return Array.from(new Set(paths));
466
- }
467
- function parsePrimitive(value) {
468
- if (value === "true")
469
- return true;
470
- if (value === "false")
471
- return false;
472
- if (value === "null")
473
- return null;
474
- if (value === "undefined")
475
- return null;
476
- const parsed = Number.parseFloat(value);
477
- if (!Number.isNaN(parsed) && isFinite(parsed))
478
- return parsed;
479
- return value;
480
- }
481
- function toNumber(value) {
482
- if (value == null)
483
- return Number.NaN;
484
- if (typeof value === "number")
485
- return value;
486
- if (typeof value === "string") {
487
- const parsed = Number.parseFloat(value);
488
- return Number.isNaN(parsed) ? Number.NaN : parsed;
489
- }
490
- if (typeof value === "boolean")
491
- return value ? 1 : 0;
492
- const coerced = Number(value);
493
- return Number.isNaN(coerced) ? Number.NaN : coerced;
494
- }
495
- function parseJson(text) {
496
- return JSON.parse(text);
497
- }
498
- function parseXml(text) {
499
- const parser = new fast_xml_parser_1.XMLParser({
500
- ignoreAttributes: false,
501
- attributeNamePrefix: "@_",
502
- textNodeName: "#text",
503
- trimValues: false,
504
- parseTagValue: false,
505
- parseAttributeValue: false
506
- });
507
- const parsed = parser.parse(text);
508
- return normalizeXmlValue(parsed);
509
- }
510
- function formatXml(value, pretty) {
511
- if (!isRecord(value) || Object.keys(value).length === 0) {
512
- return new fast_xml_parser_1.XMLBuilder({
513
- ignoreAttributes: false,
514
- attributeNamePrefix: "@_",
515
- textNodeName: "#text",
516
- format: pretty,
517
- indentBy: " "
518
- }).build({ root: null });
519
- }
520
- const builder = new fast_xml_parser_1.XMLBuilder({
521
- ignoreAttributes: false,
522
- attributeNamePrefix: "@_",
523
- textNodeName: "#text",
524
- format: pretty,
525
- indentBy: " "
526
- });
527
- if (!isRecord(value) || Object.keys(value).length === 0) {
528
- return builder.build({ root: null });
529
- }
530
- const keys = Object.keys(value);
531
- if (keys.length === 1) {
532
- const rootKey = keys[0];
533
- return builder.build({ [rootKey]: value[rootKey] });
534
- }
535
- return builder.build({ root: value });
536
- }
537
- function normalizeXmlValue(value) {
538
- if (Array.isArray(value)) {
539
- return value.map((item) => normalizeXmlValue(item));
540
- }
541
- if (isRecord(value)) {
542
- const normalized = {};
543
- for (const [key, child] of Object.entries(value)) {
544
- if (key === "#text" && typeof child === "string") {
545
- normalized[key] = parsePrimitive(child.trim());
546
- continue;
547
- }
548
- if (typeof child === "string") {
549
- normalized[key] = parsePrimitive(child.trim());
550
- continue;
551
- }
552
- normalized[key] = normalizeXmlValue(child);
553
- }
554
- return normalized;
555
- }
556
- if (typeof value === "string") {
557
- return parsePrimitive(value.trim());
558
- }
559
- return value;
560
- }
561
- function parseQueryString(text) {
562
- const trimmed = text.trim();
563
- if (!trimmed)
564
- return {};
565
- const query = trimmed.startsWith("?") ? trimmed.slice(1) : trimmed;
566
- const result = {};
567
- const pairs = query.split("&").filter((pair) => pair.length > 0);
568
- for (const pair of pairs) {
569
- const splitIndex = pair.indexOf("=");
570
- const rawKey = splitIndex >= 0 ? pair.slice(0, splitIndex) : pair;
571
- const rawValue = splitIndex >= 0 ? pair.slice(splitIndex + 1) : "";
572
- const key = decodeURIComponent(rawKey.replace(/\+/g, " "));
573
- const value = decodeURIComponent(rawValue.replace(/\+/g, " "));
574
- const path = parseQueryKey(key);
575
- setQueryValue(result, path, value);
576
- }
577
- return result;
578
- }
579
- function formatQueryString(value) {
580
- if (!isRecord(value)) {
581
- throw new Error("Query output must be an object.");
582
- }
583
- const pairs = [];
584
- const keys = Object.keys(value).sort((a, b) => a.localeCompare(b));
585
- keys.forEach((key) => {
586
- addQueryPair(pairs, key, value[key]);
587
- });
588
- return pairs
589
- .map((pair) => `${encodeURIComponent(pair.key)}=${encodeURIComponent(pair.value)}`)
590
- .join("&");
591
- }
592
- function parseQueryKey(key) {
593
- const parts = [];
594
- const matcher = /([^\[.\]]+)|\[(.*?)\]/g;
595
- let match;
596
- while ((match = matcher.exec(key)) !== null) {
597
- const token = match[1] ?? match[2] ?? "";
598
- if (!token)
599
- continue;
600
- const number = Number.parseInt(token, 10);
601
- if (!Number.isNaN(number) && number.toString() === token) {
602
- parts.push(number);
603
- }
604
- else {
605
- parts.push(token);
606
- }
607
- }
608
- if (parts.length === 0) {
609
- parts.push(key);
610
- }
611
- return parts;
612
- }
613
- function setQueryValue(target, path, value) {
614
- let current = target;
615
- let parent = null;
616
- let parentKey = null;
617
- const ensureObjectContainer = (valueToCheck) => {
618
- if (isRecord(valueToCheck))
619
- return valueToCheck;
620
- const next = {};
621
- if (parent != null && parentKey != null) {
622
- if (Array.isArray(parent)) {
623
- parent[parentKey] = next;
624
- }
625
- else if (isRecord(parent)) {
626
- parent[parentKey.toString()] = next;
627
- }
628
- }
629
- return next;
630
- };
631
- const ensureArrayContainer = (valueToCheck) => {
632
- if (Array.isArray(valueToCheck))
633
- return valueToCheck;
634
- const next = [];
635
- if (parent != null && parentKey != null) {
636
- if (Array.isArray(parent)) {
637
- parent[parentKey] = next;
638
- }
639
- else if (isRecord(parent)) {
640
- parent[parentKey.toString()] = next;
641
- }
642
- }
643
- return next;
644
- };
645
- path.forEach((segment, index) => {
646
- const isLast = index === path.length - 1;
647
- const nextSegment = index + 1 < path.length ? path[index + 1] : null;
648
- if (typeof segment === "number") {
649
- const arrayContainer = ensureArrayContainer(current);
650
- if (isLast) {
651
- const existing = arrayContainer[segment];
652
- if (existing == null) {
653
- ensureListSize(arrayContainer, segment + 1);
654
- arrayContainer[segment] = value;
655
- }
656
- else if (Array.isArray(existing)) {
657
- existing.push(value);
658
- }
659
- else {
660
- arrayContainer[segment] = [existing, value];
661
- }
662
- return;
663
- }
664
- parent = arrayContainer;
665
- parentKey = segment;
666
- ensureListSize(arrayContainer, segment + 1);
667
- const existingValue = arrayContainer[segment];
668
- const shouldBeArray = typeof nextSegment === "number";
669
- if (existingValue == null ||
670
- (shouldBeArray && !Array.isArray(existingValue)) ||
671
- (!shouldBeArray && !isRecord(existingValue))) {
672
- arrayContainer[segment] = shouldBeArray ? [] : {};
673
- }
674
- current = arrayContainer[segment];
675
- return;
676
- }
677
- const objectContainer = ensureObjectContainer(current);
678
- const key = segment;
679
- if (isLast) {
680
- const existing = objectContainer[key];
681
- if (existing === undefined) {
682
- objectContainer[key] = value;
683
- }
684
- else if (Array.isArray(existing)) {
685
- existing.push(value);
686
- }
687
- else {
688
- objectContainer[key] = [existing, value];
689
- }
690
- return;
691
- }
692
- parent = objectContainer;
693
- parentKey = key;
694
- const next = objectContainer[key];
695
- const shouldBeArray = typeof nextSegment === "number";
696
- if (next == null || (shouldBeArray && !Array.isArray(next)) || (!shouldBeArray && !isRecord(next))) {
697
- objectContainer[key] = shouldBeArray ? [] : {};
698
- }
699
- current = objectContainer[key];
700
- });
701
- }
702
- function ensureListSize(list, size) {
703
- while (list.length < size) {
704
- list.push(null);
705
- }
706
- }
707
- function addQueryPair(pairs, key, value) {
708
- if (value == null) {
709
- pairs.push({ key, value: "" });
710
- return;
711
- }
712
- if (Array.isArray(value)) {
713
- value.forEach((item) => {
714
- if (isRecord(item) || Array.isArray(item)) {
715
- pairs.push({ key, value: JSON.stringify(sanitizeForJson(item)) });
716
- }
717
- else if (item == null) {
718
- pairs.push({ key, value: "" });
719
- }
720
- else {
721
- pairs.push({ key, value: String(item) });
722
- }
723
- });
724
- return;
725
- }
726
- if (isRecord(value)) {
727
- const keys = Object.keys(value).sort((a, b) => a.localeCompare(b));
728
- keys.forEach((childKey) => {
729
- const nextKey = key.length === 0 ? childKey : `${key}.${childKey}`;
730
- addQueryPair(pairs, nextKey, value[childKey]);
731
- });
732
- return;
733
- }
734
- if (!key)
735
- return;
736
- pairs.push({ key, value: String(value) });
737
- }
738
- function isRecord(value) {
739
- return !!value && typeof value === "object" && !Array.isArray(value);
740
- }
741
- function sanitizeForJson(value) {
742
- if (Array.isArray(value)) {
743
- return value.map((item) => sanitizeForJson(item));
744
- }
745
- if (isRecord(value)) {
746
- const result = {};
747
- Object.entries(value).forEach(([key, child]) => {
748
- if (child === null) {
749
- return;
750
- }
751
- result[key] = sanitizeForJson(child);
752
- });
753
- return result;
754
- }
755
- return value;
756
- }
757
59
  //# sourceMappingURL=index.js.map