sfmc-handlebars-parser 0.1.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.
@@ -0,0 +1,757 @@
1
+ /**
2
+ * Handlebars tokenizer for sfmc-handlebars-parser.
3
+ *
4
+ * Scans raw template text (a Handlebars template or an HTML document containing `{{…}}`)
5
+ * into a flat token stream that the parser (W2a/W2b) consumes. This module performs
6
+ * LEXING ONLY — it recognises lexical constructs and records their absolute source offsets;
7
+ * it does NOT build AST nodes or decide node fields. Whitespace-control (`~`) and escaped
8
+ * (`\{{`) markers are recorded as flags on the relevant tokens; the parser interprets them.
9
+ *
10
+ * Clean-room note: written from the observed public behaviour of `@handlebars/parser` and
11
+ * the Handlebars language spec; no upstream source was copied.
12
+ *
13
+ * ── Token contract (what the parser consumes) ────────────────────────────────────────────
14
+ * Every token is `{ type, start, end, ...payload }` where:
15
+ * - `type` {@link TokenType} — the lexical class.
16
+ * - `start` number — absolute offset (UTF-16 code unit) of the first code unit of the token.
17
+ * - `end` number — absolute offset just past the last code unit (so `source.slice(start,end)`
18
+ * is the token's raw text). Use `loc.js` `locFromOffsets(table, start, end)` to get a
19
+ * `SourceLocation`.
20
+ *
21
+ * Payload fields by type:
22
+ * - CONTENT `{ value, escaped }` — `value` is the literal text to render. For a normal
23
+ * content run `value === source.slice(start,end)`. For an ESCAPED mustache
24
+ * (`\{{…}}`), `escaped` is `true`, `start`/`end` span the text AFTER the
25
+ * consumed backslash (i.e. the literal `{{…}}` text), and `value` equals that
26
+ * literal text. `escaped` is `false`/absent for ordinary content.
27
+ * - OPEN `{ open, strip }` — a mustache open delimiter. `open` is one of
28
+ * `'{{'`, `'{{{'`, `'{{{{'`. `strip` is `true` when a `~` immediately followed
29
+ * the open (`{{~`). The sigil (`#`, `/`, `^`, `>`, `#>`, `*`, `#*`, `&`) is a
30
+ * SEPARATE {@link TokenType.SIGIL} token that follows, so the parser reads it.
31
+ * - CLOSE `{ close, strip }` — a mustache close delimiter. `close` is one of
32
+ * `'}}'`, `'}}}'`, `'}}}}'`. `strip` is `true` when a `~` immediately preceded
33
+ * the close (`~}}`).
34
+ * - SIGIL `{ value }` — a leading sigil right after an OPEN: one of
35
+ * `'#'`, `'/'`, `'^'`, `'>'`, `'#>'`, `'*'`, `'#*'`, `'&'`. (Comment sigils
36
+ * `!` / `!--` are NOT emitted as SIGIL — they are lexed as COMMENT, below.)
37
+ * - COMMENT `{ value, long, open, close, strip }` — a whole `{{! … }}` or
38
+ * `{{!-- … --}}` comment. `value` is the raw inner text (between the sigil and
39
+ * the terminator). `long` is `true` for the `{{!-- --}}` form. `open`/`close`
40
+ * carry the delimiter text and `strip` the open-side `~` flag; the closing
41
+ * `~}}` strip (if any) is captured in `closeStrip`. The token spans the ENTIRE
42
+ * comment (`{{` … `}}`), so no OPEN/CLOSE tokens are emitted around it.
43
+ * - ID `{ value }` — an identifier / path segment (bare word: letters, digits,
44
+ * `_`, `$`, `-`, etc.). Booleans / `null` / `undefined` are lexed as ID; the
45
+ * parser classifies them.
46
+ * - SEGMENT `{ value }` — a segment-literal `[ … ]`. `value` is the INNER text with the
47
+ * brackets removed (may contain spaces and dots, kept verbatim).
48
+ * - SEP `{ value }` — a path separator: `'.'`, `'/'`, or `'..'` (parent).
49
+ * - DATA `{}` — the `@` data prefix.
50
+ * - EQUALS `{}` — `=` (hash assignment).
51
+ * - STRING `{ value, quote }` — a string literal. `value` is the DECODED string (escape
52
+ * sequences resolved); `quote` is `'"'` or `"'"`. `start`/`end` span the quotes.
53
+ * - NUMBER `{ value }` — a numeric literal; `value` is the raw lexeme text.
54
+ * - OPEN_PAREN `{}` — `(` (subexpression start).
55
+ * - CLOSE_PAREN `{}` — `)` (subexpression end).
56
+ * - PIPE `{}` — `|` (block-params fence, `as |a b|`).
57
+ * - WHITESPACE `{}` — a run of insignificant whitespace INSIDE an expression. Emitted so the
58
+ * parser can rely on offsets; the parser may ignore it.
59
+ * - RAW_OPEN `{ name }` — the `{{{{name}}}}` raw-block open. `name` is the block name.
60
+ * - RAW_CONTENT `{ value }` — the verbatim raw-block body (inner `{{` NOT parsed). `value ===
61
+ * source.slice(start,end)`.
62
+ * - RAW_CLOSE `{ name }` — the `{{{{/name}}}}` raw-block close. `name` is the block name.
63
+ * - EOF `{}` — the final token (`start === end === source.length`).
64
+ *
65
+ * ── Lexical-error signalling (for W2b) ───────────────────────────────────────────────────
66
+ * On a lexical error the tokenizer can detect itself (unterminated string, unterminated
67
+ * `{{!-- --}}`, unterminated raw block, unterminated segment literal), it THROWS a
68
+ * {@link TokenizerError}: an `Error` with a numeric `.offset` property giving the ABSOLUTE
69
+ * offset (UTF-16 code unit) at which the error was detected (typically the offset of the
70
+ * unterminated construct's opening, matching where upstream reports the lexical class-(b)
71
+ * "Unrecognized text" error). The message text is intentionally generic — W2b owns the final
72
+ * user-facing message and error class; it should read `.offset` (and, if present, `.kind`) to
73
+ * produce the plan's class-(b) lexical error at the right position.
74
+ */
75
+
76
+ import { buildLineTable } from './loc.js';
77
+
78
+ /**
79
+ * Lexical token classes emitted by {@link tokenize}. See the module header for each type's
80
+ * payload fields.
81
+ *
82
+ * @readonly
83
+ * @enum {string}
84
+ */
85
+ export const TokenType = {
86
+ CONTENT: 'CONTENT',
87
+ OPEN: 'OPEN',
88
+ CLOSE: 'CLOSE',
89
+ SIGIL: 'SIGIL',
90
+ COMMENT: 'COMMENT',
91
+ ID: 'ID',
92
+ SEGMENT: 'SEGMENT',
93
+ SEP: 'SEP',
94
+ DATA: 'DATA',
95
+ EQUALS: 'EQUALS',
96
+ STRING: 'STRING',
97
+ NUMBER: 'NUMBER',
98
+ OPEN_PAREN: 'OPEN_PAREN',
99
+ CLOSE_PAREN: 'CLOSE_PAREN',
100
+ PIPE: 'PIPE',
101
+ WHITESPACE: 'WHITESPACE',
102
+ RAW_OPEN: 'RAW_OPEN',
103
+ RAW_CONTENT: 'RAW_CONTENT',
104
+ RAW_CLOSE: 'RAW_CLOSE',
105
+ EOF: 'EOF',
106
+ };
107
+
108
+ /**
109
+ * Error thrown for a lexical error the tokenizer detects. Carries the absolute source
110
+ * `offset` so W2b can produce the plan's class-(b) "Unrecognized text" error at the right
111
+ * position, and a `kind` discriminator for diagnostics.
112
+ */
113
+ export class TokenizerError extends Error {
114
+ /**
115
+ * @param {string} message - Generic message (W2b owns the final wording).
116
+ * @param {number} offset - Absolute offset (UTF-16 code unit) where the error was detected.
117
+ * @param {string} kind - Short discriminator, e.g. `'unterminated-string'`,
118
+ * `'unterminated-comment'`, `'unterminated-raw-block'`, `'unterminated-segment'`.
119
+ */
120
+ constructor(message, offset, kind) {
121
+ super(message);
122
+ this.name = 'TokenizerError';
123
+ /**
124
+ @type {number} Absolute offset where the lexical error was detected.
125
+ */
126
+ this.offset = offset;
127
+ /**
128
+ @type {string} Short discriminator for the lexical-error kind.
129
+ */
130
+ this.kind = kind;
131
+ }
132
+ }
133
+
134
+ /**
135
+ * Whether `code` is an insignificant whitespace code unit (space/tab/CR/LF/FF/VT).
136
+ *
137
+ * @param {number} code - A UTF-16 code unit.
138
+ * @returns {boolean} True for a whitespace code unit.
139
+ */
140
+ const WHITESPACE_CODES = new Set([32, 9, 10, 13, 12, 11]);
141
+ function isWhitespace(code) {
142
+ return WHITESPACE_CODES.has(code);
143
+ }
144
+
145
+ /**
146
+ * Whether `code` may start or continue a bare identifier segment. Handlebars ids are liberal:
147
+ * anything that is not whitespace and not one of the structural expression characters
148
+ * (`.` `/` `=` `~` `|` `(` `)` `[` `]` `{` `}` `"` `'` `@` `!` `#` `>` `^` `*` `&`) is treated
149
+ * as id text. This keeps `$`, `_`, `-`, digits and unicode letters inside ids.
150
+ *
151
+ * @param {number} code - A UTF-16 code unit.
152
+ * @returns {boolean} True when `code` is legal inside an id lexeme.
153
+ */
154
+ function isIdChar(code) {
155
+ if (isWhitespace(code)) {
156
+ return false;
157
+ }
158
+ switch (code) {
159
+ case 46: // .
160
+ case 47: // /
161
+ case 61: // =
162
+ case 126: // ~
163
+ case 124: // |
164
+ case 40: // (
165
+ case 41: // )
166
+ case 91: // [
167
+ case 93: // ]
168
+ case 123: // {
169
+ case 125: // }
170
+ case 34: // "
171
+ case 39: // '
172
+ case 64: // @
173
+ case 33: // !
174
+ case 35: // #
175
+ case 62: // >
176
+ case 94: // ^
177
+ case 42: // *
178
+ case 38: {
179
+ // &
180
+ return false;
181
+ }
182
+ default: {
183
+ return true;
184
+ }
185
+ }
186
+ }
187
+
188
+ /**
189
+ * Tokenizes a Handlebars template into a flat array of tokens (see the module header for the
190
+ * token contract). The stream always ends with a single {@link TokenType.EOF} token.
191
+ *
192
+ * @param {string} source - The Handlebars (or HTML-with-Handlebars) source to tokenize.
193
+ * @returns {object[]} The token stream. Each token is `{ type, start, end, ...payload }`.
194
+ * @throws {TokenizerError} On a lexical error the tokenizer detects (unterminated string /
195
+ * comment / raw block / segment literal). The error carries `.offset` and `.kind`.
196
+ */
197
+ export function tokenize(source) {
198
+ const length = source.length;
199
+ /**
200
+ @type {object[]}
201
+ */
202
+ const tokens = [];
203
+ let pos = 0;
204
+
205
+ // ── Content scanning ────────────────────────────────────────────────────────────────
206
+ // Outside mustaches. Emit CONTENT runs, handle `\{{` escapes, and dispatch to the
207
+ // right mustache lexer when an unescaped `{{` is reached.
208
+ while (pos < length) {
209
+ const next = source.indexOf('{{', pos);
210
+ if (next === -1) {
211
+ // Remaining text is all content.
212
+ emitContent(pos, length, false);
213
+ break;
214
+ }
215
+ // Determine whether the `{{` at `next` is escaped by an ODD run of backslashes.
216
+ let backslashStart = next;
217
+ while (backslashStart > pos && source.codePointAt(backslashStart - 1) === 92) {
218
+ backslashStart--;
219
+ }
220
+ const backslashCount = next - backslashStart;
221
+ if (backslashCount % 2 === 1) {
222
+ // Odd backslashes → the `{{` is escaped. The last backslash is consumed; content
223
+ // before it (including any preceding escaped-out backslash pairs) is emitted, then
224
+ // the `{{…}}` run is emitted as literal (escaped) content.
225
+ // Content up to the consumed backslash (exclusive of that backslash).
226
+ if (backslashStart + backslashCount - 1 > pos) {
227
+ emitContent(pos, backslashStart + backslashCount - 1, false);
228
+ } else if (pos < backslashStart) {
229
+ emitContent(pos, backslashStart, false);
230
+ }
231
+ // The literal mustache text: from `{{` to the matching `}}` (or end of source).
232
+ const escStart = next;
233
+ const closeIndex = source.indexOf('}}', next + 2);
234
+ const escEnd = closeIndex === -1 ? length : closeIndex + 2;
235
+ emitContent(escStart, escEnd, true);
236
+ pos = escEnd;
237
+ continue;
238
+ }
239
+ // Unescaped `{{`. Emit any content before it, then lex the mustache/comment/raw block.
240
+ if (next > pos) {
241
+ emitContent(pos, next, false);
242
+ }
243
+ pos = lexMustacheRegion(next);
244
+ }
245
+
246
+ tokens.push({ type: TokenType.EOF, start: length, end: length });
247
+ return tokens;
248
+
249
+ /**
250
+ * Emits a CONTENT token for `source.slice(start,end)`. Skips empty runs.
251
+ *
252
+ * @param {number} start - Start offset.
253
+ * @param {number} end - End offset.
254
+ * @param {boolean} escaped - Whether this run is an escaped `\{{…}}` literal.
255
+ */
256
+ function emitContent(start, end, escaped) {
257
+ if (end <= start) {
258
+ return;
259
+ }
260
+ tokens.push({
261
+ type: TokenType.CONTENT,
262
+ start,
263
+ end,
264
+ value: source.slice(start, end),
265
+ escaped,
266
+ });
267
+ }
268
+
269
+ /**
270
+ * Lexes a mustache region starting at an unescaped `{{` at `at`. Dispatches to raw-block,
271
+ * comment, or ordinary-mustache lexing. Returns the offset just past the region consumed
272
+ * (for comments and raw blocks that is the whole construct; for ordinary mustaches it is
273
+ * the offset just past the closing delimiter).
274
+ *
275
+ * @param {number} at - Offset of the opening `{`.
276
+ * @returns {number} Offset to resume content scanning from.
277
+ */
278
+ function lexMustacheRegion(at) {
279
+ // Raw block open `{{{{name}}}}` (four braces).
280
+ if (source.startsWith('{{{{', at) && !source.startsWith('{{{{/', at)) {
281
+ return lexRawBlock(at);
282
+ }
283
+ // Comment `{{! … }}` / `{{!-- … --}}`. A `~` may sit between `{{` and `!`.
284
+ const afterOpen = at + (source.codePointAt(at + 2) === 126 ? 3 : 2); // skip `~`
285
+ if (source.codePointAt(afterOpen) === 33) {
286
+ // `!`
287
+ return lexComment(at);
288
+ }
289
+ return lexMustache(at);
290
+ }
291
+
292
+ /**
293
+ * Lexes a `{{{{name}}}}` raw block: the open, the verbatim body, and the matching
294
+ * `{{{{/name}}}}` close. Inner `{{` in the body are not parsed.
295
+ *
296
+ * @param {number} at - Offset of the opening `{`.
297
+ * @returns {number} Offset just past the `}}}}` of the close.
298
+ * @throws {TokenizerError} When no matching `{{{{/name}}}}` close is found.
299
+ */
300
+ function lexRawBlock(at) {
301
+ const openEnd = source.indexOf('}}}}', at + 4);
302
+ if (openEnd === -1) {
303
+ throw new TokenizerError('unterminated raw block', at, 'unterminated-raw-block');
304
+ }
305
+ const name = source.slice(at + 4, openEnd).trim();
306
+ tokens.push({ type: TokenType.RAW_OPEN, start: at, end: openEnd + 4, name });
307
+ const bodyStart = openEnd + 4;
308
+ const closeMarker = `{{{{/${name}}}}}`;
309
+ const closeStart = source.indexOf(closeMarker, bodyStart);
310
+ if (closeStart === -1) {
311
+ throw new TokenizerError('unterminated raw block', at, 'unterminated-raw-block');
312
+ }
313
+ if (closeStart > bodyStart) {
314
+ tokens.push({
315
+ type: TokenType.RAW_CONTENT,
316
+ start: bodyStart,
317
+ end: closeStart,
318
+ value: source.slice(bodyStart, closeStart),
319
+ });
320
+ }
321
+ const closeEnd = closeStart + closeMarker.length;
322
+ tokens.push({ type: TokenType.RAW_CLOSE, start: closeStart, end: closeEnd, name });
323
+ return closeEnd;
324
+ }
325
+
326
+ /**
327
+ * Lexes a comment `{{! … }}` or `{{!-- … --}}` as a single COMMENT token. The short form
328
+ * ends at the first `}}`; the long form ends at `--}}` and may contain `}}`.
329
+ *
330
+ * @param {number} at - Offset of the opening `{`.
331
+ * @returns {number} Offset just past the closing delimiter.
332
+ * @throws {TokenizerError} When a long `{{!-- --}}` comment is unterminated.
333
+ */
334
+ function lexComment(at) {
335
+ const isOpenStrip = source.codePointAt(at + 2) === 126; // `{{~`
336
+ const sigilStart = at + (isOpenStrip ? 3 : 2); // position of `!`
337
+ const long = source.startsWith('!--', sigilStart);
338
+ const openText = source.slice(at, sigilStart + (long ? 3 : 1));
339
+ if (long) {
340
+ const bodyStart = sigilStart + 3;
341
+ const term = source.indexOf('--', bodyStart);
342
+ if (term === -1) {
343
+ throw new TokenizerError('unterminated comment', at, 'unterminated-comment');
344
+ }
345
+ // After `--` there may be a `~` then `}}`.
346
+ let cursor = term + 2;
347
+ const isCloseStrip = source.codePointAt(cursor) === 126;
348
+ if (isCloseStrip) {
349
+ cursor++;
350
+ }
351
+ if (!source.startsWith('}}', cursor)) {
352
+ throw new TokenizerError('unterminated comment', at, 'unterminated-comment');
353
+ }
354
+ const closeEnd = cursor + 2;
355
+ tokens.push({
356
+ type: TokenType.COMMENT,
357
+ start: at,
358
+ end: closeEnd,
359
+ value: source.slice(bodyStart, term),
360
+ long: true,
361
+ open: openText,
362
+ close: source.slice(term, closeEnd),
363
+ strip: isOpenStrip,
364
+ closeStrip: isCloseStrip,
365
+ });
366
+ return closeEnd;
367
+ }
368
+ // Short comment: body up to the first `}}` (optionally preceded by `~`).
369
+ const bodyStart = sigilStart + 1;
370
+ const term = source.indexOf('}}', bodyStart);
371
+ if (term === -1) {
372
+ throw new TokenizerError('unterminated comment', at, 'unterminated-comment');
373
+ }
374
+ // A short comment cannot legally strip on close via `~}}` differently, but upstream
375
+ // still recognises `~}}`; capture it if the char before `}}` is `~`.
376
+ const isCloseStrip = term > bodyStart && source.codePointAt(term - 1) === 126;
377
+ const valueEnd = isCloseStrip ? term - 1 : term;
378
+ const closeEnd = term + 2;
379
+ tokens.push({
380
+ type: TokenType.COMMENT,
381
+ start: at,
382
+ end: closeEnd,
383
+ value: source.slice(bodyStart, valueEnd),
384
+ long: false,
385
+ open: openText,
386
+ close: source.slice(isCloseStrip ? term - 1 : term, closeEnd),
387
+ strip: isOpenStrip,
388
+ closeStrip: isCloseStrip,
389
+ });
390
+ return closeEnd;
391
+ }
392
+
393
+ /**
394
+ * Lexes an ordinary mustache `{{ … }}` / `{{{ … }}}` (with optional `~` strip flags and a
395
+ * leading sigil), emitting an OPEN token, the inside-expression tokens, and a CLOSE token.
396
+ *
397
+ * @param {number} at - Offset of the opening `{`.
398
+ * @returns {number} Offset just past the closing delimiter (or the end of source when the
399
+ * mustache is unterminated — the parser reports the missing close).
400
+ */
401
+ function lexMustache(at) {
402
+ // Count opening braces (2 or 3; four was handled as a raw block).
403
+ const braceCount = source.codePointAt(at + 2) === 123 ? 3 : 2;
404
+ let cursor = at + braceCount;
405
+ const isOpenStrip = source.codePointAt(cursor) === 126; // `~`
406
+ if (isOpenStrip) {
407
+ cursor++;
408
+ }
409
+ tokens.push({
410
+ type: TokenType.OPEN,
411
+ start: at,
412
+ end: cursor,
413
+ open: '{'.repeat(braceCount),
414
+ strip: isOpenStrip,
415
+ });
416
+ // Optional leading sigil.
417
+ cursor = lexSigil(cursor);
418
+ // Inside-expression tokens up to the closing delimiter.
419
+ cursor = lexExpression(cursor);
420
+ return cursor;
421
+ }
422
+
423
+ /**
424
+ * Emits a SIGIL token when a leading sigil (`#`, `/`, `^`, `>`, `#>`, `*`, `#*`, `&`) sits
425
+ * at `cursor` (right after the open, possibly after leading whitespace is NOT skipped —
426
+ * upstream requires the sigil to be adjacent). Returns the offset after the sigil, or
427
+ * `cursor` unchanged when none is present.
428
+ *
429
+ * @param {number} cursor - Offset right after the open delimiter (and its `~`).
430
+ * @returns {number} Offset after the sigil (or unchanged).
431
+ */
432
+ function lexSigil(cursor) {
433
+ const c0 = source.codePointAt(cursor);
434
+ // Two-char sigils first: `#>` and `#*`.
435
+ if (c0 === 35) {
436
+ // `#`
437
+ const c1 = source.codePointAt(cursor + 1);
438
+ if (c1 === 62) {
439
+ // `#>`
440
+ tokens.push({ type: TokenType.SIGIL, start: cursor, end: cursor + 2, value: '#>' });
441
+ return cursor + 2;
442
+ }
443
+ if (c1 === 42) {
444
+ // `#*`
445
+ tokens.push({ type: TokenType.SIGIL, start: cursor, end: cursor + 2, value: '#*' });
446
+ return cursor + 2;
447
+ }
448
+ tokens.push({ type: TokenType.SIGIL, start: cursor, end: cursor + 1, value: '#' });
449
+ return cursor + 1;
450
+ }
451
+ switch (c0) {
452
+ case 47: // /
453
+ case 94: // ^
454
+ case 62: // >
455
+ case 42: // *
456
+ case 38: {
457
+ // &
458
+ const value = source[cursor];
459
+ tokens.push({ type: TokenType.SIGIL, start: cursor, end: cursor + 1, value });
460
+ return cursor + 1;
461
+ }
462
+ default: {
463
+ return cursor;
464
+ }
465
+ }
466
+ }
467
+
468
+ /**
469
+ * Lexes the inside-expression token stream from `cursor` up to and including the closing
470
+ * mustache delimiter (`}}` / `}}}`, with an optional `~` strip). Emits ID / SEGMENT / SEP /
471
+ * DATA / EQUALS / STRING / NUMBER / paren / PIPE / WHITESPACE tokens, then a CLOSE token.
472
+ *
473
+ * @param {number} cursor - Offset to start lexing the expression body from.
474
+ * @returns {number} Offset just past the closing delimiter (or end of source if unterminated).
475
+ */
476
+ function lexExpression(cursor) {
477
+ while (cursor < length) {
478
+ // Closing delimiter? A `~` may precede `}}` / `}}}`.
479
+ const isCloseStrip = source.codePointAt(cursor) === 126;
480
+ const closeAt = isCloseStrip ? cursor + 1 : cursor;
481
+ if (source.startsWith('}}', closeAt)) {
482
+ const isTriple = source.codePointAt(closeAt + 2) === 125; // `}}}`
483
+ const braces = isTriple ? 3 : 2;
484
+ const closeEnd = closeAt + braces;
485
+ tokens.push({
486
+ type: TokenType.CLOSE,
487
+ start: cursor,
488
+ end: closeEnd,
489
+ close: '}'.repeat(braces),
490
+ strip: isCloseStrip,
491
+ });
492
+ return closeEnd;
493
+ }
494
+ const code = source.codePointAt(cursor);
495
+ if (isWhitespace(code)) {
496
+ const ws = scanWhile(cursor, isWhitespace);
497
+ tokens.push({ type: TokenType.WHITESPACE, start: cursor, end: ws });
498
+ cursor = ws;
499
+ continue;
500
+ }
501
+ cursor = lexExpressionAtom(cursor, code);
502
+ }
503
+ // Reached end of source without a close delimiter: leave it to the parser.
504
+ return cursor;
505
+ }
506
+
507
+ /**
508
+ * Lexes a single inside-expression atom at `cursor`. Returns the offset after it.
509
+ *
510
+ * @param {number} cursor - Offset of the atom's first code unit.
511
+ * @param {number} code - `source.codePointAt(cursor)` (already read by the caller).
512
+ * @returns {number} Offset just past the atom.
513
+ * @throws {TokenizerError} On an unterminated string or segment literal.
514
+ */
515
+ function lexExpressionAtom(cursor, code) {
516
+ switch (code) {
517
+ case 34: // "
518
+ case 39: {
519
+ // '
520
+ return lexString(cursor, code);
521
+ }
522
+ case 91: {
523
+ // [
524
+ return lexSegment(cursor);
525
+ }
526
+ case 40: {
527
+ // (
528
+ tokens.push({ type: TokenType.OPEN_PAREN, start: cursor, end: cursor + 1 });
529
+ return cursor + 1;
530
+ }
531
+ case 41: {
532
+ // )
533
+ tokens.push({ type: TokenType.CLOSE_PAREN, start: cursor, end: cursor + 1 });
534
+ return cursor + 1;
535
+ }
536
+ case 124: {
537
+ // |
538
+ tokens.push({ type: TokenType.PIPE, start: cursor, end: cursor + 1 });
539
+ return cursor + 1;
540
+ }
541
+ case 61: {
542
+ // =
543
+ tokens.push({ type: TokenType.EQUALS, start: cursor, end: cursor + 1 });
544
+ return cursor + 1;
545
+ }
546
+ case 64: {
547
+ // @
548
+ tokens.push({ type: TokenType.DATA, start: cursor, end: cursor + 1 });
549
+ return cursor + 1;
550
+ }
551
+ case 46: {
552
+ // . (either `.` or `..`)
553
+ if (source.codePointAt(cursor + 1) === 46) {
554
+ tokens.push({
555
+ type: TokenType.SEP,
556
+ start: cursor,
557
+ end: cursor + 2,
558
+ value: '..',
559
+ });
560
+ return cursor + 2;
561
+ }
562
+ tokens.push({ type: TokenType.SEP, start: cursor, end: cursor + 1, value: '.' });
563
+ return cursor + 1;
564
+ }
565
+ case 47: {
566
+ // /
567
+ tokens.push({ type: TokenType.SEP, start: cursor, end: cursor + 1, value: '/' });
568
+ return cursor + 1;
569
+ }
570
+ default: {
571
+ if (isNumberStart(cursor, code)) {
572
+ return lexNumber(cursor);
573
+ }
574
+ return lexId(cursor);
575
+ }
576
+ }
577
+ }
578
+
579
+ /**
580
+ * Whether a number literal begins at `cursor`. A leading `-` counts only when followed by a
581
+ * digit; a bare digit also starts a number. (Distinguishing `NumberLiteral` from a numeric
582
+ * `PathExpression` such as `0x1` is the parser's job — the tokenizer lexes the run as
583
+ * NUMBER when it is purely numeric, else as ID.)
584
+ *
585
+ * @param {number} cursor - Offset to test.
586
+ * @param {number} code - `source.codePointAt(cursor)`.
587
+ * @returns {boolean} True when a numeric literal starts here.
588
+ */
589
+ function isNumberStart(cursor, code) {
590
+ if (code >= 48 && code <= 57) {
591
+ return true;
592
+ }
593
+ if (code === 45) {
594
+ // `-` followed by a digit
595
+ const c1 = source.codePointAt(cursor + 1);
596
+ return c1 >= 48 && c1 <= 57;
597
+ }
598
+ return false;
599
+ }
600
+
601
+ /**
602
+ * Lexes a numeric literal (optional leading `-`, digits, optional single `.` fraction).
603
+ * A trailing `.` with no fraction digit is treated as a path separator, not part of the
604
+ * number.
605
+ *
606
+ * @param {number} cursor - Offset of the number's first code unit.
607
+ * @returns {number} Offset just past the number.
608
+ */
609
+ function lexNumber(cursor) {
610
+ let index = cursor;
611
+ if (source.codePointAt(index) === 45) {
612
+ index++;
613
+ }
614
+ while (index < length && isDigit(source.codePointAt(index))) {
615
+ index++;
616
+ }
617
+ // Fractional part: `.` immediately followed by a digit.
618
+ if (source.codePointAt(index) === 46 && isDigit(source.codePointAt(index + 1))) {
619
+ index++;
620
+ while (index < length && isDigit(source.codePointAt(index))) {
621
+ index++;
622
+ }
623
+ }
624
+ tokens.push({
625
+ type: TokenType.NUMBER,
626
+ start: cursor,
627
+ end: index,
628
+ value: source.slice(cursor, index),
629
+ });
630
+ return index;
631
+ }
632
+
633
+ /**
634
+ * Lexes a bare identifier / path segment run of {@link isIdChar} code units.
635
+ *
636
+ * @param {number} cursor - Offset of the id's first code unit.
637
+ * @returns {number} Offset just past the id.
638
+ */
639
+ function lexId(cursor) {
640
+ const end = scanWhile(cursor, isIdChar);
641
+ // A lone character that is not an id char would produce a zero-length id; consume one
642
+ // code unit as an id to guarantee progress (the parser will reject stray characters).
643
+ const effectiveEnd = end > cursor ? end : cursor + 1;
644
+ tokens.push({
645
+ type: TokenType.ID,
646
+ start: cursor,
647
+ end: effectiveEnd,
648
+ value: source.slice(cursor, effectiveEnd),
649
+ });
650
+ return effectiveEnd;
651
+ }
652
+
653
+ /**
654
+ * Lexes a segment literal `[ … ]`. The inner text (which may contain spaces and dots) is
655
+ * captured verbatim with the brackets removed.
656
+ *
657
+ * @param {number} cursor - Offset of the opening `[`.
658
+ * @returns {number} Offset just past the closing `]`.
659
+ * @throws {TokenizerError} When the segment literal is unterminated.
660
+ */
661
+ function lexSegment(cursor) {
662
+ const close = source.indexOf(']', cursor + 1);
663
+ if (close === -1) {
664
+ throw new TokenizerError(
665
+ 'unterminated segment literal',
666
+ cursor,
667
+ 'unterminated-segment',
668
+ );
669
+ }
670
+ tokens.push({
671
+ type: TokenType.SEGMENT,
672
+ start: cursor,
673
+ end: close + 1,
674
+ value: source.slice(cursor + 1, close),
675
+ });
676
+ return close + 1;
677
+ }
678
+
679
+ /**
680
+ * Lexes a string literal delimited by `quote` (`"` or `'`), resolving backslash escapes in
681
+ * the decoded `value`. `start`/`end` span the quotes.
682
+ *
683
+ * @param {number} cursor - Offset of the opening quote.
684
+ * @param {number} quote - The quote code unit (34 for `"`, 39 for `'`).
685
+ * @returns {number} Offset just past the closing quote.
686
+ * @throws {TokenizerError} When the string is unterminated.
687
+ */
688
+ function lexString(cursor, quote) {
689
+ let index = cursor + 1;
690
+ let value = '';
691
+ while (index < length) {
692
+ const code = source.codePointAt(index);
693
+ if (code === 92) {
694
+ // backslash escape: keep the escaped char literally (\" -> ", \\ -> \, etc.)
695
+ const escaped = source[index + 1];
696
+ if (escaped === undefined) {
697
+ break;
698
+ }
699
+ value += escaped;
700
+ index += 2;
701
+ continue;
702
+ }
703
+ if (code === quote) {
704
+ tokens.push({
705
+ type: TokenType.STRING,
706
+ start: cursor,
707
+ end: index + 1,
708
+ value,
709
+ quote: String.fromCodePoint(quote),
710
+ });
711
+ return index + 1;
712
+ }
713
+ value += source[index];
714
+ index++;
715
+ }
716
+ throw new TokenizerError('unterminated string', cursor, 'unterminated-string');
717
+ }
718
+
719
+ /**
720
+ * Scans forward from `start` while `predicate(code)` holds. Returns the first offset where
721
+ * it fails (or `length`).
722
+ *
723
+ * @param {number} start - Offset to start scanning from.
724
+ * @param {(code: number) => boolean} predicate - Per-code-unit test.
725
+ * @returns {number} The first offset at which the predicate fails.
726
+ */
727
+ function scanWhile(start, predicate) {
728
+ let index = start;
729
+ while (index < length && predicate(source.codePointAt(index))) {
730
+ index++;
731
+ }
732
+ return index;
733
+ }
734
+ }
735
+
736
+ /**
737
+ * Whether `code` is an ASCII digit `0`–`9`.
738
+ *
739
+ * @param {number} code - A UTF-16 code unit.
740
+ * @returns {boolean} True for an ASCII digit.
741
+ */
742
+ function isDigit(code) {
743
+ return code >= 48 && code <= 57;
744
+ }
745
+
746
+ /**
747
+ * Convenience wrapper: tokenizes `source` and returns both the token stream and a
748
+ * {@link import('./loc.js').LineTable} so callers can convert token offsets to positions
749
+ * without rebuilding the table.
750
+ *
751
+ * @param {string} source - The Handlebars source to tokenize.
752
+ * @returns {{tokens: object[], lineTable: import('./loc.js').LineTable}} The tokens and line table.
753
+ * @throws {TokenizerError} On a lexical error (see {@link tokenize}).
754
+ */
755
+ export function tokenizeWithLineTable(source) {
756
+ return { tokens: tokenize(source), lineTable: buildLineTable(source) };
757
+ }