* `safe` with the text of its strings blanked (offsets kept) and the `${…}` * code of its templates left in. A handler's calls are read from it: a SQL * string (`INSERT INTO jobs (user_id) VALUES (?)`) or a message (`published * apps (or …)`) is not a call to `jobs` or `apps`, but `${render(x)}`
(safe: string)
| 479 | * apps (or …)`) is not a call to `jobs` or `apps`, but `${render(x)}` is one. |
| 480 | */ |
| 481 | function codeOnly(safe: string): string { |
| 482 | const out = safe.split(''); |
| 483 | const n = safe.length; |
| 484 | const blank = (from: number, to: number): void => { |
| 485 | for (let k = from; k < to; k++) if (out[k] !== '\n' && out[k] !== '\r') out[k] = ' '; |
| 486 | }; |
| 487 | /** Past the backtick that closes the template opened at `open`. */ |
| 488 | const template = (open: number): number => { |
| 489 | let text = open + 1; |
| 490 | for (let i = open + 1; i < n; i++) { |
| 491 | const c = safe[i]; |
| 492 | if (c === '\\') i++; |
| 493 | else if (c === '`') { |
| 494 | blank(text, i); |
| 495 | return i + 1; |
| 496 | } else if (c === '$' && safe[i + 1] === '{') { |
| 497 | blank(text, i); |
| 498 | i = code(i + 2, true) - 1; |
| 499 | text = i + 1; |
| 500 | } |
| 501 | } |
| 502 | blank(text, n); |
| 503 | return n; |
| 504 | }; |
| 505 | /** Code from `at`; with `closing`, up to and past the `}` that ends a `${…}`. */ |
| 506 | const code = (at: number, closing: boolean): number => { |
| 507 | let depth = 0; |
| 508 | for (let i = at; i < n; i++) { |
| 509 | const c = safe[i]; |
| 510 | if (c === '`') { |
| 511 | i = template(i) - 1; |
| 512 | } else if ((c === '"' || c === "'") && closesOnLine(safe, i)) { |
| 513 | let end = i + 1; |
| 514 | while (end < n && safe[end] !== c) end += safe[end] === '\\' ? 2 : 1; |
| 515 | blank(i + 1, end); |
| 516 | i = end; |
| 517 | } else if (c === '{') { |
| 518 | depth++; |
| 519 | } else if (c === '}') { |
| 520 | if (depth === 0 && closing) return i + 1; |
| 521 | depth--; |
| 522 | } |
| 523 | } |
| 524 | return n; |
| 525 | }; |
| 526 | code(0, false); |
| 527 | // A name followed by its parameters and a body defines a method, it calls |
| 528 | // nothing: `stream({ onFinish() { … } })`, `new ReadableStream({ start(c) { … } })`. |
| 529 | const text = out.join(''); |
| 530 | const head = /(?<![\w$.])([A-Za-z_$][\w$]*)\s*\(/g; |
| 531 | for (let m = head.exec(text); m !== null; m = head.exec(text)) { |
| 532 | if (DEFINITION_KEYWORDS.has(m[1]!)) continue; |
| 533 | let depth = 0; |
| 534 | let close = m.index + m[0].length - 1; |
| 535 | for (; close < n; close++) { |
| 536 | if (text[close] === '(') depth++; |
| 537 | else if (text[close] === ')' && --depth === 0) break; |
| 538 | } |