All files / stringify.ts

100.00% Branches 72/72
100.00% Lines 196/196
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
x1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
x7
x7
 
x1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
x7
x7
x32
x32
x32
x32
x32
x32
x32
x32
x32
x32
x38
x114
x38
x38
x38
x38
x32
x32
x38
x38
 
x32
x32
x32
x33
x33
x56
x33
x33
x220
 
x55
x55
 
x1
 
 
 
 
 
 
 
 
x7
x7
x9
x9
x9
x9
x9
 
x1
 
 
 
 
 
 
 
 
x7
x7
x9
x9
x9
x9
x9
 
x7
x7
x32
x32
x32
 
x7
x7
x38
x38
x38
x52
x52
x80
x80
x52
x52
x38
x38
 
x7
x7
x13
x13
x13
x13
x13
x13
x25
x25
x13
x13
x13
x13
x13
x13
x13
x13
x13
x13
x13
 
x7
x7
x144
x894
x150
x150
x149
x280
x280
x280
x280
x280
x184
x184
x144
x267
x267
x267
x363
x365
x365
x363
x363
x365
x365
x363
x267
x1524
x381
x267
x286
x286
x267
x144
x157
x157
x280
x280
 
x7
x7
x174
x174
x174
x756
x436
x436
x1800
x922
x1944
x486
x490
x490
x486
x486
x436
x2068
x436
x174
 
x174
x319
x436
x436
x3397
x436
x437
x436
x552
x552
x436
x319
x174
x174
x174
 
x7
x7
x180
x180
x2448
x180
x180
 
x7
x7
x7
x7
x7
x7
x7
x7
 
x7
x7
x205
x205
x205
x207
x207
x205
x603
x603
x205
x205
x1254
x209
x399
x399




























































































































































































































































































// Imports
import type { Nullable, record, rw } from "@libs/typing"
import type { stringifyable, xml_document, xml_node, xml_text } from "./_types.ts"
export type { Nullable, stringifyable, xml_document, xml_node, xml_text }

/** XML stringifier options. */
export type options = {
  /** Format options. */
  format?: {
    /**
     * Indent string (defaults to `"  "`).
     * Set to empty string to disable indentation and enable minification.
     */
    indent?: string
    /** Break text node if its length is greater than this value (defaults to `128`). */
    breakline?: number
  }
  /** Replace options. */
  replace?: {
    /**
     * Force escape all XML entities.
     * By default, only the ones that would break the XML structure are escaped.
     */
    entities?: boolean
    /**
     * Custom replacer (this is applied after other revivals).
     * When it is applied on an attribute, `key` and `value` will be given.
     * When it is applied on a node, both `key` and `value` will be `null`.
     * Return `undefined` to delete either the attribute or the tag.
     */
    custom?: (args: { name: string; key: Nullable<string>; value: Nullable<string>; node: Readonly<xml_node> }) => unknown
  }
}

/** XML stringifier options (with non-nullable format options). */
type _options = options & { format: NonNullable<options["format"]> }

/** Internal symbol to store properties without erasing user-provided ones. */
const internal = Symbol("internal")

/**
 * Stringify an {@link xml_document} object into a XML string.
 *
 * Output can be customized using the {@link options} parameter.
 *
 * @example
 * ```ts
 * import { stringify } from "./stringify.ts"
 *
 * console.log(stringify({
 *   "@version": "1.0",
 *   "@standalone": "yes",
 *   root: {
 *     text: "hello",
 *     array: ["world", "monde", "δΈ–η•Œ", "🌏"],
 *     number: 42,
 *     boolean: true,
 *     complex: {
 *       "@attribute": "value",
 *       "#text": "content",
 *     },
 *   }
 * }))
 * ```
 *
 * @module
 */
export function stringify(document: stringifyable, options?: options): string {
  options ??= {}
  options.format ??= {}
  options.format.indent ??= "  "
  options.format.breakline ??= 128
  const _options = options as _options
  let text = ""
  // Add prolog
  text += xml_prolog(document as xml_document, _options)
  // Add processing instructions
  if (document["#instructions"]) {
    for (const nodes of Object.values(document["#instructions"])) {
      for (const node of [nodes].flat()) {
        text += xml_instruction(node, _options)
      }
    }
  }
  // Add doctype
  if (document["#doctype"]) {
    text += xml_doctype(document["#doctype"] as xml_node, _options)
  }

  // Add root node
  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()
}

/**
 * Helper to create a CDATA node.
 *
 * @example
 * ```ts
 * import { stringify, cdata } from "./stringify.ts"
 * stringify({ string: cdata(`hello <world>`) })
 * // <string><![CDATA[hello <world>]]></string>
 * ```
 */
export function cdata(text: string): Omit<xml_text, "~parent"> {
  return {
    "~name": "~cdata",
    "#text": text,
  }
}

/**
 * Helper to create a comment node.
 *
 * @example
 * ```ts
 * import { stringify, comment } from "./stringify.ts"
 * stringify({ string: comment(`hello world`) })
 * // <string><!--hello world--></string>
 * ```
 */
export function comment(text: string): Omit<xml_text, "~parent"> {
  return {
    "~name": "~comment",
    "#text": text,
  }
}

/** Create XML prolog. */
function xml_prolog(document: xml_document, options: _options): string {
  ;(document as rw)["~name"] ??= "xml"
  return xml_instruction(document, options)
}

/** Create XML instruction. */
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
}

/** Create XML doctype. */
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
}

/** Create XML node. */
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
}

/** Extract children from node. */
function xml_children(node: xml_node, options: 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, ["~name"]: key } as record
            if (((value as record)["~name"] as string)?.startsWith("~")) {
              child[internal] = (value as record)["~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
}

/** Extract attributes from node. */
function xml_attributes(node: xml_node, options: 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>
}

/** Entities */
const entities = {
  "&": "&amp;", //Keep first
  '"': "&quot;",
  "<": "&lt;",
  ">": "&gt;",
  "'": "&apos;",
} as const

/** Replace value. */
function replace(node: xml_node | xml_text, key: string, options: 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
}