sfmc-sql-converter 0.0.0-stage → 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,804 @@
1
+ /**
2
+ * Shared helpers for the reverse parsers (SSJS and AMPscript code → SQL AST): source
3
+ * positions, messages, a small tokenizer for both languages, the `// SQL:` header comment and
4
+ * value / ORDER BY conversion. Code is only read as text, never executed.
5
+ */
6
+
7
+ import {
8
+ EMPTY_INPUT,
9
+ INTERNAL_ERROR,
10
+ MISSING_CLOSING_PAREN,
11
+ NESTING_TOO_DEEP,
12
+ UNTERMINATED_COMMENT,
13
+ UNTERMINATED_STRING,
14
+ createMessage,
15
+ } from './messages.js';
16
+ import { INVALID_ORDER_BY } from './messages.js';
17
+
18
+ /**
19
+ * @typedef {object} Token
20
+ * @property {'ident'|'string'|'number'|'punct'|'variable'|'eof'} type token type
21
+ * @property {string} value identifier, unescaped string, number text or punctuation
22
+ * @property {number} start 0-based start offset
23
+ * @property {number} end 0-based exclusive end offset
24
+ */
25
+
26
+ /**
27
+ * @typedef {object} Comment
28
+ * @property {number} start 0-based start offset (at the comment opener)
29
+ * @property {number} end 0-based exclusive end offset
30
+ */
31
+
32
+ /**
33
+ * @typedef {object} ReverseContext
34
+ * @property {string} text source text
35
+ * @property {number[]} lineStarts start offset of every line
36
+ * @property {object[]} messages collected messages
37
+ * @property {Token[]} tokens tokens of the code regions
38
+ * @property {Comment[]} comments comments of the code regions
39
+ * @property {number} pos current token index
40
+ */
41
+
42
+ const PLAIN_NUMBER = /^-?(?:0|[1-9]\d*)(?:\.\d+)?$/;
43
+ const JS_IDENT = /[\p{L}_$][\p{L}\p{N}_$]*/uy;
44
+ const AMP_IDENT = /[\p{L}_][\p{L}\p{N}_]*/uy;
45
+ const AMP_VARIABLE = /@[\p{L}\p{N}_]+/uy;
46
+ const NUMBER = /\d+(?:\.\d+)?(?:[eE][+-]?\d+)?/y;
47
+ const WHITESPACE = /\s/;
48
+ const MULTI_PUNCT = [
49
+ '===',
50
+ '!==',
51
+ '==',
52
+ '!=',
53
+ '<=',
54
+ '>=',
55
+ '&&',
56
+ '||',
57
+ '++',
58
+ '--',
59
+ '+=',
60
+ '-=',
61
+ '=>',
62
+ ];
63
+ const JS_ESCAPES = { n: '\n', t: '\t', r: '\r', b: '\b', f: '\f', v: '\v', 0: '\0' };
64
+ // what `~x` in a header comment stands for (see decodeCommentText); `~/` and `~%` drop the `~`
65
+ const COMMENT_UNESCAPES = { '~': '~', q: '"', b: '\\' };
66
+ const SERVER_SCRIPT_OPEN = /<script\b[^>]*\brunat\s*=\s*["']?server["']?[^>]*>/gi;
67
+ const SCRIPT_CLOSE = /<\/script\s*>/gi;
68
+
69
+ /**
70
+ * Internal signal that parsing stopped after an error message was recorded.
71
+ */
72
+ export class ParseStop extends Error {
73
+ /**
74
+ * Creates the stop signal.
75
+ */
76
+ constructor() {
77
+ super('parse stopped');
78
+ this.name = 'ParseStop';
79
+ }
80
+ }
81
+
82
+ /**
83
+ * Creates the parse context.
84
+ *
85
+ * @param {string} text source text
86
+ * @returns {ReverseContext} context
87
+ */
88
+ export function createContext(text) {
89
+ const lineStarts = [0];
90
+ for (let index = text.indexOf('\n'); index !== -1; index = text.indexOf('\n', index + 1)) {
91
+ lineStarts.push(index + 1);
92
+ }
93
+ return { text, lineStarts, messages: [], tokens: [], comments: [], pos: 0 };
94
+ }
95
+
96
+ /**
97
+ * Converts an offset into a 1-based line / column pair.
98
+ *
99
+ * @param {number[]} lineStarts start offset of every line
100
+ * @param {number} offset 0-based offset
101
+ * @returns {{line: number, column: number}} position
102
+ */
103
+ function positionAt(lineStarts, offset) {
104
+ let low = 0;
105
+ let high = lineStarts.length - 1;
106
+ while (low < high) {
107
+ const middle = Math.ceil((low + high) / 2);
108
+ if (lineStarts[middle] <= offset) {
109
+ low = middle;
110
+ } else {
111
+ high = middle - 1;
112
+ }
113
+ }
114
+ return { line: low + 1, column: offset - lineStarts[low] + 1 };
115
+ }
116
+
117
+ /**
118
+ * Builds a location object for an offset range (same shape as the SQL parser's `loc`).
119
+ *
120
+ * @param {ReverseContext} context parse context
121
+ * @param {number} start 0-based start offset
122
+ * @param {number} end 0-based exclusive end offset
123
+ * @returns {{start: number, end: number, line: number, column: number, endLine: number, endColumn: number}} location
124
+ */
125
+ export function makeLoc(context, start, end) {
126
+ const from = positionAt(context.lineStarts, start);
127
+ const to = positionAt(context.lineStarts, end);
128
+ return {
129
+ start,
130
+ end,
131
+ line: from.line,
132
+ column: from.column,
133
+ endLine: to.line,
134
+ endColumn: to.column,
135
+ };
136
+ }
137
+
138
+ /**
139
+ * Records a message.
140
+ *
141
+ * @param {ReverseContext} context parse context
142
+ * @param {'error'|'warning'|'info'} severity severity
143
+ * @param {string} code message code
144
+ * @param {string} message plain-language text
145
+ * @param {number} start 0-based start offset
146
+ * @param {number} end 0-based exclusive end offset
147
+ */
148
+ export function report(context, severity, code, message, start, end) {
149
+ context.messages.push(createMessage(severity, code, message, makeLoc(context, start, end)));
150
+ }
151
+
152
+ /**
153
+ * Records an error and stops parsing.
154
+ *
155
+ * @param {ReverseContext} context parse context
156
+ * @param {string} code message code
157
+ * @param {string} message plain-language text
158
+ * @param {number} start 0-based start offset
159
+ * @param {number} end 0-based exclusive end offset
160
+ * @returns {never} always throws ParseStop
161
+ */
162
+ export function fail(context, code, message, start, end) {
163
+ report(context, 'error', code, message, start, end);
164
+ throw new ParseStop();
165
+ }
166
+
167
+ /**
168
+ * Runs a parser body, turning a stop or an unexpected exception into `null`.
169
+ *
170
+ * @param {ReverseContext} context parse context
171
+ * @param {() => object} body parser body returning the AST
172
+ * @returns {object|null} AST or null after an error
173
+ */
174
+ export function runParser(context, body) {
175
+ try {
176
+ return body();
177
+ } catch (ex) {
178
+ if (!(ex instanceof ParseStop)) {
179
+ const isTooDeep = ex instanceof RangeError;
180
+ report(
181
+ context,
182
+ 'error',
183
+ isTooDeep ? NESTING_TOO_DEEP : INTERNAL_ERROR,
184
+ isTooDeep
185
+ ? 'The code is nested too deeply to read. Simplify the filter.'
186
+ : 'The code could not be read because of an unexpected problem in the parser. Simplify the code and try again.',
187
+ 0,
188
+ context.text.length,
189
+ );
190
+ }
191
+ return null;
192
+ }
193
+ }
194
+
195
+ // ------------------------------------------------------------------------------------------
196
+ // Code regions
197
+ // ------------------------------------------------------------------------------------------
198
+
199
+ /**
200
+ * Finds the bodies of `<script runat="server">` blocks; the whole text when there are none.
201
+ *
202
+ * @param {string} text source text
203
+ * @returns {number[][]} [start, end) offset pairs
204
+ */
205
+ export function findScriptRegions(text) {
206
+ const regions = [];
207
+ SERVER_SCRIPT_OPEN.lastIndex = 0;
208
+ for (let open = SERVER_SCRIPT_OPEN.exec(text); open; open = SERVER_SCRIPT_OPEN.exec(text)) {
209
+ const start = open.index + open[0].length;
210
+ SCRIPT_CLOSE.lastIndex = start;
211
+ const close = SCRIPT_CLOSE.exec(text);
212
+ const end = close ? close.index : text.length;
213
+ regions.push([start, end]);
214
+ SERVER_SCRIPT_OPEN.lastIndex = close ? close.index + close[0].length : text.length;
215
+ }
216
+ return regions.length ? regions : [[0, text.length]];
217
+ }
218
+
219
+ /**
220
+ * Finds the end of an AMPscript block, skipping `"…"` and `'…'` strings (a doubled quote stands
221
+ * for one quote) and `/* … *\/` comments, so a `]%%` inside a string does not end the block.
222
+ *
223
+ * @param {string} text source text
224
+ * @param {number} start offset after the block opener
225
+ * @param {string} closer `]%%` or `=%%`
226
+ * @returns {number} offset of the closer, or -1 when the block never closes
227
+ */
228
+ function findBlockEnd(text, start, closer) {
229
+ let index = start;
230
+ while (index < text.length) {
231
+ const character = text[index];
232
+ if (character === '"' || character === "'") {
233
+ let close = text.indexOf(character, index + 1);
234
+ while (close !== -1 && text[close + 1] === character) {
235
+ close = text.indexOf(character, close + 2);
236
+ }
237
+ if (close === -1) {
238
+ // an unclosed string: fall back to the first closer after it
239
+ return text.indexOf(closer, index);
240
+ }
241
+ index = close + 1;
242
+ } else if (text.startsWith('/*', index)) {
243
+ // a quote inside a comment does not start a string
244
+ const close = text.indexOf('*/', index + 2);
245
+ index = close === -1 ? text.length : close + 2;
246
+ } else if (text.startsWith(closer, index)) {
247
+ return index;
248
+ } else {
249
+ index++;
250
+ }
251
+ }
252
+ return -1;
253
+ }
254
+
255
+ /**
256
+ * Finds the bodies of `%%[ … ]%%` and `%%= … =%%` blocks (a closer inside a string does not
257
+ * count); the whole text when there are none.
258
+ *
259
+ * @param {string} text source text
260
+ * @returns {number[][]} [start, end) offset pairs
261
+ */
262
+ export function findAmpscriptRegions(text) {
263
+ const regions = [];
264
+ let index = 0;
265
+ for (;;) {
266
+ const block = text.indexOf('%%[', index);
267
+ const inline = text.indexOf('%%=', index);
268
+ if (block === -1 && inline === -1) {
269
+ break;
270
+ }
271
+ const isBlock = inline === -1 || (block !== -1 && block < inline);
272
+ const start = (isBlock ? block : inline) + 3;
273
+ const close = findBlockEnd(text, start, isBlock ? ']%%' : '=%%');
274
+ const end = close === -1 ? text.length : close;
275
+ regions.push([start, end]);
276
+ index = close === -1 ? text.length : close + 3;
277
+ }
278
+ return regions.length ? regions : [[0, text.length]];
279
+ }
280
+
281
+ // ------------------------------------------------------------------------------------------
282
+ // Tokenizer
283
+ // ------------------------------------------------------------------------------------------
284
+
285
+ /**
286
+ * Reads a JavaScript string literal (backslash escapes, no line breaks).
287
+ *
288
+ * @param {ReverseContext} context parse context
289
+ * @param {number} start offset of the opening quote
290
+ * @param {number} limit end of the code region
291
+ * @returns {Token} string token
292
+ */
293
+ function readJsString(context, start, limit) {
294
+ const { text } = context;
295
+ const quote = text[start];
296
+ let value = '';
297
+ let index = start + 1;
298
+ while (index < limit) {
299
+ const character = text[index];
300
+ if (character === quote) {
301
+ return { type: 'string', value, start, end: index + 1 };
302
+ }
303
+ if (character === '\n') {
304
+ break;
305
+ }
306
+ if (character === '\\') {
307
+ const next = text[index + 1] ?? '';
308
+ if (next === 'u' && /^[\da-f]{4}$/i.test(text.slice(index + 2, index + 6))) {
309
+ value += String.fromCodePoint(
310
+ Number.parseInt(text.slice(index + 2, index + 6), 16),
311
+ );
312
+ index += 6;
313
+ continue;
314
+ }
315
+ if (next === 'x' && /^[\da-f]{2}$/i.test(text.slice(index + 2, index + 4))) {
316
+ value += String.fromCodePoint(
317
+ Number.parseInt(text.slice(index + 2, index + 4), 16),
318
+ );
319
+ index += 4;
320
+ continue;
321
+ }
322
+ if (next === '\r' && text[index + 2] === '\n') {
323
+ index += 3;
324
+ continue;
325
+ }
326
+ if (next !== '\n') {
327
+ value += JS_ESCAPES[next] ?? next;
328
+ }
329
+ index += 2;
330
+ continue;
331
+ }
332
+ value += character;
333
+ index++;
334
+ }
335
+ return fail(
336
+ context,
337
+ UNTERMINATED_STRING,
338
+ `This text value is never closed. Add the closing quote (${quote}) at the end of the value on the same line.`,
339
+ start,
340
+ Math.min(index, limit),
341
+ );
342
+ }
343
+
344
+ /**
345
+ * Reads an AMPscript string literal (a doubled quote stands for one quote; may span lines).
346
+ *
347
+ * @param {ReverseContext} context parse context
348
+ * @param {number} start offset of the opening quote
349
+ * @param {number} limit end of the code region
350
+ * @returns {Token} string token
351
+ */
352
+ function readAmpString(context, start, limit) {
353
+ const { text } = context;
354
+ const quote = text[start];
355
+ let value = '';
356
+ let index = start + 1;
357
+ while (index < limit) {
358
+ const close = text.indexOf(quote, index);
359
+ if (close === -1 || close >= limit) {
360
+ break;
361
+ }
362
+ value += text.slice(index, close);
363
+ if (text[close + 1] === quote && close + 1 < limit) {
364
+ value += quote;
365
+ index = close + 2;
366
+ } else {
367
+ return { type: 'string', value, start, end: close + 1 };
368
+ }
369
+ }
370
+ return fail(
371
+ context,
372
+ UNTERMINATED_STRING,
373
+ `This text value is never closed. Add the closing quote (${quote}) at the end of the value.`,
374
+ start,
375
+ limit,
376
+ );
377
+ }
378
+
379
+ /**
380
+ * Matches a sticky pattern at an offset.
381
+ *
382
+ * @param {RegExp} pattern sticky pattern
383
+ * @param {string} text source text
384
+ * @param {number} index offset
385
+ * @param {number} limit end of the code region
386
+ * @returns {string|null} matched text or null
387
+ */
388
+ function matchAt(pattern, text, index, limit) {
389
+ pattern.lastIndex = index;
390
+ const match = pattern.exec(text);
391
+ if (!match || index + match[0].length > limit) {
392
+ return null;
393
+ }
394
+ return match[0];
395
+ }
396
+
397
+ /**
398
+ * Reads the token (or comment) at an offset inside a region.
399
+ *
400
+ * @param {ReverseContext} context parse context
401
+ * @param {'js'|'ampscript'} dialect language
402
+ * @param {number} index offset
403
+ * @param {number} limit end of the region
404
+ * @returns {Token|Comment&{comment: true}} token or comment
405
+ */
406
+ function readToken(context, dialect, index, limit) {
407
+ const { text } = context;
408
+ const character = text[index];
409
+ const following = text[index + 1];
410
+ if (character === '/' && following === '/' && dialect === 'js') {
411
+ const newline = text.indexOf('\n', index);
412
+ return {
413
+ comment: true,
414
+ start: index,
415
+ end: newline === -1 || newline > limit ? limit : newline,
416
+ };
417
+ }
418
+ if (character === '/' && following === '*') {
419
+ const close = text.indexOf('*/', index + 2);
420
+ if (close === -1 || close + 2 > limit) {
421
+ fail(
422
+ context,
423
+ UNTERMINATED_COMMENT,
424
+ 'This comment is never closed. Add */ where it should end.',
425
+ index,
426
+ limit,
427
+ );
428
+ }
429
+ return { comment: true, start: index, end: close + 2 };
430
+ }
431
+ if (character === '"' || character === "'") {
432
+ return dialect === 'js'
433
+ ? readJsString(context, index, limit)
434
+ : readAmpString(context, index, limit);
435
+ }
436
+ const number = matchAt(NUMBER, text, index, limit);
437
+ if (number) {
438
+ return { type: 'number', value: number, start: index, end: index + number.length };
439
+ }
440
+ if (dialect === 'ampscript' && character === '@') {
441
+ const variable = matchAt(AMP_VARIABLE, text, index, limit);
442
+ if (variable) {
443
+ return {
444
+ type: 'variable',
445
+ value: variable,
446
+ start: index,
447
+ end: index + variable.length,
448
+ };
449
+ }
450
+ }
451
+ const word = matchAt(dialect === 'js' ? JS_IDENT : AMP_IDENT, text, index, limit);
452
+ if (word) {
453
+ return { type: 'ident', value: word, start: index, end: index + word.length };
454
+ }
455
+ const multi = MULTI_PUNCT.find(
456
+ (symbol) => text.startsWith(symbol, index) && index + symbol.length <= limit,
457
+ );
458
+ const symbol = multi ?? String.fromCodePoint(text.codePointAt(index));
459
+ return { type: 'punct', value: symbol, start: index, end: index + symbol.length };
460
+ }
461
+
462
+ /**
463
+ * Reads the token or comment at an offset and stores it on the context.
464
+ *
465
+ * @param {ReverseContext} context parse context
466
+ * @param {'js'|'ampscript'} dialect language
467
+ * @param {number} index offset
468
+ * @param {number} limit end of the region
469
+ * @returns {number} offset after the token
470
+ */
471
+ function storeToken(context, dialect, index, limit) {
472
+ const token = readToken(context, dialect, index, limit);
473
+ if (token.comment) {
474
+ context.comments.push({ start: token.start, end: token.end });
475
+ } else {
476
+ context.tokens.push(token);
477
+ }
478
+ return token.end;
479
+ }
480
+
481
+ /**
482
+ * Splits the code regions into tokens and comments (stored on the context).
483
+ *
484
+ * @param {ReverseContext} context parse context
485
+ * @param {'js'|'ampscript'} dialect language
486
+ * @param {number[][]} regions [start, end) offset pairs to read
487
+ */
488
+ export function tokenize(context, dialect, regions) {
489
+ for (const [regionStart, limit] of regions) {
490
+ let index = regionStart;
491
+ while (index < limit) {
492
+ index = WHITESPACE.test(context.text[index])
493
+ ? index + 1
494
+ : storeToken(context, dialect, index, limit);
495
+ }
496
+ }
497
+ const length = context.text.length;
498
+ context.tokens.push({ type: 'eof', value: '', start: length, end: length });
499
+ }
500
+
501
+ /**
502
+ * Fails with EMPTY_INPUT when there is no code token at all.
503
+ *
504
+ * @param {ReverseContext} context parse context
505
+ */
506
+ export function rejectEmpty(context) {
507
+ if (context.tokens.length === 1) {
508
+ fail(
509
+ context,
510
+ EMPTY_INPUT,
511
+ 'There is no code to convert. Paste a lookup call such as LookupRows(...) or a filter object.',
512
+ 0,
513
+ context.text.length,
514
+ );
515
+ }
516
+ }
517
+
518
+ /**
519
+ * Returns the token at an absolute index (the eof token when past the end).
520
+ *
521
+ * @param {ReverseContext} context parse context
522
+ * @param {number} index token index
523
+ * @returns {Token} token
524
+ */
525
+ export function tokenAt(context, index) {
526
+ const { tokens } = context;
527
+ return tokens[Math.max(0, Math.min(index, tokens.length - 1))];
528
+ }
529
+
530
+ /**
531
+ * Checks whether a token is the given punctuation.
532
+ *
533
+ * @param {Token} token token
534
+ * @param {string} symbol punctuation text
535
+ * @returns {boolean} true when it matches
536
+ */
537
+ export function isPunct(token, symbol) {
538
+ return token.type === 'punct' && token.value === symbol;
539
+ }
540
+
541
+ /**
542
+ * Checks whether a token is an identifier with the given name (case-insensitive).
543
+ *
544
+ * @param {Token} token token
545
+ * @param {string} name identifier name
546
+ * @returns {boolean} true when it matches
547
+ */
548
+ export function isIdent(token, name) {
549
+ return token.type === 'ident' && token.value.toLowerCase() === name.toLowerCase();
550
+ }
551
+
552
+ /**
553
+ * Finds the end offset of the expression starting at a token index: everything up to the next
554
+ * `,` `)` `]` `}` or `;` outside brackets.
555
+ *
556
+ * @param {ReverseContext} context parse context
557
+ * @param {number} index token index where the expression starts
558
+ * @returns {number} exclusive end offset
559
+ */
560
+ export function expressionEnd(context, index) {
561
+ let depth = 0;
562
+ let end = tokenAt(context, index).end;
563
+ for (let current = index; current < context.tokens.length; current++) {
564
+ const token = context.tokens[current];
565
+ if (token.type === 'eof') {
566
+ break;
567
+ }
568
+ if (token.type === 'punct') {
569
+ if ('([{'.includes(token.value)) {
570
+ depth++;
571
+ } else if (')]}'.includes(token.value)) {
572
+ if (depth === 0) {
573
+ break;
574
+ }
575
+ depth--;
576
+ } else if (depth === 0 && (token.value === ',' || token.value === ';')) {
577
+ break;
578
+ }
579
+ }
580
+ end = token.end;
581
+ }
582
+ return end;
583
+ }
584
+
585
+ /**
586
+ * Fails with MISSING_CLOSING_PAREN for a call whose argument list never closes.
587
+ *
588
+ * @param {ReverseContext} context parse context
589
+ * @param {Token} open the "(" token
590
+ * @returns {never} always throws ParseStop
591
+ */
592
+ export function failUnclosedCall(context, open) {
593
+ fail(
594
+ context,
595
+ MISSING_CLOSING_PAREN,
596
+ 'This argument list is never closed. Add a closing bracket ) after the last argument.',
597
+ open.start,
598
+ open.end,
599
+ );
600
+ }
601
+
602
+ // ------------------------------------------------------------------------------------------
603
+ // Header comment
604
+ // ------------------------------------------------------------------------------------------
605
+
606
+ /**
607
+ * Undoes what the emitters do to names in a header comment (`commentText` in emit-mce.js),
608
+ * reading left to right: `~~` → `~`, `~q` → `"`, `~b` → a backslash, and a `~` before `/` or
609
+ * `%` is removed.
610
+ *
611
+ * @param {string} text text read from a header comment
612
+ * @returns {string} the original text
613
+ */
614
+ export function decodeCommentText(text) {
615
+ return text.replaceAll(/~([~qb/%])/g, (_match, next) => COMMENT_UNESCAPES[next] ?? next);
616
+ }
617
+
618
+ /**
619
+ * Splits a comma-separated column list, keeping [bracketed] names intact.
620
+ *
621
+ * @param {string} list column list text
622
+ * @param {number} offset absolute offset of the list
623
+ * @returns {{name: string, start: number, end: number}[]} columns
624
+ */
625
+ function splitColumns(list, offset) {
626
+ const parts = [];
627
+ let partStart = 0;
628
+ let isInBracket = false;
629
+ for (let index = 0; index <= list.length; index++) {
630
+ const character = list[index];
631
+ if (character === '[') {
632
+ isInBracket = true;
633
+ } else if (character === ']') {
634
+ isInBracket = list[index + 1] === ']' ? (index++, true) : false;
635
+ } else if ((character === ',' && !isInBracket) || index === list.length) {
636
+ const raw = list.slice(partStart, index);
637
+ const lead = raw.length - raw.trimStart().length;
638
+ const trimmed = raw.trim();
639
+ if (trimmed) {
640
+ const isBracketed = trimmed.startsWith('[') && trimmed.endsWith(']');
641
+ parts.push({
642
+ name: decodeCommentText(
643
+ isBracketed ? trimmed.slice(1, -1).replaceAll(']]', ']') : trimmed,
644
+ ),
645
+ start: offset + partStart + lead,
646
+ end: offset + partStart + lead + trimmed.length,
647
+ });
648
+ }
649
+ partStart = index + 1;
650
+ }
651
+ }
652
+ return parts;
653
+ }
654
+
655
+ /**
656
+ * Reads the `SQL:` header comment(s): `SQL: FROM [Name] (external key Key)`,
657
+ * `SQL: SELECT a, b` and the `NOT IN` marker.
658
+ *
659
+ * @param {ReverseContext} context parse context
660
+ * @returns {{name?: string, nameLoc?: object, key?: string, columns?: '*'|{name: string, loc: object}[], foldNotIn: boolean}} header data
661
+ */
662
+ export function readHeader(context) {
663
+ const header = { foldNotIn: false };
664
+ for (const comment of context.comments) {
665
+ const body = context.text.slice(comment.start, comment.end);
666
+ let lineOffset = 0;
667
+ for (const line of body.split('\n')) {
668
+ const prefix = /^\s*(?:\/\/|\/\*+|\*+)?\s*SQL:\s*/i.exec(line);
669
+ if (prefix) {
670
+ const payload = line
671
+ .slice(prefix[0].length)
672
+ .replace(/\*\/\s*$/, '')
673
+ .trimEnd();
674
+ readHeaderPayload(
675
+ context,
676
+ header,
677
+ payload,
678
+ comment.start + lineOffset + prefix[0].length,
679
+ );
680
+ }
681
+ lineOffset += line.length + 1;
682
+ }
683
+ }
684
+ return header;
685
+ }
686
+
687
+ /**
688
+ * Reads one `SQL:` payload into the header data.
689
+ *
690
+ * @param {ReverseContext} context parse context
691
+ * @param {object} header header data (mutated)
692
+ * @param {string} payload text after "SQL:"
693
+ * @param {number} offset absolute offset of the payload
694
+ */
695
+ function readHeaderPayload(context, header, payload, offset) {
696
+ if (/\bNOT\s+IN\b/i.test(payload)) {
697
+ header.foldNotIn = true;
698
+ }
699
+ const from =
700
+ /\bFROM\s+(\[(?:[^\]]|\]\])+\]|[^\s()]+)(?:\s*\(\s*external\s+key\s+([^)]*?)\s*\))?/i.exec(
701
+ payload,
702
+ );
703
+ if (from) {
704
+ const rawName = from[1];
705
+ const nameStart = offset + from.index + from[0].indexOf(rawName);
706
+ header.name = decodeCommentText(
707
+ rawName.startsWith('[') ? rawName.slice(1, -1).replaceAll(']]', ']') : rawName,
708
+ );
709
+ header.nameLoc = makeLoc(context, nameStart, nameStart + rawName.length);
710
+ if (from[2]) {
711
+ header.key = decodeCommentText(from[2]);
712
+ }
713
+ }
714
+ const select = /\bSELECT\s+(?:TOP\s+\(?\d+\)?\s+)?(.*?)(?=\s+FROM\b|$)/i.exec(payload);
715
+ if (select && select[1].trim()) {
716
+ const listStart = offset + select.index + select[0].length - select[1].length;
717
+ header.columns =
718
+ select[1].trim() === '*'
719
+ ? '*'
720
+ : splitColumns(select[1], listStart).map((column) => ({
721
+ name: column.name,
722
+ loc: makeLoc(context, column.start, column.end),
723
+ }));
724
+ }
725
+ }
726
+
727
+ // ------------------------------------------------------------------------------------------
728
+ // Values and ORDER BY
729
+ // ------------------------------------------------------------------------------------------
730
+
731
+ /**
732
+ * Builds an AST Value from text: plain numbers without leading zeros become numbers.
733
+ *
734
+ * @param {ReverseContext} context parse context
735
+ * @param {string} text the value text
736
+ * @param {number} start 0-based start offset of the literal
737
+ * @param {number} end 0-based exclusive end offset of the literal
738
+ * @param {boolean} [isNumberLiteral] true when the code wrote a number literal (no quotes)
739
+ * @returns {{kind: 'string'|'number', value: string, loc: object}} value
740
+ */
741
+ export function makeValue(context, text, start, end, isNumberLiteral = false) {
742
+ return {
743
+ kind: isNumberLiteral || PLAIN_NUMBER.test(text) ? 'number' : 'string',
744
+ value: text,
745
+ loc: makeLoc(context, start, end),
746
+ };
747
+ }
748
+
749
+ /**
750
+ * Parses a LookupOrderedRows sort string such as "LastName ASC, Age DESC".
751
+ *
752
+ * @param {ReverseContext} context parse context
753
+ * @param {{value: string, start: number, end: number}} literal the string literal
754
+ * @returns {{column: string, direction: 'ASC'|'DESC', loc: object}[]} sort order
755
+ */
756
+ export function parseOrderString(context, literal) {
757
+ const inner = context.text.slice(literal.start + 1, literal.end - 1);
758
+ const hasExactOffsets = inner === literal.value;
759
+ const items = [];
760
+ let partStart = 0;
761
+ for (const part of literal.value.split(',')) {
762
+ const lead = part.length - part.trimStart().length;
763
+ const match = /^(\[(?:[^\]]|\]\])+\]|[^\s[\]]+)(?:\s+(ASC|DESC))?$/i.exec(part.trim());
764
+ if (!match) {
765
+ fail(
766
+ context,
767
+ INVALID_ORDER_BY,
768
+ 'The sort order could not be read. Write column names with an optional ASC or DESC, separated by commas, e.g. "LastName ASC, Age DESC".',
769
+ literal.start,
770
+ literal.end,
771
+ );
772
+ }
773
+ const raw = match[1];
774
+ const start = hasExactOffsets ? literal.start + 1 + partStart + lead : literal.start;
775
+ const end = hasExactOffsets ? start + match[0].length : literal.end;
776
+ items.push({
777
+ column: raw.startsWith('[') ? raw.slice(1, -1).replaceAll(']]', ']') : raw,
778
+ direction: match[2] ? match[2].toUpperCase() : 'ASC',
779
+ loc: makeLoc(context, start, end),
780
+ });
781
+ partStart += part.length + 1;
782
+ }
783
+ return items;
784
+ }
785
+
786
+ /**
787
+ * Joins conditions into a left-nested AND chain, as the SQL parser builds `a AND b AND c`.
788
+ *
789
+ * @param {ReverseContext} context parse context
790
+ * @param {object[]} conditions condition nodes in source order
791
+ * @returns {object} expression node
792
+ */
793
+ export function andChain(context, conditions) {
794
+ let expression = conditions[0];
795
+ for (const condition of conditions.slice(1)) {
796
+ expression = {
797
+ type: 'and',
798
+ left: expression,
799
+ right: condition,
800
+ loc: makeLoc(context, expression.loc.start, condition.loc.end),
801
+ };
802
+ }
803
+ return expression;
804
+ }