-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathinterpolate.ts
More file actions
402 lines (344 loc) · 12 KB
/
interpolate.ts
File metadata and controls
402 lines (344 loc) · 12 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
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
export interface InterpolateOptions {
strict?: boolean;
}
const VARIABLE_RE = /\{\{\s*([a-zA-Z_][a-zA-Z0-9_]*)\s*\}\}/g;
const ESCAPED_OPEN = /\\\{\\\{/g;
const ESCAPE_PLACEHOLDER = '\x00ESCAPED_OPEN\x00';
// --- Condition parsing ---
/**
* A parsed condition from a block tag.
*
* Supports:
* {{#if var}} → { variable, operator: 'truthy' }
* {{#if var == "value"}} → { variable, operator: '==', comparand: 'value' }
* {{#if var != "value"}} → { variable, operator: '!=', comparand: 'value' }
* {{#unless var}} → same as above, inverted at evaluation time
*/
interface Condition {
variable: string;
operator: 'truthy' | '==' | '!=';
comparand?: string;
}
// Matches: varName, varName == "val", varName != "val"
// Quotes can be double or single.
const CONDITION_RE =
/([a-zA-Z_][a-zA-Z0-9_]*)(?:\s*(==|!=)\s*(?:"([^"]*?)"|'([^']*?)'))?/;
function parseCondition(conditionStr: string): Condition | null {
const m = CONDITION_RE.exec(conditionStr.trim());
if (!m) return null;
const variable = m[1];
const operator = m[2] as '==' | '!=' | undefined;
const comparand = m[3] ?? m[4]; // double-quote group or single-quote group
if (operator && comparand !== undefined) {
return { variable, operator, comparand };
}
return { variable, operator: 'truthy' };
}
/**
* Evaluate a condition against the variables map.
*/
function evaluateCondition(condition: Condition, variables: Record<string, string>): boolean {
const value = variables[condition.variable];
switch (condition.operator) {
case 'truthy':
return value !== undefined && value !== '';
case '==':
return value !== undefined && value === condition.comparand;
case '!=':
return value === undefined || value !== condition.comparand;
}
}
// --- Block tag patterns ---
// Opening tags: {{#if condition}} and {{#unless condition}}
// The condition part is captured broadly; parseCondition() handles the details.
const BLOCK_IF_OPEN_RE = /\{\{#if\s+([^}]+?)\s*\}\}/;
const BLOCK_UNLESS_OPEN_RE = /\{\{#unless\s+([^}]+?)\s*\}\}/;
// Else-if tag: {{else if condition}}
const BLOCK_ELSE_IF_RE = /\{\{else\s+if\s+([^}]+?)\s*\}\}/;
// Simple else and close tags
const BLOCK_ELSE_RE = /\{\{else\}\}/;
const BLOCK_IF_CLOSE_RE = /\{\{\/if\}\}/;
const BLOCK_UNLESS_CLOSE_RE = /\{\{\/unless\}\}/;
// For extracting condition variable names (used by extractVariables)
const BLOCK_CONDITION_EXTRACT_RE =
/\{\{(?:#(?:if|unless)|else\s+if)\s+([a-zA-Z_][a-zA-Z0-9_]*)(?:\s*(?:==|!=)\s*(?:"[^"]*?"|'[^']*?'))?\s*\}\}/g;
// --- Block types ---
interface ConditionalBranch {
condition: Condition;
content: string;
}
interface ConditionalBlock {
kind: 'if' | 'unless';
branches: ConditionalBranch[]; // first branch is the {{#if}} condition
elseContent: string; // final {{else}} fallback (may be '')
fullMatch: string;
}
/**
* Find the outermost conditional block in the template.
* Returns null if no block is found.
*
* This uses a counter-based approach: find the first opening tag,
* then scan forward tracking nesting depth to find the matching
* {{else if}}, {{else}}, and {{/if}} or {{/unless}} at depth 0.
*/
function findOutermostBlock(template: string): ConditionalBlock | null {
// Find the first opening tag (either {{#if}} or {{#unless}})
const ifMatch = BLOCK_IF_OPEN_RE.exec(template);
const unlessMatch = BLOCK_UNLESS_OPEN_RE.exec(template);
let openMatch: RegExpExecArray | null = null;
let kind: 'if' | 'unless';
if (ifMatch && unlessMatch) {
if (ifMatch.index <= unlessMatch.index) {
openMatch = ifMatch;
kind = 'if';
} else {
openMatch = unlessMatch;
kind = 'unless';
}
} else if (ifMatch) {
openMatch = ifMatch;
kind = 'if';
} else if (unlessMatch) {
openMatch = unlessMatch;
kind = 'unless';
} else {
return null;
}
const openCondition = parseCondition(openMatch[1]);
if (!openCondition) return null;
const contentStart = openMatch.index + openMatch[0].length;
const remaining = template.slice(contentStart);
// Scan through remaining text tracking depth, collecting branch boundaries
let depth = 0;
let closeIndex = -1; // relative to contentStart
let closeLength = 0;
// Branch boundary tracking: positions of {{else if ...}} and {{else}} at depth 0
interface BranchBoundary {
kind: 'else-if' | 'else';
position: number; // start of the tag (relative to remaining)
length: number; // length of the tag
condition?: Condition;
}
const boundaries: BranchBoundary[] = [];
let pos = 0;
while (pos < remaining.length) {
const sub = remaining.slice(pos);
// Check for any opening block tag (nesting)
const anyOpen = /^\{\{#(?:if|unless)\s+[^}]+?\s*\}\}/.exec(sub);
if (anyOpen) {
depth++;
pos += anyOpen[0].length;
continue;
}
// Check for {{else if condition}} at depth 0
const elseIfMatch = /^\{\{else\s+if\s+([^}]+?)\s*\}\}/.exec(sub);
if (elseIfMatch && depth === 0) {
const cond = parseCondition(elseIfMatch[1]);
if (cond) {
boundaries.push({
kind: 'else-if',
position: pos,
length: elseIfMatch[0].length,
condition: cond,
});
}
pos += elseIfMatch[0].length;
continue;
}
// Check for {{else}} at depth 0
const elseMatch = /^\{\{else\}\}/.exec(sub);
if (elseMatch && depth === 0) {
boundaries.push({
kind: 'else',
position: pos,
length: elseMatch[0].length,
});
pos += elseMatch[0].length;
continue;
}
// Skip {{else}} / {{else if}} at depth > 0
if (depth > 0 && (elseIfMatch || elseMatch)) {
pos += (elseIfMatch ?? elseMatch)![0].length;
continue;
}
// Check for any closing block tag
const anyClose = /^\{\{\/(?:if|unless)\}\}/.exec(sub);
if (anyClose) {
if (depth === 0) {
closeIndex = pos;
closeLength = anyClose[0].length;
break;
}
depth--;
pos += anyClose[0].length;
continue;
}
pos++;
}
if (closeIndex === -1) {
// Unclosed block — leave it as-is (don't crash, just skip)
return null;
}
// Build branches from boundaries
const branches: ConditionalBranch[] = [];
let elseContent = '';
// First branch: from start to first boundary (or close)
const firstEnd = boundaries.length > 0 ? boundaries[0].position : closeIndex;
branches.push({
condition: openCondition,
content: remaining.slice(0, firstEnd),
});
// Middle branches (else-if) and final else
for (let i = 0; i < boundaries.length; i++) {
const boundary = boundaries[i];
const nextEnd = i + 1 < boundaries.length
? boundaries[i + 1].position
: closeIndex;
const branchContent = remaining.slice(boundary.position + boundary.length, nextEnd);
if (boundary.kind === 'else-if' && boundary.condition) {
branches.push({
condition: boundary.condition,
content: branchContent,
});
} else {
// Final {{else}} — everything from here to {{/if}}
elseContent = branchContent;
}
}
const fullMatchEnd = contentStart + closeIndex + closeLength;
const fullMatch = template.slice(openMatch.index, fullMatchEnd);
return { kind, branches, elseContent, fullMatch };
}
function escapeRegExp(str: string): string {
return str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}
/**
* Process all conditional blocks in a template.
* Evaluates {{#if}}/{{else if}}/{{else}}/{{/if}} and {{#unless}} blocks.
*
* Blocks are processed iteratively from the outermost inward.
* Conditionals are always permissive: a missing/empty variable evaluates
* as falsy (never throws), because conditionals are semantically about optionality.
*/
function processConditionals(
template: string,
variables: Record<string, string>,
): string {
let result = template;
let safety = 0;
const MAX_ITERATIONS = 100;
while (safety++ < MAX_ITERATIONS) {
const block = findOutermostBlock(result);
if (!block) break;
let winning: string | null = null;
if (block.kind === 'if') {
// Evaluate branches in order; first truthy wins
for (const branch of block.branches) {
if (evaluateCondition(branch.condition, variables)) {
winning = branch.content;
break;
}
}
if (winning === null) {
winning = block.elseContent;
}
} else {
// unless: only the first branch condition is inverted
// (else-if on unless blocks would be unusual, but we handle it)
const firstBranch = block.branches[0];
if (!evaluateCondition(firstBranch.condition, variables)) {
winning = firstBranch.content;
} else if (block.branches.length > 1) {
for (let i = 1; i < block.branches.length; i++) {
if (evaluateCondition(block.branches[i].condition, variables)) {
winning = block.branches[i].content;
break;
}
}
}
if (winning === null) {
winning = block.elseContent;
}
}
// Strip leading/trailing newline from the winning content if the block tags
// were on standalone lines. This prevents extra blank lines in output.
winning = stripBlockContentWhitespace(winning);
result = result.replace(block.fullMatch, winning);
}
return result;
}
/**
* Trim exactly one leading newline and one trailing newline from block content,
* which arise from the tag lines themselves.
*/
function stripBlockContentWhitespace(content: string): string {
let result = content;
if (result.startsWith('\n')) {
result = result.slice(1);
}
if (result.endsWith('\n')) {
result = result.slice(0, -1);
}
return result;
}
/**
* Interpolate variables into a template string.
*
* Syntax:
* {{ variable_name }} — variable substitution
* {{#if var}}...{{/if}} — conditional (truthy = exists and non-empty)
* {{#if var == "value"}}...{{/if}} — string equality comparison
* {{#if var != "value"}}...{{/if}} — string inequality comparison
* {{#if var}}...{{else if var2}}...{{/if}} — chained conditions
* {{#if var}}...{{else}}...{{/if}} — conditional with fallback
* {{#unless var}}...{{/unless}} — inverted conditional
* \{\{ produces literal {{
*
* In strict mode, throws on missing variables (but NOT for conditional checks,
* since conditionals are semantically about optionality).
* In permissive mode, leaves {{ placeholder }} intact.
*/
export function interpolate(
template: string,
variables: Record<string, string>,
options: InterpolateOptions = {},
): string {
const { strict = false } = options;
// Replace escaped sequences with placeholder
let result = template.replace(ESCAPED_OPEN, ESCAPE_PLACEHOLDER);
// Phase 1: Process conditional blocks (always permissive)
result = processConditionals(result, variables);
// Phase 2: Variable substitution
result = result.replace(VARIABLE_RE, (match, name: string) => {
if (name in variables) {
return variables[name];
}
if (strict) {
throw new Error(`Missing required variable: "${name}"`);
}
return match; // leave placeholder intact in permissive mode
});
// Restore escaped sequences
result = result.replaceAll(ESCAPE_PLACEHOLDER, '{{');
return result;
}
/**
* Extract all variable names referenced in a template.
* Includes variables used in {{#if var}}, {{#unless var}},
* {{#if var == "value"}}, and {{else if var}} conditions.
*/
export function extractVariables(template: string): string[] {
const vars = new Set<string>();
// Extract from variable substitutions: {{ var }}
let match: RegExpExecArray | null;
const re = new RegExp(VARIABLE_RE.source, 'g');
while ((match = re.exec(template)) !== null) {
vars.add(match[1]);
}
// Extract from conditional block tags: {{#if var}}, {{#unless var}}, {{else if var}}
const condRe = new RegExp(BLOCK_CONDITION_EXTRACT_RE.source, 'g');
while ((match = condRe.exec(template)) !== null) {
vars.add(match[1]);
}
return [...vars];
}