sfmc-sql-converter 0.0.0-stage → 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.
@@ -0,0 +1,956 @@
1
+ /**
2
+ * Reads Marketing Cloud Next Handlebars `query` / `queryFirst` calls back into the SQL AST of
3
+ * `parseSql`: `{{#each (query type="CRM" object="X" fields="A,B" where="A = :p1"
4
+ * params=(hash p1="v") sortBy="A ASC" limit=5)}}`, `{{get (queryFirst …) "A"}}` and the
5
+ * marketing object form `(query type="MO" object="X" Key__c="v")`.
6
+ *
7
+ * Only deterministic input converts: every value in `where` must be a `:name` placeholder that
8
+ * `params` defines exactly once (Next fails on literals in `where`). The code is read as text;
9
+ * it is never executed. Never throws.
10
+ */
11
+
12
+ import { nextLikeInner, nextLikeWildcardMessage } from './clauses.js';
13
+ import {
14
+ INVALID_ARGUMENT,
15
+ INVALID_COUNT,
16
+ INVALID_FILTER,
17
+ INVALID_FILTER_VALUE,
18
+ INVALID_ORDER_BY,
19
+ LIKE_MATCHES_ANYWHERE,
20
+ LOOKUP_FIRST_ROW_ONLY,
21
+ MISSING_CLOSING_PAREN,
22
+ MULTIPLE_LOOKUPS,
23
+ NO_LOOKUP_FOUND,
24
+ SYNTAX_ERROR,
25
+ UNKNOWN_FILTER_OPERATOR,
26
+ UNTERMINATED_STRING,
27
+ } from './messages.js';
28
+ import {
29
+ createContext,
30
+ fail,
31
+ makeLoc,
32
+ parseOrderString,
33
+ rejectEmpty,
34
+ report,
35
+ runParser,
36
+ } from './reverse-common.js';
37
+
38
+ const CALL_PATTERN = /(\{\{#?|\()\s*(queryFirst|query)(?=\s)/g;
39
+ const GET_BEFORE = /\{\{\s*get\s*\($/;
40
+ const HB_IDENT = /[A-Za-z_][\w.]*/y;
41
+ const HB_NUMBER = /-?\d+(?:\.\d+)?/y;
42
+ const WHERE_TOKEN =
43
+ /\s+|(:[A-Za-z_]\w*)|(!=|<>|<=|>=|=|<|>)|([()])|('(?:[^']|'')*'|"[^"]*"|-?\d+(?:\.\d+)?)|([A-Za-z_]\w*)|(.)/gy;
44
+ const BODY_FIELD = /\{\{\s*([A-Za-z_]\w*)\s*\}\}/g;
45
+ const OPERATORS = { '=': '=', '!=': '<>', '<>': '<>', '<': '<', '<=': '<=', '>': '>', '>=': '>=' };
46
+ const CRM_KEYS = new Set(['type', 'object', 'fields', 'where', 'params', 'sortBy', 'limit']);
47
+ const MO_FORBIDDEN = new Set(['fields', 'where', 'params', 'sortBy', 'limit']);
48
+
49
+ /**
50
+ * @typedef {object} HbToken
51
+ * @property {'string'|'number'|'ident'|'punct'|'end'} type token type
52
+ * @property {string} value unescaped string, number text, identifier or punctuation
53
+ * @property {number} start 0-based start offset
54
+ * @property {number} end 0-based exclusive end offset
55
+ */
56
+
57
+ /**
58
+ * Reads a Handlebars string literal: `\"` (or `\'`) stands for the quote.
59
+ *
60
+ * @param {object} context parse context
61
+ * @param {number} start offset of the opening quote
62
+ * @returns {HbToken} string token
63
+ */
64
+ function readString(context, start) {
65
+ const { text } = context;
66
+ const quote = text[start];
67
+ let value = '';
68
+ for (let index = start + 1; index < text.length; index++) {
69
+ const character = text[index];
70
+ if (character === '\\' && text[index + 1] === quote) {
71
+ value += quote;
72
+ index++;
73
+ } else if (character === quote) {
74
+ return { type: 'string', value, start, end: index + 1 };
75
+ } else {
76
+ value += character;
77
+ }
78
+ }
79
+ return fail(
80
+ context,
81
+ UNTERMINATED_STRING,
82
+ `This text value is never closed. Add the closing quote (${quote}).`,
83
+ start,
84
+ text.length,
85
+ );
86
+ }
87
+
88
+ /**
89
+ * Reads the next token of a Handlebars expression.
90
+ *
91
+ * @param {object} context parse context
92
+ * @param {number} index offset
93
+ * @returns {HbToken} token
94
+ */
95
+ function readToken(context, index) {
96
+ const { text } = context;
97
+ const character = text[index];
98
+ if (character === '"' || character === "'") {
99
+ return readString(context, index);
100
+ }
101
+ if (text.startsWith('}}', index)) {
102
+ return { type: 'end', value: '}}', start: index, end: index + 2 };
103
+ }
104
+ for (const [pattern, type] of [
105
+ [HB_NUMBER, 'number'],
106
+ [HB_IDENT, 'ident'],
107
+ ]) {
108
+ pattern.lastIndex = index;
109
+ const match = pattern.exec(text);
110
+ if (match) {
111
+ return { type, value: match[0], start: index, end: index + match[0].length };
112
+ }
113
+ }
114
+ return { type: 'punct', value: character, start: index, end: index + 1 };
115
+ }
116
+
117
+ /**
118
+ * Tokenizes from an offset up to the `)` that closes the call (depth 0) or the next `}}`.
119
+ *
120
+ * @param {object} context parse context
121
+ * @param {number} from offset after the helper name
122
+ * @param {boolean} isInBrackets true when the call is a `( … )` sub-expression
123
+ * @returns {{tokens: HbToken[], end: number}} tokens of the arguments and the end offset
124
+ */
125
+ function tokenizeCall(context, from, isInBrackets) {
126
+ const { text } = context;
127
+ const tokens = [];
128
+ let depth = 0;
129
+ let index = from;
130
+ while (index < text.length) {
131
+ if (/\s/.test(text[index])) {
132
+ index++;
133
+ continue;
134
+ }
135
+ const token = readToken(context, index);
136
+ index = token.end;
137
+ if (!isInBrackets && token.type === 'end') {
138
+ return { tokens, end: token.end };
139
+ }
140
+ if (token.type === 'punct' && token.value === '(') {
141
+ depth++;
142
+ } else if (token.type === 'punct' && token.value === ')') {
143
+ if (depth === 0 && isInBrackets) {
144
+ return { tokens, end: token.end };
145
+ }
146
+ depth--;
147
+ }
148
+ tokens.push(token);
149
+ }
150
+ return fail(
151
+ context,
152
+ MISSING_CLOSING_PAREN,
153
+ isInBrackets
154
+ ? 'This call is never closed. Add a closing bracket ) after the last parameter.'
155
+ : 'This call is never closed. Add }} after the last parameter.',
156
+ from,
157
+ text.length,
158
+ );
159
+ }
160
+
161
+ /**
162
+ * Reads named parameters `key=value`; a value is a string, a number, an identifier or a
163
+ * `(hash …)` sub-expression.
164
+ *
165
+ * @param {object} context parse context
166
+ * @param {HbToken[]} tokens tokens
167
+ * @param {number} position index to start at
168
+ * @param {number} stop index to stop at
169
+ * @returns {Map<string, {key: HbToken, value: HbToken|Map}>} parameters in source order
170
+ */
171
+ function readHash(context, tokens, position, stop) {
172
+ const hash = new Map();
173
+ let index = position;
174
+ while (index < stop) {
175
+ const key = tokens[index];
176
+ const equals = tokens[index + 1];
177
+ if (key.type !== 'ident' || equals?.value !== '=') {
178
+ fail(
179
+ context,
180
+ INVALID_ARGUMENT,
181
+ `Expected a named parameter such as object="Contact" but found "${key.value}". Write every parameter as name=value.`,
182
+ key.start,
183
+ key.end,
184
+ );
185
+ }
186
+ if (hash.has(key.value)) {
187
+ fail(
188
+ context,
189
+ INVALID_ARGUMENT,
190
+ `The parameter ${key.value} is given twice. Keep one.`,
191
+ key.start,
192
+ key.end,
193
+ );
194
+ }
195
+ const value = tokens[index + 2];
196
+ if (!value) {
197
+ fail(
198
+ context,
199
+ SYNTAX_ERROR,
200
+ `The parameter ${key.value} has no value.`,
201
+ key.start,
202
+ equals.end,
203
+ );
204
+ }
205
+ if (value.type === 'punct' && value.value === '(') {
206
+ const close = matchingClose(tokens, index + 2);
207
+ const head = tokens[index + 3];
208
+ if (head?.type !== 'ident' || head.value !== 'hash') {
209
+ fail(
210
+ context,
211
+ INVALID_ARGUMENT,
212
+ `${key.value} must be a plain value or (hash name=value …).`,
213
+ value.start,
214
+ tokens[close].end,
215
+ );
216
+ }
217
+ hash.set(key.value, {
218
+ key,
219
+ value: readHash(context, tokens, index + 4, close),
220
+ end: tokens[close].end,
221
+ });
222
+ index = close + 1;
223
+ continue;
224
+ }
225
+ if (value.type === 'punct') {
226
+ fail(
227
+ context,
228
+ SYNTAX_ERROR,
229
+ `Unexpected "${value.value}" after ${key.value}=.`,
230
+ value.start,
231
+ value.end,
232
+ );
233
+ }
234
+ hash.set(key.value, { key, value, end: value.end });
235
+ index += 3;
236
+ }
237
+ return hash;
238
+ }
239
+
240
+ /**
241
+ * Finds the `)` that closes the `(` at an index.
242
+ *
243
+ * @param {HbToken[]} tokens tokens
244
+ * @param {number} open index of the "("
245
+ * @returns {number} index of the matching ")"
246
+ */
247
+ function matchingClose(tokens, open) {
248
+ let depth = 0;
249
+ for (let index = open; index < tokens.length; index++) {
250
+ if (tokens[index].value === '(' && tokens[index].type === 'punct') {
251
+ depth++;
252
+ } else if (tokens[index].value === ')' && tokens[index].type === 'punct') {
253
+ depth--;
254
+ if (depth === 0) {
255
+ return index;
256
+ }
257
+ }
258
+ }
259
+ return tokens.length - 1;
260
+ }
261
+
262
+ /**
263
+ * Returns a string parameter or fails.
264
+ *
265
+ * @param {object} context parse context
266
+ * @param {Map} hash parameters
267
+ * @param {string} key parameter name
268
+ * @param {string} hint how to write it
269
+ * @param {number} callStart start offset of the call (for a missing parameter)
270
+ * @returns {HbToken} string token
271
+ */
272
+ function requireString(context, hash, key, hint, callStart) {
273
+ const entry = hash.get(key);
274
+ if (!entry) {
275
+ fail(
276
+ context,
277
+ INVALID_ARGUMENT,
278
+ `The call has no ${key}. Add ${hint}.`,
279
+ callStart,
280
+ callStart,
281
+ );
282
+ }
283
+ if (
284
+ !(entry.value instanceof Map) &&
285
+ entry.value.type === 'string' &&
286
+ entry.value.value.trim()
287
+ ) {
288
+ return entry.value;
289
+ }
290
+ return fail(
291
+ context,
292
+ INVALID_ARGUMENT,
293
+ `${key} must be text in double quotes, e.g. ${hint}.`,
294
+ entry.key.start,
295
+ entry.end,
296
+ );
297
+ }
298
+
299
+ /**
300
+ * Splits a comma-separated field list into column nodes.
301
+ *
302
+ * @param {object} context parse context
303
+ * @param {HbToken} token string token
304
+ * @returns {{name: string, loc: object}[]} columns
305
+ */
306
+ function readFields(context, token) {
307
+ const isExact = context.text.slice(token.start + 1, token.end - 1) === token.value;
308
+ const columns = [];
309
+ let offset = 0;
310
+ for (const part of token.value.split(',')) {
311
+ const name = part.trim();
312
+ const start = isExact ? token.start + 1 + offset + part.indexOf(name) : token.start;
313
+ const end = isExact ? start + name.length : token.end;
314
+ if (!name) {
315
+ fail(
316
+ context,
317
+ INVALID_ARGUMENT,
318
+ 'The field list has an empty entry. Separate the field names with single commas.',
319
+ token.start,
320
+ token.end,
321
+ );
322
+ }
323
+ columns.push({ name, loc: makeLoc(context, start, end) });
324
+ offset += part.length + 1;
325
+ }
326
+ return columns;
327
+ }
328
+
329
+ /**
330
+ * Builds the value of a condition from a parameter. The token type alone sets the kind: Next
331
+ * keeps the type, so p1="5" is text and p1=5 a number.
332
+ *
333
+ * @param {object} context parse context
334
+ * @param {{key: HbToken, value: HbToken}} entry parameter
335
+ * @returns {object} AST value
336
+ */
337
+ function paramValue(context, entry) {
338
+ const { value } = entry;
339
+ if (value instanceof Map || (value.type !== 'string' && value.type !== 'number')) {
340
+ fail(
341
+ context,
342
+ INVALID_FILTER_VALUE,
343
+ `The parameter ${entry.key.value} must be text in double quotes or a number.`,
344
+ entry.key.start,
345
+ entry.end,
346
+ );
347
+ }
348
+ return {
349
+ kind: value.type === 'number' ? 'number' : 'string',
350
+ value: value.value,
351
+ loc: makeLoc(context, value.start, value.end),
352
+ };
353
+ }
354
+
355
+ /**
356
+ * Tokenizes a where string.
357
+ *
358
+ * @param {object} context parse context
359
+ * @param {HbToken} token where string token
360
+ * @returns {{type: string, value: string, start: number, end: number}[]} tokens (offsets in
361
+ * the source text when the string has no escapes, else the whole string)
362
+ */
363
+ function whereTokens(context, token) {
364
+ const isExact = context.text.slice(token.start + 1, token.end - 1) === token.value;
365
+ const base = token.start + 1;
366
+ const types = ['param', 'op', 'bracket', 'literal', 'word', 'other'];
367
+ const tokens = [];
368
+ WHERE_TOKEN.lastIndex = 0;
369
+ for (let match = WHERE_TOKEN.exec(token.value); match; match = WHERE_TOKEN.exec(token.value)) {
370
+ const group = match.slice(1).findIndex((part) => part !== undefined);
371
+ if (group === -1) {
372
+ continue;
373
+ }
374
+ tokens.push({
375
+ type: types[group],
376
+ value: match[0],
377
+ start: isExact ? base + match.index : token.start,
378
+ end: isExact ? base + match.index + match[0].length : token.end,
379
+ });
380
+ }
381
+ tokens.push({ type: 'eof', value: '', start: token.end - 1, end: token.end - 1 });
382
+ return tokens;
383
+ }
384
+
385
+ /**
386
+ * Checks whether a where token is the given keyword.
387
+ *
388
+ * @param {{type: string, value: string}} item where token
389
+ * @param {string} word upper-case keyword
390
+ * @returns {boolean} true when it matches
391
+ */
392
+ function isWord(item, word) {
393
+ return item.type === 'word' && item.value.toUpperCase() === word;
394
+ }
395
+
396
+ /**
397
+ * Parses a where string into conditions; each `:name` must be defined once in params.
398
+ *
399
+ * @param {object} context parse context
400
+ * @param {HbToken} token where string token
401
+ * @param {Map} params parameters from `(hash …)`
402
+ * @returns {object} expression node
403
+ */
404
+ function parseWhere(context, token, params) {
405
+ const tokens = whereTokens(context, token);
406
+ const used = new Set();
407
+ let position = 0;
408
+ const peek = () => tokens[position];
409
+
410
+ const parseCondition = () => {
411
+ const column = peek();
412
+ if (column.type === 'bracket' && column.value === '(') {
413
+ position++;
414
+ const inner = parseOr();
415
+ const close = peek();
416
+ if (close.value !== ')') {
417
+ fail(
418
+ context,
419
+ MISSING_CLOSING_PAREN,
420
+ 'A bracket in where is never closed.',
421
+ column.start,
422
+ column.end,
423
+ );
424
+ }
425
+ position++;
426
+ return inner;
427
+ }
428
+ if (column.type !== 'word' || ['AND', 'OR', 'LIKE'].includes(column.value.toUpperCase())) {
429
+ fail(
430
+ context,
431
+ INVALID_FILTER,
432
+ `Expected a field name in where but found "${column.value || 'the end'}".`,
433
+ column.start,
434
+ column.end,
435
+ );
436
+ }
437
+ position++;
438
+ const operator = peek();
439
+ const isLike = isWord(operator, 'LIKE');
440
+ if (!isLike && operator.type !== 'op') {
441
+ fail(
442
+ context,
443
+ UNKNOWN_FILTER_OPERATOR,
444
+ `Expected an operator (=, !=, <, <=, >, >= or LIKE) after ${column.value} in where.`,
445
+ operator.start,
446
+ operator.end,
447
+ );
448
+ }
449
+ position++;
450
+ const placeholder = peek();
451
+ if (placeholder.type === 'literal') {
452
+ fail(
453
+ context,
454
+ INVALID_FILTER_VALUE,
455
+ `The value ${placeholder.value} is written into where. Next fails on values in where: use a placeholder such as :p1 and add it to params=(hash p1=…).`,
456
+ placeholder.start,
457
+ placeholder.end,
458
+ );
459
+ }
460
+ if (placeholder.type !== 'param') {
461
+ fail(
462
+ context,
463
+ INVALID_FILTER_VALUE,
464
+ `Expected a placeholder such as :p1 after ${column.value} ${operator.value}.`,
465
+ placeholder.start,
466
+ placeholder.end,
467
+ );
468
+ }
469
+ position++;
470
+ const name = placeholder.value.slice(1);
471
+ if (used.has(name)) {
472
+ fail(
473
+ context,
474
+ INVALID_FILTER,
475
+ `The placeholder :${name} is used twice. Give every condition its own placeholder, so the query reads back the same way.`,
476
+ placeholder.start,
477
+ placeholder.end,
478
+ );
479
+ }
480
+ used.add(name);
481
+ const entry = params.get(name);
482
+ if (!entry) {
483
+ fail(
484
+ context,
485
+ INVALID_FILTER,
486
+ `The placeholder :${name} has no value. Add ${name}=… to params=(hash …).`,
487
+ placeholder.start,
488
+ placeholder.end,
489
+ );
490
+ }
491
+ const value = paramValue(context, entry);
492
+ const loc = makeLoc(context, column.start, Math.max(placeholder.end, column.end));
493
+ if (!isLike) {
494
+ return {
495
+ type: 'compare',
496
+ op: OPERATORS[operator.value],
497
+ column: column.value,
498
+ value,
499
+ loc,
500
+ };
501
+ }
502
+ if (value.kind === 'number') {
503
+ fail(
504
+ context,
505
+ INVALID_FILTER_VALUE,
506
+ `LIKE needs a text value; write ${name}="%…%".`,
507
+ entry.key.start,
508
+ entry.end,
509
+ );
510
+ }
511
+ return { type: 'like', column: column.value, pattern: likePattern(context, value), loc };
512
+ };
513
+
514
+ const parseAnd = () => {
515
+ let left = parseCondition();
516
+ while (isWord(peek(), 'AND')) {
517
+ position++;
518
+ const right = parseCondition();
519
+ left = {
520
+ type: 'and',
521
+ left,
522
+ right,
523
+ loc: makeLoc(context, left.loc.start, right.loc.end),
524
+ };
525
+ }
526
+ return left;
527
+ };
528
+
529
+ const parseOr = () => {
530
+ let left = parseAnd();
531
+ while (isWord(peek(), 'OR')) {
532
+ position++;
533
+ const right = parseAnd();
534
+ left = {
535
+ type: 'or',
536
+ left,
537
+ right,
538
+ loc: makeLoc(context, left.loc.start, right.loc.end),
539
+ };
540
+ }
541
+ return left;
542
+ };
543
+
544
+ const expression = parseOr();
545
+ if (peek().type !== 'eof') {
546
+ fail(
547
+ context,
548
+ INVALID_FILTER,
549
+ `Unexpected "${peek().value}" in where. Join conditions with AND or OR.`,
550
+ peek().start,
551
+ peek().end,
552
+ );
553
+ }
554
+ for (const [name, entry] of params) {
555
+ if (!used.has(name)) {
556
+ fail(
557
+ context,
558
+ INVALID_FILTER,
559
+ `params defines ${name}, but where does not use :${name}. Remove it or use it in where.`,
560
+ entry.key.start,
561
+ entry.end,
562
+ );
563
+ }
564
+ }
565
+ return expression;
566
+ }
567
+
568
+ /**
569
+ * Turns a LIKE parameter into the SQL pattern: Next matches "contains", so plain text such as
570
+ * `Ro%` becomes `%Ro%` with a warning; `_`, `[` or `%` inside the text fail (no SQL equivalent).
571
+ *
572
+ * @param {object} context parse context
573
+ * @param {object} value AST value
574
+ * @returns {object} AST value holding the SQL pattern
575
+ */
576
+ function likePattern(context, value) {
577
+ const parts = nextLikeInner(value.value);
578
+ if (!parts) {
579
+ fail(
580
+ context,
581
+ INVALID_FILTER_VALUE,
582
+ nextLikeWildcardMessage(value.value),
583
+ value.loc.start,
584
+ value.loc.end,
585
+ );
586
+ }
587
+ const { inner } = parts;
588
+ if (parts.isContains) {
589
+ return { ...value, kind: 'string' };
590
+ }
591
+ report(
592
+ context,
593
+ 'warning',
594
+ LIKE_MATCHES_ANYWHERE,
595
+ `Next matches LIKE as "contains" and ignores wildcards, so "${value.value}" is converted as '%${inner}%'.`,
596
+ value.loc.start,
597
+ value.loc.end,
598
+ );
599
+ return { ...value, kind: 'string', value: `%${inner}%` };
600
+ }
601
+
602
+ /**
603
+ * Reads the fields of a marketing object query from the block body (`{{Field}}` lines).
604
+ *
605
+ * @param {object} context parse context
606
+ * @param {number} from offset after the opening block
607
+ * @returns {'*'|{name: string, loc: object}[]} columns
608
+ */
609
+ function bodyFields(context, from) {
610
+ const close = context.text.indexOf('{{/each', from);
611
+ const body = context.text.slice(from, close === -1 ? context.text.length : close);
612
+ const columns = [];
613
+ BODY_FIELD.lastIndex = 0;
614
+ for (let match = BODY_FIELD.exec(body); match; match = BODY_FIELD.exec(body)) {
615
+ if (match[1] === 'else' || match[1] === 'this') {
616
+ continue;
617
+ }
618
+ const start = from + match.index + match[0].indexOf(match[1]);
619
+ columns.push({ name: match[1], loc: makeLoc(context, start, start + match[1].length) });
620
+ }
621
+ return columns.length ? columns : '*';
622
+ }
623
+
624
+ /**
625
+ * Reads the field after `(queryFirst …)` in `{{get (queryFirst …) "Field"}}`. With a field list
626
+ * the field must be in it (case ignored): Next renders an unlisted field as empty (DB
627
+ * `mcn-handlebars-email-query.json#checklist[30]`).
628
+ *
629
+ * @param {object} context parse context
630
+ * @param {number} from offset after the closing ")"
631
+ * @param {'*'|{name: string}[]} listed fields of the call (`*` when it has no list)
632
+ * @returns {{name: string, loc: object}} column
633
+ */
634
+ function getField(context, from, listed) {
635
+ let index = from;
636
+ while (/\s/.test(context.text[index] ?? '')) {
637
+ index++;
638
+ }
639
+ const token = readToken(context, index);
640
+ if (token.type !== 'string' || !token.value.trim()) {
641
+ fail(
642
+ context,
643
+ INVALID_ARGUMENT,
644
+ 'Write the field to read after the call: {{get (queryFirst …) "Field"}}.',
645
+ token.start,
646
+ token.end,
647
+ );
648
+ }
649
+ const name = token.value.toLowerCase();
650
+ if (Array.isArray(listed) && listed.every((column) => column.name.toLowerCase() !== name)) {
651
+ fail(
652
+ context,
653
+ INVALID_ARGUMENT,
654
+ `"${token.value}" is not in the fields of the call, so Next renders it empty. Add it to fields="…" or read a listed field.`,
655
+ token.start,
656
+ token.end,
657
+ );
658
+ }
659
+ return { name: token.value, loc: makeLoc(context, token.start, token.end) };
660
+ }
661
+
662
+ /**
663
+ * Reads the parameters of a CRM call into the parts of the AST.
664
+ *
665
+ * @param {object} context parse context
666
+ * @param {Map} hash parameters
667
+ * @param {{isFirst: boolean, callStart: number}} call call details
668
+ * @returns {{columns: object[], where: object|null, orderBy: object[], top: number|null}} parts
669
+ */
670
+ function readCrm(context, hash, call) {
671
+ for (const [key, entry] of hash) {
672
+ if (!CRM_KEYS.has(key)) {
673
+ fail(
674
+ context,
675
+ INVALID_ARGUMENT,
676
+ `${key} is not a parameter of a Sales Cloud query. Use fields, where, params, sortBy and limit.`,
677
+ entry.key.start,
678
+ entry.end,
679
+ );
680
+ }
681
+ }
682
+ const fields = requireString(
683
+ context,
684
+ hash,
685
+ 'fields',
686
+ 'fields="LastName,FirstName"',
687
+ call.callStart,
688
+ );
689
+ const columns = readFields(context, fields);
690
+ let where = null;
691
+ const params = hash.get('params');
692
+ if (hash.has('where')) {
693
+ const token = requireString(
694
+ context,
695
+ hash,
696
+ 'where',
697
+ 'where="LastName = :p1"',
698
+ call.callStart,
699
+ );
700
+ if (params && !(params.value instanceof Map)) {
701
+ fail(
702
+ context,
703
+ INVALID_FILTER,
704
+ 'params must be (hash p1=… p2=…) with a value for every placeholder.',
705
+ params.key.start,
706
+ params.end,
707
+ );
708
+ }
709
+ where = parseWhere(context, token, params?.value ?? new Map());
710
+ } else if (params) {
711
+ fail(
712
+ context,
713
+ INVALID_FILTER,
714
+ 'params is given without where. Add where="Field = :p1" or remove params.',
715
+ params.key.start,
716
+ params.end,
717
+ );
718
+ }
719
+ let orderBy = [];
720
+ if (hash.has('sortBy')) {
721
+ const sortBy = requireString(
722
+ context,
723
+ hash,
724
+ 'sortBy',
725
+ 'sortBy="LastName ASC"',
726
+ call.callStart,
727
+ );
728
+ orderBy = parseOrderString(context, sortBy);
729
+ if (orderBy.length > 1) {
730
+ fail(
731
+ context,
732
+ INVALID_ORDER_BY,
733
+ 'Next sorts by one field only (sortBy="Field ASC"). Keep one field, or sort the rows in your code.',
734
+ sortBy.start,
735
+ sortBy.end,
736
+ );
737
+ }
738
+ }
739
+ let top = call.isFirst ? 1 : null;
740
+ const limit = hash.get('limit');
741
+ if (limit) {
742
+ if (call.isFirst) {
743
+ fail(
744
+ context,
745
+ INVALID_ARGUMENT,
746
+ 'queryFirst returns one record; remove limit.',
747
+ limit.key.start,
748
+ limit.end,
749
+ );
750
+ }
751
+ if (limit.value instanceof Map || !/^[1-9]\d*$/.test(limit.value.value)) {
752
+ fail(
753
+ context,
754
+ INVALID_COUNT,
755
+ 'limit must be a whole number of records, e.g. limit=10.',
756
+ limit.key.start,
757
+ limit.end,
758
+ );
759
+ }
760
+ top = Number(limit.value.value);
761
+ }
762
+ return { columns, where, orderBy, top };
763
+ }
764
+
765
+ /**
766
+ * Reads the parameters of a marketing object call: inline filters `Field=value` (AND) and an
767
+ * optional `limit` (not on queryFirst).
768
+ *
769
+ * @param {object} context parse context
770
+ * @param {Map} hash parameters
771
+ * @param {{isFirst: boolean, start: number}} call call details
772
+ * @returns {{where: object, top: number|null}} WHERE expression and row limit
773
+ */
774
+ function readMoFilter(context, hash, call) {
775
+ const conditions = [];
776
+ let top = call.isFirst ? 1 : null;
777
+ for (const [key, entry] of hash) {
778
+ if (key === 'type' || key === 'object') {
779
+ continue;
780
+ }
781
+ if (key === 'limit' && !call.isFirst) {
782
+ if (entry.value instanceof Map || !/^[1-9]\d*$/.test(entry.value.value)) {
783
+ fail(
784
+ context,
785
+ INVALID_COUNT,
786
+ 'limit must be a whole number of records, e.g. limit=10.',
787
+ entry.key.start,
788
+ entry.end,
789
+ );
790
+ }
791
+ top = Number(entry.value.value);
792
+ continue;
793
+ }
794
+ if (MO_FORBIDDEN.has(key)) {
795
+ fail(
796
+ context,
797
+ INVALID_ARGUMENT,
798
+ `${key} is not supported on a marketing object in Next. Filter with inline conditions, e.g. Key__c="value".`,
799
+ entry.key.start,
800
+ entry.end,
801
+ );
802
+ }
803
+ conditions.push({
804
+ type: 'compare',
805
+ op: '=',
806
+ column: entry.key.value,
807
+ value: paramValue(context, entry),
808
+ loc: makeLoc(context, entry.key.start, entry.end),
809
+ });
810
+ }
811
+ if (conditions.length === 0) {
812
+ fail(
813
+ context,
814
+ INVALID_FILTER,
815
+ 'A marketing object query needs at least one inline filter, e.g. Key__c="value"; Next fails without one.',
816
+ call.start,
817
+ call.start,
818
+ );
819
+ }
820
+ let where = conditions[0];
821
+ for (const condition of conditions.slice(1)) {
822
+ where = {
823
+ type: 'and',
824
+ left: where,
825
+ right: condition,
826
+ loc: makeLoc(context, where.loc.start, condition.loc.end),
827
+ };
828
+ }
829
+ return { where, top };
830
+ }
831
+
832
+ /**
833
+ * Finds the query / queryFirst calls.
834
+ *
835
+ * @param {string} text source text
836
+ * @returns {{start: number, nameEnd: number, isFirst: boolean, isInBrackets: boolean}[]} calls
837
+ */
838
+ function findCalls(text) {
839
+ const calls = [];
840
+ CALL_PATTERN.lastIndex = 0;
841
+ for (let match = CALL_PATTERN.exec(text); match; match = CALL_PATTERN.exec(text)) {
842
+ const nameStart = match.index + match[0].length - match[2].length;
843
+ calls.push({
844
+ start: match[1] === '(' ? match.index : nameStart,
845
+ nameStart,
846
+ nameEnd: nameStart + match[2].length,
847
+ isFirst: match[2] === 'queryFirst',
848
+ isInBrackets: match[1] === '(',
849
+ });
850
+ }
851
+ return calls;
852
+ }
853
+
854
+ /**
855
+ * Parses the first call and builds the AST.
856
+ *
857
+ * @param {object} context parse context
858
+ * @param {object} meta meta data (mutated)
859
+ * @returns {object} SELECT AST
860
+ */
861
+ function parseProgram(context, meta) {
862
+ const calls = findCalls(context.text);
863
+ if (calls.length === 0) {
864
+ fail(
865
+ context,
866
+ NO_LOOKUP_FOUND,
867
+ 'No Handlebars query was found. Paste a {{#each (query …)}} or {{get (queryFirst …) "Field"}} call.',
868
+ 0,
869
+ context.text.length,
870
+ );
871
+ }
872
+ const [call] = calls;
873
+ if (calls.length > 1) {
874
+ report(
875
+ context,
876
+ 'warning',
877
+ MULTIPLE_LOOKUPS,
878
+ 'The code contains more than one query; only the first one is converted.',
879
+ calls[1].nameStart,
880
+ calls[1].nameEnd,
881
+ );
882
+ }
883
+ const { tokens, end } = tokenizeCall(context, call.nameEnd, call.isInBrackets);
884
+ const hash = readHash(context, tokens, 0, tokens.length);
885
+ const callLoc = makeLoc(context, call.start, end);
886
+ const type = requireString(context, hash, 'type', 'type="CRM"', call.start);
887
+ const dataSource = type.value.toUpperCase();
888
+ if (dataSource !== 'CRM' && dataSource !== 'MO') {
889
+ fail(
890
+ context,
891
+ INVALID_ARGUMENT,
892
+ 'type must be "CRM" (Sales Cloud object) or "MO" (marketing object).',
893
+ type.start,
894
+ type.end,
895
+ );
896
+ }
897
+ const object = requireString(context, hash, 'object', 'object="Contact"', call.start);
898
+ const isGet =
899
+ call.isFirst && call.isInBrackets && GET_BEFORE.test(context.text.slice(0, call.start + 1));
900
+ meta.dataSource = dataSource;
901
+ meta.deName = object.value;
902
+ let parts;
903
+ if (dataSource === 'CRM') {
904
+ meta.target = call.isFirst ? 'handlebars-queryfirst' : 'handlebars-query';
905
+ parts = readCrm(context, hash, { isFirst: call.isFirst, callStart: call.start });
906
+ } else {
907
+ meta.target = 'handlebars-query-mo';
908
+ parts = {
909
+ columns: call.isFirst ? '*' : bodyFields(context, end),
910
+ ...readMoFilter(context, hash, call),
911
+ orderBy: [],
912
+ };
913
+ }
914
+ if (isGet) {
915
+ parts.columns = [getField(context, end, parts.columns)];
916
+ }
917
+ if (call.isFirst) {
918
+ report(
919
+ context,
920
+ 'info',
921
+ LOOKUP_FIRST_ROW_ONLY,
922
+ 'queryFirst returns the first matching record only, which TOP 1 stands for in SQL.',
923
+ call.nameStart,
924
+ call.nameEnd,
925
+ );
926
+ }
927
+ return {
928
+ type: 'select',
929
+ top: parts.top,
930
+ columns: parts.columns,
931
+ from: { name: object.value, loc: makeLoc(context, object.start, object.end) },
932
+ where: parts.where,
933
+ orderBy: parts.orderBy,
934
+ loc: callLoc,
935
+ };
936
+ }
937
+
938
+ /**
939
+ * Reads a Marketing Cloud Next Handlebars query back into the SQL AST. Never throws.
940
+ *
941
+ * @param {string} text Handlebars code
942
+ * @returns {{ast: object|null, messages: import('./messages.js').Message[], meta: {target: string|null, dataSource?: 'CRM'|'MO', deName?: string}}} AST (null on error), messages and meta data
943
+ */
944
+ export function parseHandlebars(text) {
945
+ const source = typeof text === 'string' ? text : '';
946
+ const context = createContext(source);
947
+ const meta = { target: null };
948
+ const ast = runParser(context, () => {
949
+ if (!source.trim()) {
950
+ context.tokens.push({ type: 'eof' });
951
+ rejectEmpty(context);
952
+ }
953
+ return parseProgram(context, meta);
954
+ });
955
+ return { ast, messages: context.messages, meta };
956
+ }