miki-template 1.2.0

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 (73) hide show
  1. package/.github/workflows/ci.yml +54 -0
  2. package/AGENT.md +71 -0
  3. package/API_REFERENCE.md +314 -0
  4. package/CHANGELOG.md +97 -0
  5. package/CODE_OF_CONDUCT.md +14 -0
  6. package/CONTRIBUTING.md +27 -0
  7. package/README.md +304 -0
  8. package/ROADMAP.md +40 -0
  9. package/benchmarks/report.json +17 -0
  10. package/benchmarks/run.js +49 -0
  11. package/benchmarks/templates/large.dtpl +7 -0
  12. package/benchmarks/templates/medium.dtpl +3 -0
  13. package/benchmarks/templates/small.dtpl +7 -0
  14. package/context/component.md +109 -0
  15. package/context/prd.md +131 -0
  16. package/context/project-structure.md +33 -0
  17. package/docs/README.md +18 -0
  18. package/docs/advanced_usage.md +71 -0
  19. package/docs/api.md +102 -0
  20. package/docs/filters.md +540 -0
  21. package/docs/installation.md +106 -0
  22. package/docs/overview.md +57 -0
  23. package/docs/partialdef.md +41 -0
  24. package/docs/security.md +27 -0
  25. package/docs/tags.md +610 -0
  26. package/docs/usage.md +599 -0
  27. package/eslint.config.mjs +34 -0
  28. package/miki-template-1.2.0.vsix +0 -0
  29. package/miki-template-extension/LICENSE +21 -0
  30. package/miki-template-extension/README.md +82 -0
  31. package/miki-template-extension/icon.png +0 -0
  32. package/miki-template-extension/icon.svg +10 -0
  33. package/miki-template-extension/package.json +46 -0
  34. package/miki-template-extension/snippets/miki-template.json +177 -0
  35. package/miki-template-extension/syntaxes/language-configuration.json +26 -0
  36. package/miki-template-extension/syntaxes/miki-template.tmLanguage.json +146 -0
  37. package/package.json +31 -0
  38. package/snippets/miki-template.json +177 -0
  39. package/src/asyncRender.js +21 -0
  40. package/src/cache.js +41 -0
  41. package/src/context.js +122 -0
  42. package/src/context_processors.js +41 -0
  43. package/src/esm.mjs +72 -0
  44. package/src/filters.js +527 -0
  45. package/src/i18n.js +171 -0
  46. package/src/index.js +454 -0
  47. package/src/lexer.js +92 -0
  48. package/src/libraries.js +240 -0
  49. package/src/parser.js +250 -0
  50. package/src/security.js +51 -0
  51. package/src/tags/control.js +591 -0
  52. package/src/tags/helpers.js +27 -0
  53. package/src/tags/i18n.js +230 -0
  54. package/src/tags/inheritance.js +216 -0
  55. package/src/tags/registry.js +18 -0
  56. package/src/tags/util.js +322 -0
  57. package/src/types.d.ts +107 -0
  58. package/syntaxes/language-configuration.json +26 -0
  59. package/syntaxes/miki-template.tmLanguage.json +146 -0
  60. package/tests/asyncRender.test.js +17 -0
  61. package/tests/base.html +6 -0
  62. package/tests/child.html +3 -0
  63. package/tests/context_processors.test.js +13 -0
  64. package/tests/esm.test.mjs +26 -0
  65. package/tests/filters.test.js +99 -0
  66. package/tests/include_security.test.js +9 -0
  67. package/tests/lexer.test.js +45 -0
  68. package/tests/parser.test.js +55 -0
  69. package/tests/partial.html +1 -0
  70. package/tests/partialdef.test.js +40 -0
  71. package/tests/production_checks.js +57 -0
  72. package/tests/security.test.js +28 -0
  73. package/tests/tags.test.js +203 -0
@@ -0,0 +1,240 @@
1
+ /**
2
+ * Plugin/filter library system.
3
+ *
4
+ * A "library" is a JavaScript object exporting:
5
+ * { tags?: { [name]: parserFn }, filters?: { [name]: filterFn } }
6
+ *
7
+ * Libraries can be:
8
+ * - Built-in (e.g. 'i18n', 'cache', 'humanize', 'markdown')
9
+ * - Custom user-defined via `registerLibrary(name, lib)`
10
+ * - Loaded from disk via `registerLibraryFromPath(name, path)`
11
+ *
12
+ * Once registered, a library is activated in templates via:
13
+ * {% load library_name %}
14
+ * {% load i18n cache humanize %}
15
+ */
16
+ const fs = require('fs');
17
+ const path = require('path');
18
+
19
+ const libraries = new Map(); // Map<name, libraryDef>
20
+
21
+ /**
22
+ * Register a library.
23
+ *
24
+ * registerLibrary('markdown', {
25
+ * tags: { markdown: parseMarkdown },
26
+ * filters: { markdown: renderMarkdown }
27
+ * });
28
+ */
29
+ function registerLibrary(name, def) {
30
+ if (!name || typeof name !== 'string') {
31
+ throw new TypeError('Library name must be a non-empty string');
32
+ }
33
+ if (!def || typeof def !== 'object') {
34
+ throw new TypeError(`Library '${name}' definition must be an object`);
35
+ }
36
+ libraries.set(name, {
37
+ tags: def.tags || {},
38
+ filters: def.filters || {},
39
+ helpers: def.helpers || {}
40
+ });
41
+ }
42
+
43
+ /** Unregister a library or all libraries. */
44
+ function unregisterLibrary(name) {
45
+ if (!name) {
46
+ libraries.clear();
47
+ return;
48
+ }
49
+ libraries.delete(name);
50
+ }
51
+
52
+ /** Get a registered library by name. */
53
+ function getLibrary(name) {
54
+ return libraries.get(name);
55
+ }
56
+
57
+ /** List all registered library names. */
58
+ function getLibraryNames() {
59
+ return Array.from(libraries.keys());
60
+ }
61
+
62
+ /**
63
+ * Load a library from a JavaScript file on disk.
64
+ * The file must be a CommonJS module exporting `{ tags, filters, helpers }`.
65
+ */
66
+ function registerLibraryFromPath(name, filePath, options = {}) {
67
+ const absolutePath = path.isAbsolute(filePath)
68
+ ? filePath
69
+ : path.resolve(options.baseDir || process.cwd(), filePath);
70
+ if (!fs.existsSync(absolutePath)) {
71
+ throw new Error(`Library file not found: ${absolutePath}`);
72
+ }
73
+ // Defensive: restrict to .js/.cjs/.mjs files
74
+ const ext = path.extname(absolutePath).toLowerCase();
75
+ if (ext !== '.js' && ext !== '.cjs' && ext !== '.mjs') {
76
+ throw new Error(`Library file extension '${ext}' is not allowed`);
77
+ }
78
+ // Clear require cache if not pinned
79
+ if (!options.pinned) {
80
+ delete require.cache[require.resolve(absolutePath)];
81
+ }
82
+ const def = require(absolutePath);
83
+ registerLibrary(name, def);
84
+ return def;
85
+ }
86
+
87
+ /**
88
+ * Apply the tags, filters, and helpers from a library to the runtime registries.
89
+ */
90
+ function activateLibrary(name) {
91
+ const lib = libraries.get(name);
92
+ if (!lib) {
93
+ throw new Error(`Library not found: '${name}'`);
94
+ }
95
+ const { registerTag, registerFilter, registerHelper } = require('./index');
96
+ for (const [tagName, parserFn] of Object.entries(lib.tags || {})) {
97
+ registerTag(tagName, parserFn);
98
+ }
99
+ for (const [filterName, filterFn] of Object.entries(lib.filters || {})) {
100
+ registerFilter(filterName, filterFn);
101
+ }
102
+ for (const [helperName, helperFn] of Object.entries(lib.helpers || {})) {
103
+ registerHelper(helperName, helperFn);
104
+ }
105
+ }
106
+
107
+ /**
108
+ * Check if a library is registered.
109
+ */
110
+ function hasLibrary(name) {
111
+ return libraries.has(name);
112
+ }
113
+
114
+ // --- Built-in libraries ---
115
+
116
+ /** Humanize: nice-looking text formatting filters. */
117
+ registerLibrary('humanize', {
118
+ filters: {
119
+ intcomma: (val) => {
120
+ const parts = String(val === null || val === undefined ? '' : val).split('.');
121
+ parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ',');
122
+ return parts.join('.');
123
+ },
124
+ intword: (val) => {
125
+ const n = parseFloat(val);
126
+ if (isNaN(n)) return String(val);
127
+ const abs = Math.abs(n);
128
+ if (abs >= 1e9) return (n / 1e9).toFixed(1).replace(/\.0$/, '') + ' billion';
129
+ if (abs >= 1e6) return (n / 1e6).toFixed(1).replace(/\.0$/, '') + ' million';
130
+ if (abs >= 1e3) return (n / 1e3).toFixed(1).replace(/\.0$/, '') + ' thousand';
131
+ return String(n);
132
+ },
133
+ apnumber: (val) => {
134
+ const n = parseInt(val, 10);
135
+ const words = ['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten',
136
+ 'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen'];
137
+ if (!isNaN(n) && n >= 0 && n < words.length) return words[n];
138
+ return String(val);
139
+ },
140
+ ordinal: (val) => {
141
+ const n = parseInt(val, 10);
142
+ if (isNaN(n)) return String(val);
143
+ const s = ['th', 'st', 'nd', 'rd'];
144
+ const v = n % 100;
145
+ return n + (s[(v - 20) % 10] || s[v] || s[0]);
146
+ },
147
+ naturalday: (val) => {
148
+ const d = new Date(val);
149
+ if (isNaN(d.getTime())) return String(val);
150
+ const today = new Date();
151
+ const yesterday = new Date(today);
152
+ yesterday.setDate(today.getDate() - 1);
153
+ const tomorrow = new Date(today);
154
+ tomorrow.setDate(today.getDate() + 1);
155
+ const sameDay = (a, b) =>
156
+ a.getFullYear() === b.getFullYear() &&
157
+ a.getMonth() === b.getMonth() &&
158
+ a.getDate() === b.getDate();
159
+ if (sameDay(d, today)) return 'today';
160
+ if (sameDay(d, yesterday)) return 'yesterday';
161
+ if (sameDay(d, tomorrow)) return 'tomorrow';
162
+ return String(val);
163
+ }
164
+ }
165
+ });
166
+
167
+ /** Cache: cache expensive template fragment results. */
168
+ registerLibrary('cache', {
169
+ tags: {
170
+ cache: (tagContent, parser) => {
171
+ // {% cache timeout key1 key2 ... %}...{% endcache %}
172
+ const rest = tagContent.slice(5).trim();
173
+ const tokens = rest.split(/\s+/);
174
+ const timeout = parseInt(tokens[0], 10) || 0;
175
+ const key = tokens.slice(1).join(':') || 'default';
176
+ const body = parser.parse(['endcache']);
177
+ const next = parser.peek();
178
+ if (next && next.type === 'block' && next.content.split(/\s+/)[0] === 'endcache') {
179
+ parser.advance();
180
+ }
181
+ return {
182
+ render(context) {
183
+ const ctx = context;
184
+ const fullKey = `cache:${key}`;
185
+ if (ctx.cacheStore && ctx.cacheStore.has(fullKey)) {
186
+ const entry = ctx.cacheStore.get(fullKey);
187
+ if (Date.now() - entry.time < timeout * 1000) {
188
+ return entry.value;
189
+ }
190
+ }
191
+ const value = body.map(n => n.render(context)).join('');
192
+ if (ctx.cacheStore) {
193
+ ctx.cacheStore.set(fullKey, { time: Date.now(), value });
194
+ }
195
+ return value;
196
+ }
197
+ };
198
+ }
199
+ }
200
+ });
201
+
202
+ /** Lorem: generate placeholder text. */
203
+ registerLibrary('lorem', {
204
+ filters: {
205
+ lorem: (val, arg) => {
206
+ const text = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.';
207
+ let n = parseInt(arg, 10);
208
+ if (isNaN(n)) n = 5;
209
+ if (n < 1) n = 1;
210
+ if (n > 100) n = 100;
211
+ const words = text.split(' ');
212
+ let result = [];
213
+ for (let i = 0; i < n; i++) {
214
+ result.push(words[i % words.length]);
215
+ }
216
+ return result.join(' ');
217
+ }
218
+ }
219
+ });
220
+
221
+ /** Static: additional static-file helpers. */
222
+ registerLibrary('static', {
223
+ filters: {
224
+ static: (val) => {
225
+ // Returns the value prefixed with the staticUrl (configured at compile time)
226
+ return val; // Implementation lives in the {% static %} tag
227
+ }
228
+ }
229
+ });
230
+
231
+ module.exports = {
232
+ registerLibrary,
233
+ unregisterLibrary,
234
+ getLibrary,
235
+ getLibraryNames,
236
+ hasLibrary,
237
+ registerLibraryFromPath,
238
+ activateLibrary,
239
+ libraries
240
+ };
package/src/parser.js ADDED
@@ -0,0 +1,250 @@
1
+ /**
2
+ * Parser converting token stream into AST Nodes.
3
+ */
4
+ const { escapeHtml, isSafe } = require('./security');
5
+ const filtersModule = require('./filters');
6
+
7
+ class TextNode {
8
+ constructor(content) {
9
+ this.content = content;
10
+ }
11
+
12
+ render(_context) {
13
+ return this.content;
14
+ }
15
+ }
16
+
17
+ class VariableNode {
18
+ constructor(varPath, filters, isLiteral = false, literalValue = null) {
19
+ this.varPath = varPath;
20
+ this.filters = filters;
21
+ this.isLiteral = isLiteral;
22
+ this.literalValue = literalValue;
23
+ }
24
+
25
+ render(context) {
26
+ let val = this.isLiteral ? this.literalValue : context.get(this.varPath);
27
+
28
+ for (const filterInfo of this.filters) {
29
+ const filterFn = filtersModule.getFilter(filterInfo.name);
30
+ if (!filterFn) {
31
+ throw new Error(`Unknown filter: '${filterInfo.name}'`);
32
+ }
33
+
34
+ let argVal = undefined;
35
+ if (filterInfo.arg) {
36
+ if (filterInfo.arg.type === 'literal') {
37
+ argVal = filterInfo.arg.value;
38
+ } else if (filterInfo.arg.type === 'variable') {
39
+ argVal = context.get(filterInfo.arg.value);
40
+ }
41
+ }
42
+
43
+ val = filterFn(val, argVal);
44
+ }
45
+
46
+ // Auto-escape logic – skip escaping if value is marked safe
47
+ if (context.autoescape && !isSafe(val)) {
48
+ return escapeHtml(val);
49
+ }
50
+
51
+ return val === null || val === undefined ? '' : String(val);
52
+ }
53
+ }
54
+
55
+ /**
56
+ * Parses a variable expression including filters and arguments.
57
+ * E.g., user.name|lower|default:"Guest"
58
+ */
59
+ function parseVariableExpression(expr) {
60
+ let idx = 0;
61
+ const len = expr.length;
62
+
63
+ function skipWhitespace() {
64
+ while (idx < len && /\s/.test(expr[idx])) {
65
+ idx++;
66
+ }
67
+ }
68
+
69
+ let varPath = '';
70
+ let isLiteral = false;
71
+ let literalValue = null;
72
+
73
+ // Check for string literal as base value
74
+ if (idx < len && (expr[idx] === '"' || expr[idx] === '\'')) {
75
+ const quote = expr[idx];
76
+ idx++;
77
+ let strVal = '';
78
+ while (idx < len && expr[idx] !== quote) {
79
+ if (expr[idx] === '\\' && idx + 1 < len) {
80
+ idx++;
81
+ }
82
+ strVal += expr[idx];
83
+ idx++;
84
+ }
85
+ idx++; // Skip closing quote
86
+ isLiteral = true;
87
+ literalValue = strVal;
88
+ skipWhitespace();
89
+ }
90
+
91
+ // Parse main variable path
92
+ if (!isLiteral) {
93
+ while (idx < len && expr[idx] !== '|') {
94
+ varPath += expr[idx];
95
+ idx++;
96
+ }
97
+ varPath = varPath.trim();
98
+ }
99
+
100
+ const filters = [];
101
+ while (idx < len) {
102
+ if (expr[idx] === '|') {
103
+ idx++; // Skip '|'
104
+ skipWhitespace();
105
+
106
+ // Read filter name
107
+ let filterName = '';
108
+ while (idx < len && expr[idx] !== ':' && expr[idx] !== '|' && !/\s/.test(expr[idx])) {
109
+ filterName += expr[idx];
110
+ idx++;
111
+ }
112
+
113
+ skipWhitespace();
114
+ let arg = null;
115
+
116
+ if (idx < len && expr[idx] === ':') {
117
+ idx++; // Skip ':'
118
+ skipWhitespace();
119
+
120
+ // Parse argument (string literal, number, boolean, null, or variable)
121
+ if (expr[idx] === '"' || expr[idx] === '\'') {
122
+ const quote = expr[idx];
123
+ idx++; // Skip opening quote
124
+ let argVal = '';
125
+ while (idx < len && expr[idx] !== quote) {
126
+ if (expr[idx] === '\\') {
127
+ idx++;
128
+ }
129
+ if (idx < len) {
130
+ argVal += expr[idx];
131
+ idx++;
132
+ }
133
+ }
134
+ idx++; // Skip closing quote
135
+ arg = { type: 'literal', value: argVal };
136
+ } else {
137
+ // Read unquoted token
138
+ let argVal = '';
139
+ while (idx < len && expr[idx] !== '|' && !/\s/.test(expr[idx])) {
140
+ argVal += expr[idx];
141
+ idx++;
142
+ }
143
+ argVal = argVal.trim();
144
+
145
+ // Type coercion
146
+ if (!isNaN(argVal) && argVal !== '') {
147
+ arg = { type: 'literal', value: Number(argVal) };
148
+ } else if (argVal === 'true') {
149
+ arg = { type: 'literal', value: true };
150
+ } else if (argVal === 'false') {
151
+ arg = { type: 'literal', value: false };
152
+ } else if (argVal === 'none' || argVal === 'None' || argVal === 'null') {
153
+ arg = { type: 'literal', value: null };
154
+ } else {
155
+ // Variable lookup
156
+ arg = { type: 'variable', value: argVal };
157
+ }
158
+ }
159
+ }
160
+
161
+ filters.push({ name: filterName, arg });
162
+ skipWhitespace();
163
+ } else {
164
+ idx++;
165
+ }
166
+ }
167
+
168
+ return { varPath, filters, isLiteral, literalValue };
169
+ }
170
+
171
+ class Parser {
172
+ // Existing constructor and methods remain unchanged
173
+ /**
174
+ * Parse tokens until a specific end tag, consuming the end tag token.
175
+ * @param {string} endTag - Tag name to stop at (e.g., 'endsleep').
176
+ * @returns {Array} Parsed nodes.
177
+ */
178
+ parseUntilTag(endTag) {
179
+ const nodes = this.parse([endTag]);
180
+ // Advance past the end tag token if present
181
+ const next = this.peek();
182
+ if (next && next.type === 'block' && next.content.split(/\s+/)[0] === endTag) {
183
+ this.advance();
184
+ }
185
+ return nodes;
186
+ }
187
+
188
+ constructor(tokens, tagRegistry = {}) {
189
+ this.tokens = tokens;
190
+ this.index = 0;
191
+ this.tagRegistry = tagRegistry;
192
+ }
193
+
194
+ /**
195
+ * Parses tokens into AST nodes until one of the tags in untilTags is encountered.
196
+ */
197
+ parse(untilTags = []) {
198
+ const nodes = [];
199
+ while (this.index < this.tokens.length) {
200
+ const token = this.tokens[this.index];
201
+
202
+ if (token.type === 'text') {
203
+ nodes.push(new TextNode(token.content));
204
+ this.index++;
205
+ } else if (token.type === 'var') {
206
+ const parsed = parseVariableExpression(token.content);
207
+ nodes.push(new VariableNode(parsed.varPath, parsed.filters, parsed.isLiteral, parsed.literalValue));
208
+ this.index++;
209
+ } else if (token.type === 'block') {
210
+ const parts = token.content.split(/\s+/);
211
+ const tagName = parts[0];
212
+
213
+ // Stop parsing if we hit a stop tag
214
+ if (untilTags.includes(tagName)) {
215
+ break;
216
+ }
217
+
218
+ this.index++; // Consume block token
219
+
220
+ const tagParser = this.tagRegistry[tagName];
221
+ if (!tagParser) {
222
+ throw new Error(`Unknown template tag: '${tagName}'`);
223
+ }
224
+
225
+ const node = tagParser(token.content, this);
226
+ nodes.push(node);
227
+ }
228
+ }
229
+ // If we were looking for specific end tags but didn't find them, throw
230
+ if (untilTags.length > 0 && this.index >= this.tokens.length) {
231
+ throw new Error(`Unexpected end of template - expected one of: ${untilTags.map(t => '{% ' + t + ' %}').join(', ')}`);
232
+ }
233
+ return nodes;
234
+ }
235
+
236
+ peek() {
237
+ return this.tokens[this.index];
238
+ }
239
+
240
+ advance() {
241
+ this.index++;
242
+ }
243
+ }
244
+
245
+ module.exports = {
246
+ Parser,
247
+ TextNode,
248
+ VariableNode,
249
+ parseVariableExpression
250
+ };
@@ -0,0 +1,51 @@
1
+ /**
2
+ * Security and HTML auto-escaping mechanisms.
3
+ */
4
+ const he = require('he');
5
+
6
+ class SafeString {
7
+ constructor(value) {
8
+ this.value = value === null || value === undefined ? '' : String(value);
9
+ }
10
+
11
+ toString() {
12
+ return this.value;
13
+ }
14
+ }
15
+
16
+ /**
17
+ * Mark a string as safe so it is not auto-escaped during rendering.
18
+ */
19
+ function markSafe(value) {
20
+ if (value instanceof SafeString) {
21
+ return value;
22
+ }
23
+ return new SafeString(value);
24
+ }
25
+
26
+ /**
27
+ * Check if a value is marked safe.
28
+ */
29
+ function isSafe(value) {
30
+ return value instanceof SafeString;
31
+ }
32
+
33
+ /**
34
+ * Escape a string's HTML special characters unless it is marked safe.
35
+ */
36
+ function escapeHtml(value) {
37
+ if (value instanceof SafeString) {
38
+ return value.toString();
39
+ }
40
+
41
+ const str = value === null || value === undefined ? '' : String(value);
42
+ // We use he.escape to convert <, >, &, ", ', etc. to entities
43
+ return he.escape(str);
44
+ }
45
+
46
+ module.exports = {
47
+ SafeString,
48
+ markSafe,
49
+ isSafe,
50
+ escapeHtml
51
+ };