• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1import * as assert from 'node:assert';
2import { SAXParser } from '../lib/index.js';
3import { loadSAXParserTestData } from 'parse5-test-utils/utils/load-sax-parser-test-data.js';
4import { writeChunkedToStream } from 'parse5-test-utils/utils/common.js';
5import type { Token } from 'parse5';
6
7function assertLocation({ sourceCodeLocation }: { sourceCodeLocation: Token.Location }): void {
8    assert.strictEqual(typeof sourceCodeLocation.startLine, 'number');
9    assert.strictEqual(typeof sourceCodeLocation.startCol, 'number');
10    assert.strictEqual(typeof sourceCodeLocation.startOffset, 'number');
11    assert.strictEqual(typeof sourceCodeLocation.endOffset, 'number');
12    assert.ok(sourceCodeLocation.startOffset < sourceCodeLocation.endOffset);
13}
14
15describe('location-info', () => {
16    it('Location info (SAX)', () => {
17        for (const test of loadSAXParserTestData()) {
18            //NOTE: we've already tested the correctness of the location info with the Tokenizer tests.
19            //So here we just check that SAXParser provides this info in the handlers.
20            const parser = new SAXParser({ sourceCodeLocationInfo: true });
21
22            parser.on('startTag', assertLocation);
23            parser.on('endTag', assertLocation);
24            parser.on('doctype', assertLocation);
25            parser.on('comment', assertLocation);
26            parser.on('text', assertLocation);
27
28            writeChunkedToStream(test.src, parser);
29        }
30    });
31
32    it('Regression - location info for text (GH-153, GH-266)', () => {
33        const html = '<!DOCTYPE html><html><head><title>Here is a title</title></html>';
34        const parser = new SAXParser({ sourceCodeLocationInfo: true });
35
36        parser.on('text', ({ sourceCodeLocation }) => {
37            assert.deepStrictEqual(sourceCodeLocation, {
38                startLine: 1,
39                startCol: 35,
40                startOffset: 34,
41                endLine: 1,
42                endCol: 50,
43                endOffset: 49,
44            });
45        });
46
47        parser.end(html);
48    });
49});
50