Skip to content

Commit

Permalink
fix: prevent hanging when the first character is invalid (#31)
Browse files Browse the repository at this point in the history
  • Loading branch information
Leokuma committed Nov 2, 2023
1 parent 6cade31 commit 6b255f2
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 4 deletions.
15 changes: 15 additions & 0 deletions parse_test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -494,6 +494,21 @@ Deno.test("parse: xml syntax attributes properly quoted", () =>
`)
))

Deno.test("parse: xml syntax first character", () => {
assertThrows(() =>
parse(`a>1</a>`)
)
assertThrows(() =>
parse(`xml`)
)
assertThrows(() =>
parse(`""`)
)
assertThrows(() =>
parse(`{a: 1}`)
)
})

//Example below were taken from https://www.w3schools.com/xml/default.asp

Deno.test("parse: xml example w3schools.com#1", () =>
Expand Down
12 changes: 8 additions & 4 deletions utils/parser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,21 +57,21 @@ export class Parser {
}

//Extract prolog, stylesheets and doctype
if ((this.#peek(tokens.prolog.start)) && (!this.#peek(tokens.stylesheet.start))) {
else if ((this.#peek(tokens.prolog.start)) && (!this.#peek(tokens.stylesheet.start))) {
if (document.xml) {
throw Object.assign(new SyntaxError("Multiple prolog declaration found"), { stack: false })
}
clean = false
Object.assign(document, this.#prolog({ path }))
continue
}
if (this.#peek(tokens.stylesheet.start)) {
else if (this.#peek(tokens.stylesheet.start)) {
clean = false
const stylesheets = (document[schema.stylesheets] ??= []) as unknown[]
stylesheets.push(this.#stylesheet({ path }).stylesheet)
continue
}
if (this.#peek(tokens.doctype.start)) {
else if (this.#peek(tokens.doctype.start)) {
if (document.doctype) {
throw Object.assign(new SyntaxError("Multiple doctype declaration found"), { stack: false })
}
Expand All @@ -81,7 +81,7 @@ export class Parser {
}

//Extract root node
if (this.#peek(tokens.tag.start)) {
else if (this.#peek(tokens.tag.start)) {
if (root) {
throw Object.assign(new SyntaxError("Multiple root elements found"), { stack: false })
}
Expand All @@ -91,6 +91,10 @@ export class Parser {
root = true
continue
}

else {
throw Object.assign(new SyntaxError("Invalid XML structure"), { stack: false })
}
}
} catch (error) {
if ((error instanceof Deno.errors.UnexpectedEof) && (clean)) {
Expand Down

0 comments on commit 6b255f2

Please sign in to comment.