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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314 |
x2
x2
x27
x27
x27
x27
x27
x27
x27
x27
x27
x7
x7
x7
x1
x1
x7
x7
x7
x7
x27
x6
x6
x27
x27
x1
x1
x26
x1
x1
x25
x25
x25
x2
x122
x122
x328
x328
x122
x1098
x449
x449
x122
x122
x122
x2
x2
x2
x2
x2
x2
x2
x2
x2
x2
x2
x2
x2
x27
x27
x27
x2
x34
x34
x34
x16
x16
x32
x32
x16
x16
x34
x34
x2
x6
x6
x6
x6
x6
x6
x12
x12
x6
x6
x6
x6
x6
x6
x6
x6
x6
x6
x6
x2
x158
x5
x1
x1
x5
x157
x157
x157
x157
x157
x42
x42
x158
x144
x144
x144
x109
x2
x2
x109
x109
x2
x2
x109
x144
x133
x133
x144
x26
x26
x144
x158
x13
x13
x157
x157
x2
x190
x190
x190
x190
x166
x166
x14
x166
x58
x58
x4
x4
x58
x58
x166
x94
x166
x190
x190
x166
x130
x130
x130
x130
x1
x130
x129
x129
x130
x166
x190
x190
x190
x2
x197
x197
x197
x197
x197
x2
x2
x2
x2
x2
x2
x2
x2
x217
x217
x217
x2
x2
x217
x649
x649
x217
x217
x4
x4
x213
x213 |
|
import type { Nullable, stringifyable, xml_document, xml_node, xml_text } from "./_types.ts"
export type * from "./_types.ts"
export type stringify_options = {
format?: format_options
replace?: replace_options
}
export type format_options = {
indent?: string
breakline?: number
}
export type replace_options = {
entities?: boolean
custom?: (args: { name: string; key: Nullable<string>; value: Nullable<string>; node: Readonly<xml_node> }) => unknown
}
type _options = stringify_options & { format: NonNullable<stringify_options["format"]> }
const internal = Symbol("internal")
export function stringify(document: stringifyable, options?: stringify_options): string {
options ??= {}
options.format ??= {}
options.format.indent ??= " "
options.format.breakline ??= 128
const _options = options as _options
let text = ""
document = clone(document)
text += xml_prolog(document as xml_document, _options)
if (document["#instructions"]) {
for (const [name, nodes] of Object.entries(document["#instructions"])) {
for (const node of [nodes].flat()) {
if (!("~name" in node)) {
Object.defineProperties(node, { ["~name"]: { enumerable: false, writable: false, value: name } })
}
text += xml_instruction(node, _options)
}
}
}
if (document["#doctype"]) {
text += xml_doctype(document["#doctype"] as xml_node, _options)
}
const [root, ...garbage] = xml_children(document as xml_document, _options)
if (!root) {
throw new SyntaxError("No root node detected")
}
if (garbage.length) {
throw new SyntaxError("Multiple root node detected")
}
text += xml_node(root, { ..._options, depth: 0 })
return text.trim()
}
function clone(document: Record<PropertyKey, unknown>) {
const cloned = (Array.isArray(document) ? [] : {}) as typeof document
for (const property in document) {
cloned[property] = ((document[property] !== null) && (["object", "function"].includes(typeof document[property]))) ? clone(document[property] as Record<PropertyKey, unknown>) : document[property]
}
;["~name", "~parent", "#text", "~children", "#comments", "#text", "#doctype", "#instructions", internal].forEach((property) => {
if (property in document) {
Object.defineProperty(cloned, property, Object.getOwnPropertyDescriptor(document, property)!)
}
})
return cloned
}
export function cdata(text: string): Omit<xml_text, "~parent"> {
return {
"~name": "~cdata",
"#text": text,
}
}
export function comment(text: string): Omit<xml_text, "~parent"> {
return {
"~name": "~comment",
"#text": text,
}
}
function xml_prolog(document: xml_document, options: _options): string {
;(document as Record<PropertyKey, unknown>)["~name"] ??= "xml"
return xml_instruction(document, options)
}
function xml_instruction(node: xml_node, { format: { indent } }: _options): string {
let text = ""
const attributes = xml_attributes(node as xml_node, arguments[1])
if (attributes.length) {
text += `<?${node["~name"].replace(/^~/, "")}`
for (const [name, value] of attributes) {
text += ` ${name}="${value}"`
}
text += `?>${indent ? "\n" : ""}`
}
return text
}
function xml_doctype(node: xml_node, { format: { indent } }: _options): string {
let text = ""
const attributes = xml_attributes(node, arguments[1])
const elements = xml_children(node, arguments[1])
if (attributes.length + elements.length) {
text += `<!DOCTYPE`
for (const [name] of attributes) {
text += ` ${!/^[A-Za-z0-9_]+$/.test(name) ? `"${name}"` : name}`
}
if (elements.length) {
text += `${indent ? `\n${indent}` : " "}[${indent ? "\n" : ""}`
for (const element of elements) {
text += `${indent}<!ELEMENT ${element["~name"]} (${element["#text"]})>${indent ? "\n" : ""}`
}
text += `${indent ? indent : ""}]${indent ? "\n" : ""}`
}
text += `>${indent ? "\n" : ""}`
}
return text
}
function xml_node(node: xml_node, { format: { breakline = 0, indent = "" }, replace, depth = 0 }: _options & { depth?: number }): string {
if (replace?.custom) {
if (replace.custom({ name: node["~name"], key: null, value: null, node }) === undefined) {
return ""
}
}
let text = `${indent.repeat(depth)}<${node["~name"]}`
const attributes = xml_attributes(node, arguments[1])
const children = xml_children(node, arguments[1])
const preserve = node["@xml:space"] === "preserve"
for (const [name, value] of attributes) {
text += ` ${name}="${value}"`
}
if ((children.length) || (("#text" in node) && (node["#text"].length))) {
const inline = indent && (!preserve) && ((children.length) || (node["#text"].length > breakline - indent.length * depth))
text += `>${indent && (!preserve) && (children.length) ? "\n" : ""}`
if ("#text" in node) {
if (inline) {
text += `\n${indent.repeat(depth + 1)}`
}
text += node["#text"]
if (inline) {
text += "\n"
}
}
for (const child of children) {
text += xml_node(child, { ...arguments[1], depth: depth + 1 })
}
if (inline) {
text += indent.repeat(depth)
}
text += `</${node["~name"]}>${indent ? "\n" : ""}`
} else {
text += `/>${indent ? "\n" : ""}`
}
return text
}
function xml_children(node: xml_node, options: stringify_options): Array<xml_node> {
const children = Object.keys(node)
.filter((key) => /^[A-Za-z_]/.test(key))
.flatMap((key) =>
[node![key]].flat().map((value) => {
switch (true) {
case value === null:
return ({ ["~name"]: key, ["#text"]: "" })
case typeof value === "object": {
const child = { ...value as Record<PropertyKey, unknown>, ["~name"]: key } as Record<PropertyKey, unknown>
if (((value as Record<PropertyKey, unknown>)["~name"] as string)?.startsWith("~")) {
child[internal] = (value as Record<PropertyKey, unknown>)["~name"]
}
return child
}
default:
return ({ ["~name"]: key, ["#text"]: `${value}` })
}
})
)
.map((node) => {
if ("#text" in node) {
const cdata = node[internal] === "~cdata"
const comment = node[internal] === "~comment"
node["#text"] = replace(node as xml_node, "#text", { ...options, escape: cdata ? [] : ["&", "<", ">"] }) as string
if (node["#text"] === undefined) {
delete node["#text"]
} else {
node["#text"] = cdata ? `<![CDATA[${node["#text"]}]]>` : comment ? `<!--${node["#text"]}-->` : `${node["#text"]}`
}
}
return node
}) as ReturnType<typeof xml_children>
return children
}
function xml_attributes(node: xml_node, options: stringify_options): Array<[string, string]> {
return Object.entries(node!)
.filter(([key]) => key.startsWith("@"))
.map(([key]) => [key.slice(1), replace(node!, key, { ...options, escape: ["&", '"', "'"] })])
.filter(([_, value]) => value !== undefined) as ReturnType<typeof xml_attributes>
}
const entities = {
"&": "&",
'"': """,
"<": "<",
">": ">",
"'": "'",
} as const
function replace(node: xml_node | xml_text, key: string, options: stringify_options & { escape?: Array<keyof typeof entities> }) {
let value = `${(node as xml_node)[key]}` as string
if (options?.escape) {
if (options?.replace?.entities) {
options.escape = Object.keys(entities) as Array<keyof typeof entities>
}
for (const char of options?.escape) {
value = `${value}`.replaceAll(char, entities[char])
}
}
if (options?.replace?.custom) {
return options.replace.custom({ name: node["~name"], key, value, node: node as xml_node })
}
return value
}
|