@reteps/tree-sitter-htmlmustache 0.0.18

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 Peter Stenger
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,105 @@
1
+ <p align="center">
2
+ <img src="lsp/icon.png" alt="HTML Mustache Logo" width="128">
3
+ </p>
4
+
5
+ <h1 align="center">HTML Mustache</h1>
6
+
7
+ <p align="center">
8
+ <strong>Full language support for HTML with Mustache/Handlebars templates</strong>
9
+ </p>
10
+
11
+ <p align="center">
12
+ <a href="https://github.com/reteps/tree-sitter-htmlmustache/actions/workflows/lint.yml"><img src="https://img.shields.io/github/actions/workflow/status/reteps/tree-sitter-htmlmustache/lint.yml?logo=github&label=Lint" alt="Lint"></a>
13
+ <a href="https://github.com/reteps/tree-sitter-htmlmustache/actions/workflows/lsp.yml"><img src="https://img.shields.io/github/actions/workflow/status/reteps/tree-sitter-htmlmustache/lsp.yml?logo=github&label=LSP" alt="LSP"></a>
14
+ <a href="https://marketplace.visualstudio.com/items?itemName=reteps.htmlmustache-lsp"><img src="https://img.shields.io/visual-studio-marketplace/v/reteps.htmlmustache-lsp?logo=visualstudiocode&label=VS%20Code" alt="VS Code Marketplace"></a>
15
+ </p>
16
+
17
+ ---
18
+
19
+ ## Features
20
+
21
+ - **CLI Linter** — Check templates for errors from the command line
22
+ - **Syntax Highlighting** — Full semantic highlighting for HTML and Mustache syntax
23
+ - **Document Formatting** — Auto-format with EditorConfig support
24
+ - **Document Symbols** — Outline view and breadcrumb navigation
25
+ - **Folding** — Collapse HTML elements and Mustache sections
26
+ - **Hover Information** — Tag and attribute documentation
27
+
28
+ ### Supported Mustache Syntax
29
+
30
+ | Syntax | Description |
31
+ | ------------------------- | ---------------------- |
32
+ | `{{name}}` | Variable interpolation |
33
+ | `{{{html}}}` | Unescaped HTML |
34
+ | `{{#items}}...{{/items}}` | Sections |
35
+ | `{{^items}}...{{/items}}` | Inverted sections |
36
+ | `{{! comment }}` | Comments |
37
+ | `{{> partial}}` | Partials |
38
+
39
+ ## CLI
40
+
41
+ Check templates for errors before committing:
42
+
43
+ ```
44
+ npx @reteps/tree-sitter-htmlmustache check '**/*.mustache' '**/*.hbs'
45
+ ```
46
+
47
+ ```
48
+ file.mustache:3:3 error: Mismatched mustache section: {{/wrong}}
49
+ |
50
+ 1 | {{#items}}
51
+ 2 | <li>{{name}}
52
+ 3 | {{/wrong}}
53
+ | ^^^^^^^^^^ Mismatched mustache section: {{/wrong}}
54
+
55
+ 1 error in 1 file (5 files checked)
56
+ ```
57
+
58
+ Or install globally:
59
+
60
+ ```
61
+ npm install -g @reteps/tree-sitter-htmlmustache
62
+ htmlmustache check '**/*.mustache'
63
+ ```
64
+
65
+ Detects parse errors, mismatched Mustache sections, mismatched HTML end tags, and missing tokens.
66
+
67
+ ## Installation
68
+
69
+ ### VS Code Extension
70
+
71
+ Install from the [VS Code Marketplace](https://marketplace.visualstudio.com/items?itemName=reteps.htmlmustache-lsp) or search for "HTML Mustache" in the Extensions view.
72
+
73
+ Alternatively, download `htmlmustache-lsp.vsix` from the [latest release](https://github.com/reteps/tree-sitter-htmlmustache/releases) and install via:
74
+
75
+ ```
76
+ code --install-extension htmlmustache-lsp.vsix
77
+ ```
78
+
79
+ ### WASM
80
+
81
+ Download `tree-sitter-htmlmustache.wasm` from the [latest release](https://github.com/reteps/tree-sitter-htmlmustache/releases).
82
+
83
+ ## Using with `.html` Files
84
+
85
+ By default, the extension activates for `.mustache`, `.hbs`, and `.handlebars` files. To use it with `.html` files, add this to your VS Code settings:
86
+
87
+ ```json
88
+ {
89
+ "files.associations": {
90
+ "*.html": "htmlmustache"
91
+ }
92
+ }
93
+ ```
94
+
95
+ You can also change the language mode for a single file by clicking the language indicator in the status bar and selecting "HTML Mustache".
96
+
97
+ ## Acknowledgments
98
+
99
+ This project is based on [tree-sitter-html](https://github.com/tree-sitter/tree-sitter-html) by Max Brunsfeld and Amaan Qureshi.
100
+
101
+ ## References
102
+
103
+ - [The HTML5 Spec](https://www.w3.org/TR/html5/syntax.html)
104
+ - [Mustache Manual](https://mustache.github.io/mustache.5.html)
105
+ - [Handlebars Language Guide](https://handlebarsjs.com/guide/)
package/binding.gyp ADDED
@@ -0,0 +1,30 @@
1
+ {
2
+ "targets": [
3
+ {
4
+ "target_name": "tree_sitter_html_binding",
5
+ "dependencies": [
6
+ "<!(node -p \"require('node-addon-api').targets\"):node_addon_api_except",
7
+ ],
8
+ "include_dirs": [
9
+ "src",
10
+ ],
11
+ "sources": [
12
+ "bindings/node/binding.cc",
13
+ "src/parser.c",
14
+ "src/scanner.c",
15
+ ],
16
+ "conditions": [
17
+ ["OS!='win'", {
18
+ "cflags_c": [
19
+ "-std=c11",
20
+ ],
21
+ }, { # OS == "win"
22
+ "cflags_c": [
23
+ "/std:c11",
24
+ "/utf-8",
25
+ ],
26
+ }],
27
+ ],
28
+ }
29
+ ]
30
+ }
@@ -0,0 +1,19 @@
1
+ #include <napi.h>
2
+
3
+ typedef struct TSLanguage TSLanguage;
4
+
5
+ extern "C" TSLanguage *tree_sitter_htmlmustache();
6
+
7
+ // "tree-sitter", "language" hashed with BLAKE2
8
+ const napi_type_tag LANGUAGE_TYPE_TAG = {
9
+ 0x8AF2E5212AD58ABF, 0xD5006CAD83ABBA16
10
+ };
11
+
12
+ Napi::Object Init(Napi::Env env, Napi::Object exports) {
13
+ auto language = Napi::External<TSLanguage>::New(env, tree_sitter_htmlmustache());
14
+ language.TypeTag(&LANGUAGE_TYPE_TAG);
15
+ exports["language"] = language;
16
+ return exports;
17
+ }
18
+
19
+ NODE_API_MODULE(tree_sitter_htmlmustache_binding, Init)
@@ -0,0 +1,9 @@
1
+ const assert = require('node:assert');
2
+ const { test } = require('node:test');
3
+
4
+ const Parser = require('tree-sitter');
5
+
6
+ test('can load grammar', () => {
7
+ const parser = new Parser();
8
+ assert.doesNotThrow(() => parser.setLanguage(require('.')));
9
+ });
@@ -0,0 +1,27 @@
1
+ type BaseNode = {
2
+ type: string;
3
+ named: boolean;
4
+ };
5
+
6
+ type ChildNode = {
7
+ multiple: boolean;
8
+ required: boolean;
9
+ types: BaseNode[];
10
+ };
11
+
12
+ type NodeInfo =
13
+ | (BaseNode & {
14
+ subtypes: BaseNode[];
15
+ })
16
+ | (BaseNode & {
17
+ fields: { [name: string]: ChildNode };
18
+ children: ChildNode[];
19
+ });
20
+
21
+ type Language = {
22
+ language: unknown;
23
+ nodeTypeInfo: NodeInfo[];
24
+ };
25
+
26
+ declare const language: Language;
27
+ export = language;
@@ -0,0 +1,13 @@
1
+ const root = require('path').join(__dirname, '..', '..');
2
+
3
+ module.exports =
4
+ typeof process.versions.bun === 'string'
5
+ ? // Support `bun build --compile` by being statically analyzable enough to find the .node file at build-time
6
+ require(
7
+ `../../prebuilds/${process.platform}-${process.arch}/tree-sitter-htmlmustache.node`,
8
+ )
9
+ : require('node-gyp-build')(root);
10
+
11
+ try {
12
+ module.exports.nodeTypeInfo = require('../../src/node-types.json');
13
+ } catch (_) {}
@@ -0,0 +1,210 @@
1
+ #!/usr/bin/env node
2
+ "use strict";
3
+ var __importDefault = (this && this.__importDefault) || function (mod) {
4
+ return (mod && mod.__esModule) ? mod : { "default": mod };
5
+ };
6
+ Object.defineProperty(exports, "__esModule", { value: true });
7
+ exports.collectErrors = collectErrors;
8
+ exports.formatError = formatError;
9
+ exports.formatSummary = formatSummary;
10
+ exports.expandGlobs = expandGlobs;
11
+ exports.run = run;
12
+ const node_fs_1 = __importDefault(require("node:fs"));
13
+ const node_path_1 = __importDefault(require("node:path"));
14
+ const chalk_1 = __importDefault(require("chalk"));
15
+ function loadParser() {
16
+ let Parser;
17
+ try {
18
+ Parser = require('tree-sitter');
19
+ }
20
+ catch {
21
+ console.error(chalk_1.default.red('Error: tree-sitter is not installed.\n') +
22
+ 'Install it with: npm install tree-sitter');
23
+ process.exit(1);
24
+ }
25
+ let language;
26
+ try {
27
+ language = require(node_path_1.default.resolve(__dirname, '..', '..'));
28
+ }
29
+ catch {
30
+ console.error(chalk_1.default.red('Error: could not load tree-sitter-htmlmustache bindings.\n') +
31
+ 'Run "npm install" in the tree-sitter-htmlmustache root first.');
32
+ process.exit(1);
33
+ }
34
+ const parser = new Parser();
35
+ parser.setLanguage(language);
36
+ return parser;
37
+ }
38
+ // ── Error collection ──
39
+ function errorMessageForNode(nodeType, node) {
40
+ if (nodeType === 'mustache_erroneous_section_end' || nodeType === 'mustache_erroneous_inverted_section_end') {
41
+ const tagNameNode = node.children.find((c) => c.type === 'mustache_erroneous_tag_name');
42
+ return `Mismatched mustache section: {{/${tagNameNode?.text || '?'}}}`;
43
+ }
44
+ if (nodeType === 'html_erroneous_end_tag') {
45
+ const tagNameNode = node.children.find((c) => c.type === 'html_erroneous_end_tag_name');
46
+ return `Mismatched HTML end tag: </${tagNameNode?.text || '?'}>`;
47
+ }
48
+ if (nodeType === 'ERROR') {
49
+ return 'Syntax error';
50
+ }
51
+ // isMissing node
52
+ return `Missing ${nodeType}`;
53
+ }
54
+ const ERROR_NODE_TYPES = new Set([
55
+ 'ERROR',
56
+ 'mustache_erroneous_section_end',
57
+ 'mustache_erroneous_inverted_section_end',
58
+ 'html_erroneous_end_tag',
59
+ ]);
60
+ function collectErrors(tree, file) {
61
+ const errors = [];
62
+ const cursor = tree.walk();
63
+ function visit() {
64
+ const node = cursor.currentNode;
65
+ const nodeType = cursor.nodeType;
66
+ if (ERROR_NODE_TYPES.has(nodeType) || cursor.nodeIsMissing) {
67
+ errors.push({
68
+ file,
69
+ line: node.startPosition.row + 1,
70
+ column: node.startPosition.column + 1,
71
+ endLine: node.endPosition.row + 1,
72
+ endColumn: node.endPosition.column + 1,
73
+ message: errorMessageForNode(nodeType, node),
74
+ nodeText: node.text,
75
+ });
76
+ // Don't recurse into ERROR nodes — the children are not meaningful
77
+ if (nodeType === 'ERROR')
78
+ return;
79
+ }
80
+ if (cursor.gotoFirstChild()) {
81
+ do {
82
+ visit();
83
+ } while (cursor.gotoNextSibling());
84
+ cursor.gotoParent();
85
+ }
86
+ }
87
+ visit();
88
+ return errors;
89
+ }
90
+ // ── Formatting ──
91
+ function formatError(error, source) {
92
+ const lines = source.split('\n');
93
+ const errorLine = error.line - 1; // 0-based index
94
+ // Location header
95
+ const header = chalk_1.default.bold(`${error.file}:${error.line}:${error.column}`) +
96
+ ' ' + chalk_1.default.red('error') + ': ' + error.message;
97
+ // Context lines: up to 2 before + the error line(s)
98
+ const contextStart = Math.max(0, errorLine - 2);
99
+ const contextEnd = Math.min(lines.length - 1, error.endLine - 1);
100
+ const gutterWidth = String(contextEnd + 1).length;
101
+ const pad = (n) => String(n).padStart(gutterWidth);
102
+ const outputLines = [header];
103
+ outputLines.push(chalk_1.default.dim(' '.repeat(gutterWidth) + ' |'));
104
+ for (let i = contextStart; i <= contextEnd; i++) {
105
+ const lineNum = i + 1;
106
+ outputLines.push(chalk_1.default.dim(`${pad(lineNum)} |`) + ' ' + lines[i]);
107
+ }
108
+ // Underline: only on the last displayed line of the error
109
+ const lastErrorLineIdx = error.endLine - 1;
110
+ const lastLine = lines[lastErrorLineIdx] || '';
111
+ let underlineStart;
112
+ let underlineEnd;
113
+ if (error.line === error.endLine) {
114
+ // Single-line error
115
+ underlineStart = error.column - 1;
116
+ underlineEnd = error.endColumn - 1;
117
+ }
118
+ else {
119
+ // Multi-line: underline to end of last line
120
+ underlineStart = 0;
121
+ underlineEnd = lastLine.length;
122
+ }
123
+ const underlineLength = Math.max(1, underlineEnd - underlineStart);
124
+ const underline = ' '.repeat(underlineStart) + '^'.repeat(underlineLength) +
125
+ ' ' + error.message;
126
+ outputLines.push(chalk_1.default.dim(' '.repeat(gutterWidth) + ' |') + ' ' + chalk_1.default.red(underline));
127
+ return outputLines.join('\n');
128
+ }
129
+ function formatSummary(totalErrors, filesWithErrors, totalFiles) {
130
+ if (totalErrors === 0) {
131
+ return chalk_1.default.green(`No errors found (${totalFiles} ${totalFiles === 1 ? 'file' : 'files'} checked)`);
132
+ }
133
+ const errStr = totalErrors === 1 ? 'error' : 'errors';
134
+ const errFileStr = filesWithErrors === 1 ? 'file' : 'files';
135
+ const totalStr = totalFiles === 1 ? 'file' : 'files';
136
+ return chalk_1.default.red(`${totalErrors} ${errStr} in ${filesWithErrors} ${errFileStr}`) +
137
+ ` (${totalFiles} ${totalStr} checked)`;
138
+ }
139
+ // ── Glob expansion ──
140
+ function expandGlobs(patterns) {
141
+ const files = new Set();
142
+ for (const pattern of patterns) {
143
+ for (const match of node_fs_1.default.globSync(pattern)) {
144
+ files.add(node_path_1.default.resolve(match));
145
+ }
146
+ }
147
+ return [...files].sort();
148
+ }
149
+ // ── Main ──
150
+ const USAGE = `Usage: htmlmustache check <patterns...>
151
+
152
+ Check HTML Mustache templates for errors.
153
+
154
+ Arguments:
155
+ patterns One or more glob patterns (e.g. '**/*.mustache' '**/*.hbs')
156
+
157
+ Options:
158
+ --help Show this help message
159
+
160
+ Examples:
161
+ htmlmustache check '**/*.mustache'
162
+ htmlmustache check 'templates/**/*.hbs' 'partials/**/*.mustache'`;
163
+ function run(args) {
164
+ // Strip "check" subcommand if present
165
+ if (args[0] === 'check') {
166
+ args = args.slice(1);
167
+ }
168
+ if (args.includes('--help') || args.length === 0) {
169
+ console.log(USAGE);
170
+ return args.includes('--help') ? 0 : 1;
171
+ }
172
+ const files = expandGlobs(args);
173
+ if (files.length === 0) {
174
+ console.error(chalk_1.default.yellow('No files matched the given patterns.'));
175
+ return 1;
176
+ }
177
+ const parser = loadParser();
178
+ let totalErrors = 0;
179
+ let filesWithErrors = 0;
180
+ for (const file of files) {
181
+ const source = node_fs_1.default.readFileSync(file, 'utf-8');
182
+ const tree = parser.parse(source);
183
+ const errors = collectErrors(tree, file);
184
+ if (errors.length > 0) {
185
+ filesWithErrors++;
186
+ totalErrors += errors.length;
187
+ for (const error of errors) {
188
+ console.log(formatError(error, source));
189
+ console.log();
190
+ }
191
+ }
192
+ }
193
+ console.log(formatSummary(totalErrors, filesWithErrors, files.length));
194
+ return totalErrors > 0 ? 1 : 0;
195
+ }
196
+ // CLI entry point
197
+ if (require.main === module) {
198
+ const args = process.argv.slice(2);
199
+ if (args[0] !== 'check' && !args.includes('--help')) {
200
+ if (args.length === 0) {
201
+ console.log(USAGE);
202
+ process.exit(1);
203
+ }
204
+ console.error(chalk_1.default.red(`Unknown command: ${args[0]}`));
205
+ console.error('Run "htmlmustache --help" for usage.');
206
+ process.exit(1);
207
+ }
208
+ const code = run(args);
209
+ process.exit(code);
210
+ }