miki-template 1.3.3 → 1.3.7

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.
Files changed (115) hide show
  1. package/.eslintrc.json +16 -0
  2. package/.github/release-notes/v1.3.1.md +55 -55
  3. package/.github/release-notes/v1.3.3.md +77 -0
  4. package/.github/workflows/ci.yml +38 -54
  5. package/.github/workflows/release.yml +106 -0
  6. package/AGENT.md +71 -71
  7. package/API_REFERENCE.md +314 -314
  8. package/CHANGELOG.md +173 -169
  9. package/CODE_OF_CONDUCT.md +14 -14
  10. package/CONTRIBUTING.md +27 -27
  11. package/README.md +342 -321
  12. package/ROADMAP.md +40 -40
  13. package/benchmarks/report.json +16 -16
  14. package/benchmarks/run.js +49 -49
  15. package/benchmarks/stress.mjs +647 -647
  16. package/benchmarks/templates/large.dtpl +7 -7
  17. package/benchmarks/templates/medium.dtpl +3 -3
  18. package/benchmarks/templates/small.dtpl +7 -7
  19. package/context/component.md +109 -109
  20. package/context/prd.md +131 -131
  21. package/context/project-structure.md +33 -33
  22. package/dir/base.html +22 -22
  23. package/dir/cmpnt.html +10 -10
  24. package/dir/footer.html +2 -2
  25. package/dir/home.html +80 -80
  26. package/dir/index.html +80 -0
  27. package/dir/navbar.html +8 -8
  28. package/docs/README.md +18 -18
  29. package/docs/advanced_usage.md +71 -71
  30. package/docs/api.md +119 -119
  31. package/docs/filters.md +708 -708
  32. package/docs/installation.md +106 -106
  33. package/docs/overview.md +79 -57
  34. package/docs/partialdef.md +70 -70
  35. package/docs/security.md +27 -27
  36. package/docs/tags.md +673 -673
  37. package/docs/usage.md +646 -646
  38. package/eslint.config.mjs +42 -42
  39. package/ex.mjs +34 -32
  40. package/live-test/package-lock.json +915 -0
  41. package/live-test/package.json +9 -0
  42. package/live-test/server.js +14 -0
  43. package/live-test/views/base.html +8 -0
  44. package/live-test/views/child.html +7 -0
  45. package/live-test/views/index.html +1 -0
  46. package/miki-template-extension/.github/workflows/ci.yml +116 -116
  47. package/miki-template-extension/.vscodeignore +7 -7
  48. package/miki-template-extension/CHANGELOG.md +99 -99
  49. package/miki-template-extension/LICENSE +21 -21
  50. package/miki-template-extension/README.md +273 -273
  51. package/miki-template-extension/extension.js +1013 -1013
  52. package/miki-template-extension/icon.svg +10 -10
  53. package/miki-template-extension/package.json +280 -280
  54. package/miki-template-extension/snippets/miki-template.json +717 -717
  55. package/miki-template-extension/syntaxes/language-configuration.json +114 -114
  56. package/miki-template-extension/syntaxes/miki-template.tmLanguage.json +355 -355
  57. package/miki-template-extension/tests/grammar-tests.json +162 -162
  58. package/miki-template-extension/tests/run-grammar-tests.js +82 -82
  59. package/package.json +40 -34
  60. package/sample-app/package-lock.json +901 -0
  61. package/sample-app/package.json +9 -0
  62. package/sample-app/server.js +14 -0
  63. package/sample-app/views/index.html +1 -0
  64. package/scripts/build-vsix.js +129 -129
  65. package/scripts/build-vsix.ps1 +15 -15
  66. package/snippets/miki-template.json +177 -177
  67. package/src/asyncRender.js +20 -20
  68. package/src/cache.js +80 -80
  69. package/src/context.js +126 -126
  70. package/src/context_processors.js +48 -48
  71. package/src/esm.mjs +89 -84
  72. package/src/filters.js +975 -975
  73. package/src/i18n.js +171 -171
  74. package/src/index.js +1112 -940
  75. package/src/lexer.js +114 -114
  76. package/src/libraries.js +371 -371
  77. package/src/parser.js +270 -270
  78. package/src/security.js +53 -53
  79. package/src/tags/control.js +719 -719
  80. package/src/tags/extra.js +154 -154
  81. package/src/tags/helpers.js +26 -26
  82. package/src/tags/i18n.js +256 -256
  83. package/src/tags/inheritance.js +335 -335
  84. package/src/tags/registry.js +18 -18
  85. package/src/tags/util.js +400 -400
  86. package/src/types.d.ts +107 -107
  87. package/syntaxes/language-configuration.json +26 -26
  88. package/syntaxes/miki-template.tmLanguage.json +146 -146
  89. package/tests/asyncRender.test.js +17 -17
  90. package/tests/base.html +6 -6
  91. package/tests/child.html +3 -3
  92. package/tests/context_processors.test.js +13 -13
  93. package/tests/esm.test.mjs +61 -61
  94. package/tests/filters.test.js +254 -254
  95. package/tests/finder-appdirs.test.js +19 -0
  96. package/tests/finder.test.js +17 -0
  97. package/tests/fixtures/views/nested/index.html +1 -0
  98. package/tests/fixtures/views/partial.html +1 -0
  99. package/tests/fixtures/views/sub/deepfile.html +1 -0
  100. package/tests/fixtures/views-appdirs/product/site/detail.html +1 -0
  101. package/tests/include_security.test.js +9 -9
  102. package/tests/integration/README.md +32 -32
  103. package/tests/integration/features.test.cjs +1681 -1681
  104. package/tests/integration/features.test.mjs +1697 -1697
  105. package/tests/integration/finder.esm.test.mjs +13 -0
  106. package/tests/integration/templates/base.miki +6 -6
  107. package/tests/integration/templates/child.miki +6 -6
  108. package/tests/integration/templates/index.html +17 -17
  109. package/tests/lexer.test.js +45 -45
  110. package/tests/parser.test.js +57 -57
  111. package/tests/partial.html +1 -1
  112. package/tests/partialdef.test.js +79 -79
  113. package/tests/production_checks.js +57 -57
  114. package/tests/security.test.js +28 -28
  115. package/tests/tags.test.js +233 -233
package/src/tags/util.js CHANGED
@@ -1,400 +1,400 @@
1
- /**
2
- * Utility template tags: static, url, regroup, spaceless.
3
- */
4
-
5
- // Helper to resolve expression values (literals, numbers, booleans, or context lookups)
6
- function resolveValue(token, context) {
7
- if (token === undefined || token === null) return '';
8
- if (typeof token !== 'string') return token;
9
- if (token === '') return '';
10
- if ((token.startsWith('"') && token.endsWith('"')) || (token.startsWith('\'') && token.endsWith('\''))) {
11
- return token.slice(1, -1);
12
- }
13
- if (token === 'true' || token === 'True') return true;
14
- if (token === 'false' || token === 'False') return false;
15
- if (token === 'none' || token === 'None' || token === 'null') return null;
16
- // Numeric literal (integer or float)
17
- if (/^-?\d+(\.\d+)?$/.test(token)) return Number(token);
18
- // Otherwise treat as a context variable lookup
19
- return context.get(token);
20
- }
21
-
22
- class StaticNode {
23
- constructor(pathExpr) {
24
- this.pathExpr = pathExpr;
25
- }
26
-
27
- render(context) {
28
- const resolvedPath = resolveValue(this.pathExpr, context);
29
-
30
- // Resolve static prefix
31
- let prefix = '/static/';
32
- if (context.options && context.options.staticUrl) {
33
- prefix = context.options.staticUrl;
34
- } else if (context.options && context.options.settings && context.options.settings.staticUrl) {
35
- prefix = context.options.settings.staticUrl;
36
- }
37
-
38
- // Ensure double-slash doesn't occur and ends/starts correctly
39
- const base = prefix.endsWith('/') ? prefix : prefix + '/';
40
- const relative = (typeof resolvedPath === 'string' && resolvedPath.startsWith('/'))
41
- ? resolvedPath.slice(1)
42
- : String(resolvedPath);
43
-
44
- return base + relative;
45
- }
46
- }
47
-
48
- class UrlNode {
49
- constructor(routeNameExpr, positionalArgs, kwargs) {
50
- this.routeNameExpr = routeNameExpr;
51
- this.positionalArgs = positionalArgs || [];
52
- // Each kwarg is { name, valueExpr } where valueExpr is the raw
53
- // expression token (may be a number, a quoted string, or a var).
54
- this.kwargs = kwargs || [];
55
- }
56
-
57
- render(context) {
58
- const routeName = resolveValue(this.routeNameExpr, context);
59
- const resolvedPositional = this.positionalArgs.map(arg => resolveValue(arg, context));
60
- const resolvedKwargs = {};
61
- for (const kw of this.kwargs) {
62
- resolvedKwargs[kw.name] = resolveValue(kw.valueExpr, context);
63
- }
64
- const hasKwargs = Object.keys(resolvedKwargs).length > 0;
65
-
66
- // If an Express urlHelper is provided, call it. We pass positional
67
- // args spread, and (only when kwargs are present) a kwargs object
68
- // as the last argument. This keeps the common `{{ url 'r' 42 }}`
69
- // case with a `(name, ...args) => string` helper simple.
70
- if (context.options && typeof context.options.urlHelper === 'function') {
71
- if (hasKwargs) {
72
- return context.options.urlHelper(routeName, ...resolvedPositional, resolvedKwargs);
73
- }
74
- return context.options.urlHelper(routeName, ...resolvedPositional);
75
- }
76
-
77
- // Fallback URL builder: convert dotted route names into deep paths
78
- // (e.g. "user.profile.posts.show" -> "/user/profile/posts/show")
79
- // and append positional args. Kwargs are appended as query string.
80
- const deepPath = String(routeName).split('.').map(seg => seg).join('/');
81
- const parts = ['/' + deepPath, ...resolvedPositional
82
- .filter(v => v !== '' && v !== null && v !== undefined)
83
- .map(v => String(v))];
84
- let url = parts.join('/');
85
- if (hasKwargs) {
86
- const qs = Object.keys(resolvedKwargs)
87
- .filter(k => resolvedKwargs[k] !== undefined)
88
- .map(k => `${encodeURIComponent(k)}=${encodeURIComponent(String(resolvedKwargs[k]))}`)
89
- .join('&');
90
- if (qs) url += '?' + qs;
91
- }
92
- return url;
93
- }
94
- }
95
-
96
- class RegroupNode {
97
- constructor(listPath, attr, targetName) {
98
- this.listPath = listPath;
99
- this.attr = attr;
100
- this.targetName = targetName;
101
- }
102
-
103
- render(context) {
104
- const list = context.get(this.listPath);
105
- if (!Array.isArray(list)) {
106
- context.scopes[0][this.targetName] = [];
107
- return '';
108
- }
109
-
110
- const groups = [];
111
- const groupMap = new Map();
112
-
113
- for (const item of list) {
114
- // Resolve attribute (support nested lookup on item)
115
- let val = '';
116
- if (item && typeof item === 'object') {
117
- const parts = this.attr.split('.');
118
- let current = item;
119
- for (const part of parts) {
120
- if (current && typeof current === 'object' && part in current) {
121
- current = current[part];
122
- } else {
123
- current = undefined;
124
- break;
125
- }
126
- }
127
- val = current !== undefined ? current : '';
128
- }
129
-
130
- if (!groupMap.has(val)) {
131
- const newGroup = { grouper: val, list: [] };
132
- groupMap.set(val, newGroup);
133
- groups.push(newGroup);
134
- }
135
- groupMap.get(val).list.push(item);
136
- }
137
-
138
- // Store in the current context scope
139
- context.scopes[0][this.targetName] = groups;
140
- return '';
141
- }
142
- }
143
-
144
- class SpacelessNode {
145
- constructor(body) {
146
- this.body = body;
147
- }
148
-
149
- render(context) {
150
- const content = this.body.map(n => n.render(context)).join('');
151
- // Remove space between HTML tags
152
- return content.replace(/>\s+</g, '><');
153
- }
154
- }
155
-
156
- class CsrfTokenNode {
157
- render(context) {
158
- const token = context.get('csrf_token') || '';
159
- // Escape the token for safe interpolation into an HTML attribute.
160
- // CSRF tokens are typically alphanumeric, but defending against
161
- // malicious or malformed token values is required to prevent
162
- // attribute injection (" onerror=... etc).
163
- const { escapeHtml, markSafe } = require('../security');
164
- return markSafe(
165
- `<input type="hidden" name="csrfmiddlewaretoken" value="${escapeHtml(String(token), true)}">`
166
- );
167
- }
168
- }
169
-
170
- class CspNonceAttrNode {
171
- render(context) {
172
- const nonce = context.get('csp_nonce') || '';
173
- if (!nonce) return '';
174
- // Escape the nonce for safe interpolation into an attribute value.
175
- const { escapeHtml, markSafe } = require('../security');
176
- return markSafe(`nonce="${escapeHtml(String(nonce), true)}"`);
177
- }
178
- }
179
-
180
- // --- Tag Registry Parsers ---
181
-
182
- function parseStatic(tagContent, _parser) {
183
- // tagContent: "static 'css/style.css'"
184
- const pathExpr = tagContent.slice(6).trim();
185
- return new StaticNode(pathExpr);
186
- }
187
-
188
- function parseUrl(tagContent, _parser) {
189
- // tagContent examples:
190
- // "url 'route_name' arg1 arg2"
191
- // "url 'route.name' 34"
192
- // "url 'user.show' 34 email phone"
193
- // "url 'user.show' userId=34 tab='posts'"
194
- // "url 'user.show' 34 tab='posts'"
195
- const content = tagContent.slice(3).trim();
196
-
197
- // Tokenize respecting quoted strings.
198
- const argRegex = /(".*?"|'.*?'|[^\s]+)/g;
199
- const matches = content.match(argRegex) || [];
200
-
201
- if (matches.length === 0) {
202
- throw new Error('url tag requires a route name');
203
- }
204
- const routeNameExpr = matches[0];
205
- const positionalArgs = [];
206
- const kwargs = [];
207
-
208
- for (let i = 1; i < matches.length; i++) {
209
- const tok = matches[i];
210
- // Detect `key=value` pattern (not a quoted string)
211
- const isQuoted = (tok.startsWith('"') && tok.endsWith('"')) ||
212
- (tok.startsWith('\'') && tok.endsWith('\''));
213
- if (!isQuoted) {
214
- const eq = tok.indexOf('=');
215
- if (eq > 0) {
216
- const name = tok.slice(0, eq);
217
- const valueExpr = tok.slice(eq + 1);
218
- kwargs.push({ name, valueExpr });
219
- continue;
220
- }
221
- }
222
- positionalArgs.push(tok);
223
- }
224
-
225
- return new UrlNode(routeNameExpr, positionalArgs, kwargs);
226
- }
227
-
228
- function parseRegroup(tagContent, _parser) {
229
- // tagContent: "regroup people by gender as grouped"
230
- const match = tagContent.match(/^regroup\s+(.+?)\s+by\s+(.+?)\s+as\s+(.+)$/);
231
- if (!match) {
232
- throw new Error(`Invalid regroup tag format: '${tagContent}'`);
233
- }
234
-
235
- const listPath = match[1].trim();
236
- const attr = match[2].trim();
237
- const targetName = match[3].trim();
238
-
239
- return new RegroupNode(listPath, attr, targetName);
240
- }
241
-
242
- function parseSpaceless(tagContent, parser) {
243
- const body = parser.parse(['endspaceless']);
244
- const next = parser.peek();
245
- if (next && next.type === 'block' && next.content.split(/\s+/)[0] === 'endspaceless') {
246
- parser.advance();
247
- }
248
- return new SpacelessNode(body);
249
- }
250
-
251
- function parseCsrfToken(_tagContent, _parser) {
252
- return new CsrfTokenNode();
253
- }
254
-
255
- class WidthRatioNode {
256
- constructor(value, maxValue, maxWidth) {
257
- this.value = parseFloat(value);
258
- this.maxValue = parseFloat(maxValue);
259
- this.maxWidth = parseInt(maxWidth, 10);
260
- }
261
-
262
- render(_context) {
263
- if (!isFinite(this.value) || !isFinite(this.maxValue) || this.maxValue === 0) {
264
- return '0';
265
- }
266
- const ratio = Math.floor((this.value / this.maxValue) * this.maxWidth);
267
- return String(Math.max(0, Math.min(ratio, this.maxWidth)));
268
- }
269
- }
270
-
271
- class DebugNode {
272
- render(context) {
273
- // Dump the current context (scopes) for debugging
274
- const dump = {
275
- scopes: context.scopes.map(s => {
276
- if (s && typeof s === 'object') {
277
- const out = {};
278
- for (const k of Object.keys(s)) {
279
- if (k.startsWith('__')) continue;
280
- try {
281
- const v = s[k];
282
- out[k] = typeof v === 'function' ? '[function]' : v;
283
- } catch {
284
- out[k] = '[unreadable]';
285
- }
286
- }
287
- return out;
288
- }
289
- return String(s);
290
- })
291
- };
292
- const { escapeHtml, markSafe } = require('../security');
293
- return markSafe('<pre>' + escapeHtml(JSON.stringify(dump, null, 2)) + '</pre>');
294
- }
295
- }
296
-
297
- function parseWidthRatio(tagContent, _parser) {
298
- // {% widthratio this_value max_value max_width %}
299
- const parts = tagContent.replace(/^widthratio\s+/, '').trim().split(/\s+/);
300
- if (parts.length < 3) {
301
- throw new Error('\'widthratio\' tag requires 3 arguments: value, max_value, max_width');
302
- }
303
- return new WidthRatioNode(parts[0], parts[1], parts[2]);
304
- }
305
-
306
- function parseDebug(_tagContent, _parser) {
307
- return new DebugNode();
308
- }
309
-
310
- function parseCspNonceAttr(_tagContent, _parser) {
311
- return new CspNonceAttrNode();
312
- }
313
-
314
- class LoadNode {
315
- constructor(libraries) {
316
- this.libraries = Array.isArray(libraries) ? libraries : [libraries];
317
- }
318
-
319
- render(_context) {
320
- const { activateLibrary, hasLibrary } = require('../libraries');
321
- for (const lib of this.libraries) {
322
- if (hasLibrary(lib)) {
323
- activateLibrary(lib);
324
- } else {
325
- // Emit a comment-style warning for missing library
326
- console.warn(`[miki-template] Library not found: '${lib}'`);
327
- }
328
- }
329
- return '';
330
- }
331
- }
332
-
333
- class TemplatetagNode {
334
- constructor(token) {
335
- this.token = token;
336
- }
337
-
338
- render(_context) {
339
- const map = {
340
- 'openblock': '{%',
341
- 'closeblock': '%}',
342
- 'openvariable': '{{',
343
- 'closevariable': '}}',
344
- 'openbrace': '{',
345
- 'closebrace': '}',
346
- 'opencomment': '{#',
347
- 'closecomment': '#}'
348
- };
349
- return map[this.token] || this.token;
350
- }
351
- }
352
-
353
- function parseLoad(tagContent, _parser) {
354
- const parts = tagContent.trim().split(/\s+/);
355
- if (parts.length === 0) {
356
- throw new Error('\'load\' tag requires at least one argument');
357
- }
358
- // Pre-activate the library now so any tags it provides are available
359
- // to the rest of the parser. The render-time activation in LoadNode
360
- // is a no-op if the library is already active.
361
- const { activateLibrary, hasLibrary } = require('../libraries');
362
- for (const lib of parts) {
363
- if (hasLibrary(lib)) {
364
- activateLibrary(lib);
365
- }
366
- }
367
- return new LoadNode(parts);
368
- }
369
-
370
- function parseTemplatetag(tagContent, _parser) {
371
- const parts = tagContent.trim().split(/\s+/);
372
- // First part is the tag name, rest is the argument
373
- const token = parts.length > 1 ? parts.slice(1).join(' ') : parts[0];
374
- return new TemplatetagNode(token);
375
- }
376
-
377
- module.exports = {
378
- StaticNode,
379
- UrlNode,
380
- RegroupNode,
381
- SpacelessNode,
382
- CsrfTokenNode,
383
- CspNonceAttrNode,
384
- LoadNode,
385
- TemplatetagNode,
386
- WidthRatioNode,
387
- DebugNode,
388
- parsers: {
389
- static: parseStatic,
390
- url: parseUrl,
391
- regroup: parseRegroup,
392
- spaceless: parseSpaceless,
393
- csrf_token: parseCsrfToken,
394
- csp_nonce_attr: parseCspNonceAttr,
395
- load: parseLoad,
396
- templatetag: parseTemplatetag,
397
- widthratio: parseWidthRatio,
398
- debug: parseDebug
399
- }
400
- };
1
+ /**
2
+ * Utility template tags: static, url, regroup, spaceless.
3
+ */
4
+
5
+ // Helper to resolve expression values (literals, numbers, booleans, or context lookups)
6
+ function resolveValue(token, context) {
7
+ if (token === undefined || token === null) return '';
8
+ if (typeof token !== 'string') return token;
9
+ if (token === '') return '';
10
+ if ((token.startsWith('"') && token.endsWith('"')) || (token.startsWith('\'') && token.endsWith('\''))) {
11
+ return token.slice(1, -1);
12
+ }
13
+ if (token === 'true' || token === 'True') return true;
14
+ if (token === 'false' || token === 'False') return false;
15
+ if (token === 'none' || token === 'None' || token === 'null') return null;
16
+ // Numeric literal (integer or float)
17
+ if (/^-?\d+(\.\d+)?$/.test(token)) return Number(token);
18
+ // Otherwise treat as a context variable lookup
19
+ return context.get(token);
20
+ }
21
+
22
+ class StaticNode {
23
+ constructor(pathExpr) {
24
+ this.pathExpr = pathExpr;
25
+ }
26
+
27
+ render(context) {
28
+ const resolvedPath = resolveValue(this.pathExpr, context);
29
+
30
+ // Resolve static prefix
31
+ let prefix = '/static/';
32
+ if (context.options && context.options.staticUrl) {
33
+ prefix = context.options.staticUrl;
34
+ } else if (context.options && context.options.settings && context.options.settings.staticUrl) {
35
+ prefix = context.options.settings.staticUrl;
36
+ }
37
+
38
+ // Ensure double-slash doesn't occur and ends/starts correctly
39
+ const base = prefix.endsWith('/') ? prefix : prefix + '/';
40
+ const relative = (typeof resolvedPath === 'string' && resolvedPath.startsWith('/'))
41
+ ? resolvedPath.slice(1)
42
+ : String(resolvedPath);
43
+
44
+ return base + relative;
45
+ }
46
+ }
47
+
48
+ class UrlNode {
49
+ constructor(routeNameExpr, positionalArgs, kwargs) {
50
+ this.routeNameExpr = routeNameExpr;
51
+ this.positionalArgs = positionalArgs || [];
52
+ // Each kwarg is { name, valueExpr } where valueExpr is the raw
53
+ // expression token (may be a number, a quoted string, or a var).
54
+ this.kwargs = kwargs || [];
55
+ }
56
+
57
+ render(context) {
58
+ const routeName = resolveValue(this.routeNameExpr, context);
59
+ const resolvedPositional = this.positionalArgs.map(arg => resolveValue(arg, context));
60
+ const resolvedKwargs = {};
61
+ for (const kw of this.kwargs) {
62
+ resolvedKwargs[kw.name] = resolveValue(kw.valueExpr, context);
63
+ }
64
+ const hasKwargs = Object.keys(resolvedKwargs).length > 0;
65
+
66
+ // If an Express urlHelper is provided, call it. We pass positional
67
+ // args spread, and (only when kwargs are present) a kwargs object
68
+ // as the last argument. This keeps the common `{{ url 'r' 42 }}`
69
+ // case with a `(name, ...args) => string` helper simple.
70
+ if (context.options && typeof context.options.urlHelper === 'function') {
71
+ if (hasKwargs) {
72
+ return context.options.urlHelper(routeName, ...resolvedPositional, resolvedKwargs);
73
+ }
74
+ return context.options.urlHelper(routeName, ...resolvedPositional);
75
+ }
76
+
77
+ // Fallback URL builder: convert dotted route names into deep paths
78
+ // (e.g. "user.profile.posts.show" -> "/user/profile/posts/show")
79
+ // and append positional args. Kwargs are appended as query string.
80
+ const deepPath = String(routeName).split('.').map(seg => seg).join('/');
81
+ const parts = ['/' + deepPath, ...resolvedPositional
82
+ .filter(v => v !== '' && v !== null && v !== undefined)
83
+ .map(v => String(v))];
84
+ let url = parts.join('/');
85
+ if (hasKwargs) {
86
+ const qs = Object.keys(resolvedKwargs)
87
+ .filter(k => resolvedKwargs[k] !== undefined)
88
+ .map(k => `${encodeURIComponent(k)}=${encodeURIComponent(String(resolvedKwargs[k]))}`)
89
+ .join('&');
90
+ if (qs) url += '?' + qs;
91
+ }
92
+ return url;
93
+ }
94
+ }
95
+
96
+ class RegroupNode {
97
+ constructor(listPath, attr, targetName) {
98
+ this.listPath = listPath;
99
+ this.attr = attr;
100
+ this.targetName = targetName;
101
+ }
102
+
103
+ render(context) {
104
+ const list = context.get(this.listPath);
105
+ if (!Array.isArray(list)) {
106
+ context.scopes[0][this.targetName] = [];
107
+ return '';
108
+ }
109
+
110
+ const groups = [];
111
+ const groupMap = new Map();
112
+
113
+ for (const item of list) {
114
+ // Resolve attribute (support nested lookup on item)
115
+ let val = '';
116
+ if (item && typeof item === 'object') {
117
+ const parts = this.attr.split('.');
118
+ let current = item;
119
+ for (const part of parts) {
120
+ if (current && typeof current === 'object' && part in current) {
121
+ current = current[part];
122
+ } else {
123
+ current = undefined;
124
+ break;
125
+ }
126
+ }
127
+ val = current !== undefined ? current : '';
128
+ }
129
+
130
+ if (!groupMap.has(val)) {
131
+ const newGroup = { grouper: val, list: [] };
132
+ groupMap.set(val, newGroup);
133
+ groups.push(newGroup);
134
+ }
135
+ groupMap.get(val).list.push(item);
136
+ }
137
+
138
+ // Store in the current context scope
139
+ context.scopes[0][this.targetName] = groups;
140
+ return '';
141
+ }
142
+ }
143
+
144
+ class SpacelessNode {
145
+ constructor(body) {
146
+ this.body = body;
147
+ }
148
+
149
+ render(context) {
150
+ const content = this.body.map(n => n.render(context)).join('');
151
+ // Remove space between HTML tags
152
+ return content.replace(/>\s+</g, '><');
153
+ }
154
+ }
155
+
156
+ class CsrfTokenNode {
157
+ render(context) {
158
+ const token = context.get('csrf_token') || '';
159
+ // Escape the token for safe interpolation into an HTML attribute.
160
+ // CSRF tokens are typically alphanumeric, but defending against
161
+ // malicious or malformed token values is required to prevent
162
+ // attribute injection (" onerror=... etc).
163
+ const { escapeHtml, markSafe } = require('../security');
164
+ return markSafe(
165
+ `<input type="hidden" name="csrfmiddlewaretoken" value="${escapeHtml(String(token), true)}">`
166
+ );
167
+ }
168
+ }
169
+
170
+ class CspNonceAttrNode {
171
+ render(context) {
172
+ const nonce = context.get('csp_nonce') || '';
173
+ if (!nonce) return '';
174
+ // Escape the nonce for safe interpolation into an attribute value.
175
+ const { escapeHtml, markSafe } = require('../security');
176
+ return markSafe(`nonce="${escapeHtml(String(nonce), true)}"`);
177
+ }
178
+ }
179
+
180
+ // --- Tag Registry Parsers ---
181
+
182
+ function parseStatic(tagContent, _parser) {
183
+ // tagContent: "static 'css/style.css'"
184
+ const pathExpr = tagContent.slice(6).trim();
185
+ return new StaticNode(pathExpr);
186
+ }
187
+
188
+ function parseUrl(tagContent, _parser) {
189
+ // tagContent examples:
190
+ // "url 'route_name' arg1 arg2"
191
+ // "url 'route.name' 34"
192
+ // "url 'user.show' 34 email phone"
193
+ // "url 'user.show' userId=34 tab='posts'"
194
+ // "url 'user.show' 34 tab='posts'"
195
+ const content = tagContent.slice(3).trim();
196
+
197
+ // Tokenize respecting quoted strings.
198
+ const argRegex = /(".*?"|'.*?'|[^\s]+)/g;
199
+ const matches = content.match(argRegex) || [];
200
+
201
+ if (matches.length === 0) {
202
+ throw new Error('url tag requires a route name');
203
+ }
204
+ const routeNameExpr = matches[0];
205
+ const positionalArgs = [];
206
+ const kwargs = [];
207
+
208
+ for (let i = 1; i < matches.length; i++) {
209
+ const tok = matches[i];
210
+ // Detect `key=value` pattern (not a quoted string)
211
+ const isQuoted = (tok.startsWith('"') && tok.endsWith('"')) ||
212
+ (tok.startsWith('\'') && tok.endsWith('\''));
213
+ if (!isQuoted) {
214
+ const eq = tok.indexOf('=');
215
+ if (eq > 0) {
216
+ const name = tok.slice(0, eq);
217
+ const valueExpr = tok.slice(eq + 1);
218
+ kwargs.push({ name, valueExpr });
219
+ continue;
220
+ }
221
+ }
222
+ positionalArgs.push(tok);
223
+ }
224
+
225
+ return new UrlNode(routeNameExpr, positionalArgs, kwargs);
226
+ }
227
+
228
+ function parseRegroup(tagContent, _parser) {
229
+ // tagContent: "regroup people by gender as grouped"
230
+ const match = tagContent.match(/^regroup\s+(.+?)\s+by\s+(.+?)\s+as\s+(.+)$/);
231
+ if (!match) {
232
+ throw new Error(`Invalid regroup tag format: '${tagContent}'`);
233
+ }
234
+
235
+ const listPath = match[1].trim();
236
+ const attr = match[2].trim();
237
+ const targetName = match[3].trim();
238
+
239
+ return new RegroupNode(listPath, attr, targetName);
240
+ }
241
+
242
+ function parseSpaceless(tagContent, parser) {
243
+ const body = parser.parse(['endspaceless']);
244
+ const next = parser.peek();
245
+ if (next && next.type === 'block' && next.content.split(/\s+/)[0] === 'endspaceless') {
246
+ parser.advance();
247
+ }
248
+ return new SpacelessNode(body);
249
+ }
250
+
251
+ function parseCsrfToken(_tagContent, _parser) {
252
+ return new CsrfTokenNode();
253
+ }
254
+
255
+ class WidthRatioNode {
256
+ constructor(value, maxValue, maxWidth) {
257
+ this.value = parseFloat(value);
258
+ this.maxValue = parseFloat(maxValue);
259
+ this.maxWidth = parseInt(maxWidth, 10);
260
+ }
261
+
262
+ render(_context) {
263
+ if (!isFinite(this.value) || !isFinite(this.maxValue) || this.maxValue === 0) {
264
+ return '0';
265
+ }
266
+ const ratio = Math.floor((this.value / this.maxValue) * this.maxWidth);
267
+ return String(Math.max(0, Math.min(ratio, this.maxWidth)));
268
+ }
269
+ }
270
+
271
+ class DebugNode {
272
+ render(context) {
273
+ // Dump the current context (scopes) for debugging
274
+ const dump = {
275
+ scopes: context.scopes.map(s => {
276
+ if (s && typeof s === 'object') {
277
+ const out = {};
278
+ for (const k of Object.keys(s)) {
279
+ if (k.startsWith('__')) continue;
280
+ try {
281
+ const v = s[k];
282
+ out[k] = typeof v === 'function' ? '[function]' : v;
283
+ } catch {
284
+ out[k] = '[unreadable]';
285
+ }
286
+ }
287
+ return out;
288
+ }
289
+ return String(s);
290
+ })
291
+ };
292
+ const { escapeHtml, markSafe } = require('../security');
293
+ return markSafe('<pre>' + escapeHtml(JSON.stringify(dump, null, 2)) + '</pre>');
294
+ }
295
+ }
296
+
297
+ function parseWidthRatio(tagContent, _parser) {
298
+ // {% widthratio this_value max_value max_width %}
299
+ const parts = tagContent.replace(/^widthratio\s+/, '').trim().split(/\s+/);
300
+ if (parts.length < 3) {
301
+ throw new Error('\'widthratio\' tag requires 3 arguments: value, max_value, max_width');
302
+ }
303
+ return new WidthRatioNode(parts[0], parts[1], parts[2]);
304
+ }
305
+
306
+ function parseDebug(_tagContent, _parser) {
307
+ return new DebugNode();
308
+ }
309
+
310
+ function parseCspNonceAttr(_tagContent, _parser) {
311
+ return new CspNonceAttrNode();
312
+ }
313
+
314
+ class LoadNode {
315
+ constructor(libraries) {
316
+ this.libraries = Array.isArray(libraries) ? libraries : [libraries];
317
+ }
318
+
319
+ render(_context) {
320
+ const { activateLibrary, hasLibrary } = require('../libraries');
321
+ for (const lib of this.libraries) {
322
+ if (hasLibrary(lib)) {
323
+ activateLibrary(lib);
324
+ } else {
325
+ // Emit a comment-style warning for missing library
326
+ console.warn(`[miki-template] Library not found: '${lib}'`);
327
+ }
328
+ }
329
+ return '';
330
+ }
331
+ }
332
+
333
+ class TemplatetagNode {
334
+ constructor(token) {
335
+ this.token = token;
336
+ }
337
+
338
+ render(_context) {
339
+ const map = {
340
+ 'openblock': '{%',
341
+ 'closeblock': '%}',
342
+ 'openvariable': '{{',
343
+ 'closevariable': '}}',
344
+ 'openbrace': '{',
345
+ 'closebrace': '}',
346
+ 'opencomment': '{#',
347
+ 'closecomment': '#}'
348
+ };
349
+ return map[this.token] || this.token;
350
+ }
351
+ }
352
+
353
+ function parseLoad(tagContent, _parser) {
354
+ const parts = tagContent.trim().split(/\s+/);
355
+ if (parts.length === 0) {
356
+ throw new Error('\'load\' tag requires at least one argument');
357
+ }
358
+ // Pre-activate the library now so any tags it provides are available
359
+ // to the rest of the parser. The render-time activation in LoadNode
360
+ // is a no-op if the library is already active.
361
+ const { activateLibrary, hasLibrary } = require('../libraries');
362
+ for (const lib of parts) {
363
+ if (hasLibrary(lib)) {
364
+ activateLibrary(lib);
365
+ }
366
+ }
367
+ return new LoadNode(parts);
368
+ }
369
+
370
+ function parseTemplatetag(tagContent, _parser) {
371
+ const parts = tagContent.trim().split(/\s+/);
372
+ // First part is the tag name, rest is the argument
373
+ const token = parts.length > 1 ? parts.slice(1).join(' ') : parts[0];
374
+ return new TemplatetagNode(token);
375
+ }
376
+
377
+ module.exports = {
378
+ StaticNode,
379
+ UrlNode,
380
+ RegroupNode,
381
+ SpacelessNode,
382
+ CsrfTokenNode,
383
+ CspNonceAttrNode,
384
+ LoadNode,
385
+ TemplatetagNode,
386
+ WidthRatioNode,
387
+ DebugNode,
388
+ parsers: {
389
+ static: parseStatic,
390
+ url: parseUrl,
391
+ regroup: parseRegroup,
392
+ spaceless: parseSpaceless,
393
+ csrf_token: parseCsrfToken,
394
+ csp_nonce_attr: parseCspNonceAttr,
395
+ load: parseLoad,
396
+ templatetag: parseTemplatetag,
397
+ widthratio: parseWidthRatio,
398
+ debug: parseDebug
399
+ }
400
+ };