@aljazmc/syntax 0.6.1 → 0.6.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,68 +1,46 @@
1
1
  # > syntax
2
2
 
3
3
  Shared, dependency-free scanner and recursive descent parser for CSS,
4
- HTML, JavaScript, JSON, JSX, Markdown and TypeScript, bundled into `@aljazmc/formatero` and `@aljazmc/lintero`, and published for their
5
- types.
4
+ HTML, JavaScript, JSON, JSX, Markdown and TypeScript, bundled into
5
+ `@aljazmc/formatero` and `@aljazmc/lintero` and published for their
6
+ types. Invalid sources throw a `ParseError` with the position of the
7
+ problem.
8
+
9
+ ## > Features
10
+
11
+ | Language | Entry points | Tree |
12
+ | --------------------------- | ----------------------------- | ---------------------------------------------------------------------------------- |
13
+ | CSS | `isCss`, `parseCss` | Rules, at-rules, declarations, values and selectors, with comments. |
14
+ | HTML | `isHtml`, `parseHtml` | Elements, attributes and text, comments and whitespace as trivia. |
15
+ | JavaScript, JSX, TypeScript | `language`, `parse` | ESTree, with Babel-style literals and TypeScript nodes. |
16
+ | JSON | `language`, `parse` | ESTree expressions. |
17
+ | Markdown | `isMarkdown`, `parseMarkdown` | CommonMark blocks and inlines, with GitHub's tables, task lists and strikethrough. |
18
+
19
+ | Helper | Description |
20
+ | -------------------------------- | ----------------------------------------------------------- |
21
+ | `Lines` | Turns offsets into 1-based lines and columns, for messages. |
22
+ | `parseCss(…, { recover: true })` | Skips items with errors and lists them in `errors`. |
23
+ | `ParseError` | Thrown for invalid sources, with the position. |
24
+ | `tagOf` | The known tag of an element name, like `div` for `DIV`. |
25
+ | `Walker` | Lists the child nodes of a node in source order. |
26
+
27
+ ## > Usage
6
28
 
7
29
  ```ts
8
- import { language, parse } from "@aljazmc/syntax";
9
-
10
- const options = language("a.tsx"); // { json: false, typescript: true, jsx: true }
11
- const { program, comments } = parse("let a = <b />;", options);
12
- ```
13
-
14
- Syntax trees follow ESTree, with Babel-style literals and TypeScript nodes.
15
- Invalid sources throw `ParseError` with the position of the problem.
16
-
17
- `Walker.children(node)` lists the child nodes of a node in source order, and
18
- `Lines` turns offsets into 1-based lines and columns, for messages.
19
-
20
- Markdown is parsed like CommonMark, with GitHub's tables, task list items
21
- and strikethrough:
22
-
23
- ```ts
24
- import { isMarkdown, parseMarkdown } from "@aljazmc/syntax";
25
-
26
- isMarkdown("README.md"); // true
27
- const root = parseMarkdown("# Title\n\n- [x] done\n");
28
- // root.children: a Heading and a List, with their offsets and lines
30
+ import {
31
+ language,
32
+ parse,
33
+ parseCss,
34
+ parseHtml,
35
+ parseMarkdown,
36
+ } from "@aljazmc/syntax";
37
+
38
+ const { program, comments } = parse("let a = <b />;", language("a.tsx"));
39
+ const sheet = parseCss("a > .b:hover { color: red; }\n");
40
+ const page = parseHtml('<p class="a">Hi <b>there</b></p>\n');
41
+ const doc = parseMarkdown("# Title\n\n- [x] done\n");
29
42
  ```
30
43
 
31
- Blocks have offsets into the source and 1-based lines, and keep what a
32
- formatter needs to print them as written, like the indentation of each
33
- line. Inlines have offsets into the text of their block.
34
-
35
- HTML is parsed like Biome parses it: elements must be closed, only void
36
- elements may have no closing tag, and whitespace and comments are trivia
37
- between nodes, not children:
38
-
39
- ```ts
40
- import { isHtml, parseHtml } from "@aljazmc/syntax";
41
-
42
- isHtml("index.html"); // true
43
- const root = parseHtml('<p class="a">Hi <b>there</b></p>\n');
44
- // root.children: an Element p, with its attributes, a Text and an Element b
45
- // root.comments: every <!-- --> comment
46
- ```
47
-
48
- Element names keep their case, and `tag` is the known tag they match, like
49
- `div` for `DIV` and `feBlend` for `feBlend`. Scripts, styles and
50
- preformatted elements keep their content as one raw text.
51
-
52
- CSS is parsed into rules, at-rules, declarations and their component
53
- values, and the selectors of rules into compound selectors, combinators
54
- and simple selectors, like Biome reads them:
55
-
56
- ```ts
57
- import { isCss, parseCss } from "@aljazmc/syntax";
58
-
59
- isCss("styles.css"); // true
60
- const sheet = parseCss("a > .b:hover { color: red !important; }\n");
61
- // sheet.children: a Rule, its selectors and a block with a Declaration
62
- // sheet.comments: every /* */ comment
63
- ```
44
+ ## > License
64
45
 
65
- Nested rules, `@media` queries and other at-rule preludes keep their
66
- values, keyframes keep theirs instead of selectors. Errors throw a
67
- `ParseError`, or with `parseCss(source, { recover: true })` the items
68
- with errors are skipped and listed in `sheet.errors`.
46
+ MIT, see [LICENSE](LICENSE).
package/bin/index.js CHANGED
@@ -594,6 +594,8 @@ var NTH_PSEUDOS = /* @__PURE__ */ new Set([
594
594
  "nth-col",
595
595
  "nth-last-col"
596
596
  ]);
597
+ var BLOCK_AT_RULES = /^(?:-[a-z]+-)?(?:media|supports|font-face|keyframes|page|container|document|property|scope|starting-style|counter-style|font-feature-values|view-transition|position-try|font-palette-values)$/;
598
+ var STATEMENT_AT_RULES = /^(?:import|namespace|charset)$/;
597
599
  var KEYFRAMES = /^(?:-[a-z]+-)?keyframes$/;
598
600
  var Parser = class _Parser {
599
601
  static {
@@ -653,6 +655,10 @@ var Parser = class _Parser {
653
655
  } else if (depth === 0 && type === "semicolon") return;
654
656
  }
655
657
  }
658
+ /** Where the parser is, the start of its current token. */
659
+ get position() {
660
+ return this.#peek().start;
661
+ }
656
662
  parse() {
657
663
  const children = [];
658
664
  for (; ; ) {
@@ -887,13 +893,22 @@ var Parser = class _Parser {
887
893
  let semicolon = false;
888
894
  let end = preludeEnd;
889
895
  const token = this.#peek();
896
+ if (keyword === "charset") this.#charset(prelude, token);
897
+ const needs = BLOCK_AT_RULES.test(keyword) ? "{" : STATEMENT_AT_RULES.test(keyword) ? ";" : void 0;
898
+ const found = token.type === "eof" ? "the file ends" : `found \`${token.type === "semicolon" ? ";" : token.type}\``;
890
899
  if (token.type === "{") {
900
+ if (needs === ";")
901
+ this.#error(`expected \`;\` but instead ${found}`, token.start);
891
902
  block = this.#block(KEYFRAMES.test(keyword));
892
903
  end = block.end;
893
- } else if (token.type === "semicolon") {
904
+ } else if (token.type === "semicolon" && needs !== "{") {
894
905
  end = this.#next().end;
895
906
  semicolon = true;
896
- }
907
+ } else
908
+ this.#error(
909
+ `expected \`${needs ?? ";"}\` but instead ${found}`,
910
+ token.start
911
+ );
897
912
  return {
898
913
  type: "AtRule",
899
914
  start: at.start,
@@ -907,6 +922,16 @@ var Parser = class _Parser {
907
922
  semicolon
908
923
  };
909
924
  }
925
+ /** Like Biome, `@charset` takes one string. */
926
+ #charset(prelude, next) {
927
+ const [first] = prelude;
928
+ if (prelude.length === 1 && first?.type === "String") return;
929
+ const found = first ? `'${this.#source.slice(first.start, prelude.at(-1).end)}'` : next.type === "eof" ? "the end of the file" : `'${next.type === "semicolon" ? ";" : next.type}'`;
930
+ this.#error(
931
+ `Expected a string but instead found ${found}.`,
932
+ first?.start ?? next.start
933
+ );
934
+ }
910
935
  /** A component value, with nested values of functions and blocks. */
911
936
  #value() {
912
937
  const token = this.#next();
@@ -1801,6 +1826,10 @@ var Parser2 = class {
1801
1826
  constructor(source) {
1802
1827
  this.#source = source;
1803
1828
  }
1829
+ /** Where the parser is. */
1830
+ get position() {
1831
+ return this.#position;
1832
+ }
1804
1833
  parse() {
1805
1834
  const source = this.#source;
1806
1835
  const bom = source.startsWith("\uFEFF");
@@ -2822,6 +2851,10 @@ var Blocks = class _Blocks {
2822
2851
  if (start < source.length)
2823
2852
  this.#lines.push({ text: source.slice(start), start });
2824
2853
  }
2854
+ /** Where the parser is, the start of its current line. */
2855
+ get position() {
2856
+ return this.#lineStart;
2857
+ }
2825
2858
  parse(frontmatter = false) {
2826
2859
  const bom = this.#source.startsWith("\uFEFF");
2827
2860
  let first = 0;
@@ -3642,6 +3675,41 @@ var Blocks = class _Blocks {
3642
3675
  }
3643
3676
  };
3644
3677
 
3678
+ // shared/syntax/src/lines.ts
3679
+ var Lines = class {
3680
+ static {
3681
+ __name(this, "Lines");
3682
+ }
3683
+ #starts = [0];
3684
+ #text;
3685
+ constructor(text) {
3686
+ this.#text = text;
3687
+ for (const match of text.matchAll(/\r\n|\r|\n/g))
3688
+ this.#starts.push(match.index + match[0].length);
3689
+ }
3690
+ line(offset) {
3691
+ let low = 0;
3692
+ let high = this.#starts.length - 1;
3693
+ while (low < high) {
3694
+ const middle = Math.ceil((low + high) / 2);
3695
+ if (this.#starts[middle] <= offset) low = middle;
3696
+ else high = middle - 1;
3697
+ }
3698
+ return low + 1;
3699
+ }
3700
+ column(offset) {
3701
+ const start = this.#starts[this.line(offset) - 1];
3702
+ let column = 1;
3703
+ for (let index = start; index < offset; index++) {
3704
+ const code = this.#text.charCodeAt(index);
3705
+ if (code >= 55296 && code <= 56319 && index + 1 < offset && (this.#text.charCodeAt(index + 1) & 64512) === 56320)
3706
+ index++;
3707
+ column++;
3708
+ }
3709
+ return column;
3710
+ }
3711
+ };
3712
+
3645
3713
  // shared/syntax/src/parser/base.ts
3646
3714
  var BaseParser = class {
3647
3715
  static {
@@ -3651,6 +3719,10 @@ var BaseParser = class {
3651
3719
  scanner;
3652
3720
  options;
3653
3721
  token;
3722
+ /** Where the parser is, the start of its current token. */
3723
+ get position() {
3724
+ return this.token.start;
3725
+ }
3654
3726
  /** End of the last consumed token. */
3655
3727
  previous = 0;
3656
3728
  /** Whether `in` is a binary operator here (not in a for-in head). */
@@ -3747,10 +3819,11 @@ var BaseParser = class {
3747
3819
  );
3748
3820
  }
3749
3821
  raise(message, position) {
3750
- const before = this.source.slice(0, position);
3751
- const line = before.split("\n").length;
3752
- const column = position - before.lastIndexOf("\n");
3753
- throw new ParseError(`${message} (${line}:${column})`, position);
3822
+ const lines = new Lines(this.source);
3823
+ throw new ParseError(
3824
+ `${message} (${lines.line(position)}:${lines.column(position)})`,
3825
+ position
3826
+ );
3754
3827
  }
3755
3828
  };
3756
3829
 
@@ -6372,11 +6445,12 @@ var Parser3 = class extends ExpressionParser {
6372
6445
  });
6373
6446
  }
6374
6447
  #module(start, declare) {
6375
- const keyword = this.next().value;
6448
+ const token = this.next();
6449
+ const keyword = token.value;
6376
6450
  const kind = keyword === "global" ? "global" : keyword === "module" ? "module" : "namespace";
6377
6451
  let id;
6378
6452
  if (kind === "global")
6379
- id = this.finish("Identifier", start, { name: "global" });
6453
+ id = this.finish("Identifier", token.start, { name: "global" });
6380
6454
  else if (this.token.type === "string") id = this.parseString();
6381
6455
  else id = this.parseEntityName();
6382
6456
  if (!this.is("{")) {
@@ -6401,31 +6475,6 @@ var Parser3 = class extends ExpressionParser {
6401
6475
  }
6402
6476
  };
6403
6477
 
6404
- // shared/syntax/src/lines.ts
6405
- var Lines = class {
6406
- static {
6407
- __name(this, "Lines");
6408
- }
6409
- #starts = [0];
6410
- constructor(text) {
6411
- for (const match of text.matchAll(/\r\n|\r|\n/g))
6412
- this.#starts.push(match.index + match[0].length);
6413
- }
6414
- line(offset) {
6415
- let low = 0;
6416
- let high = this.#starts.length - 1;
6417
- while (low < high) {
6418
- const middle = Math.ceil((low + high) / 2);
6419
- if (this.#starts[middle] <= offset) low = middle;
6420
- else high = middle - 1;
6421
- }
6422
- return low + 1;
6423
- }
6424
- column(offset) {
6425
- return offset - this.#starts[this.line(offset) - 1] + 1;
6426
- }
6427
- };
6428
-
6429
6478
  // shared/syntax/src/walker.ts
6430
6479
  var Walker = class _Walker {
6431
6480
  static {
@@ -6451,6 +6500,19 @@ var Walker = class _Walker {
6451
6500
  };
6452
6501
 
6453
6502
  // shared/syntax/src/index.ts
6503
+ function shallow(run, parser) {
6504
+ try {
6505
+ return run();
6506
+ } catch (error) {
6507
+ if (error instanceof RangeError && /call stack/i.test(error.message))
6508
+ throw new ParseError(
6509
+ "The nesting is too deep to parse.",
6510
+ parser.position
6511
+ );
6512
+ throw error;
6513
+ }
6514
+ }
6515
+ __name(shallow, "shallow");
6454
6516
  function language(file) {
6455
6517
  if (/\.jsonc?$/.test(file))
6456
6518
  return { json: true, typescript: false, jsx: false };
@@ -6475,35 +6537,40 @@ function isCss(file) {
6475
6537
  }
6476
6538
  __name(isCss, "isCss");
6477
6539
  function parseCss(source, options = {}) {
6478
- return new Parser(
6540
+ const parser = new Parser(
6479
6541
  source,
6480
6542
  void 0,
6481
6543
  void 0,
6482
6544
  options.recover ?? false
6483
- ).parse();
6545
+ );
6546
+ return shallow(() => parser.parse(), parser);
6484
6547
  }
6485
6548
  __name(parseCss, "parseCss");
6486
6549
  function parseCssValues(source, start = 0, end = source.length) {
6487
- return Parser.values(source, start, end);
6550
+ return shallow(() => Parser.values(source, start, end), {
6551
+ position: start
6552
+ });
6488
6553
  }
6489
6554
  __name(parseCssValues, "parseCssValues");
6490
6555
  function parseHtml(source) {
6491
- return new Parser2(source).parse();
6556
+ const parser = new Parser2(source);
6557
+ return shallow(() => parser.parse(), parser);
6492
6558
  }
6493
6559
  __name(parseHtml, "parseHtml");
6494
6560
  function parseMarkdown(source, options = {}) {
6495
- return new Blocks(source, options).parse(options.frontmatter);
6561
+ const parser = new Blocks(source, options);
6562
+ return shallow(() => parser.parse(options.frontmatter), parser);
6496
6563
  }
6497
6564
  __name(parseMarkdown, "parseMarkdown");
6498
6565
  function parse(source, options) {
6499
6566
  const parser = new Parser3(source, options);
6500
- const program = parser.parseProgram();
6567
+ const program = shallow(() => parser.parseProgram(), parser);
6501
6568
  return { program, comments: parser.comments };
6502
6569
  }
6503
6570
  __name(parse, "parse");
6504
6571
  function parseExpression(source) {
6505
6572
  const parser = new Parser3(source, { typescript: false, jsx: false });
6506
- const expression = parser.parseDocument();
6573
+ const expression = shallow(() => parser.parseDocument(), parser);
6507
6574
  const statement = {
6508
6575
  type: "ExpressionStatement",
6509
6576
  start: expression.start,
@@ -4,6 +4,8 @@ export default class Parser {
4
4
  #private;
5
5
  /** Parses a stylesheet, or only values from `start` to `end`, recovering from errors when asked. */
6
6
  constructor(source: string, start?: number, end?: number, recover?: boolean);
7
+ /** Where the parser is, the start of its current token. */
8
+ get position(): number;
7
9
  parse(): Stylesheet;
8
10
  /** Values of a range of the source, like the argument of a pseudo class. */
9
11
  static values(source: string, start: number, end: number): Value[];
@@ -51,8 +51,8 @@ export interface AttributeValue extends Base<"AttributeValue"> {
51
51
  quote: '"' | "'" | "";
52
52
  }
53
53
  /**
54
- * A run of text, without the whitespace around it, which is trivia like in
55
- * Biome. A blank line ends a text, the next one starts after it.
54
+ * A run of text, without the whitespace around it, which is trivia. A
55
+ * blank line ends a text, the next one starts after it.
56
56
  */
57
57
  export interface Text extends Base<"Text"> {
58
58
  /** The text as written, character references are not decoded. */
@@ -2,11 +2,13 @@ import type { Root } from "./ast.js";
2
2
  /** The known tag a name matches, exactly like SVG's `feBlend`, or lower-cased like HTML's `DIV`. */
3
3
  export declare function tagOf(name: string): string | null;
4
4
  /**
5
- * Parses HTML like Biome: elements are closed explicitly, only void ones may
5
+ * Parses HTML: elements are closed explicitly, only void ones may
6
6
  * have no closing tag, and whitespace and comments are trivia between nodes.
7
7
  */
8
8
  export default class Parser {
9
9
  #private;
10
10
  constructor(source: string);
11
+ /** Where the parser is. */
12
+ get position(): number;
11
13
  parse(): Root;
12
14
  }
@@ -1,2 +1,2 @@
1
- /** Tag names Biome 2.6.6 knows, SVG ones in camel case like `feBlend`. */
1
+ /** Known tag names, SVG ones in camel case like `feBlend`. */
2
2
  export declare const tagNames: ReadonlySet<string>;
@@ -4,7 +4,7 @@ import type { Root as HtmlRoot } from "./html/ast.js";
4
4
  import type { Root } from "./markdown/ast.js";
5
5
  import { type MarkdownOptions } from "./markdown/blocks.js";
6
6
  import type { Options } from "./parser/base.js";
7
- import type { Comment } from "./scanner.js";
7
+ import { type Comment } from "./scanner.js";
8
8
  export type * from "./ast.js";
9
9
  export type * as Css from "./css/ast.js";
10
10
  export type * as Html from "./html/ast.js";
@@ -43,7 +43,7 @@ export declare function parseCss(source: string, options?: {
43
43
  }): Stylesheet;
44
44
  /** Parses the component values of a range of CSS, like a `style` attribute value. */
45
45
  export declare function parseCssValues(source: string, start?: number, end?: number): import("./css/ast.js").Value[];
46
- /** Parses HTML like Biome, throwing a ParseError at the first error. */
46
+ /** Parses HTML, throwing a ParseError at the first error. */
47
47
  export declare function parseHtml(source: string): HtmlRoot;
48
48
  /** Parses CommonMark, with GitHub's tables, task lists and strikethrough unless `gfm` is false. */
49
49
  export declare function parseMarkdown(source: string, options?: MarkdownOptions): Root;
@@ -1,4 +1,8 @@
1
- /** Converts offsets to 1-based lines and columns. */
1
+ /**
2
+ * Converts offsets to 1-based lines and columns. Like Biome, columns count
3
+ * characters, so a character outside the BMP, like an emoji, is one column,
4
+ * not the two UTF-16 code units it takes.
5
+ */
2
6
  export default class Lines {
3
7
  #private;
4
8
  constructor(text: string);
@@ -9,6 +9,8 @@ export interface MarkdownOptions {
9
9
  export default class Blocks {
10
10
  #private;
11
11
  constructor(source: string, options?: MarkdownOptions);
12
+ /** Where the parser is, the start of its current line. */
13
+ get position(): number;
12
14
  parse(frontmatter?: boolean): Root;
13
15
  /** Splits a table row into its cells, on pipes that are not escaped. */
14
16
  static cells(row: string): string[];
@@ -15,6 +15,8 @@ export default abstract class BaseParser {
15
15
  protected readonly scanner: Scanner;
16
16
  protected readonly options: Options;
17
17
  protected token: Token;
18
+ /** Where the parser is, the start of its current token. */
19
+ get position(): number;
18
20
  /** End of the last consumed token. */
19
21
  protected previous: number;
20
22
  /** Whether `in` is a binary operator here (not in a for-in head). */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aljazmc/syntax",
3
- "version": "0.6.1",
3
+ "version": "0.6.2",
4
4
  "description": "Shared, dependency-free JavaScript, TypeScript, JSX, JSON, Markdown, HTML and CSS parser for @aljazmc packages.",
5
5
  "author": "aljazmc",
6
6
  "license": "MIT",
@@ -31,7 +31,6 @@
31
31
  }
32
32
  },
33
33
  "devDependencies": {
34
- "@jest/globals": "^30.5.2",
35
34
  "@types/node": "^26.6.6"
36
35
  }
37
36
  }