@monimesl/dot-dml-parser 0.1.0-alpha.19 → 0.1.0-alpha.21
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/dist/index.js +16 -13
- package/dist/index.js.map +1 -1
- package/package.json +2 -2
package/dist/index.js
CHANGED
|
@@ -6,7 +6,7 @@ var DmlParseError = class extends SourceError {
|
|
|
6
6
|
};
|
|
7
7
|
//#endregion
|
|
8
8
|
//#region src/parse.ts
|
|
9
|
-
const
|
|
9
|
+
const CLOSING_TAG = /<\/([^\s>]+)\s*>/g;
|
|
10
10
|
const OPAQUE_REGION = /<!--[\s\S]*?-->|<!\[CDATA\[[\s\S]*?]]>/g;
|
|
11
11
|
/** Parses .dml markup into an IR tree, leaving `{{ }}` bindings as raw strings. */
|
|
12
12
|
function parseDmlToIR(dmlString, options = {}) {
|
|
@@ -15,7 +15,7 @@ function parseDmlToIR(dmlString, options = {}) {
|
|
|
15
15
|
const stack = [];
|
|
16
16
|
let textBuffer = "";
|
|
17
17
|
let textStart = -1;
|
|
18
|
-
const
|
|
18
|
+
const matchedClosingTagOffsets = /* @__PURE__ */ new Set();
|
|
19
19
|
const locate = createLocator(dmlString);
|
|
20
20
|
const errorAt = (message, offset) => {
|
|
21
21
|
return new DmlParseError(message, file, locate(offset));
|
|
@@ -29,11 +29,11 @@ function parseDmlToIR(dmlString, options = {}) {
|
|
|
29
29
|
if (content.length > 0) {
|
|
30
30
|
let node;
|
|
31
31
|
if (locations) {
|
|
32
|
-
const
|
|
32
|
+
const leadingWhitespace = whitespace === "preserve" ? 0 : textBuffer.length - textBuffer.trimStart().length;
|
|
33
33
|
node = {
|
|
34
34
|
type: "Text",
|
|
35
35
|
content,
|
|
36
|
-
loc: locate(textStart +
|
|
36
|
+
loc: locate(textStart + leadingWhitespace)
|
|
37
37
|
};
|
|
38
38
|
} else node = {
|
|
39
39
|
type: "Text",
|
|
@@ -59,14 +59,16 @@ function parseDmlToIR(dmlString, options = {}) {
|
|
|
59
59
|
const attributes = {};
|
|
60
60
|
for (const [attributeName, value] of Object.entries(attribs)) if (isEventProp(attributeName)) events[attributeName] = value;
|
|
61
61
|
else attributes[attributeName] = value;
|
|
62
|
-
|
|
62
|
+
let node;
|
|
63
|
+
if (locations) node = {
|
|
63
64
|
type: "Element",
|
|
64
65
|
tag: name,
|
|
65
66
|
attributes,
|
|
66
67
|
events,
|
|
67
68
|
children: [],
|
|
68
69
|
loc: locate(parser.startIndex)
|
|
69
|
-
}
|
|
70
|
+
};
|
|
71
|
+
else node = {
|
|
70
72
|
type: "Element",
|
|
71
73
|
tag: name,
|
|
72
74
|
attributes,
|
|
@@ -82,14 +84,15 @@ function parseDmlToIR(dmlString, options = {}) {
|
|
|
82
84
|
onclosetag(name, isImplied) {
|
|
83
85
|
flushText();
|
|
84
86
|
if (unfinishedTag) throw errorAt(`<${unfinishedTag.name}> isn't finished: add \`>\` or \`/>\``, unfinishedTag.start);
|
|
85
|
-
const
|
|
86
|
-
const
|
|
87
|
+
const openTag = stack.pop();
|
|
88
|
+
const openTagName = openTag.node.tag;
|
|
89
|
+
const selfClosing = parser.startIndex === openTag.start;
|
|
87
90
|
if (isImplied && !selfClosing) {
|
|
88
91
|
const found = parser.startIndex >= dmlString.length ? "end of input" : `\`${dmlString.slice(parser.startIndex, parser.endIndex + 1)}\``;
|
|
89
|
-
throw errorAt(`<${
|
|
92
|
+
throw errorAt(`<${openTagName}> isn't closed: expected </${openTagName}>, found ${found}`, openTag.start);
|
|
90
93
|
}
|
|
91
|
-
if (name !==
|
|
92
|
-
if (!selfClosing)
|
|
94
|
+
if (name !== openTagName) throw errorAt(`</${name}> doesn't match <${openTagName}>: expected </${openTagName}>`, parser.startIndex);
|
|
95
|
+
if (!selfClosing) matchedClosingTagOffsets.add(parser.startIndex);
|
|
93
96
|
},
|
|
94
97
|
ontext(data) {
|
|
95
98
|
if (textStart < 0) textStart = parser.startIndex;
|
|
@@ -112,8 +115,8 @@ function parseDmlToIR(dmlString, options = {}) {
|
|
|
112
115
|
parser.write(dmlString);
|
|
113
116
|
parser.end();
|
|
114
117
|
flushText();
|
|
115
|
-
const
|
|
116
|
-
for (const
|
|
118
|
+
const markupOnly = dmlString.replace(OPAQUE_REGION, (region) => " ".repeat(region.length));
|
|
119
|
+
for (const closingTag of markupOnly.matchAll(CLOSING_TAG)) if (!matchedClosingTagOffsets.has(closingTag.index)) throw errorAt(`</${closingTag[1]}> has no matching opening tag`, closingTag.index);
|
|
117
120
|
return roots;
|
|
118
121
|
}
|
|
119
122
|
function normalizeText(raw, mode) {
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":[],"sources":["../src/errors.ts","../src/parse.ts","../src/ast.ts"],"sourcesContent":["import { SourceError } from '@monimesl/dot-core';\n\nexport class DmlParseError extends SourceError {\n override readonly name = 'DmlParseError';\n}\n","import { Parser } from 'htmlparser2';\nimport { createLocator, isEventProp } from '@monimesl/dot-core';\n\nimport { DmlParseError } from './errors';\nimport type { DmlElementNode, DmlNode } from './ast';\n\nexport interface ParseDmlOptions {\n file?: string;\n locations?: boolean;\n whitespace?: 'trim' | 'collapse' | 'inline' | 'preserve';\n}\n\nconst
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../src/errors.ts","../src/parse.ts","../src/ast.ts"],"sourcesContent":["import { SourceError } from '@monimesl/dot-core';\n\nexport class DmlParseError extends SourceError {\n override readonly name = 'DmlParseError';\n}\n","import { Parser } from 'htmlparser2';\nimport { createLocator, isEventProp } from '@monimesl/dot-core';\n\nimport { DmlParseError } from './errors';\nimport type { DmlElementNode, DmlNode } from './ast';\n\nexport interface ParseDmlOptions {\n file?: string;\n locations?: boolean;\n whitespace?: 'trim' | 'collapse' | 'inline' | 'preserve';\n}\n\nconst CLOSING_TAG = /<\\/([^\\s>]+)\\s*>/g;\nconst OPAQUE_REGION = /<!--[\\s\\S]*?-->|<!\\[CDATA\\[[\\s\\S]*?]]>/g;\n\ninterface OpenTag {\n node: DmlElementNode;\n start: number;\n}\n\n/** Parses .dml markup into an IR tree, leaving `{{ }}` bindings as raw strings. */\nfunction parseDmlToIR(dmlString: string, options: ParseDmlOptions = {}): DmlNode[] {\n const { file, locations = false, whitespace = 'trim' } = options;\n const roots: DmlNode[] = [];\n const stack: OpenTag[] = [];\n let textBuffer = '';\n let textStart = -1;\n const matchedClosingTagOffsets = new Set<number>();\n const locate = createLocator(dmlString);\n const errorAt = (message: string, offset: number) => {\n return new DmlParseError(message, file, locate(offset));\n };\n const currentChildren = (): DmlNode[] => {\n return stack.at(-1)?.node.children ?? roots;\n };\n const flushText = (): void => {\n if (textStart < 0) {\n return;\n }\n const content = normalizeText(textBuffer, whitespace);\n if (content.length > 0) {\n let node: DmlNode;\n if (locations) {\n const leadingWhitespace =\n whitespace === 'preserve' ? 0 : textBuffer.length - textBuffer.trimStart().length;\n node = { type: 'Text', content, loc: locate(textStart + leadingWhitespace) };\n } else {\n node = { type: 'Text', content };\n }\n currentChildren().push(node);\n }\n textBuffer = '';\n textStart = -1;\n };\n // A tag whose name has been read but not its closing `>`.\n let unfinishedTag: { name: string; start: number } | undefined;\n const parser = new Parser(\n {\n onopentagname(name) {\n unfinishedTag = { name, start: parser.startIndex };\n },\n onopentag(name, attribs) {\n unfinishedTag = undefined;\n flushText();\n const events: Record<string, string> = {};\n const attributes: Record<string, string> = {};\n for (const [attributeName, value] of Object.entries(attribs)) {\n if (isEventProp(attributeName)) {\n events[attributeName] = value;\n } else {\n attributes[attributeName] = value;\n }\n }\n let node: DmlElementNode;\n if (locations) {\n node = {\n type: 'Element',\n tag: name,\n attributes,\n events,\n children: [],\n loc: locate(parser.startIndex),\n };\n } else {\n node = { type: 'Element', tag: name, attributes, events, children: [] };\n }\n currentChildren().push(node);\n stack.push({ node, start: parser.startIndex });\n },\n onclosetag(name, isImplied) {\n flushText();\n if (unfinishedTag) {\n throw errorAt(\n `<${unfinishedTag.name}> isn't finished: add \\`>\\` or \\`/>\\``,\n unfinishedTag.start,\n );\n }\n // htmlparser2 only reports closing tags it has seen open.\n const openTag = stack.pop()!;\n const openTagName = openTag.node.tag;\n const selfClosing = parser.startIndex === openTag.start;\n if (isImplied && !selfClosing) {\n const found =\n parser.startIndex >= dmlString.length\n ? 'end of input'\n : `\\`${dmlString.slice(parser.startIndex, parser.endIndex + 1)}\\``;\n throw errorAt(\n `<${openTagName}> isn't closed: expected </${openTagName}>, found ${found}`,\n openTag.start,\n );\n }\n if (name !== openTagName) {\n throw errorAt(\n `</${name}> doesn't match <${openTagName}>: expected </${openTagName}>`,\n parser.startIndex,\n );\n }\n if (!selfClosing) {\n matchedClosingTagOffsets.add(parser.startIndex);\n }\n },\n ontext(data) {\n // htmlparser2 splits text around entities; buffer until the next tag.\n if (textStart < 0) {\n textStart = parser.startIndex;\n }\n textBuffer += data;\n },\n oncomment() {\n flushText();\n },\n onprocessinginstruction() {\n flushText();\n },\n onerror(error) {\n throw errorAt(error.message, parser.startIndex);\n },\n },\n {\n xmlMode: true,\n decodeEntities: true,\n recognizeCDATA: true,\n },\n );\n\n parser.write(dmlString);\n parser.end();\n flushText();\n\n // htmlparser2 ignores unmatched closing tags instead of throwing, so we catch them here.\n // Comments and CDATA are blanked with spaces, not removed, so offsets still match the source.\n const markupOnly = dmlString.replace(OPAQUE_REGION, (region) => ' '.repeat(region.length));\n for (const closingTag of markupOnly.matchAll(CLOSING_TAG)) {\n if (!matchedClosingTagOffsets.has(closingTag.index)) {\n throw errorAt(`</${closingTag[1]!}> has no matching opening tag`, closingTag.index);\n }\n }\n return roots;\n}\n\nexport default parseDmlToIR;\n\nfunction normalizeText(raw: string, mode: NonNullable<ParseDmlOptions['whitespace']>): string {\n switch (mode) {\n case 'preserve':\n return raw.trim().length === 0 ? '' : raw;\n case 'collapse':\n return raw.replace(/\\s+/g, ' ').trim();\n case 'inline':\n return inlineText(raw);\n case 'trim':\n return raw.trim();\n }\n}\n\n// As text flows around inline elements: whitespace with a line break in it only lays out the markup,\n// so it goes, but a space on the same line as an element stays, as in `paid <Text>SLE 50</Text> today`.\nfunction inlineText(raw: string): string {\n if (raw.trim() === '') {\n return raw.includes('\\n') ? '' : ' ';\n }\n return raw\n .replace(/^\\s*\\n\\s*/, '')\n .replace(/\\s*\\n\\s*$/, '')\n .replace(/\\s+/g, ' ');\n}\n","import type { SourceLocation } from '@monimesl/dot-core';\n\nexport interface DmlElementNode {\n readonly type: 'Element';\n readonly tag: string;\n readonly events: Record<string, string>;\n readonly attributes: Record<string, string>;\n readonly children: DmlNode[];\n readonly loc?: SourceLocation;\n}\n\nexport interface DmlTextNode {\n readonly type: 'Text';\n readonly content: string;\n readonly loc?: SourceLocation;\n}\n\nexport type DmlNode = DmlElementNode | DmlTextNode;\n\nexport function isElementNode(node: DmlNode): node is DmlElementNode {\n return node.type === 'Element';\n}\n"],"mappings":";;;AAEA,IAAa,gBAAb,cAAmC,YAAY;CAC7C,OAAyB;AAC3B;;;ACQA,MAAM,cAAc;AACpB,MAAM,gBAAgB;;AAQtB,SAAS,aAAa,WAAmB,UAA2B,CAAC,GAAc;CACjF,MAAM,EAAE,MAAM,YAAY,OAAO,aAAa,WAAW;CACzD,MAAM,QAAmB,CAAC;CAC1B,MAAM,QAAmB,CAAC;CAC1B,IAAI,aAAa;CACjB,IAAI,YAAY;CAChB,MAAM,2CAA2B,IAAI,IAAY;CACjD,MAAM,SAAS,cAAc,SAAS;CACtC,MAAM,WAAW,SAAiB,WAAmB;EACnD,OAAO,IAAI,cAAc,SAAS,MAAM,OAAO,MAAM,CAAC;CACxD;CACA,MAAM,wBAAmC;EACvC,OAAO,MAAM,GAAG,EAAE,CAAC,EAAE,KAAK,YAAY;CACxC;CACA,MAAM,kBAAwB;EAC5B,IAAI,YAAY,GACd;EAEF,MAAM,UAAU,cAAc,YAAY,UAAU;EACpD,IAAI,QAAQ,SAAS,GAAG;GACtB,IAAI;GACJ,IAAI,WAAW;IACb,MAAM,oBACJ,eAAe,aAAa,IAAI,WAAW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KAAK,SAAS;AACvB"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@monimesl/dot-dml-parser",
|
|
3
|
-
"version": "0.1.0-alpha.
|
|
3
|
+
"version": "0.1.0-alpha.21",
|
|
4
4
|
"description": "Dot .dml template parser: markup -> intermediary representation",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"repository": {
|
|
@@ -32,7 +32,7 @@
|
|
|
32
32
|
},
|
|
33
33
|
"dependencies": {
|
|
34
34
|
"htmlparser2": "^12.0.0",
|
|
35
|
-
"@monimesl/dot-core": "0.1.0-alpha.
|
|
35
|
+
"@monimesl/dot-core": "0.1.0-alpha.21"
|
|
36
36
|
},
|
|
37
37
|
"publishConfig": {
|
|
38
38
|
"access": "public"
|