-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathtemplate-engine.ts
More file actions
204 lines (188 loc) · 7.03 KB
/
Copy pathtemplate-engine.ts
File metadata and controls
204 lines (188 loc) · 7.03 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.
/**
* Minimal mustache-style template renderer.
*
* Supports `{{path.to.value}}` placeholders resolved against a plain
* JS object via dotted-path lookup. Values are HTML-escaped by
* default; use `{{{path}}}` (triple braces) to opt out of escaping
* (e.g. when injecting pre-rendered HTML fragments such as URLs in
* `<a href="">`).
*
* A hole may carry an optional formatter from the shared formula
* whitelist — `{{ order.total | currency:EUR }}`, `{{ ts | datetime }}` —
* reusing `@objectstack/formula`'s `formatValue` so dates, money, and
* (ADR-0053 Phase 2) reference-timezone `datetime` render identically to
* in-app templates. An unknown formatter falls back to the raw string,
* keeping the lenient "never throw on render" contract.
*
* Deliberately tiny (no loops / conditionals / partials) — the design
* stance is that email templates SHOULD be data-only renderings; any
* branching belongs in the caller. If we ever need more, swap for
* Handlebars, but bringing it in costs ~50KB and pulls a parser at
* runtime; we resist that until a real use case demands it.
*/
import { formatValue } from '@objectstack/formula';
// Match a hole: open braces, a BRACE-FREE inner body, close braces. Capturing
// the inner with `[^{}]*` (a single star over a negated class — no nested
// quantifier, no overlapping `\s*` groups) keeps the matcher strictly linear:
// it can never backtrack into a polynomial-ReDoS shape. The inner body is then
// parsed with plain string ops (`parseHole`) instead of a complex pattern.
// 1=open(`{{`|`{{{`) 2=inner 3=close(`}}`|`}}}`).
const PLACEHOLDER = /(\{\{\{?)([^{}]*)(\}\}\}?)/g;
/** Locale + reference timezone for hole formatters (ADR-0053 Phase 2). */
export interface RenderOptions {
locale?: string;
timeZone?: string;
}
// A hole body is a dotted path with an optional `| formatter[:arg]`. Validated
// against small, already-extracted strings (bounded input → no ReDoS).
const PATH_RE = /^[\w.]+$/;
const FILTER_RE = /^(\w+)(?::\s*'?([^']*?)'?)?$/;
interface ParsedHole {
path: string;
formatter?: string;
arg?: string;
}
/** Parse a hole's inner body into a path + optional formatter. Null if malformed. */
function parseHole(inner: string): ParsedHole | null {
const pipe = inner.indexOf('|');
if (pipe === -1) {
const path = inner.trim();
return PATH_RE.test(path) ? { path } : null;
}
const path = inner.slice(0, pipe).trim();
if (!PATH_RE.test(path)) return null;
const m = FILTER_RE.exec(inner.slice(pipe + 1).trim());
if (!m) return null;
return { path, formatter: m[1], arg: m[2] };
}
function lookup(data: Record<string, any>, path: string): unknown {
if (!path) return undefined;
const parts = path.split('.');
let cur: any = data;
for (const p of parts) {
if (cur == null) return undefined;
cur = cur[p];
}
return cur;
}
function escapeHtml(s: string): string {
return s
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/'/g, ''');
}
/**
* Render `template` with values from `data`. Missing placeholders
* render as empty strings (no throw); call `requireVars()` first if
* you need strict validation.
*/
export function renderTemplate(
template: string,
data: Record<string, any>,
opts: RenderOptions = {},
): string {
if (!template) return '';
return template.replace(
PLACEHOLDER,
(match: string, open: string, inner: string, close: string) => {
const parsed = parseHole(inner);
if (!parsed) return match; // not a path[+formatter] hole — leave verbatim
const isUnescaped = open === '{{{' && close === '}}}';
const raw = lookup(data, parsed.path);
let str: string;
if (parsed.formatter) {
// Formatted holes render '' for a missing value (the formula formatters
// treat null as empty), so they never emit "undefined".
const formatted = formatValue(parsed.formatter, raw, parsed.arg, {
locale: opts.locale,
timeZone: opts.timeZone,
});
str = formatted !== undefined
? formatted
: raw == null ? '' : (typeof raw === 'string' ? raw : String(raw)); // unknown formatter → raw
} else {
if (raw == null) return '';
str = typeof raw === 'string' ? raw : String(raw);
}
return isUnescaped ? str : escapeHtml(str);
},
);
}
/**
* Throw `Error('MISSING_VARIABLES: a, b')` when required vars are
* absent from `data`. Used by `IEmailService.sendTemplate()` to
* fail fast rather than send a half-rendered email.
*/
export function requireVars(
data: Record<string, any>,
required: ReadonlyArray<string>,
): void {
const missing = required.filter((name) => lookup(data, name) == null);
if (missing.length > 0) {
throw new Error(`MISSING_VARIABLES: ${missing.join(', ')}`);
}
}
/**
* Decode the small set of HTML entities `escapeHtml` can emit, in a
* SINGLE left-to-right pass. Doing this with one alternation regex —
* rather than a chain of `.replace('&','&').replace('<','<')…`
* — is deliberate: a sequential chain is order-dependent and can
* double-unescape (e.g. `&lt;` → `<` → `<`). Because each match
* is consumed and the scan resumes *after* it, `&lt;` decodes to
* the literal text `<` and stops, never to `<`.
*/
const ENTITIES: Record<string, string> = {
' ': ' ',
'&': '&',
'<': '<',
'>': '>',
'"': '"',
''': "'",
};
const ENTITY_RE = /&(?:nbsp|amp|lt|gt|quot|#39);/g;
function decodeEntities(s: string): string {
return s.replace(ENTITY_RE, (m) => ENTITIES[m] ?? m);
}
const TAG_RE = /<[^>]*>/g;
/**
* Remove HTML tags robustly. A single `.replace(/<[^>]*>/g, '')` pass
* is not enough: stripping a tag can splice the surrounding text into a
* fresh tag (e.g. `<scr<script>ipt>` → `<script>`), so we loop until the
* string stops changing. This closes the "incomplete multi-character
* sanitization" gap where crafted/overlapping input leaves a `<…>` tag
* behind.
*/
function stripTags(s: string): string {
let prev: string;
let out = s;
do {
prev = out;
out = out.replace(TAG_RE, '');
} while (out !== prev);
return out;
}
/**
* Strip HTML tags + collapse whitespace to derive a plain-text body
* from an HTML template. Conservative: keeps line breaks at block
* boundaries (<br>, </p>, </div>) so the resulting text is at least
* paragraph-shaped.
*
* Order matters for safety: tags are stripped (looping until stable)
* *before* entities are decoded, and entities are decoded in a single
* pass — so neither tag removal nor entity decoding can re-introduce a
* live tag or double-unescape an entity.
*/
export function htmlToText(html: string): string {
if (!html) return '';
const withBreaks = html
.replace(/<br\s*\/?>/gi, '\n')
.replace(/<\/(p|div|h[1-6]|li|tr)>/gi, '\n');
return decodeEntities(stripTags(withBreaks))
.replace(/[ \t]+/g, ' ')
.replace(/\n[ \t]+/g, '\n')
.replace(/\n{3,}/g, '\n\n')
.trim();
}