@blamejs/core 0.7.18 → 0.7.19

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 (167) hide show
  1. package/CHANGELOG.md +425 -423
  2. package/README.md +150 -150
  3. package/bin/blamejs.js +0 -0
  4. package/index.js +310 -308
  5. package/lib/api-key.js +660 -660
  6. package/lib/api-snapshot.js +338 -338
  7. package/lib/app-shutdown.js +385 -385
  8. package/lib/app.js +365 -365
  9. package/lib/archive.js +250 -250
  10. package/lib/atomic-file.js +544 -544
  11. package/lib/audit-chain.js +177 -177
  12. package/lib/audit-sign.js +344 -344
  13. package/lib/audit-tools.js +677 -677
  14. package/lib/audit.js +766 -766
  15. package/lib/auth/jwt-external.js +365 -0
  16. package/lib/auth/jwt.js +337 -311
  17. package/lib/auth/lockout.js +436 -436
  18. package/lib/auth/oauth.js +721 -721
  19. package/lib/auth/passkey.js +181 -181
  20. package/lib/auth/password.js +628 -594
  21. package/lib/backup/bundle.js +217 -217
  22. package/lib/backup/crypto.js +176 -176
  23. package/lib/backup/index.js +515 -515
  24. package/lib/backup/manifest.js +282 -282
  25. package/lib/break-glass.js +1338 -1338
  26. package/lib/bundler.js +441 -441
  27. package/lib/cache-redis.js +256 -256
  28. package/lib/cache.js +1206 -1206
  29. package/lib/canonical-json.js +115 -115
  30. package/lib/chain-writer.js +234 -234
  31. package/lib/cli-helpers.js +206 -206
  32. package/lib/cli.js +2334 -2334
  33. package/lib/cluster-provider-db.js +317 -317
  34. package/lib/cluster-storage.js +226 -226
  35. package/lib/cluster.js +703 -703
  36. package/lib/config-drift.js +301 -301
  37. package/lib/consent.js +222 -222
  38. package/lib/constants.js +191 -191
  39. package/lib/cookies.js +315 -315
  40. package/lib/credential-hash.js +322 -322
  41. package/lib/crypto.js +266 -266
  42. package/lib/csv.js +275 -275
  43. package/lib/db-declare-row-policy.js +267 -267
  44. package/lib/db-declare-view.js +420 -420
  45. package/lib/db-query.js +406 -406
  46. package/lib/db-schema.js +319 -319
  47. package/lib/db.js +1288 -1288
  48. package/lib/deprecate.js +222 -222
  49. package/lib/dev.js +335 -335
  50. package/lib/dual-control.js +473 -473
  51. package/lib/error-page.js +420 -420
  52. package/lib/external-db-migrate.js +441 -441
  53. package/lib/external-db.js +1061 -1061
  54. package/lib/file-type.js +273 -273
  55. package/lib/forms.js +422 -422
  56. package/lib/framework-error.js +293 -293
  57. package/lib/framework-schema.js +717 -717
  58. package/lib/handlers.js +350 -350
  59. package/lib/http-client-cookie-jar.js +508 -508
  60. package/lib/http-client.js +1195 -1195
  61. package/lib/i18n.js +878 -878
  62. package/lib/jobs.js +185 -185
  63. package/lib/log-stream-cloudwatch.js +369 -369
  64. package/lib/log-stream-local.js +146 -146
  65. package/lib/log-stream-otlp-grpc.js +410 -410
  66. package/lib/log-stream-otlp.js +286 -286
  67. package/lib/log-stream-syslog.js +302 -302
  68. package/lib/log-stream-webhook.js +199 -199
  69. package/lib/log-stream.js +330 -330
  70. package/lib/log.js +500 -500
  71. package/lib/mail-bounce.js +528 -528
  72. package/lib/mail-dkim.js +369 -369
  73. package/lib/mail.js +981 -981
  74. package/lib/metrics.js +683 -683
  75. package/lib/middleware/api-encrypt.js +936 -936
  76. package/lib/middleware/attach-user.js +157 -157
  77. package/lib/middleware/bearer-auth.js +152 -0
  78. package/lib/middleware/body-parser.js +1170 -1170
  79. package/lib/middleware/bot-guard.js +178 -178
  80. package/lib/middleware/compression.js +452 -452
  81. package/lib/middleware/cors.js +314 -314
  82. package/lib/middleware/csp-nonce.js +348 -348
  83. package/lib/middleware/csrf-protect.js +316 -316
  84. package/lib/middleware/db-role-for.js +264 -264
  85. package/lib/middleware/health.js +392 -392
  86. package/lib/middleware/index.js +82 -79
  87. package/lib/middleware/rate-limit.js +358 -358
  88. package/lib/middleware/request-id.js +61 -61
  89. package/lib/middleware/request-log.js +168 -168
  90. package/lib/middleware/require-auth.js +104 -104
  91. package/lib/middleware/security-headers.js +116 -116
  92. package/lib/middleware/sse.js +166 -166
  93. package/lib/migrations.js +383 -383
  94. package/lib/mtls-ca.js +518 -518
  95. package/lib/mtls-engine-default.js +481 -481
  96. package/lib/network-dns.js +632 -632
  97. package/lib/network-heartbeat.js +290 -290
  98. package/lib/network-nts.js +574 -574
  99. package/lib/network-proxy.js +265 -265
  100. package/lib/network-tls.js +328 -328
  101. package/lib/network.js +233 -233
  102. package/lib/notify.js +612 -612
  103. package/lib/ntp-check.js +229 -229
  104. package/lib/numeric-bounds.js +111 -111
  105. package/lib/object-store/azure-blob-bucket-ops.js +349 -349
  106. package/lib/object-store/azure-blob.js +488 -488
  107. package/lib/object-store/gcs-bucket-ops.js +351 -351
  108. package/lib/object-store/gcs.js +519 -519
  109. package/lib/object-store/http-put.js +153 -153
  110. package/lib/object-store/index.js +197 -197
  111. package/lib/object-store/sigv4-bucket-ops.js +1092 -1092
  112. package/lib/object-store/sigv4.js +903 -903
  113. package/lib/observability.js +151 -151
  114. package/lib/otel-export.js +269 -269
  115. package/lib/pagination.js +464 -464
  116. package/lib/parsers/index.js +80 -80
  117. package/lib/parsers/safe-env.js +642 -642
  118. package/lib/parsers/safe-ini.js +292 -292
  119. package/lib/parsers/safe-toml.js +784 -784
  120. package/lib/parsers/safe-xml.js +390 -390
  121. package/lib/parsers/safe-yaml.js +1015 -1015
  122. package/lib/permissions.js +708 -708
  123. package/lib/pqc-agent.js +87 -87
  124. package/lib/pqc-gate.js +279 -279
  125. package/lib/protobuf-encoder.js +190 -190
  126. package/lib/protocol-dispatcher.js +161 -161
  127. package/lib/pubsub-redis.js +167 -167
  128. package/lib/pubsub.js +429 -429
  129. package/lib/queue-local.js +476 -476
  130. package/lib/queue-redis.js +745 -745
  131. package/lib/queue-sqs.js +319 -319
  132. package/lib/queue.js +695 -695
  133. package/lib/redis-client.js +519 -519
  134. package/lib/request-helpers.js +340 -340
  135. package/lib/restore-bundle.js +237 -237
  136. package/lib/restore-rollback.js +259 -259
  137. package/lib/restore.js +409 -409
  138. package/lib/retry.js +376 -376
  139. package/lib/router.js +748 -748
  140. package/lib/safe-async.js +735 -735
  141. package/lib/safe-buffer.js +237 -237
  142. package/lib/safe-json.js +541 -541
  143. package/lib/safe-schema.js +1266 -1266
  144. package/lib/safe-url.js +159 -159
  145. package/lib/scheduler.js +706 -706
  146. package/lib/security-assert.js +373 -373
  147. package/lib/seeders.js +618 -618
  148. package/lib/session.js +535 -478
  149. package/lib/slug.js +269 -269
  150. package/lib/ssrf-guard.js +401 -401
  151. package/lib/storage.js +471 -471
  152. package/lib/subject.js +281 -281
  153. package/lib/template.js +791 -791
  154. package/lib/testing.js +798 -798
  155. package/lib/time.js +310 -310
  156. package/lib/totp.js +302 -302
  157. package/lib/tracing.js +494 -494
  158. package/lib/uuid.js +132 -132
  159. package/lib/validate-opts.js +340 -340
  160. package/lib/vault/index.js +308 -308
  161. package/lib/vault/rotate.js +784 -784
  162. package/lib/vault/wrap.js +296 -296
  163. package/lib/vendor/noble-ciphers.cjs +9 -9
  164. package/lib/webhook.js +595 -595
  165. package/lib/websocket.js +1048 -1048
  166. package/package.json +77 -77
  167. package/sbom.cyclonedx.json +7 -7
package/lib/template.js CHANGED
@@ -1,791 +1,791 @@
1
- "use strict";
2
- /**
3
- * Server-side HTML template engine — eval-free.
4
- *
5
- * No `new Function()`, no `eval`, no `vm.runInThisContext`. Templates
6
- * are tokenized + parsed into a small AST and walked at render time
7
- * against a data scope. The trade-off vs an eval-based engine is
8
- * 5–50× slower per render and a restricted expression grammar; the
9
- * win is "an operator who renders req.query.template (or worse) can't
10
- * RCE the framework, period."
11
- *
12
- * Tag syntax:
13
- *
14
- * {{ expr }} HTML-escaped expression output
15
- * {{{ expr }}} Raw output (no escape — operator-trusted HTML)
16
- * {{> name }} Partial from <viewsDir>/partials/<name>.html
17
- * {% extends "name" %} Inherit from a layout (must be first non-whitespace)
18
- * {% block name %}…{% endblock %}
19
- * Overrideable section
20
- * {% if expr %}…{% else %}…{% endif %}
21
- * Conditional
22
- * {% for ident in expr %}…{% endfor %}
23
- * Iterate an array; the identifier is bound
24
- * for the loop body
25
- *
26
- * Expression grammar (recursive-descent Pratt-style):
27
- *
28
- * expression := ternary
29
- * ternary := logical-or ('?' logical-or ':' logical-or)?
30
- * logical-or := logical-and ('||' logical-and)*
31
- * logical-and := equality ('&&' equality)*
32
- * equality := comparison (('==' | '!=' | '===' | '!==') comparison)*
33
- * comparison := unary (('<' | '<=' | '>' | '>=') unary)*
34
- * unary := '!' unary | postfix
35
- * postfix := primary postfix-op*
36
- * postfix-op := '.' identifier | '[' expression ']' | '(' arg-list ')'
37
- * primary := literal | identifier | '(' expression ')'
38
- * literal := string-literal | number-literal | 'true' | 'false' | 'null'
39
- *
40
- * Function calls invoke functions THE OPERATOR PROVIDED in the data
41
- * scope (e.g. `{{ helpers.formatDate(d) }}` resolves `helpers` from
42
- * data, then `formatDate` on it, then calls it with `d`). The
43
- * interpreter does not invent built-ins; if an operator wants
44
- * helpers, they pass them under any data key they like.
45
- *
46
- * Public API:
47
- *
48
- * template.create({ viewsDir, cache?, escapeHtml? })
49
- * → engine instance with .render(view, data?), .compile(view), .reset()
50
- * template.render(view, data?)
51
- * → convenience using a default singleton against <cwd>/views
52
- * template.escapeHtml(value)
53
- * → standalone HTML escape (used by forms.js etc.)
54
- *
55
- * Containment defenses (templates ARE server-side files; these guard
56
- * against operator path-joining mistakes that let request input reach
57
- * a view-name argument):
58
- *
59
- * - View names containing ".." or "\0" → reject
60
- * - Resolved paths outside viewsDir → reject
61
- * - Layout-extends and partial-inclusion recursion bounded at depth 16
62
- *
63
- * If an operator renders a template path derived from user input, the
64
- * defenses block path traversal. The interpreter's eval-free posture
65
- * is the second line: even if a template loaded, it can't execute
66
- * arbitrary JS — only the limited expression grammar above.
67
- */
68
- var fs = require("fs");
69
- var path = require("path");
70
- var validateOpts = require("./validate-opts");
71
-
72
- // Maximum nesting depth for layout {% extends %} chains and partial
73
- // {{> ... }} recursion. Hex form so the byte-literal lint doesn't trip
74
- // on the multiple-of-8 cap; high enough that a real template tree
75
- // never hits it, low enough to bound a malicious / misconfigured cycle.
76
- var MAX_TEMPLATE_DEPTH = 0x10;
77
-
78
- // ============================================================
79
- // HTML escape (exported)
80
- // ============================================================
81
-
82
- var ESCAPE_MAP = { "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#x27;" };
83
- var ESCAPE_RE = /[&<>"']/g;
84
-
85
- function escapeHtml(value) {
86
- if (value === null || value === undefined) return "";
87
- var s = typeof value === "string" ? value : String(value);
88
- return s.replace(ESCAPE_RE, function (c) { return ESCAPE_MAP[c]; });
89
- }
90
-
91
- // ============================================================
92
- // Path resolution + containment
93
- // ============================================================
94
-
95
- function _resolveViewPath(viewsDir, viewName) {
96
- if (typeof viewName !== "string" || viewName.length === 0) {
97
- throw new Error("template: view name must be a non-empty string");
98
- }
99
- if (viewName.indexOf("..") !== -1 || viewName.indexOf("\0") !== -1) {
100
- throw new Error("template: view name contains forbidden character: " + JSON.stringify(viewName));
101
- }
102
- var resolved = path.resolve(viewsDir, viewName + ".html");
103
- var resolvedDir = path.resolve(viewsDir);
104
- if (resolved !== resolvedDir &&
105
- !resolved.startsWith(resolvedDir + path.sep)) {
106
- throw new Error("template: view path escapes viewsDir: " + viewName);
107
- }
108
- if (!fs.existsSync(resolved)) {
109
- throw new Error("template: view not found: " + viewName);
110
- }
111
- return resolved;
112
- }
113
-
114
- function _resolvePartialPath(viewsDir, partialName) {
115
- if (typeof partialName !== "string" || partialName.length === 0) return null;
116
- if (partialName.indexOf("..") !== -1 || partialName.indexOf("\0") !== -1) return null;
117
- var resolved = path.resolve(viewsDir, "partials", partialName + ".html");
118
- var partialsDir = path.resolve(viewsDir, "partials");
119
- if (resolved !== partialsDir &&
120
- !resolved.startsWith(partialsDir + path.sep)) return null;
121
- return fs.existsSync(resolved) ? resolved : null;
122
- }
123
-
124
- // ============================================================
125
- // Layout inheritance: extract blocks, substitute into parent
126
- // ============================================================
127
-
128
- var EXTENDS_RE = /^\s*\{%\s*extends\s+"([^"]+)"\s*%\}\s*/;
129
- var BLOCK_FULL_RE = /\{%\s*block\s+([A-Za-z_][A-Za-z0-9_-]*)\s*%\}([\s\S]*?)\{%\s*endblock\s*%\}/g;
130
-
131
- function _extractBlocks(source) {
132
- var blocks = {};
133
- var rest = source.replace(BLOCK_FULL_RE, function (_match, name, content) {
134
- blocks[name] = content;
135
- return "";
136
- });
137
- return { rest: rest, blocks: blocks };
138
- }
139
-
140
- function _substituteBlocks(parentSource, childBlocks) {
141
- return parentSource.replace(BLOCK_FULL_RE, function (_match, name, defaultContent) {
142
- return Object.prototype.hasOwnProperty.call(childBlocks, name)
143
- ? childBlocks[name]
144
- : defaultContent;
145
- });
146
- }
147
-
148
- function _resolveExtends(viewsDir, source) {
149
- // Walk UP the extends chain accumulating block overrides. Closer-to-
150
- // leaf overrides win; each parent's blocks fill in only the names the
151
- // chain hasn't already set. When the chain hits a template with no
152
- // {% extends %}, that's the rootmost source — substitute the
153
- // accumulated overrides into its block placeholders, with each
154
- // un-overridden placeholder falling back to its default content.
155
- //
156
- // The earlier recursive substitution had a subtle bug: substituting
157
- // each level's blocks into its parent erased the parent's block
158
- // placeholders, leaving nothing for the next-level-up to override.
159
- // The accumulate-then-substitute-once shape side-steps that.
160
- var allOverrides = {};
161
- var current = source;
162
- var depth = 0;
163
- while (true) {
164
- if (depth > MAX_TEMPLATE_DEPTH) {
165
- throw new Error("template: layout inheritance depth exceeded " + MAX_TEMPLATE_DEPTH +
166
- " — possible extends cycle");
167
- }
168
- var m = current.match(EXTENDS_RE);
169
- if (!m) break;
170
- var parentName = m[1];
171
- var childRest = current.slice(m[0].length);
172
- var extracted = _extractBlocks(childRest);
173
- for (var k in extracted.blocks) {
174
- if (Object.prototype.hasOwnProperty.call(extracted.blocks, k) &&
175
- !Object.prototype.hasOwnProperty.call(allOverrides, k)) {
176
- allOverrides[k] = extracted.blocks[k];
177
- }
178
- }
179
- var parentPath = _resolveViewPath(viewsDir, parentName);
180
- current = fs.readFileSync(parentPath, "utf8");
181
- depth++;
182
- }
183
- return _substituteBlocks(current, allOverrides);
184
- }
185
-
186
- // ============================================================
187
- // Partial inlining (post-extends, pre-tokenize)
188
- // ============================================================
189
-
190
- function _inlinePartials(viewsDir, source, depth) {
191
- if (depth > MAX_TEMPLATE_DEPTH) {
192
- throw new Error("template: partial recursion depth exceeded " + MAX_TEMPLATE_DEPTH +
193
- " — possible cycle");
194
- }
195
- return source.replace(/\{\{>\s*([A-Za-z_][A-Za-z0-9_-]*)\s*\}\}/g, function (_, name) {
196
- var p = _resolvePartialPath(viewsDir, name);
197
- if (!p) return ""; // missing partial → silent empty (matches hermitstash)
198
- return _inlinePartials(viewsDir, fs.readFileSync(p, "utf8"), depth + 1);
199
- });
200
- }
201
-
202
- // ============================================================
203
- // Block tokenizer — emits LITERAL / EXPR_ESCAPED / EXPR_RAW /
204
- // DIRECTIVE tokens. Partials are already inlined by this point;
205
- // extends/block already resolved.
206
- // ============================================================
207
-
208
- function _tokenize(source) {
209
- var tokens = [];
210
- var i = 0;
211
- var len = source.length;
212
- while (i < len) {
213
- var codeStart = source.indexOf("{%", i);
214
- var rawStart = source.indexOf("{{{", i);
215
- var exprStart = source.indexOf("{{", i);
216
- var nextTag = len;
217
- var tagType = null;
218
- if (codeStart !== -1 && codeStart < nextTag) { nextTag = codeStart; tagType = "code"; }
219
- if (rawStart !== -1 && rawStart < nextTag) { nextTag = rawStart; tagType = "raw"; }
220
- if (exprStart !== -1 && exprStart < nextTag) { nextTag = exprStart; tagType = "expr"; }
221
- if (rawStart !== -1 && rawStart === nextTag && tagType === "expr") tagType = "raw";
222
- if (nextTag > i) {
223
- tokens.push({ kind: "LITERAL", text: source.slice(i, nextTag) });
224
- }
225
- if (tagType === null) break;
226
- if (tagType === "raw") {
227
- var endRaw = source.indexOf("}}}", nextTag + 3);
228
- if (endRaw === -1) throw new Error("template: unterminated {{{ raw }}} tag");
229
- tokens.push({ kind: "EXPR_RAW", expr: source.slice(nextTag + 3, endRaw).trim() });
230
- i = endRaw + 3;
231
- } else if (tagType === "expr") {
232
- var endExpr = source.indexOf("}}", nextTag + 2);
233
- if (endExpr === -1) throw new Error("template: unterminated {{ expression }} tag");
234
- tokens.push({ kind: "EXPR_ESCAPED", expr: source.slice(nextTag + 2, endExpr).trim() });
235
- i = endExpr + 2;
236
- } else { // code
237
- var endCode = source.indexOf("%}", nextTag + 2);
238
- if (endCode === -1) throw new Error("template: unterminated {% directive %} tag");
239
- tokens.push({ kind: "DIRECTIVE", body: source.slice(nextTag + 2, endCode).trim() });
240
- i = endCode + 2;
241
- }
242
- }
243
- return tokens;
244
- }
245
-
246
- // ============================================================
247
- // Block parser — tokens → AST
248
- //
249
- // Node types:
250
- // { type: "Template", body: Node[] }
251
- // { type: "Literal", text: string }
252
- // { type: "EscExpr", expr: ExprAST }
253
- // { type: "RawExpr", expr: ExprAST }
254
- // { type: "If", cond: ExprAST, thenBody: Node[], elseBody: Node[] | null }
255
- // { type: "For", binding: string, source: ExprAST, body: Node[] }
256
- //
257
- // extends and block are resolved BEFORE parsing (during _resolveExtends).
258
- // Bare `{% block %}` directives that survive into the parser are an
259
- // error (block outside a child template that doesn't extend anything).
260
- // ============================================================
261
-
262
- var DIRECTIVE_HEAD_RE = /^([a-z]+)(?:\s+([\s\S]+))?$/;
263
-
264
- function _parseTokens(tokens) {
265
- var pos = 0;
266
- function peek() { return tokens[pos]; }
267
- function next() { return tokens[pos++]; }
268
-
269
- function parseBody(terminators) {
270
- var body = [];
271
- while (pos < tokens.length) {
272
- var t = peek();
273
- if (t.kind === "LITERAL") { next(); body.push({ type: "Literal", text: t.text }); continue; }
274
- if (t.kind === "EXPR_ESCAPED"){ next(); body.push({ type: "EscExpr", expr: _parseExpression(t.expr) }); continue; }
275
- if (t.kind === "EXPR_RAW") { next(); body.push({ type: "RawExpr", expr: _parseExpression(t.expr) }); continue; }
276
- // DIRECTIVE
277
- var m = t.body.match(DIRECTIVE_HEAD_RE);
278
- if (!m) throw new Error("template: malformed directive: {% " + t.body + " %}");
279
- var head = m[1];
280
- var tail = m[2] || "";
281
- if (terminators && terminators.indexOf(head) !== -1) {
282
- return body;
283
- }
284
- next(); // consume directive token
285
- if (head === "if") {
286
- var cond = _parseExpression(tail);
287
- var thenBody = parseBody(["else", "endif"]);
288
- var elseBody = null;
289
- var sentinel = peek();
290
- if (sentinel && sentinel.kind === "DIRECTIVE" && /^else\b/.test(sentinel.body)) {
291
- next();
292
- elseBody = parseBody(["endif"]);
293
- }
294
- var endTok = next();
295
- if (!endTok || endTok.kind !== "DIRECTIVE" || !/^endif\b/.test(endTok.body)) {
296
- throw new Error("template: missing {% endif %}");
297
- }
298
- body.push({ type: "If", cond: cond, thenBody: thenBody, elseBody: elseBody });
299
- continue;
300
- }
301
- if (head === "for") {
302
- var forMatch = tail.match(/^([A-Za-z_][A-Za-z0-9_]*)\s+in\s+([\s\S]+)$/);
303
- if (!forMatch) throw new Error("template: invalid for syntax: {% for " + tail + " %}");
304
- var binding = forMatch[1];
305
- var srcExpr = _parseExpression(forMatch[2]);
306
- var loopBody = parseBody(["endfor"]);
307
- var endFor = next();
308
- if (!endFor || endFor.kind !== "DIRECTIVE" || !/^endfor\b/.test(endFor.body)) {
309
- throw new Error("template: missing {% endfor %}");
310
- }
311
- body.push({ type: "For", binding: binding, source: srcExpr, body: loopBody });
312
- continue;
313
- }
314
- if (head === "block" || head === "endblock") {
315
- // {% block %} should have been resolved by _resolveExtends. If
316
- // it's still here, the template uses block syntax without
317
- // extending anything — pass it through as no-op (the block's
318
- // default content was already inlined by _substituteBlocks).
319
- // Hitting this branch usually means the source had a stray
320
- // block; we accept it silently (matches the spec: child blocks
321
- // outside an extends are dropped, parent block defaults are
322
- // already inlined).
323
- continue;
324
- }
325
- if (head === "extends") {
326
- // Already handled in _resolveExtends. If we see one here it
327
- // wasn't at the top — error.
328
- throw new Error("template: {% extends %} must be the first non-whitespace in the file");
329
- }
330
- throw new Error("template: unknown directive: {% " + t.body + " %}");
331
- }
332
- if (terminators && terminators.length > 0) {
333
- throw new Error("template: unexpected end of template — expected one of: " + terminators.join(", "));
334
- }
335
- return body;
336
- }
337
-
338
- return { type: "Template", body: parseBody(null) };
339
- }
340
-
341
- // ============================================================
342
- // Expression tokenizer + parser
343
- // ============================================================
344
-
345
- function _tokenizeExpr(src) {
346
- var tokens = [];
347
- var i = 0;
348
- while (i < src.length) {
349
- var c = src[i];
350
- if (c === " " || c === "\t" || c === "\n" || c === "\r") { i++; continue; }
351
- // String literals (single OR double quotes)
352
- if (c === '"' || c === "'") {
353
- var quote = c;
354
- i++; // skip opening quote
355
- var s = "";
356
- while (i < src.length && src[i] !== quote) {
357
- if (src[i] === "\\" && i + 1 < src.length) {
358
- var esc = src[i + 1];
359
- if (esc === "n") s += "\n";
360
- else if (esc === "t") s += "\t";
361
- else if (esc === "r") s += "\r";
362
- else if (esc === "\\") s += "\\";
363
- else s += esc;
364
- i += 2;
365
- continue;
366
- }
367
- s += src[i++];
368
- }
369
- if (i >= src.length) throw new Error("template: unterminated string in expression");
370
- i++; // closing quote
371
- tokens.push({ kind: "STRING", value: s });
372
- continue;
373
- }
374
- // Number literals
375
- if ((c >= "0" && c <= "9") || (c === "." && src[i + 1] >= "0" && src[i + 1] <= "9")) {
376
- var nstart = i;
377
- while (i < src.length && ((src[i] >= "0" && src[i] <= "9") || src[i] === ".")) i++;
378
- tokens.push({ kind: "NUMBER", value: parseFloat(src.slice(nstart, i)) });
379
- continue;
380
- }
381
- // Identifiers + keywords
382
- if ((c >= "a" && c <= "z") || (c >= "A" && c <= "Z") || c === "_" || c === "$") {
383
- var istart = i;
384
- while (i < src.length && (
385
- (src[i] >= "a" && src[i] <= "z") || (src[i] >= "A" && src[i] <= "Z") ||
386
- (src[i] >= "0" && src[i] <= "9") || src[i] === "_" || src[i] === "$"
387
- )) i++;
388
- var name = src.slice(istart, i);
389
- if (name === "true") tokens.push({ kind: "BOOL", value: true });
390
- else if (name === "false") tokens.push({ kind: "BOOL", value: false });
391
- else if (name === "null") tokens.push({ kind: "NULL" });
392
- else tokens.push({ kind: "IDENT", name: name });
393
- continue;
394
- }
395
- // Multi-char operators (longest match first)
396
- var two = src.slice(i, i + 2);
397
- var three = src.slice(i, i + 3);
398
- if (three === "===" || three === "!==") { tokens.push({ kind: "OP", op: three }); i += 3; continue; }
399
- if (two === "==" || two === "!=" || two === "<=" || two === ">=" ||
400
- two === "&&" || two === "||") {
401
- tokens.push({ kind: "OP", op: two }); i += 2; continue;
402
- }
403
- // Single-char operators / punctuation
404
- if ("+-*/!<>?:.,()[]".indexOf(c) !== -1) {
405
- tokens.push({ kind: "OP", op: c });
406
- i++;
407
- continue;
408
- }
409
- throw new Error("template: unexpected character in expression: '" + c + "' at offset " + i);
410
- }
411
- return tokens;
412
- }
413
-
414
- function _parseExpression(src) {
415
- var tokens = _tokenizeExpr(src);
416
- var pos = 0;
417
- function peek() { return tokens[pos]; }
418
- function eat(kind, op) {
419
- var t = tokens[pos];
420
- if (!t) return null;
421
- if (t.kind !== kind) return null;
422
- if (op !== undefined && t.op !== op) return null;
423
- pos++;
424
- return t;
425
- }
426
- function expect(kind, op) {
427
- var t = eat(kind, op);
428
- if (!t) {
429
- var got = tokens[pos] ? (tokens[pos].kind + (tokens[pos].op ? ":" + tokens[pos].op : "")) : "EOF";
430
- throw new Error("template: expected " + kind + (op ? "(" + op + ")" : "") + " got " + got);
431
- }
432
- return t;
433
- }
434
-
435
- function parseTernary() {
436
- var cond = parseLogicalOr();
437
- if (eat("OP", "?")) {
438
- var thenE = parseLogicalOr();
439
- expect("OP", ":");
440
- var elseE = parseLogicalOr();
441
- return { type: "Ternary", cond: cond, thenE: thenE, elseE: elseE };
442
- }
443
- return cond;
444
- }
445
- function parseLogicalOr() {
446
- var left = parseLogicalAnd();
447
- while (eat("OP", "||")) {
448
- var right = parseLogicalAnd();
449
- left = { type: "Binary", op: "||", left: left, right: right };
450
- }
451
- return left;
452
- }
453
- function parseLogicalAnd() {
454
- var left = parseEquality();
455
- while (eat("OP", "&&")) {
456
- var right = parseEquality();
457
- left = { type: "Binary", op: "&&", left: left, right: right };
458
- }
459
- return left;
460
- }
461
- function parseEquality() {
462
- var left = parseComparison();
463
- while (true) {
464
- var op = eat("OP", "===") || eat("OP", "!==") || eat("OP", "==") || eat("OP", "!=");
465
- if (!op) break;
466
- var right = parseComparison();
467
- left = { type: "Binary", op: op.op, left: left, right: right };
468
- }
469
- return left;
470
- }
471
- function parseComparison() {
472
- var left = parseAdditive();
473
- while (true) {
474
- var op = eat("OP", "<=") || eat("OP", ">=") || eat("OP", "<") || eat("OP", ">");
475
- if (!op) break;
476
- var right = parseAdditive();
477
- left = { type: "Binary", op: op.op, left: left, right: right };
478
- }
479
- return left;
480
- }
481
- function parseAdditive() {
482
- var left = parseMultiplicative();
483
- while (true) {
484
- var op = eat("OP", "+") || eat("OP", "-");
485
- if (!op) break;
486
- var right = parseMultiplicative();
487
- left = { type: "Binary", op: op.op, left: left, right: right };
488
- }
489
- return left;
490
- }
491
- function parseMultiplicative() {
492
- var left = parseUnary();
493
- while (true) {
494
- var op = eat("OP", "*") || eat("OP", "/");
495
- if (!op) break;
496
- var right = parseUnary();
497
- left = { type: "Binary", op: op.op, left: left, right: right };
498
- }
499
- return left;
500
- }
501
- function parseUnary() {
502
- if (eat("OP", "!")) return { type: "Unary", op: "!", arg: parseUnary() };
503
- if (eat("OP", "-")) return { type: "Unary", op: "-", arg: parseUnary() };
504
- return parsePostfix();
505
- }
506
- function parsePostfix() {
507
- var expr = parsePrimary();
508
- while (true) {
509
- if (eat("OP", ".")) {
510
- var ident = expect("IDENT");
511
- expr = { type: "Member", object: expr, property: ident.name, computed: false };
512
- } else if (eat("OP", "[")) {
513
- var idx = parseTernary();
514
- expect("OP", "]");
515
- expr = { type: "Member", object: expr, property: idx, computed: true };
516
- } else if (eat("OP", "(")) {
517
- var args = [];
518
- if (peek() && !(peek().kind === "OP" && peek().op === ")")) {
519
- args.push(parseTernary());
520
- while (eat("OP", ",")) args.push(parseTernary());
521
- }
522
- expect("OP", ")");
523
- expr = { type: "Call", callee: expr, args: args };
524
- } else break;
525
- }
526
- return expr;
527
- }
528
- function parsePrimary() {
529
- var t = peek();
530
- if (!t) throw new Error("template: unexpected end of expression");
531
- if (t.kind === "STRING") { pos++; return { type: "Literal", value: t.value }; }
532
- if (t.kind === "NUMBER") { pos++; return { type: "Literal", value: t.value }; }
533
- if (t.kind === "BOOL") { pos++; return { type: "Literal", value: t.value }; }
534
- if (t.kind === "NULL") { pos++; return { type: "Literal", value: null }; }
535
- if (t.kind === "IDENT") { pos++; return { type: "Identifier", name: t.name }; }
536
- if (t.kind === "OP" && t.op === "(") {
537
- pos++;
538
- var inner = parseTernary();
539
- expect("OP", ")");
540
- return inner;
541
- }
542
- throw new Error("template: unexpected token in expression: " +
543
- (t.kind + (t.op ? ":" + t.op : "")));
544
- }
545
-
546
- var ast = parseTernary();
547
- if (pos < tokens.length) {
548
- var rest = tokens[pos];
549
- throw new Error("template: trailing tokens in expression: " +
550
- (rest.kind + (rest.op ? ":" + rest.op : "")));
551
- }
552
- return ast;
553
- }
554
-
555
- // ============================================================
556
- // Expression evaluator — walks expression AST against a scope chain
557
- // ============================================================
558
-
559
- function _scopeLookup(scopes, name) {
560
- // Walk innermost → outermost; returns undefined if not found.
561
- for (var i = scopes.length - 1; i >= 0; i--) {
562
- var s = scopes[i];
563
- if (s !== null && s !== undefined && Object.prototype.hasOwnProperty.call(s, name)) {
564
- return s[name];
565
- }
566
- }
567
- return undefined;
568
- }
569
-
570
- function _evalExpr(node, scopes) {
571
- switch (node.type) {
572
- case "Literal": return node.value;
573
- case "Identifier": return _scopeLookup(scopes, node.name);
574
- case "Member":
575
- var obj = _evalExpr(node.object, scopes);
576
- if (obj === null || obj === undefined) return undefined;
577
- var key = node.computed ? _evalExpr(node.property, scopes) : node.property;
578
- // Block prototype-chain access — only own properties resolve.
579
- // Prevents `{{ foo.constructor }}` / `{{ foo.__proto__ }}` from
580
- // walking out of the data scope into the runtime.
581
- if (Object.prototype.hasOwnProperty.call(obj, key) ||
582
- // Arrays: numeric indices + .length are legitimate even though
583
- // .length is on the prototype shape (it's an own property via
584
- // the array's internal slot — hasOwn returns true)
585
- (Array.isArray(obj) && key === "length")) {
586
- return obj[key];
587
- }
588
- return undefined;
589
- case "Call":
590
- var callee = _evalExpr(node.callee, scopes);
591
- if (typeof callee !== "function") {
592
- throw new Error("template: cannot call non-function: " +
593
- (node.callee.type === "Member" ? node.callee.property : node.callee.name || "<expr>"));
594
- }
595
- var args = [];
596
- for (var ai = 0; ai < node.args.length; ai++) {
597
- args.push(_evalExpr(node.args[ai], scopes));
598
- }
599
- // Bind `this` to the receiver when the callee is a member access.
600
- var thisRef = null;
601
- if (node.callee.type === "Member") {
602
- thisRef = _evalExpr(node.callee.object, scopes);
603
- }
604
- return callee.apply(thisRef, args);
605
- case "Unary":
606
- var v = _evalExpr(node.arg, scopes);
607
- if (node.op === "!") return !v;
608
- if (node.op === "-") return -Number(v);
609
- throw new Error("template: unknown unary op: " + node.op);
610
- case "Binary":
611
- if (node.op === "&&") return _evalExpr(node.left, scopes) && _evalExpr(node.right, scopes);
612
- if (node.op === "||") return _evalExpr(node.left, scopes) || _evalExpr(node.right, scopes);
613
- var L = _evalExpr(node.left, scopes);
614
- var R = _evalExpr(node.right, scopes);
615
- switch (node.op) {
616
- case "===": return L === R;
617
- case "!==": return L !== R;
618
- // eslint-disable-next-line eqeqeq -- template language operator
619
- case "==": return L == R;
620
- // eslint-disable-next-line eqeqeq -- template language operator
621
- case "!=": return L != R;
622
- case "<": return L < R;
623
- case "<=": return L <= R;
624
- case ">": return L > R;
625
- case ">=": return L >= R;
626
- case "+": return L + R;
627
- case "-": return L - R;
628
- case "*": return L * R;
629
- case "/": return L / R;
630
- default: throw new Error("template: unknown binary op: " + node.op);
631
- }
632
- case "Ternary":
633
- return _evalExpr(node.cond, scopes) ? _evalExpr(node.thenE, scopes) : _evalExpr(node.elseE, scopes);
634
- default:
635
- throw new Error("template: unknown expression node type: " + node.type);
636
- }
637
- }
638
-
639
- // ============================================================
640
- // Block evaluator — walks block AST, builds output string
641
- // ============================================================
642
-
643
- function _evalBlock(nodes, scopes, escFn) {
644
- var out = "";
645
- for (var i = 0; i < nodes.length; i++) {
646
- var n = nodes[i];
647
- switch (n.type) {
648
- case "Literal": out += n.text; break;
649
- case "EscExpr":
650
- out += escFn(_evalExpr(n.expr, scopes));
651
- break;
652
- case "RawExpr":
653
- var rawV = _evalExpr(n.expr, scopes);
654
- if (rawV !== null && rawV !== undefined) out += String(rawV);
655
- break;
656
- case "If":
657
- if (_evalExpr(n.cond, scopes)) {
658
- out += _evalBlock(n.thenBody, scopes, escFn);
659
- } else if (n.elseBody) {
660
- out += _evalBlock(n.elseBody, scopes, escFn);
661
- }
662
- break;
663
- case "For":
664
- var src = _evalExpr(n.source, scopes);
665
- if (src && typeof src.length === "number") {
666
- for (var fi = 0; fi < src.length; fi++) {
667
- var loopScope = {};
668
- loopScope[n.binding] = src[fi];
669
- scopes.push(loopScope);
670
- out += _evalBlock(n.body, scopes, escFn);
671
- scopes.pop();
672
- }
673
- }
674
- break;
675
- default:
676
- throw new Error("template: unknown block node type: " + n.type);
677
- }
678
- }
679
- return out;
680
- }
681
-
682
- // ============================================================
683
- // Engine instance
684
- // ============================================================
685
-
686
- function create(opts) {
687
- opts = opts || {};
688
- validateOpts(opts, ["viewsDir", "cache", "escapeHtml"], "b.template");
689
- if (!opts.viewsDir) {
690
- throw new Error("template.create({ viewsDir }) is required");
691
- }
692
- if (!fs.existsSync(opts.viewsDir)) {
693
- throw new Error("template: viewsDir does not exist: " + opts.viewsDir);
694
- }
695
- var viewsDir = path.resolve(opts.viewsDir);
696
- var cacheOn = opts.cache !== false;
697
- var customEscape = typeof opts.escapeHtml === "function" ? opts.escapeHtml : escapeHtml;
698
- var astCache = {};
699
-
700
- function compile(viewName) {
701
- if (cacheOn && astCache[viewName]) return astCache[viewName];
702
- var viewPath = _resolveViewPath(viewsDir, viewName);
703
- var source = fs.readFileSync(viewPath, "utf8");
704
- source = _resolveExtends(viewsDir, source);
705
- source = _inlinePartials(viewsDir, source, 0);
706
- var tokens = _tokenize(source);
707
- var ast = _parseTokens(tokens);
708
- if (cacheOn) astCache[viewName] = ast;
709
- return ast;
710
- }
711
-
712
- function render(viewName, data) {
713
- var ast = compile(viewName);
714
- return _evalBlock(ast.body, [data || {}], customEscape);
715
- }
716
-
717
- function reset() { astCache = {}; }
718
-
719
- // Walk viewsDir, compile every .html file. Surfaces parse errors at
720
- // boot time (with the offending view name in the message) rather than
721
- // at first request. Operators call this from the bootstrap path so
722
- // a typo like `{% if not foo %}` fails the deploy, not the user.
723
- // Returns the list of view names compiled.
724
- function precompileAll() {
725
- var compiled = [];
726
- function walk(dir, prefix) {
727
- var entries = fs.readdirSync(dir, { withFileTypes: true });
728
- for (var i = 0; i < entries.length; i++) {
729
- var e = entries[i];
730
- var rel = prefix ? prefix + "/" + e.name : e.name;
731
- if (e.isDirectory()) {
732
- walk(path.join(dir, e.name), rel);
733
- } else if (e.isFile() && /\.html$/.test(e.name)) {
734
- var viewName = rel.replace(/\.html$/, "");
735
- try {
736
- compile(viewName);
737
- } catch (err) {
738
- // Re-throw with the view name in the message — the parser's
739
- // own "trailing tokens" / "malformed directive" don't say
740
- // which file the syntax error lives in.
741
- var wrapped = new Error("template: precompile failed for view '" +
742
- viewName + "': " + (err && err.message || String(err)));
743
- wrapped.cause = err;
744
- wrapped.viewName = viewName;
745
- throw wrapped;
746
- }
747
- compiled.push(viewName);
748
- }
749
- }
750
- }
751
- walk(viewsDir, "");
752
- return compiled;
753
- }
754
-
755
- return {
756
- compile: compile,
757
- render: render,
758
- reset: reset,
759
- precompileAll: precompileAll,
760
- viewsDir: viewsDir,
761
- escapeHtml: customEscape,
762
- };
763
- }
764
-
765
- // ---- Default singleton ----
766
-
767
- var _default = null;
768
- function _ensureDefault() {
769
- if (!_default) {
770
- var defaultDir = path.resolve(process.cwd(), "views");
771
- if (!fs.existsSync(defaultDir)) {
772
- throw new Error("template.render() default uses <cwd>/views which doesn't exist; " +
773
- "call template.create({ viewsDir }) for a custom location");
774
- }
775
- _default = create({ viewsDir: defaultDir });
776
- }
777
- return _default;
778
- }
779
-
780
- function render(viewName, data) {
781
- return _ensureDefault().render(viewName, data);
782
- }
783
-
784
- function _resetDefaultForTest() { _default = null; }
785
-
786
- module.exports = {
787
- create: create,
788
- render: render,
789
- escapeHtml: escapeHtml,
790
- _resetDefaultForTest: _resetDefaultForTest,
791
- };
1
+ "use strict";
2
+ /**
3
+ * Server-side HTML template engine — eval-free.
4
+ *
5
+ * No `new Function()`, no `eval`, no `vm.runInThisContext`. Templates
6
+ * are tokenized + parsed into a small AST and walked at render time
7
+ * against a data scope. The trade-off vs an eval-based engine is
8
+ * 5–50× slower per render and a restricted expression grammar; the
9
+ * win is "an operator who renders req.query.template (or worse) can't
10
+ * RCE the framework, period."
11
+ *
12
+ * Tag syntax:
13
+ *
14
+ * {{ expr }} HTML-escaped expression output
15
+ * {{{ expr }}} Raw output (no escape — operator-trusted HTML)
16
+ * {{> name }} Partial from <viewsDir>/partials/<name>.html
17
+ * {% extends "name" %} Inherit from a layout (must be first non-whitespace)
18
+ * {% block name %}…{% endblock %}
19
+ * Overrideable section
20
+ * {% if expr %}…{% else %}…{% endif %}
21
+ * Conditional
22
+ * {% for ident in expr %}…{% endfor %}
23
+ * Iterate an array; the identifier is bound
24
+ * for the loop body
25
+ *
26
+ * Expression grammar (recursive-descent Pratt-style):
27
+ *
28
+ * expression := ternary
29
+ * ternary := logical-or ('?' logical-or ':' logical-or)?
30
+ * logical-or := logical-and ('||' logical-and)*
31
+ * logical-and := equality ('&&' equality)*
32
+ * equality := comparison (('==' | '!=' | '===' | '!==') comparison)*
33
+ * comparison := unary (('<' | '<=' | '>' | '>=') unary)*
34
+ * unary := '!' unary | postfix
35
+ * postfix := primary postfix-op*
36
+ * postfix-op := '.' identifier | '[' expression ']' | '(' arg-list ')'
37
+ * primary := literal | identifier | '(' expression ')'
38
+ * literal := string-literal | number-literal | 'true' | 'false' | 'null'
39
+ *
40
+ * Function calls invoke functions THE OPERATOR PROVIDED in the data
41
+ * scope (e.g. `{{ helpers.formatDate(d) }}` resolves `helpers` from
42
+ * data, then `formatDate` on it, then calls it with `d`). The
43
+ * interpreter does not invent built-ins; if an operator wants
44
+ * helpers, they pass them under any data key they like.
45
+ *
46
+ * Public API:
47
+ *
48
+ * template.create({ viewsDir, cache?, escapeHtml? })
49
+ * → engine instance with .render(view, data?), .compile(view), .reset()
50
+ * template.render(view, data?)
51
+ * → convenience using a default singleton against <cwd>/views
52
+ * template.escapeHtml(value)
53
+ * → standalone HTML escape (used by forms.js etc.)
54
+ *
55
+ * Containment defenses (templates ARE server-side files; these guard
56
+ * against operator path-joining mistakes that let request input reach
57
+ * a view-name argument):
58
+ *
59
+ * - View names containing ".." or "\0" → reject
60
+ * - Resolved paths outside viewsDir → reject
61
+ * - Layout-extends and partial-inclusion recursion bounded at depth 16
62
+ *
63
+ * If an operator renders a template path derived from user input, the
64
+ * defenses block path traversal. The interpreter's eval-free posture
65
+ * is the second line: even if a template loaded, it can't execute
66
+ * arbitrary JS — only the limited expression grammar above.
67
+ */
68
+ var fs = require("fs");
69
+ var path = require("path");
70
+ var validateOpts = require("./validate-opts");
71
+
72
+ // Maximum nesting depth for layout {% extends %} chains and partial
73
+ // {{> ... }} recursion. Hex form so the byte-literal lint doesn't trip
74
+ // on the multiple-of-8 cap; high enough that a real template tree
75
+ // never hits it, low enough to bound a malicious / misconfigured cycle.
76
+ var MAX_TEMPLATE_DEPTH = 0x10;
77
+
78
+ // ============================================================
79
+ // HTML escape (exported)
80
+ // ============================================================
81
+
82
+ var ESCAPE_MAP = { "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#x27;" };
83
+ var ESCAPE_RE = /[&<>"']/g;
84
+
85
+ function escapeHtml(value) {
86
+ if (value === null || value === undefined) return "";
87
+ var s = typeof value === "string" ? value : String(value);
88
+ return s.replace(ESCAPE_RE, function (c) { return ESCAPE_MAP[c]; });
89
+ }
90
+
91
+ // ============================================================
92
+ // Path resolution + containment
93
+ // ============================================================
94
+
95
+ function _resolveViewPath(viewsDir, viewName) {
96
+ if (typeof viewName !== "string" || viewName.length === 0) {
97
+ throw new Error("template: view name must be a non-empty string");
98
+ }
99
+ if (viewName.indexOf("..") !== -1 || viewName.indexOf("\0") !== -1) {
100
+ throw new Error("template: view name contains forbidden character: " + JSON.stringify(viewName));
101
+ }
102
+ var resolved = path.resolve(viewsDir, viewName + ".html");
103
+ var resolvedDir = path.resolve(viewsDir);
104
+ if (resolved !== resolvedDir &&
105
+ !resolved.startsWith(resolvedDir + path.sep)) {
106
+ throw new Error("template: view path escapes viewsDir: " + viewName);
107
+ }
108
+ if (!fs.existsSync(resolved)) {
109
+ throw new Error("template: view not found: " + viewName);
110
+ }
111
+ return resolved;
112
+ }
113
+
114
+ function _resolvePartialPath(viewsDir, partialName) {
115
+ if (typeof partialName !== "string" || partialName.length === 0) return null;
116
+ if (partialName.indexOf("..") !== -1 || partialName.indexOf("\0") !== -1) return null;
117
+ var resolved = path.resolve(viewsDir, "partials", partialName + ".html");
118
+ var partialsDir = path.resolve(viewsDir, "partials");
119
+ if (resolved !== partialsDir &&
120
+ !resolved.startsWith(partialsDir + path.sep)) return null;
121
+ return fs.existsSync(resolved) ? resolved : null;
122
+ }
123
+
124
+ // ============================================================
125
+ // Layout inheritance: extract blocks, substitute into parent
126
+ // ============================================================
127
+
128
+ var EXTENDS_RE = /^\s*\{%\s*extends\s+"([^"]+)"\s*%\}\s*/;
129
+ var BLOCK_FULL_RE = /\{%\s*block\s+([A-Za-z_][A-Za-z0-9_-]*)\s*%\}([\s\S]*?)\{%\s*endblock\s*%\}/g;
130
+
131
+ function _extractBlocks(source) {
132
+ var blocks = {};
133
+ var rest = source.replace(BLOCK_FULL_RE, function (_match, name, content) {
134
+ blocks[name] = content;
135
+ return "";
136
+ });
137
+ return { rest: rest, blocks: blocks };
138
+ }
139
+
140
+ function _substituteBlocks(parentSource, childBlocks) {
141
+ return parentSource.replace(BLOCK_FULL_RE, function (_match, name, defaultContent) {
142
+ return Object.prototype.hasOwnProperty.call(childBlocks, name)
143
+ ? childBlocks[name]
144
+ : defaultContent;
145
+ });
146
+ }
147
+
148
+ function _resolveExtends(viewsDir, source) {
149
+ // Walk UP the extends chain accumulating block overrides. Closer-to-
150
+ // leaf overrides win; each parent's blocks fill in only the names the
151
+ // chain hasn't already set. When the chain hits a template with no
152
+ // {% extends %}, that's the rootmost source — substitute the
153
+ // accumulated overrides into its block placeholders, with each
154
+ // un-overridden placeholder falling back to its default content.
155
+ //
156
+ // The earlier recursive substitution had a subtle bug: substituting
157
+ // each level's blocks into its parent erased the parent's block
158
+ // placeholders, leaving nothing for the next-level-up to override.
159
+ // The accumulate-then-substitute-once shape side-steps that.
160
+ var allOverrides = {};
161
+ var current = source;
162
+ var depth = 0;
163
+ while (true) {
164
+ if (depth > MAX_TEMPLATE_DEPTH) {
165
+ throw new Error("template: layout inheritance depth exceeded " + MAX_TEMPLATE_DEPTH +
166
+ " — possible extends cycle");
167
+ }
168
+ var m = current.match(EXTENDS_RE);
169
+ if (!m) break;
170
+ var parentName = m[1];
171
+ var childRest = current.slice(m[0].length);
172
+ var extracted = _extractBlocks(childRest);
173
+ for (var k in extracted.blocks) {
174
+ if (Object.prototype.hasOwnProperty.call(extracted.blocks, k) &&
175
+ !Object.prototype.hasOwnProperty.call(allOverrides, k)) {
176
+ allOverrides[k] = extracted.blocks[k];
177
+ }
178
+ }
179
+ var parentPath = _resolveViewPath(viewsDir, parentName);
180
+ current = fs.readFileSync(parentPath, "utf8");
181
+ depth++;
182
+ }
183
+ return _substituteBlocks(current, allOverrides);
184
+ }
185
+
186
+ // ============================================================
187
+ // Partial inlining (post-extends, pre-tokenize)
188
+ // ============================================================
189
+
190
+ function _inlinePartials(viewsDir, source, depth) {
191
+ if (depth > MAX_TEMPLATE_DEPTH) {
192
+ throw new Error("template: partial recursion depth exceeded " + MAX_TEMPLATE_DEPTH +
193
+ " — possible cycle");
194
+ }
195
+ return source.replace(/\{\{>\s*([A-Za-z_][A-Za-z0-9_-]*)\s*\}\}/g, function (_, name) {
196
+ var p = _resolvePartialPath(viewsDir, name);
197
+ if (!p) return ""; // missing partial → silent empty (matches hermitstash)
198
+ return _inlinePartials(viewsDir, fs.readFileSync(p, "utf8"), depth + 1);
199
+ });
200
+ }
201
+
202
+ // ============================================================
203
+ // Block tokenizer — emits LITERAL / EXPR_ESCAPED / EXPR_RAW /
204
+ // DIRECTIVE tokens. Partials are already inlined by this point;
205
+ // extends/block already resolved.
206
+ // ============================================================
207
+
208
+ function _tokenize(source) {
209
+ var tokens = [];
210
+ var i = 0;
211
+ var len = source.length;
212
+ while (i < len) {
213
+ var codeStart = source.indexOf("{%", i);
214
+ var rawStart = source.indexOf("{{{", i);
215
+ var exprStart = source.indexOf("{{", i);
216
+ var nextTag = len;
217
+ var tagType = null;
218
+ if (codeStart !== -1 && codeStart < nextTag) { nextTag = codeStart; tagType = "code"; }
219
+ if (rawStart !== -1 && rawStart < nextTag) { nextTag = rawStart; tagType = "raw"; }
220
+ if (exprStart !== -1 && exprStart < nextTag) { nextTag = exprStart; tagType = "expr"; }
221
+ if (rawStart !== -1 && rawStart === nextTag && tagType === "expr") tagType = "raw";
222
+ if (nextTag > i) {
223
+ tokens.push({ kind: "LITERAL", text: source.slice(i, nextTag) });
224
+ }
225
+ if (tagType === null) break;
226
+ if (tagType === "raw") {
227
+ var endRaw = source.indexOf("}}}", nextTag + 3);
228
+ if (endRaw === -1) throw new Error("template: unterminated {{{ raw }}} tag");
229
+ tokens.push({ kind: "EXPR_RAW", expr: source.slice(nextTag + 3, endRaw).trim() });
230
+ i = endRaw + 3;
231
+ } else if (tagType === "expr") {
232
+ var endExpr = source.indexOf("}}", nextTag + 2);
233
+ if (endExpr === -1) throw new Error("template: unterminated {{ expression }} tag");
234
+ tokens.push({ kind: "EXPR_ESCAPED", expr: source.slice(nextTag + 2, endExpr).trim() });
235
+ i = endExpr + 2;
236
+ } else { // code
237
+ var endCode = source.indexOf("%}", nextTag + 2);
238
+ if (endCode === -1) throw new Error("template: unterminated {% directive %} tag");
239
+ tokens.push({ kind: "DIRECTIVE", body: source.slice(nextTag + 2, endCode).trim() });
240
+ i = endCode + 2;
241
+ }
242
+ }
243
+ return tokens;
244
+ }
245
+
246
+ // ============================================================
247
+ // Block parser — tokens → AST
248
+ //
249
+ // Node types:
250
+ // { type: "Template", body: Node[] }
251
+ // { type: "Literal", text: string }
252
+ // { type: "EscExpr", expr: ExprAST }
253
+ // { type: "RawExpr", expr: ExprAST }
254
+ // { type: "If", cond: ExprAST, thenBody: Node[], elseBody: Node[] | null }
255
+ // { type: "For", binding: string, source: ExprAST, body: Node[] }
256
+ //
257
+ // extends and block are resolved BEFORE parsing (during _resolveExtends).
258
+ // Bare `{% block %}` directives that survive into the parser are an
259
+ // error (block outside a child template that doesn't extend anything).
260
+ // ============================================================
261
+
262
+ var DIRECTIVE_HEAD_RE = /^([a-z]+)(?:\s+([\s\S]+))?$/;
263
+
264
+ function _parseTokens(tokens) {
265
+ var pos = 0;
266
+ function peek() { return tokens[pos]; }
267
+ function next() { return tokens[pos++]; }
268
+
269
+ function parseBody(terminators) {
270
+ var body = [];
271
+ while (pos < tokens.length) {
272
+ var t = peek();
273
+ if (t.kind === "LITERAL") { next(); body.push({ type: "Literal", text: t.text }); continue; }
274
+ if (t.kind === "EXPR_ESCAPED"){ next(); body.push({ type: "EscExpr", expr: _parseExpression(t.expr) }); continue; }
275
+ if (t.kind === "EXPR_RAW") { next(); body.push({ type: "RawExpr", expr: _parseExpression(t.expr) }); continue; }
276
+ // DIRECTIVE
277
+ var m = t.body.match(DIRECTIVE_HEAD_RE);
278
+ if (!m) throw new Error("template: malformed directive: {% " + t.body + " %}");
279
+ var head = m[1];
280
+ var tail = m[2] || "";
281
+ if (terminators && terminators.indexOf(head) !== -1) {
282
+ return body;
283
+ }
284
+ next(); // consume directive token
285
+ if (head === "if") {
286
+ var cond = _parseExpression(tail);
287
+ var thenBody = parseBody(["else", "endif"]);
288
+ var elseBody = null;
289
+ var sentinel = peek();
290
+ if (sentinel && sentinel.kind === "DIRECTIVE" && /^else\b/.test(sentinel.body)) {
291
+ next();
292
+ elseBody = parseBody(["endif"]);
293
+ }
294
+ var endTok = next();
295
+ if (!endTok || endTok.kind !== "DIRECTIVE" || !/^endif\b/.test(endTok.body)) {
296
+ throw new Error("template: missing {% endif %}");
297
+ }
298
+ body.push({ type: "If", cond: cond, thenBody: thenBody, elseBody: elseBody });
299
+ continue;
300
+ }
301
+ if (head === "for") {
302
+ var forMatch = tail.match(/^([A-Za-z_][A-Za-z0-9_]*)\s+in\s+([\s\S]+)$/);
303
+ if (!forMatch) throw new Error("template: invalid for syntax: {% for " + tail + " %}");
304
+ var binding = forMatch[1];
305
+ var srcExpr = _parseExpression(forMatch[2]);
306
+ var loopBody = parseBody(["endfor"]);
307
+ var endFor = next();
308
+ if (!endFor || endFor.kind !== "DIRECTIVE" || !/^endfor\b/.test(endFor.body)) {
309
+ throw new Error("template: missing {% endfor %}");
310
+ }
311
+ body.push({ type: "For", binding: binding, source: srcExpr, body: loopBody });
312
+ continue;
313
+ }
314
+ if (head === "block" || head === "endblock") {
315
+ // {% block %} should have been resolved by _resolveExtends. If
316
+ // it's still here, the template uses block syntax without
317
+ // extending anything — pass it through as no-op (the block's
318
+ // default content was already inlined by _substituteBlocks).
319
+ // Hitting this branch usually means the source had a stray
320
+ // block; we accept it silently (matches the spec: child blocks
321
+ // outside an extends are dropped, parent block defaults are
322
+ // already inlined).
323
+ continue;
324
+ }
325
+ if (head === "extends") {
326
+ // Already handled in _resolveExtends. If we see one here it
327
+ // wasn't at the top — error.
328
+ throw new Error("template: {% extends %} must be the first non-whitespace in the file");
329
+ }
330
+ throw new Error("template: unknown directive: {% " + t.body + " %}");
331
+ }
332
+ if (terminators && terminators.length > 0) {
333
+ throw new Error("template: unexpected end of template — expected one of: " + terminators.join(", "));
334
+ }
335
+ return body;
336
+ }
337
+
338
+ return { type: "Template", body: parseBody(null) };
339
+ }
340
+
341
+ // ============================================================
342
+ // Expression tokenizer + parser
343
+ // ============================================================
344
+
345
+ function _tokenizeExpr(src) {
346
+ var tokens = [];
347
+ var i = 0;
348
+ while (i < src.length) {
349
+ var c = src[i];
350
+ if (c === " " || c === "\t" || c === "\n" || c === "\r") { i++; continue; }
351
+ // String literals (single OR double quotes)
352
+ if (c === '"' || c === "'") {
353
+ var quote = c;
354
+ i++; // skip opening quote
355
+ var s = "";
356
+ while (i < src.length && src[i] !== quote) {
357
+ if (src[i] === "\\" && i + 1 < src.length) {
358
+ var esc = src[i + 1];
359
+ if (esc === "n") s += "\n";
360
+ else if (esc === "t") s += "\t";
361
+ else if (esc === "r") s += "\r";
362
+ else if (esc === "\\") s += "\\";
363
+ else s += esc;
364
+ i += 2;
365
+ continue;
366
+ }
367
+ s += src[i++];
368
+ }
369
+ if (i >= src.length) throw new Error("template: unterminated string in expression");
370
+ i++; // closing quote
371
+ tokens.push({ kind: "STRING", value: s });
372
+ continue;
373
+ }
374
+ // Number literals
375
+ if ((c >= "0" && c <= "9") || (c === "." && src[i + 1] >= "0" && src[i + 1] <= "9")) {
376
+ var nstart = i;
377
+ while (i < src.length && ((src[i] >= "0" && src[i] <= "9") || src[i] === ".")) i++;
378
+ tokens.push({ kind: "NUMBER", value: parseFloat(src.slice(nstart, i)) });
379
+ continue;
380
+ }
381
+ // Identifiers + keywords
382
+ if ((c >= "a" && c <= "z") || (c >= "A" && c <= "Z") || c === "_" || c === "$") {
383
+ var istart = i;
384
+ while (i < src.length && (
385
+ (src[i] >= "a" && src[i] <= "z") || (src[i] >= "A" && src[i] <= "Z") ||
386
+ (src[i] >= "0" && src[i] <= "9") || src[i] === "_" || src[i] === "$"
387
+ )) i++;
388
+ var name = src.slice(istart, i);
389
+ if (name === "true") tokens.push({ kind: "BOOL", value: true });
390
+ else if (name === "false") tokens.push({ kind: "BOOL", value: false });
391
+ else if (name === "null") tokens.push({ kind: "NULL" });
392
+ else tokens.push({ kind: "IDENT", name: name });
393
+ continue;
394
+ }
395
+ // Multi-char operators (longest match first)
396
+ var two = src.slice(i, i + 2);
397
+ var three = src.slice(i, i + 3);
398
+ if (three === "===" || three === "!==") { tokens.push({ kind: "OP", op: three }); i += 3; continue; }
399
+ if (two === "==" || two === "!=" || two === "<=" || two === ">=" ||
400
+ two === "&&" || two === "||") {
401
+ tokens.push({ kind: "OP", op: two }); i += 2; continue;
402
+ }
403
+ // Single-char operators / punctuation
404
+ if ("+-*/!<>?:.,()[]".indexOf(c) !== -1) {
405
+ tokens.push({ kind: "OP", op: c });
406
+ i++;
407
+ continue;
408
+ }
409
+ throw new Error("template: unexpected character in expression: '" + c + "' at offset " + i);
410
+ }
411
+ return tokens;
412
+ }
413
+
414
+ function _parseExpression(src) {
415
+ var tokens = _tokenizeExpr(src);
416
+ var pos = 0;
417
+ function peek() { return tokens[pos]; }
418
+ function eat(kind, op) {
419
+ var t = tokens[pos];
420
+ if (!t) return null;
421
+ if (t.kind !== kind) return null;
422
+ if (op !== undefined && t.op !== op) return null;
423
+ pos++;
424
+ return t;
425
+ }
426
+ function expect(kind, op) {
427
+ var t = eat(kind, op);
428
+ if (!t) {
429
+ var got = tokens[pos] ? (tokens[pos].kind + (tokens[pos].op ? ":" + tokens[pos].op : "")) : "EOF";
430
+ throw new Error("template: expected " + kind + (op ? "(" + op + ")" : "") + " got " + got);
431
+ }
432
+ return t;
433
+ }
434
+
435
+ function parseTernary() {
436
+ var cond = parseLogicalOr();
437
+ if (eat("OP", "?")) {
438
+ var thenE = parseLogicalOr();
439
+ expect("OP", ":");
440
+ var elseE = parseLogicalOr();
441
+ return { type: "Ternary", cond: cond, thenE: thenE, elseE: elseE };
442
+ }
443
+ return cond;
444
+ }
445
+ function parseLogicalOr() {
446
+ var left = parseLogicalAnd();
447
+ while (eat("OP", "||")) {
448
+ var right = parseLogicalAnd();
449
+ left = { type: "Binary", op: "||", left: left, right: right };
450
+ }
451
+ return left;
452
+ }
453
+ function parseLogicalAnd() {
454
+ var left = parseEquality();
455
+ while (eat("OP", "&&")) {
456
+ var right = parseEquality();
457
+ left = { type: "Binary", op: "&&", left: left, right: right };
458
+ }
459
+ return left;
460
+ }
461
+ function parseEquality() {
462
+ var left = parseComparison();
463
+ while (true) {
464
+ var op = eat("OP", "===") || eat("OP", "!==") || eat("OP", "==") || eat("OP", "!=");
465
+ if (!op) break;
466
+ var right = parseComparison();
467
+ left = { type: "Binary", op: op.op, left: left, right: right };
468
+ }
469
+ return left;
470
+ }
471
+ function parseComparison() {
472
+ var left = parseAdditive();
473
+ while (true) {
474
+ var op = eat("OP", "<=") || eat("OP", ">=") || eat("OP", "<") || eat("OP", ">");
475
+ if (!op) break;
476
+ var right = parseAdditive();
477
+ left = { type: "Binary", op: op.op, left: left, right: right };
478
+ }
479
+ return left;
480
+ }
481
+ function parseAdditive() {
482
+ var left = parseMultiplicative();
483
+ while (true) {
484
+ var op = eat("OP", "+") || eat("OP", "-");
485
+ if (!op) break;
486
+ var right = parseMultiplicative();
487
+ left = { type: "Binary", op: op.op, left: left, right: right };
488
+ }
489
+ return left;
490
+ }
491
+ function parseMultiplicative() {
492
+ var left = parseUnary();
493
+ while (true) {
494
+ var op = eat("OP", "*") || eat("OP", "/");
495
+ if (!op) break;
496
+ var right = parseUnary();
497
+ left = { type: "Binary", op: op.op, left: left, right: right };
498
+ }
499
+ return left;
500
+ }
501
+ function parseUnary() {
502
+ if (eat("OP", "!")) return { type: "Unary", op: "!", arg: parseUnary() };
503
+ if (eat("OP", "-")) return { type: "Unary", op: "-", arg: parseUnary() };
504
+ return parsePostfix();
505
+ }
506
+ function parsePostfix() {
507
+ var expr = parsePrimary();
508
+ while (true) {
509
+ if (eat("OP", ".")) {
510
+ var ident = expect("IDENT");
511
+ expr = { type: "Member", object: expr, property: ident.name, computed: false };
512
+ } else if (eat("OP", "[")) {
513
+ var idx = parseTernary();
514
+ expect("OP", "]");
515
+ expr = { type: "Member", object: expr, property: idx, computed: true };
516
+ } else if (eat("OP", "(")) {
517
+ var args = [];
518
+ if (peek() && !(peek().kind === "OP" && peek().op === ")")) {
519
+ args.push(parseTernary());
520
+ while (eat("OP", ",")) args.push(parseTernary());
521
+ }
522
+ expect("OP", ")");
523
+ expr = { type: "Call", callee: expr, args: args };
524
+ } else break;
525
+ }
526
+ return expr;
527
+ }
528
+ function parsePrimary() {
529
+ var t = peek();
530
+ if (!t) throw new Error("template: unexpected end of expression");
531
+ if (t.kind === "STRING") { pos++; return { type: "Literal", value: t.value }; }
532
+ if (t.kind === "NUMBER") { pos++; return { type: "Literal", value: t.value }; }
533
+ if (t.kind === "BOOL") { pos++; return { type: "Literal", value: t.value }; }
534
+ if (t.kind === "NULL") { pos++; return { type: "Literal", value: null }; }
535
+ if (t.kind === "IDENT") { pos++; return { type: "Identifier", name: t.name }; }
536
+ if (t.kind === "OP" && t.op === "(") {
537
+ pos++;
538
+ var inner = parseTernary();
539
+ expect("OP", ")");
540
+ return inner;
541
+ }
542
+ throw new Error("template: unexpected token in expression: " +
543
+ (t.kind + (t.op ? ":" + t.op : "")));
544
+ }
545
+
546
+ var ast = parseTernary();
547
+ if (pos < tokens.length) {
548
+ var rest = tokens[pos];
549
+ throw new Error("template: trailing tokens in expression: " +
550
+ (rest.kind + (rest.op ? ":" + rest.op : "")));
551
+ }
552
+ return ast;
553
+ }
554
+
555
+ // ============================================================
556
+ // Expression evaluator — walks expression AST against a scope chain
557
+ // ============================================================
558
+
559
+ function _scopeLookup(scopes, name) {
560
+ // Walk innermost → outermost; returns undefined if not found.
561
+ for (var i = scopes.length - 1; i >= 0; i--) {
562
+ var s = scopes[i];
563
+ if (s !== null && s !== undefined && Object.prototype.hasOwnProperty.call(s, name)) {
564
+ return s[name];
565
+ }
566
+ }
567
+ return undefined;
568
+ }
569
+
570
+ function _evalExpr(node, scopes) {
571
+ switch (node.type) {
572
+ case "Literal": return node.value;
573
+ case "Identifier": return _scopeLookup(scopes, node.name);
574
+ case "Member":
575
+ var obj = _evalExpr(node.object, scopes);
576
+ if (obj === null || obj === undefined) return undefined;
577
+ var key = node.computed ? _evalExpr(node.property, scopes) : node.property;
578
+ // Block prototype-chain access — only own properties resolve.
579
+ // Prevents `{{ foo.constructor }}` / `{{ foo.__proto__ }}` from
580
+ // walking out of the data scope into the runtime.
581
+ if (Object.prototype.hasOwnProperty.call(obj, key) ||
582
+ // Arrays: numeric indices + .length are legitimate even though
583
+ // .length is on the prototype shape (it's an own property via
584
+ // the array's internal slot — hasOwn returns true)
585
+ (Array.isArray(obj) && key === "length")) {
586
+ return obj[key];
587
+ }
588
+ return undefined;
589
+ case "Call":
590
+ var callee = _evalExpr(node.callee, scopes);
591
+ if (typeof callee !== "function") {
592
+ throw new Error("template: cannot call non-function: " +
593
+ (node.callee.type === "Member" ? node.callee.property : node.callee.name || "<expr>"));
594
+ }
595
+ var args = [];
596
+ for (var ai = 0; ai < node.args.length; ai++) {
597
+ args.push(_evalExpr(node.args[ai], scopes));
598
+ }
599
+ // Bind `this` to the receiver when the callee is a member access.
600
+ var thisRef = null;
601
+ if (node.callee.type === "Member") {
602
+ thisRef = _evalExpr(node.callee.object, scopes);
603
+ }
604
+ return callee.apply(thisRef, args);
605
+ case "Unary":
606
+ var v = _evalExpr(node.arg, scopes);
607
+ if (node.op === "!") return !v;
608
+ if (node.op === "-") return -Number(v);
609
+ throw new Error("template: unknown unary op: " + node.op);
610
+ case "Binary":
611
+ if (node.op === "&&") return _evalExpr(node.left, scopes) && _evalExpr(node.right, scopes);
612
+ if (node.op === "||") return _evalExpr(node.left, scopes) || _evalExpr(node.right, scopes);
613
+ var L = _evalExpr(node.left, scopes);
614
+ var R = _evalExpr(node.right, scopes);
615
+ switch (node.op) {
616
+ case "===": return L === R;
617
+ case "!==": return L !== R;
618
+ // eslint-disable-next-line eqeqeq -- template language operator
619
+ case "==": return L == R;
620
+ // eslint-disable-next-line eqeqeq -- template language operator
621
+ case "!=": return L != R;
622
+ case "<": return L < R;
623
+ case "<=": return L <= R;
624
+ case ">": return L > R;
625
+ case ">=": return L >= R;
626
+ case "+": return L + R;
627
+ case "-": return L - R;
628
+ case "*": return L * R;
629
+ case "/": return L / R;
630
+ default: throw new Error("template: unknown binary op: " + node.op);
631
+ }
632
+ case "Ternary":
633
+ return _evalExpr(node.cond, scopes) ? _evalExpr(node.thenE, scopes) : _evalExpr(node.elseE, scopes);
634
+ default:
635
+ throw new Error("template: unknown expression node type: " + node.type);
636
+ }
637
+ }
638
+
639
+ // ============================================================
640
+ // Block evaluator — walks block AST, builds output string
641
+ // ============================================================
642
+
643
+ function _evalBlock(nodes, scopes, escFn) {
644
+ var out = "";
645
+ for (var i = 0; i < nodes.length; i++) {
646
+ var n = nodes[i];
647
+ switch (n.type) {
648
+ case "Literal": out += n.text; break;
649
+ case "EscExpr":
650
+ out += escFn(_evalExpr(n.expr, scopes));
651
+ break;
652
+ case "RawExpr":
653
+ var rawV = _evalExpr(n.expr, scopes);
654
+ if (rawV !== null && rawV !== undefined) out += String(rawV);
655
+ break;
656
+ case "If":
657
+ if (_evalExpr(n.cond, scopes)) {
658
+ out += _evalBlock(n.thenBody, scopes, escFn);
659
+ } else if (n.elseBody) {
660
+ out += _evalBlock(n.elseBody, scopes, escFn);
661
+ }
662
+ break;
663
+ case "For":
664
+ var src = _evalExpr(n.source, scopes);
665
+ if (src && typeof src.length === "number") {
666
+ for (var fi = 0; fi < src.length; fi++) {
667
+ var loopScope = {};
668
+ loopScope[n.binding] = src[fi];
669
+ scopes.push(loopScope);
670
+ out += _evalBlock(n.body, scopes, escFn);
671
+ scopes.pop();
672
+ }
673
+ }
674
+ break;
675
+ default:
676
+ throw new Error("template: unknown block node type: " + n.type);
677
+ }
678
+ }
679
+ return out;
680
+ }
681
+
682
+ // ============================================================
683
+ // Engine instance
684
+ // ============================================================
685
+
686
+ function create(opts) {
687
+ opts = opts || {};
688
+ validateOpts(opts, ["viewsDir", "cache", "escapeHtml"], "b.template");
689
+ if (!opts.viewsDir) {
690
+ throw new Error("template.create({ viewsDir }) is required");
691
+ }
692
+ if (!fs.existsSync(opts.viewsDir)) {
693
+ throw new Error("template: viewsDir does not exist: " + opts.viewsDir);
694
+ }
695
+ var viewsDir = path.resolve(opts.viewsDir);
696
+ var cacheOn = opts.cache !== false;
697
+ var customEscape = typeof opts.escapeHtml === "function" ? opts.escapeHtml : escapeHtml;
698
+ var astCache = {};
699
+
700
+ function compile(viewName) {
701
+ if (cacheOn && astCache[viewName]) return astCache[viewName];
702
+ var viewPath = _resolveViewPath(viewsDir, viewName);
703
+ var source = fs.readFileSync(viewPath, "utf8");
704
+ source = _resolveExtends(viewsDir, source);
705
+ source = _inlinePartials(viewsDir, source, 0);
706
+ var tokens = _tokenize(source);
707
+ var ast = _parseTokens(tokens);
708
+ if (cacheOn) astCache[viewName] = ast;
709
+ return ast;
710
+ }
711
+
712
+ function render(viewName, data) {
713
+ var ast = compile(viewName);
714
+ return _evalBlock(ast.body, [data || {}], customEscape);
715
+ }
716
+
717
+ function reset() { astCache = {}; }
718
+
719
+ // Walk viewsDir, compile every .html file. Surfaces parse errors at
720
+ // boot time (with the offending view name in the message) rather than
721
+ // at first request. Operators call this from the bootstrap path so
722
+ // a typo like `{% if not foo %}` fails the deploy, not the user.
723
+ // Returns the list of view names compiled.
724
+ function precompileAll() {
725
+ var compiled = [];
726
+ function walk(dir, prefix) {
727
+ var entries = fs.readdirSync(dir, { withFileTypes: true });
728
+ for (var i = 0; i < entries.length; i++) {
729
+ var e = entries[i];
730
+ var rel = prefix ? prefix + "/" + e.name : e.name;
731
+ if (e.isDirectory()) {
732
+ walk(path.join(dir, e.name), rel);
733
+ } else if (e.isFile() && /\.html$/.test(e.name)) {
734
+ var viewName = rel.replace(/\.html$/, "");
735
+ try {
736
+ compile(viewName);
737
+ } catch (err) {
738
+ // Re-throw with the view name in the message — the parser's
739
+ // own "trailing tokens" / "malformed directive" don't say
740
+ // which file the syntax error lives in.
741
+ var wrapped = new Error("template: precompile failed for view '" +
742
+ viewName + "': " + (err && err.message || String(err)));
743
+ wrapped.cause = err;
744
+ wrapped.viewName = viewName;
745
+ throw wrapped;
746
+ }
747
+ compiled.push(viewName);
748
+ }
749
+ }
750
+ }
751
+ walk(viewsDir, "");
752
+ return compiled;
753
+ }
754
+
755
+ return {
756
+ compile: compile,
757
+ render: render,
758
+ reset: reset,
759
+ precompileAll: precompileAll,
760
+ viewsDir: viewsDir,
761
+ escapeHtml: customEscape,
762
+ };
763
+ }
764
+
765
+ // ---- Default singleton ----
766
+
767
+ var _default = null;
768
+ function _ensureDefault() {
769
+ if (!_default) {
770
+ var defaultDir = path.resolve(process.cwd(), "views");
771
+ if (!fs.existsSync(defaultDir)) {
772
+ throw new Error("template.render() default uses <cwd>/views which doesn't exist; " +
773
+ "call template.create({ viewsDir }) for a custom location");
774
+ }
775
+ _default = create({ viewsDir: defaultDir });
776
+ }
777
+ return _default;
778
+ }
779
+
780
+ function render(viewName, data) {
781
+ return _ensureDefault().render(viewName, data);
782
+ }
783
+
784
+ function _resetDefaultForTest() { _default = null; }
785
+
786
+ module.exports = {
787
+ create: create,
788
+ render: render,
789
+ escapeHtml: escapeHtml,
790
+ _resetDefaultForTest: _resetDefaultForTest,
791
+ };