id
int64 0
3.78k
| code
stringlengths 13
37.9k
| declarations
stringlengths 16
64.6k
|
---|---|---|
1,100 | (options?: FormatDistanceFnOptions) => {
if (options?.addSuffix) {
if (options.comparison && options.comparison > 0) {
return 'жарты минут ішінде'
} else {
return 'жарты минут бұрын'
}
}
return 'жарты минут'
} | interface FormatDistanceFnOptions {
addSuffix?: boolean
comparison?: -1 | 0 | 1
} |
1,101 | function declension(scheme: Plural, count: number): string {
// scheme for count=1 exists
if (scheme.one && count === 1) return scheme.one
const rem10 = count % 10
const rem100 = count % 100
// 1, 21, 31, ...
if (rem10 === 1 && rem100 !== 11) {
return scheme.singularNominative.replace('{{count}}', String(count))
// 2, 3, 4, 22, 23, 24, 32 ...
} else if (rem10 >= 2 && rem10 <= 4 && (rem100 < 10 || rem100 > 20)) {
return scheme.singularGenitive.replace('{{count}}', String(count))
// 5, 6, 7, 8, 9, 10, 11, ...
} else {
return scheme.pluralGenitive.replace('{{count}}', String(count))
}
} | type Plural = {
one: string
other: string
} |
1,102 | function declension(scheme: Plural, count: number): string {
// scheme for count=1 exists
if (scheme.one && count === 1) return scheme.one
const rem10 = count % 10
const rem100 = count % 100
// 1, 21, 31, ...
if (rem10 === 1 && rem100 !== 11) {
return scheme.singularNominative.replace('{{count}}', String(count))
// 2, 3, 4, 22, 23, 24, 32 ...
} else if (rem10 >= 2 && rem10 <= 4 && (rem100 < 10 || rem100 > 20)) {
return scheme.singularGenitive.replace('{{count}}', String(count))
// 5, 6, 7, 8, 9, 10, 11, ...
} else {
return scheme.pluralGenitive.replace('{{count}}', String(count))
}
} | type Plural = {
one: Tense
other: Tense
} |
1,103 | function declension(scheme: Plural, count: number): string {
// scheme for count=1 exists
if (scheme.one && count === 1) return scheme.one
const rem10 = count % 10
const rem100 = count % 100
// 1, 21, 31, ...
if (rem10 === 1 && rem100 !== 11) {
return scheme.singularNominative.replace('{{count}}', String(count))
// 2, 3, 4, 22, 23, 24, 32 ...
} else if (rem10 >= 2 && rem10 <= 4 && (rem100 < 10 || rem100 > 20)) {
return scheme.singularGenitive.replace('{{count}}', String(count))
// 5, 6, 7, 8, 9, 10, 11, ...
} else {
return scheme.pluralGenitive.replace('{{count}}', String(count))
}
} | type Plural = {
one?: string
singularNominative: string
singularGenitive: string
pluralGenitive: string
} |
1,104 | function declension(scheme: Plural, count: number): string {
// scheme for count=1 exists
if (scheme.one && count === 1) return scheme.one
const rem10 = count % 10
const rem100 = count % 100
// 1, 21, 31, ...
if (rem10 === 1 && rem100 !== 11) {
return scheme.singularNominative.replace('{{count}}', String(count))
// 2, 3, 4, 22, 23, 24, 32 ...
} else if (rem10 >= 2 && rem10 <= 4 && (rem100 < 10 || rem100 > 20)) {
return scheme.singularGenitive.replace('{{count}}', String(count))
// 5, 6, 7, 8, 9, 10, 11, ...
} else {
return scheme.pluralGenitive.replace('{{count}}', String(count))
}
} | type Plural = {
one: string
two: string
few: string
other: string
} |
1,105 | function declension(scheme: Plural, count: number): string {
// scheme for count=1 exists
if (scheme.one && count === 1) return scheme.one
const rem10 = count % 10
const rem100 = count % 100
// 1, 21, 31, ...
if (rem10 === 1 && rem100 !== 11) {
return scheme.singularNominative.replace('{{count}}', String(count))
// 2, 3, 4, 22, 23, 24, 32 ...
} else if (rem10 >= 2 && rem10 <= 4 && (rem100 < 10 || rem100 > 20)) {
return scheme.singularGenitive.replace('{{count}}', String(count))
// 5, 6, 7, 8, 9, 10, 11, ...
} else {
return scheme.pluralGenitive.replace('{{count}}', String(count))
}
} | type Plural = {
one: string
other: string
} |
1,106 | function lastWeek(day: Day): string {
const weekday = accusativeWeekdays[day]
switch (day) {
case 0:
return "'в прошлое " + weekday + " в' p"
case 1:
case 2:
case 4:
return "'в прошлый " + weekday + " в' p"
case 3:
case 5:
case 6:
return "'в прошлую " + weekday + " в' p"
}
} | type Day = 0 | 1 | 2 | 3 | 4 | 5 | 6 |
1,107 | function thisWeek(day: Day) {
const weekday = accusativeWeekdays[day]
if (day === 2 /* Tue */) {
return "'во " + weekday + " в' p"
} else {
return "'в " + weekday + " в' p"
}
} | type Day = 0 | 1 | 2 | 3 | 4 | 5 | 6 |
1,108 | function nextWeek(day: Day) {
const weekday = accusativeWeekdays[day]
switch (day) {
case 0:
return "'в следующее " + weekday + " в' p"
case 1:
case 2:
case 4:
return "'в следующий " + weekday + " в' p"
case 3:
case 5:
case 6:
return "'в следующую " + weekday + " в' p"
}
} | type Day = 0 | 1 | 2 | 3 | 4 | 5 | 6 |
1,109 | function buildLocalizeTokenFn(scheme: Tense) {
return (count: number, options?: FormatDistanceFnOptions): string => {
if (options?.addSuffix) {
if (options.comparison && options.comparison > 0) {
if (scheme.future) {
return declension(scheme.future, count)
} else {
return 'через ' + declension(scheme.regular, count)
}
} else {
if (scheme.past) {
return declension(scheme.past, count)
} else {
return declension(scheme.regular, count) + ' назад'
}
}
} else {
return declension(scheme.regular, count)
}
}
} | type Tense = {
default: string
in: string
ago: string
} |
1,110 | function buildLocalizeTokenFn(scheme: Tense) {
return (count: number, options?: FormatDistanceFnOptions): string => {
if (options?.addSuffix) {
if (options.comparison && options.comparison > 0) {
if (scheme.future) {
return declension(scheme.future, count)
} else {
return 'через ' + declension(scheme.regular, count)
}
} else {
if (scheme.past) {
return declension(scheme.past, count)
} else {
return declension(scheme.regular, count) + ' назад'
}
}
} else {
return declension(scheme.regular, count)
}
}
} | type Tense = {
regular: string
past: string
future: string
} |
1,111 | function buildLocalizeTokenFn(scheme: Tense) {
return (count: number, options?: FormatDistanceFnOptions): string => {
if (options?.addSuffix) {
if (options.comparison && options.comparison > 0) {
if (scheme.future) {
return declension(scheme.future, count)
} else {
return 'через ' + declension(scheme.regular, count)
}
} else {
if (scheme.past) {
return declension(scheme.past, count)
} else {
return declension(scheme.regular, count) + ' назад'
}
}
} else {
return declension(scheme.regular, count)
}
}
} | type Tense = {
present: string
past: string
future: string
} |
1,112 | function buildLocalizeTokenFn(scheme: Tense) {
return (count: number, options?: FormatDistanceFnOptions): string => {
if (options?.addSuffix) {
if (options.comparison && options.comparison > 0) {
if (scheme.future) {
return declension(scheme.future, count)
} else {
return 'через ' + declension(scheme.regular, count)
}
} else {
if (scheme.past) {
return declension(scheme.past, count)
} else {
return declension(scheme.regular, count) + ' назад'
}
}
} else {
return declension(scheme.regular, count)
}
}
} | type Tense = {
default: string
future: string
past: string
} |
1,113 | function buildLocalizeTokenFn(scheme: Tense) {
return (count: number, options?: FormatDistanceFnOptions): string => {
if (options?.addSuffix) {
if (options.comparison && options.comparison > 0) {
if (scheme.future) {
return declension(scheme.future, count)
} else {
return 'через ' + declension(scheme.regular, count)
}
} else {
if (scheme.past) {
return declension(scheme.past, count)
} else {
return declension(scheme.regular, count) + ' назад'
}
}
} else {
return declension(scheme.regular, count)
}
}
} | type Tense = {
regular: DeclensionScheme
past?: DeclensionScheme
future?: DeclensionScheme
} |
1,114 | function buildLocalizeTokenFn(scheme: Tense) {
return (count: number, options?: FormatDistanceFnOptions): string => {
if (options?.addSuffix) {
if (options.comparison && options.comparison > 0) {
if (scheme.future) {
return declension(scheme.future, count)
} else {
return 'через ' + declension(scheme.regular, count)
}
} else {
if (scheme.past) {
return declension(scheme.past, count)
} else {
return declension(scheme.regular, count) + ' назад'
}
}
} else {
return declension(scheme.regular, count)
}
}
} | type Tense = {
past: Plural
future: Plural
present: Plural
} |
1,115 | function buildLocalizeTokenFn(scheme: Tense) {
return (count: number, options?: FormatDistanceFnOptions): string => {
if (options?.addSuffix) {
if (options.comparison && options.comparison > 0) {
if (scheme.future) {
return declension(scheme.future, count)
} else {
return 'через ' + declension(scheme.regular, count)
}
} else {
if (scheme.past) {
return declension(scheme.past, count)
} else {
return declension(scheme.regular, count) + ' назад'
}
}
} else {
return declension(scheme.regular, count)
}
}
} | type Tense = {
regular: string
past: string
future: string
} |
1,116 | function lastWeek(day: Day): string {
const weekday = accusativeWeekdays[day]
switch (day) {
case 0:
case 3:
case 5:
case 6:
return "'у минулу " + weekday + " о' p"
case 1:
case 2:
case 4:
return "'у минулий " + weekday + " о' p"
}
} | type Day = 0 | 1 | 2 | 3 | 4 | 5 | 6 |
1,117 | function thisWeek(day: Day): string {
const weekday = accusativeWeekdays[day]
return "'у " + weekday + " о' p"
} | type Day = 0 | 1 | 2 | 3 | 4 | 5 | 6 |
1,118 | function nextWeek(day: Day): string {
const weekday = accusativeWeekdays[day]
switch (day) {
case 0:
case 3:
case 5:
case 6:
return "'у наступну " + weekday + " о' p"
case 1:
case 2:
case 4:
return "'у наступний " + weekday + " о' p"
}
} | type Day = 0 | 1 | 2 | 3 | 4 | 5 | 6 |
1,119 | function declension(scheme: DeclensionScheme, count: number) {
// scheme for count=1 exists
if (scheme.one !== undefined && count === 1) {
return scheme.one
}
const rem10 = count % 10
const rem100 = count % 100
// 1, 21, 31, ...
if (rem10 === 1 && rem100 !== 11) {
return scheme.singularNominative.replace('{{count}}', String(count))
// 2, 3, 4, 22, 23, 24, 32 ...
} else if (rem10 >= 2 && rem10 <= 4 && (rem100 < 10 || rem100 > 20)) {
return scheme.singularGenitive.replace('{{count}}', String(count))
// 5, 6, 7, 8, 9, 10, 11, ...
} else {
return scheme.pluralGenitive.replace('{{count}}', String(count))
}
} | interface DeclensionScheme {
one?: string
singularNominative: string
singularGenitive: string
pluralGenitive: string
} |
1,120 | function declension(scheme: DeclensionScheme, count: number) {
// scheme for count=1 exists
if (scheme.one !== undefined && count === 1) {
return scheme.one
}
const rem10 = count % 10
const rem100 = count % 100
// 1, 21, 31, ...
if (rem10 === 1 && rem100 !== 11) {
return scheme.singularNominative.replace('{{count}}', String(count))
// 2, 3, 4, 22, 23, 24, 32 ...
} else if (rem10 >= 2 && rem10 <= 4 && (rem100 < 10 || rem100 > 20)) {
return scheme.singularGenitive.replace('{{count}}', String(count))
// 5, 6, 7, 8, 9, 10, 11, ...
} else {
return scheme.pluralGenitive.replace('{{count}}', String(count))
}
} | type DeclensionScheme = {
one?: string
singularNominative: string
singularGenitive: string
pluralGenitive: string
} |
1,121 | function declension(scheme: DeclensionScheme, count: number) {
// scheme for count=1 exists
if (scheme.one !== undefined && count === 1) {
return scheme.one
}
const rem10 = count % 10
const rem100 = count % 100
// 1, 21, 31, ...
if (rem10 === 1 && rem100 !== 11) {
return scheme.singularNominative.replace('{{count}}', String(count))
// 2, 3, 4, 22, 23, 24, 32 ...
} else if (rem10 >= 2 && rem10 <= 4 && (rem100 < 10 || rem100 > 20)) {
return scheme.singularGenitive.replace('{{count}}', String(count))
// 5, 6, 7, 8, 9, 10, 11, ...
} else {
return scheme.pluralGenitive.replace('{{count}}', String(count))
}
} | type DeclensionScheme = {
one?: string
singularNominative: string
singularGenitive: string
pluralGenitive: string
} |
1,122 | function declension(scheme: DeclensionScheme, count: number) {
// scheme for count=1 exists
if (scheme.one !== undefined && count === 1) {
return scheme.one
}
const rem10 = count % 10
const rem100 = count % 100
// 1, 21, 31, ...
if (rem10 === 1 && rem100 !== 11) {
return scheme.singularNominative.replace('{{count}}', String(count))
// 2, 3, 4, 22, 23, 24, 32 ...
} else if (rem10 >= 2 && rem10 <= 4 && (rem100 < 10 || rem100 > 20)) {
return scheme.singularGenitive.replace('{{count}}', String(count))
// 5, 6, 7, 8, 9, 10, 11, ...
} else {
return scheme.pluralGenitive.replace('{{count}}', String(count))
}
} | interface DeclensionScheme {
one?: string
singularNominative: string
singularGenitive: string
pluralGenitive: string
} |
1,123 | function renderChangelog(changelog: ChangelogVersion) {
let markdown = `## ${renderVersion(changelog.version)} - ${format(
Date.now(),
'yyyy-MM-dd'
)}
${sample(thanksOptions)!(renderAuthors(changelog.authors))}`
if (changelog.fixed.length)
markdown += `
### Fixed
${changelog.fixed.map(renderItem).join('\n\n')}`
if (changelog.changed.length)
markdown += `
### Changed
${changelog.changed.map(renderItem).join('\n\n')}`
if (changelog.added.length)
markdown += `
### Added
${changelog.added.map(renderItem).join('\n\n')}`
return markdown
} | interface ChangelogVersion {
version: Version
changed: ChangelogItem[]
fixed: ChangelogItem[]
added: ChangelogItem[]
authors: Author[]
} |
1,124 | function renderVersion({ major, minor, patch }: Version) {
return `v${major}.${minor}.${patch}`
} | interface Version {
major: number
minor: number
patch: number
} |
1,125 | function renderAuthor(author: Author) {
return `@${author.login}`
} | interface Author {
login: string
name: string
email: string
} |
1,126 | function renderItem(item: ChangelogItem) {
const message = item.pr
? `[${item.message}](https://github.com/date-fns/date-fns/pull/${item.pr})`
: item.message
const issues = item.issues
? ` (${item.issues
.map((i) => `[#${i}](https://github.com/date-fns/date-fns/issues/${i})`)
.join(', ')})`
: ''
return `- ${message}${issues}`
} | interface ChangelogItem {
type: ChangelogType
author: Author
message: string
pr?: number
issues?: number[]
breaking: boolean
} |
1,127 | (doc: DocFn) => doc.kind === 'function' && doc.isFPFn | interface DocFn {
kind: string
isFPFn: boolean
title: string
generatedFrom: string
args: {
length: number
}
} |
1,128 | async function buildFPFn({
title,
generatedFrom,
args: { length },
}: DocFn): Promise<void> {
const source = getFPFn(generatedFrom, length)
const dir = `./src/fp/${title}`
if (!existsSync(dir)) await mkdir(dir)
writeFile(`${dir}/index.ts`, source)
// remove legacy index.js (if any)
const jsPath = `${dir}/index.js`
if (existsSync(jsPath)) unlink(jsPath)
} | interface DocFn {
kind: string
isFPFn: boolean
title: string
generatedFrom: string
args: {
length: number
}
} |
1,129 | constructor(options?: Options) | interface Options extends ReadableOptions {
writable?: boolean;
readable?: boolean;
dataSize?: number;
maxDataSize?: number;
pauseStreams?: boolean;
} |
1,130 | fn(parser: SaxesParser): void {
Object.assign(parser.ENTITIES, ENTITIES);
parser.write(`${xmlStart}/>`).close();
} | class SaxesParser<O extends SaxesOptions = {}> {
private readonly fragmentOpt: boolean;
private readonly xmlnsOpt: boolean;
private readonly trackPosition: boolean;
private readonly fileName?: string;
private readonly nameStartCheck: (c: number) => boolean;
private readonly nameCheck: (c: number) => boolean;
private readonly isName: (name: string) => boolean;
private readonly ns!: Record<string, string>;
private openWakaBang!: string;
private text!: string;
private name!: string;
private piTarget!: string;
private entity!: string;
private q!: null | number;
private tags!: SaxesTagIncomplete[];
private tag!: SaxesTagIncomplete | null;
private topNS!: Record<string, string> | null;
private chunk!: string;
private chunkPosition!: number;
private i!: number;
//
// We use prevI to allow "ungetting" the previously read code point. Note
// however, that it is not safe to unget everything and anything. In
// particular ungetting EOL characters will screw positioning up.
//
// Practically, you must not unget a code which has any side effect beyond
// updating ``this.i`` and ``this.prevI``. Only EOL codes have such side
// effects.
//
private prevI!: number;
private carriedFromPrevious?: string;
private forbiddenState!: number;
private attribList!: (SaxesAttributeNSIncomplete | SaxesAttributePlain)[];
private state!: number;
private reportedTextBeforeRoot!: boolean;
private reportedTextAfterRoot!: boolean;
private closedRoot!: boolean;
private sawRoot!: boolean;
private xmlDeclPossible!: boolean;
private xmlDeclExpects!: string[];
private entityReturnState?: number;
private processAttribs!: (this: this) => void;
private positionAtNewLine!: number;
private doctype!: boolean;
private getCode!: () => number;
private isChar!: (c: number) => boolean;
private pushAttrib!: (name: string, value: string) => void;
private _closed!: boolean;
private currentXMLVersion!: string;
private readonly stateTable: ((this: SaxesParser<O>) => void)[];
private xmldeclHandler?: XMLDeclHandler;
private textHandler?: TextHandler;
private piHandler?: PIHandler;
private doctypeHandler?: DoctypeHandler;
private commentHandler?: CommentHandler;
private openTagStartHandler?: OpenTagStartHandler<O>;
private openTagHandler?: OpenTagHandler<O>;
private closeTagHandler?: CloseTagHandler<O>;
private cdataHandler?: CDataHandler;
private errorHandler?: ErrorHandler;
private endHandler?: EndHandler;
private readyHandler?: ReadyHandler;
private attributeHandler?: AttributeHandler<O>;
/**
* Indicates whether or not the parser is closed. If ``true``, wait for
* the ``ready`` event to write again.
*/
get closed(): boolean {
return this._closed;
}
readonly opt: SaxesOptions;
/**
* The XML declaration for this document.
*/
xmlDecl!: XMLDecl;
/**
* The line number of the next character to be read by the parser. This field
* is one-based. (The first line is numbered 1.)
*/
line!: number;
/**
* The column number of the next character to be read by the parser. *
* This field is zero-based. (The first column is 0.)
*
* This field counts columns by *Unicode character*. Note that this *can*
* be different from the index of the character in a JavaScript string due
* to how JavaScript handles astral plane characters.
*
* See [[columnIndex]] for a number that corresponds to the JavaScript index.
*/
column!: number;
/**
* A map of entity name to expansion.
*/
ENTITIES!: Record<string, string>;
/**
* @param opt The parser options.
*/
constructor(opt?: O) {
this.opt = opt ?? {};
this.fragmentOpt = !!(this.opt.fragment as boolean);
const xmlnsOpt = this.xmlnsOpt = !!(this.opt.xmlns as boolean);
this.trackPosition = this.opt.position !== false;
this.fileName = this.opt.fileName;
if (xmlnsOpt) {
// This is the function we use to perform name checks on PIs and entities.
// When namespaces are used, colons are not allowed in PI target names or
// entity names. So the check depends on whether namespaces are used. See:
//
// https://www.w3.org/XML/xml-names-19990114-errata.html
// NE08
//
this.nameStartCheck = isNCNameStartChar;
this.nameCheck = isNCNameChar;
this.isName = isNCName;
// eslint-disable-next-line @typescript-eslint/unbound-method
this.processAttribs = this.processAttribsNS;
// eslint-disable-next-line @typescript-eslint/unbound-method
this.pushAttrib = this.pushAttribNS;
// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-assignment
this.ns = { __proto__: null as any, ...rootNS };
const additional = this.opt.additionalNamespaces;
if (additional != null) {
nsMappingCheck(this, additional);
Object.assign(this.ns, additional);
}
}
else {
this.nameStartCheck = isNameStartChar;
this.nameCheck = isNameChar;
this.isName = isName;
// eslint-disable-next-line @typescript-eslint/unbound-method
this.processAttribs = this.processAttribsPlain;
// eslint-disable-next-line @typescript-eslint/unbound-method
this.pushAttrib = this.pushAttribPlain;
}
//
// The order of the members in this table needs to correspond to the state
// numbers given to the states that correspond to the methods being recorded
// here.
//
this.stateTable = [
/* eslint-disable @typescript-eslint/unbound-method */
this.sBegin,
this.sBeginWhitespace,
this.sDoctype,
this.sDoctypeQuote,
this.sDTD,
this.sDTDQuoted,
this.sDTDOpenWaka,
this.sDTDOpenWakaBang,
this.sDTDComment,
this.sDTDCommentEnding,
this.sDTDCommentEnded,
this.sDTDPI,
this.sDTDPIEnding,
this.sText,
this.sEntity,
this.sOpenWaka,
this.sOpenWakaBang,
this.sComment,
this.sCommentEnding,
this.sCommentEnded,
this.sCData,
this.sCDataEnding,
this.sCDataEnding2,
this.sPIFirstChar,
this.sPIRest,
this.sPIBody,
this.sPIEnding,
this.sXMLDeclNameStart,
this.sXMLDeclName,
this.sXMLDeclEq,
this.sXMLDeclValueStart,
this.sXMLDeclValue,
this.sXMLDeclSeparator,
this.sXMLDeclEnding,
this.sOpenTag,
this.sOpenTagSlash,
this.sAttrib,
this.sAttribName,
this.sAttribNameSawWhite,
this.sAttribValue,
this.sAttribValueQuoted,
this.sAttribValueClosed,
this.sAttribValueUnquoted,
this.sCloseTag,
this.sCloseTagSawWhite,
/* eslint-enable @typescript-eslint/unbound-method */
];
this._init();
}
_init(): void {
this.openWakaBang = "";
this.text = "";
this.name = "";
this.piTarget = "";
this.entity = "";
this.q = null;
this.tags = [];
this.tag = null;
this.topNS = null;
this.chunk = "";
this.chunkPosition = 0;
this.i = 0;
this.prevI = 0;
this.carriedFromPrevious = undefined;
this.forbiddenState = FORBIDDEN_START;
this.attribList = [];
// The logic is organized so as to minimize the need to check
// this.opt.fragment while parsing.
const { fragmentOpt } = this;
this.state = fragmentOpt ? S_TEXT : S_BEGIN;
// We want these to be all true if we are dealing with a fragment.
this.reportedTextBeforeRoot = this.reportedTextAfterRoot = this.closedRoot =
this.sawRoot = fragmentOpt;
// An XML declaration is intially possible only when parsing whole
// documents.
this.xmlDeclPossible = !fragmentOpt;
this.xmlDeclExpects = ["version"];
this.entityReturnState = undefined;
let { defaultXMLVersion } = this.opt;
if (defaultXMLVersion === undefined) {
if (this.opt.forceXMLVersion === true) {
throw new Error("forceXMLVersion set but defaultXMLVersion is not set");
}
defaultXMLVersion = "1.0";
}
this.setXMLVersion(defaultXMLVersion);
this.positionAtNewLine = 0;
this.doctype = false;
this._closed = false;
this.xmlDecl = {
version: undefined,
encoding: undefined,
standalone: undefined,
};
this.line = 1;
this.column = 0;
this.ENTITIES = Object.create(XML_ENTITIES) as Record<string, string>;
this.readyHandler?.();
}
/**
* The stream position the parser is currently looking at. This field is
* zero-based.
*
* This field is not based on counting Unicode characters but is to be
* interpreted as a plain index into a JavaScript string.
*/
get position(): number {
return this.chunkPosition + this.i;
}
/**
* The column number of the next character to be read by the parser. *
* This field is zero-based. (The first column in a line is 0.)
*
* This field reports the index at which the next character would be in the
* line if the line were represented as a JavaScript string. Note that this
* *can* be different to a count based on the number of *Unicode characters*
* due to how JavaScript handles astral plane characters.
*
* See [[column]] for a number that corresponds to a count of Unicode
* characters.
*/
get columnIndex(): number {
return this.position - this.positionAtNewLine;
}
/**
* Set an event listener on an event. The parser supports one handler per
* event type. If you try to set an event handler over an existing handler,
* the old handler is silently overwritten.
*
* @param name The event to listen to.
*
* @param handler The handler to set.
*/
on<N extends EventName>(name: N, handler: EventNameToHandler<O, N>): void {
// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-member-access
(this as any)[EVENT_NAME_TO_HANDLER_NAME[name]] = handler;
}
/**
* Unset an event handler.
*
* @parma name The event to stop listening to.
*/
off(name: EventName): void {
// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-member-access
(this as any)[EVENT_NAME_TO_HANDLER_NAME[name]] = undefined;
}
/**
* Make an error object. The error object will have a message that contains
* the ``fileName`` option passed at the creation of the parser. If position
* tracking was turned on, it will also have line and column number
* information.
*
* @param message The message describing the error to report.
*
* @returns An error object with a properly formatted message.
*/
makeError(message: string): Error {
let msg = this.fileName ?? "";
if (this.trackPosition) {
if (msg.length > 0) {
msg += ":";
}
msg += `${this.line}:${this.column}`;
}
if (msg.length > 0) {
msg += ": ";
}
return new Error(msg + message);
}
/**
* Report a parsing error. This method is made public so that client code may
* check for issues that are outside the scope of this project and can report
* errors.
*
* @param message The error to report.
*
* @returns this
*/
fail(message: string): this {
const err = this.makeError(message);
const handler = this.errorHandler;
if (handler === undefined) {
throw err;
}
else {
handler(err);
}
return this;
}
/**
* Write a XML data to the parser.
*
* @param chunk The XML data to write.
*
* @returns this
*/
// We do need object for the type here. Yes, it often causes problems
// but not in this case.
write(chunk: string | object | null): this {
if (this.closed) {
return this.fail("cannot write after close; assign an onready handler.");
}
let end = false;
if (chunk === null) {
// We cannot return immediately because carriedFromPrevious may need
// processing.
end = true;
chunk = "";
}
else if (typeof chunk === "object") {
chunk = chunk.toString();
}
// We checked if performing a pre-decomposition of the string into an array
// of single complete characters (``Array.from(chunk)``) would be faster
// than the current repeated calls to ``charCodeAt``. As of August 2018, it
// isn't. (There may be Node-specific code that would perform faster than
// ``Array.from`` but don't want to be dependent on Node.)
if (this.carriedFromPrevious !== undefined) {
// The previous chunk had char we must carry over.
chunk = `${this.carriedFromPrevious}${chunk}`;
this.carriedFromPrevious = undefined;
}
let limit = chunk.length;
const lastCode = chunk.charCodeAt(limit - 1);
if (!end &&
// A trailing CR or surrogate must be carried over to the next
// chunk.
(lastCode === CR || (lastCode >= 0xD800 && lastCode <= 0xDBFF))) {
// The chunk ends with a character that must be carried over. We cannot
// know how to handle it until we get the next chunk or the end of the
// stream. So save it for later.
this.carriedFromPrevious = chunk[limit - 1];
limit--;
chunk = chunk.slice(0, limit);
}
const { stateTable } = this;
this.chunk = chunk;
this.i = 0;
while (this.i < limit) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-argument
stateTable[this.state].call(this as any);
}
this.chunkPosition += limit;
return end ? this.end() : this;
}
/**
* Close the current stream. Perform final well-formedness checks and reset
* the parser tstate.
*
* @returns this
*/
close(): this {
return this.write(null);
}
/**
* Get a single code point out of the current chunk. This updates the current
* position if we do position tracking.
*
* This is the algorithm to use for XML 1.0.
*
* @returns The character read.
*/
private getCode10(): number {
const { chunk, i } = this;
this.prevI = i;
// Yes, we do this instead of doing this.i++. Doing it this way, we do not
// read this.i again, which is a bit faster.
this.i = i + 1;
if (i >= chunk.length) {
return EOC;
}
// Using charCodeAt and handling the surrogates ourselves is faster
// than using codePointAt.
const code = chunk.charCodeAt(i);
this.column++;
if (code < 0xD800) {
if (code >= SPACE || code === TAB) {
return code;
}
switch (code) {
case NL:
this.line++;
this.column = 0;
this.positionAtNewLine = this.position;
return NL;
case CR:
// We may get NaN if we read past the end of the chunk, which is fine.
if (chunk.charCodeAt(i + 1) === NL) {
// A \r\n sequence is converted to \n so we have to skip over the
// next character. We already know it has a size of 1 so ++ is fine
// here.
this.i = i + 2;
}
// Otherwise, a \r is just converted to \n, so we don't have to skip
// ahead.
// In either case, \r becomes \n.
this.line++;
this.column = 0;
this.positionAtNewLine = this.position;
return NL_LIKE;
default:
// If we get here, then code < SPACE and it is not NL CR or TAB.
this.fail("disallowed character.");
return code;
}
}
if (code > 0xDBFF) {
// This is a specialized version of isChar10 that takes into account
// that in this context code > 0xDBFF and code <= 0xFFFF. So it does not
// test cases that don't need testing.
if (!(code >= 0xE000 && code <= 0xFFFD)) {
this.fail("disallowed character.");
}
return code;
}
const final = 0x10000 + ((code - 0xD800) * 0x400) +
(chunk.charCodeAt(i + 1) - 0xDC00);
this.i = i + 2;
// This is a specialized version of isChar10 that takes into account that in
// this context necessarily final >= 0x10000.
if (final > 0x10FFFF) {
this.fail("disallowed character.");
}
return final;
}
/**
* Get a single code point out of the current chunk. This updates the current
* position if we do position tracking.
*
* This is the algorithm to use for XML 1.1.
*
* @returns {number} The character read.
*/
private getCode11(): number {
const { chunk, i } = this;
this.prevI = i;
// Yes, we do this instead of doing this.i++. Doing it this way, we do not
// read this.i again, which is a bit faster.
this.i = i + 1;
if (i >= chunk.length) {
return EOC;
}
// Using charCodeAt and handling the surrogates ourselves is faster
// than using codePointAt.
const code = chunk.charCodeAt(i);
this.column++;
if (code < 0xD800) {
if ((code > 0x1F && code < 0x7F) || (code > 0x9F && code !== LS) ||
code === TAB) {
return code;
}
switch (code) {
case NL: // 0xA
this.line++;
this.column = 0;
this.positionAtNewLine = this.position;
return NL;
case CR: { // 0xD
// We may get NaN if we read past the end of the chunk, which is
// fine.
const next = chunk.charCodeAt(i + 1);
if (next === NL || next === NEL) {
// A CR NL or CR NEL sequence is converted to NL so we have to skip
// over the next character. We already know it has a size of 1.
this.i = i + 2;
}
// Otherwise, a CR is just converted to NL, no skip.
}
/* yes, fall through */
case NEL: // 0x85
case LS: // Ox2028
this.line++;
this.column = 0;
this.positionAtNewLine = this.position;
return NL_LIKE;
default:
this.fail("disallowed character.");
return code;
}
}
if (code > 0xDBFF) {
// This is a specialized version of isCharAndNotRestricted that takes into
// account that in this context code > 0xDBFF and code <= 0xFFFF. So it
// does not test cases that don't need testing.
if (!(code >= 0xE000 && code <= 0xFFFD)) {
this.fail("disallowed character.");
}
return code;
}
const final = 0x10000 + ((code - 0xD800) * 0x400) +
(chunk.charCodeAt(i + 1) - 0xDC00);
this.i = i + 2;
// This is a specialized version of isCharAndNotRestricted that takes into
// account that in this context necessarily final >= 0x10000.
if (final > 0x10FFFF) {
this.fail("disallowed character.");
}
return final;
}
/**
* Like ``getCode`` but with the return value normalized so that ``NL`` is
* returned for ``NL_LIKE``.
*/
private getCodeNorm(): number {
const c = this.getCode();
return c === NL_LIKE ? NL : c;
}
private unget(): void {
this.i = this.prevI;
this.column--;
}
/**
* Capture characters into a buffer until encountering one of a set of
* characters.
*
* @param chars An array of codepoints. Encountering a character in the array
* ends the capture. (``chars`` may safely contain ``NL``.)
*
* @return The character code that made the capture end, or ``EOC`` if we hit
* the end of the chunk. The return value cannot be NL_LIKE: NL is returned
* instead.
*/
private captureTo(chars: number[]): number {
let { i: start } = this;
const { chunk } = this;
// eslint-disable-next-line no-constant-condition
while (true) {
const c = this.getCode();
const isNLLike = c === NL_LIKE;
const final = isNLLike ? NL : c;
if (final === EOC || chars.includes(final)) {
this.text += chunk.slice(start, this.prevI);
return final;
}
if (isNLLike) {
this.text += `${chunk.slice(start, this.prevI)}\n`;
start = this.i;
}
}
}
/**
* Capture characters into a buffer until encountering a character.
*
* @param char The codepoint that ends the capture. **NOTE ``char`` MAY NOT
* CONTAIN ``NL``.** Passing ``NL`` will result in buggy behavior.
*
* @return ``true`` if we ran into the character. Otherwise, we ran into the
* end of the current chunk.
*/
private captureToChar(char: number): boolean {
let { i: start } = this;
const { chunk } = this;
// eslint-disable-next-line no-constant-condition
while (true) {
let c = this.getCode();
switch (c) {
case NL_LIKE:
this.text += `${chunk.slice(start, this.prevI)}\n`;
start = this.i;
c = NL;
break;
case EOC:
this.text += chunk.slice(start);
return false;
default:
}
if (c === char) {
this.text += chunk.slice(start, this.prevI);
return true;
}
}
}
/**
* Capture characters that satisfy ``isNameChar`` into the ``name`` field of
* this parser.
*
* @return The character code that made the test fail, or ``EOC`` if we hit
* the end of the chunk. The return value cannot be NL_LIKE: NL is returned
* instead.
*/
private captureNameChars(): number {
const { chunk, i: start } = this;
// eslint-disable-next-line no-constant-condition
while (true) {
const c = this.getCode();
if (c === EOC) {
this.name += chunk.slice(start);
return EOC;
}
// NL is not a name char so we don't have to test specifically for it.
if (!isNameChar(c)) {
this.name += chunk.slice(start, this.prevI);
return c === NL_LIKE ? NL : c;
}
}
}
/**
* Skip white spaces.
*
* @return The character that ended the skip, or ``EOC`` if we hit
* the end of the chunk. The return value cannot be NL_LIKE: NL is returned
* instead.
*/
private skipSpaces(): number {
// eslint-disable-next-line no-constant-condition
while (true) {
const c = this.getCodeNorm();
if (c === EOC || !isS(c)) {
return c;
}
}
}
private setXMLVersion(version: string): void {
this.currentXMLVersion = version;
/* eslint-disable @typescript-eslint/unbound-method */
if (version === "1.0") {
this.isChar = isChar10;
this.getCode = this.getCode10;
}
else {
this.isChar = isChar11;
this.getCode = this.getCode11;
}
/* eslint-enable @typescript-eslint/unbound-method */
}
// STATE ENGINE METHODS
// This needs to be a state separate from S_BEGIN_WHITESPACE because we want
// to be sure never to come back to this state later.
private sBegin(): void {
// We are essentially peeking at the first character of the chunk. Since
// S_BEGIN can be in effect only when we start working on the first chunk,
// the index at which we must look is necessarily 0. Note also that the
// following test does not depend on decoding surrogates.
// If the initial character is 0xFEFF, ignore it.
if (this.chunk.charCodeAt(0) === 0xFEFF) {
this.i++;
this.column++;
}
this.state = S_BEGIN_WHITESPACE;
}
private sBeginWhitespace(): void {
// We need to know whether we've encountered spaces or not because as soon
// as we run into a space, an XML declaration is no longer possible. Rather
// than slow down skipSpaces even in places where we don't care whether it
// skipped anything or not, we check whether prevI is equal to the value of
// i from before we skip spaces.
const iBefore = this.i;
const c = this.skipSpaces();
if (this.prevI !== iBefore) {
this.xmlDeclPossible = false;
}
switch (c) {
case LESS:
this.state = S_OPEN_WAKA;
// We could naively call closeText but in this state, it is not normal
// to have text be filled with any data.
if (this.text.length !== 0) {
throw new Error("no-empty text at start");
}
break;
case EOC:
break;
default:
this.unget();
this.state = S_TEXT;
this.xmlDeclPossible = false;
}
}
private sDoctype(): void {
const c = this.captureTo(DOCTYPE_TERMINATOR);
switch (c) {
case GREATER: {
this.doctypeHandler?.(this.text);
this.text = "";
this.state = S_TEXT;
this.doctype = true; // just remember that we saw it.
break;
}
case EOC:
break;
default:
this.text += String.fromCodePoint(c);
if (c === OPEN_BRACKET) {
this.state = S_DTD;
}
else if (isQuote(c)) {
this.state = S_DOCTYPE_QUOTE;
this.q = c;
}
}
}
private sDoctypeQuote(): void {
const q = this.q!;
if (this.captureToChar(q)) {
this.text += String.fromCodePoint(q);
this.q = null;
this.state = S_DOCTYPE;
}
}
private sDTD(): void {
const c = this.captureTo(DTD_TERMINATOR);
if (c === EOC) {
return;
}
this.text += String.fromCodePoint(c);
if (c === CLOSE_BRACKET) {
this.state = S_DOCTYPE;
}
else if (c === LESS) {
this.state = S_DTD_OPEN_WAKA;
}
else if (isQuote(c)) {
this.state = S_DTD_QUOTED;
this.q = c;
}
}
private sDTDQuoted(): void {
const q = this.q!;
if (this.captureToChar(q)) {
this.text += String.fromCodePoint(q);
this.state = S_DTD;
this.q = null;
}
}
private sDTDOpenWaka(): void {
const c = this.getCodeNorm();
this.text += String.fromCodePoint(c);
switch (c) {
case BANG:
this.state = S_DTD_OPEN_WAKA_BANG;
this.openWakaBang = "";
break;
case QUESTION:
this.state = S_DTD_PI;
break;
default:
this.state = S_DTD;
}
}
private sDTDOpenWakaBang(): void {
const char = String.fromCodePoint(this.getCodeNorm());
const owb = this.openWakaBang += char;
this.text += char;
if (owb !== "-") {
this.state = owb === "--" ? S_DTD_COMMENT : S_DTD;
this.openWakaBang = "";
}
}
private sDTDComment(): void {
if (this.captureToChar(MINUS)) {
this.text += "-";
this.state = S_DTD_COMMENT_ENDING;
}
}
private sDTDCommentEnding(): void {
const c = this.getCodeNorm();
this.text += String.fromCodePoint(c);
this.state = c === MINUS ? S_DTD_COMMENT_ENDED : S_DTD_COMMENT;
}
private sDTDCommentEnded(): void {
const c = this.getCodeNorm();
this.text += String.fromCodePoint(c);
if (c === GREATER) {
this.state = S_DTD;
}
else {
this.fail("malformed comment.");
// <!-- blah -- bloo --> will be recorded as
// a comment of " blah -- bloo "
this.state = S_DTD_COMMENT;
}
}
private sDTDPI(): void {
if (this.captureToChar(QUESTION)) {
this.text += "?";
this.state = S_DTD_PI_ENDING;
}
}
private sDTDPIEnding(): void {
const c = this.getCodeNorm();
this.text += String.fromCodePoint(c);
if (c === GREATER) {
this.state = S_DTD;
}
}
private sText(): void {
//
// We did try a version of saxes where the S_TEXT state was split in two
// states: one for text inside the root element, and one for text
// outside. This was avoiding having to test this.tags.length to decide
// what implementation to actually use.
//
// Peformance testing on gigabyte-size files did not show any advantage to
// using the two states solution instead of the current one. Conversely, it
// made the code a bit more complicated elsewhere. For instance, a comment
// can appear before the root element so when a comment ended it was
// necessary to determine whether to return to the S_TEXT state or to the
// new text-outside-root state.
//
if (this.tags.length !== 0) {
this.handleTextInRoot();
}
else {
this.handleTextOutsideRoot();
}
}
private sEntity(): void {
// This is essentially a specialized version of captureToChar(SEMICOLON...)
let { i: start } = this;
const { chunk } = this;
// eslint-disable-next-line no-labels, no-restricted-syntax
loop:
// eslint-disable-next-line no-constant-condition
while (true) {
switch (this.getCode()) {
case NL_LIKE:
this.entity += `${chunk.slice(start, this.prevI)}\n`;
start = this.i;
break;
case SEMICOLON: {
const { entityReturnState } = this;
const entity = this.entity + chunk.slice(start, this.prevI);
this.state = entityReturnState!;
let parsed: string;
if (entity === "") {
this.fail("empty entity name.");
parsed = "&;";
}
else {
parsed = this.parseEntity(entity);
this.entity = "";
}
if (entityReturnState !== S_TEXT || this.textHandler !== undefined) {
this.text += parsed;
}
// eslint-disable-next-line no-labels
break loop;
}
case EOC:
this.entity += chunk.slice(start);
// eslint-disable-next-line no-labels
break loop;
default:
}
}
}
private sOpenWaka(): void {
// Reminder: a state handler is called with at least one character
// available in the current chunk. So the first call to get code inside of
// a state handler cannot return ``EOC``. That's why we don't test
// for it.
const c = this.getCode();
// either a /, ?, !, or text is coming next.
if (isNameStartChar(c)) {
this.state = S_OPEN_TAG;
this.unget();
this.xmlDeclPossible = false;
}
else {
switch (c) {
case FORWARD_SLASH:
this.state = S_CLOSE_TAG;
this.xmlDeclPossible = false;
break;
case BANG:
this.state = S_OPEN_WAKA_BANG;
this.openWakaBang = "";
this.xmlDeclPossible = false;
break;
case QUESTION:
this.state = S_PI_FIRST_CHAR;
break;
default:
this.fail("disallowed character in tag name");
this.state = S_TEXT;
this.xmlDeclPossible = false;
}
}
}
private sOpenWakaBang(): void {
this.openWakaBang += String.fromCodePoint(this.getCodeNorm());
switch (this.openWakaBang) {
case "[CDATA[":
if (!this.sawRoot && !this.reportedTextBeforeRoot) {
this.fail("text data outside of root node.");
this.reportedTextBeforeRoot = true;
}
if (this.closedRoot && !this.reportedTextAfterRoot) {
this.fail("text data outside of root node.");
this.reportedTextAfterRoot = true;
}
this.state = S_CDATA;
this.openWakaBang = "";
break;
case "--":
this.state = S_COMMENT;
this.openWakaBang = "";
break;
case "DOCTYPE":
this.state = S_DOCTYPE;
if (this.doctype || this.sawRoot) {
this.fail("inappropriately located doctype declaration.");
}
this.openWakaBang = "";
break;
default:
// 7 happens to be the maximum length of the string that can possibly
// match one of the cases above.
if (this.openWakaBang.length >= 7) {
this.fail("incorrect syntax.");
}
}
}
private sComment(): void {
if (this.captureToChar(MINUS)) {
this.state = S_COMMENT_ENDING;
}
}
private sCommentEnding(): void {
const c = this.getCodeNorm();
if (c === MINUS) {
this.state = S_COMMENT_ENDED;
this.commentHandler?.(this.text);
this.text = "";
}
else {
this.text += `-${String.fromCodePoint(c)}`;
this.state = S_COMMENT;
}
}
private sCommentEnded(): void {
const c = this.getCodeNorm();
if (c !== GREATER) {
this.fail("malformed comment.");
// <!-- blah -- bloo --> will be recorded as
// a comment of " blah -- bloo "
this.text += `--${String.fromCodePoint(c)}`;
this.state = S_COMMENT;
}
else {
this.state = S_TEXT;
}
}
private sCData(): void {
if (this.captureToChar(CLOSE_BRACKET)) {
this.state = S_CDATA_ENDING;
}
}
private sCDataEnding(): void {
const c = this.getCodeNorm();
if (c === CLOSE_BRACKET) {
this.state = S_CDATA_ENDING_2;
}
else {
this.text += `]${String.fromCodePoint(c)}`;
this.state = S_CDATA;
}
}
private sCDataEnding2(): void {
const c = this.getCodeNorm();
switch (c) {
case GREATER: {
this.cdataHandler?.(this.text);
this.text = "";
this.state = S_TEXT;
break;
}
case CLOSE_BRACKET:
this.text += "]";
break;
default:
this.text += `]]${String.fromCodePoint(c)}`;
this.state = S_CDATA;
}
}
// We need this separate state to check the first character fo the pi target
// with this.nameStartCheck which allows less characters than this.nameCheck.
private sPIFirstChar(): void {
const c = this.getCodeNorm();
// This is first because in the case where the file is well-formed this is
// the branch taken. We optimize for well-formedness.
if (this.nameStartCheck(c)) {
this.piTarget += String.fromCodePoint(c);
this.state = S_PI_REST;
}
else if (c === QUESTION || isS(c)) {
this.fail("processing instruction without a target.");
this.state = c === QUESTION ? S_PI_ENDING : S_PI_BODY;
}
else {
this.fail("disallowed character in processing instruction name.");
this.piTarget += String.fromCodePoint(c);
this.state = S_PI_REST;
}
}
private sPIRest(): void {
// Capture characters into a piTarget while ``this.nameCheck`` run on the
// character read returns true.
const { chunk, i: start } = this;
// eslint-disable-next-line no-constant-condition
while (true) {
const c = this.getCodeNorm();
if (c === EOC) {
this.piTarget += chunk.slice(start);
return;
}
// NL cannot satisfy this.nameCheck so we don't have to test specifically
// for it.
if (!this.nameCheck(c)) {
this.piTarget += chunk.slice(start, this.prevI);
const isQuestion = c === QUESTION;
if (isQuestion || isS(c)) {
if (this.piTarget === "xml") {
if (!this.xmlDeclPossible) {
this.fail(
"an XML declaration must be at the start of the document.");
}
this.state = isQuestion ? S_XML_DECL_ENDING : S_XML_DECL_NAME_START;
}
else {
this.state = isQuestion ? S_PI_ENDING : S_PI_BODY;
}
}
else {
this.fail("disallowed character in processing instruction name.");
this.piTarget += String.fromCodePoint(c);
}
break;
}
}
}
private sPIBody(): void {
if (this.text.length === 0) {
const c = this.getCodeNorm();
if (c === QUESTION) {
this.state = S_PI_ENDING;
}
else if (!isS(c)) {
this.text = String.fromCodePoint(c);
}
}
// The question mark character is not valid inside any of the XML
// declaration name/value pairs.
else if (this.captureToChar(QUESTION)) {
this.state = S_PI_ENDING;
}
}
private sPIEnding(): void {
const c = this.getCodeNorm();
if (c === GREATER) {
const { piTarget } = this;
if (piTarget.toLowerCase() === "xml") {
this.fail(
"the XML declaration must appear at the start of the document.");
}
this.piHandler?.({
target: piTarget,
body: this.text,
});
this.piTarget = this.text = "";
this.state = S_TEXT;
}
else if (c === QUESTION) {
// We ran into ?? as part of a processing instruction. We initially took
// the first ? as a sign that the PI was ending, but it is not. So we have
// to add it to the body but we take the new ? as a sign that the PI is
// ending.
this.text += "?";
}
else {
this.text += `?${String.fromCodePoint(c)}`;
this.state = S_PI_BODY;
}
this.xmlDeclPossible = false;
}
private sXMLDeclNameStart(): void {
const c = this.skipSpaces();
// The question mark character is not valid inside any of the XML
// declaration name/value pairs.
if (c === QUESTION) {
// It is valid to go to S_XML_DECL_ENDING from this state.
this.state = S_XML_DECL_ENDING;
return;
}
if (c !== EOC) {
this.state = S_XML_DECL_NAME;
this.name = String.fromCodePoint(c);
}
}
private sXMLDeclName(): void {
const c = this.captureTo(XML_DECL_NAME_TERMINATOR);
// The question mark character is not valid inside any of the XML
// declaration name/value pairs.
if (c === QUESTION) {
this.state = S_XML_DECL_ENDING;
this.name += this.text;
this.text = "";
this.fail("XML declaration is incomplete.");
return;
}
if (!(isS(c) || c === EQUAL)) {
return;
}
this.name += this.text;
this.text = "";
if (!this.xmlDeclExpects.includes(this.name)) {
switch (this.name.length) {
case 0:
this.fail("did not expect any more name/value pairs.");
break;
case 1:
this.fail(`expected the name ${this.xmlDeclExpects[0]}.`);
break;
default:
this.fail(`expected one of ${this.xmlDeclExpects.join(", ")}`);
}
}
this.state = c === EQUAL ? S_XML_DECL_VALUE_START : S_XML_DECL_EQ;
}
private sXMLDeclEq(): void {
const c = this.getCodeNorm();
// The question mark character is not valid inside any of the XML
// declaration name/value pairs.
if (c === QUESTION) {
this.state = S_XML_DECL_ENDING;
this.fail("XML declaration is incomplete.");
return;
}
if (isS(c)) {
return;
}
if (c !== EQUAL) {
this.fail("value required.");
}
this.state = S_XML_DECL_VALUE_START;
}
private sXMLDeclValueStart(): void {
const c = this.getCodeNorm();
// The question mark character is not valid inside any of the XML
// declaration name/value pairs.
if (c === QUESTION) {
this.state = S_XML_DECL_ENDING;
this.fail("XML declaration is incomplete.");
return;
}
if (isS(c)) {
return;
}
if (!isQuote(c)) {
this.fail("value must be quoted.");
this.q = SPACE;
}
else {
this.q = c;
}
this.state = S_XML_DECL_VALUE;
}
private sXMLDeclValue(): void {
const c = this.captureTo([this.q!, QUESTION]);
// The question mark character is not valid inside any of the XML
// declaration name/value pairs.
if (c === QUESTION) {
this.state = S_XML_DECL_ENDING;
this.text = "";
this.fail("XML declaration is incomplete.");
return;
}
if (c === EOC) {
return;
}
const value = this.text;
this.text = "";
switch (this.name) {
case "version": {
this.xmlDeclExpects = ["encoding", "standalone"];
const version = value;
this.xmlDecl.version = version;
// This is the test specified by XML 1.0 but it is fine for XML 1.1.
if (!/^1\.[0-9]+$/.test(version)) {
this.fail("version number must match /^1\\.[0-9]+$/.");
}
// When forceXMLVersion is set, the XML declaration is ignored.
else if (!(this.opt.forceXMLVersion as boolean)) {
this.setXMLVersion(version);
}
break;
}
case "encoding":
if (!/^[A-Za-z][A-Za-z0-9._-]*$/.test(value)) {
this.fail("encoding value must match \
/^[A-Za-z0-9][A-Za-z0-9._-]*$/.");
}
this.xmlDeclExpects = ["standalone"];
this.xmlDecl.encoding = value;
break;
case "standalone":
if (value !== "yes" && value !== "no") {
this.fail("standalone value must match \"yes\" or \"no\".");
}
this.xmlDeclExpects = [];
this.xmlDecl.standalone = value;
break;
default:
// We don't need to raise an error here since we've already raised one
// when checking what name was expected.
}
this.name = "";
this.state = S_XML_DECL_SEPARATOR;
}
private sXMLDeclSeparator(): void {
const c = this.getCodeNorm();
// The question mark character is not valid inside any of the XML
// declaration name/value pairs.
if (c === QUESTION) {
// It is valid to go to S_XML_DECL_ENDING from this state.
this.state = S_XML_DECL_ENDING;
return;
}
if (!isS(c)) {
this.fail("whitespace required.");
this.unget();
}
this.state = S_XML_DECL_NAME_START;
}
private sXMLDeclEnding(): void {
const c = this.getCodeNorm();
if (c === GREATER) {
if (this.piTarget !== "xml") {
this.fail("processing instructions are not allowed before root.");
}
else if (this.name !== "version" &&
this.xmlDeclExpects.includes("version")) {
this.fail("XML declaration must contain a version.");
}
this.xmldeclHandler?.(this.xmlDecl);
this.name = "";
this.piTarget = this.text = "";
this.state = S_TEXT;
}
else {
// We got here because the previous character was a ?, but the question
// mark character is not valid inside any of the XML declaration
// name/value pairs.
this.fail(
"The character ? is disallowed anywhere in XML declarations.");
}
this.xmlDeclPossible = false;
}
private sOpenTag(): void {
const c = this.captureNameChars();
if (c === EOC) {
return;
}
const tag: SaxesTagIncomplete = this.tag = {
name: this.name,
attributes: Object.create(null) as Record<string, string>,
};
this.name = "";
if (this.xmlnsOpt) {
this.topNS = tag.ns = Object.create(null) as Record<string, string>;
}
this.openTagStartHandler?.(tag as StartTagForOptions<O>);
this.sawRoot = true;
if (!this.fragmentOpt && this.closedRoot) {
this.fail("documents may contain only one root.");
}
switch (c) {
case GREATER:
this.openTag();
break;
case FORWARD_SLASH:
this.state = S_OPEN_TAG_SLASH;
break;
default:
if (!isS(c)) {
this.fail("disallowed character in tag name.");
}
this.state = S_ATTRIB;
}
}
private sOpenTagSlash(): void {
if (this.getCode() === GREATER) {
this.openSelfClosingTag();
}
else {
this.fail("forward-slash in opening tag not followed by >.");
this.state = S_ATTRIB;
}
}
private sAttrib(): void {
const c = this.skipSpaces();
if (c === EOC) {
return;
}
if (isNameStartChar(c)) {
this.unget();
this.state = S_ATTRIB_NAME;
}
else if (c === GREATER) {
this.openTag();
}
else if (c === FORWARD_SLASH) {
this.state = S_OPEN_TAG_SLASH;
}
else {
this.fail("disallowed character in attribute name.");
}
}
private sAttribName(): void {
const c = this.captureNameChars();
if (c === EQUAL) {
this.state = S_ATTRIB_VALUE;
}
else if (isS(c)) {
this.state = S_ATTRIB_NAME_SAW_WHITE;
}
else if (c === GREATER) {
this.fail("attribute without value.");
this.pushAttrib(this.name, this.name);
this.name = this.text = "";
this.openTag();
}
else if (c !== EOC) {
this.fail("disallowed character in attribute name.");
}
}
private sAttribNameSawWhite(): void {
const c = this.skipSpaces();
switch (c) {
case EOC:
return;
case EQUAL:
this.state = S_ATTRIB_VALUE;
break;
default:
this.fail("attribute without value.");
// Should we do this???
// this.tag.attributes[this.name] = "";
this.text = "";
this.name = "";
if (c === GREATER) {
this.openTag();
}
else if (isNameStartChar(c)) {
this.unget();
this.state = S_ATTRIB_NAME;
}
else {
this.fail("disallowed character in attribute name.");
this.state = S_ATTRIB;
}
}
}
private sAttribValue(): void {
const c = this.getCodeNorm();
if (isQuote(c)) {
this.q = c;
this.state = S_ATTRIB_VALUE_QUOTED;
}
else if (!isS(c)) {
this.fail("unquoted attribute value.");
this.state = S_ATTRIB_VALUE_UNQUOTED;
this.unget();
}
}
private sAttribValueQuoted(): void {
// We deliberately do not use captureTo here. The specialized code we use
// here is faster than using captureTo.
const { q, chunk } = this;
let { i: start } = this;
// eslint-disable-next-line no-constant-condition
while (true) {
switch (this.getCode()) {
case q:
this.pushAttrib(this.name,
this.text + chunk.slice(start, this.prevI));
this.name = this.text = "";
this.q = null;
this.state = S_ATTRIB_VALUE_CLOSED;
return;
case AMP:
this.text += chunk.slice(start, this.prevI);
this.state = S_ENTITY;
this.entityReturnState = S_ATTRIB_VALUE_QUOTED;
return;
case NL:
case NL_LIKE:
case TAB:
this.text += `${chunk.slice(start, this.prevI)} `;
start = this.i;
break;
case LESS:
this.text += chunk.slice(start, this.prevI);
this.fail("disallowed character.");
return;
case EOC:
this.text += chunk.slice(start);
return;
default:
}
}
}
private sAttribValueClosed(): void {
const c = this.getCodeNorm();
if (isS(c)) {
this.state = S_ATTRIB;
}
else if (c === GREATER) {
this.openTag();
}
else if (c === FORWARD_SLASH) {
this.state = S_OPEN_TAG_SLASH;
}
else if (isNameStartChar(c)) {
this.fail("no whitespace between attributes.");
this.unget();
this.state = S_ATTRIB_NAME;
}
else {
this.fail("disallowed character in attribute name.");
}
}
private sAttribValueUnquoted(): void {
// We don't do anything regarding EOL or space handling for unquoted
// attributes. We already have failed by the time we get here, and the
// contract that saxes upholds states that upon failure, it is not safe to
// rely on the data passed to event handlers (other than
// ``onerror``). Passing "bad" data is not a problem.
const c = this.captureTo(ATTRIB_VALUE_UNQUOTED_TERMINATOR);
switch (c) {
case AMP:
this.state = S_ENTITY;
this.entityReturnState = S_ATTRIB_VALUE_UNQUOTED;
break;
case LESS:
this.fail("disallowed character.");
break;
case EOC:
break;
default:
if (this.text.includes("]]>")) {
this.fail("the string \"]]>\" is disallowed in char data.");
}
this.pushAttrib(this.name, this.text);
this.name = this.text = "";
if (c === GREATER) {
this.openTag();
}
else {
this.state = S_ATTRIB;
}
}
}
private sCloseTag(): void {
const c = this.captureNameChars();
if (c === GREATER) {
this.closeTag();
}
else if (isS(c)) {
this.state = S_CLOSE_TAG_SAW_WHITE;
}
else if (c !== EOC) {
this.fail("disallowed character in closing tag.");
}
}
private sCloseTagSawWhite(): void {
switch (this.skipSpaces()) {
case GREATER:
this.closeTag();
break;
case EOC:
break;
default:
this.fail("disallowed character in closing tag.");
}
}
// END OF STATE ENGINE METHODS
private handleTextInRoot(): void {
// This is essentially a specialized version of captureTo which is optimized
// for performing the ]]> check. A previous version of this code, checked
// ``this.text`` for the presence of ]]>. It simplified the code but was
// very costly when character data contained a lot of entities to be parsed.
//
// Since we are using a specialized loop, we also keep track of the presence
// of ]]> in text data. The sequence ]]> is forbidden to appear as-is.
//
let { i: start, forbiddenState } = this;
const { chunk, textHandler: handler } = this;
// eslint-disable-next-line no-labels, no-restricted-syntax
scanLoop:
// eslint-disable-next-line no-constant-condition
while (true) {
switch (this.getCode()) {
case LESS: {
this.state = S_OPEN_WAKA;
if (handler !== undefined) {
const { text } = this;
const slice = chunk.slice(start, this.prevI);
if (text.length !== 0) {
handler(text + slice);
this.text = "";
}
else if (slice.length !== 0) {
handler(slice);
}
}
forbiddenState = FORBIDDEN_START;
// eslint-disable-next-line no-labels
break scanLoop;
}
case AMP:
this.state = S_ENTITY;
this.entityReturnState = S_TEXT;
if (handler !== undefined) {
this.text += chunk.slice(start, this.prevI);
}
forbiddenState = FORBIDDEN_START;
// eslint-disable-next-line no-labels
break scanLoop;
case CLOSE_BRACKET:
switch (forbiddenState) {
case FORBIDDEN_START:
forbiddenState = FORBIDDEN_BRACKET;
break;
case FORBIDDEN_BRACKET:
forbiddenState = FORBIDDEN_BRACKET_BRACKET;
break;
case FORBIDDEN_BRACKET_BRACKET:
break;
default:
throw new Error("impossible state");
}
break;
case GREATER:
if (forbiddenState === FORBIDDEN_BRACKET_BRACKET) {
this.fail("the string \"]]>\" is disallowed in char data.");
}
forbiddenState = FORBIDDEN_START;
break;
case NL_LIKE:
if (handler !== undefined) {
this.text += `${chunk.slice(start, this.prevI)}\n`;
}
start = this.i;
forbiddenState = FORBIDDEN_START;
break;
case EOC:
if (handler !== undefined) {
this.text += chunk.slice(start);
}
// eslint-disable-next-line no-labels
break scanLoop;
default:
forbiddenState = FORBIDDEN_START;
}
}
this.forbiddenState = forbiddenState;
}
private handleTextOutsideRoot(): void {
// This is essentially a specialized version of captureTo which is optimized
// for a specialized task. We keep track of the presence of non-space
// characters in the text since these are errors when appearing outside the
// document root element.
let { i: start } = this;
const { chunk, textHandler: handler } = this;
let nonSpace = false;
// eslint-disable-next-line no-labels, no-restricted-syntax
outRootLoop:
// eslint-disable-next-line no-constant-condition
while (true) {
const code = this.getCode();
switch (code) {
case LESS: {
this.state = S_OPEN_WAKA;
if (handler !== undefined) {
const { text } = this;
const slice = chunk.slice(start, this.prevI);
if (text.length !== 0) {
handler(text + slice);
this.text = "";
}
else if (slice.length !== 0) {
handler(slice);
}
}
// eslint-disable-next-line no-labels
break outRootLoop;
}
case AMP:
this.state = S_ENTITY;
this.entityReturnState = S_TEXT;
if (handler !== undefined) {
this.text += chunk.slice(start, this.prevI);
}
nonSpace = true;
// eslint-disable-next-line no-labels
break outRootLoop;
case NL_LIKE:
if (handler !== undefined) {
this.text += `${chunk.slice(start, this.prevI)}\n`;
}
start = this.i;
break;
case EOC:
if (handler !== undefined) {
this.text += chunk.slice(start);
}
// eslint-disable-next-line no-labels
break outRootLoop;
default:
if (!isS(code)) {
nonSpace = true;
}
}
}
if (!nonSpace) {
return;
}
// We use the reportedTextBeforeRoot and reportedTextAfterRoot flags
// to avoid reporting errors for every single character that is out of
// place.
if (!this.sawRoot && !this.reportedTextBeforeRoot) {
this.fail("text data outside of root node.");
this.reportedTextBeforeRoot = true;
}
if (this.closedRoot && !this.reportedTextAfterRoot) {
this.fail("text data outside of root node.");
this.reportedTextAfterRoot = true;
}
}
private pushAttribNS(name: string, value: string): void {
const { prefix, local } = this.qname(name);
const attr = { name, prefix, local, value };
this.attribList.push(attr);
this.attributeHandler?.(attr as AttributeEventForOptions<O>);
if (prefix === "xmlns") {
const trimmed = value.trim();
if (this.currentXMLVersion === "1.0" && trimmed === "") {
this.fail("invalid attempt to undefine prefix in XML 1.0");
}
this.topNS![local] = trimmed;
nsPairCheck(this, local, trimmed);
}
else if (name === "xmlns") {
const trimmed = value.trim();
this.topNS![""] = trimmed;
nsPairCheck(this, "", trimmed);
}
}
private pushAttribPlain(name: string, value: string): void {
const attr = { name, value };
this.attribList.push(attr);
this.attributeHandler?.(attr as AttributeEventForOptions<O>);
}
/**
* End parsing. This performs final well-formedness checks and resets the
* parser to a clean state.
*
* @returns this
*/
private end(): this {
if (!this.sawRoot) {
this.fail("document must contain a root element.");
}
const { tags } = this;
while (tags.length > 0) {
const tag = tags.pop()!;
this.fail(`unclosed tag: ${tag.name}`);
}
if ((this.state !== S_BEGIN) && (this.state !== S_TEXT)) {
this.fail("unexpected end.");
}
const { text } = this;
if (text.length !== 0) {
this.textHandler?.(text);
this.text = "";
}
this._closed = true;
this.endHandler?.();
this._init();
return this;
}
/**
* Resolve a namespace prefix.
*
* @param prefix The prefix to resolve.
*
* @returns The namespace URI or ``undefined`` if the prefix is not defined.
*/
resolve(prefix: string): string | undefined {
let uri = this.topNS![prefix];
if (uri !== undefined) {
return uri;
}
const { tags } = this;
for (let index = tags.length - 1; index >= 0; index--) {
uri = tags[index]!.ns![prefix];
if (uri !== undefined) {
return uri;
}
}
uri = this.ns[prefix];
if (uri !== undefined) {
return uri;
}
return this.opt.resolvePrefix?.(prefix);
}
/**
* Parse a qname into its prefix and local name parts.
*
* @param name The name to parse
*
* @returns
*/
private qname(name: string): { prefix: string; local: string } {
// This is faster than using name.split(":").
const colon = name.indexOf(":");
if (colon === -1) {
return { prefix: "", local: name };
}
const local = name.slice(colon + 1);
const prefix = name.slice(0, colon);
if (prefix === "" || local === "" || local.includes(":")) {
this.fail(`malformed name: ${name}.`);
}
return { prefix, local };
}
private processAttribsNS(): void {
const { attribList } = this;
const tag = this.tag!;
{
// add namespace info to tag
const { prefix, local } = this.qname(tag.name);
tag.prefix = prefix;
tag.local = local;
const uri = tag.uri = this.resolve(prefix) ?? "";
if (prefix !== "") {
if (prefix === "xmlns") {
this.fail("tags may not have \"xmlns\" as prefix.");
}
if (uri === "") {
this.fail(`unbound namespace prefix: ${JSON.stringify(prefix)}.`);
tag.uri = prefix;
}
}
}
if (attribList.length === 0) {
return;
}
const { attributes } = tag;
const seen = new Set();
// Note: do not apply default ns to attributes:
// http://www.w3.org/TR/REC-xml-names/#defaulting
for (const attr of attribList as SaxesAttributeNSIncomplete[]) {
const { name, prefix, local } = attr;
let uri;
let eqname;
if (prefix === "") {
uri = name === "xmlns" ? XMLNS_NAMESPACE : "";
eqname = name;
}
else {
uri = this.resolve(prefix);
// if there's any attributes with an undefined namespace,
// then fail on them now.
if (uri === undefined) {
this.fail(`unbound namespace prefix: ${JSON.stringify(prefix)}.`);
uri = prefix;
}
eqname = `{${uri}}${local}`;
}
if (seen.has(eqname)) {
this.fail(`duplicate attribute: ${eqname}.`);
}
seen.add(eqname);
attr.uri = uri;
attributes[name] = attr;
}
this.attribList = [];
}
private processAttribsPlain(): void {
const { attribList } = this;
// eslint-disable-next-line prefer-destructuring
const attributes = this.tag!.attributes;
for (const { name, value } of attribList) {
if (attributes[name] !== undefined) {
this.fail(`duplicate attribute: ${name}.`);
}
attributes[name] = value;
}
this.attribList = [];
}
/**
* Handle a complete open tag. This parser code calls this once it has seen
* the whole tag. This method checks for well-formeness and then emits
* ``onopentag``.
*/
private openTag(): void {
this.processAttribs();
const { tags } = this;
const tag = this.tag as SaxesTag;
tag.isSelfClosing = false;
// There cannot be any pending text here due to the onopentagstart that was
// necessarily emitted before we get here. So we do not check text.
this.openTagHandler?.(tag as TagForOptions<O>);
tags.push(tag);
this.state = S_TEXT;
this.name = "";
}
/**
* Handle a complete self-closing tag. This parser code calls this once it has
* seen the whole tag. This method checks for well-formeness and then emits
* ``onopentag`` and ``onclosetag``.
*/
private openSelfClosingTag(): void {
this.processAttribs();
const { tags } = this;
const tag = this.tag as SaxesTag;
tag.isSelfClosing = true;
// There cannot be any pending text here due to the onopentagstart that was
// necessarily emitted before we get here. So we do not check text.
this.openTagHandler?.(tag as TagForOptions<O>);
this.closeTagHandler?.(tag as TagForOptions<O>);
const top = this.tag = tags[tags.length - 1] ?? null;
if (top === null) {
this.closedRoot = true;
}
this.state = S_TEXT;
this.name = "";
}
/**
* Handle a complete close tag. This parser code calls this once it has seen
* the whole tag. This method checks for well-formeness and then emits
* ``onclosetag``.
*/
private closeTag(): void {
const { tags, name } = this;
// Our state after this will be S_TEXT, no matter what, and we can clear
// tagName now.
this.state = S_TEXT;
this.name = "";
if (name === "") {
this.fail("weird empty close tag.");
this.text += "</>";
return;
}
const handler = this.closeTagHandler;
let l = tags.length;
while (l-- > 0) {
const tag = this.tag = tags.pop() as SaxesTag;
this.topNS = tag.ns!;
handler?.(tag as TagForOptions<O>);
if (tag.name === name) {
break;
}
this.fail("unexpected close tag.");
}
if (l === 0) {
this.closedRoot = true;
}
else if (l < 0) {
this.fail(`unmatched closing tag: ${name}.`);
this.text += `</${name}>`;
}
}
/**
* Resolves an entity. Makes any necessary well-formedness checks.
*
* @param entity The entity to resolve.
*
* @returns The parsed entity.
*/
private parseEntity(entity: string): string {
// startsWith would be significantly slower for this test.
if (entity[0] !== "#") {
const defined = this.ENTITIES[entity];
if (defined !== undefined) {
return defined;
}
this.fail(this.isName(entity) ? "undefined entity." :
"disallowed character in entity name.");
return `&${entity};`;
}
let num = NaN;
if (entity[1] === "x" && /^#x[0-9a-f]+$/i.test(entity)) {
num = parseInt(entity.slice(2), 16);
}
else if (/^#[0-9]+$/.test(entity)) {
num = parseInt(entity.slice(1), 10);
}
// The character reference is required to match the CHAR production.
if (!this.isChar(num)) {
this.fail("malformed character entity.");
return `&${entity};`;
}
return String.fromCodePoint(num);
}
} |
1,131 | function test(options: TestOptions): void {
const { xml, name, expect: expected, fn, events } = options;
it(name, () => {
const parser = new SaxesParser(options.opt);
let expectedIx = 0;
for (const ev of events ?? EVENTS) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any, no-loop-func
parser.on(ev, (n: any) => {
if (process.env.DEBUG !== undefined) {
console.error({
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
expected: expected[expectedIx],
actual: [ev, n],
});
}
if (expectedIx >= expected.length && (ev === "end" || ev === "ready")) {
return;
}
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
expect([ev, ev === "error" ? n.message : n]).to.deep
.equal(expected[expectedIx]);
expectedIx++;
});
}
expect(xml !== undefined || fn !== undefined, "must use xml or fn")
.to.be.true;
if (xml !== undefined) {
if (Array.isArray(xml)) {
for (const chunk of xml as readonly string[]) {
parser.write(chunk);
}
parser.close();
}
else {
parser.write(xml as string).close();
}
}
fn?.(parser);
expect(expectedIx).to.equal(expected.length);
});
} | interface TestOptions {
xml?: string | readonly string[];
name: string;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
expect: readonly any[];
// eslint-disable-next-line @typescript-eslint/ban-types
fn?: (parser: SaxesParser<{}>) => void;
opt?: SaxesOptions;
events?: readonly EventName[];
} |
1,132 | fn(parser: SaxesParser): void {
// This test purposely slices the string into the poop character.
parser.write(xml.slice(0, 4));
parser.write(xml.slice(4));
parser.close();
} | class SaxesParser<O extends SaxesOptions = {}> {
private readonly fragmentOpt: boolean;
private readonly xmlnsOpt: boolean;
private readonly trackPosition: boolean;
private readonly fileName?: string;
private readonly nameStartCheck: (c: number) => boolean;
private readonly nameCheck: (c: number) => boolean;
private readonly isName: (name: string) => boolean;
private readonly ns!: Record<string, string>;
private openWakaBang!: string;
private text!: string;
private name!: string;
private piTarget!: string;
private entity!: string;
private q!: null | number;
private tags!: SaxesTagIncomplete[];
private tag!: SaxesTagIncomplete | null;
private topNS!: Record<string, string> | null;
private chunk!: string;
private chunkPosition!: number;
private i!: number;
//
// We use prevI to allow "ungetting" the previously read code point. Note
// however, that it is not safe to unget everything and anything. In
// particular ungetting EOL characters will screw positioning up.
//
// Practically, you must not unget a code which has any side effect beyond
// updating ``this.i`` and ``this.prevI``. Only EOL codes have such side
// effects.
//
private prevI!: number;
private carriedFromPrevious?: string;
private forbiddenState!: number;
private attribList!: (SaxesAttributeNSIncomplete | SaxesAttributePlain)[];
private state!: number;
private reportedTextBeforeRoot!: boolean;
private reportedTextAfterRoot!: boolean;
private closedRoot!: boolean;
private sawRoot!: boolean;
private xmlDeclPossible!: boolean;
private xmlDeclExpects!: string[];
private entityReturnState?: number;
private processAttribs!: (this: this) => void;
private positionAtNewLine!: number;
private doctype!: boolean;
private getCode!: () => number;
private isChar!: (c: number) => boolean;
private pushAttrib!: (name: string, value: string) => void;
private _closed!: boolean;
private currentXMLVersion!: string;
private readonly stateTable: ((this: SaxesParser<O>) => void)[];
private xmldeclHandler?: XMLDeclHandler;
private textHandler?: TextHandler;
private piHandler?: PIHandler;
private doctypeHandler?: DoctypeHandler;
private commentHandler?: CommentHandler;
private openTagStartHandler?: OpenTagStartHandler<O>;
private openTagHandler?: OpenTagHandler<O>;
private closeTagHandler?: CloseTagHandler<O>;
private cdataHandler?: CDataHandler;
private errorHandler?: ErrorHandler;
private endHandler?: EndHandler;
private readyHandler?: ReadyHandler;
private attributeHandler?: AttributeHandler<O>;
/**
* Indicates whether or not the parser is closed. If ``true``, wait for
* the ``ready`` event to write again.
*/
get closed(): boolean {
return this._closed;
}
readonly opt: SaxesOptions;
/**
* The XML declaration for this document.
*/
xmlDecl!: XMLDecl;
/**
* The line number of the next character to be read by the parser. This field
* is one-based. (The first line is numbered 1.)
*/
line!: number;
/**
* The column number of the next character to be read by the parser. *
* This field is zero-based. (The first column is 0.)
*
* This field counts columns by *Unicode character*. Note that this *can*
* be different from the index of the character in a JavaScript string due
* to how JavaScript handles astral plane characters.
*
* See [[columnIndex]] for a number that corresponds to the JavaScript index.
*/
column!: number;
/**
* A map of entity name to expansion.
*/
ENTITIES!: Record<string, string>;
/**
* @param opt The parser options.
*/
constructor(opt?: O) {
this.opt = opt ?? {};
this.fragmentOpt = !!(this.opt.fragment as boolean);
const xmlnsOpt = this.xmlnsOpt = !!(this.opt.xmlns as boolean);
this.trackPosition = this.opt.position !== false;
this.fileName = this.opt.fileName;
if (xmlnsOpt) {
// This is the function we use to perform name checks on PIs and entities.
// When namespaces are used, colons are not allowed in PI target names or
// entity names. So the check depends on whether namespaces are used. See:
//
// https://www.w3.org/XML/xml-names-19990114-errata.html
// NE08
//
this.nameStartCheck = isNCNameStartChar;
this.nameCheck = isNCNameChar;
this.isName = isNCName;
// eslint-disable-next-line @typescript-eslint/unbound-method
this.processAttribs = this.processAttribsNS;
// eslint-disable-next-line @typescript-eslint/unbound-method
this.pushAttrib = this.pushAttribNS;
// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-assignment
this.ns = { __proto__: null as any, ...rootNS };
const additional = this.opt.additionalNamespaces;
if (additional != null) {
nsMappingCheck(this, additional);
Object.assign(this.ns, additional);
}
}
else {
this.nameStartCheck = isNameStartChar;
this.nameCheck = isNameChar;
this.isName = isName;
// eslint-disable-next-line @typescript-eslint/unbound-method
this.processAttribs = this.processAttribsPlain;
// eslint-disable-next-line @typescript-eslint/unbound-method
this.pushAttrib = this.pushAttribPlain;
}
//
// The order of the members in this table needs to correspond to the state
// numbers given to the states that correspond to the methods being recorded
// here.
//
this.stateTable = [
/* eslint-disable @typescript-eslint/unbound-method */
this.sBegin,
this.sBeginWhitespace,
this.sDoctype,
this.sDoctypeQuote,
this.sDTD,
this.sDTDQuoted,
this.sDTDOpenWaka,
this.sDTDOpenWakaBang,
this.sDTDComment,
this.sDTDCommentEnding,
this.sDTDCommentEnded,
this.sDTDPI,
this.sDTDPIEnding,
this.sText,
this.sEntity,
this.sOpenWaka,
this.sOpenWakaBang,
this.sComment,
this.sCommentEnding,
this.sCommentEnded,
this.sCData,
this.sCDataEnding,
this.sCDataEnding2,
this.sPIFirstChar,
this.sPIRest,
this.sPIBody,
this.sPIEnding,
this.sXMLDeclNameStart,
this.sXMLDeclName,
this.sXMLDeclEq,
this.sXMLDeclValueStart,
this.sXMLDeclValue,
this.sXMLDeclSeparator,
this.sXMLDeclEnding,
this.sOpenTag,
this.sOpenTagSlash,
this.sAttrib,
this.sAttribName,
this.sAttribNameSawWhite,
this.sAttribValue,
this.sAttribValueQuoted,
this.sAttribValueClosed,
this.sAttribValueUnquoted,
this.sCloseTag,
this.sCloseTagSawWhite,
/* eslint-enable @typescript-eslint/unbound-method */
];
this._init();
}
_init(): void {
this.openWakaBang = "";
this.text = "";
this.name = "";
this.piTarget = "";
this.entity = "";
this.q = null;
this.tags = [];
this.tag = null;
this.topNS = null;
this.chunk = "";
this.chunkPosition = 0;
this.i = 0;
this.prevI = 0;
this.carriedFromPrevious = undefined;
this.forbiddenState = FORBIDDEN_START;
this.attribList = [];
// The logic is organized so as to minimize the need to check
// this.opt.fragment while parsing.
const { fragmentOpt } = this;
this.state = fragmentOpt ? S_TEXT : S_BEGIN;
// We want these to be all true if we are dealing with a fragment.
this.reportedTextBeforeRoot = this.reportedTextAfterRoot = this.closedRoot =
this.sawRoot = fragmentOpt;
// An XML declaration is intially possible only when parsing whole
// documents.
this.xmlDeclPossible = !fragmentOpt;
this.xmlDeclExpects = ["version"];
this.entityReturnState = undefined;
let { defaultXMLVersion } = this.opt;
if (defaultXMLVersion === undefined) {
if (this.opt.forceXMLVersion === true) {
throw new Error("forceXMLVersion set but defaultXMLVersion is not set");
}
defaultXMLVersion = "1.0";
}
this.setXMLVersion(defaultXMLVersion);
this.positionAtNewLine = 0;
this.doctype = false;
this._closed = false;
this.xmlDecl = {
version: undefined,
encoding: undefined,
standalone: undefined,
};
this.line = 1;
this.column = 0;
this.ENTITIES = Object.create(XML_ENTITIES) as Record<string, string>;
this.readyHandler?.();
}
/**
* The stream position the parser is currently looking at. This field is
* zero-based.
*
* This field is not based on counting Unicode characters but is to be
* interpreted as a plain index into a JavaScript string.
*/
get position(): number {
return this.chunkPosition + this.i;
}
/**
* The column number of the next character to be read by the parser. *
* This field is zero-based. (The first column in a line is 0.)
*
* This field reports the index at which the next character would be in the
* line if the line were represented as a JavaScript string. Note that this
* *can* be different to a count based on the number of *Unicode characters*
* due to how JavaScript handles astral plane characters.
*
* See [[column]] for a number that corresponds to a count of Unicode
* characters.
*/
get columnIndex(): number {
return this.position - this.positionAtNewLine;
}
/**
* Set an event listener on an event. The parser supports one handler per
* event type. If you try to set an event handler over an existing handler,
* the old handler is silently overwritten.
*
* @param name The event to listen to.
*
* @param handler The handler to set.
*/
on<N extends EventName>(name: N, handler: EventNameToHandler<O, N>): void {
// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-member-access
(this as any)[EVENT_NAME_TO_HANDLER_NAME[name]] = handler;
}
/**
* Unset an event handler.
*
* @parma name The event to stop listening to.
*/
off(name: EventName): void {
// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-member-access
(this as any)[EVENT_NAME_TO_HANDLER_NAME[name]] = undefined;
}
/**
* Make an error object. The error object will have a message that contains
* the ``fileName`` option passed at the creation of the parser. If position
* tracking was turned on, it will also have line and column number
* information.
*
* @param message The message describing the error to report.
*
* @returns An error object with a properly formatted message.
*/
makeError(message: string): Error {
let msg = this.fileName ?? "";
if (this.trackPosition) {
if (msg.length > 0) {
msg += ":";
}
msg += `${this.line}:${this.column}`;
}
if (msg.length > 0) {
msg += ": ";
}
return new Error(msg + message);
}
/**
* Report a parsing error. This method is made public so that client code may
* check for issues that are outside the scope of this project and can report
* errors.
*
* @param message The error to report.
*
* @returns this
*/
fail(message: string): this {
const err = this.makeError(message);
const handler = this.errorHandler;
if (handler === undefined) {
throw err;
}
else {
handler(err);
}
return this;
}
/**
* Write a XML data to the parser.
*
* @param chunk The XML data to write.
*
* @returns this
*/
// We do need object for the type here. Yes, it often causes problems
// but not in this case.
write(chunk: string | object | null): this {
if (this.closed) {
return this.fail("cannot write after close; assign an onready handler.");
}
let end = false;
if (chunk === null) {
// We cannot return immediately because carriedFromPrevious may need
// processing.
end = true;
chunk = "";
}
else if (typeof chunk === "object") {
chunk = chunk.toString();
}
// We checked if performing a pre-decomposition of the string into an array
// of single complete characters (``Array.from(chunk)``) would be faster
// than the current repeated calls to ``charCodeAt``. As of August 2018, it
// isn't. (There may be Node-specific code that would perform faster than
// ``Array.from`` but don't want to be dependent on Node.)
if (this.carriedFromPrevious !== undefined) {
// The previous chunk had char we must carry over.
chunk = `${this.carriedFromPrevious}${chunk}`;
this.carriedFromPrevious = undefined;
}
let limit = chunk.length;
const lastCode = chunk.charCodeAt(limit - 1);
if (!end &&
// A trailing CR or surrogate must be carried over to the next
// chunk.
(lastCode === CR || (lastCode >= 0xD800 && lastCode <= 0xDBFF))) {
// The chunk ends with a character that must be carried over. We cannot
// know how to handle it until we get the next chunk or the end of the
// stream. So save it for later.
this.carriedFromPrevious = chunk[limit - 1];
limit--;
chunk = chunk.slice(0, limit);
}
const { stateTable } = this;
this.chunk = chunk;
this.i = 0;
while (this.i < limit) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-argument
stateTable[this.state].call(this as any);
}
this.chunkPosition += limit;
return end ? this.end() : this;
}
/**
* Close the current stream. Perform final well-formedness checks and reset
* the parser tstate.
*
* @returns this
*/
close(): this {
return this.write(null);
}
/**
* Get a single code point out of the current chunk. This updates the current
* position if we do position tracking.
*
* This is the algorithm to use for XML 1.0.
*
* @returns The character read.
*/
private getCode10(): number {
const { chunk, i } = this;
this.prevI = i;
// Yes, we do this instead of doing this.i++. Doing it this way, we do not
// read this.i again, which is a bit faster.
this.i = i + 1;
if (i >= chunk.length) {
return EOC;
}
// Using charCodeAt and handling the surrogates ourselves is faster
// than using codePointAt.
const code = chunk.charCodeAt(i);
this.column++;
if (code < 0xD800) {
if (code >= SPACE || code === TAB) {
return code;
}
switch (code) {
case NL:
this.line++;
this.column = 0;
this.positionAtNewLine = this.position;
return NL;
case CR:
// We may get NaN if we read past the end of the chunk, which is fine.
if (chunk.charCodeAt(i + 1) === NL) {
// A \r\n sequence is converted to \n so we have to skip over the
// next character. We already know it has a size of 1 so ++ is fine
// here.
this.i = i + 2;
}
// Otherwise, a \r is just converted to \n, so we don't have to skip
// ahead.
// In either case, \r becomes \n.
this.line++;
this.column = 0;
this.positionAtNewLine = this.position;
return NL_LIKE;
default:
// If we get here, then code < SPACE and it is not NL CR or TAB.
this.fail("disallowed character.");
return code;
}
}
if (code > 0xDBFF) {
// This is a specialized version of isChar10 that takes into account
// that in this context code > 0xDBFF and code <= 0xFFFF. So it does not
// test cases that don't need testing.
if (!(code >= 0xE000 && code <= 0xFFFD)) {
this.fail("disallowed character.");
}
return code;
}
const final = 0x10000 + ((code - 0xD800) * 0x400) +
(chunk.charCodeAt(i + 1) - 0xDC00);
this.i = i + 2;
// This is a specialized version of isChar10 that takes into account that in
// this context necessarily final >= 0x10000.
if (final > 0x10FFFF) {
this.fail("disallowed character.");
}
return final;
}
/**
* Get a single code point out of the current chunk. This updates the current
* position if we do position tracking.
*
* This is the algorithm to use for XML 1.1.
*
* @returns {number} The character read.
*/
private getCode11(): number {
const { chunk, i } = this;
this.prevI = i;
// Yes, we do this instead of doing this.i++. Doing it this way, we do not
// read this.i again, which is a bit faster.
this.i = i + 1;
if (i >= chunk.length) {
return EOC;
}
// Using charCodeAt and handling the surrogates ourselves is faster
// than using codePointAt.
const code = chunk.charCodeAt(i);
this.column++;
if (code < 0xD800) {
if ((code > 0x1F && code < 0x7F) || (code > 0x9F && code !== LS) ||
code === TAB) {
return code;
}
switch (code) {
case NL: // 0xA
this.line++;
this.column = 0;
this.positionAtNewLine = this.position;
return NL;
case CR: { // 0xD
// We may get NaN if we read past the end of the chunk, which is
// fine.
const next = chunk.charCodeAt(i + 1);
if (next === NL || next === NEL) {
// A CR NL or CR NEL sequence is converted to NL so we have to skip
// over the next character. We already know it has a size of 1.
this.i = i + 2;
}
// Otherwise, a CR is just converted to NL, no skip.
}
/* yes, fall through */
case NEL: // 0x85
case LS: // Ox2028
this.line++;
this.column = 0;
this.positionAtNewLine = this.position;
return NL_LIKE;
default:
this.fail("disallowed character.");
return code;
}
}
if (code > 0xDBFF) {
// This is a specialized version of isCharAndNotRestricted that takes into
// account that in this context code > 0xDBFF and code <= 0xFFFF. So it
// does not test cases that don't need testing.
if (!(code >= 0xE000 && code <= 0xFFFD)) {
this.fail("disallowed character.");
}
return code;
}
const final = 0x10000 + ((code - 0xD800) * 0x400) +
(chunk.charCodeAt(i + 1) - 0xDC00);
this.i = i + 2;
// This is a specialized version of isCharAndNotRestricted that takes into
// account that in this context necessarily final >= 0x10000.
if (final > 0x10FFFF) {
this.fail("disallowed character.");
}
return final;
}
/**
* Like ``getCode`` but with the return value normalized so that ``NL`` is
* returned for ``NL_LIKE``.
*/
private getCodeNorm(): number {
const c = this.getCode();
return c === NL_LIKE ? NL : c;
}
private unget(): void {
this.i = this.prevI;
this.column--;
}
/**
* Capture characters into a buffer until encountering one of a set of
* characters.
*
* @param chars An array of codepoints. Encountering a character in the array
* ends the capture. (``chars`` may safely contain ``NL``.)
*
* @return The character code that made the capture end, or ``EOC`` if we hit
* the end of the chunk. The return value cannot be NL_LIKE: NL is returned
* instead.
*/
private captureTo(chars: number[]): number {
let { i: start } = this;
const { chunk } = this;
// eslint-disable-next-line no-constant-condition
while (true) {
const c = this.getCode();
const isNLLike = c === NL_LIKE;
const final = isNLLike ? NL : c;
if (final === EOC || chars.includes(final)) {
this.text += chunk.slice(start, this.prevI);
return final;
}
if (isNLLike) {
this.text += `${chunk.slice(start, this.prevI)}\n`;
start = this.i;
}
}
}
/**
* Capture characters into a buffer until encountering a character.
*
* @param char The codepoint that ends the capture. **NOTE ``char`` MAY NOT
* CONTAIN ``NL``.** Passing ``NL`` will result in buggy behavior.
*
* @return ``true`` if we ran into the character. Otherwise, we ran into the
* end of the current chunk.
*/
private captureToChar(char: number): boolean {
let { i: start } = this;
const { chunk } = this;
// eslint-disable-next-line no-constant-condition
while (true) {
let c = this.getCode();
switch (c) {
case NL_LIKE:
this.text += `${chunk.slice(start, this.prevI)}\n`;
start = this.i;
c = NL;
break;
case EOC:
this.text += chunk.slice(start);
return false;
default:
}
if (c === char) {
this.text += chunk.slice(start, this.prevI);
return true;
}
}
}
/**
* Capture characters that satisfy ``isNameChar`` into the ``name`` field of
* this parser.
*
* @return The character code that made the test fail, or ``EOC`` if we hit
* the end of the chunk. The return value cannot be NL_LIKE: NL is returned
* instead.
*/
private captureNameChars(): number {
const { chunk, i: start } = this;
// eslint-disable-next-line no-constant-condition
while (true) {
const c = this.getCode();
if (c === EOC) {
this.name += chunk.slice(start);
return EOC;
}
// NL is not a name char so we don't have to test specifically for it.
if (!isNameChar(c)) {
this.name += chunk.slice(start, this.prevI);
return c === NL_LIKE ? NL : c;
}
}
}
/**
* Skip white spaces.
*
* @return The character that ended the skip, or ``EOC`` if we hit
* the end of the chunk. The return value cannot be NL_LIKE: NL is returned
* instead.
*/
private skipSpaces(): number {
// eslint-disable-next-line no-constant-condition
while (true) {
const c = this.getCodeNorm();
if (c === EOC || !isS(c)) {
return c;
}
}
}
private setXMLVersion(version: string): void {
this.currentXMLVersion = version;
/* eslint-disable @typescript-eslint/unbound-method */
if (version === "1.0") {
this.isChar = isChar10;
this.getCode = this.getCode10;
}
else {
this.isChar = isChar11;
this.getCode = this.getCode11;
}
/* eslint-enable @typescript-eslint/unbound-method */
}
// STATE ENGINE METHODS
// This needs to be a state separate from S_BEGIN_WHITESPACE because we want
// to be sure never to come back to this state later.
private sBegin(): void {
// We are essentially peeking at the first character of the chunk. Since
// S_BEGIN can be in effect only when we start working on the first chunk,
// the index at which we must look is necessarily 0. Note also that the
// following test does not depend on decoding surrogates.
// If the initial character is 0xFEFF, ignore it.
if (this.chunk.charCodeAt(0) === 0xFEFF) {
this.i++;
this.column++;
}
this.state = S_BEGIN_WHITESPACE;
}
private sBeginWhitespace(): void {
// We need to know whether we've encountered spaces or not because as soon
// as we run into a space, an XML declaration is no longer possible. Rather
// than slow down skipSpaces even in places where we don't care whether it
// skipped anything or not, we check whether prevI is equal to the value of
// i from before we skip spaces.
const iBefore = this.i;
const c = this.skipSpaces();
if (this.prevI !== iBefore) {
this.xmlDeclPossible = false;
}
switch (c) {
case LESS:
this.state = S_OPEN_WAKA;
// We could naively call closeText but in this state, it is not normal
// to have text be filled with any data.
if (this.text.length !== 0) {
throw new Error("no-empty text at start");
}
break;
case EOC:
break;
default:
this.unget();
this.state = S_TEXT;
this.xmlDeclPossible = false;
}
}
private sDoctype(): void {
const c = this.captureTo(DOCTYPE_TERMINATOR);
switch (c) {
case GREATER: {
this.doctypeHandler?.(this.text);
this.text = "";
this.state = S_TEXT;
this.doctype = true; // just remember that we saw it.
break;
}
case EOC:
break;
default:
this.text += String.fromCodePoint(c);
if (c === OPEN_BRACKET) {
this.state = S_DTD;
}
else if (isQuote(c)) {
this.state = S_DOCTYPE_QUOTE;
this.q = c;
}
}
}
private sDoctypeQuote(): void {
const q = this.q!;
if (this.captureToChar(q)) {
this.text += String.fromCodePoint(q);
this.q = null;
this.state = S_DOCTYPE;
}
}
private sDTD(): void {
const c = this.captureTo(DTD_TERMINATOR);
if (c === EOC) {
return;
}
this.text += String.fromCodePoint(c);
if (c === CLOSE_BRACKET) {
this.state = S_DOCTYPE;
}
else if (c === LESS) {
this.state = S_DTD_OPEN_WAKA;
}
else if (isQuote(c)) {
this.state = S_DTD_QUOTED;
this.q = c;
}
}
private sDTDQuoted(): void {
const q = this.q!;
if (this.captureToChar(q)) {
this.text += String.fromCodePoint(q);
this.state = S_DTD;
this.q = null;
}
}
private sDTDOpenWaka(): void {
const c = this.getCodeNorm();
this.text += String.fromCodePoint(c);
switch (c) {
case BANG:
this.state = S_DTD_OPEN_WAKA_BANG;
this.openWakaBang = "";
break;
case QUESTION:
this.state = S_DTD_PI;
break;
default:
this.state = S_DTD;
}
}
private sDTDOpenWakaBang(): void {
const char = String.fromCodePoint(this.getCodeNorm());
const owb = this.openWakaBang += char;
this.text += char;
if (owb !== "-") {
this.state = owb === "--" ? S_DTD_COMMENT : S_DTD;
this.openWakaBang = "";
}
}
private sDTDComment(): void {
if (this.captureToChar(MINUS)) {
this.text += "-";
this.state = S_DTD_COMMENT_ENDING;
}
}
private sDTDCommentEnding(): void {
const c = this.getCodeNorm();
this.text += String.fromCodePoint(c);
this.state = c === MINUS ? S_DTD_COMMENT_ENDED : S_DTD_COMMENT;
}
private sDTDCommentEnded(): void {
const c = this.getCodeNorm();
this.text += String.fromCodePoint(c);
if (c === GREATER) {
this.state = S_DTD;
}
else {
this.fail("malformed comment.");
// <!-- blah -- bloo --> will be recorded as
// a comment of " blah -- bloo "
this.state = S_DTD_COMMENT;
}
}
private sDTDPI(): void {
if (this.captureToChar(QUESTION)) {
this.text += "?";
this.state = S_DTD_PI_ENDING;
}
}
private sDTDPIEnding(): void {
const c = this.getCodeNorm();
this.text += String.fromCodePoint(c);
if (c === GREATER) {
this.state = S_DTD;
}
}
private sText(): void {
//
// We did try a version of saxes where the S_TEXT state was split in two
// states: one for text inside the root element, and one for text
// outside. This was avoiding having to test this.tags.length to decide
// what implementation to actually use.
//
// Peformance testing on gigabyte-size files did not show any advantage to
// using the two states solution instead of the current one. Conversely, it
// made the code a bit more complicated elsewhere. For instance, a comment
// can appear before the root element so when a comment ended it was
// necessary to determine whether to return to the S_TEXT state or to the
// new text-outside-root state.
//
if (this.tags.length !== 0) {
this.handleTextInRoot();
}
else {
this.handleTextOutsideRoot();
}
}
private sEntity(): void {
// This is essentially a specialized version of captureToChar(SEMICOLON...)
let { i: start } = this;
const { chunk } = this;
// eslint-disable-next-line no-labels, no-restricted-syntax
loop:
// eslint-disable-next-line no-constant-condition
while (true) {
switch (this.getCode()) {
case NL_LIKE:
this.entity += `${chunk.slice(start, this.prevI)}\n`;
start = this.i;
break;
case SEMICOLON: {
const { entityReturnState } = this;
const entity = this.entity + chunk.slice(start, this.prevI);
this.state = entityReturnState!;
let parsed: string;
if (entity === "") {
this.fail("empty entity name.");
parsed = "&;";
}
else {
parsed = this.parseEntity(entity);
this.entity = "";
}
if (entityReturnState !== S_TEXT || this.textHandler !== undefined) {
this.text += parsed;
}
// eslint-disable-next-line no-labels
break loop;
}
case EOC:
this.entity += chunk.slice(start);
// eslint-disable-next-line no-labels
break loop;
default:
}
}
}
private sOpenWaka(): void {
// Reminder: a state handler is called with at least one character
// available in the current chunk. So the first call to get code inside of
// a state handler cannot return ``EOC``. That's why we don't test
// for it.
const c = this.getCode();
// either a /, ?, !, or text is coming next.
if (isNameStartChar(c)) {
this.state = S_OPEN_TAG;
this.unget();
this.xmlDeclPossible = false;
}
else {
switch (c) {
case FORWARD_SLASH:
this.state = S_CLOSE_TAG;
this.xmlDeclPossible = false;
break;
case BANG:
this.state = S_OPEN_WAKA_BANG;
this.openWakaBang = "";
this.xmlDeclPossible = false;
break;
case QUESTION:
this.state = S_PI_FIRST_CHAR;
break;
default:
this.fail("disallowed character in tag name");
this.state = S_TEXT;
this.xmlDeclPossible = false;
}
}
}
private sOpenWakaBang(): void {
this.openWakaBang += String.fromCodePoint(this.getCodeNorm());
switch (this.openWakaBang) {
case "[CDATA[":
if (!this.sawRoot && !this.reportedTextBeforeRoot) {
this.fail("text data outside of root node.");
this.reportedTextBeforeRoot = true;
}
if (this.closedRoot && !this.reportedTextAfterRoot) {
this.fail("text data outside of root node.");
this.reportedTextAfterRoot = true;
}
this.state = S_CDATA;
this.openWakaBang = "";
break;
case "--":
this.state = S_COMMENT;
this.openWakaBang = "";
break;
case "DOCTYPE":
this.state = S_DOCTYPE;
if (this.doctype || this.sawRoot) {
this.fail("inappropriately located doctype declaration.");
}
this.openWakaBang = "";
break;
default:
// 7 happens to be the maximum length of the string that can possibly
// match one of the cases above.
if (this.openWakaBang.length >= 7) {
this.fail("incorrect syntax.");
}
}
}
private sComment(): void {
if (this.captureToChar(MINUS)) {
this.state = S_COMMENT_ENDING;
}
}
private sCommentEnding(): void {
const c = this.getCodeNorm();
if (c === MINUS) {
this.state = S_COMMENT_ENDED;
this.commentHandler?.(this.text);
this.text = "";
}
else {
this.text += `-${String.fromCodePoint(c)}`;
this.state = S_COMMENT;
}
}
private sCommentEnded(): void {
const c = this.getCodeNorm();
if (c !== GREATER) {
this.fail("malformed comment.");
// <!-- blah -- bloo --> will be recorded as
// a comment of " blah -- bloo "
this.text += `--${String.fromCodePoint(c)}`;
this.state = S_COMMENT;
}
else {
this.state = S_TEXT;
}
}
private sCData(): void {
if (this.captureToChar(CLOSE_BRACKET)) {
this.state = S_CDATA_ENDING;
}
}
private sCDataEnding(): void {
const c = this.getCodeNorm();
if (c === CLOSE_BRACKET) {
this.state = S_CDATA_ENDING_2;
}
else {
this.text += `]${String.fromCodePoint(c)}`;
this.state = S_CDATA;
}
}
private sCDataEnding2(): void {
const c = this.getCodeNorm();
switch (c) {
case GREATER: {
this.cdataHandler?.(this.text);
this.text = "";
this.state = S_TEXT;
break;
}
case CLOSE_BRACKET:
this.text += "]";
break;
default:
this.text += `]]${String.fromCodePoint(c)}`;
this.state = S_CDATA;
}
}
// We need this separate state to check the first character fo the pi target
// with this.nameStartCheck which allows less characters than this.nameCheck.
private sPIFirstChar(): void {
const c = this.getCodeNorm();
// This is first because in the case where the file is well-formed this is
// the branch taken. We optimize for well-formedness.
if (this.nameStartCheck(c)) {
this.piTarget += String.fromCodePoint(c);
this.state = S_PI_REST;
}
else if (c === QUESTION || isS(c)) {
this.fail("processing instruction without a target.");
this.state = c === QUESTION ? S_PI_ENDING : S_PI_BODY;
}
else {
this.fail("disallowed character in processing instruction name.");
this.piTarget += String.fromCodePoint(c);
this.state = S_PI_REST;
}
}
private sPIRest(): void {
// Capture characters into a piTarget while ``this.nameCheck`` run on the
// character read returns true.
const { chunk, i: start } = this;
// eslint-disable-next-line no-constant-condition
while (true) {
const c = this.getCodeNorm();
if (c === EOC) {
this.piTarget += chunk.slice(start);
return;
}
// NL cannot satisfy this.nameCheck so we don't have to test specifically
// for it.
if (!this.nameCheck(c)) {
this.piTarget += chunk.slice(start, this.prevI);
const isQuestion = c === QUESTION;
if (isQuestion || isS(c)) {
if (this.piTarget === "xml") {
if (!this.xmlDeclPossible) {
this.fail(
"an XML declaration must be at the start of the document.");
}
this.state = isQuestion ? S_XML_DECL_ENDING : S_XML_DECL_NAME_START;
}
else {
this.state = isQuestion ? S_PI_ENDING : S_PI_BODY;
}
}
else {
this.fail("disallowed character in processing instruction name.");
this.piTarget += String.fromCodePoint(c);
}
break;
}
}
}
private sPIBody(): void {
if (this.text.length === 0) {
const c = this.getCodeNorm();
if (c === QUESTION) {
this.state = S_PI_ENDING;
}
else if (!isS(c)) {
this.text = String.fromCodePoint(c);
}
}
// The question mark character is not valid inside any of the XML
// declaration name/value pairs.
else if (this.captureToChar(QUESTION)) {
this.state = S_PI_ENDING;
}
}
private sPIEnding(): void {
const c = this.getCodeNorm();
if (c === GREATER) {
const { piTarget } = this;
if (piTarget.toLowerCase() === "xml") {
this.fail(
"the XML declaration must appear at the start of the document.");
}
this.piHandler?.({
target: piTarget,
body: this.text,
});
this.piTarget = this.text = "";
this.state = S_TEXT;
}
else if (c === QUESTION) {
// We ran into ?? as part of a processing instruction. We initially took
// the first ? as a sign that the PI was ending, but it is not. So we have
// to add it to the body but we take the new ? as a sign that the PI is
// ending.
this.text += "?";
}
else {
this.text += `?${String.fromCodePoint(c)}`;
this.state = S_PI_BODY;
}
this.xmlDeclPossible = false;
}
private sXMLDeclNameStart(): void {
const c = this.skipSpaces();
// The question mark character is not valid inside any of the XML
// declaration name/value pairs.
if (c === QUESTION) {
// It is valid to go to S_XML_DECL_ENDING from this state.
this.state = S_XML_DECL_ENDING;
return;
}
if (c !== EOC) {
this.state = S_XML_DECL_NAME;
this.name = String.fromCodePoint(c);
}
}
private sXMLDeclName(): void {
const c = this.captureTo(XML_DECL_NAME_TERMINATOR);
// The question mark character is not valid inside any of the XML
// declaration name/value pairs.
if (c === QUESTION) {
this.state = S_XML_DECL_ENDING;
this.name += this.text;
this.text = "";
this.fail("XML declaration is incomplete.");
return;
}
if (!(isS(c) || c === EQUAL)) {
return;
}
this.name += this.text;
this.text = "";
if (!this.xmlDeclExpects.includes(this.name)) {
switch (this.name.length) {
case 0:
this.fail("did not expect any more name/value pairs.");
break;
case 1:
this.fail(`expected the name ${this.xmlDeclExpects[0]}.`);
break;
default:
this.fail(`expected one of ${this.xmlDeclExpects.join(", ")}`);
}
}
this.state = c === EQUAL ? S_XML_DECL_VALUE_START : S_XML_DECL_EQ;
}
private sXMLDeclEq(): void {
const c = this.getCodeNorm();
// The question mark character is not valid inside any of the XML
// declaration name/value pairs.
if (c === QUESTION) {
this.state = S_XML_DECL_ENDING;
this.fail("XML declaration is incomplete.");
return;
}
if (isS(c)) {
return;
}
if (c !== EQUAL) {
this.fail("value required.");
}
this.state = S_XML_DECL_VALUE_START;
}
private sXMLDeclValueStart(): void {
const c = this.getCodeNorm();
// The question mark character is not valid inside any of the XML
// declaration name/value pairs.
if (c === QUESTION) {
this.state = S_XML_DECL_ENDING;
this.fail("XML declaration is incomplete.");
return;
}
if (isS(c)) {
return;
}
if (!isQuote(c)) {
this.fail("value must be quoted.");
this.q = SPACE;
}
else {
this.q = c;
}
this.state = S_XML_DECL_VALUE;
}
private sXMLDeclValue(): void {
const c = this.captureTo([this.q!, QUESTION]);
// The question mark character is not valid inside any of the XML
// declaration name/value pairs.
if (c === QUESTION) {
this.state = S_XML_DECL_ENDING;
this.text = "";
this.fail("XML declaration is incomplete.");
return;
}
if (c === EOC) {
return;
}
const value = this.text;
this.text = "";
switch (this.name) {
case "version": {
this.xmlDeclExpects = ["encoding", "standalone"];
const version = value;
this.xmlDecl.version = version;
// This is the test specified by XML 1.0 but it is fine for XML 1.1.
if (!/^1\.[0-9]+$/.test(version)) {
this.fail("version number must match /^1\\.[0-9]+$/.");
}
// When forceXMLVersion is set, the XML declaration is ignored.
else if (!(this.opt.forceXMLVersion as boolean)) {
this.setXMLVersion(version);
}
break;
}
case "encoding":
if (!/^[A-Za-z][A-Za-z0-9._-]*$/.test(value)) {
this.fail("encoding value must match \
/^[A-Za-z0-9][A-Za-z0-9._-]*$/.");
}
this.xmlDeclExpects = ["standalone"];
this.xmlDecl.encoding = value;
break;
case "standalone":
if (value !== "yes" && value !== "no") {
this.fail("standalone value must match \"yes\" or \"no\".");
}
this.xmlDeclExpects = [];
this.xmlDecl.standalone = value;
break;
default:
// We don't need to raise an error here since we've already raised one
// when checking what name was expected.
}
this.name = "";
this.state = S_XML_DECL_SEPARATOR;
}
private sXMLDeclSeparator(): void {
const c = this.getCodeNorm();
// The question mark character is not valid inside any of the XML
// declaration name/value pairs.
if (c === QUESTION) {
// It is valid to go to S_XML_DECL_ENDING from this state.
this.state = S_XML_DECL_ENDING;
return;
}
if (!isS(c)) {
this.fail("whitespace required.");
this.unget();
}
this.state = S_XML_DECL_NAME_START;
}
private sXMLDeclEnding(): void {
const c = this.getCodeNorm();
if (c === GREATER) {
if (this.piTarget !== "xml") {
this.fail("processing instructions are not allowed before root.");
}
else if (this.name !== "version" &&
this.xmlDeclExpects.includes("version")) {
this.fail("XML declaration must contain a version.");
}
this.xmldeclHandler?.(this.xmlDecl);
this.name = "";
this.piTarget = this.text = "";
this.state = S_TEXT;
}
else {
// We got here because the previous character was a ?, but the question
// mark character is not valid inside any of the XML declaration
// name/value pairs.
this.fail(
"The character ? is disallowed anywhere in XML declarations.");
}
this.xmlDeclPossible = false;
}
private sOpenTag(): void {
const c = this.captureNameChars();
if (c === EOC) {
return;
}
const tag: SaxesTagIncomplete = this.tag = {
name: this.name,
attributes: Object.create(null) as Record<string, string>,
};
this.name = "";
if (this.xmlnsOpt) {
this.topNS = tag.ns = Object.create(null) as Record<string, string>;
}
this.openTagStartHandler?.(tag as StartTagForOptions<O>);
this.sawRoot = true;
if (!this.fragmentOpt && this.closedRoot) {
this.fail("documents may contain only one root.");
}
switch (c) {
case GREATER:
this.openTag();
break;
case FORWARD_SLASH:
this.state = S_OPEN_TAG_SLASH;
break;
default:
if (!isS(c)) {
this.fail("disallowed character in tag name.");
}
this.state = S_ATTRIB;
}
}
private sOpenTagSlash(): void {
if (this.getCode() === GREATER) {
this.openSelfClosingTag();
}
else {
this.fail("forward-slash in opening tag not followed by >.");
this.state = S_ATTRIB;
}
}
private sAttrib(): void {
const c = this.skipSpaces();
if (c === EOC) {
return;
}
if (isNameStartChar(c)) {
this.unget();
this.state = S_ATTRIB_NAME;
}
else if (c === GREATER) {
this.openTag();
}
else if (c === FORWARD_SLASH) {
this.state = S_OPEN_TAG_SLASH;
}
else {
this.fail("disallowed character in attribute name.");
}
}
private sAttribName(): void {
const c = this.captureNameChars();
if (c === EQUAL) {
this.state = S_ATTRIB_VALUE;
}
else if (isS(c)) {
this.state = S_ATTRIB_NAME_SAW_WHITE;
}
else if (c === GREATER) {
this.fail("attribute without value.");
this.pushAttrib(this.name, this.name);
this.name = this.text = "";
this.openTag();
}
else if (c !== EOC) {
this.fail("disallowed character in attribute name.");
}
}
private sAttribNameSawWhite(): void {
const c = this.skipSpaces();
switch (c) {
case EOC:
return;
case EQUAL:
this.state = S_ATTRIB_VALUE;
break;
default:
this.fail("attribute without value.");
// Should we do this???
// this.tag.attributes[this.name] = "";
this.text = "";
this.name = "";
if (c === GREATER) {
this.openTag();
}
else if (isNameStartChar(c)) {
this.unget();
this.state = S_ATTRIB_NAME;
}
else {
this.fail("disallowed character in attribute name.");
this.state = S_ATTRIB;
}
}
}
private sAttribValue(): void {
const c = this.getCodeNorm();
if (isQuote(c)) {
this.q = c;
this.state = S_ATTRIB_VALUE_QUOTED;
}
else if (!isS(c)) {
this.fail("unquoted attribute value.");
this.state = S_ATTRIB_VALUE_UNQUOTED;
this.unget();
}
}
private sAttribValueQuoted(): void {
// We deliberately do not use captureTo here. The specialized code we use
// here is faster than using captureTo.
const { q, chunk } = this;
let { i: start } = this;
// eslint-disable-next-line no-constant-condition
while (true) {
switch (this.getCode()) {
case q:
this.pushAttrib(this.name,
this.text + chunk.slice(start, this.prevI));
this.name = this.text = "";
this.q = null;
this.state = S_ATTRIB_VALUE_CLOSED;
return;
case AMP:
this.text += chunk.slice(start, this.prevI);
this.state = S_ENTITY;
this.entityReturnState = S_ATTRIB_VALUE_QUOTED;
return;
case NL:
case NL_LIKE:
case TAB:
this.text += `${chunk.slice(start, this.prevI)} `;
start = this.i;
break;
case LESS:
this.text += chunk.slice(start, this.prevI);
this.fail("disallowed character.");
return;
case EOC:
this.text += chunk.slice(start);
return;
default:
}
}
}
private sAttribValueClosed(): void {
const c = this.getCodeNorm();
if (isS(c)) {
this.state = S_ATTRIB;
}
else if (c === GREATER) {
this.openTag();
}
else if (c === FORWARD_SLASH) {
this.state = S_OPEN_TAG_SLASH;
}
else if (isNameStartChar(c)) {
this.fail("no whitespace between attributes.");
this.unget();
this.state = S_ATTRIB_NAME;
}
else {
this.fail("disallowed character in attribute name.");
}
}
private sAttribValueUnquoted(): void {
// We don't do anything regarding EOL or space handling for unquoted
// attributes. We already have failed by the time we get here, and the
// contract that saxes upholds states that upon failure, it is not safe to
// rely on the data passed to event handlers (other than
// ``onerror``). Passing "bad" data is not a problem.
const c = this.captureTo(ATTRIB_VALUE_UNQUOTED_TERMINATOR);
switch (c) {
case AMP:
this.state = S_ENTITY;
this.entityReturnState = S_ATTRIB_VALUE_UNQUOTED;
break;
case LESS:
this.fail("disallowed character.");
break;
case EOC:
break;
default:
if (this.text.includes("]]>")) {
this.fail("the string \"]]>\" is disallowed in char data.");
}
this.pushAttrib(this.name, this.text);
this.name = this.text = "";
if (c === GREATER) {
this.openTag();
}
else {
this.state = S_ATTRIB;
}
}
}
private sCloseTag(): void {
const c = this.captureNameChars();
if (c === GREATER) {
this.closeTag();
}
else if (isS(c)) {
this.state = S_CLOSE_TAG_SAW_WHITE;
}
else if (c !== EOC) {
this.fail("disallowed character in closing tag.");
}
}
private sCloseTagSawWhite(): void {
switch (this.skipSpaces()) {
case GREATER:
this.closeTag();
break;
case EOC:
break;
default:
this.fail("disallowed character in closing tag.");
}
}
// END OF STATE ENGINE METHODS
private handleTextInRoot(): void {
// This is essentially a specialized version of captureTo which is optimized
// for performing the ]]> check. A previous version of this code, checked
// ``this.text`` for the presence of ]]>. It simplified the code but was
// very costly when character data contained a lot of entities to be parsed.
//
// Since we are using a specialized loop, we also keep track of the presence
// of ]]> in text data. The sequence ]]> is forbidden to appear as-is.
//
let { i: start, forbiddenState } = this;
const { chunk, textHandler: handler } = this;
// eslint-disable-next-line no-labels, no-restricted-syntax
scanLoop:
// eslint-disable-next-line no-constant-condition
while (true) {
switch (this.getCode()) {
case LESS: {
this.state = S_OPEN_WAKA;
if (handler !== undefined) {
const { text } = this;
const slice = chunk.slice(start, this.prevI);
if (text.length !== 0) {
handler(text + slice);
this.text = "";
}
else if (slice.length !== 0) {
handler(slice);
}
}
forbiddenState = FORBIDDEN_START;
// eslint-disable-next-line no-labels
break scanLoop;
}
case AMP:
this.state = S_ENTITY;
this.entityReturnState = S_TEXT;
if (handler !== undefined) {
this.text += chunk.slice(start, this.prevI);
}
forbiddenState = FORBIDDEN_START;
// eslint-disable-next-line no-labels
break scanLoop;
case CLOSE_BRACKET:
switch (forbiddenState) {
case FORBIDDEN_START:
forbiddenState = FORBIDDEN_BRACKET;
break;
case FORBIDDEN_BRACKET:
forbiddenState = FORBIDDEN_BRACKET_BRACKET;
break;
case FORBIDDEN_BRACKET_BRACKET:
break;
default:
throw new Error("impossible state");
}
break;
case GREATER:
if (forbiddenState === FORBIDDEN_BRACKET_BRACKET) {
this.fail("the string \"]]>\" is disallowed in char data.");
}
forbiddenState = FORBIDDEN_START;
break;
case NL_LIKE:
if (handler !== undefined) {
this.text += `${chunk.slice(start, this.prevI)}\n`;
}
start = this.i;
forbiddenState = FORBIDDEN_START;
break;
case EOC:
if (handler !== undefined) {
this.text += chunk.slice(start);
}
// eslint-disable-next-line no-labels
break scanLoop;
default:
forbiddenState = FORBIDDEN_START;
}
}
this.forbiddenState = forbiddenState;
}
private handleTextOutsideRoot(): void {
// This is essentially a specialized version of captureTo which is optimized
// for a specialized task. We keep track of the presence of non-space
// characters in the text since these are errors when appearing outside the
// document root element.
let { i: start } = this;
const { chunk, textHandler: handler } = this;
let nonSpace = false;
// eslint-disable-next-line no-labels, no-restricted-syntax
outRootLoop:
// eslint-disable-next-line no-constant-condition
while (true) {
const code = this.getCode();
switch (code) {
case LESS: {
this.state = S_OPEN_WAKA;
if (handler !== undefined) {
const { text } = this;
const slice = chunk.slice(start, this.prevI);
if (text.length !== 0) {
handler(text + slice);
this.text = "";
}
else if (slice.length !== 0) {
handler(slice);
}
}
// eslint-disable-next-line no-labels
break outRootLoop;
}
case AMP:
this.state = S_ENTITY;
this.entityReturnState = S_TEXT;
if (handler !== undefined) {
this.text += chunk.slice(start, this.prevI);
}
nonSpace = true;
// eslint-disable-next-line no-labels
break outRootLoop;
case NL_LIKE:
if (handler !== undefined) {
this.text += `${chunk.slice(start, this.prevI)}\n`;
}
start = this.i;
break;
case EOC:
if (handler !== undefined) {
this.text += chunk.slice(start);
}
// eslint-disable-next-line no-labels
break outRootLoop;
default:
if (!isS(code)) {
nonSpace = true;
}
}
}
if (!nonSpace) {
return;
}
// We use the reportedTextBeforeRoot and reportedTextAfterRoot flags
// to avoid reporting errors for every single character that is out of
// place.
if (!this.sawRoot && !this.reportedTextBeforeRoot) {
this.fail("text data outside of root node.");
this.reportedTextBeforeRoot = true;
}
if (this.closedRoot && !this.reportedTextAfterRoot) {
this.fail("text data outside of root node.");
this.reportedTextAfterRoot = true;
}
}
private pushAttribNS(name: string, value: string): void {
const { prefix, local } = this.qname(name);
const attr = { name, prefix, local, value };
this.attribList.push(attr);
this.attributeHandler?.(attr as AttributeEventForOptions<O>);
if (prefix === "xmlns") {
const trimmed = value.trim();
if (this.currentXMLVersion === "1.0" && trimmed === "") {
this.fail("invalid attempt to undefine prefix in XML 1.0");
}
this.topNS![local] = trimmed;
nsPairCheck(this, local, trimmed);
}
else if (name === "xmlns") {
const trimmed = value.trim();
this.topNS![""] = trimmed;
nsPairCheck(this, "", trimmed);
}
}
private pushAttribPlain(name: string, value: string): void {
const attr = { name, value };
this.attribList.push(attr);
this.attributeHandler?.(attr as AttributeEventForOptions<O>);
}
/**
* End parsing. This performs final well-formedness checks and resets the
* parser to a clean state.
*
* @returns this
*/
private end(): this {
if (!this.sawRoot) {
this.fail("document must contain a root element.");
}
const { tags } = this;
while (tags.length > 0) {
const tag = tags.pop()!;
this.fail(`unclosed tag: ${tag.name}`);
}
if ((this.state !== S_BEGIN) && (this.state !== S_TEXT)) {
this.fail("unexpected end.");
}
const { text } = this;
if (text.length !== 0) {
this.textHandler?.(text);
this.text = "";
}
this._closed = true;
this.endHandler?.();
this._init();
return this;
}
/**
* Resolve a namespace prefix.
*
* @param prefix The prefix to resolve.
*
* @returns The namespace URI or ``undefined`` if the prefix is not defined.
*/
resolve(prefix: string): string | undefined {
let uri = this.topNS![prefix];
if (uri !== undefined) {
return uri;
}
const { tags } = this;
for (let index = tags.length - 1; index >= 0; index--) {
uri = tags[index]!.ns![prefix];
if (uri !== undefined) {
return uri;
}
}
uri = this.ns[prefix];
if (uri !== undefined) {
return uri;
}
return this.opt.resolvePrefix?.(prefix);
}
/**
* Parse a qname into its prefix and local name parts.
*
* @param name The name to parse
*
* @returns
*/
private qname(name: string): { prefix: string; local: string } {
// This is faster than using name.split(":").
const colon = name.indexOf(":");
if (colon === -1) {
return { prefix: "", local: name };
}
const local = name.slice(colon + 1);
const prefix = name.slice(0, colon);
if (prefix === "" || local === "" || local.includes(":")) {
this.fail(`malformed name: ${name}.`);
}
return { prefix, local };
}
private processAttribsNS(): void {
const { attribList } = this;
const tag = this.tag!;
{
// add namespace info to tag
const { prefix, local } = this.qname(tag.name);
tag.prefix = prefix;
tag.local = local;
const uri = tag.uri = this.resolve(prefix) ?? "";
if (prefix !== "") {
if (prefix === "xmlns") {
this.fail("tags may not have \"xmlns\" as prefix.");
}
if (uri === "") {
this.fail(`unbound namespace prefix: ${JSON.stringify(prefix)}.`);
tag.uri = prefix;
}
}
}
if (attribList.length === 0) {
return;
}
const { attributes } = tag;
const seen = new Set();
// Note: do not apply default ns to attributes:
// http://www.w3.org/TR/REC-xml-names/#defaulting
for (const attr of attribList as SaxesAttributeNSIncomplete[]) {
const { name, prefix, local } = attr;
let uri;
let eqname;
if (prefix === "") {
uri = name === "xmlns" ? XMLNS_NAMESPACE : "";
eqname = name;
}
else {
uri = this.resolve(prefix);
// if there's any attributes with an undefined namespace,
// then fail on them now.
if (uri === undefined) {
this.fail(`unbound namespace prefix: ${JSON.stringify(prefix)}.`);
uri = prefix;
}
eqname = `{${uri}}${local}`;
}
if (seen.has(eqname)) {
this.fail(`duplicate attribute: ${eqname}.`);
}
seen.add(eqname);
attr.uri = uri;
attributes[name] = attr;
}
this.attribList = [];
}
private processAttribsPlain(): void {
const { attribList } = this;
// eslint-disable-next-line prefer-destructuring
const attributes = this.tag!.attributes;
for (const { name, value } of attribList) {
if (attributes[name] !== undefined) {
this.fail(`duplicate attribute: ${name}.`);
}
attributes[name] = value;
}
this.attribList = [];
}
/**
* Handle a complete open tag. This parser code calls this once it has seen
* the whole tag. This method checks for well-formeness and then emits
* ``onopentag``.
*/
private openTag(): void {
this.processAttribs();
const { tags } = this;
const tag = this.tag as SaxesTag;
tag.isSelfClosing = false;
// There cannot be any pending text here due to the onopentagstart that was
// necessarily emitted before we get here. So we do not check text.
this.openTagHandler?.(tag as TagForOptions<O>);
tags.push(tag);
this.state = S_TEXT;
this.name = "";
}
/**
* Handle a complete self-closing tag. This parser code calls this once it has
* seen the whole tag. This method checks for well-formeness and then emits
* ``onopentag`` and ``onclosetag``.
*/
private openSelfClosingTag(): void {
this.processAttribs();
const { tags } = this;
const tag = this.tag as SaxesTag;
tag.isSelfClosing = true;
// There cannot be any pending text here due to the onopentagstart that was
// necessarily emitted before we get here. So we do not check text.
this.openTagHandler?.(tag as TagForOptions<O>);
this.closeTagHandler?.(tag as TagForOptions<O>);
const top = this.tag = tags[tags.length - 1] ?? null;
if (top === null) {
this.closedRoot = true;
}
this.state = S_TEXT;
this.name = "";
}
/**
* Handle a complete close tag. This parser code calls this once it has seen
* the whole tag. This method checks for well-formeness and then emits
* ``onclosetag``.
*/
private closeTag(): void {
const { tags, name } = this;
// Our state after this will be S_TEXT, no matter what, and we can clear
// tagName now.
this.state = S_TEXT;
this.name = "";
if (name === "") {
this.fail("weird empty close tag.");
this.text += "</>";
return;
}
const handler = this.closeTagHandler;
let l = tags.length;
while (l-- > 0) {
const tag = this.tag = tags.pop() as SaxesTag;
this.topNS = tag.ns!;
handler?.(tag as TagForOptions<O>);
if (tag.name === name) {
break;
}
this.fail("unexpected close tag.");
}
if (l === 0) {
this.closedRoot = true;
}
else if (l < 0) {
this.fail(`unmatched closing tag: ${name}.`);
this.text += `</${name}>`;
}
}
/**
* Resolves an entity. Makes any necessary well-formedness checks.
*
* @param entity The entity to resolve.
*
* @returns The parsed entity.
*/
private parseEntity(entity: string): string {
// startsWith would be significantly slower for this test.
if (entity[0] !== "#") {
const defined = this.ENTITIES[entity];
if (defined !== undefined) {
return defined;
}
this.fail(this.isName(entity) ? "undefined entity." :
"disallowed character in entity name.");
return `&${entity};`;
}
let num = NaN;
if (entity[1] === "x" && /^#x[0-9a-f]+$/i.test(entity)) {
num = parseInt(entity.slice(2), 16);
}
else if (/^#[0-9]+$/.test(entity)) {
num = parseInt(entity.slice(1), 10);
}
// The character reference is required to match the CHAR production.
if (!this.isChar(num)) {
this.fail("malformed character entity.");
return `&${entity};`;
}
return String.fromCodePoint(num);
}
} |
1,133 | fn(parser: SaxesParser): void {
parser.write("<unbound:root/>");
} | class SaxesParser<O extends SaxesOptions = {}> {
private readonly fragmentOpt: boolean;
private readonly xmlnsOpt: boolean;
private readonly trackPosition: boolean;
private readonly fileName?: string;
private readonly nameStartCheck: (c: number) => boolean;
private readonly nameCheck: (c: number) => boolean;
private readonly isName: (name: string) => boolean;
private readonly ns!: Record<string, string>;
private openWakaBang!: string;
private text!: string;
private name!: string;
private piTarget!: string;
private entity!: string;
private q!: null | number;
private tags!: SaxesTagIncomplete[];
private tag!: SaxesTagIncomplete | null;
private topNS!: Record<string, string> | null;
private chunk!: string;
private chunkPosition!: number;
private i!: number;
//
// We use prevI to allow "ungetting" the previously read code point. Note
// however, that it is not safe to unget everything and anything. In
// particular ungetting EOL characters will screw positioning up.
//
// Practically, you must not unget a code which has any side effect beyond
// updating ``this.i`` and ``this.prevI``. Only EOL codes have such side
// effects.
//
private prevI!: number;
private carriedFromPrevious?: string;
private forbiddenState!: number;
private attribList!: (SaxesAttributeNSIncomplete | SaxesAttributePlain)[];
private state!: number;
private reportedTextBeforeRoot!: boolean;
private reportedTextAfterRoot!: boolean;
private closedRoot!: boolean;
private sawRoot!: boolean;
private xmlDeclPossible!: boolean;
private xmlDeclExpects!: string[];
private entityReturnState?: number;
private processAttribs!: (this: this) => void;
private positionAtNewLine!: number;
private doctype!: boolean;
private getCode!: () => number;
private isChar!: (c: number) => boolean;
private pushAttrib!: (name: string, value: string) => void;
private _closed!: boolean;
private currentXMLVersion!: string;
private readonly stateTable: ((this: SaxesParser<O>) => void)[];
private xmldeclHandler?: XMLDeclHandler;
private textHandler?: TextHandler;
private piHandler?: PIHandler;
private doctypeHandler?: DoctypeHandler;
private commentHandler?: CommentHandler;
private openTagStartHandler?: OpenTagStartHandler<O>;
private openTagHandler?: OpenTagHandler<O>;
private closeTagHandler?: CloseTagHandler<O>;
private cdataHandler?: CDataHandler;
private errorHandler?: ErrorHandler;
private endHandler?: EndHandler;
private readyHandler?: ReadyHandler;
private attributeHandler?: AttributeHandler<O>;
/**
* Indicates whether or not the parser is closed. If ``true``, wait for
* the ``ready`` event to write again.
*/
get closed(): boolean {
return this._closed;
}
readonly opt: SaxesOptions;
/**
* The XML declaration for this document.
*/
xmlDecl!: XMLDecl;
/**
* The line number of the next character to be read by the parser. This field
* is one-based. (The first line is numbered 1.)
*/
line!: number;
/**
* The column number of the next character to be read by the parser. *
* This field is zero-based. (The first column is 0.)
*
* This field counts columns by *Unicode character*. Note that this *can*
* be different from the index of the character in a JavaScript string due
* to how JavaScript handles astral plane characters.
*
* See [[columnIndex]] for a number that corresponds to the JavaScript index.
*/
column!: number;
/**
* A map of entity name to expansion.
*/
ENTITIES!: Record<string, string>;
/**
* @param opt The parser options.
*/
constructor(opt?: O) {
this.opt = opt ?? {};
this.fragmentOpt = !!(this.opt.fragment as boolean);
const xmlnsOpt = this.xmlnsOpt = !!(this.opt.xmlns as boolean);
this.trackPosition = this.opt.position !== false;
this.fileName = this.opt.fileName;
if (xmlnsOpt) {
// This is the function we use to perform name checks on PIs and entities.
// When namespaces are used, colons are not allowed in PI target names or
// entity names. So the check depends on whether namespaces are used. See:
//
// https://www.w3.org/XML/xml-names-19990114-errata.html
// NE08
//
this.nameStartCheck = isNCNameStartChar;
this.nameCheck = isNCNameChar;
this.isName = isNCName;
// eslint-disable-next-line @typescript-eslint/unbound-method
this.processAttribs = this.processAttribsNS;
// eslint-disable-next-line @typescript-eslint/unbound-method
this.pushAttrib = this.pushAttribNS;
// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-assignment
this.ns = { __proto__: null as any, ...rootNS };
const additional = this.opt.additionalNamespaces;
if (additional != null) {
nsMappingCheck(this, additional);
Object.assign(this.ns, additional);
}
}
else {
this.nameStartCheck = isNameStartChar;
this.nameCheck = isNameChar;
this.isName = isName;
// eslint-disable-next-line @typescript-eslint/unbound-method
this.processAttribs = this.processAttribsPlain;
// eslint-disable-next-line @typescript-eslint/unbound-method
this.pushAttrib = this.pushAttribPlain;
}
//
// The order of the members in this table needs to correspond to the state
// numbers given to the states that correspond to the methods being recorded
// here.
//
this.stateTable = [
/* eslint-disable @typescript-eslint/unbound-method */
this.sBegin,
this.sBeginWhitespace,
this.sDoctype,
this.sDoctypeQuote,
this.sDTD,
this.sDTDQuoted,
this.sDTDOpenWaka,
this.sDTDOpenWakaBang,
this.sDTDComment,
this.sDTDCommentEnding,
this.sDTDCommentEnded,
this.sDTDPI,
this.sDTDPIEnding,
this.sText,
this.sEntity,
this.sOpenWaka,
this.sOpenWakaBang,
this.sComment,
this.sCommentEnding,
this.sCommentEnded,
this.sCData,
this.sCDataEnding,
this.sCDataEnding2,
this.sPIFirstChar,
this.sPIRest,
this.sPIBody,
this.sPIEnding,
this.sXMLDeclNameStart,
this.sXMLDeclName,
this.sXMLDeclEq,
this.sXMLDeclValueStart,
this.sXMLDeclValue,
this.sXMLDeclSeparator,
this.sXMLDeclEnding,
this.sOpenTag,
this.sOpenTagSlash,
this.sAttrib,
this.sAttribName,
this.sAttribNameSawWhite,
this.sAttribValue,
this.sAttribValueQuoted,
this.sAttribValueClosed,
this.sAttribValueUnquoted,
this.sCloseTag,
this.sCloseTagSawWhite,
/* eslint-enable @typescript-eslint/unbound-method */
];
this._init();
}
_init(): void {
this.openWakaBang = "";
this.text = "";
this.name = "";
this.piTarget = "";
this.entity = "";
this.q = null;
this.tags = [];
this.tag = null;
this.topNS = null;
this.chunk = "";
this.chunkPosition = 0;
this.i = 0;
this.prevI = 0;
this.carriedFromPrevious = undefined;
this.forbiddenState = FORBIDDEN_START;
this.attribList = [];
// The logic is organized so as to minimize the need to check
// this.opt.fragment while parsing.
const { fragmentOpt } = this;
this.state = fragmentOpt ? S_TEXT : S_BEGIN;
// We want these to be all true if we are dealing with a fragment.
this.reportedTextBeforeRoot = this.reportedTextAfterRoot = this.closedRoot =
this.sawRoot = fragmentOpt;
// An XML declaration is intially possible only when parsing whole
// documents.
this.xmlDeclPossible = !fragmentOpt;
this.xmlDeclExpects = ["version"];
this.entityReturnState = undefined;
let { defaultXMLVersion } = this.opt;
if (defaultXMLVersion === undefined) {
if (this.opt.forceXMLVersion === true) {
throw new Error("forceXMLVersion set but defaultXMLVersion is not set");
}
defaultXMLVersion = "1.0";
}
this.setXMLVersion(defaultXMLVersion);
this.positionAtNewLine = 0;
this.doctype = false;
this._closed = false;
this.xmlDecl = {
version: undefined,
encoding: undefined,
standalone: undefined,
};
this.line = 1;
this.column = 0;
this.ENTITIES = Object.create(XML_ENTITIES) as Record<string, string>;
this.readyHandler?.();
}
/**
* The stream position the parser is currently looking at. This field is
* zero-based.
*
* This field is not based on counting Unicode characters but is to be
* interpreted as a plain index into a JavaScript string.
*/
get position(): number {
return this.chunkPosition + this.i;
}
/**
* The column number of the next character to be read by the parser. *
* This field is zero-based. (The first column in a line is 0.)
*
* This field reports the index at which the next character would be in the
* line if the line were represented as a JavaScript string. Note that this
* *can* be different to a count based on the number of *Unicode characters*
* due to how JavaScript handles astral plane characters.
*
* See [[column]] for a number that corresponds to a count of Unicode
* characters.
*/
get columnIndex(): number {
return this.position - this.positionAtNewLine;
}
/**
* Set an event listener on an event. The parser supports one handler per
* event type. If you try to set an event handler over an existing handler,
* the old handler is silently overwritten.
*
* @param name The event to listen to.
*
* @param handler The handler to set.
*/
on<N extends EventName>(name: N, handler: EventNameToHandler<O, N>): void {
// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-member-access
(this as any)[EVENT_NAME_TO_HANDLER_NAME[name]] = handler;
}
/**
* Unset an event handler.
*
* @parma name The event to stop listening to.
*/
off(name: EventName): void {
// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-member-access
(this as any)[EVENT_NAME_TO_HANDLER_NAME[name]] = undefined;
}
/**
* Make an error object. The error object will have a message that contains
* the ``fileName`` option passed at the creation of the parser. If position
* tracking was turned on, it will also have line and column number
* information.
*
* @param message The message describing the error to report.
*
* @returns An error object with a properly formatted message.
*/
makeError(message: string): Error {
let msg = this.fileName ?? "";
if (this.trackPosition) {
if (msg.length > 0) {
msg += ":";
}
msg += `${this.line}:${this.column}`;
}
if (msg.length > 0) {
msg += ": ";
}
return new Error(msg + message);
}
/**
* Report a parsing error. This method is made public so that client code may
* check for issues that are outside the scope of this project and can report
* errors.
*
* @param message The error to report.
*
* @returns this
*/
fail(message: string): this {
const err = this.makeError(message);
const handler = this.errorHandler;
if (handler === undefined) {
throw err;
}
else {
handler(err);
}
return this;
}
/**
* Write a XML data to the parser.
*
* @param chunk The XML data to write.
*
* @returns this
*/
// We do need object for the type here. Yes, it often causes problems
// but not in this case.
write(chunk: string | object | null): this {
if (this.closed) {
return this.fail("cannot write after close; assign an onready handler.");
}
let end = false;
if (chunk === null) {
// We cannot return immediately because carriedFromPrevious may need
// processing.
end = true;
chunk = "";
}
else if (typeof chunk === "object") {
chunk = chunk.toString();
}
// We checked if performing a pre-decomposition of the string into an array
// of single complete characters (``Array.from(chunk)``) would be faster
// than the current repeated calls to ``charCodeAt``. As of August 2018, it
// isn't. (There may be Node-specific code that would perform faster than
// ``Array.from`` but don't want to be dependent on Node.)
if (this.carriedFromPrevious !== undefined) {
// The previous chunk had char we must carry over.
chunk = `${this.carriedFromPrevious}${chunk}`;
this.carriedFromPrevious = undefined;
}
let limit = chunk.length;
const lastCode = chunk.charCodeAt(limit - 1);
if (!end &&
// A trailing CR or surrogate must be carried over to the next
// chunk.
(lastCode === CR || (lastCode >= 0xD800 && lastCode <= 0xDBFF))) {
// The chunk ends with a character that must be carried over. We cannot
// know how to handle it until we get the next chunk or the end of the
// stream. So save it for later.
this.carriedFromPrevious = chunk[limit - 1];
limit--;
chunk = chunk.slice(0, limit);
}
const { stateTable } = this;
this.chunk = chunk;
this.i = 0;
while (this.i < limit) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-argument
stateTable[this.state].call(this as any);
}
this.chunkPosition += limit;
return end ? this.end() : this;
}
/**
* Close the current stream. Perform final well-formedness checks and reset
* the parser tstate.
*
* @returns this
*/
close(): this {
return this.write(null);
}
/**
* Get a single code point out of the current chunk. This updates the current
* position if we do position tracking.
*
* This is the algorithm to use for XML 1.0.
*
* @returns The character read.
*/
private getCode10(): number {
const { chunk, i } = this;
this.prevI = i;
// Yes, we do this instead of doing this.i++. Doing it this way, we do not
// read this.i again, which is a bit faster.
this.i = i + 1;
if (i >= chunk.length) {
return EOC;
}
// Using charCodeAt and handling the surrogates ourselves is faster
// than using codePointAt.
const code = chunk.charCodeAt(i);
this.column++;
if (code < 0xD800) {
if (code >= SPACE || code === TAB) {
return code;
}
switch (code) {
case NL:
this.line++;
this.column = 0;
this.positionAtNewLine = this.position;
return NL;
case CR:
// We may get NaN if we read past the end of the chunk, which is fine.
if (chunk.charCodeAt(i + 1) === NL) {
// A \r\n sequence is converted to \n so we have to skip over the
// next character. We already know it has a size of 1 so ++ is fine
// here.
this.i = i + 2;
}
// Otherwise, a \r is just converted to \n, so we don't have to skip
// ahead.
// In either case, \r becomes \n.
this.line++;
this.column = 0;
this.positionAtNewLine = this.position;
return NL_LIKE;
default:
// If we get here, then code < SPACE and it is not NL CR or TAB.
this.fail("disallowed character.");
return code;
}
}
if (code > 0xDBFF) {
// This is a specialized version of isChar10 that takes into account
// that in this context code > 0xDBFF and code <= 0xFFFF. So it does not
// test cases that don't need testing.
if (!(code >= 0xE000 && code <= 0xFFFD)) {
this.fail("disallowed character.");
}
return code;
}
const final = 0x10000 + ((code - 0xD800) * 0x400) +
(chunk.charCodeAt(i + 1) - 0xDC00);
this.i = i + 2;
// This is a specialized version of isChar10 that takes into account that in
// this context necessarily final >= 0x10000.
if (final > 0x10FFFF) {
this.fail("disallowed character.");
}
return final;
}
/**
* Get a single code point out of the current chunk. This updates the current
* position if we do position tracking.
*
* This is the algorithm to use for XML 1.1.
*
* @returns {number} The character read.
*/
private getCode11(): number {
const { chunk, i } = this;
this.prevI = i;
// Yes, we do this instead of doing this.i++. Doing it this way, we do not
// read this.i again, which is a bit faster.
this.i = i + 1;
if (i >= chunk.length) {
return EOC;
}
// Using charCodeAt and handling the surrogates ourselves is faster
// than using codePointAt.
const code = chunk.charCodeAt(i);
this.column++;
if (code < 0xD800) {
if ((code > 0x1F && code < 0x7F) || (code > 0x9F && code !== LS) ||
code === TAB) {
return code;
}
switch (code) {
case NL: // 0xA
this.line++;
this.column = 0;
this.positionAtNewLine = this.position;
return NL;
case CR: { // 0xD
// We may get NaN if we read past the end of the chunk, which is
// fine.
const next = chunk.charCodeAt(i + 1);
if (next === NL || next === NEL) {
// A CR NL or CR NEL sequence is converted to NL so we have to skip
// over the next character. We already know it has a size of 1.
this.i = i + 2;
}
// Otherwise, a CR is just converted to NL, no skip.
}
/* yes, fall through */
case NEL: // 0x85
case LS: // Ox2028
this.line++;
this.column = 0;
this.positionAtNewLine = this.position;
return NL_LIKE;
default:
this.fail("disallowed character.");
return code;
}
}
if (code > 0xDBFF) {
// This is a specialized version of isCharAndNotRestricted that takes into
// account that in this context code > 0xDBFF and code <= 0xFFFF. So it
// does not test cases that don't need testing.
if (!(code >= 0xE000 && code <= 0xFFFD)) {
this.fail("disallowed character.");
}
return code;
}
const final = 0x10000 + ((code - 0xD800) * 0x400) +
(chunk.charCodeAt(i + 1) - 0xDC00);
this.i = i + 2;
// This is a specialized version of isCharAndNotRestricted that takes into
// account that in this context necessarily final >= 0x10000.
if (final > 0x10FFFF) {
this.fail("disallowed character.");
}
return final;
}
/**
* Like ``getCode`` but with the return value normalized so that ``NL`` is
* returned for ``NL_LIKE``.
*/
private getCodeNorm(): number {
const c = this.getCode();
return c === NL_LIKE ? NL : c;
}
private unget(): void {
this.i = this.prevI;
this.column--;
}
/**
* Capture characters into a buffer until encountering one of a set of
* characters.
*
* @param chars An array of codepoints. Encountering a character in the array
* ends the capture. (``chars`` may safely contain ``NL``.)
*
* @return The character code that made the capture end, or ``EOC`` if we hit
* the end of the chunk. The return value cannot be NL_LIKE: NL is returned
* instead.
*/
private captureTo(chars: number[]): number {
let { i: start } = this;
const { chunk } = this;
// eslint-disable-next-line no-constant-condition
while (true) {
const c = this.getCode();
const isNLLike = c === NL_LIKE;
const final = isNLLike ? NL : c;
if (final === EOC || chars.includes(final)) {
this.text += chunk.slice(start, this.prevI);
return final;
}
if (isNLLike) {
this.text += `${chunk.slice(start, this.prevI)}\n`;
start = this.i;
}
}
}
/**
* Capture characters into a buffer until encountering a character.
*
* @param char The codepoint that ends the capture. **NOTE ``char`` MAY NOT
* CONTAIN ``NL``.** Passing ``NL`` will result in buggy behavior.
*
* @return ``true`` if we ran into the character. Otherwise, we ran into the
* end of the current chunk.
*/
private captureToChar(char: number): boolean {
let { i: start } = this;
const { chunk } = this;
// eslint-disable-next-line no-constant-condition
while (true) {
let c = this.getCode();
switch (c) {
case NL_LIKE:
this.text += `${chunk.slice(start, this.prevI)}\n`;
start = this.i;
c = NL;
break;
case EOC:
this.text += chunk.slice(start);
return false;
default:
}
if (c === char) {
this.text += chunk.slice(start, this.prevI);
return true;
}
}
}
/**
* Capture characters that satisfy ``isNameChar`` into the ``name`` field of
* this parser.
*
* @return The character code that made the test fail, or ``EOC`` if we hit
* the end of the chunk. The return value cannot be NL_LIKE: NL is returned
* instead.
*/
private captureNameChars(): number {
const { chunk, i: start } = this;
// eslint-disable-next-line no-constant-condition
while (true) {
const c = this.getCode();
if (c === EOC) {
this.name += chunk.slice(start);
return EOC;
}
// NL is not a name char so we don't have to test specifically for it.
if (!isNameChar(c)) {
this.name += chunk.slice(start, this.prevI);
return c === NL_LIKE ? NL : c;
}
}
}
/**
* Skip white spaces.
*
* @return The character that ended the skip, or ``EOC`` if we hit
* the end of the chunk. The return value cannot be NL_LIKE: NL is returned
* instead.
*/
private skipSpaces(): number {
// eslint-disable-next-line no-constant-condition
while (true) {
const c = this.getCodeNorm();
if (c === EOC || !isS(c)) {
return c;
}
}
}
private setXMLVersion(version: string): void {
this.currentXMLVersion = version;
/* eslint-disable @typescript-eslint/unbound-method */
if (version === "1.0") {
this.isChar = isChar10;
this.getCode = this.getCode10;
}
else {
this.isChar = isChar11;
this.getCode = this.getCode11;
}
/* eslint-enable @typescript-eslint/unbound-method */
}
// STATE ENGINE METHODS
// This needs to be a state separate from S_BEGIN_WHITESPACE because we want
// to be sure never to come back to this state later.
private sBegin(): void {
// We are essentially peeking at the first character of the chunk. Since
// S_BEGIN can be in effect only when we start working on the first chunk,
// the index at which we must look is necessarily 0. Note also that the
// following test does not depend on decoding surrogates.
// If the initial character is 0xFEFF, ignore it.
if (this.chunk.charCodeAt(0) === 0xFEFF) {
this.i++;
this.column++;
}
this.state = S_BEGIN_WHITESPACE;
}
private sBeginWhitespace(): void {
// We need to know whether we've encountered spaces or not because as soon
// as we run into a space, an XML declaration is no longer possible. Rather
// than slow down skipSpaces even in places where we don't care whether it
// skipped anything or not, we check whether prevI is equal to the value of
// i from before we skip spaces.
const iBefore = this.i;
const c = this.skipSpaces();
if (this.prevI !== iBefore) {
this.xmlDeclPossible = false;
}
switch (c) {
case LESS:
this.state = S_OPEN_WAKA;
// We could naively call closeText but in this state, it is not normal
// to have text be filled with any data.
if (this.text.length !== 0) {
throw new Error("no-empty text at start");
}
break;
case EOC:
break;
default:
this.unget();
this.state = S_TEXT;
this.xmlDeclPossible = false;
}
}
private sDoctype(): void {
const c = this.captureTo(DOCTYPE_TERMINATOR);
switch (c) {
case GREATER: {
this.doctypeHandler?.(this.text);
this.text = "";
this.state = S_TEXT;
this.doctype = true; // just remember that we saw it.
break;
}
case EOC:
break;
default:
this.text += String.fromCodePoint(c);
if (c === OPEN_BRACKET) {
this.state = S_DTD;
}
else if (isQuote(c)) {
this.state = S_DOCTYPE_QUOTE;
this.q = c;
}
}
}
private sDoctypeQuote(): void {
const q = this.q!;
if (this.captureToChar(q)) {
this.text += String.fromCodePoint(q);
this.q = null;
this.state = S_DOCTYPE;
}
}
private sDTD(): void {
const c = this.captureTo(DTD_TERMINATOR);
if (c === EOC) {
return;
}
this.text += String.fromCodePoint(c);
if (c === CLOSE_BRACKET) {
this.state = S_DOCTYPE;
}
else if (c === LESS) {
this.state = S_DTD_OPEN_WAKA;
}
else if (isQuote(c)) {
this.state = S_DTD_QUOTED;
this.q = c;
}
}
private sDTDQuoted(): void {
const q = this.q!;
if (this.captureToChar(q)) {
this.text += String.fromCodePoint(q);
this.state = S_DTD;
this.q = null;
}
}
private sDTDOpenWaka(): void {
const c = this.getCodeNorm();
this.text += String.fromCodePoint(c);
switch (c) {
case BANG:
this.state = S_DTD_OPEN_WAKA_BANG;
this.openWakaBang = "";
break;
case QUESTION:
this.state = S_DTD_PI;
break;
default:
this.state = S_DTD;
}
}
private sDTDOpenWakaBang(): void {
const char = String.fromCodePoint(this.getCodeNorm());
const owb = this.openWakaBang += char;
this.text += char;
if (owb !== "-") {
this.state = owb === "--" ? S_DTD_COMMENT : S_DTD;
this.openWakaBang = "";
}
}
private sDTDComment(): void {
if (this.captureToChar(MINUS)) {
this.text += "-";
this.state = S_DTD_COMMENT_ENDING;
}
}
private sDTDCommentEnding(): void {
const c = this.getCodeNorm();
this.text += String.fromCodePoint(c);
this.state = c === MINUS ? S_DTD_COMMENT_ENDED : S_DTD_COMMENT;
}
private sDTDCommentEnded(): void {
const c = this.getCodeNorm();
this.text += String.fromCodePoint(c);
if (c === GREATER) {
this.state = S_DTD;
}
else {
this.fail("malformed comment.");
// <!-- blah -- bloo --> will be recorded as
// a comment of " blah -- bloo "
this.state = S_DTD_COMMENT;
}
}
private sDTDPI(): void {
if (this.captureToChar(QUESTION)) {
this.text += "?";
this.state = S_DTD_PI_ENDING;
}
}
private sDTDPIEnding(): void {
const c = this.getCodeNorm();
this.text += String.fromCodePoint(c);
if (c === GREATER) {
this.state = S_DTD;
}
}
private sText(): void {
//
// We did try a version of saxes where the S_TEXT state was split in two
// states: one for text inside the root element, and one for text
// outside. This was avoiding having to test this.tags.length to decide
// what implementation to actually use.
//
// Peformance testing on gigabyte-size files did not show any advantage to
// using the two states solution instead of the current one. Conversely, it
// made the code a bit more complicated elsewhere. For instance, a comment
// can appear before the root element so when a comment ended it was
// necessary to determine whether to return to the S_TEXT state or to the
// new text-outside-root state.
//
if (this.tags.length !== 0) {
this.handleTextInRoot();
}
else {
this.handleTextOutsideRoot();
}
}
private sEntity(): void {
// This is essentially a specialized version of captureToChar(SEMICOLON...)
let { i: start } = this;
const { chunk } = this;
// eslint-disable-next-line no-labels, no-restricted-syntax
loop:
// eslint-disable-next-line no-constant-condition
while (true) {
switch (this.getCode()) {
case NL_LIKE:
this.entity += `${chunk.slice(start, this.prevI)}\n`;
start = this.i;
break;
case SEMICOLON: {
const { entityReturnState } = this;
const entity = this.entity + chunk.slice(start, this.prevI);
this.state = entityReturnState!;
let parsed: string;
if (entity === "") {
this.fail("empty entity name.");
parsed = "&;";
}
else {
parsed = this.parseEntity(entity);
this.entity = "";
}
if (entityReturnState !== S_TEXT || this.textHandler !== undefined) {
this.text += parsed;
}
// eslint-disable-next-line no-labels
break loop;
}
case EOC:
this.entity += chunk.slice(start);
// eslint-disable-next-line no-labels
break loop;
default:
}
}
}
private sOpenWaka(): void {
// Reminder: a state handler is called with at least one character
// available in the current chunk. So the first call to get code inside of
// a state handler cannot return ``EOC``. That's why we don't test
// for it.
const c = this.getCode();
// either a /, ?, !, or text is coming next.
if (isNameStartChar(c)) {
this.state = S_OPEN_TAG;
this.unget();
this.xmlDeclPossible = false;
}
else {
switch (c) {
case FORWARD_SLASH:
this.state = S_CLOSE_TAG;
this.xmlDeclPossible = false;
break;
case BANG:
this.state = S_OPEN_WAKA_BANG;
this.openWakaBang = "";
this.xmlDeclPossible = false;
break;
case QUESTION:
this.state = S_PI_FIRST_CHAR;
break;
default:
this.fail("disallowed character in tag name");
this.state = S_TEXT;
this.xmlDeclPossible = false;
}
}
}
private sOpenWakaBang(): void {
this.openWakaBang += String.fromCodePoint(this.getCodeNorm());
switch (this.openWakaBang) {
case "[CDATA[":
if (!this.sawRoot && !this.reportedTextBeforeRoot) {
this.fail("text data outside of root node.");
this.reportedTextBeforeRoot = true;
}
if (this.closedRoot && !this.reportedTextAfterRoot) {
this.fail("text data outside of root node.");
this.reportedTextAfterRoot = true;
}
this.state = S_CDATA;
this.openWakaBang = "";
break;
case "--":
this.state = S_COMMENT;
this.openWakaBang = "";
break;
case "DOCTYPE":
this.state = S_DOCTYPE;
if (this.doctype || this.sawRoot) {
this.fail("inappropriately located doctype declaration.");
}
this.openWakaBang = "";
break;
default:
// 7 happens to be the maximum length of the string that can possibly
// match one of the cases above.
if (this.openWakaBang.length >= 7) {
this.fail("incorrect syntax.");
}
}
}
private sComment(): void {
if (this.captureToChar(MINUS)) {
this.state = S_COMMENT_ENDING;
}
}
private sCommentEnding(): void {
const c = this.getCodeNorm();
if (c === MINUS) {
this.state = S_COMMENT_ENDED;
this.commentHandler?.(this.text);
this.text = "";
}
else {
this.text += `-${String.fromCodePoint(c)}`;
this.state = S_COMMENT;
}
}
private sCommentEnded(): void {
const c = this.getCodeNorm();
if (c !== GREATER) {
this.fail("malformed comment.");
// <!-- blah -- bloo --> will be recorded as
// a comment of " blah -- bloo "
this.text += `--${String.fromCodePoint(c)}`;
this.state = S_COMMENT;
}
else {
this.state = S_TEXT;
}
}
private sCData(): void {
if (this.captureToChar(CLOSE_BRACKET)) {
this.state = S_CDATA_ENDING;
}
}
private sCDataEnding(): void {
const c = this.getCodeNorm();
if (c === CLOSE_BRACKET) {
this.state = S_CDATA_ENDING_2;
}
else {
this.text += `]${String.fromCodePoint(c)}`;
this.state = S_CDATA;
}
}
private sCDataEnding2(): void {
const c = this.getCodeNorm();
switch (c) {
case GREATER: {
this.cdataHandler?.(this.text);
this.text = "";
this.state = S_TEXT;
break;
}
case CLOSE_BRACKET:
this.text += "]";
break;
default:
this.text += `]]${String.fromCodePoint(c)}`;
this.state = S_CDATA;
}
}
// We need this separate state to check the first character fo the pi target
// with this.nameStartCheck which allows less characters than this.nameCheck.
private sPIFirstChar(): void {
const c = this.getCodeNorm();
// This is first because in the case where the file is well-formed this is
// the branch taken. We optimize for well-formedness.
if (this.nameStartCheck(c)) {
this.piTarget += String.fromCodePoint(c);
this.state = S_PI_REST;
}
else if (c === QUESTION || isS(c)) {
this.fail("processing instruction without a target.");
this.state = c === QUESTION ? S_PI_ENDING : S_PI_BODY;
}
else {
this.fail("disallowed character in processing instruction name.");
this.piTarget += String.fromCodePoint(c);
this.state = S_PI_REST;
}
}
private sPIRest(): void {
// Capture characters into a piTarget while ``this.nameCheck`` run on the
// character read returns true.
const { chunk, i: start } = this;
// eslint-disable-next-line no-constant-condition
while (true) {
const c = this.getCodeNorm();
if (c === EOC) {
this.piTarget += chunk.slice(start);
return;
}
// NL cannot satisfy this.nameCheck so we don't have to test specifically
// for it.
if (!this.nameCheck(c)) {
this.piTarget += chunk.slice(start, this.prevI);
const isQuestion = c === QUESTION;
if (isQuestion || isS(c)) {
if (this.piTarget === "xml") {
if (!this.xmlDeclPossible) {
this.fail(
"an XML declaration must be at the start of the document.");
}
this.state = isQuestion ? S_XML_DECL_ENDING : S_XML_DECL_NAME_START;
}
else {
this.state = isQuestion ? S_PI_ENDING : S_PI_BODY;
}
}
else {
this.fail("disallowed character in processing instruction name.");
this.piTarget += String.fromCodePoint(c);
}
break;
}
}
}
private sPIBody(): void {
if (this.text.length === 0) {
const c = this.getCodeNorm();
if (c === QUESTION) {
this.state = S_PI_ENDING;
}
else if (!isS(c)) {
this.text = String.fromCodePoint(c);
}
}
// The question mark character is not valid inside any of the XML
// declaration name/value pairs.
else if (this.captureToChar(QUESTION)) {
this.state = S_PI_ENDING;
}
}
private sPIEnding(): void {
const c = this.getCodeNorm();
if (c === GREATER) {
const { piTarget } = this;
if (piTarget.toLowerCase() === "xml") {
this.fail(
"the XML declaration must appear at the start of the document.");
}
this.piHandler?.({
target: piTarget,
body: this.text,
});
this.piTarget = this.text = "";
this.state = S_TEXT;
}
else if (c === QUESTION) {
// We ran into ?? as part of a processing instruction. We initially took
// the first ? as a sign that the PI was ending, but it is not. So we have
// to add it to the body but we take the new ? as a sign that the PI is
// ending.
this.text += "?";
}
else {
this.text += `?${String.fromCodePoint(c)}`;
this.state = S_PI_BODY;
}
this.xmlDeclPossible = false;
}
private sXMLDeclNameStart(): void {
const c = this.skipSpaces();
// The question mark character is not valid inside any of the XML
// declaration name/value pairs.
if (c === QUESTION) {
// It is valid to go to S_XML_DECL_ENDING from this state.
this.state = S_XML_DECL_ENDING;
return;
}
if (c !== EOC) {
this.state = S_XML_DECL_NAME;
this.name = String.fromCodePoint(c);
}
}
private sXMLDeclName(): void {
const c = this.captureTo(XML_DECL_NAME_TERMINATOR);
// The question mark character is not valid inside any of the XML
// declaration name/value pairs.
if (c === QUESTION) {
this.state = S_XML_DECL_ENDING;
this.name += this.text;
this.text = "";
this.fail("XML declaration is incomplete.");
return;
}
if (!(isS(c) || c === EQUAL)) {
return;
}
this.name += this.text;
this.text = "";
if (!this.xmlDeclExpects.includes(this.name)) {
switch (this.name.length) {
case 0:
this.fail("did not expect any more name/value pairs.");
break;
case 1:
this.fail(`expected the name ${this.xmlDeclExpects[0]}.`);
break;
default:
this.fail(`expected one of ${this.xmlDeclExpects.join(", ")}`);
}
}
this.state = c === EQUAL ? S_XML_DECL_VALUE_START : S_XML_DECL_EQ;
}
private sXMLDeclEq(): void {
const c = this.getCodeNorm();
// The question mark character is not valid inside any of the XML
// declaration name/value pairs.
if (c === QUESTION) {
this.state = S_XML_DECL_ENDING;
this.fail("XML declaration is incomplete.");
return;
}
if (isS(c)) {
return;
}
if (c !== EQUAL) {
this.fail("value required.");
}
this.state = S_XML_DECL_VALUE_START;
}
private sXMLDeclValueStart(): void {
const c = this.getCodeNorm();
// The question mark character is not valid inside any of the XML
// declaration name/value pairs.
if (c === QUESTION) {
this.state = S_XML_DECL_ENDING;
this.fail("XML declaration is incomplete.");
return;
}
if (isS(c)) {
return;
}
if (!isQuote(c)) {
this.fail("value must be quoted.");
this.q = SPACE;
}
else {
this.q = c;
}
this.state = S_XML_DECL_VALUE;
}
private sXMLDeclValue(): void {
const c = this.captureTo([this.q!, QUESTION]);
// The question mark character is not valid inside any of the XML
// declaration name/value pairs.
if (c === QUESTION) {
this.state = S_XML_DECL_ENDING;
this.text = "";
this.fail("XML declaration is incomplete.");
return;
}
if (c === EOC) {
return;
}
const value = this.text;
this.text = "";
switch (this.name) {
case "version": {
this.xmlDeclExpects = ["encoding", "standalone"];
const version = value;
this.xmlDecl.version = version;
// This is the test specified by XML 1.0 but it is fine for XML 1.1.
if (!/^1\.[0-9]+$/.test(version)) {
this.fail("version number must match /^1\\.[0-9]+$/.");
}
// When forceXMLVersion is set, the XML declaration is ignored.
else if (!(this.opt.forceXMLVersion as boolean)) {
this.setXMLVersion(version);
}
break;
}
case "encoding":
if (!/^[A-Za-z][A-Za-z0-9._-]*$/.test(value)) {
this.fail("encoding value must match \
/^[A-Za-z0-9][A-Za-z0-9._-]*$/.");
}
this.xmlDeclExpects = ["standalone"];
this.xmlDecl.encoding = value;
break;
case "standalone":
if (value !== "yes" && value !== "no") {
this.fail("standalone value must match \"yes\" or \"no\".");
}
this.xmlDeclExpects = [];
this.xmlDecl.standalone = value;
break;
default:
// We don't need to raise an error here since we've already raised one
// when checking what name was expected.
}
this.name = "";
this.state = S_XML_DECL_SEPARATOR;
}
private sXMLDeclSeparator(): void {
const c = this.getCodeNorm();
// The question mark character is not valid inside any of the XML
// declaration name/value pairs.
if (c === QUESTION) {
// It is valid to go to S_XML_DECL_ENDING from this state.
this.state = S_XML_DECL_ENDING;
return;
}
if (!isS(c)) {
this.fail("whitespace required.");
this.unget();
}
this.state = S_XML_DECL_NAME_START;
}
private sXMLDeclEnding(): void {
const c = this.getCodeNorm();
if (c === GREATER) {
if (this.piTarget !== "xml") {
this.fail("processing instructions are not allowed before root.");
}
else if (this.name !== "version" &&
this.xmlDeclExpects.includes("version")) {
this.fail("XML declaration must contain a version.");
}
this.xmldeclHandler?.(this.xmlDecl);
this.name = "";
this.piTarget = this.text = "";
this.state = S_TEXT;
}
else {
// We got here because the previous character was a ?, but the question
// mark character is not valid inside any of the XML declaration
// name/value pairs.
this.fail(
"The character ? is disallowed anywhere in XML declarations.");
}
this.xmlDeclPossible = false;
}
private sOpenTag(): void {
const c = this.captureNameChars();
if (c === EOC) {
return;
}
const tag: SaxesTagIncomplete = this.tag = {
name: this.name,
attributes: Object.create(null) as Record<string, string>,
};
this.name = "";
if (this.xmlnsOpt) {
this.topNS = tag.ns = Object.create(null) as Record<string, string>;
}
this.openTagStartHandler?.(tag as StartTagForOptions<O>);
this.sawRoot = true;
if (!this.fragmentOpt && this.closedRoot) {
this.fail("documents may contain only one root.");
}
switch (c) {
case GREATER:
this.openTag();
break;
case FORWARD_SLASH:
this.state = S_OPEN_TAG_SLASH;
break;
default:
if (!isS(c)) {
this.fail("disallowed character in tag name.");
}
this.state = S_ATTRIB;
}
}
private sOpenTagSlash(): void {
if (this.getCode() === GREATER) {
this.openSelfClosingTag();
}
else {
this.fail("forward-slash in opening tag not followed by >.");
this.state = S_ATTRIB;
}
}
private sAttrib(): void {
const c = this.skipSpaces();
if (c === EOC) {
return;
}
if (isNameStartChar(c)) {
this.unget();
this.state = S_ATTRIB_NAME;
}
else if (c === GREATER) {
this.openTag();
}
else if (c === FORWARD_SLASH) {
this.state = S_OPEN_TAG_SLASH;
}
else {
this.fail("disallowed character in attribute name.");
}
}
private sAttribName(): void {
const c = this.captureNameChars();
if (c === EQUAL) {
this.state = S_ATTRIB_VALUE;
}
else if (isS(c)) {
this.state = S_ATTRIB_NAME_SAW_WHITE;
}
else if (c === GREATER) {
this.fail("attribute without value.");
this.pushAttrib(this.name, this.name);
this.name = this.text = "";
this.openTag();
}
else if (c !== EOC) {
this.fail("disallowed character in attribute name.");
}
}
private sAttribNameSawWhite(): void {
const c = this.skipSpaces();
switch (c) {
case EOC:
return;
case EQUAL:
this.state = S_ATTRIB_VALUE;
break;
default:
this.fail("attribute without value.");
// Should we do this???
// this.tag.attributes[this.name] = "";
this.text = "";
this.name = "";
if (c === GREATER) {
this.openTag();
}
else if (isNameStartChar(c)) {
this.unget();
this.state = S_ATTRIB_NAME;
}
else {
this.fail("disallowed character in attribute name.");
this.state = S_ATTRIB;
}
}
}
private sAttribValue(): void {
const c = this.getCodeNorm();
if (isQuote(c)) {
this.q = c;
this.state = S_ATTRIB_VALUE_QUOTED;
}
else if (!isS(c)) {
this.fail("unquoted attribute value.");
this.state = S_ATTRIB_VALUE_UNQUOTED;
this.unget();
}
}
private sAttribValueQuoted(): void {
// We deliberately do not use captureTo here. The specialized code we use
// here is faster than using captureTo.
const { q, chunk } = this;
let { i: start } = this;
// eslint-disable-next-line no-constant-condition
while (true) {
switch (this.getCode()) {
case q:
this.pushAttrib(this.name,
this.text + chunk.slice(start, this.prevI));
this.name = this.text = "";
this.q = null;
this.state = S_ATTRIB_VALUE_CLOSED;
return;
case AMP:
this.text += chunk.slice(start, this.prevI);
this.state = S_ENTITY;
this.entityReturnState = S_ATTRIB_VALUE_QUOTED;
return;
case NL:
case NL_LIKE:
case TAB:
this.text += `${chunk.slice(start, this.prevI)} `;
start = this.i;
break;
case LESS:
this.text += chunk.slice(start, this.prevI);
this.fail("disallowed character.");
return;
case EOC:
this.text += chunk.slice(start);
return;
default:
}
}
}
private sAttribValueClosed(): void {
const c = this.getCodeNorm();
if (isS(c)) {
this.state = S_ATTRIB;
}
else if (c === GREATER) {
this.openTag();
}
else if (c === FORWARD_SLASH) {
this.state = S_OPEN_TAG_SLASH;
}
else if (isNameStartChar(c)) {
this.fail("no whitespace between attributes.");
this.unget();
this.state = S_ATTRIB_NAME;
}
else {
this.fail("disallowed character in attribute name.");
}
}
private sAttribValueUnquoted(): void {
// We don't do anything regarding EOL or space handling for unquoted
// attributes. We already have failed by the time we get here, and the
// contract that saxes upholds states that upon failure, it is not safe to
// rely on the data passed to event handlers (other than
// ``onerror``). Passing "bad" data is not a problem.
const c = this.captureTo(ATTRIB_VALUE_UNQUOTED_TERMINATOR);
switch (c) {
case AMP:
this.state = S_ENTITY;
this.entityReturnState = S_ATTRIB_VALUE_UNQUOTED;
break;
case LESS:
this.fail("disallowed character.");
break;
case EOC:
break;
default:
if (this.text.includes("]]>")) {
this.fail("the string \"]]>\" is disallowed in char data.");
}
this.pushAttrib(this.name, this.text);
this.name = this.text = "";
if (c === GREATER) {
this.openTag();
}
else {
this.state = S_ATTRIB;
}
}
}
private sCloseTag(): void {
const c = this.captureNameChars();
if (c === GREATER) {
this.closeTag();
}
else if (isS(c)) {
this.state = S_CLOSE_TAG_SAW_WHITE;
}
else if (c !== EOC) {
this.fail("disallowed character in closing tag.");
}
}
private sCloseTagSawWhite(): void {
switch (this.skipSpaces()) {
case GREATER:
this.closeTag();
break;
case EOC:
break;
default:
this.fail("disallowed character in closing tag.");
}
}
// END OF STATE ENGINE METHODS
private handleTextInRoot(): void {
// This is essentially a specialized version of captureTo which is optimized
// for performing the ]]> check. A previous version of this code, checked
// ``this.text`` for the presence of ]]>. It simplified the code but was
// very costly when character data contained a lot of entities to be parsed.
//
// Since we are using a specialized loop, we also keep track of the presence
// of ]]> in text data. The sequence ]]> is forbidden to appear as-is.
//
let { i: start, forbiddenState } = this;
const { chunk, textHandler: handler } = this;
// eslint-disable-next-line no-labels, no-restricted-syntax
scanLoop:
// eslint-disable-next-line no-constant-condition
while (true) {
switch (this.getCode()) {
case LESS: {
this.state = S_OPEN_WAKA;
if (handler !== undefined) {
const { text } = this;
const slice = chunk.slice(start, this.prevI);
if (text.length !== 0) {
handler(text + slice);
this.text = "";
}
else if (slice.length !== 0) {
handler(slice);
}
}
forbiddenState = FORBIDDEN_START;
// eslint-disable-next-line no-labels
break scanLoop;
}
case AMP:
this.state = S_ENTITY;
this.entityReturnState = S_TEXT;
if (handler !== undefined) {
this.text += chunk.slice(start, this.prevI);
}
forbiddenState = FORBIDDEN_START;
// eslint-disable-next-line no-labels
break scanLoop;
case CLOSE_BRACKET:
switch (forbiddenState) {
case FORBIDDEN_START:
forbiddenState = FORBIDDEN_BRACKET;
break;
case FORBIDDEN_BRACKET:
forbiddenState = FORBIDDEN_BRACKET_BRACKET;
break;
case FORBIDDEN_BRACKET_BRACKET:
break;
default:
throw new Error("impossible state");
}
break;
case GREATER:
if (forbiddenState === FORBIDDEN_BRACKET_BRACKET) {
this.fail("the string \"]]>\" is disallowed in char data.");
}
forbiddenState = FORBIDDEN_START;
break;
case NL_LIKE:
if (handler !== undefined) {
this.text += `${chunk.slice(start, this.prevI)}\n`;
}
start = this.i;
forbiddenState = FORBIDDEN_START;
break;
case EOC:
if (handler !== undefined) {
this.text += chunk.slice(start);
}
// eslint-disable-next-line no-labels
break scanLoop;
default:
forbiddenState = FORBIDDEN_START;
}
}
this.forbiddenState = forbiddenState;
}
private handleTextOutsideRoot(): void {
// This is essentially a specialized version of captureTo which is optimized
// for a specialized task. We keep track of the presence of non-space
// characters in the text since these are errors when appearing outside the
// document root element.
let { i: start } = this;
const { chunk, textHandler: handler } = this;
let nonSpace = false;
// eslint-disable-next-line no-labels, no-restricted-syntax
outRootLoop:
// eslint-disable-next-line no-constant-condition
while (true) {
const code = this.getCode();
switch (code) {
case LESS: {
this.state = S_OPEN_WAKA;
if (handler !== undefined) {
const { text } = this;
const slice = chunk.slice(start, this.prevI);
if (text.length !== 0) {
handler(text + slice);
this.text = "";
}
else if (slice.length !== 0) {
handler(slice);
}
}
// eslint-disable-next-line no-labels
break outRootLoop;
}
case AMP:
this.state = S_ENTITY;
this.entityReturnState = S_TEXT;
if (handler !== undefined) {
this.text += chunk.slice(start, this.prevI);
}
nonSpace = true;
// eslint-disable-next-line no-labels
break outRootLoop;
case NL_LIKE:
if (handler !== undefined) {
this.text += `${chunk.slice(start, this.prevI)}\n`;
}
start = this.i;
break;
case EOC:
if (handler !== undefined) {
this.text += chunk.slice(start);
}
// eslint-disable-next-line no-labels
break outRootLoop;
default:
if (!isS(code)) {
nonSpace = true;
}
}
}
if (!nonSpace) {
return;
}
// We use the reportedTextBeforeRoot and reportedTextAfterRoot flags
// to avoid reporting errors for every single character that is out of
// place.
if (!this.sawRoot && !this.reportedTextBeforeRoot) {
this.fail("text data outside of root node.");
this.reportedTextBeforeRoot = true;
}
if (this.closedRoot && !this.reportedTextAfterRoot) {
this.fail("text data outside of root node.");
this.reportedTextAfterRoot = true;
}
}
private pushAttribNS(name: string, value: string): void {
const { prefix, local } = this.qname(name);
const attr = { name, prefix, local, value };
this.attribList.push(attr);
this.attributeHandler?.(attr as AttributeEventForOptions<O>);
if (prefix === "xmlns") {
const trimmed = value.trim();
if (this.currentXMLVersion === "1.0" && trimmed === "") {
this.fail("invalid attempt to undefine prefix in XML 1.0");
}
this.topNS![local] = trimmed;
nsPairCheck(this, local, trimmed);
}
else if (name === "xmlns") {
const trimmed = value.trim();
this.topNS![""] = trimmed;
nsPairCheck(this, "", trimmed);
}
}
private pushAttribPlain(name: string, value: string): void {
const attr = { name, value };
this.attribList.push(attr);
this.attributeHandler?.(attr as AttributeEventForOptions<O>);
}
/**
* End parsing. This performs final well-formedness checks and resets the
* parser to a clean state.
*
* @returns this
*/
private end(): this {
if (!this.sawRoot) {
this.fail("document must contain a root element.");
}
const { tags } = this;
while (tags.length > 0) {
const tag = tags.pop()!;
this.fail(`unclosed tag: ${tag.name}`);
}
if ((this.state !== S_BEGIN) && (this.state !== S_TEXT)) {
this.fail("unexpected end.");
}
const { text } = this;
if (text.length !== 0) {
this.textHandler?.(text);
this.text = "";
}
this._closed = true;
this.endHandler?.();
this._init();
return this;
}
/**
* Resolve a namespace prefix.
*
* @param prefix The prefix to resolve.
*
* @returns The namespace URI or ``undefined`` if the prefix is not defined.
*/
resolve(prefix: string): string | undefined {
let uri = this.topNS![prefix];
if (uri !== undefined) {
return uri;
}
const { tags } = this;
for (let index = tags.length - 1; index >= 0; index--) {
uri = tags[index]!.ns![prefix];
if (uri !== undefined) {
return uri;
}
}
uri = this.ns[prefix];
if (uri !== undefined) {
return uri;
}
return this.opt.resolvePrefix?.(prefix);
}
/**
* Parse a qname into its prefix and local name parts.
*
* @param name The name to parse
*
* @returns
*/
private qname(name: string): { prefix: string; local: string } {
// This is faster than using name.split(":").
const colon = name.indexOf(":");
if (colon === -1) {
return { prefix: "", local: name };
}
const local = name.slice(colon + 1);
const prefix = name.slice(0, colon);
if (prefix === "" || local === "" || local.includes(":")) {
this.fail(`malformed name: ${name}.`);
}
return { prefix, local };
}
private processAttribsNS(): void {
const { attribList } = this;
const tag = this.tag!;
{
// add namespace info to tag
const { prefix, local } = this.qname(tag.name);
tag.prefix = prefix;
tag.local = local;
const uri = tag.uri = this.resolve(prefix) ?? "";
if (prefix !== "") {
if (prefix === "xmlns") {
this.fail("tags may not have \"xmlns\" as prefix.");
}
if (uri === "") {
this.fail(`unbound namespace prefix: ${JSON.stringify(prefix)}.`);
tag.uri = prefix;
}
}
}
if (attribList.length === 0) {
return;
}
const { attributes } = tag;
const seen = new Set();
// Note: do not apply default ns to attributes:
// http://www.w3.org/TR/REC-xml-names/#defaulting
for (const attr of attribList as SaxesAttributeNSIncomplete[]) {
const { name, prefix, local } = attr;
let uri;
let eqname;
if (prefix === "") {
uri = name === "xmlns" ? XMLNS_NAMESPACE : "";
eqname = name;
}
else {
uri = this.resolve(prefix);
// if there's any attributes with an undefined namespace,
// then fail on them now.
if (uri === undefined) {
this.fail(`unbound namespace prefix: ${JSON.stringify(prefix)}.`);
uri = prefix;
}
eqname = `{${uri}}${local}`;
}
if (seen.has(eqname)) {
this.fail(`duplicate attribute: ${eqname}.`);
}
seen.add(eqname);
attr.uri = uri;
attributes[name] = attr;
}
this.attribList = [];
}
private processAttribsPlain(): void {
const { attribList } = this;
// eslint-disable-next-line prefer-destructuring
const attributes = this.tag!.attributes;
for (const { name, value } of attribList) {
if (attributes[name] !== undefined) {
this.fail(`duplicate attribute: ${name}.`);
}
attributes[name] = value;
}
this.attribList = [];
}
/**
* Handle a complete open tag. This parser code calls this once it has seen
* the whole tag. This method checks for well-formeness and then emits
* ``onopentag``.
*/
private openTag(): void {
this.processAttribs();
const { tags } = this;
const tag = this.tag as SaxesTag;
tag.isSelfClosing = false;
// There cannot be any pending text here due to the onopentagstart that was
// necessarily emitted before we get here. So we do not check text.
this.openTagHandler?.(tag as TagForOptions<O>);
tags.push(tag);
this.state = S_TEXT;
this.name = "";
}
/**
* Handle a complete self-closing tag. This parser code calls this once it has
* seen the whole tag. This method checks for well-formeness and then emits
* ``onopentag`` and ``onclosetag``.
*/
private openSelfClosingTag(): void {
this.processAttribs();
const { tags } = this;
const tag = this.tag as SaxesTag;
tag.isSelfClosing = true;
// There cannot be any pending text here due to the onopentagstart that was
// necessarily emitted before we get here. So we do not check text.
this.openTagHandler?.(tag as TagForOptions<O>);
this.closeTagHandler?.(tag as TagForOptions<O>);
const top = this.tag = tags[tags.length - 1] ?? null;
if (top === null) {
this.closedRoot = true;
}
this.state = S_TEXT;
this.name = "";
}
/**
* Handle a complete close tag. This parser code calls this once it has seen
* the whole tag. This method checks for well-formeness and then emits
* ``onclosetag``.
*/
private closeTag(): void {
const { tags, name } = this;
// Our state after this will be S_TEXT, no matter what, and we can clear
// tagName now.
this.state = S_TEXT;
this.name = "";
if (name === "") {
this.fail("weird empty close tag.");
this.text += "</>";
return;
}
const handler = this.closeTagHandler;
let l = tags.length;
while (l-- > 0) {
const tag = this.tag = tags.pop() as SaxesTag;
this.topNS = tag.ns!;
handler?.(tag as TagForOptions<O>);
if (tag.name === name) {
break;
}
this.fail("unexpected close tag.");
}
if (l === 0) {
this.closedRoot = true;
}
else if (l < 0) {
this.fail(`unmatched closing tag: ${name}.`);
this.text += `</${name}>`;
}
}
/**
* Resolves an entity. Makes any necessary well-formedness checks.
*
* @param entity The entity to resolve.
*
* @returns The parsed entity.
*/
private parseEntity(entity: string): string {
// startsWith would be significantly slower for this test.
if (entity[0] !== "#") {
const defined = this.ENTITIES[entity];
if (defined !== undefined) {
return defined;
}
this.fail(this.isName(entity) ? "undefined entity." :
"disallowed character in entity name.");
return `&${entity};`;
}
let num = NaN;
if (entity[1] === "x" && /^#x[0-9a-f]+$/i.test(entity)) {
num = parseInt(entity.slice(2), 16);
}
else if (/^#[0-9]+$/.test(entity)) {
num = parseInt(entity.slice(1), 10);
}
// The character reference is required to match the CHAR production.
if (!this.isChar(num)) {
this.fail("malformed character entity.");
return `&${entity};`;
}
return String.fromCodePoint(num);
}
} |
1,134 | fn(parser: SaxesParser): void {
parser.write("<unbound:root xmlns:unbound=\"someuri\"/>");
} | class SaxesParser<O extends SaxesOptions = {}> {
private readonly fragmentOpt: boolean;
private readonly xmlnsOpt: boolean;
private readonly trackPosition: boolean;
private readonly fileName?: string;
private readonly nameStartCheck: (c: number) => boolean;
private readonly nameCheck: (c: number) => boolean;
private readonly isName: (name: string) => boolean;
private readonly ns!: Record<string, string>;
private openWakaBang!: string;
private text!: string;
private name!: string;
private piTarget!: string;
private entity!: string;
private q!: null | number;
private tags!: SaxesTagIncomplete[];
private tag!: SaxesTagIncomplete | null;
private topNS!: Record<string, string> | null;
private chunk!: string;
private chunkPosition!: number;
private i!: number;
//
// We use prevI to allow "ungetting" the previously read code point. Note
// however, that it is not safe to unget everything and anything. In
// particular ungetting EOL characters will screw positioning up.
//
// Practically, you must not unget a code which has any side effect beyond
// updating ``this.i`` and ``this.prevI``. Only EOL codes have such side
// effects.
//
private prevI!: number;
private carriedFromPrevious?: string;
private forbiddenState!: number;
private attribList!: (SaxesAttributeNSIncomplete | SaxesAttributePlain)[];
private state!: number;
private reportedTextBeforeRoot!: boolean;
private reportedTextAfterRoot!: boolean;
private closedRoot!: boolean;
private sawRoot!: boolean;
private xmlDeclPossible!: boolean;
private xmlDeclExpects!: string[];
private entityReturnState?: number;
private processAttribs!: (this: this) => void;
private positionAtNewLine!: number;
private doctype!: boolean;
private getCode!: () => number;
private isChar!: (c: number) => boolean;
private pushAttrib!: (name: string, value: string) => void;
private _closed!: boolean;
private currentXMLVersion!: string;
private readonly stateTable: ((this: SaxesParser<O>) => void)[];
private xmldeclHandler?: XMLDeclHandler;
private textHandler?: TextHandler;
private piHandler?: PIHandler;
private doctypeHandler?: DoctypeHandler;
private commentHandler?: CommentHandler;
private openTagStartHandler?: OpenTagStartHandler<O>;
private openTagHandler?: OpenTagHandler<O>;
private closeTagHandler?: CloseTagHandler<O>;
private cdataHandler?: CDataHandler;
private errorHandler?: ErrorHandler;
private endHandler?: EndHandler;
private readyHandler?: ReadyHandler;
private attributeHandler?: AttributeHandler<O>;
/**
* Indicates whether or not the parser is closed. If ``true``, wait for
* the ``ready`` event to write again.
*/
get closed(): boolean {
return this._closed;
}
readonly opt: SaxesOptions;
/**
* The XML declaration for this document.
*/
xmlDecl!: XMLDecl;
/**
* The line number of the next character to be read by the parser. This field
* is one-based. (The first line is numbered 1.)
*/
line!: number;
/**
* The column number of the next character to be read by the parser. *
* This field is zero-based. (The first column is 0.)
*
* This field counts columns by *Unicode character*. Note that this *can*
* be different from the index of the character in a JavaScript string due
* to how JavaScript handles astral plane characters.
*
* See [[columnIndex]] for a number that corresponds to the JavaScript index.
*/
column!: number;
/**
* A map of entity name to expansion.
*/
ENTITIES!: Record<string, string>;
/**
* @param opt The parser options.
*/
constructor(opt?: O) {
this.opt = opt ?? {};
this.fragmentOpt = !!(this.opt.fragment as boolean);
const xmlnsOpt = this.xmlnsOpt = !!(this.opt.xmlns as boolean);
this.trackPosition = this.opt.position !== false;
this.fileName = this.opt.fileName;
if (xmlnsOpt) {
// This is the function we use to perform name checks on PIs and entities.
// When namespaces are used, colons are not allowed in PI target names or
// entity names. So the check depends on whether namespaces are used. See:
//
// https://www.w3.org/XML/xml-names-19990114-errata.html
// NE08
//
this.nameStartCheck = isNCNameStartChar;
this.nameCheck = isNCNameChar;
this.isName = isNCName;
// eslint-disable-next-line @typescript-eslint/unbound-method
this.processAttribs = this.processAttribsNS;
// eslint-disable-next-line @typescript-eslint/unbound-method
this.pushAttrib = this.pushAttribNS;
// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-assignment
this.ns = { __proto__: null as any, ...rootNS };
const additional = this.opt.additionalNamespaces;
if (additional != null) {
nsMappingCheck(this, additional);
Object.assign(this.ns, additional);
}
}
else {
this.nameStartCheck = isNameStartChar;
this.nameCheck = isNameChar;
this.isName = isName;
// eslint-disable-next-line @typescript-eslint/unbound-method
this.processAttribs = this.processAttribsPlain;
// eslint-disable-next-line @typescript-eslint/unbound-method
this.pushAttrib = this.pushAttribPlain;
}
//
// The order of the members in this table needs to correspond to the state
// numbers given to the states that correspond to the methods being recorded
// here.
//
this.stateTable = [
/* eslint-disable @typescript-eslint/unbound-method */
this.sBegin,
this.sBeginWhitespace,
this.sDoctype,
this.sDoctypeQuote,
this.sDTD,
this.sDTDQuoted,
this.sDTDOpenWaka,
this.sDTDOpenWakaBang,
this.sDTDComment,
this.sDTDCommentEnding,
this.sDTDCommentEnded,
this.sDTDPI,
this.sDTDPIEnding,
this.sText,
this.sEntity,
this.sOpenWaka,
this.sOpenWakaBang,
this.sComment,
this.sCommentEnding,
this.sCommentEnded,
this.sCData,
this.sCDataEnding,
this.sCDataEnding2,
this.sPIFirstChar,
this.sPIRest,
this.sPIBody,
this.sPIEnding,
this.sXMLDeclNameStart,
this.sXMLDeclName,
this.sXMLDeclEq,
this.sXMLDeclValueStart,
this.sXMLDeclValue,
this.sXMLDeclSeparator,
this.sXMLDeclEnding,
this.sOpenTag,
this.sOpenTagSlash,
this.sAttrib,
this.sAttribName,
this.sAttribNameSawWhite,
this.sAttribValue,
this.sAttribValueQuoted,
this.sAttribValueClosed,
this.sAttribValueUnquoted,
this.sCloseTag,
this.sCloseTagSawWhite,
/* eslint-enable @typescript-eslint/unbound-method */
];
this._init();
}
_init(): void {
this.openWakaBang = "";
this.text = "";
this.name = "";
this.piTarget = "";
this.entity = "";
this.q = null;
this.tags = [];
this.tag = null;
this.topNS = null;
this.chunk = "";
this.chunkPosition = 0;
this.i = 0;
this.prevI = 0;
this.carriedFromPrevious = undefined;
this.forbiddenState = FORBIDDEN_START;
this.attribList = [];
// The logic is organized so as to minimize the need to check
// this.opt.fragment while parsing.
const { fragmentOpt } = this;
this.state = fragmentOpt ? S_TEXT : S_BEGIN;
// We want these to be all true if we are dealing with a fragment.
this.reportedTextBeforeRoot = this.reportedTextAfterRoot = this.closedRoot =
this.sawRoot = fragmentOpt;
// An XML declaration is intially possible only when parsing whole
// documents.
this.xmlDeclPossible = !fragmentOpt;
this.xmlDeclExpects = ["version"];
this.entityReturnState = undefined;
let { defaultXMLVersion } = this.opt;
if (defaultXMLVersion === undefined) {
if (this.opt.forceXMLVersion === true) {
throw new Error("forceXMLVersion set but defaultXMLVersion is not set");
}
defaultXMLVersion = "1.0";
}
this.setXMLVersion(defaultXMLVersion);
this.positionAtNewLine = 0;
this.doctype = false;
this._closed = false;
this.xmlDecl = {
version: undefined,
encoding: undefined,
standalone: undefined,
};
this.line = 1;
this.column = 0;
this.ENTITIES = Object.create(XML_ENTITIES) as Record<string, string>;
this.readyHandler?.();
}
/**
* The stream position the parser is currently looking at. This field is
* zero-based.
*
* This field is not based on counting Unicode characters but is to be
* interpreted as a plain index into a JavaScript string.
*/
get position(): number {
return this.chunkPosition + this.i;
}
/**
* The column number of the next character to be read by the parser. *
* This field is zero-based. (The first column in a line is 0.)
*
* This field reports the index at which the next character would be in the
* line if the line were represented as a JavaScript string. Note that this
* *can* be different to a count based on the number of *Unicode characters*
* due to how JavaScript handles astral plane characters.
*
* See [[column]] for a number that corresponds to a count of Unicode
* characters.
*/
get columnIndex(): number {
return this.position - this.positionAtNewLine;
}
/**
* Set an event listener on an event. The parser supports one handler per
* event type. If you try to set an event handler over an existing handler,
* the old handler is silently overwritten.
*
* @param name The event to listen to.
*
* @param handler The handler to set.
*/
on<N extends EventName>(name: N, handler: EventNameToHandler<O, N>): void {
// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-member-access
(this as any)[EVENT_NAME_TO_HANDLER_NAME[name]] = handler;
}
/**
* Unset an event handler.
*
* @parma name The event to stop listening to.
*/
off(name: EventName): void {
// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-member-access
(this as any)[EVENT_NAME_TO_HANDLER_NAME[name]] = undefined;
}
/**
* Make an error object. The error object will have a message that contains
* the ``fileName`` option passed at the creation of the parser. If position
* tracking was turned on, it will also have line and column number
* information.
*
* @param message The message describing the error to report.
*
* @returns An error object with a properly formatted message.
*/
makeError(message: string): Error {
let msg = this.fileName ?? "";
if (this.trackPosition) {
if (msg.length > 0) {
msg += ":";
}
msg += `${this.line}:${this.column}`;
}
if (msg.length > 0) {
msg += ": ";
}
return new Error(msg + message);
}
/**
* Report a parsing error. This method is made public so that client code may
* check for issues that are outside the scope of this project and can report
* errors.
*
* @param message The error to report.
*
* @returns this
*/
fail(message: string): this {
const err = this.makeError(message);
const handler = this.errorHandler;
if (handler === undefined) {
throw err;
}
else {
handler(err);
}
return this;
}
/**
* Write a XML data to the parser.
*
* @param chunk The XML data to write.
*
* @returns this
*/
// We do need object for the type here. Yes, it often causes problems
// but not in this case.
write(chunk: string | object | null): this {
if (this.closed) {
return this.fail("cannot write after close; assign an onready handler.");
}
let end = false;
if (chunk === null) {
// We cannot return immediately because carriedFromPrevious may need
// processing.
end = true;
chunk = "";
}
else if (typeof chunk === "object") {
chunk = chunk.toString();
}
// We checked if performing a pre-decomposition of the string into an array
// of single complete characters (``Array.from(chunk)``) would be faster
// than the current repeated calls to ``charCodeAt``. As of August 2018, it
// isn't. (There may be Node-specific code that would perform faster than
// ``Array.from`` but don't want to be dependent on Node.)
if (this.carriedFromPrevious !== undefined) {
// The previous chunk had char we must carry over.
chunk = `${this.carriedFromPrevious}${chunk}`;
this.carriedFromPrevious = undefined;
}
let limit = chunk.length;
const lastCode = chunk.charCodeAt(limit - 1);
if (!end &&
// A trailing CR or surrogate must be carried over to the next
// chunk.
(lastCode === CR || (lastCode >= 0xD800 && lastCode <= 0xDBFF))) {
// The chunk ends with a character that must be carried over. We cannot
// know how to handle it until we get the next chunk or the end of the
// stream. So save it for later.
this.carriedFromPrevious = chunk[limit - 1];
limit--;
chunk = chunk.slice(0, limit);
}
const { stateTable } = this;
this.chunk = chunk;
this.i = 0;
while (this.i < limit) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-argument
stateTable[this.state].call(this as any);
}
this.chunkPosition += limit;
return end ? this.end() : this;
}
/**
* Close the current stream. Perform final well-formedness checks and reset
* the parser tstate.
*
* @returns this
*/
close(): this {
return this.write(null);
}
/**
* Get a single code point out of the current chunk. This updates the current
* position if we do position tracking.
*
* This is the algorithm to use for XML 1.0.
*
* @returns The character read.
*/
private getCode10(): number {
const { chunk, i } = this;
this.prevI = i;
// Yes, we do this instead of doing this.i++. Doing it this way, we do not
// read this.i again, which is a bit faster.
this.i = i + 1;
if (i >= chunk.length) {
return EOC;
}
// Using charCodeAt and handling the surrogates ourselves is faster
// than using codePointAt.
const code = chunk.charCodeAt(i);
this.column++;
if (code < 0xD800) {
if (code >= SPACE || code === TAB) {
return code;
}
switch (code) {
case NL:
this.line++;
this.column = 0;
this.positionAtNewLine = this.position;
return NL;
case CR:
// We may get NaN if we read past the end of the chunk, which is fine.
if (chunk.charCodeAt(i + 1) === NL) {
// A \r\n sequence is converted to \n so we have to skip over the
// next character. We already know it has a size of 1 so ++ is fine
// here.
this.i = i + 2;
}
// Otherwise, a \r is just converted to \n, so we don't have to skip
// ahead.
// In either case, \r becomes \n.
this.line++;
this.column = 0;
this.positionAtNewLine = this.position;
return NL_LIKE;
default:
// If we get here, then code < SPACE and it is not NL CR or TAB.
this.fail("disallowed character.");
return code;
}
}
if (code > 0xDBFF) {
// This is a specialized version of isChar10 that takes into account
// that in this context code > 0xDBFF and code <= 0xFFFF. So it does not
// test cases that don't need testing.
if (!(code >= 0xE000 && code <= 0xFFFD)) {
this.fail("disallowed character.");
}
return code;
}
const final = 0x10000 + ((code - 0xD800) * 0x400) +
(chunk.charCodeAt(i + 1) - 0xDC00);
this.i = i + 2;
// This is a specialized version of isChar10 that takes into account that in
// this context necessarily final >= 0x10000.
if (final > 0x10FFFF) {
this.fail("disallowed character.");
}
return final;
}
/**
* Get a single code point out of the current chunk. This updates the current
* position if we do position tracking.
*
* This is the algorithm to use for XML 1.1.
*
* @returns {number} The character read.
*/
private getCode11(): number {
const { chunk, i } = this;
this.prevI = i;
// Yes, we do this instead of doing this.i++. Doing it this way, we do not
// read this.i again, which is a bit faster.
this.i = i + 1;
if (i >= chunk.length) {
return EOC;
}
// Using charCodeAt and handling the surrogates ourselves is faster
// than using codePointAt.
const code = chunk.charCodeAt(i);
this.column++;
if (code < 0xD800) {
if ((code > 0x1F && code < 0x7F) || (code > 0x9F && code !== LS) ||
code === TAB) {
return code;
}
switch (code) {
case NL: // 0xA
this.line++;
this.column = 0;
this.positionAtNewLine = this.position;
return NL;
case CR: { // 0xD
// We may get NaN if we read past the end of the chunk, which is
// fine.
const next = chunk.charCodeAt(i + 1);
if (next === NL || next === NEL) {
// A CR NL or CR NEL sequence is converted to NL so we have to skip
// over the next character. We already know it has a size of 1.
this.i = i + 2;
}
// Otherwise, a CR is just converted to NL, no skip.
}
/* yes, fall through */
case NEL: // 0x85
case LS: // Ox2028
this.line++;
this.column = 0;
this.positionAtNewLine = this.position;
return NL_LIKE;
default:
this.fail("disallowed character.");
return code;
}
}
if (code > 0xDBFF) {
// This is a specialized version of isCharAndNotRestricted that takes into
// account that in this context code > 0xDBFF and code <= 0xFFFF. So it
// does not test cases that don't need testing.
if (!(code >= 0xE000 && code <= 0xFFFD)) {
this.fail("disallowed character.");
}
return code;
}
const final = 0x10000 + ((code - 0xD800) * 0x400) +
(chunk.charCodeAt(i + 1) - 0xDC00);
this.i = i + 2;
// This is a specialized version of isCharAndNotRestricted that takes into
// account that in this context necessarily final >= 0x10000.
if (final > 0x10FFFF) {
this.fail("disallowed character.");
}
return final;
}
/**
* Like ``getCode`` but with the return value normalized so that ``NL`` is
* returned for ``NL_LIKE``.
*/
private getCodeNorm(): number {
const c = this.getCode();
return c === NL_LIKE ? NL : c;
}
private unget(): void {
this.i = this.prevI;
this.column--;
}
/**
* Capture characters into a buffer until encountering one of a set of
* characters.
*
* @param chars An array of codepoints. Encountering a character in the array
* ends the capture. (``chars`` may safely contain ``NL``.)
*
* @return The character code that made the capture end, or ``EOC`` if we hit
* the end of the chunk. The return value cannot be NL_LIKE: NL is returned
* instead.
*/
private captureTo(chars: number[]): number {
let { i: start } = this;
const { chunk } = this;
// eslint-disable-next-line no-constant-condition
while (true) {
const c = this.getCode();
const isNLLike = c === NL_LIKE;
const final = isNLLike ? NL : c;
if (final === EOC || chars.includes(final)) {
this.text += chunk.slice(start, this.prevI);
return final;
}
if (isNLLike) {
this.text += `${chunk.slice(start, this.prevI)}\n`;
start = this.i;
}
}
}
/**
* Capture characters into a buffer until encountering a character.
*
* @param char The codepoint that ends the capture. **NOTE ``char`` MAY NOT
* CONTAIN ``NL``.** Passing ``NL`` will result in buggy behavior.
*
* @return ``true`` if we ran into the character. Otherwise, we ran into the
* end of the current chunk.
*/
private captureToChar(char: number): boolean {
let { i: start } = this;
const { chunk } = this;
// eslint-disable-next-line no-constant-condition
while (true) {
let c = this.getCode();
switch (c) {
case NL_LIKE:
this.text += `${chunk.slice(start, this.prevI)}\n`;
start = this.i;
c = NL;
break;
case EOC:
this.text += chunk.slice(start);
return false;
default:
}
if (c === char) {
this.text += chunk.slice(start, this.prevI);
return true;
}
}
}
/**
* Capture characters that satisfy ``isNameChar`` into the ``name`` field of
* this parser.
*
* @return The character code that made the test fail, or ``EOC`` if we hit
* the end of the chunk. The return value cannot be NL_LIKE: NL is returned
* instead.
*/
private captureNameChars(): number {
const { chunk, i: start } = this;
// eslint-disable-next-line no-constant-condition
while (true) {
const c = this.getCode();
if (c === EOC) {
this.name += chunk.slice(start);
return EOC;
}
// NL is not a name char so we don't have to test specifically for it.
if (!isNameChar(c)) {
this.name += chunk.slice(start, this.prevI);
return c === NL_LIKE ? NL : c;
}
}
}
/**
* Skip white spaces.
*
* @return The character that ended the skip, or ``EOC`` if we hit
* the end of the chunk. The return value cannot be NL_LIKE: NL is returned
* instead.
*/
private skipSpaces(): number {
// eslint-disable-next-line no-constant-condition
while (true) {
const c = this.getCodeNorm();
if (c === EOC || !isS(c)) {
return c;
}
}
}
private setXMLVersion(version: string): void {
this.currentXMLVersion = version;
/* eslint-disable @typescript-eslint/unbound-method */
if (version === "1.0") {
this.isChar = isChar10;
this.getCode = this.getCode10;
}
else {
this.isChar = isChar11;
this.getCode = this.getCode11;
}
/* eslint-enable @typescript-eslint/unbound-method */
}
// STATE ENGINE METHODS
// This needs to be a state separate from S_BEGIN_WHITESPACE because we want
// to be sure never to come back to this state later.
private sBegin(): void {
// We are essentially peeking at the first character of the chunk. Since
// S_BEGIN can be in effect only when we start working on the first chunk,
// the index at which we must look is necessarily 0. Note also that the
// following test does not depend on decoding surrogates.
// If the initial character is 0xFEFF, ignore it.
if (this.chunk.charCodeAt(0) === 0xFEFF) {
this.i++;
this.column++;
}
this.state = S_BEGIN_WHITESPACE;
}
private sBeginWhitespace(): void {
// We need to know whether we've encountered spaces or not because as soon
// as we run into a space, an XML declaration is no longer possible. Rather
// than slow down skipSpaces even in places where we don't care whether it
// skipped anything or not, we check whether prevI is equal to the value of
// i from before we skip spaces.
const iBefore = this.i;
const c = this.skipSpaces();
if (this.prevI !== iBefore) {
this.xmlDeclPossible = false;
}
switch (c) {
case LESS:
this.state = S_OPEN_WAKA;
// We could naively call closeText but in this state, it is not normal
// to have text be filled with any data.
if (this.text.length !== 0) {
throw new Error("no-empty text at start");
}
break;
case EOC:
break;
default:
this.unget();
this.state = S_TEXT;
this.xmlDeclPossible = false;
}
}
private sDoctype(): void {
const c = this.captureTo(DOCTYPE_TERMINATOR);
switch (c) {
case GREATER: {
this.doctypeHandler?.(this.text);
this.text = "";
this.state = S_TEXT;
this.doctype = true; // just remember that we saw it.
break;
}
case EOC:
break;
default:
this.text += String.fromCodePoint(c);
if (c === OPEN_BRACKET) {
this.state = S_DTD;
}
else if (isQuote(c)) {
this.state = S_DOCTYPE_QUOTE;
this.q = c;
}
}
}
private sDoctypeQuote(): void {
const q = this.q!;
if (this.captureToChar(q)) {
this.text += String.fromCodePoint(q);
this.q = null;
this.state = S_DOCTYPE;
}
}
private sDTD(): void {
const c = this.captureTo(DTD_TERMINATOR);
if (c === EOC) {
return;
}
this.text += String.fromCodePoint(c);
if (c === CLOSE_BRACKET) {
this.state = S_DOCTYPE;
}
else if (c === LESS) {
this.state = S_DTD_OPEN_WAKA;
}
else if (isQuote(c)) {
this.state = S_DTD_QUOTED;
this.q = c;
}
}
private sDTDQuoted(): void {
const q = this.q!;
if (this.captureToChar(q)) {
this.text += String.fromCodePoint(q);
this.state = S_DTD;
this.q = null;
}
}
private sDTDOpenWaka(): void {
const c = this.getCodeNorm();
this.text += String.fromCodePoint(c);
switch (c) {
case BANG:
this.state = S_DTD_OPEN_WAKA_BANG;
this.openWakaBang = "";
break;
case QUESTION:
this.state = S_DTD_PI;
break;
default:
this.state = S_DTD;
}
}
private sDTDOpenWakaBang(): void {
const char = String.fromCodePoint(this.getCodeNorm());
const owb = this.openWakaBang += char;
this.text += char;
if (owb !== "-") {
this.state = owb === "--" ? S_DTD_COMMENT : S_DTD;
this.openWakaBang = "";
}
}
private sDTDComment(): void {
if (this.captureToChar(MINUS)) {
this.text += "-";
this.state = S_DTD_COMMENT_ENDING;
}
}
private sDTDCommentEnding(): void {
const c = this.getCodeNorm();
this.text += String.fromCodePoint(c);
this.state = c === MINUS ? S_DTD_COMMENT_ENDED : S_DTD_COMMENT;
}
private sDTDCommentEnded(): void {
const c = this.getCodeNorm();
this.text += String.fromCodePoint(c);
if (c === GREATER) {
this.state = S_DTD;
}
else {
this.fail("malformed comment.");
// <!-- blah -- bloo --> will be recorded as
// a comment of " blah -- bloo "
this.state = S_DTD_COMMENT;
}
}
private sDTDPI(): void {
if (this.captureToChar(QUESTION)) {
this.text += "?";
this.state = S_DTD_PI_ENDING;
}
}
private sDTDPIEnding(): void {
const c = this.getCodeNorm();
this.text += String.fromCodePoint(c);
if (c === GREATER) {
this.state = S_DTD;
}
}
private sText(): void {
//
// We did try a version of saxes where the S_TEXT state was split in two
// states: one for text inside the root element, and one for text
// outside. This was avoiding having to test this.tags.length to decide
// what implementation to actually use.
//
// Peformance testing on gigabyte-size files did not show any advantage to
// using the two states solution instead of the current one. Conversely, it
// made the code a bit more complicated elsewhere. For instance, a comment
// can appear before the root element so when a comment ended it was
// necessary to determine whether to return to the S_TEXT state or to the
// new text-outside-root state.
//
if (this.tags.length !== 0) {
this.handleTextInRoot();
}
else {
this.handleTextOutsideRoot();
}
}
private sEntity(): void {
// This is essentially a specialized version of captureToChar(SEMICOLON...)
let { i: start } = this;
const { chunk } = this;
// eslint-disable-next-line no-labels, no-restricted-syntax
loop:
// eslint-disable-next-line no-constant-condition
while (true) {
switch (this.getCode()) {
case NL_LIKE:
this.entity += `${chunk.slice(start, this.prevI)}\n`;
start = this.i;
break;
case SEMICOLON: {
const { entityReturnState } = this;
const entity = this.entity + chunk.slice(start, this.prevI);
this.state = entityReturnState!;
let parsed: string;
if (entity === "") {
this.fail("empty entity name.");
parsed = "&;";
}
else {
parsed = this.parseEntity(entity);
this.entity = "";
}
if (entityReturnState !== S_TEXT || this.textHandler !== undefined) {
this.text += parsed;
}
// eslint-disable-next-line no-labels
break loop;
}
case EOC:
this.entity += chunk.slice(start);
// eslint-disable-next-line no-labels
break loop;
default:
}
}
}
private sOpenWaka(): void {
// Reminder: a state handler is called with at least one character
// available in the current chunk. So the first call to get code inside of
// a state handler cannot return ``EOC``. That's why we don't test
// for it.
const c = this.getCode();
// either a /, ?, !, or text is coming next.
if (isNameStartChar(c)) {
this.state = S_OPEN_TAG;
this.unget();
this.xmlDeclPossible = false;
}
else {
switch (c) {
case FORWARD_SLASH:
this.state = S_CLOSE_TAG;
this.xmlDeclPossible = false;
break;
case BANG:
this.state = S_OPEN_WAKA_BANG;
this.openWakaBang = "";
this.xmlDeclPossible = false;
break;
case QUESTION:
this.state = S_PI_FIRST_CHAR;
break;
default:
this.fail("disallowed character in tag name");
this.state = S_TEXT;
this.xmlDeclPossible = false;
}
}
}
private sOpenWakaBang(): void {
this.openWakaBang += String.fromCodePoint(this.getCodeNorm());
switch (this.openWakaBang) {
case "[CDATA[":
if (!this.sawRoot && !this.reportedTextBeforeRoot) {
this.fail("text data outside of root node.");
this.reportedTextBeforeRoot = true;
}
if (this.closedRoot && !this.reportedTextAfterRoot) {
this.fail("text data outside of root node.");
this.reportedTextAfterRoot = true;
}
this.state = S_CDATA;
this.openWakaBang = "";
break;
case "--":
this.state = S_COMMENT;
this.openWakaBang = "";
break;
case "DOCTYPE":
this.state = S_DOCTYPE;
if (this.doctype || this.sawRoot) {
this.fail("inappropriately located doctype declaration.");
}
this.openWakaBang = "";
break;
default:
// 7 happens to be the maximum length of the string that can possibly
// match one of the cases above.
if (this.openWakaBang.length >= 7) {
this.fail("incorrect syntax.");
}
}
}
private sComment(): void {
if (this.captureToChar(MINUS)) {
this.state = S_COMMENT_ENDING;
}
}
private sCommentEnding(): void {
const c = this.getCodeNorm();
if (c === MINUS) {
this.state = S_COMMENT_ENDED;
this.commentHandler?.(this.text);
this.text = "";
}
else {
this.text += `-${String.fromCodePoint(c)}`;
this.state = S_COMMENT;
}
}
private sCommentEnded(): void {
const c = this.getCodeNorm();
if (c !== GREATER) {
this.fail("malformed comment.");
// <!-- blah -- bloo --> will be recorded as
// a comment of " blah -- bloo "
this.text += `--${String.fromCodePoint(c)}`;
this.state = S_COMMENT;
}
else {
this.state = S_TEXT;
}
}
private sCData(): void {
if (this.captureToChar(CLOSE_BRACKET)) {
this.state = S_CDATA_ENDING;
}
}
private sCDataEnding(): void {
const c = this.getCodeNorm();
if (c === CLOSE_BRACKET) {
this.state = S_CDATA_ENDING_2;
}
else {
this.text += `]${String.fromCodePoint(c)}`;
this.state = S_CDATA;
}
}
private sCDataEnding2(): void {
const c = this.getCodeNorm();
switch (c) {
case GREATER: {
this.cdataHandler?.(this.text);
this.text = "";
this.state = S_TEXT;
break;
}
case CLOSE_BRACKET:
this.text += "]";
break;
default:
this.text += `]]${String.fromCodePoint(c)}`;
this.state = S_CDATA;
}
}
// We need this separate state to check the first character fo the pi target
// with this.nameStartCheck which allows less characters than this.nameCheck.
private sPIFirstChar(): void {
const c = this.getCodeNorm();
// This is first because in the case where the file is well-formed this is
// the branch taken. We optimize for well-formedness.
if (this.nameStartCheck(c)) {
this.piTarget += String.fromCodePoint(c);
this.state = S_PI_REST;
}
else if (c === QUESTION || isS(c)) {
this.fail("processing instruction without a target.");
this.state = c === QUESTION ? S_PI_ENDING : S_PI_BODY;
}
else {
this.fail("disallowed character in processing instruction name.");
this.piTarget += String.fromCodePoint(c);
this.state = S_PI_REST;
}
}
private sPIRest(): void {
// Capture characters into a piTarget while ``this.nameCheck`` run on the
// character read returns true.
const { chunk, i: start } = this;
// eslint-disable-next-line no-constant-condition
while (true) {
const c = this.getCodeNorm();
if (c === EOC) {
this.piTarget += chunk.slice(start);
return;
}
// NL cannot satisfy this.nameCheck so we don't have to test specifically
// for it.
if (!this.nameCheck(c)) {
this.piTarget += chunk.slice(start, this.prevI);
const isQuestion = c === QUESTION;
if (isQuestion || isS(c)) {
if (this.piTarget === "xml") {
if (!this.xmlDeclPossible) {
this.fail(
"an XML declaration must be at the start of the document.");
}
this.state = isQuestion ? S_XML_DECL_ENDING : S_XML_DECL_NAME_START;
}
else {
this.state = isQuestion ? S_PI_ENDING : S_PI_BODY;
}
}
else {
this.fail("disallowed character in processing instruction name.");
this.piTarget += String.fromCodePoint(c);
}
break;
}
}
}
private sPIBody(): void {
if (this.text.length === 0) {
const c = this.getCodeNorm();
if (c === QUESTION) {
this.state = S_PI_ENDING;
}
else if (!isS(c)) {
this.text = String.fromCodePoint(c);
}
}
// The question mark character is not valid inside any of the XML
// declaration name/value pairs.
else if (this.captureToChar(QUESTION)) {
this.state = S_PI_ENDING;
}
}
private sPIEnding(): void {
const c = this.getCodeNorm();
if (c === GREATER) {
const { piTarget } = this;
if (piTarget.toLowerCase() === "xml") {
this.fail(
"the XML declaration must appear at the start of the document.");
}
this.piHandler?.({
target: piTarget,
body: this.text,
});
this.piTarget = this.text = "";
this.state = S_TEXT;
}
else if (c === QUESTION) {
// We ran into ?? as part of a processing instruction. We initially took
// the first ? as a sign that the PI was ending, but it is not. So we have
// to add it to the body but we take the new ? as a sign that the PI is
// ending.
this.text += "?";
}
else {
this.text += `?${String.fromCodePoint(c)}`;
this.state = S_PI_BODY;
}
this.xmlDeclPossible = false;
}
private sXMLDeclNameStart(): void {
const c = this.skipSpaces();
// The question mark character is not valid inside any of the XML
// declaration name/value pairs.
if (c === QUESTION) {
// It is valid to go to S_XML_DECL_ENDING from this state.
this.state = S_XML_DECL_ENDING;
return;
}
if (c !== EOC) {
this.state = S_XML_DECL_NAME;
this.name = String.fromCodePoint(c);
}
}
private sXMLDeclName(): void {
const c = this.captureTo(XML_DECL_NAME_TERMINATOR);
// The question mark character is not valid inside any of the XML
// declaration name/value pairs.
if (c === QUESTION) {
this.state = S_XML_DECL_ENDING;
this.name += this.text;
this.text = "";
this.fail("XML declaration is incomplete.");
return;
}
if (!(isS(c) || c === EQUAL)) {
return;
}
this.name += this.text;
this.text = "";
if (!this.xmlDeclExpects.includes(this.name)) {
switch (this.name.length) {
case 0:
this.fail("did not expect any more name/value pairs.");
break;
case 1:
this.fail(`expected the name ${this.xmlDeclExpects[0]}.`);
break;
default:
this.fail(`expected one of ${this.xmlDeclExpects.join(", ")}`);
}
}
this.state = c === EQUAL ? S_XML_DECL_VALUE_START : S_XML_DECL_EQ;
}
private sXMLDeclEq(): void {
const c = this.getCodeNorm();
// The question mark character is not valid inside any of the XML
// declaration name/value pairs.
if (c === QUESTION) {
this.state = S_XML_DECL_ENDING;
this.fail("XML declaration is incomplete.");
return;
}
if (isS(c)) {
return;
}
if (c !== EQUAL) {
this.fail("value required.");
}
this.state = S_XML_DECL_VALUE_START;
}
private sXMLDeclValueStart(): void {
const c = this.getCodeNorm();
// The question mark character is not valid inside any of the XML
// declaration name/value pairs.
if (c === QUESTION) {
this.state = S_XML_DECL_ENDING;
this.fail("XML declaration is incomplete.");
return;
}
if (isS(c)) {
return;
}
if (!isQuote(c)) {
this.fail("value must be quoted.");
this.q = SPACE;
}
else {
this.q = c;
}
this.state = S_XML_DECL_VALUE;
}
private sXMLDeclValue(): void {
const c = this.captureTo([this.q!, QUESTION]);
// The question mark character is not valid inside any of the XML
// declaration name/value pairs.
if (c === QUESTION) {
this.state = S_XML_DECL_ENDING;
this.text = "";
this.fail("XML declaration is incomplete.");
return;
}
if (c === EOC) {
return;
}
const value = this.text;
this.text = "";
switch (this.name) {
case "version": {
this.xmlDeclExpects = ["encoding", "standalone"];
const version = value;
this.xmlDecl.version = version;
// This is the test specified by XML 1.0 but it is fine for XML 1.1.
if (!/^1\.[0-9]+$/.test(version)) {
this.fail("version number must match /^1\\.[0-9]+$/.");
}
// When forceXMLVersion is set, the XML declaration is ignored.
else if (!(this.opt.forceXMLVersion as boolean)) {
this.setXMLVersion(version);
}
break;
}
case "encoding":
if (!/^[A-Za-z][A-Za-z0-9._-]*$/.test(value)) {
this.fail("encoding value must match \
/^[A-Za-z0-9][A-Za-z0-9._-]*$/.");
}
this.xmlDeclExpects = ["standalone"];
this.xmlDecl.encoding = value;
break;
case "standalone":
if (value !== "yes" && value !== "no") {
this.fail("standalone value must match \"yes\" or \"no\".");
}
this.xmlDeclExpects = [];
this.xmlDecl.standalone = value;
break;
default:
// We don't need to raise an error here since we've already raised one
// when checking what name was expected.
}
this.name = "";
this.state = S_XML_DECL_SEPARATOR;
}
private sXMLDeclSeparator(): void {
const c = this.getCodeNorm();
// The question mark character is not valid inside any of the XML
// declaration name/value pairs.
if (c === QUESTION) {
// It is valid to go to S_XML_DECL_ENDING from this state.
this.state = S_XML_DECL_ENDING;
return;
}
if (!isS(c)) {
this.fail("whitespace required.");
this.unget();
}
this.state = S_XML_DECL_NAME_START;
}
private sXMLDeclEnding(): void {
const c = this.getCodeNorm();
if (c === GREATER) {
if (this.piTarget !== "xml") {
this.fail("processing instructions are not allowed before root.");
}
else if (this.name !== "version" &&
this.xmlDeclExpects.includes("version")) {
this.fail("XML declaration must contain a version.");
}
this.xmldeclHandler?.(this.xmlDecl);
this.name = "";
this.piTarget = this.text = "";
this.state = S_TEXT;
}
else {
// We got here because the previous character was a ?, but the question
// mark character is not valid inside any of the XML declaration
// name/value pairs.
this.fail(
"The character ? is disallowed anywhere in XML declarations.");
}
this.xmlDeclPossible = false;
}
private sOpenTag(): void {
const c = this.captureNameChars();
if (c === EOC) {
return;
}
const tag: SaxesTagIncomplete = this.tag = {
name: this.name,
attributes: Object.create(null) as Record<string, string>,
};
this.name = "";
if (this.xmlnsOpt) {
this.topNS = tag.ns = Object.create(null) as Record<string, string>;
}
this.openTagStartHandler?.(tag as StartTagForOptions<O>);
this.sawRoot = true;
if (!this.fragmentOpt && this.closedRoot) {
this.fail("documents may contain only one root.");
}
switch (c) {
case GREATER:
this.openTag();
break;
case FORWARD_SLASH:
this.state = S_OPEN_TAG_SLASH;
break;
default:
if (!isS(c)) {
this.fail("disallowed character in tag name.");
}
this.state = S_ATTRIB;
}
}
private sOpenTagSlash(): void {
if (this.getCode() === GREATER) {
this.openSelfClosingTag();
}
else {
this.fail("forward-slash in opening tag not followed by >.");
this.state = S_ATTRIB;
}
}
private sAttrib(): void {
const c = this.skipSpaces();
if (c === EOC) {
return;
}
if (isNameStartChar(c)) {
this.unget();
this.state = S_ATTRIB_NAME;
}
else if (c === GREATER) {
this.openTag();
}
else if (c === FORWARD_SLASH) {
this.state = S_OPEN_TAG_SLASH;
}
else {
this.fail("disallowed character in attribute name.");
}
}
private sAttribName(): void {
const c = this.captureNameChars();
if (c === EQUAL) {
this.state = S_ATTRIB_VALUE;
}
else if (isS(c)) {
this.state = S_ATTRIB_NAME_SAW_WHITE;
}
else if (c === GREATER) {
this.fail("attribute without value.");
this.pushAttrib(this.name, this.name);
this.name = this.text = "";
this.openTag();
}
else if (c !== EOC) {
this.fail("disallowed character in attribute name.");
}
}
private sAttribNameSawWhite(): void {
const c = this.skipSpaces();
switch (c) {
case EOC:
return;
case EQUAL:
this.state = S_ATTRIB_VALUE;
break;
default:
this.fail("attribute without value.");
// Should we do this???
// this.tag.attributes[this.name] = "";
this.text = "";
this.name = "";
if (c === GREATER) {
this.openTag();
}
else if (isNameStartChar(c)) {
this.unget();
this.state = S_ATTRIB_NAME;
}
else {
this.fail("disallowed character in attribute name.");
this.state = S_ATTRIB;
}
}
}
private sAttribValue(): void {
const c = this.getCodeNorm();
if (isQuote(c)) {
this.q = c;
this.state = S_ATTRIB_VALUE_QUOTED;
}
else if (!isS(c)) {
this.fail("unquoted attribute value.");
this.state = S_ATTRIB_VALUE_UNQUOTED;
this.unget();
}
}
private sAttribValueQuoted(): void {
// We deliberately do not use captureTo here. The specialized code we use
// here is faster than using captureTo.
const { q, chunk } = this;
let { i: start } = this;
// eslint-disable-next-line no-constant-condition
while (true) {
switch (this.getCode()) {
case q:
this.pushAttrib(this.name,
this.text + chunk.slice(start, this.prevI));
this.name = this.text = "";
this.q = null;
this.state = S_ATTRIB_VALUE_CLOSED;
return;
case AMP:
this.text += chunk.slice(start, this.prevI);
this.state = S_ENTITY;
this.entityReturnState = S_ATTRIB_VALUE_QUOTED;
return;
case NL:
case NL_LIKE:
case TAB:
this.text += `${chunk.slice(start, this.prevI)} `;
start = this.i;
break;
case LESS:
this.text += chunk.slice(start, this.prevI);
this.fail("disallowed character.");
return;
case EOC:
this.text += chunk.slice(start);
return;
default:
}
}
}
private sAttribValueClosed(): void {
const c = this.getCodeNorm();
if (isS(c)) {
this.state = S_ATTRIB;
}
else if (c === GREATER) {
this.openTag();
}
else if (c === FORWARD_SLASH) {
this.state = S_OPEN_TAG_SLASH;
}
else if (isNameStartChar(c)) {
this.fail("no whitespace between attributes.");
this.unget();
this.state = S_ATTRIB_NAME;
}
else {
this.fail("disallowed character in attribute name.");
}
}
private sAttribValueUnquoted(): void {
// We don't do anything regarding EOL or space handling for unquoted
// attributes. We already have failed by the time we get here, and the
// contract that saxes upholds states that upon failure, it is not safe to
// rely on the data passed to event handlers (other than
// ``onerror``). Passing "bad" data is not a problem.
const c = this.captureTo(ATTRIB_VALUE_UNQUOTED_TERMINATOR);
switch (c) {
case AMP:
this.state = S_ENTITY;
this.entityReturnState = S_ATTRIB_VALUE_UNQUOTED;
break;
case LESS:
this.fail("disallowed character.");
break;
case EOC:
break;
default:
if (this.text.includes("]]>")) {
this.fail("the string \"]]>\" is disallowed in char data.");
}
this.pushAttrib(this.name, this.text);
this.name = this.text = "";
if (c === GREATER) {
this.openTag();
}
else {
this.state = S_ATTRIB;
}
}
}
private sCloseTag(): void {
const c = this.captureNameChars();
if (c === GREATER) {
this.closeTag();
}
else if (isS(c)) {
this.state = S_CLOSE_TAG_SAW_WHITE;
}
else if (c !== EOC) {
this.fail("disallowed character in closing tag.");
}
}
private sCloseTagSawWhite(): void {
switch (this.skipSpaces()) {
case GREATER:
this.closeTag();
break;
case EOC:
break;
default:
this.fail("disallowed character in closing tag.");
}
}
// END OF STATE ENGINE METHODS
private handleTextInRoot(): void {
// This is essentially a specialized version of captureTo which is optimized
// for performing the ]]> check. A previous version of this code, checked
// ``this.text`` for the presence of ]]>. It simplified the code but was
// very costly when character data contained a lot of entities to be parsed.
//
// Since we are using a specialized loop, we also keep track of the presence
// of ]]> in text data. The sequence ]]> is forbidden to appear as-is.
//
let { i: start, forbiddenState } = this;
const { chunk, textHandler: handler } = this;
// eslint-disable-next-line no-labels, no-restricted-syntax
scanLoop:
// eslint-disable-next-line no-constant-condition
while (true) {
switch (this.getCode()) {
case LESS: {
this.state = S_OPEN_WAKA;
if (handler !== undefined) {
const { text } = this;
const slice = chunk.slice(start, this.prevI);
if (text.length !== 0) {
handler(text + slice);
this.text = "";
}
else if (slice.length !== 0) {
handler(slice);
}
}
forbiddenState = FORBIDDEN_START;
// eslint-disable-next-line no-labels
break scanLoop;
}
case AMP:
this.state = S_ENTITY;
this.entityReturnState = S_TEXT;
if (handler !== undefined) {
this.text += chunk.slice(start, this.prevI);
}
forbiddenState = FORBIDDEN_START;
// eslint-disable-next-line no-labels
break scanLoop;
case CLOSE_BRACKET:
switch (forbiddenState) {
case FORBIDDEN_START:
forbiddenState = FORBIDDEN_BRACKET;
break;
case FORBIDDEN_BRACKET:
forbiddenState = FORBIDDEN_BRACKET_BRACKET;
break;
case FORBIDDEN_BRACKET_BRACKET:
break;
default:
throw new Error("impossible state");
}
break;
case GREATER:
if (forbiddenState === FORBIDDEN_BRACKET_BRACKET) {
this.fail("the string \"]]>\" is disallowed in char data.");
}
forbiddenState = FORBIDDEN_START;
break;
case NL_LIKE:
if (handler !== undefined) {
this.text += `${chunk.slice(start, this.prevI)}\n`;
}
start = this.i;
forbiddenState = FORBIDDEN_START;
break;
case EOC:
if (handler !== undefined) {
this.text += chunk.slice(start);
}
// eslint-disable-next-line no-labels
break scanLoop;
default:
forbiddenState = FORBIDDEN_START;
}
}
this.forbiddenState = forbiddenState;
}
private handleTextOutsideRoot(): void {
// This is essentially a specialized version of captureTo which is optimized
// for a specialized task. We keep track of the presence of non-space
// characters in the text since these are errors when appearing outside the
// document root element.
let { i: start } = this;
const { chunk, textHandler: handler } = this;
let nonSpace = false;
// eslint-disable-next-line no-labels, no-restricted-syntax
outRootLoop:
// eslint-disable-next-line no-constant-condition
while (true) {
const code = this.getCode();
switch (code) {
case LESS: {
this.state = S_OPEN_WAKA;
if (handler !== undefined) {
const { text } = this;
const slice = chunk.slice(start, this.prevI);
if (text.length !== 0) {
handler(text + slice);
this.text = "";
}
else if (slice.length !== 0) {
handler(slice);
}
}
// eslint-disable-next-line no-labels
break outRootLoop;
}
case AMP:
this.state = S_ENTITY;
this.entityReturnState = S_TEXT;
if (handler !== undefined) {
this.text += chunk.slice(start, this.prevI);
}
nonSpace = true;
// eslint-disable-next-line no-labels
break outRootLoop;
case NL_LIKE:
if (handler !== undefined) {
this.text += `${chunk.slice(start, this.prevI)}\n`;
}
start = this.i;
break;
case EOC:
if (handler !== undefined) {
this.text += chunk.slice(start);
}
// eslint-disable-next-line no-labels
break outRootLoop;
default:
if (!isS(code)) {
nonSpace = true;
}
}
}
if (!nonSpace) {
return;
}
// We use the reportedTextBeforeRoot and reportedTextAfterRoot flags
// to avoid reporting errors for every single character that is out of
// place.
if (!this.sawRoot && !this.reportedTextBeforeRoot) {
this.fail("text data outside of root node.");
this.reportedTextBeforeRoot = true;
}
if (this.closedRoot && !this.reportedTextAfterRoot) {
this.fail("text data outside of root node.");
this.reportedTextAfterRoot = true;
}
}
private pushAttribNS(name: string, value: string): void {
const { prefix, local } = this.qname(name);
const attr = { name, prefix, local, value };
this.attribList.push(attr);
this.attributeHandler?.(attr as AttributeEventForOptions<O>);
if (prefix === "xmlns") {
const trimmed = value.trim();
if (this.currentXMLVersion === "1.0" && trimmed === "") {
this.fail("invalid attempt to undefine prefix in XML 1.0");
}
this.topNS![local] = trimmed;
nsPairCheck(this, local, trimmed);
}
else if (name === "xmlns") {
const trimmed = value.trim();
this.topNS![""] = trimmed;
nsPairCheck(this, "", trimmed);
}
}
private pushAttribPlain(name: string, value: string): void {
const attr = { name, value };
this.attribList.push(attr);
this.attributeHandler?.(attr as AttributeEventForOptions<O>);
}
/**
* End parsing. This performs final well-formedness checks and resets the
* parser to a clean state.
*
* @returns this
*/
private end(): this {
if (!this.sawRoot) {
this.fail("document must contain a root element.");
}
const { tags } = this;
while (tags.length > 0) {
const tag = tags.pop()!;
this.fail(`unclosed tag: ${tag.name}`);
}
if ((this.state !== S_BEGIN) && (this.state !== S_TEXT)) {
this.fail("unexpected end.");
}
const { text } = this;
if (text.length !== 0) {
this.textHandler?.(text);
this.text = "";
}
this._closed = true;
this.endHandler?.();
this._init();
return this;
}
/**
* Resolve a namespace prefix.
*
* @param prefix The prefix to resolve.
*
* @returns The namespace URI or ``undefined`` if the prefix is not defined.
*/
resolve(prefix: string): string | undefined {
let uri = this.topNS![prefix];
if (uri !== undefined) {
return uri;
}
const { tags } = this;
for (let index = tags.length - 1; index >= 0; index--) {
uri = tags[index]!.ns![prefix];
if (uri !== undefined) {
return uri;
}
}
uri = this.ns[prefix];
if (uri !== undefined) {
return uri;
}
return this.opt.resolvePrefix?.(prefix);
}
/**
* Parse a qname into its prefix and local name parts.
*
* @param name The name to parse
*
* @returns
*/
private qname(name: string): { prefix: string; local: string } {
// This is faster than using name.split(":").
const colon = name.indexOf(":");
if (colon === -1) {
return { prefix: "", local: name };
}
const local = name.slice(colon + 1);
const prefix = name.slice(0, colon);
if (prefix === "" || local === "" || local.includes(":")) {
this.fail(`malformed name: ${name}.`);
}
return { prefix, local };
}
private processAttribsNS(): void {
const { attribList } = this;
const tag = this.tag!;
{
// add namespace info to tag
const { prefix, local } = this.qname(tag.name);
tag.prefix = prefix;
tag.local = local;
const uri = tag.uri = this.resolve(prefix) ?? "";
if (prefix !== "") {
if (prefix === "xmlns") {
this.fail("tags may not have \"xmlns\" as prefix.");
}
if (uri === "") {
this.fail(`unbound namespace prefix: ${JSON.stringify(prefix)}.`);
tag.uri = prefix;
}
}
}
if (attribList.length === 0) {
return;
}
const { attributes } = tag;
const seen = new Set();
// Note: do not apply default ns to attributes:
// http://www.w3.org/TR/REC-xml-names/#defaulting
for (const attr of attribList as SaxesAttributeNSIncomplete[]) {
const { name, prefix, local } = attr;
let uri;
let eqname;
if (prefix === "") {
uri = name === "xmlns" ? XMLNS_NAMESPACE : "";
eqname = name;
}
else {
uri = this.resolve(prefix);
// if there's any attributes with an undefined namespace,
// then fail on them now.
if (uri === undefined) {
this.fail(`unbound namespace prefix: ${JSON.stringify(prefix)}.`);
uri = prefix;
}
eqname = `{${uri}}${local}`;
}
if (seen.has(eqname)) {
this.fail(`duplicate attribute: ${eqname}.`);
}
seen.add(eqname);
attr.uri = uri;
attributes[name] = attr;
}
this.attribList = [];
}
private processAttribsPlain(): void {
const { attribList } = this;
// eslint-disable-next-line prefer-destructuring
const attributes = this.tag!.attributes;
for (const { name, value } of attribList) {
if (attributes[name] !== undefined) {
this.fail(`duplicate attribute: ${name}.`);
}
attributes[name] = value;
}
this.attribList = [];
}
/**
* Handle a complete open tag. This parser code calls this once it has seen
* the whole tag. This method checks for well-formeness and then emits
* ``onopentag``.
*/
private openTag(): void {
this.processAttribs();
const { tags } = this;
const tag = this.tag as SaxesTag;
tag.isSelfClosing = false;
// There cannot be any pending text here due to the onopentagstart that was
// necessarily emitted before we get here. So we do not check text.
this.openTagHandler?.(tag as TagForOptions<O>);
tags.push(tag);
this.state = S_TEXT;
this.name = "";
}
/**
* Handle a complete self-closing tag. This parser code calls this once it has
* seen the whole tag. This method checks for well-formeness and then emits
* ``onopentag`` and ``onclosetag``.
*/
private openSelfClosingTag(): void {
this.processAttribs();
const { tags } = this;
const tag = this.tag as SaxesTag;
tag.isSelfClosing = true;
// There cannot be any pending text here due to the onopentagstart that was
// necessarily emitted before we get here. So we do not check text.
this.openTagHandler?.(tag as TagForOptions<O>);
this.closeTagHandler?.(tag as TagForOptions<O>);
const top = this.tag = tags[tags.length - 1] ?? null;
if (top === null) {
this.closedRoot = true;
}
this.state = S_TEXT;
this.name = "";
}
/**
* Handle a complete close tag. This parser code calls this once it has seen
* the whole tag. This method checks for well-formeness and then emits
* ``onclosetag``.
*/
private closeTag(): void {
const { tags, name } = this;
// Our state after this will be S_TEXT, no matter what, and we can clear
// tagName now.
this.state = S_TEXT;
this.name = "";
if (name === "") {
this.fail("weird empty close tag.");
this.text += "</>";
return;
}
const handler = this.closeTagHandler;
let l = tags.length;
while (l-- > 0) {
const tag = this.tag = tags.pop() as SaxesTag;
this.topNS = tag.ns!;
handler?.(tag as TagForOptions<O>);
if (tag.name === name) {
break;
}
this.fail("unexpected close tag.");
}
if (l === 0) {
this.closedRoot = true;
}
else if (l < 0) {
this.fail(`unmatched closing tag: ${name}.`);
this.text += `</${name}>`;
}
}
/**
* Resolves an entity. Makes any necessary well-formedness checks.
*
* @param entity The entity to resolve.
*
* @returns The parsed entity.
*/
private parseEntity(entity: string): string {
// startsWith would be significantly slower for this test.
if (entity[0] !== "#") {
const defined = this.ENTITIES[entity];
if (defined !== undefined) {
return defined;
}
this.fail(this.isName(entity) ? "undefined entity." :
"disallowed character in entity name.");
return `&${entity};`;
}
let num = NaN;
if (entity[1] === "x" && /^#x[0-9a-f]+$/i.test(entity)) {
num = parseInt(entity.slice(2), 16);
}
else if (/^#[0-9]+$/.test(entity)) {
num = parseInt(entity.slice(1), 10);
}
// The character reference is required to match the CHAR production.
if (!this.isChar(num)) {
this.fail("malformed character entity.");
return `&${entity};`;
}
return String.fromCodePoint(num);
}
} |
1,135 | fn(parser: SaxesParser): void {
parser.write("<root unbound:attr='value'/>");
} | class SaxesParser<O extends SaxesOptions = {}> {
private readonly fragmentOpt: boolean;
private readonly xmlnsOpt: boolean;
private readonly trackPosition: boolean;
private readonly fileName?: string;
private readonly nameStartCheck: (c: number) => boolean;
private readonly nameCheck: (c: number) => boolean;
private readonly isName: (name: string) => boolean;
private readonly ns!: Record<string, string>;
private openWakaBang!: string;
private text!: string;
private name!: string;
private piTarget!: string;
private entity!: string;
private q!: null | number;
private tags!: SaxesTagIncomplete[];
private tag!: SaxesTagIncomplete | null;
private topNS!: Record<string, string> | null;
private chunk!: string;
private chunkPosition!: number;
private i!: number;
//
// We use prevI to allow "ungetting" the previously read code point. Note
// however, that it is not safe to unget everything and anything. In
// particular ungetting EOL characters will screw positioning up.
//
// Practically, you must not unget a code which has any side effect beyond
// updating ``this.i`` and ``this.prevI``. Only EOL codes have such side
// effects.
//
private prevI!: number;
private carriedFromPrevious?: string;
private forbiddenState!: number;
private attribList!: (SaxesAttributeNSIncomplete | SaxesAttributePlain)[];
private state!: number;
private reportedTextBeforeRoot!: boolean;
private reportedTextAfterRoot!: boolean;
private closedRoot!: boolean;
private sawRoot!: boolean;
private xmlDeclPossible!: boolean;
private xmlDeclExpects!: string[];
private entityReturnState?: number;
private processAttribs!: (this: this) => void;
private positionAtNewLine!: number;
private doctype!: boolean;
private getCode!: () => number;
private isChar!: (c: number) => boolean;
private pushAttrib!: (name: string, value: string) => void;
private _closed!: boolean;
private currentXMLVersion!: string;
private readonly stateTable: ((this: SaxesParser<O>) => void)[];
private xmldeclHandler?: XMLDeclHandler;
private textHandler?: TextHandler;
private piHandler?: PIHandler;
private doctypeHandler?: DoctypeHandler;
private commentHandler?: CommentHandler;
private openTagStartHandler?: OpenTagStartHandler<O>;
private openTagHandler?: OpenTagHandler<O>;
private closeTagHandler?: CloseTagHandler<O>;
private cdataHandler?: CDataHandler;
private errorHandler?: ErrorHandler;
private endHandler?: EndHandler;
private readyHandler?: ReadyHandler;
private attributeHandler?: AttributeHandler<O>;
/**
* Indicates whether or not the parser is closed. If ``true``, wait for
* the ``ready`` event to write again.
*/
get closed(): boolean {
return this._closed;
}
readonly opt: SaxesOptions;
/**
* The XML declaration for this document.
*/
xmlDecl!: XMLDecl;
/**
* The line number of the next character to be read by the parser. This field
* is one-based. (The first line is numbered 1.)
*/
line!: number;
/**
* The column number of the next character to be read by the parser. *
* This field is zero-based. (The first column is 0.)
*
* This field counts columns by *Unicode character*. Note that this *can*
* be different from the index of the character in a JavaScript string due
* to how JavaScript handles astral plane characters.
*
* See [[columnIndex]] for a number that corresponds to the JavaScript index.
*/
column!: number;
/**
* A map of entity name to expansion.
*/
ENTITIES!: Record<string, string>;
/**
* @param opt The parser options.
*/
constructor(opt?: O) {
this.opt = opt ?? {};
this.fragmentOpt = !!(this.opt.fragment as boolean);
const xmlnsOpt = this.xmlnsOpt = !!(this.opt.xmlns as boolean);
this.trackPosition = this.opt.position !== false;
this.fileName = this.opt.fileName;
if (xmlnsOpt) {
// This is the function we use to perform name checks on PIs and entities.
// When namespaces are used, colons are not allowed in PI target names or
// entity names. So the check depends on whether namespaces are used. See:
//
// https://www.w3.org/XML/xml-names-19990114-errata.html
// NE08
//
this.nameStartCheck = isNCNameStartChar;
this.nameCheck = isNCNameChar;
this.isName = isNCName;
// eslint-disable-next-line @typescript-eslint/unbound-method
this.processAttribs = this.processAttribsNS;
// eslint-disable-next-line @typescript-eslint/unbound-method
this.pushAttrib = this.pushAttribNS;
// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-assignment
this.ns = { __proto__: null as any, ...rootNS };
const additional = this.opt.additionalNamespaces;
if (additional != null) {
nsMappingCheck(this, additional);
Object.assign(this.ns, additional);
}
}
else {
this.nameStartCheck = isNameStartChar;
this.nameCheck = isNameChar;
this.isName = isName;
// eslint-disable-next-line @typescript-eslint/unbound-method
this.processAttribs = this.processAttribsPlain;
// eslint-disable-next-line @typescript-eslint/unbound-method
this.pushAttrib = this.pushAttribPlain;
}
//
// The order of the members in this table needs to correspond to the state
// numbers given to the states that correspond to the methods being recorded
// here.
//
this.stateTable = [
/* eslint-disable @typescript-eslint/unbound-method */
this.sBegin,
this.sBeginWhitespace,
this.sDoctype,
this.sDoctypeQuote,
this.sDTD,
this.sDTDQuoted,
this.sDTDOpenWaka,
this.sDTDOpenWakaBang,
this.sDTDComment,
this.sDTDCommentEnding,
this.sDTDCommentEnded,
this.sDTDPI,
this.sDTDPIEnding,
this.sText,
this.sEntity,
this.sOpenWaka,
this.sOpenWakaBang,
this.sComment,
this.sCommentEnding,
this.sCommentEnded,
this.sCData,
this.sCDataEnding,
this.sCDataEnding2,
this.sPIFirstChar,
this.sPIRest,
this.sPIBody,
this.sPIEnding,
this.sXMLDeclNameStart,
this.sXMLDeclName,
this.sXMLDeclEq,
this.sXMLDeclValueStart,
this.sXMLDeclValue,
this.sXMLDeclSeparator,
this.sXMLDeclEnding,
this.sOpenTag,
this.sOpenTagSlash,
this.sAttrib,
this.sAttribName,
this.sAttribNameSawWhite,
this.sAttribValue,
this.sAttribValueQuoted,
this.sAttribValueClosed,
this.sAttribValueUnquoted,
this.sCloseTag,
this.sCloseTagSawWhite,
/* eslint-enable @typescript-eslint/unbound-method */
];
this._init();
}
_init(): void {
this.openWakaBang = "";
this.text = "";
this.name = "";
this.piTarget = "";
this.entity = "";
this.q = null;
this.tags = [];
this.tag = null;
this.topNS = null;
this.chunk = "";
this.chunkPosition = 0;
this.i = 0;
this.prevI = 0;
this.carriedFromPrevious = undefined;
this.forbiddenState = FORBIDDEN_START;
this.attribList = [];
// The logic is organized so as to minimize the need to check
// this.opt.fragment while parsing.
const { fragmentOpt } = this;
this.state = fragmentOpt ? S_TEXT : S_BEGIN;
// We want these to be all true if we are dealing with a fragment.
this.reportedTextBeforeRoot = this.reportedTextAfterRoot = this.closedRoot =
this.sawRoot = fragmentOpt;
// An XML declaration is intially possible only when parsing whole
// documents.
this.xmlDeclPossible = !fragmentOpt;
this.xmlDeclExpects = ["version"];
this.entityReturnState = undefined;
let { defaultXMLVersion } = this.opt;
if (defaultXMLVersion === undefined) {
if (this.opt.forceXMLVersion === true) {
throw new Error("forceXMLVersion set but defaultXMLVersion is not set");
}
defaultXMLVersion = "1.0";
}
this.setXMLVersion(defaultXMLVersion);
this.positionAtNewLine = 0;
this.doctype = false;
this._closed = false;
this.xmlDecl = {
version: undefined,
encoding: undefined,
standalone: undefined,
};
this.line = 1;
this.column = 0;
this.ENTITIES = Object.create(XML_ENTITIES) as Record<string, string>;
this.readyHandler?.();
}
/**
* The stream position the parser is currently looking at. This field is
* zero-based.
*
* This field is not based on counting Unicode characters but is to be
* interpreted as a plain index into a JavaScript string.
*/
get position(): number {
return this.chunkPosition + this.i;
}
/**
* The column number of the next character to be read by the parser. *
* This field is zero-based. (The first column in a line is 0.)
*
* This field reports the index at which the next character would be in the
* line if the line were represented as a JavaScript string. Note that this
* *can* be different to a count based on the number of *Unicode characters*
* due to how JavaScript handles astral plane characters.
*
* See [[column]] for a number that corresponds to a count of Unicode
* characters.
*/
get columnIndex(): number {
return this.position - this.positionAtNewLine;
}
/**
* Set an event listener on an event. The parser supports one handler per
* event type. If you try to set an event handler over an existing handler,
* the old handler is silently overwritten.
*
* @param name The event to listen to.
*
* @param handler The handler to set.
*/
on<N extends EventName>(name: N, handler: EventNameToHandler<O, N>): void {
// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-member-access
(this as any)[EVENT_NAME_TO_HANDLER_NAME[name]] = handler;
}
/**
* Unset an event handler.
*
* @parma name The event to stop listening to.
*/
off(name: EventName): void {
// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-member-access
(this as any)[EVENT_NAME_TO_HANDLER_NAME[name]] = undefined;
}
/**
* Make an error object. The error object will have a message that contains
* the ``fileName`` option passed at the creation of the parser. If position
* tracking was turned on, it will also have line and column number
* information.
*
* @param message The message describing the error to report.
*
* @returns An error object with a properly formatted message.
*/
makeError(message: string): Error {
let msg = this.fileName ?? "";
if (this.trackPosition) {
if (msg.length > 0) {
msg += ":";
}
msg += `${this.line}:${this.column}`;
}
if (msg.length > 0) {
msg += ": ";
}
return new Error(msg + message);
}
/**
* Report a parsing error. This method is made public so that client code may
* check for issues that are outside the scope of this project and can report
* errors.
*
* @param message The error to report.
*
* @returns this
*/
fail(message: string): this {
const err = this.makeError(message);
const handler = this.errorHandler;
if (handler === undefined) {
throw err;
}
else {
handler(err);
}
return this;
}
/**
* Write a XML data to the parser.
*
* @param chunk The XML data to write.
*
* @returns this
*/
// We do need object for the type here. Yes, it often causes problems
// but not in this case.
write(chunk: string | object | null): this {
if (this.closed) {
return this.fail("cannot write after close; assign an onready handler.");
}
let end = false;
if (chunk === null) {
// We cannot return immediately because carriedFromPrevious may need
// processing.
end = true;
chunk = "";
}
else if (typeof chunk === "object") {
chunk = chunk.toString();
}
// We checked if performing a pre-decomposition of the string into an array
// of single complete characters (``Array.from(chunk)``) would be faster
// than the current repeated calls to ``charCodeAt``. As of August 2018, it
// isn't. (There may be Node-specific code that would perform faster than
// ``Array.from`` but don't want to be dependent on Node.)
if (this.carriedFromPrevious !== undefined) {
// The previous chunk had char we must carry over.
chunk = `${this.carriedFromPrevious}${chunk}`;
this.carriedFromPrevious = undefined;
}
let limit = chunk.length;
const lastCode = chunk.charCodeAt(limit - 1);
if (!end &&
// A trailing CR or surrogate must be carried over to the next
// chunk.
(lastCode === CR || (lastCode >= 0xD800 && lastCode <= 0xDBFF))) {
// The chunk ends with a character that must be carried over. We cannot
// know how to handle it until we get the next chunk or the end of the
// stream. So save it for later.
this.carriedFromPrevious = chunk[limit - 1];
limit--;
chunk = chunk.slice(0, limit);
}
const { stateTable } = this;
this.chunk = chunk;
this.i = 0;
while (this.i < limit) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-argument
stateTable[this.state].call(this as any);
}
this.chunkPosition += limit;
return end ? this.end() : this;
}
/**
* Close the current stream. Perform final well-formedness checks and reset
* the parser tstate.
*
* @returns this
*/
close(): this {
return this.write(null);
}
/**
* Get a single code point out of the current chunk. This updates the current
* position if we do position tracking.
*
* This is the algorithm to use for XML 1.0.
*
* @returns The character read.
*/
private getCode10(): number {
const { chunk, i } = this;
this.prevI = i;
// Yes, we do this instead of doing this.i++. Doing it this way, we do not
// read this.i again, which is a bit faster.
this.i = i + 1;
if (i >= chunk.length) {
return EOC;
}
// Using charCodeAt and handling the surrogates ourselves is faster
// than using codePointAt.
const code = chunk.charCodeAt(i);
this.column++;
if (code < 0xD800) {
if (code >= SPACE || code === TAB) {
return code;
}
switch (code) {
case NL:
this.line++;
this.column = 0;
this.positionAtNewLine = this.position;
return NL;
case CR:
// We may get NaN if we read past the end of the chunk, which is fine.
if (chunk.charCodeAt(i + 1) === NL) {
// A \r\n sequence is converted to \n so we have to skip over the
// next character. We already know it has a size of 1 so ++ is fine
// here.
this.i = i + 2;
}
// Otherwise, a \r is just converted to \n, so we don't have to skip
// ahead.
// In either case, \r becomes \n.
this.line++;
this.column = 0;
this.positionAtNewLine = this.position;
return NL_LIKE;
default:
// If we get here, then code < SPACE and it is not NL CR or TAB.
this.fail("disallowed character.");
return code;
}
}
if (code > 0xDBFF) {
// This is a specialized version of isChar10 that takes into account
// that in this context code > 0xDBFF and code <= 0xFFFF. So it does not
// test cases that don't need testing.
if (!(code >= 0xE000 && code <= 0xFFFD)) {
this.fail("disallowed character.");
}
return code;
}
const final = 0x10000 + ((code - 0xD800) * 0x400) +
(chunk.charCodeAt(i + 1) - 0xDC00);
this.i = i + 2;
// This is a specialized version of isChar10 that takes into account that in
// this context necessarily final >= 0x10000.
if (final > 0x10FFFF) {
this.fail("disallowed character.");
}
return final;
}
/**
* Get a single code point out of the current chunk. This updates the current
* position if we do position tracking.
*
* This is the algorithm to use for XML 1.1.
*
* @returns {number} The character read.
*/
private getCode11(): number {
const { chunk, i } = this;
this.prevI = i;
// Yes, we do this instead of doing this.i++. Doing it this way, we do not
// read this.i again, which is a bit faster.
this.i = i + 1;
if (i >= chunk.length) {
return EOC;
}
// Using charCodeAt and handling the surrogates ourselves is faster
// than using codePointAt.
const code = chunk.charCodeAt(i);
this.column++;
if (code < 0xD800) {
if ((code > 0x1F && code < 0x7F) || (code > 0x9F && code !== LS) ||
code === TAB) {
return code;
}
switch (code) {
case NL: // 0xA
this.line++;
this.column = 0;
this.positionAtNewLine = this.position;
return NL;
case CR: { // 0xD
// We may get NaN if we read past the end of the chunk, which is
// fine.
const next = chunk.charCodeAt(i + 1);
if (next === NL || next === NEL) {
// A CR NL or CR NEL sequence is converted to NL so we have to skip
// over the next character. We already know it has a size of 1.
this.i = i + 2;
}
// Otherwise, a CR is just converted to NL, no skip.
}
/* yes, fall through */
case NEL: // 0x85
case LS: // Ox2028
this.line++;
this.column = 0;
this.positionAtNewLine = this.position;
return NL_LIKE;
default:
this.fail("disallowed character.");
return code;
}
}
if (code > 0xDBFF) {
// This is a specialized version of isCharAndNotRestricted that takes into
// account that in this context code > 0xDBFF and code <= 0xFFFF. So it
// does not test cases that don't need testing.
if (!(code >= 0xE000 && code <= 0xFFFD)) {
this.fail("disallowed character.");
}
return code;
}
const final = 0x10000 + ((code - 0xD800) * 0x400) +
(chunk.charCodeAt(i + 1) - 0xDC00);
this.i = i + 2;
// This is a specialized version of isCharAndNotRestricted that takes into
// account that in this context necessarily final >= 0x10000.
if (final > 0x10FFFF) {
this.fail("disallowed character.");
}
return final;
}
/**
* Like ``getCode`` but with the return value normalized so that ``NL`` is
* returned for ``NL_LIKE``.
*/
private getCodeNorm(): number {
const c = this.getCode();
return c === NL_LIKE ? NL : c;
}
private unget(): void {
this.i = this.prevI;
this.column--;
}
/**
* Capture characters into a buffer until encountering one of a set of
* characters.
*
* @param chars An array of codepoints. Encountering a character in the array
* ends the capture. (``chars`` may safely contain ``NL``.)
*
* @return The character code that made the capture end, or ``EOC`` if we hit
* the end of the chunk. The return value cannot be NL_LIKE: NL is returned
* instead.
*/
private captureTo(chars: number[]): number {
let { i: start } = this;
const { chunk } = this;
// eslint-disable-next-line no-constant-condition
while (true) {
const c = this.getCode();
const isNLLike = c === NL_LIKE;
const final = isNLLike ? NL : c;
if (final === EOC || chars.includes(final)) {
this.text += chunk.slice(start, this.prevI);
return final;
}
if (isNLLike) {
this.text += `${chunk.slice(start, this.prevI)}\n`;
start = this.i;
}
}
}
/**
* Capture characters into a buffer until encountering a character.
*
* @param char The codepoint that ends the capture. **NOTE ``char`` MAY NOT
* CONTAIN ``NL``.** Passing ``NL`` will result in buggy behavior.
*
* @return ``true`` if we ran into the character. Otherwise, we ran into the
* end of the current chunk.
*/
private captureToChar(char: number): boolean {
let { i: start } = this;
const { chunk } = this;
// eslint-disable-next-line no-constant-condition
while (true) {
let c = this.getCode();
switch (c) {
case NL_LIKE:
this.text += `${chunk.slice(start, this.prevI)}\n`;
start = this.i;
c = NL;
break;
case EOC:
this.text += chunk.slice(start);
return false;
default:
}
if (c === char) {
this.text += chunk.slice(start, this.prevI);
return true;
}
}
}
/**
* Capture characters that satisfy ``isNameChar`` into the ``name`` field of
* this parser.
*
* @return The character code that made the test fail, or ``EOC`` if we hit
* the end of the chunk. The return value cannot be NL_LIKE: NL is returned
* instead.
*/
private captureNameChars(): number {
const { chunk, i: start } = this;
// eslint-disable-next-line no-constant-condition
while (true) {
const c = this.getCode();
if (c === EOC) {
this.name += chunk.slice(start);
return EOC;
}
// NL is not a name char so we don't have to test specifically for it.
if (!isNameChar(c)) {
this.name += chunk.slice(start, this.prevI);
return c === NL_LIKE ? NL : c;
}
}
}
/**
* Skip white spaces.
*
* @return The character that ended the skip, or ``EOC`` if we hit
* the end of the chunk. The return value cannot be NL_LIKE: NL is returned
* instead.
*/
private skipSpaces(): number {
// eslint-disable-next-line no-constant-condition
while (true) {
const c = this.getCodeNorm();
if (c === EOC || !isS(c)) {
return c;
}
}
}
private setXMLVersion(version: string): void {
this.currentXMLVersion = version;
/* eslint-disable @typescript-eslint/unbound-method */
if (version === "1.0") {
this.isChar = isChar10;
this.getCode = this.getCode10;
}
else {
this.isChar = isChar11;
this.getCode = this.getCode11;
}
/* eslint-enable @typescript-eslint/unbound-method */
}
// STATE ENGINE METHODS
// This needs to be a state separate from S_BEGIN_WHITESPACE because we want
// to be sure never to come back to this state later.
private sBegin(): void {
// We are essentially peeking at the first character of the chunk. Since
// S_BEGIN can be in effect only when we start working on the first chunk,
// the index at which we must look is necessarily 0. Note also that the
// following test does not depend on decoding surrogates.
// If the initial character is 0xFEFF, ignore it.
if (this.chunk.charCodeAt(0) === 0xFEFF) {
this.i++;
this.column++;
}
this.state = S_BEGIN_WHITESPACE;
}
private sBeginWhitespace(): void {
// We need to know whether we've encountered spaces or not because as soon
// as we run into a space, an XML declaration is no longer possible. Rather
// than slow down skipSpaces even in places where we don't care whether it
// skipped anything or not, we check whether prevI is equal to the value of
// i from before we skip spaces.
const iBefore = this.i;
const c = this.skipSpaces();
if (this.prevI !== iBefore) {
this.xmlDeclPossible = false;
}
switch (c) {
case LESS:
this.state = S_OPEN_WAKA;
// We could naively call closeText but in this state, it is not normal
// to have text be filled with any data.
if (this.text.length !== 0) {
throw new Error("no-empty text at start");
}
break;
case EOC:
break;
default:
this.unget();
this.state = S_TEXT;
this.xmlDeclPossible = false;
}
}
private sDoctype(): void {
const c = this.captureTo(DOCTYPE_TERMINATOR);
switch (c) {
case GREATER: {
this.doctypeHandler?.(this.text);
this.text = "";
this.state = S_TEXT;
this.doctype = true; // just remember that we saw it.
break;
}
case EOC:
break;
default:
this.text += String.fromCodePoint(c);
if (c === OPEN_BRACKET) {
this.state = S_DTD;
}
else if (isQuote(c)) {
this.state = S_DOCTYPE_QUOTE;
this.q = c;
}
}
}
private sDoctypeQuote(): void {
const q = this.q!;
if (this.captureToChar(q)) {
this.text += String.fromCodePoint(q);
this.q = null;
this.state = S_DOCTYPE;
}
}
private sDTD(): void {
const c = this.captureTo(DTD_TERMINATOR);
if (c === EOC) {
return;
}
this.text += String.fromCodePoint(c);
if (c === CLOSE_BRACKET) {
this.state = S_DOCTYPE;
}
else if (c === LESS) {
this.state = S_DTD_OPEN_WAKA;
}
else if (isQuote(c)) {
this.state = S_DTD_QUOTED;
this.q = c;
}
}
private sDTDQuoted(): void {
const q = this.q!;
if (this.captureToChar(q)) {
this.text += String.fromCodePoint(q);
this.state = S_DTD;
this.q = null;
}
}
private sDTDOpenWaka(): void {
const c = this.getCodeNorm();
this.text += String.fromCodePoint(c);
switch (c) {
case BANG:
this.state = S_DTD_OPEN_WAKA_BANG;
this.openWakaBang = "";
break;
case QUESTION:
this.state = S_DTD_PI;
break;
default:
this.state = S_DTD;
}
}
private sDTDOpenWakaBang(): void {
const char = String.fromCodePoint(this.getCodeNorm());
const owb = this.openWakaBang += char;
this.text += char;
if (owb !== "-") {
this.state = owb === "--" ? S_DTD_COMMENT : S_DTD;
this.openWakaBang = "";
}
}
private sDTDComment(): void {
if (this.captureToChar(MINUS)) {
this.text += "-";
this.state = S_DTD_COMMENT_ENDING;
}
}
private sDTDCommentEnding(): void {
const c = this.getCodeNorm();
this.text += String.fromCodePoint(c);
this.state = c === MINUS ? S_DTD_COMMENT_ENDED : S_DTD_COMMENT;
}
private sDTDCommentEnded(): void {
const c = this.getCodeNorm();
this.text += String.fromCodePoint(c);
if (c === GREATER) {
this.state = S_DTD;
}
else {
this.fail("malformed comment.");
// <!-- blah -- bloo --> will be recorded as
// a comment of " blah -- bloo "
this.state = S_DTD_COMMENT;
}
}
private sDTDPI(): void {
if (this.captureToChar(QUESTION)) {
this.text += "?";
this.state = S_DTD_PI_ENDING;
}
}
private sDTDPIEnding(): void {
const c = this.getCodeNorm();
this.text += String.fromCodePoint(c);
if (c === GREATER) {
this.state = S_DTD;
}
}
private sText(): void {
//
// We did try a version of saxes where the S_TEXT state was split in two
// states: one for text inside the root element, and one for text
// outside. This was avoiding having to test this.tags.length to decide
// what implementation to actually use.
//
// Peformance testing on gigabyte-size files did not show any advantage to
// using the two states solution instead of the current one. Conversely, it
// made the code a bit more complicated elsewhere. For instance, a comment
// can appear before the root element so when a comment ended it was
// necessary to determine whether to return to the S_TEXT state or to the
// new text-outside-root state.
//
if (this.tags.length !== 0) {
this.handleTextInRoot();
}
else {
this.handleTextOutsideRoot();
}
}
private sEntity(): void {
// This is essentially a specialized version of captureToChar(SEMICOLON...)
let { i: start } = this;
const { chunk } = this;
// eslint-disable-next-line no-labels, no-restricted-syntax
loop:
// eslint-disable-next-line no-constant-condition
while (true) {
switch (this.getCode()) {
case NL_LIKE:
this.entity += `${chunk.slice(start, this.prevI)}\n`;
start = this.i;
break;
case SEMICOLON: {
const { entityReturnState } = this;
const entity = this.entity + chunk.slice(start, this.prevI);
this.state = entityReturnState!;
let parsed: string;
if (entity === "") {
this.fail("empty entity name.");
parsed = "&;";
}
else {
parsed = this.parseEntity(entity);
this.entity = "";
}
if (entityReturnState !== S_TEXT || this.textHandler !== undefined) {
this.text += parsed;
}
// eslint-disable-next-line no-labels
break loop;
}
case EOC:
this.entity += chunk.slice(start);
// eslint-disable-next-line no-labels
break loop;
default:
}
}
}
private sOpenWaka(): void {
// Reminder: a state handler is called with at least one character
// available in the current chunk. So the first call to get code inside of
// a state handler cannot return ``EOC``. That's why we don't test
// for it.
const c = this.getCode();
// either a /, ?, !, or text is coming next.
if (isNameStartChar(c)) {
this.state = S_OPEN_TAG;
this.unget();
this.xmlDeclPossible = false;
}
else {
switch (c) {
case FORWARD_SLASH:
this.state = S_CLOSE_TAG;
this.xmlDeclPossible = false;
break;
case BANG:
this.state = S_OPEN_WAKA_BANG;
this.openWakaBang = "";
this.xmlDeclPossible = false;
break;
case QUESTION:
this.state = S_PI_FIRST_CHAR;
break;
default:
this.fail("disallowed character in tag name");
this.state = S_TEXT;
this.xmlDeclPossible = false;
}
}
}
private sOpenWakaBang(): void {
this.openWakaBang += String.fromCodePoint(this.getCodeNorm());
switch (this.openWakaBang) {
case "[CDATA[":
if (!this.sawRoot && !this.reportedTextBeforeRoot) {
this.fail("text data outside of root node.");
this.reportedTextBeforeRoot = true;
}
if (this.closedRoot && !this.reportedTextAfterRoot) {
this.fail("text data outside of root node.");
this.reportedTextAfterRoot = true;
}
this.state = S_CDATA;
this.openWakaBang = "";
break;
case "--":
this.state = S_COMMENT;
this.openWakaBang = "";
break;
case "DOCTYPE":
this.state = S_DOCTYPE;
if (this.doctype || this.sawRoot) {
this.fail("inappropriately located doctype declaration.");
}
this.openWakaBang = "";
break;
default:
// 7 happens to be the maximum length of the string that can possibly
// match one of the cases above.
if (this.openWakaBang.length >= 7) {
this.fail("incorrect syntax.");
}
}
}
private sComment(): void {
if (this.captureToChar(MINUS)) {
this.state = S_COMMENT_ENDING;
}
}
private sCommentEnding(): void {
const c = this.getCodeNorm();
if (c === MINUS) {
this.state = S_COMMENT_ENDED;
this.commentHandler?.(this.text);
this.text = "";
}
else {
this.text += `-${String.fromCodePoint(c)}`;
this.state = S_COMMENT;
}
}
private sCommentEnded(): void {
const c = this.getCodeNorm();
if (c !== GREATER) {
this.fail("malformed comment.");
// <!-- blah -- bloo --> will be recorded as
// a comment of " blah -- bloo "
this.text += `--${String.fromCodePoint(c)}`;
this.state = S_COMMENT;
}
else {
this.state = S_TEXT;
}
}
private sCData(): void {
if (this.captureToChar(CLOSE_BRACKET)) {
this.state = S_CDATA_ENDING;
}
}
private sCDataEnding(): void {
const c = this.getCodeNorm();
if (c === CLOSE_BRACKET) {
this.state = S_CDATA_ENDING_2;
}
else {
this.text += `]${String.fromCodePoint(c)}`;
this.state = S_CDATA;
}
}
private sCDataEnding2(): void {
const c = this.getCodeNorm();
switch (c) {
case GREATER: {
this.cdataHandler?.(this.text);
this.text = "";
this.state = S_TEXT;
break;
}
case CLOSE_BRACKET:
this.text += "]";
break;
default:
this.text += `]]${String.fromCodePoint(c)}`;
this.state = S_CDATA;
}
}
// We need this separate state to check the first character fo the pi target
// with this.nameStartCheck which allows less characters than this.nameCheck.
private sPIFirstChar(): void {
const c = this.getCodeNorm();
// This is first because in the case where the file is well-formed this is
// the branch taken. We optimize for well-formedness.
if (this.nameStartCheck(c)) {
this.piTarget += String.fromCodePoint(c);
this.state = S_PI_REST;
}
else if (c === QUESTION || isS(c)) {
this.fail("processing instruction without a target.");
this.state = c === QUESTION ? S_PI_ENDING : S_PI_BODY;
}
else {
this.fail("disallowed character in processing instruction name.");
this.piTarget += String.fromCodePoint(c);
this.state = S_PI_REST;
}
}
private sPIRest(): void {
// Capture characters into a piTarget while ``this.nameCheck`` run on the
// character read returns true.
const { chunk, i: start } = this;
// eslint-disable-next-line no-constant-condition
while (true) {
const c = this.getCodeNorm();
if (c === EOC) {
this.piTarget += chunk.slice(start);
return;
}
// NL cannot satisfy this.nameCheck so we don't have to test specifically
// for it.
if (!this.nameCheck(c)) {
this.piTarget += chunk.slice(start, this.prevI);
const isQuestion = c === QUESTION;
if (isQuestion || isS(c)) {
if (this.piTarget === "xml") {
if (!this.xmlDeclPossible) {
this.fail(
"an XML declaration must be at the start of the document.");
}
this.state = isQuestion ? S_XML_DECL_ENDING : S_XML_DECL_NAME_START;
}
else {
this.state = isQuestion ? S_PI_ENDING : S_PI_BODY;
}
}
else {
this.fail("disallowed character in processing instruction name.");
this.piTarget += String.fromCodePoint(c);
}
break;
}
}
}
private sPIBody(): void {
if (this.text.length === 0) {
const c = this.getCodeNorm();
if (c === QUESTION) {
this.state = S_PI_ENDING;
}
else if (!isS(c)) {
this.text = String.fromCodePoint(c);
}
}
// The question mark character is not valid inside any of the XML
// declaration name/value pairs.
else if (this.captureToChar(QUESTION)) {
this.state = S_PI_ENDING;
}
}
private sPIEnding(): void {
const c = this.getCodeNorm();
if (c === GREATER) {
const { piTarget } = this;
if (piTarget.toLowerCase() === "xml") {
this.fail(
"the XML declaration must appear at the start of the document.");
}
this.piHandler?.({
target: piTarget,
body: this.text,
});
this.piTarget = this.text = "";
this.state = S_TEXT;
}
else if (c === QUESTION) {
// We ran into ?? as part of a processing instruction. We initially took
// the first ? as a sign that the PI was ending, but it is not. So we have
// to add it to the body but we take the new ? as a sign that the PI is
// ending.
this.text += "?";
}
else {
this.text += `?${String.fromCodePoint(c)}`;
this.state = S_PI_BODY;
}
this.xmlDeclPossible = false;
}
private sXMLDeclNameStart(): void {
const c = this.skipSpaces();
// The question mark character is not valid inside any of the XML
// declaration name/value pairs.
if (c === QUESTION) {
// It is valid to go to S_XML_DECL_ENDING from this state.
this.state = S_XML_DECL_ENDING;
return;
}
if (c !== EOC) {
this.state = S_XML_DECL_NAME;
this.name = String.fromCodePoint(c);
}
}
private sXMLDeclName(): void {
const c = this.captureTo(XML_DECL_NAME_TERMINATOR);
// The question mark character is not valid inside any of the XML
// declaration name/value pairs.
if (c === QUESTION) {
this.state = S_XML_DECL_ENDING;
this.name += this.text;
this.text = "";
this.fail("XML declaration is incomplete.");
return;
}
if (!(isS(c) || c === EQUAL)) {
return;
}
this.name += this.text;
this.text = "";
if (!this.xmlDeclExpects.includes(this.name)) {
switch (this.name.length) {
case 0:
this.fail("did not expect any more name/value pairs.");
break;
case 1:
this.fail(`expected the name ${this.xmlDeclExpects[0]}.`);
break;
default:
this.fail(`expected one of ${this.xmlDeclExpects.join(", ")}`);
}
}
this.state = c === EQUAL ? S_XML_DECL_VALUE_START : S_XML_DECL_EQ;
}
private sXMLDeclEq(): void {
const c = this.getCodeNorm();
// The question mark character is not valid inside any of the XML
// declaration name/value pairs.
if (c === QUESTION) {
this.state = S_XML_DECL_ENDING;
this.fail("XML declaration is incomplete.");
return;
}
if (isS(c)) {
return;
}
if (c !== EQUAL) {
this.fail("value required.");
}
this.state = S_XML_DECL_VALUE_START;
}
private sXMLDeclValueStart(): void {
const c = this.getCodeNorm();
// The question mark character is not valid inside any of the XML
// declaration name/value pairs.
if (c === QUESTION) {
this.state = S_XML_DECL_ENDING;
this.fail("XML declaration is incomplete.");
return;
}
if (isS(c)) {
return;
}
if (!isQuote(c)) {
this.fail("value must be quoted.");
this.q = SPACE;
}
else {
this.q = c;
}
this.state = S_XML_DECL_VALUE;
}
private sXMLDeclValue(): void {
const c = this.captureTo([this.q!, QUESTION]);
// The question mark character is not valid inside any of the XML
// declaration name/value pairs.
if (c === QUESTION) {
this.state = S_XML_DECL_ENDING;
this.text = "";
this.fail("XML declaration is incomplete.");
return;
}
if (c === EOC) {
return;
}
const value = this.text;
this.text = "";
switch (this.name) {
case "version": {
this.xmlDeclExpects = ["encoding", "standalone"];
const version = value;
this.xmlDecl.version = version;
// This is the test specified by XML 1.0 but it is fine for XML 1.1.
if (!/^1\.[0-9]+$/.test(version)) {
this.fail("version number must match /^1\\.[0-9]+$/.");
}
// When forceXMLVersion is set, the XML declaration is ignored.
else if (!(this.opt.forceXMLVersion as boolean)) {
this.setXMLVersion(version);
}
break;
}
case "encoding":
if (!/^[A-Za-z][A-Za-z0-9._-]*$/.test(value)) {
this.fail("encoding value must match \
/^[A-Za-z0-9][A-Za-z0-9._-]*$/.");
}
this.xmlDeclExpects = ["standalone"];
this.xmlDecl.encoding = value;
break;
case "standalone":
if (value !== "yes" && value !== "no") {
this.fail("standalone value must match \"yes\" or \"no\".");
}
this.xmlDeclExpects = [];
this.xmlDecl.standalone = value;
break;
default:
// We don't need to raise an error here since we've already raised one
// when checking what name was expected.
}
this.name = "";
this.state = S_XML_DECL_SEPARATOR;
}
private sXMLDeclSeparator(): void {
const c = this.getCodeNorm();
// The question mark character is not valid inside any of the XML
// declaration name/value pairs.
if (c === QUESTION) {
// It is valid to go to S_XML_DECL_ENDING from this state.
this.state = S_XML_DECL_ENDING;
return;
}
if (!isS(c)) {
this.fail("whitespace required.");
this.unget();
}
this.state = S_XML_DECL_NAME_START;
}
private sXMLDeclEnding(): void {
const c = this.getCodeNorm();
if (c === GREATER) {
if (this.piTarget !== "xml") {
this.fail("processing instructions are not allowed before root.");
}
else if (this.name !== "version" &&
this.xmlDeclExpects.includes("version")) {
this.fail("XML declaration must contain a version.");
}
this.xmldeclHandler?.(this.xmlDecl);
this.name = "";
this.piTarget = this.text = "";
this.state = S_TEXT;
}
else {
// We got here because the previous character was a ?, but the question
// mark character is not valid inside any of the XML declaration
// name/value pairs.
this.fail(
"The character ? is disallowed anywhere in XML declarations.");
}
this.xmlDeclPossible = false;
}
private sOpenTag(): void {
const c = this.captureNameChars();
if (c === EOC) {
return;
}
const tag: SaxesTagIncomplete = this.tag = {
name: this.name,
attributes: Object.create(null) as Record<string, string>,
};
this.name = "";
if (this.xmlnsOpt) {
this.topNS = tag.ns = Object.create(null) as Record<string, string>;
}
this.openTagStartHandler?.(tag as StartTagForOptions<O>);
this.sawRoot = true;
if (!this.fragmentOpt && this.closedRoot) {
this.fail("documents may contain only one root.");
}
switch (c) {
case GREATER:
this.openTag();
break;
case FORWARD_SLASH:
this.state = S_OPEN_TAG_SLASH;
break;
default:
if (!isS(c)) {
this.fail("disallowed character in tag name.");
}
this.state = S_ATTRIB;
}
}
private sOpenTagSlash(): void {
if (this.getCode() === GREATER) {
this.openSelfClosingTag();
}
else {
this.fail("forward-slash in opening tag not followed by >.");
this.state = S_ATTRIB;
}
}
private sAttrib(): void {
const c = this.skipSpaces();
if (c === EOC) {
return;
}
if (isNameStartChar(c)) {
this.unget();
this.state = S_ATTRIB_NAME;
}
else if (c === GREATER) {
this.openTag();
}
else if (c === FORWARD_SLASH) {
this.state = S_OPEN_TAG_SLASH;
}
else {
this.fail("disallowed character in attribute name.");
}
}
private sAttribName(): void {
const c = this.captureNameChars();
if (c === EQUAL) {
this.state = S_ATTRIB_VALUE;
}
else if (isS(c)) {
this.state = S_ATTRIB_NAME_SAW_WHITE;
}
else if (c === GREATER) {
this.fail("attribute without value.");
this.pushAttrib(this.name, this.name);
this.name = this.text = "";
this.openTag();
}
else if (c !== EOC) {
this.fail("disallowed character in attribute name.");
}
}
private sAttribNameSawWhite(): void {
const c = this.skipSpaces();
switch (c) {
case EOC:
return;
case EQUAL:
this.state = S_ATTRIB_VALUE;
break;
default:
this.fail("attribute without value.");
// Should we do this???
// this.tag.attributes[this.name] = "";
this.text = "";
this.name = "";
if (c === GREATER) {
this.openTag();
}
else if (isNameStartChar(c)) {
this.unget();
this.state = S_ATTRIB_NAME;
}
else {
this.fail("disallowed character in attribute name.");
this.state = S_ATTRIB;
}
}
}
private sAttribValue(): void {
const c = this.getCodeNorm();
if (isQuote(c)) {
this.q = c;
this.state = S_ATTRIB_VALUE_QUOTED;
}
else if (!isS(c)) {
this.fail("unquoted attribute value.");
this.state = S_ATTRIB_VALUE_UNQUOTED;
this.unget();
}
}
private sAttribValueQuoted(): void {
// We deliberately do not use captureTo here. The specialized code we use
// here is faster than using captureTo.
const { q, chunk } = this;
let { i: start } = this;
// eslint-disable-next-line no-constant-condition
while (true) {
switch (this.getCode()) {
case q:
this.pushAttrib(this.name,
this.text + chunk.slice(start, this.prevI));
this.name = this.text = "";
this.q = null;
this.state = S_ATTRIB_VALUE_CLOSED;
return;
case AMP:
this.text += chunk.slice(start, this.prevI);
this.state = S_ENTITY;
this.entityReturnState = S_ATTRIB_VALUE_QUOTED;
return;
case NL:
case NL_LIKE:
case TAB:
this.text += `${chunk.slice(start, this.prevI)} `;
start = this.i;
break;
case LESS:
this.text += chunk.slice(start, this.prevI);
this.fail("disallowed character.");
return;
case EOC:
this.text += chunk.slice(start);
return;
default:
}
}
}
private sAttribValueClosed(): void {
const c = this.getCodeNorm();
if (isS(c)) {
this.state = S_ATTRIB;
}
else if (c === GREATER) {
this.openTag();
}
else if (c === FORWARD_SLASH) {
this.state = S_OPEN_TAG_SLASH;
}
else if (isNameStartChar(c)) {
this.fail("no whitespace between attributes.");
this.unget();
this.state = S_ATTRIB_NAME;
}
else {
this.fail("disallowed character in attribute name.");
}
}
private sAttribValueUnquoted(): void {
// We don't do anything regarding EOL or space handling for unquoted
// attributes. We already have failed by the time we get here, and the
// contract that saxes upholds states that upon failure, it is not safe to
// rely on the data passed to event handlers (other than
// ``onerror``). Passing "bad" data is not a problem.
const c = this.captureTo(ATTRIB_VALUE_UNQUOTED_TERMINATOR);
switch (c) {
case AMP:
this.state = S_ENTITY;
this.entityReturnState = S_ATTRIB_VALUE_UNQUOTED;
break;
case LESS:
this.fail("disallowed character.");
break;
case EOC:
break;
default:
if (this.text.includes("]]>")) {
this.fail("the string \"]]>\" is disallowed in char data.");
}
this.pushAttrib(this.name, this.text);
this.name = this.text = "";
if (c === GREATER) {
this.openTag();
}
else {
this.state = S_ATTRIB;
}
}
}
private sCloseTag(): void {
const c = this.captureNameChars();
if (c === GREATER) {
this.closeTag();
}
else if (isS(c)) {
this.state = S_CLOSE_TAG_SAW_WHITE;
}
else if (c !== EOC) {
this.fail("disallowed character in closing tag.");
}
}
private sCloseTagSawWhite(): void {
switch (this.skipSpaces()) {
case GREATER:
this.closeTag();
break;
case EOC:
break;
default:
this.fail("disallowed character in closing tag.");
}
}
// END OF STATE ENGINE METHODS
private handleTextInRoot(): void {
// This is essentially a specialized version of captureTo which is optimized
// for performing the ]]> check. A previous version of this code, checked
// ``this.text`` for the presence of ]]>. It simplified the code but was
// very costly when character data contained a lot of entities to be parsed.
//
// Since we are using a specialized loop, we also keep track of the presence
// of ]]> in text data. The sequence ]]> is forbidden to appear as-is.
//
let { i: start, forbiddenState } = this;
const { chunk, textHandler: handler } = this;
// eslint-disable-next-line no-labels, no-restricted-syntax
scanLoop:
// eslint-disable-next-line no-constant-condition
while (true) {
switch (this.getCode()) {
case LESS: {
this.state = S_OPEN_WAKA;
if (handler !== undefined) {
const { text } = this;
const slice = chunk.slice(start, this.prevI);
if (text.length !== 0) {
handler(text + slice);
this.text = "";
}
else if (slice.length !== 0) {
handler(slice);
}
}
forbiddenState = FORBIDDEN_START;
// eslint-disable-next-line no-labels
break scanLoop;
}
case AMP:
this.state = S_ENTITY;
this.entityReturnState = S_TEXT;
if (handler !== undefined) {
this.text += chunk.slice(start, this.prevI);
}
forbiddenState = FORBIDDEN_START;
// eslint-disable-next-line no-labels
break scanLoop;
case CLOSE_BRACKET:
switch (forbiddenState) {
case FORBIDDEN_START:
forbiddenState = FORBIDDEN_BRACKET;
break;
case FORBIDDEN_BRACKET:
forbiddenState = FORBIDDEN_BRACKET_BRACKET;
break;
case FORBIDDEN_BRACKET_BRACKET:
break;
default:
throw new Error("impossible state");
}
break;
case GREATER:
if (forbiddenState === FORBIDDEN_BRACKET_BRACKET) {
this.fail("the string \"]]>\" is disallowed in char data.");
}
forbiddenState = FORBIDDEN_START;
break;
case NL_LIKE:
if (handler !== undefined) {
this.text += `${chunk.slice(start, this.prevI)}\n`;
}
start = this.i;
forbiddenState = FORBIDDEN_START;
break;
case EOC:
if (handler !== undefined) {
this.text += chunk.slice(start);
}
// eslint-disable-next-line no-labels
break scanLoop;
default:
forbiddenState = FORBIDDEN_START;
}
}
this.forbiddenState = forbiddenState;
}
private handleTextOutsideRoot(): void {
// This is essentially a specialized version of captureTo which is optimized
// for a specialized task. We keep track of the presence of non-space
// characters in the text since these are errors when appearing outside the
// document root element.
let { i: start } = this;
const { chunk, textHandler: handler } = this;
let nonSpace = false;
// eslint-disable-next-line no-labels, no-restricted-syntax
outRootLoop:
// eslint-disable-next-line no-constant-condition
while (true) {
const code = this.getCode();
switch (code) {
case LESS: {
this.state = S_OPEN_WAKA;
if (handler !== undefined) {
const { text } = this;
const slice = chunk.slice(start, this.prevI);
if (text.length !== 0) {
handler(text + slice);
this.text = "";
}
else if (slice.length !== 0) {
handler(slice);
}
}
// eslint-disable-next-line no-labels
break outRootLoop;
}
case AMP:
this.state = S_ENTITY;
this.entityReturnState = S_TEXT;
if (handler !== undefined) {
this.text += chunk.slice(start, this.prevI);
}
nonSpace = true;
// eslint-disable-next-line no-labels
break outRootLoop;
case NL_LIKE:
if (handler !== undefined) {
this.text += `${chunk.slice(start, this.prevI)}\n`;
}
start = this.i;
break;
case EOC:
if (handler !== undefined) {
this.text += chunk.slice(start);
}
// eslint-disable-next-line no-labels
break outRootLoop;
default:
if (!isS(code)) {
nonSpace = true;
}
}
}
if (!nonSpace) {
return;
}
// We use the reportedTextBeforeRoot and reportedTextAfterRoot flags
// to avoid reporting errors for every single character that is out of
// place.
if (!this.sawRoot && !this.reportedTextBeforeRoot) {
this.fail("text data outside of root node.");
this.reportedTextBeforeRoot = true;
}
if (this.closedRoot && !this.reportedTextAfterRoot) {
this.fail("text data outside of root node.");
this.reportedTextAfterRoot = true;
}
}
private pushAttribNS(name: string, value: string): void {
const { prefix, local } = this.qname(name);
const attr = { name, prefix, local, value };
this.attribList.push(attr);
this.attributeHandler?.(attr as AttributeEventForOptions<O>);
if (prefix === "xmlns") {
const trimmed = value.trim();
if (this.currentXMLVersion === "1.0" && trimmed === "") {
this.fail("invalid attempt to undefine prefix in XML 1.0");
}
this.topNS![local] = trimmed;
nsPairCheck(this, local, trimmed);
}
else if (name === "xmlns") {
const trimmed = value.trim();
this.topNS![""] = trimmed;
nsPairCheck(this, "", trimmed);
}
}
private pushAttribPlain(name: string, value: string): void {
const attr = { name, value };
this.attribList.push(attr);
this.attributeHandler?.(attr as AttributeEventForOptions<O>);
}
/**
* End parsing. This performs final well-formedness checks and resets the
* parser to a clean state.
*
* @returns this
*/
private end(): this {
if (!this.sawRoot) {
this.fail("document must contain a root element.");
}
const { tags } = this;
while (tags.length > 0) {
const tag = tags.pop()!;
this.fail(`unclosed tag: ${tag.name}`);
}
if ((this.state !== S_BEGIN) && (this.state !== S_TEXT)) {
this.fail("unexpected end.");
}
const { text } = this;
if (text.length !== 0) {
this.textHandler?.(text);
this.text = "";
}
this._closed = true;
this.endHandler?.();
this._init();
return this;
}
/**
* Resolve a namespace prefix.
*
* @param prefix The prefix to resolve.
*
* @returns The namespace URI or ``undefined`` if the prefix is not defined.
*/
resolve(prefix: string): string | undefined {
let uri = this.topNS![prefix];
if (uri !== undefined) {
return uri;
}
const { tags } = this;
for (let index = tags.length - 1; index >= 0; index--) {
uri = tags[index]!.ns![prefix];
if (uri !== undefined) {
return uri;
}
}
uri = this.ns[prefix];
if (uri !== undefined) {
return uri;
}
return this.opt.resolvePrefix?.(prefix);
}
/**
* Parse a qname into its prefix and local name parts.
*
* @param name The name to parse
*
* @returns
*/
private qname(name: string): { prefix: string; local: string } {
// This is faster than using name.split(":").
const colon = name.indexOf(":");
if (colon === -1) {
return { prefix: "", local: name };
}
const local = name.slice(colon + 1);
const prefix = name.slice(0, colon);
if (prefix === "" || local === "" || local.includes(":")) {
this.fail(`malformed name: ${name}.`);
}
return { prefix, local };
}
private processAttribsNS(): void {
const { attribList } = this;
const tag = this.tag!;
{
// add namespace info to tag
const { prefix, local } = this.qname(tag.name);
tag.prefix = prefix;
tag.local = local;
const uri = tag.uri = this.resolve(prefix) ?? "";
if (prefix !== "") {
if (prefix === "xmlns") {
this.fail("tags may not have \"xmlns\" as prefix.");
}
if (uri === "") {
this.fail(`unbound namespace prefix: ${JSON.stringify(prefix)}.`);
tag.uri = prefix;
}
}
}
if (attribList.length === 0) {
return;
}
const { attributes } = tag;
const seen = new Set();
// Note: do not apply default ns to attributes:
// http://www.w3.org/TR/REC-xml-names/#defaulting
for (const attr of attribList as SaxesAttributeNSIncomplete[]) {
const { name, prefix, local } = attr;
let uri;
let eqname;
if (prefix === "") {
uri = name === "xmlns" ? XMLNS_NAMESPACE : "";
eqname = name;
}
else {
uri = this.resolve(prefix);
// if there's any attributes with an undefined namespace,
// then fail on them now.
if (uri === undefined) {
this.fail(`unbound namespace prefix: ${JSON.stringify(prefix)}.`);
uri = prefix;
}
eqname = `{${uri}}${local}`;
}
if (seen.has(eqname)) {
this.fail(`duplicate attribute: ${eqname}.`);
}
seen.add(eqname);
attr.uri = uri;
attributes[name] = attr;
}
this.attribList = [];
}
private processAttribsPlain(): void {
const { attribList } = this;
// eslint-disable-next-line prefer-destructuring
const attributes = this.tag!.attributes;
for (const { name, value } of attribList) {
if (attributes[name] !== undefined) {
this.fail(`duplicate attribute: ${name}.`);
}
attributes[name] = value;
}
this.attribList = [];
}
/**
* Handle a complete open tag. This parser code calls this once it has seen
* the whole tag. This method checks for well-formeness and then emits
* ``onopentag``.
*/
private openTag(): void {
this.processAttribs();
const { tags } = this;
const tag = this.tag as SaxesTag;
tag.isSelfClosing = false;
// There cannot be any pending text here due to the onopentagstart that was
// necessarily emitted before we get here. So we do not check text.
this.openTagHandler?.(tag as TagForOptions<O>);
tags.push(tag);
this.state = S_TEXT;
this.name = "";
}
/**
* Handle a complete self-closing tag. This parser code calls this once it has
* seen the whole tag. This method checks for well-formeness and then emits
* ``onopentag`` and ``onclosetag``.
*/
private openSelfClosingTag(): void {
this.processAttribs();
const { tags } = this;
const tag = this.tag as SaxesTag;
tag.isSelfClosing = true;
// There cannot be any pending text here due to the onopentagstart that was
// necessarily emitted before we get here. So we do not check text.
this.openTagHandler?.(tag as TagForOptions<O>);
this.closeTagHandler?.(tag as TagForOptions<O>);
const top = this.tag = tags[tags.length - 1] ?? null;
if (top === null) {
this.closedRoot = true;
}
this.state = S_TEXT;
this.name = "";
}
/**
* Handle a complete close tag. This parser code calls this once it has seen
* the whole tag. This method checks for well-formeness and then emits
* ``onclosetag``.
*/
private closeTag(): void {
const { tags, name } = this;
// Our state after this will be S_TEXT, no matter what, and we can clear
// tagName now.
this.state = S_TEXT;
this.name = "";
if (name === "") {
this.fail("weird empty close tag.");
this.text += "</>";
return;
}
const handler = this.closeTagHandler;
let l = tags.length;
while (l-- > 0) {
const tag = this.tag = tags.pop() as SaxesTag;
this.topNS = tag.ns!;
handler?.(tag as TagForOptions<O>);
if (tag.name === name) {
break;
}
this.fail("unexpected close tag.");
}
if (l === 0) {
this.closedRoot = true;
}
else if (l < 0) {
this.fail(`unmatched closing tag: ${name}.`);
this.text += `</${name}>`;
}
}
/**
* Resolves an entity. Makes any necessary well-formedness checks.
*
* @param entity The entity to resolve.
*
* @returns The parsed entity.
*/
private parseEntity(entity: string): string {
// startsWith would be significantly slower for this test.
if (entity[0] !== "#") {
const defined = this.ENTITIES[entity];
if (defined !== undefined) {
return defined;
}
this.fail(this.isName(entity) ? "undefined entity." :
"disallowed character in entity name.");
return `&${entity};`;
}
let num = NaN;
if (entity[1] === "x" && /^#x[0-9a-f]+$/i.test(entity)) {
num = parseInt(entity.slice(2), 16);
}
else if (/^#[0-9]+$/.test(entity)) {
num = parseInt(entity.slice(1), 10);
}
// The character reference is required to match the CHAR production.
if (!this.isChar(num)) {
this.fail("malformed character entity.");
return `&${entity};`;
}
return String.fromCodePoint(num);
}
} |
1,136 | (node: SaxesTagPlain) => {
expect(node).to.deep.equal({
name: "x",
attributes: {},
isSelfClosing: false,
});
seen = true;
} | type SaxesTagPlain =
Pick<SaxesTag, "name" | "attributes" | "isSelfClosing"> & {
attributes: Record<string, string>;
}; |
1,137 | fn(parser: SaxesParser): void {
parser.write("<r><![CDATA[ this is ]")
.write("]>")
.write("</r>")
.close();
} | class SaxesParser<O extends SaxesOptions = {}> {
private readonly fragmentOpt: boolean;
private readonly xmlnsOpt: boolean;
private readonly trackPosition: boolean;
private readonly fileName?: string;
private readonly nameStartCheck: (c: number) => boolean;
private readonly nameCheck: (c: number) => boolean;
private readonly isName: (name: string) => boolean;
private readonly ns!: Record<string, string>;
private openWakaBang!: string;
private text!: string;
private name!: string;
private piTarget!: string;
private entity!: string;
private q!: null | number;
private tags!: SaxesTagIncomplete[];
private tag!: SaxesTagIncomplete | null;
private topNS!: Record<string, string> | null;
private chunk!: string;
private chunkPosition!: number;
private i!: number;
//
// We use prevI to allow "ungetting" the previously read code point. Note
// however, that it is not safe to unget everything and anything. In
// particular ungetting EOL characters will screw positioning up.
//
// Practically, you must not unget a code which has any side effect beyond
// updating ``this.i`` and ``this.prevI``. Only EOL codes have such side
// effects.
//
private prevI!: number;
private carriedFromPrevious?: string;
private forbiddenState!: number;
private attribList!: (SaxesAttributeNSIncomplete | SaxesAttributePlain)[];
private state!: number;
private reportedTextBeforeRoot!: boolean;
private reportedTextAfterRoot!: boolean;
private closedRoot!: boolean;
private sawRoot!: boolean;
private xmlDeclPossible!: boolean;
private xmlDeclExpects!: string[];
private entityReturnState?: number;
private processAttribs!: (this: this) => void;
private positionAtNewLine!: number;
private doctype!: boolean;
private getCode!: () => number;
private isChar!: (c: number) => boolean;
private pushAttrib!: (name: string, value: string) => void;
private _closed!: boolean;
private currentXMLVersion!: string;
private readonly stateTable: ((this: SaxesParser<O>) => void)[];
private xmldeclHandler?: XMLDeclHandler;
private textHandler?: TextHandler;
private piHandler?: PIHandler;
private doctypeHandler?: DoctypeHandler;
private commentHandler?: CommentHandler;
private openTagStartHandler?: OpenTagStartHandler<O>;
private openTagHandler?: OpenTagHandler<O>;
private closeTagHandler?: CloseTagHandler<O>;
private cdataHandler?: CDataHandler;
private errorHandler?: ErrorHandler;
private endHandler?: EndHandler;
private readyHandler?: ReadyHandler;
private attributeHandler?: AttributeHandler<O>;
/**
* Indicates whether or not the parser is closed. If ``true``, wait for
* the ``ready`` event to write again.
*/
get closed(): boolean {
return this._closed;
}
readonly opt: SaxesOptions;
/**
* The XML declaration for this document.
*/
xmlDecl!: XMLDecl;
/**
* The line number of the next character to be read by the parser. This field
* is one-based. (The first line is numbered 1.)
*/
line!: number;
/**
* The column number of the next character to be read by the parser. *
* This field is zero-based. (The first column is 0.)
*
* This field counts columns by *Unicode character*. Note that this *can*
* be different from the index of the character in a JavaScript string due
* to how JavaScript handles astral plane characters.
*
* See [[columnIndex]] for a number that corresponds to the JavaScript index.
*/
column!: number;
/**
* A map of entity name to expansion.
*/
ENTITIES!: Record<string, string>;
/**
* @param opt The parser options.
*/
constructor(opt?: O) {
this.opt = opt ?? {};
this.fragmentOpt = !!(this.opt.fragment as boolean);
const xmlnsOpt = this.xmlnsOpt = !!(this.opt.xmlns as boolean);
this.trackPosition = this.opt.position !== false;
this.fileName = this.opt.fileName;
if (xmlnsOpt) {
// This is the function we use to perform name checks on PIs and entities.
// When namespaces are used, colons are not allowed in PI target names or
// entity names. So the check depends on whether namespaces are used. See:
//
// https://www.w3.org/XML/xml-names-19990114-errata.html
// NE08
//
this.nameStartCheck = isNCNameStartChar;
this.nameCheck = isNCNameChar;
this.isName = isNCName;
// eslint-disable-next-line @typescript-eslint/unbound-method
this.processAttribs = this.processAttribsNS;
// eslint-disable-next-line @typescript-eslint/unbound-method
this.pushAttrib = this.pushAttribNS;
// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-assignment
this.ns = { __proto__: null as any, ...rootNS };
const additional = this.opt.additionalNamespaces;
if (additional != null) {
nsMappingCheck(this, additional);
Object.assign(this.ns, additional);
}
}
else {
this.nameStartCheck = isNameStartChar;
this.nameCheck = isNameChar;
this.isName = isName;
// eslint-disable-next-line @typescript-eslint/unbound-method
this.processAttribs = this.processAttribsPlain;
// eslint-disable-next-line @typescript-eslint/unbound-method
this.pushAttrib = this.pushAttribPlain;
}
//
// The order of the members in this table needs to correspond to the state
// numbers given to the states that correspond to the methods being recorded
// here.
//
this.stateTable = [
/* eslint-disable @typescript-eslint/unbound-method */
this.sBegin,
this.sBeginWhitespace,
this.sDoctype,
this.sDoctypeQuote,
this.sDTD,
this.sDTDQuoted,
this.sDTDOpenWaka,
this.sDTDOpenWakaBang,
this.sDTDComment,
this.sDTDCommentEnding,
this.sDTDCommentEnded,
this.sDTDPI,
this.sDTDPIEnding,
this.sText,
this.sEntity,
this.sOpenWaka,
this.sOpenWakaBang,
this.sComment,
this.sCommentEnding,
this.sCommentEnded,
this.sCData,
this.sCDataEnding,
this.sCDataEnding2,
this.sPIFirstChar,
this.sPIRest,
this.sPIBody,
this.sPIEnding,
this.sXMLDeclNameStart,
this.sXMLDeclName,
this.sXMLDeclEq,
this.sXMLDeclValueStart,
this.sXMLDeclValue,
this.sXMLDeclSeparator,
this.sXMLDeclEnding,
this.sOpenTag,
this.sOpenTagSlash,
this.sAttrib,
this.sAttribName,
this.sAttribNameSawWhite,
this.sAttribValue,
this.sAttribValueQuoted,
this.sAttribValueClosed,
this.sAttribValueUnquoted,
this.sCloseTag,
this.sCloseTagSawWhite,
/* eslint-enable @typescript-eslint/unbound-method */
];
this._init();
}
_init(): void {
this.openWakaBang = "";
this.text = "";
this.name = "";
this.piTarget = "";
this.entity = "";
this.q = null;
this.tags = [];
this.tag = null;
this.topNS = null;
this.chunk = "";
this.chunkPosition = 0;
this.i = 0;
this.prevI = 0;
this.carriedFromPrevious = undefined;
this.forbiddenState = FORBIDDEN_START;
this.attribList = [];
// The logic is organized so as to minimize the need to check
// this.opt.fragment while parsing.
const { fragmentOpt } = this;
this.state = fragmentOpt ? S_TEXT : S_BEGIN;
// We want these to be all true if we are dealing with a fragment.
this.reportedTextBeforeRoot = this.reportedTextAfterRoot = this.closedRoot =
this.sawRoot = fragmentOpt;
// An XML declaration is intially possible only when parsing whole
// documents.
this.xmlDeclPossible = !fragmentOpt;
this.xmlDeclExpects = ["version"];
this.entityReturnState = undefined;
let { defaultXMLVersion } = this.opt;
if (defaultXMLVersion === undefined) {
if (this.opt.forceXMLVersion === true) {
throw new Error("forceXMLVersion set but defaultXMLVersion is not set");
}
defaultXMLVersion = "1.0";
}
this.setXMLVersion(defaultXMLVersion);
this.positionAtNewLine = 0;
this.doctype = false;
this._closed = false;
this.xmlDecl = {
version: undefined,
encoding: undefined,
standalone: undefined,
};
this.line = 1;
this.column = 0;
this.ENTITIES = Object.create(XML_ENTITIES) as Record<string, string>;
this.readyHandler?.();
}
/**
* The stream position the parser is currently looking at. This field is
* zero-based.
*
* This field is not based on counting Unicode characters but is to be
* interpreted as a plain index into a JavaScript string.
*/
get position(): number {
return this.chunkPosition + this.i;
}
/**
* The column number of the next character to be read by the parser. *
* This field is zero-based. (The first column in a line is 0.)
*
* This field reports the index at which the next character would be in the
* line if the line were represented as a JavaScript string. Note that this
* *can* be different to a count based on the number of *Unicode characters*
* due to how JavaScript handles astral plane characters.
*
* See [[column]] for a number that corresponds to a count of Unicode
* characters.
*/
get columnIndex(): number {
return this.position - this.positionAtNewLine;
}
/**
* Set an event listener on an event. The parser supports one handler per
* event type. If you try to set an event handler over an existing handler,
* the old handler is silently overwritten.
*
* @param name The event to listen to.
*
* @param handler The handler to set.
*/
on<N extends EventName>(name: N, handler: EventNameToHandler<O, N>): void {
// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-member-access
(this as any)[EVENT_NAME_TO_HANDLER_NAME[name]] = handler;
}
/**
* Unset an event handler.
*
* @parma name The event to stop listening to.
*/
off(name: EventName): void {
// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-member-access
(this as any)[EVENT_NAME_TO_HANDLER_NAME[name]] = undefined;
}
/**
* Make an error object. The error object will have a message that contains
* the ``fileName`` option passed at the creation of the parser. If position
* tracking was turned on, it will also have line and column number
* information.
*
* @param message The message describing the error to report.
*
* @returns An error object with a properly formatted message.
*/
makeError(message: string): Error {
let msg = this.fileName ?? "";
if (this.trackPosition) {
if (msg.length > 0) {
msg += ":";
}
msg += `${this.line}:${this.column}`;
}
if (msg.length > 0) {
msg += ": ";
}
return new Error(msg + message);
}
/**
* Report a parsing error. This method is made public so that client code may
* check for issues that are outside the scope of this project and can report
* errors.
*
* @param message The error to report.
*
* @returns this
*/
fail(message: string): this {
const err = this.makeError(message);
const handler = this.errorHandler;
if (handler === undefined) {
throw err;
}
else {
handler(err);
}
return this;
}
/**
* Write a XML data to the parser.
*
* @param chunk The XML data to write.
*
* @returns this
*/
// We do need object for the type here. Yes, it often causes problems
// but not in this case.
write(chunk: string | object | null): this {
if (this.closed) {
return this.fail("cannot write after close; assign an onready handler.");
}
let end = false;
if (chunk === null) {
// We cannot return immediately because carriedFromPrevious may need
// processing.
end = true;
chunk = "";
}
else if (typeof chunk === "object") {
chunk = chunk.toString();
}
// We checked if performing a pre-decomposition of the string into an array
// of single complete characters (``Array.from(chunk)``) would be faster
// than the current repeated calls to ``charCodeAt``. As of August 2018, it
// isn't. (There may be Node-specific code that would perform faster than
// ``Array.from`` but don't want to be dependent on Node.)
if (this.carriedFromPrevious !== undefined) {
// The previous chunk had char we must carry over.
chunk = `${this.carriedFromPrevious}${chunk}`;
this.carriedFromPrevious = undefined;
}
let limit = chunk.length;
const lastCode = chunk.charCodeAt(limit - 1);
if (!end &&
// A trailing CR or surrogate must be carried over to the next
// chunk.
(lastCode === CR || (lastCode >= 0xD800 && lastCode <= 0xDBFF))) {
// The chunk ends with a character that must be carried over. We cannot
// know how to handle it until we get the next chunk or the end of the
// stream. So save it for later.
this.carriedFromPrevious = chunk[limit - 1];
limit--;
chunk = chunk.slice(0, limit);
}
const { stateTable } = this;
this.chunk = chunk;
this.i = 0;
while (this.i < limit) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-argument
stateTable[this.state].call(this as any);
}
this.chunkPosition += limit;
return end ? this.end() : this;
}
/**
* Close the current stream. Perform final well-formedness checks and reset
* the parser tstate.
*
* @returns this
*/
close(): this {
return this.write(null);
}
/**
* Get a single code point out of the current chunk. This updates the current
* position if we do position tracking.
*
* This is the algorithm to use for XML 1.0.
*
* @returns The character read.
*/
private getCode10(): number {
const { chunk, i } = this;
this.prevI = i;
// Yes, we do this instead of doing this.i++. Doing it this way, we do not
// read this.i again, which is a bit faster.
this.i = i + 1;
if (i >= chunk.length) {
return EOC;
}
// Using charCodeAt and handling the surrogates ourselves is faster
// than using codePointAt.
const code = chunk.charCodeAt(i);
this.column++;
if (code < 0xD800) {
if (code >= SPACE || code === TAB) {
return code;
}
switch (code) {
case NL:
this.line++;
this.column = 0;
this.positionAtNewLine = this.position;
return NL;
case CR:
// We may get NaN if we read past the end of the chunk, which is fine.
if (chunk.charCodeAt(i + 1) === NL) {
// A \r\n sequence is converted to \n so we have to skip over the
// next character. We already know it has a size of 1 so ++ is fine
// here.
this.i = i + 2;
}
// Otherwise, a \r is just converted to \n, so we don't have to skip
// ahead.
// In either case, \r becomes \n.
this.line++;
this.column = 0;
this.positionAtNewLine = this.position;
return NL_LIKE;
default:
// If we get here, then code < SPACE and it is not NL CR or TAB.
this.fail("disallowed character.");
return code;
}
}
if (code > 0xDBFF) {
// This is a specialized version of isChar10 that takes into account
// that in this context code > 0xDBFF and code <= 0xFFFF. So it does not
// test cases that don't need testing.
if (!(code >= 0xE000 && code <= 0xFFFD)) {
this.fail("disallowed character.");
}
return code;
}
const final = 0x10000 + ((code - 0xD800) * 0x400) +
(chunk.charCodeAt(i + 1) - 0xDC00);
this.i = i + 2;
// This is a specialized version of isChar10 that takes into account that in
// this context necessarily final >= 0x10000.
if (final > 0x10FFFF) {
this.fail("disallowed character.");
}
return final;
}
/**
* Get a single code point out of the current chunk. This updates the current
* position if we do position tracking.
*
* This is the algorithm to use for XML 1.1.
*
* @returns {number} The character read.
*/
private getCode11(): number {
const { chunk, i } = this;
this.prevI = i;
// Yes, we do this instead of doing this.i++. Doing it this way, we do not
// read this.i again, which is a bit faster.
this.i = i + 1;
if (i >= chunk.length) {
return EOC;
}
// Using charCodeAt and handling the surrogates ourselves is faster
// than using codePointAt.
const code = chunk.charCodeAt(i);
this.column++;
if (code < 0xD800) {
if ((code > 0x1F && code < 0x7F) || (code > 0x9F && code !== LS) ||
code === TAB) {
return code;
}
switch (code) {
case NL: // 0xA
this.line++;
this.column = 0;
this.positionAtNewLine = this.position;
return NL;
case CR: { // 0xD
// We may get NaN if we read past the end of the chunk, which is
// fine.
const next = chunk.charCodeAt(i + 1);
if (next === NL || next === NEL) {
// A CR NL or CR NEL sequence is converted to NL so we have to skip
// over the next character. We already know it has a size of 1.
this.i = i + 2;
}
// Otherwise, a CR is just converted to NL, no skip.
}
/* yes, fall through */
case NEL: // 0x85
case LS: // Ox2028
this.line++;
this.column = 0;
this.positionAtNewLine = this.position;
return NL_LIKE;
default:
this.fail("disallowed character.");
return code;
}
}
if (code > 0xDBFF) {
// This is a specialized version of isCharAndNotRestricted that takes into
// account that in this context code > 0xDBFF and code <= 0xFFFF. So it
// does not test cases that don't need testing.
if (!(code >= 0xE000 && code <= 0xFFFD)) {
this.fail("disallowed character.");
}
return code;
}
const final = 0x10000 + ((code - 0xD800) * 0x400) +
(chunk.charCodeAt(i + 1) - 0xDC00);
this.i = i + 2;
// This is a specialized version of isCharAndNotRestricted that takes into
// account that in this context necessarily final >= 0x10000.
if (final > 0x10FFFF) {
this.fail("disallowed character.");
}
return final;
}
/**
* Like ``getCode`` but with the return value normalized so that ``NL`` is
* returned for ``NL_LIKE``.
*/
private getCodeNorm(): number {
const c = this.getCode();
return c === NL_LIKE ? NL : c;
}
private unget(): void {
this.i = this.prevI;
this.column--;
}
/**
* Capture characters into a buffer until encountering one of a set of
* characters.
*
* @param chars An array of codepoints. Encountering a character in the array
* ends the capture. (``chars`` may safely contain ``NL``.)
*
* @return The character code that made the capture end, or ``EOC`` if we hit
* the end of the chunk. The return value cannot be NL_LIKE: NL is returned
* instead.
*/
private captureTo(chars: number[]): number {
let { i: start } = this;
const { chunk } = this;
// eslint-disable-next-line no-constant-condition
while (true) {
const c = this.getCode();
const isNLLike = c === NL_LIKE;
const final = isNLLike ? NL : c;
if (final === EOC || chars.includes(final)) {
this.text += chunk.slice(start, this.prevI);
return final;
}
if (isNLLike) {
this.text += `${chunk.slice(start, this.prevI)}\n`;
start = this.i;
}
}
}
/**
* Capture characters into a buffer until encountering a character.
*
* @param char The codepoint that ends the capture. **NOTE ``char`` MAY NOT
* CONTAIN ``NL``.** Passing ``NL`` will result in buggy behavior.
*
* @return ``true`` if we ran into the character. Otherwise, we ran into the
* end of the current chunk.
*/
private captureToChar(char: number): boolean {
let { i: start } = this;
const { chunk } = this;
// eslint-disable-next-line no-constant-condition
while (true) {
let c = this.getCode();
switch (c) {
case NL_LIKE:
this.text += `${chunk.slice(start, this.prevI)}\n`;
start = this.i;
c = NL;
break;
case EOC:
this.text += chunk.slice(start);
return false;
default:
}
if (c === char) {
this.text += chunk.slice(start, this.prevI);
return true;
}
}
}
/**
* Capture characters that satisfy ``isNameChar`` into the ``name`` field of
* this parser.
*
* @return The character code that made the test fail, or ``EOC`` if we hit
* the end of the chunk. The return value cannot be NL_LIKE: NL is returned
* instead.
*/
private captureNameChars(): number {
const { chunk, i: start } = this;
// eslint-disable-next-line no-constant-condition
while (true) {
const c = this.getCode();
if (c === EOC) {
this.name += chunk.slice(start);
return EOC;
}
// NL is not a name char so we don't have to test specifically for it.
if (!isNameChar(c)) {
this.name += chunk.slice(start, this.prevI);
return c === NL_LIKE ? NL : c;
}
}
}
/**
* Skip white spaces.
*
* @return The character that ended the skip, or ``EOC`` if we hit
* the end of the chunk. The return value cannot be NL_LIKE: NL is returned
* instead.
*/
private skipSpaces(): number {
// eslint-disable-next-line no-constant-condition
while (true) {
const c = this.getCodeNorm();
if (c === EOC || !isS(c)) {
return c;
}
}
}
private setXMLVersion(version: string): void {
this.currentXMLVersion = version;
/* eslint-disable @typescript-eslint/unbound-method */
if (version === "1.0") {
this.isChar = isChar10;
this.getCode = this.getCode10;
}
else {
this.isChar = isChar11;
this.getCode = this.getCode11;
}
/* eslint-enable @typescript-eslint/unbound-method */
}
// STATE ENGINE METHODS
// This needs to be a state separate from S_BEGIN_WHITESPACE because we want
// to be sure never to come back to this state later.
private sBegin(): void {
// We are essentially peeking at the first character of the chunk. Since
// S_BEGIN can be in effect only when we start working on the first chunk,
// the index at which we must look is necessarily 0. Note also that the
// following test does not depend on decoding surrogates.
// If the initial character is 0xFEFF, ignore it.
if (this.chunk.charCodeAt(0) === 0xFEFF) {
this.i++;
this.column++;
}
this.state = S_BEGIN_WHITESPACE;
}
private sBeginWhitespace(): void {
// We need to know whether we've encountered spaces or not because as soon
// as we run into a space, an XML declaration is no longer possible. Rather
// than slow down skipSpaces even in places where we don't care whether it
// skipped anything or not, we check whether prevI is equal to the value of
// i from before we skip spaces.
const iBefore = this.i;
const c = this.skipSpaces();
if (this.prevI !== iBefore) {
this.xmlDeclPossible = false;
}
switch (c) {
case LESS:
this.state = S_OPEN_WAKA;
// We could naively call closeText but in this state, it is not normal
// to have text be filled with any data.
if (this.text.length !== 0) {
throw new Error("no-empty text at start");
}
break;
case EOC:
break;
default:
this.unget();
this.state = S_TEXT;
this.xmlDeclPossible = false;
}
}
private sDoctype(): void {
const c = this.captureTo(DOCTYPE_TERMINATOR);
switch (c) {
case GREATER: {
this.doctypeHandler?.(this.text);
this.text = "";
this.state = S_TEXT;
this.doctype = true; // just remember that we saw it.
break;
}
case EOC:
break;
default:
this.text += String.fromCodePoint(c);
if (c === OPEN_BRACKET) {
this.state = S_DTD;
}
else if (isQuote(c)) {
this.state = S_DOCTYPE_QUOTE;
this.q = c;
}
}
}
private sDoctypeQuote(): void {
const q = this.q!;
if (this.captureToChar(q)) {
this.text += String.fromCodePoint(q);
this.q = null;
this.state = S_DOCTYPE;
}
}
private sDTD(): void {
const c = this.captureTo(DTD_TERMINATOR);
if (c === EOC) {
return;
}
this.text += String.fromCodePoint(c);
if (c === CLOSE_BRACKET) {
this.state = S_DOCTYPE;
}
else if (c === LESS) {
this.state = S_DTD_OPEN_WAKA;
}
else if (isQuote(c)) {
this.state = S_DTD_QUOTED;
this.q = c;
}
}
private sDTDQuoted(): void {
const q = this.q!;
if (this.captureToChar(q)) {
this.text += String.fromCodePoint(q);
this.state = S_DTD;
this.q = null;
}
}
private sDTDOpenWaka(): void {
const c = this.getCodeNorm();
this.text += String.fromCodePoint(c);
switch (c) {
case BANG:
this.state = S_DTD_OPEN_WAKA_BANG;
this.openWakaBang = "";
break;
case QUESTION:
this.state = S_DTD_PI;
break;
default:
this.state = S_DTD;
}
}
private sDTDOpenWakaBang(): void {
const char = String.fromCodePoint(this.getCodeNorm());
const owb = this.openWakaBang += char;
this.text += char;
if (owb !== "-") {
this.state = owb === "--" ? S_DTD_COMMENT : S_DTD;
this.openWakaBang = "";
}
}
private sDTDComment(): void {
if (this.captureToChar(MINUS)) {
this.text += "-";
this.state = S_DTD_COMMENT_ENDING;
}
}
private sDTDCommentEnding(): void {
const c = this.getCodeNorm();
this.text += String.fromCodePoint(c);
this.state = c === MINUS ? S_DTD_COMMENT_ENDED : S_DTD_COMMENT;
}
private sDTDCommentEnded(): void {
const c = this.getCodeNorm();
this.text += String.fromCodePoint(c);
if (c === GREATER) {
this.state = S_DTD;
}
else {
this.fail("malformed comment.");
// <!-- blah -- bloo --> will be recorded as
// a comment of " blah -- bloo "
this.state = S_DTD_COMMENT;
}
}
private sDTDPI(): void {
if (this.captureToChar(QUESTION)) {
this.text += "?";
this.state = S_DTD_PI_ENDING;
}
}
private sDTDPIEnding(): void {
const c = this.getCodeNorm();
this.text += String.fromCodePoint(c);
if (c === GREATER) {
this.state = S_DTD;
}
}
private sText(): void {
//
// We did try a version of saxes where the S_TEXT state was split in two
// states: one for text inside the root element, and one for text
// outside. This was avoiding having to test this.tags.length to decide
// what implementation to actually use.
//
// Peformance testing on gigabyte-size files did not show any advantage to
// using the two states solution instead of the current one. Conversely, it
// made the code a bit more complicated elsewhere. For instance, a comment
// can appear before the root element so when a comment ended it was
// necessary to determine whether to return to the S_TEXT state or to the
// new text-outside-root state.
//
if (this.tags.length !== 0) {
this.handleTextInRoot();
}
else {
this.handleTextOutsideRoot();
}
}
private sEntity(): void {
// This is essentially a specialized version of captureToChar(SEMICOLON...)
let { i: start } = this;
const { chunk } = this;
// eslint-disable-next-line no-labels, no-restricted-syntax
loop:
// eslint-disable-next-line no-constant-condition
while (true) {
switch (this.getCode()) {
case NL_LIKE:
this.entity += `${chunk.slice(start, this.prevI)}\n`;
start = this.i;
break;
case SEMICOLON: {
const { entityReturnState } = this;
const entity = this.entity + chunk.slice(start, this.prevI);
this.state = entityReturnState!;
let parsed: string;
if (entity === "") {
this.fail("empty entity name.");
parsed = "&;";
}
else {
parsed = this.parseEntity(entity);
this.entity = "";
}
if (entityReturnState !== S_TEXT || this.textHandler !== undefined) {
this.text += parsed;
}
// eslint-disable-next-line no-labels
break loop;
}
case EOC:
this.entity += chunk.slice(start);
// eslint-disable-next-line no-labels
break loop;
default:
}
}
}
private sOpenWaka(): void {
// Reminder: a state handler is called with at least one character
// available in the current chunk. So the first call to get code inside of
// a state handler cannot return ``EOC``. That's why we don't test
// for it.
const c = this.getCode();
// either a /, ?, !, or text is coming next.
if (isNameStartChar(c)) {
this.state = S_OPEN_TAG;
this.unget();
this.xmlDeclPossible = false;
}
else {
switch (c) {
case FORWARD_SLASH:
this.state = S_CLOSE_TAG;
this.xmlDeclPossible = false;
break;
case BANG:
this.state = S_OPEN_WAKA_BANG;
this.openWakaBang = "";
this.xmlDeclPossible = false;
break;
case QUESTION:
this.state = S_PI_FIRST_CHAR;
break;
default:
this.fail("disallowed character in tag name");
this.state = S_TEXT;
this.xmlDeclPossible = false;
}
}
}
private sOpenWakaBang(): void {
this.openWakaBang += String.fromCodePoint(this.getCodeNorm());
switch (this.openWakaBang) {
case "[CDATA[":
if (!this.sawRoot && !this.reportedTextBeforeRoot) {
this.fail("text data outside of root node.");
this.reportedTextBeforeRoot = true;
}
if (this.closedRoot && !this.reportedTextAfterRoot) {
this.fail("text data outside of root node.");
this.reportedTextAfterRoot = true;
}
this.state = S_CDATA;
this.openWakaBang = "";
break;
case "--":
this.state = S_COMMENT;
this.openWakaBang = "";
break;
case "DOCTYPE":
this.state = S_DOCTYPE;
if (this.doctype || this.sawRoot) {
this.fail("inappropriately located doctype declaration.");
}
this.openWakaBang = "";
break;
default:
// 7 happens to be the maximum length of the string that can possibly
// match one of the cases above.
if (this.openWakaBang.length >= 7) {
this.fail("incorrect syntax.");
}
}
}
private sComment(): void {
if (this.captureToChar(MINUS)) {
this.state = S_COMMENT_ENDING;
}
}
private sCommentEnding(): void {
const c = this.getCodeNorm();
if (c === MINUS) {
this.state = S_COMMENT_ENDED;
this.commentHandler?.(this.text);
this.text = "";
}
else {
this.text += `-${String.fromCodePoint(c)}`;
this.state = S_COMMENT;
}
}
private sCommentEnded(): void {
const c = this.getCodeNorm();
if (c !== GREATER) {
this.fail("malformed comment.");
// <!-- blah -- bloo --> will be recorded as
// a comment of " blah -- bloo "
this.text += `--${String.fromCodePoint(c)}`;
this.state = S_COMMENT;
}
else {
this.state = S_TEXT;
}
}
private sCData(): void {
if (this.captureToChar(CLOSE_BRACKET)) {
this.state = S_CDATA_ENDING;
}
}
private sCDataEnding(): void {
const c = this.getCodeNorm();
if (c === CLOSE_BRACKET) {
this.state = S_CDATA_ENDING_2;
}
else {
this.text += `]${String.fromCodePoint(c)}`;
this.state = S_CDATA;
}
}
private sCDataEnding2(): void {
const c = this.getCodeNorm();
switch (c) {
case GREATER: {
this.cdataHandler?.(this.text);
this.text = "";
this.state = S_TEXT;
break;
}
case CLOSE_BRACKET:
this.text += "]";
break;
default:
this.text += `]]${String.fromCodePoint(c)}`;
this.state = S_CDATA;
}
}
// We need this separate state to check the first character fo the pi target
// with this.nameStartCheck which allows less characters than this.nameCheck.
private sPIFirstChar(): void {
const c = this.getCodeNorm();
// This is first because in the case where the file is well-formed this is
// the branch taken. We optimize for well-formedness.
if (this.nameStartCheck(c)) {
this.piTarget += String.fromCodePoint(c);
this.state = S_PI_REST;
}
else if (c === QUESTION || isS(c)) {
this.fail("processing instruction without a target.");
this.state = c === QUESTION ? S_PI_ENDING : S_PI_BODY;
}
else {
this.fail("disallowed character in processing instruction name.");
this.piTarget += String.fromCodePoint(c);
this.state = S_PI_REST;
}
}
private sPIRest(): void {
// Capture characters into a piTarget while ``this.nameCheck`` run on the
// character read returns true.
const { chunk, i: start } = this;
// eslint-disable-next-line no-constant-condition
while (true) {
const c = this.getCodeNorm();
if (c === EOC) {
this.piTarget += chunk.slice(start);
return;
}
// NL cannot satisfy this.nameCheck so we don't have to test specifically
// for it.
if (!this.nameCheck(c)) {
this.piTarget += chunk.slice(start, this.prevI);
const isQuestion = c === QUESTION;
if (isQuestion || isS(c)) {
if (this.piTarget === "xml") {
if (!this.xmlDeclPossible) {
this.fail(
"an XML declaration must be at the start of the document.");
}
this.state = isQuestion ? S_XML_DECL_ENDING : S_XML_DECL_NAME_START;
}
else {
this.state = isQuestion ? S_PI_ENDING : S_PI_BODY;
}
}
else {
this.fail("disallowed character in processing instruction name.");
this.piTarget += String.fromCodePoint(c);
}
break;
}
}
}
private sPIBody(): void {
if (this.text.length === 0) {
const c = this.getCodeNorm();
if (c === QUESTION) {
this.state = S_PI_ENDING;
}
else if (!isS(c)) {
this.text = String.fromCodePoint(c);
}
}
// The question mark character is not valid inside any of the XML
// declaration name/value pairs.
else if (this.captureToChar(QUESTION)) {
this.state = S_PI_ENDING;
}
}
private sPIEnding(): void {
const c = this.getCodeNorm();
if (c === GREATER) {
const { piTarget } = this;
if (piTarget.toLowerCase() === "xml") {
this.fail(
"the XML declaration must appear at the start of the document.");
}
this.piHandler?.({
target: piTarget,
body: this.text,
});
this.piTarget = this.text = "";
this.state = S_TEXT;
}
else if (c === QUESTION) {
// We ran into ?? as part of a processing instruction. We initially took
// the first ? as a sign that the PI was ending, but it is not. So we have
// to add it to the body but we take the new ? as a sign that the PI is
// ending.
this.text += "?";
}
else {
this.text += `?${String.fromCodePoint(c)}`;
this.state = S_PI_BODY;
}
this.xmlDeclPossible = false;
}
private sXMLDeclNameStart(): void {
const c = this.skipSpaces();
// The question mark character is not valid inside any of the XML
// declaration name/value pairs.
if (c === QUESTION) {
// It is valid to go to S_XML_DECL_ENDING from this state.
this.state = S_XML_DECL_ENDING;
return;
}
if (c !== EOC) {
this.state = S_XML_DECL_NAME;
this.name = String.fromCodePoint(c);
}
}
private sXMLDeclName(): void {
const c = this.captureTo(XML_DECL_NAME_TERMINATOR);
// The question mark character is not valid inside any of the XML
// declaration name/value pairs.
if (c === QUESTION) {
this.state = S_XML_DECL_ENDING;
this.name += this.text;
this.text = "";
this.fail("XML declaration is incomplete.");
return;
}
if (!(isS(c) || c === EQUAL)) {
return;
}
this.name += this.text;
this.text = "";
if (!this.xmlDeclExpects.includes(this.name)) {
switch (this.name.length) {
case 0:
this.fail("did not expect any more name/value pairs.");
break;
case 1:
this.fail(`expected the name ${this.xmlDeclExpects[0]}.`);
break;
default:
this.fail(`expected one of ${this.xmlDeclExpects.join(", ")}`);
}
}
this.state = c === EQUAL ? S_XML_DECL_VALUE_START : S_XML_DECL_EQ;
}
private sXMLDeclEq(): void {
const c = this.getCodeNorm();
// The question mark character is not valid inside any of the XML
// declaration name/value pairs.
if (c === QUESTION) {
this.state = S_XML_DECL_ENDING;
this.fail("XML declaration is incomplete.");
return;
}
if (isS(c)) {
return;
}
if (c !== EQUAL) {
this.fail("value required.");
}
this.state = S_XML_DECL_VALUE_START;
}
private sXMLDeclValueStart(): void {
const c = this.getCodeNorm();
// The question mark character is not valid inside any of the XML
// declaration name/value pairs.
if (c === QUESTION) {
this.state = S_XML_DECL_ENDING;
this.fail("XML declaration is incomplete.");
return;
}
if (isS(c)) {
return;
}
if (!isQuote(c)) {
this.fail("value must be quoted.");
this.q = SPACE;
}
else {
this.q = c;
}
this.state = S_XML_DECL_VALUE;
}
private sXMLDeclValue(): void {
const c = this.captureTo([this.q!, QUESTION]);
// The question mark character is not valid inside any of the XML
// declaration name/value pairs.
if (c === QUESTION) {
this.state = S_XML_DECL_ENDING;
this.text = "";
this.fail("XML declaration is incomplete.");
return;
}
if (c === EOC) {
return;
}
const value = this.text;
this.text = "";
switch (this.name) {
case "version": {
this.xmlDeclExpects = ["encoding", "standalone"];
const version = value;
this.xmlDecl.version = version;
// This is the test specified by XML 1.0 but it is fine for XML 1.1.
if (!/^1\.[0-9]+$/.test(version)) {
this.fail("version number must match /^1\\.[0-9]+$/.");
}
// When forceXMLVersion is set, the XML declaration is ignored.
else if (!(this.opt.forceXMLVersion as boolean)) {
this.setXMLVersion(version);
}
break;
}
case "encoding":
if (!/^[A-Za-z][A-Za-z0-9._-]*$/.test(value)) {
this.fail("encoding value must match \
/^[A-Za-z0-9][A-Za-z0-9._-]*$/.");
}
this.xmlDeclExpects = ["standalone"];
this.xmlDecl.encoding = value;
break;
case "standalone":
if (value !== "yes" && value !== "no") {
this.fail("standalone value must match \"yes\" or \"no\".");
}
this.xmlDeclExpects = [];
this.xmlDecl.standalone = value;
break;
default:
// We don't need to raise an error here since we've already raised one
// when checking what name was expected.
}
this.name = "";
this.state = S_XML_DECL_SEPARATOR;
}
private sXMLDeclSeparator(): void {
const c = this.getCodeNorm();
// The question mark character is not valid inside any of the XML
// declaration name/value pairs.
if (c === QUESTION) {
// It is valid to go to S_XML_DECL_ENDING from this state.
this.state = S_XML_DECL_ENDING;
return;
}
if (!isS(c)) {
this.fail("whitespace required.");
this.unget();
}
this.state = S_XML_DECL_NAME_START;
}
private sXMLDeclEnding(): void {
const c = this.getCodeNorm();
if (c === GREATER) {
if (this.piTarget !== "xml") {
this.fail("processing instructions are not allowed before root.");
}
else if (this.name !== "version" &&
this.xmlDeclExpects.includes("version")) {
this.fail("XML declaration must contain a version.");
}
this.xmldeclHandler?.(this.xmlDecl);
this.name = "";
this.piTarget = this.text = "";
this.state = S_TEXT;
}
else {
// We got here because the previous character was a ?, but the question
// mark character is not valid inside any of the XML declaration
// name/value pairs.
this.fail(
"The character ? is disallowed anywhere in XML declarations.");
}
this.xmlDeclPossible = false;
}
private sOpenTag(): void {
const c = this.captureNameChars();
if (c === EOC) {
return;
}
const tag: SaxesTagIncomplete = this.tag = {
name: this.name,
attributes: Object.create(null) as Record<string, string>,
};
this.name = "";
if (this.xmlnsOpt) {
this.topNS = tag.ns = Object.create(null) as Record<string, string>;
}
this.openTagStartHandler?.(tag as StartTagForOptions<O>);
this.sawRoot = true;
if (!this.fragmentOpt && this.closedRoot) {
this.fail("documents may contain only one root.");
}
switch (c) {
case GREATER:
this.openTag();
break;
case FORWARD_SLASH:
this.state = S_OPEN_TAG_SLASH;
break;
default:
if (!isS(c)) {
this.fail("disallowed character in tag name.");
}
this.state = S_ATTRIB;
}
}
private sOpenTagSlash(): void {
if (this.getCode() === GREATER) {
this.openSelfClosingTag();
}
else {
this.fail("forward-slash in opening tag not followed by >.");
this.state = S_ATTRIB;
}
}
private sAttrib(): void {
const c = this.skipSpaces();
if (c === EOC) {
return;
}
if (isNameStartChar(c)) {
this.unget();
this.state = S_ATTRIB_NAME;
}
else if (c === GREATER) {
this.openTag();
}
else if (c === FORWARD_SLASH) {
this.state = S_OPEN_TAG_SLASH;
}
else {
this.fail("disallowed character in attribute name.");
}
}
private sAttribName(): void {
const c = this.captureNameChars();
if (c === EQUAL) {
this.state = S_ATTRIB_VALUE;
}
else if (isS(c)) {
this.state = S_ATTRIB_NAME_SAW_WHITE;
}
else if (c === GREATER) {
this.fail("attribute without value.");
this.pushAttrib(this.name, this.name);
this.name = this.text = "";
this.openTag();
}
else if (c !== EOC) {
this.fail("disallowed character in attribute name.");
}
}
private sAttribNameSawWhite(): void {
const c = this.skipSpaces();
switch (c) {
case EOC:
return;
case EQUAL:
this.state = S_ATTRIB_VALUE;
break;
default:
this.fail("attribute without value.");
// Should we do this???
// this.tag.attributes[this.name] = "";
this.text = "";
this.name = "";
if (c === GREATER) {
this.openTag();
}
else if (isNameStartChar(c)) {
this.unget();
this.state = S_ATTRIB_NAME;
}
else {
this.fail("disallowed character in attribute name.");
this.state = S_ATTRIB;
}
}
}
private sAttribValue(): void {
const c = this.getCodeNorm();
if (isQuote(c)) {
this.q = c;
this.state = S_ATTRIB_VALUE_QUOTED;
}
else if (!isS(c)) {
this.fail("unquoted attribute value.");
this.state = S_ATTRIB_VALUE_UNQUOTED;
this.unget();
}
}
private sAttribValueQuoted(): void {
// We deliberately do not use captureTo here. The specialized code we use
// here is faster than using captureTo.
const { q, chunk } = this;
let { i: start } = this;
// eslint-disable-next-line no-constant-condition
while (true) {
switch (this.getCode()) {
case q:
this.pushAttrib(this.name,
this.text + chunk.slice(start, this.prevI));
this.name = this.text = "";
this.q = null;
this.state = S_ATTRIB_VALUE_CLOSED;
return;
case AMP:
this.text += chunk.slice(start, this.prevI);
this.state = S_ENTITY;
this.entityReturnState = S_ATTRIB_VALUE_QUOTED;
return;
case NL:
case NL_LIKE:
case TAB:
this.text += `${chunk.slice(start, this.prevI)} `;
start = this.i;
break;
case LESS:
this.text += chunk.slice(start, this.prevI);
this.fail("disallowed character.");
return;
case EOC:
this.text += chunk.slice(start);
return;
default:
}
}
}
private sAttribValueClosed(): void {
const c = this.getCodeNorm();
if (isS(c)) {
this.state = S_ATTRIB;
}
else if (c === GREATER) {
this.openTag();
}
else if (c === FORWARD_SLASH) {
this.state = S_OPEN_TAG_SLASH;
}
else if (isNameStartChar(c)) {
this.fail("no whitespace between attributes.");
this.unget();
this.state = S_ATTRIB_NAME;
}
else {
this.fail("disallowed character in attribute name.");
}
}
private sAttribValueUnquoted(): void {
// We don't do anything regarding EOL or space handling for unquoted
// attributes. We already have failed by the time we get here, and the
// contract that saxes upholds states that upon failure, it is not safe to
// rely on the data passed to event handlers (other than
// ``onerror``). Passing "bad" data is not a problem.
const c = this.captureTo(ATTRIB_VALUE_UNQUOTED_TERMINATOR);
switch (c) {
case AMP:
this.state = S_ENTITY;
this.entityReturnState = S_ATTRIB_VALUE_UNQUOTED;
break;
case LESS:
this.fail("disallowed character.");
break;
case EOC:
break;
default:
if (this.text.includes("]]>")) {
this.fail("the string \"]]>\" is disallowed in char data.");
}
this.pushAttrib(this.name, this.text);
this.name = this.text = "";
if (c === GREATER) {
this.openTag();
}
else {
this.state = S_ATTRIB;
}
}
}
private sCloseTag(): void {
const c = this.captureNameChars();
if (c === GREATER) {
this.closeTag();
}
else if (isS(c)) {
this.state = S_CLOSE_TAG_SAW_WHITE;
}
else if (c !== EOC) {
this.fail("disallowed character in closing tag.");
}
}
private sCloseTagSawWhite(): void {
switch (this.skipSpaces()) {
case GREATER:
this.closeTag();
break;
case EOC:
break;
default:
this.fail("disallowed character in closing tag.");
}
}
// END OF STATE ENGINE METHODS
private handleTextInRoot(): void {
// This is essentially a specialized version of captureTo which is optimized
// for performing the ]]> check. A previous version of this code, checked
// ``this.text`` for the presence of ]]>. It simplified the code but was
// very costly when character data contained a lot of entities to be parsed.
//
// Since we are using a specialized loop, we also keep track of the presence
// of ]]> in text data. The sequence ]]> is forbidden to appear as-is.
//
let { i: start, forbiddenState } = this;
const { chunk, textHandler: handler } = this;
// eslint-disable-next-line no-labels, no-restricted-syntax
scanLoop:
// eslint-disable-next-line no-constant-condition
while (true) {
switch (this.getCode()) {
case LESS: {
this.state = S_OPEN_WAKA;
if (handler !== undefined) {
const { text } = this;
const slice = chunk.slice(start, this.prevI);
if (text.length !== 0) {
handler(text + slice);
this.text = "";
}
else if (slice.length !== 0) {
handler(slice);
}
}
forbiddenState = FORBIDDEN_START;
// eslint-disable-next-line no-labels
break scanLoop;
}
case AMP:
this.state = S_ENTITY;
this.entityReturnState = S_TEXT;
if (handler !== undefined) {
this.text += chunk.slice(start, this.prevI);
}
forbiddenState = FORBIDDEN_START;
// eslint-disable-next-line no-labels
break scanLoop;
case CLOSE_BRACKET:
switch (forbiddenState) {
case FORBIDDEN_START:
forbiddenState = FORBIDDEN_BRACKET;
break;
case FORBIDDEN_BRACKET:
forbiddenState = FORBIDDEN_BRACKET_BRACKET;
break;
case FORBIDDEN_BRACKET_BRACKET:
break;
default:
throw new Error("impossible state");
}
break;
case GREATER:
if (forbiddenState === FORBIDDEN_BRACKET_BRACKET) {
this.fail("the string \"]]>\" is disallowed in char data.");
}
forbiddenState = FORBIDDEN_START;
break;
case NL_LIKE:
if (handler !== undefined) {
this.text += `${chunk.slice(start, this.prevI)}\n`;
}
start = this.i;
forbiddenState = FORBIDDEN_START;
break;
case EOC:
if (handler !== undefined) {
this.text += chunk.slice(start);
}
// eslint-disable-next-line no-labels
break scanLoop;
default:
forbiddenState = FORBIDDEN_START;
}
}
this.forbiddenState = forbiddenState;
}
private handleTextOutsideRoot(): void {
// This is essentially a specialized version of captureTo which is optimized
// for a specialized task. We keep track of the presence of non-space
// characters in the text since these are errors when appearing outside the
// document root element.
let { i: start } = this;
const { chunk, textHandler: handler } = this;
let nonSpace = false;
// eslint-disable-next-line no-labels, no-restricted-syntax
outRootLoop:
// eslint-disable-next-line no-constant-condition
while (true) {
const code = this.getCode();
switch (code) {
case LESS: {
this.state = S_OPEN_WAKA;
if (handler !== undefined) {
const { text } = this;
const slice = chunk.slice(start, this.prevI);
if (text.length !== 0) {
handler(text + slice);
this.text = "";
}
else if (slice.length !== 0) {
handler(slice);
}
}
// eslint-disable-next-line no-labels
break outRootLoop;
}
case AMP:
this.state = S_ENTITY;
this.entityReturnState = S_TEXT;
if (handler !== undefined) {
this.text += chunk.slice(start, this.prevI);
}
nonSpace = true;
// eslint-disable-next-line no-labels
break outRootLoop;
case NL_LIKE:
if (handler !== undefined) {
this.text += `${chunk.slice(start, this.prevI)}\n`;
}
start = this.i;
break;
case EOC:
if (handler !== undefined) {
this.text += chunk.slice(start);
}
// eslint-disable-next-line no-labels
break outRootLoop;
default:
if (!isS(code)) {
nonSpace = true;
}
}
}
if (!nonSpace) {
return;
}
// We use the reportedTextBeforeRoot and reportedTextAfterRoot flags
// to avoid reporting errors for every single character that is out of
// place.
if (!this.sawRoot && !this.reportedTextBeforeRoot) {
this.fail("text data outside of root node.");
this.reportedTextBeforeRoot = true;
}
if (this.closedRoot && !this.reportedTextAfterRoot) {
this.fail("text data outside of root node.");
this.reportedTextAfterRoot = true;
}
}
private pushAttribNS(name: string, value: string): void {
const { prefix, local } = this.qname(name);
const attr = { name, prefix, local, value };
this.attribList.push(attr);
this.attributeHandler?.(attr as AttributeEventForOptions<O>);
if (prefix === "xmlns") {
const trimmed = value.trim();
if (this.currentXMLVersion === "1.0" && trimmed === "") {
this.fail("invalid attempt to undefine prefix in XML 1.0");
}
this.topNS![local] = trimmed;
nsPairCheck(this, local, trimmed);
}
else if (name === "xmlns") {
const trimmed = value.trim();
this.topNS![""] = trimmed;
nsPairCheck(this, "", trimmed);
}
}
private pushAttribPlain(name: string, value: string): void {
const attr = { name, value };
this.attribList.push(attr);
this.attributeHandler?.(attr as AttributeEventForOptions<O>);
}
/**
* End parsing. This performs final well-formedness checks and resets the
* parser to a clean state.
*
* @returns this
*/
private end(): this {
if (!this.sawRoot) {
this.fail("document must contain a root element.");
}
const { tags } = this;
while (tags.length > 0) {
const tag = tags.pop()!;
this.fail(`unclosed tag: ${tag.name}`);
}
if ((this.state !== S_BEGIN) && (this.state !== S_TEXT)) {
this.fail("unexpected end.");
}
const { text } = this;
if (text.length !== 0) {
this.textHandler?.(text);
this.text = "";
}
this._closed = true;
this.endHandler?.();
this._init();
return this;
}
/**
* Resolve a namespace prefix.
*
* @param prefix The prefix to resolve.
*
* @returns The namespace URI or ``undefined`` if the prefix is not defined.
*/
resolve(prefix: string): string | undefined {
let uri = this.topNS![prefix];
if (uri !== undefined) {
return uri;
}
const { tags } = this;
for (let index = tags.length - 1; index >= 0; index--) {
uri = tags[index]!.ns![prefix];
if (uri !== undefined) {
return uri;
}
}
uri = this.ns[prefix];
if (uri !== undefined) {
return uri;
}
return this.opt.resolvePrefix?.(prefix);
}
/**
* Parse a qname into its prefix and local name parts.
*
* @param name The name to parse
*
* @returns
*/
private qname(name: string): { prefix: string; local: string } {
// This is faster than using name.split(":").
const colon = name.indexOf(":");
if (colon === -1) {
return { prefix: "", local: name };
}
const local = name.slice(colon + 1);
const prefix = name.slice(0, colon);
if (prefix === "" || local === "" || local.includes(":")) {
this.fail(`malformed name: ${name}.`);
}
return { prefix, local };
}
private processAttribsNS(): void {
const { attribList } = this;
const tag = this.tag!;
{
// add namespace info to tag
const { prefix, local } = this.qname(tag.name);
tag.prefix = prefix;
tag.local = local;
const uri = tag.uri = this.resolve(prefix) ?? "";
if (prefix !== "") {
if (prefix === "xmlns") {
this.fail("tags may not have \"xmlns\" as prefix.");
}
if (uri === "") {
this.fail(`unbound namespace prefix: ${JSON.stringify(prefix)}.`);
tag.uri = prefix;
}
}
}
if (attribList.length === 0) {
return;
}
const { attributes } = tag;
const seen = new Set();
// Note: do not apply default ns to attributes:
// http://www.w3.org/TR/REC-xml-names/#defaulting
for (const attr of attribList as SaxesAttributeNSIncomplete[]) {
const { name, prefix, local } = attr;
let uri;
let eqname;
if (prefix === "") {
uri = name === "xmlns" ? XMLNS_NAMESPACE : "";
eqname = name;
}
else {
uri = this.resolve(prefix);
// if there's any attributes with an undefined namespace,
// then fail on them now.
if (uri === undefined) {
this.fail(`unbound namespace prefix: ${JSON.stringify(prefix)}.`);
uri = prefix;
}
eqname = `{${uri}}${local}`;
}
if (seen.has(eqname)) {
this.fail(`duplicate attribute: ${eqname}.`);
}
seen.add(eqname);
attr.uri = uri;
attributes[name] = attr;
}
this.attribList = [];
}
private processAttribsPlain(): void {
const { attribList } = this;
// eslint-disable-next-line prefer-destructuring
const attributes = this.tag!.attributes;
for (const { name, value } of attribList) {
if (attributes[name] !== undefined) {
this.fail(`duplicate attribute: ${name}.`);
}
attributes[name] = value;
}
this.attribList = [];
}
/**
* Handle a complete open tag. This parser code calls this once it has seen
* the whole tag. This method checks for well-formeness and then emits
* ``onopentag``.
*/
private openTag(): void {
this.processAttribs();
const { tags } = this;
const tag = this.tag as SaxesTag;
tag.isSelfClosing = false;
// There cannot be any pending text here due to the onopentagstart that was
// necessarily emitted before we get here. So we do not check text.
this.openTagHandler?.(tag as TagForOptions<O>);
tags.push(tag);
this.state = S_TEXT;
this.name = "";
}
/**
* Handle a complete self-closing tag. This parser code calls this once it has
* seen the whole tag. This method checks for well-formeness and then emits
* ``onopentag`` and ``onclosetag``.
*/
private openSelfClosingTag(): void {
this.processAttribs();
const { tags } = this;
const tag = this.tag as SaxesTag;
tag.isSelfClosing = true;
// There cannot be any pending text here due to the onopentagstart that was
// necessarily emitted before we get here. So we do not check text.
this.openTagHandler?.(tag as TagForOptions<O>);
this.closeTagHandler?.(tag as TagForOptions<O>);
const top = this.tag = tags[tags.length - 1] ?? null;
if (top === null) {
this.closedRoot = true;
}
this.state = S_TEXT;
this.name = "";
}
/**
* Handle a complete close tag. This parser code calls this once it has seen
* the whole tag. This method checks for well-formeness and then emits
* ``onclosetag``.
*/
private closeTag(): void {
const { tags, name } = this;
// Our state after this will be S_TEXT, no matter what, and we can clear
// tagName now.
this.state = S_TEXT;
this.name = "";
if (name === "") {
this.fail("weird empty close tag.");
this.text += "</>";
return;
}
const handler = this.closeTagHandler;
let l = tags.length;
while (l-- > 0) {
const tag = this.tag = tags.pop() as SaxesTag;
this.topNS = tag.ns!;
handler?.(tag as TagForOptions<O>);
if (tag.name === name) {
break;
}
this.fail("unexpected close tag.");
}
if (l === 0) {
this.closedRoot = true;
}
else if (l < 0) {
this.fail(`unmatched closing tag: ${name}.`);
this.text += `</${name}>`;
}
}
/**
* Resolves an entity. Makes any necessary well-formedness checks.
*
* @param entity The entity to resolve.
*
* @returns The parsed entity.
*/
private parseEntity(entity: string): string {
// startsWith would be significantly slower for this test.
if (entity[0] !== "#") {
const defined = this.ENTITIES[entity];
if (defined !== undefined) {
return defined;
}
this.fail(this.isName(entity) ? "undefined entity." :
"disallowed character in entity name.");
return `&${entity};`;
}
let num = NaN;
if (entity[1] === "x" && /^#x[0-9a-f]+$/i.test(entity)) {
num = parseInt(entity.slice(2), 16);
}
else if (/^#[0-9]+$/.test(entity)) {
num = parseInt(entity.slice(1), 10);
}
// The character reference is required to match the CHAR production.
if (!this.isChar(num)) {
this.fail("malformed character entity.");
return `&${entity};`;
}
return String.fromCodePoint(num);
}
} |
1,138 | fn(parser: SaxesParser): void {
parser.write("<root length=12").write("345></root>").close();
} | class SaxesParser<O extends SaxesOptions = {}> {
private readonly fragmentOpt: boolean;
private readonly xmlnsOpt: boolean;
private readonly trackPosition: boolean;
private readonly fileName?: string;
private readonly nameStartCheck: (c: number) => boolean;
private readonly nameCheck: (c: number) => boolean;
private readonly isName: (name: string) => boolean;
private readonly ns!: Record<string, string>;
private openWakaBang!: string;
private text!: string;
private name!: string;
private piTarget!: string;
private entity!: string;
private q!: null | number;
private tags!: SaxesTagIncomplete[];
private tag!: SaxesTagIncomplete | null;
private topNS!: Record<string, string> | null;
private chunk!: string;
private chunkPosition!: number;
private i!: number;
//
// We use prevI to allow "ungetting" the previously read code point. Note
// however, that it is not safe to unget everything and anything. In
// particular ungetting EOL characters will screw positioning up.
//
// Practically, you must not unget a code which has any side effect beyond
// updating ``this.i`` and ``this.prevI``. Only EOL codes have such side
// effects.
//
private prevI!: number;
private carriedFromPrevious?: string;
private forbiddenState!: number;
private attribList!: (SaxesAttributeNSIncomplete | SaxesAttributePlain)[];
private state!: number;
private reportedTextBeforeRoot!: boolean;
private reportedTextAfterRoot!: boolean;
private closedRoot!: boolean;
private sawRoot!: boolean;
private xmlDeclPossible!: boolean;
private xmlDeclExpects!: string[];
private entityReturnState?: number;
private processAttribs!: (this: this) => void;
private positionAtNewLine!: number;
private doctype!: boolean;
private getCode!: () => number;
private isChar!: (c: number) => boolean;
private pushAttrib!: (name: string, value: string) => void;
private _closed!: boolean;
private currentXMLVersion!: string;
private readonly stateTable: ((this: SaxesParser<O>) => void)[];
private xmldeclHandler?: XMLDeclHandler;
private textHandler?: TextHandler;
private piHandler?: PIHandler;
private doctypeHandler?: DoctypeHandler;
private commentHandler?: CommentHandler;
private openTagStartHandler?: OpenTagStartHandler<O>;
private openTagHandler?: OpenTagHandler<O>;
private closeTagHandler?: CloseTagHandler<O>;
private cdataHandler?: CDataHandler;
private errorHandler?: ErrorHandler;
private endHandler?: EndHandler;
private readyHandler?: ReadyHandler;
private attributeHandler?: AttributeHandler<O>;
/**
* Indicates whether or not the parser is closed. If ``true``, wait for
* the ``ready`` event to write again.
*/
get closed(): boolean {
return this._closed;
}
readonly opt: SaxesOptions;
/**
* The XML declaration for this document.
*/
xmlDecl!: XMLDecl;
/**
* The line number of the next character to be read by the parser. This field
* is one-based. (The first line is numbered 1.)
*/
line!: number;
/**
* The column number of the next character to be read by the parser. *
* This field is zero-based. (The first column is 0.)
*
* This field counts columns by *Unicode character*. Note that this *can*
* be different from the index of the character in a JavaScript string due
* to how JavaScript handles astral plane characters.
*
* See [[columnIndex]] for a number that corresponds to the JavaScript index.
*/
column!: number;
/**
* A map of entity name to expansion.
*/
ENTITIES!: Record<string, string>;
/**
* @param opt The parser options.
*/
constructor(opt?: O) {
this.opt = opt ?? {};
this.fragmentOpt = !!(this.opt.fragment as boolean);
const xmlnsOpt = this.xmlnsOpt = !!(this.opt.xmlns as boolean);
this.trackPosition = this.opt.position !== false;
this.fileName = this.opt.fileName;
if (xmlnsOpt) {
// This is the function we use to perform name checks on PIs and entities.
// When namespaces are used, colons are not allowed in PI target names or
// entity names. So the check depends on whether namespaces are used. See:
//
// https://www.w3.org/XML/xml-names-19990114-errata.html
// NE08
//
this.nameStartCheck = isNCNameStartChar;
this.nameCheck = isNCNameChar;
this.isName = isNCName;
// eslint-disable-next-line @typescript-eslint/unbound-method
this.processAttribs = this.processAttribsNS;
// eslint-disable-next-line @typescript-eslint/unbound-method
this.pushAttrib = this.pushAttribNS;
// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-assignment
this.ns = { __proto__: null as any, ...rootNS };
const additional = this.opt.additionalNamespaces;
if (additional != null) {
nsMappingCheck(this, additional);
Object.assign(this.ns, additional);
}
}
else {
this.nameStartCheck = isNameStartChar;
this.nameCheck = isNameChar;
this.isName = isName;
// eslint-disable-next-line @typescript-eslint/unbound-method
this.processAttribs = this.processAttribsPlain;
// eslint-disable-next-line @typescript-eslint/unbound-method
this.pushAttrib = this.pushAttribPlain;
}
//
// The order of the members in this table needs to correspond to the state
// numbers given to the states that correspond to the methods being recorded
// here.
//
this.stateTable = [
/* eslint-disable @typescript-eslint/unbound-method */
this.sBegin,
this.sBeginWhitespace,
this.sDoctype,
this.sDoctypeQuote,
this.sDTD,
this.sDTDQuoted,
this.sDTDOpenWaka,
this.sDTDOpenWakaBang,
this.sDTDComment,
this.sDTDCommentEnding,
this.sDTDCommentEnded,
this.sDTDPI,
this.sDTDPIEnding,
this.sText,
this.sEntity,
this.sOpenWaka,
this.sOpenWakaBang,
this.sComment,
this.sCommentEnding,
this.sCommentEnded,
this.sCData,
this.sCDataEnding,
this.sCDataEnding2,
this.sPIFirstChar,
this.sPIRest,
this.sPIBody,
this.sPIEnding,
this.sXMLDeclNameStart,
this.sXMLDeclName,
this.sXMLDeclEq,
this.sXMLDeclValueStart,
this.sXMLDeclValue,
this.sXMLDeclSeparator,
this.sXMLDeclEnding,
this.sOpenTag,
this.sOpenTagSlash,
this.sAttrib,
this.sAttribName,
this.sAttribNameSawWhite,
this.sAttribValue,
this.sAttribValueQuoted,
this.sAttribValueClosed,
this.sAttribValueUnquoted,
this.sCloseTag,
this.sCloseTagSawWhite,
/* eslint-enable @typescript-eslint/unbound-method */
];
this._init();
}
_init(): void {
this.openWakaBang = "";
this.text = "";
this.name = "";
this.piTarget = "";
this.entity = "";
this.q = null;
this.tags = [];
this.tag = null;
this.topNS = null;
this.chunk = "";
this.chunkPosition = 0;
this.i = 0;
this.prevI = 0;
this.carriedFromPrevious = undefined;
this.forbiddenState = FORBIDDEN_START;
this.attribList = [];
// The logic is organized so as to minimize the need to check
// this.opt.fragment while parsing.
const { fragmentOpt } = this;
this.state = fragmentOpt ? S_TEXT : S_BEGIN;
// We want these to be all true if we are dealing with a fragment.
this.reportedTextBeforeRoot = this.reportedTextAfterRoot = this.closedRoot =
this.sawRoot = fragmentOpt;
// An XML declaration is intially possible only when parsing whole
// documents.
this.xmlDeclPossible = !fragmentOpt;
this.xmlDeclExpects = ["version"];
this.entityReturnState = undefined;
let { defaultXMLVersion } = this.opt;
if (defaultXMLVersion === undefined) {
if (this.opt.forceXMLVersion === true) {
throw new Error("forceXMLVersion set but defaultXMLVersion is not set");
}
defaultXMLVersion = "1.0";
}
this.setXMLVersion(defaultXMLVersion);
this.positionAtNewLine = 0;
this.doctype = false;
this._closed = false;
this.xmlDecl = {
version: undefined,
encoding: undefined,
standalone: undefined,
};
this.line = 1;
this.column = 0;
this.ENTITIES = Object.create(XML_ENTITIES) as Record<string, string>;
this.readyHandler?.();
}
/**
* The stream position the parser is currently looking at. This field is
* zero-based.
*
* This field is not based on counting Unicode characters but is to be
* interpreted as a plain index into a JavaScript string.
*/
get position(): number {
return this.chunkPosition + this.i;
}
/**
* The column number of the next character to be read by the parser. *
* This field is zero-based. (The first column in a line is 0.)
*
* This field reports the index at which the next character would be in the
* line if the line were represented as a JavaScript string. Note that this
* *can* be different to a count based on the number of *Unicode characters*
* due to how JavaScript handles astral plane characters.
*
* See [[column]] for a number that corresponds to a count of Unicode
* characters.
*/
get columnIndex(): number {
return this.position - this.positionAtNewLine;
}
/**
* Set an event listener on an event. The parser supports one handler per
* event type. If you try to set an event handler over an existing handler,
* the old handler is silently overwritten.
*
* @param name The event to listen to.
*
* @param handler The handler to set.
*/
on<N extends EventName>(name: N, handler: EventNameToHandler<O, N>): void {
// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-member-access
(this as any)[EVENT_NAME_TO_HANDLER_NAME[name]] = handler;
}
/**
* Unset an event handler.
*
* @parma name The event to stop listening to.
*/
off(name: EventName): void {
// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-member-access
(this as any)[EVENT_NAME_TO_HANDLER_NAME[name]] = undefined;
}
/**
* Make an error object. The error object will have a message that contains
* the ``fileName`` option passed at the creation of the parser. If position
* tracking was turned on, it will also have line and column number
* information.
*
* @param message The message describing the error to report.
*
* @returns An error object with a properly formatted message.
*/
makeError(message: string): Error {
let msg = this.fileName ?? "";
if (this.trackPosition) {
if (msg.length > 0) {
msg += ":";
}
msg += `${this.line}:${this.column}`;
}
if (msg.length > 0) {
msg += ": ";
}
return new Error(msg + message);
}
/**
* Report a parsing error. This method is made public so that client code may
* check for issues that are outside the scope of this project and can report
* errors.
*
* @param message The error to report.
*
* @returns this
*/
fail(message: string): this {
const err = this.makeError(message);
const handler = this.errorHandler;
if (handler === undefined) {
throw err;
}
else {
handler(err);
}
return this;
}
/**
* Write a XML data to the parser.
*
* @param chunk The XML data to write.
*
* @returns this
*/
// We do need object for the type here. Yes, it often causes problems
// but not in this case.
write(chunk: string | object | null): this {
if (this.closed) {
return this.fail("cannot write after close; assign an onready handler.");
}
let end = false;
if (chunk === null) {
// We cannot return immediately because carriedFromPrevious may need
// processing.
end = true;
chunk = "";
}
else if (typeof chunk === "object") {
chunk = chunk.toString();
}
// We checked if performing a pre-decomposition of the string into an array
// of single complete characters (``Array.from(chunk)``) would be faster
// than the current repeated calls to ``charCodeAt``. As of August 2018, it
// isn't. (There may be Node-specific code that would perform faster than
// ``Array.from`` but don't want to be dependent on Node.)
if (this.carriedFromPrevious !== undefined) {
// The previous chunk had char we must carry over.
chunk = `${this.carriedFromPrevious}${chunk}`;
this.carriedFromPrevious = undefined;
}
let limit = chunk.length;
const lastCode = chunk.charCodeAt(limit - 1);
if (!end &&
// A trailing CR or surrogate must be carried over to the next
// chunk.
(lastCode === CR || (lastCode >= 0xD800 && lastCode <= 0xDBFF))) {
// The chunk ends with a character that must be carried over. We cannot
// know how to handle it until we get the next chunk or the end of the
// stream. So save it for later.
this.carriedFromPrevious = chunk[limit - 1];
limit--;
chunk = chunk.slice(0, limit);
}
const { stateTable } = this;
this.chunk = chunk;
this.i = 0;
while (this.i < limit) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-argument
stateTable[this.state].call(this as any);
}
this.chunkPosition += limit;
return end ? this.end() : this;
}
/**
* Close the current stream. Perform final well-formedness checks and reset
* the parser tstate.
*
* @returns this
*/
close(): this {
return this.write(null);
}
/**
* Get a single code point out of the current chunk. This updates the current
* position if we do position tracking.
*
* This is the algorithm to use for XML 1.0.
*
* @returns The character read.
*/
private getCode10(): number {
const { chunk, i } = this;
this.prevI = i;
// Yes, we do this instead of doing this.i++. Doing it this way, we do not
// read this.i again, which is a bit faster.
this.i = i + 1;
if (i >= chunk.length) {
return EOC;
}
// Using charCodeAt and handling the surrogates ourselves is faster
// than using codePointAt.
const code = chunk.charCodeAt(i);
this.column++;
if (code < 0xD800) {
if (code >= SPACE || code === TAB) {
return code;
}
switch (code) {
case NL:
this.line++;
this.column = 0;
this.positionAtNewLine = this.position;
return NL;
case CR:
// We may get NaN if we read past the end of the chunk, which is fine.
if (chunk.charCodeAt(i + 1) === NL) {
// A \r\n sequence is converted to \n so we have to skip over the
// next character. We already know it has a size of 1 so ++ is fine
// here.
this.i = i + 2;
}
// Otherwise, a \r is just converted to \n, so we don't have to skip
// ahead.
// In either case, \r becomes \n.
this.line++;
this.column = 0;
this.positionAtNewLine = this.position;
return NL_LIKE;
default:
// If we get here, then code < SPACE and it is not NL CR or TAB.
this.fail("disallowed character.");
return code;
}
}
if (code > 0xDBFF) {
// This is a specialized version of isChar10 that takes into account
// that in this context code > 0xDBFF and code <= 0xFFFF. So it does not
// test cases that don't need testing.
if (!(code >= 0xE000 && code <= 0xFFFD)) {
this.fail("disallowed character.");
}
return code;
}
const final = 0x10000 + ((code - 0xD800) * 0x400) +
(chunk.charCodeAt(i + 1) - 0xDC00);
this.i = i + 2;
// This is a specialized version of isChar10 that takes into account that in
// this context necessarily final >= 0x10000.
if (final > 0x10FFFF) {
this.fail("disallowed character.");
}
return final;
}
/**
* Get a single code point out of the current chunk. This updates the current
* position if we do position tracking.
*
* This is the algorithm to use for XML 1.1.
*
* @returns {number} The character read.
*/
private getCode11(): number {
const { chunk, i } = this;
this.prevI = i;
// Yes, we do this instead of doing this.i++. Doing it this way, we do not
// read this.i again, which is a bit faster.
this.i = i + 1;
if (i >= chunk.length) {
return EOC;
}
// Using charCodeAt and handling the surrogates ourselves is faster
// than using codePointAt.
const code = chunk.charCodeAt(i);
this.column++;
if (code < 0xD800) {
if ((code > 0x1F && code < 0x7F) || (code > 0x9F && code !== LS) ||
code === TAB) {
return code;
}
switch (code) {
case NL: // 0xA
this.line++;
this.column = 0;
this.positionAtNewLine = this.position;
return NL;
case CR: { // 0xD
// We may get NaN if we read past the end of the chunk, which is
// fine.
const next = chunk.charCodeAt(i + 1);
if (next === NL || next === NEL) {
// A CR NL or CR NEL sequence is converted to NL so we have to skip
// over the next character. We already know it has a size of 1.
this.i = i + 2;
}
// Otherwise, a CR is just converted to NL, no skip.
}
/* yes, fall through */
case NEL: // 0x85
case LS: // Ox2028
this.line++;
this.column = 0;
this.positionAtNewLine = this.position;
return NL_LIKE;
default:
this.fail("disallowed character.");
return code;
}
}
if (code > 0xDBFF) {
// This is a specialized version of isCharAndNotRestricted that takes into
// account that in this context code > 0xDBFF and code <= 0xFFFF. So it
// does not test cases that don't need testing.
if (!(code >= 0xE000 && code <= 0xFFFD)) {
this.fail("disallowed character.");
}
return code;
}
const final = 0x10000 + ((code - 0xD800) * 0x400) +
(chunk.charCodeAt(i + 1) - 0xDC00);
this.i = i + 2;
// This is a specialized version of isCharAndNotRestricted that takes into
// account that in this context necessarily final >= 0x10000.
if (final > 0x10FFFF) {
this.fail("disallowed character.");
}
return final;
}
/**
* Like ``getCode`` but with the return value normalized so that ``NL`` is
* returned for ``NL_LIKE``.
*/
private getCodeNorm(): number {
const c = this.getCode();
return c === NL_LIKE ? NL : c;
}
private unget(): void {
this.i = this.prevI;
this.column--;
}
/**
* Capture characters into a buffer until encountering one of a set of
* characters.
*
* @param chars An array of codepoints. Encountering a character in the array
* ends the capture. (``chars`` may safely contain ``NL``.)
*
* @return The character code that made the capture end, or ``EOC`` if we hit
* the end of the chunk. The return value cannot be NL_LIKE: NL is returned
* instead.
*/
private captureTo(chars: number[]): number {
let { i: start } = this;
const { chunk } = this;
// eslint-disable-next-line no-constant-condition
while (true) {
const c = this.getCode();
const isNLLike = c === NL_LIKE;
const final = isNLLike ? NL : c;
if (final === EOC || chars.includes(final)) {
this.text += chunk.slice(start, this.prevI);
return final;
}
if (isNLLike) {
this.text += `${chunk.slice(start, this.prevI)}\n`;
start = this.i;
}
}
}
/**
* Capture characters into a buffer until encountering a character.
*
* @param char The codepoint that ends the capture. **NOTE ``char`` MAY NOT
* CONTAIN ``NL``.** Passing ``NL`` will result in buggy behavior.
*
* @return ``true`` if we ran into the character. Otherwise, we ran into the
* end of the current chunk.
*/
private captureToChar(char: number): boolean {
let { i: start } = this;
const { chunk } = this;
// eslint-disable-next-line no-constant-condition
while (true) {
let c = this.getCode();
switch (c) {
case NL_LIKE:
this.text += `${chunk.slice(start, this.prevI)}\n`;
start = this.i;
c = NL;
break;
case EOC:
this.text += chunk.slice(start);
return false;
default:
}
if (c === char) {
this.text += chunk.slice(start, this.prevI);
return true;
}
}
}
/**
* Capture characters that satisfy ``isNameChar`` into the ``name`` field of
* this parser.
*
* @return The character code that made the test fail, or ``EOC`` if we hit
* the end of the chunk. The return value cannot be NL_LIKE: NL is returned
* instead.
*/
private captureNameChars(): number {
const { chunk, i: start } = this;
// eslint-disable-next-line no-constant-condition
while (true) {
const c = this.getCode();
if (c === EOC) {
this.name += chunk.slice(start);
return EOC;
}
// NL is not a name char so we don't have to test specifically for it.
if (!isNameChar(c)) {
this.name += chunk.slice(start, this.prevI);
return c === NL_LIKE ? NL : c;
}
}
}
/**
* Skip white spaces.
*
* @return The character that ended the skip, or ``EOC`` if we hit
* the end of the chunk. The return value cannot be NL_LIKE: NL is returned
* instead.
*/
private skipSpaces(): number {
// eslint-disable-next-line no-constant-condition
while (true) {
const c = this.getCodeNorm();
if (c === EOC || !isS(c)) {
return c;
}
}
}
private setXMLVersion(version: string): void {
this.currentXMLVersion = version;
/* eslint-disable @typescript-eslint/unbound-method */
if (version === "1.0") {
this.isChar = isChar10;
this.getCode = this.getCode10;
}
else {
this.isChar = isChar11;
this.getCode = this.getCode11;
}
/* eslint-enable @typescript-eslint/unbound-method */
}
// STATE ENGINE METHODS
// This needs to be a state separate from S_BEGIN_WHITESPACE because we want
// to be sure never to come back to this state later.
private sBegin(): void {
// We are essentially peeking at the first character of the chunk. Since
// S_BEGIN can be in effect only when we start working on the first chunk,
// the index at which we must look is necessarily 0. Note also that the
// following test does not depend on decoding surrogates.
// If the initial character is 0xFEFF, ignore it.
if (this.chunk.charCodeAt(0) === 0xFEFF) {
this.i++;
this.column++;
}
this.state = S_BEGIN_WHITESPACE;
}
private sBeginWhitespace(): void {
// We need to know whether we've encountered spaces or not because as soon
// as we run into a space, an XML declaration is no longer possible. Rather
// than slow down skipSpaces even in places where we don't care whether it
// skipped anything or not, we check whether prevI is equal to the value of
// i from before we skip spaces.
const iBefore = this.i;
const c = this.skipSpaces();
if (this.prevI !== iBefore) {
this.xmlDeclPossible = false;
}
switch (c) {
case LESS:
this.state = S_OPEN_WAKA;
// We could naively call closeText but in this state, it is not normal
// to have text be filled with any data.
if (this.text.length !== 0) {
throw new Error("no-empty text at start");
}
break;
case EOC:
break;
default:
this.unget();
this.state = S_TEXT;
this.xmlDeclPossible = false;
}
}
private sDoctype(): void {
const c = this.captureTo(DOCTYPE_TERMINATOR);
switch (c) {
case GREATER: {
this.doctypeHandler?.(this.text);
this.text = "";
this.state = S_TEXT;
this.doctype = true; // just remember that we saw it.
break;
}
case EOC:
break;
default:
this.text += String.fromCodePoint(c);
if (c === OPEN_BRACKET) {
this.state = S_DTD;
}
else if (isQuote(c)) {
this.state = S_DOCTYPE_QUOTE;
this.q = c;
}
}
}
private sDoctypeQuote(): void {
const q = this.q!;
if (this.captureToChar(q)) {
this.text += String.fromCodePoint(q);
this.q = null;
this.state = S_DOCTYPE;
}
}
private sDTD(): void {
const c = this.captureTo(DTD_TERMINATOR);
if (c === EOC) {
return;
}
this.text += String.fromCodePoint(c);
if (c === CLOSE_BRACKET) {
this.state = S_DOCTYPE;
}
else if (c === LESS) {
this.state = S_DTD_OPEN_WAKA;
}
else if (isQuote(c)) {
this.state = S_DTD_QUOTED;
this.q = c;
}
}
private sDTDQuoted(): void {
const q = this.q!;
if (this.captureToChar(q)) {
this.text += String.fromCodePoint(q);
this.state = S_DTD;
this.q = null;
}
}
private sDTDOpenWaka(): void {
const c = this.getCodeNorm();
this.text += String.fromCodePoint(c);
switch (c) {
case BANG:
this.state = S_DTD_OPEN_WAKA_BANG;
this.openWakaBang = "";
break;
case QUESTION:
this.state = S_DTD_PI;
break;
default:
this.state = S_DTD;
}
}
private sDTDOpenWakaBang(): void {
const char = String.fromCodePoint(this.getCodeNorm());
const owb = this.openWakaBang += char;
this.text += char;
if (owb !== "-") {
this.state = owb === "--" ? S_DTD_COMMENT : S_DTD;
this.openWakaBang = "";
}
}
private sDTDComment(): void {
if (this.captureToChar(MINUS)) {
this.text += "-";
this.state = S_DTD_COMMENT_ENDING;
}
}
private sDTDCommentEnding(): void {
const c = this.getCodeNorm();
this.text += String.fromCodePoint(c);
this.state = c === MINUS ? S_DTD_COMMENT_ENDED : S_DTD_COMMENT;
}
private sDTDCommentEnded(): void {
const c = this.getCodeNorm();
this.text += String.fromCodePoint(c);
if (c === GREATER) {
this.state = S_DTD;
}
else {
this.fail("malformed comment.");
// <!-- blah -- bloo --> will be recorded as
// a comment of " blah -- bloo "
this.state = S_DTD_COMMENT;
}
}
private sDTDPI(): void {
if (this.captureToChar(QUESTION)) {
this.text += "?";
this.state = S_DTD_PI_ENDING;
}
}
private sDTDPIEnding(): void {
const c = this.getCodeNorm();
this.text += String.fromCodePoint(c);
if (c === GREATER) {
this.state = S_DTD;
}
}
private sText(): void {
//
// We did try a version of saxes where the S_TEXT state was split in two
// states: one for text inside the root element, and one for text
// outside. This was avoiding having to test this.tags.length to decide
// what implementation to actually use.
//
// Peformance testing on gigabyte-size files did not show any advantage to
// using the two states solution instead of the current one. Conversely, it
// made the code a bit more complicated elsewhere. For instance, a comment
// can appear before the root element so when a comment ended it was
// necessary to determine whether to return to the S_TEXT state or to the
// new text-outside-root state.
//
if (this.tags.length !== 0) {
this.handleTextInRoot();
}
else {
this.handleTextOutsideRoot();
}
}
private sEntity(): void {
// This is essentially a specialized version of captureToChar(SEMICOLON...)
let { i: start } = this;
const { chunk } = this;
// eslint-disable-next-line no-labels, no-restricted-syntax
loop:
// eslint-disable-next-line no-constant-condition
while (true) {
switch (this.getCode()) {
case NL_LIKE:
this.entity += `${chunk.slice(start, this.prevI)}\n`;
start = this.i;
break;
case SEMICOLON: {
const { entityReturnState } = this;
const entity = this.entity + chunk.slice(start, this.prevI);
this.state = entityReturnState!;
let parsed: string;
if (entity === "") {
this.fail("empty entity name.");
parsed = "&;";
}
else {
parsed = this.parseEntity(entity);
this.entity = "";
}
if (entityReturnState !== S_TEXT || this.textHandler !== undefined) {
this.text += parsed;
}
// eslint-disable-next-line no-labels
break loop;
}
case EOC:
this.entity += chunk.slice(start);
// eslint-disable-next-line no-labels
break loop;
default:
}
}
}
private sOpenWaka(): void {
// Reminder: a state handler is called with at least one character
// available in the current chunk. So the first call to get code inside of
// a state handler cannot return ``EOC``. That's why we don't test
// for it.
const c = this.getCode();
// either a /, ?, !, or text is coming next.
if (isNameStartChar(c)) {
this.state = S_OPEN_TAG;
this.unget();
this.xmlDeclPossible = false;
}
else {
switch (c) {
case FORWARD_SLASH:
this.state = S_CLOSE_TAG;
this.xmlDeclPossible = false;
break;
case BANG:
this.state = S_OPEN_WAKA_BANG;
this.openWakaBang = "";
this.xmlDeclPossible = false;
break;
case QUESTION:
this.state = S_PI_FIRST_CHAR;
break;
default:
this.fail("disallowed character in tag name");
this.state = S_TEXT;
this.xmlDeclPossible = false;
}
}
}
private sOpenWakaBang(): void {
this.openWakaBang += String.fromCodePoint(this.getCodeNorm());
switch (this.openWakaBang) {
case "[CDATA[":
if (!this.sawRoot && !this.reportedTextBeforeRoot) {
this.fail("text data outside of root node.");
this.reportedTextBeforeRoot = true;
}
if (this.closedRoot && !this.reportedTextAfterRoot) {
this.fail("text data outside of root node.");
this.reportedTextAfterRoot = true;
}
this.state = S_CDATA;
this.openWakaBang = "";
break;
case "--":
this.state = S_COMMENT;
this.openWakaBang = "";
break;
case "DOCTYPE":
this.state = S_DOCTYPE;
if (this.doctype || this.sawRoot) {
this.fail("inappropriately located doctype declaration.");
}
this.openWakaBang = "";
break;
default:
// 7 happens to be the maximum length of the string that can possibly
// match one of the cases above.
if (this.openWakaBang.length >= 7) {
this.fail("incorrect syntax.");
}
}
}
private sComment(): void {
if (this.captureToChar(MINUS)) {
this.state = S_COMMENT_ENDING;
}
}
private sCommentEnding(): void {
const c = this.getCodeNorm();
if (c === MINUS) {
this.state = S_COMMENT_ENDED;
this.commentHandler?.(this.text);
this.text = "";
}
else {
this.text += `-${String.fromCodePoint(c)}`;
this.state = S_COMMENT;
}
}
private sCommentEnded(): void {
const c = this.getCodeNorm();
if (c !== GREATER) {
this.fail("malformed comment.");
// <!-- blah -- bloo --> will be recorded as
// a comment of " blah -- bloo "
this.text += `--${String.fromCodePoint(c)}`;
this.state = S_COMMENT;
}
else {
this.state = S_TEXT;
}
}
private sCData(): void {
if (this.captureToChar(CLOSE_BRACKET)) {
this.state = S_CDATA_ENDING;
}
}
private sCDataEnding(): void {
const c = this.getCodeNorm();
if (c === CLOSE_BRACKET) {
this.state = S_CDATA_ENDING_2;
}
else {
this.text += `]${String.fromCodePoint(c)}`;
this.state = S_CDATA;
}
}
private sCDataEnding2(): void {
const c = this.getCodeNorm();
switch (c) {
case GREATER: {
this.cdataHandler?.(this.text);
this.text = "";
this.state = S_TEXT;
break;
}
case CLOSE_BRACKET:
this.text += "]";
break;
default:
this.text += `]]${String.fromCodePoint(c)}`;
this.state = S_CDATA;
}
}
// We need this separate state to check the first character fo the pi target
// with this.nameStartCheck which allows less characters than this.nameCheck.
private sPIFirstChar(): void {
const c = this.getCodeNorm();
// This is first because in the case where the file is well-formed this is
// the branch taken. We optimize for well-formedness.
if (this.nameStartCheck(c)) {
this.piTarget += String.fromCodePoint(c);
this.state = S_PI_REST;
}
else if (c === QUESTION || isS(c)) {
this.fail("processing instruction without a target.");
this.state = c === QUESTION ? S_PI_ENDING : S_PI_BODY;
}
else {
this.fail("disallowed character in processing instruction name.");
this.piTarget += String.fromCodePoint(c);
this.state = S_PI_REST;
}
}
private sPIRest(): void {
// Capture characters into a piTarget while ``this.nameCheck`` run on the
// character read returns true.
const { chunk, i: start } = this;
// eslint-disable-next-line no-constant-condition
while (true) {
const c = this.getCodeNorm();
if (c === EOC) {
this.piTarget += chunk.slice(start);
return;
}
// NL cannot satisfy this.nameCheck so we don't have to test specifically
// for it.
if (!this.nameCheck(c)) {
this.piTarget += chunk.slice(start, this.prevI);
const isQuestion = c === QUESTION;
if (isQuestion || isS(c)) {
if (this.piTarget === "xml") {
if (!this.xmlDeclPossible) {
this.fail(
"an XML declaration must be at the start of the document.");
}
this.state = isQuestion ? S_XML_DECL_ENDING : S_XML_DECL_NAME_START;
}
else {
this.state = isQuestion ? S_PI_ENDING : S_PI_BODY;
}
}
else {
this.fail("disallowed character in processing instruction name.");
this.piTarget += String.fromCodePoint(c);
}
break;
}
}
}
private sPIBody(): void {
if (this.text.length === 0) {
const c = this.getCodeNorm();
if (c === QUESTION) {
this.state = S_PI_ENDING;
}
else if (!isS(c)) {
this.text = String.fromCodePoint(c);
}
}
// The question mark character is not valid inside any of the XML
// declaration name/value pairs.
else if (this.captureToChar(QUESTION)) {
this.state = S_PI_ENDING;
}
}
private sPIEnding(): void {
const c = this.getCodeNorm();
if (c === GREATER) {
const { piTarget } = this;
if (piTarget.toLowerCase() === "xml") {
this.fail(
"the XML declaration must appear at the start of the document.");
}
this.piHandler?.({
target: piTarget,
body: this.text,
});
this.piTarget = this.text = "";
this.state = S_TEXT;
}
else if (c === QUESTION) {
// We ran into ?? as part of a processing instruction. We initially took
// the first ? as a sign that the PI was ending, but it is not. So we have
// to add it to the body but we take the new ? as a sign that the PI is
// ending.
this.text += "?";
}
else {
this.text += `?${String.fromCodePoint(c)}`;
this.state = S_PI_BODY;
}
this.xmlDeclPossible = false;
}
private sXMLDeclNameStart(): void {
const c = this.skipSpaces();
// The question mark character is not valid inside any of the XML
// declaration name/value pairs.
if (c === QUESTION) {
// It is valid to go to S_XML_DECL_ENDING from this state.
this.state = S_XML_DECL_ENDING;
return;
}
if (c !== EOC) {
this.state = S_XML_DECL_NAME;
this.name = String.fromCodePoint(c);
}
}
private sXMLDeclName(): void {
const c = this.captureTo(XML_DECL_NAME_TERMINATOR);
// The question mark character is not valid inside any of the XML
// declaration name/value pairs.
if (c === QUESTION) {
this.state = S_XML_DECL_ENDING;
this.name += this.text;
this.text = "";
this.fail("XML declaration is incomplete.");
return;
}
if (!(isS(c) || c === EQUAL)) {
return;
}
this.name += this.text;
this.text = "";
if (!this.xmlDeclExpects.includes(this.name)) {
switch (this.name.length) {
case 0:
this.fail("did not expect any more name/value pairs.");
break;
case 1:
this.fail(`expected the name ${this.xmlDeclExpects[0]}.`);
break;
default:
this.fail(`expected one of ${this.xmlDeclExpects.join(", ")}`);
}
}
this.state = c === EQUAL ? S_XML_DECL_VALUE_START : S_XML_DECL_EQ;
}
private sXMLDeclEq(): void {
const c = this.getCodeNorm();
// The question mark character is not valid inside any of the XML
// declaration name/value pairs.
if (c === QUESTION) {
this.state = S_XML_DECL_ENDING;
this.fail("XML declaration is incomplete.");
return;
}
if (isS(c)) {
return;
}
if (c !== EQUAL) {
this.fail("value required.");
}
this.state = S_XML_DECL_VALUE_START;
}
private sXMLDeclValueStart(): void {
const c = this.getCodeNorm();
// The question mark character is not valid inside any of the XML
// declaration name/value pairs.
if (c === QUESTION) {
this.state = S_XML_DECL_ENDING;
this.fail("XML declaration is incomplete.");
return;
}
if (isS(c)) {
return;
}
if (!isQuote(c)) {
this.fail("value must be quoted.");
this.q = SPACE;
}
else {
this.q = c;
}
this.state = S_XML_DECL_VALUE;
}
private sXMLDeclValue(): void {
const c = this.captureTo([this.q!, QUESTION]);
// The question mark character is not valid inside any of the XML
// declaration name/value pairs.
if (c === QUESTION) {
this.state = S_XML_DECL_ENDING;
this.text = "";
this.fail("XML declaration is incomplete.");
return;
}
if (c === EOC) {
return;
}
const value = this.text;
this.text = "";
switch (this.name) {
case "version": {
this.xmlDeclExpects = ["encoding", "standalone"];
const version = value;
this.xmlDecl.version = version;
// This is the test specified by XML 1.0 but it is fine for XML 1.1.
if (!/^1\.[0-9]+$/.test(version)) {
this.fail("version number must match /^1\\.[0-9]+$/.");
}
// When forceXMLVersion is set, the XML declaration is ignored.
else if (!(this.opt.forceXMLVersion as boolean)) {
this.setXMLVersion(version);
}
break;
}
case "encoding":
if (!/^[A-Za-z][A-Za-z0-9._-]*$/.test(value)) {
this.fail("encoding value must match \
/^[A-Za-z0-9][A-Za-z0-9._-]*$/.");
}
this.xmlDeclExpects = ["standalone"];
this.xmlDecl.encoding = value;
break;
case "standalone":
if (value !== "yes" && value !== "no") {
this.fail("standalone value must match \"yes\" or \"no\".");
}
this.xmlDeclExpects = [];
this.xmlDecl.standalone = value;
break;
default:
// We don't need to raise an error here since we've already raised one
// when checking what name was expected.
}
this.name = "";
this.state = S_XML_DECL_SEPARATOR;
}
private sXMLDeclSeparator(): void {
const c = this.getCodeNorm();
// The question mark character is not valid inside any of the XML
// declaration name/value pairs.
if (c === QUESTION) {
// It is valid to go to S_XML_DECL_ENDING from this state.
this.state = S_XML_DECL_ENDING;
return;
}
if (!isS(c)) {
this.fail("whitespace required.");
this.unget();
}
this.state = S_XML_DECL_NAME_START;
}
private sXMLDeclEnding(): void {
const c = this.getCodeNorm();
if (c === GREATER) {
if (this.piTarget !== "xml") {
this.fail("processing instructions are not allowed before root.");
}
else if (this.name !== "version" &&
this.xmlDeclExpects.includes("version")) {
this.fail("XML declaration must contain a version.");
}
this.xmldeclHandler?.(this.xmlDecl);
this.name = "";
this.piTarget = this.text = "";
this.state = S_TEXT;
}
else {
// We got here because the previous character was a ?, but the question
// mark character is not valid inside any of the XML declaration
// name/value pairs.
this.fail(
"The character ? is disallowed anywhere in XML declarations.");
}
this.xmlDeclPossible = false;
}
private sOpenTag(): void {
const c = this.captureNameChars();
if (c === EOC) {
return;
}
const tag: SaxesTagIncomplete = this.tag = {
name: this.name,
attributes: Object.create(null) as Record<string, string>,
};
this.name = "";
if (this.xmlnsOpt) {
this.topNS = tag.ns = Object.create(null) as Record<string, string>;
}
this.openTagStartHandler?.(tag as StartTagForOptions<O>);
this.sawRoot = true;
if (!this.fragmentOpt && this.closedRoot) {
this.fail("documents may contain only one root.");
}
switch (c) {
case GREATER:
this.openTag();
break;
case FORWARD_SLASH:
this.state = S_OPEN_TAG_SLASH;
break;
default:
if (!isS(c)) {
this.fail("disallowed character in tag name.");
}
this.state = S_ATTRIB;
}
}
private sOpenTagSlash(): void {
if (this.getCode() === GREATER) {
this.openSelfClosingTag();
}
else {
this.fail("forward-slash in opening tag not followed by >.");
this.state = S_ATTRIB;
}
}
private sAttrib(): void {
const c = this.skipSpaces();
if (c === EOC) {
return;
}
if (isNameStartChar(c)) {
this.unget();
this.state = S_ATTRIB_NAME;
}
else if (c === GREATER) {
this.openTag();
}
else if (c === FORWARD_SLASH) {
this.state = S_OPEN_TAG_SLASH;
}
else {
this.fail("disallowed character in attribute name.");
}
}
private sAttribName(): void {
const c = this.captureNameChars();
if (c === EQUAL) {
this.state = S_ATTRIB_VALUE;
}
else if (isS(c)) {
this.state = S_ATTRIB_NAME_SAW_WHITE;
}
else if (c === GREATER) {
this.fail("attribute without value.");
this.pushAttrib(this.name, this.name);
this.name = this.text = "";
this.openTag();
}
else if (c !== EOC) {
this.fail("disallowed character in attribute name.");
}
}
private sAttribNameSawWhite(): void {
const c = this.skipSpaces();
switch (c) {
case EOC:
return;
case EQUAL:
this.state = S_ATTRIB_VALUE;
break;
default:
this.fail("attribute without value.");
// Should we do this???
// this.tag.attributes[this.name] = "";
this.text = "";
this.name = "";
if (c === GREATER) {
this.openTag();
}
else if (isNameStartChar(c)) {
this.unget();
this.state = S_ATTRIB_NAME;
}
else {
this.fail("disallowed character in attribute name.");
this.state = S_ATTRIB;
}
}
}
private sAttribValue(): void {
const c = this.getCodeNorm();
if (isQuote(c)) {
this.q = c;
this.state = S_ATTRIB_VALUE_QUOTED;
}
else if (!isS(c)) {
this.fail("unquoted attribute value.");
this.state = S_ATTRIB_VALUE_UNQUOTED;
this.unget();
}
}
private sAttribValueQuoted(): void {
// We deliberately do not use captureTo here. The specialized code we use
// here is faster than using captureTo.
const { q, chunk } = this;
let { i: start } = this;
// eslint-disable-next-line no-constant-condition
while (true) {
switch (this.getCode()) {
case q:
this.pushAttrib(this.name,
this.text + chunk.slice(start, this.prevI));
this.name = this.text = "";
this.q = null;
this.state = S_ATTRIB_VALUE_CLOSED;
return;
case AMP:
this.text += chunk.slice(start, this.prevI);
this.state = S_ENTITY;
this.entityReturnState = S_ATTRIB_VALUE_QUOTED;
return;
case NL:
case NL_LIKE:
case TAB:
this.text += `${chunk.slice(start, this.prevI)} `;
start = this.i;
break;
case LESS:
this.text += chunk.slice(start, this.prevI);
this.fail("disallowed character.");
return;
case EOC:
this.text += chunk.slice(start);
return;
default:
}
}
}
private sAttribValueClosed(): void {
const c = this.getCodeNorm();
if (isS(c)) {
this.state = S_ATTRIB;
}
else if (c === GREATER) {
this.openTag();
}
else if (c === FORWARD_SLASH) {
this.state = S_OPEN_TAG_SLASH;
}
else if (isNameStartChar(c)) {
this.fail("no whitespace between attributes.");
this.unget();
this.state = S_ATTRIB_NAME;
}
else {
this.fail("disallowed character in attribute name.");
}
}
private sAttribValueUnquoted(): void {
// We don't do anything regarding EOL or space handling for unquoted
// attributes. We already have failed by the time we get here, and the
// contract that saxes upholds states that upon failure, it is not safe to
// rely on the data passed to event handlers (other than
// ``onerror``). Passing "bad" data is not a problem.
const c = this.captureTo(ATTRIB_VALUE_UNQUOTED_TERMINATOR);
switch (c) {
case AMP:
this.state = S_ENTITY;
this.entityReturnState = S_ATTRIB_VALUE_UNQUOTED;
break;
case LESS:
this.fail("disallowed character.");
break;
case EOC:
break;
default:
if (this.text.includes("]]>")) {
this.fail("the string \"]]>\" is disallowed in char data.");
}
this.pushAttrib(this.name, this.text);
this.name = this.text = "";
if (c === GREATER) {
this.openTag();
}
else {
this.state = S_ATTRIB;
}
}
}
private sCloseTag(): void {
const c = this.captureNameChars();
if (c === GREATER) {
this.closeTag();
}
else if (isS(c)) {
this.state = S_CLOSE_TAG_SAW_WHITE;
}
else if (c !== EOC) {
this.fail("disallowed character in closing tag.");
}
}
private sCloseTagSawWhite(): void {
switch (this.skipSpaces()) {
case GREATER:
this.closeTag();
break;
case EOC:
break;
default:
this.fail("disallowed character in closing tag.");
}
}
// END OF STATE ENGINE METHODS
private handleTextInRoot(): void {
// This is essentially a specialized version of captureTo which is optimized
// for performing the ]]> check. A previous version of this code, checked
// ``this.text`` for the presence of ]]>. It simplified the code but was
// very costly when character data contained a lot of entities to be parsed.
//
// Since we are using a specialized loop, we also keep track of the presence
// of ]]> in text data. The sequence ]]> is forbidden to appear as-is.
//
let { i: start, forbiddenState } = this;
const { chunk, textHandler: handler } = this;
// eslint-disable-next-line no-labels, no-restricted-syntax
scanLoop:
// eslint-disable-next-line no-constant-condition
while (true) {
switch (this.getCode()) {
case LESS: {
this.state = S_OPEN_WAKA;
if (handler !== undefined) {
const { text } = this;
const slice = chunk.slice(start, this.prevI);
if (text.length !== 0) {
handler(text + slice);
this.text = "";
}
else if (slice.length !== 0) {
handler(slice);
}
}
forbiddenState = FORBIDDEN_START;
// eslint-disable-next-line no-labels
break scanLoop;
}
case AMP:
this.state = S_ENTITY;
this.entityReturnState = S_TEXT;
if (handler !== undefined) {
this.text += chunk.slice(start, this.prevI);
}
forbiddenState = FORBIDDEN_START;
// eslint-disable-next-line no-labels
break scanLoop;
case CLOSE_BRACKET:
switch (forbiddenState) {
case FORBIDDEN_START:
forbiddenState = FORBIDDEN_BRACKET;
break;
case FORBIDDEN_BRACKET:
forbiddenState = FORBIDDEN_BRACKET_BRACKET;
break;
case FORBIDDEN_BRACKET_BRACKET:
break;
default:
throw new Error("impossible state");
}
break;
case GREATER:
if (forbiddenState === FORBIDDEN_BRACKET_BRACKET) {
this.fail("the string \"]]>\" is disallowed in char data.");
}
forbiddenState = FORBIDDEN_START;
break;
case NL_LIKE:
if (handler !== undefined) {
this.text += `${chunk.slice(start, this.prevI)}\n`;
}
start = this.i;
forbiddenState = FORBIDDEN_START;
break;
case EOC:
if (handler !== undefined) {
this.text += chunk.slice(start);
}
// eslint-disable-next-line no-labels
break scanLoop;
default:
forbiddenState = FORBIDDEN_START;
}
}
this.forbiddenState = forbiddenState;
}
private handleTextOutsideRoot(): void {
// This is essentially a specialized version of captureTo which is optimized
// for a specialized task. We keep track of the presence of non-space
// characters in the text since these are errors when appearing outside the
// document root element.
let { i: start } = this;
const { chunk, textHandler: handler } = this;
let nonSpace = false;
// eslint-disable-next-line no-labels, no-restricted-syntax
outRootLoop:
// eslint-disable-next-line no-constant-condition
while (true) {
const code = this.getCode();
switch (code) {
case LESS: {
this.state = S_OPEN_WAKA;
if (handler !== undefined) {
const { text } = this;
const slice = chunk.slice(start, this.prevI);
if (text.length !== 0) {
handler(text + slice);
this.text = "";
}
else if (slice.length !== 0) {
handler(slice);
}
}
// eslint-disable-next-line no-labels
break outRootLoop;
}
case AMP:
this.state = S_ENTITY;
this.entityReturnState = S_TEXT;
if (handler !== undefined) {
this.text += chunk.slice(start, this.prevI);
}
nonSpace = true;
// eslint-disable-next-line no-labels
break outRootLoop;
case NL_LIKE:
if (handler !== undefined) {
this.text += `${chunk.slice(start, this.prevI)}\n`;
}
start = this.i;
break;
case EOC:
if (handler !== undefined) {
this.text += chunk.slice(start);
}
// eslint-disable-next-line no-labels
break outRootLoop;
default:
if (!isS(code)) {
nonSpace = true;
}
}
}
if (!nonSpace) {
return;
}
// We use the reportedTextBeforeRoot and reportedTextAfterRoot flags
// to avoid reporting errors for every single character that is out of
// place.
if (!this.sawRoot && !this.reportedTextBeforeRoot) {
this.fail("text data outside of root node.");
this.reportedTextBeforeRoot = true;
}
if (this.closedRoot && !this.reportedTextAfterRoot) {
this.fail("text data outside of root node.");
this.reportedTextAfterRoot = true;
}
}
private pushAttribNS(name: string, value: string): void {
const { prefix, local } = this.qname(name);
const attr = { name, prefix, local, value };
this.attribList.push(attr);
this.attributeHandler?.(attr as AttributeEventForOptions<O>);
if (prefix === "xmlns") {
const trimmed = value.trim();
if (this.currentXMLVersion === "1.0" && trimmed === "") {
this.fail("invalid attempt to undefine prefix in XML 1.0");
}
this.topNS![local] = trimmed;
nsPairCheck(this, local, trimmed);
}
else if (name === "xmlns") {
const trimmed = value.trim();
this.topNS![""] = trimmed;
nsPairCheck(this, "", trimmed);
}
}
private pushAttribPlain(name: string, value: string): void {
const attr = { name, value };
this.attribList.push(attr);
this.attributeHandler?.(attr as AttributeEventForOptions<O>);
}
/**
* End parsing. This performs final well-formedness checks and resets the
* parser to a clean state.
*
* @returns this
*/
private end(): this {
if (!this.sawRoot) {
this.fail("document must contain a root element.");
}
const { tags } = this;
while (tags.length > 0) {
const tag = tags.pop()!;
this.fail(`unclosed tag: ${tag.name}`);
}
if ((this.state !== S_BEGIN) && (this.state !== S_TEXT)) {
this.fail("unexpected end.");
}
const { text } = this;
if (text.length !== 0) {
this.textHandler?.(text);
this.text = "";
}
this._closed = true;
this.endHandler?.();
this._init();
return this;
}
/**
* Resolve a namespace prefix.
*
* @param prefix The prefix to resolve.
*
* @returns The namespace URI or ``undefined`` if the prefix is not defined.
*/
resolve(prefix: string): string | undefined {
let uri = this.topNS![prefix];
if (uri !== undefined) {
return uri;
}
const { tags } = this;
for (let index = tags.length - 1; index >= 0; index--) {
uri = tags[index]!.ns![prefix];
if (uri !== undefined) {
return uri;
}
}
uri = this.ns[prefix];
if (uri !== undefined) {
return uri;
}
return this.opt.resolvePrefix?.(prefix);
}
/**
* Parse a qname into its prefix and local name parts.
*
* @param name The name to parse
*
* @returns
*/
private qname(name: string): { prefix: string; local: string } {
// This is faster than using name.split(":").
const colon = name.indexOf(":");
if (colon === -1) {
return { prefix: "", local: name };
}
const local = name.slice(colon + 1);
const prefix = name.slice(0, colon);
if (prefix === "" || local === "" || local.includes(":")) {
this.fail(`malformed name: ${name}.`);
}
return { prefix, local };
}
private processAttribsNS(): void {
const { attribList } = this;
const tag = this.tag!;
{
// add namespace info to tag
const { prefix, local } = this.qname(tag.name);
tag.prefix = prefix;
tag.local = local;
const uri = tag.uri = this.resolve(prefix) ?? "";
if (prefix !== "") {
if (prefix === "xmlns") {
this.fail("tags may not have \"xmlns\" as prefix.");
}
if (uri === "") {
this.fail(`unbound namespace prefix: ${JSON.stringify(prefix)}.`);
tag.uri = prefix;
}
}
}
if (attribList.length === 0) {
return;
}
const { attributes } = tag;
const seen = new Set();
// Note: do not apply default ns to attributes:
// http://www.w3.org/TR/REC-xml-names/#defaulting
for (const attr of attribList as SaxesAttributeNSIncomplete[]) {
const { name, prefix, local } = attr;
let uri;
let eqname;
if (prefix === "") {
uri = name === "xmlns" ? XMLNS_NAMESPACE : "";
eqname = name;
}
else {
uri = this.resolve(prefix);
// if there's any attributes with an undefined namespace,
// then fail on them now.
if (uri === undefined) {
this.fail(`unbound namespace prefix: ${JSON.stringify(prefix)}.`);
uri = prefix;
}
eqname = `{${uri}}${local}`;
}
if (seen.has(eqname)) {
this.fail(`duplicate attribute: ${eqname}.`);
}
seen.add(eqname);
attr.uri = uri;
attributes[name] = attr;
}
this.attribList = [];
}
private processAttribsPlain(): void {
const { attribList } = this;
// eslint-disable-next-line prefer-destructuring
const attributes = this.tag!.attributes;
for (const { name, value } of attribList) {
if (attributes[name] !== undefined) {
this.fail(`duplicate attribute: ${name}.`);
}
attributes[name] = value;
}
this.attribList = [];
}
/**
* Handle a complete open tag. This parser code calls this once it has seen
* the whole tag. This method checks for well-formeness and then emits
* ``onopentag``.
*/
private openTag(): void {
this.processAttribs();
const { tags } = this;
const tag = this.tag as SaxesTag;
tag.isSelfClosing = false;
// There cannot be any pending text here due to the onopentagstart that was
// necessarily emitted before we get here. So we do not check text.
this.openTagHandler?.(tag as TagForOptions<O>);
tags.push(tag);
this.state = S_TEXT;
this.name = "";
}
/**
* Handle a complete self-closing tag. This parser code calls this once it has
* seen the whole tag. This method checks for well-formeness and then emits
* ``onopentag`` and ``onclosetag``.
*/
private openSelfClosingTag(): void {
this.processAttribs();
const { tags } = this;
const tag = this.tag as SaxesTag;
tag.isSelfClosing = true;
// There cannot be any pending text here due to the onopentagstart that was
// necessarily emitted before we get here. So we do not check text.
this.openTagHandler?.(tag as TagForOptions<O>);
this.closeTagHandler?.(tag as TagForOptions<O>);
const top = this.tag = tags[tags.length - 1] ?? null;
if (top === null) {
this.closedRoot = true;
}
this.state = S_TEXT;
this.name = "";
}
/**
* Handle a complete close tag. This parser code calls this once it has seen
* the whole tag. This method checks for well-formeness and then emits
* ``onclosetag``.
*/
private closeTag(): void {
const { tags, name } = this;
// Our state after this will be S_TEXT, no matter what, and we can clear
// tagName now.
this.state = S_TEXT;
this.name = "";
if (name === "") {
this.fail("weird empty close tag.");
this.text += "</>";
return;
}
const handler = this.closeTagHandler;
let l = tags.length;
while (l-- > 0) {
const tag = this.tag = tags.pop() as SaxesTag;
this.topNS = tag.ns!;
handler?.(tag as TagForOptions<O>);
if (tag.name === name) {
break;
}
this.fail("unexpected close tag.");
}
if (l === 0) {
this.closedRoot = true;
}
else if (l < 0) {
this.fail(`unmatched closing tag: ${name}.`);
this.text += `</${name}>`;
}
}
/**
* Resolves an entity. Makes any necessary well-formedness checks.
*
* @param entity The entity to resolve.
*
* @returns The parsed entity.
*/
private parseEntity(entity: string): string {
// startsWith would be significantly slower for this test.
if (entity[0] !== "#") {
const defined = this.ENTITIES[entity];
if (defined !== undefined) {
return defined;
}
this.fail(this.isName(entity) ? "undefined entity." :
"disallowed character in entity name.");
return `&${entity};`;
}
let num = NaN;
if (entity[1] === "x" && /^#x[0-9a-f]+$/i.test(entity)) {
num = parseInt(entity.slice(2), 16);
}
else if (/^#[0-9]+$/.test(entity)) {
num = parseInt(entity.slice(1), 10);
}
// The character reference is required to match the CHAR production.
if (!this.isChar(num)) {
this.fail("malformed character entity.");
return `&${entity};`;
}
return String.fromCodePoint(num);
}
} |
1,139 | fn(parser: SaxesParser): void {
const x = "<r><![CDATA[[[[[[[[[]]]]]]]]]]></r>";
for (let i = 0; i < x.length; i++) {
parser.write(x.charAt(i));
}
parser.close();
} | class SaxesParser<O extends SaxesOptions = {}> {
private readonly fragmentOpt: boolean;
private readonly xmlnsOpt: boolean;
private readonly trackPosition: boolean;
private readonly fileName?: string;
private readonly nameStartCheck: (c: number) => boolean;
private readonly nameCheck: (c: number) => boolean;
private readonly isName: (name: string) => boolean;
private readonly ns!: Record<string, string>;
private openWakaBang!: string;
private text!: string;
private name!: string;
private piTarget!: string;
private entity!: string;
private q!: null | number;
private tags!: SaxesTagIncomplete[];
private tag!: SaxesTagIncomplete | null;
private topNS!: Record<string, string> | null;
private chunk!: string;
private chunkPosition!: number;
private i!: number;
//
// We use prevI to allow "ungetting" the previously read code point. Note
// however, that it is not safe to unget everything and anything. In
// particular ungetting EOL characters will screw positioning up.
//
// Practically, you must not unget a code which has any side effect beyond
// updating ``this.i`` and ``this.prevI``. Only EOL codes have such side
// effects.
//
private prevI!: number;
private carriedFromPrevious?: string;
private forbiddenState!: number;
private attribList!: (SaxesAttributeNSIncomplete | SaxesAttributePlain)[];
private state!: number;
private reportedTextBeforeRoot!: boolean;
private reportedTextAfterRoot!: boolean;
private closedRoot!: boolean;
private sawRoot!: boolean;
private xmlDeclPossible!: boolean;
private xmlDeclExpects!: string[];
private entityReturnState?: number;
private processAttribs!: (this: this) => void;
private positionAtNewLine!: number;
private doctype!: boolean;
private getCode!: () => number;
private isChar!: (c: number) => boolean;
private pushAttrib!: (name: string, value: string) => void;
private _closed!: boolean;
private currentXMLVersion!: string;
private readonly stateTable: ((this: SaxesParser<O>) => void)[];
private xmldeclHandler?: XMLDeclHandler;
private textHandler?: TextHandler;
private piHandler?: PIHandler;
private doctypeHandler?: DoctypeHandler;
private commentHandler?: CommentHandler;
private openTagStartHandler?: OpenTagStartHandler<O>;
private openTagHandler?: OpenTagHandler<O>;
private closeTagHandler?: CloseTagHandler<O>;
private cdataHandler?: CDataHandler;
private errorHandler?: ErrorHandler;
private endHandler?: EndHandler;
private readyHandler?: ReadyHandler;
private attributeHandler?: AttributeHandler<O>;
/**
* Indicates whether or not the parser is closed. If ``true``, wait for
* the ``ready`` event to write again.
*/
get closed(): boolean {
return this._closed;
}
readonly opt: SaxesOptions;
/**
* The XML declaration for this document.
*/
xmlDecl!: XMLDecl;
/**
* The line number of the next character to be read by the parser. This field
* is one-based. (The first line is numbered 1.)
*/
line!: number;
/**
* The column number of the next character to be read by the parser. *
* This field is zero-based. (The first column is 0.)
*
* This field counts columns by *Unicode character*. Note that this *can*
* be different from the index of the character in a JavaScript string due
* to how JavaScript handles astral plane characters.
*
* See [[columnIndex]] for a number that corresponds to the JavaScript index.
*/
column!: number;
/**
* A map of entity name to expansion.
*/
ENTITIES!: Record<string, string>;
/**
* @param opt The parser options.
*/
constructor(opt?: O) {
this.opt = opt ?? {};
this.fragmentOpt = !!(this.opt.fragment as boolean);
const xmlnsOpt = this.xmlnsOpt = !!(this.opt.xmlns as boolean);
this.trackPosition = this.opt.position !== false;
this.fileName = this.opt.fileName;
if (xmlnsOpt) {
// This is the function we use to perform name checks on PIs and entities.
// When namespaces are used, colons are not allowed in PI target names or
// entity names. So the check depends on whether namespaces are used. See:
//
// https://www.w3.org/XML/xml-names-19990114-errata.html
// NE08
//
this.nameStartCheck = isNCNameStartChar;
this.nameCheck = isNCNameChar;
this.isName = isNCName;
// eslint-disable-next-line @typescript-eslint/unbound-method
this.processAttribs = this.processAttribsNS;
// eslint-disable-next-line @typescript-eslint/unbound-method
this.pushAttrib = this.pushAttribNS;
// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-assignment
this.ns = { __proto__: null as any, ...rootNS };
const additional = this.opt.additionalNamespaces;
if (additional != null) {
nsMappingCheck(this, additional);
Object.assign(this.ns, additional);
}
}
else {
this.nameStartCheck = isNameStartChar;
this.nameCheck = isNameChar;
this.isName = isName;
// eslint-disable-next-line @typescript-eslint/unbound-method
this.processAttribs = this.processAttribsPlain;
// eslint-disable-next-line @typescript-eslint/unbound-method
this.pushAttrib = this.pushAttribPlain;
}
//
// The order of the members in this table needs to correspond to the state
// numbers given to the states that correspond to the methods being recorded
// here.
//
this.stateTable = [
/* eslint-disable @typescript-eslint/unbound-method */
this.sBegin,
this.sBeginWhitespace,
this.sDoctype,
this.sDoctypeQuote,
this.sDTD,
this.sDTDQuoted,
this.sDTDOpenWaka,
this.sDTDOpenWakaBang,
this.sDTDComment,
this.sDTDCommentEnding,
this.sDTDCommentEnded,
this.sDTDPI,
this.sDTDPIEnding,
this.sText,
this.sEntity,
this.sOpenWaka,
this.sOpenWakaBang,
this.sComment,
this.sCommentEnding,
this.sCommentEnded,
this.sCData,
this.sCDataEnding,
this.sCDataEnding2,
this.sPIFirstChar,
this.sPIRest,
this.sPIBody,
this.sPIEnding,
this.sXMLDeclNameStart,
this.sXMLDeclName,
this.sXMLDeclEq,
this.sXMLDeclValueStart,
this.sXMLDeclValue,
this.sXMLDeclSeparator,
this.sXMLDeclEnding,
this.sOpenTag,
this.sOpenTagSlash,
this.sAttrib,
this.sAttribName,
this.sAttribNameSawWhite,
this.sAttribValue,
this.sAttribValueQuoted,
this.sAttribValueClosed,
this.sAttribValueUnquoted,
this.sCloseTag,
this.sCloseTagSawWhite,
/* eslint-enable @typescript-eslint/unbound-method */
];
this._init();
}
_init(): void {
this.openWakaBang = "";
this.text = "";
this.name = "";
this.piTarget = "";
this.entity = "";
this.q = null;
this.tags = [];
this.tag = null;
this.topNS = null;
this.chunk = "";
this.chunkPosition = 0;
this.i = 0;
this.prevI = 0;
this.carriedFromPrevious = undefined;
this.forbiddenState = FORBIDDEN_START;
this.attribList = [];
// The logic is organized so as to minimize the need to check
// this.opt.fragment while parsing.
const { fragmentOpt } = this;
this.state = fragmentOpt ? S_TEXT : S_BEGIN;
// We want these to be all true if we are dealing with a fragment.
this.reportedTextBeforeRoot = this.reportedTextAfterRoot = this.closedRoot =
this.sawRoot = fragmentOpt;
// An XML declaration is intially possible only when parsing whole
// documents.
this.xmlDeclPossible = !fragmentOpt;
this.xmlDeclExpects = ["version"];
this.entityReturnState = undefined;
let { defaultXMLVersion } = this.opt;
if (defaultXMLVersion === undefined) {
if (this.opt.forceXMLVersion === true) {
throw new Error("forceXMLVersion set but defaultXMLVersion is not set");
}
defaultXMLVersion = "1.0";
}
this.setXMLVersion(defaultXMLVersion);
this.positionAtNewLine = 0;
this.doctype = false;
this._closed = false;
this.xmlDecl = {
version: undefined,
encoding: undefined,
standalone: undefined,
};
this.line = 1;
this.column = 0;
this.ENTITIES = Object.create(XML_ENTITIES) as Record<string, string>;
this.readyHandler?.();
}
/**
* The stream position the parser is currently looking at. This field is
* zero-based.
*
* This field is not based on counting Unicode characters but is to be
* interpreted as a plain index into a JavaScript string.
*/
get position(): number {
return this.chunkPosition + this.i;
}
/**
* The column number of the next character to be read by the parser. *
* This field is zero-based. (The first column in a line is 0.)
*
* This field reports the index at which the next character would be in the
* line if the line were represented as a JavaScript string. Note that this
* *can* be different to a count based on the number of *Unicode characters*
* due to how JavaScript handles astral plane characters.
*
* See [[column]] for a number that corresponds to a count of Unicode
* characters.
*/
get columnIndex(): number {
return this.position - this.positionAtNewLine;
}
/**
* Set an event listener on an event. The parser supports one handler per
* event type. If you try to set an event handler over an existing handler,
* the old handler is silently overwritten.
*
* @param name The event to listen to.
*
* @param handler The handler to set.
*/
on<N extends EventName>(name: N, handler: EventNameToHandler<O, N>): void {
// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-member-access
(this as any)[EVENT_NAME_TO_HANDLER_NAME[name]] = handler;
}
/**
* Unset an event handler.
*
* @parma name The event to stop listening to.
*/
off(name: EventName): void {
// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-member-access
(this as any)[EVENT_NAME_TO_HANDLER_NAME[name]] = undefined;
}
/**
* Make an error object. The error object will have a message that contains
* the ``fileName`` option passed at the creation of the parser. If position
* tracking was turned on, it will also have line and column number
* information.
*
* @param message The message describing the error to report.
*
* @returns An error object with a properly formatted message.
*/
makeError(message: string): Error {
let msg = this.fileName ?? "";
if (this.trackPosition) {
if (msg.length > 0) {
msg += ":";
}
msg += `${this.line}:${this.column}`;
}
if (msg.length > 0) {
msg += ": ";
}
return new Error(msg + message);
}
/**
* Report a parsing error. This method is made public so that client code may
* check for issues that are outside the scope of this project and can report
* errors.
*
* @param message The error to report.
*
* @returns this
*/
fail(message: string): this {
const err = this.makeError(message);
const handler = this.errorHandler;
if (handler === undefined) {
throw err;
}
else {
handler(err);
}
return this;
}
/**
* Write a XML data to the parser.
*
* @param chunk The XML data to write.
*
* @returns this
*/
// We do need object for the type here. Yes, it often causes problems
// but not in this case.
write(chunk: string | object | null): this {
if (this.closed) {
return this.fail("cannot write after close; assign an onready handler.");
}
let end = false;
if (chunk === null) {
// We cannot return immediately because carriedFromPrevious may need
// processing.
end = true;
chunk = "";
}
else if (typeof chunk === "object") {
chunk = chunk.toString();
}
// We checked if performing a pre-decomposition of the string into an array
// of single complete characters (``Array.from(chunk)``) would be faster
// than the current repeated calls to ``charCodeAt``. As of August 2018, it
// isn't. (There may be Node-specific code that would perform faster than
// ``Array.from`` but don't want to be dependent on Node.)
if (this.carriedFromPrevious !== undefined) {
// The previous chunk had char we must carry over.
chunk = `${this.carriedFromPrevious}${chunk}`;
this.carriedFromPrevious = undefined;
}
let limit = chunk.length;
const lastCode = chunk.charCodeAt(limit - 1);
if (!end &&
// A trailing CR or surrogate must be carried over to the next
// chunk.
(lastCode === CR || (lastCode >= 0xD800 && lastCode <= 0xDBFF))) {
// The chunk ends with a character that must be carried over. We cannot
// know how to handle it until we get the next chunk or the end of the
// stream. So save it for later.
this.carriedFromPrevious = chunk[limit - 1];
limit--;
chunk = chunk.slice(0, limit);
}
const { stateTable } = this;
this.chunk = chunk;
this.i = 0;
while (this.i < limit) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-argument
stateTable[this.state].call(this as any);
}
this.chunkPosition += limit;
return end ? this.end() : this;
}
/**
* Close the current stream. Perform final well-formedness checks and reset
* the parser tstate.
*
* @returns this
*/
close(): this {
return this.write(null);
}
/**
* Get a single code point out of the current chunk. This updates the current
* position if we do position tracking.
*
* This is the algorithm to use for XML 1.0.
*
* @returns The character read.
*/
private getCode10(): number {
const { chunk, i } = this;
this.prevI = i;
// Yes, we do this instead of doing this.i++. Doing it this way, we do not
// read this.i again, which is a bit faster.
this.i = i + 1;
if (i >= chunk.length) {
return EOC;
}
// Using charCodeAt and handling the surrogates ourselves is faster
// than using codePointAt.
const code = chunk.charCodeAt(i);
this.column++;
if (code < 0xD800) {
if (code >= SPACE || code === TAB) {
return code;
}
switch (code) {
case NL:
this.line++;
this.column = 0;
this.positionAtNewLine = this.position;
return NL;
case CR:
// We may get NaN if we read past the end of the chunk, which is fine.
if (chunk.charCodeAt(i + 1) === NL) {
// A \r\n sequence is converted to \n so we have to skip over the
// next character. We already know it has a size of 1 so ++ is fine
// here.
this.i = i + 2;
}
// Otherwise, a \r is just converted to \n, so we don't have to skip
// ahead.
// In either case, \r becomes \n.
this.line++;
this.column = 0;
this.positionAtNewLine = this.position;
return NL_LIKE;
default:
// If we get here, then code < SPACE and it is not NL CR or TAB.
this.fail("disallowed character.");
return code;
}
}
if (code > 0xDBFF) {
// This is a specialized version of isChar10 that takes into account
// that in this context code > 0xDBFF and code <= 0xFFFF. So it does not
// test cases that don't need testing.
if (!(code >= 0xE000 && code <= 0xFFFD)) {
this.fail("disallowed character.");
}
return code;
}
const final = 0x10000 + ((code - 0xD800) * 0x400) +
(chunk.charCodeAt(i + 1) - 0xDC00);
this.i = i + 2;
// This is a specialized version of isChar10 that takes into account that in
// this context necessarily final >= 0x10000.
if (final > 0x10FFFF) {
this.fail("disallowed character.");
}
return final;
}
/**
* Get a single code point out of the current chunk. This updates the current
* position if we do position tracking.
*
* This is the algorithm to use for XML 1.1.
*
* @returns {number} The character read.
*/
private getCode11(): number {
const { chunk, i } = this;
this.prevI = i;
// Yes, we do this instead of doing this.i++. Doing it this way, we do not
// read this.i again, which is a bit faster.
this.i = i + 1;
if (i >= chunk.length) {
return EOC;
}
// Using charCodeAt and handling the surrogates ourselves is faster
// than using codePointAt.
const code = chunk.charCodeAt(i);
this.column++;
if (code < 0xD800) {
if ((code > 0x1F && code < 0x7F) || (code > 0x9F && code !== LS) ||
code === TAB) {
return code;
}
switch (code) {
case NL: // 0xA
this.line++;
this.column = 0;
this.positionAtNewLine = this.position;
return NL;
case CR: { // 0xD
// We may get NaN if we read past the end of the chunk, which is
// fine.
const next = chunk.charCodeAt(i + 1);
if (next === NL || next === NEL) {
// A CR NL or CR NEL sequence is converted to NL so we have to skip
// over the next character. We already know it has a size of 1.
this.i = i + 2;
}
// Otherwise, a CR is just converted to NL, no skip.
}
/* yes, fall through */
case NEL: // 0x85
case LS: // Ox2028
this.line++;
this.column = 0;
this.positionAtNewLine = this.position;
return NL_LIKE;
default:
this.fail("disallowed character.");
return code;
}
}
if (code > 0xDBFF) {
// This is a specialized version of isCharAndNotRestricted that takes into
// account that in this context code > 0xDBFF and code <= 0xFFFF. So it
// does not test cases that don't need testing.
if (!(code >= 0xE000 && code <= 0xFFFD)) {
this.fail("disallowed character.");
}
return code;
}
const final = 0x10000 + ((code - 0xD800) * 0x400) +
(chunk.charCodeAt(i + 1) - 0xDC00);
this.i = i + 2;
// This is a specialized version of isCharAndNotRestricted that takes into
// account that in this context necessarily final >= 0x10000.
if (final > 0x10FFFF) {
this.fail("disallowed character.");
}
return final;
}
/**
* Like ``getCode`` but with the return value normalized so that ``NL`` is
* returned for ``NL_LIKE``.
*/
private getCodeNorm(): number {
const c = this.getCode();
return c === NL_LIKE ? NL : c;
}
private unget(): void {
this.i = this.prevI;
this.column--;
}
/**
* Capture characters into a buffer until encountering one of a set of
* characters.
*
* @param chars An array of codepoints. Encountering a character in the array
* ends the capture. (``chars`` may safely contain ``NL``.)
*
* @return The character code that made the capture end, or ``EOC`` if we hit
* the end of the chunk. The return value cannot be NL_LIKE: NL is returned
* instead.
*/
private captureTo(chars: number[]): number {
let { i: start } = this;
const { chunk } = this;
// eslint-disable-next-line no-constant-condition
while (true) {
const c = this.getCode();
const isNLLike = c === NL_LIKE;
const final = isNLLike ? NL : c;
if (final === EOC || chars.includes(final)) {
this.text += chunk.slice(start, this.prevI);
return final;
}
if (isNLLike) {
this.text += `${chunk.slice(start, this.prevI)}\n`;
start = this.i;
}
}
}
/**
* Capture characters into a buffer until encountering a character.
*
* @param char The codepoint that ends the capture. **NOTE ``char`` MAY NOT
* CONTAIN ``NL``.** Passing ``NL`` will result in buggy behavior.
*
* @return ``true`` if we ran into the character. Otherwise, we ran into the
* end of the current chunk.
*/
private captureToChar(char: number): boolean {
let { i: start } = this;
const { chunk } = this;
// eslint-disable-next-line no-constant-condition
while (true) {
let c = this.getCode();
switch (c) {
case NL_LIKE:
this.text += `${chunk.slice(start, this.prevI)}\n`;
start = this.i;
c = NL;
break;
case EOC:
this.text += chunk.slice(start);
return false;
default:
}
if (c === char) {
this.text += chunk.slice(start, this.prevI);
return true;
}
}
}
/**
* Capture characters that satisfy ``isNameChar`` into the ``name`` field of
* this parser.
*
* @return The character code that made the test fail, or ``EOC`` if we hit
* the end of the chunk. The return value cannot be NL_LIKE: NL is returned
* instead.
*/
private captureNameChars(): number {
const { chunk, i: start } = this;
// eslint-disable-next-line no-constant-condition
while (true) {
const c = this.getCode();
if (c === EOC) {
this.name += chunk.slice(start);
return EOC;
}
// NL is not a name char so we don't have to test specifically for it.
if (!isNameChar(c)) {
this.name += chunk.slice(start, this.prevI);
return c === NL_LIKE ? NL : c;
}
}
}
/**
* Skip white spaces.
*
* @return The character that ended the skip, or ``EOC`` if we hit
* the end of the chunk. The return value cannot be NL_LIKE: NL is returned
* instead.
*/
private skipSpaces(): number {
// eslint-disable-next-line no-constant-condition
while (true) {
const c = this.getCodeNorm();
if (c === EOC || !isS(c)) {
return c;
}
}
}
private setXMLVersion(version: string): void {
this.currentXMLVersion = version;
/* eslint-disable @typescript-eslint/unbound-method */
if (version === "1.0") {
this.isChar = isChar10;
this.getCode = this.getCode10;
}
else {
this.isChar = isChar11;
this.getCode = this.getCode11;
}
/* eslint-enable @typescript-eslint/unbound-method */
}
// STATE ENGINE METHODS
// This needs to be a state separate from S_BEGIN_WHITESPACE because we want
// to be sure never to come back to this state later.
private sBegin(): void {
// We are essentially peeking at the first character of the chunk. Since
// S_BEGIN can be in effect only when we start working on the first chunk,
// the index at which we must look is necessarily 0. Note also that the
// following test does not depend on decoding surrogates.
// If the initial character is 0xFEFF, ignore it.
if (this.chunk.charCodeAt(0) === 0xFEFF) {
this.i++;
this.column++;
}
this.state = S_BEGIN_WHITESPACE;
}
private sBeginWhitespace(): void {
// We need to know whether we've encountered spaces or not because as soon
// as we run into a space, an XML declaration is no longer possible. Rather
// than slow down skipSpaces even in places where we don't care whether it
// skipped anything or not, we check whether prevI is equal to the value of
// i from before we skip spaces.
const iBefore = this.i;
const c = this.skipSpaces();
if (this.prevI !== iBefore) {
this.xmlDeclPossible = false;
}
switch (c) {
case LESS:
this.state = S_OPEN_WAKA;
// We could naively call closeText but in this state, it is not normal
// to have text be filled with any data.
if (this.text.length !== 0) {
throw new Error("no-empty text at start");
}
break;
case EOC:
break;
default:
this.unget();
this.state = S_TEXT;
this.xmlDeclPossible = false;
}
}
private sDoctype(): void {
const c = this.captureTo(DOCTYPE_TERMINATOR);
switch (c) {
case GREATER: {
this.doctypeHandler?.(this.text);
this.text = "";
this.state = S_TEXT;
this.doctype = true; // just remember that we saw it.
break;
}
case EOC:
break;
default:
this.text += String.fromCodePoint(c);
if (c === OPEN_BRACKET) {
this.state = S_DTD;
}
else if (isQuote(c)) {
this.state = S_DOCTYPE_QUOTE;
this.q = c;
}
}
}
private sDoctypeQuote(): void {
const q = this.q!;
if (this.captureToChar(q)) {
this.text += String.fromCodePoint(q);
this.q = null;
this.state = S_DOCTYPE;
}
}
private sDTD(): void {
const c = this.captureTo(DTD_TERMINATOR);
if (c === EOC) {
return;
}
this.text += String.fromCodePoint(c);
if (c === CLOSE_BRACKET) {
this.state = S_DOCTYPE;
}
else if (c === LESS) {
this.state = S_DTD_OPEN_WAKA;
}
else if (isQuote(c)) {
this.state = S_DTD_QUOTED;
this.q = c;
}
}
private sDTDQuoted(): void {
const q = this.q!;
if (this.captureToChar(q)) {
this.text += String.fromCodePoint(q);
this.state = S_DTD;
this.q = null;
}
}
private sDTDOpenWaka(): void {
const c = this.getCodeNorm();
this.text += String.fromCodePoint(c);
switch (c) {
case BANG:
this.state = S_DTD_OPEN_WAKA_BANG;
this.openWakaBang = "";
break;
case QUESTION:
this.state = S_DTD_PI;
break;
default:
this.state = S_DTD;
}
}
private sDTDOpenWakaBang(): void {
const char = String.fromCodePoint(this.getCodeNorm());
const owb = this.openWakaBang += char;
this.text += char;
if (owb !== "-") {
this.state = owb === "--" ? S_DTD_COMMENT : S_DTD;
this.openWakaBang = "";
}
}
private sDTDComment(): void {
if (this.captureToChar(MINUS)) {
this.text += "-";
this.state = S_DTD_COMMENT_ENDING;
}
}
private sDTDCommentEnding(): void {
const c = this.getCodeNorm();
this.text += String.fromCodePoint(c);
this.state = c === MINUS ? S_DTD_COMMENT_ENDED : S_DTD_COMMENT;
}
private sDTDCommentEnded(): void {
const c = this.getCodeNorm();
this.text += String.fromCodePoint(c);
if (c === GREATER) {
this.state = S_DTD;
}
else {
this.fail("malformed comment.");
// <!-- blah -- bloo --> will be recorded as
// a comment of " blah -- bloo "
this.state = S_DTD_COMMENT;
}
}
private sDTDPI(): void {
if (this.captureToChar(QUESTION)) {
this.text += "?";
this.state = S_DTD_PI_ENDING;
}
}
private sDTDPIEnding(): void {
const c = this.getCodeNorm();
this.text += String.fromCodePoint(c);
if (c === GREATER) {
this.state = S_DTD;
}
}
private sText(): void {
//
// We did try a version of saxes where the S_TEXT state was split in two
// states: one for text inside the root element, and one for text
// outside. This was avoiding having to test this.tags.length to decide
// what implementation to actually use.
//
// Peformance testing on gigabyte-size files did not show any advantage to
// using the two states solution instead of the current one. Conversely, it
// made the code a bit more complicated elsewhere. For instance, a comment
// can appear before the root element so when a comment ended it was
// necessary to determine whether to return to the S_TEXT state or to the
// new text-outside-root state.
//
if (this.tags.length !== 0) {
this.handleTextInRoot();
}
else {
this.handleTextOutsideRoot();
}
}
private sEntity(): void {
// This is essentially a specialized version of captureToChar(SEMICOLON...)
let { i: start } = this;
const { chunk } = this;
// eslint-disable-next-line no-labels, no-restricted-syntax
loop:
// eslint-disable-next-line no-constant-condition
while (true) {
switch (this.getCode()) {
case NL_LIKE:
this.entity += `${chunk.slice(start, this.prevI)}\n`;
start = this.i;
break;
case SEMICOLON: {
const { entityReturnState } = this;
const entity = this.entity + chunk.slice(start, this.prevI);
this.state = entityReturnState!;
let parsed: string;
if (entity === "") {
this.fail("empty entity name.");
parsed = "&;";
}
else {
parsed = this.parseEntity(entity);
this.entity = "";
}
if (entityReturnState !== S_TEXT || this.textHandler !== undefined) {
this.text += parsed;
}
// eslint-disable-next-line no-labels
break loop;
}
case EOC:
this.entity += chunk.slice(start);
// eslint-disable-next-line no-labels
break loop;
default:
}
}
}
private sOpenWaka(): void {
// Reminder: a state handler is called with at least one character
// available in the current chunk. So the first call to get code inside of
// a state handler cannot return ``EOC``. That's why we don't test
// for it.
const c = this.getCode();
// either a /, ?, !, or text is coming next.
if (isNameStartChar(c)) {
this.state = S_OPEN_TAG;
this.unget();
this.xmlDeclPossible = false;
}
else {
switch (c) {
case FORWARD_SLASH:
this.state = S_CLOSE_TAG;
this.xmlDeclPossible = false;
break;
case BANG:
this.state = S_OPEN_WAKA_BANG;
this.openWakaBang = "";
this.xmlDeclPossible = false;
break;
case QUESTION:
this.state = S_PI_FIRST_CHAR;
break;
default:
this.fail("disallowed character in tag name");
this.state = S_TEXT;
this.xmlDeclPossible = false;
}
}
}
private sOpenWakaBang(): void {
this.openWakaBang += String.fromCodePoint(this.getCodeNorm());
switch (this.openWakaBang) {
case "[CDATA[":
if (!this.sawRoot && !this.reportedTextBeforeRoot) {
this.fail("text data outside of root node.");
this.reportedTextBeforeRoot = true;
}
if (this.closedRoot && !this.reportedTextAfterRoot) {
this.fail("text data outside of root node.");
this.reportedTextAfterRoot = true;
}
this.state = S_CDATA;
this.openWakaBang = "";
break;
case "--":
this.state = S_COMMENT;
this.openWakaBang = "";
break;
case "DOCTYPE":
this.state = S_DOCTYPE;
if (this.doctype || this.sawRoot) {
this.fail("inappropriately located doctype declaration.");
}
this.openWakaBang = "";
break;
default:
// 7 happens to be the maximum length of the string that can possibly
// match one of the cases above.
if (this.openWakaBang.length >= 7) {
this.fail("incorrect syntax.");
}
}
}
private sComment(): void {
if (this.captureToChar(MINUS)) {
this.state = S_COMMENT_ENDING;
}
}
private sCommentEnding(): void {
const c = this.getCodeNorm();
if (c === MINUS) {
this.state = S_COMMENT_ENDED;
this.commentHandler?.(this.text);
this.text = "";
}
else {
this.text += `-${String.fromCodePoint(c)}`;
this.state = S_COMMENT;
}
}
private sCommentEnded(): void {
const c = this.getCodeNorm();
if (c !== GREATER) {
this.fail("malformed comment.");
// <!-- blah -- bloo --> will be recorded as
// a comment of " blah -- bloo "
this.text += `--${String.fromCodePoint(c)}`;
this.state = S_COMMENT;
}
else {
this.state = S_TEXT;
}
}
private sCData(): void {
if (this.captureToChar(CLOSE_BRACKET)) {
this.state = S_CDATA_ENDING;
}
}
private sCDataEnding(): void {
const c = this.getCodeNorm();
if (c === CLOSE_BRACKET) {
this.state = S_CDATA_ENDING_2;
}
else {
this.text += `]${String.fromCodePoint(c)}`;
this.state = S_CDATA;
}
}
private sCDataEnding2(): void {
const c = this.getCodeNorm();
switch (c) {
case GREATER: {
this.cdataHandler?.(this.text);
this.text = "";
this.state = S_TEXT;
break;
}
case CLOSE_BRACKET:
this.text += "]";
break;
default:
this.text += `]]${String.fromCodePoint(c)}`;
this.state = S_CDATA;
}
}
// We need this separate state to check the first character fo the pi target
// with this.nameStartCheck which allows less characters than this.nameCheck.
private sPIFirstChar(): void {
const c = this.getCodeNorm();
// This is first because in the case where the file is well-formed this is
// the branch taken. We optimize for well-formedness.
if (this.nameStartCheck(c)) {
this.piTarget += String.fromCodePoint(c);
this.state = S_PI_REST;
}
else if (c === QUESTION || isS(c)) {
this.fail("processing instruction without a target.");
this.state = c === QUESTION ? S_PI_ENDING : S_PI_BODY;
}
else {
this.fail("disallowed character in processing instruction name.");
this.piTarget += String.fromCodePoint(c);
this.state = S_PI_REST;
}
}
private sPIRest(): void {
// Capture characters into a piTarget while ``this.nameCheck`` run on the
// character read returns true.
const { chunk, i: start } = this;
// eslint-disable-next-line no-constant-condition
while (true) {
const c = this.getCodeNorm();
if (c === EOC) {
this.piTarget += chunk.slice(start);
return;
}
// NL cannot satisfy this.nameCheck so we don't have to test specifically
// for it.
if (!this.nameCheck(c)) {
this.piTarget += chunk.slice(start, this.prevI);
const isQuestion = c === QUESTION;
if (isQuestion || isS(c)) {
if (this.piTarget === "xml") {
if (!this.xmlDeclPossible) {
this.fail(
"an XML declaration must be at the start of the document.");
}
this.state = isQuestion ? S_XML_DECL_ENDING : S_XML_DECL_NAME_START;
}
else {
this.state = isQuestion ? S_PI_ENDING : S_PI_BODY;
}
}
else {
this.fail("disallowed character in processing instruction name.");
this.piTarget += String.fromCodePoint(c);
}
break;
}
}
}
private sPIBody(): void {
if (this.text.length === 0) {
const c = this.getCodeNorm();
if (c === QUESTION) {
this.state = S_PI_ENDING;
}
else if (!isS(c)) {
this.text = String.fromCodePoint(c);
}
}
// The question mark character is not valid inside any of the XML
// declaration name/value pairs.
else if (this.captureToChar(QUESTION)) {
this.state = S_PI_ENDING;
}
}
private sPIEnding(): void {
const c = this.getCodeNorm();
if (c === GREATER) {
const { piTarget } = this;
if (piTarget.toLowerCase() === "xml") {
this.fail(
"the XML declaration must appear at the start of the document.");
}
this.piHandler?.({
target: piTarget,
body: this.text,
});
this.piTarget = this.text = "";
this.state = S_TEXT;
}
else if (c === QUESTION) {
// We ran into ?? as part of a processing instruction. We initially took
// the first ? as a sign that the PI was ending, but it is not. So we have
// to add it to the body but we take the new ? as a sign that the PI is
// ending.
this.text += "?";
}
else {
this.text += `?${String.fromCodePoint(c)}`;
this.state = S_PI_BODY;
}
this.xmlDeclPossible = false;
}
private sXMLDeclNameStart(): void {
const c = this.skipSpaces();
// The question mark character is not valid inside any of the XML
// declaration name/value pairs.
if (c === QUESTION) {
// It is valid to go to S_XML_DECL_ENDING from this state.
this.state = S_XML_DECL_ENDING;
return;
}
if (c !== EOC) {
this.state = S_XML_DECL_NAME;
this.name = String.fromCodePoint(c);
}
}
private sXMLDeclName(): void {
const c = this.captureTo(XML_DECL_NAME_TERMINATOR);
// The question mark character is not valid inside any of the XML
// declaration name/value pairs.
if (c === QUESTION) {
this.state = S_XML_DECL_ENDING;
this.name += this.text;
this.text = "";
this.fail("XML declaration is incomplete.");
return;
}
if (!(isS(c) || c === EQUAL)) {
return;
}
this.name += this.text;
this.text = "";
if (!this.xmlDeclExpects.includes(this.name)) {
switch (this.name.length) {
case 0:
this.fail("did not expect any more name/value pairs.");
break;
case 1:
this.fail(`expected the name ${this.xmlDeclExpects[0]}.`);
break;
default:
this.fail(`expected one of ${this.xmlDeclExpects.join(", ")}`);
}
}
this.state = c === EQUAL ? S_XML_DECL_VALUE_START : S_XML_DECL_EQ;
}
private sXMLDeclEq(): void {
const c = this.getCodeNorm();
// The question mark character is not valid inside any of the XML
// declaration name/value pairs.
if (c === QUESTION) {
this.state = S_XML_DECL_ENDING;
this.fail("XML declaration is incomplete.");
return;
}
if (isS(c)) {
return;
}
if (c !== EQUAL) {
this.fail("value required.");
}
this.state = S_XML_DECL_VALUE_START;
}
private sXMLDeclValueStart(): void {
const c = this.getCodeNorm();
// The question mark character is not valid inside any of the XML
// declaration name/value pairs.
if (c === QUESTION) {
this.state = S_XML_DECL_ENDING;
this.fail("XML declaration is incomplete.");
return;
}
if (isS(c)) {
return;
}
if (!isQuote(c)) {
this.fail("value must be quoted.");
this.q = SPACE;
}
else {
this.q = c;
}
this.state = S_XML_DECL_VALUE;
}
private sXMLDeclValue(): void {
const c = this.captureTo([this.q!, QUESTION]);
// The question mark character is not valid inside any of the XML
// declaration name/value pairs.
if (c === QUESTION) {
this.state = S_XML_DECL_ENDING;
this.text = "";
this.fail("XML declaration is incomplete.");
return;
}
if (c === EOC) {
return;
}
const value = this.text;
this.text = "";
switch (this.name) {
case "version": {
this.xmlDeclExpects = ["encoding", "standalone"];
const version = value;
this.xmlDecl.version = version;
// This is the test specified by XML 1.0 but it is fine for XML 1.1.
if (!/^1\.[0-9]+$/.test(version)) {
this.fail("version number must match /^1\\.[0-9]+$/.");
}
// When forceXMLVersion is set, the XML declaration is ignored.
else if (!(this.opt.forceXMLVersion as boolean)) {
this.setXMLVersion(version);
}
break;
}
case "encoding":
if (!/^[A-Za-z][A-Za-z0-9._-]*$/.test(value)) {
this.fail("encoding value must match \
/^[A-Za-z0-9][A-Za-z0-9._-]*$/.");
}
this.xmlDeclExpects = ["standalone"];
this.xmlDecl.encoding = value;
break;
case "standalone":
if (value !== "yes" && value !== "no") {
this.fail("standalone value must match \"yes\" or \"no\".");
}
this.xmlDeclExpects = [];
this.xmlDecl.standalone = value;
break;
default:
// We don't need to raise an error here since we've already raised one
// when checking what name was expected.
}
this.name = "";
this.state = S_XML_DECL_SEPARATOR;
}
private sXMLDeclSeparator(): void {
const c = this.getCodeNorm();
// The question mark character is not valid inside any of the XML
// declaration name/value pairs.
if (c === QUESTION) {
// It is valid to go to S_XML_DECL_ENDING from this state.
this.state = S_XML_DECL_ENDING;
return;
}
if (!isS(c)) {
this.fail("whitespace required.");
this.unget();
}
this.state = S_XML_DECL_NAME_START;
}
private sXMLDeclEnding(): void {
const c = this.getCodeNorm();
if (c === GREATER) {
if (this.piTarget !== "xml") {
this.fail("processing instructions are not allowed before root.");
}
else if (this.name !== "version" &&
this.xmlDeclExpects.includes("version")) {
this.fail("XML declaration must contain a version.");
}
this.xmldeclHandler?.(this.xmlDecl);
this.name = "";
this.piTarget = this.text = "";
this.state = S_TEXT;
}
else {
// We got here because the previous character was a ?, but the question
// mark character is not valid inside any of the XML declaration
// name/value pairs.
this.fail(
"The character ? is disallowed anywhere in XML declarations.");
}
this.xmlDeclPossible = false;
}
private sOpenTag(): void {
const c = this.captureNameChars();
if (c === EOC) {
return;
}
const tag: SaxesTagIncomplete = this.tag = {
name: this.name,
attributes: Object.create(null) as Record<string, string>,
};
this.name = "";
if (this.xmlnsOpt) {
this.topNS = tag.ns = Object.create(null) as Record<string, string>;
}
this.openTagStartHandler?.(tag as StartTagForOptions<O>);
this.sawRoot = true;
if (!this.fragmentOpt && this.closedRoot) {
this.fail("documents may contain only one root.");
}
switch (c) {
case GREATER:
this.openTag();
break;
case FORWARD_SLASH:
this.state = S_OPEN_TAG_SLASH;
break;
default:
if (!isS(c)) {
this.fail("disallowed character in tag name.");
}
this.state = S_ATTRIB;
}
}
private sOpenTagSlash(): void {
if (this.getCode() === GREATER) {
this.openSelfClosingTag();
}
else {
this.fail("forward-slash in opening tag not followed by >.");
this.state = S_ATTRIB;
}
}
private sAttrib(): void {
const c = this.skipSpaces();
if (c === EOC) {
return;
}
if (isNameStartChar(c)) {
this.unget();
this.state = S_ATTRIB_NAME;
}
else if (c === GREATER) {
this.openTag();
}
else if (c === FORWARD_SLASH) {
this.state = S_OPEN_TAG_SLASH;
}
else {
this.fail("disallowed character in attribute name.");
}
}
private sAttribName(): void {
const c = this.captureNameChars();
if (c === EQUAL) {
this.state = S_ATTRIB_VALUE;
}
else if (isS(c)) {
this.state = S_ATTRIB_NAME_SAW_WHITE;
}
else if (c === GREATER) {
this.fail("attribute without value.");
this.pushAttrib(this.name, this.name);
this.name = this.text = "";
this.openTag();
}
else if (c !== EOC) {
this.fail("disallowed character in attribute name.");
}
}
private sAttribNameSawWhite(): void {
const c = this.skipSpaces();
switch (c) {
case EOC:
return;
case EQUAL:
this.state = S_ATTRIB_VALUE;
break;
default:
this.fail("attribute without value.");
// Should we do this???
// this.tag.attributes[this.name] = "";
this.text = "";
this.name = "";
if (c === GREATER) {
this.openTag();
}
else if (isNameStartChar(c)) {
this.unget();
this.state = S_ATTRIB_NAME;
}
else {
this.fail("disallowed character in attribute name.");
this.state = S_ATTRIB;
}
}
}
private sAttribValue(): void {
const c = this.getCodeNorm();
if (isQuote(c)) {
this.q = c;
this.state = S_ATTRIB_VALUE_QUOTED;
}
else if (!isS(c)) {
this.fail("unquoted attribute value.");
this.state = S_ATTRIB_VALUE_UNQUOTED;
this.unget();
}
}
private sAttribValueQuoted(): void {
// We deliberately do not use captureTo here. The specialized code we use
// here is faster than using captureTo.
const { q, chunk } = this;
let { i: start } = this;
// eslint-disable-next-line no-constant-condition
while (true) {
switch (this.getCode()) {
case q:
this.pushAttrib(this.name,
this.text + chunk.slice(start, this.prevI));
this.name = this.text = "";
this.q = null;
this.state = S_ATTRIB_VALUE_CLOSED;
return;
case AMP:
this.text += chunk.slice(start, this.prevI);
this.state = S_ENTITY;
this.entityReturnState = S_ATTRIB_VALUE_QUOTED;
return;
case NL:
case NL_LIKE:
case TAB:
this.text += `${chunk.slice(start, this.prevI)} `;
start = this.i;
break;
case LESS:
this.text += chunk.slice(start, this.prevI);
this.fail("disallowed character.");
return;
case EOC:
this.text += chunk.slice(start);
return;
default:
}
}
}
private sAttribValueClosed(): void {
const c = this.getCodeNorm();
if (isS(c)) {
this.state = S_ATTRIB;
}
else if (c === GREATER) {
this.openTag();
}
else if (c === FORWARD_SLASH) {
this.state = S_OPEN_TAG_SLASH;
}
else if (isNameStartChar(c)) {
this.fail("no whitespace between attributes.");
this.unget();
this.state = S_ATTRIB_NAME;
}
else {
this.fail("disallowed character in attribute name.");
}
}
private sAttribValueUnquoted(): void {
// We don't do anything regarding EOL or space handling for unquoted
// attributes. We already have failed by the time we get here, and the
// contract that saxes upholds states that upon failure, it is not safe to
// rely on the data passed to event handlers (other than
// ``onerror``). Passing "bad" data is not a problem.
const c = this.captureTo(ATTRIB_VALUE_UNQUOTED_TERMINATOR);
switch (c) {
case AMP:
this.state = S_ENTITY;
this.entityReturnState = S_ATTRIB_VALUE_UNQUOTED;
break;
case LESS:
this.fail("disallowed character.");
break;
case EOC:
break;
default:
if (this.text.includes("]]>")) {
this.fail("the string \"]]>\" is disallowed in char data.");
}
this.pushAttrib(this.name, this.text);
this.name = this.text = "";
if (c === GREATER) {
this.openTag();
}
else {
this.state = S_ATTRIB;
}
}
}
private sCloseTag(): void {
const c = this.captureNameChars();
if (c === GREATER) {
this.closeTag();
}
else if (isS(c)) {
this.state = S_CLOSE_TAG_SAW_WHITE;
}
else if (c !== EOC) {
this.fail("disallowed character in closing tag.");
}
}
private sCloseTagSawWhite(): void {
switch (this.skipSpaces()) {
case GREATER:
this.closeTag();
break;
case EOC:
break;
default:
this.fail("disallowed character in closing tag.");
}
}
// END OF STATE ENGINE METHODS
private handleTextInRoot(): void {
// This is essentially a specialized version of captureTo which is optimized
// for performing the ]]> check. A previous version of this code, checked
// ``this.text`` for the presence of ]]>. It simplified the code but was
// very costly when character data contained a lot of entities to be parsed.
//
// Since we are using a specialized loop, we also keep track of the presence
// of ]]> in text data. The sequence ]]> is forbidden to appear as-is.
//
let { i: start, forbiddenState } = this;
const { chunk, textHandler: handler } = this;
// eslint-disable-next-line no-labels, no-restricted-syntax
scanLoop:
// eslint-disable-next-line no-constant-condition
while (true) {
switch (this.getCode()) {
case LESS: {
this.state = S_OPEN_WAKA;
if (handler !== undefined) {
const { text } = this;
const slice = chunk.slice(start, this.prevI);
if (text.length !== 0) {
handler(text + slice);
this.text = "";
}
else if (slice.length !== 0) {
handler(slice);
}
}
forbiddenState = FORBIDDEN_START;
// eslint-disable-next-line no-labels
break scanLoop;
}
case AMP:
this.state = S_ENTITY;
this.entityReturnState = S_TEXT;
if (handler !== undefined) {
this.text += chunk.slice(start, this.prevI);
}
forbiddenState = FORBIDDEN_START;
// eslint-disable-next-line no-labels
break scanLoop;
case CLOSE_BRACKET:
switch (forbiddenState) {
case FORBIDDEN_START:
forbiddenState = FORBIDDEN_BRACKET;
break;
case FORBIDDEN_BRACKET:
forbiddenState = FORBIDDEN_BRACKET_BRACKET;
break;
case FORBIDDEN_BRACKET_BRACKET:
break;
default:
throw new Error("impossible state");
}
break;
case GREATER:
if (forbiddenState === FORBIDDEN_BRACKET_BRACKET) {
this.fail("the string \"]]>\" is disallowed in char data.");
}
forbiddenState = FORBIDDEN_START;
break;
case NL_LIKE:
if (handler !== undefined) {
this.text += `${chunk.slice(start, this.prevI)}\n`;
}
start = this.i;
forbiddenState = FORBIDDEN_START;
break;
case EOC:
if (handler !== undefined) {
this.text += chunk.slice(start);
}
// eslint-disable-next-line no-labels
break scanLoop;
default:
forbiddenState = FORBIDDEN_START;
}
}
this.forbiddenState = forbiddenState;
}
private handleTextOutsideRoot(): void {
// This is essentially a specialized version of captureTo which is optimized
// for a specialized task. We keep track of the presence of non-space
// characters in the text since these are errors when appearing outside the
// document root element.
let { i: start } = this;
const { chunk, textHandler: handler } = this;
let nonSpace = false;
// eslint-disable-next-line no-labels, no-restricted-syntax
outRootLoop:
// eslint-disable-next-line no-constant-condition
while (true) {
const code = this.getCode();
switch (code) {
case LESS: {
this.state = S_OPEN_WAKA;
if (handler !== undefined) {
const { text } = this;
const slice = chunk.slice(start, this.prevI);
if (text.length !== 0) {
handler(text + slice);
this.text = "";
}
else if (slice.length !== 0) {
handler(slice);
}
}
// eslint-disable-next-line no-labels
break outRootLoop;
}
case AMP:
this.state = S_ENTITY;
this.entityReturnState = S_TEXT;
if (handler !== undefined) {
this.text += chunk.slice(start, this.prevI);
}
nonSpace = true;
// eslint-disable-next-line no-labels
break outRootLoop;
case NL_LIKE:
if (handler !== undefined) {
this.text += `${chunk.slice(start, this.prevI)}\n`;
}
start = this.i;
break;
case EOC:
if (handler !== undefined) {
this.text += chunk.slice(start);
}
// eslint-disable-next-line no-labels
break outRootLoop;
default:
if (!isS(code)) {
nonSpace = true;
}
}
}
if (!nonSpace) {
return;
}
// We use the reportedTextBeforeRoot and reportedTextAfterRoot flags
// to avoid reporting errors for every single character that is out of
// place.
if (!this.sawRoot && !this.reportedTextBeforeRoot) {
this.fail("text data outside of root node.");
this.reportedTextBeforeRoot = true;
}
if (this.closedRoot && !this.reportedTextAfterRoot) {
this.fail("text data outside of root node.");
this.reportedTextAfterRoot = true;
}
}
private pushAttribNS(name: string, value: string): void {
const { prefix, local } = this.qname(name);
const attr = { name, prefix, local, value };
this.attribList.push(attr);
this.attributeHandler?.(attr as AttributeEventForOptions<O>);
if (prefix === "xmlns") {
const trimmed = value.trim();
if (this.currentXMLVersion === "1.0" && trimmed === "") {
this.fail("invalid attempt to undefine prefix in XML 1.0");
}
this.topNS![local] = trimmed;
nsPairCheck(this, local, trimmed);
}
else if (name === "xmlns") {
const trimmed = value.trim();
this.topNS![""] = trimmed;
nsPairCheck(this, "", trimmed);
}
}
private pushAttribPlain(name: string, value: string): void {
const attr = { name, value };
this.attribList.push(attr);
this.attributeHandler?.(attr as AttributeEventForOptions<O>);
}
/**
* End parsing. This performs final well-formedness checks and resets the
* parser to a clean state.
*
* @returns this
*/
private end(): this {
if (!this.sawRoot) {
this.fail("document must contain a root element.");
}
const { tags } = this;
while (tags.length > 0) {
const tag = tags.pop()!;
this.fail(`unclosed tag: ${tag.name}`);
}
if ((this.state !== S_BEGIN) && (this.state !== S_TEXT)) {
this.fail("unexpected end.");
}
const { text } = this;
if (text.length !== 0) {
this.textHandler?.(text);
this.text = "";
}
this._closed = true;
this.endHandler?.();
this._init();
return this;
}
/**
* Resolve a namespace prefix.
*
* @param prefix The prefix to resolve.
*
* @returns The namespace URI or ``undefined`` if the prefix is not defined.
*/
resolve(prefix: string): string | undefined {
let uri = this.topNS![prefix];
if (uri !== undefined) {
return uri;
}
const { tags } = this;
for (let index = tags.length - 1; index >= 0; index--) {
uri = tags[index]!.ns![prefix];
if (uri !== undefined) {
return uri;
}
}
uri = this.ns[prefix];
if (uri !== undefined) {
return uri;
}
return this.opt.resolvePrefix?.(prefix);
}
/**
* Parse a qname into its prefix and local name parts.
*
* @param name The name to parse
*
* @returns
*/
private qname(name: string): { prefix: string; local: string } {
// This is faster than using name.split(":").
const colon = name.indexOf(":");
if (colon === -1) {
return { prefix: "", local: name };
}
const local = name.slice(colon + 1);
const prefix = name.slice(0, colon);
if (prefix === "" || local === "" || local.includes(":")) {
this.fail(`malformed name: ${name}.`);
}
return { prefix, local };
}
private processAttribsNS(): void {
const { attribList } = this;
const tag = this.tag!;
{
// add namespace info to tag
const { prefix, local } = this.qname(tag.name);
tag.prefix = prefix;
tag.local = local;
const uri = tag.uri = this.resolve(prefix) ?? "";
if (prefix !== "") {
if (prefix === "xmlns") {
this.fail("tags may not have \"xmlns\" as prefix.");
}
if (uri === "") {
this.fail(`unbound namespace prefix: ${JSON.stringify(prefix)}.`);
tag.uri = prefix;
}
}
}
if (attribList.length === 0) {
return;
}
const { attributes } = tag;
const seen = new Set();
// Note: do not apply default ns to attributes:
// http://www.w3.org/TR/REC-xml-names/#defaulting
for (const attr of attribList as SaxesAttributeNSIncomplete[]) {
const { name, prefix, local } = attr;
let uri;
let eqname;
if (prefix === "") {
uri = name === "xmlns" ? XMLNS_NAMESPACE : "";
eqname = name;
}
else {
uri = this.resolve(prefix);
// if there's any attributes with an undefined namespace,
// then fail on them now.
if (uri === undefined) {
this.fail(`unbound namespace prefix: ${JSON.stringify(prefix)}.`);
uri = prefix;
}
eqname = `{${uri}}${local}`;
}
if (seen.has(eqname)) {
this.fail(`duplicate attribute: ${eqname}.`);
}
seen.add(eqname);
attr.uri = uri;
attributes[name] = attr;
}
this.attribList = [];
}
private processAttribsPlain(): void {
const { attribList } = this;
// eslint-disable-next-line prefer-destructuring
const attributes = this.tag!.attributes;
for (const { name, value } of attribList) {
if (attributes[name] !== undefined) {
this.fail(`duplicate attribute: ${name}.`);
}
attributes[name] = value;
}
this.attribList = [];
}
/**
* Handle a complete open tag. This parser code calls this once it has seen
* the whole tag. This method checks for well-formeness and then emits
* ``onopentag``.
*/
private openTag(): void {
this.processAttribs();
const { tags } = this;
const tag = this.tag as SaxesTag;
tag.isSelfClosing = false;
// There cannot be any pending text here due to the onopentagstart that was
// necessarily emitted before we get here. So we do not check text.
this.openTagHandler?.(tag as TagForOptions<O>);
tags.push(tag);
this.state = S_TEXT;
this.name = "";
}
/**
* Handle a complete self-closing tag. This parser code calls this once it has
* seen the whole tag. This method checks for well-formeness and then emits
* ``onopentag`` and ``onclosetag``.
*/
private openSelfClosingTag(): void {
this.processAttribs();
const { tags } = this;
const tag = this.tag as SaxesTag;
tag.isSelfClosing = true;
// There cannot be any pending text here due to the onopentagstart that was
// necessarily emitted before we get here. So we do not check text.
this.openTagHandler?.(tag as TagForOptions<O>);
this.closeTagHandler?.(tag as TagForOptions<O>);
const top = this.tag = tags[tags.length - 1] ?? null;
if (top === null) {
this.closedRoot = true;
}
this.state = S_TEXT;
this.name = "";
}
/**
* Handle a complete close tag. This parser code calls this once it has seen
* the whole tag. This method checks for well-formeness and then emits
* ``onclosetag``.
*/
private closeTag(): void {
const { tags, name } = this;
// Our state after this will be S_TEXT, no matter what, and we can clear
// tagName now.
this.state = S_TEXT;
this.name = "";
if (name === "") {
this.fail("weird empty close tag.");
this.text += "</>";
return;
}
const handler = this.closeTagHandler;
let l = tags.length;
while (l-- > 0) {
const tag = this.tag = tags.pop() as SaxesTag;
this.topNS = tag.ns!;
handler?.(tag as TagForOptions<O>);
if (tag.name === name) {
break;
}
this.fail("unexpected close tag.");
}
if (l === 0) {
this.closedRoot = true;
}
else if (l < 0) {
this.fail(`unmatched closing tag: ${name}.`);
this.text += `</${name}>`;
}
}
/**
* Resolves an entity. Makes any necessary well-formedness checks.
*
* @param entity The entity to resolve.
*
* @returns The parsed entity.
*/
private parseEntity(entity: string): string {
// startsWith would be significantly slower for this test.
if (entity[0] !== "#") {
const defined = this.ENTITIES[entity];
if (defined !== undefined) {
return defined;
}
this.fail(this.isName(entity) ? "undefined entity." :
"disallowed character in entity name.");
return `&${entity};`;
}
let num = NaN;
if (entity[1] === "x" && /^#x[0-9a-f]+$/i.test(entity)) {
num = parseInt(entity.slice(2), 16);
}
else if (/^#[0-9]+$/.test(entity)) {
num = parseInt(entity.slice(1), 10);
}
// The character reference is required to match the CHAR production.
if (!this.isChar(num)) {
this.fail("malformed character entity.");
return `&${entity};`;
}
return String.fromCodePoint(num);
}
} |
1,140 | fn(parser: SaxesParser): void {
parser.write("<r><![CDATA[ this is ]]>").write("<![CDA")
.write("T")
.write("A[")
.write("character data ")
.write("]]></r>")
.close();
} | class SaxesParser<O extends SaxesOptions = {}> {
private readonly fragmentOpt: boolean;
private readonly xmlnsOpt: boolean;
private readonly trackPosition: boolean;
private readonly fileName?: string;
private readonly nameStartCheck: (c: number) => boolean;
private readonly nameCheck: (c: number) => boolean;
private readonly isName: (name: string) => boolean;
private readonly ns!: Record<string, string>;
private openWakaBang!: string;
private text!: string;
private name!: string;
private piTarget!: string;
private entity!: string;
private q!: null | number;
private tags!: SaxesTagIncomplete[];
private tag!: SaxesTagIncomplete | null;
private topNS!: Record<string, string> | null;
private chunk!: string;
private chunkPosition!: number;
private i!: number;
//
// We use prevI to allow "ungetting" the previously read code point. Note
// however, that it is not safe to unget everything and anything. In
// particular ungetting EOL characters will screw positioning up.
//
// Practically, you must not unget a code which has any side effect beyond
// updating ``this.i`` and ``this.prevI``. Only EOL codes have such side
// effects.
//
private prevI!: number;
private carriedFromPrevious?: string;
private forbiddenState!: number;
private attribList!: (SaxesAttributeNSIncomplete | SaxesAttributePlain)[];
private state!: number;
private reportedTextBeforeRoot!: boolean;
private reportedTextAfterRoot!: boolean;
private closedRoot!: boolean;
private sawRoot!: boolean;
private xmlDeclPossible!: boolean;
private xmlDeclExpects!: string[];
private entityReturnState?: number;
private processAttribs!: (this: this) => void;
private positionAtNewLine!: number;
private doctype!: boolean;
private getCode!: () => number;
private isChar!: (c: number) => boolean;
private pushAttrib!: (name: string, value: string) => void;
private _closed!: boolean;
private currentXMLVersion!: string;
private readonly stateTable: ((this: SaxesParser<O>) => void)[];
private xmldeclHandler?: XMLDeclHandler;
private textHandler?: TextHandler;
private piHandler?: PIHandler;
private doctypeHandler?: DoctypeHandler;
private commentHandler?: CommentHandler;
private openTagStartHandler?: OpenTagStartHandler<O>;
private openTagHandler?: OpenTagHandler<O>;
private closeTagHandler?: CloseTagHandler<O>;
private cdataHandler?: CDataHandler;
private errorHandler?: ErrorHandler;
private endHandler?: EndHandler;
private readyHandler?: ReadyHandler;
private attributeHandler?: AttributeHandler<O>;
/**
* Indicates whether or not the parser is closed. If ``true``, wait for
* the ``ready`` event to write again.
*/
get closed(): boolean {
return this._closed;
}
readonly opt: SaxesOptions;
/**
* The XML declaration for this document.
*/
xmlDecl!: XMLDecl;
/**
* The line number of the next character to be read by the parser. This field
* is one-based. (The first line is numbered 1.)
*/
line!: number;
/**
* The column number of the next character to be read by the parser. *
* This field is zero-based. (The first column is 0.)
*
* This field counts columns by *Unicode character*. Note that this *can*
* be different from the index of the character in a JavaScript string due
* to how JavaScript handles astral plane characters.
*
* See [[columnIndex]] for a number that corresponds to the JavaScript index.
*/
column!: number;
/**
* A map of entity name to expansion.
*/
ENTITIES!: Record<string, string>;
/**
* @param opt The parser options.
*/
constructor(opt?: O) {
this.opt = opt ?? {};
this.fragmentOpt = !!(this.opt.fragment as boolean);
const xmlnsOpt = this.xmlnsOpt = !!(this.opt.xmlns as boolean);
this.trackPosition = this.opt.position !== false;
this.fileName = this.opt.fileName;
if (xmlnsOpt) {
// This is the function we use to perform name checks on PIs and entities.
// When namespaces are used, colons are not allowed in PI target names or
// entity names. So the check depends on whether namespaces are used. See:
//
// https://www.w3.org/XML/xml-names-19990114-errata.html
// NE08
//
this.nameStartCheck = isNCNameStartChar;
this.nameCheck = isNCNameChar;
this.isName = isNCName;
// eslint-disable-next-line @typescript-eslint/unbound-method
this.processAttribs = this.processAttribsNS;
// eslint-disable-next-line @typescript-eslint/unbound-method
this.pushAttrib = this.pushAttribNS;
// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-assignment
this.ns = { __proto__: null as any, ...rootNS };
const additional = this.opt.additionalNamespaces;
if (additional != null) {
nsMappingCheck(this, additional);
Object.assign(this.ns, additional);
}
}
else {
this.nameStartCheck = isNameStartChar;
this.nameCheck = isNameChar;
this.isName = isName;
// eslint-disable-next-line @typescript-eslint/unbound-method
this.processAttribs = this.processAttribsPlain;
// eslint-disable-next-line @typescript-eslint/unbound-method
this.pushAttrib = this.pushAttribPlain;
}
//
// The order of the members in this table needs to correspond to the state
// numbers given to the states that correspond to the methods being recorded
// here.
//
this.stateTable = [
/* eslint-disable @typescript-eslint/unbound-method */
this.sBegin,
this.sBeginWhitespace,
this.sDoctype,
this.sDoctypeQuote,
this.sDTD,
this.sDTDQuoted,
this.sDTDOpenWaka,
this.sDTDOpenWakaBang,
this.sDTDComment,
this.sDTDCommentEnding,
this.sDTDCommentEnded,
this.sDTDPI,
this.sDTDPIEnding,
this.sText,
this.sEntity,
this.sOpenWaka,
this.sOpenWakaBang,
this.sComment,
this.sCommentEnding,
this.sCommentEnded,
this.sCData,
this.sCDataEnding,
this.sCDataEnding2,
this.sPIFirstChar,
this.sPIRest,
this.sPIBody,
this.sPIEnding,
this.sXMLDeclNameStart,
this.sXMLDeclName,
this.sXMLDeclEq,
this.sXMLDeclValueStart,
this.sXMLDeclValue,
this.sXMLDeclSeparator,
this.sXMLDeclEnding,
this.sOpenTag,
this.sOpenTagSlash,
this.sAttrib,
this.sAttribName,
this.sAttribNameSawWhite,
this.sAttribValue,
this.sAttribValueQuoted,
this.sAttribValueClosed,
this.sAttribValueUnquoted,
this.sCloseTag,
this.sCloseTagSawWhite,
/* eslint-enable @typescript-eslint/unbound-method */
];
this._init();
}
_init(): void {
this.openWakaBang = "";
this.text = "";
this.name = "";
this.piTarget = "";
this.entity = "";
this.q = null;
this.tags = [];
this.tag = null;
this.topNS = null;
this.chunk = "";
this.chunkPosition = 0;
this.i = 0;
this.prevI = 0;
this.carriedFromPrevious = undefined;
this.forbiddenState = FORBIDDEN_START;
this.attribList = [];
// The logic is organized so as to minimize the need to check
// this.opt.fragment while parsing.
const { fragmentOpt } = this;
this.state = fragmentOpt ? S_TEXT : S_BEGIN;
// We want these to be all true if we are dealing with a fragment.
this.reportedTextBeforeRoot = this.reportedTextAfterRoot = this.closedRoot =
this.sawRoot = fragmentOpt;
// An XML declaration is intially possible only when parsing whole
// documents.
this.xmlDeclPossible = !fragmentOpt;
this.xmlDeclExpects = ["version"];
this.entityReturnState = undefined;
let { defaultXMLVersion } = this.opt;
if (defaultXMLVersion === undefined) {
if (this.opt.forceXMLVersion === true) {
throw new Error("forceXMLVersion set but defaultXMLVersion is not set");
}
defaultXMLVersion = "1.0";
}
this.setXMLVersion(defaultXMLVersion);
this.positionAtNewLine = 0;
this.doctype = false;
this._closed = false;
this.xmlDecl = {
version: undefined,
encoding: undefined,
standalone: undefined,
};
this.line = 1;
this.column = 0;
this.ENTITIES = Object.create(XML_ENTITIES) as Record<string, string>;
this.readyHandler?.();
}
/**
* The stream position the parser is currently looking at. This field is
* zero-based.
*
* This field is not based on counting Unicode characters but is to be
* interpreted as a plain index into a JavaScript string.
*/
get position(): number {
return this.chunkPosition + this.i;
}
/**
* The column number of the next character to be read by the parser. *
* This field is zero-based. (The first column in a line is 0.)
*
* This field reports the index at which the next character would be in the
* line if the line were represented as a JavaScript string. Note that this
* *can* be different to a count based on the number of *Unicode characters*
* due to how JavaScript handles astral plane characters.
*
* See [[column]] for a number that corresponds to a count of Unicode
* characters.
*/
get columnIndex(): number {
return this.position - this.positionAtNewLine;
}
/**
* Set an event listener on an event. The parser supports one handler per
* event type. If you try to set an event handler over an existing handler,
* the old handler is silently overwritten.
*
* @param name The event to listen to.
*
* @param handler The handler to set.
*/
on<N extends EventName>(name: N, handler: EventNameToHandler<O, N>): void {
// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-member-access
(this as any)[EVENT_NAME_TO_HANDLER_NAME[name]] = handler;
}
/**
* Unset an event handler.
*
* @parma name The event to stop listening to.
*/
off(name: EventName): void {
// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-member-access
(this as any)[EVENT_NAME_TO_HANDLER_NAME[name]] = undefined;
}
/**
* Make an error object. The error object will have a message that contains
* the ``fileName`` option passed at the creation of the parser. If position
* tracking was turned on, it will also have line and column number
* information.
*
* @param message The message describing the error to report.
*
* @returns An error object with a properly formatted message.
*/
makeError(message: string): Error {
let msg = this.fileName ?? "";
if (this.trackPosition) {
if (msg.length > 0) {
msg += ":";
}
msg += `${this.line}:${this.column}`;
}
if (msg.length > 0) {
msg += ": ";
}
return new Error(msg + message);
}
/**
* Report a parsing error. This method is made public so that client code may
* check for issues that are outside the scope of this project and can report
* errors.
*
* @param message The error to report.
*
* @returns this
*/
fail(message: string): this {
const err = this.makeError(message);
const handler = this.errorHandler;
if (handler === undefined) {
throw err;
}
else {
handler(err);
}
return this;
}
/**
* Write a XML data to the parser.
*
* @param chunk The XML data to write.
*
* @returns this
*/
// We do need object for the type here. Yes, it often causes problems
// but not in this case.
write(chunk: string | object | null): this {
if (this.closed) {
return this.fail("cannot write after close; assign an onready handler.");
}
let end = false;
if (chunk === null) {
// We cannot return immediately because carriedFromPrevious may need
// processing.
end = true;
chunk = "";
}
else if (typeof chunk === "object") {
chunk = chunk.toString();
}
// We checked if performing a pre-decomposition of the string into an array
// of single complete characters (``Array.from(chunk)``) would be faster
// than the current repeated calls to ``charCodeAt``. As of August 2018, it
// isn't. (There may be Node-specific code that would perform faster than
// ``Array.from`` but don't want to be dependent on Node.)
if (this.carriedFromPrevious !== undefined) {
// The previous chunk had char we must carry over.
chunk = `${this.carriedFromPrevious}${chunk}`;
this.carriedFromPrevious = undefined;
}
let limit = chunk.length;
const lastCode = chunk.charCodeAt(limit - 1);
if (!end &&
// A trailing CR or surrogate must be carried over to the next
// chunk.
(lastCode === CR || (lastCode >= 0xD800 && lastCode <= 0xDBFF))) {
// The chunk ends with a character that must be carried over. We cannot
// know how to handle it until we get the next chunk or the end of the
// stream. So save it for later.
this.carriedFromPrevious = chunk[limit - 1];
limit--;
chunk = chunk.slice(0, limit);
}
const { stateTable } = this;
this.chunk = chunk;
this.i = 0;
while (this.i < limit) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-argument
stateTable[this.state].call(this as any);
}
this.chunkPosition += limit;
return end ? this.end() : this;
}
/**
* Close the current stream. Perform final well-formedness checks and reset
* the parser tstate.
*
* @returns this
*/
close(): this {
return this.write(null);
}
/**
* Get a single code point out of the current chunk. This updates the current
* position if we do position tracking.
*
* This is the algorithm to use for XML 1.0.
*
* @returns The character read.
*/
private getCode10(): number {
const { chunk, i } = this;
this.prevI = i;
// Yes, we do this instead of doing this.i++. Doing it this way, we do not
// read this.i again, which is a bit faster.
this.i = i + 1;
if (i >= chunk.length) {
return EOC;
}
// Using charCodeAt and handling the surrogates ourselves is faster
// than using codePointAt.
const code = chunk.charCodeAt(i);
this.column++;
if (code < 0xD800) {
if (code >= SPACE || code === TAB) {
return code;
}
switch (code) {
case NL:
this.line++;
this.column = 0;
this.positionAtNewLine = this.position;
return NL;
case CR:
// We may get NaN if we read past the end of the chunk, which is fine.
if (chunk.charCodeAt(i + 1) === NL) {
// A \r\n sequence is converted to \n so we have to skip over the
// next character. We already know it has a size of 1 so ++ is fine
// here.
this.i = i + 2;
}
// Otherwise, a \r is just converted to \n, so we don't have to skip
// ahead.
// In either case, \r becomes \n.
this.line++;
this.column = 0;
this.positionAtNewLine = this.position;
return NL_LIKE;
default:
// If we get here, then code < SPACE and it is not NL CR or TAB.
this.fail("disallowed character.");
return code;
}
}
if (code > 0xDBFF) {
// This is a specialized version of isChar10 that takes into account
// that in this context code > 0xDBFF and code <= 0xFFFF. So it does not
// test cases that don't need testing.
if (!(code >= 0xE000 && code <= 0xFFFD)) {
this.fail("disallowed character.");
}
return code;
}
const final = 0x10000 + ((code - 0xD800) * 0x400) +
(chunk.charCodeAt(i + 1) - 0xDC00);
this.i = i + 2;
// This is a specialized version of isChar10 that takes into account that in
// this context necessarily final >= 0x10000.
if (final > 0x10FFFF) {
this.fail("disallowed character.");
}
return final;
}
/**
* Get a single code point out of the current chunk. This updates the current
* position if we do position tracking.
*
* This is the algorithm to use for XML 1.1.
*
* @returns {number} The character read.
*/
private getCode11(): number {
const { chunk, i } = this;
this.prevI = i;
// Yes, we do this instead of doing this.i++. Doing it this way, we do not
// read this.i again, which is a bit faster.
this.i = i + 1;
if (i >= chunk.length) {
return EOC;
}
// Using charCodeAt and handling the surrogates ourselves is faster
// than using codePointAt.
const code = chunk.charCodeAt(i);
this.column++;
if (code < 0xD800) {
if ((code > 0x1F && code < 0x7F) || (code > 0x9F && code !== LS) ||
code === TAB) {
return code;
}
switch (code) {
case NL: // 0xA
this.line++;
this.column = 0;
this.positionAtNewLine = this.position;
return NL;
case CR: { // 0xD
// We may get NaN if we read past the end of the chunk, which is
// fine.
const next = chunk.charCodeAt(i + 1);
if (next === NL || next === NEL) {
// A CR NL or CR NEL sequence is converted to NL so we have to skip
// over the next character. We already know it has a size of 1.
this.i = i + 2;
}
// Otherwise, a CR is just converted to NL, no skip.
}
/* yes, fall through */
case NEL: // 0x85
case LS: // Ox2028
this.line++;
this.column = 0;
this.positionAtNewLine = this.position;
return NL_LIKE;
default:
this.fail("disallowed character.");
return code;
}
}
if (code > 0xDBFF) {
// This is a specialized version of isCharAndNotRestricted that takes into
// account that in this context code > 0xDBFF and code <= 0xFFFF. So it
// does not test cases that don't need testing.
if (!(code >= 0xE000 && code <= 0xFFFD)) {
this.fail("disallowed character.");
}
return code;
}
const final = 0x10000 + ((code - 0xD800) * 0x400) +
(chunk.charCodeAt(i + 1) - 0xDC00);
this.i = i + 2;
// This is a specialized version of isCharAndNotRestricted that takes into
// account that in this context necessarily final >= 0x10000.
if (final > 0x10FFFF) {
this.fail("disallowed character.");
}
return final;
}
/**
* Like ``getCode`` but with the return value normalized so that ``NL`` is
* returned for ``NL_LIKE``.
*/
private getCodeNorm(): number {
const c = this.getCode();
return c === NL_LIKE ? NL : c;
}
private unget(): void {
this.i = this.prevI;
this.column--;
}
/**
* Capture characters into a buffer until encountering one of a set of
* characters.
*
* @param chars An array of codepoints. Encountering a character in the array
* ends the capture. (``chars`` may safely contain ``NL``.)
*
* @return The character code that made the capture end, or ``EOC`` if we hit
* the end of the chunk. The return value cannot be NL_LIKE: NL is returned
* instead.
*/
private captureTo(chars: number[]): number {
let { i: start } = this;
const { chunk } = this;
// eslint-disable-next-line no-constant-condition
while (true) {
const c = this.getCode();
const isNLLike = c === NL_LIKE;
const final = isNLLike ? NL : c;
if (final === EOC || chars.includes(final)) {
this.text += chunk.slice(start, this.prevI);
return final;
}
if (isNLLike) {
this.text += `${chunk.slice(start, this.prevI)}\n`;
start = this.i;
}
}
}
/**
* Capture characters into a buffer until encountering a character.
*
* @param char The codepoint that ends the capture. **NOTE ``char`` MAY NOT
* CONTAIN ``NL``.** Passing ``NL`` will result in buggy behavior.
*
* @return ``true`` if we ran into the character. Otherwise, we ran into the
* end of the current chunk.
*/
private captureToChar(char: number): boolean {
let { i: start } = this;
const { chunk } = this;
// eslint-disable-next-line no-constant-condition
while (true) {
let c = this.getCode();
switch (c) {
case NL_LIKE:
this.text += `${chunk.slice(start, this.prevI)}\n`;
start = this.i;
c = NL;
break;
case EOC:
this.text += chunk.slice(start);
return false;
default:
}
if (c === char) {
this.text += chunk.slice(start, this.prevI);
return true;
}
}
}
/**
* Capture characters that satisfy ``isNameChar`` into the ``name`` field of
* this parser.
*
* @return The character code that made the test fail, or ``EOC`` if we hit
* the end of the chunk. The return value cannot be NL_LIKE: NL is returned
* instead.
*/
private captureNameChars(): number {
const { chunk, i: start } = this;
// eslint-disable-next-line no-constant-condition
while (true) {
const c = this.getCode();
if (c === EOC) {
this.name += chunk.slice(start);
return EOC;
}
// NL is not a name char so we don't have to test specifically for it.
if (!isNameChar(c)) {
this.name += chunk.slice(start, this.prevI);
return c === NL_LIKE ? NL : c;
}
}
}
/**
* Skip white spaces.
*
* @return The character that ended the skip, or ``EOC`` if we hit
* the end of the chunk. The return value cannot be NL_LIKE: NL is returned
* instead.
*/
private skipSpaces(): number {
// eslint-disable-next-line no-constant-condition
while (true) {
const c = this.getCodeNorm();
if (c === EOC || !isS(c)) {
return c;
}
}
}
private setXMLVersion(version: string): void {
this.currentXMLVersion = version;
/* eslint-disable @typescript-eslint/unbound-method */
if (version === "1.0") {
this.isChar = isChar10;
this.getCode = this.getCode10;
}
else {
this.isChar = isChar11;
this.getCode = this.getCode11;
}
/* eslint-enable @typescript-eslint/unbound-method */
}
// STATE ENGINE METHODS
// This needs to be a state separate from S_BEGIN_WHITESPACE because we want
// to be sure never to come back to this state later.
private sBegin(): void {
// We are essentially peeking at the first character of the chunk. Since
// S_BEGIN can be in effect only when we start working on the first chunk,
// the index at which we must look is necessarily 0. Note also that the
// following test does not depend on decoding surrogates.
// If the initial character is 0xFEFF, ignore it.
if (this.chunk.charCodeAt(0) === 0xFEFF) {
this.i++;
this.column++;
}
this.state = S_BEGIN_WHITESPACE;
}
private sBeginWhitespace(): void {
// We need to know whether we've encountered spaces or not because as soon
// as we run into a space, an XML declaration is no longer possible. Rather
// than slow down skipSpaces even in places where we don't care whether it
// skipped anything or not, we check whether prevI is equal to the value of
// i from before we skip spaces.
const iBefore = this.i;
const c = this.skipSpaces();
if (this.prevI !== iBefore) {
this.xmlDeclPossible = false;
}
switch (c) {
case LESS:
this.state = S_OPEN_WAKA;
// We could naively call closeText but in this state, it is not normal
// to have text be filled with any data.
if (this.text.length !== 0) {
throw new Error("no-empty text at start");
}
break;
case EOC:
break;
default:
this.unget();
this.state = S_TEXT;
this.xmlDeclPossible = false;
}
}
private sDoctype(): void {
const c = this.captureTo(DOCTYPE_TERMINATOR);
switch (c) {
case GREATER: {
this.doctypeHandler?.(this.text);
this.text = "";
this.state = S_TEXT;
this.doctype = true; // just remember that we saw it.
break;
}
case EOC:
break;
default:
this.text += String.fromCodePoint(c);
if (c === OPEN_BRACKET) {
this.state = S_DTD;
}
else if (isQuote(c)) {
this.state = S_DOCTYPE_QUOTE;
this.q = c;
}
}
}
private sDoctypeQuote(): void {
const q = this.q!;
if (this.captureToChar(q)) {
this.text += String.fromCodePoint(q);
this.q = null;
this.state = S_DOCTYPE;
}
}
private sDTD(): void {
const c = this.captureTo(DTD_TERMINATOR);
if (c === EOC) {
return;
}
this.text += String.fromCodePoint(c);
if (c === CLOSE_BRACKET) {
this.state = S_DOCTYPE;
}
else if (c === LESS) {
this.state = S_DTD_OPEN_WAKA;
}
else if (isQuote(c)) {
this.state = S_DTD_QUOTED;
this.q = c;
}
}
private sDTDQuoted(): void {
const q = this.q!;
if (this.captureToChar(q)) {
this.text += String.fromCodePoint(q);
this.state = S_DTD;
this.q = null;
}
}
private sDTDOpenWaka(): void {
const c = this.getCodeNorm();
this.text += String.fromCodePoint(c);
switch (c) {
case BANG:
this.state = S_DTD_OPEN_WAKA_BANG;
this.openWakaBang = "";
break;
case QUESTION:
this.state = S_DTD_PI;
break;
default:
this.state = S_DTD;
}
}
private sDTDOpenWakaBang(): void {
const char = String.fromCodePoint(this.getCodeNorm());
const owb = this.openWakaBang += char;
this.text += char;
if (owb !== "-") {
this.state = owb === "--" ? S_DTD_COMMENT : S_DTD;
this.openWakaBang = "";
}
}
private sDTDComment(): void {
if (this.captureToChar(MINUS)) {
this.text += "-";
this.state = S_DTD_COMMENT_ENDING;
}
}
private sDTDCommentEnding(): void {
const c = this.getCodeNorm();
this.text += String.fromCodePoint(c);
this.state = c === MINUS ? S_DTD_COMMENT_ENDED : S_DTD_COMMENT;
}
private sDTDCommentEnded(): void {
const c = this.getCodeNorm();
this.text += String.fromCodePoint(c);
if (c === GREATER) {
this.state = S_DTD;
}
else {
this.fail("malformed comment.");
// <!-- blah -- bloo --> will be recorded as
// a comment of " blah -- bloo "
this.state = S_DTD_COMMENT;
}
}
private sDTDPI(): void {
if (this.captureToChar(QUESTION)) {
this.text += "?";
this.state = S_DTD_PI_ENDING;
}
}
private sDTDPIEnding(): void {
const c = this.getCodeNorm();
this.text += String.fromCodePoint(c);
if (c === GREATER) {
this.state = S_DTD;
}
}
private sText(): void {
//
// We did try a version of saxes where the S_TEXT state was split in two
// states: one for text inside the root element, and one for text
// outside. This was avoiding having to test this.tags.length to decide
// what implementation to actually use.
//
// Peformance testing on gigabyte-size files did not show any advantage to
// using the two states solution instead of the current one. Conversely, it
// made the code a bit more complicated elsewhere. For instance, a comment
// can appear before the root element so when a comment ended it was
// necessary to determine whether to return to the S_TEXT state or to the
// new text-outside-root state.
//
if (this.tags.length !== 0) {
this.handleTextInRoot();
}
else {
this.handleTextOutsideRoot();
}
}
private sEntity(): void {
// This is essentially a specialized version of captureToChar(SEMICOLON...)
let { i: start } = this;
const { chunk } = this;
// eslint-disable-next-line no-labels, no-restricted-syntax
loop:
// eslint-disable-next-line no-constant-condition
while (true) {
switch (this.getCode()) {
case NL_LIKE:
this.entity += `${chunk.slice(start, this.prevI)}\n`;
start = this.i;
break;
case SEMICOLON: {
const { entityReturnState } = this;
const entity = this.entity + chunk.slice(start, this.prevI);
this.state = entityReturnState!;
let parsed: string;
if (entity === "") {
this.fail("empty entity name.");
parsed = "&;";
}
else {
parsed = this.parseEntity(entity);
this.entity = "";
}
if (entityReturnState !== S_TEXT || this.textHandler !== undefined) {
this.text += parsed;
}
// eslint-disable-next-line no-labels
break loop;
}
case EOC:
this.entity += chunk.slice(start);
// eslint-disable-next-line no-labels
break loop;
default:
}
}
}
private sOpenWaka(): void {
// Reminder: a state handler is called with at least one character
// available in the current chunk. So the first call to get code inside of
// a state handler cannot return ``EOC``. That's why we don't test
// for it.
const c = this.getCode();
// either a /, ?, !, or text is coming next.
if (isNameStartChar(c)) {
this.state = S_OPEN_TAG;
this.unget();
this.xmlDeclPossible = false;
}
else {
switch (c) {
case FORWARD_SLASH:
this.state = S_CLOSE_TAG;
this.xmlDeclPossible = false;
break;
case BANG:
this.state = S_OPEN_WAKA_BANG;
this.openWakaBang = "";
this.xmlDeclPossible = false;
break;
case QUESTION:
this.state = S_PI_FIRST_CHAR;
break;
default:
this.fail("disallowed character in tag name");
this.state = S_TEXT;
this.xmlDeclPossible = false;
}
}
}
private sOpenWakaBang(): void {
this.openWakaBang += String.fromCodePoint(this.getCodeNorm());
switch (this.openWakaBang) {
case "[CDATA[":
if (!this.sawRoot && !this.reportedTextBeforeRoot) {
this.fail("text data outside of root node.");
this.reportedTextBeforeRoot = true;
}
if (this.closedRoot && !this.reportedTextAfterRoot) {
this.fail("text data outside of root node.");
this.reportedTextAfterRoot = true;
}
this.state = S_CDATA;
this.openWakaBang = "";
break;
case "--":
this.state = S_COMMENT;
this.openWakaBang = "";
break;
case "DOCTYPE":
this.state = S_DOCTYPE;
if (this.doctype || this.sawRoot) {
this.fail("inappropriately located doctype declaration.");
}
this.openWakaBang = "";
break;
default:
// 7 happens to be the maximum length of the string that can possibly
// match one of the cases above.
if (this.openWakaBang.length >= 7) {
this.fail("incorrect syntax.");
}
}
}
private sComment(): void {
if (this.captureToChar(MINUS)) {
this.state = S_COMMENT_ENDING;
}
}
private sCommentEnding(): void {
const c = this.getCodeNorm();
if (c === MINUS) {
this.state = S_COMMENT_ENDED;
this.commentHandler?.(this.text);
this.text = "";
}
else {
this.text += `-${String.fromCodePoint(c)}`;
this.state = S_COMMENT;
}
}
private sCommentEnded(): void {
const c = this.getCodeNorm();
if (c !== GREATER) {
this.fail("malformed comment.");
// <!-- blah -- bloo --> will be recorded as
// a comment of " blah -- bloo "
this.text += `--${String.fromCodePoint(c)}`;
this.state = S_COMMENT;
}
else {
this.state = S_TEXT;
}
}
private sCData(): void {
if (this.captureToChar(CLOSE_BRACKET)) {
this.state = S_CDATA_ENDING;
}
}
private sCDataEnding(): void {
const c = this.getCodeNorm();
if (c === CLOSE_BRACKET) {
this.state = S_CDATA_ENDING_2;
}
else {
this.text += `]${String.fromCodePoint(c)}`;
this.state = S_CDATA;
}
}
private sCDataEnding2(): void {
const c = this.getCodeNorm();
switch (c) {
case GREATER: {
this.cdataHandler?.(this.text);
this.text = "";
this.state = S_TEXT;
break;
}
case CLOSE_BRACKET:
this.text += "]";
break;
default:
this.text += `]]${String.fromCodePoint(c)}`;
this.state = S_CDATA;
}
}
// We need this separate state to check the first character fo the pi target
// with this.nameStartCheck which allows less characters than this.nameCheck.
private sPIFirstChar(): void {
const c = this.getCodeNorm();
// This is first because in the case where the file is well-formed this is
// the branch taken. We optimize for well-formedness.
if (this.nameStartCheck(c)) {
this.piTarget += String.fromCodePoint(c);
this.state = S_PI_REST;
}
else if (c === QUESTION || isS(c)) {
this.fail("processing instruction without a target.");
this.state = c === QUESTION ? S_PI_ENDING : S_PI_BODY;
}
else {
this.fail("disallowed character in processing instruction name.");
this.piTarget += String.fromCodePoint(c);
this.state = S_PI_REST;
}
}
private sPIRest(): void {
// Capture characters into a piTarget while ``this.nameCheck`` run on the
// character read returns true.
const { chunk, i: start } = this;
// eslint-disable-next-line no-constant-condition
while (true) {
const c = this.getCodeNorm();
if (c === EOC) {
this.piTarget += chunk.slice(start);
return;
}
// NL cannot satisfy this.nameCheck so we don't have to test specifically
// for it.
if (!this.nameCheck(c)) {
this.piTarget += chunk.slice(start, this.prevI);
const isQuestion = c === QUESTION;
if (isQuestion || isS(c)) {
if (this.piTarget === "xml") {
if (!this.xmlDeclPossible) {
this.fail(
"an XML declaration must be at the start of the document.");
}
this.state = isQuestion ? S_XML_DECL_ENDING : S_XML_DECL_NAME_START;
}
else {
this.state = isQuestion ? S_PI_ENDING : S_PI_BODY;
}
}
else {
this.fail("disallowed character in processing instruction name.");
this.piTarget += String.fromCodePoint(c);
}
break;
}
}
}
private sPIBody(): void {
if (this.text.length === 0) {
const c = this.getCodeNorm();
if (c === QUESTION) {
this.state = S_PI_ENDING;
}
else if (!isS(c)) {
this.text = String.fromCodePoint(c);
}
}
// The question mark character is not valid inside any of the XML
// declaration name/value pairs.
else if (this.captureToChar(QUESTION)) {
this.state = S_PI_ENDING;
}
}
private sPIEnding(): void {
const c = this.getCodeNorm();
if (c === GREATER) {
const { piTarget } = this;
if (piTarget.toLowerCase() === "xml") {
this.fail(
"the XML declaration must appear at the start of the document.");
}
this.piHandler?.({
target: piTarget,
body: this.text,
});
this.piTarget = this.text = "";
this.state = S_TEXT;
}
else if (c === QUESTION) {
// We ran into ?? as part of a processing instruction. We initially took
// the first ? as a sign that the PI was ending, but it is not. So we have
// to add it to the body but we take the new ? as a sign that the PI is
// ending.
this.text += "?";
}
else {
this.text += `?${String.fromCodePoint(c)}`;
this.state = S_PI_BODY;
}
this.xmlDeclPossible = false;
}
private sXMLDeclNameStart(): void {
const c = this.skipSpaces();
// The question mark character is not valid inside any of the XML
// declaration name/value pairs.
if (c === QUESTION) {
// It is valid to go to S_XML_DECL_ENDING from this state.
this.state = S_XML_DECL_ENDING;
return;
}
if (c !== EOC) {
this.state = S_XML_DECL_NAME;
this.name = String.fromCodePoint(c);
}
}
private sXMLDeclName(): void {
const c = this.captureTo(XML_DECL_NAME_TERMINATOR);
// The question mark character is not valid inside any of the XML
// declaration name/value pairs.
if (c === QUESTION) {
this.state = S_XML_DECL_ENDING;
this.name += this.text;
this.text = "";
this.fail("XML declaration is incomplete.");
return;
}
if (!(isS(c) || c === EQUAL)) {
return;
}
this.name += this.text;
this.text = "";
if (!this.xmlDeclExpects.includes(this.name)) {
switch (this.name.length) {
case 0:
this.fail("did not expect any more name/value pairs.");
break;
case 1:
this.fail(`expected the name ${this.xmlDeclExpects[0]}.`);
break;
default:
this.fail(`expected one of ${this.xmlDeclExpects.join(", ")}`);
}
}
this.state = c === EQUAL ? S_XML_DECL_VALUE_START : S_XML_DECL_EQ;
}
private sXMLDeclEq(): void {
const c = this.getCodeNorm();
// The question mark character is not valid inside any of the XML
// declaration name/value pairs.
if (c === QUESTION) {
this.state = S_XML_DECL_ENDING;
this.fail("XML declaration is incomplete.");
return;
}
if (isS(c)) {
return;
}
if (c !== EQUAL) {
this.fail("value required.");
}
this.state = S_XML_DECL_VALUE_START;
}
private sXMLDeclValueStart(): void {
const c = this.getCodeNorm();
// The question mark character is not valid inside any of the XML
// declaration name/value pairs.
if (c === QUESTION) {
this.state = S_XML_DECL_ENDING;
this.fail("XML declaration is incomplete.");
return;
}
if (isS(c)) {
return;
}
if (!isQuote(c)) {
this.fail("value must be quoted.");
this.q = SPACE;
}
else {
this.q = c;
}
this.state = S_XML_DECL_VALUE;
}
private sXMLDeclValue(): void {
const c = this.captureTo([this.q!, QUESTION]);
// The question mark character is not valid inside any of the XML
// declaration name/value pairs.
if (c === QUESTION) {
this.state = S_XML_DECL_ENDING;
this.text = "";
this.fail("XML declaration is incomplete.");
return;
}
if (c === EOC) {
return;
}
const value = this.text;
this.text = "";
switch (this.name) {
case "version": {
this.xmlDeclExpects = ["encoding", "standalone"];
const version = value;
this.xmlDecl.version = version;
// This is the test specified by XML 1.0 but it is fine for XML 1.1.
if (!/^1\.[0-9]+$/.test(version)) {
this.fail("version number must match /^1\\.[0-9]+$/.");
}
// When forceXMLVersion is set, the XML declaration is ignored.
else if (!(this.opt.forceXMLVersion as boolean)) {
this.setXMLVersion(version);
}
break;
}
case "encoding":
if (!/^[A-Za-z][A-Za-z0-9._-]*$/.test(value)) {
this.fail("encoding value must match \
/^[A-Za-z0-9][A-Za-z0-9._-]*$/.");
}
this.xmlDeclExpects = ["standalone"];
this.xmlDecl.encoding = value;
break;
case "standalone":
if (value !== "yes" && value !== "no") {
this.fail("standalone value must match \"yes\" or \"no\".");
}
this.xmlDeclExpects = [];
this.xmlDecl.standalone = value;
break;
default:
// We don't need to raise an error here since we've already raised one
// when checking what name was expected.
}
this.name = "";
this.state = S_XML_DECL_SEPARATOR;
}
private sXMLDeclSeparator(): void {
const c = this.getCodeNorm();
// The question mark character is not valid inside any of the XML
// declaration name/value pairs.
if (c === QUESTION) {
// It is valid to go to S_XML_DECL_ENDING from this state.
this.state = S_XML_DECL_ENDING;
return;
}
if (!isS(c)) {
this.fail("whitespace required.");
this.unget();
}
this.state = S_XML_DECL_NAME_START;
}
private sXMLDeclEnding(): void {
const c = this.getCodeNorm();
if (c === GREATER) {
if (this.piTarget !== "xml") {
this.fail("processing instructions are not allowed before root.");
}
else if (this.name !== "version" &&
this.xmlDeclExpects.includes("version")) {
this.fail("XML declaration must contain a version.");
}
this.xmldeclHandler?.(this.xmlDecl);
this.name = "";
this.piTarget = this.text = "";
this.state = S_TEXT;
}
else {
// We got here because the previous character was a ?, but the question
// mark character is not valid inside any of the XML declaration
// name/value pairs.
this.fail(
"The character ? is disallowed anywhere in XML declarations.");
}
this.xmlDeclPossible = false;
}
private sOpenTag(): void {
const c = this.captureNameChars();
if (c === EOC) {
return;
}
const tag: SaxesTagIncomplete = this.tag = {
name: this.name,
attributes: Object.create(null) as Record<string, string>,
};
this.name = "";
if (this.xmlnsOpt) {
this.topNS = tag.ns = Object.create(null) as Record<string, string>;
}
this.openTagStartHandler?.(tag as StartTagForOptions<O>);
this.sawRoot = true;
if (!this.fragmentOpt && this.closedRoot) {
this.fail("documents may contain only one root.");
}
switch (c) {
case GREATER:
this.openTag();
break;
case FORWARD_SLASH:
this.state = S_OPEN_TAG_SLASH;
break;
default:
if (!isS(c)) {
this.fail("disallowed character in tag name.");
}
this.state = S_ATTRIB;
}
}
private sOpenTagSlash(): void {
if (this.getCode() === GREATER) {
this.openSelfClosingTag();
}
else {
this.fail("forward-slash in opening tag not followed by >.");
this.state = S_ATTRIB;
}
}
private sAttrib(): void {
const c = this.skipSpaces();
if (c === EOC) {
return;
}
if (isNameStartChar(c)) {
this.unget();
this.state = S_ATTRIB_NAME;
}
else if (c === GREATER) {
this.openTag();
}
else if (c === FORWARD_SLASH) {
this.state = S_OPEN_TAG_SLASH;
}
else {
this.fail("disallowed character in attribute name.");
}
}
private sAttribName(): void {
const c = this.captureNameChars();
if (c === EQUAL) {
this.state = S_ATTRIB_VALUE;
}
else if (isS(c)) {
this.state = S_ATTRIB_NAME_SAW_WHITE;
}
else if (c === GREATER) {
this.fail("attribute without value.");
this.pushAttrib(this.name, this.name);
this.name = this.text = "";
this.openTag();
}
else if (c !== EOC) {
this.fail("disallowed character in attribute name.");
}
}
private sAttribNameSawWhite(): void {
const c = this.skipSpaces();
switch (c) {
case EOC:
return;
case EQUAL:
this.state = S_ATTRIB_VALUE;
break;
default:
this.fail("attribute without value.");
// Should we do this???
// this.tag.attributes[this.name] = "";
this.text = "";
this.name = "";
if (c === GREATER) {
this.openTag();
}
else if (isNameStartChar(c)) {
this.unget();
this.state = S_ATTRIB_NAME;
}
else {
this.fail("disallowed character in attribute name.");
this.state = S_ATTRIB;
}
}
}
private sAttribValue(): void {
const c = this.getCodeNorm();
if (isQuote(c)) {
this.q = c;
this.state = S_ATTRIB_VALUE_QUOTED;
}
else if (!isS(c)) {
this.fail("unquoted attribute value.");
this.state = S_ATTRIB_VALUE_UNQUOTED;
this.unget();
}
}
private sAttribValueQuoted(): void {
// We deliberately do not use captureTo here. The specialized code we use
// here is faster than using captureTo.
const { q, chunk } = this;
let { i: start } = this;
// eslint-disable-next-line no-constant-condition
while (true) {
switch (this.getCode()) {
case q:
this.pushAttrib(this.name,
this.text + chunk.slice(start, this.prevI));
this.name = this.text = "";
this.q = null;
this.state = S_ATTRIB_VALUE_CLOSED;
return;
case AMP:
this.text += chunk.slice(start, this.prevI);
this.state = S_ENTITY;
this.entityReturnState = S_ATTRIB_VALUE_QUOTED;
return;
case NL:
case NL_LIKE:
case TAB:
this.text += `${chunk.slice(start, this.prevI)} `;
start = this.i;
break;
case LESS:
this.text += chunk.slice(start, this.prevI);
this.fail("disallowed character.");
return;
case EOC:
this.text += chunk.slice(start);
return;
default:
}
}
}
private sAttribValueClosed(): void {
const c = this.getCodeNorm();
if (isS(c)) {
this.state = S_ATTRIB;
}
else if (c === GREATER) {
this.openTag();
}
else if (c === FORWARD_SLASH) {
this.state = S_OPEN_TAG_SLASH;
}
else if (isNameStartChar(c)) {
this.fail("no whitespace between attributes.");
this.unget();
this.state = S_ATTRIB_NAME;
}
else {
this.fail("disallowed character in attribute name.");
}
}
private sAttribValueUnquoted(): void {
// We don't do anything regarding EOL or space handling for unquoted
// attributes. We already have failed by the time we get here, and the
// contract that saxes upholds states that upon failure, it is not safe to
// rely on the data passed to event handlers (other than
// ``onerror``). Passing "bad" data is not a problem.
const c = this.captureTo(ATTRIB_VALUE_UNQUOTED_TERMINATOR);
switch (c) {
case AMP:
this.state = S_ENTITY;
this.entityReturnState = S_ATTRIB_VALUE_UNQUOTED;
break;
case LESS:
this.fail("disallowed character.");
break;
case EOC:
break;
default:
if (this.text.includes("]]>")) {
this.fail("the string \"]]>\" is disallowed in char data.");
}
this.pushAttrib(this.name, this.text);
this.name = this.text = "";
if (c === GREATER) {
this.openTag();
}
else {
this.state = S_ATTRIB;
}
}
}
private sCloseTag(): void {
const c = this.captureNameChars();
if (c === GREATER) {
this.closeTag();
}
else if (isS(c)) {
this.state = S_CLOSE_TAG_SAW_WHITE;
}
else if (c !== EOC) {
this.fail("disallowed character in closing tag.");
}
}
private sCloseTagSawWhite(): void {
switch (this.skipSpaces()) {
case GREATER:
this.closeTag();
break;
case EOC:
break;
default:
this.fail("disallowed character in closing tag.");
}
}
// END OF STATE ENGINE METHODS
private handleTextInRoot(): void {
// This is essentially a specialized version of captureTo which is optimized
// for performing the ]]> check. A previous version of this code, checked
// ``this.text`` for the presence of ]]>. It simplified the code but was
// very costly when character data contained a lot of entities to be parsed.
//
// Since we are using a specialized loop, we also keep track of the presence
// of ]]> in text data. The sequence ]]> is forbidden to appear as-is.
//
let { i: start, forbiddenState } = this;
const { chunk, textHandler: handler } = this;
// eslint-disable-next-line no-labels, no-restricted-syntax
scanLoop:
// eslint-disable-next-line no-constant-condition
while (true) {
switch (this.getCode()) {
case LESS: {
this.state = S_OPEN_WAKA;
if (handler !== undefined) {
const { text } = this;
const slice = chunk.slice(start, this.prevI);
if (text.length !== 0) {
handler(text + slice);
this.text = "";
}
else if (slice.length !== 0) {
handler(slice);
}
}
forbiddenState = FORBIDDEN_START;
// eslint-disable-next-line no-labels
break scanLoop;
}
case AMP:
this.state = S_ENTITY;
this.entityReturnState = S_TEXT;
if (handler !== undefined) {
this.text += chunk.slice(start, this.prevI);
}
forbiddenState = FORBIDDEN_START;
// eslint-disable-next-line no-labels
break scanLoop;
case CLOSE_BRACKET:
switch (forbiddenState) {
case FORBIDDEN_START:
forbiddenState = FORBIDDEN_BRACKET;
break;
case FORBIDDEN_BRACKET:
forbiddenState = FORBIDDEN_BRACKET_BRACKET;
break;
case FORBIDDEN_BRACKET_BRACKET:
break;
default:
throw new Error("impossible state");
}
break;
case GREATER:
if (forbiddenState === FORBIDDEN_BRACKET_BRACKET) {
this.fail("the string \"]]>\" is disallowed in char data.");
}
forbiddenState = FORBIDDEN_START;
break;
case NL_LIKE:
if (handler !== undefined) {
this.text += `${chunk.slice(start, this.prevI)}\n`;
}
start = this.i;
forbiddenState = FORBIDDEN_START;
break;
case EOC:
if (handler !== undefined) {
this.text += chunk.slice(start);
}
// eslint-disable-next-line no-labels
break scanLoop;
default:
forbiddenState = FORBIDDEN_START;
}
}
this.forbiddenState = forbiddenState;
}
private handleTextOutsideRoot(): void {
// This is essentially a specialized version of captureTo which is optimized
// for a specialized task. We keep track of the presence of non-space
// characters in the text since these are errors when appearing outside the
// document root element.
let { i: start } = this;
const { chunk, textHandler: handler } = this;
let nonSpace = false;
// eslint-disable-next-line no-labels, no-restricted-syntax
outRootLoop:
// eslint-disable-next-line no-constant-condition
while (true) {
const code = this.getCode();
switch (code) {
case LESS: {
this.state = S_OPEN_WAKA;
if (handler !== undefined) {
const { text } = this;
const slice = chunk.slice(start, this.prevI);
if (text.length !== 0) {
handler(text + slice);
this.text = "";
}
else if (slice.length !== 0) {
handler(slice);
}
}
// eslint-disable-next-line no-labels
break outRootLoop;
}
case AMP:
this.state = S_ENTITY;
this.entityReturnState = S_TEXT;
if (handler !== undefined) {
this.text += chunk.slice(start, this.prevI);
}
nonSpace = true;
// eslint-disable-next-line no-labels
break outRootLoop;
case NL_LIKE:
if (handler !== undefined) {
this.text += `${chunk.slice(start, this.prevI)}\n`;
}
start = this.i;
break;
case EOC:
if (handler !== undefined) {
this.text += chunk.slice(start);
}
// eslint-disable-next-line no-labels
break outRootLoop;
default:
if (!isS(code)) {
nonSpace = true;
}
}
}
if (!nonSpace) {
return;
}
// We use the reportedTextBeforeRoot and reportedTextAfterRoot flags
// to avoid reporting errors for every single character that is out of
// place.
if (!this.sawRoot && !this.reportedTextBeforeRoot) {
this.fail("text data outside of root node.");
this.reportedTextBeforeRoot = true;
}
if (this.closedRoot && !this.reportedTextAfterRoot) {
this.fail("text data outside of root node.");
this.reportedTextAfterRoot = true;
}
}
private pushAttribNS(name: string, value: string): void {
const { prefix, local } = this.qname(name);
const attr = { name, prefix, local, value };
this.attribList.push(attr);
this.attributeHandler?.(attr as AttributeEventForOptions<O>);
if (prefix === "xmlns") {
const trimmed = value.trim();
if (this.currentXMLVersion === "1.0" && trimmed === "") {
this.fail("invalid attempt to undefine prefix in XML 1.0");
}
this.topNS![local] = trimmed;
nsPairCheck(this, local, trimmed);
}
else if (name === "xmlns") {
const trimmed = value.trim();
this.topNS![""] = trimmed;
nsPairCheck(this, "", trimmed);
}
}
private pushAttribPlain(name: string, value: string): void {
const attr = { name, value };
this.attribList.push(attr);
this.attributeHandler?.(attr as AttributeEventForOptions<O>);
}
/**
* End parsing. This performs final well-formedness checks and resets the
* parser to a clean state.
*
* @returns this
*/
private end(): this {
if (!this.sawRoot) {
this.fail("document must contain a root element.");
}
const { tags } = this;
while (tags.length > 0) {
const tag = tags.pop()!;
this.fail(`unclosed tag: ${tag.name}`);
}
if ((this.state !== S_BEGIN) && (this.state !== S_TEXT)) {
this.fail("unexpected end.");
}
const { text } = this;
if (text.length !== 0) {
this.textHandler?.(text);
this.text = "";
}
this._closed = true;
this.endHandler?.();
this._init();
return this;
}
/**
* Resolve a namespace prefix.
*
* @param prefix The prefix to resolve.
*
* @returns The namespace URI or ``undefined`` if the prefix is not defined.
*/
resolve(prefix: string): string | undefined {
let uri = this.topNS![prefix];
if (uri !== undefined) {
return uri;
}
const { tags } = this;
for (let index = tags.length - 1; index >= 0; index--) {
uri = tags[index]!.ns![prefix];
if (uri !== undefined) {
return uri;
}
}
uri = this.ns[prefix];
if (uri !== undefined) {
return uri;
}
return this.opt.resolvePrefix?.(prefix);
}
/**
* Parse a qname into its prefix and local name parts.
*
* @param name The name to parse
*
* @returns
*/
private qname(name: string): { prefix: string; local: string } {
// This is faster than using name.split(":").
const colon = name.indexOf(":");
if (colon === -1) {
return { prefix: "", local: name };
}
const local = name.slice(colon + 1);
const prefix = name.slice(0, colon);
if (prefix === "" || local === "" || local.includes(":")) {
this.fail(`malformed name: ${name}.`);
}
return { prefix, local };
}
private processAttribsNS(): void {
const { attribList } = this;
const tag = this.tag!;
{
// add namespace info to tag
const { prefix, local } = this.qname(tag.name);
tag.prefix = prefix;
tag.local = local;
const uri = tag.uri = this.resolve(prefix) ?? "";
if (prefix !== "") {
if (prefix === "xmlns") {
this.fail("tags may not have \"xmlns\" as prefix.");
}
if (uri === "") {
this.fail(`unbound namespace prefix: ${JSON.stringify(prefix)}.`);
tag.uri = prefix;
}
}
}
if (attribList.length === 0) {
return;
}
const { attributes } = tag;
const seen = new Set();
// Note: do not apply default ns to attributes:
// http://www.w3.org/TR/REC-xml-names/#defaulting
for (const attr of attribList as SaxesAttributeNSIncomplete[]) {
const { name, prefix, local } = attr;
let uri;
let eqname;
if (prefix === "") {
uri = name === "xmlns" ? XMLNS_NAMESPACE : "";
eqname = name;
}
else {
uri = this.resolve(prefix);
// if there's any attributes with an undefined namespace,
// then fail on them now.
if (uri === undefined) {
this.fail(`unbound namespace prefix: ${JSON.stringify(prefix)}.`);
uri = prefix;
}
eqname = `{${uri}}${local}`;
}
if (seen.has(eqname)) {
this.fail(`duplicate attribute: ${eqname}.`);
}
seen.add(eqname);
attr.uri = uri;
attributes[name] = attr;
}
this.attribList = [];
}
private processAttribsPlain(): void {
const { attribList } = this;
// eslint-disable-next-line prefer-destructuring
const attributes = this.tag!.attributes;
for (const { name, value } of attribList) {
if (attributes[name] !== undefined) {
this.fail(`duplicate attribute: ${name}.`);
}
attributes[name] = value;
}
this.attribList = [];
}
/**
* Handle a complete open tag. This parser code calls this once it has seen
* the whole tag. This method checks for well-formeness and then emits
* ``onopentag``.
*/
private openTag(): void {
this.processAttribs();
const { tags } = this;
const tag = this.tag as SaxesTag;
tag.isSelfClosing = false;
// There cannot be any pending text here due to the onopentagstart that was
// necessarily emitted before we get here. So we do not check text.
this.openTagHandler?.(tag as TagForOptions<O>);
tags.push(tag);
this.state = S_TEXT;
this.name = "";
}
/**
* Handle a complete self-closing tag. This parser code calls this once it has
* seen the whole tag. This method checks for well-formeness and then emits
* ``onopentag`` and ``onclosetag``.
*/
private openSelfClosingTag(): void {
this.processAttribs();
const { tags } = this;
const tag = this.tag as SaxesTag;
tag.isSelfClosing = true;
// There cannot be any pending text here due to the onopentagstart that was
// necessarily emitted before we get here. So we do not check text.
this.openTagHandler?.(tag as TagForOptions<O>);
this.closeTagHandler?.(tag as TagForOptions<O>);
const top = this.tag = tags[tags.length - 1] ?? null;
if (top === null) {
this.closedRoot = true;
}
this.state = S_TEXT;
this.name = "";
}
/**
* Handle a complete close tag. This parser code calls this once it has seen
* the whole tag. This method checks for well-formeness and then emits
* ``onclosetag``.
*/
private closeTag(): void {
const { tags, name } = this;
// Our state after this will be S_TEXT, no matter what, and we can clear
// tagName now.
this.state = S_TEXT;
this.name = "";
if (name === "") {
this.fail("weird empty close tag.");
this.text += "</>";
return;
}
const handler = this.closeTagHandler;
let l = tags.length;
while (l-- > 0) {
const tag = this.tag = tags.pop() as SaxesTag;
this.topNS = tag.ns!;
handler?.(tag as TagForOptions<O>);
if (tag.name === name) {
break;
}
this.fail("unexpected close tag.");
}
if (l === 0) {
this.closedRoot = true;
}
else if (l < 0) {
this.fail(`unmatched closing tag: ${name}.`);
this.text += `</${name}>`;
}
}
/**
* Resolves an entity. Makes any necessary well-formedness checks.
*
* @param entity The entity to resolve.
*
* @returns The parsed entity.
*/
private parseEntity(entity: string): string {
// startsWith would be significantly slower for this test.
if (entity[0] !== "#") {
const defined = this.ENTITIES[entity];
if (defined !== undefined) {
return defined;
}
this.fail(this.isName(entity) ? "undefined entity." :
"disallowed character in entity name.");
return `&${entity};`;
}
let num = NaN;
if (entity[1] === "x" && /^#x[0-9a-f]+$/i.test(entity)) {
num = parseInt(entity.slice(2), 16);
}
else if (/^#[0-9]+$/.test(entity)) {
num = parseInt(entity.slice(1), 10);
}
// The character reference is required to match the CHAR production.
if (!this.isChar(num)) {
this.fail("malformed character entity.");
return `&${entity};`;
}
return String.fromCodePoint(num);
}
} |
1,141 | writeSource(parser: SaxesParser, source: string): void {
parser.write(source);
parser.close();
} | class SaxesParser<O extends SaxesOptions = {}> {
private readonly fragmentOpt: boolean;
private readonly xmlnsOpt: boolean;
private readonly trackPosition: boolean;
private readonly fileName?: string;
private readonly nameStartCheck: (c: number) => boolean;
private readonly nameCheck: (c: number) => boolean;
private readonly isName: (name: string) => boolean;
private readonly ns!: Record<string, string>;
private openWakaBang!: string;
private text!: string;
private name!: string;
private piTarget!: string;
private entity!: string;
private q!: null | number;
private tags!: SaxesTagIncomplete[];
private tag!: SaxesTagIncomplete | null;
private topNS!: Record<string, string> | null;
private chunk!: string;
private chunkPosition!: number;
private i!: number;
//
// We use prevI to allow "ungetting" the previously read code point. Note
// however, that it is not safe to unget everything and anything. In
// particular ungetting EOL characters will screw positioning up.
//
// Practically, you must not unget a code which has any side effect beyond
// updating ``this.i`` and ``this.prevI``. Only EOL codes have such side
// effects.
//
private prevI!: number;
private carriedFromPrevious?: string;
private forbiddenState!: number;
private attribList!: (SaxesAttributeNSIncomplete | SaxesAttributePlain)[];
private state!: number;
private reportedTextBeforeRoot!: boolean;
private reportedTextAfterRoot!: boolean;
private closedRoot!: boolean;
private sawRoot!: boolean;
private xmlDeclPossible!: boolean;
private xmlDeclExpects!: string[];
private entityReturnState?: number;
private processAttribs!: (this: this) => void;
private positionAtNewLine!: number;
private doctype!: boolean;
private getCode!: () => number;
private isChar!: (c: number) => boolean;
private pushAttrib!: (name: string, value: string) => void;
private _closed!: boolean;
private currentXMLVersion!: string;
private readonly stateTable: ((this: SaxesParser<O>) => void)[];
private xmldeclHandler?: XMLDeclHandler;
private textHandler?: TextHandler;
private piHandler?: PIHandler;
private doctypeHandler?: DoctypeHandler;
private commentHandler?: CommentHandler;
private openTagStartHandler?: OpenTagStartHandler<O>;
private openTagHandler?: OpenTagHandler<O>;
private closeTagHandler?: CloseTagHandler<O>;
private cdataHandler?: CDataHandler;
private errorHandler?: ErrorHandler;
private endHandler?: EndHandler;
private readyHandler?: ReadyHandler;
private attributeHandler?: AttributeHandler<O>;
/**
* Indicates whether or not the parser is closed. If ``true``, wait for
* the ``ready`` event to write again.
*/
get closed(): boolean {
return this._closed;
}
readonly opt: SaxesOptions;
/**
* The XML declaration for this document.
*/
xmlDecl!: XMLDecl;
/**
* The line number of the next character to be read by the parser. This field
* is one-based. (The first line is numbered 1.)
*/
line!: number;
/**
* The column number of the next character to be read by the parser. *
* This field is zero-based. (The first column is 0.)
*
* This field counts columns by *Unicode character*. Note that this *can*
* be different from the index of the character in a JavaScript string due
* to how JavaScript handles astral plane characters.
*
* See [[columnIndex]] for a number that corresponds to the JavaScript index.
*/
column!: number;
/**
* A map of entity name to expansion.
*/
ENTITIES!: Record<string, string>;
/**
* @param opt The parser options.
*/
constructor(opt?: O) {
this.opt = opt ?? {};
this.fragmentOpt = !!(this.opt.fragment as boolean);
const xmlnsOpt = this.xmlnsOpt = !!(this.opt.xmlns as boolean);
this.trackPosition = this.opt.position !== false;
this.fileName = this.opt.fileName;
if (xmlnsOpt) {
// This is the function we use to perform name checks on PIs and entities.
// When namespaces are used, colons are not allowed in PI target names or
// entity names. So the check depends on whether namespaces are used. See:
//
// https://www.w3.org/XML/xml-names-19990114-errata.html
// NE08
//
this.nameStartCheck = isNCNameStartChar;
this.nameCheck = isNCNameChar;
this.isName = isNCName;
// eslint-disable-next-line @typescript-eslint/unbound-method
this.processAttribs = this.processAttribsNS;
// eslint-disable-next-line @typescript-eslint/unbound-method
this.pushAttrib = this.pushAttribNS;
// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-assignment
this.ns = { __proto__: null as any, ...rootNS };
const additional = this.opt.additionalNamespaces;
if (additional != null) {
nsMappingCheck(this, additional);
Object.assign(this.ns, additional);
}
}
else {
this.nameStartCheck = isNameStartChar;
this.nameCheck = isNameChar;
this.isName = isName;
// eslint-disable-next-line @typescript-eslint/unbound-method
this.processAttribs = this.processAttribsPlain;
// eslint-disable-next-line @typescript-eslint/unbound-method
this.pushAttrib = this.pushAttribPlain;
}
//
// The order of the members in this table needs to correspond to the state
// numbers given to the states that correspond to the methods being recorded
// here.
//
this.stateTable = [
/* eslint-disable @typescript-eslint/unbound-method */
this.sBegin,
this.sBeginWhitespace,
this.sDoctype,
this.sDoctypeQuote,
this.sDTD,
this.sDTDQuoted,
this.sDTDOpenWaka,
this.sDTDOpenWakaBang,
this.sDTDComment,
this.sDTDCommentEnding,
this.sDTDCommentEnded,
this.sDTDPI,
this.sDTDPIEnding,
this.sText,
this.sEntity,
this.sOpenWaka,
this.sOpenWakaBang,
this.sComment,
this.sCommentEnding,
this.sCommentEnded,
this.sCData,
this.sCDataEnding,
this.sCDataEnding2,
this.sPIFirstChar,
this.sPIRest,
this.sPIBody,
this.sPIEnding,
this.sXMLDeclNameStart,
this.sXMLDeclName,
this.sXMLDeclEq,
this.sXMLDeclValueStart,
this.sXMLDeclValue,
this.sXMLDeclSeparator,
this.sXMLDeclEnding,
this.sOpenTag,
this.sOpenTagSlash,
this.sAttrib,
this.sAttribName,
this.sAttribNameSawWhite,
this.sAttribValue,
this.sAttribValueQuoted,
this.sAttribValueClosed,
this.sAttribValueUnquoted,
this.sCloseTag,
this.sCloseTagSawWhite,
/* eslint-enable @typescript-eslint/unbound-method */
];
this._init();
}
_init(): void {
this.openWakaBang = "";
this.text = "";
this.name = "";
this.piTarget = "";
this.entity = "";
this.q = null;
this.tags = [];
this.tag = null;
this.topNS = null;
this.chunk = "";
this.chunkPosition = 0;
this.i = 0;
this.prevI = 0;
this.carriedFromPrevious = undefined;
this.forbiddenState = FORBIDDEN_START;
this.attribList = [];
// The logic is organized so as to minimize the need to check
// this.opt.fragment while parsing.
const { fragmentOpt } = this;
this.state = fragmentOpt ? S_TEXT : S_BEGIN;
// We want these to be all true if we are dealing with a fragment.
this.reportedTextBeforeRoot = this.reportedTextAfterRoot = this.closedRoot =
this.sawRoot = fragmentOpt;
// An XML declaration is intially possible only when parsing whole
// documents.
this.xmlDeclPossible = !fragmentOpt;
this.xmlDeclExpects = ["version"];
this.entityReturnState = undefined;
let { defaultXMLVersion } = this.opt;
if (defaultXMLVersion === undefined) {
if (this.opt.forceXMLVersion === true) {
throw new Error("forceXMLVersion set but defaultXMLVersion is not set");
}
defaultXMLVersion = "1.0";
}
this.setXMLVersion(defaultXMLVersion);
this.positionAtNewLine = 0;
this.doctype = false;
this._closed = false;
this.xmlDecl = {
version: undefined,
encoding: undefined,
standalone: undefined,
};
this.line = 1;
this.column = 0;
this.ENTITIES = Object.create(XML_ENTITIES) as Record<string, string>;
this.readyHandler?.();
}
/**
* The stream position the parser is currently looking at. This field is
* zero-based.
*
* This field is not based on counting Unicode characters but is to be
* interpreted as a plain index into a JavaScript string.
*/
get position(): number {
return this.chunkPosition + this.i;
}
/**
* The column number of the next character to be read by the parser. *
* This field is zero-based. (The first column in a line is 0.)
*
* This field reports the index at which the next character would be in the
* line if the line were represented as a JavaScript string. Note that this
* *can* be different to a count based on the number of *Unicode characters*
* due to how JavaScript handles astral plane characters.
*
* See [[column]] for a number that corresponds to a count of Unicode
* characters.
*/
get columnIndex(): number {
return this.position - this.positionAtNewLine;
}
/**
* Set an event listener on an event. The parser supports one handler per
* event type. If you try to set an event handler over an existing handler,
* the old handler is silently overwritten.
*
* @param name The event to listen to.
*
* @param handler The handler to set.
*/
on<N extends EventName>(name: N, handler: EventNameToHandler<O, N>): void {
// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-member-access
(this as any)[EVENT_NAME_TO_HANDLER_NAME[name]] = handler;
}
/**
* Unset an event handler.
*
* @parma name The event to stop listening to.
*/
off(name: EventName): void {
// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-member-access
(this as any)[EVENT_NAME_TO_HANDLER_NAME[name]] = undefined;
}
/**
* Make an error object. The error object will have a message that contains
* the ``fileName`` option passed at the creation of the parser. If position
* tracking was turned on, it will also have line and column number
* information.
*
* @param message The message describing the error to report.
*
* @returns An error object with a properly formatted message.
*/
makeError(message: string): Error {
let msg = this.fileName ?? "";
if (this.trackPosition) {
if (msg.length > 0) {
msg += ":";
}
msg += `${this.line}:${this.column}`;
}
if (msg.length > 0) {
msg += ": ";
}
return new Error(msg + message);
}
/**
* Report a parsing error. This method is made public so that client code may
* check for issues that are outside the scope of this project and can report
* errors.
*
* @param message The error to report.
*
* @returns this
*/
fail(message: string): this {
const err = this.makeError(message);
const handler = this.errorHandler;
if (handler === undefined) {
throw err;
}
else {
handler(err);
}
return this;
}
/**
* Write a XML data to the parser.
*
* @param chunk The XML data to write.
*
* @returns this
*/
// We do need object for the type here. Yes, it often causes problems
// but not in this case.
write(chunk: string | object | null): this {
if (this.closed) {
return this.fail("cannot write after close; assign an onready handler.");
}
let end = false;
if (chunk === null) {
// We cannot return immediately because carriedFromPrevious may need
// processing.
end = true;
chunk = "";
}
else if (typeof chunk === "object") {
chunk = chunk.toString();
}
// We checked if performing a pre-decomposition of the string into an array
// of single complete characters (``Array.from(chunk)``) would be faster
// than the current repeated calls to ``charCodeAt``. As of August 2018, it
// isn't. (There may be Node-specific code that would perform faster than
// ``Array.from`` but don't want to be dependent on Node.)
if (this.carriedFromPrevious !== undefined) {
// The previous chunk had char we must carry over.
chunk = `${this.carriedFromPrevious}${chunk}`;
this.carriedFromPrevious = undefined;
}
let limit = chunk.length;
const lastCode = chunk.charCodeAt(limit - 1);
if (!end &&
// A trailing CR or surrogate must be carried over to the next
// chunk.
(lastCode === CR || (lastCode >= 0xD800 && lastCode <= 0xDBFF))) {
// The chunk ends with a character that must be carried over. We cannot
// know how to handle it until we get the next chunk or the end of the
// stream. So save it for later.
this.carriedFromPrevious = chunk[limit - 1];
limit--;
chunk = chunk.slice(0, limit);
}
const { stateTable } = this;
this.chunk = chunk;
this.i = 0;
while (this.i < limit) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-argument
stateTable[this.state].call(this as any);
}
this.chunkPosition += limit;
return end ? this.end() : this;
}
/**
* Close the current stream. Perform final well-formedness checks and reset
* the parser tstate.
*
* @returns this
*/
close(): this {
return this.write(null);
}
/**
* Get a single code point out of the current chunk. This updates the current
* position if we do position tracking.
*
* This is the algorithm to use for XML 1.0.
*
* @returns The character read.
*/
private getCode10(): number {
const { chunk, i } = this;
this.prevI = i;
// Yes, we do this instead of doing this.i++. Doing it this way, we do not
// read this.i again, which is a bit faster.
this.i = i + 1;
if (i >= chunk.length) {
return EOC;
}
// Using charCodeAt and handling the surrogates ourselves is faster
// than using codePointAt.
const code = chunk.charCodeAt(i);
this.column++;
if (code < 0xD800) {
if (code >= SPACE || code === TAB) {
return code;
}
switch (code) {
case NL:
this.line++;
this.column = 0;
this.positionAtNewLine = this.position;
return NL;
case CR:
// We may get NaN if we read past the end of the chunk, which is fine.
if (chunk.charCodeAt(i + 1) === NL) {
// A \r\n sequence is converted to \n so we have to skip over the
// next character. We already know it has a size of 1 so ++ is fine
// here.
this.i = i + 2;
}
// Otherwise, a \r is just converted to \n, so we don't have to skip
// ahead.
// In either case, \r becomes \n.
this.line++;
this.column = 0;
this.positionAtNewLine = this.position;
return NL_LIKE;
default:
// If we get here, then code < SPACE and it is not NL CR or TAB.
this.fail("disallowed character.");
return code;
}
}
if (code > 0xDBFF) {
// This is a specialized version of isChar10 that takes into account
// that in this context code > 0xDBFF and code <= 0xFFFF. So it does not
// test cases that don't need testing.
if (!(code >= 0xE000 && code <= 0xFFFD)) {
this.fail("disallowed character.");
}
return code;
}
const final = 0x10000 + ((code - 0xD800) * 0x400) +
(chunk.charCodeAt(i + 1) - 0xDC00);
this.i = i + 2;
// This is a specialized version of isChar10 that takes into account that in
// this context necessarily final >= 0x10000.
if (final > 0x10FFFF) {
this.fail("disallowed character.");
}
return final;
}
/**
* Get a single code point out of the current chunk. This updates the current
* position if we do position tracking.
*
* This is the algorithm to use for XML 1.1.
*
* @returns {number} The character read.
*/
private getCode11(): number {
const { chunk, i } = this;
this.prevI = i;
// Yes, we do this instead of doing this.i++. Doing it this way, we do not
// read this.i again, which is a bit faster.
this.i = i + 1;
if (i >= chunk.length) {
return EOC;
}
// Using charCodeAt and handling the surrogates ourselves is faster
// than using codePointAt.
const code = chunk.charCodeAt(i);
this.column++;
if (code < 0xD800) {
if ((code > 0x1F && code < 0x7F) || (code > 0x9F && code !== LS) ||
code === TAB) {
return code;
}
switch (code) {
case NL: // 0xA
this.line++;
this.column = 0;
this.positionAtNewLine = this.position;
return NL;
case CR: { // 0xD
// We may get NaN if we read past the end of the chunk, which is
// fine.
const next = chunk.charCodeAt(i + 1);
if (next === NL || next === NEL) {
// A CR NL or CR NEL sequence is converted to NL so we have to skip
// over the next character. We already know it has a size of 1.
this.i = i + 2;
}
// Otherwise, a CR is just converted to NL, no skip.
}
/* yes, fall through */
case NEL: // 0x85
case LS: // Ox2028
this.line++;
this.column = 0;
this.positionAtNewLine = this.position;
return NL_LIKE;
default:
this.fail("disallowed character.");
return code;
}
}
if (code > 0xDBFF) {
// This is a specialized version of isCharAndNotRestricted that takes into
// account that in this context code > 0xDBFF and code <= 0xFFFF. So it
// does not test cases that don't need testing.
if (!(code >= 0xE000 && code <= 0xFFFD)) {
this.fail("disallowed character.");
}
return code;
}
const final = 0x10000 + ((code - 0xD800) * 0x400) +
(chunk.charCodeAt(i + 1) - 0xDC00);
this.i = i + 2;
// This is a specialized version of isCharAndNotRestricted that takes into
// account that in this context necessarily final >= 0x10000.
if (final > 0x10FFFF) {
this.fail("disallowed character.");
}
return final;
}
/**
* Like ``getCode`` but with the return value normalized so that ``NL`` is
* returned for ``NL_LIKE``.
*/
private getCodeNorm(): number {
const c = this.getCode();
return c === NL_LIKE ? NL : c;
}
private unget(): void {
this.i = this.prevI;
this.column--;
}
/**
* Capture characters into a buffer until encountering one of a set of
* characters.
*
* @param chars An array of codepoints. Encountering a character in the array
* ends the capture. (``chars`` may safely contain ``NL``.)
*
* @return The character code that made the capture end, or ``EOC`` if we hit
* the end of the chunk. The return value cannot be NL_LIKE: NL is returned
* instead.
*/
private captureTo(chars: number[]): number {
let { i: start } = this;
const { chunk } = this;
// eslint-disable-next-line no-constant-condition
while (true) {
const c = this.getCode();
const isNLLike = c === NL_LIKE;
const final = isNLLike ? NL : c;
if (final === EOC || chars.includes(final)) {
this.text += chunk.slice(start, this.prevI);
return final;
}
if (isNLLike) {
this.text += `${chunk.slice(start, this.prevI)}\n`;
start = this.i;
}
}
}
/**
* Capture characters into a buffer until encountering a character.
*
* @param char The codepoint that ends the capture. **NOTE ``char`` MAY NOT
* CONTAIN ``NL``.** Passing ``NL`` will result in buggy behavior.
*
* @return ``true`` if we ran into the character. Otherwise, we ran into the
* end of the current chunk.
*/
private captureToChar(char: number): boolean {
let { i: start } = this;
const { chunk } = this;
// eslint-disable-next-line no-constant-condition
while (true) {
let c = this.getCode();
switch (c) {
case NL_LIKE:
this.text += `${chunk.slice(start, this.prevI)}\n`;
start = this.i;
c = NL;
break;
case EOC:
this.text += chunk.slice(start);
return false;
default:
}
if (c === char) {
this.text += chunk.slice(start, this.prevI);
return true;
}
}
}
/**
* Capture characters that satisfy ``isNameChar`` into the ``name`` field of
* this parser.
*
* @return The character code that made the test fail, or ``EOC`` if we hit
* the end of the chunk. The return value cannot be NL_LIKE: NL is returned
* instead.
*/
private captureNameChars(): number {
const { chunk, i: start } = this;
// eslint-disable-next-line no-constant-condition
while (true) {
const c = this.getCode();
if (c === EOC) {
this.name += chunk.slice(start);
return EOC;
}
// NL is not a name char so we don't have to test specifically for it.
if (!isNameChar(c)) {
this.name += chunk.slice(start, this.prevI);
return c === NL_LIKE ? NL : c;
}
}
}
/**
* Skip white spaces.
*
* @return The character that ended the skip, or ``EOC`` if we hit
* the end of the chunk. The return value cannot be NL_LIKE: NL is returned
* instead.
*/
private skipSpaces(): number {
// eslint-disable-next-line no-constant-condition
while (true) {
const c = this.getCodeNorm();
if (c === EOC || !isS(c)) {
return c;
}
}
}
private setXMLVersion(version: string): void {
this.currentXMLVersion = version;
/* eslint-disable @typescript-eslint/unbound-method */
if (version === "1.0") {
this.isChar = isChar10;
this.getCode = this.getCode10;
}
else {
this.isChar = isChar11;
this.getCode = this.getCode11;
}
/* eslint-enable @typescript-eslint/unbound-method */
}
// STATE ENGINE METHODS
// This needs to be a state separate from S_BEGIN_WHITESPACE because we want
// to be sure never to come back to this state later.
private sBegin(): void {
// We are essentially peeking at the first character of the chunk. Since
// S_BEGIN can be in effect only when we start working on the first chunk,
// the index at which we must look is necessarily 0. Note also that the
// following test does not depend on decoding surrogates.
// If the initial character is 0xFEFF, ignore it.
if (this.chunk.charCodeAt(0) === 0xFEFF) {
this.i++;
this.column++;
}
this.state = S_BEGIN_WHITESPACE;
}
private sBeginWhitespace(): void {
// We need to know whether we've encountered spaces or not because as soon
// as we run into a space, an XML declaration is no longer possible. Rather
// than slow down skipSpaces even in places where we don't care whether it
// skipped anything or not, we check whether prevI is equal to the value of
// i from before we skip spaces.
const iBefore = this.i;
const c = this.skipSpaces();
if (this.prevI !== iBefore) {
this.xmlDeclPossible = false;
}
switch (c) {
case LESS:
this.state = S_OPEN_WAKA;
// We could naively call closeText but in this state, it is not normal
// to have text be filled with any data.
if (this.text.length !== 0) {
throw new Error("no-empty text at start");
}
break;
case EOC:
break;
default:
this.unget();
this.state = S_TEXT;
this.xmlDeclPossible = false;
}
}
private sDoctype(): void {
const c = this.captureTo(DOCTYPE_TERMINATOR);
switch (c) {
case GREATER: {
this.doctypeHandler?.(this.text);
this.text = "";
this.state = S_TEXT;
this.doctype = true; // just remember that we saw it.
break;
}
case EOC:
break;
default:
this.text += String.fromCodePoint(c);
if (c === OPEN_BRACKET) {
this.state = S_DTD;
}
else if (isQuote(c)) {
this.state = S_DOCTYPE_QUOTE;
this.q = c;
}
}
}
private sDoctypeQuote(): void {
const q = this.q!;
if (this.captureToChar(q)) {
this.text += String.fromCodePoint(q);
this.q = null;
this.state = S_DOCTYPE;
}
}
private sDTD(): void {
const c = this.captureTo(DTD_TERMINATOR);
if (c === EOC) {
return;
}
this.text += String.fromCodePoint(c);
if (c === CLOSE_BRACKET) {
this.state = S_DOCTYPE;
}
else if (c === LESS) {
this.state = S_DTD_OPEN_WAKA;
}
else if (isQuote(c)) {
this.state = S_DTD_QUOTED;
this.q = c;
}
}
private sDTDQuoted(): void {
const q = this.q!;
if (this.captureToChar(q)) {
this.text += String.fromCodePoint(q);
this.state = S_DTD;
this.q = null;
}
}
private sDTDOpenWaka(): void {
const c = this.getCodeNorm();
this.text += String.fromCodePoint(c);
switch (c) {
case BANG:
this.state = S_DTD_OPEN_WAKA_BANG;
this.openWakaBang = "";
break;
case QUESTION:
this.state = S_DTD_PI;
break;
default:
this.state = S_DTD;
}
}
private sDTDOpenWakaBang(): void {
const char = String.fromCodePoint(this.getCodeNorm());
const owb = this.openWakaBang += char;
this.text += char;
if (owb !== "-") {
this.state = owb === "--" ? S_DTD_COMMENT : S_DTD;
this.openWakaBang = "";
}
}
private sDTDComment(): void {
if (this.captureToChar(MINUS)) {
this.text += "-";
this.state = S_DTD_COMMENT_ENDING;
}
}
private sDTDCommentEnding(): void {
const c = this.getCodeNorm();
this.text += String.fromCodePoint(c);
this.state = c === MINUS ? S_DTD_COMMENT_ENDED : S_DTD_COMMENT;
}
private sDTDCommentEnded(): void {
const c = this.getCodeNorm();
this.text += String.fromCodePoint(c);
if (c === GREATER) {
this.state = S_DTD;
}
else {
this.fail("malformed comment.");
// <!-- blah -- bloo --> will be recorded as
// a comment of " blah -- bloo "
this.state = S_DTD_COMMENT;
}
}
private sDTDPI(): void {
if (this.captureToChar(QUESTION)) {
this.text += "?";
this.state = S_DTD_PI_ENDING;
}
}
private sDTDPIEnding(): void {
const c = this.getCodeNorm();
this.text += String.fromCodePoint(c);
if (c === GREATER) {
this.state = S_DTD;
}
}
private sText(): void {
//
// We did try a version of saxes where the S_TEXT state was split in two
// states: one for text inside the root element, and one for text
// outside. This was avoiding having to test this.tags.length to decide
// what implementation to actually use.
//
// Peformance testing on gigabyte-size files did not show any advantage to
// using the two states solution instead of the current one. Conversely, it
// made the code a bit more complicated elsewhere. For instance, a comment
// can appear before the root element so when a comment ended it was
// necessary to determine whether to return to the S_TEXT state or to the
// new text-outside-root state.
//
if (this.tags.length !== 0) {
this.handleTextInRoot();
}
else {
this.handleTextOutsideRoot();
}
}
private sEntity(): void {
// This is essentially a specialized version of captureToChar(SEMICOLON...)
let { i: start } = this;
const { chunk } = this;
// eslint-disable-next-line no-labels, no-restricted-syntax
loop:
// eslint-disable-next-line no-constant-condition
while (true) {
switch (this.getCode()) {
case NL_LIKE:
this.entity += `${chunk.slice(start, this.prevI)}\n`;
start = this.i;
break;
case SEMICOLON: {
const { entityReturnState } = this;
const entity = this.entity + chunk.slice(start, this.prevI);
this.state = entityReturnState!;
let parsed: string;
if (entity === "") {
this.fail("empty entity name.");
parsed = "&;";
}
else {
parsed = this.parseEntity(entity);
this.entity = "";
}
if (entityReturnState !== S_TEXT || this.textHandler !== undefined) {
this.text += parsed;
}
// eslint-disable-next-line no-labels
break loop;
}
case EOC:
this.entity += chunk.slice(start);
// eslint-disable-next-line no-labels
break loop;
default:
}
}
}
private sOpenWaka(): void {
// Reminder: a state handler is called with at least one character
// available in the current chunk. So the first call to get code inside of
// a state handler cannot return ``EOC``. That's why we don't test
// for it.
const c = this.getCode();
// either a /, ?, !, or text is coming next.
if (isNameStartChar(c)) {
this.state = S_OPEN_TAG;
this.unget();
this.xmlDeclPossible = false;
}
else {
switch (c) {
case FORWARD_SLASH:
this.state = S_CLOSE_TAG;
this.xmlDeclPossible = false;
break;
case BANG:
this.state = S_OPEN_WAKA_BANG;
this.openWakaBang = "";
this.xmlDeclPossible = false;
break;
case QUESTION:
this.state = S_PI_FIRST_CHAR;
break;
default:
this.fail("disallowed character in tag name");
this.state = S_TEXT;
this.xmlDeclPossible = false;
}
}
}
private sOpenWakaBang(): void {
this.openWakaBang += String.fromCodePoint(this.getCodeNorm());
switch (this.openWakaBang) {
case "[CDATA[":
if (!this.sawRoot && !this.reportedTextBeforeRoot) {
this.fail("text data outside of root node.");
this.reportedTextBeforeRoot = true;
}
if (this.closedRoot && !this.reportedTextAfterRoot) {
this.fail("text data outside of root node.");
this.reportedTextAfterRoot = true;
}
this.state = S_CDATA;
this.openWakaBang = "";
break;
case "--":
this.state = S_COMMENT;
this.openWakaBang = "";
break;
case "DOCTYPE":
this.state = S_DOCTYPE;
if (this.doctype || this.sawRoot) {
this.fail("inappropriately located doctype declaration.");
}
this.openWakaBang = "";
break;
default:
// 7 happens to be the maximum length of the string that can possibly
// match one of the cases above.
if (this.openWakaBang.length >= 7) {
this.fail("incorrect syntax.");
}
}
}
private sComment(): void {
if (this.captureToChar(MINUS)) {
this.state = S_COMMENT_ENDING;
}
}
private sCommentEnding(): void {
const c = this.getCodeNorm();
if (c === MINUS) {
this.state = S_COMMENT_ENDED;
this.commentHandler?.(this.text);
this.text = "";
}
else {
this.text += `-${String.fromCodePoint(c)}`;
this.state = S_COMMENT;
}
}
private sCommentEnded(): void {
const c = this.getCodeNorm();
if (c !== GREATER) {
this.fail("malformed comment.");
// <!-- blah -- bloo --> will be recorded as
// a comment of " blah -- bloo "
this.text += `--${String.fromCodePoint(c)}`;
this.state = S_COMMENT;
}
else {
this.state = S_TEXT;
}
}
private sCData(): void {
if (this.captureToChar(CLOSE_BRACKET)) {
this.state = S_CDATA_ENDING;
}
}
private sCDataEnding(): void {
const c = this.getCodeNorm();
if (c === CLOSE_BRACKET) {
this.state = S_CDATA_ENDING_2;
}
else {
this.text += `]${String.fromCodePoint(c)}`;
this.state = S_CDATA;
}
}
private sCDataEnding2(): void {
const c = this.getCodeNorm();
switch (c) {
case GREATER: {
this.cdataHandler?.(this.text);
this.text = "";
this.state = S_TEXT;
break;
}
case CLOSE_BRACKET:
this.text += "]";
break;
default:
this.text += `]]${String.fromCodePoint(c)}`;
this.state = S_CDATA;
}
}
// We need this separate state to check the first character fo the pi target
// with this.nameStartCheck which allows less characters than this.nameCheck.
private sPIFirstChar(): void {
const c = this.getCodeNorm();
// This is first because in the case where the file is well-formed this is
// the branch taken. We optimize for well-formedness.
if (this.nameStartCheck(c)) {
this.piTarget += String.fromCodePoint(c);
this.state = S_PI_REST;
}
else if (c === QUESTION || isS(c)) {
this.fail("processing instruction without a target.");
this.state = c === QUESTION ? S_PI_ENDING : S_PI_BODY;
}
else {
this.fail("disallowed character in processing instruction name.");
this.piTarget += String.fromCodePoint(c);
this.state = S_PI_REST;
}
}
private sPIRest(): void {
// Capture characters into a piTarget while ``this.nameCheck`` run on the
// character read returns true.
const { chunk, i: start } = this;
// eslint-disable-next-line no-constant-condition
while (true) {
const c = this.getCodeNorm();
if (c === EOC) {
this.piTarget += chunk.slice(start);
return;
}
// NL cannot satisfy this.nameCheck so we don't have to test specifically
// for it.
if (!this.nameCheck(c)) {
this.piTarget += chunk.slice(start, this.prevI);
const isQuestion = c === QUESTION;
if (isQuestion || isS(c)) {
if (this.piTarget === "xml") {
if (!this.xmlDeclPossible) {
this.fail(
"an XML declaration must be at the start of the document.");
}
this.state = isQuestion ? S_XML_DECL_ENDING : S_XML_DECL_NAME_START;
}
else {
this.state = isQuestion ? S_PI_ENDING : S_PI_BODY;
}
}
else {
this.fail("disallowed character in processing instruction name.");
this.piTarget += String.fromCodePoint(c);
}
break;
}
}
}
private sPIBody(): void {
if (this.text.length === 0) {
const c = this.getCodeNorm();
if (c === QUESTION) {
this.state = S_PI_ENDING;
}
else if (!isS(c)) {
this.text = String.fromCodePoint(c);
}
}
// The question mark character is not valid inside any of the XML
// declaration name/value pairs.
else if (this.captureToChar(QUESTION)) {
this.state = S_PI_ENDING;
}
}
private sPIEnding(): void {
const c = this.getCodeNorm();
if (c === GREATER) {
const { piTarget } = this;
if (piTarget.toLowerCase() === "xml") {
this.fail(
"the XML declaration must appear at the start of the document.");
}
this.piHandler?.({
target: piTarget,
body: this.text,
});
this.piTarget = this.text = "";
this.state = S_TEXT;
}
else if (c === QUESTION) {
// We ran into ?? as part of a processing instruction. We initially took
// the first ? as a sign that the PI was ending, but it is not. So we have
// to add it to the body but we take the new ? as a sign that the PI is
// ending.
this.text += "?";
}
else {
this.text += `?${String.fromCodePoint(c)}`;
this.state = S_PI_BODY;
}
this.xmlDeclPossible = false;
}
private sXMLDeclNameStart(): void {
const c = this.skipSpaces();
// The question mark character is not valid inside any of the XML
// declaration name/value pairs.
if (c === QUESTION) {
// It is valid to go to S_XML_DECL_ENDING from this state.
this.state = S_XML_DECL_ENDING;
return;
}
if (c !== EOC) {
this.state = S_XML_DECL_NAME;
this.name = String.fromCodePoint(c);
}
}
private sXMLDeclName(): void {
const c = this.captureTo(XML_DECL_NAME_TERMINATOR);
// The question mark character is not valid inside any of the XML
// declaration name/value pairs.
if (c === QUESTION) {
this.state = S_XML_DECL_ENDING;
this.name += this.text;
this.text = "";
this.fail("XML declaration is incomplete.");
return;
}
if (!(isS(c) || c === EQUAL)) {
return;
}
this.name += this.text;
this.text = "";
if (!this.xmlDeclExpects.includes(this.name)) {
switch (this.name.length) {
case 0:
this.fail("did not expect any more name/value pairs.");
break;
case 1:
this.fail(`expected the name ${this.xmlDeclExpects[0]}.`);
break;
default:
this.fail(`expected one of ${this.xmlDeclExpects.join(", ")}`);
}
}
this.state = c === EQUAL ? S_XML_DECL_VALUE_START : S_XML_DECL_EQ;
}
private sXMLDeclEq(): void {
const c = this.getCodeNorm();
// The question mark character is not valid inside any of the XML
// declaration name/value pairs.
if (c === QUESTION) {
this.state = S_XML_DECL_ENDING;
this.fail("XML declaration is incomplete.");
return;
}
if (isS(c)) {
return;
}
if (c !== EQUAL) {
this.fail("value required.");
}
this.state = S_XML_DECL_VALUE_START;
}
private sXMLDeclValueStart(): void {
const c = this.getCodeNorm();
// The question mark character is not valid inside any of the XML
// declaration name/value pairs.
if (c === QUESTION) {
this.state = S_XML_DECL_ENDING;
this.fail("XML declaration is incomplete.");
return;
}
if (isS(c)) {
return;
}
if (!isQuote(c)) {
this.fail("value must be quoted.");
this.q = SPACE;
}
else {
this.q = c;
}
this.state = S_XML_DECL_VALUE;
}
private sXMLDeclValue(): void {
const c = this.captureTo([this.q!, QUESTION]);
// The question mark character is not valid inside any of the XML
// declaration name/value pairs.
if (c === QUESTION) {
this.state = S_XML_DECL_ENDING;
this.text = "";
this.fail("XML declaration is incomplete.");
return;
}
if (c === EOC) {
return;
}
const value = this.text;
this.text = "";
switch (this.name) {
case "version": {
this.xmlDeclExpects = ["encoding", "standalone"];
const version = value;
this.xmlDecl.version = version;
// This is the test specified by XML 1.0 but it is fine for XML 1.1.
if (!/^1\.[0-9]+$/.test(version)) {
this.fail("version number must match /^1\\.[0-9]+$/.");
}
// When forceXMLVersion is set, the XML declaration is ignored.
else if (!(this.opt.forceXMLVersion as boolean)) {
this.setXMLVersion(version);
}
break;
}
case "encoding":
if (!/^[A-Za-z][A-Za-z0-9._-]*$/.test(value)) {
this.fail("encoding value must match \
/^[A-Za-z0-9][A-Za-z0-9._-]*$/.");
}
this.xmlDeclExpects = ["standalone"];
this.xmlDecl.encoding = value;
break;
case "standalone":
if (value !== "yes" && value !== "no") {
this.fail("standalone value must match \"yes\" or \"no\".");
}
this.xmlDeclExpects = [];
this.xmlDecl.standalone = value;
break;
default:
// We don't need to raise an error here since we've already raised one
// when checking what name was expected.
}
this.name = "";
this.state = S_XML_DECL_SEPARATOR;
}
private sXMLDeclSeparator(): void {
const c = this.getCodeNorm();
// The question mark character is not valid inside any of the XML
// declaration name/value pairs.
if (c === QUESTION) {
// It is valid to go to S_XML_DECL_ENDING from this state.
this.state = S_XML_DECL_ENDING;
return;
}
if (!isS(c)) {
this.fail("whitespace required.");
this.unget();
}
this.state = S_XML_DECL_NAME_START;
}
private sXMLDeclEnding(): void {
const c = this.getCodeNorm();
if (c === GREATER) {
if (this.piTarget !== "xml") {
this.fail("processing instructions are not allowed before root.");
}
else if (this.name !== "version" &&
this.xmlDeclExpects.includes("version")) {
this.fail("XML declaration must contain a version.");
}
this.xmldeclHandler?.(this.xmlDecl);
this.name = "";
this.piTarget = this.text = "";
this.state = S_TEXT;
}
else {
// We got here because the previous character was a ?, but the question
// mark character is not valid inside any of the XML declaration
// name/value pairs.
this.fail(
"The character ? is disallowed anywhere in XML declarations.");
}
this.xmlDeclPossible = false;
}
private sOpenTag(): void {
const c = this.captureNameChars();
if (c === EOC) {
return;
}
const tag: SaxesTagIncomplete = this.tag = {
name: this.name,
attributes: Object.create(null) as Record<string, string>,
};
this.name = "";
if (this.xmlnsOpt) {
this.topNS = tag.ns = Object.create(null) as Record<string, string>;
}
this.openTagStartHandler?.(tag as StartTagForOptions<O>);
this.sawRoot = true;
if (!this.fragmentOpt && this.closedRoot) {
this.fail("documents may contain only one root.");
}
switch (c) {
case GREATER:
this.openTag();
break;
case FORWARD_SLASH:
this.state = S_OPEN_TAG_SLASH;
break;
default:
if (!isS(c)) {
this.fail("disallowed character in tag name.");
}
this.state = S_ATTRIB;
}
}
private sOpenTagSlash(): void {
if (this.getCode() === GREATER) {
this.openSelfClosingTag();
}
else {
this.fail("forward-slash in opening tag not followed by >.");
this.state = S_ATTRIB;
}
}
private sAttrib(): void {
const c = this.skipSpaces();
if (c === EOC) {
return;
}
if (isNameStartChar(c)) {
this.unget();
this.state = S_ATTRIB_NAME;
}
else if (c === GREATER) {
this.openTag();
}
else if (c === FORWARD_SLASH) {
this.state = S_OPEN_TAG_SLASH;
}
else {
this.fail("disallowed character in attribute name.");
}
}
private sAttribName(): void {
const c = this.captureNameChars();
if (c === EQUAL) {
this.state = S_ATTRIB_VALUE;
}
else if (isS(c)) {
this.state = S_ATTRIB_NAME_SAW_WHITE;
}
else if (c === GREATER) {
this.fail("attribute without value.");
this.pushAttrib(this.name, this.name);
this.name = this.text = "";
this.openTag();
}
else if (c !== EOC) {
this.fail("disallowed character in attribute name.");
}
}
private sAttribNameSawWhite(): void {
const c = this.skipSpaces();
switch (c) {
case EOC:
return;
case EQUAL:
this.state = S_ATTRIB_VALUE;
break;
default:
this.fail("attribute without value.");
// Should we do this???
// this.tag.attributes[this.name] = "";
this.text = "";
this.name = "";
if (c === GREATER) {
this.openTag();
}
else if (isNameStartChar(c)) {
this.unget();
this.state = S_ATTRIB_NAME;
}
else {
this.fail("disallowed character in attribute name.");
this.state = S_ATTRIB;
}
}
}
private sAttribValue(): void {
const c = this.getCodeNorm();
if (isQuote(c)) {
this.q = c;
this.state = S_ATTRIB_VALUE_QUOTED;
}
else if (!isS(c)) {
this.fail("unquoted attribute value.");
this.state = S_ATTRIB_VALUE_UNQUOTED;
this.unget();
}
}
private sAttribValueQuoted(): void {
// We deliberately do not use captureTo here. The specialized code we use
// here is faster than using captureTo.
const { q, chunk } = this;
let { i: start } = this;
// eslint-disable-next-line no-constant-condition
while (true) {
switch (this.getCode()) {
case q:
this.pushAttrib(this.name,
this.text + chunk.slice(start, this.prevI));
this.name = this.text = "";
this.q = null;
this.state = S_ATTRIB_VALUE_CLOSED;
return;
case AMP:
this.text += chunk.slice(start, this.prevI);
this.state = S_ENTITY;
this.entityReturnState = S_ATTRIB_VALUE_QUOTED;
return;
case NL:
case NL_LIKE:
case TAB:
this.text += `${chunk.slice(start, this.prevI)} `;
start = this.i;
break;
case LESS:
this.text += chunk.slice(start, this.prevI);
this.fail("disallowed character.");
return;
case EOC:
this.text += chunk.slice(start);
return;
default:
}
}
}
private sAttribValueClosed(): void {
const c = this.getCodeNorm();
if (isS(c)) {
this.state = S_ATTRIB;
}
else if (c === GREATER) {
this.openTag();
}
else if (c === FORWARD_SLASH) {
this.state = S_OPEN_TAG_SLASH;
}
else if (isNameStartChar(c)) {
this.fail("no whitespace between attributes.");
this.unget();
this.state = S_ATTRIB_NAME;
}
else {
this.fail("disallowed character in attribute name.");
}
}
private sAttribValueUnquoted(): void {
// We don't do anything regarding EOL or space handling for unquoted
// attributes. We already have failed by the time we get here, and the
// contract that saxes upholds states that upon failure, it is not safe to
// rely on the data passed to event handlers (other than
// ``onerror``). Passing "bad" data is not a problem.
const c = this.captureTo(ATTRIB_VALUE_UNQUOTED_TERMINATOR);
switch (c) {
case AMP:
this.state = S_ENTITY;
this.entityReturnState = S_ATTRIB_VALUE_UNQUOTED;
break;
case LESS:
this.fail("disallowed character.");
break;
case EOC:
break;
default:
if (this.text.includes("]]>")) {
this.fail("the string \"]]>\" is disallowed in char data.");
}
this.pushAttrib(this.name, this.text);
this.name = this.text = "";
if (c === GREATER) {
this.openTag();
}
else {
this.state = S_ATTRIB;
}
}
}
private sCloseTag(): void {
const c = this.captureNameChars();
if (c === GREATER) {
this.closeTag();
}
else if (isS(c)) {
this.state = S_CLOSE_TAG_SAW_WHITE;
}
else if (c !== EOC) {
this.fail("disallowed character in closing tag.");
}
}
private sCloseTagSawWhite(): void {
switch (this.skipSpaces()) {
case GREATER:
this.closeTag();
break;
case EOC:
break;
default:
this.fail("disallowed character in closing tag.");
}
}
// END OF STATE ENGINE METHODS
private handleTextInRoot(): void {
// This is essentially a specialized version of captureTo which is optimized
// for performing the ]]> check. A previous version of this code, checked
// ``this.text`` for the presence of ]]>. It simplified the code but was
// very costly when character data contained a lot of entities to be parsed.
//
// Since we are using a specialized loop, we also keep track of the presence
// of ]]> in text data. The sequence ]]> is forbidden to appear as-is.
//
let { i: start, forbiddenState } = this;
const { chunk, textHandler: handler } = this;
// eslint-disable-next-line no-labels, no-restricted-syntax
scanLoop:
// eslint-disable-next-line no-constant-condition
while (true) {
switch (this.getCode()) {
case LESS: {
this.state = S_OPEN_WAKA;
if (handler !== undefined) {
const { text } = this;
const slice = chunk.slice(start, this.prevI);
if (text.length !== 0) {
handler(text + slice);
this.text = "";
}
else if (slice.length !== 0) {
handler(slice);
}
}
forbiddenState = FORBIDDEN_START;
// eslint-disable-next-line no-labels
break scanLoop;
}
case AMP:
this.state = S_ENTITY;
this.entityReturnState = S_TEXT;
if (handler !== undefined) {
this.text += chunk.slice(start, this.prevI);
}
forbiddenState = FORBIDDEN_START;
// eslint-disable-next-line no-labels
break scanLoop;
case CLOSE_BRACKET:
switch (forbiddenState) {
case FORBIDDEN_START:
forbiddenState = FORBIDDEN_BRACKET;
break;
case FORBIDDEN_BRACKET:
forbiddenState = FORBIDDEN_BRACKET_BRACKET;
break;
case FORBIDDEN_BRACKET_BRACKET:
break;
default:
throw new Error("impossible state");
}
break;
case GREATER:
if (forbiddenState === FORBIDDEN_BRACKET_BRACKET) {
this.fail("the string \"]]>\" is disallowed in char data.");
}
forbiddenState = FORBIDDEN_START;
break;
case NL_LIKE:
if (handler !== undefined) {
this.text += `${chunk.slice(start, this.prevI)}\n`;
}
start = this.i;
forbiddenState = FORBIDDEN_START;
break;
case EOC:
if (handler !== undefined) {
this.text += chunk.slice(start);
}
// eslint-disable-next-line no-labels
break scanLoop;
default:
forbiddenState = FORBIDDEN_START;
}
}
this.forbiddenState = forbiddenState;
}
private handleTextOutsideRoot(): void {
// This is essentially a specialized version of captureTo which is optimized
// for a specialized task. We keep track of the presence of non-space
// characters in the text since these are errors when appearing outside the
// document root element.
let { i: start } = this;
const { chunk, textHandler: handler } = this;
let nonSpace = false;
// eslint-disable-next-line no-labels, no-restricted-syntax
outRootLoop:
// eslint-disable-next-line no-constant-condition
while (true) {
const code = this.getCode();
switch (code) {
case LESS: {
this.state = S_OPEN_WAKA;
if (handler !== undefined) {
const { text } = this;
const slice = chunk.slice(start, this.prevI);
if (text.length !== 0) {
handler(text + slice);
this.text = "";
}
else if (slice.length !== 0) {
handler(slice);
}
}
// eslint-disable-next-line no-labels
break outRootLoop;
}
case AMP:
this.state = S_ENTITY;
this.entityReturnState = S_TEXT;
if (handler !== undefined) {
this.text += chunk.slice(start, this.prevI);
}
nonSpace = true;
// eslint-disable-next-line no-labels
break outRootLoop;
case NL_LIKE:
if (handler !== undefined) {
this.text += `${chunk.slice(start, this.prevI)}\n`;
}
start = this.i;
break;
case EOC:
if (handler !== undefined) {
this.text += chunk.slice(start);
}
// eslint-disable-next-line no-labels
break outRootLoop;
default:
if (!isS(code)) {
nonSpace = true;
}
}
}
if (!nonSpace) {
return;
}
// We use the reportedTextBeforeRoot and reportedTextAfterRoot flags
// to avoid reporting errors for every single character that is out of
// place.
if (!this.sawRoot && !this.reportedTextBeforeRoot) {
this.fail("text data outside of root node.");
this.reportedTextBeforeRoot = true;
}
if (this.closedRoot && !this.reportedTextAfterRoot) {
this.fail("text data outside of root node.");
this.reportedTextAfterRoot = true;
}
}
private pushAttribNS(name: string, value: string): void {
const { prefix, local } = this.qname(name);
const attr = { name, prefix, local, value };
this.attribList.push(attr);
this.attributeHandler?.(attr as AttributeEventForOptions<O>);
if (prefix === "xmlns") {
const trimmed = value.trim();
if (this.currentXMLVersion === "1.0" && trimmed === "") {
this.fail("invalid attempt to undefine prefix in XML 1.0");
}
this.topNS![local] = trimmed;
nsPairCheck(this, local, trimmed);
}
else if (name === "xmlns") {
const trimmed = value.trim();
this.topNS![""] = trimmed;
nsPairCheck(this, "", trimmed);
}
}
private pushAttribPlain(name: string, value: string): void {
const attr = { name, value };
this.attribList.push(attr);
this.attributeHandler?.(attr as AttributeEventForOptions<O>);
}
/**
* End parsing. This performs final well-formedness checks and resets the
* parser to a clean state.
*
* @returns this
*/
private end(): this {
if (!this.sawRoot) {
this.fail("document must contain a root element.");
}
const { tags } = this;
while (tags.length > 0) {
const tag = tags.pop()!;
this.fail(`unclosed tag: ${tag.name}`);
}
if ((this.state !== S_BEGIN) && (this.state !== S_TEXT)) {
this.fail("unexpected end.");
}
const { text } = this;
if (text.length !== 0) {
this.textHandler?.(text);
this.text = "";
}
this._closed = true;
this.endHandler?.();
this._init();
return this;
}
/**
* Resolve a namespace prefix.
*
* @param prefix The prefix to resolve.
*
* @returns The namespace URI or ``undefined`` if the prefix is not defined.
*/
resolve(prefix: string): string | undefined {
let uri = this.topNS![prefix];
if (uri !== undefined) {
return uri;
}
const { tags } = this;
for (let index = tags.length - 1; index >= 0; index--) {
uri = tags[index]!.ns![prefix];
if (uri !== undefined) {
return uri;
}
}
uri = this.ns[prefix];
if (uri !== undefined) {
return uri;
}
return this.opt.resolvePrefix?.(prefix);
}
/**
* Parse a qname into its prefix and local name parts.
*
* @param name The name to parse
*
* @returns
*/
private qname(name: string): { prefix: string; local: string } {
// This is faster than using name.split(":").
const colon = name.indexOf(":");
if (colon === -1) {
return { prefix: "", local: name };
}
const local = name.slice(colon + 1);
const prefix = name.slice(0, colon);
if (prefix === "" || local === "" || local.includes(":")) {
this.fail(`malformed name: ${name}.`);
}
return { prefix, local };
}
private processAttribsNS(): void {
const { attribList } = this;
const tag = this.tag!;
{
// add namespace info to tag
const { prefix, local } = this.qname(tag.name);
tag.prefix = prefix;
tag.local = local;
const uri = tag.uri = this.resolve(prefix) ?? "";
if (prefix !== "") {
if (prefix === "xmlns") {
this.fail("tags may not have \"xmlns\" as prefix.");
}
if (uri === "") {
this.fail(`unbound namespace prefix: ${JSON.stringify(prefix)}.`);
tag.uri = prefix;
}
}
}
if (attribList.length === 0) {
return;
}
const { attributes } = tag;
const seen = new Set();
// Note: do not apply default ns to attributes:
// http://www.w3.org/TR/REC-xml-names/#defaulting
for (const attr of attribList as SaxesAttributeNSIncomplete[]) {
const { name, prefix, local } = attr;
let uri;
let eqname;
if (prefix === "") {
uri = name === "xmlns" ? XMLNS_NAMESPACE : "";
eqname = name;
}
else {
uri = this.resolve(prefix);
// if there's any attributes with an undefined namespace,
// then fail on them now.
if (uri === undefined) {
this.fail(`unbound namespace prefix: ${JSON.stringify(prefix)}.`);
uri = prefix;
}
eqname = `{${uri}}${local}`;
}
if (seen.has(eqname)) {
this.fail(`duplicate attribute: ${eqname}.`);
}
seen.add(eqname);
attr.uri = uri;
attributes[name] = attr;
}
this.attribList = [];
}
private processAttribsPlain(): void {
const { attribList } = this;
// eslint-disable-next-line prefer-destructuring
const attributes = this.tag!.attributes;
for (const { name, value } of attribList) {
if (attributes[name] !== undefined) {
this.fail(`duplicate attribute: ${name}.`);
}
attributes[name] = value;
}
this.attribList = [];
}
/**
* Handle a complete open tag. This parser code calls this once it has seen
* the whole tag. This method checks for well-formeness and then emits
* ``onopentag``.
*/
private openTag(): void {
this.processAttribs();
const { tags } = this;
const tag = this.tag as SaxesTag;
tag.isSelfClosing = false;
// There cannot be any pending text here due to the onopentagstart that was
// necessarily emitted before we get here. So we do not check text.
this.openTagHandler?.(tag as TagForOptions<O>);
tags.push(tag);
this.state = S_TEXT;
this.name = "";
}
/**
* Handle a complete self-closing tag. This parser code calls this once it has
* seen the whole tag. This method checks for well-formeness and then emits
* ``onopentag`` and ``onclosetag``.
*/
private openSelfClosingTag(): void {
this.processAttribs();
const { tags } = this;
const tag = this.tag as SaxesTag;
tag.isSelfClosing = true;
// There cannot be any pending text here due to the onopentagstart that was
// necessarily emitted before we get here. So we do not check text.
this.openTagHandler?.(tag as TagForOptions<O>);
this.closeTagHandler?.(tag as TagForOptions<O>);
const top = this.tag = tags[tags.length - 1] ?? null;
if (top === null) {
this.closedRoot = true;
}
this.state = S_TEXT;
this.name = "";
}
/**
* Handle a complete close tag. This parser code calls this once it has seen
* the whole tag. This method checks for well-formeness and then emits
* ``onclosetag``.
*/
private closeTag(): void {
const { tags, name } = this;
// Our state after this will be S_TEXT, no matter what, and we can clear
// tagName now.
this.state = S_TEXT;
this.name = "";
if (name === "") {
this.fail("weird empty close tag.");
this.text += "</>";
return;
}
const handler = this.closeTagHandler;
let l = tags.length;
while (l-- > 0) {
const tag = this.tag = tags.pop() as SaxesTag;
this.topNS = tag.ns!;
handler?.(tag as TagForOptions<O>);
if (tag.name === name) {
break;
}
this.fail("unexpected close tag.");
}
if (l === 0) {
this.closedRoot = true;
}
else if (l < 0) {
this.fail(`unmatched closing tag: ${name}.`);
this.text += `</${name}>`;
}
}
/**
* Resolves an entity. Makes any necessary well-formedness checks.
*
* @param entity The entity to resolve.
*
* @returns The parsed entity.
*/
private parseEntity(entity: string): string {
// startsWith would be significantly slower for this test.
if (entity[0] !== "#") {
const defined = this.ENTITIES[entity];
if (defined !== undefined) {
return defined;
}
this.fail(this.isName(entity) ? "undefined entity." :
"disallowed character in entity name.");
return `&${entity};`;
}
let num = NaN;
if (entity[1] === "x" && /^#x[0-9a-f]+$/i.test(entity)) {
num = parseInt(entity.slice(2), 16);
}
else if (/^#[0-9]+$/.test(entity)) {
num = parseInt(entity.slice(1), 10);
}
// The character reference is required to match the CHAR production.
if (!this.isChar(num)) {
this.fail("malformed character entity.");
return `&${entity};`;
}
return String.fromCodePoint(num);
}
} |
1,142 | writeSource(parser: SaxesParser, source: string): void {
for (const x of source) {
parser.write(x);
}
parser.close();
} | class SaxesParser<O extends SaxesOptions = {}> {
private readonly fragmentOpt: boolean;
private readonly xmlnsOpt: boolean;
private readonly trackPosition: boolean;
private readonly fileName?: string;
private readonly nameStartCheck: (c: number) => boolean;
private readonly nameCheck: (c: number) => boolean;
private readonly isName: (name: string) => boolean;
private readonly ns!: Record<string, string>;
private openWakaBang!: string;
private text!: string;
private name!: string;
private piTarget!: string;
private entity!: string;
private q!: null | number;
private tags!: SaxesTagIncomplete[];
private tag!: SaxesTagIncomplete | null;
private topNS!: Record<string, string> | null;
private chunk!: string;
private chunkPosition!: number;
private i!: number;
//
// We use prevI to allow "ungetting" the previously read code point. Note
// however, that it is not safe to unget everything and anything. In
// particular ungetting EOL characters will screw positioning up.
//
// Practically, you must not unget a code which has any side effect beyond
// updating ``this.i`` and ``this.prevI``. Only EOL codes have such side
// effects.
//
private prevI!: number;
private carriedFromPrevious?: string;
private forbiddenState!: number;
private attribList!: (SaxesAttributeNSIncomplete | SaxesAttributePlain)[];
private state!: number;
private reportedTextBeforeRoot!: boolean;
private reportedTextAfterRoot!: boolean;
private closedRoot!: boolean;
private sawRoot!: boolean;
private xmlDeclPossible!: boolean;
private xmlDeclExpects!: string[];
private entityReturnState?: number;
private processAttribs!: (this: this) => void;
private positionAtNewLine!: number;
private doctype!: boolean;
private getCode!: () => number;
private isChar!: (c: number) => boolean;
private pushAttrib!: (name: string, value: string) => void;
private _closed!: boolean;
private currentXMLVersion!: string;
private readonly stateTable: ((this: SaxesParser<O>) => void)[];
private xmldeclHandler?: XMLDeclHandler;
private textHandler?: TextHandler;
private piHandler?: PIHandler;
private doctypeHandler?: DoctypeHandler;
private commentHandler?: CommentHandler;
private openTagStartHandler?: OpenTagStartHandler<O>;
private openTagHandler?: OpenTagHandler<O>;
private closeTagHandler?: CloseTagHandler<O>;
private cdataHandler?: CDataHandler;
private errorHandler?: ErrorHandler;
private endHandler?: EndHandler;
private readyHandler?: ReadyHandler;
private attributeHandler?: AttributeHandler<O>;
/**
* Indicates whether or not the parser is closed. If ``true``, wait for
* the ``ready`` event to write again.
*/
get closed(): boolean {
return this._closed;
}
readonly opt: SaxesOptions;
/**
* The XML declaration for this document.
*/
xmlDecl!: XMLDecl;
/**
* The line number of the next character to be read by the parser. This field
* is one-based. (The first line is numbered 1.)
*/
line!: number;
/**
* The column number of the next character to be read by the parser. *
* This field is zero-based. (The first column is 0.)
*
* This field counts columns by *Unicode character*. Note that this *can*
* be different from the index of the character in a JavaScript string due
* to how JavaScript handles astral plane characters.
*
* See [[columnIndex]] for a number that corresponds to the JavaScript index.
*/
column!: number;
/**
* A map of entity name to expansion.
*/
ENTITIES!: Record<string, string>;
/**
* @param opt The parser options.
*/
constructor(opt?: O) {
this.opt = opt ?? {};
this.fragmentOpt = !!(this.opt.fragment as boolean);
const xmlnsOpt = this.xmlnsOpt = !!(this.opt.xmlns as boolean);
this.trackPosition = this.opt.position !== false;
this.fileName = this.opt.fileName;
if (xmlnsOpt) {
// This is the function we use to perform name checks on PIs and entities.
// When namespaces are used, colons are not allowed in PI target names or
// entity names. So the check depends on whether namespaces are used. See:
//
// https://www.w3.org/XML/xml-names-19990114-errata.html
// NE08
//
this.nameStartCheck = isNCNameStartChar;
this.nameCheck = isNCNameChar;
this.isName = isNCName;
// eslint-disable-next-line @typescript-eslint/unbound-method
this.processAttribs = this.processAttribsNS;
// eslint-disable-next-line @typescript-eslint/unbound-method
this.pushAttrib = this.pushAttribNS;
// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-assignment
this.ns = { __proto__: null as any, ...rootNS };
const additional = this.opt.additionalNamespaces;
if (additional != null) {
nsMappingCheck(this, additional);
Object.assign(this.ns, additional);
}
}
else {
this.nameStartCheck = isNameStartChar;
this.nameCheck = isNameChar;
this.isName = isName;
// eslint-disable-next-line @typescript-eslint/unbound-method
this.processAttribs = this.processAttribsPlain;
// eslint-disable-next-line @typescript-eslint/unbound-method
this.pushAttrib = this.pushAttribPlain;
}
//
// The order of the members in this table needs to correspond to the state
// numbers given to the states that correspond to the methods being recorded
// here.
//
this.stateTable = [
/* eslint-disable @typescript-eslint/unbound-method */
this.sBegin,
this.sBeginWhitespace,
this.sDoctype,
this.sDoctypeQuote,
this.sDTD,
this.sDTDQuoted,
this.sDTDOpenWaka,
this.sDTDOpenWakaBang,
this.sDTDComment,
this.sDTDCommentEnding,
this.sDTDCommentEnded,
this.sDTDPI,
this.sDTDPIEnding,
this.sText,
this.sEntity,
this.sOpenWaka,
this.sOpenWakaBang,
this.sComment,
this.sCommentEnding,
this.sCommentEnded,
this.sCData,
this.sCDataEnding,
this.sCDataEnding2,
this.sPIFirstChar,
this.sPIRest,
this.sPIBody,
this.sPIEnding,
this.sXMLDeclNameStart,
this.sXMLDeclName,
this.sXMLDeclEq,
this.sXMLDeclValueStart,
this.sXMLDeclValue,
this.sXMLDeclSeparator,
this.sXMLDeclEnding,
this.sOpenTag,
this.sOpenTagSlash,
this.sAttrib,
this.sAttribName,
this.sAttribNameSawWhite,
this.sAttribValue,
this.sAttribValueQuoted,
this.sAttribValueClosed,
this.sAttribValueUnquoted,
this.sCloseTag,
this.sCloseTagSawWhite,
/* eslint-enable @typescript-eslint/unbound-method */
];
this._init();
}
_init(): void {
this.openWakaBang = "";
this.text = "";
this.name = "";
this.piTarget = "";
this.entity = "";
this.q = null;
this.tags = [];
this.tag = null;
this.topNS = null;
this.chunk = "";
this.chunkPosition = 0;
this.i = 0;
this.prevI = 0;
this.carriedFromPrevious = undefined;
this.forbiddenState = FORBIDDEN_START;
this.attribList = [];
// The logic is organized so as to minimize the need to check
// this.opt.fragment while parsing.
const { fragmentOpt } = this;
this.state = fragmentOpt ? S_TEXT : S_BEGIN;
// We want these to be all true if we are dealing with a fragment.
this.reportedTextBeforeRoot = this.reportedTextAfterRoot = this.closedRoot =
this.sawRoot = fragmentOpt;
// An XML declaration is intially possible only when parsing whole
// documents.
this.xmlDeclPossible = !fragmentOpt;
this.xmlDeclExpects = ["version"];
this.entityReturnState = undefined;
let { defaultXMLVersion } = this.opt;
if (defaultXMLVersion === undefined) {
if (this.opt.forceXMLVersion === true) {
throw new Error("forceXMLVersion set but defaultXMLVersion is not set");
}
defaultXMLVersion = "1.0";
}
this.setXMLVersion(defaultXMLVersion);
this.positionAtNewLine = 0;
this.doctype = false;
this._closed = false;
this.xmlDecl = {
version: undefined,
encoding: undefined,
standalone: undefined,
};
this.line = 1;
this.column = 0;
this.ENTITIES = Object.create(XML_ENTITIES) as Record<string, string>;
this.readyHandler?.();
}
/**
* The stream position the parser is currently looking at. This field is
* zero-based.
*
* This field is not based on counting Unicode characters but is to be
* interpreted as a plain index into a JavaScript string.
*/
get position(): number {
return this.chunkPosition + this.i;
}
/**
* The column number of the next character to be read by the parser. *
* This field is zero-based. (The first column in a line is 0.)
*
* This field reports the index at which the next character would be in the
* line if the line were represented as a JavaScript string. Note that this
* *can* be different to a count based on the number of *Unicode characters*
* due to how JavaScript handles astral plane characters.
*
* See [[column]] for a number that corresponds to a count of Unicode
* characters.
*/
get columnIndex(): number {
return this.position - this.positionAtNewLine;
}
/**
* Set an event listener on an event. The parser supports one handler per
* event type. If you try to set an event handler over an existing handler,
* the old handler is silently overwritten.
*
* @param name The event to listen to.
*
* @param handler The handler to set.
*/
on<N extends EventName>(name: N, handler: EventNameToHandler<O, N>): void {
// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-member-access
(this as any)[EVENT_NAME_TO_HANDLER_NAME[name]] = handler;
}
/**
* Unset an event handler.
*
* @parma name The event to stop listening to.
*/
off(name: EventName): void {
// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-member-access
(this as any)[EVENT_NAME_TO_HANDLER_NAME[name]] = undefined;
}
/**
* Make an error object. The error object will have a message that contains
* the ``fileName`` option passed at the creation of the parser. If position
* tracking was turned on, it will also have line and column number
* information.
*
* @param message The message describing the error to report.
*
* @returns An error object with a properly formatted message.
*/
makeError(message: string): Error {
let msg = this.fileName ?? "";
if (this.trackPosition) {
if (msg.length > 0) {
msg += ":";
}
msg += `${this.line}:${this.column}`;
}
if (msg.length > 0) {
msg += ": ";
}
return new Error(msg + message);
}
/**
* Report a parsing error. This method is made public so that client code may
* check for issues that are outside the scope of this project and can report
* errors.
*
* @param message The error to report.
*
* @returns this
*/
fail(message: string): this {
const err = this.makeError(message);
const handler = this.errorHandler;
if (handler === undefined) {
throw err;
}
else {
handler(err);
}
return this;
}
/**
* Write a XML data to the parser.
*
* @param chunk The XML data to write.
*
* @returns this
*/
// We do need object for the type here. Yes, it often causes problems
// but not in this case.
write(chunk: string | object | null): this {
if (this.closed) {
return this.fail("cannot write after close; assign an onready handler.");
}
let end = false;
if (chunk === null) {
// We cannot return immediately because carriedFromPrevious may need
// processing.
end = true;
chunk = "";
}
else if (typeof chunk === "object") {
chunk = chunk.toString();
}
// We checked if performing a pre-decomposition of the string into an array
// of single complete characters (``Array.from(chunk)``) would be faster
// than the current repeated calls to ``charCodeAt``. As of August 2018, it
// isn't. (There may be Node-specific code that would perform faster than
// ``Array.from`` but don't want to be dependent on Node.)
if (this.carriedFromPrevious !== undefined) {
// The previous chunk had char we must carry over.
chunk = `${this.carriedFromPrevious}${chunk}`;
this.carriedFromPrevious = undefined;
}
let limit = chunk.length;
const lastCode = chunk.charCodeAt(limit - 1);
if (!end &&
// A trailing CR or surrogate must be carried over to the next
// chunk.
(lastCode === CR || (lastCode >= 0xD800 && lastCode <= 0xDBFF))) {
// The chunk ends with a character that must be carried over. We cannot
// know how to handle it until we get the next chunk or the end of the
// stream. So save it for later.
this.carriedFromPrevious = chunk[limit - 1];
limit--;
chunk = chunk.slice(0, limit);
}
const { stateTable } = this;
this.chunk = chunk;
this.i = 0;
while (this.i < limit) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-argument
stateTable[this.state].call(this as any);
}
this.chunkPosition += limit;
return end ? this.end() : this;
}
/**
* Close the current stream. Perform final well-formedness checks and reset
* the parser tstate.
*
* @returns this
*/
close(): this {
return this.write(null);
}
/**
* Get a single code point out of the current chunk. This updates the current
* position if we do position tracking.
*
* This is the algorithm to use for XML 1.0.
*
* @returns The character read.
*/
private getCode10(): number {
const { chunk, i } = this;
this.prevI = i;
// Yes, we do this instead of doing this.i++. Doing it this way, we do not
// read this.i again, which is a bit faster.
this.i = i + 1;
if (i >= chunk.length) {
return EOC;
}
// Using charCodeAt and handling the surrogates ourselves is faster
// than using codePointAt.
const code = chunk.charCodeAt(i);
this.column++;
if (code < 0xD800) {
if (code >= SPACE || code === TAB) {
return code;
}
switch (code) {
case NL:
this.line++;
this.column = 0;
this.positionAtNewLine = this.position;
return NL;
case CR:
// We may get NaN if we read past the end of the chunk, which is fine.
if (chunk.charCodeAt(i + 1) === NL) {
// A \r\n sequence is converted to \n so we have to skip over the
// next character. We already know it has a size of 1 so ++ is fine
// here.
this.i = i + 2;
}
// Otherwise, a \r is just converted to \n, so we don't have to skip
// ahead.
// In either case, \r becomes \n.
this.line++;
this.column = 0;
this.positionAtNewLine = this.position;
return NL_LIKE;
default:
// If we get here, then code < SPACE and it is not NL CR or TAB.
this.fail("disallowed character.");
return code;
}
}
if (code > 0xDBFF) {
// This is a specialized version of isChar10 that takes into account
// that in this context code > 0xDBFF and code <= 0xFFFF. So it does not
// test cases that don't need testing.
if (!(code >= 0xE000 && code <= 0xFFFD)) {
this.fail("disallowed character.");
}
return code;
}
const final = 0x10000 + ((code - 0xD800) * 0x400) +
(chunk.charCodeAt(i + 1) - 0xDC00);
this.i = i + 2;
// This is a specialized version of isChar10 that takes into account that in
// this context necessarily final >= 0x10000.
if (final > 0x10FFFF) {
this.fail("disallowed character.");
}
return final;
}
/**
* Get a single code point out of the current chunk. This updates the current
* position if we do position tracking.
*
* This is the algorithm to use for XML 1.1.
*
* @returns {number} The character read.
*/
private getCode11(): number {
const { chunk, i } = this;
this.prevI = i;
// Yes, we do this instead of doing this.i++. Doing it this way, we do not
// read this.i again, which is a bit faster.
this.i = i + 1;
if (i >= chunk.length) {
return EOC;
}
// Using charCodeAt and handling the surrogates ourselves is faster
// than using codePointAt.
const code = chunk.charCodeAt(i);
this.column++;
if (code < 0xD800) {
if ((code > 0x1F && code < 0x7F) || (code > 0x9F && code !== LS) ||
code === TAB) {
return code;
}
switch (code) {
case NL: // 0xA
this.line++;
this.column = 0;
this.positionAtNewLine = this.position;
return NL;
case CR: { // 0xD
// We may get NaN if we read past the end of the chunk, which is
// fine.
const next = chunk.charCodeAt(i + 1);
if (next === NL || next === NEL) {
// A CR NL or CR NEL sequence is converted to NL so we have to skip
// over the next character. We already know it has a size of 1.
this.i = i + 2;
}
// Otherwise, a CR is just converted to NL, no skip.
}
/* yes, fall through */
case NEL: // 0x85
case LS: // Ox2028
this.line++;
this.column = 0;
this.positionAtNewLine = this.position;
return NL_LIKE;
default:
this.fail("disallowed character.");
return code;
}
}
if (code > 0xDBFF) {
// This is a specialized version of isCharAndNotRestricted that takes into
// account that in this context code > 0xDBFF and code <= 0xFFFF. So it
// does not test cases that don't need testing.
if (!(code >= 0xE000 && code <= 0xFFFD)) {
this.fail("disallowed character.");
}
return code;
}
const final = 0x10000 + ((code - 0xD800) * 0x400) +
(chunk.charCodeAt(i + 1) - 0xDC00);
this.i = i + 2;
// This is a specialized version of isCharAndNotRestricted that takes into
// account that in this context necessarily final >= 0x10000.
if (final > 0x10FFFF) {
this.fail("disallowed character.");
}
return final;
}
/**
* Like ``getCode`` but with the return value normalized so that ``NL`` is
* returned for ``NL_LIKE``.
*/
private getCodeNorm(): number {
const c = this.getCode();
return c === NL_LIKE ? NL : c;
}
private unget(): void {
this.i = this.prevI;
this.column--;
}
/**
* Capture characters into a buffer until encountering one of a set of
* characters.
*
* @param chars An array of codepoints. Encountering a character in the array
* ends the capture. (``chars`` may safely contain ``NL``.)
*
* @return The character code that made the capture end, or ``EOC`` if we hit
* the end of the chunk. The return value cannot be NL_LIKE: NL is returned
* instead.
*/
private captureTo(chars: number[]): number {
let { i: start } = this;
const { chunk } = this;
// eslint-disable-next-line no-constant-condition
while (true) {
const c = this.getCode();
const isNLLike = c === NL_LIKE;
const final = isNLLike ? NL : c;
if (final === EOC || chars.includes(final)) {
this.text += chunk.slice(start, this.prevI);
return final;
}
if (isNLLike) {
this.text += `${chunk.slice(start, this.prevI)}\n`;
start = this.i;
}
}
}
/**
* Capture characters into a buffer until encountering a character.
*
* @param char The codepoint that ends the capture. **NOTE ``char`` MAY NOT
* CONTAIN ``NL``.** Passing ``NL`` will result in buggy behavior.
*
* @return ``true`` if we ran into the character. Otherwise, we ran into the
* end of the current chunk.
*/
private captureToChar(char: number): boolean {
let { i: start } = this;
const { chunk } = this;
// eslint-disable-next-line no-constant-condition
while (true) {
let c = this.getCode();
switch (c) {
case NL_LIKE:
this.text += `${chunk.slice(start, this.prevI)}\n`;
start = this.i;
c = NL;
break;
case EOC:
this.text += chunk.slice(start);
return false;
default:
}
if (c === char) {
this.text += chunk.slice(start, this.prevI);
return true;
}
}
}
/**
* Capture characters that satisfy ``isNameChar`` into the ``name`` field of
* this parser.
*
* @return The character code that made the test fail, or ``EOC`` if we hit
* the end of the chunk. The return value cannot be NL_LIKE: NL is returned
* instead.
*/
private captureNameChars(): number {
const { chunk, i: start } = this;
// eslint-disable-next-line no-constant-condition
while (true) {
const c = this.getCode();
if (c === EOC) {
this.name += chunk.slice(start);
return EOC;
}
// NL is not a name char so we don't have to test specifically for it.
if (!isNameChar(c)) {
this.name += chunk.slice(start, this.prevI);
return c === NL_LIKE ? NL : c;
}
}
}
/**
* Skip white spaces.
*
* @return The character that ended the skip, or ``EOC`` if we hit
* the end of the chunk. The return value cannot be NL_LIKE: NL is returned
* instead.
*/
private skipSpaces(): number {
// eslint-disable-next-line no-constant-condition
while (true) {
const c = this.getCodeNorm();
if (c === EOC || !isS(c)) {
return c;
}
}
}
private setXMLVersion(version: string): void {
this.currentXMLVersion = version;
/* eslint-disable @typescript-eslint/unbound-method */
if (version === "1.0") {
this.isChar = isChar10;
this.getCode = this.getCode10;
}
else {
this.isChar = isChar11;
this.getCode = this.getCode11;
}
/* eslint-enable @typescript-eslint/unbound-method */
}
// STATE ENGINE METHODS
// This needs to be a state separate from S_BEGIN_WHITESPACE because we want
// to be sure never to come back to this state later.
private sBegin(): void {
// We are essentially peeking at the first character of the chunk. Since
// S_BEGIN can be in effect only when we start working on the first chunk,
// the index at which we must look is necessarily 0. Note also that the
// following test does not depend on decoding surrogates.
// If the initial character is 0xFEFF, ignore it.
if (this.chunk.charCodeAt(0) === 0xFEFF) {
this.i++;
this.column++;
}
this.state = S_BEGIN_WHITESPACE;
}
private sBeginWhitespace(): void {
// We need to know whether we've encountered spaces or not because as soon
// as we run into a space, an XML declaration is no longer possible. Rather
// than slow down skipSpaces even in places where we don't care whether it
// skipped anything or not, we check whether prevI is equal to the value of
// i from before we skip spaces.
const iBefore = this.i;
const c = this.skipSpaces();
if (this.prevI !== iBefore) {
this.xmlDeclPossible = false;
}
switch (c) {
case LESS:
this.state = S_OPEN_WAKA;
// We could naively call closeText but in this state, it is not normal
// to have text be filled with any data.
if (this.text.length !== 0) {
throw new Error("no-empty text at start");
}
break;
case EOC:
break;
default:
this.unget();
this.state = S_TEXT;
this.xmlDeclPossible = false;
}
}
private sDoctype(): void {
const c = this.captureTo(DOCTYPE_TERMINATOR);
switch (c) {
case GREATER: {
this.doctypeHandler?.(this.text);
this.text = "";
this.state = S_TEXT;
this.doctype = true; // just remember that we saw it.
break;
}
case EOC:
break;
default:
this.text += String.fromCodePoint(c);
if (c === OPEN_BRACKET) {
this.state = S_DTD;
}
else if (isQuote(c)) {
this.state = S_DOCTYPE_QUOTE;
this.q = c;
}
}
}
private sDoctypeQuote(): void {
const q = this.q!;
if (this.captureToChar(q)) {
this.text += String.fromCodePoint(q);
this.q = null;
this.state = S_DOCTYPE;
}
}
private sDTD(): void {
const c = this.captureTo(DTD_TERMINATOR);
if (c === EOC) {
return;
}
this.text += String.fromCodePoint(c);
if (c === CLOSE_BRACKET) {
this.state = S_DOCTYPE;
}
else if (c === LESS) {
this.state = S_DTD_OPEN_WAKA;
}
else if (isQuote(c)) {
this.state = S_DTD_QUOTED;
this.q = c;
}
}
private sDTDQuoted(): void {
const q = this.q!;
if (this.captureToChar(q)) {
this.text += String.fromCodePoint(q);
this.state = S_DTD;
this.q = null;
}
}
private sDTDOpenWaka(): void {
const c = this.getCodeNorm();
this.text += String.fromCodePoint(c);
switch (c) {
case BANG:
this.state = S_DTD_OPEN_WAKA_BANG;
this.openWakaBang = "";
break;
case QUESTION:
this.state = S_DTD_PI;
break;
default:
this.state = S_DTD;
}
}
private sDTDOpenWakaBang(): void {
const char = String.fromCodePoint(this.getCodeNorm());
const owb = this.openWakaBang += char;
this.text += char;
if (owb !== "-") {
this.state = owb === "--" ? S_DTD_COMMENT : S_DTD;
this.openWakaBang = "";
}
}
private sDTDComment(): void {
if (this.captureToChar(MINUS)) {
this.text += "-";
this.state = S_DTD_COMMENT_ENDING;
}
}
private sDTDCommentEnding(): void {
const c = this.getCodeNorm();
this.text += String.fromCodePoint(c);
this.state = c === MINUS ? S_DTD_COMMENT_ENDED : S_DTD_COMMENT;
}
private sDTDCommentEnded(): void {
const c = this.getCodeNorm();
this.text += String.fromCodePoint(c);
if (c === GREATER) {
this.state = S_DTD;
}
else {
this.fail("malformed comment.");
// <!-- blah -- bloo --> will be recorded as
// a comment of " blah -- bloo "
this.state = S_DTD_COMMENT;
}
}
private sDTDPI(): void {
if (this.captureToChar(QUESTION)) {
this.text += "?";
this.state = S_DTD_PI_ENDING;
}
}
private sDTDPIEnding(): void {
const c = this.getCodeNorm();
this.text += String.fromCodePoint(c);
if (c === GREATER) {
this.state = S_DTD;
}
}
private sText(): void {
//
// We did try a version of saxes where the S_TEXT state was split in two
// states: one for text inside the root element, and one for text
// outside. This was avoiding having to test this.tags.length to decide
// what implementation to actually use.
//
// Peformance testing on gigabyte-size files did not show any advantage to
// using the two states solution instead of the current one. Conversely, it
// made the code a bit more complicated elsewhere. For instance, a comment
// can appear before the root element so when a comment ended it was
// necessary to determine whether to return to the S_TEXT state or to the
// new text-outside-root state.
//
if (this.tags.length !== 0) {
this.handleTextInRoot();
}
else {
this.handleTextOutsideRoot();
}
}
private sEntity(): void {
// This is essentially a specialized version of captureToChar(SEMICOLON...)
let { i: start } = this;
const { chunk } = this;
// eslint-disable-next-line no-labels, no-restricted-syntax
loop:
// eslint-disable-next-line no-constant-condition
while (true) {
switch (this.getCode()) {
case NL_LIKE:
this.entity += `${chunk.slice(start, this.prevI)}\n`;
start = this.i;
break;
case SEMICOLON: {
const { entityReturnState } = this;
const entity = this.entity + chunk.slice(start, this.prevI);
this.state = entityReturnState!;
let parsed: string;
if (entity === "") {
this.fail("empty entity name.");
parsed = "&;";
}
else {
parsed = this.parseEntity(entity);
this.entity = "";
}
if (entityReturnState !== S_TEXT || this.textHandler !== undefined) {
this.text += parsed;
}
// eslint-disable-next-line no-labels
break loop;
}
case EOC:
this.entity += chunk.slice(start);
// eslint-disable-next-line no-labels
break loop;
default:
}
}
}
private sOpenWaka(): void {
// Reminder: a state handler is called with at least one character
// available in the current chunk. So the first call to get code inside of
// a state handler cannot return ``EOC``. That's why we don't test
// for it.
const c = this.getCode();
// either a /, ?, !, or text is coming next.
if (isNameStartChar(c)) {
this.state = S_OPEN_TAG;
this.unget();
this.xmlDeclPossible = false;
}
else {
switch (c) {
case FORWARD_SLASH:
this.state = S_CLOSE_TAG;
this.xmlDeclPossible = false;
break;
case BANG:
this.state = S_OPEN_WAKA_BANG;
this.openWakaBang = "";
this.xmlDeclPossible = false;
break;
case QUESTION:
this.state = S_PI_FIRST_CHAR;
break;
default:
this.fail("disallowed character in tag name");
this.state = S_TEXT;
this.xmlDeclPossible = false;
}
}
}
private sOpenWakaBang(): void {
this.openWakaBang += String.fromCodePoint(this.getCodeNorm());
switch (this.openWakaBang) {
case "[CDATA[":
if (!this.sawRoot && !this.reportedTextBeforeRoot) {
this.fail("text data outside of root node.");
this.reportedTextBeforeRoot = true;
}
if (this.closedRoot && !this.reportedTextAfterRoot) {
this.fail("text data outside of root node.");
this.reportedTextAfterRoot = true;
}
this.state = S_CDATA;
this.openWakaBang = "";
break;
case "--":
this.state = S_COMMENT;
this.openWakaBang = "";
break;
case "DOCTYPE":
this.state = S_DOCTYPE;
if (this.doctype || this.sawRoot) {
this.fail("inappropriately located doctype declaration.");
}
this.openWakaBang = "";
break;
default:
// 7 happens to be the maximum length of the string that can possibly
// match one of the cases above.
if (this.openWakaBang.length >= 7) {
this.fail("incorrect syntax.");
}
}
}
private sComment(): void {
if (this.captureToChar(MINUS)) {
this.state = S_COMMENT_ENDING;
}
}
private sCommentEnding(): void {
const c = this.getCodeNorm();
if (c === MINUS) {
this.state = S_COMMENT_ENDED;
this.commentHandler?.(this.text);
this.text = "";
}
else {
this.text += `-${String.fromCodePoint(c)}`;
this.state = S_COMMENT;
}
}
private sCommentEnded(): void {
const c = this.getCodeNorm();
if (c !== GREATER) {
this.fail("malformed comment.");
// <!-- blah -- bloo --> will be recorded as
// a comment of " blah -- bloo "
this.text += `--${String.fromCodePoint(c)}`;
this.state = S_COMMENT;
}
else {
this.state = S_TEXT;
}
}
private sCData(): void {
if (this.captureToChar(CLOSE_BRACKET)) {
this.state = S_CDATA_ENDING;
}
}
private sCDataEnding(): void {
const c = this.getCodeNorm();
if (c === CLOSE_BRACKET) {
this.state = S_CDATA_ENDING_2;
}
else {
this.text += `]${String.fromCodePoint(c)}`;
this.state = S_CDATA;
}
}
private sCDataEnding2(): void {
const c = this.getCodeNorm();
switch (c) {
case GREATER: {
this.cdataHandler?.(this.text);
this.text = "";
this.state = S_TEXT;
break;
}
case CLOSE_BRACKET:
this.text += "]";
break;
default:
this.text += `]]${String.fromCodePoint(c)}`;
this.state = S_CDATA;
}
}
// We need this separate state to check the first character fo the pi target
// with this.nameStartCheck which allows less characters than this.nameCheck.
private sPIFirstChar(): void {
const c = this.getCodeNorm();
// This is first because in the case where the file is well-formed this is
// the branch taken. We optimize for well-formedness.
if (this.nameStartCheck(c)) {
this.piTarget += String.fromCodePoint(c);
this.state = S_PI_REST;
}
else if (c === QUESTION || isS(c)) {
this.fail("processing instruction without a target.");
this.state = c === QUESTION ? S_PI_ENDING : S_PI_BODY;
}
else {
this.fail("disallowed character in processing instruction name.");
this.piTarget += String.fromCodePoint(c);
this.state = S_PI_REST;
}
}
private sPIRest(): void {
// Capture characters into a piTarget while ``this.nameCheck`` run on the
// character read returns true.
const { chunk, i: start } = this;
// eslint-disable-next-line no-constant-condition
while (true) {
const c = this.getCodeNorm();
if (c === EOC) {
this.piTarget += chunk.slice(start);
return;
}
// NL cannot satisfy this.nameCheck so we don't have to test specifically
// for it.
if (!this.nameCheck(c)) {
this.piTarget += chunk.slice(start, this.prevI);
const isQuestion = c === QUESTION;
if (isQuestion || isS(c)) {
if (this.piTarget === "xml") {
if (!this.xmlDeclPossible) {
this.fail(
"an XML declaration must be at the start of the document.");
}
this.state = isQuestion ? S_XML_DECL_ENDING : S_XML_DECL_NAME_START;
}
else {
this.state = isQuestion ? S_PI_ENDING : S_PI_BODY;
}
}
else {
this.fail("disallowed character in processing instruction name.");
this.piTarget += String.fromCodePoint(c);
}
break;
}
}
}
private sPIBody(): void {
if (this.text.length === 0) {
const c = this.getCodeNorm();
if (c === QUESTION) {
this.state = S_PI_ENDING;
}
else if (!isS(c)) {
this.text = String.fromCodePoint(c);
}
}
// The question mark character is not valid inside any of the XML
// declaration name/value pairs.
else if (this.captureToChar(QUESTION)) {
this.state = S_PI_ENDING;
}
}
private sPIEnding(): void {
const c = this.getCodeNorm();
if (c === GREATER) {
const { piTarget } = this;
if (piTarget.toLowerCase() === "xml") {
this.fail(
"the XML declaration must appear at the start of the document.");
}
this.piHandler?.({
target: piTarget,
body: this.text,
});
this.piTarget = this.text = "";
this.state = S_TEXT;
}
else if (c === QUESTION) {
// We ran into ?? as part of a processing instruction. We initially took
// the first ? as a sign that the PI was ending, but it is not. So we have
// to add it to the body but we take the new ? as a sign that the PI is
// ending.
this.text += "?";
}
else {
this.text += `?${String.fromCodePoint(c)}`;
this.state = S_PI_BODY;
}
this.xmlDeclPossible = false;
}
private sXMLDeclNameStart(): void {
const c = this.skipSpaces();
// The question mark character is not valid inside any of the XML
// declaration name/value pairs.
if (c === QUESTION) {
// It is valid to go to S_XML_DECL_ENDING from this state.
this.state = S_XML_DECL_ENDING;
return;
}
if (c !== EOC) {
this.state = S_XML_DECL_NAME;
this.name = String.fromCodePoint(c);
}
}
private sXMLDeclName(): void {
const c = this.captureTo(XML_DECL_NAME_TERMINATOR);
// The question mark character is not valid inside any of the XML
// declaration name/value pairs.
if (c === QUESTION) {
this.state = S_XML_DECL_ENDING;
this.name += this.text;
this.text = "";
this.fail("XML declaration is incomplete.");
return;
}
if (!(isS(c) || c === EQUAL)) {
return;
}
this.name += this.text;
this.text = "";
if (!this.xmlDeclExpects.includes(this.name)) {
switch (this.name.length) {
case 0:
this.fail("did not expect any more name/value pairs.");
break;
case 1:
this.fail(`expected the name ${this.xmlDeclExpects[0]}.`);
break;
default:
this.fail(`expected one of ${this.xmlDeclExpects.join(", ")}`);
}
}
this.state = c === EQUAL ? S_XML_DECL_VALUE_START : S_XML_DECL_EQ;
}
private sXMLDeclEq(): void {
const c = this.getCodeNorm();
// The question mark character is not valid inside any of the XML
// declaration name/value pairs.
if (c === QUESTION) {
this.state = S_XML_DECL_ENDING;
this.fail("XML declaration is incomplete.");
return;
}
if (isS(c)) {
return;
}
if (c !== EQUAL) {
this.fail("value required.");
}
this.state = S_XML_DECL_VALUE_START;
}
private sXMLDeclValueStart(): void {
const c = this.getCodeNorm();
// The question mark character is not valid inside any of the XML
// declaration name/value pairs.
if (c === QUESTION) {
this.state = S_XML_DECL_ENDING;
this.fail("XML declaration is incomplete.");
return;
}
if (isS(c)) {
return;
}
if (!isQuote(c)) {
this.fail("value must be quoted.");
this.q = SPACE;
}
else {
this.q = c;
}
this.state = S_XML_DECL_VALUE;
}
private sXMLDeclValue(): void {
const c = this.captureTo([this.q!, QUESTION]);
// The question mark character is not valid inside any of the XML
// declaration name/value pairs.
if (c === QUESTION) {
this.state = S_XML_DECL_ENDING;
this.text = "";
this.fail("XML declaration is incomplete.");
return;
}
if (c === EOC) {
return;
}
const value = this.text;
this.text = "";
switch (this.name) {
case "version": {
this.xmlDeclExpects = ["encoding", "standalone"];
const version = value;
this.xmlDecl.version = version;
// This is the test specified by XML 1.0 but it is fine for XML 1.1.
if (!/^1\.[0-9]+$/.test(version)) {
this.fail("version number must match /^1\\.[0-9]+$/.");
}
// When forceXMLVersion is set, the XML declaration is ignored.
else if (!(this.opt.forceXMLVersion as boolean)) {
this.setXMLVersion(version);
}
break;
}
case "encoding":
if (!/^[A-Za-z][A-Za-z0-9._-]*$/.test(value)) {
this.fail("encoding value must match \
/^[A-Za-z0-9][A-Za-z0-9._-]*$/.");
}
this.xmlDeclExpects = ["standalone"];
this.xmlDecl.encoding = value;
break;
case "standalone":
if (value !== "yes" && value !== "no") {
this.fail("standalone value must match \"yes\" or \"no\".");
}
this.xmlDeclExpects = [];
this.xmlDecl.standalone = value;
break;
default:
// We don't need to raise an error here since we've already raised one
// when checking what name was expected.
}
this.name = "";
this.state = S_XML_DECL_SEPARATOR;
}
private sXMLDeclSeparator(): void {
const c = this.getCodeNorm();
// The question mark character is not valid inside any of the XML
// declaration name/value pairs.
if (c === QUESTION) {
// It is valid to go to S_XML_DECL_ENDING from this state.
this.state = S_XML_DECL_ENDING;
return;
}
if (!isS(c)) {
this.fail("whitespace required.");
this.unget();
}
this.state = S_XML_DECL_NAME_START;
}
private sXMLDeclEnding(): void {
const c = this.getCodeNorm();
if (c === GREATER) {
if (this.piTarget !== "xml") {
this.fail("processing instructions are not allowed before root.");
}
else if (this.name !== "version" &&
this.xmlDeclExpects.includes("version")) {
this.fail("XML declaration must contain a version.");
}
this.xmldeclHandler?.(this.xmlDecl);
this.name = "";
this.piTarget = this.text = "";
this.state = S_TEXT;
}
else {
// We got here because the previous character was a ?, but the question
// mark character is not valid inside any of the XML declaration
// name/value pairs.
this.fail(
"The character ? is disallowed anywhere in XML declarations.");
}
this.xmlDeclPossible = false;
}
private sOpenTag(): void {
const c = this.captureNameChars();
if (c === EOC) {
return;
}
const tag: SaxesTagIncomplete = this.tag = {
name: this.name,
attributes: Object.create(null) as Record<string, string>,
};
this.name = "";
if (this.xmlnsOpt) {
this.topNS = tag.ns = Object.create(null) as Record<string, string>;
}
this.openTagStartHandler?.(tag as StartTagForOptions<O>);
this.sawRoot = true;
if (!this.fragmentOpt && this.closedRoot) {
this.fail("documents may contain only one root.");
}
switch (c) {
case GREATER:
this.openTag();
break;
case FORWARD_SLASH:
this.state = S_OPEN_TAG_SLASH;
break;
default:
if (!isS(c)) {
this.fail("disallowed character in tag name.");
}
this.state = S_ATTRIB;
}
}
private sOpenTagSlash(): void {
if (this.getCode() === GREATER) {
this.openSelfClosingTag();
}
else {
this.fail("forward-slash in opening tag not followed by >.");
this.state = S_ATTRIB;
}
}
private sAttrib(): void {
const c = this.skipSpaces();
if (c === EOC) {
return;
}
if (isNameStartChar(c)) {
this.unget();
this.state = S_ATTRIB_NAME;
}
else if (c === GREATER) {
this.openTag();
}
else if (c === FORWARD_SLASH) {
this.state = S_OPEN_TAG_SLASH;
}
else {
this.fail("disallowed character in attribute name.");
}
}
private sAttribName(): void {
const c = this.captureNameChars();
if (c === EQUAL) {
this.state = S_ATTRIB_VALUE;
}
else if (isS(c)) {
this.state = S_ATTRIB_NAME_SAW_WHITE;
}
else if (c === GREATER) {
this.fail("attribute without value.");
this.pushAttrib(this.name, this.name);
this.name = this.text = "";
this.openTag();
}
else if (c !== EOC) {
this.fail("disallowed character in attribute name.");
}
}
private sAttribNameSawWhite(): void {
const c = this.skipSpaces();
switch (c) {
case EOC:
return;
case EQUAL:
this.state = S_ATTRIB_VALUE;
break;
default:
this.fail("attribute without value.");
// Should we do this???
// this.tag.attributes[this.name] = "";
this.text = "";
this.name = "";
if (c === GREATER) {
this.openTag();
}
else if (isNameStartChar(c)) {
this.unget();
this.state = S_ATTRIB_NAME;
}
else {
this.fail("disallowed character in attribute name.");
this.state = S_ATTRIB;
}
}
}
private sAttribValue(): void {
const c = this.getCodeNorm();
if (isQuote(c)) {
this.q = c;
this.state = S_ATTRIB_VALUE_QUOTED;
}
else if (!isS(c)) {
this.fail("unquoted attribute value.");
this.state = S_ATTRIB_VALUE_UNQUOTED;
this.unget();
}
}
private sAttribValueQuoted(): void {
// We deliberately do not use captureTo here. The specialized code we use
// here is faster than using captureTo.
const { q, chunk } = this;
let { i: start } = this;
// eslint-disable-next-line no-constant-condition
while (true) {
switch (this.getCode()) {
case q:
this.pushAttrib(this.name,
this.text + chunk.slice(start, this.prevI));
this.name = this.text = "";
this.q = null;
this.state = S_ATTRIB_VALUE_CLOSED;
return;
case AMP:
this.text += chunk.slice(start, this.prevI);
this.state = S_ENTITY;
this.entityReturnState = S_ATTRIB_VALUE_QUOTED;
return;
case NL:
case NL_LIKE:
case TAB:
this.text += `${chunk.slice(start, this.prevI)} `;
start = this.i;
break;
case LESS:
this.text += chunk.slice(start, this.prevI);
this.fail("disallowed character.");
return;
case EOC:
this.text += chunk.slice(start);
return;
default:
}
}
}
private sAttribValueClosed(): void {
const c = this.getCodeNorm();
if (isS(c)) {
this.state = S_ATTRIB;
}
else if (c === GREATER) {
this.openTag();
}
else if (c === FORWARD_SLASH) {
this.state = S_OPEN_TAG_SLASH;
}
else if (isNameStartChar(c)) {
this.fail("no whitespace between attributes.");
this.unget();
this.state = S_ATTRIB_NAME;
}
else {
this.fail("disallowed character in attribute name.");
}
}
private sAttribValueUnquoted(): void {
// We don't do anything regarding EOL or space handling for unquoted
// attributes. We already have failed by the time we get here, and the
// contract that saxes upholds states that upon failure, it is not safe to
// rely on the data passed to event handlers (other than
// ``onerror``). Passing "bad" data is not a problem.
const c = this.captureTo(ATTRIB_VALUE_UNQUOTED_TERMINATOR);
switch (c) {
case AMP:
this.state = S_ENTITY;
this.entityReturnState = S_ATTRIB_VALUE_UNQUOTED;
break;
case LESS:
this.fail("disallowed character.");
break;
case EOC:
break;
default:
if (this.text.includes("]]>")) {
this.fail("the string \"]]>\" is disallowed in char data.");
}
this.pushAttrib(this.name, this.text);
this.name = this.text = "";
if (c === GREATER) {
this.openTag();
}
else {
this.state = S_ATTRIB;
}
}
}
private sCloseTag(): void {
const c = this.captureNameChars();
if (c === GREATER) {
this.closeTag();
}
else if (isS(c)) {
this.state = S_CLOSE_TAG_SAW_WHITE;
}
else if (c !== EOC) {
this.fail("disallowed character in closing tag.");
}
}
private sCloseTagSawWhite(): void {
switch (this.skipSpaces()) {
case GREATER:
this.closeTag();
break;
case EOC:
break;
default:
this.fail("disallowed character in closing tag.");
}
}
// END OF STATE ENGINE METHODS
private handleTextInRoot(): void {
// This is essentially a specialized version of captureTo which is optimized
// for performing the ]]> check. A previous version of this code, checked
// ``this.text`` for the presence of ]]>. It simplified the code but was
// very costly when character data contained a lot of entities to be parsed.
//
// Since we are using a specialized loop, we also keep track of the presence
// of ]]> in text data. The sequence ]]> is forbidden to appear as-is.
//
let { i: start, forbiddenState } = this;
const { chunk, textHandler: handler } = this;
// eslint-disable-next-line no-labels, no-restricted-syntax
scanLoop:
// eslint-disable-next-line no-constant-condition
while (true) {
switch (this.getCode()) {
case LESS: {
this.state = S_OPEN_WAKA;
if (handler !== undefined) {
const { text } = this;
const slice = chunk.slice(start, this.prevI);
if (text.length !== 0) {
handler(text + slice);
this.text = "";
}
else if (slice.length !== 0) {
handler(slice);
}
}
forbiddenState = FORBIDDEN_START;
// eslint-disable-next-line no-labels
break scanLoop;
}
case AMP:
this.state = S_ENTITY;
this.entityReturnState = S_TEXT;
if (handler !== undefined) {
this.text += chunk.slice(start, this.prevI);
}
forbiddenState = FORBIDDEN_START;
// eslint-disable-next-line no-labels
break scanLoop;
case CLOSE_BRACKET:
switch (forbiddenState) {
case FORBIDDEN_START:
forbiddenState = FORBIDDEN_BRACKET;
break;
case FORBIDDEN_BRACKET:
forbiddenState = FORBIDDEN_BRACKET_BRACKET;
break;
case FORBIDDEN_BRACKET_BRACKET:
break;
default:
throw new Error("impossible state");
}
break;
case GREATER:
if (forbiddenState === FORBIDDEN_BRACKET_BRACKET) {
this.fail("the string \"]]>\" is disallowed in char data.");
}
forbiddenState = FORBIDDEN_START;
break;
case NL_LIKE:
if (handler !== undefined) {
this.text += `${chunk.slice(start, this.prevI)}\n`;
}
start = this.i;
forbiddenState = FORBIDDEN_START;
break;
case EOC:
if (handler !== undefined) {
this.text += chunk.slice(start);
}
// eslint-disable-next-line no-labels
break scanLoop;
default:
forbiddenState = FORBIDDEN_START;
}
}
this.forbiddenState = forbiddenState;
}
private handleTextOutsideRoot(): void {
// This is essentially a specialized version of captureTo which is optimized
// for a specialized task. We keep track of the presence of non-space
// characters in the text since these are errors when appearing outside the
// document root element.
let { i: start } = this;
const { chunk, textHandler: handler } = this;
let nonSpace = false;
// eslint-disable-next-line no-labels, no-restricted-syntax
outRootLoop:
// eslint-disable-next-line no-constant-condition
while (true) {
const code = this.getCode();
switch (code) {
case LESS: {
this.state = S_OPEN_WAKA;
if (handler !== undefined) {
const { text } = this;
const slice = chunk.slice(start, this.prevI);
if (text.length !== 0) {
handler(text + slice);
this.text = "";
}
else if (slice.length !== 0) {
handler(slice);
}
}
// eslint-disable-next-line no-labels
break outRootLoop;
}
case AMP:
this.state = S_ENTITY;
this.entityReturnState = S_TEXT;
if (handler !== undefined) {
this.text += chunk.slice(start, this.prevI);
}
nonSpace = true;
// eslint-disable-next-line no-labels
break outRootLoop;
case NL_LIKE:
if (handler !== undefined) {
this.text += `${chunk.slice(start, this.prevI)}\n`;
}
start = this.i;
break;
case EOC:
if (handler !== undefined) {
this.text += chunk.slice(start);
}
// eslint-disable-next-line no-labels
break outRootLoop;
default:
if (!isS(code)) {
nonSpace = true;
}
}
}
if (!nonSpace) {
return;
}
// We use the reportedTextBeforeRoot and reportedTextAfterRoot flags
// to avoid reporting errors for every single character that is out of
// place.
if (!this.sawRoot && !this.reportedTextBeforeRoot) {
this.fail("text data outside of root node.");
this.reportedTextBeforeRoot = true;
}
if (this.closedRoot && !this.reportedTextAfterRoot) {
this.fail("text data outside of root node.");
this.reportedTextAfterRoot = true;
}
}
private pushAttribNS(name: string, value: string): void {
const { prefix, local } = this.qname(name);
const attr = { name, prefix, local, value };
this.attribList.push(attr);
this.attributeHandler?.(attr as AttributeEventForOptions<O>);
if (prefix === "xmlns") {
const trimmed = value.trim();
if (this.currentXMLVersion === "1.0" && trimmed === "") {
this.fail("invalid attempt to undefine prefix in XML 1.0");
}
this.topNS![local] = trimmed;
nsPairCheck(this, local, trimmed);
}
else if (name === "xmlns") {
const trimmed = value.trim();
this.topNS![""] = trimmed;
nsPairCheck(this, "", trimmed);
}
}
private pushAttribPlain(name: string, value: string): void {
const attr = { name, value };
this.attribList.push(attr);
this.attributeHandler?.(attr as AttributeEventForOptions<O>);
}
/**
* End parsing. This performs final well-formedness checks and resets the
* parser to a clean state.
*
* @returns this
*/
private end(): this {
if (!this.sawRoot) {
this.fail("document must contain a root element.");
}
const { tags } = this;
while (tags.length > 0) {
const tag = tags.pop()!;
this.fail(`unclosed tag: ${tag.name}`);
}
if ((this.state !== S_BEGIN) && (this.state !== S_TEXT)) {
this.fail("unexpected end.");
}
const { text } = this;
if (text.length !== 0) {
this.textHandler?.(text);
this.text = "";
}
this._closed = true;
this.endHandler?.();
this._init();
return this;
}
/**
* Resolve a namespace prefix.
*
* @param prefix The prefix to resolve.
*
* @returns The namespace URI or ``undefined`` if the prefix is not defined.
*/
resolve(prefix: string): string | undefined {
let uri = this.topNS![prefix];
if (uri !== undefined) {
return uri;
}
const { tags } = this;
for (let index = tags.length - 1; index >= 0; index--) {
uri = tags[index]!.ns![prefix];
if (uri !== undefined) {
return uri;
}
}
uri = this.ns[prefix];
if (uri !== undefined) {
return uri;
}
return this.opt.resolvePrefix?.(prefix);
}
/**
* Parse a qname into its prefix and local name parts.
*
* @param name The name to parse
*
* @returns
*/
private qname(name: string): { prefix: string; local: string } {
// This is faster than using name.split(":").
const colon = name.indexOf(":");
if (colon === -1) {
return { prefix: "", local: name };
}
const local = name.slice(colon + 1);
const prefix = name.slice(0, colon);
if (prefix === "" || local === "" || local.includes(":")) {
this.fail(`malformed name: ${name}.`);
}
return { prefix, local };
}
private processAttribsNS(): void {
const { attribList } = this;
const tag = this.tag!;
{
// add namespace info to tag
const { prefix, local } = this.qname(tag.name);
tag.prefix = prefix;
tag.local = local;
const uri = tag.uri = this.resolve(prefix) ?? "";
if (prefix !== "") {
if (prefix === "xmlns") {
this.fail("tags may not have \"xmlns\" as prefix.");
}
if (uri === "") {
this.fail(`unbound namespace prefix: ${JSON.stringify(prefix)}.`);
tag.uri = prefix;
}
}
}
if (attribList.length === 0) {
return;
}
const { attributes } = tag;
const seen = new Set();
// Note: do not apply default ns to attributes:
// http://www.w3.org/TR/REC-xml-names/#defaulting
for (const attr of attribList as SaxesAttributeNSIncomplete[]) {
const { name, prefix, local } = attr;
let uri;
let eqname;
if (prefix === "") {
uri = name === "xmlns" ? XMLNS_NAMESPACE : "";
eqname = name;
}
else {
uri = this.resolve(prefix);
// if there's any attributes with an undefined namespace,
// then fail on them now.
if (uri === undefined) {
this.fail(`unbound namespace prefix: ${JSON.stringify(prefix)}.`);
uri = prefix;
}
eqname = `{${uri}}${local}`;
}
if (seen.has(eqname)) {
this.fail(`duplicate attribute: ${eqname}.`);
}
seen.add(eqname);
attr.uri = uri;
attributes[name] = attr;
}
this.attribList = [];
}
private processAttribsPlain(): void {
const { attribList } = this;
// eslint-disable-next-line prefer-destructuring
const attributes = this.tag!.attributes;
for (const { name, value } of attribList) {
if (attributes[name] !== undefined) {
this.fail(`duplicate attribute: ${name}.`);
}
attributes[name] = value;
}
this.attribList = [];
}
/**
* Handle a complete open tag. This parser code calls this once it has seen
* the whole tag. This method checks for well-formeness and then emits
* ``onopentag``.
*/
private openTag(): void {
this.processAttribs();
const { tags } = this;
const tag = this.tag as SaxesTag;
tag.isSelfClosing = false;
// There cannot be any pending text here due to the onopentagstart that was
// necessarily emitted before we get here. So we do not check text.
this.openTagHandler?.(tag as TagForOptions<O>);
tags.push(tag);
this.state = S_TEXT;
this.name = "";
}
/**
* Handle a complete self-closing tag. This parser code calls this once it has
* seen the whole tag. This method checks for well-formeness and then emits
* ``onopentag`` and ``onclosetag``.
*/
private openSelfClosingTag(): void {
this.processAttribs();
const { tags } = this;
const tag = this.tag as SaxesTag;
tag.isSelfClosing = true;
// There cannot be any pending text here due to the onopentagstart that was
// necessarily emitted before we get here. So we do not check text.
this.openTagHandler?.(tag as TagForOptions<O>);
this.closeTagHandler?.(tag as TagForOptions<O>);
const top = this.tag = tags[tags.length - 1] ?? null;
if (top === null) {
this.closedRoot = true;
}
this.state = S_TEXT;
this.name = "";
}
/**
* Handle a complete close tag. This parser code calls this once it has seen
* the whole tag. This method checks for well-formeness and then emits
* ``onclosetag``.
*/
private closeTag(): void {
const { tags, name } = this;
// Our state after this will be S_TEXT, no matter what, and we can clear
// tagName now.
this.state = S_TEXT;
this.name = "";
if (name === "") {
this.fail("weird empty close tag.");
this.text += "</>";
return;
}
const handler = this.closeTagHandler;
let l = tags.length;
while (l-- > 0) {
const tag = this.tag = tags.pop() as SaxesTag;
this.topNS = tag.ns!;
handler?.(tag as TagForOptions<O>);
if (tag.name === name) {
break;
}
this.fail("unexpected close tag.");
}
if (l === 0) {
this.closedRoot = true;
}
else if (l < 0) {
this.fail(`unmatched closing tag: ${name}.`);
this.text += `</${name}>`;
}
}
/**
* Resolves an entity. Makes any necessary well-formedness checks.
*
* @param entity The entity to resolve.
*
* @returns The parsed entity.
*/
private parseEntity(entity: string): string {
// startsWith would be significantly slower for this test.
if (entity[0] !== "#") {
const defined = this.ENTITIES[entity];
if (defined !== undefined) {
return defined;
}
this.fail(this.isName(entity) ? "undefined entity." :
"disallowed character in entity name.");
return `&${entity};`;
}
let num = NaN;
if (entity[1] === "x" && /^#x[0-9a-f]+$/i.test(entity)) {
num = parseInt(entity.slice(2), 16);
}
else if (/^#[0-9]+$/.test(entity)) {
num = parseInt(entity.slice(1), 10);
}
// The character reference is required to match the CHAR production.
if (!this.isChar(num)) {
this.fail("malformed character entity.");
return `&${entity};`;
}
return String.fromCodePoint(num);
}
} |
1,143 | fn(parser: SaxesParser): void {
for (const x of xml) {
parser.write(x);
}
parser.close();
} | class SaxesParser<O extends SaxesOptions = {}> {
private readonly fragmentOpt: boolean;
private readonly xmlnsOpt: boolean;
private readonly trackPosition: boolean;
private readonly fileName?: string;
private readonly nameStartCheck: (c: number) => boolean;
private readonly nameCheck: (c: number) => boolean;
private readonly isName: (name: string) => boolean;
private readonly ns!: Record<string, string>;
private openWakaBang!: string;
private text!: string;
private name!: string;
private piTarget!: string;
private entity!: string;
private q!: null | number;
private tags!: SaxesTagIncomplete[];
private tag!: SaxesTagIncomplete | null;
private topNS!: Record<string, string> | null;
private chunk!: string;
private chunkPosition!: number;
private i!: number;
//
// We use prevI to allow "ungetting" the previously read code point. Note
// however, that it is not safe to unget everything and anything. In
// particular ungetting EOL characters will screw positioning up.
//
// Practically, you must not unget a code which has any side effect beyond
// updating ``this.i`` and ``this.prevI``. Only EOL codes have such side
// effects.
//
private prevI!: number;
private carriedFromPrevious?: string;
private forbiddenState!: number;
private attribList!: (SaxesAttributeNSIncomplete | SaxesAttributePlain)[];
private state!: number;
private reportedTextBeforeRoot!: boolean;
private reportedTextAfterRoot!: boolean;
private closedRoot!: boolean;
private sawRoot!: boolean;
private xmlDeclPossible!: boolean;
private xmlDeclExpects!: string[];
private entityReturnState?: number;
private processAttribs!: (this: this) => void;
private positionAtNewLine!: number;
private doctype!: boolean;
private getCode!: () => number;
private isChar!: (c: number) => boolean;
private pushAttrib!: (name: string, value: string) => void;
private _closed!: boolean;
private currentXMLVersion!: string;
private readonly stateTable: ((this: SaxesParser<O>) => void)[];
private xmldeclHandler?: XMLDeclHandler;
private textHandler?: TextHandler;
private piHandler?: PIHandler;
private doctypeHandler?: DoctypeHandler;
private commentHandler?: CommentHandler;
private openTagStartHandler?: OpenTagStartHandler<O>;
private openTagHandler?: OpenTagHandler<O>;
private closeTagHandler?: CloseTagHandler<O>;
private cdataHandler?: CDataHandler;
private errorHandler?: ErrorHandler;
private endHandler?: EndHandler;
private readyHandler?: ReadyHandler;
private attributeHandler?: AttributeHandler<O>;
/**
* Indicates whether or not the parser is closed. If ``true``, wait for
* the ``ready`` event to write again.
*/
get closed(): boolean {
return this._closed;
}
readonly opt: SaxesOptions;
/**
* The XML declaration for this document.
*/
xmlDecl!: XMLDecl;
/**
* The line number of the next character to be read by the parser. This field
* is one-based. (The first line is numbered 1.)
*/
line!: number;
/**
* The column number of the next character to be read by the parser. *
* This field is zero-based. (The first column is 0.)
*
* This field counts columns by *Unicode character*. Note that this *can*
* be different from the index of the character in a JavaScript string due
* to how JavaScript handles astral plane characters.
*
* See [[columnIndex]] for a number that corresponds to the JavaScript index.
*/
column!: number;
/**
* A map of entity name to expansion.
*/
ENTITIES!: Record<string, string>;
/**
* @param opt The parser options.
*/
constructor(opt?: O) {
this.opt = opt ?? {};
this.fragmentOpt = !!(this.opt.fragment as boolean);
const xmlnsOpt = this.xmlnsOpt = !!(this.opt.xmlns as boolean);
this.trackPosition = this.opt.position !== false;
this.fileName = this.opt.fileName;
if (xmlnsOpt) {
// This is the function we use to perform name checks on PIs and entities.
// When namespaces are used, colons are not allowed in PI target names or
// entity names. So the check depends on whether namespaces are used. See:
//
// https://www.w3.org/XML/xml-names-19990114-errata.html
// NE08
//
this.nameStartCheck = isNCNameStartChar;
this.nameCheck = isNCNameChar;
this.isName = isNCName;
// eslint-disable-next-line @typescript-eslint/unbound-method
this.processAttribs = this.processAttribsNS;
// eslint-disable-next-line @typescript-eslint/unbound-method
this.pushAttrib = this.pushAttribNS;
// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-assignment
this.ns = { __proto__: null as any, ...rootNS };
const additional = this.opt.additionalNamespaces;
if (additional != null) {
nsMappingCheck(this, additional);
Object.assign(this.ns, additional);
}
}
else {
this.nameStartCheck = isNameStartChar;
this.nameCheck = isNameChar;
this.isName = isName;
// eslint-disable-next-line @typescript-eslint/unbound-method
this.processAttribs = this.processAttribsPlain;
// eslint-disable-next-line @typescript-eslint/unbound-method
this.pushAttrib = this.pushAttribPlain;
}
//
// The order of the members in this table needs to correspond to the state
// numbers given to the states that correspond to the methods being recorded
// here.
//
this.stateTable = [
/* eslint-disable @typescript-eslint/unbound-method */
this.sBegin,
this.sBeginWhitespace,
this.sDoctype,
this.sDoctypeQuote,
this.sDTD,
this.sDTDQuoted,
this.sDTDOpenWaka,
this.sDTDOpenWakaBang,
this.sDTDComment,
this.sDTDCommentEnding,
this.sDTDCommentEnded,
this.sDTDPI,
this.sDTDPIEnding,
this.sText,
this.sEntity,
this.sOpenWaka,
this.sOpenWakaBang,
this.sComment,
this.sCommentEnding,
this.sCommentEnded,
this.sCData,
this.sCDataEnding,
this.sCDataEnding2,
this.sPIFirstChar,
this.sPIRest,
this.sPIBody,
this.sPIEnding,
this.sXMLDeclNameStart,
this.sXMLDeclName,
this.sXMLDeclEq,
this.sXMLDeclValueStart,
this.sXMLDeclValue,
this.sXMLDeclSeparator,
this.sXMLDeclEnding,
this.sOpenTag,
this.sOpenTagSlash,
this.sAttrib,
this.sAttribName,
this.sAttribNameSawWhite,
this.sAttribValue,
this.sAttribValueQuoted,
this.sAttribValueClosed,
this.sAttribValueUnquoted,
this.sCloseTag,
this.sCloseTagSawWhite,
/* eslint-enable @typescript-eslint/unbound-method */
];
this._init();
}
_init(): void {
this.openWakaBang = "";
this.text = "";
this.name = "";
this.piTarget = "";
this.entity = "";
this.q = null;
this.tags = [];
this.tag = null;
this.topNS = null;
this.chunk = "";
this.chunkPosition = 0;
this.i = 0;
this.prevI = 0;
this.carriedFromPrevious = undefined;
this.forbiddenState = FORBIDDEN_START;
this.attribList = [];
// The logic is organized so as to minimize the need to check
// this.opt.fragment while parsing.
const { fragmentOpt } = this;
this.state = fragmentOpt ? S_TEXT : S_BEGIN;
// We want these to be all true if we are dealing with a fragment.
this.reportedTextBeforeRoot = this.reportedTextAfterRoot = this.closedRoot =
this.sawRoot = fragmentOpt;
// An XML declaration is intially possible only when parsing whole
// documents.
this.xmlDeclPossible = !fragmentOpt;
this.xmlDeclExpects = ["version"];
this.entityReturnState = undefined;
let { defaultXMLVersion } = this.opt;
if (defaultXMLVersion === undefined) {
if (this.opt.forceXMLVersion === true) {
throw new Error("forceXMLVersion set but defaultXMLVersion is not set");
}
defaultXMLVersion = "1.0";
}
this.setXMLVersion(defaultXMLVersion);
this.positionAtNewLine = 0;
this.doctype = false;
this._closed = false;
this.xmlDecl = {
version: undefined,
encoding: undefined,
standalone: undefined,
};
this.line = 1;
this.column = 0;
this.ENTITIES = Object.create(XML_ENTITIES) as Record<string, string>;
this.readyHandler?.();
}
/**
* The stream position the parser is currently looking at. This field is
* zero-based.
*
* This field is not based on counting Unicode characters but is to be
* interpreted as a plain index into a JavaScript string.
*/
get position(): number {
return this.chunkPosition + this.i;
}
/**
* The column number of the next character to be read by the parser. *
* This field is zero-based. (The first column in a line is 0.)
*
* This field reports the index at which the next character would be in the
* line if the line were represented as a JavaScript string. Note that this
* *can* be different to a count based on the number of *Unicode characters*
* due to how JavaScript handles astral plane characters.
*
* See [[column]] for a number that corresponds to a count of Unicode
* characters.
*/
get columnIndex(): number {
return this.position - this.positionAtNewLine;
}
/**
* Set an event listener on an event. The parser supports one handler per
* event type. If you try to set an event handler over an existing handler,
* the old handler is silently overwritten.
*
* @param name The event to listen to.
*
* @param handler The handler to set.
*/
on<N extends EventName>(name: N, handler: EventNameToHandler<O, N>): void {
// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-member-access
(this as any)[EVENT_NAME_TO_HANDLER_NAME[name]] = handler;
}
/**
* Unset an event handler.
*
* @parma name The event to stop listening to.
*/
off(name: EventName): void {
// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-member-access
(this as any)[EVENT_NAME_TO_HANDLER_NAME[name]] = undefined;
}
/**
* Make an error object. The error object will have a message that contains
* the ``fileName`` option passed at the creation of the parser. If position
* tracking was turned on, it will also have line and column number
* information.
*
* @param message The message describing the error to report.
*
* @returns An error object with a properly formatted message.
*/
makeError(message: string): Error {
let msg = this.fileName ?? "";
if (this.trackPosition) {
if (msg.length > 0) {
msg += ":";
}
msg += `${this.line}:${this.column}`;
}
if (msg.length > 0) {
msg += ": ";
}
return new Error(msg + message);
}
/**
* Report a parsing error. This method is made public so that client code may
* check for issues that are outside the scope of this project and can report
* errors.
*
* @param message The error to report.
*
* @returns this
*/
fail(message: string): this {
const err = this.makeError(message);
const handler = this.errorHandler;
if (handler === undefined) {
throw err;
}
else {
handler(err);
}
return this;
}
/**
* Write a XML data to the parser.
*
* @param chunk The XML data to write.
*
* @returns this
*/
// We do need object for the type here. Yes, it often causes problems
// but not in this case.
write(chunk: string | object | null): this {
if (this.closed) {
return this.fail("cannot write after close; assign an onready handler.");
}
let end = false;
if (chunk === null) {
// We cannot return immediately because carriedFromPrevious may need
// processing.
end = true;
chunk = "";
}
else if (typeof chunk === "object") {
chunk = chunk.toString();
}
// We checked if performing a pre-decomposition of the string into an array
// of single complete characters (``Array.from(chunk)``) would be faster
// than the current repeated calls to ``charCodeAt``. As of August 2018, it
// isn't. (There may be Node-specific code that would perform faster than
// ``Array.from`` but don't want to be dependent on Node.)
if (this.carriedFromPrevious !== undefined) {
// The previous chunk had char we must carry over.
chunk = `${this.carriedFromPrevious}${chunk}`;
this.carriedFromPrevious = undefined;
}
let limit = chunk.length;
const lastCode = chunk.charCodeAt(limit - 1);
if (!end &&
// A trailing CR or surrogate must be carried over to the next
// chunk.
(lastCode === CR || (lastCode >= 0xD800 && lastCode <= 0xDBFF))) {
// The chunk ends with a character that must be carried over. We cannot
// know how to handle it until we get the next chunk or the end of the
// stream. So save it for later.
this.carriedFromPrevious = chunk[limit - 1];
limit--;
chunk = chunk.slice(0, limit);
}
const { stateTable } = this;
this.chunk = chunk;
this.i = 0;
while (this.i < limit) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-argument
stateTable[this.state].call(this as any);
}
this.chunkPosition += limit;
return end ? this.end() : this;
}
/**
* Close the current stream. Perform final well-formedness checks and reset
* the parser tstate.
*
* @returns this
*/
close(): this {
return this.write(null);
}
/**
* Get a single code point out of the current chunk. This updates the current
* position if we do position tracking.
*
* This is the algorithm to use for XML 1.0.
*
* @returns The character read.
*/
private getCode10(): number {
const { chunk, i } = this;
this.prevI = i;
// Yes, we do this instead of doing this.i++. Doing it this way, we do not
// read this.i again, which is a bit faster.
this.i = i + 1;
if (i >= chunk.length) {
return EOC;
}
// Using charCodeAt and handling the surrogates ourselves is faster
// than using codePointAt.
const code = chunk.charCodeAt(i);
this.column++;
if (code < 0xD800) {
if (code >= SPACE || code === TAB) {
return code;
}
switch (code) {
case NL:
this.line++;
this.column = 0;
this.positionAtNewLine = this.position;
return NL;
case CR:
// We may get NaN if we read past the end of the chunk, which is fine.
if (chunk.charCodeAt(i + 1) === NL) {
// A \r\n sequence is converted to \n so we have to skip over the
// next character. We already know it has a size of 1 so ++ is fine
// here.
this.i = i + 2;
}
// Otherwise, a \r is just converted to \n, so we don't have to skip
// ahead.
// In either case, \r becomes \n.
this.line++;
this.column = 0;
this.positionAtNewLine = this.position;
return NL_LIKE;
default:
// If we get here, then code < SPACE and it is not NL CR or TAB.
this.fail("disallowed character.");
return code;
}
}
if (code > 0xDBFF) {
// This is a specialized version of isChar10 that takes into account
// that in this context code > 0xDBFF and code <= 0xFFFF. So it does not
// test cases that don't need testing.
if (!(code >= 0xE000 && code <= 0xFFFD)) {
this.fail("disallowed character.");
}
return code;
}
const final = 0x10000 + ((code - 0xD800) * 0x400) +
(chunk.charCodeAt(i + 1) - 0xDC00);
this.i = i + 2;
// This is a specialized version of isChar10 that takes into account that in
// this context necessarily final >= 0x10000.
if (final > 0x10FFFF) {
this.fail("disallowed character.");
}
return final;
}
/**
* Get a single code point out of the current chunk. This updates the current
* position if we do position tracking.
*
* This is the algorithm to use for XML 1.1.
*
* @returns {number} The character read.
*/
private getCode11(): number {
const { chunk, i } = this;
this.prevI = i;
// Yes, we do this instead of doing this.i++. Doing it this way, we do not
// read this.i again, which is a bit faster.
this.i = i + 1;
if (i >= chunk.length) {
return EOC;
}
// Using charCodeAt and handling the surrogates ourselves is faster
// than using codePointAt.
const code = chunk.charCodeAt(i);
this.column++;
if (code < 0xD800) {
if ((code > 0x1F && code < 0x7F) || (code > 0x9F && code !== LS) ||
code === TAB) {
return code;
}
switch (code) {
case NL: // 0xA
this.line++;
this.column = 0;
this.positionAtNewLine = this.position;
return NL;
case CR: { // 0xD
// We may get NaN if we read past the end of the chunk, which is
// fine.
const next = chunk.charCodeAt(i + 1);
if (next === NL || next === NEL) {
// A CR NL or CR NEL sequence is converted to NL so we have to skip
// over the next character. We already know it has a size of 1.
this.i = i + 2;
}
// Otherwise, a CR is just converted to NL, no skip.
}
/* yes, fall through */
case NEL: // 0x85
case LS: // Ox2028
this.line++;
this.column = 0;
this.positionAtNewLine = this.position;
return NL_LIKE;
default:
this.fail("disallowed character.");
return code;
}
}
if (code > 0xDBFF) {
// This is a specialized version of isCharAndNotRestricted that takes into
// account that in this context code > 0xDBFF and code <= 0xFFFF. So it
// does not test cases that don't need testing.
if (!(code >= 0xE000 && code <= 0xFFFD)) {
this.fail("disallowed character.");
}
return code;
}
const final = 0x10000 + ((code - 0xD800) * 0x400) +
(chunk.charCodeAt(i + 1) - 0xDC00);
this.i = i + 2;
// This is a specialized version of isCharAndNotRestricted that takes into
// account that in this context necessarily final >= 0x10000.
if (final > 0x10FFFF) {
this.fail("disallowed character.");
}
return final;
}
/**
* Like ``getCode`` but with the return value normalized so that ``NL`` is
* returned for ``NL_LIKE``.
*/
private getCodeNorm(): number {
const c = this.getCode();
return c === NL_LIKE ? NL : c;
}
private unget(): void {
this.i = this.prevI;
this.column--;
}
/**
* Capture characters into a buffer until encountering one of a set of
* characters.
*
* @param chars An array of codepoints. Encountering a character in the array
* ends the capture. (``chars`` may safely contain ``NL``.)
*
* @return The character code that made the capture end, or ``EOC`` if we hit
* the end of the chunk. The return value cannot be NL_LIKE: NL is returned
* instead.
*/
private captureTo(chars: number[]): number {
let { i: start } = this;
const { chunk } = this;
// eslint-disable-next-line no-constant-condition
while (true) {
const c = this.getCode();
const isNLLike = c === NL_LIKE;
const final = isNLLike ? NL : c;
if (final === EOC || chars.includes(final)) {
this.text += chunk.slice(start, this.prevI);
return final;
}
if (isNLLike) {
this.text += `${chunk.slice(start, this.prevI)}\n`;
start = this.i;
}
}
}
/**
* Capture characters into a buffer until encountering a character.
*
* @param char The codepoint that ends the capture. **NOTE ``char`` MAY NOT
* CONTAIN ``NL``.** Passing ``NL`` will result in buggy behavior.
*
* @return ``true`` if we ran into the character. Otherwise, we ran into the
* end of the current chunk.
*/
private captureToChar(char: number): boolean {
let { i: start } = this;
const { chunk } = this;
// eslint-disable-next-line no-constant-condition
while (true) {
let c = this.getCode();
switch (c) {
case NL_LIKE:
this.text += `${chunk.slice(start, this.prevI)}\n`;
start = this.i;
c = NL;
break;
case EOC:
this.text += chunk.slice(start);
return false;
default:
}
if (c === char) {
this.text += chunk.slice(start, this.prevI);
return true;
}
}
}
/**
* Capture characters that satisfy ``isNameChar`` into the ``name`` field of
* this parser.
*
* @return The character code that made the test fail, or ``EOC`` if we hit
* the end of the chunk. The return value cannot be NL_LIKE: NL is returned
* instead.
*/
private captureNameChars(): number {
const { chunk, i: start } = this;
// eslint-disable-next-line no-constant-condition
while (true) {
const c = this.getCode();
if (c === EOC) {
this.name += chunk.slice(start);
return EOC;
}
// NL is not a name char so we don't have to test specifically for it.
if (!isNameChar(c)) {
this.name += chunk.slice(start, this.prevI);
return c === NL_LIKE ? NL : c;
}
}
}
/**
* Skip white spaces.
*
* @return The character that ended the skip, or ``EOC`` if we hit
* the end of the chunk. The return value cannot be NL_LIKE: NL is returned
* instead.
*/
private skipSpaces(): number {
// eslint-disable-next-line no-constant-condition
while (true) {
const c = this.getCodeNorm();
if (c === EOC || !isS(c)) {
return c;
}
}
}
private setXMLVersion(version: string): void {
this.currentXMLVersion = version;
/* eslint-disable @typescript-eslint/unbound-method */
if (version === "1.0") {
this.isChar = isChar10;
this.getCode = this.getCode10;
}
else {
this.isChar = isChar11;
this.getCode = this.getCode11;
}
/* eslint-enable @typescript-eslint/unbound-method */
}
// STATE ENGINE METHODS
// This needs to be a state separate from S_BEGIN_WHITESPACE because we want
// to be sure never to come back to this state later.
private sBegin(): void {
// We are essentially peeking at the first character of the chunk. Since
// S_BEGIN can be in effect only when we start working on the first chunk,
// the index at which we must look is necessarily 0. Note also that the
// following test does not depend on decoding surrogates.
// If the initial character is 0xFEFF, ignore it.
if (this.chunk.charCodeAt(0) === 0xFEFF) {
this.i++;
this.column++;
}
this.state = S_BEGIN_WHITESPACE;
}
private sBeginWhitespace(): void {
// We need to know whether we've encountered spaces or not because as soon
// as we run into a space, an XML declaration is no longer possible. Rather
// than slow down skipSpaces even in places where we don't care whether it
// skipped anything or not, we check whether prevI is equal to the value of
// i from before we skip spaces.
const iBefore = this.i;
const c = this.skipSpaces();
if (this.prevI !== iBefore) {
this.xmlDeclPossible = false;
}
switch (c) {
case LESS:
this.state = S_OPEN_WAKA;
// We could naively call closeText but in this state, it is not normal
// to have text be filled with any data.
if (this.text.length !== 0) {
throw new Error("no-empty text at start");
}
break;
case EOC:
break;
default:
this.unget();
this.state = S_TEXT;
this.xmlDeclPossible = false;
}
}
private sDoctype(): void {
const c = this.captureTo(DOCTYPE_TERMINATOR);
switch (c) {
case GREATER: {
this.doctypeHandler?.(this.text);
this.text = "";
this.state = S_TEXT;
this.doctype = true; // just remember that we saw it.
break;
}
case EOC:
break;
default:
this.text += String.fromCodePoint(c);
if (c === OPEN_BRACKET) {
this.state = S_DTD;
}
else if (isQuote(c)) {
this.state = S_DOCTYPE_QUOTE;
this.q = c;
}
}
}
private sDoctypeQuote(): void {
const q = this.q!;
if (this.captureToChar(q)) {
this.text += String.fromCodePoint(q);
this.q = null;
this.state = S_DOCTYPE;
}
}
private sDTD(): void {
const c = this.captureTo(DTD_TERMINATOR);
if (c === EOC) {
return;
}
this.text += String.fromCodePoint(c);
if (c === CLOSE_BRACKET) {
this.state = S_DOCTYPE;
}
else if (c === LESS) {
this.state = S_DTD_OPEN_WAKA;
}
else if (isQuote(c)) {
this.state = S_DTD_QUOTED;
this.q = c;
}
}
private sDTDQuoted(): void {
const q = this.q!;
if (this.captureToChar(q)) {
this.text += String.fromCodePoint(q);
this.state = S_DTD;
this.q = null;
}
}
private sDTDOpenWaka(): void {
const c = this.getCodeNorm();
this.text += String.fromCodePoint(c);
switch (c) {
case BANG:
this.state = S_DTD_OPEN_WAKA_BANG;
this.openWakaBang = "";
break;
case QUESTION:
this.state = S_DTD_PI;
break;
default:
this.state = S_DTD;
}
}
private sDTDOpenWakaBang(): void {
const char = String.fromCodePoint(this.getCodeNorm());
const owb = this.openWakaBang += char;
this.text += char;
if (owb !== "-") {
this.state = owb === "--" ? S_DTD_COMMENT : S_DTD;
this.openWakaBang = "";
}
}
private sDTDComment(): void {
if (this.captureToChar(MINUS)) {
this.text += "-";
this.state = S_DTD_COMMENT_ENDING;
}
}
private sDTDCommentEnding(): void {
const c = this.getCodeNorm();
this.text += String.fromCodePoint(c);
this.state = c === MINUS ? S_DTD_COMMENT_ENDED : S_DTD_COMMENT;
}
private sDTDCommentEnded(): void {
const c = this.getCodeNorm();
this.text += String.fromCodePoint(c);
if (c === GREATER) {
this.state = S_DTD;
}
else {
this.fail("malformed comment.");
// <!-- blah -- bloo --> will be recorded as
// a comment of " blah -- bloo "
this.state = S_DTD_COMMENT;
}
}
private sDTDPI(): void {
if (this.captureToChar(QUESTION)) {
this.text += "?";
this.state = S_DTD_PI_ENDING;
}
}
private sDTDPIEnding(): void {
const c = this.getCodeNorm();
this.text += String.fromCodePoint(c);
if (c === GREATER) {
this.state = S_DTD;
}
}
private sText(): void {
//
// We did try a version of saxes where the S_TEXT state was split in two
// states: one for text inside the root element, and one for text
// outside. This was avoiding having to test this.tags.length to decide
// what implementation to actually use.
//
// Peformance testing on gigabyte-size files did not show any advantage to
// using the two states solution instead of the current one. Conversely, it
// made the code a bit more complicated elsewhere. For instance, a comment
// can appear before the root element so when a comment ended it was
// necessary to determine whether to return to the S_TEXT state or to the
// new text-outside-root state.
//
if (this.tags.length !== 0) {
this.handleTextInRoot();
}
else {
this.handleTextOutsideRoot();
}
}
private sEntity(): void {
// This is essentially a specialized version of captureToChar(SEMICOLON...)
let { i: start } = this;
const { chunk } = this;
// eslint-disable-next-line no-labels, no-restricted-syntax
loop:
// eslint-disable-next-line no-constant-condition
while (true) {
switch (this.getCode()) {
case NL_LIKE:
this.entity += `${chunk.slice(start, this.prevI)}\n`;
start = this.i;
break;
case SEMICOLON: {
const { entityReturnState } = this;
const entity = this.entity + chunk.slice(start, this.prevI);
this.state = entityReturnState!;
let parsed: string;
if (entity === "") {
this.fail("empty entity name.");
parsed = "&;";
}
else {
parsed = this.parseEntity(entity);
this.entity = "";
}
if (entityReturnState !== S_TEXT || this.textHandler !== undefined) {
this.text += parsed;
}
// eslint-disable-next-line no-labels
break loop;
}
case EOC:
this.entity += chunk.slice(start);
// eslint-disable-next-line no-labels
break loop;
default:
}
}
}
private sOpenWaka(): void {
// Reminder: a state handler is called with at least one character
// available in the current chunk. So the first call to get code inside of
// a state handler cannot return ``EOC``. That's why we don't test
// for it.
const c = this.getCode();
// either a /, ?, !, or text is coming next.
if (isNameStartChar(c)) {
this.state = S_OPEN_TAG;
this.unget();
this.xmlDeclPossible = false;
}
else {
switch (c) {
case FORWARD_SLASH:
this.state = S_CLOSE_TAG;
this.xmlDeclPossible = false;
break;
case BANG:
this.state = S_OPEN_WAKA_BANG;
this.openWakaBang = "";
this.xmlDeclPossible = false;
break;
case QUESTION:
this.state = S_PI_FIRST_CHAR;
break;
default:
this.fail("disallowed character in tag name");
this.state = S_TEXT;
this.xmlDeclPossible = false;
}
}
}
private sOpenWakaBang(): void {
this.openWakaBang += String.fromCodePoint(this.getCodeNorm());
switch (this.openWakaBang) {
case "[CDATA[":
if (!this.sawRoot && !this.reportedTextBeforeRoot) {
this.fail("text data outside of root node.");
this.reportedTextBeforeRoot = true;
}
if (this.closedRoot && !this.reportedTextAfterRoot) {
this.fail("text data outside of root node.");
this.reportedTextAfterRoot = true;
}
this.state = S_CDATA;
this.openWakaBang = "";
break;
case "--":
this.state = S_COMMENT;
this.openWakaBang = "";
break;
case "DOCTYPE":
this.state = S_DOCTYPE;
if (this.doctype || this.sawRoot) {
this.fail("inappropriately located doctype declaration.");
}
this.openWakaBang = "";
break;
default:
// 7 happens to be the maximum length of the string that can possibly
// match one of the cases above.
if (this.openWakaBang.length >= 7) {
this.fail("incorrect syntax.");
}
}
}
private sComment(): void {
if (this.captureToChar(MINUS)) {
this.state = S_COMMENT_ENDING;
}
}
private sCommentEnding(): void {
const c = this.getCodeNorm();
if (c === MINUS) {
this.state = S_COMMENT_ENDED;
this.commentHandler?.(this.text);
this.text = "";
}
else {
this.text += `-${String.fromCodePoint(c)}`;
this.state = S_COMMENT;
}
}
private sCommentEnded(): void {
const c = this.getCodeNorm();
if (c !== GREATER) {
this.fail("malformed comment.");
// <!-- blah -- bloo --> will be recorded as
// a comment of " blah -- bloo "
this.text += `--${String.fromCodePoint(c)}`;
this.state = S_COMMENT;
}
else {
this.state = S_TEXT;
}
}
private sCData(): void {
if (this.captureToChar(CLOSE_BRACKET)) {
this.state = S_CDATA_ENDING;
}
}
private sCDataEnding(): void {
const c = this.getCodeNorm();
if (c === CLOSE_BRACKET) {
this.state = S_CDATA_ENDING_2;
}
else {
this.text += `]${String.fromCodePoint(c)}`;
this.state = S_CDATA;
}
}
private sCDataEnding2(): void {
const c = this.getCodeNorm();
switch (c) {
case GREATER: {
this.cdataHandler?.(this.text);
this.text = "";
this.state = S_TEXT;
break;
}
case CLOSE_BRACKET:
this.text += "]";
break;
default:
this.text += `]]${String.fromCodePoint(c)}`;
this.state = S_CDATA;
}
}
// We need this separate state to check the first character fo the pi target
// with this.nameStartCheck which allows less characters than this.nameCheck.
private sPIFirstChar(): void {
const c = this.getCodeNorm();
// This is first because in the case where the file is well-formed this is
// the branch taken. We optimize for well-formedness.
if (this.nameStartCheck(c)) {
this.piTarget += String.fromCodePoint(c);
this.state = S_PI_REST;
}
else if (c === QUESTION || isS(c)) {
this.fail("processing instruction without a target.");
this.state = c === QUESTION ? S_PI_ENDING : S_PI_BODY;
}
else {
this.fail("disallowed character in processing instruction name.");
this.piTarget += String.fromCodePoint(c);
this.state = S_PI_REST;
}
}
private sPIRest(): void {
// Capture characters into a piTarget while ``this.nameCheck`` run on the
// character read returns true.
const { chunk, i: start } = this;
// eslint-disable-next-line no-constant-condition
while (true) {
const c = this.getCodeNorm();
if (c === EOC) {
this.piTarget += chunk.slice(start);
return;
}
// NL cannot satisfy this.nameCheck so we don't have to test specifically
// for it.
if (!this.nameCheck(c)) {
this.piTarget += chunk.slice(start, this.prevI);
const isQuestion = c === QUESTION;
if (isQuestion || isS(c)) {
if (this.piTarget === "xml") {
if (!this.xmlDeclPossible) {
this.fail(
"an XML declaration must be at the start of the document.");
}
this.state = isQuestion ? S_XML_DECL_ENDING : S_XML_DECL_NAME_START;
}
else {
this.state = isQuestion ? S_PI_ENDING : S_PI_BODY;
}
}
else {
this.fail("disallowed character in processing instruction name.");
this.piTarget += String.fromCodePoint(c);
}
break;
}
}
}
private sPIBody(): void {
if (this.text.length === 0) {
const c = this.getCodeNorm();
if (c === QUESTION) {
this.state = S_PI_ENDING;
}
else if (!isS(c)) {
this.text = String.fromCodePoint(c);
}
}
// The question mark character is not valid inside any of the XML
// declaration name/value pairs.
else if (this.captureToChar(QUESTION)) {
this.state = S_PI_ENDING;
}
}
private sPIEnding(): void {
const c = this.getCodeNorm();
if (c === GREATER) {
const { piTarget } = this;
if (piTarget.toLowerCase() === "xml") {
this.fail(
"the XML declaration must appear at the start of the document.");
}
this.piHandler?.({
target: piTarget,
body: this.text,
});
this.piTarget = this.text = "";
this.state = S_TEXT;
}
else if (c === QUESTION) {
// We ran into ?? as part of a processing instruction. We initially took
// the first ? as a sign that the PI was ending, but it is not. So we have
// to add it to the body but we take the new ? as a sign that the PI is
// ending.
this.text += "?";
}
else {
this.text += `?${String.fromCodePoint(c)}`;
this.state = S_PI_BODY;
}
this.xmlDeclPossible = false;
}
private sXMLDeclNameStart(): void {
const c = this.skipSpaces();
// The question mark character is not valid inside any of the XML
// declaration name/value pairs.
if (c === QUESTION) {
// It is valid to go to S_XML_DECL_ENDING from this state.
this.state = S_XML_DECL_ENDING;
return;
}
if (c !== EOC) {
this.state = S_XML_DECL_NAME;
this.name = String.fromCodePoint(c);
}
}
private sXMLDeclName(): void {
const c = this.captureTo(XML_DECL_NAME_TERMINATOR);
// The question mark character is not valid inside any of the XML
// declaration name/value pairs.
if (c === QUESTION) {
this.state = S_XML_DECL_ENDING;
this.name += this.text;
this.text = "";
this.fail("XML declaration is incomplete.");
return;
}
if (!(isS(c) || c === EQUAL)) {
return;
}
this.name += this.text;
this.text = "";
if (!this.xmlDeclExpects.includes(this.name)) {
switch (this.name.length) {
case 0:
this.fail("did not expect any more name/value pairs.");
break;
case 1:
this.fail(`expected the name ${this.xmlDeclExpects[0]}.`);
break;
default:
this.fail(`expected one of ${this.xmlDeclExpects.join(", ")}`);
}
}
this.state = c === EQUAL ? S_XML_DECL_VALUE_START : S_XML_DECL_EQ;
}
private sXMLDeclEq(): void {
const c = this.getCodeNorm();
// The question mark character is not valid inside any of the XML
// declaration name/value pairs.
if (c === QUESTION) {
this.state = S_XML_DECL_ENDING;
this.fail("XML declaration is incomplete.");
return;
}
if (isS(c)) {
return;
}
if (c !== EQUAL) {
this.fail("value required.");
}
this.state = S_XML_DECL_VALUE_START;
}
private sXMLDeclValueStart(): void {
const c = this.getCodeNorm();
// The question mark character is not valid inside any of the XML
// declaration name/value pairs.
if (c === QUESTION) {
this.state = S_XML_DECL_ENDING;
this.fail("XML declaration is incomplete.");
return;
}
if (isS(c)) {
return;
}
if (!isQuote(c)) {
this.fail("value must be quoted.");
this.q = SPACE;
}
else {
this.q = c;
}
this.state = S_XML_DECL_VALUE;
}
private sXMLDeclValue(): void {
const c = this.captureTo([this.q!, QUESTION]);
// The question mark character is not valid inside any of the XML
// declaration name/value pairs.
if (c === QUESTION) {
this.state = S_XML_DECL_ENDING;
this.text = "";
this.fail("XML declaration is incomplete.");
return;
}
if (c === EOC) {
return;
}
const value = this.text;
this.text = "";
switch (this.name) {
case "version": {
this.xmlDeclExpects = ["encoding", "standalone"];
const version = value;
this.xmlDecl.version = version;
// This is the test specified by XML 1.0 but it is fine for XML 1.1.
if (!/^1\.[0-9]+$/.test(version)) {
this.fail("version number must match /^1\\.[0-9]+$/.");
}
// When forceXMLVersion is set, the XML declaration is ignored.
else if (!(this.opt.forceXMLVersion as boolean)) {
this.setXMLVersion(version);
}
break;
}
case "encoding":
if (!/^[A-Za-z][A-Za-z0-9._-]*$/.test(value)) {
this.fail("encoding value must match \
/^[A-Za-z0-9][A-Za-z0-9._-]*$/.");
}
this.xmlDeclExpects = ["standalone"];
this.xmlDecl.encoding = value;
break;
case "standalone":
if (value !== "yes" && value !== "no") {
this.fail("standalone value must match \"yes\" or \"no\".");
}
this.xmlDeclExpects = [];
this.xmlDecl.standalone = value;
break;
default:
// We don't need to raise an error here since we've already raised one
// when checking what name was expected.
}
this.name = "";
this.state = S_XML_DECL_SEPARATOR;
}
private sXMLDeclSeparator(): void {
const c = this.getCodeNorm();
// The question mark character is not valid inside any of the XML
// declaration name/value pairs.
if (c === QUESTION) {
// It is valid to go to S_XML_DECL_ENDING from this state.
this.state = S_XML_DECL_ENDING;
return;
}
if (!isS(c)) {
this.fail("whitespace required.");
this.unget();
}
this.state = S_XML_DECL_NAME_START;
}
private sXMLDeclEnding(): void {
const c = this.getCodeNorm();
if (c === GREATER) {
if (this.piTarget !== "xml") {
this.fail("processing instructions are not allowed before root.");
}
else if (this.name !== "version" &&
this.xmlDeclExpects.includes("version")) {
this.fail("XML declaration must contain a version.");
}
this.xmldeclHandler?.(this.xmlDecl);
this.name = "";
this.piTarget = this.text = "";
this.state = S_TEXT;
}
else {
// We got here because the previous character was a ?, but the question
// mark character is not valid inside any of the XML declaration
// name/value pairs.
this.fail(
"The character ? is disallowed anywhere in XML declarations.");
}
this.xmlDeclPossible = false;
}
private sOpenTag(): void {
const c = this.captureNameChars();
if (c === EOC) {
return;
}
const tag: SaxesTagIncomplete = this.tag = {
name: this.name,
attributes: Object.create(null) as Record<string, string>,
};
this.name = "";
if (this.xmlnsOpt) {
this.topNS = tag.ns = Object.create(null) as Record<string, string>;
}
this.openTagStartHandler?.(tag as StartTagForOptions<O>);
this.sawRoot = true;
if (!this.fragmentOpt && this.closedRoot) {
this.fail("documents may contain only one root.");
}
switch (c) {
case GREATER:
this.openTag();
break;
case FORWARD_SLASH:
this.state = S_OPEN_TAG_SLASH;
break;
default:
if (!isS(c)) {
this.fail("disallowed character in tag name.");
}
this.state = S_ATTRIB;
}
}
private sOpenTagSlash(): void {
if (this.getCode() === GREATER) {
this.openSelfClosingTag();
}
else {
this.fail("forward-slash in opening tag not followed by >.");
this.state = S_ATTRIB;
}
}
private sAttrib(): void {
const c = this.skipSpaces();
if (c === EOC) {
return;
}
if (isNameStartChar(c)) {
this.unget();
this.state = S_ATTRIB_NAME;
}
else if (c === GREATER) {
this.openTag();
}
else if (c === FORWARD_SLASH) {
this.state = S_OPEN_TAG_SLASH;
}
else {
this.fail("disallowed character in attribute name.");
}
}
private sAttribName(): void {
const c = this.captureNameChars();
if (c === EQUAL) {
this.state = S_ATTRIB_VALUE;
}
else if (isS(c)) {
this.state = S_ATTRIB_NAME_SAW_WHITE;
}
else if (c === GREATER) {
this.fail("attribute without value.");
this.pushAttrib(this.name, this.name);
this.name = this.text = "";
this.openTag();
}
else if (c !== EOC) {
this.fail("disallowed character in attribute name.");
}
}
private sAttribNameSawWhite(): void {
const c = this.skipSpaces();
switch (c) {
case EOC:
return;
case EQUAL:
this.state = S_ATTRIB_VALUE;
break;
default:
this.fail("attribute without value.");
// Should we do this???
// this.tag.attributes[this.name] = "";
this.text = "";
this.name = "";
if (c === GREATER) {
this.openTag();
}
else if (isNameStartChar(c)) {
this.unget();
this.state = S_ATTRIB_NAME;
}
else {
this.fail("disallowed character in attribute name.");
this.state = S_ATTRIB;
}
}
}
private sAttribValue(): void {
const c = this.getCodeNorm();
if (isQuote(c)) {
this.q = c;
this.state = S_ATTRIB_VALUE_QUOTED;
}
else if (!isS(c)) {
this.fail("unquoted attribute value.");
this.state = S_ATTRIB_VALUE_UNQUOTED;
this.unget();
}
}
private sAttribValueQuoted(): void {
// We deliberately do not use captureTo here. The specialized code we use
// here is faster than using captureTo.
const { q, chunk } = this;
let { i: start } = this;
// eslint-disable-next-line no-constant-condition
while (true) {
switch (this.getCode()) {
case q:
this.pushAttrib(this.name,
this.text + chunk.slice(start, this.prevI));
this.name = this.text = "";
this.q = null;
this.state = S_ATTRIB_VALUE_CLOSED;
return;
case AMP:
this.text += chunk.slice(start, this.prevI);
this.state = S_ENTITY;
this.entityReturnState = S_ATTRIB_VALUE_QUOTED;
return;
case NL:
case NL_LIKE:
case TAB:
this.text += `${chunk.slice(start, this.prevI)} `;
start = this.i;
break;
case LESS:
this.text += chunk.slice(start, this.prevI);
this.fail("disallowed character.");
return;
case EOC:
this.text += chunk.slice(start);
return;
default:
}
}
}
private sAttribValueClosed(): void {
const c = this.getCodeNorm();
if (isS(c)) {
this.state = S_ATTRIB;
}
else if (c === GREATER) {
this.openTag();
}
else if (c === FORWARD_SLASH) {
this.state = S_OPEN_TAG_SLASH;
}
else if (isNameStartChar(c)) {
this.fail("no whitespace between attributes.");
this.unget();
this.state = S_ATTRIB_NAME;
}
else {
this.fail("disallowed character in attribute name.");
}
}
private sAttribValueUnquoted(): void {
// We don't do anything regarding EOL or space handling for unquoted
// attributes. We already have failed by the time we get here, and the
// contract that saxes upholds states that upon failure, it is not safe to
// rely on the data passed to event handlers (other than
// ``onerror``). Passing "bad" data is not a problem.
const c = this.captureTo(ATTRIB_VALUE_UNQUOTED_TERMINATOR);
switch (c) {
case AMP:
this.state = S_ENTITY;
this.entityReturnState = S_ATTRIB_VALUE_UNQUOTED;
break;
case LESS:
this.fail("disallowed character.");
break;
case EOC:
break;
default:
if (this.text.includes("]]>")) {
this.fail("the string \"]]>\" is disallowed in char data.");
}
this.pushAttrib(this.name, this.text);
this.name = this.text = "";
if (c === GREATER) {
this.openTag();
}
else {
this.state = S_ATTRIB;
}
}
}
private sCloseTag(): void {
const c = this.captureNameChars();
if (c === GREATER) {
this.closeTag();
}
else if (isS(c)) {
this.state = S_CLOSE_TAG_SAW_WHITE;
}
else if (c !== EOC) {
this.fail("disallowed character in closing tag.");
}
}
private sCloseTagSawWhite(): void {
switch (this.skipSpaces()) {
case GREATER:
this.closeTag();
break;
case EOC:
break;
default:
this.fail("disallowed character in closing tag.");
}
}
// END OF STATE ENGINE METHODS
private handleTextInRoot(): void {
// This is essentially a specialized version of captureTo which is optimized
// for performing the ]]> check. A previous version of this code, checked
// ``this.text`` for the presence of ]]>. It simplified the code but was
// very costly when character data contained a lot of entities to be parsed.
//
// Since we are using a specialized loop, we also keep track of the presence
// of ]]> in text data. The sequence ]]> is forbidden to appear as-is.
//
let { i: start, forbiddenState } = this;
const { chunk, textHandler: handler } = this;
// eslint-disable-next-line no-labels, no-restricted-syntax
scanLoop:
// eslint-disable-next-line no-constant-condition
while (true) {
switch (this.getCode()) {
case LESS: {
this.state = S_OPEN_WAKA;
if (handler !== undefined) {
const { text } = this;
const slice = chunk.slice(start, this.prevI);
if (text.length !== 0) {
handler(text + slice);
this.text = "";
}
else if (slice.length !== 0) {
handler(slice);
}
}
forbiddenState = FORBIDDEN_START;
// eslint-disable-next-line no-labels
break scanLoop;
}
case AMP:
this.state = S_ENTITY;
this.entityReturnState = S_TEXT;
if (handler !== undefined) {
this.text += chunk.slice(start, this.prevI);
}
forbiddenState = FORBIDDEN_START;
// eslint-disable-next-line no-labels
break scanLoop;
case CLOSE_BRACKET:
switch (forbiddenState) {
case FORBIDDEN_START:
forbiddenState = FORBIDDEN_BRACKET;
break;
case FORBIDDEN_BRACKET:
forbiddenState = FORBIDDEN_BRACKET_BRACKET;
break;
case FORBIDDEN_BRACKET_BRACKET:
break;
default:
throw new Error("impossible state");
}
break;
case GREATER:
if (forbiddenState === FORBIDDEN_BRACKET_BRACKET) {
this.fail("the string \"]]>\" is disallowed in char data.");
}
forbiddenState = FORBIDDEN_START;
break;
case NL_LIKE:
if (handler !== undefined) {
this.text += `${chunk.slice(start, this.prevI)}\n`;
}
start = this.i;
forbiddenState = FORBIDDEN_START;
break;
case EOC:
if (handler !== undefined) {
this.text += chunk.slice(start);
}
// eslint-disable-next-line no-labels
break scanLoop;
default:
forbiddenState = FORBIDDEN_START;
}
}
this.forbiddenState = forbiddenState;
}
private handleTextOutsideRoot(): void {
// This is essentially a specialized version of captureTo which is optimized
// for a specialized task. We keep track of the presence of non-space
// characters in the text since these are errors when appearing outside the
// document root element.
let { i: start } = this;
const { chunk, textHandler: handler } = this;
let nonSpace = false;
// eslint-disable-next-line no-labels, no-restricted-syntax
outRootLoop:
// eslint-disable-next-line no-constant-condition
while (true) {
const code = this.getCode();
switch (code) {
case LESS: {
this.state = S_OPEN_WAKA;
if (handler !== undefined) {
const { text } = this;
const slice = chunk.slice(start, this.prevI);
if (text.length !== 0) {
handler(text + slice);
this.text = "";
}
else if (slice.length !== 0) {
handler(slice);
}
}
// eslint-disable-next-line no-labels
break outRootLoop;
}
case AMP:
this.state = S_ENTITY;
this.entityReturnState = S_TEXT;
if (handler !== undefined) {
this.text += chunk.slice(start, this.prevI);
}
nonSpace = true;
// eslint-disable-next-line no-labels
break outRootLoop;
case NL_LIKE:
if (handler !== undefined) {
this.text += `${chunk.slice(start, this.prevI)}\n`;
}
start = this.i;
break;
case EOC:
if (handler !== undefined) {
this.text += chunk.slice(start);
}
// eslint-disable-next-line no-labels
break outRootLoop;
default:
if (!isS(code)) {
nonSpace = true;
}
}
}
if (!nonSpace) {
return;
}
// We use the reportedTextBeforeRoot and reportedTextAfterRoot flags
// to avoid reporting errors for every single character that is out of
// place.
if (!this.sawRoot && !this.reportedTextBeforeRoot) {
this.fail("text data outside of root node.");
this.reportedTextBeforeRoot = true;
}
if (this.closedRoot && !this.reportedTextAfterRoot) {
this.fail("text data outside of root node.");
this.reportedTextAfterRoot = true;
}
}
private pushAttribNS(name: string, value: string): void {
const { prefix, local } = this.qname(name);
const attr = { name, prefix, local, value };
this.attribList.push(attr);
this.attributeHandler?.(attr as AttributeEventForOptions<O>);
if (prefix === "xmlns") {
const trimmed = value.trim();
if (this.currentXMLVersion === "1.0" && trimmed === "") {
this.fail("invalid attempt to undefine prefix in XML 1.0");
}
this.topNS![local] = trimmed;
nsPairCheck(this, local, trimmed);
}
else if (name === "xmlns") {
const trimmed = value.trim();
this.topNS![""] = trimmed;
nsPairCheck(this, "", trimmed);
}
}
private pushAttribPlain(name: string, value: string): void {
const attr = { name, value };
this.attribList.push(attr);
this.attributeHandler?.(attr as AttributeEventForOptions<O>);
}
/**
* End parsing. This performs final well-formedness checks and resets the
* parser to a clean state.
*
* @returns this
*/
private end(): this {
if (!this.sawRoot) {
this.fail("document must contain a root element.");
}
const { tags } = this;
while (tags.length > 0) {
const tag = tags.pop()!;
this.fail(`unclosed tag: ${tag.name}`);
}
if ((this.state !== S_BEGIN) && (this.state !== S_TEXT)) {
this.fail("unexpected end.");
}
const { text } = this;
if (text.length !== 0) {
this.textHandler?.(text);
this.text = "";
}
this._closed = true;
this.endHandler?.();
this._init();
return this;
}
/**
* Resolve a namespace prefix.
*
* @param prefix The prefix to resolve.
*
* @returns The namespace URI or ``undefined`` if the prefix is not defined.
*/
resolve(prefix: string): string | undefined {
let uri = this.topNS![prefix];
if (uri !== undefined) {
return uri;
}
const { tags } = this;
for (let index = tags.length - 1; index >= 0; index--) {
uri = tags[index]!.ns![prefix];
if (uri !== undefined) {
return uri;
}
}
uri = this.ns[prefix];
if (uri !== undefined) {
return uri;
}
return this.opt.resolvePrefix?.(prefix);
}
/**
* Parse a qname into its prefix and local name parts.
*
* @param name The name to parse
*
* @returns
*/
private qname(name: string): { prefix: string; local: string } {
// This is faster than using name.split(":").
const colon = name.indexOf(":");
if (colon === -1) {
return { prefix: "", local: name };
}
const local = name.slice(colon + 1);
const prefix = name.slice(0, colon);
if (prefix === "" || local === "" || local.includes(":")) {
this.fail(`malformed name: ${name}.`);
}
return { prefix, local };
}
private processAttribsNS(): void {
const { attribList } = this;
const tag = this.tag!;
{
// add namespace info to tag
const { prefix, local } = this.qname(tag.name);
tag.prefix = prefix;
tag.local = local;
const uri = tag.uri = this.resolve(prefix) ?? "";
if (prefix !== "") {
if (prefix === "xmlns") {
this.fail("tags may not have \"xmlns\" as prefix.");
}
if (uri === "") {
this.fail(`unbound namespace prefix: ${JSON.stringify(prefix)}.`);
tag.uri = prefix;
}
}
}
if (attribList.length === 0) {
return;
}
const { attributes } = tag;
const seen = new Set();
// Note: do not apply default ns to attributes:
// http://www.w3.org/TR/REC-xml-names/#defaulting
for (const attr of attribList as SaxesAttributeNSIncomplete[]) {
const { name, prefix, local } = attr;
let uri;
let eqname;
if (prefix === "") {
uri = name === "xmlns" ? XMLNS_NAMESPACE : "";
eqname = name;
}
else {
uri = this.resolve(prefix);
// if there's any attributes with an undefined namespace,
// then fail on them now.
if (uri === undefined) {
this.fail(`unbound namespace prefix: ${JSON.stringify(prefix)}.`);
uri = prefix;
}
eqname = `{${uri}}${local}`;
}
if (seen.has(eqname)) {
this.fail(`duplicate attribute: ${eqname}.`);
}
seen.add(eqname);
attr.uri = uri;
attributes[name] = attr;
}
this.attribList = [];
}
private processAttribsPlain(): void {
const { attribList } = this;
// eslint-disable-next-line prefer-destructuring
const attributes = this.tag!.attributes;
for (const { name, value } of attribList) {
if (attributes[name] !== undefined) {
this.fail(`duplicate attribute: ${name}.`);
}
attributes[name] = value;
}
this.attribList = [];
}
/**
* Handle a complete open tag. This parser code calls this once it has seen
* the whole tag. This method checks for well-formeness and then emits
* ``onopentag``.
*/
private openTag(): void {
this.processAttribs();
const { tags } = this;
const tag = this.tag as SaxesTag;
tag.isSelfClosing = false;
// There cannot be any pending text here due to the onopentagstart that was
// necessarily emitted before we get here. So we do not check text.
this.openTagHandler?.(tag as TagForOptions<O>);
tags.push(tag);
this.state = S_TEXT;
this.name = "";
}
/**
* Handle a complete self-closing tag. This parser code calls this once it has
* seen the whole tag. This method checks for well-formeness and then emits
* ``onopentag`` and ``onclosetag``.
*/
private openSelfClosingTag(): void {
this.processAttribs();
const { tags } = this;
const tag = this.tag as SaxesTag;
tag.isSelfClosing = true;
// There cannot be any pending text here due to the onopentagstart that was
// necessarily emitted before we get here. So we do not check text.
this.openTagHandler?.(tag as TagForOptions<O>);
this.closeTagHandler?.(tag as TagForOptions<O>);
const top = this.tag = tags[tags.length - 1] ?? null;
if (top === null) {
this.closedRoot = true;
}
this.state = S_TEXT;
this.name = "";
}
/**
* Handle a complete close tag. This parser code calls this once it has seen
* the whole tag. This method checks for well-formeness and then emits
* ``onclosetag``.
*/
private closeTag(): void {
const { tags, name } = this;
// Our state after this will be S_TEXT, no matter what, and we can clear
// tagName now.
this.state = S_TEXT;
this.name = "";
if (name === "") {
this.fail("weird empty close tag.");
this.text += "</>";
return;
}
const handler = this.closeTagHandler;
let l = tags.length;
while (l-- > 0) {
const tag = this.tag = tags.pop() as SaxesTag;
this.topNS = tag.ns!;
handler?.(tag as TagForOptions<O>);
if (tag.name === name) {
break;
}
this.fail("unexpected close tag.");
}
if (l === 0) {
this.closedRoot = true;
}
else if (l < 0) {
this.fail(`unmatched closing tag: ${name}.`);
this.text += `</${name}>`;
}
}
/**
* Resolves an entity. Makes any necessary well-formedness checks.
*
* @param entity The entity to resolve.
*
* @returns The parsed entity.
*/
private parseEntity(entity: string): string {
// startsWith would be significantly slower for this test.
if (entity[0] !== "#") {
const defined = this.ENTITIES[entity];
if (defined !== undefined) {
return defined;
}
this.fail(this.isName(entity) ? "undefined entity." :
"disallowed character in entity name.");
return `&${entity};`;
}
let num = NaN;
if (entity[1] === "x" && /^#x[0-9a-f]+$/i.test(entity)) {
num = parseInt(entity.slice(2), 16);
}
else if (/^#[0-9]+$/.test(entity)) {
num = parseInt(entity.slice(1), 10);
}
// The character reference is required to match the CHAR production.
if (!this.isChar(num)) {
this.fail("malformed character entity.");
return `&${entity};`;
}
return String.fromCodePoint(num);
}
} |
1,144 | fn(parser: SaxesParser): void {
for (const x of nl) {
parser.write(x);
}
parser.close();
} | class SaxesParser<O extends SaxesOptions = {}> {
private readonly fragmentOpt: boolean;
private readonly xmlnsOpt: boolean;
private readonly trackPosition: boolean;
private readonly fileName?: string;
private readonly nameStartCheck: (c: number) => boolean;
private readonly nameCheck: (c: number) => boolean;
private readonly isName: (name: string) => boolean;
private readonly ns!: Record<string, string>;
private openWakaBang!: string;
private text!: string;
private name!: string;
private piTarget!: string;
private entity!: string;
private q!: null | number;
private tags!: SaxesTagIncomplete[];
private tag!: SaxesTagIncomplete | null;
private topNS!: Record<string, string> | null;
private chunk!: string;
private chunkPosition!: number;
private i!: number;
//
// We use prevI to allow "ungetting" the previously read code point. Note
// however, that it is not safe to unget everything and anything. In
// particular ungetting EOL characters will screw positioning up.
//
// Practically, you must not unget a code which has any side effect beyond
// updating ``this.i`` and ``this.prevI``. Only EOL codes have such side
// effects.
//
private prevI!: number;
private carriedFromPrevious?: string;
private forbiddenState!: number;
private attribList!: (SaxesAttributeNSIncomplete | SaxesAttributePlain)[];
private state!: number;
private reportedTextBeforeRoot!: boolean;
private reportedTextAfterRoot!: boolean;
private closedRoot!: boolean;
private sawRoot!: boolean;
private xmlDeclPossible!: boolean;
private xmlDeclExpects!: string[];
private entityReturnState?: number;
private processAttribs!: (this: this) => void;
private positionAtNewLine!: number;
private doctype!: boolean;
private getCode!: () => number;
private isChar!: (c: number) => boolean;
private pushAttrib!: (name: string, value: string) => void;
private _closed!: boolean;
private currentXMLVersion!: string;
private readonly stateTable: ((this: SaxesParser<O>) => void)[];
private xmldeclHandler?: XMLDeclHandler;
private textHandler?: TextHandler;
private piHandler?: PIHandler;
private doctypeHandler?: DoctypeHandler;
private commentHandler?: CommentHandler;
private openTagStartHandler?: OpenTagStartHandler<O>;
private openTagHandler?: OpenTagHandler<O>;
private closeTagHandler?: CloseTagHandler<O>;
private cdataHandler?: CDataHandler;
private errorHandler?: ErrorHandler;
private endHandler?: EndHandler;
private readyHandler?: ReadyHandler;
private attributeHandler?: AttributeHandler<O>;
/**
* Indicates whether or not the parser is closed. If ``true``, wait for
* the ``ready`` event to write again.
*/
get closed(): boolean {
return this._closed;
}
readonly opt: SaxesOptions;
/**
* The XML declaration for this document.
*/
xmlDecl!: XMLDecl;
/**
* The line number of the next character to be read by the parser. This field
* is one-based. (The first line is numbered 1.)
*/
line!: number;
/**
* The column number of the next character to be read by the parser. *
* This field is zero-based. (The first column is 0.)
*
* This field counts columns by *Unicode character*. Note that this *can*
* be different from the index of the character in a JavaScript string due
* to how JavaScript handles astral plane characters.
*
* See [[columnIndex]] for a number that corresponds to the JavaScript index.
*/
column!: number;
/**
* A map of entity name to expansion.
*/
ENTITIES!: Record<string, string>;
/**
* @param opt The parser options.
*/
constructor(opt?: O) {
this.opt = opt ?? {};
this.fragmentOpt = !!(this.opt.fragment as boolean);
const xmlnsOpt = this.xmlnsOpt = !!(this.opt.xmlns as boolean);
this.trackPosition = this.opt.position !== false;
this.fileName = this.opt.fileName;
if (xmlnsOpt) {
// This is the function we use to perform name checks on PIs and entities.
// When namespaces are used, colons are not allowed in PI target names or
// entity names. So the check depends on whether namespaces are used. See:
//
// https://www.w3.org/XML/xml-names-19990114-errata.html
// NE08
//
this.nameStartCheck = isNCNameStartChar;
this.nameCheck = isNCNameChar;
this.isName = isNCName;
// eslint-disable-next-line @typescript-eslint/unbound-method
this.processAttribs = this.processAttribsNS;
// eslint-disable-next-line @typescript-eslint/unbound-method
this.pushAttrib = this.pushAttribNS;
// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-assignment
this.ns = { __proto__: null as any, ...rootNS };
const additional = this.opt.additionalNamespaces;
if (additional != null) {
nsMappingCheck(this, additional);
Object.assign(this.ns, additional);
}
}
else {
this.nameStartCheck = isNameStartChar;
this.nameCheck = isNameChar;
this.isName = isName;
// eslint-disable-next-line @typescript-eslint/unbound-method
this.processAttribs = this.processAttribsPlain;
// eslint-disable-next-line @typescript-eslint/unbound-method
this.pushAttrib = this.pushAttribPlain;
}
//
// The order of the members in this table needs to correspond to the state
// numbers given to the states that correspond to the methods being recorded
// here.
//
this.stateTable = [
/* eslint-disable @typescript-eslint/unbound-method */
this.sBegin,
this.sBeginWhitespace,
this.sDoctype,
this.sDoctypeQuote,
this.sDTD,
this.sDTDQuoted,
this.sDTDOpenWaka,
this.sDTDOpenWakaBang,
this.sDTDComment,
this.sDTDCommentEnding,
this.sDTDCommentEnded,
this.sDTDPI,
this.sDTDPIEnding,
this.sText,
this.sEntity,
this.sOpenWaka,
this.sOpenWakaBang,
this.sComment,
this.sCommentEnding,
this.sCommentEnded,
this.sCData,
this.sCDataEnding,
this.sCDataEnding2,
this.sPIFirstChar,
this.sPIRest,
this.sPIBody,
this.sPIEnding,
this.sXMLDeclNameStart,
this.sXMLDeclName,
this.sXMLDeclEq,
this.sXMLDeclValueStart,
this.sXMLDeclValue,
this.sXMLDeclSeparator,
this.sXMLDeclEnding,
this.sOpenTag,
this.sOpenTagSlash,
this.sAttrib,
this.sAttribName,
this.sAttribNameSawWhite,
this.sAttribValue,
this.sAttribValueQuoted,
this.sAttribValueClosed,
this.sAttribValueUnquoted,
this.sCloseTag,
this.sCloseTagSawWhite,
/* eslint-enable @typescript-eslint/unbound-method */
];
this._init();
}
_init(): void {
this.openWakaBang = "";
this.text = "";
this.name = "";
this.piTarget = "";
this.entity = "";
this.q = null;
this.tags = [];
this.tag = null;
this.topNS = null;
this.chunk = "";
this.chunkPosition = 0;
this.i = 0;
this.prevI = 0;
this.carriedFromPrevious = undefined;
this.forbiddenState = FORBIDDEN_START;
this.attribList = [];
// The logic is organized so as to minimize the need to check
// this.opt.fragment while parsing.
const { fragmentOpt } = this;
this.state = fragmentOpt ? S_TEXT : S_BEGIN;
// We want these to be all true if we are dealing with a fragment.
this.reportedTextBeforeRoot = this.reportedTextAfterRoot = this.closedRoot =
this.sawRoot = fragmentOpt;
// An XML declaration is intially possible only when parsing whole
// documents.
this.xmlDeclPossible = !fragmentOpt;
this.xmlDeclExpects = ["version"];
this.entityReturnState = undefined;
let { defaultXMLVersion } = this.opt;
if (defaultXMLVersion === undefined) {
if (this.opt.forceXMLVersion === true) {
throw new Error("forceXMLVersion set but defaultXMLVersion is not set");
}
defaultXMLVersion = "1.0";
}
this.setXMLVersion(defaultXMLVersion);
this.positionAtNewLine = 0;
this.doctype = false;
this._closed = false;
this.xmlDecl = {
version: undefined,
encoding: undefined,
standalone: undefined,
};
this.line = 1;
this.column = 0;
this.ENTITIES = Object.create(XML_ENTITIES) as Record<string, string>;
this.readyHandler?.();
}
/**
* The stream position the parser is currently looking at. This field is
* zero-based.
*
* This field is not based on counting Unicode characters but is to be
* interpreted as a plain index into a JavaScript string.
*/
get position(): number {
return this.chunkPosition + this.i;
}
/**
* The column number of the next character to be read by the parser. *
* This field is zero-based. (The first column in a line is 0.)
*
* This field reports the index at which the next character would be in the
* line if the line were represented as a JavaScript string. Note that this
* *can* be different to a count based on the number of *Unicode characters*
* due to how JavaScript handles astral plane characters.
*
* See [[column]] for a number that corresponds to a count of Unicode
* characters.
*/
get columnIndex(): number {
return this.position - this.positionAtNewLine;
}
/**
* Set an event listener on an event. The parser supports one handler per
* event type. If you try to set an event handler over an existing handler,
* the old handler is silently overwritten.
*
* @param name The event to listen to.
*
* @param handler The handler to set.
*/
on<N extends EventName>(name: N, handler: EventNameToHandler<O, N>): void {
// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-member-access
(this as any)[EVENT_NAME_TO_HANDLER_NAME[name]] = handler;
}
/**
* Unset an event handler.
*
* @parma name The event to stop listening to.
*/
off(name: EventName): void {
// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-member-access
(this as any)[EVENT_NAME_TO_HANDLER_NAME[name]] = undefined;
}
/**
* Make an error object. The error object will have a message that contains
* the ``fileName`` option passed at the creation of the parser. If position
* tracking was turned on, it will also have line and column number
* information.
*
* @param message The message describing the error to report.
*
* @returns An error object with a properly formatted message.
*/
makeError(message: string): Error {
let msg = this.fileName ?? "";
if (this.trackPosition) {
if (msg.length > 0) {
msg += ":";
}
msg += `${this.line}:${this.column}`;
}
if (msg.length > 0) {
msg += ": ";
}
return new Error(msg + message);
}
/**
* Report a parsing error. This method is made public so that client code may
* check for issues that are outside the scope of this project and can report
* errors.
*
* @param message The error to report.
*
* @returns this
*/
fail(message: string): this {
const err = this.makeError(message);
const handler = this.errorHandler;
if (handler === undefined) {
throw err;
}
else {
handler(err);
}
return this;
}
/**
* Write a XML data to the parser.
*
* @param chunk The XML data to write.
*
* @returns this
*/
// We do need object for the type here. Yes, it often causes problems
// but not in this case.
write(chunk: string | object | null): this {
if (this.closed) {
return this.fail("cannot write after close; assign an onready handler.");
}
let end = false;
if (chunk === null) {
// We cannot return immediately because carriedFromPrevious may need
// processing.
end = true;
chunk = "";
}
else if (typeof chunk === "object") {
chunk = chunk.toString();
}
// We checked if performing a pre-decomposition of the string into an array
// of single complete characters (``Array.from(chunk)``) would be faster
// than the current repeated calls to ``charCodeAt``. As of August 2018, it
// isn't. (There may be Node-specific code that would perform faster than
// ``Array.from`` but don't want to be dependent on Node.)
if (this.carriedFromPrevious !== undefined) {
// The previous chunk had char we must carry over.
chunk = `${this.carriedFromPrevious}${chunk}`;
this.carriedFromPrevious = undefined;
}
let limit = chunk.length;
const lastCode = chunk.charCodeAt(limit - 1);
if (!end &&
// A trailing CR or surrogate must be carried over to the next
// chunk.
(lastCode === CR || (lastCode >= 0xD800 && lastCode <= 0xDBFF))) {
// The chunk ends with a character that must be carried over. We cannot
// know how to handle it until we get the next chunk or the end of the
// stream. So save it for later.
this.carriedFromPrevious = chunk[limit - 1];
limit--;
chunk = chunk.slice(0, limit);
}
const { stateTable } = this;
this.chunk = chunk;
this.i = 0;
while (this.i < limit) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-argument
stateTable[this.state].call(this as any);
}
this.chunkPosition += limit;
return end ? this.end() : this;
}
/**
* Close the current stream. Perform final well-formedness checks and reset
* the parser tstate.
*
* @returns this
*/
close(): this {
return this.write(null);
}
/**
* Get a single code point out of the current chunk. This updates the current
* position if we do position tracking.
*
* This is the algorithm to use for XML 1.0.
*
* @returns The character read.
*/
private getCode10(): number {
const { chunk, i } = this;
this.prevI = i;
// Yes, we do this instead of doing this.i++. Doing it this way, we do not
// read this.i again, which is a bit faster.
this.i = i + 1;
if (i >= chunk.length) {
return EOC;
}
// Using charCodeAt and handling the surrogates ourselves is faster
// than using codePointAt.
const code = chunk.charCodeAt(i);
this.column++;
if (code < 0xD800) {
if (code >= SPACE || code === TAB) {
return code;
}
switch (code) {
case NL:
this.line++;
this.column = 0;
this.positionAtNewLine = this.position;
return NL;
case CR:
// We may get NaN if we read past the end of the chunk, which is fine.
if (chunk.charCodeAt(i + 1) === NL) {
// A \r\n sequence is converted to \n so we have to skip over the
// next character. We already know it has a size of 1 so ++ is fine
// here.
this.i = i + 2;
}
// Otherwise, a \r is just converted to \n, so we don't have to skip
// ahead.
// In either case, \r becomes \n.
this.line++;
this.column = 0;
this.positionAtNewLine = this.position;
return NL_LIKE;
default:
// If we get here, then code < SPACE and it is not NL CR or TAB.
this.fail("disallowed character.");
return code;
}
}
if (code > 0xDBFF) {
// This is a specialized version of isChar10 that takes into account
// that in this context code > 0xDBFF and code <= 0xFFFF. So it does not
// test cases that don't need testing.
if (!(code >= 0xE000 && code <= 0xFFFD)) {
this.fail("disallowed character.");
}
return code;
}
const final = 0x10000 + ((code - 0xD800) * 0x400) +
(chunk.charCodeAt(i + 1) - 0xDC00);
this.i = i + 2;
// This is a specialized version of isChar10 that takes into account that in
// this context necessarily final >= 0x10000.
if (final > 0x10FFFF) {
this.fail("disallowed character.");
}
return final;
}
/**
* Get a single code point out of the current chunk. This updates the current
* position if we do position tracking.
*
* This is the algorithm to use for XML 1.1.
*
* @returns {number} The character read.
*/
private getCode11(): number {
const { chunk, i } = this;
this.prevI = i;
// Yes, we do this instead of doing this.i++. Doing it this way, we do not
// read this.i again, which is a bit faster.
this.i = i + 1;
if (i >= chunk.length) {
return EOC;
}
// Using charCodeAt and handling the surrogates ourselves is faster
// than using codePointAt.
const code = chunk.charCodeAt(i);
this.column++;
if (code < 0xD800) {
if ((code > 0x1F && code < 0x7F) || (code > 0x9F && code !== LS) ||
code === TAB) {
return code;
}
switch (code) {
case NL: // 0xA
this.line++;
this.column = 0;
this.positionAtNewLine = this.position;
return NL;
case CR: { // 0xD
// We may get NaN if we read past the end of the chunk, which is
// fine.
const next = chunk.charCodeAt(i + 1);
if (next === NL || next === NEL) {
// A CR NL or CR NEL sequence is converted to NL so we have to skip
// over the next character. We already know it has a size of 1.
this.i = i + 2;
}
// Otherwise, a CR is just converted to NL, no skip.
}
/* yes, fall through */
case NEL: // 0x85
case LS: // Ox2028
this.line++;
this.column = 0;
this.positionAtNewLine = this.position;
return NL_LIKE;
default:
this.fail("disallowed character.");
return code;
}
}
if (code > 0xDBFF) {
// This is a specialized version of isCharAndNotRestricted that takes into
// account that in this context code > 0xDBFF and code <= 0xFFFF. So it
// does not test cases that don't need testing.
if (!(code >= 0xE000 && code <= 0xFFFD)) {
this.fail("disallowed character.");
}
return code;
}
const final = 0x10000 + ((code - 0xD800) * 0x400) +
(chunk.charCodeAt(i + 1) - 0xDC00);
this.i = i + 2;
// This is a specialized version of isCharAndNotRestricted that takes into
// account that in this context necessarily final >= 0x10000.
if (final > 0x10FFFF) {
this.fail("disallowed character.");
}
return final;
}
/**
* Like ``getCode`` but with the return value normalized so that ``NL`` is
* returned for ``NL_LIKE``.
*/
private getCodeNorm(): number {
const c = this.getCode();
return c === NL_LIKE ? NL : c;
}
private unget(): void {
this.i = this.prevI;
this.column--;
}
/**
* Capture characters into a buffer until encountering one of a set of
* characters.
*
* @param chars An array of codepoints. Encountering a character in the array
* ends the capture. (``chars`` may safely contain ``NL``.)
*
* @return The character code that made the capture end, or ``EOC`` if we hit
* the end of the chunk. The return value cannot be NL_LIKE: NL is returned
* instead.
*/
private captureTo(chars: number[]): number {
let { i: start } = this;
const { chunk } = this;
// eslint-disable-next-line no-constant-condition
while (true) {
const c = this.getCode();
const isNLLike = c === NL_LIKE;
const final = isNLLike ? NL : c;
if (final === EOC || chars.includes(final)) {
this.text += chunk.slice(start, this.prevI);
return final;
}
if (isNLLike) {
this.text += `${chunk.slice(start, this.prevI)}\n`;
start = this.i;
}
}
}
/**
* Capture characters into a buffer until encountering a character.
*
* @param char The codepoint that ends the capture. **NOTE ``char`` MAY NOT
* CONTAIN ``NL``.** Passing ``NL`` will result in buggy behavior.
*
* @return ``true`` if we ran into the character. Otherwise, we ran into the
* end of the current chunk.
*/
private captureToChar(char: number): boolean {
let { i: start } = this;
const { chunk } = this;
// eslint-disable-next-line no-constant-condition
while (true) {
let c = this.getCode();
switch (c) {
case NL_LIKE:
this.text += `${chunk.slice(start, this.prevI)}\n`;
start = this.i;
c = NL;
break;
case EOC:
this.text += chunk.slice(start);
return false;
default:
}
if (c === char) {
this.text += chunk.slice(start, this.prevI);
return true;
}
}
}
/**
* Capture characters that satisfy ``isNameChar`` into the ``name`` field of
* this parser.
*
* @return The character code that made the test fail, or ``EOC`` if we hit
* the end of the chunk. The return value cannot be NL_LIKE: NL is returned
* instead.
*/
private captureNameChars(): number {
const { chunk, i: start } = this;
// eslint-disable-next-line no-constant-condition
while (true) {
const c = this.getCode();
if (c === EOC) {
this.name += chunk.slice(start);
return EOC;
}
// NL is not a name char so we don't have to test specifically for it.
if (!isNameChar(c)) {
this.name += chunk.slice(start, this.prevI);
return c === NL_LIKE ? NL : c;
}
}
}
/**
* Skip white spaces.
*
* @return The character that ended the skip, or ``EOC`` if we hit
* the end of the chunk. The return value cannot be NL_LIKE: NL is returned
* instead.
*/
private skipSpaces(): number {
// eslint-disable-next-line no-constant-condition
while (true) {
const c = this.getCodeNorm();
if (c === EOC || !isS(c)) {
return c;
}
}
}
private setXMLVersion(version: string): void {
this.currentXMLVersion = version;
/* eslint-disable @typescript-eslint/unbound-method */
if (version === "1.0") {
this.isChar = isChar10;
this.getCode = this.getCode10;
}
else {
this.isChar = isChar11;
this.getCode = this.getCode11;
}
/* eslint-enable @typescript-eslint/unbound-method */
}
// STATE ENGINE METHODS
// This needs to be a state separate from S_BEGIN_WHITESPACE because we want
// to be sure never to come back to this state later.
private sBegin(): void {
// We are essentially peeking at the first character of the chunk. Since
// S_BEGIN can be in effect only when we start working on the first chunk,
// the index at which we must look is necessarily 0. Note also that the
// following test does not depend on decoding surrogates.
// If the initial character is 0xFEFF, ignore it.
if (this.chunk.charCodeAt(0) === 0xFEFF) {
this.i++;
this.column++;
}
this.state = S_BEGIN_WHITESPACE;
}
private sBeginWhitespace(): void {
// We need to know whether we've encountered spaces or not because as soon
// as we run into a space, an XML declaration is no longer possible. Rather
// than slow down skipSpaces even in places where we don't care whether it
// skipped anything or not, we check whether prevI is equal to the value of
// i from before we skip spaces.
const iBefore = this.i;
const c = this.skipSpaces();
if (this.prevI !== iBefore) {
this.xmlDeclPossible = false;
}
switch (c) {
case LESS:
this.state = S_OPEN_WAKA;
// We could naively call closeText but in this state, it is not normal
// to have text be filled with any data.
if (this.text.length !== 0) {
throw new Error("no-empty text at start");
}
break;
case EOC:
break;
default:
this.unget();
this.state = S_TEXT;
this.xmlDeclPossible = false;
}
}
private sDoctype(): void {
const c = this.captureTo(DOCTYPE_TERMINATOR);
switch (c) {
case GREATER: {
this.doctypeHandler?.(this.text);
this.text = "";
this.state = S_TEXT;
this.doctype = true; // just remember that we saw it.
break;
}
case EOC:
break;
default:
this.text += String.fromCodePoint(c);
if (c === OPEN_BRACKET) {
this.state = S_DTD;
}
else if (isQuote(c)) {
this.state = S_DOCTYPE_QUOTE;
this.q = c;
}
}
}
private sDoctypeQuote(): void {
const q = this.q!;
if (this.captureToChar(q)) {
this.text += String.fromCodePoint(q);
this.q = null;
this.state = S_DOCTYPE;
}
}
private sDTD(): void {
const c = this.captureTo(DTD_TERMINATOR);
if (c === EOC) {
return;
}
this.text += String.fromCodePoint(c);
if (c === CLOSE_BRACKET) {
this.state = S_DOCTYPE;
}
else if (c === LESS) {
this.state = S_DTD_OPEN_WAKA;
}
else if (isQuote(c)) {
this.state = S_DTD_QUOTED;
this.q = c;
}
}
private sDTDQuoted(): void {
const q = this.q!;
if (this.captureToChar(q)) {
this.text += String.fromCodePoint(q);
this.state = S_DTD;
this.q = null;
}
}
private sDTDOpenWaka(): void {
const c = this.getCodeNorm();
this.text += String.fromCodePoint(c);
switch (c) {
case BANG:
this.state = S_DTD_OPEN_WAKA_BANG;
this.openWakaBang = "";
break;
case QUESTION:
this.state = S_DTD_PI;
break;
default:
this.state = S_DTD;
}
}
private sDTDOpenWakaBang(): void {
const char = String.fromCodePoint(this.getCodeNorm());
const owb = this.openWakaBang += char;
this.text += char;
if (owb !== "-") {
this.state = owb === "--" ? S_DTD_COMMENT : S_DTD;
this.openWakaBang = "";
}
}
private sDTDComment(): void {
if (this.captureToChar(MINUS)) {
this.text += "-";
this.state = S_DTD_COMMENT_ENDING;
}
}
private sDTDCommentEnding(): void {
const c = this.getCodeNorm();
this.text += String.fromCodePoint(c);
this.state = c === MINUS ? S_DTD_COMMENT_ENDED : S_DTD_COMMENT;
}
private sDTDCommentEnded(): void {
const c = this.getCodeNorm();
this.text += String.fromCodePoint(c);
if (c === GREATER) {
this.state = S_DTD;
}
else {
this.fail("malformed comment.");
// <!-- blah -- bloo --> will be recorded as
// a comment of " blah -- bloo "
this.state = S_DTD_COMMENT;
}
}
private sDTDPI(): void {
if (this.captureToChar(QUESTION)) {
this.text += "?";
this.state = S_DTD_PI_ENDING;
}
}
private sDTDPIEnding(): void {
const c = this.getCodeNorm();
this.text += String.fromCodePoint(c);
if (c === GREATER) {
this.state = S_DTD;
}
}
private sText(): void {
//
// We did try a version of saxes where the S_TEXT state was split in two
// states: one for text inside the root element, and one for text
// outside. This was avoiding having to test this.tags.length to decide
// what implementation to actually use.
//
// Peformance testing on gigabyte-size files did not show any advantage to
// using the two states solution instead of the current one. Conversely, it
// made the code a bit more complicated elsewhere. For instance, a comment
// can appear before the root element so when a comment ended it was
// necessary to determine whether to return to the S_TEXT state or to the
// new text-outside-root state.
//
if (this.tags.length !== 0) {
this.handleTextInRoot();
}
else {
this.handleTextOutsideRoot();
}
}
private sEntity(): void {
// This is essentially a specialized version of captureToChar(SEMICOLON...)
let { i: start } = this;
const { chunk } = this;
// eslint-disable-next-line no-labels, no-restricted-syntax
loop:
// eslint-disable-next-line no-constant-condition
while (true) {
switch (this.getCode()) {
case NL_LIKE:
this.entity += `${chunk.slice(start, this.prevI)}\n`;
start = this.i;
break;
case SEMICOLON: {
const { entityReturnState } = this;
const entity = this.entity + chunk.slice(start, this.prevI);
this.state = entityReturnState!;
let parsed: string;
if (entity === "") {
this.fail("empty entity name.");
parsed = "&;";
}
else {
parsed = this.parseEntity(entity);
this.entity = "";
}
if (entityReturnState !== S_TEXT || this.textHandler !== undefined) {
this.text += parsed;
}
// eslint-disable-next-line no-labels
break loop;
}
case EOC:
this.entity += chunk.slice(start);
// eslint-disable-next-line no-labels
break loop;
default:
}
}
}
private sOpenWaka(): void {
// Reminder: a state handler is called with at least one character
// available in the current chunk. So the first call to get code inside of
// a state handler cannot return ``EOC``. That's why we don't test
// for it.
const c = this.getCode();
// either a /, ?, !, or text is coming next.
if (isNameStartChar(c)) {
this.state = S_OPEN_TAG;
this.unget();
this.xmlDeclPossible = false;
}
else {
switch (c) {
case FORWARD_SLASH:
this.state = S_CLOSE_TAG;
this.xmlDeclPossible = false;
break;
case BANG:
this.state = S_OPEN_WAKA_BANG;
this.openWakaBang = "";
this.xmlDeclPossible = false;
break;
case QUESTION:
this.state = S_PI_FIRST_CHAR;
break;
default:
this.fail("disallowed character in tag name");
this.state = S_TEXT;
this.xmlDeclPossible = false;
}
}
}
private sOpenWakaBang(): void {
this.openWakaBang += String.fromCodePoint(this.getCodeNorm());
switch (this.openWakaBang) {
case "[CDATA[":
if (!this.sawRoot && !this.reportedTextBeforeRoot) {
this.fail("text data outside of root node.");
this.reportedTextBeforeRoot = true;
}
if (this.closedRoot && !this.reportedTextAfterRoot) {
this.fail("text data outside of root node.");
this.reportedTextAfterRoot = true;
}
this.state = S_CDATA;
this.openWakaBang = "";
break;
case "--":
this.state = S_COMMENT;
this.openWakaBang = "";
break;
case "DOCTYPE":
this.state = S_DOCTYPE;
if (this.doctype || this.sawRoot) {
this.fail("inappropriately located doctype declaration.");
}
this.openWakaBang = "";
break;
default:
// 7 happens to be the maximum length of the string that can possibly
// match one of the cases above.
if (this.openWakaBang.length >= 7) {
this.fail("incorrect syntax.");
}
}
}
private sComment(): void {
if (this.captureToChar(MINUS)) {
this.state = S_COMMENT_ENDING;
}
}
private sCommentEnding(): void {
const c = this.getCodeNorm();
if (c === MINUS) {
this.state = S_COMMENT_ENDED;
this.commentHandler?.(this.text);
this.text = "";
}
else {
this.text += `-${String.fromCodePoint(c)}`;
this.state = S_COMMENT;
}
}
private sCommentEnded(): void {
const c = this.getCodeNorm();
if (c !== GREATER) {
this.fail("malformed comment.");
// <!-- blah -- bloo --> will be recorded as
// a comment of " blah -- bloo "
this.text += `--${String.fromCodePoint(c)}`;
this.state = S_COMMENT;
}
else {
this.state = S_TEXT;
}
}
private sCData(): void {
if (this.captureToChar(CLOSE_BRACKET)) {
this.state = S_CDATA_ENDING;
}
}
private sCDataEnding(): void {
const c = this.getCodeNorm();
if (c === CLOSE_BRACKET) {
this.state = S_CDATA_ENDING_2;
}
else {
this.text += `]${String.fromCodePoint(c)}`;
this.state = S_CDATA;
}
}
private sCDataEnding2(): void {
const c = this.getCodeNorm();
switch (c) {
case GREATER: {
this.cdataHandler?.(this.text);
this.text = "";
this.state = S_TEXT;
break;
}
case CLOSE_BRACKET:
this.text += "]";
break;
default:
this.text += `]]${String.fromCodePoint(c)}`;
this.state = S_CDATA;
}
}
// We need this separate state to check the first character fo the pi target
// with this.nameStartCheck which allows less characters than this.nameCheck.
private sPIFirstChar(): void {
const c = this.getCodeNorm();
// This is first because in the case where the file is well-formed this is
// the branch taken. We optimize for well-formedness.
if (this.nameStartCheck(c)) {
this.piTarget += String.fromCodePoint(c);
this.state = S_PI_REST;
}
else if (c === QUESTION || isS(c)) {
this.fail("processing instruction without a target.");
this.state = c === QUESTION ? S_PI_ENDING : S_PI_BODY;
}
else {
this.fail("disallowed character in processing instruction name.");
this.piTarget += String.fromCodePoint(c);
this.state = S_PI_REST;
}
}
private sPIRest(): void {
// Capture characters into a piTarget while ``this.nameCheck`` run on the
// character read returns true.
const { chunk, i: start } = this;
// eslint-disable-next-line no-constant-condition
while (true) {
const c = this.getCodeNorm();
if (c === EOC) {
this.piTarget += chunk.slice(start);
return;
}
// NL cannot satisfy this.nameCheck so we don't have to test specifically
// for it.
if (!this.nameCheck(c)) {
this.piTarget += chunk.slice(start, this.prevI);
const isQuestion = c === QUESTION;
if (isQuestion || isS(c)) {
if (this.piTarget === "xml") {
if (!this.xmlDeclPossible) {
this.fail(
"an XML declaration must be at the start of the document.");
}
this.state = isQuestion ? S_XML_DECL_ENDING : S_XML_DECL_NAME_START;
}
else {
this.state = isQuestion ? S_PI_ENDING : S_PI_BODY;
}
}
else {
this.fail("disallowed character in processing instruction name.");
this.piTarget += String.fromCodePoint(c);
}
break;
}
}
}
private sPIBody(): void {
if (this.text.length === 0) {
const c = this.getCodeNorm();
if (c === QUESTION) {
this.state = S_PI_ENDING;
}
else if (!isS(c)) {
this.text = String.fromCodePoint(c);
}
}
// The question mark character is not valid inside any of the XML
// declaration name/value pairs.
else if (this.captureToChar(QUESTION)) {
this.state = S_PI_ENDING;
}
}
private sPIEnding(): void {
const c = this.getCodeNorm();
if (c === GREATER) {
const { piTarget } = this;
if (piTarget.toLowerCase() === "xml") {
this.fail(
"the XML declaration must appear at the start of the document.");
}
this.piHandler?.({
target: piTarget,
body: this.text,
});
this.piTarget = this.text = "";
this.state = S_TEXT;
}
else if (c === QUESTION) {
// We ran into ?? as part of a processing instruction. We initially took
// the first ? as a sign that the PI was ending, but it is not. So we have
// to add it to the body but we take the new ? as a sign that the PI is
// ending.
this.text += "?";
}
else {
this.text += `?${String.fromCodePoint(c)}`;
this.state = S_PI_BODY;
}
this.xmlDeclPossible = false;
}
private sXMLDeclNameStart(): void {
const c = this.skipSpaces();
// The question mark character is not valid inside any of the XML
// declaration name/value pairs.
if (c === QUESTION) {
// It is valid to go to S_XML_DECL_ENDING from this state.
this.state = S_XML_DECL_ENDING;
return;
}
if (c !== EOC) {
this.state = S_XML_DECL_NAME;
this.name = String.fromCodePoint(c);
}
}
private sXMLDeclName(): void {
const c = this.captureTo(XML_DECL_NAME_TERMINATOR);
// The question mark character is not valid inside any of the XML
// declaration name/value pairs.
if (c === QUESTION) {
this.state = S_XML_DECL_ENDING;
this.name += this.text;
this.text = "";
this.fail("XML declaration is incomplete.");
return;
}
if (!(isS(c) || c === EQUAL)) {
return;
}
this.name += this.text;
this.text = "";
if (!this.xmlDeclExpects.includes(this.name)) {
switch (this.name.length) {
case 0:
this.fail("did not expect any more name/value pairs.");
break;
case 1:
this.fail(`expected the name ${this.xmlDeclExpects[0]}.`);
break;
default:
this.fail(`expected one of ${this.xmlDeclExpects.join(", ")}`);
}
}
this.state = c === EQUAL ? S_XML_DECL_VALUE_START : S_XML_DECL_EQ;
}
private sXMLDeclEq(): void {
const c = this.getCodeNorm();
// The question mark character is not valid inside any of the XML
// declaration name/value pairs.
if (c === QUESTION) {
this.state = S_XML_DECL_ENDING;
this.fail("XML declaration is incomplete.");
return;
}
if (isS(c)) {
return;
}
if (c !== EQUAL) {
this.fail("value required.");
}
this.state = S_XML_DECL_VALUE_START;
}
private sXMLDeclValueStart(): void {
const c = this.getCodeNorm();
// The question mark character is not valid inside any of the XML
// declaration name/value pairs.
if (c === QUESTION) {
this.state = S_XML_DECL_ENDING;
this.fail("XML declaration is incomplete.");
return;
}
if (isS(c)) {
return;
}
if (!isQuote(c)) {
this.fail("value must be quoted.");
this.q = SPACE;
}
else {
this.q = c;
}
this.state = S_XML_DECL_VALUE;
}
private sXMLDeclValue(): void {
const c = this.captureTo([this.q!, QUESTION]);
// The question mark character is not valid inside any of the XML
// declaration name/value pairs.
if (c === QUESTION) {
this.state = S_XML_DECL_ENDING;
this.text = "";
this.fail("XML declaration is incomplete.");
return;
}
if (c === EOC) {
return;
}
const value = this.text;
this.text = "";
switch (this.name) {
case "version": {
this.xmlDeclExpects = ["encoding", "standalone"];
const version = value;
this.xmlDecl.version = version;
// This is the test specified by XML 1.0 but it is fine for XML 1.1.
if (!/^1\.[0-9]+$/.test(version)) {
this.fail("version number must match /^1\\.[0-9]+$/.");
}
// When forceXMLVersion is set, the XML declaration is ignored.
else if (!(this.opt.forceXMLVersion as boolean)) {
this.setXMLVersion(version);
}
break;
}
case "encoding":
if (!/^[A-Za-z][A-Za-z0-9._-]*$/.test(value)) {
this.fail("encoding value must match \
/^[A-Za-z0-9][A-Za-z0-9._-]*$/.");
}
this.xmlDeclExpects = ["standalone"];
this.xmlDecl.encoding = value;
break;
case "standalone":
if (value !== "yes" && value !== "no") {
this.fail("standalone value must match \"yes\" or \"no\".");
}
this.xmlDeclExpects = [];
this.xmlDecl.standalone = value;
break;
default:
// We don't need to raise an error here since we've already raised one
// when checking what name was expected.
}
this.name = "";
this.state = S_XML_DECL_SEPARATOR;
}
private sXMLDeclSeparator(): void {
const c = this.getCodeNorm();
// The question mark character is not valid inside any of the XML
// declaration name/value pairs.
if (c === QUESTION) {
// It is valid to go to S_XML_DECL_ENDING from this state.
this.state = S_XML_DECL_ENDING;
return;
}
if (!isS(c)) {
this.fail("whitespace required.");
this.unget();
}
this.state = S_XML_DECL_NAME_START;
}
private sXMLDeclEnding(): void {
const c = this.getCodeNorm();
if (c === GREATER) {
if (this.piTarget !== "xml") {
this.fail("processing instructions are not allowed before root.");
}
else if (this.name !== "version" &&
this.xmlDeclExpects.includes("version")) {
this.fail("XML declaration must contain a version.");
}
this.xmldeclHandler?.(this.xmlDecl);
this.name = "";
this.piTarget = this.text = "";
this.state = S_TEXT;
}
else {
// We got here because the previous character was a ?, but the question
// mark character is not valid inside any of the XML declaration
// name/value pairs.
this.fail(
"The character ? is disallowed anywhere in XML declarations.");
}
this.xmlDeclPossible = false;
}
private sOpenTag(): void {
const c = this.captureNameChars();
if (c === EOC) {
return;
}
const tag: SaxesTagIncomplete = this.tag = {
name: this.name,
attributes: Object.create(null) as Record<string, string>,
};
this.name = "";
if (this.xmlnsOpt) {
this.topNS = tag.ns = Object.create(null) as Record<string, string>;
}
this.openTagStartHandler?.(tag as StartTagForOptions<O>);
this.sawRoot = true;
if (!this.fragmentOpt && this.closedRoot) {
this.fail("documents may contain only one root.");
}
switch (c) {
case GREATER:
this.openTag();
break;
case FORWARD_SLASH:
this.state = S_OPEN_TAG_SLASH;
break;
default:
if (!isS(c)) {
this.fail("disallowed character in tag name.");
}
this.state = S_ATTRIB;
}
}
private sOpenTagSlash(): void {
if (this.getCode() === GREATER) {
this.openSelfClosingTag();
}
else {
this.fail("forward-slash in opening tag not followed by >.");
this.state = S_ATTRIB;
}
}
private sAttrib(): void {
const c = this.skipSpaces();
if (c === EOC) {
return;
}
if (isNameStartChar(c)) {
this.unget();
this.state = S_ATTRIB_NAME;
}
else if (c === GREATER) {
this.openTag();
}
else if (c === FORWARD_SLASH) {
this.state = S_OPEN_TAG_SLASH;
}
else {
this.fail("disallowed character in attribute name.");
}
}
private sAttribName(): void {
const c = this.captureNameChars();
if (c === EQUAL) {
this.state = S_ATTRIB_VALUE;
}
else if (isS(c)) {
this.state = S_ATTRIB_NAME_SAW_WHITE;
}
else if (c === GREATER) {
this.fail("attribute without value.");
this.pushAttrib(this.name, this.name);
this.name = this.text = "";
this.openTag();
}
else if (c !== EOC) {
this.fail("disallowed character in attribute name.");
}
}
private sAttribNameSawWhite(): void {
const c = this.skipSpaces();
switch (c) {
case EOC:
return;
case EQUAL:
this.state = S_ATTRIB_VALUE;
break;
default:
this.fail("attribute without value.");
// Should we do this???
// this.tag.attributes[this.name] = "";
this.text = "";
this.name = "";
if (c === GREATER) {
this.openTag();
}
else if (isNameStartChar(c)) {
this.unget();
this.state = S_ATTRIB_NAME;
}
else {
this.fail("disallowed character in attribute name.");
this.state = S_ATTRIB;
}
}
}
private sAttribValue(): void {
const c = this.getCodeNorm();
if (isQuote(c)) {
this.q = c;
this.state = S_ATTRIB_VALUE_QUOTED;
}
else if (!isS(c)) {
this.fail("unquoted attribute value.");
this.state = S_ATTRIB_VALUE_UNQUOTED;
this.unget();
}
}
private sAttribValueQuoted(): void {
// We deliberately do not use captureTo here. The specialized code we use
// here is faster than using captureTo.
const { q, chunk } = this;
let { i: start } = this;
// eslint-disable-next-line no-constant-condition
while (true) {
switch (this.getCode()) {
case q:
this.pushAttrib(this.name,
this.text + chunk.slice(start, this.prevI));
this.name = this.text = "";
this.q = null;
this.state = S_ATTRIB_VALUE_CLOSED;
return;
case AMP:
this.text += chunk.slice(start, this.prevI);
this.state = S_ENTITY;
this.entityReturnState = S_ATTRIB_VALUE_QUOTED;
return;
case NL:
case NL_LIKE:
case TAB:
this.text += `${chunk.slice(start, this.prevI)} `;
start = this.i;
break;
case LESS:
this.text += chunk.slice(start, this.prevI);
this.fail("disallowed character.");
return;
case EOC:
this.text += chunk.slice(start);
return;
default:
}
}
}
private sAttribValueClosed(): void {
const c = this.getCodeNorm();
if (isS(c)) {
this.state = S_ATTRIB;
}
else if (c === GREATER) {
this.openTag();
}
else if (c === FORWARD_SLASH) {
this.state = S_OPEN_TAG_SLASH;
}
else if (isNameStartChar(c)) {
this.fail("no whitespace between attributes.");
this.unget();
this.state = S_ATTRIB_NAME;
}
else {
this.fail("disallowed character in attribute name.");
}
}
private sAttribValueUnquoted(): void {
// We don't do anything regarding EOL or space handling for unquoted
// attributes. We already have failed by the time we get here, and the
// contract that saxes upholds states that upon failure, it is not safe to
// rely on the data passed to event handlers (other than
// ``onerror``). Passing "bad" data is not a problem.
const c = this.captureTo(ATTRIB_VALUE_UNQUOTED_TERMINATOR);
switch (c) {
case AMP:
this.state = S_ENTITY;
this.entityReturnState = S_ATTRIB_VALUE_UNQUOTED;
break;
case LESS:
this.fail("disallowed character.");
break;
case EOC:
break;
default:
if (this.text.includes("]]>")) {
this.fail("the string \"]]>\" is disallowed in char data.");
}
this.pushAttrib(this.name, this.text);
this.name = this.text = "";
if (c === GREATER) {
this.openTag();
}
else {
this.state = S_ATTRIB;
}
}
}
private sCloseTag(): void {
const c = this.captureNameChars();
if (c === GREATER) {
this.closeTag();
}
else if (isS(c)) {
this.state = S_CLOSE_TAG_SAW_WHITE;
}
else if (c !== EOC) {
this.fail("disallowed character in closing tag.");
}
}
private sCloseTagSawWhite(): void {
switch (this.skipSpaces()) {
case GREATER:
this.closeTag();
break;
case EOC:
break;
default:
this.fail("disallowed character in closing tag.");
}
}
// END OF STATE ENGINE METHODS
private handleTextInRoot(): void {
// This is essentially a specialized version of captureTo which is optimized
// for performing the ]]> check. A previous version of this code, checked
// ``this.text`` for the presence of ]]>. It simplified the code but was
// very costly when character data contained a lot of entities to be parsed.
//
// Since we are using a specialized loop, we also keep track of the presence
// of ]]> in text data. The sequence ]]> is forbidden to appear as-is.
//
let { i: start, forbiddenState } = this;
const { chunk, textHandler: handler } = this;
// eslint-disable-next-line no-labels, no-restricted-syntax
scanLoop:
// eslint-disable-next-line no-constant-condition
while (true) {
switch (this.getCode()) {
case LESS: {
this.state = S_OPEN_WAKA;
if (handler !== undefined) {
const { text } = this;
const slice = chunk.slice(start, this.prevI);
if (text.length !== 0) {
handler(text + slice);
this.text = "";
}
else if (slice.length !== 0) {
handler(slice);
}
}
forbiddenState = FORBIDDEN_START;
// eslint-disable-next-line no-labels
break scanLoop;
}
case AMP:
this.state = S_ENTITY;
this.entityReturnState = S_TEXT;
if (handler !== undefined) {
this.text += chunk.slice(start, this.prevI);
}
forbiddenState = FORBIDDEN_START;
// eslint-disable-next-line no-labels
break scanLoop;
case CLOSE_BRACKET:
switch (forbiddenState) {
case FORBIDDEN_START:
forbiddenState = FORBIDDEN_BRACKET;
break;
case FORBIDDEN_BRACKET:
forbiddenState = FORBIDDEN_BRACKET_BRACKET;
break;
case FORBIDDEN_BRACKET_BRACKET:
break;
default:
throw new Error("impossible state");
}
break;
case GREATER:
if (forbiddenState === FORBIDDEN_BRACKET_BRACKET) {
this.fail("the string \"]]>\" is disallowed in char data.");
}
forbiddenState = FORBIDDEN_START;
break;
case NL_LIKE:
if (handler !== undefined) {
this.text += `${chunk.slice(start, this.prevI)}\n`;
}
start = this.i;
forbiddenState = FORBIDDEN_START;
break;
case EOC:
if (handler !== undefined) {
this.text += chunk.slice(start);
}
// eslint-disable-next-line no-labels
break scanLoop;
default:
forbiddenState = FORBIDDEN_START;
}
}
this.forbiddenState = forbiddenState;
}
private handleTextOutsideRoot(): void {
// This is essentially a specialized version of captureTo which is optimized
// for a specialized task. We keep track of the presence of non-space
// characters in the text since these are errors when appearing outside the
// document root element.
let { i: start } = this;
const { chunk, textHandler: handler } = this;
let nonSpace = false;
// eslint-disable-next-line no-labels, no-restricted-syntax
outRootLoop:
// eslint-disable-next-line no-constant-condition
while (true) {
const code = this.getCode();
switch (code) {
case LESS: {
this.state = S_OPEN_WAKA;
if (handler !== undefined) {
const { text } = this;
const slice = chunk.slice(start, this.prevI);
if (text.length !== 0) {
handler(text + slice);
this.text = "";
}
else if (slice.length !== 0) {
handler(slice);
}
}
// eslint-disable-next-line no-labels
break outRootLoop;
}
case AMP:
this.state = S_ENTITY;
this.entityReturnState = S_TEXT;
if (handler !== undefined) {
this.text += chunk.slice(start, this.prevI);
}
nonSpace = true;
// eslint-disable-next-line no-labels
break outRootLoop;
case NL_LIKE:
if (handler !== undefined) {
this.text += `${chunk.slice(start, this.prevI)}\n`;
}
start = this.i;
break;
case EOC:
if (handler !== undefined) {
this.text += chunk.slice(start);
}
// eslint-disable-next-line no-labels
break outRootLoop;
default:
if (!isS(code)) {
nonSpace = true;
}
}
}
if (!nonSpace) {
return;
}
// We use the reportedTextBeforeRoot and reportedTextAfterRoot flags
// to avoid reporting errors for every single character that is out of
// place.
if (!this.sawRoot && !this.reportedTextBeforeRoot) {
this.fail("text data outside of root node.");
this.reportedTextBeforeRoot = true;
}
if (this.closedRoot && !this.reportedTextAfterRoot) {
this.fail("text data outside of root node.");
this.reportedTextAfterRoot = true;
}
}
private pushAttribNS(name: string, value: string): void {
const { prefix, local } = this.qname(name);
const attr = { name, prefix, local, value };
this.attribList.push(attr);
this.attributeHandler?.(attr as AttributeEventForOptions<O>);
if (prefix === "xmlns") {
const trimmed = value.trim();
if (this.currentXMLVersion === "1.0" && trimmed === "") {
this.fail("invalid attempt to undefine prefix in XML 1.0");
}
this.topNS![local] = trimmed;
nsPairCheck(this, local, trimmed);
}
else if (name === "xmlns") {
const trimmed = value.trim();
this.topNS![""] = trimmed;
nsPairCheck(this, "", trimmed);
}
}
private pushAttribPlain(name: string, value: string): void {
const attr = { name, value };
this.attribList.push(attr);
this.attributeHandler?.(attr as AttributeEventForOptions<O>);
}
/**
* End parsing. This performs final well-formedness checks and resets the
* parser to a clean state.
*
* @returns this
*/
private end(): this {
if (!this.sawRoot) {
this.fail("document must contain a root element.");
}
const { tags } = this;
while (tags.length > 0) {
const tag = tags.pop()!;
this.fail(`unclosed tag: ${tag.name}`);
}
if ((this.state !== S_BEGIN) && (this.state !== S_TEXT)) {
this.fail("unexpected end.");
}
const { text } = this;
if (text.length !== 0) {
this.textHandler?.(text);
this.text = "";
}
this._closed = true;
this.endHandler?.();
this._init();
return this;
}
/**
* Resolve a namespace prefix.
*
* @param prefix The prefix to resolve.
*
* @returns The namespace URI or ``undefined`` if the prefix is not defined.
*/
resolve(prefix: string): string | undefined {
let uri = this.topNS![prefix];
if (uri !== undefined) {
return uri;
}
const { tags } = this;
for (let index = tags.length - 1; index >= 0; index--) {
uri = tags[index]!.ns![prefix];
if (uri !== undefined) {
return uri;
}
}
uri = this.ns[prefix];
if (uri !== undefined) {
return uri;
}
return this.opt.resolvePrefix?.(prefix);
}
/**
* Parse a qname into its prefix and local name parts.
*
* @param name The name to parse
*
* @returns
*/
private qname(name: string): { prefix: string; local: string } {
// This is faster than using name.split(":").
const colon = name.indexOf(":");
if (colon === -1) {
return { prefix: "", local: name };
}
const local = name.slice(colon + 1);
const prefix = name.slice(0, colon);
if (prefix === "" || local === "" || local.includes(":")) {
this.fail(`malformed name: ${name}.`);
}
return { prefix, local };
}
private processAttribsNS(): void {
const { attribList } = this;
const tag = this.tag!;
{
// add namespace info to tag
const { prefix, local } = this.qname(tag.name);
tag.prefix = prefix;
tag.local = local;
const uri = tag.uri = this.resolve(prefix) ?? "";
if (prefix !== "") {
if (prefix === "xmlns") {
this.fail("tags may not have \"xmlns\" as prefix.");
}
if (uri === "") {
this.fail(`unbound namespace prefix: ${JSON.stringify(prefix)}.`);
tag.uri = prefix;
}
}
}
if (attribList.length === 0) {
return;
}
const { attributes } = tag;
const seen = new Set();
// Note: do not apply default ns to attributes:
// http://www.w3.org/TR/REC-xml-names/#defaulting
for (const attr of attribList as SaxesAttributeNSIncomplete[]) {
const { name, prefix, local } = attr;
let uri;
let eqname;
if (prefix === "") {
uri = name === "xmlns" ? XMLNS_NAMESPACE : "";
eqname = name;
}
else {
uri = this.resolve(prefix);
// if there's any attributes with an undefined namespace,
// then fail on them now.
if (uri === undefined) {
this.fail(`unbound namespace prefix: ${JSON.stringify(prefix)}.`);
uri = prefix;
}
eqname = `{${uri}}${local}`;
}
if (seen.has(eqname)) {
this.fail(`duplicate attribute: ${eqname}.`);
}
seen.add(eqname);
attr.uri = uri;
attributes[name] = attr;
}
this.attribList = [];
}
private processAttribsPlain(): void {
const { attribList } = this;
// eslint-disable-next-line prefer-destructuring
const attributes = this.tag!.attributes;
for (const { name, value } of attribList) {
if (attributes[name] !== undefined) {
this.fail(`duplicate attribute: ${name}.`);
}
attributes[name] = value;
}
this.attribList = [];
}
/**
* Handle a complete open tag. This parser code calls this once it has seen
* the whole tag. This method checks for well-formeness and then emits
* ``onopentag``.
*/
private openTag(): void {
this.processAttribs();
const { tags } = this;
const tag = this.tag as SaxesTag;
tag.isSelfClosing = false;
// There cannot be any pending text here due to the onopentagstart that was
// necessarily emitted before we get here. So we do not check text.
this.openTagHandler?.(tag as TagForOptions<O>);
tags.push(tag);
this.state = S_TEXT;
this.name = "";
}
/**
* Handle a complete self-closing tag. This parser code calls this once it has
* seen the whole tag. This method checks for well-formeness and then emits
* ``onopentag`` and ``onclosetag``.
*/
private openSelfClosingTag(): void {
this.processAttribs();
const { tags } = this;
const tag = this.tag as SaxesTag;
tag.isSelfClosing = true;
// There cannot be any pending text here due to the onopentagstart that was
// necessarily emitted before we get here. So we do not check text.
this.openTagHandler?.(tag as TagForOptions<O>);
this.closeTagHandler?.(tag as TagForOptions<O>);
const top = this.tag = tags[tags.length - 1] ?? null;
if (top === null) {
this.closedRoot = true;
}
this.state = S_TEXT;
this.name = "";
}
/**
* Handle a complete close tag. This parser code calls this once it has seen
* the whole tag. This method checks for well-formeness and then emits
* ``onclosetag``.
*/
private closeTag(): void {
const { tags, name } = this;
// Our state after this will be S_TEXT, no matter what, and we can clear
// tagName now.
this.state = S_TEXT;
this.name = "";
if (name === "") {
this.fail("weird empty close tag.");
this.text += "</>";
return;
}
const handler = this.closeTagHandler;
let l = tags.length;
while (l-- > 0) {
const tag = this.tag = tags.pop() as SaxesTag;
this.topNS = tag.ns!;
handler?.(tag as TagForOptions<O>);
if (tag.name === name) {
break;
}
this.fail("unexpected close tag.");
}
if (l === 0) {
this.closedRoot = true;
}
else if (l < 0) {
this.fail(`unmatched closing tag: ${name}.`);
this.text += `</${name}>`;
}
}
/**
* Resolves an entity. Makes any necessary well-formedness checks.
*
* @param entity The entity to resolve.
*
* @returns The parsed entity.
*/
private parseEntity(entity: string): string {
// startsWith would be significantly slower for this test.
if (entity[0] !== "#") {
const defined = this.ENTITIES[entity];
if (defined !== undefined) {
return defined;
}
this.fail(this.isName(entity) ? "undefined entity." :
"disallowed character in entity name.");
return `&${entity};`;
}
let num = NaN;
if (entity[1] === "x" && /^#x[0-9a-f]+$/i.test(entity)) {
num = parseInt(entity.slice(2), 16);
}
else if (/^#[0-9]+$/.test(entity)) {
num = parseInt(entity.slice(1), 10);
}
// The character reference is required to match the CHAR production.
if (!this.isChar(num)) {
this.fail("malformed character entity.");
return `&${entity};`;
}
return String.fromCodePoint(num);
}
} |
1,145 | fn(parser: SaxesParser): void {
for (const x of cr) {
parser.write(x);
}
parser.close();
} | class SaxesParser<O extends SaxesOptions = {}> {
private readonly fragmentOpt: boolean;
private readonly xmlnsOpt: boolean;
private readonly trackPosition: boolean;
private readonly fileName?: string;
private readonly nameStartCheck: (c: number) => boolean;
private readonly nameCheck: (c: number) => boolean;
private readonly isName: (name: string) => boolean;
private readonly ns!: Record<string, string>;
private openWakaBang!: string;
private text!: string;
private name!: string;
private piTarget!: string;
private entity!: string;
private q!: null | number;
private tags!: SaxesTagIncomplete[];
private tag!: SaxesTagIncomplete | null;
private topNS!: Record<string, string> | null;
private chunk!: string;
private chunkPosition!: number;
private i!: number;
//
// We use prevI to allow "ungetting" the previously read code point. Note
// however, that it is not safe to unget everything and anything. In
// particular ungetting EOL characters will screw positioning up.
//
// Practically, you must not unget a code which has any side effect beyond
// updating ``this.i`` and ``this.prevI``. Only EOL codes have such side
// effects.
//
private prevI!: number;
private carriedFromPrevious?: string;
private forbiddenState!: number;
private attribList!: (SaxesAttributeNSIncomplete | SaxesAttributePlain)[];
private state!: number;
private reportedTextBeforeRoot!: boolean;
private reportedTextAfterRoot!: boolean;
private closedRoot!: boolean;
private sawRoot!: boolean;
private xmlDeclPossible!: boolean;
private xmlDeclExpects!: string[];
private entityReturnState?: number;
private processAttribs!: (this: this) => void;
private positionAtNewLine!: number;
private doctype!: boolean;
private getCode!: () => number;
private isChar!: (c: number) => boolean;
private pushAttrib!: (name: string, value: string) => void;
private _closed!: boolean;
private currentXMLVersion!: string;
private readonly stateTable: ((this: SaxesParser<O>) => void)[];
private xmldeclHandler?: XMLDeclHandler;
private textHandler?: TextHandler;
private piHandler?: PIHandler;
private doctypeHandler?: DoctypeHandler;
private commentHandler?: CommentHandler;
private openTagStartHandler?: OpenTagStartHandler<O>;
private openTagHandler?: OpenTagHandler<O>;
private closeTagHandler?: CloseTagHandler<O>;
private cdataHandler?: CDataHandler;
private errorHandler?: ErrorHandler;
private endHandler?: EndHandler;
private readyHandler?: ReadyHandler;
private attributeHandler?: AttributeHandler<O>;
/**
* Indicates whether or not the parser is closed. If ``true``, wait for
* the ``ready`` event to write again.
*/
get closed(): boolean {
return this._closed;
}
readonly opt: SaxesOptions;
/**
* The XML declaration for this document.
*/
xmlDecl!: XMLDecl;
/**
* The line number of the next character to be read by the parser. This field
* is one-based. (The first line is numbered 1.)
*/
line!: number;
/**
* The column number of the next character to be read by the parser. *
* This field is zero-based. (The first column is 0.)
*
* This field counts columns by *Unicode character*. Note that this *can*
* be different from the index of the character in a JavaScript string due
* to how JavaScript handles astral plane characters.
*
* See [[columnIndex]] for a number that corresponds to the JavaScript index.
*/
column!: number;
/**
* A map of entity name to expansion.
*/
ENTITIES!: Record<string, string>;
/**
* @param opt The parser options.
*/
constructor(opt?: O) {
this.opt = opt ?? {};
this.fragmentOpt = !!(this.opt.fragment as boolean);
const xmlnsOpt = this.xmlnsOpt = !!(this.opt.xmlns as boolean);
this.trackPosition = this.opt.position !== false;
this.fileName = this.opt.fileName;
if (xmlnsOpt) {
// This is the function we use to perform name checks on PIs and entities.
// When namespaces are used, colons are not allowed in PI target names or
// entity names. So the check depends on whether namespaces are used. See:
//
// https://www.w3.org/XML/xml-names-19990114-errata.html
// NE08
//
this.nameStartCheck = isNCNameStartChar;
this.nameCheck = isNCNameChar;
this.isName = isNCName;
// eslint-disable-next-line @typescript-eslint/unbound-method
this.processAttribs = this.processAttribsNS;
// eslint-disable-next-line @typescript-eslint/unbound-method
this.pushAttrib = this.pushAttribNS;
// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-assignment
this.ns = { __proto__: null as any, ...rootNS };
const additional = this.opt.additionalNamespaces;
if (additional != null) {
nsMappingCheck(this, additional);
Object.assign(this.ns, additional);
}
}
else {
this.nameStartCheck = isNameStartChar;
this.nameCheck = isNameChar;
this.isName = isName;
// eslint-disable-next-line @typescript-eslint/unbound-method
this.processAttribs = this.processAttribsPlain;
// eslint-disable-next-line @typescript-eslint/unbound-method
this.pushAttrib = this.pushAttribPlain;
}
//
// The order of the members in this table needs to correspond to the state
// numbers given to the states that correspond to the methods being recorded
// here.
//
this.stateTable = [
/* eslint-disable @typescript-eslint/unbound-method */
this.sBegin,
this.sBeginWhitespace,
this.sDoctype,
this.sDoctypeQuote,
this.sDTD,
this.sDTDQuoted,
this.sDTDOpenWaka,
this.sDTDOpenWakaBang,
this.sDTDComment,
this.sDTDCommentEnding,
this.sDTDCommentEnded,
this.sDTDPI,
this.sDTDPIEnding,
this.sText,
this.sEntity,
this.sOpenWaka,
this.sOpenWakaBang,
this.sComment,
this.sCommentEnding,
this.sCommentEnded,
this.sCData,
this.sCDataEnding,
this.sCDataEnding2,
this.sPIFirstChar,
this.sPIRest,
this.sPIBody,
this.sPIEnding,
this.sXMLDeclNameStart,
this.sXMLDeclName,
this.sXMLDeclEq,
this.sXMLDeclValueStart,
this.sXMLDeclValue,
this.sXMLDeclSeparator,
this.sXMLDeclEnding,
this.sOpenTag,
this.sOpenTagSlash,
this.sAttrib,
this.sAttribName,
this.sAttribNameSawWhite,
this.sAttribValue,
this.sAttribValueQuoted,
this.sAttribValueClosed,
this.sAttribValueUnquoted,
this.sCloseTag,
this.sCloseTagSawWhite,
/* eslint-enable @typescript-eslint/unbound-method */
];
this._init();
}
_init(): void {
this.openWakaBang = "";
this.text = "";
this.name = "";
this.piTarget = "";
this.entity = "";
this.q = null;
this.tags = [];
this.tag = null;
this.topNS = null;
this.chunk = "";
this.chunkPosition = 0;
this.i = 0;
this.prevI = 0;
this.carriedFromPrevious = undefined;
this.forbiddenState = FORBIDDEN_START;
this.attribList = [];
// The logic is organized so as to minimize the need to check
// this.opt.fragment while parsing.
const { fragmentOpt } = this;
this.state = fragmentOpt ? S_TEXT : S_BEGIN;
// We want these to be all true if we are dealing with a fragment.
this.reportedTextBeforeRoot = this.reportedTextAfterRoot = this.closedRoot =
this.sawRoot = fragmentOpt;
// An XML declaration is intially possible only when parsing whole
// documents.
this.xmlDeclPossible = !fragmentOpt;
this.xmlDeclExpects = ["version"];
this.entityReturnState = undefined;
let { defaultXMLVersion } = this.opt;
if (defaultXMLVersion === undefined) {
if (this.opt.forceXMLVersion === true) {
throw new Error("forceXMLVersion set but defaultXMLVersion is not set");
}
defaultXMLVersion = "1.0";
}
this.setXMLVersion(defaultXMLVersion);
this.positionAtNewLine = 0;
this.doctype = false;
this._closed = false;
this.xmlDecl = {
version: undefined,
encoding: undefined,
standalone: undefined,
};
this.line = 1;
this.column = 0;
this.ENTITIES = Object.create(XML_ENTITIES) as Record<string, string>;
this.readyHandler?.();
}
/**
* The stream position the parser is currently looking at. This field is
* zero-based.
*
* This field is not based on counting Unicode characters but is to be
* interpreted as a plain index into a JavaScript string.
*/
get position(): number {
return this.chunkPosition + this.i;
}
/**
* The column number of the next character to be read by the parser. *
* This field is zero-based. (The first column in a line is 0.)
*
* This field reports the index at which the next character would be in the
* line if the line were represented as a JavaScript string. Note that this
* *can* be different to a count based on the number of *Unicode characters*
* due to how JavaScript handles astral plane characters.
*
* See [[column]] for a number that corresponds to a count of Unicode
* characters.
*/
get columnIndex(): number {
return this.position - this.positionAtNewLine;
}
/**
* Set an event listener on an event. The parser supports one handler per
* event type. If you try to set an event handler over an existing handler,
* the old handler is silently overwritten.
*
* @param name The event to listen to.
*
* @param handler The handler to set.
*/
on<N extends EventName>(name: N, handler: EventNameToHandler<O, N>): void {
// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-member-access
(this as any)[EVENT_NAME_TO_HANDLER_NAME[name]] = handler;
}
/**
* Unset an event handler.
*
* @parma name The event to stop listening to.
*/
off(name: EventName): void {
// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-member-access
(this as any)[EVENT_NAME_TO_HANDLER_NAME[name]] = undefined;
}
/**
* Make an error object. The error object will have a message that contains
* the ``fileName`` option passed at the creation of the parser. If position
* tracking was turned on, it will also have line and column number
* information.
*
* @param message The message describing the error to report.
*
* @returns An error object with a properly formatted message.
*/
makeError(message: string): Error {
let msg = this.fileName ?? "";
if (this.trackPosition) {
if (msg.length > 0) {
msg += ":";
}
msg += `${this.line}:${this.column}`;
}
if (msg.length > 0) {
msg += ": ";
}
return new Error(msg + message);
}
/**
* Report a parsing error. This method is made public so that client code may
* check for issues that are outside the scope of this project and can report
* errors.
*
* @param message The error to report.
*
* @returns this
*/
fail(message: string): this {
const err = this.makeError(message);
const handler = this.errorHandler;
if (handler === undefined) {
throw err;
}
else {
handler(err);
}
return this;
}
/**
* Write a XML data to the parser.
*
* @param chunk The XML data to write.
*
* @returns this
*/
// We do need object for the type here. Yes, it often causes problems
// but not in this case.
write(chunk: string | object | null): this {
if (this.closed) {
return this.fail("cannot write after close; assign an onready handler.");
}
let end = false;
if (chunk === null) {
// We cannot return immediately because carriedFromPrevious may need
// processing.
end = true;
chunk = "";
}
else if (typeof chunk === "object") {
chunk = chunk.toString();
}
// We checked if performing a pre-decomposition of the string into an array
// of single complete characters (``Array.from(chunk)``) would be faster
// than the current repeated calls to ``charCodeAt``. As of August 2018, it
// isn't. (There may be Node-specific code that would perform faster than
// ``Array.from`` but don't want to be dependent on Node.)
if (this.carriedFromPrevious !== undefined) {
// The previous chunk had char we must carry over.
chunk = `${this.carriedFromPrevious}${chunk}`;
this.carriedFromPrevious = undefined;
}
let limit = chunk.length;
const lastCode = chunk.charCodeAt(limit - 1);
if (!end &&
// A trailing CR or surrogate must be carried over to the next
// chunk.
(lastCode === CR || (lastCode >= 0xD800 && lastCode <= 0xDBFF))) {
// The chunk ends with a character that must be carried over. We cannot
// know how to handle it until we get the next chunk or the end of the
// stream. So save it for later.
this.carriedFromPrevious = chunk[limit - 1];
limit--;
chunk = chunk.slice(0, limit);
}
const { stateTable } = this;
this.chunk = chunk;
this.i = 0;
while (this.i < limit) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-argument
stateTable[this.state].call(this as any);
}
this.chunkPosition += limit;
return end ? this.end() : this;
}
/**
* Close the current stream. Perform final well-formedness checks and reset
* the parser tstate.
*
* @returns this
*/
close(): this {
return this.write(null);
}
/**
* Get a single code point out of the current chunk. This updates the current
* position if we do position tracking.
*
* This is the algorithm to use for XML 1.0.
*
* @returns The character read.
*/
private getCode10(): number {
const { chunk, i } = this;
this.prevI = i;
// Yes, we do this instead of doing this.i++. Doing it this way, we do not
// read this.i again, which is a bit faster.
this.i = i + 1;
if (i >= chunk.length) {
return EOC;
}
// Using charCodeAt and handling the surrogates ourselves is faster
// than using codePointAt.
const code = chunk.charCodeAt(i);
this.column++;
if (code < 0xD800) {
if (code >= SPACE || code === TAB) {
return code;
}
switch (code) {
case NL:
this.line++;
this.column = 0;
this.positionAtNewLine = this.position;
return NL;
case CR:
// We may get NaN if we read past the end of the chunk, which is fine.
if (chunk.charCodeAt(i + 1) === NL) {
// A \r\n sequence is converted to \n so we have to skip over the
// next character. We already know it has a size of 1 so ++ is fine
// here.
this.i = i + 2;
}
// Otherwise, a \r is just converted to \n, so we don't have to skip
// ahead.
// In either case, \r becomes \n.
this.line++;
this.column = 0;
this.positionAtNewLine = this.position;
return NL_LIKE;
default:
// If we get here, then code < SPACE and it is not NL CR or TAB.
this.fail("disallowed character.");
return code;
}
}
if (code > 0xDBFF) {
// This is a specialized version of isChar10 that takes into account
// that in this context code > 0xDBFF and code <= 0xFFFF. So it does not
// test cases that don't need testing.
if (!(code >= 0xE000 && code <= 0xFFFD)) {
this.fail("disallowed character.");
}
return code;
}
const final = 0x10000 + ((code - 0xD800) * 0x400) +
(chunk.charCodeAt(i + 1) - 0xDC00);
this.i = i + 2;
// This is a specialized version of isChar10 that takes into account that in
// this context necessarily final >= 0x10000.
if (final > 0x10FFFF) {
this.fail("disallowed character.");
}
return final;
}
/**
* Get a single code point out of the current chunk. This updates the current
* position if we do position tracking.
*
* This is the algorithm to use for XML 1.1.
*
* @returns {number} The character read.
*/
private getCode11(): number {
const { chunk, i } = this;
this.prevI = i;
// Yes, we do this instead of doing this.i++. Doing it this way, we do not
// read this.i again, which is a bit faster.
this.i = i + 1;
if (i >= chunk.length) {
return EOC;
}
// Using charCodeAt and handling the surrogates ourselves is faster
// than using codePointAt.
const code = chunk.charCodeAt(i);
this.column++;
if (code < 0xD800) {
if ((code > 0x1F && code < 0x7F) || (code > 0x9F && code !== LS) ||
code === TAB) {
return code;
}
switch (code) {
case NL: // 0xA
this.line++;
this.column = 0;
this.positionAtNewLine = this.position;
return NL;
case CR: { // 0xD
// We may get NaN if we read past the end of the chunk, which is
// fine.
const next = chunk.charCodeAt(i + 1);
if (next === NL || next === NEL) {
// A CR NL or CR NEL sequence is converted to NL so we have to skip
// over the next character. We already know it has a size of 1.
this.i = i + 2;
}
// Otherwise, a CR is just converted to NL, no skip.
}
/* yes, fall through */
case NEL: // 0x85
case LS: // Ox2028
this.line++;
this.column = 0;
this.positionAtNewLine = this.position;
return NL_LIKE;
default:
this.fail("disallowed character.");
return code;
}
}
if (code > 0xDBFF) {
// This is a specialized version of isCharAndNotRestricted that takes into
// account that in this context code > 0xDBFF and code <= 0xFFFF. So it
// does not test cases that don't need testing.
if (!(code >= 0xE000 && code <= 0xFFFD)) {
this.fail("disallowed character.");
}
return code;
}
const final = 0x10000 + ((code - 0xD800) * 0x400) +
(chunk.charCodeAt(i + 1) - 0xDC00);
this.i = i + 2;
// This is a specialized version of isCharAndNotRestricted that takes into
// account that in this context necessarily final >= 0x10000.
if (final > 0x10FFFF) {
this.fail("disallowed character.");
}
return final;
}
/**
* Like ``getCode`` but with the return value normalized so that ``NL`` is
* returned for ``NL_LIKE``.
*/
private getCodeNorm(): number {
const c = this.getCode();
return c === NL_LIKE ? NL : c;
}
private unget(): void {
this.i = this.prevI;
this.column--;
}
/**
* Capture characters into a buffer until encountering one of a set of
* characters.
*
* @param chars An array of codepoints. Encountering a character in the array
* ends the capture. (``chars`` may safely contain ``NL``.)
*
* @return The character code that made the capture end, or ``EOC`` if we hit
* the end of the chunk. The return value cannot be NL_LIKE: NL is returned
* instead.
*/
private captureTo(chars: number[]): number {
let { i: start } = this;
const { chunk } = this;
// eslint-disable-next-line no-constant-condition
while (true) {
const c = this.getCode();
const isNLLike = c === NL_LIKE;
const final = isNLLike ? NL : c;
if (final === EOC || chars.includes(final)) {
this.text += chunk.slice(start, this.prevI);
return final;
}
if (isNLLike) {
this.text += `${chunk.slice(start, this.prevI)}\n`;
start = this.i;
}
}
}
/**
* Capture characters into a buffer until encountering a character.
*
* @param char The codepoint that ends the capture. **NOTE ``char`` MAY NOT
* CONTAIN ``NL``.** Passing ``NL`` will result in buggy behavior.
*
* @return ``true`` if we ran into the character. Otherwise, we ran into the
* end of the current chunk.
*/
private captureToChar(char: number): boolean {
let { i: start } = this;
const { chunk } = this;
// eslint-disable-next-line no-constant-condition
while (true) {
let c = this.getCode();
switch (c) {
case NL_LIKE:
this.text += `${chunk.slice(start, this.prevI)}\n`;
start = this.i;
c = NL;
break;
case EOC:
this.text += chunk.slice(start);
return false;
default:
}
if (c === char) {
this.text += chunk.slice(start, this.prevI);
return true;
}
}
}
/**
* Capture characters that satisfy ``isNameChar`` into the ``name`` field of
* this parser.
*
* @return The character code that made the test fail, or ``EOC`` if we hit
* the end of the chunk. The return value cannot be NL_LIKE: NL is returned
* instead.
*/
private captureNameChars(): number {
const { chunk, i: start } = this;
// eslint-disable-next-line no-constant-condition
while (true) {
const c = this.getCode();
if (c === EOC) {
this.name += chunk.slice(start);
return EOC;
}
// NL is not a name char so we don't have to test specifically for it.
if (!isNameChar(c)) {
this.name += chunk.slice(start, this.prevI);
return c === NL_LIKE ? NL : c;
}
}
}
/**
* Skip white spaces.
*
* @return The character that ended the skip, or ``EOC`` if we hit
* the end of the chunk. The return value cannot be NL_LIKE: NL is returned
* instead.
*/
private skipSpaces(): number {
// eslint-disable-next-line no-constant-condition
while (true) {
const c = this.getCodeNorm();
if (c === EOC || !isS(c)) {
return c;
}
}
}
private setXMLVersion(version: string): void {
this.currentXMLVersion = version;
/* eslint-disable @typescript-eslint/unbound-method */
if (version === "1.0") {
this.isChar = isChar10;
this.getCode = this.getCode10;
}
else {
this.isChar = isChar11;
this.getCode = this.getCode11;
}
/* eslint-enable @typescript-eslint/unbound-method */
}
// STATE ENGINE METHODS
// This needs to be a state separate from S_BEGIN_WHITESPACE because we want
// to be sure never to come back to this state later.
private sBegin(): void {
// We are essentially peeking at the first character of the chunk. Since
// S_BEGIN can be in effect only when we start working on the first chunk,
// the index at which we must look is necessarily 0. Note also that the
// following test does not depend on decoding surrogates.
// If the initial character is 0xFEFF, ignore it.
if (this.chunk.charCodeAt(0) === 0xFEFF) {
this.i++;
this.column++;
}
this.state = S_BEGIN_WHITESPACE;
}
private sBeginWhitespace(): void {
// We need to know whether we've encountered spaces or not because as soon
// as we run into a space, an XML declaration is no longer possible. Rather
// than slow down skipSpaces even in places where we don't care whether it
// skipped anything or not, we check whether prevI is equal to the value of
// i from before we skip spaces.
const iBefore = this.i;
const c = this.skipSpaces();
if (this.prevI !== iBefore) {
this.xmlDeclPossible = false;
}
switch (c) {
case LESS:
this.state = S_OPEN_WAKA;
// We could naively call closeText but in this state, it is not normal
// to have text be filled with any data.
if (this.text.length !== 0) {
throw new Error("no-empty text at start");
}
break;
case EOC:
break;
default:
this.unget();
this.state = S_TEXT;
this.xmlDeclPossible = false;
}
}
private sDoctype(): void {
const c = this.captureTo(DOCTYPE_TERMINATOR);
switch (c) {
case GREATER: {
this.doctypeHandler?.(this.text);
this.text = "";
this.state = S_TEXT;
this.doctype = true; // just remember that we saw it.
break;
}
case EOC:
break;
default:
this.text += String.fromCodePoint(c);
if (c === OPEN_BRACKET) {
this.state = S_DTD;
}
else if (isQuote(c)) {
this.state = S_DOCTYPE_QUOTE;
this.q = c;
}
}
}
private sDoctypeQuote(): void {
const q = this.q!;
if (this.captureToChar(q)) {
this.text += String.fromCodePoint(q);
this.q = null;
this.state = S_DOCTYPE;
}
}
private sDTD(): void {
const c = this.captureTo(DTD_TERMINATOR);
if (c === EOC) {
return;
}
this.text += String.fromCodePoint(c);
if (c === CLOSE_BRACKET) {
this.state = S_DOCTYPE;
}
else if (c === LESS) {
this.state = S_DTD_OPEN_WAKA;
}
else if (isQuote(c)) {
this.state = S_DTD_QUOTED;
this.q = c;
}
}
private sDTDQuoted(): void {
const q = this.q!;
if (this.captureToChar(q)) {
this.text += String.fromCodePoint(q);
this.state = S_DTD;
this.q = null;
}
}
private sDTDOpenWaka(): void {
const c = this.getCodeNorm();
this.text += String.fromCodePoint(c);
switch (c) {
case BANG:
this.state = S_DTD_OPEN_WAKA_BANG;
this.openWakaBang = "";
break;
case QUESTION:
this.state = S_DTD_PI;
break;
default:
this.state = S_DTD;
}
}
private sDTDOpenWakaBang(): void {
const char = String.fromCodePoint(this.getCodeNorm());
const owb = this.openWakaBang += char;
this.text += char;
if (owb !== "-") {
this.state = owb === "--" ? S_DTD_COMMENT : S_DTD;
this.openWakaBang = "";
}
}
private sDTDComment(): void {
if (this.captureToChar(MINUS)) {
this.text += "-";
this.state = S_DTD_COMMENT_ENDING;
}
}
private sDTDCommentEnding(): void {
const c = this.getCodeNorm();
this.text += String.fromCodePoint(c);
this.state = c === MINUS ? S_DTD_COMMENT_ENDED : S_DTD_COMMENT;
}
private sDTDCommentEnded(): void {
const c = this.getCodeNorm();
this.text += String.fromCodePoint(c);
if (c === GREATER) {
this.state = S_DTD;
}
else {
this.fail("malformed comment.");
// <!-- blah -- bloo --> will be recorded as
// a comment of " blah -- bloo "
this.state = S_DTD_COMMENT;
}
}
private sDTDPI(): void {
if (this.captureToChar(QUESTION)) {
this.text += "?";
this.state = S_DTD_PI_ENDING;
}
}
private sDTDPIEnding(): void {
const c = this.getCodeNorm();
this.text += String.fromCodePoint(c);
if (c === GREATER) {
this.state = S_DTD;
}
}
private sText(): void {
//
// We did try a version of saxes where the S_TEXT state was split in two
// states: one for text inside the root element, and one for text
// outside. This was avoiding having to test this.tags.length to decide
// what implementation to actually use.
//
// Peformance testing on gigabyte-size files did not show any advantage to
// using the two states solution instead of the current one. Conversely, it
// made the code a bit more complicated elsewhere. For instance, a comment
// can appear before the root element so when a comment ended it was
// necessary to determine whether to return to the S_TEXT state or to the
// new text-outside-root state.
//
if (this.tags.length !== 0) {
this.handleTextInRoot();
}
else {
this.handleTextOutsideRoot();
}
}
private sEntity(): void {
// This is essentially a specialized version of captureToChar(SEMICOLON...)
let { i: start } = this;
const { chunk } = this;
// eslint-disable-next-line no-labels, no-restricted-syntax
loop:
// eslint-disable-next-line no-constant-condition
while (true) {
switch (this.getCode()) {
case NL_LIKE:
this.entity += `${chunk.slice(start, this.prevI)}\n`;
start = this.i;
break;
case SEMICOLON: {
const { entityReturnState } = this;
const entity = this.entity + chunk.slice(start, this.prevI);
this.state = entityReturnState!;
let parsed: string;
if (entity === "") {
this.fail("empty entity name.");
parsed = "&;";
}
else {
parsed = this.parseEntity(entity);
this.entity = "";
}
if (entityReturnState !== S_TEXT || this.textHandler !== undefined) {
this.text += parsed;
}
// eslint-disable-next-line no-labels
break loop;
}
case EOC:
this.entity += chunk.slice(start);
// eslint-disable-next-line no-labels
break loop;
default:
}
}
}
private sOpenWaka(): void {
// Reminder: a state handler is called with at least one character
// available in the current chunk. So the first call to get code inside of
// a state handler cannot return ``EOC``. That's why we don't test
// for it.
const c = this.getCode();
// either a /, ?, !, or text is coming next.
if (isNameStartChar(c)) {
this.state = S_OPEN_TAG;
this.unget();
this.xmlDeclPossible = false;
}
else {
switch (c) {
case FORWARD_SLASH:
this.state = S_CLOSE_TAG;
this.xmlDeclPossible = false;
break;
case BANG:
this.state = S_OPEN_WAKA_BANG;
this.openWakaBang = "";
this.xmlDeclPossible = false;
break;
case QUESTION:
this.state = S_PI_FIRST_CHAR;
break;
default:
this.fail("disallowed character in tag name");
this.state = S_TEXT;
this.xmlDeclPossible = false;
}
}
}
private sOpenWakaBang(): void {
this.openWakaBang += String.fromCodePoint(this.getCodeNorm());
switch (this.openWakaBang) {
case "[CDATA[":
if (!this.sawRoot && !this.reportedTextBeforeRoot) {
this.fail("text data outside of root node.");
this.reportedTextBeforeRoot = true;
}
if (this.closedRoot && !this.reportedTextAfterRoot) {
this.fail("text data outside of root node.");
this.reportedTextAfterRoot = true;
}
this.state = S_CDATA;
this.openWakaBang = "";
break;
case "--":
this.state = S_COMMENT;
this.openWakaBang = "";
break;
case "DOCTYPE":
this.state = S_DOCTYPE;
if (this.doctype || this.sawRoot) {
this.fail("inappropriately located doctype declaration.");
}
this.openWakaBang = "";
break;
default:
// 7 happens to be the maximum length of the string that can possibly
// match one of the cases above.
if (this.openWakaBang.length >= 7) {
this.fail("incorrect syntax.");
}
}
}
private sComment(): void {
if (this.captureToChar(MINUS)) {
this.state = S_COMMENT_ENDING;
}
}
private sCommentEnding(): void {
const c = this.getCodeNorm();
if (c === MINUS) {
this.state = S_COMMENT_ENDED;
this.commentHandler?.(this.text);
this.text = "";
}
else {
this.text += `-${String.fromCodePoint(c)}`;
this.state = S_COMMENT;
}
}
private sCommentEnded(): void {
const c = this.getCodeNorm();
if (c !== GREATER) {
this.fail("malformed comment.");
// <!-- blah -- bloo --> will be recorded as
// a comment of " blah -- bloo "
this.text += `--${String.fromCodePoint(c)}`;
this.state = S_COMMENT;
}
else {
this.state = S_TEXT;
}
}
private sCData(): void {
if (this.captureToChar(CLOSE_BRACKET)) {
this.state = S_CDATA_ENDING;
}
}
private sCDataEnding(): void {
const c = this.getCodeNorm();
if (c === CLOSE_BRACKET) {
this.state = S_CDATA_ENDING_2;
}
else {
this.text += `]${String.fromCodePoint(c)}`;
this.state = S_CDATA;
}
}
private sCDataEnding2(): void {
const c = this.getCodeNorm();
switch (c) {
case GREATER: {
this.cdataHandler?.(this.text);
this.text = "";
this.state = S_TEXT;
break;
}
case CLOSE_BRACKET:
this.text += "]";
break;
default:
this.text += `]]${String.fromCodePoint(c)}`;
this.state = S_CDATA;
}
}
// We need this separate state to check the first character fo the pi target
// with this.nameStartCheck which allows less characters than this.nameCheck.
private sPIFirstChar(): void {
const c = this.getCodeNorm();
// This is first because in the case where the file is well-formed this is
// the branch taken. We optimize for well-formedness.
if (this.nameStartCheck(c)) {
this.piTarget += String.fromCodePoint(c);
this.state = S_PI_REST;
}
else if (c === QUESTION || isS(c)) {
this.fail("processing instruction without a target.");
this.state = c === QUESTION ? S_PI_ENDING : S_PI_BODY;
}
else {
this.fail("disallowed character in processing instruction name.");
this.piTarget += String.fromCodePoint(c);
this.state = S_PI_REST;
}
}
private sPIRest(): void {
// Capture characters into a piTarget while ``this.nameCheck`` run on the
// character read returns true.
const { chunk, i: start } = this;
// eslint-disable-next-line no-constant-condition
while (true) {
const c = this.getCodeNorm();
if (c === EOC) {
this.piTarget += chunk.slice(start);
return;
}
// NL cannot satisfy this.nameCheck so we don't have to test specifically
// for it.
if (!this.nameCheck(c)) {
this.piTarget += chunk.slice(start, this.prevI);
const isQuestion = c === QUESTION;
if (isQuestion || isS(c)) {
if (this.piTarget === "xml") {
if (!this.xmlDeclPossible) {
this.fail(
"an XML declaration must be at the start of the document.");
}
this.state = isQuestion ? S_XML_DECL_ENDING : S_XML_DECL_NAME_START;
}
else {
this.state = isQuestion ? S_PI_ENDING : S_PI_BODY;
}
}
else {
this.fail("disallowed character in processing instruction name.");
this.piTarget += String.fromCodePoint(c);
}
break;
}
}
}
private sPIBody(): void {
if (this.text.length === 0) {
const c = this.getCodeNorm();
if (c === QUESTION) {
this.state = S_PI_ENDING;
}
else if (!isS(c)) {
this.text = String.fromCodePoint(c);
}
}
// The question mark character is not valid inside any of the XML
// declaration name/value pairs.
else if (this.captureToChar(QUESTION)) {
this.state = S_PI_ENDING;
}
}
private sPIEnding(): void {
const c = this.getCodeNorm();
if (c === GREATER) {
const { piTarget } = this;
if (piTarget.toLowerCase() === "xml") {
this.fail(
"the XML declaration must appear at the start of the document.");
}
this.piHandler?.({
target: piTarget,
body: this.text,
});
this.piTarget = this.text = "";
this.state = S_TEXT;
}
else if (c === QUESTION) {
// We ran into ?? as part of a processing instruction. We initially took
// the first ? as a sign that the PI was ending, but it is not. So we have
// to add it to the body but we take the new ? as a sign that the PI is
// ending.
this.text += "?";
}
else {
this.text += `?${String.fromCodePoint(c)}`;
this.state = S_PI_BODY;
}
this.xmlDeclPossible = false;
}
private sXMLDeclNameStart(): void {
const c = this.skipSpaces();
// The question mark character is not valid inside any of the XML
// declaration name/value pairs.
if (c === QUESTION) {
// It is valid to go to S_XML_DECL_ENDING from this state.
this.state = S_XML_DECL_ENDING;
return;
}
if (c !== EOC) {
this.state = S_XML_DECL_NAME;
this.name = String.fromCodePoint(c);
}
}
private sXMLDeclName(): void {
const c = this.captureTo(XML_DECL_NAME_TERMINATOR);
// The question mark character is not valid inside any of the XML
// declaration name/value pairs.
if (c === QUESTION) {
this.state = S_XML_DECL_ENDING;
this.name += this.text;
this.text = "";
this.fail("XML declaration is incomplete.");
return;
}
if (!(isS(c) || c === EQUAL)) {
return;
}
this.name += this.text;
this.text = "";
if (!this.xmlDeclExpects.includes(this.name)) {
switch (this.name.length) {
case 0:
this.fail("did not expect any more name/value pairs.");
break;
case 1:
this.fail(`expected the name ${this.xmlDeclExpects[0]}.`);
break;
default:
this.fail(`expected one of ${this.xmlDeclExpects.join(", ")}`);
}
}
this.state = c === EQUAL ? S_XML_DECL_VALUE_START : S_XML_DECL_EQ;
}
private sXMLDeclEq(): void {
const c = this.getCodeNorm();
// The question mark character is not valid inside any of the XML
// declaration name/value pairs.
if (c === QUESTION) {
this.state = S_XML_DECL_ENDING;
this.fail("XML declaration is incomplete.");
return;
}
if (isS(c)) {
return;
}
if (c !== EQUAL) {
this.fail("value required.");
}
this.state = S_XML_DECL_VALUE_START;
}
private sXMLDeclValueStart(): void {
const c = this.getCodeNorm();
// The question mark character is not valid inside any of the XML
// declaration name/value pairs.
if (c === QUESTION) {
this.state = S_XML_DECL_ENDING;
this.fail("XML declaration is incomplete.");
return;
}
if (isS(c)) {
return;
}
if (!isQuote(c)) {
this.fail("value must be quoted.");
this.q = SPACE;
}
else {
this.q = c;
}
this.state = S_XML_DECL_VALUE;
}
private sXMLDeclValue(): void {
const c = this.captureTo([this.q!, QUESTION]);
// The question mark character is not valid inside any of the XML
// declaration name/value pairs.
if (c === QUESTION) {
this.state = S_XML_DECL_ENDING;
this.text = "";
this.fail("XML declaration is incomplete.");
return;
}
if (c === EOC) {
return;
}
const value = this.text;
this.text = "";
switch (this.name) {
case "version": {
this.xmlDeclExpects = ["encoding", "standalone"];
const version = value;
this.xmlDecl.version = version;
// This is the test specified by XML 1.0 but it is fine for XML 1.1.
if (!/^1\.[0-9]+$/.test(version)) {
this.fail("version number must match /^1\\.[0-9]+$/.");
}
// When forceXMLVersion is set, the XML declaration is ignored.
else if (!(this.opt.forceXMLVersion as boolean)) {
this.setXMLVersion(version);
}
break;
}
case "encoding":
if (!/^[A-Za-z][A-Za-z0-9._-]*$/.test(value)) {
this.fail("encoding value must match \
/^[A-Za-z0-9][A-Za-z0-9._-]*$/.");
}
this.xmlDeclExpects = ["standalone"];
this.xmlDecl.encoding = value;
break;
case "standalone":
if (value !== "yes" && value !== "no") {
this.fail("standalone value must match \"yes\" or \"no\".");
}
this.xmlDeclExpects = [];
this.xmlDecl.standalone = value;
break;
default:
// We don't need to raise an error here since we've already raised one
// when checking what name was expected.
}
this.name = "";
this.state = S_XML_DECL_SEPARATOR;
}
private sXMLDeclSeparator(): void {
const c = this.getCodeNorm();
// The question mark character is not valid inside any of the XML
// declaration name/value pairs.
if (c === QUESTION) {
// It is valid to go to S_XML_DECL_ENDING from this state.
this.state = S_XML_DECL_ENDING;
return;
}
if (!isS(c)) {
this.fail("whitespace required.");
this.unget();
}
this.state = S_XML_DECL_NAME_START;
}
private sXMLDeclEnding(): void {
const c = this.getCodeNorm();
if (c === GREATER) {
if (this.piTarget !== "xml") {
this.fail("processing instructions are not allowed before root.");
}
else if (this.name !== "version" &&
this.xmlDeclExpects.includes("version")) {
this.fail("XML declaration must contain a version.");
}
this.xmldeclHandler?.(this.xmlDecl);
this.name = "";
this.piTarget = this.text = "";
this.state = S_TEXT;
}
else {
// We got here because the previous character was a ?, but the question
// mark character is not valid inside any of the XML declaration
// name/value pairs.
this.fail(
"The character ? is disallowed anywhere in XML declarations.");
}
this.xmlDeclPossible = false;
}
private sOpenTag(): void {
const c = this.captureNameChars();
if (c === EOC) {
return;
}
const tag: SaxesTagIncomplete = this.tag = {
name: this.name,
attributes: Object.create(null) as Record<string, string>,
};
this.name = "";
if (this.xmlnsOpt) {
this.topNS = tag.ns = Object.create(null) as Record<string, string>;
}
this.openTagStartHandler?.(tag as StartTagForOptions<O>);
this.sawRoot = true;
if (!this.fragmentOpt && this.closedRoot) {
this.fail("documents may contain only one root.");
}
switch (c) {
case GREATER:
this.openTag();
break;
case FORWARD_SLASH:
this.state = S_OPEN_TAG_SLASH;
break;
default:
if (!isS(c)) {
this.fail("disallowed character in tag name.");
}
this.state = S_ATTRIB;
}
}
private sOpenTagSlash(): void {
if (this.getCode() === GREATER) {
this.openSelfClosingTag();
}
else {
this.fail("forward-slash in opening tag not followed by >.");
this.state = S_ATTRIB;
}
}
private sAttrib(): void {
const c = this.skipSpaces();
if (c === EOC) {
return;
}
if (isNameStartChar(c)) {
this.unget();
this.state = S_ATTRIB_NAME;
}
else if (c === GREATER) {
this.openTag();
}
else if (c === FORWARD_SLASH) {
this.state = S_OPEN_TAG_SLASH;
}
else {
this.fail("disallowed character in attribute name.");
}
}
private sAttribName(): void {
const c = this.captureNameChars();
if (c === EQUAL) {
this.state = S_ATTRIB_VALUE;
}
else if (isS(c)) {
this.state = S_ATTRIB_NAME_SAW_WHITE;
}
else if (c === GREATER) {
this.fail("attribute without value.");
this.pushAttrib(this.name, this.name);
this.name = this.text = "";
this.openTag();
}
else if (c !== EOC) {
this.fail("disallowed character in attribute name.");
}
}
private sAttribNameSawWhite(): void {
const c = this.skipSpaces();
switch (c) {
case EOC:
return;
case EQUAL:
this.state = S_ATTRIB_VALUE;
break;
default:
this.fail("attribute without value.");
// Should we do this???
// this.tag.attributes[this.name] = "";
this.text = "";
this.name = "";
if (c === GREATER) {
this.openTag();
}
else if (isNameStartChar(c)) {
this.unget();
this.state = S_ATTRIB_NAME;
}
else {
this.fail("disallowed character in attribute name.");
this.state = S_ATTRIB;
}
}
}
private sAttribValue(): void {
const c = this.getCodeNorm();
if (isQuote(c)) {
this.q = c;
this.state = S_ATTRIB_VALUE_QUOTED;
}
else if (!isS(c)) {
this.fail("unquoted attribute value.");
this.state = S_ATTRIB_VALUE_UNQUOTED;
this.unget();
}
}
private sAttribValueQuoted(): void {
// We deliberately do not use captureTo here. The specialized code we use
// here is faster than using captureTo.
const { q, chunk } = this;
let { i: start } = this;
// eslint-disable-next-line no-constant-condition
while (true) {
switch (this.getCode()) {
case q:
this.pushAttrib(this.name,
this.text + chunk.slice(start, this.prevI));
this.name = this.text = "";
this.q = null;
this.state = S_ATTRIB_VALUE_CLOSED;
return;
case AMP:
this.text += chunk.slice(start, this.prevI);
this.state = S_ENTITY;
this.entityReturnState = S_ATTRIB_VALUE_QUOTED;
return;
case NL:
case NL_LIKE:
case TAB:
this.text += `${chunk.slice(start, this.prevI)} `;
start = this.i;
break;
case LESS:
this.text += chunk.slice(start, this.prevI);
this.fail("disallowed character.");
return;
case EOC:
this.text += chunk.slice(start);
return;
default:
}
}
}
private sAttribValueClosed(): void {
const c = this.getCodeNorm();
if (isS(c)) {
this.state = S_ATTRIB;
}
else if (c === GREATER) {
this.openTag();
}
else if (c === FORWARD_SLASH) {
this.state = S_OPEN_TAG_SLASH;
}
else if (isNameStartChar(c)) {
this.fail("no whitespace between attributes.");
this.unget();
this.state = S_ATTRIB_NAME;
}
else {
this.fail("disallowed character in attribute name.");
}
}
private sAttribValueUnquoted(): void {
// We don't do anything regarding EOL or space handling for unquoted
// attributes. We already have failed by the time we get here, and the
// contract that saxes upholds states that upon failure, it is not safe to
// rely on the data passed to event handlers (other than
// ``onerror``). Passing "bad" data is not a problem.
const c = this.captureTo(ATTRIB_VALUE_UNQUOTED_TERMINATOR);
switch (c) {
case AMP:
this.state = S_ENTITY;
this.entityReturnState = S_ATTRIB_VALUE_UNQUOTED;
break;
case LESS:
this.fail("disallowed character.");
break;
case EOC:
break;
default:
if (this.text.includes("]]>")) {
this.fail("the string \"]]>\" is disallowed in char data.");
}
this.pushAttrib(this.name, this.text);
this.name = this.text = "";
if (c === GREATER) {
this.openTag();
}
else {
this.state = S_ATTRIB;
}
}
}
private sCloseTag(): void {
const c = this.captureNameChars();
if (c === GREATER) {
this.closeTag();
}
else if (isS(c)) {
this.state = S_CLOSE_TAG_SAW_WHITE;
}
else if (c !== EOC) {
this.fail("disallowed character in closing tag.");
}
}
private sCloseTagSawWhite(): void {
switch (this.skipSpaces()) {
case GREATER:
this.closeTag();
break;
case EOC:
break;
default:
this.fail("disallowed character in closing tag.");
}
}
// END OF STATE ENGINE METHODS
private handleTextInRoot(): void {
// This is essentially a specialized version of captureTo which is optimized
// for performing the ]]> check. A previous version of this code, checked
// ``this.text`` for the presence of ]]>. It simplified the code but was
// very costly when character data contained a lot of entities to be parsed.
//
// Since we are using a specialized loop, we also keep track of the presence
// of ]]> in text data. The sequence ]]> is forbidden to appear as-is.
//
let { i: start, forbiddenState } = this;
const { chunk, textHandler: handler } = this;
// eslint-disable-next-line no-labels, no-restricted-syntax
scanLoop:
// eslint-disable-next-line no-constant-condition
while (true) {
switch (this.getCode()) {
case LESS: {
this.state = S_OPEN_WAKA;
if (handler !== undefined) {
const { text } = this;
const slice = chunk.slice(start, this.prevI);
if (text.length !== 0) {
handler(text + slice);
this.text = "";
}
else if (slice.length !== 0) {
handler(slice);
}
}
forbiddenState = FORBIDDEN_START;
// eslint-disable-next-line no-labels
break scanLoop;
}
case AMP:
this.state = S_ENTITY;
this.entityReturnState = S_TEXT;
if (handler !== undefined) {
this.text += chunk.slice(start, this.prevI);
}
forbiddenState = FORBIDDEN_START;
// eslint-disable-next-line no-labels
break scanLoop;
case CLOSE_BRACKET:
switch (forbiddenState) {
case FORBIDDEN_START:
forbiddenState = FORBIDDEN_BRACKET;
break;
case FORBIDDEN_BRACKET:
forbiddenState = FORBIDDEN_BRACKET_BRACKET;
break;
case FORBIDDEN_BRACKET_BRACKET:
break;
default:
throw new Error("impossible state");
}
break;
case GREATER:
if (forbiddenState === FORBIDDEN_BRACKET_BRACKET) {
this.fail("the string \"]]>\" is disallowed in char data.");
}
forbiddenState = FORBIDDEN_START;
break;
case NL_LIKE:
if (handler !== undefined) {
this.text += `${chunk.slice(start, this.prevI)}\n`;
}
start = this.i;
forbiddenState = FORBIDDEN_START;
break;
case EOC:
if (handler !== undefined) {
this.text += chunk.slice(start);
}
// eslint-disable-next-line no-labels
break scanLoop;
default:
forbiddenState = FORBIDDEN_START;
}
}
this.forbiddenState = forbiddenState;
}
private handleTextOutsideRoot(): void {
// This is essentially a specialized version of captureTo which is optimized
// for a specialized task. We keep track of the presence of non-space
// characters in the text since these are errors when appearing outside the
// document root element.
let { i: start } = this;
const { chunk, textHandler: handler } = this;
let nonSpace = false;
// eslint-disable-next-line no-labels, no-restricted-syntax
outRootLoop:
// eslint-disable-next-line no-constant-condition
while (true) {
const code = this.getCode();
switch (code) {
case LESS: {
this.state = S_OPEN_WAKA;
if (handler !== undefined) {
const { text } = this;
const slice = chunk.slice(start, this.prevI);
if (text.length !== 0) {
handler(text + slice);
this.text = "";
}
else if (slice.length !== 0) {
handler(slice);
}
}
// eslint-disable-next-line no-labels
break outRootLoop;
}
case AMP:
this.state = S_ENTITY;
this.entityReturnState = S_TEXT;
if (handler !== undefined) {
this.text += chunk.slice(start, this.prevI);
}
nonSpace = true;
// eslint-disable-next-line no-labels
break outRootLoop;
case NL_LIKE:
if (handler !== undefined) {
this.text += `${chunk.slice(start, this.prevI)}\n`;
}
start = this.i;
break;
case EOC:
if (handler !== undefined) {
this.text += chunk.slice(start);
}
// eslint-disable-next-line no-labels
break outRootLoop;
default:
if (!isS(code)) {
nonSpace = true;
}
}
}
if (!nonSpace) {
return;
}
// We use the reportedTextBeforeRoot and reportedTextAfterRoot flags
// to avoid reporting errors for every single character that is out of
// place.
if (!this.sawRoot && !this.reportedTextBeforeRoot) {
this.fail("text data outside of root node.");
this.reportedTextBeforeRoot = true;
}
if (this.closedRoot && !this.reportedTextAfterRoot) {
this.fail("text data outside of root node.");
this.reportedTextAfterRoot = true;
}
}
private pushAttribNS(name: string, value: string): void {
const { prefix, local } = this.qname(name);
const attr = { name, prefix, local, value };
this.attribList.push(attr);
this.attributeHandler?.(attr as AttributeEventForOptions<O>);
if (prefix === "xmlns") {
const trimmed = value.trim();
if (this.currentXMLVersion === "1.0" && trimmed === "") {
this.fail("invalid attempt to undefine prefix in XML 1.0");
}
this.topNS![local] = trimmed;
nsPairCheck(this, local, trimmed);
}
else if (name === "xmlns") {
const trimmed = value.trim();
this.topNS![""] = trimmed;
nsPairCheck(this, "", trimmed);
}
}
private pushAttribPlain(name: string, value: string): void {
const attr = { name, value };
this.attribList.push(attr);
this.attributeHandler?.(attr as AttributeEventForOptions<O>);
}
/**
* End parsing. This performs final well-formedness checks and resets the
* parser to a clean state.
*
* @returns this
*/
private end(): this {
if (!this.sawRoot) {
this.fail("document must contain a root element.");
}
const { tags } = this;
while (tags.length > 0) {
const tag = tags.pop()!;
this.fail(`unclosed tag: ${tag.name}`);
}
if ((this.state !== S_BEGIN) && (this.state !== S_TEXT)) {
this.fail("unexpected end.");
}
const { text } = this;
if (text.length !== 0) {
this.textHandler?.(text);
this.text = "";
}
this._closed = true;
this.endHandler?.();
this._init();
return this;
}
/**
* Resolve a namespace prefix.
*
* @param prefix The prefix to resolve.
*
* @returns The namespace URI or ``undefined`` if the prefix is not defined.
*/
resolve(prefix: string): string | undefined {
let uri = this.topNS![prefix];
if (uri !== undefined) {
return uri;
}
const { tags } = this;
for (let index = tags.length - 1; index >= 0; index--) {
uri = tags[index]!.ns![prefix];
if (uri !== undefined) {
return uri;
}
}
uri = this.ns[prefix];
if (uri !== undefined) {
return uri;
}
return this.opt.resolvePrefix?.(prefix);
}
/**
* Parse a qname into its prefix and local name parts.
*
* @param name The name to parse
*
* @returns
*/
private qname(name: string): { prefix: string; local: string } {
// This is faster than using name.split(":").
const colon = name.indexOf(":");
if (colon === -1) {
return { prefix: "", local: name };
}
const local = name.slice(colon + 1);
const prefix = name.slice(0, colon);
if (prefix === "" || local === "" || local.includes(":")) {
this.fail(`malformed name: ${name}.`);
}
return { prefix, local };
}
private processAttribsNS(): void {
const { attribList } = this;
const tag = this.tag!;
{
// add namespace info to tag
const { prefix, local } = this.qname(tag.name);
tag.prefix = prefix;
tag.local = local;
const uri = tag.uri = this.resolve(prefix) ?? "";
if (prefix !== "") {
if (prefix === "xmlns") {
this.fail("tags may not have \"xmlns\" as prefix.");
}
if (uri === "") {
this.fail(`unbound namespace prefix: ${JSON.stringify(prefix)}.`);
tag.uri = prefix;
}
}
}
if (attribList.length === 0) {
return;
}
const { attributes } = tag;
const seen = new Set();
// Note: do not apply default ns to attributes:
// http://www.w3.org/TR/REC-xml-names/#defaulting
for (const attr of attribList as SaxesAttributeNSIncomplete[]) {
const { name, prefix, local } = attr;
let uri;
let eqname;
if (prefix === "") {
uri = name === "xmlns" ? XMLNS_NAMESPACE : "";
eqname = name;
}
else {
uri = this.resolve(prefix);
// if there's any attributes with an undefined namespace,
// then fail on them now.
if (uri === undefined) {
this.fail(`unbound namespace prefix: ${JSON.stringify(prefix)}.`);
uri = prefix;
}
eqname = `{${uri}}${local}`;
}
if (seen.has(eqname)) {
this.fail(`duplicate attribute: ${eqname}.`);
}
seen.add(eqname);
attr.uri = uri;
attributes[name] = attr;
}
this.attribList = [];
}
private processAttribsPlain(): void {
const { attribList } = this;
// eslint-disable-next-line prefer-destructuring
const attributes = this.tag!.attributes;
for (const { name, value } of attribList) {
if (attributes[name] !== undefined) {
this.fail(`duplicate attribute: ${name}.`);
}
attributes[name] = value;
}
this.attribList = [];
}
/**
* Handle a complete open tag. This parser code calls this once it has seen
* the whole tag. This method checks for well-formeness and then emits
* ``onopentag``.
*/
private openTag(): void {
this.processAttribs();
const { tags } = this;
const tag = this.tag as SaxesTag;
tag.isSelfClosing = false;
// There cannot be any pending text here due to the onopentagstart that was
// necessarily emitted before we get here. So we do not check text.
this.openTagHandler?.(tag as TagForOptions<O>);
tags.push(tag);
this.state = S_TEXT;
this.name = "";
}
/**
* Handle a complete self-closing tag. This parser code calls this once it has
* seen the whole tag. This method checks for well-formeness and then emits
* ``onopentag`` and ``onclosetag``.
*/
private openSelfClosingTag(): void {
this.processAttribs();
const { tags } = this;
const tag = this.tag as SaxesTag;
tag.isSelfClosing = true;
// There cannot be any pending text here due to the onopentagstart that was
// necessarily emitted before we get here. So we do not check text.
this.openTagHandler?.(tag as TagForOptions<O>);
this.closeTagHandler?.(tag as TagForOptions<O>);
const top = this.tag = tags[tags.length - 1] ?? null;
if (top === null) {
this.closedRoot = true;
}
this.state = S_TEXT;
this.name = "";
}
/**
* Handle a complete close tag. This parser code calls this once it has seen
* the whole tag. This method checks for well-formeness and then emits
* ``onclosetag``.
*/
private closeTag(): void {
const { tags, name } = this;
// Our state after this will be S_TEXT, no matter what, and we can clear
// tagName now.
this.state = S_TEXT;
this.name = "";
if (name === "") {
this.fail("weird empty close tag.");
this.text += "</>";
return;
}
const handler = this.closeTagHandler;
let l = tags.length;
while (l-- > 0) {
const tag = this.tag = tags.pop() as SaxesTag;
this.topNS = tag.ns!;
handler?.(tag as TagForOptions<O>);
if (tag.name === name) {
break;
}
this.fail("unexpected close tag.");
}
if (l === 0) {
this.closedRoot = true;
}
else if (l < 0) {
this.fail(`unmatched closing tag: ${name}.`);
this.text += `</${name}>`;
}
}
/**
* Resolves an entity. Makes any necessary well-formedness checks.
*
* @param entity The entity to resolve.
*
* @returns The parsed entity.
*/
private parseEntity(entity: string): string {
// startsWith would be significantly slower for this test.
if (entity[0] !== "#") {
const defined = this.ENTITIES[entity];
if (defined !== undefined) {
return defined;
}
this.fail(this.isName(entity) ? "undefined entity." :
"disallowed character in entity name.");
return `&${entity};`;
}
let num = NaN;
if (entity[1] === "x" && /^#x[0-9a-f]+$/i.test(entity)) {
num = parseInt(entity.slice(2), 16);
}
else if (/^#[0-9]+$/.test(entity)) {
num = parseInt(entity.slice(1), 10);
}
// The character reference is required to match the CHAR production.
if (!this.isChar(num)) {
this.fail("malformed character entity.");
return `&${entity};`;
}
return String.fromCodePoint(num);
}
} |
1,146 | fn(parser: SaxesParser): void {
for (const x of crnl) {
parser.write(x);
}
parser.close();
} | class SaxesParser<O extends SaxesOptions = {}> {
private readonly fragmentOpt: boolean;
private readonly xmlnsOpt: boolean;
private readonly trackPosition: boolean;
private readonly fileName?: string;
private readonly nameStartCheck: (c: number) => boolean;
private readonly nameCheck: (c: number) => boolean;
private readonly isName: (name: string) => boolean;
private readonly ns!: Record<string, string>;
private openWakaBang!: string;
private text!: string;
private name!: string;
private piTarget!: string;
private entity!: string;
private q!: null | number;
private tags!: SaxesTagIncomplete[];
private tag!: SaxesTagIncomplete | null;
private topNS!: Record<string, string> | null;
private chunk!: string;
private chunkPosition!: number;
private i!: number;
//
// We use prevI to allow "ungetting" the previously read code point. Note
// however, that it is not safe to unget everything and anything. In
// particular ungetting EOL characters will screw positioning up.
//
// Practically, you must not unget a code which has any side effect beyond
// updating ``this.i`` and ``this.prevI``. Only EOL codes have such side
// effects.
//
private prevI!: number;
private carriedFromPrevious?: string;
private forbiddenState!: number;
private attribList!: (SaxesAttributeNSIncomplete | SaxesAttributePlain)[];
private state!: number;
private reportedTextBeforeRoot!: boolean;
private reportedTextAfterRoot!: boolean;
private closedRoot!: boolean;
private sawRoot!: boolean;
private xmlDeclPossible!: boolean;
private xmlDeclExpects!: string[];
private entityReturnState?: number;
private processAttribs!: (this: this) => void;
private positionAtNewLine!: number;
private doctype!: boolean;
private getCode!: () => number;
private isChar!: (c: number) => boolean;
private pushAttrib!: (name: string, value: string) => void;
private _closed!: boolean;
private currentXMLVersion!: string;
private readonly stateTable: ((this: SaxesParser<O>) => void)[];
private xmldeclHandler?: XMLDeclHandler;
private textHandler?: TextHandler;
private piHandler?: PIHandler;
private doctypeHandler?: DoctypeHandler;
private commentHandler?: CommentHandler;
private openTagStartHandler?: OpenTagStartHandler<O>;
private openTagHandler?: OpenTagHandler<O>;
private closeTagHandler?: CloseTagHandler<O>;
private cdataHandler?: CDataHandler;
private errorHandler?: ErrorHandler;
private endHandler?: EndHandler;
private readyHandler?: ReadyHandler;
private attributeHandler?: AttributeHandler<O>;
/**
* Indicates whether or not the parser is closed. If ``true``, wait for
* the ``ready`` event to write again.
*/
get closed(): boolean {
return this._closed;
}
readonly opt: SaxesOptions;
/**
* The XML declaration for this document.
*/
xmlDecl!: XMLDecl;
/**
* The line number of the next character to be read by the parser. This field
* is one-based. (The first line is numbered 1.)
*/
line!: number;
/**
* The column number of the next character to be read by the parser. *
* This field is zero-based. (The first column is 0.)
*
* This field counts columns by *Unicode character*. Note that this *can*
* be different from the index of the character in a JavaScript string due
* to how JavaScript handles astral plane characters.
*
* See [[columnIndex]] for a number that corresponds to the JavaScript index.
*/
column!: number;
/**
* A map of entity name to expansion.
*/
ENTITIES!: Record<string, string>;
/**
* @param opt The parser options.
*/
constructor(opt?: O) {
this.opt = opt ?? {};
this.fragmentOpt = !!(this.opt.fragment as boolean);
const xmlnsOpt = this.xmlnsOpt = !!(this.opt.xmlns as boolean);
this.trackPosition = this.opt.position !== false;
this.fileName = this.opt.fileName;
if (xmlnsOpt) {
// This is the function we use to perform name checks on PIs and entities.
// When namespaces are used, colons are not allowed in PI target names or
// entity names. So the check depends on whether namespaces are used. See:
//
// https://www.w3.org/XML/xml-names-19990114-errata.html
// NE08
//
this.nameStartCheck = isNCNameStartChar;
this.nameCheck = isNCNameChar;
this.isName = isNCName;
// eslint-disable-next-line @typescript-eslint/unbound-method
this.processAttribs = this.processAttribsNS;
// eslint-disable-next-line @typescript-eslint/unbound-method
this.pushAttrib = this.pushAttribNS;
// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-assignment
this.ns = { __proto__: null as any, ...rootNS };
const additional = this.opt.additionalNamespaces;
if (additional != null) {
nsMappingCheck(this, additional);
Object.assign(this.ns, additional);
}
}
else {
this.nameStartCheck = isNameStartChar;
this.nameCheck = isNameChar;
this.isName = isName;
// eslint-disable-next-line @typescript-eslint/unbound-method
this.processAttribs = this.processAttribsPlain;
// eslint-disable-next-line @typescript-eslint/unbound-method
this.pushAttrib = this.pushAttribPlain;
}
//
// The order of the members in this table needs to correspond to the state
// numbers given to the states that correspond to the methods being recorded
// here.
//
this.stateTable = [
/* eslint-disable @typescript-eslint/unbound-method */
this.sBegin,
this.sBeginWhitespace,
this.sDoctype,
this.sDoctypeQuote,
this.sDTD,
this.sDTDQuoted,
this.sDTDOpenWaka,
this.sDTDOpenWakaBang,
this.sDTDComment,
this.sDTDCommentEnding,
this.sDTDCommentEnded,
this.sDTDPI,
this.sDTDPIEnding,
this.sText,
this.sEntity,
this.sOpenWaka,
this.sOpenWakaBang,
this.sComment,
this.sCommentEnding,
this.sCommentEnded,
this.sCData,
this.sCDataEnding,
this.sCDataEnding2,
this.sPIFirstChar,
this.sPIRest,
this.sPIBody,
this.sPIEnding,
this.sXMLDeclNameStart,
this.sXMLDeclName,
this.sXMLDeclEq,
this.sXMLDeclValueStart,
this.sXMLDeclValue,
this.sXMLDeclSeparator,
this.sXMLDeclEnding,
this.sOpenTag,
this.sOpenTagSlash,
this.sAttrib,
this.sAttribName,
this.sAttribNameSawWhite,
this.sAttribValue,
this.sAttribValueQuoted,
this.sAttribValueClosed,
this.sAttribValueUnquoted,
this.sCloseTag,
this.sCloseTagSawWhite,
/* eslint-enable @typescript-eslint/unbound-method */
];
this._init();
}
_init(): void {
this.openWakaBang = "";
this.text = "";
this.name = "";
this.piTarget = "";
this.entity = "";
this.q = null;
this.tags = [];
this.tag = null;
this.topNS = null;
this.chunk = "";
this.chunkPosition = 0;
this.i = 0;
this.prevI = 0;
this.carriedFromPrevious = undefined;
this.forbiddenState = FORBIDDEN_START;
this.attribList = [];
// The logic is organized so as to minimize the need to check
// this.opt.fragment while parsing.
const { fragmentOpt } = this;
this.state = fragmentOpt ? S_TEXT : S_BEGIN;
// We want these to be all true if we are dealing with a fragment.
this.reportedTextBeforeRoot = this.reportedTextAfterRoot = this.closedRoot =
this.sawRoot = fragmentOpt;
// An XML declaration is intially possible only when parsing whole
// documents.
this.xmlDeclPossible = !fragmentOpt;
this.xmlDeclExpects = ["version"];
this.entityReturnState = undefined;
let { defaultXMLVersion } = this.opt;
if (defaultXMLVersion === undefined) {
if (this.opt.forceXMLVersion === true) {
throw new Error("forceXMLVersion set but defaultXMLVersion is not set");
}
defaultXMLVersion = "1.0";
}
this.setXMLVersion(defaultXMLVersion);
this.positionAtNewLine = 0;
this.doctype = false;
this._closed = false;
this.xmlDecl = {
version: undefined,
encoding: undefined,
standalone: undefined,
};
this.line = 1;
this.column = 0;
this.ENTITIES = Object.create(XML_ENTITIES) as Record<string, string>;
this.readyHandler?.();
}
/**
* The stream position the parser is currently looking at. This field is
* zero-based.
*
* This field is not based on counting Unicode characters but is to be
* interpreted as a plain index into a JavaScript string.
*/
get position(): number {
return this.chunkPosition + this.i;
}
/**
* The column number of the next character to be read by the parser. *
* This field is zero-based. (The first column in a line is 0.)
*
* This field reports the index at which the next character would be in the
* line if the line were represented as a JavaScript string. Note that this
* *can* be different to a count based on the number of *Unicode characters*
* due to how JavaScript handles astral plane characters.
*
* See [[column]] for a number that corresponds to a count of Unicode
* characters.
*/
get columnIndex(): number {
return this.position - this.positionAtNewLine;
}
/**
* Set an event listener on an event. The parser supports one handler per
* event type. If you try to set an event handler over an existing handler,
* the old handler is silently overwritten.
*
* @param name The event to listen to.
*
* @param handler The handler to set.
*/
on<N extends EventName>(name: N, handler: EventNameToHandler<O, N>): void {
// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-member-access
(this as any)[EVENT_NAME_TO_HANDLER_NAME[name]] = handler;
}
/**
* Unset an event handler.
*
* @parma name The event to stop listening to.
*/
off(name: EventName): void {
// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-member-access
(this as any)[EVENT_NAME_TO_HANDLER_NAME[name]] = undefined;
}
/**
* Make an error object. The error object will have a message that contains
* the ``fileName`` option passed at the creation of the parser. If position
* tracking was turned on, it will also have line and column number
* information.
*
* @param message The message describing the error to report.
*
* @returns An error object with a properly formatted message.
*/
makeError(message: string): Error {
let msg = this.fileName ?? "";
if (this.trackPosition) {
if (msg.length > 0) {
msg += ":";
}
msg += `${this.line}:${this.column}`;
}
if (msg.length > 0) {
msg += ": ";
}
return new Error(msg + message);
}
/**
* Report a parsing error. This method is made public so that client code may
* check for issues that are outside the scope of this project and can report
* errors.
*
* @param message The error to report.
*
* @returns this
*/
fail(message: string): this {
const err = this.makeError(message);
const handler = this.errorHandler;
if (handler === undefined) {
throw err;
}
else {
handler(err);
}
return this;
}
/**
* Write a XML data to the parser.
*
* @param chunk The XML data to write.
*
* @returns this
*/
// We do need object for the type here. Yes, it often causes problems
// but not in this case.
write(chunk: string | object | null): this {
if (this.closed) {
return this.fail("cannot write after close; assign an onready handler.");
}
let end = false;
if (chunk === null) {
// We cannot return immediately because carriedFromPrevious may need
// processing.
end = true;
chunk = "";
}
else if (typeof chunk === "object") {
chunk = chunk.toString();
}
// We checked if performing a pre-decomposition of the string into an array
// of single complete characters (``Array.from(chunk)``) would be faster
// than the current repeated calls to ``charCodeAt``. As of August 2018, it
// isn't. (There may be Node-specific code that would perform faster than
// ``Array.from`` but don't want to be dependent on Node.)
if (this.carriedFromPrevious !== undefined) {
// The previous chunk had char we must carry over.
chunk = `${this.carriedFromPrevious}${chunk}`;
this.carriedFromPrevious = undefined;
}
let limit = chunk.length;
const lastCode = chunk.charCodeAt(limit - 1);
if (!end &&
// A trailing CR or surrogate must be carried over to the next
// chunk.
(lastCode === CR || (lastCode >= 0xD800 && lastCode <= 0xDBFF))) {
// The chunk ends with a character that must be carried over. We cannot
// know how to handle it until we get the next chunk or the end of the
// stream. So save it for later.
this.carriedFromPrevious = chunk[limit - 1];
limit--;
chunk = chunk.slice(0, limit);
}
const { stateTable } = this;
this.chunk = chunk;
this.i = 0;
while (this.i < limit) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-argument
stateTable[this.state].call(this as any);
}
this.chunkPosition += limit;
return end ? this.end() : this;
}
/**
* Close the current stream. Perform final well-formedness checks and reset
* the parser tstate.
*
* @returns this
*/
close(): this {
return this.write(null);
}
/**
* Get a single code point out of the current chunk. This updates the current
* position if we do position tracking.
*
* This is the algorithm to use for XML 1.0.
*
* @returns The character read.
*/
private getCode10(): number {
const { chunk, i } = this;
this.prevI = i;
// Yes, we do this instead of doing this.i++. Doing it this way, we do not
// read this.i again, which is a bit faster.
this.i = i + 1;
if (i >= chunk.length) {
return EOC;
}
// Using charCodeAt and handling the surrogates ourselves is faster
// than using codePointAt.
const code = chunk.charCodeAt(i);
this.column++;
if (code < 0xD800) {
if (code >= SPACE || code === TAB) {
return code;
}
switch (code) {
case NL:
this.line++;
this.column = 0;
this.positionAtNewLine = this.position;
return NL;
case CR:
// We may get NaN if we read past the end of the chunk, which is fine.
if (chunk.charCodeAt(i + 1) === NL) {
// A \r\n sequence is converted to \n so we have to skip over the
// next character. We already know it has a size of 1 so ++ is fine
// here.
this.i = i + 2;
}
// Otherwise, a \r is just converted to \n, so we don't have to skip
// ahead.
// In either case, \r becomes \n.
this.line++;
this.column = 0;
this.positionAtNewLine = this.position;
return NL_LIKE;
default:
// If we get here, then code < SPACE and it is not NL CR or TAB.
this.fail("disallowed character.");
return code;
}
}
if (code > 0xDBFF) {
// This is a specialized version of isChar10 that takes into account
// that in this context code > 0xDBFF and code <= 0xFFFF. So it does not
// test cases that don't need testing.
if (!(code >= 0xE000 && code <= 0xFFFD)) {
this.fail("disallowed character.");
}
return code;
}
const final = 0x10000 + ((code - 0xD800) * 0x400) +
(chunk.charCodeAt(i + 1) - 0xDC00);
this.i = i + 2;
// This is a specialized version of isChar10 that takes into account that in
// this context necessarily final >= 0x10000.
if (final > 0x10FFFF) {
this.fail("disallowed character.");
}
return final;
}
/**
* Get a single code point out of the current chunk. This updates the current
* position if we do position tracking.
*
* This is the algorithm to use for XML 1.1.
*
* @returns {number} The character read.
*/
private getCode11(): number {
const { chunk, i } = this;
this.prevI = i;
// Yes, we do this instead of doing this.i++. Doing it this way, we do not
// read this.i again, which is a bit faster.
this.i = i + 1;
if (i >= chunk.length) {
return EOC;
}
// Using charCodeAt and handling the surrogates ourselves is faster
// than using codePointAt.
const code = chunk.charCodeAt(i);
this.column++;
if (code < 0xD800) {
if ((code > 0x1F && code < 0x7F) || (code > 0x9F && code !== LS) ||
code === TAB) {
return code;
}
switch (code) {
case NL: // 0xA
this.line++;
this.column = 0;
this.positionAtNewLine = this.position;
return NL;
case CR: { // 0xD
// We may get NaN if we read past the end of the chunk, which is
// fine.
const next = chunk.charCodeAt(i + 1);
if (next === NL || next === NEL) {
// A CR NL or CR NEL sequence is converted to NL so we have to skip
// over the next character. We already know it has a size of 1.
this.i = i + 2;
}
// Otherwise, a CR is just converted to NL, no skip.
}
/* yes, fall through */
case NEL: // 0x85
case LS: // Ox2028
this.line++;
this.column = 0;
this.positionAtNewLine = this.position;
return NL_LIKE;
default:
this.fail("disallowed character.");
return code;
}
}
if (code > 0xDBFF) {
// This is a specialized version of isCharAndNotRestricted that takes into
// account that in this context code > 0xDBFF and code <= 0xFFFF. So it
// does not test cases that don't need testing.
if (!(code >= 0xE000 && code <= 0xFFFD)) {
this.fail("disallowed character.");
}
return code;
}
const final = 0x10000 + ((code - 0xD800) * 0x400) +
(chunk.charCodeAt(i + 1) - 0xDC00);
this.i = i + 2;
// This is a specialized version of isCharAndNotRestricted that takes into
// account that in this context necessarily final >= 0x10000.
if (final > 0x10FFFF) {
this.fail("disallowed character.");
}
return final;
}
/**
* Like ``getCode`` but with the return value normalized so that ``NL`` is
* returned for ``NL_LIKE``.
*/
private getCodeNorm(): number {
const c = this.getCode();
return c === NL_LIKE ? NL : c;
}
private unget(): void {
this.i = this.prevI;
this.column--;
}
/**
* Capture characters into a buffer until encountering one of a set of
* characters.
*
* @param chars An array of codepoints. Encountering a character in the array
* ends the capture. (``chars`` may safely contain ``NL``.)
*
* @return The character code that made the capture end, or ``EOC`` if we hit
* the end of the chunk. The return value cannot be NL_LIKE: NL is returned
* instead.
*/
private captureTo(chars: number[]): number {
let { i: start } = this;
const { chunk } = this;
// eslint-disable-next-line no-constant-condition
while (true) {
const c = this.getCode();
const isNLLike = c === NL_LIKE;
const final = isNLLike ? NL : c;
if (final === EOC || chars.includes(final)) {
this.text += chunk.slice(start, this.prevI);
return final;
}
if (isNLLike) {
this.text += `${chunk.slice(start, this.prevI)}\n`;
start = this.i;
}
}
}
/**
* Capture characters into a buffer until encountering a character.
*
* @param char The codepoint that ends the capture. **NOTE ``char`` MAY NOT
* CONTAIN ``NL``.** Passing ``NL`` will result in buggy behavior.
*
* @return ``true`` if we ran into the character. Otherwise, we ran into the
* end of the current chunk.
*/
private captureToChar(char: number): boolean {
let { i: start } = this;
const { chunk } = this;
// eslint-disable-next-line no-constant-condition
while (true) {
let c = this.getCode();
switch (c) {
case NL_LIKE:
this.text += `${chunk.slice(start, this.prevI)}\n`;
start = this.i;
c = NL;
break;
case EOC:
this.text += chunk.slice(start);
return false;
default:
}
if (c === char) {
this.text += chunk.slice(start, this.prevI);
return true;
}
}
}
/**
* Capture characters that satisfy ``isNameChar`` into the ``name`` field of
* this parser.
*
* @return The character code that made the test fail, or ``EOC`` if we hit
* the end of the chunk. The return value cannot be NL_LIKE: NL is returned
* instead.
*/
private captureNameChars(): number {
const { chunk, i: start } = this;
// eslint-disable-next-line no-constant-condition
while (true) {
const c = this.getCode();
if (c === EOC) {
this.name += chunk.slice(start);
return EOC;
}
// NL is not a name char so we don't have to test specifically for it.
if (!isNameChar(c)) {
this.name += chunk.slice(start, this.prevI);
return c === NL_LIKE ? NL : c;
}
}
}
/**
* Skip white spaces.
*
* @return The character that ended the skip, or ``EOC`` if we hit
* the end of the chunk. The return value cannot be NL_LIKE: NL is returned
* instead.
*/
private skipSpaces(): number {
// eslint-disable-next-line no-constant-condition
while (true) {
const c = this.getCodeNorm();
if (c === EOC || !isS(c)) {
return c;
}
}
}
private setXMLVersion(version: string): void {
this.currentXMLVersion = version;
/* eslint-disable @typescript-eslint/unbound-method */
if (version === "1.0") {
this.isChar = isChar10;
this.getCode = this.getCode10;
}
else {
this.isChar = isChar11;
this.getCode = this.getCode11;
}
/* eslint-enable @typescript-eslint/unbound-method */
}
// STATE ENGINE METHODS
// This needs to be a state separate from S_BEGIN_WHITESPACE because we want
// to be sure never to come back to this state later.
private sBegin(): void {
// We are essentially peeking at the first character of the chunk. Since
// S_BEGIN can be in effect only when we start working on the first chunk,
// the index at which we must look is necessarily 0. Note also that the
// following test does not depend on decoding surrogates.
// If the initial character is 0xFEFF, ignore it.
if (this.chunk.charCodeAt(0) === 0xFEFF) {
this.i++;
this.column++;
}
this.state = S_BEGIN_WHITESPACE;
}
private sBeginWhitespace(): void {
// We need to know whether we've encountered spaces or not because as soon
// as we run into a space, an XML declaration is no longer possible. Rather
// than slow down skipSpaces even in places where we don't care whether it
// skipped anything or not, we check whether prevI is equal to the value of
// i from before we skip spaces.
const iBefore = this.i;
const c = this.skipSpaces();
if (this.prevI !== iBefore) {
this.xmlDeclPossible = false;
}
switch (c) {
case LESS:
this.state = S_OPEN_WAKA;
// We could naively call closeText but in this state, it is not normal
// to have text be filled with any data.
if (this.text.length !== 0) {
throw new Error("no-empty text at start");
}
break;
case EOC:
break;
default:
this.unget();
this.state = S_TEXT;
this.xmlDeclPossible = false;
}
}
private sDoctype(): void {
const c = this.captureTo(DOCTYPE_TERMINATOR);
switch (c) {
case GREATER: {
this.doctypeHandler?.(this.text);
this.text = "";
this.state = S_TEXT;
this.doctype = true; // just remember that we saw it.
break;
}
case EOC:
break;
default:
this.text += String.fromCodePoint(c);
if (c === OPEN_BRACKET) {
this.state = S_DTD;
}
else if (isQuote(c)) {
this.state = S_DOCTYPE_QUOTE;
this.q = c;
}
}
}
private sDoctypeQuote(): void {
const q = this.q!;
if (this.captureToChar(q)) {
this.text += String.fromCodePoint(q);
this.q = null;
this.state = S_DOCTYPE;
}
}
private sDTD(): void {
const c = this.captureTo(DTD_TERMINATOR);
if (c === EOC) {
return;
}
this.text += String.fromCodePoint(c);
if (c === CLOSE_BRACKET) {
this.state = S_DOCTYPE;
}
else if (c === LESS) {
this.state = S_DTD_OPEN_WAKA;
}
else if (isQuote(c)) {
this.state = S_DTD_QUOTED;
this.q = c;
}
}
private sDTDQuoted(): void {
const q = this.q!;
if (this.captureToChar(q)) {
this.text += String.fromCodePoint(q);
this.state = S_DTD;
this.q = null;
}
}
private sDTDOpenWaka(): void {
const c = this.getCodeNorm();
this.text += String.fromCodePoint(c);
switch (c) {
case BANG:
this.state = S_DTD_OPEN_WAKA_BANG;
this.openWakaBang = "";
break;
case QUESTION:
this.state = S_DTD_PI;
break;
default:
this.state = S_DTD;
}
}
private sDTDOpenWakaBang(): void {
const char = String.fromCodePoint(this.getCodeNorm());
const owb = this.openWakaBang += char;
this.text += char;
if (owb !== "-") {
this.state = owb === "--" ? S_DTD_COMMENT : S_DTD;
this.openWakaBang = "";
}
}
private sDTDComment(): void {
if (this.captureToChar(MINUS)) {
this.text += "-";
this.state = S_DTD_COMMENT_ENDING;
}
}
private sDTDCommentEnding(): void {
const c = this.getCodeNorm();
this.text += String.fromCodePoint(c);
this.state = c === MINUS ? S_DTD_COMMENT_ENDED : S_DTD_COMMENT;
}
private sDTDCommentEnded(): void {
const c = this.getCodeNorm();
this.text += String.fromCodePoint(c);
if (c === GREATER) {
this.state = S_DTD;
}
else {
this.fail("malformed comment.");
// <!-- blah -- bloo --> will be recorded as
// a comment of " blah -- bloo "
this.state = S_DTD_COMMENT;
}
}
private sDTDPI(): void {
if (this.captureToChar(QUESTION)) {
this.text += "?";
this.state = S_DTD_PI_ENDING;
}
}
private sDTDPIEnding(): void {
const c = this.getCodeNorm();
this.text += String.fromCodePoint(c);
if (c === GREATER) {
this.state = S_DTD;
}
}
private sText(): void {
//
// We did try a version of saxes where the S_TEXT state was split in two
// states: one for text inside the root element, and one for text
// outside. This was avoiding having to test this.tags.length to decide
// what implementation to actually use.
//
// Peformance testing on gigabyte-size files did not show any advantage to
// using the two states solution instead of the current one. Conversely, it
// made the code a bit more complicated elsewhere. For instance, a comment
// can appear before the root element so when a comment ended it was
// necessary to determine whether to return to the S_TEXT state or to the
// new text-outside-root state.
//
if (this.tags.length !== 0) {
this.handleTextInRoot();
}
else {
this.handleTextOutsideRoot();
}
}
private sEntity(): void {
// This is essentially a specialized version of captureToChar(SEMICOLON...)
let { i: start } = this;
const { chunk } = this;
// eslint-disable-next-line no-labels, no-restricted-syntax
loop:
// eslint-disable-next-line no-constant-condition
while (true) {
switch (this.getCode()) {
case NL_LIKE:
this.entity += `${chunk.slice(start, this.prevI)}\n`;
start = this.i;
break;
case SEMICOLON: {
const { entityReturnState } = this;
const entity = this.entity + chunk.slice(start, this.prevI);
this.state = entityReturnState!;
let parsed: string;
if (entity === "") {
this.fail("empty entity name.");
parsed = "&;";
}
else {
parsed = this.parseEntity(entity);
this.entity = "";
}
if (entityReturnState !== S_TEXT || this.textHandler !== undefined) {
this.text += parsed;
}
// eslint-disable-next-line no-labels
break loop;
}
case EOC:
this.entity += chunk.slice(start);
// eslint-disable-next-line no-labels
break loop;
default:
}
}
}
private sOpenWaka(): void {
// Reminder: a state handler is called with at least one character
// available in the current chunk. So the first call to get code inside of
// a state handler cannot return ``EOC``. That's why we don't test
// for it.
const c = this.getCode();
// either a /, ?, !, or text is coming next.
if (isNameStartChar(c)) {
this.state = S_OPEN_TAG;
this.unget();
this.xmlDeclPossible = false;
}
else {
switch (c) {
case FORWARD_SLASH:
this.state = S_CLOSE_TAG;
this.xmlDeclPossible = false;
break;
case BANG:
this.state = S_OPEN_WAKA_BANG;
this.openWakaBang = "";
this.xmlDeclPossible = false;
break;
case QUESTION:
this.state = S_PI_FIRST_CHAR;
break;
default:
this.fail("disallowed character in tag name");
this.state = S_TEXT;
this.xmlDeclPossible = false;
}
}
}
private sOpenWakaBang(): void {
this.openWakaBang += String.fromCodePoint(this.getCodeNorm());
switch (this.openWakaBang) {
case "[CDATA[":
if (!this.sawRoot && !this.reportedTextBeforeRoot) {
this.fail("text data outside of root node.");
this.reportedTextBeforeRoot = true;
}
if (this.closedRoot && !this.reportedTextAfterRoot) {
this.fail("text data outside of root node.");
this.reportedTextAfterRoot = true;
}
this.state = S_CDATA;
this.openWakaBang = "";
break;
case "--":
this.state = S_COMMENT;
this.openWakaBang = "";
break;
case "DOCTYPE":
this.state = S_DOCTYPE;
if (this.doctype || this.sawRoot) {
this.fail("inappropriately located doctype declaration.");
}
this.openWakaBang = "";
break;
default:
// 7 happens to be the maximum length of the string that can possibly
// match one of the cases above.
if (this.openWakaBang.length >= 7) {
this.fail("incorrect syntax.");
}
}
}
private sComment(): void {
if (this.captureToChar(MINUS)) {
this.state = S_COMMENT_ENDING;
}
}
private sCommentEnding(): void {
const c = this.getCodeNorm();
if (c === MINUS) {
this.state = S_COMMENT_ENDED;
this.commentHandler?.(this.text);
this.text = "";
}
else {
this.text += `-${String.fromCodePoint(c)}`;
this.state = S_COMMENT;
}
}
private sCommentEnded(): void {
const c = this.getCodeNorm();
if (c !== GREATER) {
this.fail("malformed comment.");
// <!-- blah -- bloo --> will be recorded as
// a comment of " blah -- bloo "
this.text += `--${String.fromCodePoint(c)}`;
this.state = S_COMMENT;
}
else {
this.state = S_TEXT;
}
}
private sCData(): void {
if (this.captureToChar(CLOSE_BRACKET)) {
this.state = S_CDATA_ENDING;
}
}
private sCDataEnding(): void {
const c = this.getCodeNorm();
if (c === CLOSE_BRACKET) {
this.state = S_CDATA_ENDING_2;
}
else {
this.text += `]${String.fromCodePoint(c)}`;
this.state = S_CDATA;
}
}
private sCDataEnding2(): void {
const c = this.getCodeNorm();
switch (c) {
case GREATER: {
this.cdataHandler?.(this.text);
this.text = "";
this.state = S_TEXT;
break;
}
case CLOSE_BRACKET:
this.text += "]";
break;
default:
this.text += `]]${String.fromCodePoint(c)}`;
this.state = S_CDATA;
}
}
// We need this separate state to check the first character fo the pi target
// with this.nameStartCheck which allows less characters than this.nameCheck.
private sPIFirstChar(): void {
const c = this.getCodeNorm();
// This is first because in the case where the file is well-formed this is
// the branch taken. We optimize for well-formedness.
if (this.nameStartCheck(c)) {
this.piTarget += String.fromCodePoint(c);
this.state = S_PI_REST;
}
else if (c === QUESTION || isS(c)) {
this.fail("processing instruction without a target.");
this.state = c === QUESTION ? S_PI_ENDING : S_PI_BODY;
}
else {
this.fail("disallowed character in processing instruction name.");
this.piTarget += String.fromCodePoint(c);
this.state = S_PI_REST;
}
}
private sPIRest(): void {
// Capture characters into a piTarget while ``this.nameCheck`` run on the
// character read returns true.
const { chunk, i: start } = this;
// eslint-disable-next-line no-constant-condition
while (true) {
const c = this.getCodeNorm();
if (c === EOC) {
this.piTarget += chunk.slice(start);
return;
}
// NL cannot satisfy this.nameCheck so we don't have to test specifically
// for it.
if (!this.nameCheck(c)) {
this.piTarget += chunk.slice(start, this.prevI);
const isQuestion = c === QUESTION;
if (isQuestion || isS(c)) {
if (this.piTarget === "xml") {
if (!this.xmlDeclPossible) {
this.fail(
"an XML declaration must be at the start of the document.");
}
this.state = isQuestion ? S_XML_DECL_ENDING : S_XML_DECL_NAME_START;
}
else {
this.state = isQuestion ? S_PI_ENDING : S_PI_BODY;
}
}
else {
this.fail("disallowed character in processing instruction name.");
this.piTarget += String.fromCodePoint(c);
}
break;
}
}
}
private sPIBody(): void {
if (this.text.length === 0) {
const c = this.getCodeNorm();
if (c === QUESTION) {
this.state = S_PI_ENDING;
}
else if (!isS(c)) {
this.text = String.fromCodePoint(c);
}
}
// The question mark character is not valid inside any of the XML
// declaration name/value pairs.
else if (this.captureToChar(QUESTION)) {
this.state = S_PI_ENDING;
}
}
private sPIEnding(): void {
const c = this.getCodeNorm();
if (c === GREATER) {
const { piTarget } = this;
if (piTarget.toLowerCase() === "xml") {
this.fail(
"the XML declaration must appear at the start of the document.");
}
this.piHandler?.({
target: piTarget,
body: this.text,
});
this.piTarget = this.text = "";
this.state = S_TEXT;
}
else if (c === QUESTION) {
// We ran into ?? as part of a processing instruction. We initially took
// the first ? as a sign that the PI was ending, but it is not. So we have
// to add it to the body but we take the new ? as a sign that the PI is
// ending.
this.text += "?";
}
else {
this.text += `?${String.fromCodePoint(c)}`;
this.state = S_PI_BODY;
}
this.xmlDeclPossible = false;
}
private sXMLDeclNameStart(): void {
const c = this.skipSpaces();
// The question mark character is not valid inside any of the XML
// declaration name/value pairs.
if (c === QUESTION) {
// It is valid to go to S_XML_DECL_ENDING from this state.
this.state = S_XML_DECL_ENDING;
return;
}
if (c !== EOC) {
this.state = S_XML_DECL_NAME;
this.name = String.fromCodePoint(c);
}
}
private sXMLDeclName(): void {
const c = this.captureTo(XML_DECL_NAME_TERMINATOR);
// The question mark character is not valid inside any of the XML
// declaration name/value pairs.
if (c === QUESTION) {
this.state = S_XML_DECL_ENDING;
this.name += this.text;
this.text = "";
this.fail("XML declaration is incomplete.");
return;
}
if (!(isS(c) || c === EQUAL)) {
return;
}
this.name += this.text;
this.text = "";
if (!this.xmlDeclExpects.includes(this.name)) {
switch (this.name.length) {
case 0:
this.fail("did not expect any more name/value pairs.");
break;
case 1:
this.fail(`expected the name ${this.xmlDeclExpects[0]}.`);
break;
default:
this.fail(`expected one of ${this.xmlDeclExpects.join(", ")}`);
}
}
this.state = c === EQUAL ? S_XML_DECL_VALUE_START : S_XML_DECL_EQ;
}
private sXMLDeclEq(): void {
const c = this.getCodeNorm();
// The question mark character is not valid inside any of the XML
// declaration name/value pairs.
if (c === QUESTION) {
this.state = S_XML_DECL_ENDING;
this.fail("XML declaration is incomplete.");
return;
}
if (isS(c)) {
return;
}
if (c !== EQUAL) {
this.fail("value required.");
}
this.state = S_XML_DECL_VALUE_START;
}
private sXMLDeclValueStart(): void {
const c = this.getCodeNorm();
// The question mark character is not valid inside any of the XML
// declaration name/value pairs.
if (c === QUESTION) {
this.state = S_XML_DECL_ENDING;
this.fail("XML declaration is incomplete.");
return;
}
if (isS(c)) {
return;
}
if (!isQuote(c)) {
this.fail("value must be quoted.");
this.q = SPACE;
}
else {
this.q = c;
}
this.state = S_XML_DECL_VALUE;
}
private sXMLDeclValue(): void {
const c = this.captureTo([this.q!, QUESTION]);
// The question mark character is not valid inside any of the XML
// declaration name/value pairs.
if (c === QUESTION) {
this.state = S_XML_DECL_ENDING;
this.text = "";
this.fail("XML declaration is incomplete.");
return;
}
if (c === EOC) {
return;
}
const value = this.text;
this.text = "";
switch (this.name) {
case "version": {
this.xmlDeclExpects = ["encoding", "standalone"];
const version = value;
this.xmlDecl.version = version;
// This is the test specified by XML 1.0 but it is fine for XML 1.1.
if (!/^1\.[0-9]+$/.test(version)) {
this.fail("version number must match /^1\\.[0-9]+$/.");
}
// When forceXMLVersion is set, the XML declaration is ignored.
else if (!(this.opt.forceXMLVersion as boolean)) {
this.setXMLVersion(version);
}
break;
}
case "encoding":
if (!/^[A-Za-z][A-Za-z0-9._-]*$/.test(value)) {
this.fail("encoding value must match \
/^[A-Za-z0-9][A-Za-z0-9._-]*$/.");
}
this.xmlDeclExpects = ["standalone"];
this.xmlDecl.encoding = value;
break;
case "standalone":
if (value !== "yes" && value !== "no") {
this.fail("standalone value must match \"yes\" or \"no\".");
}
this.xmlDeclExpects = [];
this.xmlDecl.standalone = value;
break;
default:
// We don't need to raise an error here since we've already raised one
// when checking what name was expected.
}
this.name = "";
this.state = S_XML_DECL_SEPARATOR;
}
private sXMLDeclSeparator(): void {
const c = this.getCodeNorm();
// The question mark character is not valid inside any of the XML
// declaration name/value pairs.
if (c === QUESTION) {
// It is valid to go to S_XML_DECL_ENDING from this state.
this.state = S_XML_DECL_ENDING;
return;
}
if (!isS(c)) {
this.fail("whitespace required.");
this.unget();
}
this.state = S_XML_DECL_NAME_START;
}
private sXMLDeclEnding(): void {
const c = this.getCodeNorm();
if (c === GREATER) {
if (this.piTarget !== "xml") {
this.fail("processing instructions are not allowed before root.");
}
else if (this.name !== "version" &&
this.xmlDeclExpects.includes("version")) {
this.fail("XML declaration must contain a version.");
}
this.xmldeclHandler?.(this.xmlDecl);
this.name = "";
this.piTarget = this.text = "";
this.state = S_TEXT;
}
else {
// We got here because the previous character was a ?, but the question
// mark character is not valid inside any of the XML declaration
// name/value pairs.
this.fail(
"The character ? is disallowed anywhere in XML declarations.");
}
this.xmlDeclPossible = false;
}
private sOpenTag(): void {
const c = this.captureNameChars();
if (c === EOC) {
return;
}
const tag: SaxesTagIncomplete = this.tag = {
name: this.name,
attributes: Object.create(null) as Record<string, string>,
};
this.name = "";
if (this.xmlnsOpt) {
this.topNS = tag.ns = Object.create(null) as Record<string, string>;
}
this.openTagStartHandler?.(tag as StartTagForOptions<O>);
this.sawRoot = true;
if (!this.fragmentOpt && this.closedRoot) {
this.fail("documents may contain only one root.");
}
switch (c) {
case GREATER:
this.openTag();
break;
case FORWARD_SLASH:
this.state = S_OPEN_TAG_SLASH;
break;
default:
if (!isS(c)) {
this.fail("disallowed character in tag name.");
}
this.state = S_ATTRIB;
}
}
private sOpenTagSlash(): void {
if (this.getCode() === GREATER) {
this.openSelfClosingTag();
}
else {
this.fail("forward-slash in opening tag not followed by >.");
this.state = S_ATTRIB;
}
}
private sAttrib(): void {
const c = this.skipSpaces();
if (c === EOC) {
return;
}
if (isNameStartChar(c)) {
this.unget();
this.state = S_ATTRIB_NAME;
}
else if (c === GREATER) {
this.openTag();
}
else if (c === FORWARD_SLASH) {
this.state = S_OPEN_TAG_SLASH;
}
else {
this.fail("disallowed character in attribute name.");
}
}
private sAttribName(): void {
const c = this.captureNameChars();
if (c === EQUAL) {
this.state = S_ATTRIB_VALUE;
}
else if (isS(c)) {
this.state = S_ATTRIB_NAME_SAW_WHITE;
}
else if (c === GREATER) {
this.fail("attribute without value.");
this.pushAttrib(this.name, this.name);
this.name = this.text = "";
this.openTag();
}
else if (c !== EOC) {
this.fail("disallowed character in attribute name.");
}
}
private sAttribNameSawWhite(): void {
const c = this.skipSpaces();
switch (c) {
case EOC:
return;
case EQUAL:
this.state = S_ATTRIB_VALUE;
break;
default:
this.fail("attribute without value.");
// Should we do this???
// this.tag.attributes[this.name] = "";
this.text = "";
this.name = "";
if (c === GREATER) {
this.openTag();
}
else if (isNameStartChar(c)) {
this.unget();
this.state = S_ATTRIB_NAME;
}
else {
this.fail("disallowed character in attribute name.");
this.state = S_ATTRIB;
}
}
}
private sAttribValue(): void {
const c = this.getCodeNorm();
if (isQuote(c)) {
this.q = c;
this.state = S_ATTRIB_VALUE_QUOTED;
}
else if (!isS(c)) {
this.fail("unquoted attribute value.");
this.state = S_ATTRIB_VALUE_UNQUOTED;
this.unget();
}
}
private sAttribValueQuoted(): void {
// We deliberately do not use captureTo here. The specialized code we use
// here is faster than using captureTo.
const { q, chunk } = this;
let { i: start } = this;
// eslint-disable-next-line no-constant-condition
while (true) {
switch (this.getCode()) {
case q:
this.pushAttrib(this.name,
this.text + chunk.slice(start, this.prevI));
this.name = this.text = "";
this.q = null;
this.state = S_ATTRIB_VALUE_CLOSED;
return;
case AMP:
this.text += chunk.slice(start, this.prevI);
this.state = S_ENTITY;
this.entityReturnState = S_ATTRIB_VALUE_QUOTED;
return;
case NL:
case NL_LIKE:
case TAB:
this.text += `${chunk.slice(start, this.prevI)} `;
start = this.i;
break;
case LESS:
this.text += chunk.slice(start, this.prevI);
this.fail("disallowed character.");
return;
case EOC:
this.text += chunk.slice(start);
return;
default:
}
}
}
private sAttribValueClosed(): void {
const c = this.getCodeNorm();
if (isS(c)) {
this.state = S_ATTRIB;
}
else if (c === GREATER) {
this.openTag();
}
else if (c === FORWARD_SLASH) {
this.state = S_OPEN_TAG_SLASH;
}
else if (isNameStartChar(c)) {
this.fail("no whitespace between attributes.");
this.unget();
this.state = S_ATTRIB_NAME;
}
else {
this.fail("disallowed character in attribute name.");
}
}
private sAttribValueUnquoted(): void {
// We don't do anything regarding EOL or space handling for unquoted
// attributes. We already have failed by the time we get here, and the
// contract that saxes upholds states that upon failure, it is not safe to
// rely on the data passed to event handlers (other than
// ``onerror``). Passing "bad" data is not a problem.
const c = this.captureTo(ATTRIB_VALUE_UNQUOTED_TERMINATOR);
switch (c) {
case AMP:
this.state = S_ENTITY;
this.entityReturnState = S_ATTRIB_VALUE_UNQUOTED;
break;
case LESS:
this.fail("disallowed character.");
break;
case EOC:
break;
default:
if (this.text.includes("]]>")) {
this.fail("the string \"]]>\" is disallowed in char data.");
}
this.pushAttrib(this.name, this.text);
this.name = this.text = "";
if (c === GREATER) {
this.openTag();
}
else {
this.state = S_ATTRIB;
}
}
}
private sCloseTag(): void {
const c = this.captureNameChars();
if (c === GREATER) {
this.closeTag();
}
else if (isS(c)) {
this.state = S_CLOSE_TAG_SAW_WHITE;
}
else if (c !== EOC) {
this.fail("disallowed character in closing tag.");
}
}
private sCloseTagSawWhite(): void {
switch (this.skipSpaces()) {
case GREATER:
this.closeTag();
break;
case EOC:
break;
default:
this.fail("disallowed character in closing tag.");
}
}
// END OF STATE ENGINE METHODS
private handleTextInRoot(): void {
// This is essentially a specialized version of captureTo which is optimized
// for performing the ]]> check. A previous version of this code, checked
// ``this.text`` for the presence of ]]>. It simplified the code but was
// very costly when character data contained a lot of entities to be parsed.
//
// Since we are using a specialized loop, we also keep track of the presence
// of ]]> in text data. The sequence ]]> is forbidden to appear as-is.
//
let { i: start, forbiddenState } = this;
const { chunk, textHandler: handler } = this;
// eslint-disable-next-line no-labels, no-restricted-syntax
scanLoop:
// eslint-disable-next-line no-constant-condition
while (true) {
switch (this.getCode()) {
case LESS: {
this.state = S_OPEN_WAKA;
if (handler !== undefined) {
const { text } = this;
const slice = chunk.slice(start, this.prevI);
if (text.length !== 0) {
handler(text + slice);
this.text = "";
}
else if (slice.length !== 0) {
handler(slice);
}
}
forbiddenState = FORBIDDEN_START;
// eslint-disable-next-line no-labels
break scanLoop;
}
case AMP:
this.state = S_ENTITY;
this.entityReturnState = S_TEXT;
if (handler !== undefined) {
this.text += chunk.slice(start, this.prevI);
}
forbiddenState = FORBIDDEN_START;
// eslint-disable-next-line no-labels
break scanLoop;
case CLOSE_BRACKET:
switch (forbiddenState) {
case FORBIDDEN_START:
forbiddenState = FORBIDDEN_BRACKET;
break;
case FORBIDDEN_BRACKET:
forbiddenState = FORBIDDEN_BRACKET_BRACKET;
break;
case FORBIDDEN_BRACKET_BRACKET:
break;
default:
throw new Error("impossible state");
}
break;
case GREATER:
if (forbiddenState === FORBIDDEN_BRACKET_BRACKET) {
this.fail("the string \"]]>\" is disallowed in char data.");
}
forbiddenState = FORBIDDEN_START;
break;
case NL_LIKE:
if (handler !== undefined) {
this.text += `${chunk.slice(start, this.prevI)}\n`;
}
start = this.i;
forbiddenState = FORBIDDEN_START;
break;
case EOC:
if (handler !== undefined) {
this.text += chunk.slice(start);
}
// eslint-disable-next-line no-labels
break scanLoop;
default:
forbiddenState = FORBIDDEN_START;
}
}
this.forbiddenState = forbiddenState;
}
private handleTextOutsideRoot(): void {
// This is essentially a specialized version of captureTo which is optimized
// for a specialized task. We keep track of the presence of non-space
// characters in the text since these are errors when appearing outside the
// document root element.
let { i: start } = this;
const { chunk, textHandler: handler } = this;
let nonSpace = false;
// eslint-disable-next-line no-labels, no-restricted-syntax
outRootLoop:
// eslint-disable-next-line no-constant-condition
while (true) {
const code = this.getCode();
switch (code) {
case LESS: {
this.state = S_OPEN_WAKA;
if (handler !== undefined) {
const { text } = this;
const slice = chunk.slice(start, this.prevI);
if (text.length !== 0) {
handler(text + slice);
this.text = "";
}
else if (slice.length !== 0) {
handler(slice);
}
}
// eslint-disable-next-line no-labels
break outRootLoop;
}
case AMP:
this.state = S_ENTITY;
this.entityReturnState = S_TEXT;
if (handler !== undefined) {
this.text += chunk.slice(start, this.prevI);
}
nonSpace = true;
// eslint-disable-next-line no-labels
break outRootLoop;
case NL_LIKE:
if (handler !== undefined) {
this.text += `${chunk.slice(start, this.prevI)}\n`;
}
start = this.i;
break;
case EOC:
if (handler !== undefined) {
this.text += chunk.slice(start);
}
// eslint-disable-next-line no-labels
break outRootLoop;
default:
if (!isS(code)) {
nonSpace = true;
}
}
}
if (!nonSpace) {
return;
}
// We use the reportedTextBeforeRoot and reportedTextAfterRoot flags
// to avoid reporting errors for every single character that is out of
// place.
if (!this.sawRoot && !this.reportedTextBeforeRoot) {
this.fail("text data outside of root node.");
this.reportedTextBeforeRoot = true;
}
if (this.closedRoot && !this.reportedTextAfterRoot) {
this.fail("text data outside of root node.");
this.reportedTextAfterRoot = true;
}
}
private pushAttribNS(name: string, value: string): void {
const { prefix, local } = this.qname(name);
const attr = { name, prefix, local, value };
this.attribList.push(attr);
this.attributeHandler?.(attr as AttributeEventForOptions<O>);
if (prefix === "xmlns") {
const trimmed = value.trim();
if (this.currentXMLVersion === "1.0" && trimmed === "") {
this.fail("invalid attempt to undefine prefix in XML 1.0");
}
this.topNS![local] = trimmed;
nsPairCheck(this, local, trimmed);
}
else if (name === "xmlns") {
const trimmed = value.trim();
this.topNS![""] = trimmed;
nsPairCheck(this, "", trimmed);
}
}
private pushAttribPlain(name: string, value: string): void {
const attr = { name, value };
this.attribList.push(attr);
this.attributeHandler?.(attr as AttributeEventForOptions<O>);
}
/**
* End parsing. This performs final well-formedness checks and resets the
* parser to a clean state.
*
* @returns this
*/
private end(): this {
if (!this.sawRoot) {
this.fail("document must contain a root element.");
}
const { tags } = this;
while (tags.length > 0) {
const tag = tags.pop()!;
this.fail(`unclosed tag: ${tag.name}`);
}
if ((this.state !== S_BEGIN) && (this.state !== S_TEXT)) {
this.fail("unexpected end.");
}
const { text } = this;
if (text.length !== 0) {
this.textHandler?.(text);
this.text = "";
}
this._closed = true;
this.endHandler?.();
this._init();
return this;
}
/**
* Resolve a namespace prefix.
*
* @param prefix The prefix to resolve.
*
* @returns The namespace URI or ``undefined`` if the prefix is not defined.
*/
resolve(prefix: string): string | undefined {
let uri = this.topNS![prefix];
if (uri !== undefined) {
return uri;
}
const { tags } = this;
for (let index = tags.length - 1; index >= 0; index--) {
uri = tags[index]!.ns![prefix];
if (uri !== undefined) {
return uri;
}
}
uri = this.ns[prefix];
if (uri !== undefined) {
return uri;
}
return this.opt.resolvePrefix?.(prefix);
}
/**
* Parse a qname into its prefix and local name parts.
*
* @param name The name to parse
*
* @returns
*/
private qname(name: string): { prefix: string; local: string } {
// This is faster than using name.split(":").
const colon = name.indexOf(":");
if (colon === -1) {
return { prefix: "", local: name };
}
const local = name.slice(colon + 1);
const prefix = name.slice(0, colon);
if (prefix === "" || local === "" || local.includes(":")) {
this.fail(`malformed name: ${name}.`);
}
return { prefix, local };
}
private processAttribsNS(): void {
const { attribList } = this;
const tag = this.tag!;
{
// add namespace info to tag
const { prefix, local } = this.qname(tag.name);
tag.prefix = prefix;
tag.local = local;
const uri = tag.uri = this.resolve(prefix) ?? "";
if (prefix !== "") {
if (prefix === "xmlns") {
this.fail("tags may not have \"xmlns\" as prefix.");
}
if (uri === "") {
this.fail(`unbound namespace prefix: ${JSON.stringify(prefix)}.`);
tag.uri = prefix;
}
}
}
if (attribList.length === 0) {
return;
}
const { attributes } = tag;
const seen = new Set();
// Note: do not apply default ns to attributes:
// http://www.w3.org/TR/REC-xml-names/#defaulting
for (const attr of attribList as SaxesAttributeNSIncomplete[]) {
const { name, prefix, local } = attr;
let uri;
let eqname;
if (prefix === "") {
uri = name === "xmlns" ? XMLNS_NAMESPACE : "";
eqname = name;
}
else {
uri = this.resolve(prefix);
// if there's any attributes with an undefined namespace,
// then fail on them now.
if (uri === undefined) {
this.fail(`unbound namespace prefix: ${JSON.stringify(prefix)}.`);
uri = prefix;
}
eqname = `{${uri}}${local}`;
}
if (seen.has(eqname)) {
this.fail(`duplicate attribute: ${eqname}.`);
}
seen.add(eqname);
attr.uri = uri;
attributes[name] = attr;
}
this.attribList = [];
}
private processAttribsPlain(): void {
const { attribList } = this;
// eslint-disable-next-line prefer-destructuring
const attributes = this.tag!.attributes;
for (const { name, value } of attribList) {
if (attributes[name] !== undefined) {
this.fail(`duplicate attribute: ${name}.`);
}
attributes[name] = value;
}
this.attribList = [];
}
/**
* Handle a complete open tag. This parser code calls this once it has seen
* the whole tag. This method checks for well-formeness and then emits
* ``onopentag``.
*/
private openTag(): void {
this.processAttribs();
const { tags } = this;
const tag = this.tag as SaxesTag;
tag.isSelfClosing = false;
// There cannot be any pending text here due to the onopentagstart that was
// necessarily emitted before we get here. So we do not check text.
this.openTagHandler?.(tag as TagForOptions<O>);
tags.push(tag);
this.state = S_TEXT;
this.name = "";
}
/**
* Handle a complete self-closing tag. This parser code calls this once it has
* seen the whole tag. This method checks for well-formeness and then emits
* ``onopentag`` and ``onclosetag``.
*/
private openSelfClosingTag(): void {
this.processAttribs();
const { tags } = this;
const tag = this.tag as SaxesTag;
tag.isSelfClosing = true;
// There cannot be any pending text here due to the onopentagstart that was
// necessarily emitted before we get here. So we do not check text.
this.openTagHandler?.(tag as TagForOptions<O>);
this.closeTagHandler?.(tag as TagForOptions<O>);
const top = this.tag = tags[tags.length - 1] ?? null;
if (top === null) {
this.closedRoot = true;
}
this.state = S_TEXT;
this.name = "";
}
/**
* Handle a complete close tag. This parser code calls this once it has seen
* the whole tag. This method checks for well-formeness and then emits
* ``onclosetag``.
*/
private closeTag(): void {
const { tags, name } = this;
// Our state after this will be S_TEXT, no matter what, and we can clear
// tagName now.
this.state = S_TEXT;
this.name = "";
if (name === "") {
this.fail("weird empty close tag.");
this.text += "</>";
return;
}
const handler = this.closeTagHandler;
let l = tags.length;
while (l-- > 0) {
const tag = this.tag = tags.pop() as SaxesTag;
this.topNS = tag.ns!;
handler?.(tag as TagForOptions<O>);
if (tag.name === name) {
break;
}
this.fail("unexpected close tag.");
}
if (l === 0) {
this.closedRoot = true;
}
else if (l < 0) {
this.fail(`unmatched closing tag: ${name}.`);
this.text += `</${name}>`;
}
}
/**
* Resolves an entity. Makes any necessary well-formedness checks.
*
* @param entity The entity to resolve.
*
* @returns The parsed entity.
*/
private parseEntity(entity: string): string {
// startsWith would be significantly slower for this test.
if (entity[0] !== "#") {
const defined = this.ENTITIES[entity];
if (defined !== undefined) {
return defined;
}
this.fail(this.isName(entity) ? "undefined entity." :
"disallowed character in entity name.");
return `&${entity};`;
}
let num = NaN;
if (entity[1] === "x" && /^#x[0-9a-f]+$/i.test(entity)) {
num = parseInt(entity.slice(2), 16);
}
else if (/^#[0-9]+$/.test(entity)) {
num = parseInt(entity.slice(1), 10);
}
// The character reference is required to match the CHAR production.
if (!this.isChar(num)) {
this.fail("malformed character entity.");
return `&${entity};`;
}
return String.fromCodePoint(num);
}
} |
1,147 | fn(parser: SaxesParser): void {
for (const x of nel) {
parser.write(x);
}
parser.close();
} | class SaxesParser<O extends SaxesOptions = {}> {
private readonly fragmentOpt: boolean;
private readonly xmlnsOpt: boolean;
private readonly trackPosition: boolean;
private readonly fileName?: string;
private readonly nameStartCheck: (c: number) => boolean;
private readonly nameCheck: (c: number) => boolean;
private readonly isName: (name: string) => boolean;
private readonly ns!: Record<string, string>;
private openWakaBang!: string;
private text!: string;
private name!: string;
private piTarget!: string;
private entity!: string;
private q!: null | number;
private tags!: SaxesTagIncomplete[];
private tag!: SaxesTagIncomplete | null;
private topNS!: Record<string, string> | null;
private chunk!: string;
private chunkPosition!: number;
private i!: number;
//
// We use prevI to allow "ungetting" the previously read code point. Note
// however, that it is not safe to unget everything and anything. In
// particular ungetting EOL characters will screw positioning up.
//
// Practically, you must not unget a code which has any side effect beyond
// updating ``this.i`` and ``this.prevI``. Only EOL codes have such side
// effects.
//
private prevI!: number;
private carriedFromPrevious?: string;
private forbiddenState!: number;
private attribList!: (SaxesAttributeNSIncomplete | SaxesAttributePlain)[];
private state!: number;
private reportedTextBeforeRoot!: boolean;
private reportedTextAfterRoot!: boolean;
private closedRoot!: boolean;
private sawRoot!: boolean;
private xmlDeclPossible!: boolean;
private xmlDeclExpects!: string[];
private entityReturnState?: number;
private processAttribs!: (this: this) => void;
private positionAtNewLine!: number;
private doctype!: boolean;
private getCode!: () => number;
private isChar!: (c: number) => boolean;
private pushAttrib!: (name: string, value: string) => void;
private _closed!: boolean;
private currentXMLVersion!: string;
private readonly stateTable: ((this: SaxesParser<O>) => void)[];
private xmldeclHandler?: XMLDeclHandler;
private textHandler?: TextHandler;
private piHandler?: PIHandler;
private doctypeHandler?: DoctypeHandler;
private commentHandler?: CommentHandler;
private openTagStartHandler?: OpenTagStartHandler<O>;
private openTagHandler?: OpenTagHandler<O>;
private closeTagHandler?: CloseTagHandler<O>;
private cdataHandler?: CDataHandler;
private errorHandler?: ErrorHandler;
private endHandler?: EndHandler;
private readyHandler?: ReadyHandler;
private attributeHandler?: AttributeHandler<O>;
/**
* Indicates whether or not the parser is closed. If ``true``, wait for
* the ``ready`` event to write again.
*/
get closed(): boolean {
return this._closed;
}
readonly opt: SaxesOptions;
/**
* The XML declaration for this document.
*/
xmlDecl!: XMLDecl;
/**
* The line number of the next character to be read by the parser. This field
* is one-based. (The first line is numbered 1.)
*/
line!: number;
/**
* The column number of the next character to be read by the parser. *
* This field is zero-based. (The first column is 0.)
*
* This field counts columns by *Unicode character*. Note that this *can*
* be different from the index of the character in a JavaScript string due
* to how JavaScript handles astral plane characters.
*
* See [[columnIndex]] for a number that corresponds to the JavaScript index.
*/
column!: number;
/**
* A map of entity name to expansion.
*/
ENTITIES!: Record<string, string>;
/**
* @param opt The parser options.
*/
constructor(opt?: O) {
this.opt = opt ?? {};
this.fragmentOpt = !!(this.opt.fragment as boolean);
const xmlnsOpt = this.xmlnsOpt = !!(this.opt.xmlns as boolean);
this.trackPosition = this.opt.position !== false;
this.fileName = this.opt.fileName;
if (xmlnsOpt) {
// This is the function we use to perform name checks on PIs and entities.
// When namespaces are used, colons are not allowed in PI target names or
// entity names. So the check depends on whether namespaces are used. See:
//
// https://www.w3.org/XML/xml-names-19990114-errata.html
// NE08
//
this.nameStartCheck = isNCNameStartChar;
this.nameCheck = isNCNameChar;
this.isName = isNCName;
// eslint-disable-next-line @typescript-eslint/unbound-method
this.processAttribs = this.processAttribsNS;
// eslint-disable-next-line @typescript-eslint/unbound-method
this.pushAttrib = this.pushAttribNS;
// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-assignment
this.ns = { __proto__: null as any, ...rootNS };
const additional = this.opt.additionalNamespaces;
if (additional != null) {
nsMappingCheck(this, additional);
Object.assign(this.ns, additional);
}
}
else {
this.nameStartCheck = isNameStartChar;
this.nameCheck = isNameChar;
this.isName = isName;
// eslint-disable-next-line @typescript-eslint/unbound-method
this.processAttribs = this.processAttribsPlain;
// eslint-disable-next-line @typescript-eslint/unbound-method
this.pushAttrib = this.pushAttribPlain;
}
//
// The order of the members in this table needs to correspond to the state
// numbers given to the states that correspond to the methods being recorded
// here.
//
this.stateTable = [
/* eslint-disable @typescript-eslint/unbound-method */
this.sBegin,
this.sBeginWhitespace,
this.sDoctype,
this.sDoctypeQuote,
this.sDTD,
this.sDTDQuoted,
this.sDTDOpenWaka,
this.sDTDOpenWakaBang,
this.sDTDComment,
this.sDTDCommentEnding,
this.sDTDCommentEnded,
this.sDTDPI,
this.sDTDPIEnding,
this.sText,
this.sEntity,
this.sOpenWaka,
this.sOpenWakaBang,
this.sComment,
this.sCommentEnding,
this.sCommentEnded,
this.sCData,
this.sCDataEnding,
this.sCDataEnding2,
this.sPIFirstChar,
this.sPIRest,
this.sPIBody,
this.sPIEnding,
this.sXMLDeclNameStart,
this.sXMLDeclName,
this.sXMLDeclEq,
this.sXMLDeclValueStart,
this.sXMLDeclValue,
this.sXMLDeclSeparator,
this.sXMLDeclEnding,
this.sOpenTag,
this.sOpenTagSlash,
this.sAttrib,
this.sAttribName,
this.sAttribNameSawWhite,
this.sAttribValue,
this.sAttribValueQuoted,
this.sAttribValueClosed,
this.sAttribValueUnquoted,
this.sCloseTag,
this.sCloseTagSawWhite,
/* eslint-enable @typescript-eslint/unbound-method */
];
this._init();
}
_init(): void {
this.openWakaBang = "";
this.text = "";
this.name = "";
this.piTarget = "";
this.entity = "";
this.q = null;
this.tags = [];
this.tag = null;
this.topNS = null;
this.chunk = "";
this.chunkPosition = 0;
this.i = 0;
this.prevI = 0;
this.carriedFromPrevious = undefined;
this.forbiddenState = FORBIDDEN_START;
this.attribList = [];
// The logic is organized so as to minimize the need to check
// this.opt.fragment while parsing.
const { fragmentOpt } = this;
this.state = fragmentOpt ? S_TEXT : S_BEGIN;
// We want these to be all true if we are dealing with a fragment.
this.reportedTextBeforeRoot = this.reportedTextAfterRoot = this.closedRoot =
this.sawRoot = fragmentOpt;
// An XML declaration is intially possible only when parsing whole
// documents.
this.xmlDeclPossible = !fragmentOpt;
this.xmlDeclExpects = ["version"];
this.entityReturnState = undefined;
let { defaultXMLVersion } = this.opt;
if (defaultXMLVersion === undefined) {
if (this.opt.forceXMLVersion === true) {
throw new Error("forceXMLVersion set but defaultXMLVersion is not set");
}
defaultXMLVersion = "1.0";
}
this.setXMLVersion(defaultXMLVersion);
this.positionAtNewLine = 0;
this.doctype = false;
this._closed = false;
this.xmlDecl = {
version: undefined,
encoding: undefined,
standalone: undefined,
};
this.line = 1;
this.column = 0;
this.ENTITIES = Object.create(XML_ENTITIES) as Record<string, string>;
this.readyHandler?.();
}
/**
* The stream position the parser is currently looking at. This field is
* zero-based.
*
* This field is not based on counting Unicode characters but is to be
* interpreted as a plain index into a JavaScript string.
*/
get position(): number {
return this.chunkPosition + this.i;
}
/**
* The column number of the next character to be read by the parser. *
* This field is zero-based. (The first column in a line is 0.)
*
* This field reports the index at which the next character would be in the
* line if the line were represented as a JavaScript string. Note that this
* *can* be different to a count based on the number of *Unicode characters*
* due to how JavaScript handles astral plane characters.
*
* See [[column]] for a number that corresponds to a count of Unicode
* characters.
*/
get columnIndex(): number {
return this.position - this.positionAtNewLine;
}
/**
* Set an event listener on an event. The parser supports one handler per
* event type. If you try to set an event handler over an existing handler,
* the old handler is silently overwritten.
*
* @param name The event to listen to.
*
* @param handler The handler to set.
*/
on<N extends EventName>(name: N, handler: EventNameToHandler<O, N>): void {
// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-member-access
(this as any)[EVENT_NAME_TO_HANDLER_NAME[name]] = handler;
}
/**
* Unset an event handler.
*
* @parma name The event to stop listening to.
*/
off(name: EventName): void {
// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-member-access
(this as any)[EVENT_NAME_TO_HANDLER_NAME[name]] = undefined;
}
/**
* Make an error object. The error object will have a message that contains
* the ``fileName`` option passed at the creation of the parser. If position
* tracking was turned on, it will also have line and column number
* information.
*
* @param message The message describing the error to report.
*
* @returns An error object with a properly formatted message.
*/
makeError(message: string): Error {
let msg = this.fileName ?? "";
if (this.trackPosition) {
if (msg.length > 0) {
msg += ":";
}
msg += `${this.line}:${this.column}`;
}
if (msg.length > 0) {
msg += ": ";
}
return new Error(msg + message);
}
/**
* Report a parsing error. This method is made public so that client code may
* check for issues that are outside the scope of this project and can report
* errors.
*
* @param message The error to report.
*
* @returns this
*/
fail(message: string): this {
const err = this.makeError(message);
const handler = this.errorHandler;
if (handler === undefined) {
throw err;
}
else {
handler(err);
}
return this;
}
/**
* Write a XML data to the parser.
*
* @param chunk The XML data to write.
*
* @returns this
*/
// We do need object for the type here. Yes, it often causes problems
// but not in this case.
write(chunk: string | object | null): this {
if (this.closed) {
return this.fail("cannot write after close; assign an onready handler.");
}
let end = false;
if (chunk === null) {
// We cannot return immediately because carriedFromPrevious may need
// processing.
end = true;
chunk = "";
}
else if (typeof chunk === "object") {
chunk = chunk.toString();
}
// We checked if performing a pre-decomposition of the string into an array
// of single complete characters (``Array.from(chunk)``) would be faster
// than the current repeated calls to ``charCodeAt``. As of August 2018, it
// isn't. (There may be Node-specific code that would perform faster than
// ``Array.from`` but don't want to be dependent on Node.)
if (this.carriedFromPrevious !== undefined) {
// The previous chunk had char we must carry over.
chunk = `${this.carriedFromPrevious}${chunk}`;
this.carriedFromPrevious = undefined;
}
let limit = chunk.length;
const lastCode = chunk.charCodeAt(limit - 1);
if (!end &&
// A trailing CR or surrogate must be carried over to the next
// chunk.
(lastCode === CR || (lastCode >= 0xD800 && lastCode <= 0xDBFF))) {
// The chunk ends with a character that must be carried over. We cannot
// know how to handle it until we get the next chunk or the end of the
// stream. So save it for later.
this.carriedFromPrevious = chunk[limit - 1];
limit--;
chunk = chunk.slice(0, limit);
}
const { stateTable } = this;
this.chunk = chunk;
this.i = 0;
while (this.i < limit) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-argument
stateTable[this.state].call(this as any);
}
this.chunkPosition += limit;
return end ? this.end() : this;
}
/**
* Close the current stream. Perform final well-formedness checks and reset
* the parser tstate.
*
* @returns this
*/
close(): this {
return this.write(null);
}
/**
* Get a single code point out of the current chunk. This updates the current
* position if we do position tracking.
*
* This is the algorithm to use for XML 1.0.
*
* @returns The character read.
*/
private getCode10(): number {
const { chunk, i } = this;
this.prevI = i;
// Yes, we do this instead of doing this.i++. Doing it this way, we do not
// read this.i again, which is a bit faster.
this.i = i + 1;
if (i >= chunk.length) {
return EOC;
}
// Using charCodeAt and handling the surrogates ourselves is faster
// than using codePointAt.
const code = chunk.charCodeAt(i);
this.column++;
if (code < 0xD800) {
if (code >= SPACE || code === TAB) {
return code;
}
switch (code) {
case NL:
this.line++;
this.column = 0;
this.positionAtNewLine = this.position;
return NL;
case CR:
// We may get NaN if we read past the end of the chunk, which is fine.
if (chunk.charCodeAt(i + 1) === NL) {
// A \r\n sequence is converted to \n so we have to skip over the
// next character. We already know it has a size of 1 so ++ is fine
// here.
this.i = i + 2;
}
// Otherwise, a \r is just converted to \n, so we don't have to skip
// ahead.
// In either case, \r becomes \n.
this.line++;
this.column = 0;
this.positionAtNewLine = this.position;
return NL_LIKE;
default:
// If we get here, then code < SPACE and it is not NL CR or TAB.
this.fail("disallowed character.");
return code;
}
}
if (code > 0xDBFF) {
// This is a specialized version of isChar10 that takes into account
// that in this context code > 0xDBFF and code <= 0xFFFF. So it does not
// test cases that don't need testing.
if (!(code >= 0xE000 && code <= 0xFFFD)) {
this.fail("disallowed character.");
}
return code;
}
const final = 0x10000 + ((code - 0xD800) * 0x400) +
(chunk.charCodeAt(i + 1) - 0xDC00);
this.i = i + 2;
// This is a specialized version of isChar10 that takes into account that in
// this context necessarily final >= 0x10000.
if (final > 0x10FFFF) {
this.fail("disallowed character.");
}
return final;
}
/**
* Get a single code point out of the current chunk. This updates the current
* position if we do position tracking.
*
* This is the algorithm to use for XML 1.1.
*
* @returns {number} The character read.
*/
private getCode11(): number {
const { chunk, i } = this;
this.prevI = i;
// Yes, we do this instead of doing this.i++. Doing it this way, we do not
// read this.i again, which is a bit faster.
this.i = i + 1;
if (i >= chunk.length) {
return EOC;
}
// Using charCodeAt and handling the surrogates ourselves is faster
// than using codePointAt.
const code = chunk.charCodeAt(i);
this.column++;
if (code < 0xD800) {
if ((code > 0x1F && code < 0x7F) || (code > 0x9F && code !== LS) ||
code === TAB) {
return code;
}
switch (code) {
case NL: // 0xA
this.line++;
this.column = 0;
this.positionAtNewLine = this.position;
return NL;
case CR: { // 0xD
// We may get NaN if we read past the end of the chunk, which is
// fine.
const next = chunk.charCodeAt(i + 1);
if (next === NL || next === NEL) {
// A CR NL or CR NEL sequence is converted to NL so we have to skip
// over the next character. We already know it has a size of 1.
this.i = i + 2;
}
// Otherwise, a CR is just converted to NL, no skip.
}
/* yes, fall through */
case NEL: // 0x85
case LS: // Ox2028
this.line++;
this.column = 0;
this.positionAtNewLine = this.position;
return NL_LIKE;
default:
this.fail("disallowed character.");
return code;
}
}
if (code > 0xDBFF) {
// This is a specialized version of isCharAndNotRestricted that takes into
// account that in this context code > 0xDBFF and code <= 0xFFFF. So it
// does not test cases that don't need testing.
if (!(code >= 0xE000 && code <= 0xFFFD)) {
this.fail("disallowed character.");
}
return code;
}
const final = 0x10000 + ((code - 0xD800) * 0x400) +
(chunk.charCodeAt(i + 1) - 0xDC00);
this.i = i + 2;
// This is a specialized version of isCharAndNotRestricted that takes into
// account that in this context necessarily final >= 0x10000.
if (final > 0x10FFFF) {
this.fail("disallowed character.");
}
return final;
}
/**
* Like ``getCode`` but with the return value normalized so that ``NL`` is
* returned for ``NL_LIKE``.
*/
private getCodeNorm(): number {
const c = this.getCode();
return c === NL_LIKE ? NL : c;
}
private unget(): void {
this.i = this.prevI;
this.column--;
}
/**
* Capture characters into a buffer until encountering one of a set of
* characters.
*
* @param chars An array of codepoints. Encountering a character in the array
* ends the capture. (``chars`` may safely contain ``NL``.)
*
* @return The character code that made the capture end, or ``EOC`` if we hit
* the end of the chunk. The return value cannot be NL_LIKE: NL is returned
* instead.
*/
private captureTo(chars: number[]): number {
let { i: start } = this;
const { chunk } = this;
// eslint-disable-next-line no-constant-condition
while (true) {
const c = this.getCode();
const isNLLike = c === NL_LIKE;
const final = isNLLike ? NL : c;
if (final === EOC || chars.includes(final)) {
this.text += chunk.slice(start, this.prevI);
return final;
}
if (isNLLike) {
this.text += `${chunk.slice(start, this.prevI)}\n`;
start = this.i;
}
}
}
/**
* Capture characters into a buffer until encountering a character.
*
* @param char The codepoint that ends the capture. **NOTE ``char`` MAY NOT
* CONTAIN ``NL``.** Passing ``NL`` will result in buggy behavior.
*
* @return ``true`` if we ran into the character. Otherwise, we ran into the
* end of the current chunk.
*/
private captureToChar(char: number): boolean {
let { i: start } = this;
const { chunk } = this;
// eslint-disable-next-line no-constant-condition
while (true) {
let c = this.getCode();
switch (c) {
case NL_LIKE:
this.text += `${chunk.slice(start, this.prevI)}\n`;
start = this.i;
c = NL;
break;
case EOC:
this.text += chunk.slice(start);
return false;
default:
}
if (c === char) {
this.text += chunk.slice(start, this.prevI);
return true;
}
}
}
/**
* Capture characters that satisfy ``isNameChar`` into the ``name`` field of
* this parser.
*
* @return The character code that made the test fail, or ``EOC`` if we hit
* the end of the chunk. The return value cannot be NL_LIKE: NL is returned
* instead.
*/
private captureNameChars(): number {
const { chunk, i: start } = this;
// eslint-disable-next-line no-constant-condition
while (true) {
const c = this.getCode();
if (c === EOC) {
this.name += chunk.slice(start);
return EOC;
}
// NL is not a name char so we don't have to test specifically for it.
if (!isNameChar(c)) {
this.name += chunk.slice(start, this.prevI);
return c === NL_LIKE ? NL : c;
}
}
}
/**
* Skip white spaces.
*
* @return The character that ended the skip, or ``EOC`` if we hit
* the end of the chunk. The return value cannot be NL_LIKE: NL is returned
* instead.
*/
private skipSpaces(): number {
// eslint-disable-next-line no-constant-condition
while (true) {
const c = this.getCodeNorm();
if (c === EOC || !isS(c)) {
return c;
}
}
}
private setXMLVersion(version: string): void {
this.currentXMLVersion = version;
/* eslint-disable @typescript-eslint/unbound-method */
if (version === "1.0") {
this.isChar = isChar10;
this.getCode = this.getCode10;
}
else {
this.isChar = isChar11;
this.getCode = this.getCode11;
}
/* eslint-enable @typescript-eslint/unbound-method */
}
// STATE ENGINE METHODS
// This needs to be a state separate from S_BEGIN_WHITESPACE because we want
// to be sure never to come back to this state later.
private sBegin(): void {
// We are essentially peeking at the first character of the chunk. Since
// S_BEGIN can be in effect only when we start working on the first chunk,
// the index at which we must look is necessarily 0. Note also that the
// following test does not depend on decoding surrogates.
// If the initial character is 0xFEFF, ignore it.
if (this.chunk.charCodeAt(0) === 0xFEFF) {
this.i++;
this.column++;
}
this.state = S_BEGIN_WHITESPACE;
}
private sBeginWhitespace(): void {
// We need to know whether we've encountered spaces or not because as soon
// as we run into a space, an XML declaration is no longer possible. Rather
// than slow down skipSpaces even in places where we don't care whether it
// skipped anything or not, we check whether prevI is equal to the value of
// i from before we skip spaces.
const iBefore = this.i;
const c = this.skipSpaces();
if (this.prevI !== iBefore) {
this.xmlDeclPossible = false;
}
switch (c) {
case LESS:
this.state = S_OPEN_WAKA;
// We could naively call closeText but in this state, it is not normal
// to have text be filled with any data.
if (this.text.length !== 0) {
throw new Error("no-empty text at start");
}
break;
case EOC:
break;
default:
this.unget();
this.state = S_TEXT;
this.xmlDeclPossible = false;
}
}
private sDoctype(): void {
const c = this.captureTo(DOCTYPE_TERMINATOR);
switch (c) {
case GREATER: {
this.doctypeHandler?.(this.text);
this.text = "";
this.state = S_TEXT;
this.doctype = true; // just remember that we saw it.
break;
}
case EOC:
break;
default:
this.text += String.fromCodePoint(c);
if (c === OPEN_BRACKET) {
this.state = S_DTD;
}
else if (isQuote(c)) {
this.state = S_DOCTYPE_QUOTE;
this.q = c;
}
}
}
private sDoctypeQuote(): void {
const q = this.q!;
if (this.captureToChar(q)) {
this.text += String.fromCodePoint(q);
this.q = null;
this.state = S_DOCTYPE;
}
}
private sDTD(): void {
const c = this.captureTo(DTD_TERMINATOR);
if (c === EOC) {
return;
}
this.text += String.fromCodePoint(c);
if (c === CLOSE_BRACKET) {
this.state = S_DOCTYPE;
}
else if (c === LESS) {
this.state = S_DTD_OPEN_WAKA;
}
else if (isQuote(c)) {
this.state = S_DTD_QUOTED;
this.q = c;
}
}
private sDTDQuoted(): void {
const q = this.q!;
if (this.captureToChar(q)) {
this.text += String.fromCodePoint(q);
this.state = S_DTD;
this.q = null;
}
}
private sDTDOpenWaka(): void {
const c = this.getCodeNorm();
this.text += String.fromCodePoint(c);
switch (c) {
case BANG:
this.state = S_DTD_OPEN_WAKA_BANG;
this.openWakaBang = "";
break;
case QUESTION:
this.state = S_DTD_PI;
break;
default:
this.state = S_DTD;
}
}
private sDTDOpenWakaBang(): void {
const char = String.fromCodePoint(this.getCodeNorm());
const owb = this.openWakaBang += char;
this.text += char;
if (owb !== "-") {
this.state = owb === "--" ? S_DTD_COMMENT : S_DTD;
this.openWakaBang = "";
}
}
private sDTDComment(): void {
if (this.captureToChar(MINUS)) {
this.text += "-";
this.state = S_DTD_COMMENT_ENDING;
}
}
private sDTDCommentEnding(): void {
const c = this.getCodeNorm();
this.text += String.fromCodePoint(c);
this.state = c === MINUS ? S_DTD_COMMENT_ENDED : S_DTD_COMMENT;
}
private sDTDCommentEnded(): void {
const c = this.getCodeNorm();
this.text += String.fromCodePoint(c);
if (c === GREATER) {
this.state = S_DTD;
}
else {
this.fail("malformed comment.");
// <!-- blah -- bloo --> will be recorded as
// a comment of " blah -- bloo "
this.state = S_DTD_COMMENT;
}
}
private sDTDPI(): void {
if (this.captureToChar(QUESTION)) {
this.text += "?";
this.state = S_DTD_PI_ENDING;
}
}
private sDTDPIEnding(): void {
const c = this.getCodeNorm();
this.text += String.fromCodePoint(c);
if (c === GREATER) {
this.state = S_DTD;
}
}
private sText(): void {
//
// We did try a version of saxes where the S_TEXT state was split in two
// states: one for text inside the root element, and one for text
// outside. This was avoiding having to test this.tags.length to decide
// what implementation to actually use.
//
// Peformance testing on gigabyte-size files did not show any advantage to
// using the two states solution instead of the current one. Conversely, it
// made the code a bit more complicated elsewhere. For instance, a comment
// can appear before the root element so when a comment ended it was
// necessary to determine whether to return to the S_TEXT state or to the
// new text-outside-root state.
//
if (this.tags.length !== 0) {
this.handleTextInRoot();
}
else {
this.handleTextOutsideRoot();
}
}
private sEntity(): void {
// This is essentially a specialized version of captureToChar(SEMICOLON...)
let { i: start } = this;
const { chunk } = this;
// eslint-disable-next-line no-labels, no-restricted-syntax
loop:
// eslint-disable-next-line no-constant-condition
while (true) {
switch (this.getCode()) {
case NL_LIKE:
this.entity += `${chunk.slice(start, this.prevI)}\n`;
start = this.i;
break;
case SEMICOLON: {
const { entityReturnState } = this;
const entity = this.entity + chunk.slice(start, this.prevI);
this.state = entityReturnState!;
let parsed: string;
if (entity === "") {
this.fail("empty entity name.");
parsed = "&;";
}
else {
parsed = this.parseEntity(entity);
this.entity = "";
}
if (entityReturnState !== S_TEXT || this.textHandler !== undefined) {
this.text += parsed;
}
// eslint-disable-next-line no-labels
break loop;
}
case EOC:
this.entity += chunk.slice(start);
// eslint-disable-next-line no-labels
break loop;
default:
}
}
}
private sOpenWaka(): void {
// Reminder: a state handler is called with at least one character
// available in the current chunk. So the first call to get code inside of
// a state handler cannot return ``EOC``. That's why we don't test
// for it.
const c = this.getCode();
// either a /, ?, !, or text is coming next.
if (isNameStartChar(c)) {
this.state = S_OPEN_TAG;
this.unget();
this.xmlDeclPossible = false;
}
else {
switch (c) {
case FORWARD_SLASH:
this.state = S_CLOSE_TAG;
this.xmlDeclPossible = false;
break;
case BANG:
this.state = S_OPEN_WAKA_BANG;
this.openWakaBang = "";
this.xmlDeclPossible = false;
break;
case QUESTION:
this.state = S_PI_FIRST_CHAR;
break;
default:
this.fail("disallowed character in tag name");
this.state = S_TEXT;
this.xmlDeclPossible = false;
}
}
}
private sOpenWakaBang(): void {
this.openWakaBang += String.fromCodePoint(this.getCodeNorm());
switch (this.openWakaBang) {
case "[CDATA[":
if (!this.sawRoot && !this.reportedTextBeforeRoot) {
this.fail("text data outside of root node.");
this.reportedTextBeforeRoot = true;
}
if (this.closedRoot && !this.reportedTextAfterRoot) {
this.fail("text data outside of root node.");
this.reportedTextAfterRoot = true;
}
this.state = S_CDATA;
this.openWakaBang = "";
break;
case "--":
this.state = S_COMMENT;
this.openWakaBang = "";
break;
case "DOCTYPE":
this.state = S_DOCTYPE;
if (this.doctype || this.sawRoot) {
this.fail("inappropriately located doctype declaration.");
}
this.openWakaBang = "";
break;
default:
// 7 happens to be the maximum length of the string that can possibly
// match one of the cases above.
if (this.openWakaBang.length >= 7) {
this.fail("incorrect syntax.");
}
}
}
private sComment(): void {
if (this.captureToChar(MINUS)) {
this.state = S_COMMENT_ENDING;
}
}
private sCommentEnding(): void {
const c = this.getCodeNorm();
if (c === MINUS) {
this.state = S_COMMENT_ENDED;
this.commentHandler?.(this.text);
this.text = "";
}
else {
this.text += `-${String.fromCodePoint(c)}`;
this.state = S_COMMENT;
}
}
private sCommentEnded(): void {
const c = this.getCodeNorm();
if (c !== GREATER) {
this.fail("malformed comment.");
// <!-- blah -- bloo --> will be recorded as
// a comment of " blah -- bloo "
this.text += `--${String.fromCodePoint(c)}`;
this.state = S_COMMENT;
}
else {
this.state = S_TEXT;
}
}
private sCData(): void {
if (this.captureToChar(CLOSE_BRACKET)) {
this.state = S_CDATA_ENDING;
}
}
private sCDataEnding(): void {
const c = this.getCodeNorm();
if (c === CLOSE_BRACKET) {
this.state = S_CDATA_ENDING_2;
}
else {
this.text += `]${String.fromCodePoint(c)}`;
this.state = S_CDATA;
}
}
private sCDataEnding2(): void {
const c = this.getCodeNorm();
switch (c) {
case GREATER: {
this.cdataHandler?.(this.text);
this.text = "";
this.state = S_TEXT;
break;
}
case CLOSE_BRACKET:
this.text += "]";
break;
default:
this.text += `]]${String.fromCodePoint(c)}`;
this.state = S_CDATA;
}
}
// We need this separate state to check the first character fo the pi target
// with this.nameStartCheck which allows less characters than this.nameCheck.
private sPIFirstChar(): void {
const c = this.getCodeNorm();
// This is first because in the case where the file is well-formed this is
// the branch taken. We optimize for well-formedness.
if (this.nameStartCheck(c)) {
this.piTarget += String.fromCodePoint(c);
this.state = S_PI_REST;
}
else if (c === QUESTION || isS(c)) {
this.fail("processing instruction without a target.");
this.state = c === QUESTION ? S_PI_ENDING : S_PI_BODY;
}
else {
this.fail("disallowed character in processing instruction name.");
this.piTarget += String.fromCodePoint(c);
this.state = S_PI_REST;
}
}
private sPIRest(): void {
// Capture characters into a piTarget while ``this.nameCheck`` run on the
// character read returns true.
const { chunk, i: start } = this;
// eslint-disable-next-line no-constant-condition
while (true) {
const c = this.getCodeNorm();
if (c === EOC) {
this.piTarget += chunk.slice(start);
return;
}
// NL cannot satisfy this.nameCheck so we don't have to test specifically
// for it.
if (!this.nameCheck(c)) {
this.piTarget += chunk.slice(start, this.prevI);
const isQuestion = c === QUESTION;
if (isQuestion || isS(c)) {
if (this.piTarget === "xml") {
if (!this.xmlDeclPossible) {
this.fail(
"an XML declaration must be at the start of the document.");
}
this.state = isQuestion ? S_XML_DECL_ENDING : S_XML_DECL_NAME_START;
}
else {
this.state = isQuestion ? S_PI_ENDING : S_PI_BODY;
}
}
else {
this.fail("disallowed character in processing instruction name.");
this.piTarget += String.fromCodePoint(c);
}
break;
}
}
}
private sPIBody(): void {
if (this.text.length === 0) {
const c = this.getCodeNorm();
if (c === QUESTION) {
this.state = S_PI_ENDING;
}
else if (!isS(c)) {
this.text = String.fromCodePoint(c);
}
}
// The question mark character is not valid inside any of the XML
// declaration name/value pairs.
else if (this.captureToChar(QUESTION)) {
this.state = S_PI_ENDING;
}
}
private sPIEnding(): void {
const c = this.getCodeNorm();
if (c === GREATER) {
const { piTarget } = this;
if (piTarget.toLowerCase() === "xml") {
this.fail(
"the XML declaration must appear at the start of the document.");
}
this.piHandler?.({
target: piTarget,
body: this.text,
});
this.piTarget = this.text = "";
this.state = S_TEXT;
}
else if (c === QUESTION) {
// We ran into ?? as part of a processing instruction. We initially took
// the first ? as a sign that the PI was ending, but it is not. So we have
// to add it to the body but we take the new ? as a sign that the PI is
// ending.
this.text += "?";
}
else {
this.text += `?${String.fromCodePoint(c)}`;
this.state = S_PI_BODY;
}
this.xmlDeclPossible = false;
}
private sXMLDeclNameStart(): void {
const c = this.skipSpaces();
// The question mark character is not valid inside any of the XML
// declaration name/value pairs.
if (c === QUESTION) {
// It is valid to go to S_XML_DECL_ENDING from this state.
this.state = S_XML_DECL_ENDING;
return;
}
if (c !== EOC) {
this.state = S_XML_DECL_NAME;
this.name = String.fromCodePoint(c);
}
}
private sXMLDeclName(): void {
const c = this.captureTo(XML_DECL_NAME_TERMINATOR);
// The question mark character is not valid inside any of the XML
// declaration name/value pairs.
if (c === QUESTION) {
this.state = S_XML_DECL_ENDING;
this.name += this.text;
this.text = "";
this.fail("XML declaration is incomplete.");
return;
}
if (!(isS(c) || c === EQUAL)) {
return;
}
this.name += this.text;
this.text = "";
if (!this.xmlDeclExpects.includes(this.name)) {
switch (this.name.length) {
case 0:
this.fail("did not expect any more name/value pairs.");
break;
case 1:
this.fail(`expected the name ${this.xmlDeclExpects[0]}.`);
break;
default:
this.fail(`expected one of ${this.xmlDeclExpects.join(", ")}`);
}
}
this.state = c === EQUAL ? S_XML_DECL_VALUE_START : S_XML_DECL_EQ;
}
private sXMLDeclEq(): void {
const c = this.getCodeNorm();
// The question mark character is not valid inside any of the XML
// declaration name/value pairs.
if (c === QUESTION) {
this.state = S_XML_DECL_ENDING;
this.fail("XML declaration is incomplete.");
return;
}
if (isS(c)) {
return;
}
if (c !== EQUAL) {
this.fail("value required.");
}
this.state = S_XML_DECL_VALUE_START;
}
private sXMLDeclValueStart(): void {
const c = this.getCodeNorm();
// The question mark character is not valid inside any of the XML
// declaration name/value pairs.
if (c === QUESTION) {
this.state = S_XML_DECL_ENDING;
this.fail("XML declaration is incomplete.");
return;
}
if (isS(c)) {
return;
}
if (!isQuote(c)) {
this.fail("value must be quoted.");
this.q = SPACE;
}
else {
this.q = c;
}
this.state = S_XML_DECL_VALUE;
}
private sXMLDeclValue(): void {
const c = this.captureTo([this.q!, QUESTION]);
// The question mark character is not valid inside any of the XML
// declaration name/value pairs.
if (c === QUESTION) {
this.state = S_XML_DECL_ENDING;
this.text = "";
this.fail("XML declaration is incomplete.");
return;
}
if (c === EOC) {
return;
}
const value = this.text;
this.text = "";
switch (this.name) {
case "version": {
this.xmlDeclExpects = ["encoding", "standalone"];
const version = value;
this.xmlDecl.version = version;
// This is the test specified by XML 1.0 but it is fine for XML 1.1.
if (!/^1\.[0-9]+$/.test(version)) {
this.fail("version number must match /^1\\.[0-9]+$/.");
}
// When forceXMLVersion is set, the XML declaration is ignored.
else if (!(this.opt.forceXMLVersion as boolean)) {
this.setXMLVersion(version);
}
break;
}
case "encoding":
if (!/^[A-Za-z][A-Za-z0-9._-]*$/.test(value)) {
this.fail("encoding value must match \
/^[A-Za-z0-9][A-Za-z0-9._-]*$/.");
}
this.xmlDeclExpects = ["standalone"];
this.xmlDecl.encoding = value;
break;
case "standalone":
if (value !== "yes" && value !== "no") {
this.fail("standalone value must match \"yes\" or \"no\".");
}
this.xmlDeclExpects = [];
this.xmlDecl.standalone = value;
break;
default:
// We don't need to raise an error here since we've already raised one
// when checking what name was expected.
}
this.name = "";
this.state = S_XML_DECL_SEPARATOR;
}
private sXMLDeclSeparator(): void {
const c = this.getCodeNorm();
// The question mark character is not valid inside any of the XML
// declaration name/value pairs.
if (c === QUESTION) {
// It is valid to go to S_XML_DECL_ENDING from this state.
this.state = S_XML_DECL_ENDING;
return;
}
if (!isS(c)) {
this.fail("whitespace required.");
this.unget();
}
this.state = S_XML_DECL_NAME_START;
}
private sXMLDeclEnding(): void {
const c = this.getCodeNorm();
if (c === GREATER) {
if (this.piTarget !== "xml") {
this.fail("processing instructions are not allowed before root.");
}
else if (this.name !== "version" &&
this.xmlDeclExpects.includes("version")) {
this.fail("XML declaration must contain a version.");
}
this.xmldeclHandler?.(this.xmlDecl);
this.name = "";
this.piTarget = this.text = "";
this.state = S_TEXT;
}
else {
// We got here because the previous character was a ?, but the question
// mark character is not valid inside any of the XML declaration
// name/value pairs.
this.fail(
"The character ? is disallowed anywhere in XML declarations.");
}
this.xmlDeclPossible = false;
}
private sOpenTag(): void {
const c = this.captureNameChars();
if (c === EOC) {
return;
}
const tag: SaxesTagIncomplete = this.tag = {
name: this.name,
attributes: Object.create(null) as Record<string, string>,
};
this.name = "";
if (this.xmlnsOpt) {
this.topNS = tag.ns = Object.create(null) as Record<string, string>;
}
this.openTagStartHandler?.(tag as StartTagForOptions<O>);
this.sawRoot = true;
if (!this.fragmentOpt && this.closedRoot) {
this.fail("documents may contain only one root.");
}
switch (c) {
case GREATER:
this.openTag();
break;
case FORWARD_SLASH:
this.state = S_OPEN_TAG_SLASH;
break;
default:
if (!isS(c)) {
this.fail("disallowed character in tag name.");
}
this.state = S_ATTRIB;
}
}
private sOpenTagSlash(): void {
if (this.getCode() === GREATER) {
this.openSelfClosingTag();
}
else {
this.fail("forward-slash in opening tag not followed by >.");
this.state = S_ATTRIB;
}
}
private sAttrib(): void {
const c = this.skipSpaces();
if (c === EOC) {
return;
}
if (isNameStartChar(c)) {
this.unget();
this.state = S_ATTRIB_NAME;
}
else if (c === GREATER) {
this.openTag();
}
else if (c === FORWARD_SLASH) {
this.state = S_OPEN_TAG_SLASH;
}
else {
this.fail("disallowed character in attribute name.");
}
}
private sAttribName(): void {
const c = this.captureNameChars();
if (c === EQUAL) {
this.state = S_ATTRIB_VALUE;
}
else if (isS(c)) {
this.state = S_ATTRIB_NAME_SAW_WHITE;
}
else if (c === GREATER) {
this.fail("attribute without value.");
this.pushAttrib(this.name, this.name);
this.name = this.text = "";
this.openTag();
}
else if (c !== EOC) {
this.fail("disallowed character in attribute name.");
}
}
private sAttribNameSawWhite(): void {
const c = this.skipSpaces();
switch (c) {
case EOC:
return;
case EQUAL:
this.state = S_ATTRIB_VALUE;
break;
default:
this.fail("attribute without value.");
// Should we do this???
// this.tag.attributes[this.name] = "";
this.text = "";
this.name = "";
if (c === GREATER) {
this.openTag();
}
else if (isNameStartChar(c)) {
this.unget();
this.state = S_ATTRIB_NAME;
}
else {
this.fail("disallowed character in attribute name.");
this.state = S_ATTRIB;
}
}
}
private sAttribValue(): void {
const c = this.getCodeNorm();
if (isQuote(c)) {
this.q = c;
this.state = S_ATTRIB_VALUE_QUOTED;
}
else if (!isS(c)) {
this.fail("unquoted attribute value.");
this.state = S_ATTRIB_VALUE_UNQUOTED;
this.unget();
}
}
private sAttribValueQuoted(): void {
// We deliberately do not use captureTo here. The specialized code we use
// here is faster than using captureTo.
const { q, chunk } = this;
let { i: start } = this;
// eslint-disable-next-line no-constant-condition
while (true) {
switch (this.getCode()) {
case q:
this.pushAttrib(this.name,
this.text + chunk.slice(start, this.prevI));
this.name = this.text = "";
this.q = null;
this.state = S_ATTRIB_VALUE_CLOSED;
return;
case AMP:
this.text += chunk.slice(start, this.prevI);
this.state = S_ENTITY;
this.entityReturnState = S_ATTRIB_VALUE_QUOTED;
return;
case NL:
case NL_LIKE:
case TAB:
this.text += `${chunk.slice(start, this.prevI)} `;
start = this.i;
break;
case LESS:
this.text += chunk.slice(start, this.prevI);
this.fail("disallowed character.");
return;
case EOC:
this.text += chunk.slice(start);
return;
default:
}
}
}
private sAttribValueClosed(): void {
const c = this.getCodeNorm();
if (isS(c)) {
this.state = S_ATTRIB;
}
else if (c === GREATER) {
this.openTag();
}
else if (c === FORWARD_SLASH) {
this.state = S_OPEN_TAG_SLASH;
}
else if (isNameStartChar(c)) {
this.fail("no whitespace between attributes.");
this.unget();
this.state = S_ATTRIB_NAME;
}
else {
this.fail("disallowed character in attribute name.");
}
}
private sAttribValueUnquoted(): void {
// We don't do anything regarding EOL or space handling for unquoted
// attributes. We already have failed by the time we get here, and the
// contract that saxes upholds states that upon failure, it is not safe to
// rely on the data passed to event handlers (other than
// ``onerror``). Passing "bad" data is not a problem.
const c = this.captureTo(ATTRIB_VALUE_UNQUOTED_TERMINATOR);
switch (c) {
case AMP:
this.state = S_ENTITY;
this.entityReturnState = S_ATTRIB_VALUE_UNQUOTED;
break;
case LESS:
this.fail("disallowed character.");
break;
case EOC:
break;
default:
if (this.text.includes("]]>")) {
this.fail("the string \"]]>\" is disallowed in char data.");
}
this.pushAttrib(this.name, this.text);
this.name = this.text = "";
if (c === GREATER) {
this.openTag();
}
else {
this.state = S_ATTRIB;
}
}
}
private sCloseTag(): void {
const c = this.captureNameChars();
if (c === GREATER) {
this.closeTag();
}
else if (isS(c)) {
this.state = S_CLOSE_TAG_SAW_WHITE;
}
else if (c !== EOC) {
this.fail("disallowed character in closing tag.");
}
}
private sCloseTagSawWhite(): void {
switch (this.skipSpaces()) {
case GREATER:
this.closeTag();
break;
case EOC:
break;
default:
this.fail("disallowed character in closing tag.");
}
}
// END OF STATE ENGINE METHODS
private handleTextInRoot(): void {
// This is essentially a specialized version of captureTo which is optimized
// for performing the ]]> check. A previous version of this code, checked
// ``this.text`` for the presence of ]]>. It simplified the code but was
// very costly when character data contained a lot of entities to be parsed.
//
// Since we are using a specialized loop, we also keep track of the presence
// of ]]> in text data. The sequence ]]> is forbidden to appear as-is.
//
let { i: start, forbiddenState } = this;
const { chunk, textHandler: handler } = this;
// eslint-disable-next-line no-labels, no-restricted-syntax
scanLoop:
// eslint-disable-next-line no-constant-condition
while (true) {
switch (this.getCode()) {
case LESS: {
this.state = S_OPEN_WAKA;
if (handler !== undefined) {
const { text } = this;
const slice = chunk.slice(start, this.prevI);
if (text.length !== 0) {
handler(text + slice);
this.text = "";
}
else if (slice.length !== 0) {
handler(slice);
}
}
forbiddenState = FORBIDDEN_START;
// eslint-disable-next-line no-labels
break scanLoop;
}
case AMP:
this.state = S_ENTITY;
this.entityReturnState = S_TEXT;
if (handler !== undefined) {
this.text += chunk.slice(start, this.prevI);
}
forbiddenState = FORBIDDEN_START;
// eslint-disable-next-line no-labels
break scanLoop;
case CLOSE_BRACKET:
switch (forbiddenState) {
case FORBIDDEN_START:
forbiddenState = FORBIDDEN_BRACKET;
break;
case FORBIDDEN_BRACKET:
forbiddenState = FORBIDDEN_BRACKET_BRACKET;
break;
case FORBIDDEN_BRACKET_BRACKET:
break;
default:
throw new Error("impossible state");
}
break;
case GREATER:
if (forbiddenState === FORBIDDEN_BRACKET_BRACKET) {
this.fail("the string \"]]>\" is disallowed in char data.");
}
forbiddenState = FORBIDDEN_START;
break;
case NL_LIKE:
if (handler !== undefined) {
this.text += `${chunk.slice(start, this.prevI)}\n`;
}
start = this.i;
forbiddenState = FORBIDDEN_START;
break;
case EOC:
if (handler !== undefined) {
this.text += chunk.slice(start);
}
// eslint-disable-next-line no-labels
break scanLoop;
default:
forbiddenState = FORBIDDEN_START;
}
}
this.forbiddenState = forbiddenState;
}
private handleTextOutsideRoot(): void {
// This is essentially a specialized version of captureTo which is optimized
// for a specialized task. We keep track of the presence of non-space
// characters in the text since these are errors when appearing outside the
// document root element.
let { i: start } = this;
const { chunk, textHandler: handler } = this;
let nonSpace = false;
// eslint-disable-next-line no-labels, no-restricted-syntax
outRootLoop:
// eslint-disable-next-line no-constant-condition
while (true) {
const code = this.getCode();
switch (code) {
case LESS: {
this.state = S_OPEN_WAKA;
if (handler !== undefined) {
const { text } = this;
const slice = chunk.slice(start, this.prevI);
if (text.length !== 0) {
handler(text + slice);
this.text = "";
}
else if (slice.length !== 0) {
handler(slice);
}
}
// eslint-disable-next-line no-labels
break outRootLoop;
}
case AMP:
this.state = S_ENTITY;
this.entityReturnState = S_TEXT;
if (handler !== undefined) {
this.text += chunk.slice(start, this.prevI);
}
nonSpace = true;
// eslint-disable-next-line no-labels
break outRootLoop;
case NL_LIKE:
if (handler !== undefined) {
this.text += `${chunk.slice(start, this.prevI)}\n`;
}
start = this.i;
break;
case EOC:
if (handler !== undefined) {
this.text += chunk.slice(start);
}
// eslint-disable-next-line no-labels
break outRootLoop;
default:
if (!isS(code)) {
nonSpace = true;
}
}
}
if (!nonSpace) {
return;
}
// We use the reportedTextBeforeRoot and reportedTextAfterRoot flags
// to avoid reporting errors for every single character that is out of
// place.
if (!this.sawRoot && !this.reportedTextBeforeRoot) {
this.fail("text data outside of root node.");
this.reportedTextBeforeRoot = true;
}
if (this.closedRoot && !this.reportedTextAfterRoot) {
this.fail("text data outside of root node.");
this.reportedTextAfterRoot = true;
}
}
private pushAttribNS(name: string, value: string): void {
const { prefix, local } = this.qname(name);
const attr = { name, prefix, local, value };
this.attribList.push(attr);
this.attributeHandler?.(attr as AttributeEventForOptions<O>);
if (prefix === "xmlns") {
const trimmed = value.trim();
if (this.currentXMLVersion === "1.0" && trimmed === "") {
this.fail("invalid attempt to undefine prefix in XML 1.0");
}
this.topNS![local] = trimmed;
nsPairCheck(this, local, trimmed);
}
else if (name === "xmlns") {
const trimmed = value.trim();
this.topNS![""] = trimmed;
nsPairCheck(this, "", trimmed);
}
}
private pushAttribPlain(name: string, value: string): void {
const attr = { name, value };
this.attribList.push(attr);
this.attributeHandler?.(attr as AttributeEventForOptions<O>);
}
/**
* End parsing. This performs final well-formedness checks and resets the
* parser to a clean state.
*
* @returns this
*/
private end(): this {
if (!this.sawRoot) {
this.fail("document must contain a root element.");
}
const { tags } = this;
while (tags.length > 0) {
const tag = tags.pop()!;
this.fail(`unclosed tag: ${tag.name}`);
}
if ((this.state !== S_BEGIN) && (this.state !== S_TEXT)) {
this.fail("unexpected end.");
}
const { text } = this;
if (text.length !== 0) {
this.textHandler?.(text);
this.text = "";
}
this._closed = true;
this.endHandler?.();
this._init();
return this;
}
/**
* Resolve a namespace prefix.
*
* @param prefix The prefix to resolve.
*
* @returns The namespace URI or ``undefined`` if the prefix is not defined.
*/
resolve(prefix: string): string | undefined {
let uri = this.topNS![prefix];
if (uri !== undefined) {
return uri;
}
const { tags } = this;
for (let index = tags.length - 1; index >= 0; index--) {
uri = tags[index]!.ns![prefix];
if (uri !== undefined) {
return uri;
}
}
uri = this.ns[prefix];
if (uri !== undefined) {
return uri;
}
return this.opt.resolvePrefix?.(prefix);
}
/**
* Parse a qname into its prefix and local name parts.
*
* @param name The name to parse
*
* @returns
*/
private qname(name: string): { prefix: string; local: string } {
// This is faster than using name.split(":").
const colon = name.indexOf(":");
if (colon === -1) {
return { prefix: "", local: name };
}
const local = name.slice(colon + 1);
const prefix = name.slice(0, colon);
if (prefix === "" || local === "" || local.includes(":")) {
this.fail(`malformed name: ${name}.`);
}
return { prefix, local };
}
private processAttribsNS(): void {
const { attribList } = this;
const tag = this.tag!;
{
// add namespace info to tag
const { prefix, local } = this.qname(tag.name);
tag.prefix = prefix;
tag.local = local;
const uri = tag.uri = this.resolve(prefix) ?? "";
if (prefix !== "") {
if (prefix === "xmlns") {
this.fail("tags may not have \"xmlns\" as prefix.");
}
if (uri === "") {
this.fail(`unbound namespace prefix: ${JSON.stringify(prefix)}.`);
tag.uri = prefix;
}
}
}
if (attribList.length === 0) {
return;
}
const { attributes } = tag;
const seen = new Set();
// Note: do not apply default ns to attributes:
// http://www.w3.org/TR/REC-xml-names/#defaulting
for (const attr of attribList as SaxesAttributeNSIncomplete[]) {
const { name, prefix, local } = attr;
let uri;
let eqname;
if (prefix === "") {
uri = name === "xmlns" ? XMLNS_NAMESPACE : "";
eqname = name;
}
else {
uri = this.resolve(prefix);
// if there's any attributes with an undefined namespace,
// then fail on them now.
if (uri === undefined) {
this.fail(`unbound namespace prefix: ${JSON.stringify(prefix)}.`);
uri = prefix;
}
eqname = `{${uri}}${local}`;
}
if (seen.has(eqname)) {
this.fail(`duplicate attribute: ${eqname}.`);
}
seen.add(eqname);
attr.uri = uri;
attributes[name] = attr;
}
this.attribList = [];
}
private processAttribsPlain(): void {
const { attribList } = this;
// eslint-disable-next-line prefer-destructuring
const attributes = this.tag!.attributes;
for (const { name, value } of attribList) {
if (attributes[name] !== undefined) {
this.fail(`duplicate attribute: ${name}.`);
}
attributes[name] = value;
}
this.attribList = [];
}
/**
* Handle a complete open tag. This parser code calls this once it has seen
* the whole tag. This method checks for well-formeness and then emits
* ``onopentag``.
*/
private openTag(): void {
this.processAttribs();
const { tags } = this;
const tag = this.tag as SaxesTag;
tag.isSelfClosing = false;
// There cannot be any pending text here due to the onopentagstart that was
// necessarily emitted before we get here. So we do not check text.
this.openTagHandler?.(tag as TagForOptions<O>);
tags.push(tag);
this.state = S_TEXT;
this.name = "";
}
/**
* Handle a complete self-closing tag. This parser code calls this once it has
* seen the whole tag. This method checks for well-formeness and then emits
* ``onopentag`` and ``onclosetag``.
*/
private openSelfClosingTag(): void {
this.processAttribs();
const { tags } = this;
const tag = this.tag as SaxesTag;
tag.isSelfClosing = true;
// There cannot be any pending text here due to the onopentagstart that was
// necessarily emitted before we get here. So we do not check text.
this.openTagHandler?.(tag as TagForOptions<O>);
this.closeTagHandler?.(tag as TagForOptions<O>);
const top = this.tag = tags[tags.length - 1] ?? null;
if (top === null) {
this.closedRoot = true;
}
this.state = S_TEXT;
this.name = "";
}
/**
* Handle a complete close tag. This parser code calls this once it has seen
* the whole tag. This method checks for well-formeness and then emits
* ``onclosetag``.
*/
private closeTag(): void {
const { tags, name } = this;
// Our state after this will be S_TEXT, no matter what, and we can clear
// tagName now.
this.state = S_TEXT;
this.name = "";
if (name === "") {
this.fail("weird empty close tag.");
this.text += "</>";
return;
}
const handler = this.closeTagHandler;
let l = tags.length;
while (l-- > 0) {
const tag = this.tag = tags.pop() as SaxesTag;
this.topNS = tag.ns!;
handler?.(tag as TagForOptions<O>);
if (tag.name === name) {
break;
}
this.fail("unexpected close tag.");
}
if (l === 0) {
this.closedRoot = true;
}
else if (l < 0) {
this.fail(`unmatched closing tag: ${name}.`);
this.text += `</${name}>`;
}
}
/**
* Resolves an entity. Makes any necessary well-formedness checks.
*
* @param entity The entity to resolve.
*
* @returns The parsed entity.
*/
private parseEntity(entity: string): string {
// startsWith would be significantly slower for this test.
if (entity[0] !== "#") {
const defined = this.ENTITIES[entity];
if (defined !== undefined) {
return defined;
}
this.fail(this.isName(entity) ? "undefined entity." :
"disallowed character in entity name.");
return `&${entity};`;
}
let num = NaN;
if (entity[1] === "x" && /^#x[0-9a-f]+$/i.test(entity)) {
num = parseInt(entity.slice(2), 16);
}
else if (/^#[0-9]+$/.test(entity)) {
num = parseInt(entity.slice(1), 10);
}
// The character reference is required to match the CHAR production.
if (!this.isChar(num)) {
this.fail("malformed character entity.");
return `&${entity};`;
}
return String.fromCodePoint(num);
}
} |
1,148 | fn(parser: SaxesParser): void {
for (const x of ls) {
parser.write(x);
}
parser.close();
} | class SaxesParser<O extends SaxesOptions = {}> {
private readonly fragmentOpt: boolean;
private readonly xmlnsOpt: boolean;
private readonly trackPosition: boolean;
private readonly fileName?: string;
private readonly nameStartCheck: (c: number) => boolean;
private readonly nameCheck: (c: number) => boolean;
private readonly isName: (name: string) => boolean;
private readonly ns!: Record<string, string>;
private openWakaBang!: string;
private text!: string;
private name!: string;
private piTarget!: string;
private entity!: string;
private q!: null | number;
private tags!: SaxesTagIncomplete[];
private tag!: SaxesTagIncomplete | null;
private topNS!: Record<string, string> | null;
private chunk!: string;
private chunkPosition!: number;
private i!: number;
//
// We use prevI to allow "ungetting" the previously read code point. Note
// however, that it is not safe to unget everything and anything. In
// particular ungetting EOL characters will screw positioning up.
//
// Practically, you must not unget a code which has any side effect beyond
// updating ``this.i`` and ``this.prevI``. Only EOL codes have such side
// effects.
//
private prevI!: number;
private carriedFromPrevious?: string;
private forbiddenState!: number;
private attribList!: (SaxesAttributeNSIncomplete | SaxesAttributePlain)[];
private state!: number;
private reportedTextBeforeRoot!: boolean;
private reportedTextAfterRoot!: boolean;
private closedRoot!: boolean;
private sawRoot!: boolean;
private xmlDeclPossible!: boolean;
private xmlDeclExpects!: string[];
private entityReturnState?: number;
private processAttribs!: (this: this) => void;
private positionAtNewLine!: number;
private doctype!: boolean;
private getCode!: () => number;
private isChar!: (c: number) => boolean;
private pushAttrib!: (name: string, value: string) => void;
private _closed!: boolean;
private currentXMLVersion!: string;
private readonly stateTable: ((this: SaxesParser<O>) => void)[];
private xmldeclHandler?: XMLDeclHandler;
private textHandler?: TextHandler;
private piHandler?: PIHandler;
private doctypeHandler?: DoctypeHandler;
private commentHandler?: CommentHandler;
private openTagStartHandler?: OpenTagStartHandler<O>;
private openTagHandler?: OpenTagHandler<O>;
private closeTagHandler?: CloseTagHandler<O>;
private cdataHandler?: CDataHandler;
private errorHandler?: ErrorHandler;
private endHandler?: EndHandler;
private readyHandler?: ReadyHandler;
private attributeHandler?: AttributeHandler<O>;
/**
* Indicates whether or not the parser is closed. If ``true``, wait for
* the ``ready`` event to write again.
*/
get closed(): boolean {
return this._closed;
}
readonly opt: SaxesOptions;
/**
* The XML declaration for this document.
*/
xmlDecl!: XMLDecl;
/**
* The line number of the next character to be read by the parser. This field
* is one-based. (The first line is numbered 1.)
*/
line!: number;
/**
* The column number of the next character to be read by the parser. *
* This field is zero-based. (The first column is 0.)
*
* This field counts columns by *Unicode character*. Note that this *can*
* be different from the index of the character in a JavaScript string due
* to how JavaScript handles astral plane characters.
*
* See [[columnIndex]] for a number that corresponds to the JavaScript index.
*/
column!: number;
/**
* A map of entity name to expansion.
*/
ENTITIES!: Record<string, string>;
/**
* @param opt The parser options.
*/
constructor(opt?: O) {
this.opt = opt ?? {};
this.fragmentOpt = !!(this.opt.fragment as boolean);
const xmlnsOpt = this.xmlnsOpt = !!(this.opt.xmlns as boolean);
this.trackPosition = this.opt.position !== false;
this.fileName = this.opt.fileName;
if (xmlnsOpt) {
// This is the function we use to perform name checks on PIs and entities.
// When namespaces are used, colons are not allowed in PI target names or
// entity names. So the check depends on whether namespaces are used. See:
//
// https://www.w3.org/XML/xml-names-19990114-errata.html
// NE08
//
this.nameStartCheck = isNCNameStartChar;
this.nameCheck = isNCNameChar;
this.isName = isNCName;
// eslint-disable-next-line @typescript-eslint/unbound-method
this.processAttribs = this.processAttribsNS;
// eslint-disable-next-line @typescript-eslint/unbound-method
this.pushAttrib = this.pushAttribNS;
// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-assignment
this.ns = { __proto__: null as any, ...rootNS };
const additional = this.opt.additionalNamespaces;
if (additional != null) {
nsMappingCheck(this, additional);
Object.assign(this.ns, additional);
}
}
else {
this.nameStartCheck = isNameStartChar;
this.nameCheck = isNameChar;
this.isName = isName;
// eslint-disable-next-line @typescript-eslint/unbound-method
this.processAttribs = this.processAttribsPlain;
// eslint-disable-next-line @typescript-eslint/unbound-method
this.pushAttrib = this.pushAttribPlain;
}
//
// The order of the members in this table needs to correspond to the state
// numbers given to the states that correspond to the methods being recorded
// here.
//
this.stateTable = [
/* eslint-disable @typescript-eslint/unbound-method */
this.sBegin,
this.sBeginWhitespace,
this.sDoctype,
this.sDoctypeQuote,
this.sDTD,
this.sDTDQuoted,
this.sDTDOpenWaka,
this.sDTDOpenWakaBang,
this.sDTDComment,
this.sDTDCommentEnding,
this.sDTDCommentEnded,
this.sDTDPI,
this.sDTDPIEnding,
this.sText,
this.sEntity,
this.sOpenWaka,
this.sOpenWakaBang,
this.sComment,
this.sCommentEnding,
this.sCommentEnded,
this.sCData,
this.sCDataEnding,
this.sCDataEnding2,
this.sPIFirstChar,
this.sPIRest,
this.sPIBody,
this.sPIEnding,
this.sXMLDeclNameStart,
this.sXMLDeclName,
this.sXMLDeclEq,
this.sXMLDeclValueStart,
this.sXMLDeclValue,
this.sXMLDeclSeparator,
this.sXMLDeclEnding,
this.sOpenTag,
this.sOpenTagSlash,
this.sAttrib,
this.sAttribName,
this.sAttribNameSawWhite,
this.sAttribValue,
this.sAttribValueQuoted,
this.sAttribValueClosed,
this.sAttribValueUnquoted,
this.sCloseTag,
this.sCloseTagSawWhite,
/* eslint-enable @typescript-eslint/unbound-method */
];
this._init();
}
_init(): void {
this.openWakaBang = "";
this.text = "";
this.name = "";
this.piTarget = "";
this.entity = "";
this.q = null;
this.tags = [];
this.tag = null;
this.topNS = null;
this.chunk = "";
this.chunkPosition = 0;
this.i = 0;
this.prevI = 0;
this.carriedFromPrevious = undefined;
this.forbiddenState = FORBIDDEN_START;
this.attribList = [];
// The logic is organized so as to minimize the need to check
// this.opt.fragment while parsing.
const { fragmentOpt } = this;
this.state = fragmentOpt ? S_TEXT : S_BEGIN;
// We want these to be all true if we are dealing with a fragment.
this.reportedTextBeforeRoot = this.reportedTextAfterRoot = this.closedRoot =
this.sawRoot = fragmentOpt;
// An XML declaration is intially possible only when parsing whole
// documents.
this.xmlDeclPossible = !fragmentOpt;
this.xmlDeclExpects = ["version"];
this.entityReturnState = undefined;
let { defaultXMLVersion } = this.opt;
if (defaultXMLVersion === undefined) {
if (this.opt.forceXMLVersion === true) {
throw new Error("forceXMLVersion set but defaultXMLVersion is not set");
}
defaultXMLVersion = "1.0";
}
this.setXMLVersion(defaultXMLVersion);
this.positionAtNewLine = 0;
this.doctype = false;
this._closed = false;
this.xmlDecl = {
version: undefined,
encoding: undefined,
standalone: undefined,
};
this.line = 1;
this.column = 0;
this.ENTITIES = Object.create(XML_ENTITIES) as Record<string, string>;
this.readyHandler?.();
}
/**
* The stream position the parser is currently looking at. This field is
* zero-based.
*
* This field is not based on counting Unicode characters but is to be
* interpreted as a plain index into a JavaScript string.
*/
get position(): number {
return this.chunkPosition + this.i;
}
/**
* The column number of the next character to be read by the parser. *
* This field is zero-based. (The first column in a line is 0.)
*
* This field reports the index at which the next character would be in the
* line if the line were represented as a JavaScript string. Note that this
* *can* be different to a count based on the number of *Unicode characters*
* due to how JavaScript handles astral plane characters.
*
* See [[column]] for a number that corresponds to a count of Unicode
* characters.
*/
get columnIndex(): number {
return this.position - this.positionAtNewLine;
}
/**
* Set an event listener on an event. The parser supports one handler per
* event type. If you try to set an event handler over an existing handler,
* the old handler is silently overwritten.
*
* @param name The event to listen to.
*
* @param handler The handler to set.
*/
on<N extends EventName>(name: N, handler: EventNameToHandler<O, N>): void {
// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-member-access
(this as any)[EVENT_NAME_TO_HANDLER_NAME[name]] = handler;
}
/**
* Unset an event handler.
*
* @parma name The event to stop listening to.
*/
off(name: EventName): void {
// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-member-access
(this as any)[EVENT_NAME_TO_HANDLER_NAME[name]] = undefined;
}
/**
* Make an error object. The error object will have a message that contains
* the ``fileName`` option passed at the creation of the parser. If position
* tracking was turned on, it will also have line and column number
* information.
*
* @param message The message describing the error to report.
*
* @returns An error object with a properly formatted message.
*/
makeError(message: string): Error {
let msg = this.fileName ?? "";
if (this.trackPosition) {
if (msg.length > 0) {
msg += ":";
}
msg += `${this.line}:${this.column}`;
}
if (msg.length > 0) {
msg += ": ";
}
return new Error(msg + message);
}
/**
* Report a parsing error. This method is made public so that client code may
* check for issues that are outside the scope of this project and can report
* errors.
*
* @param message The error to report.
*
* @returns this
*/
fail(message: string): this {
const err = this.makeError(message);
const handler = this.errorHandler;
if (handler === undefined) {
throw err;
}
else {
handler(err);
}
return this;
}
/**
* Write a XML data to the parser.
*
* @param chunk The XML data to write.
*
* @returns this
*/
// We do need object for the type here. Yes, it often causes problems
// but not in this case.
write(chunk: string | object | null): this {
if (this.closed) {
return this.fail("cannot write after close; assign an onready handler.");
}
let end = false;
if (chunk === null) {
// We cannot return immediately because carriedFromPrevious may need
// processing.
end = true;
chunk = "";
}
else if (typeof chunk === "object") {
chunk = chunk.toString();
}
// We checked if performing a pre-decomposition of the string into an array
// of single complete characters (``Array.from(chunk)``) would be faster
// than the current repeated calls to ``charCodeAt``. As of August 2018, it
// isn't. (There may be Node-specific code that would perform faster than
// ``Array.from`` but don't want to be dependent on Node.)
if (this.carriedFromPrevious !== undefined) {
// The previous chunk had char we must carry over.
chunk = `${this.carriedFromPrevious}${chunk}`;
this.carriedFromPrevious = undefined;
}
let limit = chunk.length;
const lastCode = chunk.charCodeAt(limit - 1);
if (!end &&
// A trailing CR or surrogate must be carried over to the next
// chunk.
(lastCode === CR || (lastCode >= 0xD800 && lastCode <= 0xDBFF))) {
// The chunk ends with a character that must be carried over. We cannot
// know how to handle it until we get the next chunk or the end of the
// stream. So save it for later.
this.carriedFromPrevious = chunk[limit - 1];
limit--;
chunk = chunk.slice(0, limit);
}
const { stateTable } = this;
this.chunk = chunk;
this.i = 0;
while (this.i < limit) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-argument
stateTable[this.state].call(this as any);
}
this.chunkPosition += limit;
return end ? this.end() : this;
}
/**
* Close the current stream. Perform final well-formedness checks and reset
* the parser tstate.
*
* @returns this
*/
close(): this {
return this.write(null);
}
/**
* Get a single code point out of the current chunk. This updates the current
* position if we do position tracking.
*
* This is the algorithm to use for XML 1.0.
*
* @returns The character read.
*/
private getCode10(): number {
const { chunk, i } = this;
this.prevI = i;
// Yes, we do this instead of doing this.i++. Doing it this way, we do not
// read this.i again, which is a bit faster.
this.i = i + 1;
if (i >= chunk.length) {
return EOC;
}
// Using charCodeAt and handling the surrogates ourselves is faster
// than using codePointAt.
const code = chunk.charCodeAt(i);
this.column++;
if (code < 0xD800) {
if (code >= SPACE || code === TAB) {
return code;
}
switch (code) {
case NL:
this.line++;
this.column = 0;
this.positionAtNewLine = this.position;
return NL;
case CR:
// We may get NaN if we read past the end of the chunk, which is fine.
if (chunk.charCodeAt(i + 1) === NL) {
// A \r\n sequence is converted to \n so we have to skip over the
// next character. We already know it has a size of 1 so ++ is fine
// here.
this.i = i + 2;
}
// Otherwise, a \r is just converted to \n, so we don't have to skip
// ahead.
// In either case, \r becomes \n.
this.line++;
this.column = 0;
this.positionAtNewLine = this.position;
return NL_LIKE;
default:
// If we get here, then code < SPACE and it is not NL CR or TAB.
this.fail("disallowed character.");
return code;
}
}
if (code > 0xDBFF) {
// This is a specialized version of isChar10 that takes into account
// that in this context code > 0xDBFF and code <= 0xFFFF. So it does not
// test cases that don't need testing.
if (!(code >= 0xE000 && code <= 0xFFFD)) {
this.fail("disallowed character.");
}
return code;
}
const final = 0x10000 + ((code - 0xD800) * 0x400) +
(chunk.charCodeAt(i + 1) - 0xDC00);
this.i = i + 2;
// This is a specialized version of isChar10 that takes into account that in
// this context necessarily final >= 0x10000.
if (final > 0x10FFFF) {
this.fail("disallowed character.");
}
return final;
}
/**
* Get a single code point out of the current chunk. This updates the current
* position if we do position tracking.
*
* This is the algorithm to use for XML 1.1.
*
* @returns {number} The character read.
*/
private getCode11(): number {
const { chunk, i } = this;
this.prevI = i;
// Yes, we do this instead of doing this.i++. Doing it this way, we do not
// read this.i again, which is a bit faster.
this.i = i + 1;
if (i >= chunk.length) {
return EOC;
}
// Using charCodeAt and handling the surrogates ourselves is faster
// than using codePointAt.
const code = chunk.charCodeAt(i);
this.column++;
if (code < 0xD800) {
if ((code > 0x1F && code < 0x7F) || (code > 0x9F && code !== LS) ||
code === TAB) {
return code;
}
switch (code) {
case NL: // 0xA
this.line++;
this.column = 0;
this.positionAtNewLine = this.position;
return NL;
case CR: { // 0xD
// We may get NaN if we read past the end of the chunk, which is
// fine.
const next = chunk.charCodeAt(i + 1);
if (next === NL || next === NEL) {
// A CR NL or CR NEL sequence is converted to NL so we have to skip
// over the next character. We already know it has a size of 1.
this.i = i + 2;
}
// Otherwise, a CR is just converted to NL, no skip.
}
/* yes, fall through */
case NEL: // 0x85
case LS: // Ox2028
this.line++;
this.column = 0;
this.positionAtNewLine = this.position;
return NL_LIKE;
default:
this.fail("disallowed character.");
return code;
}
}
if (code > 0xDBFF) {
// This is a specialized version of isCharAndNotRestricted that takes into
// account that in this context code > 0xDBFF and code <= 0xFFFF. So it
// does not test cases that don't need testing.
if (!(code >= 0xE000 && code <= 0xFFFD)) {
this.fail("disallowed character.");
}
return code;
}
const final = 0x10000 + ((code - 0xD800) * 0x400) +
(chunk.charCodeAt(i + 1) - 0xDC00);
this.i = i + 2;
// This is a specialized version of isCharAndNotRestricted that takes into
// account that in this context necessarily final >= 0x10000.
if (final > 0x10FFFF) {
this.fail("disallowed character.");
}
return final;
}
/**
* Like ``getCode`` but with the return value normalized so that ``NL`` is
* returned for ``NL_LIKE``.
*/
private getCodeNorm(): number {
const c = this.getCode();
return c === NL_LIKE ? NL : c;
}
private unget(): void {
this.i = this.prevI;
this.column--;
}
/**
* Capture characters into a buffer until encountering one of a set of
* characters.
*
* @param chars An array of codepoints. Encountering a character in the array
* ends the capture. (``chars`` may safely contain ``NL``.)
*
* @return The character code that made the capture end, or ``EOC`` if we hit
* the end of the chunk. The return value cannot be NL_LIKE: NL is returned
* instead.
*/
private captureTo(chars: number[]): number {
let { i: start } = this;
const { chunk } = this;
// eslint-disable-next-line no-constant-condition
while (true) {
const c = this.getCode();
const isNLLike = c === NL_LIKE;
const final = isNLLike ? NL : c;
if (final === EOC || chars.includes(final)) {
this.text += chunk.slice(start, this.prevI);
return final;
}
if (isNLLike) {
this.text += `${chunk.slice(start, this.prevI)}\n`;
start = this.i;
}
}
}
/**
* Capture characters into a buffer until encountering a character.
*
* @param char The codepoint that ends the capture. **NOTE ``char`` MAY NOT
* CONTAIN ``NL``.** Passing ``NL`` will result in buggy behavior.
*
* @return ``true`` if we ran into the character. Otherwise, we ran into the
* end of the current chunk.
*/
private captureToChar(char: number): boolean {
let { i: start } = this;
const { chunk } = this;
// eslint-disable-next-line no-constant-condition
while (true) {
let c = this.getCode();
switch (c) {
case NL_LIKE:
this.text += `${chunk.slice(start, this.prevI)}\n`;
start = this.i;
c = NL;
break;
case EOC:
this.text += chunk.slice(start);
return false;
default:
}
if (c === char) {
this.text += chunk.slice(start, this.prevI);
return true;
}
}
}
/**
* Capture characters that satisfy ``isNameChar`` into the ``name`` field of
* this parser.
*
* @return The character code that made the test fail, or ``EOC`` if we hit
* the end of the chunk. The return value cannot be NL_LIKE: NL is returned
* instead.
*/
private captureNameChars(): number {
const { chunk, i: start } = this;
// eslint-disable-next-line no-constant-condition
while (true) {
const c = this.getCode();
if (c === EOC) {
this.name += chunk.slice(start);
return EOC;
}
// NL is not a name char so we don't have to test specifically for it.
if (!isNameChar(c)) {
this.name += chunk.slice(start, this.prevI);
return c === NL_LIKE ? NL : c;
}
}
}
/**
* Skip white spaces.
*
* @return The character that ended the skip, or ``EOC`` if we hit
* the end of the chunk. The return value cannot be NL_LIKE: NL is returned
* instead.
*/
private skipSpaces(): number {
// eslint-disable-next-line no-constant-condition
while (true) {
const c = this.getCodeNorm();
if (c === EOC || !isS(c)) {
return c;
}
}
}
private setXMLVersion(version: string): void {
this.currentXMLVersion = version;
/* eslint-disable @typescript-eslint/unbound-method */
if (version === "1.0") {
this.isChar = isChar10;
this.getCode = this.getCode10;
}
else {
this.isChar = isChar11;
this.getCode = this.getCode11;
}
/* eslint-enable @typescript-eslint/unbound-method */
}
// STATE ENGINE METHODS
// This needs to be a state separate from S_BEGIN_WHITESPACE because we want
// to be sure never to come back to this state later.
private sBegin(): void {
// We are essentially peeking at the first character of the chunk. Since
// S_BEGIN can be in effect only when we start working on the first chunk,
// the index at which we must look is necessarily 0. Note also that the
// following test does not depend on decoding surrogates.
// If the initial character is 0xFEFF, ignore it.
if (this.chunk.charCodeAt(0) === 0xFEFF) {
this.i++;
this.column++;
}
this.state = S_BEGIN_WHITESPACE;
}
private sBeginWhitespace(): void {
// We need to know whether we've encountered spaces or not because as soon
// as we run into a space, an XML declaration is no longer possible. Rather
// than slow down skipSpaces even in places where we don't care whether it
// skipped anything or not, we check whether prevI is equal to the value of
// i from before we skip spaces.
const iBefore = this.i;
const c = this.skipSpaces();
if (this.prevI !== iBefore) {
this.xmlDeclPossible = false;
}
switch (c) {
case LESS:
this.state = S_OPEN_WAKA;
// We could naively call closeText but in this state, it is not normal
// to have text be filled with any data.
if (this.text.length !== 0) {
throw new Error("no-empty text at start");
}
break;
case EOC:
break;
default:
this.unget();
this.state = S_TEXT;
this.xmlDeclPossible = false;
}
}
private sDoctype(): void {
const c = this.captureTo(DOCTYPE_TERMINATOR);
switch (c) {
case GREATER: {
this.doctypeHandler?.(this.text);
this.text = "";
this.state = S_TEXT;
this.doctype = true; // just remember that we saw it.
break;
}
case EOC:
break;
default:
this.text += String.fromCodePoint(c);
if (c === OPEN_BRACKET) {
this.state = S_DTD;
}
else if (isQuote(c)) {
this.state = S_DOCTYPE_QUOTE;
this.q = c;
}
}
}
private sDoctypeQuote(): void {
const q = this.q!;
if (this.captureToChar(q)) {
this.text += String.fromCodePoint(q);
this.q = null;
this.state = S_DOCTYPE;
}
}
private sDTD(): void {
const c = this.captureTo(DTD_TERMINATOR);
if (c === EOC) {
return;
}
this.text += String.fromCodePoint(c);
if (c === CLOSE_BRACKET) {
this.state = S_DOCTYPE;
}
else if (c === LESS) {
this.state = S_DTD_OPEN_WAKA;
}
else if (isQuote(c)) {
this.state = S_DTD_QUOTED;
this.q = c;
}
}
private sDTDQuoted(): void {
const q = this.q!;
if (this.captureToChar(q)) {
this.text += String.fromCodePoint(q);
this.state = S_DTD;
this.q = null;
}
}
private sDTDOpenWaka(): void {
const c = this.getCodeNorm();
this.text += String.fromCodePoint(c);
switch (c) {
case BANG:
this.state = S_DTD_OPEN_WAKA_BANG;
this.openWakaBang = "";
break;
case QUESTION:
this.state = S_DTD_PI;
break;
default:
this.state = S_DTD;
}
}
private sDTDOpenWakaBang(): void {
const char = String.fromCodePoint(this.getCodeNorm());
const owb = this.openWakaBang += char;
this.text += char;
if (owb !== "-") {
this.state = owb === "--" ? S_DTD_COMMENT : S_DTD;
this.openWakaBang = "";
}
}
private sDTDComment(): void {
if (this.captureToChar(MINUS)) {
this.text += "-";
this.state = S_DTD_COMMENT_ENDING;
}
}
private sDTDCommentEnding(): void {
const c = this.getCodeNorm();
this.text += String.fromCodePoint(c);
this.state = c === MINUS ? S_DTD_COMMENT_ENDED : S_DTD_COMMENT;
}
private sDTDCommentEnded(): void {
const c = this.getCodeNorm();
this.text += String.fromCodePoint(c);
if (c === GREATER) {
this.state = S_DTD;
}
else {
this.fail("malformed comment.");
// <!-- blah -- bloo --> will be recorded as
// a comment of " blah -- bloo "
this.state = S_DTD_COMMENT;
}
}
private sDTDPI(): void {
if (this.captureToChar(QUESTION)) {
this.text += "?";
this.state = S_DTD_PI_ENDING;
}
}
private sDTDPIEnding(): void {
const c = this.getCodeNorm();
this.text += String.fromCodePoint(c);
if (c === GREATER) {
this.state = S_DTD;
}
}
private sText(): void {
//
// We did try a version of saxes where the S_TEXT state was split in two
// states: one for text inside the root element, and one for text
// outside. This was avoiding having to test this.tags.length to decide
// what implementation to actually use.
//
// Peformance testing on gigabyte-size files did not show any advantage to
// using the two states solution instead of the current one. Conversely, it
// made the code a bit more complicated elsewhere. For instance, a comment
// can appear before the root element so when a comment ended it was
// necessary to determine whether to return to the S_TEXT state or to the
// new text-outside-root state.
//
if (this.tags.length !== 0) {
this.handleTextInRoot();
}
else {
this.handleTextOutsideRoot();
}
}
private sEntity(): void {
// This is essentially a specialized version of captureToChar(SEMICOLON...)
let { i: start } = this;
const { chunk } = this;
// eslint-disable-next-line no-labels, no-restricted-syntax
loop:
// eslint-disable-next-line no-constant-condition
while (true) {
switch (this.getCode()) {
case NL_LIKE:
this.entity += `${chunk.slice(start, this.prevI)}\n`;
start = this.i;
break;
case SEMICOLON: {
const { entityReturnState } = this;
const entity = this.entity + chunk.slice(start, this.prevI);
this.state = entityReturnState!;
let parsed: string;
if (entity === "") {
this.fail("empty entity name.");
parsed = "&;";
}
else {
parsed = this.parseEntity(entity);
this.entity = "";
}
if (entityReturnState !== S_TEXT || this.textHandler !== undefined) {
this.text += parsed;
}
// eslint-disable-next-line no-labels
break loop;
}
case EOC:
this.entity += chunk.slice(start);
// eslint-disable-next-line no-labels
break loop;
default:
}
}
}
private sOpenWaka(): void {
// Reminder: a state handler is called with at least one character
// available in the current chunk. So the first call to get code inside of
// a state handler cannot return ``EOC``. That's why we don't test
// for it.
const c = this.getCode();
// either a /, ?, !, or text is coming next.
if (isNameStartChar(c)) {
this.state = S_OPEN_TAG;
this.unget();
this.xmlDeclPossible = false;
}
else {
switch (c) {
case FORWARD_SLASH:
this.state = S_CLOSE_TAG;
this.xmlDeclPossible = false;
break;
case BANG:
this.state = S_OPEN_WAKA_BANG;
this.openWakaBang = "";
this.xmlDeclPossible = false;
break;
case QUESTION:
this.state = S_PI_FIRST_CHAR;
break;
default:
this.fail("disallowed character in tag name");
this.state = S_TEXT;
this.xmlDeclPossible = false;
}
}
}
private sOpenWakaBang(): void {
this.openWakaBang += String.fromCodePoint(this.getCodeNorm());
switch (this.openWakaBang) {
case "[CDATA[":
if (!this.sawRoot && !this.reportedTextBeforeRoot) {
this.fail("text data outside of root node.");
this.reportedTextBeforeRoot = true;
}
if (this.closedRoot && !this.reportedTextAfterRoot) {
this.fail("text data outside of root node.");
this.reportedTextAfterRoot = true;
}
this.state = S_CDATA;
this.openWakaBang = "";
break;
case "--":
this.state = S_COMMENT;
this.openWakaBang = "";
break;
case "DOCTYPE":
this.state = S_DOCTYPE;
if (this.doctype || this.sawRoot) {
this.fail("inappropriately located doctype declaration.");
}
this.openWakaBang = "";
break;
default:
// 7 happens to be the maximum length of the string that can possibly
// match one of the cases above.
if (this.openWakaBang.length >= 7) {
this.fail("incorrect syntax.");
}
}
}
private sComment(): void {
if (this.captureToChar(MINUS)) {
this.state = S_COMMENT_ENDING;
}
}
private sCommentEnding(): void {
const c = this.getCodeNorm();
if (c === MINUS) {
this.state = S_COMMENT_ENDED;
this.commentHandler?.(this.text);
this.text = "";
}
else {
this.text += `-${String.fromCodePoint(c)}`;
this.state = S_COMMENT;
}
}
private sCommentEnded(): void {
const c = this.getCodeNorm();
if (c !== GREATER) {
this.fail("malformed comment.");
// <!-- blah -- bloo --> will be recorded as
// a comment of " blah -- bloo "
this.text += `--${String.fromCodePoint(c)}`;
this.state = S_COMMENT;
}
else {
this.state = S_TEXT;
}
}
private sCData(): void {
if (this.captureToChar(CLOSE_BRACKET)) {
this.state = S_CDATA_ENDING;
}
}
private sCDataEnding(): void {
const c = this.getCodeNorm();
if (c === CLOSE_BRACKET) {
this.state = S_CDATA_ENDING_2;
}
else {
this.text += `]${String.fromCodePoint(c)}`;
this.state = S_CDATA;
}
}
private sCDataEnding2(): void {
const c = this.getCodeNorm();
switch (c) {
case GREATER: {
this.cdataHandler?.(this.text);
this.text = "";
this.state = S_TEXT;
break;
}
case CLOSE_BRACKET:
this.text += "]";
break;
default:
this.text += `]]${String.fromCodePoint(c)}`;
this.state = S_CDATA;
}
}
// We need this separate state to check the first character fo the pi target
// with this.nameStartCheck which allows less characters than this.nameCheck.
private sPIFirstChar(): void {
const c = this.getCodeNorm();
// This is first because in the case where the file is well-formed this is
// the branch taken. We optimize for well-formedness.
if (this.nameStartCheck(c)) {
this.piTarget += String.fromCodePoint(c);
this.state = S_PI_REST;
}
else if (c === QUESTION || isS(c)) {
this.fail("processing instruction without a target.");
this.state = c === QUESTION ? S_PI_ENDING : S_PI_BODY;
}
else {
this.fail("disallowed character in processing instruction name.");
this.piTarget += String.fromCodePoint(c);
this.state = S_PI_REST;
}
}
private sPIRest(): void {
// Capture characters into a piTarget while ``this.nameCheck`` run on the
// character read returns true.
const { chunk, i: start } = this;
// eslint-disable-next-line no-constant-condition
while (true) {
const c = this.getCodeNorm();
if (c === EOC) {
this.piTarget += chunk.slice(start);
return;
}
// NL cannot satisfy this.nameCheck so we don't have to test specifically
// for it.
if (!this.nameCheck(c)) {
this.piTarget += chunk.slice(start, this.prevI);
const isQuestion = c === QUESTION;
if (isQuestion || isS(c)) {
if (this.piTarget === "xml") {
if (!this.xmlDeclPossible) {
this.fail(
"an XML declaration must be at the start of the document.");
}
this.state = isQuestion ? S_XML_DECL_ENDING : S_XML_DECL_NAME_START;
}
else {
this.state = isQuestion ? S_PI_ENDING : S_PI_BODY;
}
}
else {
this.fail("disallowed character in processing instruction name.");
this.piTarget += String.fromCodePoint(c);
}
break;
}
}
}
private sPIBody(): void {
if (this.text.length === 0) {
const c = this.getCodeNorm();
if (c === QUESTION) {
this.state = S_PI_ENDING;
}
else if (!isS(c)) {
this.text = String.fromCodePoint(c);
}
}
// The question mark character is not valid inside any of the XML
// declaration name/value pairs.
else if (this.captureToChar(QUESTION)) {
this.state = S_PI_ENDING;
}
}
private sPIEnding(): void {
const c = this.getCodeNorm();
if (c === GREATER) {
const { piTarget } = this;
if (piTarget.toLowerCase() === "xml") {
this.fail(
"the XML declaration must appear at the start of the document.");
}
this.piHandler?.({
target: piTarget,
body: this.text,
});
this.piTarget = this.text = "";
this.state = S_TEXT;
}
else if (c === QUESTION) {
// We ran into ?? as part of a processing instruction. We initially took
// the first ? as a sign that the PI was ending, but it is not. So we have
// to add it to the body but we take the new ? as a sign that the PI is
// ending.
this.text += "?";
}
else {
this.text += `?${String.fromCodePoint(c)}`;
this.state = S_PI_BODY;
}
this.xmlDeclPossible = false;
}
private sXMLDeclNameStart(): void {
const c = this.skipSpaces();
// The question mark character is not valid inside any of the XML
// declaration name/value pairs.
if (c === QUESTION) {
// It is valid to go to S_XML_DECL_ENDING from this state.
this.state = S_XML_DECL_ENDING;
return;
}
if (c !== EOC) {
this.state = S_XML_DECL_NAME;
this.name = String.fromCodePoint(c);
}
}
private sXMLDeclName(): void {
const c = this.captureTo(XML_DECL_NAME_TERMINATOR);
// The question mark character is not valid inside any of the XML
// declaration name/value pairs.
if (c === QUESTION) {
this.state = S_XML_DECL_ENDING;
this.name += this.text;
this.text = "";
this.fail("XML declaration is incomplete.");
return;
}
if (!(isS(c) || c === EQUAL)) {
return;
}
this.name += this.text;
this.text = "";
if (!this.xmlDeclExpects.includes(this.name)) {
switch (this.name.length) {
case 0:
this.fail("did not expect any more name/value pairs.");
break;
case 1:
this.fail(`expected the name ${this.xmlDeclExpects[0]}.`);
break;
default:
this.fail(`expected one of ${this.xmlDeclExpects.join(", ")}`);
}
}
this.state = c === EQUAL ? S_XML_DECL_VALUE_START : S_XML_DECL_EQ;
}
private sXMLDeclEq(): void {
const c = this.getCodeNorm();
// The question mark character is not valid inside any of the XML
// declaration name/value pairs.
if (c === QUESTION) {
this.state = S_XML_DECL_ENDING;
this.fail("XML declaration is incomplete.");
return;
}
if (isS(c)) {
return;
}
if (c !== EQUAL) {
this.fail("value required.");
}
this.state = S_XML_DECL_VALUE_START;
}
private sXMLDeclValueStart(): void {
const c = this.getCodeNorm();
// The question mark character is not valid inside any of the XML
// declaration name/value pairs.
if (c === QUESTION) {
this.state = S_XML_DECL_ENDING;
this.fail("XML declaration is incomplete.");
return;
}
if (isS(c)) {
return;
}
if (!isQuote(c)) {
this.fail("value must be quoted.");
this.q = SPACE;
}
else {
this.q = c;
}
this.state = S_XML_DECL_VALUE;
}
private sXMLDeclValue(): void {
const c = this.captureTo([this.q!, QUESTION]);
// The question mark character is not valid inside any of the XML
// declaration name/value pairs.
if (c === QUESTION) {
this.state = S_XML_DECL_ENDING;
this.text = "";
this.fail("XML declaration is incomplete.");
return;
}
if (c === EOC) {
return;
}
const value = this.text;
this.text = "";
switch (this.name) {
case "version": {
this.xmlDeclExpects = ["encoding", "standalone"];
const version = value;
this.xmlDecl.version = version;
// This is the test specified by XML 1.0 but it is fine for XML 1.1.
if (!/^1\.[0-9]+$/.test(version)) {
this.fail("version number must match /^1\\.[0-9]+$/.");
}
// When forceXMLVersion is set, the XML declaration is ignored.
else if (!(this.opt.forceXMLVersion as boolean)) {
this.setXMLVersion(version);
}
break;
}
case "encoding":
if (!/^[A-Za-z][A-Za-z0-9._-]*$/.test(value)) {
this.fail("encoding value must match \
/^[A-Za-z0-9][A-Za-z0-9._-]*$/.");
}
this.xmlDeclExpects = ["standalone"];
this.xmlDecl.encoding = value;
break;
case "standalone":
if (value !== "yes" && value !== "no") {
this.fail("standalone value must match \"yes\" or \"no\".");
}
this.xmlDeclExpects = [];
this.xmlDecl.standalone = value;
break;
default:
// We don't need to raise an error here since we've already raised one
// when checking what name was expected.
}
this.name = "";
this.state = S_XML_DECL_SEPARATOR;
}
private sXMLDeclSeparator(): void {
const c = this.getCodeNorm();
// The question mark character is not valid inside any of the XML
// declaration name/value pairs.
if (c === QUESTION) {
// It is valid to go to S_XML_DECL_ENDING from this state.
this.state = S_XML_DECL_ENDING;
return;
}
if (!isS(c)) {
this.fail("whitespace required.");
this.unget();
}
this.state = S_XML_DECL_NAME_START;
}
private sXMLDeclEnding(): void {
const c = this.getCodeNorm();
if (c === GREATER) {
if (this.piTarget !== "xml") {
this.fail("processing instructions are not allowed before root.");
}
else if (this.name !== "version" &&
this.xmlDeclExpects.includes("version")) {
this.fail("XML declaration must contain a version.");
}
this.xmldeclHandler?.(this.xmlDecl);
this.name = "";
this.piTarget = this.text = "";
this.state = S_TEXT;
}
else {
// We got here because the previous character was a ?, but the question
// mark character is not valid inside any of the XML declaration
// name/value pairs.
this.fail(
"The character ? is disallowed anywhere in XML declarations.");
}
this.xmlDeclPossible = false;
}
private sOpenTag(): void {
const c = this.captureNameChars();
if (c === EOC) {
return;
}
const tag: SaxesTagIncomplete = this.tag = {
name: this.name,
attributes: Object.create(null) as Record<string, string>,
};
this.name = "";
if (this.xmlnsOpt) {
this.topNS = tag.ns = Object.create(null) as Record<string, string>;
}
this.openTagStartHandler?.(tag as StartTagForOptions<O>);
this.sawRoot = true;
if (!this.fragmentOpt && this.closedRoot) {
this.fail("documents may contain only one root.");
}
switch (c) {
case GREATER:
this.openTag();
break;
case FORWARD_SLASH:
this.state = S_OPEN_TAG_SLASH;
break;
default:
if (!isS(c)) {
this.fail("disallowed character in tag name.");
}
this.state = S_ATTRIB;
}
}
private sOpenTagSlash(): void {
if (this.getCode() === GREATER) {
this.openSelfClosingTag();
}
else {
this.fail("forward-slash in opening tag not followed by >.");
this.state = S_ATTRIB;
}
}
private sAttrib(): void {
const c = this.skipSpaces();
if (c === EOC) {
return;
}
if (isNameStartChar(c)) {
this.unget();
this.state = S_ATTRIB_NAME;
}
else if (c === GREATER) {
this.openTag();
}
else if (c === FORWARD_SLASH) {
this.state = S_OPEN_TAG_SLASH;
}
else {
this.fail("disallowed character in attribute name.");
}
}
private sAttribName(): void {
const c = this.captureNameChars();
if (c === EQUAL) {
this.state = S_ATTRIB_VALUE;
}
else if (isS(c)) {
this.state = S_ATTRIB_NAME_SAW_WHITE;
}
else if (c === GREATER) {
this.fail("attribute without value.");
this.pushAttrib(this.name, this.name);
this.name = this.text = "";
this.openTag();
}
else if (c !== EOC) {
this.fail("disallowed character in attribute name.");
}
}
private sAttribNameSawWhite(): void {
const c = this.skipSpaces();
switch (c) {
case EOC:
return;
case EQUAL:
this.state = S_ATTRIB_VALUE;
break;
default:
this.fail("attribute without value.");
// Should we do this???
// this.tag.attributes[this.name] = "";
this.text = "";
this.name = "";
if (c === GREATER) {
this.openTag();
}
else if (isNameStartChar(c)) {
this.unget();
this.state = S_ATTRIB_NAME;
}
else {
this.fail("disallowed character in attribute name.");
this.state = S_ATTRIB;
}
}
}
private sAttribValue(): void {
const c = this.getCodeNorm();
if (isQuote(c)) {
this.q = c;
this.state = S_ATTRIB_VALUE_QUOTED;
}
else if (!isS(c)) {
this.fail("unquoted attribute value.");
this.state = S_ATTRIB_VALUE_UNQUOTED;
this.unget();
}
}
private sAttribValueQuoted(): void {
// We deliberately do not use captureTo here. The specialized code we use
// here is faster than using captureTo.
const { q, chunk } = this;
let { i: start } = this;
// eslint-disable-next-line no-constant-condition
while (true) {
switch (this.getCode()) {
case q:
this.pushAttrib(this.name,
this.text + chunk.slice(start, this.prevI));
this.name = this.text = "";
this.q = null;
this.state = S_ATTRIB_VALUE_CLOSED;
return;
case AMP:
this.text += chunk.slice(start, this.prevI);
this.state = S_ENTITY;
this.entityReturnState = S_ATTRIB_VALUE_QUOTED;
return;
case NL:
case NL_LIKE:
case TAB:
this.text += `${chunk.slice(start, this.prevI)} `;
start = this.i;
break;
case LESS:
this.text += chunk.slice(start, this.prevI);
this.fail("disallowed character.");
return;
case EOC:
this.text += chunk.slice(start);
return;
default:
}
}
}
private sAttribValueClosed(): void {
const c = this.getCodeNorm();
if (isS(c)) {
this.state = S_ATTRIB;
}
else if (c === GREATER) {
this.openTag();
}
else if (c === FORWARD_SLASH) {
this.state = S_OPEN_TAG_SLASH;
}
else if (isNameStartChar(c)) {
this.fail("no whitespace between attributes.");
this.unget();
this.state = S_ATTRIB_NAME;
}
else {
this.fail("disallowed character in attribute name.");
}
}
private sAttribValueUnquoted(): void {
// We don't do anything regarding EOL or space handling for unquoted
// attributes. We already have failed by the time we get here, and the
// contract that saxes upholds states that upon failure, it is not safe to
// rely on the data passed to event handlers (other than
// ``onerror``). Passing "bad" data is not a problem.
const c = this.captureTo(ATTRIB_VALUE_UNQUOTED_TERMINATOR);
switch (c) {
case AMP:
this.state = S_ENTITY;
this.entityReturnState = S_ATTRIB_VALUE_UNQUOTED;
break;
case LESS:
this.fail("disallowed character.");
break;
case EOC:
break;
default:
if (this.text.includes("]]>")) {
this.fail("the string \"]]>\" is disallowed in char data.");
}
this.pushAttrib(this.name, this.text);
this.name = this.text = "";
if (c === GREATER) {
this.openTag();
}
else {
this.state = S_ATTRIB;
}
}
}
private sCloseTag(): void {
const c = this.captureNameChars();
if (c === GREATER) {
this.closeTag();
}
else if (isS(c)) {
this.state = S_CLOSE_TAG_SAW_WHITE;
}
else if (c !== EOC) {
this.fail("disallowed character in closing tag.");
}
}
private sCloseTagSawWhite(): void {
switch (this.skipSpaces()) {
case GREATER:
this.closeTag();
break;
case EOC:
break;
default:
this.fail("disallowed character in closing tag.");
}
}
// END OF STATE ENGINE METHODS
private handleTextInRoot(): void {
// This is essentially a specialized version of captureTo which is optimized
// for performing the ]]> check. A previous version of this code, checked
// ``this.text`` for the presence of ]]>. It simplified the code but was
// very costly when character data contained a lot of entities to be parsed.
//
// Since we are using a specialized loop, we also keep track of the presence
// of ]]> in text data. The sequence ]]> is forbidden to appear as-is.
//
let { i: start, forbiddenState } = this;
const { chunk, textHandler: handler } = this;
// eslint-disable-next-line no-labels, no-restricted-syntax
scanLoop:
// eslint-disable-next-line no-constant-condition
while (true) {
switch (this.getCode()) {
case LESS: {
this.state = S_OPEN_WAKA;
if (handler !== undefined) {
const { text } = this;
const slice = chunk.slice(start, this.prevI);
if (text.length !== 0) {
handler(text + slice);
this.text = "";
}
else if (slice.length !== 0) {
handler(slice);
}
}
forbiddenState = FORBIDDEN_START;
// eslint-disable-next-line no-labels
break scanLoop;
}
case AMP:
this.state = S_ENTITY;
this.entityReturnState = S_TEXT;
if (handler !== undefined) {
this.text += chunk.slice(start, this.prevI);
}
forbiddenState = FORBIDDEN_START;
// eslint-disable-next-line no-labels
break scanLoop;
case CLOSE_BRACKET:
switch (forbiddenState) {
case FORBIDDEN_START:
forbiddenState = FORBIDDEN_BRACKET;
break;
case FORBIDDEN_BRACKET:
forbiddenState = FORBIDDEN_BRACKET_BRACKET;
break;
case FORBIDDEN_BRACKET_BRACKET:
break;
default:
throw new Error("impossible state");
}
break;
case GREATER:
if (forbiddenState === FORBIDDEN_BRACKET_BRACKET) {
this.fail("the string \"]]>\" is disallowed in char data.");
}
forbiddenState = FORBIDDEN_START;
break;
case NL_LIKE:
if (handler !== undefined) {
this.text += `${chunk.slice(start, this.prevI)}\n`;
}
start = this.i;
forbiddenState = FORBIDDEN_START;
break;
case EOC:
if (handler !== undefined) {
this.text += chunk.slice(start);
}
// eslint-disable-next-line no-labels
break scanLoop;
default:
forbiddenState = FORBIDDEN_START;
}
}
this.forbiddenState = forbiddenState;
}
private handleTextOutsideRoot(): void {
// This is essentially a specialized version of captureTo which is optimized
// for a specialized task. We keep track of the presence of non-space
// characters in the text since these are errors when appearing outside the
// document root element.
let { i: start } = this;
const { chunk, textHandler: handler } = this;
let nonSpace = false;
// eslint-disable-next-line no-labels, no-restricted-syntax
outRootLoop:
// eslint-disable-next-line no-constant-condition
while (true) {
const code = this.getCode();
switch (code) {
case LESS: {
this.state = S_OPEN_WAKA;
if (handler !== undefined) {
const { text } = this;
const slice = chunk.slice(start, this.prevI);
if (text.length !== 0) {
handler(text + slice);
this.text = "";
}
else if (slice.length !== 0) {
handler(slice);
}
}
// eslint-disable-next-line no-labels
break outRootLoop;
}
case AMP:
this.state = S_ENTITY;
this.entityReturnState = S_TEXT;
if (handler !== undefined) {
this.text += chunk.slice(start, this.prevI);
}
nonSpace = true;
// eslint-disable-next-line no-labels
break outRootLoop;
case NL_LIKE:
if (handler !== undefined) {
this.text += `${chunk.slice(start, this.prevI)}\n`;
}
start = this.i;
break;
case EOC:
if (handler !== undefined) {
this.text += chunk.slice(start);
}
// eslint-disable-next-line no-labels
break outRootLoop;
default:
if (!isS(code)) {
nonSpace = true;
}
}
}
if (!nonSpace) {
return;
}
// We use the reportedTextBeforeRoot and reportedTextAfterRoot flags
// to avoid reporting errors for every single character that is out of
// place.
if (!this.sawRoot && !this.reportedTextBeforeRoot) {
this.fail("text data outside of root node.");
this.reportedTextBeforeRoot = true;
}
if (this.closedRoot && !this.reportedTextAfterRoot) {
this.fail("text data outside of root node.");
this.reportedTextAfterRoot = true;
}
}
private pushAttribNS(name: string, value: string): void {
const { prefix, local } = this.qname(name);
const attr = { name, prefix, local, value };
this.attribList.push(attr);
this.attributeHandler?.(attr as AttributeEventForOptions<O>);
if (prefix === "xmlns") {
const trimmed = value.trim();
if (this.currentXMLVersion === "1.0" && trimmed === "") {
this.fail("invalid attempt to undefine prefix in XML 1.0");
}
this.topNS![local] = trimmed;
nsPairCheck(this, local, trimmed);
}
else if (name === "xmlns") {
const trimmed = value.trim();
this.topNS![""] = trimmed;
nsPairCheck(this, "", trimmed);
}
}
private pushAttribPlain(name: string, value: string): void {
const attr = { name, value };
this.attribList.push(attr);
this.attributeHandler?.(attr as AttributeEventForOptions<O>);
}
/**
* End parsing. This performs final well-formedness checks and resets the
* parser to a clean state.
*
* @returns this
*/
private end(): this {
if (!this.sawRoot) {
this.fail("document must contain a root element.");
}
const { tags } = this;
while (tags.length > 0) {
const tag = tags.pop()!;
this.fail(`unclosed tag: ${tag.name}`);
}
if ((this.state !== S_BEGIN) && (this.state !== S_TEXT)) {
this.fail("unexpected end.");
}
const { text } = this;
if (text.length !== 0) {
this.textHandler?.(text);
this.text = "";
}
this._closed = true;
this.endHandler?.();
this._init();
return this;
}
/**
* Resolve a namespace prefix.
*
* @param prefix The prefix to resolve.
*
* @returns The namespace URI or ``undefined`` if the prefix is not defined.
*/
resolve(prefix: string): string | undefined {
let uri = this.topNS![prefix];
if (uri !== undefined) {
return uri;
}
const { tags } = this;
for (let index = tags.length - 1; index >= 0; index--) {
uri = tags[index]!.ns![prefix];
if (uri !== undefined) {
return uri;
}
}
uri = this.ns[prefix];
if (uri !== undefined) {
return uri;
}
return this.opt.resolvePrefix?.(prefix);
}
/**
* Parse a qname into its prefix and local name parts.
*
* @param name The name to parse
*
* @returns
*/
private qname(name: string): { prefix: string; local: string } {
// This is faster than using name.split(":").
const colon = name.indexOf(":");
if (colon === -1) {
return { prefix: "", local: name };
}
const local = name.slice(colon + 1);
const prefix = name.slice(0, colon);
if (prefix === "" || local === "" || local.includes(":")) {
this.fail(`malformed name: ${name}.`);
}
return { prefix, local };
}
private processAttribsNS(): void {
const { attribList } = this;
const tag = this.tag!;
{
// add namespace info to tag
const { prefix, local } = this.qname(tag.name);
tag.prefix = prefix;
tag.local = local;
const uri = tag.uri = this.resolve(prefix) ?? "";
if (prefix !== "") {
if (prefix === "xmlns") {
this.fail("tags may not have \"xmlns\" as prefix.");
}
if (uri === "") {
this.fail(`unbound namespace prefix: ${JSON.stringify(prefix)}.`);
tag.uri = prefix;
}
}
}
if (attribList.length === 0) {
return;
}
const { attributes } = tag;
const seen = new Set();
// Note: do not apply default ns to attributes:
// http://www.w3.org/TR/REC-xml-names/#defaulting
for (const attr of attribList as SaxesAttributeNSIncomplete[]) {
const { name, prefix, local } = attr;
let uri;
let eqname;
if (prefix === "") {
uri = name === "xmlns" ? XMLNS_NAMESPACE : "";
eqname = name;
}
else {
uri = this.resolve(prefix);
// if there's any attributes with an undefined namespace,
// then fail on them now.
if (uri === undefined) {
this.fail(`unbound namespace prefix: ${JSON.stringify(prefix)}.`);
uri = prefix;
}
eqname = `{${uri}}${local}`;
}
if (seen.has(eqname)) {
this.fail(`duplicate attribute: ${eqname}.`);
}
seen.add(eqname);
attr.uri = uri;
attributes[name] = attr;
}
this.attribList = [];
}
private processAttribsPlain(): void {
const { attribList } = this;
// eslint-disable-next-line prefer-destructuring
const attributes = this.tag!.attributes;
for (const { name, value } of attribList) {
if (attributes[name] !== undefined) {
this.fail(`duplicate attribute: ${name}.`);
}
attributes[name] = value;
}
this.attribList = [];
}
/**
* Handle a complete open tag. This parser code calls this once it has seen
* the whole tag. This method checks for well-formeness and then emits
* ``onopentag``.
*/
private openTag(): void {
this.processAttribs();
const { tags } = this;
const tag = this.tag as SaxesTag;
tag.isSelfClosing = false;
// There cannot be any pending text here due to the onopentagstart that was
// necessarily emitted before we get here. So we do not check text.
this.openTagHandler?.(tag as TagForOptions<O>);
tags.push(tag);
this.state = S_TEXT;
this.name = "";
}
/**
* Handle a complete self-closing tag. This parser code calls this once it has
* seen the whole tag. This method checks for well-formeness and then emits
* ``onopentag`` and ``onclosetag``.
*/
private openSelfClosingTag(): void {
this.processAttribs();
const { tags } = this;
const tag = this.tag as SaxesTag;
tag.isSelfClosing = true;
// There cannot be any pending text here due to the onopentagstart that was
// necessarily emitted before we get here. So we do not check text.
this.openTagHandler?.(tag as TagForOptions<O>);
this.closeTagHandler?.(tag as TagForOptions<O>);
const top = this.tag = tags[tags.length - 1] ?? null;
if (top === null) {
this.closedRoot = true;
}
this.state = S_TEXT;
this.name = "";
}
/**
* Handle a complete close tag. This parser code calls this once it has seen
* the whole tag. This method checks for well-formeness and then emits
* ``onclosetag``.
*/
private closeTag(): void {
const { tags, name } = this;
// Our state after this will be S_TEXT, no matter what, and we can clear
// tagName now.
this.state = S_TEXT;
this.name = "";
if (name === "") {
this.fail("weird empty close tag.");
this.text += "</>";
return;
}
const handler = this.closeTagHandler;
let l = tags.length;
while (l-- > 0) {
const tag = this.tag = tags.pop() as SaxesTag;
this.topNS = tag.ns!;
handler?.(tag as TagForOptions<O>);
if (tag.name === name) {
break;
}
this.fail("unexpected close tag.");
}
if (l === 0) {
this.closedRoot = true;
}
else if (l < 0) {
this.fail(`unmatched closing tag: ${name}.`);
this.text += `</${name}>`;
}
}
/**
* Resolves an entity. Makes any necessary well-formedness checks.
*
* @param entity The entity to resolve.
*
* @returns The parsed entity.
*/
private parseEntity(entity: string): string {
// startsWith would be significantly slower for this test.
if (entity[0] !== "#") {
const defined = this.ENTITIES[entity];
if (defined !== undefined) {
return defined;
}
this.fail(this.isName(entity) ? "undefined entity." :
"disallowed character in entity name.");
return `&${entity};`;
}
let num = NaN;
if (entity[1] === "x" && /^#x[0-9a-f]+$/i.test(entity)) {
num = parseInt(entity.slice(2), 16);
}
else if (/^#[0-9]+$/.test(entity)) {
num = parseInt(entity.slice(1), 10);
}
// The character reference is required to match the CHAR production.
if (!this.isChar(num)) {
this.fail("malformed character entity.");
return `&${entity};`;
}
return String.fromCodePoint(num);
}
} |
1,149 | fn(parser: SaxesParser): void {
for (const x of xml) {
parser.write(x);
}
parser.close();
} | class SaxesParser<O extends SaxesOptions = {}> {
private readonly fragmentOpt: boolean;
private readonly xmlnsOpt: boolean;
private readonly trackPosition: boolean;
private readonly fileName?: string;
private readonly nameStartCheck: (c: number) => boolean;
private readonly nameCheck: (c: number) => boolean;
private readonly isName: (name: string) => boolean;
private readonly ns!: Record<string, string>;
private openWakaBang!: string;
private text!: string;
private name!: string;
private piTarget!: string;
private entity!: string;
private q!: null | number;
private tags!: SaxesTagIncomplete[];
private tag!: SaxesTagIncomplete | null;
private topNS!: Record<string, string> | null;
private chunk!: string;
private chunkPosition!: number;
private i!: number;
//
// We use prevI to allow "ungetting" the previously read code point. Note
// however, that it is not safe to unget everything and anything. In
// particular ungetting EOL characters will screw positioning up.
//
// Practically, you must not unget a code which has any side effect beyond
// updating ``this.i`` and ``this.prevI``. Only EOL codes have such side
// effects.
//
private prevI!: number;
private carriedFromPrevious?: string;
private forbiddenState!: number;
private attribList!: (SaxesAttributeNSIncomplete | SaxesAttributePlain)[];
private state!: number;
private reportedTextBeforeRoot!: boolean;
private reportedTextAfterRoot!: boolean;
private closedRoot!: boolean;
private sawRoot!: boolean;
private xmlDeclPossible!: boolean;
private xmlDeclExpects!: string[];
private entityReturnState?: number;
private processAttribs!: (this: this) => void;
private positionAtNewLine!: number;
private doctype!: boolean;
private getCode!: () => number;
private isChar!: (c: number) => boolean;
private pushAttrib!: (name: string, value: string) => void;
private _closed!: boolean;
private currentXMLVersion!: string;
private readonly stateTable: ((this: SaxesParser<O>) => void)[];
private xmldeclHandler?: XMLDeclHandler;
private textHandler?: TextHandler;
private piHandler?: PIHandler;
private doctypeHandler?: DoctypeHandler;
private commentHandler?: CommentHandler;
private openTagStartHandler?: OpenTagStartHandler<O>;
private openTagHandler?: OpenTagHandler<O>;
private closeTagHandler?: CloseTagHandler<O>;
private cdataHandler?: CDataHandler;
private errorHandler?: ErrorHandler;
private endHandler?: EndHandler;
private readyHandler?: ReadyHandler;
private attributeHandler?: AttributeHandler<O>;
/**
* Indicates whether or not the parser is closed. If ``true``, wait for
* the ``ready`` event to write again.
*/
get closed(): boolean {
return this._closed;
}
readonly opt: SaxesOptions;
/**
* The XML declaration for this document.
*/
xmlDecl!: XMLDecl;
/**
* The line number of the next character to be read by the parser. This field
* is one-based. (The first line is numbered 1.)
*/
line!: number;
/**
* The column number of the next character to be read by the parser. *
* This field is zero-based. (The first column is 0.)
*
* This field counts columns by *Unicode character*. Note that this *can*
* be different from the index of the character in a JavaScript string due
* to how JavaScript handles astral plane characters.
*
* See [[columnIndex]] for a number that corresponds to the JavaScript index.
*/
column!: number;
/**
* A map of entity name to expansion.
*/
ENTITIES!: Record<string, string>;
/**
* @param opt The parser options.
*/
constructor(opt?: O) {
this.opt = opt ?? {};
this.fragmentOpt = !!(this.opt.fragment as boolean);
const xmlnsOpt = this.xmlnsOpt = !!(this.opt.xmlns as boolean);
this.trackPosition = this.opt.position !== false;
this.fileName = this.opt.fileName;
if (xmlnsOpt) {
// This is the function we use to perform name checks on PIs and entities.
// When namespaces are used, colons are not allowed in PI target names or
// entity names. So the check depends on whether namespaces are used. See:
//
// https://www.w3.org/XML/xml-names-19990114-errata.html
// NE08
//
this.nameStartCheck = isNCNameStartChar;
this.nameCheck = isNCNameChar;
this.isName = isNCName;
// eslint-disable-next-line @typescript-eslint/unbound-method
this.processAttribs = this.processAttribsNS;
// eslint-disable-next-line @typescript-eslint/unbound-method
this.pushAttrib = this.pushAttribNS;
// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-assignment
this.ns = { __proto__: null as any, ...rootNS };
const additional = this.opt.additionalNamespaces;
if (additional != null) {
nsMappingCheck(this, additional);
Object.assign(this.ns, additional);
}
}
else {
this.nameStartCheck = isNameStartChar;
this.nameCheck = isNameChar;
this.isName = isName;
// eslint-disable-next-line @typescript-eslint/unbound-method
this.processAttribs = this.processAttribsPlain;
// eslint-disable-next-line @typescript-eslint/unbound-method
this.pushAttrib = this.pushAttribPlain;
}
//
// The order of the members in this table needs to correspond to the state
// numbers given to the states that correspond to the methods being recorded
// here.
//
this.stateTable = [
/* eslint-disable @typescript-eslint/unbound-method */
this.sBegin,
this.sBeginWhitespace,
this.sDoctype,
this.sDoctypeQuote,
this.sDTD,
this.sDTDQuoted,
this.sDTDOpenWaka,
this.sDTDOpenWakaBang,
this.sDTDComment,
this.sDTDCommentEnding,
this.sDTDCommentEnded,
this.sDTDPI,
this.sDTDPIEnding,
this.sText,
this.sEntity,
this.sOpenWaka,
this.sOpenWakaBang,
this.sComment,
this.sCommentEnding,
this.sCommentEnded,
this.sCData,
this.sCDataEnding,
this.sCDataEnding2,
this.sPIFirstChar,
this.sPIRest,
this.sPIBody,
this.sPIEnding,
this.sXMLDeclNameStart,
this.sXMLDeclName,
this.sXMLDeclEq,
this.sXMLDeclValueStart,
this.sXMLDeclValue,
this.sXMLDeclSeparator,
this.sXMLDeclEnding,
this.sOpenTag,
this.sOpenTagSlash,
this.sAttrib,
this.sAttribName,
this.sAttribNameSawWhite,
this.sAttribValue,
this.sAttribValueQuoted,
this.sAttribValueClosed,
this.sAttribValueUnquoted,
this.sCloseTag,
this.sCloseTagSawWhite,
/* eslint-enable @typescript-eslint/unbound-method */
];
this._init();
}
_init(): void {
this.openWakaBang = "";
this.text = "";
this.name = "";
this.piTarget = "";
this.entity = "";
this.q = null;
this.tags = [];
this.tag = null;
this.topNS = null;
this.chunk = "";
this.chunkPosition = 0;
this.i = 0;
this.prevI = 0;
this.carriedFromPrevious = undefined;
this.forbiddenState = FORBIDDEN_START;
this.attribList = [];
// The logic is organized so as to minimize the need to check
// this.opt.fragment while parsing.
const { fragmentOpt } = this;
this.state = fragmentOpt ? S_TEXT : S_BEGIN;
// We want these to be all true if we are dealing with a fragment.
this.reportedTextBeforeRoot = this.reportedTextAfterRoot = this.closedRoot =
this.sawRoot = fragmentOpt;
// An XML declaration is intially possible only when parsing whole
// documents.
this.xmlDeclPossible = !fragmentOpt;
this.xmlDeclExpects = ["version"];
this.entityReturnState = undefined;
let { defaultXMLVersion } = this.opt;
if (defaultXMLVersion === undefined) {
if (this.opt.forceXMLVersion === true) {
throw new Error("forceXMLVersion set but defaultXMLVersion is not set");
}
defaultXMLVersion = "1.0";
}
this.setXMLVersion(defaultXMLVersion);
this.positionAtNewLine = 0;
this.doctype = false;
this._closed = false;
this.xmlDecl = {
version: undefined,
encoding: undefined,
standalone: undefined,
};
this.line = 1;
this.column = 0;
this.ENTITIES = Object.create(XML_ENTITIES) as Record<string, string>;
this.readyHandler?.();
}
/**
* The stream position the parser is currently looking at. This field is
* zero-based.
*
* This field is not based on counting Unicode characters but is to be
* interpreted as a plain index into a JavaScript string.
*/
get position(): number {
return this.chunkPosition + this.i;
}
/**
* The column number of the next character to be read by the parser. *
* This field is zero-based. (The first column in a line is 0.)
*
* This field reports the index at which the next character would be in the
* line if the line were represented as a JavaScript string. Note that this
* *can* be different to a count based on the number of *Unicode characters*
* due to how JavaScript handles astral plane characters.
*
* See [[column]] for a number that corresponds to a count of Unicode
* characters.
*/
get columnIndex(): number {
return this.position - this.positionAtNewLine;
}
/**
* Set an event listener on an event. The parser supports one handler per
* event type. If you try to set an event handler over an existing handler,
* the old handler is silently overwritten.
*
* @param name The event to listen to.
*
* @param handler The handler to set.
*/
on<N extends EventName>(name: N, handler: EventNameToHandler<O, N>): void {
// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-member-access
(this as any)[EVENT_NAME_TO_HANDLER_NAME[name]] = handler;
}
/**
* Unset an event handler.
*
* @parma name The event to stop listening to.
*/
off(name: EventName): void {
// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-member-access
(this as any)[EVENT_NAME_TO_HANDLER_NAME[name]] = undefined;
}
/**
* Make an error object. The error object will have a message that contains
* the ``fileName`` option passed at the creation of the parser. If position
* tracking was turned on, it will also have line and column number
* information.
*
* @param message The message describing the error to report.
*
* @returns An error object with a properly formatted message.
*/
makeError(message: string): Error {
let msg = this.fileName ?? "";
if (this.trackPosition) {
if (msg.length > 0) {
msg += ":";
}
msg += `${this.line}:${this.column}`;
}
if (msg.length > 0) {
msg += ": ";
}
return new Error(msg + message);
}
/**
* Report a parsing error. This method is made public so that client code may
* check for issues that are outside the scope of this project and can report
* errors.
*
* @param message The error to report.
*
* @returns this
*/
fail(message: string): this {
const err = this.makeError(message);
const handler = this.errorHandler;
if (handler === undefined) {
throw err;
}
else {
handler(err);
}
return this;
}
/**
* Write a XML data to the parser.
*
* @param chunk The XML data to write.
*
* @returns this
*/
// We do need object for the type here. Yes, it often causes problems
// but not in this case.
write(chunk: string | object | null): this {
if (this.closed) {
return this.fail("cannot write after close; assign an onready handler.");
}
let end = false;
if (chunk === null) {
// We cannot return immediately because carriedFromPrevious may need
// processing.
end = true;
chunk = "";
}
else if (typeof chunk === "object") {
chunk = chunk.toString();
}
// We checked if performing a pre-decomposition of the string into an array
// of single complete characters (``Array.from(chunk)``) would be faster
// than the current repeated calls to ``charCodeAt``. As of August 2018, it
// isn't. (There may be Node-specific code that would perform faster than
// ``Array.from`` but don't want to be dependent on Node.)
if (this.carriedFromPrevious !== undefined) {
// The previous chunk had char we must carry over.
chunk = `${this.carriedFromPrevious}${chunk}`;
this.carriedFromPrevious = undefined;
}
let limit = chunk.length;
const lastCode = chunk.charCodeAt(limit - 1);
if (!end &&
// A trailing CR or surrogate must be carried over to the next
// chunk.
(lastCode === CR || (lastCode >= 0xD800 && lastCode <= 0xDBFF))) {
// The chunk ends with a character that must be carried over. We cannot
// know how to handle it until we get the next chunk or the end of the
// stream. So save it for later.
this.carriedFromPrevious = chunk[limit - 1];
limit--;
chunk = chunk.slice(0, limit);
}
const { stateTable } = this;
this.chunk = chunk;
this.i = 0;
while (this.i < limit) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-argument
stateTable[this.state].call(this as any);
}
this.chunkPosition += limit;
return end ? this.end() : this;
}
/**
* Close the current stream. Perform final well-formedness checks and reset
* the parser tstate.
*
* @returns this
*/
close(): this {
return this.write(null);
}
/**
* Get a single code point out of the current chunk. This updates the current
* position if we do position tracking.
*
* This is the algorithm to use for XML 1.0.
*
* @returns The character read.
*/
private getCode10(): number {
const { chunk, i } = this;
this.prevI = i;
// Yes, we do this instead of doing this.i++. Doing it this way, we do not
// read this.i again, which is a bit faster.
this.i = i + 1;
if (i >= chunk.length) {
return EOC;
}
// Using charCodeAt and handling the surrogates ourselves is faster
// than using codePointAt.
const code = chunk.charCodeAt(i);
this.column++;
if (code < 0xD800) {
if (code >= SPACE || code === TAB) {
return code;
}
switch (code) {
case NL:
this.line++;
this.column = 0;
this.positionAtNewLine = this.position;
return NL;
case CR:
// We may get NaN if we read past the end of the chunk, which is fine.
if (chunk.charCodeAt(i + 1) === NL) {
// A \r\n sequence is converted to \n so we have to skip over the
// next character. We already know it has a size of 1 so ++ is fine
// here.
this.i = i + 2;
}
// Otherwise, a \r is just converted to \n, so we don't have to skip
// ahead.
// In either case, \r becomes \n.
this.line++;
this.column = 0;
this.positionAtNewLine = this.position;
return NL_LIKE;
default:
// If we get here, then code < SPACE and it is not NL CR or TAB.
this.fail("disallowed character.");
return code;
}
}
if (code > 0xDBFF) {
// This is a specialized version of isChar10 that takes into account
// that in this context code > 0xDBFF and code <= 0xFFFF. So it does not
// test cases that don't need testing.
if (!(code >= 0xE000 && code <= 0xFFFD)) {
this.fail("disallowed character.");
}
return code;
}
const final = 0x10000 + ((code - 0xD800) * 0x400) +
(chunk.charCodeAt(i + 1) - 0xDC00);
this.i = i + 2;
// This is a specialized version of isChar10 that takes into account that in
// this context necessarily final >= 0x10000.
if (final > 0x10FFFF) {
this.fail("disallowed character.");
}
return final;
}
/**
* Get a single code point out of the current chunk. This updates the current
* position if we do position tracking.
*
* This is the algorithm to use for XML 1.1.
*
* @returns {number} The character read.
*/
private getCode11(): number {
const { chunk, i } = this;
this.prevI = i;
// Yes, we do this instead of doing this.i++. Doing it this way, we do not
// read this.i again, which is a bit faster.
this.i = i + 1;
if (i >= chunk.length) {
return EOC;
}
// Using charCodeAt and handling the surrogates ourselves is faster
// than using codePointAt.
const code = chunk.charCodeAt(i);
this.column++;
if (code < 0xD800) {
if ((code > 0x1F && code < 0x7F) || (code > 0x9F && code !== LS) ||
code === TAB) {
return code;
}
switch (code) {
case NL: // 0xA
this.line++;
this.column = 0;
this.positionAtNewLine = this.position;
return NL;
case CR: { // 0xD
// We may get NaN if we read past the end of the chunk, which is
// fine.
const next = chunk.charCodeAt(i + 1);
if (next === NL || next === NEL) {
// A CR NL or CR NEL sequence is converted to NL so we have to skip
// over the next character. We already know it has a size of 1.
this.i = i + 2;
}
// Otherwise, a CR is just converted to NL, no skip.
}
/* yes, fall through */
case NEL: // 0x85
case LS: // Ox2028
this.line++;
this.column = 0;
this.positionAtNewLine = this.position;
return NL_LIKE;
default:
this.fail("disallowed character.");
return code;
}
}
if (code > 0xDBFF) {
// This is a specialized version of isCharAndNotRestricted that takes into
// account that in this context code > 0xDBFF and code <= 0xFFFF. So it
// does not test cases that don't need testing.
if (!(code >= 0xE000 && code <= 0xFFFD)) {
this.fail("disallowed character.");
}
return code;
}
const final = 0x10000 + ((code - 0xD800) * 0x400) +
(chunk.charCodeAt(i + 1) - 0xDC00);
this.i = i + 2;
// This is a specialized version of isCharAndNotRestricted that takes into
// account that in this context necessarily final >= 0x10000.
if (final > 0x10FFFF) {
this.fail("disallowed character.");
}
return final;
}
/**
* Like ``getCode`` but with the return value normalized so that ``NL`` is
* returned for ``NL_LIKE``.
*/
private getCodeNorm(): number {
const c = this.getCode();
return c === NL_LIKE ? NL : c;
}
private unget(): void {
this.i = this.prevI;
this.column--;
}
/**
* Capture characters into a buffer until encountering one of a set of
* characters.
*
* @param chars An array of codepoints. Encountering a character in the array
* ends the capture. (``chars`` may safely contain ``NL``.)
*
* @return The character code that made the capture end, or ``EOC`` if we hit
* the end of the chunk. The return value cannot be NL_LIKE: NL is returned
* instead.
*/
private captureTo(chars: number[]): number {
let { i: start } = this;
const { chunk } = this;
// eslint-disable-next-line no-constant-condition
while (true) {
const c = this.getCode();
const isNLLike = c === NL_LIKE;
const final = isNLLike ? NL : c;
if (final === EOC || chars.includes(final)) {
this.text += chunk.slice(start, this.prevI);
return final;
}
if (isNLLike) {
this.text += `${chunk.slice(start, this.prevI)}\n`;
start = this.i;
}
}
}
/**
* Capture characters into a buffer until encountering a character.
*
* @param char The codepoint that ends the capture. **NOTE ``char`` MAY NOT
* CONTAIN ``NL``.** Passing ``NL`` will result in buggy behavior.
*
* @return ``true`` if we ran into the character. Otherwise, we ran into the
* end of the current chunk.
*/
private captureToChar(char: number): boolean {
let { i: start } = this;
const { chunk } = this;
// eslint-disable-next-line no-constant-condition
while (true) {
let c = this.getCode();
switch (c) {
case NL_LIKE:
this.text += `${chunk.slice(start, this.prevI)}\n`;
start = this.i;
c = NL;
break;
case EOC:
this.text += chunk.slice(start);
return false;
default:
}
if (c === char) {
this.text += chunk.slice(start, this.prevI);
return true;
}
}
}
/**
* Capture characters that satisfy ``isNameChar`` into the ``name`` field of
* this parser.
*
* @return The character code that made the test fail, or ``EOC`` if we hit
* the end of the chunk. The return value cannot be NL_LIKE: NL is returned
* instead.
*/
private captureNameChars(): number {
const { chunk, i: start } = this;
// eslint-disable-next-line no-constant-condition
while (true) {
const c = this.getCode();
if (c === EOC) {
this.name += chunk.slice(start);
return EOC;
}
// NL is not a name char so we don't have to test specifically for it.
if (!isNameChar(c)) {
this.name += chunk.slice(start, this.prevI);
return c === NL_LIKE ? NL : c;
}
}
}
/**
* Skip white spaces.
*
* @return The character that ended the skip, or ``EOC`` if we hit
* the end of the chunk. The return value cannot be NL_LIKE: NL is returned
* instead.
*/
private skipSpaces(): number {
// eslint-disable-next-line no-constant-condition
while (true) {
const c = this.getCodeNorm();
if (c === EOC || !isS(c)) {
return c;
}
}
}
private setXMLVersion(version: string): void {
this.currentXMLVersion = version;
/* eslint-disable @typescript-eslint/unbound-method */
if (version === "1.0") {
this.isChar = isChar10;
this.getCode = this.getCode10;
}
else {
this.isChar = isChar11;
this.getCode = this.getCode11;
}
/* eslint-enable @typescript-eslint/unbound-method */
}
// STATE ENGINE METHODS
// This needs to be a state separate from S_BEGIN_WHITESPACE because we want
// to be sure never to come back to this state later.
private sBegin(): void {
// We are essentially peeking at the first character of the chunk. Since
// S_BEGIN can be in effect only when we start working on the first chunk,
// the index at which we must look is necessarily 0. Note also that the
// following test does not depend on decoding surrogates.
// If the initial character is 0xFEFF, ignore it.
if (this.chunk.charCodeAt(0) === 0xFEFF) {
this.i++;
this.column++;
}
this.state = S_BEGIN_WHITESPACE;
}
private sBeginWhitespace(): void {
// We need to know whether we've encountered spaces or not because as soon
// as we run into a space, an XML declaration is no longer possible. Rather
// than slow down skipSpaces even in places where we don't care whether it
// skipped anything or not, we check whether prevI is equal to the value of
// i from before we skip spaces.
const iBefore = this.i;
const c = this.skipSpaces();
if (this.prevI !== iBefore) {
this.xmlDeclPossible = false;
}
switch (c) {
case LESS:
this.state = S_OPEN_WAKA;
// We could naively call closeText but in this state, it is not normal
// to have text be filled with any data.
if (this.text.length !== 0) {
throw new Error("no-empty text at start");
}
break;
case EOC:
break;
default:
this.unget();
this.state = S_TEXT;
this.xmlDeclPossible = false;
}
}
private sDoctype(): void {
const c = this.captureTo(DOCTYPE_TERMINATOR);
switch (c) {
case GREATER: {
this.doctypeHandler?.(this.text);
this.text = "";
this.state = S_TEXT;
this.doctype = true; // just remember that we saw it.
break;
}
case EOC:
break;
default:
this.text += String.fromCodePoint(c);
if (c === OPEN_BRACKET) {
this.state = S_DTD;
}
else if (isQuote(c)) {
this.state = S_DOCTYPE_QUOTE;
this.q = c;
}
}
}
private sDoctypeQuote(): void {
const q = this.q!;
if (this.captureToChar(q)) {
this.text += String.fromCodePoint(q);
this.q = null;
this.state = S_DOCTYPE;
}
}
private sDTD(): void {
const c = this.captureTo(DTD_TERMINATOR);
if (c === EOC) {
return;
}
this.text += String.fromCodePoint(c);
if (c === CLOSE_BRACKET) {
this.state = S_DOCTYPE;
}
else if (c === LESS) {
this.state = S_DTD_OPEN_WAKA;
}
else if (isQuote(c)) {
this.state = S_DTD_QUOTED;
this.q = c;
}
}
private sDTDQuoted(): void {
const q = this.q!;
if (this.captureToChar(q)) {
this.text += String.fromCodePoint(q);
this.state = S_DTD;
this.q = null;
}
}
private sDTDOpenWaka(): void {
const c = this.getCodeNorm();
this.text += String.fromCodePoint(c);
switch (c) {
case BANG:
this.state = S_DTD_OPEN_WAKA_BANG;
this.openWakaBang = "";
break;
case QUESTION:
this.state = S_DTD_PI;
break;
default:
this.state = S_DTD;
}
}
private sDTDOpenWakaBang(): void {
const char = String.fromCodePoint(this.getCodeNorm());
const owb = this.openWakaBang += char;
this.text += char;
if (owb !== "-") {
this.state = owb === "--" ? S_DTD_COMMENT : S_DTD;
this.openWakaBang = "";
}
}
private sDTDComment(): void {
if (this.captureToChar(MINUS)) {
this.text += "-";
this.state = S_DTD_COMMENT_ENDING;
}
}
private sDTDCommentEnding(): void {
const c = this.getCodeNorm();
this.text += String.fromCodePoint(c);
this.state = c === MINUS ? S_DTD_COMMENT_ENDED : S_DTD_COMMENT;
}
private sDTDCommentEnded(): void {
const c = this.getCodeNorm();
this.text += String.fromCodePoint(c);
if (c === GREATER) {
this.state = S_DTD;
}
else {
this.fail("malformed comment.");
// <!-- blah -- bloo --> will be recorded as
// a comment of " blah -- bloo "
this.state = S_DTD_COMMENT;
}
}
private sDTDPI(): void {
if (this.captureToChar(QUESTION)) {
this.text += "?";
this.state = S_DTD_PI_ENDING;
}
}
private sDTDPIEnding(): void {
const c = this.getCodeNorm();
this.text += String.fromCodePoint(c);
if (c === GREATER) {
this.state = S_DTD;
}
}
private sText(): void {
//
// We did try a version of saxes where the S_TEXT state was split in two
// states: one for text inside the root element, and one for text
// outside. This was avoiding having to test this.tags.length to decide
// what implementation to actually use.
//
// Peformance testing on gigabyte-size files did not show any advantage to
// using the two states solution instead of the current one. Conversely, it
// made the code a bit more complicated elsewhere. For instance, a comment
// can appear before the root element so when a comment ended it was
// necessary to determine whether to return to the S_TEXT state or to the
// new text-outside-root state.
//
if (this.tags.length !== 0) {
this.handleTextInRoot();
}
else {
this.handleTextOutsideRoot();
}
}
private sEntity(): void {
// This is essentially a specialized version of captureToChar(SEMICOLON...)
let { i: start } = this;
const { chunk } = this;
// eslint-disable-next-line no-labels, no-restricted-syntax
loop:
// eslint-disable-next-line no-constant-condition
while (true) {
switch (this.getCode()) {
case NL_LIKE:
this.entity += `${chunk.slice(start, this.prevI)}\n`;
start = this.i;
break;
case SEMICOLON: {
const { entityReturnState } = this;
const entity = this.entity + chunk.slice(start, this.prevI);
this.state = entityReturnState!;
let parsed: string;
if (entity === "") {
this.fail("empty entity name.");
parsed = "&;";
}
else {
parsed = this.parseEntity(entity);
this.entity = "";
}
if (entityReturnState !== S_TEXT || this.textHandler !== undefined) {
this.text += parsed;
}
// eslint-disable-next-line no-labels
break loop;
}
case EOC:
this.entity += chunk.slice(start);
// eslint-disable-next-line no-labels
break loop;
default:
}
}
}
private sOpenWaka(): void {
// Reminder: a state handler is called with at least one character
// available in the current chunk. So the first call to get code inside of
// a state handler cannot return ``EOC``. That's why we don't test
// for it.
const c = this.getCode();
// either a /, ?, !, or text is coming next.
if (isNameStartChar(c)) {
this.state = S_OPEN_TAG;
this.unget();
this.xmlDeclPossible = false;
}
else {
switch (c) {
case FORWARD_SLASH:
this.state = S_CLOSE_TAG;
this.xmlDeclPossible = false;
break;
case BANG:
this.state = S_OPEN_WAKA_BANG;
this.openWakaBang = "";
this.xmlDeclPossible = false;
break;
case QUESTION:
this.state = S_PI_FIRST_CHAR;
break;
default:
this.fail("disallowed character in tag name");
this.state = S_TEXT;
this.xmlDeclPossible = false;
}
}
}
private sOpenWakaBang(): void {
this.openWakaBang += String.fromCodePoint(this.getCodeNorm());
switch (this.openWakaBang) {
case "[CDATA[":
if (!this.sawRoot && !this.reportedTextBeforeRoot) {
this.fail("text data outside of root node.");
this.reportedTextBeforeRoot = true;
}
if (this.closedRoot && !this.reportedTextAfterRoot) {
this.fail("text data outside of root node.");
this.reportedTextAfterRoot = true;
}
this.state = S_CDATA;
this.openWakaBang = "";
break;
case "--":
this.state = S_COMMENT;
this.openWakaBang = "";
break;
case "DOCTYPE":
this.state = S_DOCTYPE;
if (this.doctype || this.sawRoot) {
this.fail("inappropriately located doctype declaration.");
}
this.openWakaBang = "";
break;
default:
// 7 happens to be the maximum length of the string that can possibly
// match one of the cases above.
if (this.openWakaBang.length >= 7) {
this.fail("incorrect syntax.");
}
}
}
private sComment(): void {
if (this.captureToChar(MINUS)) {
this.state = S_COMMENT_ENDING;
}
}
private sCommentEnding(): void {
const c = this.getCodeNorm();
if (c === MINUS) {
this.state = S_COMMENT_ENDED;
this.commentHandler?.(this.text);
this.text = "";
}
else {
this.text += `-${String.fromCodePoint(c)}`;
this.state = S_COMMENT;
}
}
private sCommentEnded(): void {
const c = this.getCodeNorm();
if (c !== GREATER) {
this.fail("malformed comment.");
// <!-- blah -- bloo --> will be recorded as
// a comment of " blah -- bloo "
this.text += `--${String.fromCodePoint(c)}`;
this.state = S_COMMENT;
}
else {
this.state = S_TEXT;
}
}
private sCData(): void {
if (this.captureToChar(CLOSE_BRACKET)) {
this.state = S_CDATA_ENDING;
}
}
private sCDataEnding(): void {
const c = this.getCodeNorm();
if (c === CLOSE_BRACKET) {
this.state = S_CDATA_ENDING_2;
}
else {
this.text += `]${String.fromCodePoint(c)}`;
this.state = S_CDATA;
}
}
private sCDataEnding2(): void {
const c = this.getCodeNorm();
switch (c) {
case GREATER: {
this.cdataHandler?.(this.text);
this.text = "";
this.state = S_TEXT;
break;
}
case CLOSE_BRACKET:
this.text += "]";
break;
default:
this.text += `]]${String.fromCodePoint(c)}`;
this.state = S_CDATA;
}
}
// We need this separate state to check the first character fo the pi target
// with this.nameStartCheck which allows less characters than this.nameCheck.
private sPIFirstChar(): void {
const c = this.getCodeNorm();
// This is first because in the case where the file is well-formed this is
// the branch taken. We optimize for well-formedness.
if (this.nameStartCheck(c)) {
this.piTarget += String.fromCodePoint(c);
this.state = S_PI_REST;
}
else if (c === QUESTION || isS(c)) {
this.fail("processing instruction without a target.");
this.state = c === QUESTION ? S_PI_ENDING : S_PI_BODY;
}
else {
this.fail("disallowed character in processing instruction name.");
this.piTarget += String.fromCodePoint(c);
this.state = S_PI_REST;
}
}
private sPIRest(): void {
// Capture characters into a piTarget while ``this.nameCheck`` run on the
// character read returns true.
const { chunk, i: start } = this;
// eslint-disable-next-line no-constant-condition
while (true) {
const c = this.getCodeNorm();
if (c === EOC) {
this.piTarget += chunk.slice(start);
return;
}
// NL cannot satisfy this.nameCheck so we don't have to test specifically
// for it.
if (!this.nameCheck(c)) {
this.piTarget += chunk.slice(start, this.prevI);
const isQuestion = c === QUESTION;
if (isQuestion || isS(c)) {
if (this.piTarget === "xml") {
if (!this.xmlDeclPossible) {
this.fail(
"an XML declaration must be at the start of the document.");
}
this.state = isQuestion ? S_XML_DECL_ENDING : S_XML_DECL_NAME_START;
}
else {
this.state = isQuestion ? S_PI_ENDING : S_PI_BODY;
}
}
else {
this.fail("disallowed character in processing instruction name.");
this.piTarget += String.fromCodePoint(c);
}
break;
}
}
}
private sPIBody(): void {
if (this.text.length === 0) {
const c = this.getCodeNorm();
if (c === QUESTION) {
this.state = S_PI_ENDING;
}
else if (!isS(c)) {
this.text = String.fromCodePoint(c);
}
}
// The question mark character is not valid inside any of the XML
// declaration name/value pairs.
else if (this.captureToChar(QUESTION)) {
this.state = S_PI_ENDING;
}
}
private sPIEnding(): void {
const c = this.getCodeNorm();
if (c === GREATER) {
const { piTarget } = this;
if (piTarget.toLowerCase() === "xml") {
this.fail(
"the XML declaration must appear at the start of the document.");
}
this.piHandler?.({
target: piTarget,
body: this.text,
});
this.piTarget = this.text = "";
this.state = S_TEXT;
}
else if (c === QUESTION) {
// We ran into ?? as part of a processing instruction. We initially took
// the first ? as a sign that the PI was ending, but it is not. So we have
// to add it to the body but we take the new ? as a sign that the PI is
// ending.
this.text += "?";
}
else {
this.text += `?${String.fromCodePoint(c)}`;
this.state = S_PI_BODY;
}
this.xmlDeclPossible = false;
}
private sXMLDeclNameStart(): void {
const c = this.skipSpaces();
// The question mark character is not valid inside any of the XML
// declaration name/value pairs.
if (c === QUESTION) {
// It is valid to go to S_XML_DECL_ENDING from this state.
this.state = S_XML_DECL_ENDING;
return;
}
if (c !== EOC) {
this.state = S_XML_DECL_NAME;
this.name = String.fromCodePoint(c);
}
}
private sXMLDeclName(): void {
const c = this.captureTo(XML_DECL_NAME_TERMINATOR);
// The question mark character is not valid inside any of the XML
// declaration name/value pairs.
if (c === QUESTION) {
this.state = S_XML_DECL_ENDING;
this.name += this.text;
this.text = "";
this.fail("XML declaration is incomplete.");
return;
}
if (!(isS(c) || c === EQUAL)) {
return;
}
this.name += this.text;
this.text = "";
if (!this.xmlDeclExpects.includes(this.name)) {
switch (this.name.length) {
case 0:
this.fail("did not expect any more name/value pairs.");
break;
case 1:
this.fail(`expected the name ${this.xmlDeclExpects[0]}.`);
break;
default:
this.fail(`expected one of ${this.xmlDeclExpects.join(", ")}`);
}
}
this.state = c === EQUAL ? S_XML_DECL_VALUE_START : S_XML_DECL_EQ;
}
private sXMLDeclEq(): void {
const c = this.getCodeNorm();
// The question mark character is not valid inside any of the XML
// declaration name/value pairs.
if (c === QUESTION) {
this.state = S_XML_DECL_ENDING;
this.fail("XML declaration is incomplete.");
return;
}
if (isS(c)) {
return;
}
if (c !== EQUAL) {
this.fail("value required.");
}
this.state = S_XML_DECL_VALUE_START;
}
private sXMLDeclValueStart(): void {
const c = this.getCodeNorm();
// The question mark character is not valid inside any of the XML
// declaration name/value pairs.
if (c === QUESTION) {
this.state = S_XML_DECL_ENDING;
this.fail("XML declaration is incomplete.");
return;
}
if (isS(c)) {
return;
}
if (!isQuote(c)) {
this.fail("value must be quoted.");
this.q = SPACE;
}
else {
this.q = c;
}
this.state = S_XML_DECL_VALUE;
}
private sXMLDeclValue(): void {
const c = this.captureTo([this.q!, QUESTION]);
// The question mark character is not valid inside any of the XML
// declaration name/value pairs.
if (c === QUESTION) {
this.state = S_XML_DECL_ENDING;
this.text = "";
this.fail("XML declaration is incomplete.");
return;
}
if (c === EOC) {
return;
}
const value = this.text;
this.text = "";
switch (this.name) {
case "version": {
this.xmlDeclExpects = ["encoding", "standalone"];
const version = value;
this.xmlDecl.version = version;
// This is the test specified by XML 1.0 but it is fine for XML 1.1.
if (!/^1\.[0-9]+$/.test(version)) {
this.fail("version number must match /^1\\.[0-9]+$/.");
}
// When forceXMLVersion is set, the XML declaration is ignored.
else if (!(this.opt.forceXMLVersion as boolean)) {
this.setXMLVersion(version);
}
break;
}
case "encoding":
if (!/^[A-Za-z][A-Za-z0-9._-]*$/.test(value)) {
this.fail("encoding value must match \
/^[A-Za-z0-9][A-Za-z0-9._-]*$/.");
}
this.xmlDeclExpects = ["standalone"];
this.xmlDecl.encoding = value;
break;
case "standalone":
if (value !== "yes" && value !== "no") {
this.fail("standalone value must match \"yes\" or \"no\".");
}
this.xmlDeclExpects = [];
this.xmlDecl.standalone = value;
break;
default:
// We don't need to raise an error here since we've already raised one
// when checking what name was expected.
}
this.name = "";
this.state = S_XML_DECL_SEPARATOR;
}
private sXMLDeclSeparator(): void {
const c = this.getCodeNorm();
// The question mark character is not valid inside any of the XML
// declaration name/value pairs.
if (c === QUESTION) {
// It is valid to go to S_XML_DECL_ENDING from this state.
this.state = S_XML_DECL_ENDING;
return;
}
if (!isS(c)) {
this.fail("whitespace required.");
this.unget();
}
this.state = S_XML_DECL_NAME_START;
}
private sXMLDeclEnding(): void {
const c = this.getCodeNorm();
if (c === GREATER) {
if (this.piTarget !== "xml") {
this.fail("processing instructions are not allowed before root.");
}
else if (this.name !== "version" &&
this.xmlDeclExpects.includes("version")) {
this.fail("XML declaration must contain a version.");
}
this.xmldeclHandler?.(this.xmlDecl);
this.name = "";
this.piTarget = this.text = "";
this.state = S_TEXT;
}
else {
// We got here because the previous character was a ?, but the question
// mark character is not valid inside any of the XML declaration
// name/value pairs.
this.fail(
"The character ? is disallowed anywhere in XML declarations.");
}
this.xmlDeclPossible = false;
}
private sOpenTag(): void {
const c = this.captureNameChars();
if (c === EOC) {
return;
}
const tag: SaxesTagIncomplete = this.tag = {
name: this.name,
attributes: Object.create(null) as Record<string, string>,
};
this.name = "";
if (this.xmlnsOpt) {
this.topNS = tag.ns = Object.create(null) as Record<string, string>;
}
this.openTagStartHandler?.(tag as StartTagForOptions<O>);
this.sawRoot = true;
if (!this.fragmentOpt && this.closedRoot) {
this.fail("documents may contain only one root.");
}
switch (c) {
case GREATER:
this.openTag();
break;
case FORWARD_SLASH:
this.state = S_OPEN_TAG_SLASH;
break;
default:
if (!isS(c)) {
this.fail("disallowed character in tag name.");
}
this.state = S_ATTRIB;
}
}
private sOpenTagSlash(): void {
if (this.getCode() === GREATER) {
this.openSelfClosingTag();
}
else {
this.fail("forward-slash in opening tag not followed by >.");
this.state = S_ATTRIB;
}
}
private sAttrib(): void {
const c = this.skipSpaces();
if (c === EOC) {
return;
}
if (isNameStartChar(c)) {
this.unget();
this.state = S_ATTRIB_NAME;
}
else if (c === GREATER) {
this.openTag();
}
else if (c === FORWARD_SLASH) {
this.state = S_OPEN_TAG_SLASH;
}
else {
this.fail("disallowed character in attribute name.");
}
}
private sAttribName(): void {
const c = this.captureNameChars();
if (c === EQUAL) {
this.state = S_ATTRIB_VALUE;
}
else if (isS(c)) {
this.state = S_ATTRIB_NAME_SAW_WHITE;
}
else if (c === GREATER) {
this.fail("attribute without value.");
this.pushAttrib(this.name, this.name);
this.name = this.text = "";
this.openTag();
}
else if (c !== EOC) {
this.fail("disallowed character in attribute name.");
}
}
private sAttribNameSawWhite(): void {
const c = this.skipSpaces();
switch (c) {
case EOC:
return;
case EQUAL:
this.state = S_ATTRIB_VALUE;
break;
default:
this.fail("attribute without value.");
// Should we do this???
// this.tag.attributes[this.name] = "";
this.text = "";
this.name = "";
if (c === GREATER) {
this.openTag();
}
else if (isNameStartChar(c)) {
this.unget();
this.state = S_ATTRIB_NAME;
}
else {
this.fail("disallowed character in attribute name.");
this.state = S_ATTRIB;
}
}
}
private sAttribValue(): void {
const c = this.getCodeNorm();
if (isQuote(c)) {
this.q = c;
this.state = S_ATTRIB_VALUE_QUOTED;
}
else if (!isS(c)) {
this.fail("unquoted attribute value.");
this.state = S_ATTRIB_VALUE_UNQUOTED;
this.unget();
}
}
private sAttribValueQuoted(): void {
// We deliberately do not use captureTo here. The specialized code we use
// here is faster than using captureTo.
const { q, chunk } = this;
let { i: start } = this;
// eslint-disable-next-line no-constant-condition
while (true) {
switch (this.getCode()) {
case q:
this.pushAttrib(this.name,
this.text + chunk.slice(start, this.prevI));
this.name = this.text = "";
this.q = null;
this.state = S_ATTRIB_VALUE_CLOSED;
return;
case AMP:
this.text += chunk.slice(start, this.prevI);
this.state = S_ENTITY;
this.entityReturnState = S_ATTRIB_VALUE_QUOTED;
return;
case NL:
case NL_LIKE:
case TAB:
this.text += `${chunk.slice(start, this.prevI)} `;
start = this.i;
break;
case LESS:
this.text += chunk.slice(start, this.prevI);
this.fail("disallowed character.");
return;
case EOC:
this.text += chunk.slice(start);
return;
default:
}
}
}
private sAttribValueClosed(): void {
const c = this.getCodeNorm();
if (isS(c)) {
this.state = S_ATTRIB;
}
else if (c === GREATER) {
this.openTag();
}
else if (c === FORWARD_SLASH) {
this.state = S_OPEN_TAG_SLASH;
}
else if (isNameStartChar(c)) {
this.fail("no whitespace between attributes.");
this.unget();
this.state = S_ATTRIB_NAME;
}
else {
this.fail("disallowed character in attribute name.");
}
}
private sAttribValueUnquoted(): void {
// We don't do anything regarding EOL or space handling for unquoted
// attributes. We already have failed by the time we get here, and the
// contract that saxes upholds states that upon failure, it is not safe to
// rely on the data passed to event handlers (other than
// ``onerror``). Passing "bad" data is not a problem.
const c = this.captureTo(ATTRIB_VALUE_UNQUOTED_TERMINATOR);
switch (c) {
case AMP:
this.state = S_ENTITY;
this.entityReturnState = S_ATTRIB_VALUE_UNQUOTED;
break;
case LESS:
this.fail("disallowed character.");
break;
case EOC:
break;
default:
if (this.text.includes("]]>")) {
this.fail("the string \"]]>\" is disallowed in char data.");
}
this.pushAttrib(this.name, this.text);
this.name = this.text = "";
if (c === GREATER) {
this.openTag();
}
else {
this.state = S_ATTRIB;
}
}
}
private sCloseTag(): void {
const c = this.captureNameChars();
if (c === GREATER) {
this.closeTag();
}
else if (isS(c)) {
this.state = S_CLOSE_TAG_SAW_WHITE;
}
else if (c !== EOC) {
this.fail("disallowed character in closing tag.");
}
}
private sCloseTagSawWhite(): void {
switch (this.skipSpaces()) {
case GREATER:
this.closeTag();
break;
case EOC:
break;
default:
this.fail("disallowed character in closing tag.");
}
}
// END OF STATE ENGINE METHODS
private handleTextInRoot(): void {
// This is essentially a specialized version of captureTo which is optimized
// for performing the ]]> check. A previous version of this code, checked
// ``this.text`` for the presence of ]]>. It simplified the code but was
// very costly when character data contained a lot of entities to be parsed.
//
// Since we are using a specialized loop, we also keep track of the presence
// of ]]> in text data. The sequence ]]> is forbidden to appear as-is.
//
let { i: start, forbiddenState } = this;
const { chunk, textHandler: handler } = this;
// eslint-disable-next-line no-labels, no-restricted-syntax
scanLoop:
// eslint-disable-next-line no-constant-condition
while (true) {
switch (this.getCode()) {
case LESS: {
this.state = S_OPEN_WAKA;
if (handler !== undefined) {
const { text } = this;
const slice = chunk.slice(start, this.prevI);
if (text.length !== 0) {
handler(text + slice);
this.text = "";
}
else if (slice.length !== 0) {
handler(slice);
}
}
forbiddenState = FORBIDDEN_START;
// eslint-disable-next-line no-labels
break scanLoop;
}
case AMP:
this.state = S_ENTITY;
this.entityReturnState = S_TEXT;
if (handler !== undefined) {
this.text += chunk.slice(start, this.prevI);
}
forbiddenState = FORBIDDEN_START;
// eslint-disable-next-line no-labels
break scanLoop;
case CLOSE_BRACKET:
switch (forbiddenState) {
case FORBIDDEN_START:
forbiddenState = FORBIDDEN_BRACKET;
break;
case FORBIDDEN_BRACKET:
forbiddenState = FORBIDDEN_BRACKET_BRACKET;
break;
case FORBIDDEN_BRACKET_BRACKET:
break;
default:
throw new Error("impossible state");
}
break;
case GREATER:
if (forbiddenState === FORBIDDEN_BRACKET_BRACKET) {
this.fail("the string \"]]>\" is disallowed in char data.");
}
forbiddenState = FORBIDDEN_START;
break;
case NL_LIKE:
if (handler !== undefined) {
this.text += `${chunk.slice(start, this.prevI)}\n`;
}
start = this.i;
forbiddenState = FORBIDDEN_START;
break;
case EOC:
if (handler !== undefined) {
this.text += chunk.slice(start);
}
// eslint-disable-next-line no-labels
break scanLoop;
default:
forbiddenState = FORBIDDEN_START;
}
}
this.forbiddenState = forbiddenState;
}
private handleTextOutsideRoot(): void {
// This is essentially a specialized version of captureTo which is optimized
// for a specialized task. We keep track of the presence of non-space
// characters in the text since these are errors when appearing outside the
// document root element.
let { i: start } = this;
const { chunk, textHandler: handler } = this;
let nonSpace = false;
// eslint-disable-next-line no-labels, no-restricted-syntax
outRootLoop:
// eslint-disable-next-line no-constant-condition
while (true) {
const code = this.getCode();
switch (code) {
case LESS: {
this.state = S_OPEN_WAKA;
if (handler !== undefined) {
const { text } = this;
const slice = chunk.slice(start, this.prevI);
if (text.length !== 0) {
handler(text + slice);
this.text = "";
}
else if (slice.length !== 0) {
handler(slice);
}
}
// eslint-disable-next-line no-labels
break outRootLoop;
}
case AMP:
this.state = S_ENTITY;
this.entityReturnState = S_TEXT;
if (handler !== undefined) {
this.text += chunk.slice(start, this.prevI);
}
nonSpace = true;
// eslint-disable-next-line no-labels
break outRootLoop;
case NL_LIKE:
if (handler !== undefined) {
this.text += `${chunk.slice(start, this.prevI)}\n`;
}
start = this.i;
break;
case EOC:
if (handler !== undefined) {
this.text += chunk.slice(start);
}
// eslint-disable-next-line no-labels
break outRootLoop;
default:
if (!isS(code)) {
nonSpace = true;
}
}
}
if (!nonSpace) {
return;
}
// We use the reportedTextBeforeRoot and reportedTextAfterRoot flags
// to avoid reporting errors for every single character that is out of
// place.
if (!this.sawRoot && !this.reportedTextBeforeRoot) {
this.fail("text data outside of root node.");
this.reportedTextBeforeRoot = true;
}
if (this.closedRoot && !this.reportedTextAfterRoot) {
this.fail("text data outside of root node.");
this.reportedTextAfterRoot = true;
}
}
private pushAttribNS(name: string, value: string): void {
const { prefix, local } = this.qname(name);
const attr = { name, prefix, local, value };
this.attribList.push(attr);
this.attributeHandler?.(attr as AttributeEventForOptions<O>);
if (prefix === "xmlns") {
const trimmed = value.trim();
if (this.currentXMLVersion === "1.0" && trimmed === "") {
this.fail("invalid attempt to undefine prefix in XML 1.0");
}
this.topNS![local] = trimmed;
nsPairCheck(this, local, trimmed);
}
else if (name === "xmlns") {
const trimmed = value.trim();
this.topNS![""] = trimmed;
nsPairCheck(this, "", trimmed);
}
}
private pushAttribPlain(name: string, value: string): void {
const attr = { name, value };
this.attribList.push(attr);
this.attributeHandler?.(attr as AttributeEventForOptions<O>);
}
/**
* End parsing. This performs final well-formedness checks and resets the
* parser to a clean state.
*
* @returns this
*/
private end(): this {
if (!this.sawRoot) {
this.fail("document must contain a root element.");
}
const { tags } = this;
while (tags.length > 0) {
const tag = tags.pop()!;
this.fail(`unclosed tag: ${tag.name}`);
}
if ((this.state !== S_BEGIN) && (this.state !== S_TEXT)) {
this.fail("unexpected end.");
}
const { text } = this;
if (text.length !== 0) {
this.textHandler?.(text);
this.text = "";
}
this._closed = true;
this.endHandler?.();
this._init();
return this;
}
/**
* Resolve a namespace prefix.
*
* @param prefix The prefix to resolve.
*
* @returns The namespace URI or ``undefined`` if the prefix is not defined.
*/
resolve(prefix: string): string | undefined {
let uri = this.topNS![prefix];
if (uri !== undefined) {
return uri;
}
const { tags } = this;
for (let index = tags.length - 1; index >= 0; index--) {
uri = tags[index]!.ns![prefix];
if (uri !== undefined) {
return uri;
}
}
uri = this.ns[prefix];
if (uri !== undefined) {
return uri;
}
return this.opt.resolvePrefix?.(prefix);
}
/**
* Parse a qname into its prefix and local name parts.
*
* @param name The name to parse
*
* @returns
*/
private qname(name: string): { prefix: string; local: string } {
// This is faster than using name.split(":").
const colon = name.indexOf(":");
if (colon === -1) {
return { prefix: "", local: name };
}
const local = name.slice(colon + 1);
const prefix = name.slice(0, colon);
if (prefix === "" || local === "" || local.includes(":")) {
this.fail(`malformed name: ${name}.`);
}
return { prefix, local };
}
private processAttribsNS(): void {
const { attribList } = this;
const tag = this.tag!;
{
// add namespace info to tag
const { prefix, local } = this.qname(tag.name);
tag.prefix = prefix;
tag.local = local;
const uri = tag.uri = this.resolve(prefix) ?? "";
if (prefix !== "") {
if (prefix === "xmlns") {
this.fail("tags may not have \"xmlns\" as prefix.");
}
if (uri === "") {
this.fail(`unbound namespace prefix: ${JSON.stringify(prefix)}.`);
tag.uri = prefix;
}
}
}
if (attribList.length === 0) {
return;
}
const { attributes } = tag;
const seen = new Set();
// Note: do not apply default ns to attributes:
// http://www.w3.org/TR/REC-xml-names/#defaulting
for (const attr of attribList as SaxesAttributeNSIncomplete[]) {
const { name, prefix, local } = attr;
let uri;
let eqname;
if (prefix === "") {
uri = name === "xmlns" ? XMLNS_NAMESPACE : "";
eqname = name;
}
else {
uri = this.resolve(prefix);
// if there's any attributes with an undefined namespace,
// then fail on them now.
if (uri === undefined) {
this.fail(`unbound namespace prefix: ${JSON.stringify(prefix)}.`);
uri = prefix;
}
eqname = `{${uri}}${local}`;
}
if (seen.has(eqname)) {
this.fail(`duplicate attribute: ${eqname}.`);
}
seen.add(eqname);
attr.uri = uri;
attributes[name] = attr;
}
this.attribList = [];
}
private processAttribsPlain(): void {
const { attribList } = this;
// eslint-disable-next-line prefer-destructuring
const attributes = this.tag!.attributes;
for (const { name, value } of attribList) {
if (attributes[name] !== undefined) {
this.fail(`duplicate attribute: ${name}.`);
}
attributes[name] = value;
}
this.attribList = [];
}
/**
* Handle a complete open tag. This parser code calls this once it has seen
* the whole tag. This method checks for well-formeness and then emits
* ``onopentag``.
*/
private openTag(): void {
this.processAttribs();
const { tags } = this;
const tag = this.tag as SaxesTag;
tag.isSelfClosing = false;
// There cannot be any pending text here due to the onopentagstart that was
// necessarily emitted before we get here. So we do not check text.
this.openTagHandler?.(tag as TagForOptions<O>);
tags.push(tag);
this.state = S_TEXT;
this.name = "";
}
/**
* Handle a complete self-closing tag. This parser code calls this once it has
* seen the whole tag. This method checks for well-formeness and then emits
* ``onopentag`` and ``onclosetag``.
*/
private openSelfClosingTag(): void {
this.processAttribs();
const { tags } = this;
const tag = this.tag as SaxesTag;
tag.isSelfClosing = true;
// There cannot be any pending text here due to the onopentagstart that was
// necessarily emitted before we get here. So we do not check text.
this.openTagHandler?.(tag as TagForOptions<O>);
this.closeTagHandler?.(tag as TagForOptions<O>);
const top = this.tag = tags[tags.length - 1] ?? null;
if (top === null) {
this.closedRoot = true;
}
this.state = S_TEXT;
this.name = "";
}
/**
* Handle a complete close tag. This parser code calls this once it has seen
* the whole tag. This method checks for well-formeness and then emits
* ``onclosetag``.
*/
private closeTag(): void {
const { tags, name } = this;
// Our state after this will be S_TEXT, no matter what, and we can clear
// tagName now.
this.state = S_TEXT;
this.name = "";
if (name === "") {
this.fail("weird empty close tag.");
this.text += "</>";
return;
}
const handler = this.closeTagHandler;
let l = tags.length;
while (l-- > 0) {
const tag = this.tag = tags.pop() as SaxesTag;
this.topNS = tag.ns!;
handler?.(tag as TagForOptions<O>);
if (tag.name === name) {
break;
}
this.fail("unexpected close tag.");
}
if (l === 0) {
this.closedRoot = true;
}
else if (l < 0) {
this.fail(`unmatched closing tag: ${name}.`);
this.text += `</${name}>`;
}
}
/**
* Resolves an entity. Makes any necessary well-formedness checks.
*
* @param entity The entity to resolve.
*
* @returns The parsed entity.
*/
private parseEntity(entity: string): string {
// startsWith would be significantly slower for this test.
if (entity[0] !== "#") {
const defined = this.ENTITIES[entity];
if (defined !== undefined) {
return defined;
}
this.fail(this.isName(entity) ? "undefined entity." :
"disallowed character in entity name.");
return `&${entity};`;
}
let num = NaN;
if (entity[1] === "x" && /^#x[0-9a-f]+$/i.test(entity)) {
num = parseInt(entity.slice(2), 16);
}
else if (/^#[0-9]+$/.test(entity)) {
num = parseInt(entity.slice(1), 10);
}
// The character reference is required to match the CHAR production.
if (!this.isChar(num)) {
this.fail("malformed character entity.");
return `&${entity};`;
}
return String.fromCodePoint(num);
}
} |
1,150 | fn(parser: SaxesParser): void {
for (const x of xml) {
parser.write(x);
}
parser.close();
} | class SaxesParser<O extends SaxesOptions = {}> {
private readonly fragmentOpt: boolean;
private readonly xmlnsOpt: boolean;
private readonly trackPosition: boolean;
private readonly fileName?: string;
private readonly nameStartCheck: (c: number) => boolean;
private readonly nameCheck: (c: number) => boolean;
private readonly isName: (name: string) => boolean;
private readonly ns!: Record<string, string>;
private openWakaBang!: string;
private text!: string;
private name!: string;
private piTarget!: string;
private entity!: string;
private q!: null | number;
private tags!: SaxesTagIncomplete[];
private tag!: SaxesTagIncomplete | null;
private topNS!: Record<string, string> | null;
private chunk!: string;
private chunkPosition!: number;
private i!: number;
//
// We use prevI to allow "ungetting" the previously read code point. Note
// however, that it is not safe to unget everything and anything. In
// particular ungetting EOL characters will screw positioning up.
//
// Practically, you must not unget a code which has any side effect beyond
// updating ``this.i`` and ``this.prevI``. Only EOL codes have such side
// effects.
//
private prevI!: number;
private carriedFromPrevious?: string;
private forbiddenState!: number;
private attribList!: (SaxesAttributeNSIncomplete | SaxesAttributePlain)[];
private state!: number;
private reportedTextBeforeRoot!: boolean;
private reportedTextAfterRoot!: boolean;
private closedRoot!: boolean;
private sawRoot!: boolean;
private xmlDeclPossible!: boolean;
private xmlDeclExpects!: string[];
private entityReturnState?: number;
private processAttribs!: (this: this) => void;
private positionAtNewLine!: number;
private doctype!: boolean;
private getCode!: () => number;
private isChar!: (c: number) => boolean;
private pushAttrib!: (name: string, value: string) => void;
private _closed!: boolean;
private currentXMLVersion!: string;
private readonly stateTable: ((this: SaxesParser<O>) => void)[];
private xmldeclHandler?: XMLDeclHandler;
private textHandler?: TextHandler;
private piHandler?: PIHandler;
private doctypeHandler?: DoctypeHandler;
private commentHandler?: CommentHandler;
private openTagStartHandler?: OpenTagStartHandler<O>;
private openTagHandler?: OpenTagHandler<O>;
private closeTagHandler?: CloseTagHandler<O>;
private cdataHandler?: CDataHandler;
private errorHandler?: ErrorHandler;
private endHandler?: EndHandler;
private readyHandler?: ReadyHandler;
private attributeHandler?: AttributeHandler<O>;
/**
* Indicates whether or not the parser is closed. If ``true``, wait for
* the ``ready`` event to write again.
*/
get closed(): boolean {
return this._closed;
}
readonly opt: SaxesOptions;
/**
* The XML declaration for this document.
*/
xmlDecl!: XMLDecl;
/**
* The line number of the next character to be read by the parser. This field
* is one-based. (The first line is numbered 1.)
*/
line!: number;
/**
* The column number of the next character to be read by the parser. *
* This field is zero-based. (The first column is 0.)
*
* This field counts columns by *Unicode character*. Note that this *can*
* be different from the index of the character in a JavaScript string due
* to how JavaScript handles astral plane characters.
*
* See [[columnIndex]] for a number that corresponds to the JavaScript index.
*/
column!: number;
/**
* A map of entity name to expansion.
*/
ENTITIES!: Record<string, string>;
/**
* @param opt The parser options.
*/
constructor(opt?: O) {
this.opt = opt ?? {};
this.fragmentOpt = !!(this.opt.fragment as boolean);
const xmlnsOpt = this.xmlnsOpt = !!(this.opt.xmlns as boolean);
this.trackPosition = this.opt.position !== false;
this.fileName = this.opt.fileName;
if (xmlnsOpt) {
// This is the function we use to perform name checks on PIs and entities.
// When namespaces are used, colons are not allowed in PI target names or
// entity names. So the check depends on whether namespaces are used. See:
//
// https://www.w3.org/XML/xml-names-19990114-errata.html
// NE08
//
this.nameStartCheck = isNCNameStartChar;
this.nameCheck = isNCNameChar;
this.isName = isNCName;
// eslint-disable-next-line @typescript-eslint/unbound-method
this.processAttribs = this.processAttribsNS;
// eslint-disable-next-line @typescript-eslint/unbound-method
this.pushAttrib = this.pushAttribNS;
// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-assignment
this.ns = { __proto__: null as any, ...rootNS };
const additional = this.opt.additionalNamespaces;
if (additional != null) {
nsMappingCheck(this, additional);
Object.assign(this.ns, additional);
}
}
else {
this.nameStartCheck = isNameStartChar;
this.nameCheck = isNameChar;
this.isName = isName;
// eslint-disable-next-line @typescript-eslint/unbound-method
this.processAttribs = this.processAttribsPlain;
// eslint-disable-next-line @typescript-eslint/unbound-method
this.pushAttrib = this.pushAttribPlain;
}
//
// The order of the members in this table needs to correspond to the state
// numbers given to the states that correspond to the methods being recorded
// here.
//
this.stateTable = [
/* eslint-disable @typescript-eslint/unbound-method */
this.sBegin,
this.sBeginWhitespace,
this.sDoctype,
this.sDoctypeQuote,
this.sDTD,
this.sDTDQuoted,
this.sDTDOpenWaka,
this.sDTDOpenWakaBang,
this.sDTDComment,
this.sDTDCommentEnding,
this.sDTDCommentEnded,
this.sDTDPI,
this.sDTDPIEnding,
this.sText,
this.sEntity,
this.sOpenWaka,
this.sOpenWakaBang,
this.sComment,
this.sCommentEnding,
this.sCommentEnded,
this.sCData,
this.sCDataEnding,
this.sCDataEnding2,
this.sPIFirstChar,
this.sPIRest,
this.sPIBody,
this.sPIEnding,
this.sXMLDeclNameStart,
this.sXMLDeclName,
this.sXMLDeclEq,
this.sXMLDeclValueStart,
this.sXMLDeclValue,
this.sXMLDeclSeparator,
this.sXMLDeclEnding,
this.sOpenTag,
this.sOpenTagSlash,
this.sAttrib,
this.sAttribName,
this.sAttribNameSawWhite,
this.sAttribValue,
this.sAttribValueQuoted,
this.sAttribValueClosed,
this.sAttribValueUnquoted,
this.sCloseTag,
this.sCloseTagSawWhite,
/* eslint-enable @typescript-eslint/unbound-method */
];
this._init();
}
_init(): void {
this.openWakaBang = "";
this.text = "";
this.name = "";
this.piTarget = "";
this.entity = "";
this.q = null;
this.tags = [];
this.tag = null;
this.topNS = null;
this.chunk = "";
this.chunkPosition = 0;
this.i = 0;
this.prevI = 0;
this.carriedFromPrevious = undefined;
this.forbiddenState = FORBIDDEN_START;
this.attribList = [];
// The logic is organized so as to minimize the need to check
// this.opt.fragment while parsing.
const { fragmentOpt } = this;
this.state = fragmentOpt ? S_TEXT : S_BEGIN;
// We want these to be all true if we are dealing with a fragment.
this.reportedTextBeforeRoot = this.reportedTextAfterRoot = this.closedRoot =
this.sawRoot = fragmentOpt;
// An XML declaration is intially possible only when parsing whole
// documents.
this.xmlDeclPossible = !fragmentOpt;
this.xmlDeclExpects = ["version"];
this.entityReturnState = undefined;
let { defaultXMLVersion } = this.opt;
if (defaultXMLVersion === undefined) {
if (this.opt.forceXMLVersion === true) {
throw new Error("forceXMLVersion set but defaultXMLVersion is not set");
}
defaultXMLVersion = "1.0";
}
this.setXMLVersion(defaultXMLVersion);
this.positionAtNewLine = 0;
this.doctype = false;
this._closed = false;
this.xmlDecl = {
version: undefined,
encoding: undefined,
standalone: undefined,
};
this.line = 1;
this.column = 0;
this.ENTITIES = Object.create(XML_ENTITIES) as Record<string, string>;
this.readyHandler?.();
}
/**
* The stream position the parser is currently looking at. This field is
* zero-based.
*
* This field is not based on counting Unicode characters but is to be
* interpreted as a plain index into a JavaScript string.
*/
get position(): number {
return this.chunkPosition + this.i;
}
/**
* The column number of the next character to be read by the parser. *
* This field is zero-based. (The first column in a line is 0.)
*
* This field reports the index at which the next character would be in the
* line if the line were represented as a JavaScript string. Note that this
* *can* be different to a count based on the number of *Unicode characters*
* due to how JavaScript handles astral plane characters.
*
* See [[column]] for a number that corresponds to a count of Unicode
* characters.
*/
get columnIndex(): number {
return this.position - this.positionAtNewLine;
}
/**
* Set an event listener on an event. The parser supports one handler per
* event type. If you try to set an event handler over an existing handler,
* the old handler is silently overwritten.
*
* @param name The event to listen to.
*
* @param handler The handler to set.
*/
on<N extends EventName>(name: N, handler: EventNameToHandler<O, N>): void {
// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-member-access
(this as any)[EVENT_NAME_TO_HANDLER_NAME[name]] = handler;
}
/**
* Unset an event handler.
*
* @parma name The event to stop listening to.
*/
off(name: EventName): void {
// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-member-access
(this as any)[EVENT_NAME_TO_HANDLER_NAME[name]] = undefined;
}
/**
* Make an error object. The error object will have a message that contains
* the ``fileName`` option passed at the creation of the parser. If position
* tracking was turned on, it will also have line and column number
* information.
*
* @param message The message describing the error to report.
*
* @returns An error object with a properly formatted message.
*/
makeError(message: string): Error {
let msg = this.fileName ?? "";
if (this.trackPosition) {
if (msg.length > 0) {
msg += ":";
}
msg += `${this.line}:${this.column}`;
}
if (msg.length > 0) {
msg += ": ";
}
return new Error(msg + message);
}
/**
* Report a parsing error. This method is made public so that client code may
* check for issues that are outside the scope of this project and can report
* errors.
*
* @param message The error to report.
*
* @returns this
*/
fail(message: string): this {
const err = this.makeError(message);
const handler = this.errorHandler;
if (handler === undefined) {
throw err;
}
else {
handler(err);
}
return this;
}
/**
* Write a XML data to the parser.
*
* @param chunk The XML data to write.
*
* @returns this
*/
// We do need object for the type here. Yes, it often causes problems
// but not in this case.
write(chunk: string | object | null): this {
if (this.closed) {
return this.fail("cannot write after close; assign an onready handler.");
}
let end = false;
if (chunk === null) {
// We cannot return immediately because carriedFromPrevious may need
// processing.
end = true;
chunk = "";
}
else if (typeof chunk === "object") {
chunk = chunk.toString();
}
// We checked if performing a pre-decomposition of the string into an array
// of single complete characters (``Array.from(chunk)``) would be faster
// than the current repeated calls to ``charCodeAt``. As of August 2018, it
// isn't. (There may be Node-specific code that would perform faster than
// ``Array.from`` but don't want to be dependent on Node.)
if (this.carriedFromPrevious !== undefined) {
// The previous chunk had char we must carry over.
chunk = `${this.carriedFromPrevious}${chunk}`;
this.carriedFromPrevious = undefined;
}
let limit = chunk.length;
const lastCode = chunk.charCodeAt(limit - 1);
if (!end &&
// A trailing CR or surrogate must be carried over to the next
// chunk.
(lastCode === CR || (lastCode >= 0xD800 && lastCode <= 0xDBFF))) {
// The chunk ends with a character that must be carried over. We cannot
// know how to handle it until we get the next chunk or the end of the
// stream. So save it for later.
this.carriedFromPrevious = chunk[limit - 1];
limit--;
chunk = chunk.slice(0, limit);
}
const { stateTable } = this;
this.chunk = chunk;
this.i = 0;
while (this.i < limit) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-argument
stateTable[this.state].call(this as any);
}
this.chunkPosition += limit;
return end ? this.end() : this;
}
/**
* Close the current stream. Perform final well-formedness checks and reset
* the parser tstate.
*
* @returns this
*/
close(): this {
return this.write(null);
}
/**
* Get a single code point out of the current chunk. This updates the current
* position if we do position tracking.
*
* This is the algorithm to use for XML 1.0.
*
* @returns The character read.
*/
private getCode10(): number {
const { chunk, i } = this;
this.prevI = i;
// Yes, we do this instead of doing this.i++. Doing it this way, we do not
// read this.i again, which is a bit faster.
this.i = i + 1;
if (i >= chunk.length) {
return EOC;
}
// Using charCodeAt and handling the surrogates ourselves is faster
// than using codePointAt.
const code = chunk.charCodeAt(i);
this.column++;
if (code < 0xD800) {
if (code >= SPACE || code === TAB) {
return code;
}
switch (code) {
case NL:
this.line++;
this.column = 0;
this.positionAtNewLine = this.position;
return NL;
case CR:
// We may get NaN if we read past the end of the chunk, which is fine.
if (chunk.charCodeAt(i + 1) === NL) {
// A \r\n sequence is converted to \n so we have to skip over the
// next character. We already know it has a size of 1 so ++ is fine
// here.
this.i = i + 2;
}
// Otherwise, a \r is just converted to \n, so we don't have to skip
// ahead.
// In either case, \r becomes \n.
this.line++;
this.column = 0;
this.positionAtNewLine = this.position;
return NL_LIKE;
default:
// If we get here, then code < SPACE and it is not NL CR or TAB.
this.fail("disallowed character.");
return code;
}
}
if (code > 0xDBFF) {
// This is a specialized version of isChar10 that takes into account
// that in this context code > 0xDBFF and code <= 0xFFFF. So it does not
// test cases that don't need testing.
if (!(code >= 0xE000 && code <= 0xFFFD)) {
this.fail("disallowed character.");
}
return code;
}
const final = 0x10000 + ((code - 0xD800) * 0x400) +
(chunk.charCodeAt(i + 1) - 0xDC00);
this.i = i + 2;
// This is a specialized version of isChar10 that takes into account that in
// this context necessarily final >= 0x10000.
if (final > 0x10FFFF) {
this.fail("disallowed character.");
}
return final;
}
/**
* Get a single code point out of the current chunk. This updates the current
* position if we do position tracking.
*
* This is the algorithm to use for XML 1.1.
*
* @returns {number} The character read.
*/
private getCode11(): number {
const { chunk, i } = this;
this.prevI = i;
// Yes, we do this instead of doing this.i++. Doing it this way, we do not
// read this.i again, which is a bit faster.
this.i = i + 1;
if (i >= chunk.length) {
return EOC;
}
// Using charCodeAt and handling the surrogates ourselves is faster
// than using codePointAt.
const code = chunk.charCodeAt(i);
this.column++;
if (code < 0xD800) {
if ((code > 0x1F && code < 0x7F) || (code > 0x9F && code !== LS) ||
code === TAB) {
return code;
}
switch (code) {
case NL: // 0xA
this.line++;
this.column = 0;
this.positionAtNewLine = this.position;
return NL;
case CR: { // 0xD
// We may get NaN if we read past the end of the chunk, which is
// fine.
const next = chunk.charCodeAt(i + 1);
if (next === NL || next === NEL) {
// A CR NL or CR NEL sequence is converted to NL so we have to skip
// over the next character. We already know it has a size of 1.
this.i = i + 2;
}
// Otherwise, a CR is just converted to NL, no skip.
}
/* yes, fall through */
case NEL: // 0x85
case LS: // Ox2028
this.line++;
this.column = 0;
this.positionAtNewLine = this.position;
return NL_LIKE;
default:
this.fail("disallowed character.");
return code;
}
}
if (code > 0xDBFF) {
// This is a specialized version of isCharAndNotRestricted that takes into
// account that in this context code > 0xDBFF and code <= 0xFFFF. So it
// does not test cases that don't need testing.
if (!(code >= 0xE000 && code <= 0xFFFD)) {
this.fail("disallowed character.");
}
return code;
}
const final = 0x10000 + ((code - 0xD800) * 0x400) +
(chunk.charCodeAt(i + 1) - 0xDC00);
this.i = i + 2;
// This is a specialized version of isCharAndNotRestricted that takes into
// account that in this context necessarily final >= 0x10000.
if (final > 0x10FFFF) {
this.fail("disallowed character.");
}
return final;
}
/**
* Like ``getCode`` but with the return value normalized so that ``NL`` is
* returned for ``NL_LIKE``.
*/
private getCodeNorm(): number {
const c = this.getCode();
return c === NL_LIKE ? NL : c;
}
private unget(): void {
this.i = this.prevI;
this.column--;
}
/**
* Capture characters into a buffer until encountering one of a set of
* characters.
*
* @param chars An array of codepoints. Encountering a character in the array
* ends the capture. (``chars`` may safely contain ``NL``.)
*
* @return The character code that made the capture end, or ``EOC`` if we hit
* the end of the chunk. The return value cannot be NL_LIKE: NL is returned
* instead.
*/
private captureTo(chars: number[]): number {
let { i: start } = this;
const { chunk } = this;
// eslint-disable-next-line no-constant-condition
while (true) {
const c = this.getCode();
const isNLLike = c === NL_LIKE;
const final = isNLLike ? NL : c;
if (final === EOC || chars.includes(final)) {
this.text += chunk.slice(start, this.prevI);
return final;
}
if (isNLLike) {
this.text += `${chunk.slice(start, this.prevI)}\n`;
start = this.i;
}
}
}
/**
* Capture characters into a buffer until encountering a character.
*
* @param char The codepoint that ends the capture. **NOTE ``char`` MAY NOT
* CONTAIN ``NL``.** Passing ``NL`` will result in buggy behavior.
*
* @return ``true`` if we ran into the character. Otherwise, we ran into the
* end of the current chunk.
*/
private captureToChar(char: number): boolean {
let { i: start } = this;
const { chunk } = this;
// eslint-disable-next-line no-constant-condition
while (true) {
let c = this.getCode();
switch (c) {
case NL_LIKE:
this.text += `${chunk.slice(start, this.prevI)}\n`;
start = this.i;
c = NL;
break;
case EOC:
this.text += chunk.slice(start);
return false;
default:
}
if (c === char) {
this.text += chunk.slice(start, this.prevI);
return true;
}
}
}
/**
* Capture characters that satisfy ``isNameChar`` into the ``name`` field of
* this parser.
*
* @return The character code that made the test fail, or ``EOC`` if we hit
* the end of the chunk. The return value cannot be NL_LIKE: NL is returned
* instead.
*/
private captureNameChars(): number {
const { chunk, i: start } = this;
// eslint-disable-next-line no-constant-condition
while (true) {
const c = this.getCode();
if (c === EOC) {
this.name += chunk.slice(start);
return EOC;
}
// NL is not a name char so we don't have to test specifically for it.
if (!isNameChar(c)) {
this.name += chunk.slice(start, this.prevI);
return c === NL_LIKE ? NL : c;
}
}
}
/**
* Skip white spaces.
*
* @return The character that ended the skip, or ``EOC`` if we hit
* the end of the chunk. The return value cannot be NL_LIKE: NL is returned
* instead.
*/
private skipSpaces(): number {
// eslint-disable-next-line no-constant-condition
while (true) {
const c = this.getCodeNorm();
if (c === EOC || !isS(c)) {
return c;
}
}
}
private setXMLVersion(version: string): void {
this.currentXMLVersion = version;
/* eslint-disable @typescript-eslint/unbound-method */
if (version === "1.0") {
this.isChar = isChar10;
this.getCode = this.getCode10;
}
else {
this.isChar = isChar11;
this.getCode = this.getCode11;
}
/* eslint-enable @typescript-eslint/unbound-method */
}
// STATE ENGINE METHODS
// This needs to be a state separate from S_BEGIN_WHITESPACE because we want
// to be sure never to come back to this state later.
private sBegin(): void {
// We are essentially peeking at the first character of the chunk. Since
// S_BEGIN can be in effect only when we start working on the first chunk,
// the index at which we must look is necessarily 0. Note also that the
// following test does not depend on decoding surrogates.
// If the initial character is 0xFEFF, ignore it.
if (this.chunk.charCodeAt(0) === 0xFEFF) {
this.i++;
this.column++;
}
this.state = S_BEGIN_WHITESPACE;
}
private sBeginWhitespace(): void {
// We need to know whether we've encountered spaces or not because as soon
// as we run into a space, an XML declaration is no longer possible. Rather
// than slow down skipSpaces even in places where we don't care whether it
// skipped anything or not, we check whether prevI is equal to the value of
// i from before we skip spaces.
const iBefore = this.i;
const c = this.skipSpaces();
if (this.prevI !== iBefore) {
this.xmlDeclPossible = false;
}
switch (c) {
case LESS:
this.state = S_OPEN_WAKA;
// We could naively call closeText but in this state, it is not normal
// to have text be filled with any data.
if (this.text.length !== 0) {
throw new Error("no-empty text at start");
}
break;
case EOC:
break;
default:
this.unget();
this.state = S_TEXT;
this.xmlDeclPossible = false;
}
}
private sDoctype(): void {
const c = this.captureTo(DOCTYPE_TERMINATOR);
switch (c) {
case GREATER: {
this.doctypeHandler?.(this.text);
this.text = "";
this.state = S_TEXT;
this.doctype = true; // just remember that we saw it.
break;
}
case EOC:
break;
default:
this.text += String.fromCodePoint(c);
if (c === OPEN_BRACKET) {
this.state = S_DTD;
}
else if (isQuote(c)) {
this.state = S_DOCTYPE_QUOTE;
this.q = c;
}
}
}
private sDoctypeQuote(): void {
const q = this.q!;
if (this.captureToChar(q)) {
this.text += String.fromCodePoint(q);
this.q = null;
this.state = S_DOCTYPE;
}
}
private sDTD(): void {
const c = this.captureTo(DTD_TERMINATOR);
if (c === EOC) {
return;
}
this.text += String.fromCodePoint(c);
if (c === CLOSE_BRACKET) {
this.state = S_DOCTYPE;
}
else if (c === LESS) {
this.state = S_DTD_OPEN_WAKA;
}
else if (isQuote(c)) {
this.state = S_DTD_QUOTED;
this.q = c;
}
}
private sDTDQuoted(): void {
const q = this.q!;
if (this.captureToChar(q)) {
this.text += String.fromCodePoint(q);
this.state = S_DTD;
this.q = null;
}
}
private sDTDOpenWaka(): void {
const c = this.getCodeNorm();
this.text += String.fromCodePoint(c);
switch (c) {
case BANG:
this.state = S_DTD_OPEN_WAKA_BANG;
this.openWakaBang = "";
break;
case QUESTION:
this.state = S_DTD_PI;
break;
default:
this.state = S_DTD;
}
}
private sDTDOpenWakaBang(): void {
const char = String.fromCodePoint(this.getCodeNorm());
const owb = this.openWakaBang += char;
this.text += char;
if (owb !== "-") {
this.state = owb === "--" ? S_DTD_COMMENT : S_DTD;
this.openWakaBang = "";
}
}
private sDTDComment(): void {
if (this.captureToChar(MINUS)) {
this.text += "-";
this.state = S_DTD_COMMENT_ENDING;
}
}
private sDTDCommentEnding(): void {
const c = this.getCodeNorm();
this.text += String.fromCodePoint(c);
this.state = c === MINUS ? S_DTD_COMMENT_ENDED : S_DTD_COMMENT;
}
private sDTDCommentEnded(): void {
const c = this.getCodeNorm();
this.text += String.fromCodePoint(c);
if (c === GREATER) {
this.state = S_DTD;
}
else {
this.fail("malformed comment.");
// <!-- blah -- bloo --> will be recorded as
// a comment of " blah -- bloo "
this.state = S_DTD_COMMENT;
}
}
private sDTDPI(): void {
if (this.captureToChar(QUESTION)) {
this.text += "?";
this.state = S_DTD_PI_ENDING;
}
}
private sDTDPIEnding(): void {
const c = this.getCodeNorm();
this.text += String.fromCodePoint(c);
if (c === GREATER) {
this.state = S_DTD;
}
}
private sText(): void {
//
// We did try a version of saxes where the S_TEXT state was split in two
// states: one for text inside the root element, and one for text
// outside. This was avoiding having to test this.tags.length to decide
// what implementation to actually use.
//
// Peformance testing on gigabyte-size files did not show any advantage to
// using the two states solution instead of the current one. Conversely, it
// made the code a bit more complicated elsewhere. For instance, a comment
// can appear before the root element so when a comment ended it was
// necessary to determine whether to return to the S_TEXT state or to the
// new text-outside-root state.
//
if (this.tags.length !== 0) {
this.handleTextInRoot();
}
else {
this.handleTextOutsideRoot();
}
}
private sEntity(): void {
// This is essentially a specialized version of captureToChar(SEMICOLON...)
let { i: start } = this;
const { chunk } = this;
// eslint-disable-next-line no-labels, no-restricted-syntax
loop:
// eslint-disable-next-line no-constant-condition
while (true) {
switch (this.getCode()) {
case NL_LIKE:
this.entity += `${chunk.slice(start, this.prevI)}\n`;
start = this.i;
break;
case SEMICOLON: {
const { entityReturnState } = this;
const entity = this.entity + chunk.slice(start, this.prevI);
this.state = entityReturnState!;
let parsed: string;
if (entity === "") {
this.fail("empty entity name.");
parsed = "&;";
}
else {
parsed = this.parseEntity(entity);
this.entity = "";
}
if (entityReturnState !== S_TEXT || this.textHandler !== undefined) {
this.text += parsed;
}
// eslint-disable-next-line no-labels
break loop;
}
case EOC:
this.entity += chunk.slice(start);
// eslint-disable-next-line no-labels
break loop;
default:
}
}
}
private sOpenWaka(): void {
// Reminder: a state handler is called with at least one character
// available in the current chunk. So the first call to get code inside of
// a state handler cannot return ``EOC``. That's why we don't test
// for it.
const c = this.getCode();
// either a /, ?, !, or text is coming next.
if (isNameStartChar(c)) {
this.state = S_OPEN_TAG;
this.unget();
this.xmlDeclPossible = false;
}
else {
switch (c) {
case FORWARD_SLASH:
this.state = S_CLOSE_TAG;
this.xmlDeclPossible = false;
break;
case BANG:
this.state = S_OPEN_WAKA_BANG;
this.openWakaBang = "";
this.xmlDeclPossible = false;
break;
case QUESTION:
this.state = S_PI_FIRST_CHAR;
break;
default:
this.fail("disallowed character in tag name");
this.state = S_TEXT;
this.xmlDeclPossible = false;
}
}
}
private sOpenWakaBang(): void {
this.openWakaBang += String.fromCodePoint(this.getCodeNorm());
switch (this.openWakaBang) {
case "[CDATA[":
if (!this.sawRoot && !this.reportedTextBeforeRoot) {
this.fail("text data outside of root node.");
this.reportedTextBeforeRoot = true;
}
if (this.closedRoot && !this.reportedTextAfterRoot) {
this.fail("text data outside of root node.");
this.reportedTextAfterRoot = true;
}
this.state = S_CDATA;
this.openWakaBang = "";
break;
case "--":
this.state = S_COMMENT;
this.openWakaBang = "";
break;
case "DOCTYPE":
this.state = S_DOCTYPE;
if (this.doctype || this.sawRoot) {
this.fail("inappropriately located doctype declaration.");
}
this.openWakaBang = "";
break;
default:
// 7 happens to be the maximum length of the string that can possibly
// match one of the cases above.
if (this.openWakaBang.length >= 7) {
this.fail("incorrect syntax.");
}
}
}
private sComment(): void {
if (this.captureToChar(MINUS)) {
this.state = S_COMMENT_ENDING;
}
}
private sCommentEnding(): void {
const c = this.getCodeNorm();
if (c === MINUS) {
this.state = S_COMMENT_ENDED;
this.commentHandler?.(this.text);
this.text = "";
}
else {
this.text += `-${String.fromCodePoint(c)}`;
this.state = S_COMMENT;
}
}
private sCommentEnded(): void {
const c = this.getCodeNorm();
if (c !== GREATER) {
this.fail("malformed comment.");
// <!-- blah -- bloo --> will be recorded as
// a comment of " blah -- bloo "
this.text += `--${String.fromCodePoint(c)}`;
this.state = S_COMMENT;
}
else {
this.state = S_TEXT;
}
}
private sCData(): void {
if (this.captureToChar(CLOSE_BRACKET)) {
this.state = S_CDATA_ENDING;
}
}
private sCDataEnding(): void {
const c = this.getCodeNorm();
if (c === CLOSE_BRACKET) {
this.state = S_CDATA_ENDING_2;
}
else {
this.text += `]${String.fromCodePoint(c)}`;
this.state = S_CDATA;
}
}
private sCDataEnding2(): void {
const c = this.getCodeNorm();
switch (c) {
case GREATER: {
this.cdataHandler?.(this.text);
this.text = "";
this.state = S_TEXT;
break;
}
case CLOSE_BRACKET:
this.text += "]";
break;
default:
this.text += `]]${String.fromCodePoint(c)}`;
this.state = S_CDATA;
}
}
// We need this separate state to check the first character fo the pi target
// with this.nameStartCheck which allows less characters than this.nameCheck.
private sPIFirstChar(): void {
const c = this.getCodeNorm();
// This is first because in the case where the file is well-formed this is
// the branch taken. We optimize for well-formedness.
if (this.nameStartCheck(c)) {
this.piTarget += String.fromCodePoint(c);
this.state = S_PI_REST;
}
else if (c === QUESTION || isS(c)) {
this.fail("processing instruction without a target.");
this.state = c === QUESTION ? S_PI_ENDING : S_PI_BODY;
}
else {
this.fail("disallowed character in processing instruction name.");
this.piTarget += String.fromCodePoint(c);
this.state = S_PI_REST;
}
}
private sPIRest(): void {
// Capture characters into a piTarget while ``this.nameCheck`` run on the
// character read returns true.
const { chunk, i: start } = this;
// eslint-disable-next-line no-constant-condition
while (true) {
const c = this.getCodeNorm();
if (c === EOC) {
this.piTarget += chunk.slice(start);
return;
}
// NL cannot satisfy this.nameCheck so we don't have to test specifically
// for it.
if (!this.nameCheck(c)) {
this.piTarget += chunk.slice(start, this.prevI);
const isQuestion = c === QUESTION;
if (isQuestion || isS(c)) {
if (this.piTarget === "xml") {
if (!this.xmlDeclPossible) {
this.fail(
"an XML declaration must be at the start of the document.");
}
this.state = isQuestion ? S_XML_DECL_ENDING : S_XML_DECL_NAME_START;
}
else {
this.state = isQuestion ? S_PI_ENDING : S_PI_BODY;
}
}
else {
this.fail("disallowed character in processing instruction name.");
this.piTarget += String.fromCodePoint(c);
}
break;
}
}
}
private sPIBody(): void {
if (this.text.length === 0) {
const c = this.getCodeNorm();
if (c === QUESTION) {
this.state = S_PI_ENDING;
}
else if (!isS(c)) {
this.text = String.fromCodePoint(c);
}
}
// The question mark character is not valid inside any of the XML
// declaration name/value pairs.
else if (this.captureToChar(QUESTION)) {
this.state = S_PI_ENDING;
}
}
private sPIEnding(): void {
const c = this.getCodeNorm();
if (c === GREATER) {
const { piTarget } = this;
if (piTarget.toLowerCase() === "xml") {
this.fail(
"the XML declaration must appear at the start of the document.");
}
this.piHandler?.({
target: piTarget,
body: this.text,
});
this.piTarget = this.text = "";
this.state = S_TEXT;
}
else if (c === QUESTION) {
// We ran into ?? as part of a processing instruction. We initially took
// the first ? as a sign that the PI was ending, but it is not. So we have
// to add it to the body but we take the new ? as a sign that the PI is
// ending.
this.text += "?";
}
else {
this.text += `?${String.fromCodePoint(c)}`;
this.state = S_PI_BODY;
}
this.xmlDeclPossible = false;
}
private sXMLDeclNameStart(): void {
const c = this.skipSpaces();
// The question mark character is not valid inside any of the XML
// declaration name/value pairs.
if (c === QUESTION) {
// It is valid to go to S_XML_DECL_ENDING from this state.
this.state = S_XML_DECL_ENDING;
return;
}
if (c !== EOC) {
this.state = S_XML_DECL_NAME;
this.name = String.fromCodePoint(c);
}
}
private sXMLDeclName(): void {
const c = this.captureTo(XML_DECL_NAME_TERMINATOR);
// The question mark character is not valid inside any of the XML
// declaration name/value pairs.
if (c === QUESTION) {
this.state = S_XML_DECL_ENDING;
this.name += this.text;
this.text = "";
this.fail("XML declaration is incomplete.");
return;
}
if (!(isS(c) || c === EQUAL)) {
return;
}
this.name += this.text;
this.text = "";
if (!this.xmlDeclExpects.includes(this.name)) {
switch (this.name.length) {
case 0:
this.fail("did not expect any more name/value pairs.");
break;
case 1:
this.fail(`expected the name ${this.xmlDeclExpects[0]}.`);
break;
default:
this.fail(`expected one of ${this.xmlDeclExpects.join(", ")}`);
}
}
this.state = c === EQUAL ? S_XML_DECL_VALUE_START : S_XML_DECL_EQ;
}
private sXMLDeclEq(): void {
const c = this.getCodeNorm();
// The question mark character is not valid inside any of the XML
// declaration name/value pairs.
if (c === QUESTION) {
this.state = S_XML_DECL_ENDING;
this.fail("XML declaration is incomplete.");
return;
}
if (isS(c)) {
return;
}
if (c !== EQUAL) {
this.fail("value required.");
}
this.state = S_XML_DECL_VALUE_START;
}
private sXMLDeclValueStart(): void {
const c = this.getCodeNorm();
// The question mark character is not valid inside any of the XML
// declaration name/value pairs.
if (c === QUESTION) {
this.state = S_XML_DECL_ENDING;
this.fail("XML declaration is incomplete.");
return;
}
if (isS(c)) {
return;
}
if (!isQuote(c)) {
this.fail("value must be quoted.");
this.q = SPACE;
}
else {
this.q = c;
}
this.state = S_XML_DECL_VALUE;
}
private sXMLDeclValue(): void {
const c = this.captureTo([this.q!, QUESTION]);
// The question mark character is not valid inside any of the XML
// declaration name/value pairs.
if (c === QUESTION) {
this.state = S_XML_DECL_ENDING;
this.text = "";
this.fail("XML declaration is incomplete.");
return;
}
if (c === EOC) {
return;
}
const value = this.text;
this.text = "";
switch (this.name) {
case "version": {
this.xmlDeclExpects = ["encoding", "standalone"];
const version = value;
this.xmlDecl.version = version;
// This is the test specified by XML 1.0 but it is fine for XML 1.1.
if (!/^1\.[0-9]+$/.test(version)) {
this.fail("version number must match /^1\\.[0-9]+$/.");
}
// When forceXMLVersion is set, the XML declaration is ignored.
else if (!(this.opt.forceXMLVersion as boolean)) {
this.setXMLVersion(version);
}
break;
}
case "encoding":
if (!/^[A-Za-z][A-Za-z0-9._-]*$/.test(value)) {
this.fail("encoding value must match \
/^[A-Za-z0-9][A-Za-z0-9._-]*$/.");
}
this.xmlDeclExpects = ["standalone"];
this.xmlDecl.encoding = value;
break;
case "standalone":
if (value !== "yes" && value !== "no") {
this.fail("standalone value must match \"yes\" or \"no\".");
}
this.xmlDeclExpects = [];
this.xmlDecl.standalone = value;
break;
default:
// We don't need to raise an error here since we've already raised one
// when checking what name was expected.
}
this.name = "";
this.state = S_XML_DECL_SEPARATOR;
}
private sXMLDeclSeparator(): void {
const c = this.getCodeNorm();
// The question mark character is not valid inside any of the XML
// declaration name/value pairs.
if (c === QUESTION) {
// It is valid to go to S_XML_DECL_ENDING from this state.
this.state = S_XML_DECL_ENDING;
return;
}
if (!isS(c)) {
this.fail("whitespace required.");
this.unget();
}
this.state = S_XML_DECL_NAME_START;
}
private sXMLDeclEnding(): void {
const c = this.getCodeNorm();
if (c === GREATER) {
if (this.piTarget !== "xml") {
this.fail("processing instructions are not allowed before root.");
}
else if (this.name !== "version" &&
this.xmlDeclExpects.includes("version")) {
this.fail("XML declaration must contain a version.");
}
this.xmldeclHandler?.(this.xmlDecl);
this.name = "";
this.piTarget = this.text = "";
this.state = S_TEXT;
}
else {
// We got here because the previous character was a ?, but the question
// mark character is not valid inside any of the XML declaration
// name/value pairs.
this.fail(
"The character ? is disallowed anywhere in XML declarations.");
}
this.xmlDeclPossible = false;
}
private sOpenTag(): void {
const c = this.captureNameChars();
if (c === EOC) {
return;
}
const tag: SaxesTagIncomplete = this.tag = {
name: this.name,
attributes: Object.create(null) as Record<string, string>,
};
this.name = "";
if (this.xmlnsOpt) {
this.topNS = tag.ns = Object.create(null) as Record<string, string>;
}
this.openTagStartHandler?.(tag as StartTagForOptions<O>);
this.sawRoot = true;
if (!this.fragmentOpt && this.closedRoot) {
this.fail("documents may contain only one root.");
}
switch (c) {
case GREATER:
this.openTag();
break;
case FORWARD_SLASH:
this.state = S_OPEN_TAG_SLASH;
break;
default:
if (!isS(c)) {
this.fail("disallowed character in tag name.");
}
this.state = S_ATTRIB;
}
}
private sOpenTagSlash(): void {
if (this.getCode() === GREATER) {
this.openSelfClosingTag();
}
else {
this.fail("forward-slash in opening tag not followed by >.");
this.state = S_ATTRIB;
}
}
private sAttrib(): void {
const c = this.skipSpaces();
if (c === EOC) {
return;
}
if (isNameStartChar(c)) {
this.unget();
this.state = S_ATTRIB_NAME;
}
else if (c === GREATER) {
this.openTag();
}
else if (c === FORWARD_SLASH) {
this.state = S_OPEN_TAG_SLASH;
}
else {
this.fail("disallowed character in attribute name.");
}
}
private sAttribName(): void {
const c = this.captureNameChars();
if (c === EQUAL) {
this.state = S_ATTRIB_VALUE;
}
else if (isS(c)) {
this.state = S_ATTRIB_NAME_SAW_WHITE;
}
else if (c === GREATER) {
this.fail("attribute without value.");
this.pushAttrib(this.name, this.name);
this.name = this.text = "";
this.openTag();
}
else if (c !== EOC) {
this.fail("disallowed character in attribute name.");
}
}
private sAttribNameSawWhite(): void {
const c = this.skipSpaces();
switch (c) {
case EOC:
return;
case EQUAL:
this.state = S_ATTRIB_VALUE;
break;
default:
this.fail("attribute without value.");
// Should we do this???
// this.tag.attributes[this.name] = "";
this.text = "";
this.name = "";
if (c === GREATER) {
this.openTag();
}
else if (isNameStartChar(c)) {
this.unget();
this.state = S_ATTRIB_NAME;
}
else {
this.fail("disallowed character in attribute name.");
this.state = S_ATTRIB;
}
}
}
private sAttribValue(): void {
const c = this.getCodeNorm();
if (isQuote(c)) {
this.q = c;
this.state = S_ATTRIB_VALUE_QUOTED;
}
else if (!isS(c)) {
this.fail("unquoted attribute value.");
this.state = S_ATTRIB_VALUE_UNQUOTED;
this.unget();
}
}
private sAttribValueQuoted(): void {
// We deliberately do not use captureTo here. The specialized code we use
// here is faster than using captureTo.
const { q, chunk } = this;
let { i: start } = this;
// eslint-disable-next-line no-constant-condition
while (true) {
switch (this.getCode()) {
case q:
this.pushAttrib(this.name,
this.text + chunk.slice(start, this.prevI));
this.name = this.text = "";
this.q = null;
this.state = S_ATTRIB_VALUE_CLOSED;
return;
case AMP:
this.text += chunk.slice(start, this.prevI);
this.state = S_ENTITY;
this.entityReturnState = S_ATTRIB_VALUE_QUOTED;
return;
case NL:
case NL_LIKE:
case TAB:
this.text += `${chunk.slice(start, this.prevI)} `;
start = this.i;
break;
case LESS:
this.text += chunk.slice(start, this.prevI);
this.fail("disallowed character.");
return;
case EOC:
this.text += chunk.slice(start);
return;
default:
}
}
}
private sAttribValueClosed(): void {
const c = this.getCodeNorm();
if (isS(c)) {
this.state = S_ATTRIB;
}
else if (c === GREATER) {
this.openTag();
}
else if (c === FORWARD_SLASH) {
this.state = S_OPEN_TAG_SLASH;
}
else if (isNameStartChar(c)) {
this.fail("no whitespace between attributes.");
this.unget();
this.state = S_ATTRIB_NAME;
}
else {
this.fail("disallowed character in attribute name.");
}
}
private sAttribValueUnquoted(): void {
// We don't do anything regarding EOL or space handling for unquoted
// attributes. We already have failed by the time we get here, and the
// contract that saxes upholds states that upon failure, it is not safe to
// rely on the data passed to event handlers (other than
// ``onerror``). Passing "bad" data is not a problem.
const c = this.captureTo(ATTRIB_VALUE_UNQUOTED_TERMINATOR);
switch (c) {
case AMP:
this.state = S_ENTITY;
this.entityReturnState = S_ATTRIB_VALUE_UNQUOTED;
break;
case LESS:
this.fail("disallowed character.");
break;
case EOC:
break;
default:
if (this.text.includes("]]>")) {
this.fail("the string \"]]>\" is disallowed in char data.");
}
this.pushAttrib(this.name, this.text);
this.name = this.text = "";
if (c === GREATER) {
this.openTag();
}
else {
this.state = S_ATTRIB;
}
}
}
private sCloseTag(): void {
const c = this.captureNameChars();
if (c === GREATER) {
this.closeTag();
}
else if (isS(c)) {
this.state = S_CLOSE_TAG_SAW_WHITE;
}
else if (c !== EOC) {
this.fail("disallowed character in closing tag.");
}
}
private sCloseTagSawWhite(): void {
switch (this.skipSpaces()) {
case GREATER:
this.closeTag();
break;
case EOC:
break;
default:
this.fail("disallowed character in closing tag.");
}
}
// END OF STATE ENGINE METHODS
private handleTextInRoot(): void {
// This is essentially a specialized version of captureTo which is optimized
// for performing the ]]> check. A previous version of this code, checked
// ``this.text`` for the presence of ]]>. It simplified the code but was
// very costly when character data contained a lot of entities to be parsed.
//
// Since we are using a specialized loop, we also keep track of the presence
// of ]]> in text data. The sequence ]]> is forbidden to appear as-is.
//
let { i: start, forbiddenState } = this;
const { chunk, textHandler: handler } = this;
// eslint-disable-next-line no-labels, no-restricted-syntax
scanLoop:
// eslint-disable-next-line no-constant-condition
while (true) {
switch (this.getCode()) {
case LESS: {
this.state = S_OPEN_WAKA;
if (handler !== undefined) {
const { text } = this;
const slice = chunk.slice(start, this.prevI);
if (text.length !== 0) {
handler(text + slice);
this.text = "";
}
else if (slice.length !== 0) {
handler(slice);
}
}
forbiddenState = FORBIDDEN_START;
// eslint-disable-next-line no-labels
break scanLoop;
}
case AMP:
this.state = S_ENTITY;
this.entityReturnState = S_TEXT;
if (handler !== undefined) {
this.text += chunk.slice(start, this.prevI);
}
forbiddenState = FORBIDDEN_START;
// eslint-disable-next-line no-labels
break scanLoop;
case CLOSE_BRACKET:
switch (forbiddenState) {
case FORBIDDEN_START:
forbiddenState = FORBIDDEN_BRACKET;
break;
case FORBIDDEN_BRACKET:
forbiddenState = FORBIDDEN_BRACKET_BRACKET;
break;
case FORBIDDEN_BRACKET_BRACKET:
break;
default:
throw new Error("impossible state");
}
break;
case GREATER:
if (forbiddenState === FORBIDDEN_BRACKET_BRACKET) {
this.fail("the string \"]]>\" is disallowed in char data.");
}
forbiddenState = FORBIDDEN_START;
break;
case NL_LIKE:
if (handler !== undefined) {
this.text += `${chunk.slice(start, this.prevI)}\n`;
}
start = this.i;
forbiddenState = FORBIDDEN_START;
break;
case EOC:
if (handler !== undefined) {
this.text += chunk.slice(start);
}
// eslint-disable-next-line no-labels
break scanLoop;
default:
forbiddenState = FORBIDDEN_START;
}
}
this.forbiddenState = forbiddenState;
}
private handleTextOutsideRoot(): void {
// This is essentially a specialized version of captureTo which is optimized
// for a specialized task. We keep track of the presence of non-space
// characters in the text since these are errors when appearing outside the
// document root element.
let { i: start } = this;
const { chunk, textHandler: handler } = this;
let nonSpace = false;
// eslint-disable-next-line no-labels, no-restricted-syntax
outRootLoop:
// eslint-disable-next-line no-constant-condition
while (true) {
const code = this.getCode();
switch (code) {
case LESS: {
this.state = S_OPEN_WAKA;
if (handler !== undefined) {
const { text } = this;
const slice = chunk.slice(start, this.prevI);
if (text.length !== 0) {
handler(text + slice);
this.text = "";
}
else if (slice.length !== 0) {
handler(slice);
}
}
// eslint-disable-next-line no-labels
break outRootLoop;
}
case AMP:
this.state = S_ENTITY;
this.entityReturnState = S_TEXT;
if (handler !== undefined) {
this.text += chunk.slice(start, this.prevI);
}
nonSpace = true;
// eslint-disable-next-line no-labels
break outRootLoop;
case NL_LIKE:
if (handler !== undefined) {
this.text += `${chunk.slice(start, this.prevI)}\n`;
}
start = this.i;
break;
case EOC:
if (handler !== undefined) {
this.text += chunk.slice(start);
}
// eslint-disable-next-line no-labels
break outRootLoop;
default:
if (!isS(code)) {
nonSpace = true;
}
}
}
if (!nonSpace) {
return;
}
// We use the reportedTextBeforeRoot and reportedTextAfterRoot flags
// to avoid reporting errors for every single character that is out of
// place.
if (!this.sawRoot && !this.reportedTextBeforeRoot) {
this.fail("text data outside of root node.");
this.reportedTextBeforeRoot = true;
}
if (this.closedRoot && !this.reportedTextAfterRoot) {
this.fail("text data outside of root node.");
this.reportedTextAfterRoot = true;
}
}
private pushAttribNS(name: string, value: string): void {
const { prefix, local } = this.qname(name);
const attr = { name, prefix, local, value };
this.attribList.push(attr);
this.attributeHandler?.(attr as AttributeEventForOptions<O>);
if (prefix === "xmlns") {
const trimmed = value.trim();
if (this.currentXMLVersion === "1.0" && trimmed === "") {
this.fail("invalid attempt to undefine prefix in XML 1.0");
}
this.topNS![local] = trimmed;
nsPairCheck(this, local, trimmed);
}
else if (name === "xmlns") {
const trimmed = value.trim();
this.topNS![""] = trimmed;
nsPairCheck(this, "", trimmed);
}
}
private pushAttribPlain(name: string, value: string): void {
const attr = { name, value };
this.attribList.push(attr);
this.attributeHandler?.(attr as AttributeEventForOptions<O>);
}
/**
* End parsing. This performs final well-formedness checks and resets the
* parser to a clean state.
*
* @returns this
*/
private end(): this {
if (!this.sawRoot) {
this.fail("document must contain a root element.");
}
const { tags } = this;
while (tags.length > 0) {
const tag = tags.pop()!;
this.fail(`unclosed tag: ${tag.name}`);
}
if ((this.state !== S_BEGIN) && (this.state !== S_TEXT)) {
this.fail("unexpected end.");
}
const { text } = this;
if (text.length !== 0) {
this.textHandler?.(text);
this.text = "";
}
this._closed = true;
this.endHandler?.();
this._init();
return this;
}
/**
* Resolve a namespace prefix.
*
* @param prefix The prefix to resolve.
*
* @returns The namespace URI or ``undefined`` if the prefix is not defined.
*/
resolve(prefix: string): string | undefined {
let uri = this.topNS![prefix];
if (uri !== undefined) {
return uri;
}
const { tags } = this;
for (let index = tags.length - 1; index >= 0; index--) {
uri = tags[index]!.ns![prefix];
if (uri !== undefined) {
return uri;
}
}
uri = this.ns[prefix];
if (uri !== undefined) {
return uri;
}
return this.opt.resolvePrefix?.(prefix);
}
/**
* Parse a qname into its prefix and local name parts.
*
* @param name The name to parse
*
* @returns
*/
private qname(name: string): { prefix: string; local: string } {
// This is faster than using name.split(":").
const colon = name.indexOf(":");
if (colon === -1) {
return { prefix: "", local: name };
}
const local = name.slice(colon + 1);
const prefix = name.slice(0, colon);
if (prefix === "" || local === "" || local.includes(":")) {
this.fail(`malformed name: ${name}.`);
}
return { prefix, local };
}
private processAttribsNS(): void {
const { attribList } = this;
const tag = this.tag!;
{
// add namespace info to tag
const { prefix, local } = this.qname(tag.name);
tag.prefix = prefix;
tag.local = local;
const uri = tag.uri = this.resolve(prefix) ?? "";
if (prefix !== "") {
if (prefix === "xmlns") {
this.fail("tags may not have \"xmlns\" as prefix.");
}
if (uri === "") {
this.fail(`unbound namespace prefix: ${JSON.stringify(prefix)}.`);
tag.uri = prefix;
}
}
}
if (attribList.length === 0) {
return;
}
const { attributes } = tag;
const seen = new Set();
// Note: do not apply default ns to attributes:
// http://www.w3.org/TR/REC-xml-names/#defaulting
for (const attr of attribList as SaxesAttributeNSIncomplete[]) {
const { name, prefix, local } = attr;
let uri;
let eqname;
if (prefix === "") {
uri = name === "xmlns" ? XMLNS_NAMESPACE : "";
eqname = name;
}
else {
uri = this.resolve(prefix);
// if there's any attributes with an undefined namespace,
// then fail on them now.
if (uri === undefined) {
this.fail(`unbound namespace prefix: ${JSON.stringify(prefix)}.`);
uri = prefix;
}
eqname = `{${uri}}${local}`;
}
if (seen.has(eqname)) {
this.fail(`duplicate attribute: ${eqname}.`);
}
seen.add(eqname);
attr.uri = uri;
attributes[name] = attr;
}
this.attribList = [];
}
private processAttribsPlain(): void {
const { attribList } = this;
// eslint-disable-next-line prefer-destructuring
const attributes = this.tag!.attributes;
for (const { name, value } of attribList) {
if (attributes[name] !== undefined) {
this.fail(`duplicate attribute: ${name}.`);
}
attributes[name] = value;
}
this.attribList = [];
}
/**
* Handle a complete open tag. This parser code calls this once it has seen
* the whole tag. This method checks for well-formeness and then emits
* ``onopentag``.
*/
private openTag(): void {
this.processAttribs();
const { tags } = this;
const tag = this.tag as SaxesTag;
tag.isSelfClosing = false;
// There cannot be any pending text here due to the onopentagstart that was
// necessarily emitted before we get here. So we do not check text.
this.openTagHandler?.(tag as TagForOptions<O>);
tags.push(tag);
this.state = S_TEXT;
this.name = "";
}
/**
* Handle a complete self-closing tag. This parser code calls this once it has
* seen the whole tag. This method checks for well-formeness and then emits
* ``onopentag`` and ``onclosetag``.
*/
private openSelfClosingTag(): void {
this.processAttribs();
const { tags } = this;
const tag = this.tag as SaxesTag;
tag.isSelfClosing = true;
// There cannot be any pending text here due to the onopentagstart that was
// necessarily emitted before we get here. So we do not check text.
this.openTagHandler?.(tag as TagForOptions<O>);
this.closeTagHandler?.(tag as TagForOptions<O>);
const top = this.tag = tags[tags.length - 1] ?? null;
if (top === null) {
this.closedRoot = true;
}
this.state = S_TEXT;
this.name = "";
}
/**
* Handle a complete close tag. This parser code calls this once it has seen
* the whole tag. This method checks for well-formeness and then emits
* ``onclosetag``.
*/
private closeTag(): void {
const { tags, name } = this;
// Our state after this will be S_TEXT, no matter what, and we can clear
// tagName now.
this.state = S_TEXT;
this.name = "";
if (name === "") {
this.fail("weird empty close tag.");
this.text += "</>";
return;
}
const handler = this.closeTagHandler;
let l = tags.length;
while (l-- > 0) {
const tag = this.tag = tags.pop() as SaxesTag;
this.topNS = tag.ns!;
handler?.(tag as TagForOptions<O>);
if (tag.name === name) {
break;
}
this.fail("unexpected close tag.");
}
if (l === 0) {
this.closedRoot = true;
}
else if (l < 0) {
this.fail(`unmatched closing tag: ${name}.`);
this.text += `</${name}>`;
}
}
/**
* Resolves an entity. Makes any necessary well-formedness checks.
*
* @param entity The entity to resolve.
*
* @returns The parsed entity.
*/
private parseEntity(entity: string): string {
// startsWith would be significantly slower for this test.
if (entity[0] !== "#") {
const defined = this.ENTITIES[entity];
if (defined !== undefined) {
return defined;
}
this.fail(this.isName(entity) ? "undefined entity." :
"disallowed character in entity name.");
return `&${entity};`;
}
let num = NaN;
if (entity[1] === "x" && /^#x[0-9a-f]+$/i.test(entity)) {
num = parseInt(entity.slice(2), 16);
}
else if (/^#[0-9]+$/.test(entity)) {
num = parseInt(entity.slice(1), 10);
}
// The character reference is required to match the CHAR production.
if (!this.isChar(num)) {
this.fail("malformed character entity.");
return `&${entity};`;
}
return String.fromCodePoint(num);
}
} |
1,151 | fn(parser: SaxesParser): void {
for (let ix = 0; ix < xml.length; ix += 2) {
parser.write(xml.slice(ix, ix + 2));
}
parser.close();
} | class SaxesParser<O extends SaxesOptions = {}> {
private readonly fragmentOpt: boolean;
private readonly xmlnsOpt: boolean;
private readonly trackPosition: boolean;
private readonly fileName?: string;
private readonly nameStartCheck: (c: number) => boolean;
private readonly nameCheck: (c: number) => boolean;
private readonly isName: (name: string) => boolean;
private readonly ns!: Record<string, string>;
private openWakaBang!: string;
private text!: string;
private name!: string;
private piTarget!: string;
private entity!: string;
private q!: null | number;
private tags!: SaxesTagIncomplete[];
private tag!: SaxesTagIncomplete | null;
private topNS!: Record<string, string> | null;
private chunk!: string;
private chunkPosition!: number;
private i!: number;
//
// We use prevI to allow "ungetting" the previously read code point. Note
// however, that it is not safe to unget everything and anything. In
// particular ungetting EOL characters will screw positioning up.
//
// Practically, you must not unget a code which has any side effect beyond
// updating ``this.i`` and ``this.prevI``. Only EOL codes have such side
// effects.
//
private prevI!: number;
private carriedFromPrevious?: string;
private forbiddenState!: number;
private attribList!: (SaxesAttributeNSIncomplete | SaxesAttributePlain)[];
private state!: number;
private reportedTextBeforeRoot!: boolean;
private reportedTextAfterRoot!: boolean;
private closedRoot!: boolean;
private sawRoot!: boolean;
private xmlDeclPossible!: boolean;
private xmlDeclExpects!: string[];
private entityReturnState?: number;
private processAttribs!: (this: this) => void;
private positionAtNewLine!: number;
private doctype!: boolean;
private getCode!: () => number;
private isChar!: (c: number) => boolean;
private pushAttrib!: (name: string, value: string) => void;
private _closed!: boolean;
private currentXMLVersion!: string;
private readonly stateTable: ((this: SaxesParser<O>) => void)[];
private xmldeclHandler?: XMLDeclHandler;
private textHandler?: TextHandler;
private piHandler?: PIHandler;
private doctypeHandler?: DoctypeHandler;
private commentHandler?: CommentHandler;
private openTagStartHandler?: OpenTagStartHandler<O>;
private openTagHandler?: OpenTagHandler<O>;
private closeTagHandler?: CloseTagHandler<O>;
private cdataHandler?: CDataHandler;
private errorHandler?: ErrorHandler;
private endHandler?: EndHandler;
private readyHandler?: ReadyHandler;
private attributeHandler?: AttributeHandler<O>;
/**
* Indicates whether or not the parser is closed. If ``true``, wait for
* the ``ready`` event to write again.
*/
get closed(): boolean {
return this._closed;
}
readonly opt: SaxesOptions;
/**
* The XML declaration for this document.
*/
xmlDecl!: XMLDecl;
/**
* The line number of the next character to be read by the parser. This field
* is one-based. (The first line is numbered 1.)
*/
line!: number;
/**
* The column number of the next character to be read by the parser. *
* This field is zero-based. (The first column is 0.)
*
* This field counts columns by *Unicode character*. Note that this *can*
* be different from the index of the character in a JavaScript string due
* to how JavaScript handles astral plane characters.
*
* See [[columnIndex]] for a number that corresponds to the JavaScript index.
*/
column!: number;
/**
* A map of entity name to expansion.
*/
ENTITIES!: Record<string, string>;
/**
* @param opt The parser options.
*/
constructor(opt?: O) {
this.opt = opt ?? {};
this.fragmentOpt = !!(this.opt.fragment as boolean);
const xmlnsOpt = this.xmlnsOpt = !!(this.opt.xmlns as boolean);
this.trackPosition = this.opt.position !== false;
this.fileName = this.opt.fileName;
if (xmlnsOpt) {
// This is the function we use to perform name checks on PIs and entities.
// When namespaces are used, colons are not allowed in PI target names or
// entity names. So the check depends on whether namespaces are used. See:
//
// https://www.w3.org/XML/xml-names-19990114-errata.html
// NE08
//
this.nameStartCheck = isNCNameStartChar;
this.nameCheck = isNCNameChar;
this.isName = isNCName;
// eslint-disable-next-line @typescript-eslint/unbound-method
this.processAttribs = this.processAttribsNS;
// eslint-disable-next-line @typescript-eslint/unbound-method
this.pushAttrib = this.pushAttribNS;
// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-assignment
this.ns = { __proto__: null as any, ...rootNS };
const additional = this.opt.additionalNamespaces;
if (additional != null) {
nsMappingCheck(this, additional);
Object.assign(this.ns, additional);
}
}
else {
this.nameStartCheck = isNameStartChar;
this.nameCheck = isNameChar;
this.isName = isName;
// eslint-disable-next-line @typescript-eslint/unbound-method
this.processAttribs = this.processAttribsPlain;
// eslint-disable-next-line @typescript-eslint/unbound-method
this.pushAttrib = this.pushAttribPlain;
}
//
// The order of the members in this table needs to correspond to the state
// numbers given to the states that correspond to the methods being recorded
// here.
//
this.stateTable = [
/* eslint-disable @typescript-eslint/unbound-method */
this.sBegin,
this.sBeginWhitespace,
this.sDoctype,
this.sDoctypeQuote,
this.sDTD,
this.sDTDQuoted,
this.sDTDOpenWaka,
this.sDTDOpenWakaBang,
this.sDTDComment,
this.sDTDCommentEnding,
this.sDTDCommentEnded,
this.sDTDPI,
this.sDTDPIEnding,
this.sText,
this.sEntity,
this.sOpenWaka,
this.sOpenWakaBang,
this.sComment,
this.sCommentEnding,
this.sCommentEnded,
this.sCData,
this.sCDataEnding,
this.sCDataEnding2,
this.sPIFirstChar,
this.sPIRest,
this.sPIBody,
this.sPIEnding,
this.sXMLDeclNameStart,
this.sXMLDeclName,
this.sXMLDeclEq,
this.sXMLDeclValueStart,
this.sXMLDeclValue,
this.sXMLDeclSeparator,
this.sXMLDeclEnding,
this.sOpenTag,
this.sOpenTagSlash,
this.sAttrib,
this.sAttribName,
this.sAttribNameSawWhite,
this.sAttribValue,
this.sAttribValueQuoted,
this.sAttribValueClosed,
this.sAttribValueUnquoted,
this.sCloseTag,
this.sCloseTagSawWhite,
/* eslint-enable @typescript-eslint/unbound-method */
];
this._init();
}
_init(): void {
this.openWakaBang = "";
this.text = "";
this.name = "";
this.piTarget = "";
this.entity = "";
this.q = null;
this.tags = [];
this.tag = null;
this.topNS = null;
this.chunk = "";
this.chunkPosition = 0;
this.i = 0;
this.prevI = 0;
this.carriedFromPrevious = undefined;
this.forbiddenState = FORBIDDEN_START;
this.attribList = [];
// The logic is organized so as to minimize the need to check
// this.opt.fragment while parsing.
const { fragmentOpt } = this;
this.state = fragmentOpt ? S_TEXT : S_BEGIN;
// We want these to be all true if we are dealing with a fragment.
this.reportedTextBeforeRoot = this.reportedTextAfterRoot = this.closedRoot =
this.sawRoot = fragmentOpt;
// An XML declaration is intially possible only when parsing whole
// documents.
this.xmlDeclPossible = !fragmentOpt;
this.xmlDeclExpects = ["version"];
this.entityReturnState = undefined;
let { defaultXMLVersion } = this.opt;
if (defaultXMLVersion === undefined) {
if (this.opt.forceXMLVersion === true) {
throw new Error("forceXMLVersion set but defaultXMLVersion is not set");
}
defaultXMLVersion = "1.0";
}
this.setXMLVersion(defaultXMLVersion);
this.positionAtNewLine = 0;
this.doctype = false;
this._closed = false;
this.xmlDecl = {
version: undefined,
encoding: undefined,
standalone: undefined,
};
this.line = 1;
this.column = 0;
this.ENTITIES = Object.create(XML_ENTITIES) as Record<string, string>;
this.readyHandler?.();
}
/**
* The stream position the parser is currently looking at. This field is
* zero-based.
*
* This field is not based on counting Unicode characters but is to be
* interpreted as a plain index into a JavaScript string.
*/
get position(): number {
return this.chunkPosition + this.i;
}
/**
* The column number of the next character to be read by the parser. *
* This field is zero-based. (The first column in a line is 0.)
*
* This field reports the index at which the next character would be in the
* line if the line were represented as a JavaScript string. Note that this
* *can* be different to a count based on the number of *Unicode characters*
* due to how JavaScript handles astral plane characters.
*
* See [[column]] for a number that corresponds to a count of Unicode
* characters.
*/
get columnIndex(): number {
return this.position - this.positionAtNewLine;
}
/**
* Set an event listener on an event. The parser supports one handler per
* event type. If you try to set an event handler over an existing handler,
* the old handler is silently overwritten.
*
* @param name The event to listen to.
*
* @param handler The handler to set.
*/
on<N extends EventName>(name: N, handler: EventNameToHandler<O, N>): void {
// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-member-access
(this as any)[EVENT_NAME_TO_HANDLER_NAME[name]] = handler;
}
/**
* Unset an event handler.
*
* @parma name The event to stop listening to.
*/
off(name: EventName): void {
// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-member-access
(this as any)[EVENT_NAME_TO_HANDLER_NAME[name]] = undefined;
}
/**
* Make an error object. The error object will have a message that contains
* the ``fileName`` option passed at the creation of the parser. If position
* tracking was turned on, it will also have line and column number
* information.
*
* @param message The message describing the error to report.
*
* @returns An error object with a properly formatted message.
*/
makeError(message: string): Error {
let msg = this.fileName ?? "";
if (this.trackPosition) {
if (msg.length > 0) {
msg += ":";
}
msg += `${this.line}:${this.column}`;
}
if (msg.length > 0) {
msg += ": ";
}
return new Error(msg + message);
}
/**
* Report a parsing error. This method is made public so that client code may
* check for issues that are outside the scope of this project and can report
* errors.
*
* @param message The error to report.
*
* @returns this
*/
fail(message: string): this {
const err = this.makeError(message);
const handler = this.errorHandler;
if (handler === undefined) {
throw err;
}
else {
handler(err);
}
return this;
}
/**
* Write a XML data to the parser.
*
* @param chunk The XML data to write.
*
* @returns this
*/
// We do need object for the type here. Yes, it often causes problems
// but not in this case.
write(chunk: string | object | null): this {
if (this.closed) {
return this.fail("cannot write after close; assign an onready handler.");
}
let end = false;
if (chunk === null) {
// We cannot return immediately because carriedFromPrevious may need
// processing.
end = true;
chunk = "";
}
else if (typeof chunk === "object") {
chunk = chunk.toString();
}
// We checked if performing a pre-decomposition of the string into an array
// of single complete characters (``Array.from(chunk)``) would be faster
// than the current repeated calls to ``charCodeAt``. As of August 2018, it
// isn't. (There may be Node-specific code that would perform faster than
// ``Array.from`` but don't want to be dependent on Node.)
if (this.carriedFromPrevious !== undefined) {
// The previous chunk had char we must carry over.
chunk = `${this.carriedFromPrevious}${chunk}`;
this.carriedFromPrevious = undefined;
}
let limit = chunk.length;
const lastCode = chunk.charCodeAt(limit - 1);
if (!end &&
// A trailing CR or surrogate must be carried over to the next
// chunk.
(lastCode === CR || (lastCode >= 0xD800 && lastCode <= 0xDBFF))) {
// The chunk ends with a character that must be carried over. We cannot
// know how to handle it until we get the next chunk or the end of the
// stream. So save it for later.
this.carriedFromPrevious = chunk[limit - 1];
limit--;
chunk = chunk.slice(0, limit);
}
const { stateTable } = this;
this.chunk = chunk;
this.i = 0;
while (this.i < limit) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-argument
stateTable[this.state].call(this as any);
}
this.chunkPosition += limit;
return end ? this.end() : this;
}
/**
* Close the current stream. Perform final well-formedness checks and reset
* the parser tstate.
*
* @returns this
*/
close(): this {
return this.write(null);
}
/**
* Get a single code point out of the current chunk. This updates the current
* position if we do position tracking.
*
* This is the algorithm to use for XML 1.0.
*
* @returns The character read.
*/
private getCode10(): number {
const { chunk, i } = this;
this.prevI = i;
// Yes, we do this instead of doing this.i++. Doing it this way, we do not
// read this.i again, which is a bit faster.
this.i = i + 1;
if (i >= chunk.length) {
return EOC;
}
// Using charCodeAt and handling the surrogates ourselves is faster
// than using codePointAt.
const code = chunk.charCodeAt(i);
this.column++;
if (code < 0xD800) {
if (code >= SPACE || code === TAB) {
return code;
}
switch (code) {
case NL:
this.line++;
this.column = 0;
this.positionAtNewLine = this.position;
return NL;
case CR:
// We may get NaN if we read past the end of the chunk, which is fine.
if (chunk.charCodeAt(i + 1) === NL) {
// A \r\n sequence is converted to \n so we have to skip over the
// next character. We already know it has a size of 1 so ++ is fine
// here.
this.i = i + 2;
}
// Otherwise, a \r is just converted to \n, so we don't have to skip
// ahead.
// In either case, \r becomes \n.
this.line++;
this.column = 0;
this.positionAtNewLine = this.position;
return NL_LIKE;
default:
// If we get here, then code < SPACE and it is not NL CR or TAB.
this.fail("disallowed character.");
return code;
}
}
if (code > 0xDBFF) {
// This is a specialized version of isChar10 that takes into account
// that in this context code > 0xDBFF and code <= 0xFFFF. So it does not
// test cases that don't need testing.
if (!(code >= 0xE000 && code <= 0xFFFD)) {
this.fail("disallowed character.");
}
return code;
}
const final = 0x10000 + ((code - 0xD800) * 0x400) +
(chunk.charCodeAt(i + 1) - 0xDC00);
this.i = i + 2;
// This is a specialized version of isChar10 that takes into account that in
// this context necessarily final >= 0x10000.
if (final > 0x10FFFF) {
this.fail("disallowed character.");
}
return final;
}
/**
* Get a single code point out of the current chunk. This updates the current
* position if we do position tracking.
*
* This is the algorithm to use for XML 1.1.
*
* @returns {number} The character read.
*/
private getCode11(): number {
const { chunk, i } = this;
this.prevI = i;
// Yes, we do this instead of doing this.i++. Doing it this way, we do not
// read this.i again, which is a bit faster.
this.i = i + 1;
if (i >= chunk.length) {
return EOC;
}
// Using charCodeAt and handling the surrogates ourselves is faster
// than using codePointAt.
const code = chunk.charCodeAt(i);
this.column++;
if (code < 0xD800) {
if ((code > 0x1F && code < 0x7F) || (code > 0x9F && code !== LS) ||
code === TAB) {
return code;
}
switch (code) {
case NL: // 0xA
this.line++;
this.column = 0;
this.positionAtNewLine = this.position;
return NL;
case CR: { // 0xD
// We may get NaN if we read past the end of the chunk, which is
// fine.
const next = chunk.charCodeAt(i + 1);
if (next === NL || next === NEL) {
// A CR NL or CR NEL sequence is converted to NL so we have to skip
// over the next character. We already know it has a size of 1.
this.i = i + 2;
}
// Otherwise, a CR is just converted to NL, no skip.
}
/* yes, fall through */
case NEL: // 0x85
case LS: // Ox2028
this.line++;
this.column = 0;
this.positionAtNewLine = this.position;
return NL_LIKE;
default:
this.fail("disallowed character.");
return code;
}
}
if (code > 0xDBFF) {
// This is a specialized version of isCharAndNotRestricted that takes into
// account that in this context code > 0xDBFF and code <= 0xFFFF. So it
// does not test cases that don't need testing.
if (!(code >= 0xE000 && code <= 0xFFFD)) {
this.fail("disallowed character.");
}
return code;
}
const final = 0x10000 + ((code - 0xD800) * 0x400) +
(chunk.charCodeAt(i + 1) - 0xDC00);
this.i = i + 2;
// This is a specialized version of isCharAndNotRestricted that takes into
// account that in this context necessarily final >= 0x10000.
if (final > 0x10FFFF) {
this.fail("disallowed character.");
}
return final;
}
/**
* Like ``getCode`` but with the return value normalized so that ``NL`` is
* returned for ``NL_LIKE``.
*/
private getCodeNorm(): number {
const c = this.getCode();
return c === NL_LIKE ? NL : c;
}
private unget(): void {
this.i = this.prevI;
this.column--;
}
/**
* Capture characters into a buffer until encountering one of a set of
* characters.
*
* @param chars An array of codepoints. Encountering a character in the array
* ends the capture. (``chars`` may safely contain ``NL``.)
*
* @return The character code that made the capture end, or ``EOC`` if we hit
* the end of the chunk. The return value cannot be NL_LIKE: NL is returned
* instead.
*/
private captureTo(chars: number[]): number {
let { i: start } = this;
const { chunk } = this;
// eslint-disable-next-line no-constant-condition
while (true) {
const c = this.getCode();
const isNLLike = c === NL_LIKE;
const final = isNLLike ? NL : c;
if (final === EOC || chars.includes(final)) {
this.text += chunk.slice(start, this.prevI);
return final;
}
if (isNLLike) {
this.text += `${chunk.slice(start, this.prevI)}\n`;
start = this.i;
}
}
}
/**
* Capture characters into a buffer until encountering a character.
*
* @param char The codepoint that ends the capture. **NOTE ``char`` MAY NOT
* CONTAIN ``NL``.** Passing ``NL`` will result in buggy behavior.
*
* @return ``true`` if we ran into the character. Otherwise, we ran into the
* end of the current chunk.
*/
private captureToChar(char: number): boolean {
let { i: start } = this;
const { chunk } = this;
// eslint-disable-next-line no-constant-condition
while (true) {
let c = this.getCode();
switch (c) {
case NL_LIKE:
this.text += `${chunk.slice(start, this.prevI)}\n`;
start = this.i;
c = NL;
break;
case EOC:
this.text += chunk.slice(start);
return false;
default:
}
if (c === char) {
this.text += chunk.slice(start, this.prevI);
return true;
}
}
}
/**
* Capture characters that satisfy ``isNameChar`` into the ``name`` field of
* this parser.
*
* @return The character code that made the test fail, or ``EOC`` if we hit
* the end of the chunk. The return value cannot be NL_LIKE: NL is returned
* instead.
*/
private captureNameChars(): number {
const { chunk, i: start } = this;
// eslint-disable-next-line no-constant-condition
while (true) {
const c = this.getCode();
if (c === EOC) {
this.name += chunk.slice(start);
return EOC;
}
// NL is not a name char so we don't have to test specifically for it.
if (!isNameChar(c)) {
this.name += chunk.slice(start, this.prevI);
return c === NL_LIKE ? NL : c;
}
}
}
/**
* Skip white spaces.
*
* @return The character that ended the skip, or ``EOC`` if we hit
* the end of the chunk. The return value cannot be NL_LIKE: NL is returned
* instead.
*/
private skipSpaces(): number {
// eslint-disable-next-line no-constant-condition
while (true) {
const c = this.getCodeNorm();
if (c === EOC || !isS(c)) {
return c;
}
}
}
private setXMLVersion(version: string): void {
this.currentXMLVersion = version;
/* eslint-disable @typescript-eslint/unbound-method */
if (version === "1.0") {
this.isChar = isChar10;
this.getCode = this.getCode10;
}
else {
this.isChar = isChar11;
this.getCode = this.getCode11;
}
/* eslint-enable @typescript-eslint/unbound-method */
}
// STATE ENGINE METHODS
// This needs to be a state separate from S_BEGIN_WHITESPACE because we want
// to be sure never to come back to this state later.
private sBegin(): void {
// We are essentially peeking at the first character of the chunk. Since
// S_BEGIN can be in effect only when we start working on the first chunk,
// the index at which we must look is necessarily 0. Note also that the
// following test does not depend on decoding surrogates.
// If the initial character is 0xFEFF, ignore it.
if (this.chunk.charCodeAt(0) === 0xFEFF) {
this.i++;
this.column++;
}
this.state = S_BEGIN_WHITESPACE;
}
private sBeginWhitespace(): void {
// We need to know whether we've encountered spaces or not because as soon
// as we run into a space, an XML declaration is no longer possible. Rather
// than slow down skipSpaces even in places where we don't care whether it
// skipped anything or not, we check whether prevI is equal to the value of
// i from before we skip spaces.
const iBefore = this.i;
const c = this.skipSpaces();
if (this.prevI !== iBefore) {
this.xmlDeclPossible = false;
}
switch (c) {
case LESS:
this.state = S_OPEN_WAKA;
// We could naively call closeText but in this state, it is not normal
// to have text be filled with any data.
if (this.text.length !== 0) {
throw new Error("no-empty text at start");
}
break;
case EOC:
break;
default:
this.unget();
this.state = S_TEXT;
this.xmlDeclPossible = false;
}
}
private sDoctype(): void {
const c = this.captureTo(DOCTYPE_TERMINATOR);
switch (c) {
case GREATER: {
this.doctypeHandler?.(this.text);
this.text = "";
this.state = S_TEXT;
this.doctype = true; // just remember that we saw it.
break;
}
case EOC:
break;
default:
this.text += String.fromCodePoint(c);
if (c === OPEN_BRACKET) {
this.state = S_DTD;
}
else if (isQuote(c)) {
this.state = S_DOCTYPE_QUOTE;
this.q = c;
}
}
}
private sDoctypeQuote(): void {
const q = this.q!;
if (this.captureToChar(q)) {
this.text += String.fromCodePoint(q);
this.q = null;
this.state = S_DOCTYPE;
}
}
private sDTD(): void {
const c = this.captureTo(DTD_TERMINATOR);
if (c === EOC) {
return;
}
this.text += String.fromCodePoint(c);
if (c === CLOSE_BRACKET) {
this.state = S_DOCTYPE;
}
else if (c === LESS) {
this.state = S_DTD_OPEN_WAKA;
}
else if (isQuote(c)) {
this.state = S_DTD_QUOTED;
this.q = c;
}
}
private sDTDQuoted(): void {
const q = this.q!;
if (this.captureToChar(q)) {
this.text += String.fromCodePoint(q);
this.state = S_DTD;
this.q = null;
}
}
private sDTDOpenWaka(): void {
const c = this.getCodeNorm();
this.text += String.fromCodePoint(c);
switch (c) {
case BANG:
this.state = S_DTD_OPEN_WAKA_BANG;
this.openWakaBang = "";
break;
case QUESTION:
this.state = S_DTD_PI;
break;
default:
this.state = S_DTD;
}
}
private sDTDOpenWakaBang(): void {
const char = String.fromCodePoint(this.getCodeNorm());
const owb = this.openWakaBang += char;
this.text += char;
if (owb !== "-") {
this.state = owb === "--" ? S_DTD_COMMENT : S_DTD;
this.openWakaBang = "";
}
}
private sDTDComment(): void {
if (this.captureToChar(MINUS)) {
this.text += "-";
this.state = S_DTD_COMMENT_ENDING;
}
}
private sDTDCommentEnding(): void {
const c = this.getCodeNorm();
this.text += String.fromCodePoint(c);
this.state = c === MINUS ? S_DTD_COMMENT_ENDED : S_DTD_COMMENT;
}
private sDTDCommentEnded(): void {
const c = this.getCodeNorm();
this.text += String.fromCodePoint(c);
if (c === GREATER) {
this.state = S_DTD;
}
else {
this.fail("malformed comment.");
// <!-- blah -- bloo --> will be recorded as
// a comment of " blah -- bloo "
this.state = S_DTD_COMMENT;
}
}
private sDTDPI(): void {
if (this.captureToChar(QUESTION)) {
this.text += "?";
this.state = S_DTD_PI_ENDING;
}
}
private sDTDPIEnding(): void {
const c = this.getCodeNorm();
this.text += String.fromCodePoint(c);
if (c === GREATER) {
this.state = S_DTD;
}
}
private sText(): void {
//
// We did try a version of saxes where the S_TEXT state was split in two
// states: one for text inside the root element, and one for text
// outside. This was avoiding having to test this.tags.length to decide
// what implementation to actually use.
//
// Peformance testing on gigabyte-size files did not show any advantage to
// using the two states solution instead of the current one. Conversely, it
// made the code a bit more complicated elsewhere. For instance, a comment
// can appear before the root element so when a comment ended it was
// necessary to determine whether to return to the S_TEXT state or to the
// new text-outside-root state.
//
if (this.tags.length !== 0) {
this.handleTextInRoot();
}
else {
this.handleTextOutsideRoot();
}
}
private sEntity(): void {
// This is essentially a specialized version of captureToChar(SEMICOLON...)
let { i: start } = this;
const { chunk } = this;
// eslint-disable-next-line no-labels, no-restricted-syntax
loop:
// eslint-disable-next-line no-constant-condition
while (true) {
switch (this.getCode()) {
case NL_LIKE:
this.entity += `${chunk.slice(start, this.prevI)}\n`;
start = this.i;
break;
case SEMICOLON: {
const { entityReturnState } = this;
const entity = this.entity + chunk.slice(start, this.prevI);
this.state = entityReturnState!;
let parsed: string;
if (entity === "") {
this.fail("empty entity name.");
parsed = "&;";
}
else {
parsed = this.parseEntity(entity);
this.entity = "";
}
if (entityReturnState !== S_TEXT || this.textHandler !== undefined) {
this.text += parsed;
}
// eslint-disable-next-line no-labels
break loop;
}
case EOC:
this.entity += chunk.slice(start);
// eslint-disable-next-line no-labels
break loop;
default:
}
}
}
private sOpenWaka(): void {
// Reminder: a state handler is called with at least one character
// available in the current chunk. So the first call to get code inside of
// a state handler cannot return ``EOC``. That's why we don't test
// for it.
const c = this.getCode();
// either a /, ?, !, or text is coming next.
if (isNameStartChar(c)) {
this.state = S_OPEN_TAG;
this.unget();
this.xmlDeclPossible = false;
}
else {
switch (c) {
case FORWARD_SLASH:
this.state = S_CLOSE_TAG;
this.xmlDeclPossible = false;
break;
case BANG:
this.state = S_OPEN_WAKA_BANG;
this.openWakaBang = "";
this.xmlDeclPossible = false;
break;
case QUESTION:
this.state = S_PI_FIRST_CHAR;
break;
default:
this.fail("disallowed character in tag name");
this.state = S_TEXT;
this.xmlDeclPossible = false;
}
}
}
private sOpenWakaBang(): void {
this.openWakaBang += String.fromCodePoint(this.getCodeNorm());
switch (this.openWakaBang) {
case "[CDATA[":
if (!this.sawRoot && !this.reportedTextBeforeRoot) {
this.fail("text data outside of root node.");
this.reportedTextBeforeRoot = true;
}
if (this.closedRoot && !this.reportedTextAfterRoot) {
this.fail("text data outside of root node.");
this.reportedTextAfterRoot = true;
}
this.state = S_CDATA;
this.openWakaBang = "";
break;
case "--":
this.state = S_COMMENT;
this.openWakaBang = "";
break;
case "DOCTYPE":
this.state = S_DOCTYPE;
if (this.doctype || this.sawRoot) {
this.fail("inappropriately located doctype declaration.");
}
this.openWakaBang = "";
break;
default:
// 7 happens to be the maximum length of the string that can possibly
// match one of the cases above.
if (this.openWakaBang.length >= 7) {
this.fail("incorrect syntax.");
}
}
}
private sComment(): void {
if (this.captureToChar(MINUS)) {
this.state = S_COMMENT_ENDING;
}
}
private sCommentEnding(): void {
const c = this.getCodeNorm();
if (c === MINUS) {
this.state = S_COMMENT_ENDED;
this.commentHandler?.(this.text);
this.text = "";
}
else {
this.text += `-${String.fromCodePoint(c)}`;
this.state = S_COMMENT;
}
}
private sCommentEnded(): void {
const c = this.getCodeNorm();
if (c !== GREATER) {
this.fail("malformed comment.");
// <!-- blah -- bloo --> will be recorded as
// a comment of " blah -- bloo "
this.text += `--${String.fromCodePoint(c)}`;
this.state = S_COMMENT;
}
else {
this.state = S_TEXT;
}
}
private sCData(): void {
if (this.captureToChar(CLOSE_BRACKET)) {
this.state = S_CDATA_ENDING;
}
}
private sCDataEnding(): void {
const c = this.getCodeNorm();
if (c === CLOSE_BRACKET) {
this.state = S_CDATA_ENDING_2;
}
else {
this.text += `]${String.fromCodePoint(c)}`;
this.state = S_CDATA;
}
}
private sCDataEnding2(): void {
const c = this.getCodeNorm();
switch (c) {
case GREATER: {
this.cdataHandler?.(this.text);
this.text = "";
this.state = S_TEXT;
break;
}
case CLOSE_BRACKET:
this.text += "]";
break;
default:
this.text += `]]${String.fromCodePoint(c)}`;
this.state = S_CDATA;
}
}
// We need this separate state to check the first character fo the pi target
// with this.nameStartCheck which allows less characters than this.nameCheck.
private sPIFirstChar(): void {
const c = this.getCodeNorm();
// This is first because in the case where the file is well-formed this is
// the branch taken. We optimize for well-formedness.
if (this.nameStartCheck(c)) {
this.piTarget += String.fromCodePoint(c);
this.state = S_PI_REST;
}
else if (c === QUESTION || isS(c)) {
this.fail("processing instruction without a target.");
this.state = c === QUESTION ? S_PI_ENDING : S_PI_BODY;
}
else {
this.fail("disallowed character in processing instruction name.");
this.piTarget += String.fromCodePoint(c);
this.state = S_PI_REST;
}
}
private sPIRest(): void {
// Capture characters into a piTarget while ``this.nameCheck`` run on the
// character read returns true.
const { chunk, i: start } = this;
// eslint-disable-next-line no-constant-condition
while (true) {
const c = this.getCodeNorm();
if (c === EOC) {
this.piTarget += chunk.slice(start);
return;
}
// NL cannot satisfy this.nameCheck so we don't have to test specifically
// for it.
if (!this.nameCheck(c)) {
this.piTarget += chunk.slice(start, this.prevI);
const isQuestion = c === QUESTION;
if (isQuestion || isS(c)) {
if (this.piTarget === "xml") {
if (!this.xmlDeclPossible) {
this.fail(
"an XML declaration must be at the start of the document.");
}
this.state = isQuestion ? S_XML_DECL_ENDING : S_XML_DECL_NAME_START;
}
else {
this.state = isQuestion ? S_PI_ENDING : S_PI_BODY;
}
}
else {
this.fail("disallowed character in processing instruction name.");
this.piTarget += String.fromCodePoint(c);
}
break;
}
}
}
private sPIBody(): void {
if (this.text.length === 0) {
const c = this.getCodeNorm();
if (c === QUESTION) {
this.state = S_PI_ENDING;
}
else if (!isS(c)) {
this.text = String.fromCodePoint(c);
}
}
// The question mark character is not valid inside any of the XML
// declaration name/value pairs.
else if (this.captureToChar(QUESTION)) {
this.state = S_PI_ENDING;
}
}
private sPIEnding(): void {
const c = this.getCodeNorm();
if (c === GREATER) {
const { piTarget } = this;
if (piTarget.toLowerCase() === "xml") {
this.fail(
"the XML declaration must appear at the start of the document.");
}
this.piHandler?.({
target: piTarget,
body: this.text,
});
this.piTarget = this.text = "";
this.state = S_TEXT;
}
else if (c === QUESTION) {
// We ran into ?? as part of a processing instruction. We initially took
// the first ? as a sign that the PI was ending, but it is not. So we have
// to add it to the body but we take the new ? as a sign that the PI is
// ending.
this.text += "?";
}
else {
this.text += `?${String.fromCodePoint(c)}`;
this.state = S_PI_BODY;
}
this.xmlDeclPossible = false;
}
private sXMLDeclNameStart(): void {
const c = this.skipSpaces();
// The question mark character is not valid inside any of the XML
// declaration name/value pairs.
if (c === QUESTION) {
// It is valid to go to S_XML_DECL_ENDING from this state.
this.state = S_XML_DECL_ENDING;
return;
}
if (c !== EOC) {
this.state = S_XML_DECL_NAME;
this.name = String.fromCodePoint(c);
}
}
private sXMLDeclName(): void {
const c = this.captureTo(XML_DECL_NAME_TERMINATOR);
// The question mark character is not valid inside any of the XML
// declaration name/value pairs.
if (c === QUESTION) {
this.state = S_XML_DECL_ENDING;
this.name += this.text;
this.text = "";
this.fail("XML declaration is incomplete.");
return;
}
if (!(isS(c) || c === EQUAL)) {
return;
}
this.name += this.text;
this.text = "";
if (!this.xmlDeclExpects.includes(this.name)) {
switch (this.name.length) {
case 0:
this.fail("did not expect any more name/value pairs.");
break;
case 1:
this.fail(`expected the name ${this.xmlDeclExpects[0]}.`);
break;
default:
this.fail(`expected one of ${this.xmlDeclExpects.join(", ")}`);
}
}
this.state = c === EQUAL ? S_XML_DECL_VALUE_START : S_XML_DECL_EQ;
}
private sXMLDeclEq(): void {
const c = this.getCodeNorm();
// The question mark character is not valid inside any of the XML
// declaration name/value pairs.
if (c === QUESTION) {
this.state = S_XML_DECL_ENDING;
this.fail("XML declaration is incomplete.");
return;
}
if (isS(c)) {
return;
}
if (c !== EQUAL) {
this.fail("value required.");
}
this.state = S_XML_DECL_VALUE_START;
}
private sXMLDeclValueStart(): void {
const c = this.getCodeNorm();
// The question mark character is not valid inside any of the XML
// declaration name/value pairs.
if (c === QUESTION) {
this.state = S_XML_DECL_ENDING;
this.fail("XML declaration is incomplete.");
return;
}
if (isS(c)) {
return;
}
if (!isQuote(c)) {
this.fail("value must be quoted.");
this.q = SPACE;
}
else {
this.q = c;
}
this.state = S_XML_DECL_VALUE;
}
private sXMLDeclValue(): void {
const c = this.captureTo([this.q!, QUESTION]);
// The question mark character is not valid inside any of the XML
// declaration name/value pairs.
if (c === QUESTION) {
this.state = S_XML_DECL_ENDING;
this.text = "";
this.fail("XML declaration is incomplete.");
return;
}
if (c === EOC) {
return;
}
const value = this.text;
this.text = "";
switch (this.name) {
case "version": {
this.xmlDeclExpects = ["encoding", "standalone"];
const version = value;
this.xmlDecl.version = version;
// This is the test specified by XML 1.0 but it is fine for XML 1.1.
if (!/^1\.[0-9]+$/.test(version)) {
this.fail("version number must match /^1\\.[0-9]+$/.");
}
// When forceXMLVersion is set, the XML declaration is ignored.
else if (!(this.opt.forceXMLVersion as boolean)) {
this.setXMLVersion(version);
}
break;
}
case "encoding":
if (!/^[A-Za-z][A-Za-z0-9._-]*$/.test(value)) {
this.fail("encoding value must match \
/^[A-Za-z0-9][A-Za-z0-9._-]*$/.");
}
this.xmlDeclExpects = ["standalone"];
this.xmlDecl.encoding = value;
break;
case "standalone":
if (value !== "yes" && value !== "no") {
this.fail("standalone value must match \"yes\" or \"no\".");
}
this.xmlDeclExpects = [];
this.xmlDecl.standalone = value;
break;
default:
// We don't need to raise an error here since we've already raised one
// when checking what name was expected.
}
this.name = "";
this.state = S_XML_DECL_SEPARATOR;
}
private sXMLDeclSeparator(): void {
const c = this.getCodeNorm();
// The question mark character is not valid inside any of the XML
// declaration name/value pairs.
if (c === QUESTION) {
// It is valid to go to S_XML_DECL_ENDING from this state.
this.state = S_XML_DECL_ENDING;
return;
}
if (!isS(c)) {
this.fail("whitespace required.");
this.unget();
}
this.state = S_XML_DECL_NAME_START;
}
private sXMLDeclEnding(): void {
const c = this.getCodeNorm();
if (c === GREATER) {
if (this.piTarget !== "xml") {
this.fail("processing instructions are not allowed before root.");
}
else if (this.name !== "version" &&
this.xmlDeclExpects.includes("version")) {
this.fail("XML declaration must contain a version.");
}
this.xmldeclHandler?.(this.xmlDecl);
this.name = "";
this.piTarget = this.text = "";
this.state = S_TEXT;
}
else {
// We got here because the previous character was a ?, but the question
// mark character is not valid inside any of the XML declaration
// name/value pairs.
this.fail(
"The character ? is disallowed anywhere in XML declarations.");
}
this.xmlDeclPossible = false;
}
private sOpenTag(): void {
const c = this.captureNameChars();
if (c === EOC) {
return;
}
const tag: SaxesTagIncomplete = this.tag = {
name: this.name,
attributes: Object.create(null) as Record<string, string>,
};
this.name = "";
if (this.xmlnsOpt) {
this.topNS = tag.ns = Object.create(null) as Record<string, string>;
}
this.openTagStartHandler?.(tag as StartTagForOptions<O>);
this.sawRoot = true;
if (!this.fragmentOpt && this.closedRoot) {
this.fail("documents may contain only one root.");
}
switch (c) {
case GREATER:
this.openTag();
break;
case FORWARD_SLASH:
this.state = S_OPEN_TAG_SLASH;
break;
default:
if (!isS(c)) {
this.fail("disallowed character in tag name.");
}
this.state = S_ATTRIB;
}
}
private sOpenTagSlash(): void {
if (this.getCode() === GREATER) {
this.openSelfClosingTag();
}
else {
this.fail("forward-slash in opening tag not followed by >.");
this.state = S_ATTRIB;
}
}
private sAttrib(): void {
const c = this.skipSpaces();
if (c === EOC) {
return;
}
if (isNameStartChar(c)) {
this.unget();
this.state = S_ATTRIB_NAME;
}
else if (c === GREATER) {
this.openTag();
}
else if (c === FORWARD_SLASH) {
this.state = S_OPEN_TAG_SLASH;
}
else {
this.fail("disallowed character in attribute name.");
}
}
private sAttribName(): void {
const c = this.captureNameChars();
if (c === EQUAL) {
this.state = S_ATTRIB_VALUE;
}
else if (isS(c)) {
this.state = S_ATTRIB_NAME_SAW_WHITE;
}
else if (c === GREATER) {
this.fail("attribute without value.");
this.pushAttrib(this.name, this.name);
this.name = this.text = "";
this.openTag();
}
else if (c !== EOC) {
this.fail("disallowed character in attribute name.");
}
}
private sAttribNameSawWhite(): void {
const c = this.skipSpaces();
switch (c) {
case EOC:
return;
case EQUAL:
this.state = S_ATTRIB_VALUE;
break;
default:
this.fail("attribute without value.");
// Should we do this???
// this.tag.attributes[this.name] = "";
this.text = "";
this.name = "";
if (c === GREATER) {
this.openTag();
}
else if (isNameStartChar(c)) {
this.unget();
this.state = S_ATTRIB_NAME;
}
else {
this.fail("disallowed character in attribute name.");
this.state = S_ATTRIB;
}
}
}
private sAttribValue(): void {
const c = this.getCodeNorm();
if (isQuote(c)) {
this.q = c;
this.state = S_ATTRIB_VALUE_QUOTED;
}
else if (!isS(c)) {
this.fail("unquoted attribute value.");
this.state = S_ATTRIB_VALUE_UNQUOTED;
this.unget();
}
}
private sAttribValueQuoted(): void {
// We deliberately do not use captureTo here. The specialized code we use
// here is faster than using captureTo.
const { q, chunk } = this;
let { i: start } = this;
// eslint-disable-next-line no-constant-condition
while (true) {
switch (this.getCode()) {
case q:
this.pushAttrib(this.name,
this.text + chunk.slice(start, this.prevI));
this.name = this.text = "";
this.q = null;
this.state = S_ATTRIB_VALUE_CLOSED;
return;
case AMP:
this.text += chunk.slice(start, this.prevI);
this.state = S_ENTITY;
this.entityReturnState = S_ATTRIB_VALUE_QUOTED;
return;
case NL:
case NL_LIKE:
case TAB:
this.text += `${chunk.slice(start, this.prevI)} `;
start = this.i;
break;
case LESS:
this.text += chunk.slice(start, this.prevI);
this.fail("disallowed character.");
return;
case EOC:
this.text += chunk.slice(start);
return;
default:
}
}
}
private sAttribValueClosed(): void {
const c = this.getCodeNorm();
if (isS(c)) {
this.state = S_ATTRIB;
}
else if (c === GREATER) {
this.openTag();
}
else if (c === FORWARD_SLASH) {
this.state = S_OPEN_TAG_SLASH;
}
else if (isNameStartChar(c)) {
this.fail("no whitespace between attributes.");
this.unget();
this.state = S_ATTRIB_NAME;
}
else {
this.fail("disallowed character in attribute name.");
}
}
private sAttribValueUnquoted(): void {
// We don't do anything regarding EOL or space handling for unquoted
// attributes. We already have failed by the time we get here, and the
// contract that saxes upholds states that upon failure, it is not safe to
// rely on the data passed to event handlers (other than
// ``onerror``). Passing "bad" data is not a problem.
const c = this.captureTo(ATTRIB_VALUE_UNQUOTED_TERMINATOR);
switch (c) {
case AMP:
this.state = S_ENTITY;
this.entityReturnState = S_ATTRIB_VALUE_UNQUOTED;
break;
case LESS:
this.fail("disallowed character.");
break;
case EOC:
break;
default:
if (this.text.includes("]]>")) {
this.fail("the string \"]]>\" is disallowed in char data.");
}
this.pushAttrib(this.name, this.text);
this.name = this.text = "";
if (c === GREATER) {
this.openTag();
}
else {
this.state = S_ATTRIB;
}
}
}
private sCloseTag(): void {
const c = this.captureNameChars();
if (c === GREATER) {
this.closeTag();
}
else if (isS(c)) {
this.state = S_CLOSE_TAG_SAW_WHITE;
}
else if (c !== EOC) {
this.fail("disallowed character in closing tag.");
}
}
private sCloseTagSawWhite(): void {
switch (this.skipSpaces()) {
case GREATER:
this.closeTag();
break;
case EOC:
break;
default:
this.fail("disallowed character in closing tag.");
}
}
// END OF STATE ENGINE METHODS
private handleTextInRoot(): void {
// This is essentially a specialized version of captureTo which is optimized
// for performing the ]]> check. A previous version of this code, checked
// ``this.text`` for the presence of ]]>. It simplified the code but was
// very costly when character data contained a lot of entities to be parsed.
//
// Since we are using a specialized loop, we also keep track of the presence
// of ]]> in text data. The sequence ]]> is forbidden to appear as-is.
//
let { i: start, forbiddenState } = this;
const { chunk, textHandler: handler } = this;
// eslint-disable-next-line no-labels, no-restricted-syntax
scanLoop:
// eslint-disable-next-line no-constant-condition
while (true) {
switch (this.getCode()) {
case LESS: {
this.state = S_OPEN_WAKA;
if (handler !== undefined) {
const { text } = this;
const slice = chunk.slice(start, this.prevI);
if (text.length !== 0) {
handler(text + slice);
this.text = "";
}
else if (slice.length !== 0) {
handler(slice);
}
}
forbiddenState = FORBIDDEN_START;
// eslint-disable-next-line no-labels
break scanLoop;
}
case AMP:
this.state = S_ENTITY;
this.entityReturnState = S_TEXT;
if (handler !== undefined) {
this.text += chunk.slice(start, this.prevI);
}
forbiddenState = FORBIDDEN_START;
// eslint-disable-next-line no-labels
break scanLoop;
case CLOSE_BRACKET:
switch (forbiddenState) {
case FORBIDDEN_START:
forbiddenState = FORBIDDEN_BRACKET;
break;
case FORBIDDEN_BRACKET:
forbiddenState = FORBIDDEN_BRACKET_BRACKET;
break;
case FORBIDDEN_BRACKET_BRACKET:
break;
default:
throw new Error("impossible state");
}
break;
case GREATER:
if (forbiddenState === FORBIDDEN_BRACKET_BRACKET) {
this.fail("the string \"]]>\" is disallowed in char data.");
}
forbiddenState = FORBIDDEN_START;
break;
case NL_LIKE:
if (handler !== undefined) {
this.text += `${chunk.slice(start, this.prevI)}\n`;
}
start = this.i;
forbiddenState = FORBIDDEN_START;
break;
case EOC:
if (handler !== undefined) {
this.text += chunk.slice(start);
}
// eslint-disable-next-line no-labels
break scanLoop;
default:
forbiddenState = FORBIDDEN_START;
}
}
this.forbiddenState = forbiddenState;
}
private handleTextOutsideRoot(): void {
// This is essentially a specialized version of captureTo which is optimized
// for a specialized task. We keep track of the presence of non-space
// characters in the text since these are errors when appearing outside the
// document root element.
let { i: start } = this;
const { chunk, textHandler: handler } = this;
let nonSpace = false;
// eslint-disable-next-line no-labels, no-restricted-syntax
outRootLoop:
// eslint-disable-next-line no-constant-condition
while (true) {
const code = this.getCode();
switch (code) {
case LESS: {
this.state = S_OPEN_WAKA;
if (handler !== undefined) {
const { text } = this;
const slice = chunk.slice(start, this.prevI);
if (text.length !== 0) {
handler(text + slice);
this.text = "";
}
else if (slice.length !== 0) {
handler(slice);
}
}
// eslint-disable-next-line no-labels
break outRootLoop;
}
case AMP:
this.state = S_ENTITY;
this.entityReturnState = S_TEXT;
if (handler !== undefined) {
this.text += chunk.slice(start, this.prevI);
}
nonSpace = true;
// eslint-disable-next-line no-labels
break outRootLoop;
case NL_LIKE:
if (handler !== undefined) {
this.text += `${chunk.slice(start, this.prevI)}\n`;
}
start = this.i;
break;
case EOC:
if (handler !== undefined) {
this.text += chunk.slice(start);
}
// eslint-disable-next-line no-labels
break outRootLoop;
default:
if (!isS(code)) {
nonSpace = true;
}
}
}
if (!nonSpace) {
return;
}
// We use the reportedTextBeforeRoot and reportedTextAfterRoot flags
// to avoid reporting errors for every single character that is out of
// place.
if (!this.sawRoot && !this.reportedTextBeforeRoot) {
this.fail("text data outside of root node.");
this.reportedTextBeforeRoot = true;
}
if (this.closedRoot && !this.reportedTextAfterRoot) {
this.fail("text data outside of root node.");
this.reportedTextAfterRoot = true;
}
}
private pushAttribNS(name: string, value: string): void {
const { prefix, local } = this.qname(name);
const attr = { name, prefix, local, value };
this.attribList.push(attr);
this.attributeHandler?.(attr as AttributeEventForOptions<O>);
if (prefix === "xmlns") {
const trimmed = value.trim();
if (this.currentXMLVersion === "1.0" && trimmed === "") {
this.fail("invalid attempt to undefine prefix in XML 1.0");
}
this.topNS![local] = trimmed;
nsPairCheck(this, local, trimmed);
}
else if (name === "xmlns") {
const trimmed = value.trim();
this.topNS![""] = trimmed;
nsPairCheck(this, "", trimmed);
}
}
private pushAttribPlain(name: string, value: string): void {
const attr = { name, value };
this.attribList.push(attr);
this.attributeHandler?.(attr as AttributeEventForOptions<O>);
}
/**
* End parsing. This performs final well-formedness checks and resets the
* parser to a clean state.
*
* @returns this
*/
private end(): this {
if (!this.sawRoot) {
this.fail("document must contain a root element.");
}
const { tags } = this;
while (tags.length > 0) {
const tag = tags.pop()!;
this.fail(`unclosed tag: ${tag.name}`);
}
if ((this.state !== S_BEGIN) && (this.state !== S_TEXT)) {
this.fail("unexpected end.");
}
const { text } = this;
if (text.length !== 0) {
this.textHandler?.(text);
this.text = "";
}
this._closed = true;
this.endHandler?.();
this._init();
return this;
}
/**
* Resolve a namespace prefix.
*
* @param prefix The prefix to resolve.
*
* @returns The namespace URI or ``undefined`` if the prefix is not defined.
*/
resolve(prefix: string): string | undefined {
let uri = this.topNS![prefix];
if (uri !== undefined) {
return uri;
}
const { tags } = this;
for (let index = tags.length - 1; index >= 0; index--) {
uri = tags[index]!.ns![prefix];
if (uri !== undefined) {
return uri;
}
}
uri = this.ns[prefix];
if (uri !== undefined) {
return uri;
}
return this.opt.resolvePrefix?.(prefix);
}
/**
* Parse a qname into its prefix and local name parts.
*
* @param name The name to parse
*
* @returns
*/
private qname(name: string): { prefix: string; local: string } {
// This is faster than using name.split(":").
const colon = name.indexOf(":");
if (colon === -1) {
return { prefix: "", local: name };
}
const local = name.slice(colon + 1);
const prefix = name.slice(0, colon);
if (prefix === "" || local === "" || local.includes(":")) {
this.fail(`malformed name: ${name}.`);
}
return { prefix, local };
}
private processAttribsNS(): void {
const { attribList } = this;
const tag = this.tag!;
{
// add namespace info to tag
const { prefix, local } = this.qname(tag.name);
tag.prefix = prefix;
tag.local = local;
const uri = tag.uri = this.resolve(prefix) ?? "";
if (prefix !== "") {
if (prefix === "xmlns") {
this.fail("tags may not have \"xmlns\" as prefix.");
}
if (uri === "") {
this.fail(`unbound namespace prefix: ${JSON.stringify(prefix)}.`);
tag.uri = prefix;
}
}
}
if (attribList.length === 0) {
return;
}
const { attributes } = tag;
const seen = new Set();
// Note: do not apply default ns to attributes:
// http://www.w3.org/TR/REC-xml-names/#defaulting
for (const attr of attribList as SaxesAttributeNSIncomplete[]) {
const { name, prefix, local } = attr;
let uri;
let eqname;
if (prefix === "") {
uri = name === "xmlns" ? XMLNS_NAMESPACE : "";
eqname = name;
}
else {
uri = this.resolve(prefix);
// if there's any attributes with an undefined namespace,
// then fail on them now.
if (uri === undefined) {
this.fail(`unbound namespace prefix: ${JSON.stringify(prefix)}.`);
uri = prefix;
}
eqname = `{${uri}}${local}`;
}
if (seen.has(eqname)) {
this.fail(`duplicate attribute: ${eqname}.`);
}
seen.add(eqname);
attr.uri = uri;
attributes[name] = attr;
}
this.attribList = [];
}
private processAttribsPlain(): void {
const { attribList } = this;
// eslint-disable-next-line prefer-destructuring
const attributes = this.tag!.attributes;
for (const { name, value } of attribList) {
if (attributes[name] !== undefined) {
this.fail(`duplicate attribute: ${name}.`);
}
attributes[name] = value;
}
this.attribList = [];
}
/**
* Handle a complete open tag. This parser code calls this once it has seen
* the whole tag. This method checks for well-formeness and then emits
* ``onopentag``.
*/
private openTag(): void {
this.processAttribs();
const { tags } = this;
const tag = this.tag as SaxesTag;
tag.isSelfClosing = false;
// There cannot be any pending text here due to the onopentagstart that was
// necessarily emitted before we get here. So we do not check text.
this.openTagHandler?.(tag as TagForOptions<O>);
tags.push(tag);
this.state = S_TEXT;
this.name = "";
}
/**
* Handle a complete self-closing tag. This parser code calls this once it has
* seen the whole tag. This method checks for well-formeness and then emits
* ``onopentag`` and ``onclosetag``.
*/
private openSelfClosingTag(): void {
this.processAttribs();
const { tags } = this;
const tag = this.tag as SaxesTag;
tag.isSelfClosing = true;
// There cannot be any pending text here due to the onopentagstart that was
// necessarily emitted before we get here. So we do not check text.
this.openTagHandler?.(tag as TagForOptions<O>);
this.closeTagHandler?.(tag as TagForOptions<O>);
const top = this.tag = tags[tags.length - 1] ?? null;
if (top === null) {
this.closedRoot = true;
}
this.state = S_TEXT;
this.name = "";
}
/**
* Handle a complete close tag. This parser code calls this once it has seen
* the whole tag. This method checks for well-formeness and then emits
* ``onclosetag``.
*/
private closeTag(): void {
const { tags, name } = this;
// Our state after this will be S_TEXT, no matter what, and we can clear
// tagName now.
this.state = S_TEXT;
this.name = "";
if (name === "") {
this.fail("weird empty close tag.");
this.text += "</>";
return;
}
const handler = this.closeTagHandler;
let l = tags.length;
while (l-- > 0) {
const tag = this.tag = tags.pop() as SaxesTag;
this.topNS = tag.ns!;
handler?.(tag as TagForOptions<O>);
if (tag.name === name) {
break;
}
this.fail("unexpected close tag.");
}
if (l === 0) {
this.closedRoot = true;
}
else if (l < 0) {
this.fail(`unmatched closing tag: ${name}.`);
this.text += `</${name}>`;
}
}
/**
* Resolves an entity. Makes any necessary well-formedness checks.
*
* @param entity The entity to resolve.
*
* @returns The parsed entity.
*/
private parseEntity(entity: string): string {
// startsWith would be significantly slower for this test.
if (entity[0] !== "#") {
const defined = this.ENTITIES[entity];
if (defined !== undefined) {
return defined;
}
this.fail(this.isName(entity) ? "undefined entity." :
"disallowed character in entity name.");
return `&${entity};`;
}
let num = NaN;
if (entity[1] === "x" && /^#x[0-9a-f]+$/i.test(entity)) {
num = parseInt(entity.slice(2), 16);
}
else if (/^#[0-9]+$/.test(entity)) {
num = parseInt(entity.slice(1), 10);
}
// The character reference is required to match the CHAR production.
if (!this.isChar(num)) {
this.fail("malformed character entity.");
return `&${entity};`;
}
return String.fromCodePoint(num);
}
} |
1,152 | fn(parser: SaxesParser): void {
parser.write("<r><![CDATA[ this is ").write("character data ")
.write("]]></r>")
.close();
} | class SaxesParser<O extends SaxesOptions = {}> {
private readonly fragmentOpt: boolean;
private readonly xmlnsOpt: boolean;
private readonly trackPosition: boolean;
private readonly fileName?: string;
private readonly nameStartCheck: (c: number) => boolean;
private readonly nameCheck: (c: number) => boolean;
private readonly isName: (name: string) => boolean;
private readonly ns!: Record<string, string>;
private openWakaBang!: string;
private text!: string;
private name!: string;
private piTarget!: string;
private entity!: string;
private q!: null | number;
private tags!: SaxesTagIncomplete[];
private tag!: SaxesTagIncomplete | null;
private topNS!: Record<string, string> | null;
private chunk!: string;
private chunkPosition!: number;
private i!: number;
//
// We use prevI to allow "ungetting" the previously read code point. Note
// however, that it is not safe to unget everything and anything. In
// particular ungetting EOL characters will screw positioning up.
//
// Practically, you must not unget a code which has any side effect beyond
// updating ``this.i`` and ``this.prevI``. Only EOL codes have such side
// effects.
//
private prevI!: number;
private carriedFromPrevious?: string;
private forbiddenState!: number;
private attribList!: (SaxesAttributeNSIncomplete | SaxesAttributePlain)[];
private state!: number;
private reportedTextBeforeRoot!: boolean;
private reportedTextAfterRoot!: boolean;
private closedRoot!: boolean;
private sawRoot!: boolean;
private xmlDeclPossible!: boolean;
private xmlDeclExpects!: string[];
private entityReturnState?: number;
private processAttribs!: (this: this) => void;
private positionAtNewLine!: number;
private doctype!: boolean;
private getCode!: () => number;
private isChar!: (c: number) => boolean;
private pushAttrib!: (name: string, value: string) => void;
private _closed!: boolean;
private currentXMLVersion!: string;
private readonly stateTable: ((this: SaxesParser<O>) => void)[];
private xmldeclHandler?: XMLDeclHandler;
private textHandler?: TextHandler;
private piHandler?: PIHandler;
private doctypeHandler?: DoctypeHandler;
private commentHandler?: CommentHandler;
private openTagStartHandler?: OpenTagStartHandler<O>;
private openTagHandler?: OpenTagHandler<O>;
private closeTagHandler?: CloseTagHandler<O>;
private cdataHandler?: CDataHandler;
private errorHandler?: ErrorHandler;
private endHandler?: EndHandler;
private readyHandler?: ReadyHandler;
private attributeHandler?: AttributeHandler<O>;
/**
* Indicates whether or not the parser is closed. If ``true``, wait for
* the ``ready`` event to write again.
*/
get closed(): boolean {
return this._closed;
}
readonly opt: SaxesOptions;
/**
* The XML declaration for this document.
*/
xmlDecl!: XMLDecl;
/**
* The line number of the next character to be read by the parser. This field
* is one-based. (The first line is numbered 1.)
*/
line!: number;
/**
* The column number of the next character to be read by the parser. *
* This field is zero-based. (The first column is 0.)
*
* This field counts columns by *Unicode character*. Note that this *can*
* be different from the index of the character in a JavaScript string due
* to how JavaScript handles astral plane characters.
*
* See [[columnIndex]] for a number that corresponds to the JavaScript index.
*/
column!: number;
/**
* A map of entity name to expansion.
*/
ENTITIES!: Record<string, string>;
/**
* @param opt The parser options.
*/
constructor(opt?: O) {
this.opt = opt ?? {};
this.fragmentOpt = !!(this.opt.fragment as boolean);
const xmlnsOpt = this.xmlnsOpt = !!(this.opt.xmlns as boolean);
this.trackPosition = this.opt.position !== false;
this.fileName = this.opt.fileName;
if (xmlnsOpt) {
// This is the function we use to perform name checks on PIs and entities.
// When namespaces are used, colons are not allowed in PI target names or
// entity names. So the check depends on whether namespaces are used. See:
//
// https://www.w3.org/XML/xml-names-19990114-errata.html
// NE08
//
this.nameStartCheck = isNCNameStartChar;
this.nameCheck = isNCNameChar;
this.isName = isNCName;
// eslint-disable-next-line @typescript-eslint/unbound-method
this.processAttribs = this.processAttribsNS;
// eslint-disable-next-line @typescript-eslint/unbound-method
this.pushAttrib = this.pushAttribNS;
// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-assignment
this.ns = { __proto__: null as any, ...rootNS };
const additional = this.opt.additionalNamespaces;
if (additional != null) {
nsMappingCheck(this, additional);
Object.assign(this.ns, additional);
}
}
else {
this.nameStartCheck = isNameStartChar;
this.nameCheck = isNameChar;
this.isName = isName;
// eslint-disable-next-line @typescript-eslint/unbound-method
this.processAttribs = this.processAttribsPlain;
// eslint-disable-next-line @typescript-eslint/unbound-method
this.pushAttrib = this.pushAttribPlain;
}
//
// The order of the members in this table needs to correspond to the state
// numbers given to the states that correspond to the methods being recorded
// here.
//
this.stateTable = [
/* eslint-disable @typescript-eslint/unbound-method */
this.sBegin,
this.sBeginWhitespace,
this.sDoctype,
this.sDoctypeQuote,
this.sDTD,
this.sDTDQuoted,
this.sDTDOpenWaka,
this.sDTDOpenWakaBang,
this.sDTDComment,
this.sDTDCommentEnding,
this.sDTDCommentEnded,
this.sDTDPI,
this.sDTDPIEnding,
this.sText,
this.sEntity,
this.sOpenWaka,
this.sOpenWakaBang,
this.sComment,
this.sCommentEnding,
this.sCommentEnded,
this.sCData,
this.sCDataEnding,
this.sCDataEnding2,
this.sPIFirstChar,
this.sPIRest,
this.sPIBody,
this.sPIEnding,
this.sXMLDeclNameStart,
this.sXMLDeclName,
this.sXMLDeclEq,
this.sXMLDeclValueStart,
this.sXMLDeclValue,
this.sXMLDeclSeparator,
this.sXMLDeclEnding,
this.sOpenTag,
this.sOpenTagSlash,
this.sAttrib,
this.sAttribName,
this.sAttribNameSawWhite,
this.sAttribValue,
this.sAttribValueQuoted,
this.sAttribValueClosed,
this.sAttribValueUnquoted,
this.sCloseTag,
this.sCloseTagSawWhite,
/* eslint-enable @typescript-eslint/unbound-method */
];
this._init();
}
_init(): void {
this.openWakaBang = "";
this.text = "";
this.name = "";
this.piTarget = "";
this.entity = "";
this.q = null;
this.tags = [];
this.tag = null;
this.topNS = null;
this.chunk = "";
this.chunkPosition = 0;
this.i = 0;
this.prevI = 0;
this.carriedFromPrevious = undefined;
this.forbiddenState = FORBIDDEN_START;
this.attribList = [];
// The logic is organized so as to minimize the need to check
// this.opt.fragment while parsing.
const { fragmentOpt } = this;
this.state = fragmentOpt ? S_TEXT : S_BEGIN;
// We want these to be all true if we are dealing with a fragment.
this.reportedTextBeforeRoot = this.reportedTextAfterRoot = this.closedRoot =
this.sawRoot = fragmentOpt;
// An XML declaration is intially possible only when parsing whole
// documents.
this.xmlDeclPossible = !fragmentOpt;
this.xmlDeclExpects = ["version"];
this.entityReturnState = undefined;
let { defaultXMLVersion } = this.opt;
if (defaultXMLVersion === undefined) {
if (this.opt.forceXMLVersion === true) {
throw new Error("forceXMLVersion set but defaultXMLVersion is not set");
}
defaultXMLVersion = "1.0";
}
this.setXMLVersion(defaultXMLVersion);
this.positionAtNewLine = 0;
this.doctype = false;
this._closed = false;
this.xmlDecl = {
version: undefined,
encoding: undefined,
standalone: undefined,
};
this.line = 1;
this.column = 0;
this.ENTITIES = Object.create(XML_ENTITIES) as Record<string, string>;
this.readyHandler?.();
}
/**
* The stream position the parser is currently looking at. This field is
* zero-based.
*
* This field is not based on counting Unicode characters but is to be
* interpreted as a plain index into a JavaScript string.
*/
get position(): number {
return this.chunkPosition + this.i;
}
/**
* The column number of the next character to be read by the parser. *
* This field is zero-based. (The first column in a line is 0.)
*
* This field reports the index at which the next character would be in the
* line if the line were represented as a JavaScript string. Note that this
* *can* be different to a count based on the number of *Unicode characters*
* due to how JavaScript handles astral plane characters.
*
* See [[column]] for a number that corresponds to a count of Unicode
* characters.
*/
get columnIndex(): number {
return this.position - this.positionAtNewLine;
}
/**
* Set an event listener on an event. The parser supports one handler per
* event type. If you try to set an event handler over an existing handler,
* the old handler is silently overwritten.
*
* @param name The event to listen to.
*
* @param handler The handler to set.
*/
on<N extends EventName>(name: N, handler: EventNameToHandler<O, N>): void {
// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-member-access
(this as any)[EVENT_NAME_TO_HANDLER_NAME[name]] = handler;
}
/**
* Unset an event handler.
*
* @parma name The event to stop listening to.
*/
off(name: EventName): void {
// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-member-access
(this as any)[EVENT_NAME_TO_HANDLER_NAME[name]] = undefined;
}
/**
* Make an error object. The error object will have a message that contains
* the ``fileName`` option passed at the creation of the parser. If position
* tracking was turned on, it will also have line and column number
* information.
*
* @param message The message describing the error to report.
*
* @returns An error object with a properly formatted message.
*/
makeError(message: string): Error {
let msg = this.fileName ?? "";
if (this.trackPosition) {
if (msg.length > 0) {
msg += ":";
}
msg += `${this.line}:${this.column}`;
}
if (msg.length > 0) {
msg += ": ";
}
return new Error(msg + message);
}
/**
* Report a parsing error. This method is made public so that client code may
* check for issues that are outside the scope of this project and can report
* errors.
*
* @param message The error to report.
*
* @returns this
*/
fail(message: string): this {
const err = this.makeError(message);
const handler = this.errorHandler;
if (handler === undefined) {
throw err;
}
else {
handler(err);
}
return this;
}
/**
* Write a XML data to the parser.
*
* @param chunk The XML data to write.
*
* @returns this
*/
// We do need object for the type here. Yes, it often causes problems
// but not in this case.
write(chunk: string | object | null): this {
if (this.closed) {
return this.fail("cannot write after close; assign an onready handler.");
}
let end = false;
if (chunk === null) {
// We cannot return immediately because carriedFromPrevious may need
// processing.
end = true;
chunk = "";
}
else if (typeof chunk === "object") {
chunk = chunk.toString();
}
// We checked if performing a pre-decomposition of the string into an array
// of single complete characters (``Array.from(chunk)``) would be faster
// than the current repeated calls to ``charCodeAt``. As of August 2018, it
// isn't. (There may be Node-specific code that would perform faster than
// ``Array.from`` but don't want to be dependent on Node.)
if (this.carriedFromPrevious !== undefined) {
// The previous chunk had char we must carry over.
chunk = `${this.carriedFromPrevious}${chunk}`;
this.carriedFromPrevious = undefined;
}
let limit = chunk.length;
const lastCode = chunk.charCodeAt(limit - 1);
if (!end &&
// A trailing CR or surrogate must be carried over to the next
// chunk.
(lastCode === CR || (lastCode >= 0xD800 && lastCode <= 0xDBFF))) {
// The chunk ends with a character that must be carried over. We cannot
// know how to handle it until we get the next chunk or the end of the
// stream. So save it for later.
this.carriedFromPrevious = chunk[limit - 1];
limit--;
chunk = chunk.slice(0, limit);
}
const { stateTable } = this;
this.chunk = chunk;
this.i = 0;
while (this.i < limit) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-argument
stateTable[this.state].call(this as any);
}
this.chunkPosition += limit;
return end ? this.end() : this;
}
/**
* Close the current stream. Perform final well-formedness checks and reset
* the parser tstate.
*
* @returns this
*/
close(): this {
return this.write(null);
}
/**
* Get a single code point out of the current chunk. This updates the current
* position if we do position tracking.
*
* This is the algorithm to use for XML 1.0.
*
* @returns The character read.
*/
private getCode10(): number {
const { chunk, i } = this;
this.prevI = i;
// Yes, we do this instead of doing this.i++. Doing it this way, we do not
// read this.i again, which is a bit faster.
this.i = i + 1;
if (i >= chunk.length) {
return EOC;
}
// Using charCodeAt and handling the surrogates ourselves is faster
// than using codePointAt.
const code = chunk.charCodeAt(i);
this.column++;
if (code < 0xD800) {
if (code >= SPACE || code === TAB) {
return code;
}
switch (code) {
case NL:
this.line++;
this.column = 0;
this.positionAtNewLine = this.position;
return NL;
case CR:
// We may get NaN if we read past the end of the chunk, which is fine.
if (chunk.charCodeAt(i + 1) === NL) {
// A \r\n sequence is converted to \n so we have to skip over the
// next character. We already know it has a size of 1 so ++ is fine
// here.
this.i = i + 2;
}
// Otherwise, a \r is just converted to \n, so we don't have to skip
// ahead.
// In either case, \r becomes \n.
this.line++;
this.column = 0;
this.positionAtNewLine = this.position;
return NL_LIKE;
default:
// If we get here, then code < SPACE and it is not NL CR or TAB.
this.fail("disallowed character.");
return code;
}
}
if (code > 0xDBFF) {
// This is a specialized version of isChar10 that takes into account
// that in this context code > 0xDBFF and code <= 0xFFFF. So it does not
// test cases that don't need testing.
if (!(code >= 0xE000 && code <= 0xFFFD)) {
this.fail("disallowed character.");
}
return code;
}
const final = 0x10000 + ((code - 0xD800) * 0x400) +
(chunk.charCodeAt(i + 1) - 0xDC00);
this.i = i + 2;
// This is a specialized version of isChar10 that takes into account that in
// this context necessarily final >= 0x10000.
if (final > 0x10FFFF) {
this.fail("disallowed character.");
}
return final;
}
/**
* Get a single code point out of the current chunk. This updates the current
* position if we do position tracking.
*
* This is the algorithm to use for XML 1.1.
*
* @returns {number} The character read.
*/
private getCode11(): number {
const { chunk, i } = this;
this.prevI = i;
// Yes, we do this instead of doing this.i++. Doing it this way, we do not
// read this.i again, which is a bit faster.
this.i = i + 1;
if (i >= chunk.length) {
return EOC;
}
// Using charCodeAt and handling the surrogates ourselves is faster
// than using codePointAt.
const code = chunk.charCodeAt(i);
this.column++;
if (code < 0xD800) {
if ((code > 0x1F && code < 0x7F) || (code > 0x9F && code !== LS) ||
code === TAB) {
return code;
}
switch (code) {
case NL: // 0xA
this.line++;
this.column = 0;
this.positionAtNewLine = this.position;
return NL;
case CR: { // 0xD
// We may get NaN if we read past the end of the chunk, which is
// fine.
const next = chunk.charCodeAt(i + 1);
if (next === NL || next === NEL) {
// A CR NL or CR NEL sequence is converted to NL so we have to skip
// over the next character. We already know it has a size of 1.
this.i = i + 2;
}
// Otherwise, a CR is just converted to NL, no skip.
}
/* yes, fall through */
case NEL: // 0x85
case LS: // Ox2028
this.line++;
this.column = 0;
this.positionAtNewLine = this.position;
return NL_LIKE;
default:
this.fail("disallowed character.");
return code;
}
}
if (code > 0xDBFF) {
// This is a specialized version of isCharAndNotRestricted that takes into
// account that in this context code > 0xDBFF and code <= 0xFFFF. So it
// does not test cases that don't need testing.
if (!(code >= 0xE000 && code <= 0xFFFD)) {
this.fail("disallowed character.");
}
return code;
}
const final = 0x10000 + ((code - 0xD800) * 0x400) +
(chunk.charCodeAt(i + 1) - 0xDC00);
this.i = i + 2;
// This is a specialized version of isCharAndNotRestricted that takes into
// account that in this context necessarily final >= 0x10000.
if (final > 0x10FFFF) {
this.fail("disallowed character.");
}
return final;
}
/**
* Like ``getCode`` but with the return value normalized so that ``NL`` is
* returned for ``NL_LIKE``.
*/
private getCodeNorm(): number {
const c = this.getCode();
return c === NL_LIKE ? NL : c;
}
private unget(): void {
this.i = this.prevI;
this.column--;
}
/**
* Capture characters into a buffer until encountering one of a set of
* characters.
*
* @param chars An array of codepoints. Encountering a character in the array
* ends the capture. (``chars`` may safely contain ``NL``.)
*
* @return The character code that made the capture end, or ``EOC`` if we hit
* the end of the chunk. The return value cannot be NL_LIKE: NL is returned
* instead.
*/
private captureTo(chars: number[]): number {
let { i: start } = this;
const { chunk } = this;
// eslint-disable-next-line no-constant-condition
while (true) {
const c = this.getCode();
const isNLLike = c === NL_LIKE;
const final = isNLLike ? NL : c;
if (final === EOC || chars.includes(final)) {
this.text += chunk.slice(start, this.prevI);
return final;
}
if (isNLLike) {
this.text += `${chunk.slice(start, this.prevI)}\n`;
start = this.i;
}
}
}
/**
* Capture characters into a buffer until encountering a character.
*
* @param char The codepoint that ends the capture. **NOTE ``char`` MAY NOT
* CONTAIN ``NL``.** Passing ``NL`` will result in buggy behavior.
*
* @return ``true`` if we ran into the character. Otherwise, we ran into the
* end of the current chunk.
*/
private captureToChar(char: number): boolean {
let { i: start } = this;
const { chunk } = this;
// eslint-disable-next-line no-constant-condition
while (true) {
let c = this.getCode();
switch (c) {
case NL_LIKE:
this.text += `${chunk.slice(start, this.prevI)}\n`;
start = this.i;
c = NL;
break;
case EOC:
this.text += chunk.slice(start);
return false;
default:
}
if (c === char) {
this.text += chunk.slice(start, this.prevI);
return true;
}
}
}
/**
* Capture characters that satisfy ``isNameChar`` into the ``name`` field of
* this parser.
*
* @return The character code that made the test fail, or ``EOC`` if we hit
* the end of the chunk. The return value cannot be NL_LIKE: NL is returned
* instead.
*/
private captureNameChars(): number {
const { chunk, i: start } = this;
// eslint-disable-next-line no-constant-condition
while (true) {
const c = this.getCode();
if (c === EOC) {
this.name += chunk.slice(start);
return EOC;
}
// NL is not a name char so we don't have to test specifically for it.
if (!isNameChar(c)) {
this.name += chunk.slice(start, this.prevI);
return c === NL_LIKE ? NL : c;
}
}
}
/**
* Skip white spaces.
*
* @return The character that ended the skip, or ``EOC`` if we hit
* the end of the chunk. The return value cannot be NL_LIKE: NL is returned
* instead.
*/
private skipSpaces(): number {
// eslint-disable-next-line no-constant-condition
while (true) {
const c = this.getCodeNorm();
if (c === EOC || !isS(c)) {
return c;
}
}
}
private setXMLVersion(version: string): void {
this.currentXMLVersion = version;
/* eslint-disable @typescript-eslint/unbound-method */
if (version === "1.0") {
this.isChar = isChar10;
this.getCode = this.getCode10;
}
else {
this.isChar = isChar11;
this.getCode = this.getCode11;
}
/* eslint-enable @typescript-eslint/unbound-method */
}
// STATE ENGINE METHODS
// This needs to be a state separate from S_BEGIN_WHITESPACE because we want
// to be sure never to come back to this state later.
private sBegin(): void {
// We are essentially peeking at the first character of the chunk. Since
// S_BEGIN can be in effect only when we start working on the first chunk,
// the index at which we must look is necessarily 0. Note also that the
// following test does not depend on decoding surrogates.
// If the initial character is 0xFEFF, ignore it.
if (this.chunk.charCodeAt(0) === 0xFEFF) {
this.i++;
this.column++;
}
this.state = S_BEGIN_WHITESPACE;
}
private sBeginWhitespace(): void {
// We need to know whether we've encountered spaces or not because as soon
// as we run into a space, an XML declaration is no longer possible. Rather
// than slow down skipSpaces even in places where we don't care whether it
// skipped anything or not, we check whether prevI is equal to the value of
// i from before we skip spaces.
const iBefore = this.i;
const c = this.skipSpaces();
if (this.prevI !== iBefore) {
this.xmlDeclPossible = false;
}
switch (c) {
case LESS:
this.state = S_OPEN_WAKA;
// We could naively call closeText but in this state, it is not normal
// to have text be filled with any data.
if (this.text.length !== 0) {
throw new Error("no-empty text at start");
}
break;
case EOC:
break;
default:
this.unget();
this.state = S_TEXT;
this.xmlDeclPossible = false;
}
}
private sDoctype(): void {
const c = this.captureTo(DOCTYPE_TERMINATOR);
switch (c) {
case GREATER: {
this.doctypeHandler?.(this.text);
this.text = "";
this.state = S_TEXT;
this.doctype = true; // just remember that we saw it.
break;
}
case EOC:
break;
default:
this.text += String.fromCodePoint(c);
if (c === OPEN_BRACKET) {
this.state = S_DTD;
}
else if (isQuote(c)) {
this.state = S_DOCTYPE_QUOTE;
this.q = c;
}
}
}
private sDoctypeQuote(): void {
const q = this.q!;
if (this.captureToChar(q)) {
this.text += String.fromCodePoint(q);
this.q = null;
this.state = S_DOCTYPE;
}
}
private sDTD(): void {
const c = this.captureTo(DTD_TERMINATOR);
if (c === EOC) {
return;
}
this.text += String.fromCodePoint(c);
if (c === CLOSE_BRACKET) {
this.state = S_DOCTYPE;
}
else if (c === LESS) {
this.state = S_DTD_OPEN_WAKA;
}
else if (isQuote(c)) {
this.state = S_DTD_QUOTED;
this.q = c;
}
}
private sDTDQuoted(): void {
const q = this.q!;
if (this.captureToChar(q)) {
this.text += String.fromCodePoint(q);
this.state = S_DTD;
this.q = null;
}
}
private sDTDOpenWaka(): void {
const c = this.getCodeNorm();
this.text += String.fromCodePoint(c);
switch (c) {
case BANG:
this.state = S_DTD_OPEN_WAKA_BANG;
this.openWakaBang = "";
break;
case QUESTION:
this.state = S_DTD_PI;
break;
default:
this.state = S_DTD;
}
}
private sDTDOpenWakaBang(): void {
const char = String.fromCodePoint(this.getCodeNorm());
const owb = this.openWakaBang += char;
this.text += char;
if (owb !== "-") {
this.state = owb === "--" ? S_DTD_COMMENT : S_DTD;
this.openWakaBang = "";
}
}
private sDTDComment(): void {
if (this.captureToChar(MINUS)) {
this.text += "-";
this.state = S_DTD_COMMENT_ENDING;
}
}
private sDTDCommentEnding(): void {
const c = this.getCodeNorm();
this.text += String.fromCodePoint(c);
this.state = c === MINUS ? S_DTD_COMMENT_ENDED : S_DTD_COMMENT;
}
private sDTDCommentEnded(): void {
const c = this.getCodeNorm();
this.text += String.fromCodePoint(c);
if (c === GREATER) {
this.state = S_DTD;
}
else {
this.fail("malformed comment.");
// <!-- blah -- bloo --> will be recorded as
// a comment of " blah -- bloo "
this.state = S_DTD_COMMENT;
}
}
private sDTDPI(): void {
if (this.captureToChar(QUESTION)) {
this.text += "?";
this.state = S_DTD_PI_ENDING;
}
}
private sDTDPIEnding(): void {
const c = this.getCodeNorm();
this.text += String.fromCodePoint(c);
if (c === GREATER) {
this.state = S_DTD;
}
}
private sText(): void {
//
// We did try a version of saxes where the S_TEXT state was split in two
// states: one for text inside the root element, and one for text
// outside. This was avoiding having to test this.tags.length to decide
// what implementation to actually use.
//
// Peformance testing on gigabyte-size files did not show any advantage to
// using the two states solution instead of the current one. Conversely, it
// made the code a bit more complicated elsewhere. For instance, a comment
// can appear before the root element so when a comment ended it was
// necessary to determine whether to return to the S_TEXT state or to the
// new text-outside-root state.
//
if (this.tags.length !== 0) {
this.handleTextInRoot();
}
else {
this.handleTextOutsideRoot();
}
}
private sEntity(): void {
// This is essentially a specialized version of captureToChar(SEMICOLON...)
let { i: start } = this;
const { chunk } = this;
// eslint-disable-next-line no-labels, no-restricted-syntax
loop:
// eslint-disable-next-line no-constant-condition
while (true) {
switch (this.getCode()) {
case NL_LIKE:
this.entity += `${chunk.slice(start, this.prevI)}\n`;
start = this.i;
break;
case SEMICOLON: {
const { entityReturnState } = this;
const entity = this.entity + chunk.slice(start, this.prevI);
this.state = entityReturnState!;
let parsed: string;
if (entity === "") {
this.fail("empty entity name.");
parsed = "&;";
}
else {
parsed = this.parseEntity(entity);
this.entity = "";
}
if (entityReturnState !== S_TEXT || this.textHandler !== undefined) {
this.text += parsed;
}
// eslint-disable-next-line no-labels
break loop;
}
case EOC:
this.entity += chunk.slice(start);
// eslint-disable-next-line no-labels
break loop;
default:
}
}
}
private sOpenWaka(): void {
// Reminder: a state handler is called with at least one character
// available in the current chunk. So the first call to get code inside of
// a state handler cannot return ``EOC``. That's why we don't test
// for it.
const c = this.getCode();
// either a /, ?, !, or text is coming next.
if (isNameStartChar(c)) {
this.state = S_OPEN_TAG;
this.unget();
this.xmlDeclPossible = false;
}
else {
switch (c) {
case FORWARD_SLASH:
this.state = S_CLOSE_TAG;
this.xmlDeclPossible = false;
break;
case BANG:
this.state = S_OPEN_WAKA_BANG;
this.openWakaBang = "";
this.xmlDeclPossible = false;
break;
case QUESTION:
this.state = S_PI_FIRST_CHAR;
break;
default:
this.fail("disallowed character in tag name");
this.state = S_TEXT;
this.xmlDeclPossible = false;
}
}
}
private sOpenWakaBang(): void {
this.openWakaBang += String.fromCodePoint(this.getCodeNorm());
switch (this.openWakaBang) {
case "[CDATA[":
if (!this.sawRoot && !this.reportedTextBeforeRoot) {
this.fail("text data outside of root node.");
this.reportedTextBeforeRoot = true;
}
if (this.closedRoot && !this.reportedTextAfterRoot) {
this.fail("text data outside of root node.");
this.reportedTextAfterRoot = true;
}
this.state = S_CDATA;
this.openWakaBang = "";
break;
case "--":
this.state = S_COMMENT;
this.openWakaBang = "";
break;
case "DOCTYPE":
this.state = S_DOCTYPE;
if (this.doctype || this.sawRoot) {
this.fail("inappropriately located doctype declaration.");
}
this.openWakaBang = "";
break;
default:
// 7 happens to be the maximum length of the string that can possibly
// match one of the cases above.
if (this.openWakaBang.length >= 7) {
this.fail("incorrect syntax.");
}
}
}
private sComment(): void {
if (this.captureToChar(MINUS)) {
this.state = S_COMMENT_ENDING;
}
}
private sCommentEnding(): void {
const c = this.getCodeNorm();
if (c === MINUS) {
this.state = S_COMMENT_ENDED;
this.commentHandler?.(this.text);
this.text = "";
}
else {
this.text += `-${String.fromCodePoint(c)}`;
this.state = S_COMMENT;
}
}
private sCommentEnded(): void {
const c = this.getCodeNorm();
if (c !== GREATER) {
this.fail("malformed comment.");
// <!-- blah -- bloo --> will be recorded as
// a comment of " blah -- bloo "
this.text += `--${String.fromCodePoint(c)}`;
this.state = S_COMMENT;
}
else {
this.state = S_TEXT;
}
}
private sCData(): void {
if (this.captureToChar(CLOSE_BRACKET)) {
this.state = S_CDATA_ENDING;
}
}
private sCDataEnding(): void {
const c = this.getCodeNorm();
if (c === CLOSE_BRACKET) {
this.state = S_CDATA_ENDING_2;
}
else {
this.text += `]${String.fromCodePoint(c)}`;
this.state = S_CDATA;
}
}
private sCDataEnding2(): void {
const c = this.getCodeNorm();
switch (c) {
case GREATER: {
this.cdataHandler?.(this.text);
this.text = "";
this.state = S_TEXT;
break;
}
case CLOSE_BRACKET:
this.text += "]";
break;
default:
this.text += `]]${String.fromCodePoint(c)}`;
this.state = S_CDATA;
}
}
// We need this separate state to check the first character fo the pi target
// with this.nameStartCheck which allows less characters than this.nameCheck.
private sPIFirstChar(): void {
const c = this.getCodeNorm();
// This is first because in the case where the file is well-formed this is
// the branch taken. We optimize for well-formedness.
if (this.nameStartCheck(c)) {
this.piTarget += String.fromCodePoint(c);
this.state = S_PI_REST;
}
else if (c === QUESTION || isS(c)) {
this.fail("processing instruction without a target.");
this.state = c === QUESTION ? S_PI_ENDING : S_PI_BODY;
}
else {
this.fail("disallowed character in processing instruction name.");
this.piTarget += String.fromCodePoint(c);
this.state = S_PI_REST;
}
}
private sPIRest(): void {
// Capture characters into a piTarget while ``this.nameCheck`` run on the
// character read returns true.
const { chunk, i: start } = this;
// eslint-disable-next-line no-constant-condition
while (true) {
const c = this.getCodeNorm();
if (c === EOC) {
this.piTarget += chunk.slice(start);
return;
}
// NL cannot satisfy this.nameCheck so we don't have to test specifically
// for it.
if (!this.nameCheck(c)) {
this.piTarget += chunk.slice(start, this.prevI);
const isQuestion = c === QUESTION;
if (isQuestion || isS(c)) {
if (this.piTarget === "xml") {
if (!this.xmlDeclPossible) {
this.fail(
"an XML declaration must be at the start of the document.");
}
this.state = isQuestion ? S_XML_DECL_ENDING : S_XML_DECL_NAME_START;
}
else {
this.state = isQuestion ? S_PI_ENDING : S_PI_BODY;
}
}
else {
this.fail("disallowed character in processing instruction name.");
this.piTarget += String.fromCodePoint(c);
}
break;
}
}
}
private sPIBody(): void {
if (this.text.length === 0) {
const c = this.getCodeNorm();
if (c === QUESTION) {
this.state = S_PI_ENDING;
}
else if (!isS(c)) {
this.text = String.fromCodePoint(c);
}
}
// The question mark character is not valid inside any of the XML
// declaration name/value pairs.
else if (this.captureToChar(QUESTION)) {
this.state = S_PI_ENDING;
}
}
private sPIEnding(): void {
const c = this.getCodeNorm();
if (c === GREATER) {
const { piTarget } = this;
if (piTarget.toLowerCase() === "xml") {
this.fail(
"the XML declaration must appear at the start of the document.");
}
this.piHandler?.({
target: piTarget,
body: this.text,
});
this.piTarget = this.text = "";
this.state = S_TEXT;
}
else if (c === QUESTION) {
// We ran into ?? as part of a processing instruction. We initially took
// the first ? as a sign that the PI was ending, but it is not. So we have
// to add it to the body but we take the new ? as a sign that the PI is
// ending.
this.text += "?";
}
else {
this.text += `?${String.fromCodePoint(c)}`;
this.state = S_PI_BODY;
}
this.xmlDeclPossible = false;
}
private sXMLDeclNameStart(): void {
const c = this.skipSpaces();
// The question mark character is not valid inside any of the XML
// declaration name/value pairs.
if (c === QUESTION) {
// It is valid to go to S_XML_DECL_ENDING from this state.
this.state = S_XML_DECL_ENDING;
return;
}
if (c !== EOC) {
this.state = S_XML_DECL_NAME;
this.name = String.fromCodePoint(c);
}
}
private sXMLDeclName(): void {
const c = this.captureTo(XML_DECL_NAME_TERMINATOR);
// The question mark character is not valid inside any of the XML
// declaration name/value pairs.
if (c === QUESTION) {
this.state = S_XML_DECL_ENDING;
this.name += this.text;
this.text = "";
this.fail("XML declaration is incomplete.");
return;
}
if (!(isS(c) || c === EQUAL)) {
return;
}
this.name += this.text;
this.text = "";
if (!this.xmlDeclExpects.includes(this.name)) {
switch (this.name.length) {
case 0:
this.fail("did not expect any more name/value pairs.");
break;
case 1:
this.fail(`expected the name ${this.xmlDeclExpects[0]}.`);
break;
default:
this.fail(`expected one of ${this.xmlDeclExpects.join(", ")}`);
}
}
this.state = c === EQUAL ? S_XML_DECL_VALUE_START : S_XML_DECL_EQ;
}
private sXMLDeclEq(): void {
const c = this.getCodeNorm();
// The question mark character is not valid inside any of the XML
// declaration name/value pairs.
if (c === QUESTION) {
this.state = S_XML_DECL_ENDING;
this.fail("XML declaration is incomplete.");
return;
}
if (isS(c)) {
return;
}
if (c !== EQUAL) {
this.fail("value required.");
}
this.state = S_XML_DECL_VALUE_START;
}
private sXMLDeclValueStart(): void {
const c = this.getCodeNorm();
// The question mark character is not valid inside any of the XML
// declaration name/value pairs.
if (c === QUESTION) {
this.state = S_XML_DECL_ENDING;
this.fail("XML declaration is incomplete.");
return;
}
if (isS(c)) {
return;
}
if (!isQuote(c)) {
this.fail("value must be quoted.");
this.q = SPACE;
}
else {
this.q = c;
}
this.state = S_XML_DECL_VALUE;
}
private sXMLDeclValue(): void {
const c = this.captureTo([this.q!, QUESTION]);
// The question mark character is not valid inside any of the XML
// declaration name/value pairs.
if (c === QUESTION) {
this.state = S_XML_DECL_ENDING;
this.text = "";
this.fail("XML declaration is incomplete.");
return;
}
if (c === EOC) {
return;
}
const value = this.text;
this.text = "";
switch (this.name) {
case "version": {
this.xmlDeclExpects = ["encoding", "standalone"];
const version = value;
this.xmlDecl.version = version;
// This is the test specified by XML 1.0 but it is fine for XML 1.1.
if (!/^1\.[0-9]+$/.test(version)) {
this.fail("version number must match /^1\\.[0-9]+$/.");
}
// When forceXMLVersion is set, the XML declaration is ignored.
else if (!(this.opt.forceXMLVersion as boolean)) {
this.setXMLVersion(version);
}
break;
}
case "encoding":
if (!/^[A-Za-z][A-Za-z0-9._-]*$/.test(value)) {
this.fail("encoding value must match \
/^[A-Za-z0-9][A-Za-z0-9._-]*$/.");
}
this.xmlDeclExpects = ["standalone"];
this.xmlDecl.encoding = value;
break;
case "standalone":
if (value !== "yes" && value !== "no") {
this.fail("standalone value must match \"yes\" or \"no\".");
}
this.xmlDeclExpects = [];
this.xmlDecl.standalone = value;
break;
default:
// We don't need to raise an error here since we've already raised one
// when checking what name was expected.
}
this.name = "";
this.state = S_XML_DECL_SEPARATOR;
}
private sXMLDeclSeparator(): void {
const c = this.getCodeNorm();
// The question mark character is not valid inside any of the XML
// declaration name/value pairs.
if (c === QUESTION) {
// It is valid to go to S_XML_DECL_ENDING from this state.
this.state = S_XML_DECL_ENDING;
return;
}
if (!isS(c)) {
this.fail("whitespace required.");
this.unget();
}
this.state = S_XML_DECL_NAME_START;
}
private sXMLDeclEnding(): void {
const c = this.getCodeNorm();
if (c === GREATER) {
if (this.piTarget !== "xml") {
this.fail("processing instructions are not allowed before root.");
}
else if (this.name !== "version" &&
this.xmlDeclExpects.includes("version")) {
this.fail("XML declaration must contain a version.");
}
this.xmldeclHandler?.(this.xmlDecl);
this.name = "";
this.piTarget = this.text = "";
this.state = S_TEXT;
}
else {
// We got here because the previous character was a ?, but the question
// mark character is not valid inside any of the XML declaration
// name/value pairs.
this.fail(
"The character ? is disallowed anywhere in XML declarations.");
}
this.xmlDeclPossible = false;
}
private sOpenTag(): void {
const c = this.captureNameChars();
if (c === EOC) {
return;
}
const tag: SaxesTagIncomplete = this.tag = {
name: this.name,
attributes: Object.create(null) as Record<string, string>,
};
this.name = "";
if (this.xmlnsOpt) {
this.topNS = tag.ns = Object.create(null) as Record<string, string>;
}
this.openTagStartHandler?.(tag as StartTagForOptions<O>);
this.sawRoot = true;
if (!this.fragmentOpt && this.closedRoot) {
this.fail("documents may contain only one root.");
}
switch (c) {
case GREATER:
this.openTag();
break;
case FORWARD_SLASH:
this.state = S_OPEN_TAG_SLASH;
break;
default:
if (!isS(c)) {
this.fail("disallowed character in tag name.");
}
this.state = S_ATTRIB;
}
}
private sOpenTagSlash(): void {
if (this.getCode() === GREATER) {
this.openSelfClosingTag();
}
else {
this.fail("forward-slash in opening tag not followed by >.");
this.state = S_ATTRIB;
}
}
private sAttrib(): void {
const c = this.skipSpaces();
if (c === EOC) {
return;
}
if (isNameStartChar(c)) {
this.unget();
this.state = S_ATTRIB_NAME;
}
else if (c === GREATER) {
this.openTag();
}
else if (c === FORWARD_SLASH) {
this.state = S_OPEN_TAG_SLASH;
}
else {
this.fail("disallowed character in attribute name.");
}
}
private sAttribName(): void {
const c = this.captureNameChars();
if (c === EQUAL) {
this.state = S_ATTRIB_VALUE;
}
else if (isS(c)) {
this.state = S_ATTRIB_NAME_SAW_WHITE;
}
else if (c === GREATER) {
this.fail("attribute without value.");
this.pushAttrib(this.name, this.name);
this.name = this.text = "";
this.openTag();
}
else if (c !== EOC) {
this.fail("disallowed character in attribute name.");
}
}
private sAttribNameSawWhite(): void {
const c = this.skipSpaces();
switch (c) {
case EOC:
return;
case EQUAL:
this.state = S_ATTRIB_VALUE;
break;
default:
this.fail("attribute without value.");
// Should we do this???
// this.tag.attributes[this.name] = "";
this.text = "";
this.name = "";
if (c === GREATER) {
this.openTag();
}
else if (isNameStartChar(c)) {
this.unget();
this.state = S_ATTRIB_NAME;
}
else {
this.fail("disallowed character in attribute name.");
this.state = S_ATTRIB;
}
}
}
private sAttribValue(): void {
const c = this.getCodeNorm();
if (isQuote(c)) {
this.q = c;
this.state = S_ATTRIB_VALUE_QUOTED;
}
else if (!isS(c)) {
this.fail("unquoted attribute value.");
this.state = S_ATTRIB_VALUE_UNQUOTED;
this.unget();
}
}
private sAttribValueQuoted(): void {
// We deliberately do not use captureTo here. The specialized code we use
// here is faster than using captureTo.
const { q, chunk } = this;
let { i: start } = this;
// eslint-disable-next-line no-constant-condition
while (true) {
switch (this.getCode()) {
case q:
this.pushAttrib(this.name,
this.text + chunk.slice(start, this.prevI));
this.name = this.text = "";
this.q = null;
this.state = S_ATTRIB_VALUE_CLOSED;
return;
case AMP:
this.text += chunk.slice(start, this.prevI);
this.state = S_ENTITY;
this.entityReturnState = S_ATTRIB_VALUE_QUOTED;
return;
case NL:
case NL_LIKE:
case TAB:
this.text += `${chunk.slice(start, this.prevI)} `;
start = this.i;
break;
case LESS:
this.text += chunk.slice(start, this.prevI);
this.fail("disallowed character.");
return;
case EOC:
this.text += chunk.slice(start);
return;
default:
}
}
}
private sAttribValueClosed(): void {
const c = this.getCodeNorm();
if (isS(c)) {
this.state = S_ATTRIB;
}
else if (c === GREATER) {
this.openTag();
}
else if (c === FORWARD_SLASH) {
this.state = S_OPEN_TAG_SLASH;
}
else if (isNameStartChar(c)) {
this.fail("no whitespace between attributes.");
this.unget();
this.state = S_ATTRIB_NAME;
}
else {
this.fail("disallowed character in attribute name.");
}
}
private sAttribValueUnquoted(): void {
// We don't do anything regarding EOL or space handling for unquoted
// attributes. We already have failed by the time we get here, and the
// contract that saxes upholds states that upon failure, it is not safe to
// rely on the data passed to event handlers (other than
// ``onerror``). Passing "bad" data is not a problem.
const c = this.captureTo(ATTRIB_VALUE_UNQUOTED_TERMINATOR);
switch (c) {
case AMP:
this.state = S_ENTITY;
this.entityReturnState = S_ATTRIB_VALUE_UNQUOTED;
break;
case LESS:
this.fail("disallowed character.");
break;
case EOC:
break;
default:
if (this.text.includes("]]>")) {
this.fail("the string \"]]>\" is disallowed in char data.");
}
this.pushAttrib(this.name, this.text);
this.name = this.text = "";
if (c === GREATER) {
this.openTag();
}
else {
this.state = S_ATTRIB;
}
}
}
private sCloseTag(): void {
const c = this.captureNameChars();
if (c === GREATER) {
this.closeTag();
}
else if (isS(c)) {
this.state = S_CLOSE_TAG_SAW_WHITE;
}
else if (c !== EOC) {
this.fail("disallowed character in closing tag.");
}
}
private sCloseTagSawWhite(): void {
switch (this.skipSpaces()) {
case GREATER:
this.closeTag();
break;
case EOC:
break;
default:
this.fail("disallowed character in closing tag.");
}
}
// END OF STATE ENGINE METHODS
private handleTextInRoot(): void {
// This is essentially a specialized version of captureTo which is optimized
// for performing the ]]> check. A previous version of this code, checked
// ``this.text`` for the presence of ]]>. It simplified the code but was
// very costly when character data contained a lot of entities to be parsed.
//
// Since we are using a specialized loop, we also keep track of the presence
// of ]]> in text data. The sequence ]]> is forbidden to appear as-is.
//
let { i: start, forbiddenState } = this;
const { chunk, textHandler: handler } = this;
// eslint-disable-next-line no-labels, no-restricted-syntax
scanLoop:
// eslint-disable-next-line no-constant-condition
while (true) {
switch (this.getCode()) {
case LESS: {
this.state = S_OPEN_WAKA;
if (handler !== undefined) {
const { text } = this;
const slice = chunk.slice(start, this.prevI);
if (text.length !== 0) {
handler(text + slice);
this.text = "";
}
else if (slice.length !== 0) {
handler(slice);
}
}
forbiddenState = FORBIDDEN_START;
// eslint-disable-next-line no-labels
break scanLoop;
}
case AMP:
this.state = S_ENTITY;
this.entityReturnState = S_TEXT;
if (handler !== undefined) {
this.text += chunk.slice(start, this.prevI);
}
forbiddenState = FORBIDDEN_START;
// eslint-disable-next-line no-labels
break scanLoop;
case CLOSE_BRACKET:
switch (forbiddenState) {
case FORBIDDEN_START:
forbiddenState = FORBIDDEN_BRACKET;
break;
case FORBIDDEN_BRACKET:
forbiddenState = FORBIDDEN_BRACKET_BRACKET;
break;
case FORBIDDEN_BRACKET_BRACKET:
break;
default:
throw new Error("impossible state");
}
break;
case GREATER:
if (forbiddenState === FORBIDDEN_BRACKET_BRACKET) {
this.fail("the string \"]]>\" is disallowed in char data.");
}
forbiddenState = FORBIDDEN_START;
break;
case NL_LIKE:
if (handler !== undefined) {
this.text += `${chunk.slice(start, this.prevI)}\n`;
}
start = this.i;
forbiddenState = FORBIDDEN_START;
break;
case EOC:
if (handler !== undefined) {
this.text += chunk.slice(start);
}
// eslint-disable-next-line no-labels
break scanLoop;
default:
forbiddenState = FORBIDDEN_START;
}
}
this.forbiddenState = forbiddenState;
}
private handleTextOutsideRoot(): void {
// This is essentially a specialized version of captureTo which is optimized
// for a specialized task. We keep track of the presence of non-space
// characters in the text since these are errors when appearing outside the
// document root element.
let { i: start } = this;
const { chunk, textHandler: handler } = this;
let nonSpace = false;
// eslint-disable-next-line no-labels, no-restricted-syntax
outRootLoop:
// eslint-disable-next-line no-constant-condition
while (true) {
const code = this.getCode();
switch (code) {
case LESS: {
this.state = S_OPEN_WAKA;
if (handler !== undefined) {
const { text } = this;
const slice = chunk.slice(start, this.prevI);
if (text.length !== 0) {
handler(text + slice);
this.text = "";
}
else if (slice.length !== 0) {
handler(slice);
}
}
// eslint-disable-next-line no-labels
break outRootLoop;
}
case AMP:
this.state = S_ENTITY;
this.entityReturnState = S_TEXT;
if (handler !== undefined) {
this.text += chunk.slice(start, this.prevI);
}
nonSpace = true;
// eslint-disable-next-line no-labels
break outRootLoop;
case NL_LIKE:
if (handler !== undefined) {
this.text += `${chunk.slice(start, this.prevI)}\n`;
}
start = this.i;
break;
case EOC:
if (handler !== undefined) {
this.text += chunk.slice(start);
}
// eslint-disable-next-line no-labels
break outRootLoop;
default:
if (!isS(code)) {
nonSpace = true;
}
}
}
if (!nonSpace) {
return;
}
// We use the reportedTextBeforeRoot and reportedTextAfterRoot flags
// to avoid reporting errors for every single character that is out of
// place.
if (!this.sawRoot && !this.reportedTextBeforeRoot) {
this.fail("text data outside of root node.");
this.reportedTextBeforeRoot = true;
}
if (this.closedRoot && !this.reportedTextAfterRoot) {
this.fail("text data outside of root node.");
this.reportedTextAfterRoot = true;
}
}
private pushAttribNS(name: string, value: string): void {
const { prefix, local } = this.qname(name);
const attr = { name, prefix, local, value };
this.attribList.push(attr);
this.attributeHandler?.(attr as AttributeEventForOptions<O>);
if (prefix === "xmlns") {
const trimmed = value.trim();
if (this.currentXMLVersion === "1.0" && trimmed === "") {
this.fail("invalid attempt to undefine prefix in XML 1.0");
}
this.topNS![local] = trimmed;
nsPairCheck(this, local, trimmed);
}
else if (name === "xmlns") {
const trimmed = value.trim();
this.topNS![""] = trimmed;
nsPairCheck(this, "", trimmed);
}
}
private pushAttribPlain(name: string, value: string): void {
const attr = { name, value };
this.attribList.push(attr);
this.attributeHandler?.(attr as AttributeEventForOptions<O>);
}
/**
* End parsing. This performs final well-formedness checks and resets the
* parser to a clean state.
*
* @returns this
*/
private end(): this {
if (!this.sawRoot) {
this.fail("document must contain a root element.");
}
const { tags } = this;
while (tags.length > 0) {
const tag = tags.pop()!;
this.fail(`unclosed tag: ${tag.name}`);
}
if ((this.state !== S_BEGIN) && (this.state !== S_TEXT)) {
this.fail("unexpected end.");
}
const { text } = this;
if (text.length !== 0) {
this.textHandler?.(text);
this.text = "";
}
this._closed = true;
this.endHandler?.();
this._init();
return this;
}
/**
* Resolve a namespace prefix.
*
* @param prefix The prefix to resolve.
*
* @returns The namespace URI or ``undefined`` if the prefix is not defined.
*/
resolve(prefix: string): string | undefined {
let uri = this.topNS![prefix];
if (uri !== undefined) {
return uri;
}
const { tags } = this;
for (let index = tags.length - 1; index >= 0; index--) {
uri = tags[index]!.ns![prefix];
if (uri !== undefined) {
return uri;
}
}
uri = this.ns[prefix];
if (uri !== undefined) {
return uri;
}
return this.opt.resolvePrefix?.(prefix);
}
/**
* Parse a qname into its prefix and local name parts.
*
* @param name The name to parse
*
* @returns
*/
private qname(name: string): { prefix: string; local: string } {
// This is faster than using name.split(":").
const colon = name.indexOf(":");
if (colon === -1) {
return { prefix: "", local: name };
}
const local = name.slice(colon + 1);
const prefix = name.slice(0, colon);
if (prefix === "" || local === "" || local.includes(":")) {
this.fail(`malformed name: ${name}.`);
}
return { prefix, local };
}
private processAttribsNS(): void {
const { attribList } = this;
const tag = this.tag!;
{
// add namespace info to tag
const { prefix, local } = this.qname(tag.name);
tag.prefix = prefix;
tag.local = local;
const uri = tag.uri = this.resolve(prefix) ?? "";
if (prefix !== "") {
if (prefix === "xmlns") {
this.fail("tags may not have \"xmlns\" as prefix.");
}
if (uri === "") {
this.fail(`unbound namespace prefix: ${JSON.stringify(prefix)}.`);
tag.uri = prefix;
}
}
}
if (attribList.length === 0) {
return;
}
const { attributes } = tag;
const seen = new Set();
// Note: do not apply default ns to attributes:
// http://www.w3.org/TR/REC-xml-names/#defaulting
for (const attr of attribList as SaxesAttributeNSIncomplete[]) {
const { name, prefix, local } = attr;
let uri;
let eqname;
if (prefix === "") {
uri = name === "xmlns" ? XMLNS_NAMESPACE : "";
eqname = name;
}
else {
uri = this.resolve(prefix);
// if there's any attributes with an undefined namespace,
// then fail on them now.
if (uri === undefined) {
this.fail(`unbound namespace prefix: ${JSON.stringify(prefix)}.`);
uri = prefix;
}
eqname = `{${uri}}${local}`;
}
if (seen.has(eqname)) {
this.fail(`duplicate attribute: ${eqname}.`);
}
seen.add(eqname);
attr.uri = uri;
attributes[name] = attr;
}
this.attribList = [];
}
private processAttribsPlain(): void {
const { attribList } = this;
// eslint-disable-next-line prefer-destructuring
const attributes = this.tag!.attributes;
for (const { name, value } of attribList) {
if (attributes[name] !== undefined) {
this.fail(`duplicate attribute: ${name}.`);
}
attributes[name] = value;
}
this.attribList = [];
}
/**
* Handle a complete open tag. This parser code calls this once it has seen
* the whole tag. This method checks for well-formeness and then emits
* ``onopentag``.
*/
private openTag(): void {
this.processAttribs();
const { tags } = this;
const tag = this.tag as SaxesTag;
tag.isSelfClosing = false;
// There cannot be any pending text here due to the onopentagstart that was
// necessarily emitted before we get here. So we do not check text.
this.openTagHandler?.(tag as TagForOptions<O>);
tags.push(tag);
this.state = S_TEXT;
this.name = "";
}
/**
* Handle a complete self-closing tag. This parser code calls this once it has
* seen the whole tag. This method checks for well-formeness and then emits
* ``onopentag`` and ``onclosetag``.
*/
private openSelfClosingTag(): void {
this.processAttribs();
const { tags } = this;
const tag = this.tag as SaxesTag;
tag.isSelfClosing = true;
// There cannot be any pending text here due to the onopentagstart that was
// necessarily emitted before we get here. So we do not check text.
this.openTagHandler?.(tag as TagForOptions<O>);
this.closeTagHandler?.(tag as TagForOptions<O>);
const top = this.tag = tags[tags.length - 1] ?? null;
if (top === null) {
this.closedRoot = true;
}
this.state = S_TEXT;
this.name = "";
}
/**
* Handle a complete close tag. This parser code calls this once it has seen
* the whole tag. This method checks for well-formeness and then emits
* ``onclosetag``.
*/
private closeTag(): void {
const { tags, name } = this;
// Our state after this will be S_TEXT, no matter what, and we can clear
// tagName now.
this.state = S_TEXT;
this.name = "";
if (name === "") {
this.fail("weird empty close tag.");
this.text += "</>";
return;
}
const handler = this.closeTagHandler;
let l = tags.length;
while (l-- > 0) {
const tag = this.tag = tags.pop() as SaxesTag;
this.topNS = tag.ns!;
handler?.(tag as TagForOptions<O>);
if (tag.name === name) {
break;
}
this.fail("unexpected close tag.");
}
if (l === 0) {
this.closedRoot = true;
}
else if (l < 0) {
this.fail(`unmatched closing tag: ${name}.`);
this.text += `</${name}>`;
}
}
/**
* Resolves an entity. Makes any necessary well-formedness checks.
*
* @param entity The entity to resolve.
*
* @returns The parsed entity.
*/
private parseEntity(entity: string): string {
// startsWith would be significantly slower for this test.
if (entity[0] !== "#") {
const defined = this.ENTITIES[entity];
if (defined !== undefined) {
return defined;
}
this.fail(this.isName(entity) ? "undefined entity." :
"disallowed character in entity name.");
return `&${entity};`;
}
let num = NaN;
if (entity[1] === "x" && /^#x[0-9a-f]+$/i.test(entity)) {
num = parseInt(entity.slice(2), 16);
}
else if (/^#[0-9]+$/.test(entity)) {
num = parseInt(entity.slice(1), 10);
}
// The character reference is required to match the CHAR production.
if (!this.isChar(num)) {
this.fail("malformed character entity.");
return `&${entity};`;
}
return String.fromCodePoint(num);
}
} |
1,153 | (decl: XMLDecl) => void | interface XMLDecl {
/** The version specified by the XML declaration. */
version?: string;
/** The encoding specified by the XML declaration. */
encoding?: string;
/** The value of the standalone parameter */
standalone?: string;
} |
1,154 | off(name: EventName): void {
// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-member-access
(this as any)[EVENT_NAME_TO_HANDLER_NAME[name]] = undefined;
} | type EventName = (typeof EVENTS)[number]; |
1,155 | (element: Element) => void | class Element extends NodeWithChildren {
/**
* @param name Name of the tag, eg. `div`, `span`.
* @param attribs Object mapping attribute names to attribute values.
* @param children Children of the node.
*/
constructor(
public name: string,
public attribs: { [name: string]: string },
children: ChildNode[] = [],
public type:
| ElementType.Tag
| ElementType.Script
| ElementType.Style = name === "script"
? ElementType.Script
: name === "style"
? ElementType.Style
: ElementType.Tag
) {
super(children);
}
get nodeType(): 1 {
return 1;
}
/**
* `parse5` source code location info, with start & end tags.
*
* Available if parsing with parse5 and location info is enabled.
*/
sourceCodeLocation?: TagSourceCodeLocation | null;
// DOM Level 1 aliases
/**
* Same as {@link name}.
* [DOM spec](https://dom.spec.whatwg.org)-compatible alias.
*/
get tagName(): string {
return this.name;
}
set tagName(name: string) {
this.name = name;
}
get attributes(): Attribute[] {
return Object.keys(this.attribs).map((name) => ({
name,
value: this.attribs[name],
namespace: this["x-attribsNamespace"]?.[name],
prefix: this["x-attribsPrefix"]?.[name],
}));
}
/** Element namespace (parse5 only). */
namespace?: string;
/** Element attribute namespaces (parse5 only). */
"x-attribsNamespace"?: Record<string, string>;
/** Element attribute namespace-related prefixes (parse5 only). */
"x-attribsPrefix"?: Record<string, string>;
} |
1,156 | public onparserinit(parser: ParserInterface): void {
this.parser = parser;
} | interface ParserInterface {
startIndex: number | null;
endIndex: number | null;
} |
1,157 | protected addNode(node: ChildNode): void {
const parent = this.tagStack[this.tagStack.length - 1];
const previousSibling = parent.children[parent.children.length - 1] as
| ChildNode
| undefined;
if (this.options.withStartIndices) {
node.startIndex = this.parser!.startIndex;
}
if (this.options.withEndIndices) {
node.endIndex = this.parser!.endIndex;
}
parent.children.push(node);
if (previousSibling) {
node.prev = previousSibling;
previousSibling.next = node;
}
node.parent = parent;
this.lastNode = null;
} | type ChildNode =
| Text
| Comment
| ProcessingInstruction
| Element
| CDATA
// `Document` is also used for document fragments, and can be a child node.
| Document; |
1,158 | (fork: Fork) => T | type Fork = {
use<T>(plugin: Plugin<T>): T;
}; |
1,159 | function typesPlugin(_fork: Fork) {
const Type = {
or(...types: any[]): Type<any> {
return new OrType(types.map(type => Type.from(type)));
},
from<T>(value: any, name?: string): Type<T> {
if (
value instanceof ArrayType ||
value instanceof IdentityType ||
value instanceof ObjectType ||
value instanceof OrType ||
value instanceof PredicateType
) {
return value;
}
// The Def type is used as a helper for constructing compound
// interface types for AST nodes.
if (value instanceof Def) {
return value.type;
}
// Support [ElemType] syntax.
if (isArray.check(value)) {
if (value.length !== 1) {
throw new Error("only one element type is permitted for typed arrays");
}
return new ArrayType(Type.from(value[0]));
}
// Support { someField: FieldType, ... } syntax.
if (isObject.check(value)) {
return new ObjectType(Object.keys(value).map(name => {
return new Field(name, Type.from(value[name], name));
}));
}
if (typeof value === "function") {
var bicfIndex = builtInCtorFns.indexOf(value);
if (bicfIndex >= 0) {
return builtInCtorTypes[bicfIndex];
}
if (typeof name !== "string") {
throw new Error("missing name");
}
return new PredicateType(name, value);
}
// As a last resort, toType returns a type that matches any value that
// is === from. This is primarily useful for literal values like
// toType(null), but it has the additional advantage of allowing
// toType to be a total function.
return new IdentityType(value);
},
// Define a type whose name is registered in a namespace (the defCache) so
// that future definitions will return the same type given the same name.
// In particular, this system allows for circular and forward definitions.
// The Def object d returned from Type.def may be used to configure the
// type d.type by calling methods such as d.bases, d.build, and d.field.
def(typeName: string): Def {
return hasOwn.call(defCache, typeName)
? defCache[typeName]
: defCache[typeName] = new DefImpl(typeName);
},
hasDef(typeName: string) {
return hasOwn.call(defCache, typeName);
}
};
var builtInCtorFns: Function[] = [];
var builtInCtorTypes: Type<any>[] = [];
type BuiltInTypes = {
string: string;
function: Function;
array: any[];
object: { [key: string]: any };
RegExp: RegExp;
Date: Date;
number: number;
boolean: boolean;
null: null;
undefined: undefined;
BigInt: BigInt;
};
function defBuiltInType<K extends keyof BuiltInTypes>(
name: K,
example: BuiltInTypes[K]
): Type<BuiltInTypes[K]> {
const objStr: string = objToStr.call(example);
const type = new PredicateType<BuiltInTypes[K]>(
name,
value => objToStr.call(value) === objStr);
if (example && typeof example.constructor === "function") {
builtInCtorFns.push(example.constructor);
builtInCtorTypes.push(type);
}
return type;
}
// These types check the underlying [[Class]] attribute of the given
// value, rather than using the problematic typeof operator. Note however
// that no subtyping is considered; so, for instance, isObject.check
// returns false for [], /./, new Date, and null.
const isString = defBuiltInType("string", "truthy");
const isFunction = defBuiltInType("function", function () {});
const isArray = defBuiltInType("array", []);
const isObject = defBuiltInType("object", {});
const isRegExp = defBuiltInType("RegExp", /./);
const isDate = defBuiltInType("Date", new Date());
const isNumber = defBuiltInType("number", 3);
const isBoolean = defBuiltInType("boolean", true);
const isNull = defBuiltInType("null", null);
const isUndefined = defBuiltInType("undefined", undefined);
const isBigInt = typeof BigInt === "function"
? defBuiltInType("BigInt", BigInt(1234))
: new PredicateType<BigInt>("BigInt", () => false);
const builtInTypes = {
string: isString,
function: isFunction,
array: isArray,
object: isObject,
RegExp: isRegExp,
Date: isDate,
number: isNumber,
boolean: isBoolean,
null: isNull,
undefined: isUndefined,
BigInt: isBigInt,
};
// In order to return the same Def instance every time Type.def is called
// with a particular name, those instances need to be stored in a cache.
var defCache: { [typeName: string]: Def<any> } = Object.create(null);
function defFromValue(value: any): Def<any> | null {
if (value && typeof value === "object") {
var type = value.type;
if (typeof type === "string" &&
hasOwn.call(defCache, type)) {
var d = defCache[type];
if (d.finalized) {
return d;
}
}
}
return null;
}
class DefImpl<T = any> extends Def<T> {
constructor(typeName: string) {
super(
new PredicateType<T>(typeName, (value, deep) => this.check(value, deep)),
typeName,
);
}
check(value: any, deep?: any): boolean {
if (this.finalized !== true) {
throw new Error(
"prematurely checking unfinalized type " + this.typeName
);
}
// A Def type can only match an object value.
if (value === null || typeof value !== "object") {
return false;
}
var vDef = defFromValue(value);
if (!vDef) {
// If we couldn't infer the Def associated with the given value,
// and we expected it to be a SourceLocation or a Position, it was
// probably just missing a "type" field (because Esprima does not
// assign a type property to such nodes). Be optimistic and let
// this.checkAllFields make the final decision.
if (this.typeName === "SourceLocation" ||
this.typeName === "Position") {
return this.checkAllFields(value, deep);
}
// Calling this.checkAllFields for any other type of node is both
// bad for performance and way too forgiving.
return false;
}
// If checking deeply and vDef === this, then we only need to call
// checkAllFields once. Calling checkAllFields is too strict when deep
// is false, because then we only care about this.isSupertypeOf(vDef).
if (deep && vDef === this) {
return this.checkAllFields(value, deep);
}
// In most cases we rely exclusively on isSupertypeOf to make O(1)
// subtyping determinations. This suffices in most situations outside
// of unit tests, since interface conformance is checked whenever new
// instances are created using builder functions.
if (!this.isSupertypeOf(vDef)) {
return false;
}
// The exception is when deep is true; then, we recursively check all
// fields.
if (!deep) {
return true;
}
// Use the more specific Def (vDef) to perform the deep check, but
// shallow-check fields defined by the less specific Def (this).
return vDef.checkAllFields(value, deep)
&& this.checkAllFields(value, false);
}
build(...buildParams: string[]): this {
// Calling Def.prototype.build multiple times has the effect of merely
// redefining this property.
this.buildParams = buildParams;
if (this.buildable) {
// If this Def is already buildable, update self.buildParams and
// continue using the old builder function.
return this;
}
// Every buildable type will have its "type" field filled in
// automatically. This includes types that are not subtypes of Node,
// like SourceLocation, but that seems harmless (TODO?).
this.field("type", String, () => this.typeName);
// Override Dp.buildable for this Def instance.
this.buildable = true;
const addParam = (built: any, param: any, arg: any, isArgAvailable: boolean) => {
if (hasOwn.call(built, param))
return;
var all = this.allFields;
if (!hasOwn.call(all, param)) {
throw new Error("" + param);
}
var field = all[param];
var type = field.type;
var value;
if (isArgAvailable) {
value = arg;
} else if (field.defaultFn) {
// Expose the partially-built object to the default
// function as its `this` object.
value = field.defaultFn.call(built);
} else {
var message = "no value or default function given for field " +
JSON.stringify(param) + " of " + this.typeName + "(" +
this.buildParams.map(function (name) {
return all[name];
}).join(", ") + ")";
throw new Error(message);
}
if (!type.check(value)) {
throw new Error(
shallowStringify(value) +
" does not match field " + field +
" of type " + this.typeName
);
}
built[param] = value;
}
// Calling the builder function will construct an instance of the Def,
// with positional arguments mapped to the fields original passed to .build.
// If not enough arguments are provided, the default value for the remaining fields
// will be used.
const builder: Builder = (...args: any[]) => {
var argc = args.length;
if (!this.finalized) {
throw new Error(
"attempting to instantiate unfinalized type " +
this.typeName
);
}
var built: ASTNode = Object.create(nodePrototype);
this.buildParams.forEach(function (param, i) {
if (i < argc) {
addParam(built, param, args[i], true)
} else {
addParam(built, param, null, false);
}
});
Object.keys(this.allFields).forEach(function (param) {
// Use the default value.
addParam(built, param, null, false);
});
// Make sure that the "type" field was filled automatically.
if (built.type !== this.typeName) {
throw new Error("");
}
return built;
}
// Calling .from on the builder function will construct an instance of the Def,
// using field values from the passed object. For fields missing from the passed object,
// their default value will be used.
builder.from = (obj: { [fieldName: string]: any }) => {
if (!this.finalized) {
throw new Error(
"attempting to instantiate unfinalized type " +
this.typeName
);
}
var built: ASTNode = Object.create(nodePrototype);
Object.keys(this.allFields).forEach(function (param) {
if (hasOwn.call(obj, param)) {
addParam(built, param, obj[param], true);
} else {
addParam(built, param, null, false);
}
});
// Make sure that the "type" field was filled automatically.
if (built.type !== this.typeName) {
throw new Error("");
}
return built;
}
Object.defineProperty(builders, getBuilderName(this.typeName), {
enumerable: true,
value: builder
});
return this;
}
// The reason fields are specified using .field(...) instead of an object
// literal syntax is somewhat subtle: the object literal syntax would
// support only one key and one value, but with .field(...) we can pass
// any number of arguments to specify the field.
field(
name: string,
type: any,
defaultFn?: Function,
hidden?: boolean,
): this {
if (this.finalized) {
console.error("Ignoring attempt to redefine field " +
JSON.stringify(name) + " of finalized type " +
JSON.stringify(this.typeName));
return this;
}
this.ownFields[name] = new Field(name, Type.from(type), defaultFn, hidden);
return this; // For chaining.
}
finalize() {
// It's not an error to finalize a type more than once, but only the
// first call to .finalize does anything.
if (!this.finalized) {
var allFields = this.allFields;
var allSupertypes = this.allSupertypes;
this.baseNames.forEach(name => {
var def = defCache[name];
if (def instanceof Def) {
def.finalize();
extend(allFields, def.allFields);
extend(allSupertypes, def.allSupertypes);
} else {
var message = "unknown supertype name " +
JSON.stringify(name) +
" for subtype " +
JSON.stringify(this.typeName);
throw new Error(message);
}
});
// TODO Warn if fields are overridden with incompatible types.
extend(allFields, this.ownFields);
allSupertypes[this.typeName] = this;
this.fieldNames.length = 0;
for (var fieldName in allFields) {
if (hasOwn.call(allFields, fieldName) &&
!allFields[fieldName].hidden) {
this.fieldNames.push(fieldName);
}
}
// Types are exported only once they have been finalized.
Object.defineProperty(namedTypes, this.typeName, {
enumerable: true,
value: this.type
});
this.finalized = true;
// A linearization of the inheritance hierarchy.
populateSupertypeList(this.typeName, this.supertypeList);
if (this.buildable &&
this.supertypeList.lastIndexOf("Expression") >= 0) {
wrapExpressionBuilderWithStatement(this.typeName);
}
}
}
}
// Note that the list returned by this function is a copy of the internal
// supertypeList, *without* the typeName itself as the first element.
function getSupertypeNames(typeName: string): string[] {
if (!hasOwn.call(defCache, typeName)) {
throw new Error("");
}
var d = defCache[typeName];
if (d.finalized !== true) {
throw new Error("");
}
return d.supertypeList.slice(1);
}
// Returns an object mapping from every known type in the defCache to the
// most specific supertype whose name is an own property of the candidates
// object.
function computeSupertypeLookupTable(candidates: any) {
var table: { [typeName: string ]: any } = {};
var typeNames = Object.keys(defCache);
var typeNameCount = typeNames.length;
for (var i = 0; i < typeNameCount; ++i) {
var typeName = typeNames[i];
var d = defCache[typeName];
if (d.finalized !== true) {
throw new Error("" + typeName);
}
for (var j = 0; j < d.supertypeList.length; ++j) {
var superTypeName = d.supertypeList[j];
if (hasOwn.call(candidates, superTypeName)) {
table[typeName] = superTypeName;
break;
}
}
}
return table;
}
var builders: import("./gen/builders").builders = Object.create(null);
// This object is used as prototype for any node created by a builder.
var nodePrototype: { [definedMethod: string]: Function } = {};
// Call this function to define a new method to be shared by all AST
// nodes. The replaced method (if any) is returned for easy wrapping.
function defineMethod(name: any, func?: Function) {
var old = nodePrototype[name];
// Pass undefined as func to delete nodePrototype[name].
if (isUndefined.check(func)) {
delete nodePrototype[name];
} else {
isFunction.assert(func);
Object.defineProperty(nodePrototype, name, {
enumerable: true, // For discoverability.
configurable: true, // For delete proto[name].
value: func
});
}
return old;
}
function getBuilderName(typeName: any) {
return typeName.replace(/^[A-Z]+/, function (upperCasePrefix: any) {
var len = upperCasePrefix.length;
switch (len) {
case 0: return "";
// If there's only one initial capital letter, just lower-case it.
case 1: return upperCasePrefix.toLowerCase();
default:
// If there's more than one initial capital letter, lower-case
// all but the last one, so that XMLDefaultDeclaration (for
// example) becomes xmlDefaultDeclaration.
return upperCasePrefix.slice(
0, len - 1).toLowerCase() +
upperCasePrefix.charAt(len - 1);
}
});
}
function getStatementBuilderName(typeName: any) {
typeName = getBuilderName(typeName);
return typeName.replace(/(Expression)?$/, "Statement");
}
var namedTypes = {} as import("./gen/namedTypes").NamedTypes;
// Like Object.keys, but aware of what fields each AST type should have.
function getFieldNames(object: any) {
var d = defFromValue(object);
if (d) {
return d.fieldNames.slice(0);
}
if ("type" in object) {
throw new Error(
"did not recognize object of type " +
JSON.stringify(object.type)
);
}
return Object.keys(object);
}
// Get the value of an object property, taking object.type and default
// functions into account.
function getFieldValue(object: any, fieldName: any) {
var d = defFromValue(object);
if (d) {
var field = d.allFields[fieldName];
if (field) {
return field.getValue(object);
}
}
return object && object[fieldName];
}
// Iterate over all defined fields of an object, including those missing
// or undefined, passing each field name and effective value (as returned
// by getFieldValue) to the callback. If the object has no corresponding
// Def, the callback will never be called.
function eachField(
object: any,
callback: (name: any, value: any) => any,
context?: any
) {
getFieldNames(object).forEach(function (this: any, name: any) {
callback.call(this, name, getFieldValue(object, name));
}, context);
}
// Similar to eachField, except that iteration stops as soon as the
// callback returns a truthy value. Like Array.prototype.some, the final
// result is either true or false to indicates whether the callback
// returned true for any element or not.
function someField(
object: any,
callback: (name: any, value: any) => any,
context?: any
) {
return getFieldNames(object).some(function (this: any, name: any) {
return callback.call(this, name, getFieldValue(object, name));
}, context);
}
// Adds an additional builder for Expression subtypes
// that wraps the built Expression in an ExpressionStatements.
function wrapExpressionBuilderWithStatement(typeName: string) {
var wrapperName = getStatementBuilderName(typeName);
// skip if the builder already exists
if (builders[wrapperName]) return;
// the builder function to wrap with builders.ExpressionStatement
var wrapped = builders[getBuilderName(typeName)];
// skip if there is nothing to wrap
if (!wrapped) return;
const builder: Builder = function (...args: Parameters<typeof wrapped>) {
return builders.expressionStatement(wrapped.apply(builders, args));
};
builder.from = function (...args: Parameters<typeof wrapped.from>) {
return builders.expressionStatement(wrapped.from.apply(builders, args));
}
builders[wrapperName] = builder;
}
function populateSupertypeList(typeName: any, list: any) {
list.length = 0;
list.push(typeName);
var lastSeen = Object.create(null);
for (var pos = 0; pos < list.length; ++pos) {
typeName = list[pos];
var d = defCache[typeName];
if (d.finalized !== true) {
throw new Error("");
}
// If we saw typeName earlier in the breadth-first traversal,
// delete the last-seen occurrence.
if (hasOwn.call(lastSeen, typeName)) {
delete list[lastSeen[typeName]];
}
// Record the new index of the last-seen occurrence of typeName.
lastSeen[typeName] = pos;
// Enqueue the base names of this type.
list.push.apply(list, d.baseNames);
}
// Compaction loop to remove array holes.
for (var to = 0, from = to, len = list.length; from < len; ++from) {
if (hasOwn.call(list, from)) {
list[to++] = list[from];
}
}
list.length = to;
}
function extend(into: any, from: any) {
Object.keys(from).forEach(function (name) {
into[name] = from[name];
});
return into;
}
function finalize() {
Object.keys(defCache).forEach(function (name) {
defCache[name].finalize();
});
}
return {
Type,
builtInTypes,
getSupertypeNames,
computeSupertypeLookupTable,
builders,
defineMethod,
getBuilderName,
getStatementBuilderName,
namedTypes,
getFieldNames,
getFieldValue,
eachField,
someField,
finalize,
};
} | type Fork = {
use<T>(plugin: Plugin<T>): T;
}; |
1,160 | function (fork: Fork) {
var types = fork.use(typesPlugin);
var getFieldNames = types.getFieldNames;
var getFieldValue = types.getFieldValue;
var isArray = types.builtInTypes.array;
var isObject = types.builtInTypes.object;
var isDate = types.builtInTypes.Date;
var isRegExp = types.builtInTypes.RegExp;
var hasOwn = Object.prototype.hasOwnProperty;
function astNodesAreEquivalent(a: any, b: any, problemPath?: any) {
if (isArray.check(problemPath)) {
problemPath.length = 0;
} else {
problemPath = null;
}
return areEquivalent(a, b, problemPath);
}
astNodesAreEquivalent.assert = function (a: any, b: any) {
var problemPath: any[] = [];
if (!astNodesAreEquivalent(a, b, problemPath)) {
if (problemPath.length === 0) {
if (a !== b) {
throw new Error("Nodes must be equal");
}
} else {
throw new Error(
"Nodes differ in the following path: " +
problemPath.map(subscriptForProperty).join("")
);
}
}
};
function subscriptForProperty(property: any) {
if (/[_$a-z][_$a-z0-9]*/i.test(property)) {
return "." + property;
}
return "[" + JSON.stringify(property) + "]";
}
function areEquivalent(a: any, b: any, problemPath: any) {
if (a === b) {
return true;
}
if (isArray.check(a)) {
return arraysAreEquivalent(a, b, problemPath);
}
if (isObject.check(a)) {
return objectsAreEquivalent(a, b, problemPath);
}
if (isDate.check(a)) {
return isDate.check(b) && (+a === +b);
}
if (isRegExp.check(a)) {
return isRegExp.check(b) && (
a.source === b.source &&
a.global === b.global &&
a.multiline === b.multiline &&
a.ignoreCase === b.ignoreCase
);
}
return a == b;
}
function arraysAreEquivalent(a: any, b: any, problemPath: any) {
isArray.assert(a);
var aLength = a.length;
if (!isArray.check(b) || b.length !== aLength) {
if (problemPath) {
problemPath.push("length");
}
return false;
}
for (var i = 0; i < aLength; ++i) {
if (problemPath) {
problemPath.push(i);
}
if (i in a !== i in b) {
return false;
}
if (!areEquivalent(a[i], b[i], problemPath)) {
return false;
}
if (problemPath) {
var problemPathTail = problemPath.pop();
if (problemPathTail !== i) {
throw new Error("" + problemPathTail);
}
}
}
return true;
}
function objectsAreEquivalent(a: any, b: any, problemPath: any) {
isObject.assert(a);
if (!isObject.check(b)) {
return false;
}
// Fast path for a common property of AST nodes.
if (a.type !== b.type) {
if (problemPath) {
problemPath.push("type");
}
return false;
}
var aNames = getFieldNames(a);
var aNameCount = aNames.length;
var bNames = getFieldNames(b);
var bNameCount = bNames.length;
if (aNameCount === bNameCount) {
for (var i = 0; i < aNameCount; ++i) {
var name = aNames[i];
var aChild = getFieldValue(a, name);
var bChild = getFieldValue(b, name);
if (problemPath) {
problemPath.push(name);
}
if (!areEquivalent(aChild, bChild, problemPath)) {
return false;
}
if (problemPath) {
var problemPathTail = problemPath.pop();
if (problemPathTail !== name) {
throw new Error("" + problemPathTail);
}
}
}
return true;
}
if (!problemPath) {
return false;
}
// Since aNameCount !== bNameCount, we need to find some name that's
// missing in aNames but present in bNames, or vice-versa.
var seenNames = Object.create(null);
for (i = 0; i < aNameCount; ++i) {
seenNames[aNames[i]] = true;
}
for (i = 0; i < bNameCount; ++i) {
name = bNames[i];
if (!hasOwn.call(seenNames, name)) {
problemPath.push(name);
return false;
}
delete seenNames[name];
}
for (name in seenNames) {
problemPath.push(name);
break;
}
return false;
}
return astNodesAreEquivalent;
} | type Fork = {
use<T>(plugin: Plugin<T>): T;
}; |
1,161 | visit<M = {}>(node: ASTNode, methods?: import("./gen/visitor").Visitor<M>): any | interface ASTNode {
type: string;
} |
1,162 | (path: NodePath) => any | interface NodePath<N = any, V = any> extends Path<V> {
node: N;
parent: any;
scope: any;
replace: Path['replace'];
prune(...args: any[]): any;
_computeNode(): any;
_computeParent(): any;
_computeScope(): Scope | null;
getValueProperty(name: any): any;
needsParens(assumeExpressionContext?: boolean): boolean;
canBeFirstInStatement(): boolean;
firstInStatement(): boolean;
} |
1,163 | function pathVisitorPlugin(fork: Fork) {
var types = fork.use(typesPlugin);
var NodePath = fork.use(nodePathPlugin);
var isArray = types.builtInTypes.array;
var isObject = types.builtInTypes.object;
var isFunction = types.builtInTypes.function;
var undefined: any;
const PathVisitor = function PathVisitor(this: PathVisitor) {
if (!(this instanceof PathVisitor)) {
throw new Error(
"PathVisitor constructor cannot be invoked without 'new'"
);
}
// Permanent state.
this._reusableContextStack = [];
this._methodNameTable = computeMethodNameTable(this);
this._shouldVisitComments =
hasOwn.call(this._methodNameTable, "Block") ||
hasOwn.call(this._methodNameTable, "Line");
this.Context = makeContextConstructor(this);
// State reset every time PathVisitor.prototype.visit is called.
this._visiting = false;
this._changeReported = false;
} as any as PathVisitorConstructor;
function computeMethodNameTable(visitor: any) {
var typeNames = Object.create(null);
for (var methodName in visitor) {
if (/^visit[A-Z]/.test(methodName)) {
typeNames[methodName.slice("visit".length)] = true;
}
}
var supertypeTable = types.computeSupertypeLookupTable(typeNames);
var methodNameTable = Object.create(null);
var typeNameKeys = Object.keys(supertypeTable);
var typeNameCount = typeNameKeys.length;
for (var i = 0; i < typeNameCount; ++i) {
var typeName = typeNameKeys[i];
methodName = "visit" + supertypeTable[typeName];
if (isFunction.check(visitor[methodName])) {
methodNameTable[typeName] = methodName;
}
}
return methodNameTable;
}
PathVisitor.fromMethodsObject = function fromMethodsObject(methods) {
if (methods instanceof PathVisitor) {
return methods;
}
if (!isObject.check(methods)) {
// An empty visitor?
return new PathVisitor;
}
const Visitor = function Visitor(this: any) {
if (!(this instanceof Visitor)) {
throw new Error(
"Visitor constructor cannot be invoked without 'new'"
);
}
PathVisitor.call(this);
} as any as VisitorConstructor;
var Vp = Visitor.prototype = Object.create(PVp);
Vp.constructor = Visitor;
extend(Vp, methods);
extend(Visitor, PathVisitor);
isFunction.assert(Visitor.fromMethodsObject);
isFunction.assert(Visitor.visit);
return new Visitor;
};
function extend(target: any, source: any) {
for (var property in source) {
if (hasOwn.call(source, property)) {
target[property] = source[property];
}
}
return target;
}
PathVisitor.visit = function visit(node, methods) {
return PathVisitor.fromMethodsObject(methods).visit(node);
};
var PVp: PathVisitor = PathVisitor.prototype;
PVp.visit = function () {
if (this._visiting) {
throw new Error(
"Recursively calling visitor.visit(path) resets visitor state. " +
"Try this.visit(path) or this.traverse(path) instead."
);
}
// Private state that needs to be reset before every traversal.
this._visiting = true;
this._changeReported = false;
this._abortRequested = false;
var argc = arguments.length;
var args = new Array(argc)
for (var i = 0; i < argc; ++i) {
args[i] = arguments[i];
}
if (!(args[0] instanceof NodePath)) {
args[0] = new NodePath({root: args[0]}).get("root");
}
// Called with the same arguments as .visit.
this.reset.apply(this, args);
var didNotThrow;
try {
var root = this.visitWithoutReset(args[0]);
didNotThrow = true;
} finally {
this._visiting = false;
if (!didNotThrow && this._abortRequested) {
// If this.visitWithoutReset threw an exception and
// this._abortRequested was set to true, return the root of
// the AST instead of letting the exception propagate, so that
// client code does not have to provide a try-catch block to
// intercept the AbortRequest exception. Other kinds of
// exceptions will propagate without being intercepted and
// rethrown by a catch block, so their stacks will accurately
// reflect the original throwing context.
return args[0].value;
}
}
return root;
};
PVp.AbortRequest = function AbortRequest() {};
PVp.abort = function () {
var visitor = this;
visitor._abortRequested = true;
var request = new visitor.AbortRequest();
// If you decide to catch this exception and stop it from propagating,
// make sure to call its cancel method to avoid silencing other
// exceptions that might be thrown later in the traversal.
request.cancel = function () {
visitor._abortRequested = false;
};
throw request;
};
PVp.reset = function (_path/*, additional arguments */) {
// Empty stub; may be reassigned or overridden by subclasses.
};
PVp.visitWithoutReset = function (path) {
if (this instanceof this.Context) {
// Since this.Context.prototype === this, there's a chance we
// might accidentally call context.visitWithoutReset. If that
// happens, re-invoke the method against context.visitor.
return this.visitor.visitWithoutReset(path);
}
if (!(path instanceof NodePath)) {
throw new Error("");
}
var value = path.value;
var methodName = value &&
typeof value === "object" &&
typeof value.type === "string" &&
this._methodNameTable[value.type];
if (methodName) {
var context = this.acquireContext(path);
try {
return context.invokeVisitorMethod(methodName);
} finally {
this.releaseContext(context);
}
} else {
// If there was no visitor method to call, visit the children of
// this node generically.
return visitChildren(path, this);
}
};
function visitChildren(path: any, visitor: any) {
if (!(path instanceof NodePath)) {
throw new Error("");
}
if (!(visitor instanceof PathVisitor)) {
throw new Error("");
}
var value = path.value;
if (isArray.check(value)) {
path.each(visitor.visitWithoutReset, visitor);
} else if (!isObject.check(value)) {
// No children to visit.
} else {
var childNames = types.getFieldNames(value);
// The .comments field of the Node type is hidden, so we only
// visit it if the visitor defines visitBlock or visitLine, and
// value.comments is defined.
if (visitor._shouldVisitComments &&
value.comments &&
childNames.indexOf("comments") < 0) {
childNames.push("comments");
}
var childCount = childNames.length;
var childPaths = [];
for (var i = 0; i < childCount; ++i) {
var childName = childNames[i];
if (!hasOwn.call(value, childName)) {
value[childName] = types.getFieldValue(value, childName);
}
childPaths.push(path.get(childName));
}
for (var i = 0; i < childCount; ++i) {
visitor.visitWithoutReset(childPaths[i]);
}
}
return path.value;
}
PVp.acquireContext = function (path) {
if (this._reusableContextStack.length === 0) {
return new this.Context(path);
}
return this._reusableContextStack.pop().reset(path);
};
PVp.releaseContext = function (context) {
if (!(context instanceof this.Context)) {
throw new Error("");
}
this._reusableContextStack.push(context);
context.currentPath = null;
};
PVp.reportChanged = function () {
this._changeReported = true;
};
PVp.wasChangeReported = function () {
return this._changeReported;
};
function makeContextConstructor(visitor: any) {
function Context(this: Context, path: any) {
if (!(this instanceof Context)) {
throw new Error("");
}
if (!(this instanceof PathVisitor)) {
throw new Error("");
}
if (!(path instanceof NodePath)) {
throw new Error("");
}
Object.defineProperty(this, "visitor", {
value: visitor,
writable: false,
enumerable: true,
configurable: false
});
this.currentPath = path;
this.needToCallTraverse = true;
Object.seal(this);
}
if (!(visitor instanceof PathVisitor)) {
throw new Error("");
}
// Note that the visitor object is the prototype of Context.prototype,
// so all visitor methods are inherited by context objects.
var Cp = Context.prototype = Object.create(visitor);
Cp.constructor = Context;
extend(Cp, sharedContextProtoMethods);
return Context;
}
// Every PathVisitor has a different this.Context constructor and
// this.Context.prototype object, but those prototypes can all use the
// same reset, invokeVisitorMethod, and traverse function objects.
var sharedContextProtoMethods: SharedContextMethods = Object.create(null);
sharedContextProtoMethods.reset =
function reset(path) {
if (!(this instanceof this.Context)) {
throw new Error("");
}
if (!(path instanceof NodePath)) {
throw new Error("");
}
this.currentPath = path;
this.needToCallTraverse = true;
return this;
};
sharedContextProtoMethods.invokeVisitorMethod =
function invokeVisitorMethod(methodName) {
if (!(this instanceof this.Context)) {
throw new Error("");
}
if (!(this.currentPath instanceof NodePath)) {
throw new Error("");
}
var result = this.visitor[methodName].call(this, this.currentPath);
if (result === false) {
// Visitor methods return false to indicate that they have handled
// their own traversal needs, and we should not complain if
// this.needToCallTraverse is still true.
this.needToCallTraverse = false;
} else if (result !== undefined) {
// Any other non-undefined value returned from the visitor method
// is interpreted as a replacement value.
this.currentPath = this.currentPath.replace(result)[0];
if (this.needToCallTraverse) {
// If this.traverse still hasn't been called, visit the
// children of the replacement node.
this.traverse(this.currentPath);
}
}
if (this.needToCallTraverse !== false) {
throw new Error(
"Must either call this.traverse or return false in " + methodName
);
}
var path = this.currentPath;
return path && path.value;
};
sharedContextProtoMethods.traverse =
function traverse(path, newVisitor) {
if (!(this instanceof this.Context)) {
throw new Error("");
}
if (!(path instanceof NodePath)) {
throw new Error("");
}
if (!(this.currentPath instanceof NodePath)) {
throw new Error("");
}
this.needToCallTraverse = false;
return visitChildren(path, PathVisitor.fromMethodsObject(
newVisitor || this.visitor
));
};
sharedContextProtoMethods.visit =
function visit(path, newVisitor) {
if (!(this instanceof this.Context)) {
throw new Error("");
}
if (!(path instanceof NodePath)) {
throw new Error("");
}
if (!(this.currentPath instanceof NodePath)) {
throw new Error("");
}
this.needToCallTraverse = false;
return PathVisitor.fromMethodsObject(
newVisitor || this.visitor
).visitWithoutReset(path);
};
sharedContextProtoMethods.reportChanged = function reportChanged() {
this.visitor.reportChanged();
};
sharedContextProtoMethods.abort = function abort() {
this.needToCallTraverse = false;
this.visitor.abort();
};
return PathVisitor;
} | type Fork = {
use<T>(plugin: Plugin<T>): T;
}; |
1,164 | function PathVisitor(this: PathVisitor) {
if (!(this instanceof PathVisitor)) {
throw new Error(
"PathVisitor constructor cannot be invoked without 'new'"
);
}
// Permanent state.
this._reusableContextStack = [];
this._methodNameTable = computeMethodNameTable(this);
this._shouldVisitComments =
hasOwn.call(this._methodNameTable, "Block") ||
hasOwn.call(this._methodNameTable, "Line");
this.Context = makeContextConstructor(this);
// State reset every time PathVisitor.prototype.visit is called.
this._visiting = false;
this._changeReported = false;
} | interface PathVisitor {
_reusableContextStack: any;
_methodNameTable: any;
_shouldVisitComments: any;
Context: any;
_visiting: any;
_changeReported: any;
_abortRequested: boolean;
visit(...args: any[]): any;
reset(...args: any[]): any;
visitWithoutReset(path: any): any;
AbortRequest: any;
abort(): void;
visitor: any;
acquireContext(path: any): any;
releaseContext(context: any): void;
reportChanged(): void;
wasChangeReported(): any;
} |
1,165 | function Context(this: Context, path: any) {
if (!(this instanceof Context)) {
throw new Error("");
}
if (!(this instanceof PathVisitor)) {
throw new Error("");
}
if (!(path instanceof NodePath)) {
throw new Error("");
}
Object.defineProperty(this, "visitor", {
value: visitor,
writable: false,
enumerable: true,
configurable: false
});
this.currentPath = path;
this.needToCallTraverse = true;
Object.seal(this);
} | interface Context extends Omit<PathVisitor, "visit" | "reset">, SharedContextMethods {} |
1,166 | replace(replacement?: ASTNode, ...args: ASTNode[]): any | interface ASTNode {
type: string;
} |
1,167 | function pathPlugin(fork: Fork): PathConstructor {
var types = fork.use(typesPlugin);
var isArray = types.builtInTypes.array;
var isNumber = types.builtInTypes.number;
const Path = function Path(this: Path, value: any, parentPath?: any, name?: any) {
if (!(this instanceof Path)) {
throw new Error("Path constructor cannot be invoked without 'new'");
}
if (parentPath) {
if (!(parentPath instanceof Path)) {
throw new Error("");
}
} else {
parentPath = null;
name = null;
}
// The value encapsulated by this Path, generally equal to
// parentPath.value[name] if we have a parentPath.
this.value = value;
// The immediate parent Path of this Path.
this.parentPath = parentPath;
// The name of the property of parentPath.value through which this
// Path's value was reached.
this.name = name;
// Calling path.get("child") multiple times always returns the same
// child Path object, for both performance and consistency reasons.
this.__childCache = null;
} as any as PathConstructor;
var Pp: Path = Path.prototype;
function getChildCache(path: any) {
// Lazily create the child cache. This also cheapens cache
// invalidation, since you can just reset path.__childCache to null.
return path.__childCache || (path.__childCache = Object.create(null));
}
function getChildPath(path: any, name: any) {
var cache = getChildCache(path);
var actualChildValue = path.getValueProperty(name);
var childPath = cache[name];
if (!hasOwn.call(cache, name) ||
// Ensure consistency between cache and reality.
childPath.value !== actualChildValue) {
childPath = cache[name] = new path.constructor(
actualChildValue, path, name
);
}
return childPath;
}
// This method is designed to be overridden by subclasses that need to
// handle missing properties, etc.
Pp.getValueProperty = function getValueProperty(name) {
return this.value[name];
};
Pp.get = function get(...names) {
var path = this;
var count = names.length;
for (var i = 0; i < count; ++i) {
path = getChildPath(path, names[i]);
}
return path;
};
Pp.each = function each(callback, context) {
var childPaths = [];
var len = this.value.length;
var i = 0;
// Collect all the original child paths before invoking the callback.
for (var i = 0; i < len; ++i) {
if (hasOwn.call(this.value, i)) {
childPaths[i] = this.get(i);
}
}
// Invoke the callback on just the original child paths, regardless of
// any modifications made to the array by the callback. I chose these
// semantics over cleverly invoking the callback on new elements because
// this way is much easier to reason about.
context = context || this;
for (i = 0; i < len; ++i) {
if (hasOwn.call(childPaths, i)) {
callback.call(context, childPaths[i]);
}
}
};
Pp.map = function map(callback, context) {
var result: any[] = [];
this.each(function (this: any, childPath: any) {
result.push(callback.call(this, childPath));
}, context);
return result;
};
Pp.filter = function filter(callback, context) {
var result: any[] = [];
this.each(function (this: any, childPath: any) {
if (callback.call(this, childPath)) {
result.push(childPath);
}
}, context);
return result;
};
function emptyMoves() {}
function getMoves(path: any, offset: number, start?: any, end?: any) {
isArray.assert(path.value);
if (offset === 0) {
return emptyMoves;
}
var length = path.value.length;
if (length < 1) {
return emptyMoves;
}
var argc = arguments.length;
if (argc === 2) {
start = 0;
end = length;
} else if (argc === 3) {
start = Math.max(start, 0);
end = length;
} else {
start = Math.max(start, 0);
end = Math.min(end, length);
}
isNumber.assert(start);
isNumber.assert(end);
var moves = Object.create(null);
var cache = getChildCache(path);
for (var i = start; i < end; ++i) {
if (hasOwn.call(path.value, i)) {
var childPath = path.get(i);
if (childPath.name !== i) {
throw new Error("");
}
var newIndex = i + offset;
childPath.name = newIndex;
moves[newIndex] = childPath;
delete cache[i];
}
}
delete cache.length;
return function () {
for (var newIndex in moves) {
var childPath = moves[newIndex];
if (childPath.name !== +newIndex) {
throw new Error("");
}
cache[newIndex] = childPath;
path.value[newIndex] = childPath.value;
}
};
}
Pp.shift = function shift() {
var move = getMoves(this, -1);
var result = this.value.shift();
move();
return result;
};
Pp.unshift = function unshift(...args) {
var move = getMoves(this, args.length);
var result = this.value.unshift.apply(this.value, args);
move();
return result;
};
Pp.push = function push(...args) {
isArray.assert(this.value);
delete getChildCache(this).length
return this.value.push.apply(this.value, args);
};
Pp.pop = function pop() {
isArray.assert(this.value);
var cache = getChildCache(this);
delete cache[this.value.length - 1];
delete cache.length;
return this.value.pop();
};
Pp.insertAt = function insertAt(index) {
var argc = arguments.length;
var move = getMoves(this, argc - 1, index);
if (move === emptyMoves && argc <= 1) {
return this;
}
index = Math.max(index, 0);
for (var i = 1; i < argc; ++i) {
this.value[index + i - 1] = arguments[i];
}
move();
return this;
};
Pp.insertBefore = function insertBefore(...args) {
var pp = this.parentPath;
var argc = args.length;
var insertAtArgs = [this.name];
for (var i = 0; i < argc; ++i) {
insertAtArgs.push(args[i]);
}
return pp.insertAt.apply(pp, insertAtArgs);
};
Pp.insertAfter = function insertAfter(...args) {
var pp = this.parentPath;
var argc = args.length;
var insertAtArgs = [this.name + 1];
for (var i = 0; i < argc; ++i) {
insertAtArgs.push(args[i]);
}
return pp.insertAt.apply(pp, insertAtArgs);
};
function repairRelationshipWithParent(path: any) {
if (!(path instanceof Path)) {
throw new Error("");
}
var pp = path.parentPath;
if (!pp) {
// Orphan paths have no relationship to repair.
return path;
}
var parentValue = pp.value;
var parentCache = getChildCache(pp);
// Make sure parentCache[path.name] is populated.
if (parentValue[path.name] === path.value) {
parentCache[path.name] = path;
} else if (isArray.check(parentValue)) {
// Something caused path.name to become out of date, so attempt to
// recover by searching for path.value in parentValue.
var i = parentValue.indexOf(path.value);
if (i >= 0) {
parentCache[path.name = i] = path;
}
} else {
// If path.value disagrees with parentValue[path.name], and
// path.name is not an array index, let path.value become the new
// parentValue[path.name] and update parentCache accordingly.
parentValue[path.name] = path.value;
parentCache[path.name] = path;
}
if (parentValue[path.name] !== path.value) {
throw new Error("");
}
if (path.parentPath.get(path.name) !== path) {
throw new Error("");
}
return path;
}
Pp.replace = function replace(replacement) {
var results = [];
var parentValue = this.parentPath.value;
var parentCache = getChildCache(this.parentPath);
var count = arguments.length;
repairRelationshipWithParent(this);
if (isArray.check(parentValue)) {
var originalLength = parentValue.length;
var move = getMoves(this.parentPath, count - 1, this.name + 1);
var spliceArgs: [number, number, ...any[]] = [this.name, 1];
for (var i = 0; i < count; ++i) {
spliceArgs.push(arguments[i]);
}
var splicedOut = parentValue.splice.apply(parentValue, spliceArgs);
if (splicedOut[0] !== this.value) {
throw new Error("");
}
if (parentValue.length !== (originalLength - 1 + count)) {
throw new Error("");
}
move();
if (count === 0) {
delete this.value;
delete parentCache[this.name];
this.__childCache = null;
} else {
if (parentValue[this.name] !== replacement) {
throw new Error("");
}
if (this.value !== replacement) {
this.value = replacement;
this.__childCache = null;
}
for (i = 0; i < count; ++i) {
results.push(this.parentPath.get(this.name + i));
}
if (results[0] !== this) {
throw new Error("");
}
}
} else if (count === 1) {
if (this.value !== replacement) {
this.__childCache = null;
}
this.value = parentValue[this.name] = replacement;
results.push(this);
} else if (count === 0) {
delete parentValue[this.name];
delete this.value;
this.__childCache = null;
// Leave this path cached as parentCache[this.name], even though
// it no longer has a value defined.
} else {
throw new Error("Could not replace path");
}
return results;
};
return Path;
} | type Fork = {
use<T>(plugin: Plugin<T>): T;
}; |
1,168 | function Path(this: Path, value: any, parentPath?: any, name?: any) {
if (!(this instanceof Path)) {
throw new Error("Path constructor cannot be invoked without 'new'");
}
if (parentPath) {
if (!(parentPath instanceof Path)) {
throw new Error("");
}
} else {
parentPath = null;
name = null;
}
// The value encapsulated by this Path, generally equal to
// parentPath.value[name] if we have a parentPath.
this.value = value;
// The immediate parent Path of this Path.
this.parentPath = parentPath;
// The name of the property of parentPath.value through which this
// Path's value was reached.
this.name = name;
// Calling path.get("child") multiple times always returns the same
// child Path object, for both performance and consistency reasons.
this.__childCache = null;
} | interface Path<V = any> {
value: V;
parentPath: any;
name: any;
__childCache: object | null;
getValueProperty(name: any): any;
get(...names: any[]): any;
each(callback: any, context?: any): any;
map(callback: any, context?: any): any;
filter(callback: any, context?: any): any;
shift(): any;
unshift(...args: any[]): any;
push(...args: any[]): any;
pop(): any;
insertAt(index: number, ...args: any[]): any;
insertBefore(...args: any[]): any;
insertAfter(...args: any[]): any;
replace(replacement?: ASTNode, ...args: ASTNode[]): any;
} |
1,169 | new(path: NodePath, parentScope: any): Scope | interface NodePath<N = any, V = any> extends Path<V> {
node: N;
parent: any;
scope: any;
replace: Path['replace'];
prune(...args: any[]): any;
_computeNode(): any;
_computeParent(): any;
_computeScope(): Scope | null;
getValueProperty(name: any): any;
needsParens(assumeExpressionContext?: boolean): boolean;
canBeFirstInStatement(): boolean;
firstInStatement(): boolean;
} |
1,170 | function scopePlugin(fork: Fork) {
var types = fork.use(typesPlugin);
var Type = types.Type;
var namedTypes = types.namedTypes;
var Node = namedTypes.Node;
var Expression = namedTypes.Expression;
var isArray = types.builtInTypes.array;
var b = types.builders;
const Scope = function Scope(this: Scope, path: NodePath, parentScope: unknown) {
if (!(this instanceof Scope)) {
throw new Error("Scope constructor cannot be invoked without 'new'");
}
if (!TypeParameterScopeType.check(path.value)) {
ScopeType.assert(path.value);
}
var depth: number;
if (parentScope) {
if (!(parentScope instanceof Scope)) {
throw new Error("");
}
depth = (parentScope as Scope).depth + 1;
} else {
parentScope = null;
depth = 0;
}
Object.defineProperties(this, {
path: { value: path },
node: { value: path.value },
isGlobal: { value: !parentScope, enumerable: true },
depth: { value: depth },
parent: { value: parentScope },
bindings: { value: {} },
types: { value: {} },
});
} as any as ScopeConstructor;
var ScopeType = Type.or(
// Program nodes introduce global scopes.
namedTypes.Program,
// Function is the supertype of FunctionExpression,
// FunctionDeclaration, ArrowExpression, etc.
namedTypes.Function,
// In case you didn't know, the caught parameter shadows any variable
// of the same name in an outer scope.
namedTypes.CatchClause
);
// These types introduce scopes that are restricted to type parameters in
// Flow (this doesn't apply to ECMAScript).
var TypeParameterScopeType = Type.or(
namedTypes.Function,
namedTypes.ClassDeclaration,
namedTypes.ClassExpression,
namedTypes.InterfaceDeclaration,
namedTypes.TSInterfaceDeclaration,
namedTypes.TypeAlias,
namedTypes.TSTypeAliasDeclaration,
);
var FlowOrTSTypeParameterType = Type.or(
namedTypes.TypeParameter,
namedTypes.TSTypeParameter,
);
Scope.isEstablishedBy = function(node) {
return ScopeType.check(node) || TypeParameterScopeType.check(node);
};
var Sp: Scope = Scope.prototype;
// Will be overridden after an instance lazily calls scanScope.
Sp.didScan = false;
Sp.declares = function(name) {
this.scan();
return hasOwn.call(this.bindings, name);
};
Sp.declaresType = function(name) {
this.scan();
return hasOwn.call(this.types, name);
};
Sp.declareTemporary = function(prefix) {
if (prefix) {
if (!/^[a-z$_]/i.test(prefix)) {
throw new Error("");
}
} else {
prefix = "t$";
}
// Include this.depth in the name to make sure the name does not
// collide with any variables in nested/enclosing scopes.
prefix += this.depth.toString(36) + "$";
this.scan();
var index = 0;
while (this.declares(prefix + index)) {
++index;
}
var name = prefix + index;
return this.bindings[name] = types.builders.identifier(name);
};
Sp.injectTemporary = function(identifier, init) {
identifier || (identifier = this.declareTemporary());
var bodyPath = this.path.get("body");
if (namedTypes.BlockStatement.check(bodyPath.value)) {
bodyPath = bodyPath.get("body");
}
bodyPath.unshift(
b.variableDeclaration(
"var",
[b.variableDeclarator(identifier, init || null)]
)
);
return identifier;
};
Sp.scan = function(force) {
if (force || !this.didScan) {
for (var name in this.bindings) {
// Empty out this.bindings, just in cases.
delete this.bindings[name];
}
for (var name in this.types) {
// Empty out this.types, just in cases.
delete this.types[name];
}
scanScope(this.path, this.bindings, this.types);
this.didScan = true;
}
};
Sp.getBindings = function () {
this.scan();
return this.bindings;
};
Sp.getTypes = function () {
this.scan();
return this.types;
};
function scanScope(path: NodePath, bindings: any, scopeTypes: any) {
var node = path.value;
if (TypeParameterScopeType.check(node)) {
const params = path.get('typeParameters', 'params');
if (isArray.check(params.value)) {
params.each((childPath: NodePath) => {
addTypeParameter(childPath, scopeTypes);
});
}
}
if (ScopeType.check(node)) {
if (namedTypes.CatchClause.check(node)) {
// A catch clause establishes a new scope but the only variable
// bound in that scope is the catch parameter. Any other
// declarations create bindings in the outer scope.
addPattern(path.get("param"), bindings);
} else {
recursiveScanScope(path, bindings, scopeTypes);
}
}
}
function recursiveScanScope(path: NodePath, bindings: any, scopeTypes: any) {
var node = path.value;
if (path.parent &&
namedTypes.FunctionExpression.check(path.parent.node) &&
path.parent.node.id) {
addPattern(path.parent.get("id"), bindings);
}
if (!node) {
// None of the remaining cases matter if node is falsy.
} else if (isArray.check(node)) {
path.each((childPath: NodePath) => {
recursiveScanChild(childPath, bindings, scopeTypes);
});
} else if (namedTypes.Function.check(node)) {
path.get("params").each((paramPath: NodePath) => {
addPattern(paramPath, bindings);
});
recursiveScanChild(path.get("body"), bindings, scopeTypes);
recursiveScanScope(path.get("typeParameters"), bindings, scopeTypes);
} else if (
(namedTypes.TypeAlias && namedTypes.TypeAlias.check(node)) ||
(namedTypes.InterfaceDeclaration && namedTypes.InterfaceDeclaration.check(node)) ||
(namedTypes.TSTypeAliasDeclaration && namedTypes.TSTypeAliasDeclaration.check(node)) ||
(namedTypes.TSInterfaceDeclaration && namedTypes.TSInterfaceDeclaration.check(node))
) {
addTypePattern(path.get("id"), scopeTypes);
} else if (namedTypes.VariableDeclarator.check(node)) {
addPattern(path.get("id"), bindings);
recursiveScanChild(path.get("init"), bindings, scopeTypes);
} else if (node.type === "ImportSpecifier" ||
node.type === "ImportNamespaceSpecifier" ||
node.type === "ImportDefaultSpecifier") {
addPattern(
// Esprima used to use the .name field to refer to the local
// binding identifier for ImportSpecifier nodes, but .id for
// ImportNamespaceSpecifier and ImportDefaultSpecifier nodes.
// ESTree/Acorn/ESpree use .local for all three node types.
path.get(node.local ? "local" :
node.name ? "name" : "id"),
bindings
);
} else if (Node.check(node) && !Expression.check(node)) {
types.eachField(node, function(name: any, child: any) {
var childPath = path.get(name);
if (!pathHasValue(childPath, child)) {
throw new Error("");
}
recursiveScanChild(childPath, bindings, scopeTypes);
});
}
}
function pathHasValue(path: NodePath, value: any) {
if (path.value === value) {
return true;
}
// Empty arrays are probably produced by defaults.emptyArray, in which
// case is makes sense to regard them as equivalent, if not ===.
if (Array.isArray(path.value) &&
path.value.length === 0 &&
Array.isArray(value) &&
value.length === 0) {
return true;
}
return false;
}
function recursiveScanChild(path: NodePath, bindings: any, scopeTypes: any) {
var node = path.value;
if (!node || Expression.check(node)) {
// Ignore falsy values and Expressions.
} else if (namedTypes.FunctionDeclaration.check(node) &&
node.id !== null) {
addPattern(path.get("id"), bindings);
} else if (namedTypes.ClassDeclaration &&
namedTypes.ClassDeclaration.check(node) &&
node.id !== null) {
addPattern(path.get("id"), bindings);
recursiveScanScope(path.get("typeParameters"), bindings, scopeTypes);
} else if (
(namedTypes.InterfaceDeclaration &&
namedTypes.InterfaceDeclaration.check(node)) ||
(namedTypes.TSInterfaceDeclaration &&
namedTypes.TSInterfaceDeclaration.check(node))
) {
addTypePattern(path.get("id"), scopeTypes);
} else if (ScopeType.check(node)) {
if (
namedTypes.CatchClause.check(node) &&
// TODO Broaden this to accept any pattern.
namedTypes.Identifier.check(node.param)
) {
var catchParamName = node.param.name;
var hadBinding = hasOwn.call(bindings, catchParamName);
// Any declarations that occur inside the catch body that do
// not have the same name as the catch parameter should count
// as bindings in the outer scope.
recursiveScanScope(path.get("body"), bindings, scopeTypes);
// If a new binding matching the catch parameter name was
// created while scanning the catch body, ignore it because it
// actually refers to the catch parameter and not the outer
// scope that we're currently scanning.
if (!hadBinding) {
delete bindings[catchParamName];
}
}
} else {
recursiveScanScope(path, bindings, scopeTypes);
}
}
function addPattern(patternPath: NodePath, bindings: any) {
var pattern = patternPath.value;
namedTypes.Pattern.assert(pattern);
if (namedTypes.Identifier.check(pattern)) {
if (hasOwn.call(bindings, pattern.name)) {
bindings[pattern.name].push(patternPath);
} else {
bindings[pattern.name] = [patternPath];
}
} else if (namedTypes.AssignmentPattern &&
namedTypes.AssignmentPattern.check(pattern)) {
addPattern(patternPath.get('left'), bindings);
} else if (
namedTypes.ObjectPattern &&
namedTypes.ObjectPattern.check(pattern)
) {
patternPath.get('properties').each(function(propertyPath: any) {
var property = propertyPath.value;
if (namedTypes.Pattern.check(property)) {
addPattern(propertyPath, bindings);
} else if (
namedTypes.Property.check(property) ||
(namedTypes.ObjectProperty &&
namedTypes.ObjectProperty.check(property))
) {
addPattern(propertyPath.get('value'), bindings);
} else if (
namedTypes.SpreadProperty &&
namedTypes.SpreadProperty.check(property)
) {
addPattern(propertyPath.get('argument'), bindings);
}
});
} else if (
namedTypes.ArrayPattern &&
namedTypes.ArrayPattern.check(pattern)
) {
patternPath.get('elements').each(function(elementPath: any) {
var element = elementPath.value;
if (namedTypes.Pattern.check(element)) {
addPattern(elementPath, bindings);
} else if (
namedTypes.SpreadElement &&
namedTypes.SpreadElement.check(element)
) {
addPattern(elementPath.get("argument"), bindings);
}
});
} else if (
namedTypes.PropertyPattern &&
namedTypes.PropertyPattern.check(pattern)
) {
addPattern(patternPath.get('pattern'), bindings);
} else if (
(namedTypes.SpreadElementPattern &&
namedTypes.SpreadElementPattern.check(pattern)) ||
(namedTypes.RestElement &&
namedTypes.RestElement.check(pattern)) ||
(namedTypes.SpreadPropertyPattern &&
namedTypes.SpreadPropertyPattern.check(pattern))
) {
addPattern(patternPath.get('argument'), bindings);
}
}
function addTypePattern(patternPath: NodePath, types: any) {
var pattern = patternPath.value;
namedTypes.Pattern.assert(pattern);
if (namedTypes.Identifier.check(pattern)) {
if (hasOwn.call(types, pattern.name)) {
types[pattern.name].push(patternPath);
} else {
types[pattern.name] = [patternPath];
}
}
}
function addTypeParameter(parameterPath: NodePath, types: any) {
var parameter = parameterPath.value;
FlowOrTSTypeParameterType.assert(parameter);
if (hasOwn.call(types, parameter.name)) {
types[parameter.name].push(parameterPath);
} else {
types[parameter.name] = [parameterPath];
}
}
Sp.lookup = function(name) {
for (var scope = this; scope; scope = scope.parent)
if (scope.declares(name))
break;
return scope;
};
Sp.lookupType = function(name) {
for (var scope = this; scope; scope = scope.parent)
if (scope.declaresType(name))
break;
return scope;
};
Sp.getGlobalScope = function() {
var scope = this;
while (!scope.isGlobal)
scope = scope.parent;
return scope;
};
return Scope;
} | type Fork = {
use<T>(plugin: Plugin<T>): T;
}; |
1,171 | function Scope(this: Scope, path: NodePath, parentScope: unknown) {
if (!(this instanceof Scope)) {
throw new Error("Scope constructor cannot be invoked without 'new'");
}
if (!TypeParameterScopeType.check(path.value)) {
ScopeType.assert(path.value);
}
var depth: number;
if (parentScope) {
if (!(parentScope instanceof Scope)) {
throw new Error("");
}
depth = (parentScope as Scope).depth + 1;
} else {
parentScope = null;
depth = 0;
}
Object.defineProperties(this, {
path: { value: path },
node: { value: path.value },
isGlobal: { value: !parentScope, enumerable: true },
depth: { value: depth },
parent: { value: parentScope },
bindings: { value: {} },
types: { value: {} },
});
} | interface Scope {
path: NodePath;
node: any;
isGlobal: boolean;
depth: number;
parent: any;
bindings: any;
types: any;
didScan: boolean;
declares(name: any): any
declaresType(name: any): any
declareTemporary(prefix?: any): any;
injectTemporary(identifier: any, init: any): any;
scan(force?: any): any;
getBindings(): any;
getTypes(): any;
lookup(name: any): any;
lookupType(name: any): any;
getGlobalScope(): Scope;
} |
1,172 | function Scope(this: Scope, path: NodePath, parentScope: unknown) {
if (!(this instanceof Scope)) {
throw new Error("Scope constructor cannot be invoked without 'new'");
}
if (!TypeParameterScopeType.check(path.value)) {
ScopeType.assert(path.value);
}
var depth: number;
if (parentScope) {
if (!(parentScope instanceof Scope)) {
throw new Error("");
}
depth = (parentScope as Scope).depth + 1;
} else {
parentScope = null;
depth = 0;
}
Object.defineProperties(this, {
path: { value: path },
node: { value: path.value },
isGlobal: { value: !parentScope, enumerable: true },
depth: { value: depth },
parent: { value: parentScope },
bindings: { value: {} },
types: { value: {} },
});
} | interface NodePath<N = any, V = any> extends Path<V> {
node: N;
parent: any;
scope: any;
replace: Path['replace'];
prune(...args: any[]): any;
_computeNode(): any;
_computeParent(): any;
_computeScope(): Scope | null;
getValueProperty(name: any): any;
needsParens(assumeExpressionContext?: boolean): boolean;
canBeFirstInStatement(): boolean;
firstInStatement(): boolean;
} |
1,173 | function scanScope(path: NodePath, bindings: any, scopeTypes: any) {
var node = path.value;
if (TypeParameterScopeType.check(node)) {
const params = path.get('typeParameters', 'params');
if (isArray.check(params.value)) {
params.each((childPath: NodePath) => {
addTypeParameter(childPath, scopeTypes);
});
}
}
if (ScopeType.check(node)) {
if (namedTypes.CatchClause.check(node)) {
// A catch clause establishes a new scope but the only variable
// bound in that scope is the catch parameter. Any other
// declarations create bindings in the outer scope.
addPattern(path.get("param"), bindings);
} else {
recursiveScanScope(path, bindings, scopeTypes);
}
}
} | interface NodePath<N = any, V = any> extends Path<V> {
node: N;
parent: any;
scope: any;
replace: Path['replace'];
prune(...args: any[]): any;
_computeNode(): any;
_computeParent(): any;
_computeScope(): Scope | null;
getValueProperty(name: any): any;
needsParens(assumeExpressionContext?: boolean): boolean;
canBeFirstInStatement(): boolean;
firstInStatement(): boolean;
} |
1,174 | (childPath: NodePath) => {
addTypeParameter(childPath, scopeTypes);
} | interface NodePath<N = any, V = any> extends Path<V> {
node: N;
parent: any;
scope: any;
replace: Path['replace'];
prune(...args: any[]): any;
_computeNode(): any;
_computeParent(): any;
_computeScope(): Scope | null;
getValueProperty(name: any): any;
needsParens(assumeExpressionContext?: boolean): boolean;
canBeFirstInStatement(): boolean;
firstInStatement(): boolean;
} |
1,175 | function recursiveScanScope(path: NodePath, bindings: any, scopeTypes: any) {
var node = path.value;
if (path.parent &&
namedTypes.FunctionExpression.check(path.parent.node) &&
path.parent.node.id) {
addPattern(path.parent.get("id"), bindings);
}
if (!node) {
// None of the remaining cases matter if node is falsy.
} else if (isArray.check(node)) {
path.each((childPath: NodePath) => {
recursiveScanChild(childPath, bindings, scopeTypes);
});
} else if (namedTypes.Function.check(node)) {
path.get("params").each((paramPath: NodePath) => {
addPattern(paramPath, bindings);
});
recursiveScanChild(path.get("body"), bindings, scopeTypes);
recursiveScanScope(path.get("typeParameters"), bindings, scopeTypes);
} else if (
(namedTypes.TypeAlias && namedTypes.TypeAlias.check(node)) ||
(namedTypes.InterfaceDeclaration && namedTypes.InterfaceDeclaration.check(node)) ||
(namedTypes.TSTypeAliasDeclaration && namedTypes.TSTypeAliasDeclaration.check(node)) ||
(namedTypes.TSInterfaceDeclaration && namedTypes.TSInterfaceDeclaration.check(node))
) {
addTypePattern(path.get("id"), scopeTypes);
} else if (namedTypes.VariableDeclarator.check(node)) {
addPattern(path.get("id"), bindings);
recursiveScanChild(path.get("init"), bindings, scopeTypes);
} else if (node.type === "ImportSpecifier" ||
node.type === "ImportNamespaceSpecifier" ||
node.type === "ImportDefaultSpecifier") {
addPattern(
// Esprima used to use the .name field to refer to the local
// binding identifier for ImportSpecifier nodes, but .id for
// ImportNamespaceSpecifier and ImportDefaultSpecifier nodes.
// ESTree/Acorn/ESpree use .local for all three node types.
path.get(node.local ? "local" :
node.name ? "name" : "id"),
bindings
);
} else if (Node.check(node) && !Expression.check(node)) {
types.eachField(node, function(name: any, child: any) {
var childPath = path.get(name);
if (!pathHasValue(childPath, child)) {
throw new Error("");
}
recursiveScanChild(childPath, bindings, scopeTypes);
});
}
} | interface NodePath<N = any, V = any> extends Path<V> {
node: N;
parent: any;
scope: any;
replace: Path['replace'];
prune(...args: any[]): any;
_computeNode(): any;
_computeParent(): any;
_computeScope(): Scope | null;
getValueProperty(name: any): any;
needsParens(assumeExpressionContext?: boolean): boolean;
canBeFirstInStatement(): boolean;
firstInStatement(): boolean;
} |
1,176 | (childPath: NodePath) => {
recursiveScanChild(childPath, bindings, scopeTypes);
} | interface NodePath<N = any, V = any> extends Path<V> {
node: N;
parent: any;
scope: any;
replace: Path['replace'];
prune(...args: any[]): any;
_computeNode(): any;
_computeParent(): any;
_computeScope(): Scope | null;
getValueProperty(name: any): any;
needsParens(assumeExpressionContext?: boolean): boolean;
canBeFirstInStatement(): boolean;
firstInStatement(): boolean;
} |
1,177 | (paramPath: NodePath) => {
addPattern(paramPath, bindings);
} | interface NodePath<N = any, V = any> extends Path<V> {
node: N;
parent: any;
scope: any;
replace: Path['replace'];
prune(...args: any[]): any;
_computeNode(): any;
_computeParent(): any;
_computeScope(): Scope | null;
getValueProperty(name: any): any;
needsParens(assumeExpressionContext?: boolean): boolean;
canBeFirstInStatement(): boolean;
firstInStatement(): boolean;
} |
1,178 | function pathHasValue(path: NodePath, value: any) {
if (path.value === value) {
return true;
}
// Empty arrays are probably produced by defaults.emptyArray, in which
// case is makes sense to regard them as equivalent, if not ===.
if (Array.isArray(path.value) &&
path.value.length === 0 &&
Array.isArray(value) &&
value.length === 0) {
return true;
}
return false;
} | interface NodePath<N = any, V = any> extends Path<V> {
node: N;
parent: any;
scope: any;
replace: Path['replace'];
prune(...args: any[]): any;
_computeNode(): any;
_computeParent(): any;
_computeScope(): Scope | null;
getValueProperty(name: any): any;
needsParens(assumeExpressionContext?: boolean): boolean;
canBeFirstInStatement(): boolean;
firstInStatement(): boolean;
} |
1,179 | function recursiveScanChild(path: NodePath, bindings: any, scopeTypes: any) {
var node = path.value;
if (!node || Expression.check(node)) {
// Ignore falsy values and Expressions.
} else if (namedTypes.FunctionDeclaration.check(node) &&
node.id !== null) {
addPattern(path.get("id"), bindings);
} else if (namedTypes.ClassDeclaration &&
namedTypes.ClassDeclaration.check(node) &&
node.id !== null) {
addPattern(path.get("id"), bindings);
recursiveScanScope(path.get("typeParameters"), bindings, scopeTypes);
} else if (
(namedTypes.InterfaceDeclaration &&
namedTypes.InterfaceDeclaration.check(node)) ||
(namedTypes.TSInterfaceDeclaration &&
namedTypes.TSInterfaceDeclaration.check(node))
) {
addTypePattern(path.get("id"), scopeTypes);
} else if (ScopeType.check(node)) {
if (
namedTypes.CatchClause.check(node) &&
// TODO Broaden this to accept any pattern.
namedTypes.Identifier.check(node.param)
) {
var catchParamName = node.param.name;
var hadBinding = hasOwn.call(bindings, catchParamName);
// Any declarations that occur inside the catch body that do
// not have the same name as the catch parameter should count
// as bindings in the outer scope.
recursiveScanScope(path.get("body"), bindings, scopeTypes);
// If a new binding matching the catch parameter name was
// created while scanning the catch body, ignore it because it
// actually refers to the catch parameter and not the outer
// scope that we're currently scanning.
if (!hadBinding) {
delete bindings[catchParamName];
}
}
} else {
recursiveScanScope(path, bindings, scopeTypes);
}
} | interface NodePath<N = any, V = any> extends Path<V> {
node: N;
parent: any;
scope: any;
replace: Path['replace'];
prune(...args: any[]): any;
_computeNode(): any;
_computeParent(): any;
_computeScope(): Scope | null;
getValueProperty(name: any): any;
needsParens(assumeExpressionContext?: boolean): boolean;
canBeFirstInStatement(): boolean;
firstInStatement(): boolean;
} |
1,180 | function addPattern(patternPath: NodePath, bindings: any) {
var pattern = patternPath.value;
namedTypes.Pattern.assert(pattern);
if (namedTypes.Identifier.check(pattern)) {
if (hasOwn.call(bindings, pattern.name)) {
bindings[pattern.name].push(patternPath);
} else {
bindings[pattern.name] = [patternPath];
}
} else if (namedTypes.AssignmentPattern &&
namedTypes.AssignmentPattern.check(pattern)) {
addPattern(patternPath.get('left'), bindings);
} else if (
namedTypes.ObjectPattern &&
namedTypes.ObjectPattern.check(pattern)
) {
patternPath.get('properties').each(function(propertyPath: any) {
var property = propertyPath.value;
if (namedTypes.Pattern.check(property)) {
addPattern(propertyPath, bindings);
} else if (
namedTypes.Property.check(property) ||
(namedTypes.ObjectProperty &&
namedTypes.ObjectProperty.check(property))
) {
addPattern(propertyPath.get('value'), bindings);
} else if (
namedTypes.SpreadProperty &&
namedTypes.SpreadProperty.check(property)
) {
addPattern(propertyPath.get('argument'), bindings);
}
});
} else if (
namedTypes.ArrayPattern &&
namedTypes.ArrayPattern.check(pattern)
) {
patternPath.get('elements').each(function(elementPath: any) {
var element = elementPath.value;
if (namedTypes.Pattern.check(element)) {
addPattern(elementPath, bindings);
} else if (
namedTypes.SpreadElement &&
namedTypes.SpreadElement.check(element)
) {
addPattern(elementPath.get("argument"), bindings);
}
});
} else if (
namedTypes.PropertyPattern &&
namedTypes.PropertyPattern.check(pattern)
) {
addPattern(patternPath.get('pattern'), bindings);
} else if (
(namedTypes.SpreadElementPattern &&
namedTypes.SpreadElementPattern.check(pattern)) ||
(namedTypes.RestElement &&
namedTypes.RestElement.check(pattern)) ||
(namedTypes.SpreadPropertyPattern &&
namedTypes.SpreadPropertyPattern.check(pattern))
) {
addPattern(patternPath.get('argument'), bindings);
}
} | interface NodePath<N = any, V = any> extends Path<V> {
node: N;
parent: any;
scope: any;
replace: Path['replace'];
prune(...args: any[]): any;
_computeNode(): any;
_computeParent(): any;
_computeScope(): Scope | null;
getValueProperty(name: any): any;
needsParens(assumeExpressionContext?: boolean): boolean;
canBeFirstInStatement(): boolean;
firstInStatement(): boolean;
} |
1,181 | function addTypePattern(patternPath: NodePath, types: any) {
var pattern = patternPath.value;
namedTypes.Pattern.assert(pattern);
if (namedTypes.Identifier.check(pattern)) {
if (hasOwn.call(types, pattern.name)) {
types[pattern.name].push(patternPath);
} else {
types[pattern.name] = [patternPath];
}
}
} | interface NodePath<N = any, V = any> extends Path<V> {
node: N;
parent: any;
scope: any;
replace: Path['replace'];
prune(...args: any[]): any;
_computeNode(): any;
_computeParent(): any;
_computeScope(): Scope | null;
getValueProperty(name: any): any;
needsParens(assumeExpressionContext?: boolean): boolean;
canBeFirstInStatement(): boolean;
firstInStatement(): boolean;
} |
1,182 | function addTypeParameter(parameterPath: NodePath, types: any) {
var parameter = parameterPath.value;
FlowOrTSTypeParameterType.assert(parameter);
if (hasOwn.call(types, parameter.name)) {
types[parameter.name].push(parameterPath);
} else {
types[parameter.name] = [parameterPath];
}
} | interface NodePath<N = any, V = any> extends Path<V> {
node: N;
parent: any;
scope: any;
replace: Path['replace'];
prune(...args: any[]): any;
_computeNode(): any;
_computeParent(): any;
_computeScope(): Scope | null;
getValueProperty(name: any): any;
needsParens(assumeExpressionContext?: boolean): boolean;
canBeFirstInStatement(): boolean;
firstInStatement(): boolean;
} |
1,183 | function nodePathPlugin(fork: Fork): NodePathConstructor {
var types = fork.use(typesPlugin);
var n = types.namedTypes;
var b = types.builders;
var isNumber = types.builtInTypes.number;
var isArray = types.builtInTypes.array;
var Path = fork.use(pathPlugin);
var Scope = fork.use(scopePlugin);
const NodePath = function NodePath(this: NodePath, value: any, parentPath?: any, name?: any) {
if (!(this instanceof NodePath)) {
throw new Error("NodePath constructor cannot be invoked without 'new'");
}
Path.call(this, value, parentPath, name);
} as any as NodePathConstructor;
var NPp: NodePath = NodePath.prototype = Object.create(Path.prototype, {
constructor: {
value: NodePath,
enumerable: false,
writable: true,
configurable: true
}
});
Object.defineProperties(NPp, {
node: {
get: function () {
Object.defineProperty(this, "node", {
configurable: true, // Enable deletion.
value: this._computeNode()
});
return this.node;
}
},
parent: {
get: function () {
Object.defineProperty(this, "parent", {
configurable: true, // Enable deletion.
value: this._computeParent()
});
return this.parent;
}
},
scope: {
get: function () {
Object.defineProperty(this, "scope", {
configurable: true, // Enable deletion.
value: this._computeScope()
});
return this.scope;
}
}
});
NPp.replace = function () {
delete this.node;
delete this.parent;
delete this.scope;
return Path.prototype.replace.apply(this, arguments);
};
NPp.prune = function () {
var remainingNodePath = this.parent;
this.replace();
return cleanUpNodesAfterPrune(remainingNodePath);
};
// The value of the first ancestor Path whose value is a Node.
NPp._computeNode = function () {
var value = this.value;
if (n.Node.check(value)) {
return value;
}
var pp = this.parentPath;
return pp && pp.node || null;
};
// The first ancestor Path whose value is a Node distinct from this.node.
NPp._computeParent = function () {
var value = this.value;
var pp = this.parentPath;
if (!n.Node.check(value)) {
while (pp && !n.Node.check(pp.value)) {
pp = pp.parentPath;
}
if (pp) {
pp = pp.parentPath;
}
}
while (pp && !n.Node.check(pp.value)) {
pp = pp.parentPath;
}
return pp || null;
};
// The closest enclosing scope that governs this node.
NPp._computeScope = function () {
var value = this.value;
var pp = this.parentPath;
var scope = pp && pp.scope;
if (n.Node.check(value) &&
Scope.isEstablishedBy(value)) {
scope = new Scope(this, scope);
}
return scope || null;
};
NPp.getValueProperty = function (name) {
return types.getFieldValue(this.value, name);
};
/**
* Determine whether this.node needs to be wrapped in parentheses in order
* for a parser to reproduce the same local AST structure.
*
* For instance, in the expression `(1 + 2) * 3`, the BinaryExpression
* whose operator is "+" needs parentheses, because `1 + 2 * 3` would
* parse differently.
*
* If assumeExpressionContext === true, we don't worry about edge cases
* like an anonymous FunctionExpression appearing lexically first in its
* enclosing statement and thus needing parentheses to avoid being parsed
* as a FunctionDeclaration with a missing name.
*/
NPp.needsParens = function (assumeExpressionContext) {
var pp = this.parentPath;
if (!pp) {
return false;
}
var node = this.value;
// Only expressions need parentheses.
if (!n.Expression.check(node)) {
return false;
}
// Identifiers never need parentheses.
if (node.type === "Identifier") {
return false;
}
while (!n.Node.check(pp.value)) {
pp = pp.parentPath;
if (!pp) {
return false;
}
}
var parent = pp.value;
switch (node.type) {
case "UnaryExpression":
case "SpreadElement":
case "SpreadProperty":
return parent.type === "MemberExpression"
&& this.name === "object"
&& parent.object === node;
case "BinaryExpression":
case "LogicalExpression":
switch (parent.type) {
case "CallExpression":
return this.name === "callee"
&& parent.callee === node;
case "UnaryExpression":
case "SpreadElement":
case "SpreadProperty":
return true;
case "MemberExpression":
return this.name === "object"
&& parent.object === node;
case "BinaryExpression":
case "LogicalExpression": {
const n = node as namedTypes.BinaryExpression | namedTypes.LogicalExpression;
const po = parent.operator;
const pp = PRECEDENCE[po];
const no = n.operator;
const np = PRECEDENCE[no];
if (pp > np) {
return true;
}
if (pp === np && this.name === "right") {
if (parent.right !== n) {
throw new Error("Nodes must be equal");
}
return true;
}
}
default:
return false;
}
case "SequenceExpression":
switch (parent.type) {
case "ForStatement":
// Although parentheses wouldn't hurt around sequence
// expressions in the head of for loops, traditional style
// dictates that e.g. i++, j++ should not be wrapped with
// parentheses.
return false;
case "ExpressionStatement":
return this.name !== "expression";
default:
// Otherwise err on the side of overparenthesization, adding
// explicit exceptions above if this proves overzealous.
return true;
}
case "YieldExpression":
switch (parent.type) {
case "BinaryExpression":
case "LogicalExpression":
case "UnaryExpression":
case "SpreadElement":
case "SpreadProperty":
case "CallExpression":
case "MemberExpression":
case "NewExpression":
case "ConditionalExpression":
case "YieldExpression":
return true;
default:
return false;
}
case "Literal":
return parent.type === "MemberExpression"
&& isNumber.check((node as namedTypes.Literal).value)
&& this.name === "object"
&& parent.object === node;
case "AssignmentExpression":
case "ConditionalExpression":
switch (parent.type) {
case "UnaryExpression":
case "SpreadElement":
case "SpreadProperty":
case "BinaryExpression":
case "LogicalExpression":
return true;
case "CallExpression":
return this.name === "callee"
&& parent.callee === node;
case "ConditionalExpression":
return this.name === "test"
&& parent.test === node;
case "MemberExpression":
return this.name === "object"
&& parent.object === node;
default:
return false;
}
default:
if (parent.type === "NewExpression" &&
this.name === "callee" &&
parent.callee === node) {
return containsCallExpression(node);
}
}
if (assumeExpressionContext !== true &&
!this.canBeFirstInStatement() &&
this.firstInStatement())
return true;
return false;
};
function isBinary(node: any) {
return n.BinaryExpression.check(node)
|| n.LogicalExpression.check(node);
}
// @ts-ignore 'isUnaryLike' is declared but its value is never read. [6133]
function isUnaryLike(node: any) {
return n.UnaryExpression.check(node)
// I considered making SpreadElement and SpreadProperty subtypes
// of UnaryExpression, but they're not really Expression nodes.
|| (n.SpreadElement && n.SpreadElement.check(node))
|| (n.SpreadProperty && n.SpreadProperty.check(node));
}
var PRECEDENCE: any = {};
[["||"],
["&&"],
["|"],
["^"],
["&"],
["==", "===", "!=", "!=="],
["<", ">", "<=", ">=", "in", "instanceof"],
[">>", "<<", ">>>"],
["+", "-"],
["*", "/", "%"]
].forEach(function (tier, i) {
tier.forEach(function (op) {
PRECEDENCE[op] = i;
});
});
function containsCallExpression(node: any): any {
if (n.CallExpression.check(node)) {
return true;
}
if (isArray.check(node)) {
return node.some(containsCallExpression);
}
if (n.Node.check(node)) {
return types.someField(node, function (_name: any, child: any) {
return containsCallExpression(child);
});
}
return false;
}
NPp.canBeFirstInStatement = function () {
var node = this.node;
return !n.FunctionExpression.check(node)
&& !n.ObjectExpression.check(node);
};
NPp.firstInStatement = function () {
return firstInStatement(this);
};
function firstInStatement(path: any) {
for (var node, parent; path.parent; path = path.parent) {
node = path.node;
parent = path.parent.node;
if (n.BlockStatement.check(parent) &&
path.parent.name === "body" &&
path.name === 0) {
if (parent.body[0] !== node) {
throw new Error("Nodes must be equal");
}
return true;
}
if (n.ExpressionStatement.check(parent) &&
path.name === "expression") {
if (parent.expression !== node) {
throw new Error("Nodes must be equal");
}
return true;
}
if (n.SequenceExpression.check(parent) &&
path.parent.name === "expressions" &&
path.name === 0) {
if (parent.expressions[0] !== node) {
throw new Error("Nodes must be equal");
}
continue;
}
if (n.CallExpression.check(parent) &&
path.name === "callee") {
if (parent.callee !== node) {
throw new Error("Nodes must be equal");
}
continue;
}
if (n.MemberExpression.check(parent) &&
path.name === "object") {
if (parent.object !== node) {
throw new Error("Nodes must be equal");
}
continue;
}
if (n.ConditionalExpression.check(parent) &&
path.name === "test") {
if (parent.test !== node) {
throw new Error("Nodes must be equal");
}
continue;
}
if (isBinary(parent) &&
path.name === "left") {
if (parent.left !== node) {
throw new Error("Nodes must be equal");
}
continue;
}
if (n.UnaryExpression.check(parent) &&
!parent.prefix &&
path.name === "argument") {
if (parent.argument !== node) {
throw new Error("Nodes must be equal");
}
continue;
}
return false;
}
return true;
}
/**
* Pruning certain nodes will result in empty or incomplete nodes, here we clean those nodes up.
*/
function cleanUpNodesAfterPrune(remainingNodePath: any) {
if (n.VariableDeclaration.check(remainingNodePath.node)) {
var declarations = remainingNodePath.get('declarations').value;
if (!declarations || declarations.length === 0) {
return remainingNodePath.prune();
}
} else if (n.ExpressionStatement.check(remainingNodePath.node)) {
if (!remainingNodePath.get('expression').value) {
return remainingNodePath.prune();
}
} else if (n.IfStatement.check(remainingNodePath.node)) {
cleanUpIfStatementAfterPrune(remainingNodePath);
}
return remainingNodePath;
}
function cleanUpIfStatementAfterPrune(ifStatement: any) {
var testExpression = ifStatement.get('test').value;
var alternate = ifStatement.get('alternate').value;
var consequent = ifStatement.get('consequent').value;
if (!consequent && !alternate) {
var testExpressionStatement = b.expressionStatement(testExpression);
ifStatement.replace(testExpressionStatement);
} else if (!consequent && alternate) {
var negatedTestExpression: namedTypes.Expression =
b.unaryExpression('!', testExpression, true);
if (n.UnaryExpression.check(testExpression) && testExpression.operator === '!') {
negatedTestExpression = testExpression.argument;
}
ifStatement.get("test").replace(negatedTestExpression);
ifStatement.get("consequent").replace(alternate);
ifStatement.get("alternate").replace();
}
}
return NodePath;
} | type Fork = {
use<T>(plugin: Plugin<T>): T;
}; |
1,184 | function NodePath(this: NodePath, value: any, parentPath?: any, name?: any) {
if (!(this instanceof NodePath)) {
throw new Error("NodePath constructor cannot be invoked without 'new'");
}
Path.call(this, value, parentPath, name);
} | interface NodePath<N = any, V = any> extends Path<V> {
node: N;
parent: any;
scope: any;
replace: Path['replace'];
prune(...args: any[]): any;
_computeNode(): any;
_computeParent(): any;
_computeScope(): Scope | null;
getValueProperty(name: any): any;
needsParens(assumeExpressionContext?: boolean): boolean;
canBeFirstInStatement(): boolean;
firstInStatement(): boolean;
} |
1,185 | function (fork: Fork) {
var types = fork.use(typesPlugin);
var Type = types.Type;
var builtin = types.builtInTypes;
var isNumber = builtin.number;
// An example of constructing a new type with arbitrary constraints from
// an existing type.
function geq(than: any) {
return Type.from(
(value: number) => isNumber.check(value) && value >= than,
isNumber + " >= " + than,
);
};
// Default value-returning functions that may optionally be passed as a
// third argument to Def.prototype.field.
const defaults = {
// Functions were used because (among other reasons) that's the most
// elegant way to allow for the emptyArray one always to give a new
// array instance.
"null": function () { return null },
"emptyArray": function () { return [] },
"false": function () { return false },
"true": function () { return true },
"undefined": function () {},
"use strict": function () { return "use strict"; }
};
var naiveIsPrimitive = Type.or(
builtin.string,
builtin.number,
builtin.boolean,
builtin.null,
builtin.undefined
);
const isPrimitive = Type.from(
(value: any) => {
if (value === null)
return true;
var type = typeof value;
if (type === "object" ||
type === "function") {
return false;
}
return true;
},
naiveIsPrimitive.toString(),
);
return {
geq,
defaults,
isPrimitive,
};
} | type Fork = {
use<T>(plugin: Plugin<T>): T;
}; |
1,186 | function assertVisited(node: ASTNode, visitors: Visitor<any>): any {
const visitedSet: Set<string> = new Set();
const wrappedVisitors: Visitor<any> = {}
for (const _key of Object.keys(visitors)) {
const key = _key as keyof Visitor<any>
wrappedVisitors[key] = function (this: Context, path: NodePath<any>) {
visitedSet.add(key);
(visitors[key] as any)?.call(this, path)
}
}
types.visit(node, wrappedVisitors);
for (const key of Object.keys(visitors)) {
assert.equal(visitedSet.has(key), true);
}
} | interface ASTNode {
type: string;
} |
1,187 | function (this: Context, path: NodePath<any>) {
visitedSet.add(key);
(visitors[key] as any)?.call(this, path)
} | interface Context extends Omit<PathVisitor, "visit" | "reset">, SharedContextMethods {} |
1,188 | function assertVisited(node: ASTNode, visitors: Visitor<any>): any {
const visitedSet: Set<string> = new Set();
const wrappedVisitors: Visitor<any> = {}
for (const _key of Object.keys(visitors)) {
const key = _key as keyof Visitor<any>
wrappedVisitors[key] = function (this: Context, path: NodePath<any>) {
visitedSet.add(key);
(visitors[key] as any)?.call(this, path)
}
}
tsTypes.visit(node, wrappedVisitors);
for (const key of Object.keys(visitors)) {
assert.equal(visitedSet.has(key), true);
}
} | interface ASTNode {
type: string;
} |
1,189 | function (fork: Fork) {
fork.use(esProposalsDef);
var types = fork.use(typesPlugin);
var defaults = fork.use(sharedPlugin).defaults;
var def = types.Type.def;
var or = types.Type.or;
def("VariableDeclaration")
.field("declarations", [or(
def("VariableDeclarator"),
def("Identifier") // Esprima deviation.
)]);
def("Property")
.field("value", or(
def("Expression"),
def("Pattern") // Esprima deviation.
));
def("ArrayPattern")
.field("elements", [or(
def("Pattern"),
def("SpreadElement"),
null
)]);
def("ObjectPattern")
.field("properties", [or(
def("Property"),
def("PropertyPattern"),
def("SpreadPropertyPattern"),
def("SpreadProperty") // Used by Esprima.
)]);
// Like ModuleSpecifier, except type:"ExportSpecifier" and buildable.
// export {<id [as name]>} [from ...];
def("ExportSpecifier")
.bases("ModuleSpecifier")
.build("id", "name");
// export <*> from ...;
def("ExportBatchSpecifier")
.bases("Specifier")
.build();
def("ExportDeclaration")
.bases("Declaration")
.build("default", "declaration", "specifiers", "source")
.field("default", Boolean)
.field("declaration", or(
def("Declaration"),
def("Expression"), // Implies default.
null
))
.field("specifiers", [or(
def("ExportSpecifier"),
def("ExportBatchSpecifier")
)], defaults.emptyArray)
.field("source", or(
def("Literal"),
null
), defaults["null"]);
def("Block")
.bases("Comment")
.build("value", /*optional:*/ "leading", "trailing");
def("Line")
.bases("Comment")
.build("value", /*optional:*/ "leading", "trailing");
} | type Fork = {
use<T>(plugin: Plugin<T>): T;
}; |
1,190 | function (fork: Fork) {
fork.use(coreDef);
const types = fork.use(typesPlugin);
const def = types.Type.def;
const or = types.Type.or;
const defaults = fork.use(sharedPlugin).defaults;
def("Function")
.field("generator", Boolean, defaults["false"])
.field("expression", Boolean, defaults["false"])
.field("defaults", [or(def("Expression"), null)], defaults.emptyArray)
// Legacy
.field("rest", or(def("Identifier"), null), defaults["null"]);
// The ESTree way of representing a ...rest parameter.
def("RestElement")
.bases("Pattern")
.build("argument")
.field("argument", def("Pattern"))
.field("typeAnnotation", // for Babylon. Flow parser puts it on the identifier
or(def("TypeAnnotation"), def("TSTypeAnnotation"), null), defaults["null"]);
def("SpreadElementPattern")
.bases("Pattern")
.build("argument")
.field("argument", def("Pattern"));
def("FunctionDeclaration")
.build("id", "params", "body", "generator", "expression")
// May be `null` in the context of `export default function () {}`
.field("id", or(def("Identifier"), null))
def("FunctionExpression")
.build("id", "params", "body", "generator", "expression");
def("ArrowFunctionExpression")
.bases("Function", "Expression")
.build("params", "body", "expression")
// The forced null value here is compatible with the overridden
// definition of the "id" field in the Function interface.
.field("id", null, defaults["null"])
// Arrow function bodies are allowed to be expressions.
.field("body", or(def("BlockStatement"), def("Expression")))
// The current spec forbids arrow generators, so I have taken the
// liberty of enforcing that. TODO Report this.
.field("generator", false, defaults["false"]);
def("ForOfStatement")
.bases("Statement")
.build("left", "right", "body")
.field("left", or(
def("VariableDeclaration"),
def("Pattern")))
.field("right", def("Expression"))
.field("body", def("Statement"));
def("YieldExpression")
.bases("Expression")
.build("argument", "delegate")
.field("argument", or(def("Expression"), null))
.field("delegate", Boolean, defaults["false"]);
def("GeneratorExpression")
.bases("Expression")
.build("body", "blocks", "filter")
.field("body", def("Expression"))
.field("blocks", [def("ComprehensionBlock")])
.field("filter", or(def("Expression"), null));
def("ComprehensionExpression")
.bases("Expression")
.build("body", "blocks", "filter")
.field("body", def("Expression"))
.field("blocks", [def("ComprehensionBlock")])
.field("filter", or(def("Expression"), null));
def("ComprehensionBlock")
.bases("Node")
.build("left", "right", "each")
.field("left", def("Pattern"))
.field("right", def("Expression"))
.field("each", Boolean);
def("Property")
.field("key", or(def("Literal"), def("Identifier"), def("Expression")))
.field("value", or(def("Expression"), def("Pattern")))
.field("method", Boolean, defaults["false"])
.field("shorthand", Boolean, defaults["false"])
.field("computed", Boolean, defaults["false"]);
def("ObjectProperty")
.field("shorthand", Boolean, defaults["false"]);
def("PropertyPattern")
.bases("Pattern")
.build("key", "pattern")
.field("key", or(def("Literal"), def("Identifier"), def("Expression")))
.field("pattern", def("Pattern"))
.field("computed", Boolean, defaults["false"]);
def("ObjectPattern")
.bases("Pattern")
.build("properties")
.field("properties", [or(def("PropertyPattern"), def("Property"))]);
def("ArrayPattern")
.bases("Pattern")
.build("elements")
.field("elements", [or(def("Pattern"), null)]);
def("SpreadElement")
.bases("Node")
.build("argument")
.field("argument", def("Expression"));
def("ArrayExpression")
.field("elements", [or(
def("Expression"),
def("SpreadElement"),
def("RestElement"),
null
)]);
def("NewExpression")
.field("arguments", [or(def("Expression"), def("SpreadElement"))]);
def("CallExpression")
.field("arguments", [or(def("Expression"), def("SpreadElement"))]);
// Note: this node type is *not* an AssignmentExpression with a Pattern on
// the left-hand side! The existing AssignmentExpression type already
// supports destructuring assignments. AssignmentPattern nodes may appear
// wherever a Pattern is allowed, and the right-hand side represents a
// default value to be destructured against the left-hand side, if no
// value is otherwise provided. For example: default parameter values.
def("AssignmentPattern")
.bases("Pattern")
.build("left", "right")
.field("left", def("Pattern"))
.field("right", def("Expression"));
def("MethodDefinition")
.bases("Declaration")
.build("kind", "key", "value", "static")
.field("kind", or("constructor", "method", "get", "set"))
.field("key", def("Expression"))
.field("value", def("Function"))
.field("computed", Boolean, defaults["false"])
.field("static", Boolean, defaults["false"]);
const ClassBodyElement = or(
def("MethodDefinition"),
def("VariableDeclarator"),
def("ClassPropertyDefinition"),
def("ClassProperty"),
def("StaticBlock"),
);
def("ClassProperty")
.bases("Declaration")
.build("key")
.field("key", or(def("Literal"), def("Identifier"), def("Expression")))
.field("computed", Boolean, defaults["false"]);
def("ClassPropertyDefinition") // static property
.bases("Declaration")
.build("definition")
// Yes, Virginia, circular definitions are permitted.
.field("definition", ClassBodyElement);
def("ClassBody")
.bases("Declaration")
.build("body")
.field("body", [ClassBodyElement]);
def("ClassDeclaration")
.bases("Declaration")
.build("id", "body", "superClass")
.field("id", or(def("Identifier"), null))
.field("body", def("ClassBody"))
.field("superClass", or(def("Expression"), null), defaults["null"]);
def("ClassExpression")
.bases("Expression")
.build("id", "body", "superClass")
.field("id", or(def("Identifier"), null), defaults["null"])
.field("body", def("ClassBody"))
.field("superClass", or(def("Expression"), null), defaults["null"]);
def("Super")
.bases("Expression")
.build();
// Specifier and ModuleSpecifier are abstract non-standard types
// introduced for definitional convenience.
def("Specifier").bases("Node");
// This supertype is shared/abused by both def/babel.js and
// def/esprima.js. In the future, it will be possible to load only one set
// of definitions appropriate for a given parser, but until then we must
// rely on default functions to reconcile the conflicting AST formats.
def("ModuleSpecifier")
.bases("Specifier")
// This local field is used by Babel/Acorn. It should not technically
// be optional in the Babel/Acorn AST format, but it must be optional
// in the Esprima AST format.
.field("local", or(def("Identifier"), null), defaults["null"])
// The id and name fields are used by Esprima. The id field should not
// technically be optional in the Esprima AST format, but it must be
// optional in the Babel/Acorn AST format.
.field("id", or(def("Identifier"), null), defaults["null"])
.field("name", or(def("Identifier"), null), defaults["null"]);
// import {<id [as name]>} from ...;
def("ImportSpecifier")
.bases("ModuleSpecifier")
.build("imported", "local")
.field("imported", def("Identifier"));
// import <id> from ...;
def("ImportDefaultSpecifier")
.bases("ModuleSpecifier")
.build("local");
// import <* as id> from ...;
def("ImportNamespaceSpecifier")
.bases("ModuleSpecifier")
.build("local");
def("ImportDeclaration")
.bases("Declaration")
.build("specifiers", "source", "importKind")
.field("specifiers", [or(
def("ImportSpecifier"),
def("ImportNamespaceSpecifier"),
def("ImportDefaultSpecifier")
)], defaults.emptyArray)
.field("source", def("Literal"))
.field("importKind", or(
"value",
"type"
), function() {
return "value";
});
def("ExportNamedDeclaration")
.bases("Declaration")
.build("declaration", "specifiers", "source")
.field("declaration", or(def("Declaration"), null))
.field("specifiers", [def("ExportSpecifier")], defaults.emptyArray)
.field("source", or(def("Literal"), null), defaults["null"]);
def("ExportSpecifier")
.bases("ModuleSpecifier")
.build("local", "exported")
.field("exported", def("Identifier"));
def("ExportDefaultDeclaration")
.bases("Declaration")
.build("declaration")
.field("declaration", or(def("Declaration"), def("Expression")));
def("ExportAllDeclaration")
.bases("Declaration")
.build("source")
.field("source", def("Literal"));
def("TaggedTemplateExpression")
.bases("Expression")
.build("tag", "quasi")
.field("tag", def("Expression"))
.field("quasi", def("TemplateLiteral"));
def("TemplateLiteral")
.bases("Expression")
.build("quasis", "expressions")
.field("quasis", [def("TemplateElement")])
.field("expressions", [def("Expression")]);
def("TemplateElement")
.bases("Node")
.build("value", "tail")
.field("value", {"cooked": String, "raw": String})
.field("tail", Boolean);
def("MetaProperty")
.bases("Expression")
.build("meta", "property")
.field("meta", def("Identifier"))
.field("property", def("Identifier"));
} | type Fork = {
use<T>(plugin: Plugin<T>): T;
}; |
1,191 | function (fork: Fork) {
// The es2016OpsDef plugin comes before es6Def so BinaryOperators and
// AssignmentOperators will be appropriately augmented before they are first
// used in the core definitions for this fork.
fork.use(es2016OpsDef);
fork.use(es6Def);
} | type Fork = {
use<T>(plugin: Plugin<T>): T;
}; |
1,192 | function (fork: Fork) {
fork.use(esProposalsDef);
fork.use(typeAnnotationsDef);
const types = fork.use(typesPlugin);
const def = types.Type.def;
const or = types.Type.or;
const defaults = fork.use(sharedPlugin).defaults;
// Base types
def("Flow").bases("Node");
def("FlowType").bases("Flow");
// Type annotations
def("AnyTypeAnnotation")
.bases("FlowType")
.build();
def("EmptyTypeAnnotation")
.bases("FlowType")
.build();
def("MixedTypeAnnotation")
.bases("FlowType")
.build();
def("VoidTypeAnnotation")
.bases("FlowType")
.build();
def("SymbolTypeAnnotation")
.bases("FlowType")
.build();
def("NumberTypeAnnotation")
.bases("FlowType")
.build();
def("BigIntTypeAnnotation")
.bases("FlowType")
.build();
def("NumberLiteralTypeAnnotation")
.bases("FlowType")
.build("value", "raw")
.field("value", Number)
.field("raw", String);
// Babylon 6 differs in AST from Flow
// same as NumberLiteralTypeAnnotation
def("NumericLiteralTypeAnnotation")
.bases("FlowType")
.build("value", "raw")
.field("value", Number)
.field("raw", String);
def("BigIntLiteralTypeAnnotation")
.bases("FlowType")
.build("value", "raw")
.field("value", null)
.field("raw", String);
def("StringTypeAnnotation")
.bases("FlowType")
.build();
def("StringLiteralTypeAnnotation")
.bases("FlowType")
.build("value", "raw")
.field("value", String)
.field("raw", String);
def("BooleanTypeAnnotation")
.bases("FlowType")
.build();
def("BooleanLiteralTypeAnnotation")
.bases("FlowType")
.build("value", "raw")
.field("value", Boolean)
.field("raw", String);
def("TypeAnnotation")
.bases("Node")
.build("typeAnnotation")
.field("typeAnnotation", def("FlowType"));
def("NullableTypeAnnotation")
.bases("FlowType")
.build("typeAnnotation")
.field("typeAnnotation", def("FlowType"));
def("NullLiteralTypeAnnotation")
.bases("FlowType")
.build();
def("NullTypeAnnotation")
.bases("FlowType")
.build();
def("ThisTypeAnnotation")
.bases("FlowType")
.build();
def("ExistsTypeAnnotation")
.bases("FlowType")
.build();
def("ExistentialTypeParam")
.bases("FlowType")
.build();
def("FunctionTypeAnnotation")
.bases("FlowType")
.build("params", "returnType", "rest", "typeParameters")
.field("params", [def("FunctionTypeParam")])
.field("returnType", def("FlowType"))
.field("rest", or(def("FunctionTypeParam"), null))
.field("typeParameters", or(def("TypeParameterDeclaration"), null));
def("FunctionTypeParam")
.bases("Node")
.build("name", "typeAnnotation", "optional")
.field("name", or(def("Identifier"), null))
.field("typeAnnotation", def("FlowType"))
.field("optional", Boolean);
def("ArrayTypeAnnotation")
.bases("FlowType")
.build("elementType")
.field("elementType", def("FlowType"));
def("ObjectTypeAnnotation")
.bases("FlowType")
.build("properties", "indexers", "callProperties")
.field("properties", [
or(def("ObjectTypeProperty"),
def("ObjectTypeSpreadProperty"))
])
.field("indexers", [def("ObjectTypeIndexer")], defaults.emptyArray)
.field("callProperties",
[def("ObjectTypeCallProperty")],
defaults.emptyArray)
.field("inexact", or(Boolean, void 0), defaults["undefined"])
.field("exact", Boolean, defaults["false"])
.field("internalSlots", [def("ObjectTypeInternalSlot")], defaults.emptyArray);
def("Variance")
.bases("Node")
.build("kind")
.field("kind", or("plus", "minus"));
const LegacyVariance = or(
def("Variance"),
"plus",
"minus",
null
);
def("ObjectTypeProperty")
.bases("Node")
.build("key", "value", "optional")
.field("key", or(def("Literal"), def("Identifier")))
.field("value", def("FlowType"))
.field("optional", Boolean)
.field("variance", LegacyVariance, defaults["null"]);
def("ObjectTypeIndexer")
.bases("Node")
.build("id", "key", "value")
.field("id", def("Identifier"))
.field("key", def("FlowType"))
.field("value", def("FlowType"))
.field("variance", LegacyVariance, defaults["null"])
.field("static", Boolean, defaults["false"]);
def("ObjectTypeCallProperty")
.bases("Node")
.build("value")
.field("value", def("FunctionTypeAnnotation"))
.field("static", Boolean, defaults["false"]);
def("QualifiedTypeIdentifier")
.bases("Node")
.build("qualification", "id")
.field("qualification",
or(def("Identifier"),
def("QualifiedTypeIdentifier")))
.field("id", def("Identifier"));
def("GenericTypeAnnotation")
.bases("FlowType")
.build("id", "typeParameters")
.field("id", or(def("Identifier"), def("QualifiedTypeIdentifier")))
.field("typeParameters", or(def("TypeParameterInstantiation"), null));
def("MemberTypeAnnotation")
.bases("FlowType")
.build("object", "property")
.field("object", def("Identifier"))
.field("property",
or(def("MemberTypeAnnotation"),
def("GenericTypeAnnotation")));
def("IndexedAccessType")
.bases("FlowType")
.build("objectType", "indexType")
.field("objectType", def("FlowType"))
.field("indexType", def("FlowType"));
def("OptionalIndexedAccessType")
.bases("FlowType")
.build("objectType", "indexType", "optional")
.field("objectType", def("FlowType"))
.field("indexType", def("FlowType"))
.field('optional', Boolean);
def("UnionTypeAnnotation")
.bases("FlowType")
.build("types")
.field("types", [def("FlowType")]);
def("IntersectionTypeAnnotation")
.bases("FlowType")
.build("types")
.field("types", [def("FlowType")]);
def("TypeofTypeAnnotation")
.bases("FlowType")
.build("argument")
.field("argument", def("FlowType"));
def("ObjectTypeSpreadProperty")
.bases("Node")
.build("argument")
.field("argument", def("FlowType"));
def("ObjectTypeInternalSlot")
.bases("Node")
.build("id", "value", "optional", "static", "method")
.field("id", def("Identifier"))
.field("value", def("FlowType"))
.field("optional", Boolean)
.field("static", Boolean)
.field("method", Boolean);
def("TypeParameterDeclaration")
.bases("Node")
.build("params")
.field("params", [def("TypeParameter")]);
def("TypeParameterInstantiation")
.bases("Node")
.build("params")
.field("params", [def("FlowType")]);
def("TypeParameter")
.bases("FlowType")
.build("name", "variance", "bound", "default")
.field("name", String)
.field("variance", LegacyVariance, defaults["null"])
.field("bound", or(def("TypeAnnotation"), null), defaults["null"])
.field("default", or(def("FlowType"), null), defaults["null"]);
def("ClassProperty")
.field("variance", LegacyVariance, defaults["null"]);
def("ClassImplements")
.bases("Node")
.build("id")
.field("id", def("Identifier"))
.field("superClass", or(def("Expression"), null), defaults["null"])
.field("typeParameters",
or(def("TypeParameterInstantiation"), null),
defaults["null"]);
def("InterfaceTypeAnnotation")
.bases("FlowType")
.build("body", "extends")
.field("body", def("ObjectTypeAnnotation"))
.field("extends", or([def("InterfaceExtends")], null), defaults["null"]);
def("InterfaceDeclaration")
.bases("Declaration")
.build("id", "body", "extends")
.field("id", def("Identifier"))
.field("typeParameters",
or(def("TypeParameterDeclaration"), null),
defaults["null"])
.field("body", def("ObjectTypeAnnotation"))
.field("extends", [def("InterfaceExtends")]);
def("DeclareInterface")
.bases("InterfaceDeclaration")
.build("id", "body", "extends");
def("InterfaceExtends")
.bases("Node")
.build("id")
.field("id", def("Identifier"))
.field("typeParameters",
or(def("TypeParameterInstantiation"), null),
defaults["null"]);
def("TypeAlias")
.bases("Declaration")
.build("id", "typeParameters", "right")
.field("id", def("Identifier"))
.field("typeParameters", or(def("TypeParameterDeclaration"), null))
.field("right", def("FlowType"));
def("DeclareTypeAlias")
.bases("TypeAlias")
.build("id", "typeParameters", "right");
def("OpaqueType")
.bases("Declaration")
.build("id", "typeParameters", "impltype", "supertype")
.field("id", def("Identifier"))
.field("typeParameters", or(def("TypeParameterDeclaration"), null))
.field("impltype", def("FlowType"))
.field("supertype", or(def("FlowType"), null));
def("DeclareOpaqueType")
.bases("OpaqueType")
.build("id", "typeParameters", "supertype")
.field("impltype", or(def("FlowType"), null));
def("TypeCastExpression")
.bases("Expression")
.build("expression", "typeAnnotation")
.field("expression", def("Expression"))
.field("typeAnnotation", def("TypeAnnotation"));
def("TupleTypeAnnotation")
.bases("FlowType")
.build("types")
.field("types", [def("FlowType")]);
def("DeclareVariable")
.bases("Statement")
.build("id")
.field("id", def("Identifier"));
def("DeclareFunction")
.bases("Statement")
.build("id")
.field("id", def("Identifier"))
.field("predicate", or(def("FlowPredicate"), null), defaults["null"]);
def("DeclareClass")
.bases("InterfaceDeclaration")
.build("id");
def("DeclareModule")
.bases("Statement")
.build("id", "body")
.field("id", or(def("Identifier"), def("Literal")))
.field("body", def("BlockStatement"));
def("DeclareModuleExports")
.bases("Statement")
.build("typeAnnotation")
.field("typeAnnotation", def("TypeAnnotation"));
def("DeclareExportDeclaration")
.bases("Declaration")
.build("default", "declaration", "specifiers", "source")
.field("default", Boolean)
.field("declaration", or(
def("DeclareVariable"),
def("DeclareFunction"),
def("DeclareClass"),
def("FlowType"), // Implies default.
def("TypeAlias"), // Implies named type
def("DeclareOpaqueType"), // Implies named opaque type
def("InterfaceDeclaration"),
null
))
.field("specifiers", [or(
def("ExportSpecifier"),
def("ExportBatchSpecifier")
)], defaults.emptyArray)
.field("source", or(
def("Literal"),
null
), defaults["null"]);
def("DeclareExportAllDeclaration")
.bases("Declaration")
.build("source")
.field("source", or(
def("Literal"),
null
), defaults["null"]);
def("ImportDeclaration")
.field("importKind", or("value", "type", "typeof"), () => "value");
def("FlowPredicate").bases("Flow");
def("InferredPredicate")
.bases("FlowPredicate")
.build();
def("DeclaredPredicate")
.bases("FlowPredicate")
.build("value")
.field("value", def("Expression"));
def("Function")
.field("predicate", or(def("FlowPredicate"), null), defaults["null"]);
def("CallExpression")
.field("typeArguments", or(
null,
def("TypeParameterInstantiation"),
), defaults["null"]);
def("NewExpression")
.field("typeArguments", or(
null,
def("TypeParameterInstantiation"),
), defaults["null"]);
// Enums
def("EnumDeclaration")
.bases("Declaration")
.build("id", "body")
.field("id", def("Identifier"))
.field("body", or(
def("EnumBooleanBody"),
def("EnumNumberBody"),
def("EnumStringBody"),
def("EnumSymbolBody")));
def("EnumBooleanBody")
.build("members", "explicitType")
.field("members", [def("EnumBooleanMember")])
.field("explicitType", Boolean);
def("EnumNumberBody")
.build("members", "explicitType")
.field("members", [def("EnumNumberMember")])
.field("explicitType", Boolean);
def("EnumStringBody")
.build("members", "explicitType")
.field("members", or([def("EnumStringMember")], [def("EnumDefaultedMember")]))
.field("explicitType", Boolean);
def("EnumSymbolBody")
.build("members")
.field("members", [def("EnumDefaultedMember")]);
def("EnumBooleanMember")
.build("id", "init")
.field("id", def("Identifier"))
.field("init", or(def("Literal"), Boolean));
def("EnumNumberMember")
.build("id", "init")
.field("id", def("Identifier"))
.field("init", def("Literal"));
def("EnumStringMember")
.build("id", "init")
.field("id", def("Identifier"))
.field("init", def("Literal"));
def("EnumDefaultedMember")
.build("id")
.field("id", def("Identifier"));
} | type Fork = {
use<T>(plugin: Plugin<T>): T;
}; |
1,193 | function (fork: Fork) {
fork.use(es2017Def);
const types = fork.use(typesPlugin);
const def = types.Type.def;
const or = types.Type.or;
const defaults = fork.use(sharedPlugin).defaults;
def("ForOfStatement")
.field("await", Boolean, defaults["false"]);
// Legacy
def("SpreadProperty")
.bases("Node")
.build("argument")
.field("argument", def("Expression"));
def("ObjectExpression")
.field("properties", [or(
def("Property"),
def("SpreadProperty"), // Legacy
def("SpreadElement")
)]);
def("TemplateElement")
.field("value", {"cooked": or(String, null), "raw": String});
// Legacy
def("SpreadPropertyPattern")
.bases("Pattern")
.build("argument")
.field("argument", def("Pattern"));
def("ObjectPattern")
.field("properties", [or(def("PropertyPattern"), def("Property"), def("RestElement"), def("SpreadPropertyPattern"))]);
} | type Fork = {
use<T>(plugin: Plugin<T>): T;
}; |
1,194 | function (fork: Fork) {
// The es2020OpsDef plugin comes before es2019Def so LogicalOperators will be
// appropriately augmented before first used.
fork.use(es2020OpsDef);
fork.use(es2019Def);
const types = fork.use(typesPlugin);
const def = types.Type.def;
const or = types.Type.or;
const shared = fork.use(sharedPlugin);
const defaults = shared.defaults;
def("ImportExpression")
.bases("Expression")
.build("source")
.field("source", def("Expression"));
def("ExportAllDeclaration")
.bases("Declaration")
.build("source", "exported")
.field("source", def("Literal"))
.field("exported", or(
def("Identifier"),
null,
void 0,
), defaults["null"]);
// Optional chaining
def("ChainElement")
.bases("Node")
.field("optional", Boolean, defaults["false"]);
def("CallExpression")
.bases("Expression", "ChainElement");
def("MemberExpression")
.bases("Expression", "ChainElement");
def("ChainExpression")
.bases("Expression")
.build("expression")
.field("expression", def("ChainElement"));
def("OptionalCallExpression")
.bases("CallExpression")
.build("callee", "arguments", "optional")
.field("optional", Boolean, defaults["true"]);
// Deprecated optional chaining type, doesn't work with [email protected] or newer
def("OptionalMemberExpression")
.bases("MemberExpression")
.build("object", "property", "computed", "optional")
.field("optional", Boolean, defaults["true"]);
} | type Fork = {
use<T>(plugin: Plugin<T>): T;
}; |
1,195 | function (fork: Fork) {
// The es2021OpsDef plugin comes before es2020Def so AssignmentOperators will
// be appropriately augmented before first used.
fork.use(es2021OpsDef);
fork.use(es2020Def);
} | type Fork = {
use<T>(plugin: Plugin<T>): T;
}; |
1,196 | function (fork: Fork) {
const types = fork.use(typesPlugin);
const def = types.Type.def;
fork.use(babelCoreDef);
fork.use(flowDef);
// https://github.com/babel/babel/pull/10148
def("V8IntrinsicIdentifier")
.bases("Expression")
.build("name")
.field("name", String);
// https://github.com/babel/babel/pull/13191
// https://github.com/babel/website/pull/2541
def("TopicReference")
.bases("Expression")
.build();
} | type Fork = {
use<T>(plugin: Plugin<T>): T;
}; |
1,197 | function (fork: Fork) {
fork.use(esProposalsDef);
const types = fork.use(typesPlugin);
const defaults = fork.use(sharedPlugin).defaults;
const def = types.Type.def;
const or = types.Type.or;
const {
undefined: isUndefined,
} = types.builtInTypes;
def("Noop")
.bases("Statement")
.build();
def("DoExpression")
.bases("Expression")
.build("body")
.field("body", [def("Statement")]);
def("BindExpression")
.bases("Expression")
.build("object", "callee")
.field("object", or(def("Expression"), null))
.field("callee", def("Expression"));
def("ParenthesizedExpression")
.bases("Expression")
.build("expression")
.field("expression", def("Expression"));
def("ExportNamespaceSpecifier")
.bases("Specifier")
.build("exported")
.field("exported", def("Identifier"));
def("ExportDefaultSpecifier")
.bases("Specifier")
.build("exported")
.field("exported", def("Identifier"));
def("CommentBlock")
.bases("Comment")
.build("value", /*optional:*/ "leading", "trailing");
def("CommentLine")
.bases("Comment")
.build("value", /*optional:*/ "leading", "trailing");
def("Directive")
.bases("Node")
.build("value")
.field("value", def("DirectiveLiteral"));
def("DirectiveLiteral")
.bases("Node", "Expression")
.build("value")
.field("value", String, defaults["use strict"]);
def("InterpreterDirective")
.bases("Node")
.build("value")
.field("value", String);
def("BlockStatement")
.bases("Statement")
.build("body")
.field("body", [def("Statement")])
.field("directives", [def("Directive")], defaults.emptyArray);
def("Program")
.bases("Node")
.build("body")
.field("body", [def("Statement")])
.field("directives", [def("Directive")], defaults.emptyArray)
.field("interpreter", or(def("InterpreterDirective"), null), defaults["null"]);
function makeLiteralExtra<
// Allowing N.RegExpLiteral explicitly here is important because the
// node.value field of RegExpLiteral nodes can be undefined, which is not
// allowed for other Literal subtypes.
TNode extends Omit<N.Literal, "type"> | N.RegExpLiteral
>(
rawValueType: any = String,
toRaw?: (value: any) => string,
): Parameters<import("../types").Def["field"]> {
return [
"extra",
{
rawValue: rawValueType,
raw: String,
},
function getDefault(this: TNode) {
const value = types.getFieldValue(this, "value");
return {
rawValue: value,
raw: toRaw ? toRaw(value) : String(value),
};
},
];
}
// Split Literal
def("StringLiteral")
.bases("Literal")
.build("value")
.field("value", String)
.field(...makeLiteralExtra<N.StringLiteral>(String, val => JSON.stringify(val)));
def("NumericLiteral")
.bases("Literal")
.build("value")
.field("value", Number)
.field("raw", or(String, null), defaults["null"])
.field(...makeLiteralExtra<N.NumericLiteral>(Number));
def("BigIntLiteral")
.bases("Literal")
.build("value")
// Only String really seems appropriate here, since BigInt values
// often exceed the limits of JS numbers.
.field("value", or(String, Number))
.field(...makeLiteralExtra<N.BigIntLiteral>(String, val => val + "n"));
// https://github.com/tc39/proposal-decimal
// https://github.com/babel/babel/pull/11640
def("DecimalLiteral")
.bases("Literal")
.build("value")
.field("value", String)
.field(...makeLiteralExtra<N.DecimalLiteral>(String, val => val + "m"));
def("NullLiteral")
.bases("Literal")
.build()
.field("value", null, defaults["null"]);
def("BooleanLiteral")
.bases("Literal")
.build("value")
.field("value", Boolean);
def("RegExpLiteral")
.bases("Literal")
.build("pattern", "flags")
.field("pattern", String)
.field("flags", String)
.field("value", RegExp, function (this: N.RegExpLiteral) {
return new RegExp(this.pattern, this.flags);
})
.field(...makeLiteralExtra<N.RegExpLiteral>(
or(RegExp, isUndefined),
exp => `/${exp.pattern}/${exp.flags || ""}`,
))
// I'm not sure why this field exists, but it's "specified" by estree:
// https://github.com/estree/estree/blob/master/es5.md#regexpliteral
.field("regex", {
pattern: String,
flags: String
}, function (this: N.RegExpLiteral) {
return {
pattern: this.pattern,
flags: this.flags,
};
});
var ObjectExpressionProperty = or(
def("Property"),
def("ObjectMethod"),
def("ObjectProperty"),
def("SpreadProperty"),
def("SpreadElement")
);
// Split Property -> ObjectProperty and ObjectMethod
def("ObjectExpression")
.bases("Expression")
.build("properties")
.field("properties", [ObjectExpressionProperty]);
// ObjectMethod hoist .value properties to own properties
def("ObjectMethod")
.bases("Node", "Function")
.build("kind", "key", "params", "body", "computed")
.field("kind", or("method", "get", "set"))
.field("key", or(def("Literal"), def("Identifier"), def("Expression")))
.field("params", [def("Pattern")])
.field("body", def("BlockStatement"))
.field("computed", Boolean, defaults["false"])
.field("generator", Boolean, defaults["false"])
.field("async", Boolean, defaults["false"])
.field("accessibility", // TypeScript
or(def("Literal"), null),
defaults["null"])
.field("decorators",
or([def("Decorator")], null),
defaults["null"]);
def("ObjectProperty")
.bases("Node")
.build("key", "value")
.field("key", or(def("Literal"), def("Identifier"), def("Expression")))
.field("value", or(def("Expression"), def("Pattern")))
.field("accessibility", // TypeScript
or(def("Literal"), null),
defaults["null"])
.field("computed", Boolean, defaults["false"]);
var ClassBodyElement = or(
def("MethodDefinition"),
def("VariableDeclarator"),
def("ClassPropertyDefinition"),
def("ClassProperty"),
def("ClassPrivateProperty"),
def("ClassMethod"),
def("ClassPrivateMethod"),
def("ClassAccessorProperty"),
def("StaticBlock"),
);
// MethodDefinition -> ClassMethod
def("ClassBody")
.bases("Declaration")
.build("body")
.field("body", [ClassBodyElement]);
def("ClassMethod")
.bases("Declaration", "Function")
.build("kind", "key", "params", "body", "computed", "static")
.field("key", or(def("Literal"), def("Identifier"), def("Expression")));
def("ClassPrivateMethod")
.bases("Declaration", "Function")
.build("key", "params", "body", "kind", "computed", "static")
.field("key", def("PrivateName"));
def("ClassAccessorProperty")
.bases("Declaration")
.build("key", "value", "decorators", "computed", "static")
.field("key", or(
def("Literal"),
def("Identifier"),
def("PrivateName"),
// Only when .computed is true (TODO enforce this)
def("Expression"),
))
.field("value", or(def("Expression"), null), defaults["null"]);
["ClassMethod",
"ClassPrivateMethod",
].forEach(typeName => {
def(typeName)
.field("kind", or("get", "set", "method", "constructor"), () => "method")
.field("body", def("BlockStatement"))
// For backwards compatibility only. Expect accessibility instead (see below).
.field("access", or("public", "private", "protected", null), defaults["null"])
});
["ClassMethod",
"ClassPrivateMethod",
"ClassAccessorProperty",
].forEach(typeName => {
def(typeName)
.field("computed", Boolean, defaults["false"])
.field("static", Boolean, defaults["false"])
.field("abstract", Boolean, defaults["false"])
.field("accessibility", or("public", "private", "protected", null), defaults["null"])
.field("decorators", or([def("Decorator")], null), defaults["null"])
.field("definite", Boolean, defaults["false"])
.field("optional", Boolean, defaults["false"])
.field("override", Boolean, defaults["false"])
.field("readonly", Boolean, defaults["false"]);
});
var ObjectPatternProperty = or(
def("Property"),
def("PropertyPattern"),
def("SpreadPropertyPattern"),
def("SpreadProperty"), // Used by Esprima
def("ObjectProperty"), // Babel 6
def("RestProperty"), // Babel 6
def("RestElement"), // Babel 6
);
// Split into RestProperty and SpreadProperty
def("ObjectPattern")
.bases("Pattern")
.build("properties")
.field("properties", [ObjectPatternProperty])
.field("decorators",
or([def("Decorator")], null),
defaults["null"]);
def("SpreadProperty")
.bases("Node")
.build("argument")
.field("argument", def("Expression"));
def("RestProperty")
.bases("Node")
.build("argument")
.field("argument", def("Expression"));
def("ForAwaitStatement")
.bases("Statement")
.build("left", "right", "body")
.field("left", or(
def("VariableDeclaration"),
def("Expression")))
.field("right", def("Expression"))
.field("body", def("Statement"));
// The callee node of a dynamic import(...) expression.
def("Import")
.bases("Expression")
.build();
} | type Fork = {
use<T>(plugin: Plugin<T>): T;
}; |
1,198 | function (fork: Fork) {
fork.use(esProposalsDef);
const types = fork.use(typesPlugin);
const def = types.Type.def;
const or = types.Type.or;
const defaults = fork.use(sharedPlugin).defaults;
def("JSXAttribute")
.bases("Node")
.build("name", "value")
.field("name", or(def("JSXIdentifier"), def("JSXNamespacedName")))
.field("value", or(
def("Literal"), // attr="value"
def("JSXExpressionContainer"), // attr={value}
def("JSXElement"), // attr=<div />
def("JSXFragment"), // attr=<></>
null // attr= or just attr
), defaults["null"]);
def("JSXIdentifier")
.bases("Identifier")
.build("name")
.field("name", String);
def("JSXNamespacedName")
.bases("Node")
.build("namespace", "name")
.field("namespace", def("JSXIdentifier"))
.field("name", def("JSXIdentifier"));
def("JSXMemberExpression")
.bases("MemberExpression")
.build("object", "property")
.field("object", or(def("JSXIdentifier"), def("JSXMemberExpression")))
.field("property", def("JSXIdentifier"))
.field("computed", Boolean, defaults.false);
const JSXElementName = or(
def("JSXIdentifier"),
def("JSXNamespacedName"),
def("JSXMemberExpression")
);
def("JSXSpreadAttribute")
.bases("Node")
.build("argument")
.field("argument", def("Expression"));
const JSXAttributes = [or(
def("JSXAttribute"),
def("JSXSpreadAttribute")
)];
def("JSXExpressionContainer")
.bases("Expression")
.build("expression")
.field("expression", or(def("Expression"), def("JSXEmptyExpression")));
const JSXChildren = [or(
def("JSXText"),
def("JSXExpressionContainer"),
def("JSXSpreadChild"),
def("JSXElement"),
def("JSXFragment"),
def("Literal") // Legacy: Esprima should return JSXText instead.
)];
def("JSXElement")
.bases("Expression")
.build("openingElement", "closingElement", "children")
.field("openingElement", def("JSXOpeningElement"))
.field("closingElement", or(def("JSXClosingElement"), null), defaults["null"])
.field("children", JSXChildren, defaults.emptyArray)
.field("name", JSXElementName, function (this: N.JSXElement) {
// Little-known fact: the `this` object inside a default function
// is none other than the partially-built object itself, and any
// fields initialized directly from builder function arguments
// (like openingElement, closingElement, and children) are
// guaranteed to be available.
return this.openingElement.name;
}, true) // hidden from traversal
.field("selfClosing", Boolean, function (this: N.JSXElement) {
return this.openingElement.selfClosing;
}, true) // hidden from traversal
.field("attributes", JSXAttributes, function (this: N.JSXElement) {
return this.openingElement.attributes;
}, true); // hidden from traversal
def("JSXOpeningElement")
.bases("Node")
.build("name", "attributes", "selfClosing")
.field("name", JSXElementName)
.field("attributes", JSXAttributes, defaults.emptyArray)
.field("selfClosing", Boolean, defaults["false"]);
def("JSXClosingElement")
.bases("Node")
.build("name")
.field("name", JSXElementName);
def("JSXFragment")
.bases("Expression")
.build("openingFragment", "closingFragment", "children")
.field("openingFragment", def("JSXOpeningFragment"))
.field("closingFragment", def("JSXClosingFragment"))
.field("children", JSXChildren, defaults.emptyArray);
def("JSXOpeningFragment")
.bases("Node")
.build();
def("JSXClosingFragment")
.bases("Node")
.build();
def("JSXText")
.bases("Literal")
.build("value", "raw")
.field("value", String)
.field("raw", String, function (this: N.JSXText) {
return this.value;
});
def("JSXEmptyExpression")
.bases("Node")
.build();
def("JSXSpreadChild")
.bases("Node")
.build("expression")
.field("expression", def("Expression"));
} | type Fork = {
use<T>(plugin: Plugin<T>): T;
}; |
1,199 | function (fork: Fork) {
// Since TypeScript is parsed by Babylon, include the core Babylon types
// but omit the Flow-related types.
fork.use(babelCoreDef);
fork.use(typeAnnotationsDef);
var types = fork.use(typesPlugin);
var n = types.namedTypes;
var def = types.Type.def;
var or = types.Type.or;
var defaults = fork.use(sharedPlugin).defaults;
var StringLiteral = types.Type.from(function (value: any, deep?: any) {
if (n.StringLiteral &&
n.StringLiteral.check(value, deep)) {
return true
}
if (n.Literal &&
n.Literal.check(value, deep) &&
typeof value.value === "string") {
return true;
}
return false;
}, "StringLiteral");
def("TSType")
.bases("Node");
var TSEntityName = or(
def("Identifier"),
def("TSQualifiedName")
);
def("TSTypeReference")
.bases("TSType", "TSHasOptionalTypeParameterInstantiation")
.build("typeName", "typeParameters")
.field("typeName", TSEntityName);
// An abstract (non-buildable) base type that provide a commonly-needed
// optional .typeParameters field.
def("TSHasOptionalTypeParameterInstantiation")
.field("typeParameters",
or(def("TSTypeParameterInstantiation"), null),
defaults["null"]);
// An abstract (non-buildable) base type that provide a commonly-needed
// optional .typeParameters field.
def("TSHasOptionalTypeParameters")
.field("typeParameters",
or(def("TSTypeParameterDeclaration"), null, void 0),
defaults["null"]);
// An abstract (non-buildable) base type that provide a commonly-needed
// optional .typeAnnotation field.
def("TSHasOptionalTypeAnnotation")
.field("typeAnnotation",
or(def("TSTypeAnnotation"), null),
defaults["null"]);
def("TSQualifiedName")
.bases("Node")
.build("left", "right")
.field("left", TSEntityName)
.field("right", TSEntityName);
def("TSAsExpression")
.bases("Expression", "Pattern")
.build("expression", "typeAnnotation")
.field("expression", def("Expression"))
.field("typeAnnotation", def("TSType"))
.field("extra",
or({ parenthesized: Boolean }, null),
defaults["null"]);
def("TSTypeCastExpression")
.bases("Expression")
.build("expression", "typeAnnotation")
.field("expression", def("Expression"))
.field("typeAnnotation", def("TSType"));
def("TSSatisfiesExpression")
.bases("Expression", "Pattern")
.build("expression", "typeAnnotation")
.field("expression", def("Expression"))
.field("typeAnnotation", def("TSType"));
def("TSNonNullExpression")
.bases("Expression", "Pattern")
.build("expression")
.field("expression", def("Expression"));
[ // Define all the simple keyword types.
"TSAnyKeyword",
"TSBigIntKeyword",
"TSBooleanKeyword",
"TSNeverKeyword",
"TSNullKeyword",
"TSNumberKeyword",
"TSObjectKeyword",
"TSStringKeyword",
"TSSymbolKeyword",
"TSUndefinedKeyword",
"TSUnknownKeyword",
"TSVoidKeyword",
"TSIntrinsicKeyword",
"TSThisType",
].forEach(keywordType => {
def(keywordType)
.bases("TSType")
.build();
});
def("TSArrayType")
.bases("TSType")
.build("elementType")
.field("elementType", def("TSType"))
def("TSLiteralType")
.bases("TSType")
.build("literal")
.field("literal", or(
def("NumericLiteral"),
def("StringLiteral"),
def("BooleanLiteral"),
def("TemplateLiteral"),
def("UnaryExpression"),
def("BigIntLiteral"),
));
def("TemplateLiteral")
// The TemplateLiteral type appears to be reused for TypeScript template
// literal types (instead of introducing a new TSTemplateLiteralType type),
// so we allow the templateLiteral.expressions array to be either all
// expressions or all TypeScript types.
.field("expressions", or(
[def("Expression")],
[def("TSType")],
));
["TSUnionType",
"TSIntersectionType",
].forEach(typeName => {
def(typeName)
.bases("TSType")
.build("types")
.field("types", [def("TSType")]);
});
def("TSConditionalType")
.bases("TSType")
.build("checkType", "extendsType", "trueType", "falseType")
.field("checkType", def("TSType"))
.field("extendsType", def("TSType"))
.field("trueType", def("TSType"))
.field("falseType", def("TSType"));
def("TSInferType")
.bases("TSType")
.build("typeParameter")
.field("typeParameter", def("TSTypeParameter"));
def("TSParenthesizedType")
.bases("TSType")
.build("typeAnnotation")
.field("typeAnnotation", def("TSType"));
var ParametersType = [or(
def("Identifier"),
def("RestElement"),
def("ArrayPattern"),
def("ObjectPattern")
)];
["TSFunctionType",
"TSConstructorType",
].forEach(typeName => {
def(typeName)
.bases("TSType",
"TSHasOptionalTypeParameters",
"TSHasOptionalTypeAnnotation")
.build("parameters")
.field("parameters", ParametersType);
});
def("TSDeclareFunction")
.bases("Declaration", "TSHasOptionalTypeParameters")
.build("id", "params", "returnType")
.field("declare", Boolean, defaults["false"])
.field("async", Boolean, defaults["false"])
.field("generator", Boolean, defaults["false"])
.field("id", or(def("Identifier"), null), defaults["null"])
.field("params", [def("Pattern")])
// tSFunctionTypeAnnotationCommon
.field("returnType",
or(def("TSTypeAnnotation"),
def("Noop"), // Still used?
null),
defaults["null"]);
def("TSDeclareMethod")
.bases("Declaration", "TSHasOptionalTypeParameters")
.build("key", "params", "returnType")
.field("async", Boolean, defaults["false"])
.field("generator", Boolean, defaults["false"])
.field("params", [def("Pattern")])
// classMethodOrPropertyCommon
.field("abstract", Boolean, defaults["false"])
.field("accessibility",
or("public", "private", "protected", void 0),
defaults["undefined"])
.field("static", Boolean, defaults["false"])
.field("computed", Boolean, defaults["false"])
.field("optional", Boolean, defaults["false"])
.field("key", or(
def("Identifier"),
def("StringLiteral"),
def("NumericLiteral"),
// Only allowed if .computed is true.
def("Expression")
))
// classMethodOrDeclareMethodCommon
.field("kind",
or("get", "set", "method", "constructor"),
function getDefault() { return "method"; })
.field("access", // Not "accessibility"?
or("public", "private", "protected", void 0),
defaults["undefined"])
.field("decorators",
or([def("Decorator")], null),
defaults["null"])
// tSFunctionTypeAnnotationCommon
.field("returnType",
or(def("TSTypeAnnotation"),
def("Noop"), // Still used?
null),
defaults["null"]);
def("TSMappedType")
.bases("TSType")
.build("typeParameter", "typeAnnotation")
.field("readonly", or(Boolean, "+", "-"), defaults["false"])
.field("typeParameter", def("TSTypeParameter"))
.field("optional", or(Boolean, "+", "-"), defaults["false"])
.field("typeAnnotation",
or(def("TSType"), null),
defaults["null"]);
def("TSTupleType")
.bases("TSType")
.build("elementTypes")
.field("elementTypes", [or(
def("TSType"),
def("TSNamedTupleMember")
)]);
def("TSNamedTupleMember")
.bases("TSType")
.build("label", "elementType", "optional")
.field("label", def("Identifier"))
.field("optional", Boolean, defaults["false"])
.field("elementType", def("TSType"));
def("TSRestType")
.bases("TSType")
.build("typeAnnotation")
.field("typeAnnotation", def("TSType"));
def("TSOptionalType")
.bases("TSType")
.build("typeAnnotation")
.field("typeAnnotation", def("TSType"));
def("TSIndexedAccessType")
.bases("TSType")
.build("objectType", "indexType")
.field("objectType", def("TSType"))
.field("indexType", def("TSType"))
def("TSTypeOperator")
.bases("TSType")
.build("operator")
.field("operator", String)
.field("typeAnnotation", def("TSType"));
def("TSTypeAnnotation")
.bases("Node")
.build("typeAnnotation")
.field("typeAnnotation",
or(def("TSType"),
def("TSTypeAnnotation")));
def("TSIndexSignature")
.bases("Declaration", "TSHasOptionalTypeAnnotation")
.build("parameters", "typeAnnotation")
.field("parameters", [def("Identifier")]) // Length === 1
.field("readonly", Boolean, defaults["false"]);
def("TSPropertySignature")
.bases("Declaration", "TSHasOptionalTypeAnnotation")
.build("key", "typeAnnotation", "optional")
.field("key", def("Expression"))
.field("computed", Boolean, defaults["false"])
.field("readonly", Boolean, defaults["false"])
.field("optional", Boolean, defaults["false"])
.field("initializer",
or(def("Expression"), null),
defaults["null"]);
def("TSMethodSignature")
.bases("Declaration",
"TSHasOptionalTypeParameters",
"TSHasOptionalTypeAnnotation")
.build("key", "parameters", "typeAnnotation")
.field("key", def("Expression"))
.field("computed", Boolean, defaults["false"])
.field("optional", Boolean, defaults["false"])
.field("parameters", ParametersType);
def("TSTypePredicate")
.bases("TSTypeAnnotation", "TSType")
.build("parameterName", "typeAnnotation", "asserts")
.field("parameterName",
or(def("Identifier"),
def("TSThisType")))
.field("typeAnnotation", or(def("TSTypeAnnotation"), null),
defaults["null"])
.field("asserts", Boolean, defaults["false"]);
["TSCallSignatureDeclaration",
"TSConstructSignatureDeclaration",
].forEach(typeName => {
def(typeName)
.bases("Declaration",
"TSHasOptionalTypeParameters",
"TSHasOptionalTypeAnnotation")
.build("parameters", "typeAnnotation")
.field("parameters", ParametersType);
});
def("TSEnumMember")
.bases("Node")
.build("id", "initializer")
.field("id", or(def("Identifier"), StringLiteral))
.field("initializer",
or(def("Expression"), null),
defaults["null"]);
def("TSTypeQuery")
.bases("TSType")
.build("exprName")
.field("exprName", or(TSEntityName, def("TSImportType")));
// Inferred from Babylon's tsParseTypeMember method.
var TSTypeMember = or(
def("TSCallSignatureDeclaration"),
def("TSConstructSignatureDeclaration"),
def("TSIndexSignature"),
def("TSMethodSignature"),
def("TSPropertySignature")
);
def("TSTypeLiteral")
.bases("TSType")
.build("members")
.field("members", [TSTypeMember]);
def("TSTypeParameter")
.bases("Identifier")
.build("name", "constraint", "default")
.field("name", or(def("Identifier"), String))
.field("constraint", or(def("TSType"), void 0), defaults["undefined"])
.field("default", or(def("TSType"), void 0), defaults["undefined"]);
def("TSTypeAssertion")
.bases("Expression", "Pattern")
.build("typeAnnotation", "expression")
.field("typeAnnotation", def("TSType"))
.field("expression", def("Expression"))
.field("extra",
or({ parenthesized: Boolean }, null),
defaults["null"]);
def("TSTypeParameterDeclaration")
.bases("Declaration")
.build("params")
.field("params", [def("TSTypeParameter")]);
def("TSInstantiationExpression")
.bases("Expression", "TSHasOptionalTypeParameterInstantiation")
.build("expression", "typeParameters")
.field("expression", def("Expression"));
def("TSTypeParameterInstantiation")
.bases("Node")
.build("params")
.field("params", [def("TSType")]);
def("TSEnumDeclaration")
.bases("Declaration")
.build("id", "members")
.field("id", def("Identifier"))
.field("const", Boolean, defaults["false"])
.field("declare", Boolean, defaults["false"])
.field("members", [def("TSEnumMember")])
.field("initializer",
or(def("Expression"), null),
defaults["null"]);
def("TSTypeAliasDeclaration")
.bases("Declaration", "TSHasOptionalTypeParameters")
.build("id", "typeAnnotation")
.field("id", def("Identifier"))
.field("declare", Boolean, defaults["false"])
.field("typeAnnotation", def("TSType"));
def("TSModuleBlock")
.bases("Node")
.build("body")
.field("body", [def("Statement")]);
def("TSModuleDeclaration")
.bases("Declaration")
.build("id", "body")
.field("id", or(StringLiteral, TSEntityName))
.field("declare", Boolean, defaults["false"])
.field("global", Boolean, defaults["false"])
.field("body",
or(def("TSModuleBlock"),
def("TSModuleDeclaration"),
null),
defaults["null"]);
def("TSImportType")
.bases("TSType", "TSHasOptionalTypeParameterInstantiation")
.build("argument", "qualifier", "typeParameters")
.field("argument", StringLiteral)
.field("qualifier", or(TSEntityName, void 0), defaults["undefined"]);
def("TSImportEqualsDeclaration")
.bases("Declaration")
.build("id", "moduleReference")
.field("id", def("Identifier"))
.field("isExport", Boolean, defaults["false"])
.field("moduleReference",
or(TSEntityName,
def("TSExternalModuleReference")));
def("TSExternalModuleReference")
.bases("Declaration")
.build("expression")
.field("expression", StringLiteral);
def("TSExportAssignment")
.bases("Statement")
.build("expression")
.field("expression", def("Expression"));
def("TSNamespaceExportDeclaration")
.bases("Declaration")
.build("id")
.field("id", def("Identifier"));
def("TSInterfaceBody")
.bases("Node")
.build("body")
.field("body", [TSTypeMember]);
def("TSExpressionWithTypeArguments")
.bases("TSType", "TSHasOptionalTypeParameterInstantiation")
.build("expression", "typeParameters")
.field("expression", TSEntityName);
def("TSInterfaceDeclaration")
.bases("Declaration", "TSHasOptionalTypeParameters")
.build("id", "body")
.field("id", TSEntityName)
.field("declare", Boolean, defaults["false"])
.field("extends",
or([def("TSExpressionWithTypeArguments")], null),
defaults["null"])
.field("body", def("TSInterfaceBody"));
def("TSParameterProperty")
.bases("Pattern")
.build("parameter")
.field("accessibility",
or("public", "private", "protected", void 0),
defaults["undefined"])
.field("readonly", Boolean, defaults["false"])
.field("parameter", or(def("Identifier"),
def("AssignmentPattern")));
def("ClassProperty")
.field("access", // Not "accessibility"?
or("public", "private", "protected", void 0),
defaults["undefined"]);
def("ClassAccessorProperty")
.bases("Declaration", "TSHasOptionalTypeAnnotation");
// Defined already in es6 and babel-core.
def("ClassBody")
.field("body", [or(
def("MethodDefinition"),
def("VariableDeclarator"),
def("ClassPropertyDefinition"),
def("ClassProperty"),
def("ClassPrivateProperty"),
def("ClassAccessorProperty"),
def("ClassMethod"),
def("ClassPrivateMethod"),
def("StaticBlock"),
// Just need to add these types:
def("TSDeclareMethod"),
TSTypeMember
)]);
} | type Fork = {
use<T>(plugin: Plugin<T>): T;
}; |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.