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 |
x5
x5
x5
x5
x5
x5
x5
x5
x5
x53
x53
x53
x53
x53
x5
x5
x86
x86
x86
x5
x5
x163
x163
x5
x42
x42
x5
x24
x24
x5
x54
x54
x5
x20
x20
x5
x105
x105
x5
x40
x40
x40
x40
x40
x40
x5
x11
x11
x5
x41
x51
x51
x76
x41
x5
x5
x5
x86
x86
x86
x86
x86
x86
x86
x86
x86
x86
x86
x86
x86
x86
x86
x86
x86
x5
x5
x86
x86
x86
x86
x86
x86
x86
x5
x5
x5
x5
x5
x5
x107
x107
x107
x107
x108
x108
x540
x108
x107
x108
x108
x540
x108
x207
x207
x207
x207
x207
x207
x207
x207
x107
x5
x43
x43
x43
x43
x43
x44
x44
x44
x44
x44
x44
x44
x44
x43
x56
x56
x56
x57
x57
x57
x57
x57
x57
x57
x57
x68
x68
x68
x385
x77
x272
x68
x68
x56
x79
x43
x44
x44
x44
x44
x44
x44
x44
x44
x78
x78
x43
x5
x101
x101
x101
x102
x102
x102
x102
x102
x102
x102
x102
x196
x101
x110
x110
x118
x119
x119
x119
x119
x119
x119
x119
x119
x125
x110
x111
x111
x110
x195
x195
x101
x135
x135
x154
x154
x154
x166
x166
x154
x156
x156
x156
x154
x155
x155
x155
x155
x155
x155
x155
x155
x171
x171
x167
x170
x170
x171
x154
x155
x154
x471
x157
x154
x135
x194
x101
x104
x104
x105
x105
x107
x107
x108
x108
x108
x108
x108
x108
x108
x108
x108
x108
x104
x106
x193
x101
x169
x169
x101
x101
x101
x101
x101
x101
x101
x101
x101
x101
x141
x141
x141
x141
x141
x141
x141
x141
x170
x170
x141
x145
x145
x147
x147
x147
x147
x145
x145
x101
x153
x153
x153
x153
x153
x153
x153
x153
x153
x153
x193
x193
x193
x101
x5
x5
x5
x5
x5
x5
x57
x57
x59
x59
x295
x59
x57
x58
x58
x290
x58
x106
x57
x63
x63
x68
x63
x64
x64
x63
x63
x57
x57
x57
x57
x57
x57
x57
x57
x93
x93
x57
x5
x5
x5
x5
x5
x5
x47
x47
x47
x53
x54
x54
x270
x54
x53
x56
x57
x57
x285
x56
x58
x58
x290
x58
x56
x55
x53
x53
x83
x47
x47
x47
x5
x5
x5
x5
x5
x5
x11
x11
x12
x12
x60
x12
x11
x16
x16
x80
x16
x11
x13
x13
x13
x13
x11
x5
x5
x5
x5
x5
x5
x8
x8
x8
x5
x5
x5
x5
x5
x5
x5
x10
x10
x10
x10
x10
x10
x10
x10
x10
x5
x5
x5
x5
x5
x5
x5
x5
x10
x10
x10
x10
x10
x10
x10
x10
x5
x5
x67
x69
x69
x69
x69
x69
x127
x67
x5 |
I
I
I
I
|
// Copyright 2018-2026 the Deno authors. MIT license.
// This module is browser compatible.
/**
* Internal XML parser module.
*
* Transforms raw tokens from the tokenizer into high-level events,
* handling namespace prefixes, entity decoding, and well-formedness validation.
*
* Uses a callback-based API for zero-allocation streaming.
*
* @module
*/
import type {
ParseStreamOptions,
XmlAttributeIterator,
XmlEventCallbacks,
XmlTokenCallbacks,
} from "./types.ts";
import { XmlSyntaxError } from "./types.ts";
import { decodeEntities } from "./_entities.ts";
import {
validateNamespaceBinding,
validateQName,
WHITESPACE_ONLY_RE,
XML_NAMESPACE,
} from "./_common.ts";
/**
* Normalizes attribute value per XML 1.0 §3.3.3.
*
* Only predefined entities are expanded (lt, gt, amp, apos, quot).
* Custom entities from DTD are NOT expanded.
*
* @see {@link https://www.w3.org/TR/xml/#AVNormalize}
*/
function normalizeAttributeValue(raw: string): string {
// Replace literal \t and \n with space BEFORE entity decoding (preserves )
const normalized = raw.includes("\t") || raw.includes("\n")
? raw.replace(/[\t\n]/g, " ")
: raw;
return decodeEntities(normalized);
}
/**
* Reusable attribute iterator implementation.
*
* This class reuses internal arrays across elements to avoid allocations.
* The iterator is valid only until the next element is processed.
*/
class AttributeIteratorImpl implements XmlAttributeIterator {
#names: string[] = [];
#values: string[] = [];
#colonIndices: number[] = [];
#uris: (string | undefined)[] = [];
#count = 0;
get count(): number {
return this.#count;
}
getName(index: number): string {
return this.#names[index]!;
}
getValue(index: number): string {
return this.#values[index]!;
}
getColonIndex(index: number): number {
return this.#colonIndices[index]!;
}
getUri(index: number): string | undefined {
return this.#uris[index];
}
/** @internal Reset the iterator for a new element. */
_reset(): void {
this.#count = 0;
}
/** @internal Add an attribute (name already decoded, value raw). */
_add(name: string, value: string): void {
this.#names[this.#count] = name;
this.#values[this.#count] = normalizeAttributeValue(value);
this.#colonIndices[this.#count] = name.indexOf(":");
this.#uris[this.#count] = undefined; // Will be set later
this.#count++;
}
/** @internal Set the URI for an attribute at the given index. */
_setUri(index: number, uri: string | undefined): void {
this.#uris[index] = uri;
}
/** @internal Check if an attribute with this name already exists. */
_has(name: string): boolean {
for (let i = 0; i < this.#count; i++) {
if (this.#names[i] === name) return true;
}
return false;
}
}
/**
* Stateful XML Event Parser.
*
* Implements {@linkcode XmlTokenCallbacks} to receive tokens from the tokenizer,
* and emits events via {@linkcode XmlEventCallbacks}. This enables zero-allocation
* streaming from tokenizer through parser to consumer.
*/
export class XmlEventParser implements XmlTokenCallbacks {
#callbacks: XmlEventCallbacks;
#ignoreWhitespace: boolean;
#ignoreComments: boolean;
#ignoreProcessingInstructions: boolean;
#coerceCDataToText: boolean;
#elementStack: Array<{
rawName: string;
colonIndex: number;
uri: string | undefined;
line: number;
column: number;
offset: number;
}> = [];
/** Track whether root element has been seen and closed */
#hasRoot = false;
#rootClosed = false;
// Note: We do NOT expand custom entities from DTD.
// Only predefined entities (lt, gt, amp, apos, quot) are supported.
// External entities (SYSTEM/PUBLIC) are also not supported.
/** Pending element state (reused across elements). */
#pendingName = "";
#pendingColonIndex = -1;
#pendingLine = 0;
#pendingColumn = 0;
#pendingOffset = 0;
#hasPendingElement = false;
/** Reusable attribute iterator. */
#attrIterator = new AttributeIteratorImpl();
/** Namespace tracking (lazy initialization for performance) */
#nsBindings: Map<string, string> | null = null;
/** Stack of namespace bindings per element scope */
#nsStack: Array<Array<[string, string | undefined]>> = [];
/** Pending namespace bindings for current element */
#pendingNsBindings: Array<[string, string | undefined]> = [];
constructor(callbacks: XmlEventCallbacks, options: ParseStreamOptions = {}) {
this.#callbacks = callbacks;
this.#ignoreWhitespace = options.ignoreWhitespace ?? false;
this.#ignoreComments = options.ignoreComments ?? false;
this.#ignoreProcessingInstructions = options.ignoreProcessingInstructions ??
false;
this.#coerceCDataToText = options.coerceCDataToText ?? false;
}
// XmlTokenCallbacks implementation
onStartTagOpen(
name: string,
line: number,
column: number,
offset: number,
): void {
const colonIndex = name.indexOf(":");
// Validate QName syntax (Namespaces §3)
const qnameError = validateQName(name, colonIndex);
if (qnameError) {
throw new XmlSyntaxError(
`Invalid element name '${name}': ${qnameError}`,
{ line, column, offset },
);
}
// Elements cannot use xmlns prefix (Namespaces 1.0 errata NE08)
if (colonIndex !== -1 && name.slice(0, colonIndex) === "xmlns") {
throw new XmlSyntaxError(
"Element name cannot use the 'xmlns' prefix",
{ line, column, offset },
);
}
this.#pendingName = name;
this.#pendingColonIndex = colonIndex;
this.#pendingLine = line;
this.#pendingColumn = column;
this.#pendingOffset = offset;
this.#hasPendingElement = true;
this.#attrIterator._reset();
this.#pendingNsBindings.length = 0; // Reset for new element
}
onAttribute(name: string, value: string): void {
if (this.#hasPendingElement) {
// Validate QName syntax for attribute name (Namespaces §3)
const colonIndex = name.indexOf(":");
const qnameError = validateQName(name, colonIndex);
if (qnameError) {
throw new XmlSyntaxError(
`Invalid attribute name '${name}': ${qnameError}`,
{
line: this.#pendingLine,
column: this.#pendingColumn,
offset: this.#pendingOffset,
},
);
}
// Validate namespace binding if this is an xmlns attribute
if (name === "xmlns" || name.startsWith("xmlns:")) {
// Normalize the attribute value for namespace URI
const normalizedValue = normalizeAttributeValue(value);
const nsError = validateNamespaceBinding(name, normalizedValue);
if (nsError) {
throw new XmlSyntaxError(
nsError,
{
line: this.#pendingLine,
column: this.#pendingColumn,
offset: this.#pendingOffset,
},
);
}
// Track xmlns:prefix declarations
if (name.startsWith("xmlns:")) {
const prefix = name.slice(6); // After "xmlns:"
// Lazy init namespace bindings
if (!this.#nsBindings) {
this.#nsBindings = new Map([["xml", XML_NAMESPACE]]);
}
// Save previous binding for restoration
this.#pendingNsBindings.push([prefix, this.#nsBindings.get(prefix)]);
this.#nsBindings.set(prefix, normalizedValue);
}
}
// XML 1.0 §3.1: Attribute names must be unique within a start-tag
if (this.#attrIterator._has(name)) {
throw new XmlSyntaxError(
`Duplicate attribute '${name}'`,
{
line: this.#pendingLine,
column: this.#pendingColumn,
offset: this.#pendingOffset,
},
);
}
this.#attrIterator._add(name, value);
}
}
onStartTagClose(selfClosing: boolean): void {
if (this.#hasPendingElement) {
// XML 1.0 §2.8: Only one root element is allowed
if (this.#rootClosed) {
throw new XmlSyntaxError(
"Only one root element is allowed (XML 1.0 §2.8)",
{
line: this.#pendingLine,
column: this.#pendingColumn,
offset: this.#pendingOffset,
},
);
}
// Validate element prefix is bound (if it has one) and resolve URI
let elementUri: string | undefined;
if (this.#pendingColonIndex !== -1) {
const prefix = this.#pendingName.slice(0, this.#pendingColonIndex);
// xml prefix is always implicitly bound, xmlns prefix is handled separately
if (prefix !== "xml" && prefix !== "xmlns") {
if (!this.#nsBindings || !this.#nsBindings.has(prefix)) {
throw new XmlSyntaxError(
`Unbound namespace prefix '${prefix}' in element <${this.#pendingName}>`,
{
line: this.#pendingLine,
column: this.#pendingColumn,
offset: this.#pendingOffset,
},
);
}
elementUri = this.#nsBindings.get(prefix);
} else if (prefix === "xml") {
elementUri = XML_NAMESPACE;
}
}
// Validate attribute prefixes are bound, resolve URIs, and check for duplicate expanded names
// Optimized: only do expensive expansion check when same local name appears with different prefixes
const attrCount = this.#attrIterator.count;
let localNameToPrefixes: Map<string, string[]> | null = null;
for (let i = 0; i < attrCount; i++) {
const colonIdx = this.#attrIterator.getColonIndex(i);
if (colonIdx !== -1) {
const attrName = this.#attrIterator.getName(i);
const prefix = attrName.slice(0, colonIdx);
// Skip xmlns: attributes (they declare, not use, prefixes)
if (prefix === "xmlns") {
// xmlns: attributes don't have namespace URIs (they ARE the declarations)
continue;
}
// xml prefix is always implicitly bound
if (prefix === "xml") {
this.#attrIterator._setUri(i, XML_NAMESPACE);
continue;
}
if (!this.#nsBindings || !this.#nsBindings.has(prefix)) {
throw new XmlSyntaxError(
`Unbound namespace prefix '${prefix}' in attribute '${attrName}'`,
{
line: this.#pendingLine,
column: this.#pendingColumn,
offset: this.#pendingOffset,
},
);
}
// Set the resolved URI for this attribute
this.#attrIterator._setUri(i, this.#nsBindings.get(prefix));
// Track local names for duplicate expanded name detection
const localName = attrName.slice(colonIdx + 1);
if (!localNameToPrefixes) {
localNameToPrefixes = new Map();
}
const prefixes = localNameToPrefixes.get(localName);
if (prefixes) {
prefixes.push(prefix);
} else {
localNameToPrefixes.set(localName, [prefix]);
}
}
}
// Check for duplicate expanded attribute names (Namespaces §6.3)
// Only when same local name appears with multiple prefixes
if (localNameToPrefixes && this.#nsBindings) {
for (const [localName, prefixes] of localNameToPrefixes) {
if (prefixes.length > 1) {
// Multiple prefixes for same local name - check if any resolve to same URI
const seenUris = new Set<string>();
for (const prefix of prefixes) {
const uri = this.#nsBindings.get(prefix)!;
if (seenUris.has(uri)) {
throw new XmlSyntaxError(
`Duplicate expanded attribute name '{${uri}}${localName}'`,
{
line: this.#pendingLine,
column: this.#pendingColumn,
offset: this.#pendingOffset,
},
);
}
seenUris.add(uri);
}
}
}
}
// Track root element
const isRoot = !this.#hasRoot;
if (isRoot) {
this.#hasRoot = true;
}
this.#callbacks.onStartElement?.(
this.#pendingName,
this.#pendingColonIndex,
elementUri,
this.#attrIterator,
selfClosing,
this.#pendingLine,
this.#pendingColumn,
this.#pendingOffset,
);
if (selfClosing) {
this.#callbacks.onEndElement?.(
this.#pendingName,
this.#pendingColonIndex,
elementUri,
this.#pendingLine,
this.#pendingColumn,
this.#pendingOffset,
);
// If this was the root and it's self-closing, root is now closed
if (isRoot) {
this.#rootClosed = true;
}
// Restore namespace bindings for self-closing element
if (this.#pendingNsBindings.length > 0 && this.#nsBindings) {
for (const [prefix, previousUri] of this.#pendingNsBindings) {
if (previousUri === undefined) {
this.#nsBindings.delete(prefix);
} else {
this.#nsBindings.set(prefix, previousUri);
}
}
}
} else {
this.#elementStack.push({
rawName: this.#pendingName,
colonIndex: this.#pendingColonIndex,
uri: elementUri,
line: this.#pendingLine,
column: this.#pendingColumn,
offset: this.#pendingOffset,
});
// Push namespace bindings to stack
this.#nsStack.push(this.#pendingNsBindings.slice());
}
// Reset pending namespace bindings for next element
this.#pendingNsBindings.length = 0;
this.#hasPendingElement = false;
}
}
onEndTag(
name: string,
line: number,
column: number,
offset: number,
): void {
const expected = this.#elementStack.pop();
if (expected === undefined) {
throw new XmlSyntaxError(
`Unexpected closing tag </${name}> with no matching opening tag`,
{ line, column, offset },
);
}
if (expected.rawName !== name) {
throw new XmlSyntaxError(
`Mismatched closing tag: expected </${expected.rawName}> but found </${name}>`,
{ line, column, offset },
);
}
// Restore namespace bindings from this element's scope
const elementBindings = this.#nsStack.pop();
if (elementBindings && this.#nsBindings) {
for (const [prefix, previousUri] of elementBindings) {
if (previousUri === undefined) {
this.#nsBindings.delete(prefix);
} else {
this.#nsBindings.set(prefix, previousUri);
}
}
}
this.#callbacks.onEndElement?.(
name,
expected.colonIndex,
expected.uri,
line,
column,
offset,
);
// Track when root element closes
if (this.#elementStack.length === 0 && this.#hasRoot) {
this.#rootClosed = true;
}
}
onText(
content: string,
line: number,
column: number,
offset: number,
): void {
// XML 1.0 §2.8: Prolog and epilog only allow Misc, where:
// Misc ::= Comment | PI | S
// S is LITERAL whitespace only, not character/entity references
const outsideRoot = !this.#hasRoot || this.#rootClosed;
if (outsideRoot) {
// Check raw content for any entity/character references
if (content.includes("&")) {
throw new XmlSyntaxError(
"Character/entity references are not allowed in prolog/epilog (XML 1.0 §2.8)",
{ line, column, offset },
);
}
// For outside root, only whitespace is allowed - check raw content first
// (avoids entity decoding for whitespace-only content)
if (!WHITESPACE_ONLY_RE.test(content)) {
if (!this.#hasRoot) {
throw new XmlSyntaxError(
"Content is not allowed before the root element (XML 1.0 §2.8)",
{ line, column, offset },
);
} else {
throw new XmlSyntaxError(
"Content is not allowed after the root element (XML 1.0 §2.8)",
{ line, column, offset },
);
}
}
// Outside root whitespace - skip if ignoring whitespace, otherwise emit
if (this.#ignoreWhitespace) return;
this.#callbacks.onText?.(content, line, column, offset);
return;
}
// Inside root element - decode entities
const text = decodeEntities(content);
if (this.#ignoreWhitespace && WHITESPACE_ONLY_RE.test(text)) return;
this.#callbacks.onText?.(text, line, column, offset);
}
onCData(
content: string,
line: number,
column: number,
offset: number,
): void {
// XML 1.0 §2.8: CDATA sections are only allowed within elements
if (!this.#hasRoot) {
throw new XmlSyntaxError(
"CDATA section is not allowed before the root element (XML 1.0 §2.8)",
{ line, column, offset },
);
}
if (this.#rootClosed) {
throw new XmlSyntaxError(
"CDATA section is not allowed after the root element (XML 1.0 §2.8)",
{ line, column, offset },
);
}
if (this.#coerceCDataToText) {
this.#callbacks.onText?.(content, line, column, offset);
} else {
this.#callbacks.onCData?.(content, line, column, offset);
}
}
onComment(
content: string,
line: number,
column: number,
offset: number,
): void {
if (this.#ignoreComments) return;
this.#callbacks.onComment?.(content, line, column, offset);
}
onProcessingInstruction(
target: string,
content: string,
line: number,
column: number,
offset: number,
): void {
// XML Namespaces §3: PI targets must not contain colons
if (target.includes(":")) {
throw new XmlSyntaxError(
"Processing instruction target must not contain ':' (Namespaces §3)",
{ line, column, offset },
);
}
if (this.#ignoreProcessingInstructions) return;
this.#callbacks.onProcessingInstruction?.(
target,
content,
line,
column,
offset,
);
}
onDeclaration(
version: string,
encoding: string | undefined,
standalone: "yes" | "no" | undefined,
line: number,
column: number,
offset: number,
): void {
this.#callbacks.onDeclaration?.(
version,
encoding,
standalone,
line,
column,
offset,
);
}
// DOCTYPE parsed by tokenizer but not emitted as event
onDoctype(): void {}
// Entity declarations from DTD are intentionally NOT stored.
// We only support the 5 predefined XML entities.
// deno-lint-ignore no-unused-vars
onEntityDeclaration(name: string, value: string): void {
// Intentionally empty - custom entities are not expanded
}
// Public API
/**
* Finalize parsing and validate that all elements are closed.
*
* @throws {XmlSyntaxError} If there are unclosed elements or no root element.
*/
finalize(): void {
if (this.#elementStack.length > 0) {
const unclosed = this.#elementStack[this.#elementStack.length - 1]!;
throw new XmlSyntaxError(
`Unclosed element <${unclosed.rawName}>`,
unclosed,
);
}
// XML 1.0 §2.1: A well-formed document must have exactly one root element
if (!this.#hasRoot) {
throw new XmlSyntaxError(
"No root element found in XML document",
{ line: 0, column: 0, offset: 0 },
);
}
}
}
|