generated from parzh/package-javascript
-
Notifications
You must be signed in to change notification settings - Fork 1
/
convert-intermediate-json-to-js-xml.impl.ts
102 lines (80 loc) · 2.19 KB
/
convert-intermediate-json-to-js-xml.impl.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
import type { Intermediate } from "./convert-xml-to-intermediate-json.impl";
import type { JSXml, Primitive } from "./js-xml.type";
/** @private */
function isPrimitive(value: unknown): value is Primitive {
return typeof value === "string" || typeof value === "number" && !isNaN(value) || typeof value === "boolean";
}
export abstract class ConflictingDataError extends Error {
abstract readonly node: JSXml;
}
export class CannotSetLiteralContentError extends ConflictingDataError {
constructor(public node: JSXml) {
super("Cannot set literal content in a node that has child nodes");
}
}
export class CannotAddChildNodesError extends ConflictingDataError {
constructor(public node: JSXml) {
super("Cannot add child nodes in a node that has literal content");
}
}
/** @private */
function assertCanSetLiteralContent(node: JSXml): asserts node is JSXml<Primitive> {
if (node.$data !== "")
throw new CannotSetLiteralContentError(node);
}
/** @private */
function assertCanAddChildNode(node: JSXml): asserts node is JSXml<JSXml[]> {
if (node.$data === "")
node.$data = [];
else if (!Array.isArray(node.$data))
throw new CannotAddChildNodesError(node);
}
/** @private */
const _ = {} as const;
/** @private */
function populateNode(
node: JSXml,
host: Intermediate,
prop: string,
data = host[prop],
): void {
if (data == null || Number.isNaN(data))
return;
if (isPrimitive(data)) {
if (prop === "$t") {
assertCanSetLiteralContent(node);
node.$data = data;
} else {
node.$attr[prop] = data;
}
return;
}
if (data instanceof Array) {
for (const item of data)
populateNode(node, _ /* unused */, prop, item);
return;
}
assertCanAddChildNode(node);
const childNode: JSXml = {
$name: prop,
$attr: {},
$data: "",
};
for (const key in data)
populateNode(childNode, data, key);
node.$data.push(childNode);
}
export default function convertIntermediateJsonToJSXml(intermediate: Intermediate, key?: string): JSXml {
const node: JSXml<JSXml[]> = {
$name: "",
$attr: {},
$data: [],
};
if (key != null) {
populateNode(node, intermediate, key);
return node.$data[0];
}
for (const key in intermediate)
populateNode(node, intermediate, key);
return node;
}