sfmc-handlebars-parser 0.1.1 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -58,7 +58,10 @@ It accepts every construct `@handlebars/parser@2.2.2` accepts:
58
58
 
59
59
  On a malformed template, `parse` throws. Parse errors mirror the two upstream error
60
60
  classes: a Jison-class error carries `hash.loc` (`{first_line, first_column, last_line,
61
- last_column}`); an exception-class error carries `lineNumber` / `column`.
61
+ last_column}`); an exception-class error carries `lineNumber` (1-based) / `column`
62
+ (0-based). The positions follow upstream. The messages are our own, one line each, and say
63
+ what is wrong, for example `Unclosed block {{#if}}: expected {{/if}}.`. Every error has a
64
+ position, including an expression that is still being typed.
62
65
 
63
66
  ```js
64
67
  import { parse } from 'sfmc-handlebars-parser';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "sfmc-handlebars-parser",
3
- "version": "0.1.1",
3
+ "version": "0.2.0",
4
4
  "description": "Zero-dependency Handlebars parser producing the @handlebars/parser AST contract for SFMC tooling",
5
5
  "type": "module",
6
6
  "main": "./src/index.js",
package/src/errors.js CHANGED
@@ -11,7 +11,7 @@
11
11
  * `first_column` and reports the real position.
12
12
  * - {@link HandlebarsException} — the **exception-class** logic error (block-name mismatch,
13
13
  * `Invalid path:`, lexical "Unrecognized text"). Carries NO `hash`; instead it MAY set
14
- * `lineNumber` / `column` (1-based line, 1-based column, matching upstream's `Exception`).
14
+ * `lineNumber` / `column` (1-based line, 0-based column, matching upstream's `Exception`).
15
15
  * When it carries neither (the lexical case), the wrapper falls back to reporting `1:1`.
16
16
  *
17
17
  * The golden error projection (`tests/golden/errors.baseline.json`) classifies an error as
@@ -53,9 +53,9 @@ export class HandlebarsException extends Error {
53
53
  /**
54
54
  * @param {string} message - The diagnostic message (the ` - line:column` suffix, if any, is
55
55
  * expected to already be appended by the caller for the logic-error cases).
56
- * @param {object} [position] - Optional 1-based line / 1-based column of the error.
56
+ * @param {object} [position] - Optional 1-based line / 0-based column of the error.
57
57
  * @param {number} [position.lineNumber] - 1-based line number.
58
- * @param {number} [position.column] - 1-based column number.
58
+ * @param {number} [position.column] - 0-based column number.
59
59
  */
60
60
  constructor(message, position) {
61
61
  super(message);
package/src/expression.js CHANGED
@@ -26,7 +26,33 @@
26
26
  */
27
27
 
28
28
  import { TokenType } from './tokenizer.js';
29
- import { HandlebarsException } from './errors.js';
29
+ import { HandlebarsException, HandlebarsParseError } from './errors.js';
30
+
31
+ /**
32
+ * Readable names of the tokens `expect()` can ask for, for error messages.
33
+ */
34
+ const TOKEN_DESCRIPTIONS = {
35
+ CLOSE: "'}}'",
36
+ CLOSE_PAREN: "')'",
37
+ OPEN: "'{{'",
38
+ OPEN_PAREN: "'('",
39
+ EQUALS: "'='",
40
+ PIPE: "'|'",
41
+ ID: 'a name',
42
+ SIGIL: 'a block sigil',
43
+ RAW_CLOSE: "'}}}}'",
44
+ RAW_OPEN: "'{{{{'",
45
+ };
46
+
47
+ /**
48
+ * Readable name of a token type.
49
+ *
50
+ * @param {string} type - A {@link import('./tokenizer.js').TokenType} value.
51
+ * @returns {string} The description used in error messages.
52
+ */
53
+ function describeToken(type) {
54
+ return TOKEN_DESCRIPTIONS[type] ?? type;
55
+ }
30
56
  import { offsetToPosition } from './loc.js';
31
57
  import {
32
58
  booleanLiteral,
@@ -121,8 +147,9 @@ export function createReader(tokens, table, source) {
121
147
  },
122
148
 
123
149
  /**
124
- * Consumes the current token, asserting its `type`. Throws a plain `Error` (W2b owns
125
- * user-facing error classes) when the type does not match.
150
+ * Consumes the current token, asserting its `type`. Throws a {@link HandlebarsParseError}
151
+ * on the unexpected token (or the end of the source) when the type does not match. This
152
+ * position is best effort: it is not part of the upstream parity gate.
126
153
  *
127
154
  * @param {string} type - The expected {@link import('./tokenizer.js').TokenType}.
128
155
  * @returns {object} The consumed token.
@@ -130,8 +157,22 @@ export function createReader(tokens, table, source) {
130
157
  expect(type) {
131
158
  const token = tokens[reader.index];
132
159
  if (!token || token.type !== type) {
133
- throw new Error(
134
- `expected ${type} but found ${token ? token.type : 'end of input'}`,
160
+ const isAtEnd = !token || token.type === TokenType.EOF;
161
+ const startOffset = isAtEnd ? source.length : token.start;
162
+ const endOffset = isAtEnd ? source.length : token.end;
163
+ const found = isAtEnd
164
+ ? 'the end of the template'
165
+ : `'${source.slice(startOffset, endOffset)}'`;
166
+ const start = offsetToPosition(table, startOffset);
167
+ const end = offsetToPosition(table, endOffset);
168
+ throw new HandlebarsParseError(
169
+ `Expected ${describeToken(type)} but found ${found}.`,
170
+ {
171
+ first_line: start.line,
172
+ first_column: start.column,
173
+ last_line: end.line,
174
+ last_column: end.column,
175
+ },
135
176
  );
136
177
  }
137
178
  reader.index++;
package/src/index.js CHANGED
@@ -87,7 +87,12 @@ export function parse(code) {
87
87
  // A well-formed block-free template consumes every token up to EOF.
88
88
  if (!reader.atEnd()) {
89
89
  const token = reader.peek();
90
- throw jisonAt(lineTable, token.start, token.end);
90
+ throw jisonAt(
91
+ lineTable,
92
+ token.start,
93
+ token.end,
94
+ `Unexpected '${code.slice(token.start, token.end)}'.`,
95
+ );
91
96
  }
92
97
  // Upstream spans the Program from its FIRST child's start to its LAST child's end (the
93
98
  // per-node `loc`s already account for escaped content trimming a leading `\`). An empty
@@ -158,7 +163,7 @@ export function parseProgram(reader, isTerminator) {
158
163
  // an unexpected INVERSE token at statement level. Upstream throws a Jison parse
159
164
  // error at `1:0`; reproduce that here (W2b-1 owns bare-caret).
160
165
  if (sigil.value === '^' && isBareInverse(reader)) {
161
- throw jisonAt(reader.table, 0, 0);
166
+ throw jisonAt(reader.table, 0, 0, '{{^}} is only allowed inside a block.');
162
167
  }
163
168
  body.push(parseBlockLike(reader));
164
169
  continue;
@@ -168,13 +173,23 @@ export function parseProgram(reader, isTerminator) {
168
173
  // at the opener (`got 'INVERSE'`). Block bodies consume their own `{{else}}` via the
169
174
  // terminator, so this only fires for a stray/top-level else.
170
175
  if (sigil && sigil.type === TokenType.ID && sigil.value === 'else') {
171
- throw jisonAt(reader.table, token.start, token.start);
176
+ throw jisonAt(
177
+ reader.table,
178
+ token.start,
179
+ token.start,
180
+ '{{else}} is only allowed inside a block.',
181
+ );
172
182
  }
173
183
  body.push(parseMustache(reader));
174
184
  continue;
175
185
  }
176
186
  // Any other statement-level token here is unexpected (e.g. a stray CLOSE / SIGIL).
177
- throw jisonAt(reader.table, token.start, token.end);
187
+ throw jisonAt(
188
+ reader.table,
189
+ token.start,
190
+ token.end,
191
+ `Unexpected '${reader.source.slice(token.start, token.end)}'.`,
192
+ );
178
193
  }
179
194
  return body;
180
195
  }
@@ -270,10 +285,25 @@ function parseMustache(reader) {
270
285
  isEscaped = false;
271
286
  reader.next();
272
287
  }
288
+ // A closing tag without an open block (`{{/if}}`) reaches here as a plain mustache.
289
+ if (reader.peekType() === TokenType.SIGIL && reader.peek().value === '/') {
290
+ const name = /^\{\{~?\s*\/\s*([^\s}~]*)/.exec(reader.source.slice(open.start))?.[1] ?? '';
291
+ throw jisonAt(
292
+ reader.table,
293
+ open.start,
294
+ open.end,
295
+ `{{/${name}}} has no matching {{#${name}}} before it.`,
296
+ );
297
+ }
273
298
  reader.skipWhitespace();
274
299
  // Empty body (`{{ }}`) — upstream throws a Jison parse error anchored at the OPEN token.
275
300
  if (reader.peekType() === TokenType.CLOSE) {
276
- throw jisonAt(reader.table, open.start, open.end);
301
+ throw jisonAt(
302
+ reader.table,
303
+ open.start,
304
+ open.end,
305
+ 'Empty expression: write a helper or a value between the braces.',
306
+ );
277
307
  }
278
308
  const head = parseCallHead(reader, open);
279
309
  const { params, hash } = parseParametersAndHash(
@@ -281,6 +311,17 @@ function parseMustache(reader) {
281
311
  (token) => token.type === TokenType.CLOSE,
282
312
  );
283
313
  reader.skipWhitespace();
314
+ // A missing `}}` (an expression still being typed, `{{upp`) is reported on the opener, where
315
+ // upstream reports the single-word case; other shapes are best effort (not parity-gated).
316
+ if (reader.peekType() !== TokenType.CLOSE) {
317
+ const typed = /^\{\{\{?[^\s{}]*/.exec(reader.source.slice(open.start))?.[0] ?? '{{';
318
+ throw jisonAt(
319
+ reader.table,
320
+ open.start,
321
+ open.end,
322
+ `Unclosed expression ${typed}: expected '}}'.`,
323
+ );
324
+ }
284
325
  const close = reader.expect(TokenType.CLOSE);
285
326
  const strip = { open: !!open.strip, close: !!close.strip };
286
327
  return mustacheStatement(
@@ -327,7 +368,12 @@ function parseCallHead(reader, open) {
327
368
  next && [TokenType.ID, TokenType.NUMBER, TokenType.SEGMENT].includes(next.type);
328
369
  const isCurrentContext = token.value === '.' && !nextIsSegment;
329
370
  if (!isSlashContinue && !isParentContext && !isCurrentContext) {
330
- throw jisonAt(reader.table, open.start, open.end);
371
+ throw jisonAt(
372
+ reader.table,
373
+ open.start,
374
+ open.end,
375
+ "Invalid path: a name cannot follow a leading '.'.",
376
+ );
331
377
  }
332
378
  }
333
379
  return parsePath(reader);
@@ -497,7 +543,7 @@ function consumeCloseTag(reader, openName, openPath) {
497
543
  if (closePath.original !== openName) {
498
544
  const at = openPath.loc.start;
499
545
  throw new HandlebarsException(
500
- `${openName} doesn't match ${closePath.original} - ${at.line}:${at.column}`,
546
+ `{{/${closePath.original}}} does not close {{#${openName}}}. Expected {{/${openName}}}.`,
501
547
  { lineNumber: at.line, column: at.column },
502
548
  );
503
549
  }
@@ -511,17 +557,21 @@ function consumeCloseTag(reader, openName, openPath) {
511
557
  * close was expected (the next token, typically `EOF`), e.g. `got 'EOF'`.
512
558
  *
513
559
  * @param {object} reader - The shared cursor, positioned where a close/inverse was expected.
560
+ * @param {string} [name] - The open block's name, for the message.
514
561
  * @returns {never} Always throws.
515
562
  * @throws {HandlebarsParseError} The Jison-class unclosed-block error.
516
563
  */
517
- function throwUnclosed(reader) {
564
+ function throwUnclosed(reader, name) {
565
+ const message = name
566
+ ? `Unclosed block {{#${name}}}: expected {{/${name}}}.`
567
+ : 'Unclosed block: expected its closing tag.';
518
568
  // Upstream anchors an unclosed block at the last consumed token through the point where the
519
569
  // close was expected (typically `EOF`): e.g. `{{#alpha}}x` reports `1:10`-`1:11` (the `x`
520
570
  // content start through `EOF`). Span `[previousToken.start, currentToken.end]`.
521
571
  const current = reader.peek() || { start: reader.source.length, end: reader.source.length };
522
572
  const previous = reader.peek(-1);
523
573
  const startOffset = previous ? previous.start : current.start;
524
- throw jisonAt(reader.table, startOffset, current.end);
574
+ throw jisonAt(reader.table, startOffset, current.end, message);
525
575
  }
526
576
 
527
577
  /**
@@ -550,7 +600,7 @@ function parseBlockStatement(reader, isCaret) {
550
600
  // Body statements until an inverse split or the `{{/name}}` close.
551
601
  const body = parseProgram(reader, () => atBranchEnd(reader));
552
602
  if (reader.atEnd()) {
553
- throwUnclosed(reader);
603
+ throwUnclosed(reader, path.original);
554
604
  }
555
605
  const bodyEnd = reader.peek().start;
556
606
  const bodyProgram = makeSubProgram(reader, body, bodyStart, bodyEnd, {
@@ -571,7 +621,7 @@ function parseBlockStatement(reader, isCaret) {
571
621
 
572
622
  // Consume the matching `{{/name}}` close.
573
623
  if (!isCloseTag(reader)) {
574
- throwUnclosed(reader);
624
+ throwUnclosed(reader, path.original);
575
625
  }
576
626
  const { closeToken } = consumeCloseTag(reader, path.original, path);
577
627
  return blockStatement(reader.table, open.start, closeToken.end, {
@@ -619,7 +669,7 @@ function parseInverseBranch(reader, blockPath) {
619
669
  const bodyStart = elseClose.end;
620
670
  const body = parseProgram(reader, () => atBranchEnd(reader));
621
671
  if (reader.atEnd()) {
622
- throwUnclosed(reader);
672
+ throwUnclosed(reader, blockPath.original);
623
673
  }
624
674
  const bodyEnd = reader.peek().start;
625
675
  const inverse = makeSubProgram(reader, body, bodyStart, bodyEnd);
@@ -667,7 +717,7 @@ function parseChainedBlock(reader, blockPath) {
667
717
 
668
718
  const body = parseProgram(reader, () => atBranchEnd(reader));
669
719
  if (reader.atEnd()) {
670
- throwUnclosed(reader);
720
+ throwUnclosed(reader, blockPath.original);
671
721
  }
672
722
  const bodyEnd = reader.peek().start;
673
723
  const primaryProgram = makeSubProgram(reader, body, bodyStart, bodyEnd, {
@@ -678,7 +728,7 @@ function parseChainedBlock(reader, blockPath) {
678
728
 
679
729
  // The nested block ends at the shared `{{/name}}` close's OPEN start (not consumed here).
680
730
  if (!isCloseTag(reader)) {
681
- throwUnclosed(reader);
731
+ throwUnclosed(reader, blockPath.original);
682
732
  }
683
733
  const closeOpenStart = reader.peek().start;
684
734
  const block = blockStatement(reader.table, open.start, closeOpenStart, {
@@ -934,12 +984,13 @@ function parseDecoratorBlock(reader) {
934
984
  * @param {import('./loc.js').LineTable} table - Line table for the source.
935
985
  * @param {number} startOffset - Absolute start offset of the error span.
936
986
  * @param {number} endOffset - Absolute end offset of the error span.
987
+ * @param {string} message - What is wrong, in one line (the span is reported separately).
937
988
  * @returns {HandlebarsParseError} The Jison-class parse error.
938
989
  */
939
- function jisonAt(table, startOffset, endOffset) {
990
+ function jisonAt(table, startOffset, endOffset, message) {
940
991
  const start = offsetToPosition(table, startOffset);
941
992
  const end = offsetToPosition(table, endOffset);
942
- return new HandlebarsParseError('Parse error', {
993
+ return new HandlebarsParseError(message, {
943
994
  first_line: start.line,
944
995
  first_column: start.column,
945
996
  last_line: end.line,
@@ -970,11 +1021,16 @@ function convertTokenizerError(error, source) {
970
1021
  // Jison class. Upstream anchors at the preceding call-head token (the id before the
971
1022
  // opening quote). Locate the maximal id run ending just before the quote at `error.offset`.
972
1023
  const { start, end } = precedingIdSpan(source, error.offset);
973
- return jisonAt(buildLineTable(source), start, end);
1024
+ return jisonAt(
1025
+ buildLineTable(source),
1026
+ start,
1027
+ end,
1028
+ 'Unterminated string: the closing quote is missing.',
1029
+ );
974
1030
  }
975
1031
  // Other lexical kinds (unterminated raw block / segment) belong to W2b-2's block surface;
976
1032
  // surface them as a Jison error at the reported offset for now.
977
- return jisonAt(buildLineTable(source), error.offset, error.offset);
1033
+ return jisonAt(buildLineTable(source), error.offset, error.offset, error.message);
978
1034
  }
979
1035
 
980
1036
  /**