-
-
Notifications
You must be signed in to change notification settings - Fork 38
Expand file tree
/
Copy pathXMLBuilderCBImpl.ts
More file actions
804 lines (687 loc) · 26 KB
/
Copy pathXMLBuilderCBImpl.ts
File metadata and controls
804 lines (687 loc) · 26 KB
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
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
import {
XMLBuilderCB, AttributesObject, PIObject, DTDOptions, XMLBuilder,
XMLBuilderCBOptions, XMLBuilderCreateOptions, DefaultXMLBuilderCBOptions,
ExpandObject, XMLBuilderCBCreateOptions, XMLBuilderOptions, BaseCBWriterOptions
} from "../interfaces"
import { applyDefaults, isString, isObject } from "@oozcitak/util"
import { fragment, create } from "./BuilderFunctions"
import { sanitizeInput } from "./dom"
import {
xml_isName, xml_isLegalChar, xml_isPubidChar
} from "@oozcitak/dom/lib/algorithm"
import { namespace as infraNamespace } from "@oozcitak/infra"
import { NamespacePrefixMap } from "@oozcitak/dom/lib/serializer/NamespacePrefixMap"
import {
Comment, Text, ProcessingInstruction, DocumentType, Element, Node
} from "@oozcitak/dom/lib/dom/interfaces"
import { LocalNameSet } from "@oozcitak/dom/lib/serializer/LocalNameSet"
import { Guard } from "@oozcitak/dom/lib/util"
import { BaseCBWriter } from "../writers/BaseCBWriter"
import { XMLCBWriter } from "../writers/XMLCBWriter"
import { JSONCBWriter } from "../writers/JSONCBWriter"
import { YAMLCBWriter } from "../writers/YAMLCBWriter"
import { EventEmitter } from "events"
import {
nonEntityAmpersandRegex, encodeTextValueRegex, encodeTextValueLookup,
encodeAttributeValueRegex, encodeAttributeValueLookup
} from "../constants"
/**
* Stores the last generated prefix. An object is used instead of a number so
* that the value can be passed by reference.
*/
type PrefixIndex = { value: number }
/**
* Represents a readable XML document stream.
*/
export class XMLBuilderCBImpl extends EventEmitter implements XMLBuilderCB {
private static _VoidElementNames = new Set(['area', 'base', 'basefont',
'bgsound', 'br', 'col', 'embed', 'frame', 'hr', 'img', 'input', 'keygen',
'link', 'menuitem', 'meta', 'param', 'source', 'track', 'wbr'])
private _options: Required<XMLBuilderCBOptions>
private _builderOptions: XMLBuilderCreateOptions
private _writer: BaseCBWriter<BaseCBWriterOptions>
private _fragment: boolean
private _hasDeclaration = false
private _docTypeName = ""
private _hasDocumentElement = false
private _currentElement?: XMLBuilder
private _currentElementSerialized = false
private _openTags: Array<[
string, // qualified name
string | null, // original inherited ns
NamespacePrefixMap, // original prefix map
boolean, // has children,
boolean | undefined // has text payload
]> = []
private _prefixMap: NamespacePrefixMap
private _prefixIndex: PrefixIndex
private _ended = false
/**
* Initializes a new instance of `XMLStream`.
*
* @param options - stream writer options
* @param fragment - whether to create fragment stream or a document stream
*
* @returns XML stream
*/
public constructor(options?: XMLBuilderCBCreateOptions, fragment = false) {
super()
this._fragment = fragment
// provide default options
this._options = applyDefaults(options || {},
DefaultXMLBuilderCBOptions
) as Required<XMLBuilderCBOptions>
this._builderOptions = {
defaultNamespace: this._options.defaultNamespace,
namespaceAlias: this._options.namespaceAlias
}
if (this._options.format === "json") {
this._writer = new JSONCBWriter(this._options)
} else if (this._options.format === "yaml") {
this._writer = new YAMLCBWriter(this._options)
} else {
this._writer = new XMLCBWriter(this._options)
}
// automatically create listeners for callbacks passed via options
if (this._options.data !== undefined) {
this.on("data", this._options.data)
}
if (this._options.end !== undefined) {
this.on("end", this._options.end)
}
if (this._options.error !== undefined) {
this.on("error", this._options.error)
}
this._prefixMap = new NamespacePrefixMap()
this._prefixMap.set("xml", infraNamespace.XML)
this._prefixIndex = { value: 1 }
this._push(this._writer.frontMatter())
}
/** @inheritdoc */
ele(p1: string | null | ExpandObject, p2?: AttributesObject | string,
p3?: AttributesObject): this {
// parse if JS object or XML or JSON string
if (isObject(p1) || (isString(p1) && (/^\s*</.test(p1) || /^\s*[\{\[]/.test(p1) || /^(\s*|(#.*)|(%.*))*---/.test(p1)))) {
const frag = fragment().set(this._options as unknown as Partial<XMLBuilderOptions>)
try {
frag.ele(p1 as any)
} catch (err) {
this.emit("error", err)
return this
}
for (const node of frag.node.childNodes) {
this._fromNode(node)
}
return this
}
this._serializeOpenTag(true)
if (!this._fragment && this._hasDocumentElement && this._writer.level === 0) {
this.emit("error", new Error("Document cannot have multiple document element nodes."))
return this
}
try {
this._currentElement = fragment(this._builderOptions).ele(p1 as any, p2 as any, p3 as any)
} catch (err) {
this.emit("error", err)
return this
}
if (!this._fragment && !this._hasDocumentElement && this._docTypeName !== ""
&& (this._currentElement.node as Element)._qualifiedName !== this._docTypeName) {
this.emit("error", new Error("Document element name does not match DocType declaration name."))
return this
}
this._currentElementSerialized = false
if (!this._fragment) {
this._hasDocumentElement = true
}
return this
}
/** @inheritdoc */
att(p1: AttributesObject | string | null, p2?: string, p3?: string): this {
if (this._currentElement === undefined) {
this.emit("error", new Error("Cannot insert an attribute node as child of a document node."))
return this
}
try {
this._currentElement.att(p1 as any, p2 as any, p3 as any)
} catch (err) {
this.emit("error", err)
return this
}
return this
}
/** @inheritdoc */
com(content: string): this {
this._serializeOpenTag(true)
let node: Comment
try {
node = fragment(this._builderOptions).com(content).first().node as Comment
} catch (err) {
/* istanbul ignore next */
this.emit("error", err)
/* istanbul ignore next */
return this
}
if (this._options.wellFormed && (!xml_isLegalChar(node.data) ||
node.data.indexOf("--") !== -1 || node.data.endsWith("-"))) {
this.emit("error", new Error("Comment data contains invalid characters (well-formed required)."))
return this
}
this._push(this._writer.comment(node.data))
return this
}
/** @inheritdoc */
txt(content: string): this {
if (!this._fragment && this._currentElement === undefined) {
this.emit("error", new Error("Cannot insert a text node as child of a document node."))
return this
}
this._serializeOpenTag(true)
let node: Text
try {
node = fragment(this._builderOptions).txt(content).first().node as Text
} catch (err) {
/* istanbul ignore next */
this.emit("error", err)
/* istanbul ignore next */
return this
}
if (this._options.wellFormed && !xml_isLegalChar(node.data)) {
this.emit("error", new Error("Text data contains invalid characters (well-formed required)."))
return this
}
const markup = node.data.replace(nonEntityAmpersandRegex, '&')
.replace(encodeTextValueRegex, token => encodeTextValueLookup[token])
this._push(this._writer.text(markup))
const lastEl = this._openTags[this._openTags.length - 1]
// edge case: text on top level.
if (lastEl) {
lastEl[lastEl.length - 1] = true
}
return this
}
/** @inheritdoc */
ins(target: string | PIObject, content: string = ''): this {
this._serializeOpenTag(true)
let node: ProcessingInstruction
try {
node = fragment(this._builderOptions).ins(target as any, content).first().node as ProcessingInstruction
} catch (err) {
/* istanbul ignore next */
this.emit("error", err)
/* istanbul ignore next */
return this
}
if (this._options.wellFormed && (node.target.indexOf(":") !== -1 || (/^xml$/i).test(node.target))) {
this.emit("error", new Error("Processing instruction target contains invalid characters (well-formed required)."))
return this
}
if (this._options.wellFormed && !xml_isLegalChar(node.data)) {
this.emit("error", Error("Processing instruction data contains invalid characters (well-formed required)."))
return this
}
this._push(this._writer.instruction(node.target, node.data))
return this
}
/** @inheritdoc */
dat(content: string): this {
this._serializeOpenTag(true)
if (content === null || content === undefined) {
if (this._options.keepNullNodes) {
content = ""
} else {
return this
}
}
let data: string
try {
data = sanitizeInput(content, this._options.invalidCharReplacement)
} catch (err) {
this.emit("error", err)
return this
}
if (this._options.wellFormed && !xml_isLegalChar(data)) {
this.emit("error", new Error("CDATA contains invalid characters (well-formed required)."))
return this
}
this._push(this._writer.cdata(data))
return this
}
/** @inheritdoc */
dec(options: { version?: "1.0", encoding?: string, standalone?: boolean } = { version: "1.0" }): this {
if (this._fragment) {
this.emit("error", Error("Cannot insert an XML declaration into a document fragment."))
return this
}
if (this._hasDeclaration) {
this.emit("error", Error("XML declaration is already inserted."))
return this
}
this._push(this._writer.declaration(options.version || "1.0", options.encoding, options.standalone))
this._hasDeclaration = true
return this
}
/** @inheritdoc */
dtd(options: DTDOptions & { name: string }): this {
if (this._fragment) {
this.emit("error", Error("Cannot insert a DocType declaration into a document fragment."))
return this
}
if (this._docTypeName !== "") {
this.emit("error", new Error("DocType declaration is already inserted."))
return this
}
if (this._hasDocumentElement) {
this.emit("error", new Error("Cannot insert DocType declaration after document element."))
return this
}
let node: DocumentType
try {
node = create().dtd(options).first().node as DocumentType
} catch (err) {
this.emit("error", err)
return this
}
if (this._options.wellFormed && !xml_isPubidChar(node.publicId)) {
this.emit("error", new Error("DocType public identifier does not match PubidChar construct (well-formed required)."))
return this
}
if (this._options.wellFormed &&
(!xml_isLegalChar(node.systemId) ||
(node.systemId.indexOf('"') !== -1 && node.systemId.indexOf("'") !== -1))) {
this.emit("error", new Error("DocType system identifier contains invalid characters (well-formed required)."))
return this
}
this._docTypeName = options.name
this._push(this._writer.docType(options.name, node.publicId, node.systemId))
return this
}
/** @inheritdoc */
import(node: XMLBuilder): this {
const frag = fragment().set(this._options as unknown as Partial<XMLBuilderOptions>)
try {
frag.import(node)
} catch (err) {
this.emit("error", err)
return this
}
for (const node of frag.node.childNodes) {
this._fromNode(node)
}
return this
}
/** @inheritdoc */
up(): this {
this._serializeOpenTag(false)
this._serializeCloseTag()
return this
}
/** @inheritdoc */
end(): this {
this._serializeOpenTag(false)
while (this._openTags.length > 0) {
this._serializeCloseTag()
}
this._push(null)
return this
}
/**
* Serializes the opening tag of an element node.
*
* @param hasChildren - whether the element node has child nodes
*/
private _serializeOpenTag(hasChildren: boolean): void {
if (this._currentElementSerialized) return
if (this._currentElement === undefined) return
const node = this._currentElement.node as Element
if (this._options.wellFormed && (node.localName.indexOf(":") !== -1 ||
!xml_isName(node.localName))) {
this.emit("error", new Error("Node local name contains invalid characters (well-formed required)."))
return
}
let qualifiedName = ""
let ignoreNamespaceDefinitionAttribute = false
let map = this._prefixMap.copy()
let localPrefixesMap: { [key: string]: string } = {}
let localDefaultNamespace = this._recordNamespaceInformation(node, map, localPrefixesMap)
let inheritedNS = this._openTags.length === 0 ? null : this._openTags[this._openTags.length - 1][1]
let ns = node.namespaceURI
if (ns === null) ns = inheritedNS
if (inheritedNS === ns) {
if (localDefaultNamespace !== null) {
ignoreNamespaceDefinitionAttribute = true
}
if (ns === infraNamespace.XML) {
qualifiedName = "xml:" + node.localName
} else {
qualifiedName = node.localName
}
this._writer.beginElement(qualifiedName)
this._push(this._writer.openTagBegin(qualifiedName))
} else {
let prefix = node.prefix
let candidatePrefix: string | null = null
if (prefix !== null || ns !== localDefaultNamespace) {
candidatePrefix = map.get(prefix, ns)
}
if (prefix === "xmlns") {
if (this._options.wellFormed) {
this.emit("error", new Error("An element cannot have the 'xmlns' prefix (well-formed required)."))
return
}
candidatePrefix = prefix
}
if (candidatePrefix !== null) {
qualifiedName = candidatePrefix + ':' + node.localName
if (localDefaultNamespace !== null && localDefaultNamespace !== infraNamespace.XML) {
inheritedNS = localDefaultNamespace || null
}
this._writer.beginElement(qualifiedName)
this._push(this._writer.openTagBegin(qualifiedName))
} else if (prefix !== null) {
if (prefix in localPrefixesMap) {
prefix = this._generatePrefix(ns, map, this._prefixIndex)
}
map.set(prefix, ns)
qualifiedName += prefix + ':' + node.localName
this._writer.beginElement(qualifiedName)
this._push(this._writer.openTagBegin(qualifiedName))
this._push(this._writer.attribute("xmlns:" + prefix,
this._serializeAttributeValue(ns, this._options.wellFormed)))
if (localDefaultNamespace !== null) {
inheritedNS = localDefaultNamespace || null
}
} else if (localDefaultNamespace === null ||
(localDefaultNamespace !== null && localDefaultNamespace !== ns)) {
ignoreNamespaceDefinitionAttribute = true
qualifiedName += node.localName
inheritedNS = ns
this._writer.beginElement(qualifiedName)
this._push(this._writer.openTagBegin(qualifiedName))
this._push(this._writer.attribute("xmlns",
this._serializeAttributeValue(ns, this._options.wellFormed)))
} else {
qualifiedName += node.localName
inheritedNS = ns
this._writer.beginElement(qualifiedName)
this._push(this._writer.openTagBegin(qualifiedName))
}
}
this._serializeAttributes(node, map, this._prefixIndex, localPrefixesMap,
ignoreNamespaceDefinitionAttribute, this._options.wellFormed)
const isHTML = (ns === infraNamespace.HTML)
if (isHTML && !hasChildren &&
XMLBuilderCBImpl._VoidElementNames.has(node.localName)) {
this._push(this._writer.openTagEnd(qualifiedName, true, true))
this._writer.endElement(qualifiedName)
} else if (!isHTML && !hasChildren) {
this._push(this._writer.openTagEnd(qualifiedName, true, false))
this._writer.endElement(qualifiedName)
} else {
this._push(this._writer.openTagEnd(qualifiedName, false, false))
}
this._currentElementSerialized = true
/**
* Save qualified name, original inherited ns, original prefix map, and
* hasChildren flag.
*/
this._openTags.push([qualifiedName, inheritedNS, this._prefixMap, hasChildren, undefined])
/**
* New values of inherited namespace and prefix map will be used while
* serializing child nodes. They will be returned to their original values
* when this node is closed using the _openTags array item we saved above.
*/
if (this._isPrefixMapModified(this._prefixMap, map)) {
this._prefixMap = map
}
/**
* Calls following this will either serialize child nodes or close this tag.
*/
this._writer.level++
}
/**
* Serializes the closing tag of an element node.
*/
private _serializeCloseTag(): void {
this._writer.level--
const lastEle = this._openTags.pop()
/* istanbul ignore next */
if (lastEle === undefined) {
this.emit("error", new Error("Last element is undefined."))
return
}
const [qualifiedName, ns, map, hasChildren, hasTextPayload] = lastEle
/**
* Restore original values of inherited namespace and prefix map.
*/
this._prefixMap = map
if (!hasChildren) return
this._push(this._writer.closeTag(qualifiedName, hasTextPayload))
this._writer.endElement(qualifiedName)
}
/**
* Pushes data to internal buffer.
*
* @param data - data
*/
private _push(data: string | null): void {
if (data === null) {
this._ended = true
this.emit("end")
} else if (this._ended) {
this.emit("error", new Error("Cannot push to ended stream."))
} else if (data.length !== 0) {
this._writer.hasData = true
this.emit("data", data, this._writer.level)
}
}
/**
* Reads and serializes an XML tree.
*
* @param node - root node
*/
private _fromNode(node: Node) {
if (Guard.isElementNode(node)) {
const name = node.prefix ? node.prefix + ":" + node.localName : node.localName
if (node.namespaceURI !== null) {
this.ele(node.namespaceURI, name)
} else {
this.ele(name)
}
for (const attr of node.attributes) {
const name = attr.prefix ? attr.prefix + ":" + attr.localName : attr.localName
if (attr.namespaceURI !== null) {
this.att(attr.namespaceURI, name, attr.value)
} else {
this.att(name, attr.value)
}
}
for (const child of node.childNodes) {
this._fromNode(child)
}
this.up()
} else if (Guard.isExclusiveTextNode(node) && node.data) {
this.txt(node.data)
} else if (Guard.isCommentNode(node)) {
this.com(node.data)
} else if (Guard.isCDATASectionNode(node)) {
this.dat(node.data)
} else if (Guard.isProcessingInstructionNode(node)) {
this.ins(node.target, node.data)
}
}
/**
* Produces an XML serialization of the attributes of an element node.
*
* @param node - node to serialize
* @param map - namespace prefix map
* @param prefixIndex - generated namespace prefix index
* @param localPrefixesMap - local prefixes map
* @param ignoreNamespaceDefinitionAttribute - whether to ignore namespace
* attributes
* @param requireWellFormed - whether to check conformance
*/
private _serializeAttributes(node: Element, map: NamespacePrefixMap,
prefixIndex: PrefixIndex, localPrefixesMap: { [key: string]: string },
ignoreNamespaceDefinitionAttribute: boolean,
requireWellFormed: boolean): void {
const localNameSet = requireWellFormed ? new LocalNameSet() : undefined
for (const attr of node.attributes) {
// Optimize common case
if (!requireWellFormed && !ignoreNamespaceDefinitionAttribute && attr.namespaceURI === null) {
this._push(this._writer.attribute(attr.localName,
this._serializeAttributeValue(attr.value, this._options.wellFormed)))
continue
}
if (requireWellFormed && localNameSet && localNameSet.has(attr.namespaceURI, attr.localName)) {
this.emit("error", new Error("Element contains duplicate attributes (well-formed required)."))
return
}
if (requireWellFormed && localNameSet) localNameSet.set(attr.namespaceURI, attr.localName)
let attributeNamespace = attr.namespaceURI
let candidatePrefix: string | null = null
if (attributeNamespace !== null) {
candidatePrefix = map.get(attr.prefix, attributeNamespace)
if (attributeNamespace === infraNamespace.XMLNS) {
if (attr.value === infraNamespace.XML ||
(attr.prefix === null && ignoreNamespaceDefinitionAttribute) ||
(attr.prefix !== null && (!(attr.localName in localPrefixesMap) ||
localPrefixesMap[attr.localName] !== attr.value) &&
map.has(attr.localName, attr.value)))
continue
if (requireWellFormed && attr.value === infraNamespace.XMLNS) {
this.emit("error", new Error("XMLNS namespace is reserved (well-formed required)."))
return
}
if (requireWellFormed && attr.value === '') {
this.emit("error", new Error("Namespace prefix declarations cannot be used to undeclare a namespace (well-formed required)."))
return
}
if (attr.prefix === 'xmlns') candidatePrefix = 'xmlns'
/**
* _Note:_ The (candidatePrefix === null) check is not in the spec.
* We deviate from the spec here. Otherwise a prefix is generated for
* all attributes with namespaces.
*/
} else if (candidatePrefix === null) {
if (attr.prefix !== null &&
(!map.hasPrefix(attr.prefix) ||
map.has(attr.prefix, attributeNamespace))) {
/**
* Check if we can use the attribute's own prefix.
* We deviate from the spec here.
* TODO: This is not an efficient way of searching for prefixes.
* Follow developments to the spec.
*/
candidatePrefix = attr.prefix
} else {
candidatePrefix = this._generatePrefix(attributeNamespace, map, prefixIndex)
}
this._push(this._writer.attribute("xmlns:" + candidatePrefix,
this._serializeAttributeValue(attributeNamespace, this._options.wellFormed)))
}
}
if (requireWellFormed && (attr.localName.indexOf(":") !== -1 ||
!xml_isName(attr.localName) ||
(attr.localName === "xmlns" && attributeNamespace === null))) {
this.emit("error", new Error("Attribute local name contains invalid characters (well-formed required)."))
return
}
this._push(this._writer.attribute(
(candidatePrefix !== null ? candidatePrefix + ":" : "") + attr.localName,
this._serializeAttributeValue(attr.value, this._options.wellFormed)))
}
}
/**
* Produces an XML serialization of an attribute value.
*
* @param value - attribute value
* @param requireWellFormed - whether to check conformance
*/
private _serializeAttributeValue(value: string | null, requireWellFormed: boolean): string {
if (requireWellFormed && value !== null && !xml_isLegalChar(value)) {
this.emit("error", new Error("Invalid characters in attribute value."))
return ""
}
if (value === null) return ""
return value.replace(nonEntityAmpersandRegex, '&')
.replace(encodeAttributeValueRegex, token => encodeAttributeValueLookup[token])
}
/**
* Records namespace information for the given element and returns the
* default namespace attribute value.
*
* @param node - element node to process
* @param map - namespace prefix map
* @param localPrefixesMap - local prefixes map
*/
private _recordNamespaceInformation(node: Element, map: NamespacePrefixMap,
localPrefixesMap: { [key: string]: string }): string | null {
let defaultNamespaceAttrValue: string | null = null
for (const attr of node.attributes) {
let attributeNamespace = attr.namespaceURI
let attributePrefix = attr.prefix
if (attributeNamespace === infraNamespace.XMLNS) {
if (attributePrefix === null) {
defaultNamespaceAttrValue = attr.value
continue
} else {
let prefixDefinition = attr.localName
let namespaceDefinition: string | null = attr.value
if (namespaceDefinition === infraNamespace.XML) {
continue
}
if (namespaceDefinition === '') {
namespaceDefinition = null
}
if (map.has(prefixDefinition, namespaceDefinition)) {
continue
}
map.set(prefixDefinition, namespaceDefinition)
localPrefixesMap[prefixDefinition] = namespaceDefinition || ''
}
}
}
return defaultNamespaceAttrValue
}
/**
* Generates a new prefix for the given namespace.
*
* @param newNamespace - a namespace to generate prefix for
* @param prefixMap - namespace prefix map
* @param prefixIndex - generated namespace prefix index
*/
private _generatePrefix(newNamespace: string | null,
prefixMap: NamespacePrefixMap, prefixIndex: PrefixIndex): string {
let generatedPrefix = "ns" + prefixIndex.value
prefixIndex.value++
prefixMap.set(generatedPrefix, newNamespace)
return generatedPrefix
}
/**
* Determines if the namespace prefix map was modified from its original.
*
* @param originalMap - original namespace prefix map
* @param newMap - new namespace prefix map
*/
private _isPrefixMapModified(originalMap: NamespacePrefixMap, newMap: NamespacePrefixMap) {
const items1: { [key: string]: string[] } = (originalMap as any)._items
const items2: { [key: string]: string[] } = (newMap as any)._items
const nullItems1: string[] = (originalMap as any)._nullItems
const nullItems2: string[] = (newMap as any)._nullItems
for (const key in items2) {
const arr1 = items1[key]
if (arr1 === undefined) return true
const arr2 = items2[key]
if (arr1.length !== arr2.length) return true
for (let i = 0; i < arr1.length; i++) {
if (arr1[i] !== arr2[i]) return true
}
}
if (nullItems1.length !== nullItems2.length) return true
for (let i = 0; i < nullItems1.length; i++) {
if (nullItems1[i] !== nullItems2[i]) return true
}
return false
}
}