Skip to content

Commit 71d32ed

Browse files
committed
Version 2 rewrite
This is a redesign of the old library that splits the code internally into three parts: - The grammar. This uses Peggy now instead of PEG.js, but is pretty much unchanged. - The AST types. These are plain objects with `type` properties. The compiled parser outputs data matching these types. - The expander. This does the work that was previously combined into the expression classes. The external API is compatible with version 1, but it's possible that people were relying on internal details of library (e.g. instanceof checks) so I'm bumping the major to version 2. Because this version also returns the AST for the parsed expressions, it should be much more suitable for constructing a separate "matcher" that can extract variable values from a URL string.
1 parent 3ff7efb commit 71d32ed

File tree

8 files changed

+284
-339
lines changed

8 files changed

+284
-339
lines changed

Makefile

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
.PHONY: check publish clean
22

3-
all: lib/grammar.js dist/index.js dist/classes.js
3+
all: lib/grammar.js dist/index.js
44

55
dist/%.js: lib/%.ts
66
@npx tsc

lib/ast.ts

+59
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
import { abort } from "process";
2+
3+
export interface Template {
4+
type: "template";
5+
parts: (Literal | Expression)[];
6+
}
7+
8+
export interface Literal {
9+
type: "literal";
10+
value: string;
11+
}
12+
13+
export interface Expression {
14+
type: "expression";
15+
operator: Operator;
16+
variables: Variable[];
17+
}
18+
19+
export type Operator = "/" | ";" | "." | "?" | "&" | "+" | "#" | "";
20+
21+
export interface Variable {
22+
type: "variable";
23+
name: string;
24+
modifier?: SubstrModifier | ExplodeModifier;
25+
extension?: string;
26+
}
27+
28+
export interface ExplodeModifier {
29+
type: "explode";
30+
}
31+
32+
export interface SubstrModifier {
33+
type: "substr";
34+
length: number;
35+
}
36+
37+
export function toString(
38+
node: Template | Literal | Expression | Variable
39+
): string {
40+
switch (node.type) {
41+
case "template":
42+
return node.parts.map(toString).join("");
43+
case "literal":
44+
return node.value;
45+
case "expression":
46+
return `{${node.operator}${node.variables.map(toString).join(",")}}`;
47+
case "variable":
48+
let out = node.name;
49+
if (node.modifier?.type == "explode") {
50+
out += "*";
51+
} else if (node.modifier?.type == "substr") {
52+
out += `:${node.modifier.length}`;
53+
}
54+
if (node.extension) {
55+
out += `(${node.extension})`;
56+
}
57+
return out;
58+
}
59+
}

lib/classes.ts

-282
This file was deleted.

0 commit comments

Comments
 (0)