Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

embeddedScripts.ts

735 lines23.8 KB

1import { getFiletypeFromFileName } from "@pierre/diffs/utils/getFiletypeFromFileName";
2import {
3 parse,
4 type Command,
5 type DoubleQuotedChild,
6 type HereDoc,
7 type Word,
8 type WordPart,
9} from "unbash";
10​
11/** starts[i]..ends[i] spans the original spelling of text[i], including escapes. */
12export interface EmbeddedScript {
13 readonly language: string;
14 readonly text: string;
15 readonly starts: ReadonlyArray<number>;
16 readonly ends: ReadonlyArray<number>;
18​
19export interface SyntaxToken {
20 readonly content: string;
21 readonly offset: number;
22 readonly color?: string;
23 readonly fontStyle?: number;
25​
26type TokenLines = ReadonlyArray<ReadonlyArray<SyntaxToken>>;
27​
28interface MappedText {
29 readonly text: string;
30 readonly starts: ReadonlyArray<number>;
31 readonly ends: ReadonlyArray<number>;
33​
34interface Interpreter {
35 readonly language: string;
36 readonly inline: (flag: string) => boolean;
37 readonly optionalInline?: ReadonlySet<string>;
38 readonly shortFlags?: RegExp;
39 readonly valueOptions?: ReadonlySet<string>;
40 readonly scriptFileOptions?: ReadonlySet<string>;
41 /** A script file named `-` is read from stdin. */
42 readonly stdinScriptFile?: boolean;
43 readonly stdin: "always" | "without-script-file" | "never";
44 readonly positionalScript?: number;
45 readonly repeatable?: boolean;
46 readonly subcommand?: string;
47 /** PowerShell matches parameters case-insensitively; the lists above are lowercase. */
48 readonly ignoreCase?: boolean;
50​
51const MAX_DEPTH = 4;
52​
53const flagIn =
54 (...flags: string[]) =>
55 (flag: string) =>
56 flags.includes(flag);
57​
58const SHELL: Interpreter = {
59 language: "shellscript",
60 inline: (flag) => /^-[a-zA-Z]*c[a-zA-Z]*$/u.test(flag),
61 valueOptions: new Set(["-o", "-O", "--rcfile", "--init-file"]),
62 stdin: "without-script-file",
63};
64​
65const PYTHON: Interpreter = {
66 language: "python",
67 // Bundles like -uc and -IBc; -W and -X take a value, so a c after them is that value.
68 inline: flagIn("-c"),
69 shortFlags: /^-(?!-)[bBdEiIOPqRsStuvx]*/u,
70 valueOptions: new Set(["-W", "-X", "--check-hash-based-pycs"]),
71 scriptFileOptions: new Set(["-m"]),
72 stdin: "without-script-file",
73};
74​
75const SQL_SHELL = {
76 language: "sql",
77 valueOptions: new Set([
78 "-d",
79 "-h",
80 "-u",
81 "-U",
82 "--dbname",
83 "--host",
84 "--user",
85 "--username",
86 "-separator",
87 "-nullvalue",
88 "-init",
89 ]),
90 stdin: "always",
91 repeatable: true,
92} satisfies Omit<Interpreter, "inline">;
93​
94const INTERPRETERS: Record<string, Interpreter> = {
95 sh: SHELL,
96 bash: SHELL,
97 zsh: SHELL,
98 dash: SHELL,
99 ash: SHELL,
100 ksh: SHELL,
101 fish: {
102 language: "fish",
103 inline: flagIn("-c", "--command"),
104 // Bundles like -lc and -ic; a c after a value option such as -C or -d is that option's value.
105 shortFlags: /^-(?!-)[hilnNPv]*/u,
106 valueOptions: new Set([
107 "-C",
108 "--init-command",
109 "-d",
110 "--debug",
111 "-D",
112 "--debug-stack-frames",
113 "-o",
114 "--debug-output",
115 "-p",
116 "--profile",
117 "--profile-startup",
118 "-f",
119 "--features",
120 ]),
121 stdin: "without-script-file",
122 },
123 node: {
124 language: "javascript",
125 inline: flagIn("-e", "--eval", "-pe"),
126 optionalInline: new Set(["-p", "--print"]),
127 valueOptions: new Set([
128 "-r",
129 "--require",
130 "--import",
131 "--loader",
132 "-C",
133 "--conditions",
134 "--input-type",
135 "--env-file",
136 "--env-file-if-exists",
137 "--experimental-loader",
138 "--title",
139 "--inspect-port",
140 "--disable-warning",
141 "--unhandled-rejections",
142 "--redirect-warnings",
143 ]),
144 stdin: "without-script-file",
145 },
146 bun: { language: "typescript", inline: flagIn("-e", "--eval", "-p", "--print"), stdin: "never" },
147 deno: {
148 language: "typescript",
149 inline: () => false,
150 // `--env-file` takes its optional path only as `--env-file=path`.
151 valueOptions: new Set(["-c", "--config", "--import-map", "--ext"]),
152 stdin: "never",
153 subcommand: "eval",
154 },
155 ruby: {
156 language: "ruby",
157 // Bundles like -ne and -lane; -i, -I, -r and -C take a value, so an e after them is that value.
158 inline: flagIn("-e"),
159 shortFlags: /^-(?!-)(?:[acdlnpsSUvwy]|0[0-7]{0,3}|W[0-7]?|K[\x20-\x7e]?)*/u,
160 valueOptions: new Set(["-r", "-I", "-C"]),
161 stdin: "without-script-file",
162 repeatable: true,
163 },
164 perl: {
165 language: "perl",
166 // Bundles like -pe and -0777ne; in -pie or -Me the e is the value of -i or -M.
167 inline: flagIn("-e", "-E"),
168 shortFlags: /^-(?!-)(?:[acdfgnpsStTuUwWX]|0[0-7]{0,3}|l0?[0-7]{0,3})*/u,
169 // -M and -m take their module only attached (`-Mstrict`).
170 valueOptions: new Set(["-I"]),
171 stdin: "without-script-file",
172 repeatable: true,
173 },
174 osascript: {
175 language: "applescript",
176 inline: flagIn("-e"),
177 valueOptions: new Set(["-l", "-s"]),
178 stdin: "without-script-file",
179 repeatable: true,
180 },
181 pwsh: {
182 language: "powershell",
183 inline: flagIn("-c", "-command"),
184 valueOptions: new Set(["-executionpolicy", "-workingdirectory", "-windowstyle"]),
185 scriptFileOptions: new Set(["-f", "-file", "-encodedcommand"]),
186 stdin: "never",
187 ignoreCase: true,
188 },
189 psql: {
190 ...SQL_SHELL,
191 inline: flagIn("-c", "--command"),
192 // Bundles like -Atc and -Xtf; a c or f after -d, -h, -U and the like is that option's value.
193 shortFlags: /^-(?!-)[aAbeEHlnqsStwWxXz01]*/u,
194 scriptFileOptions: new Set(["-f", "--file"]),
195 stdinScriptFile: true,
196 },
197 mysql: {
198 ...SQL_SHELL,
199 inline: flagIn("-e", "--execute"),
200 // Bundles like -Ne and -sNe; an e after -D, -h, -u and the like is that option's value.
201 shortFlags: /^-(?!-)[AbBcCEfGHinNoqrstUvVwWX]*/u,
202 },
203 sqlite3: { ...SQL_SHELL, inline: flagIn("-cmd"), positionalScript: 1 },
204 duckdb: {
205 ...SQL_SHELL,
206 inline: flagIn("-c", "-cmd"),
207 scriptFileOptions: new Set(["-f"]),
208 positionalScript: 1,
209 },
210};
211INTERPRETERS.powershell = INTERPRETERS.pwsh!;
212INTERPRETERS.mariadb = INTERPRETERS.mysql!;
213​
214const JXA: Interpreter = { ...INTERPRETERS.osascript!, language: "javascript" };
215​
216/** `osascript -l JavaScript` runs JXA; the last `-l` option wins, and the name is case-sensitive. */
217function isJxa(args: ReadonlyArray<Word>): boolean {
218 let language = "AppleScript";
219 for (let index = 0; index < args.length; index += 1) {
220 const value = args[index]!.value;
221 if (value === "-l") language = args[++index]?.value ?? language;
222 else if (value.startsWith("-l")) language = value.slice(2);
223 else if (value === "-e" || value === "-s") index += 1;
224 else if (!value.startsWith("-") || value === "-" || value === "--") break;
225 }
226 return language === "JavaScript";
228​
229const PROGRAM_WRAPPERS: Record<string, ReadonlySet<string>> = {
230 env: new Set(["-u", "--unset", "-C", "--chdir"]),
231 sudo: new Set([
232 "-u",
233 "--user",
234 "-g",
235 "--group",
236 "-C",
237 "--close-from",
238 "-D",
239 "--chdir",
240 "-p",
241 "--prompt",
242 "-h",
243 "--host",
244 "-r",
245 "--role",
246 "-t",
247 "--type",
248 "-T",
249 "--command-timeout",
250 "-R",
251 "--chroot",
252 ]),
253 nice: new Set(["-n", "--adjustment"]),
254 nohup: new Set(),
255 exec: new Set(["-a"]),
256 command: new Set(),
257 builtin: new Set(),
258 timeout: new Set(["-k", "--kill-after", "-s", "--signal"]),
259};
260PROGRAM_WRAPPERS.gtimeout = PROGRAM_WRAPPERS.timeout!;
261​
262const DELIMITER_LANGUAGES: Record<string, string> = {
263 py: "python",
264 python: "python",
265 js: "javascript",
266 javascript: "javascript",
267 ts: "typescript",
268 typescript: "typescript",
269 sql: "sql",
270 json: "json",
271 yaml: "yaml",
272 yml: "yaml",
273 toml: "toml",
274 sh: "shellscript",
275 bash: "shellscript",
276 shell: "shellscript",
277 rb: "ruby",
278 ruby: "ruby",
279 html: "html",
280 css: "css",
281 md: "markdown",
282 markdown: "markdown",
283 xml: "xml",
284 diff: "diff",
285 patch: "diff",
286};
287​
288/** Returns nothing for commands that do not parse cleanly. */
289export function embeddedScripts(command: string): EmbeddedScript[] {
290 const identity = Array.from({ length: command.length }, (_, index) => index);
291 return scriptsIn(
292 { text: command, starts: identity, ends: identity.map((index) => index + 1) },
293 0,
294 );
296​
297function scriptsIn(source: MappedText, depth: number): EmbeddedScript[] {
298 const script = parse(source.text);
299 if (script.errors?.length) return [];
300 const found: EmbeddedScript[] = [];
301 forEachCommand(script.commands, (command) => {
302 for (const { language, mapped } of commandScripts(command, source.text)) {
303 if (mapped.text.trim() === "") continue;
304 const embedded: EmbeddedScript = {
305 language,
306 text: mapped.text,
307 starts: mapped.starts.map((start) => source.starts[start]!),
308 ends: mapped.ends.map((end) => source.ends[end - 1]!),
309 };
310 found.push(embedded);
311 if (language === "shellscript" && depth + 1 < MAX_DEPTH) {
312 found.push(...scriptsIn(embedded, depth + 1));
313 }
314 }
315 });
316 return found;
318​
319function isNode(value: unknown): value is { readonly type: string } {
320 return typeof value === "object" && value !== null && "type" in value;
322​
323function forEachCommand(
324 node: unknown,
325 visit: (command: Command) => void,
326 seen = new WeakSet<object>(),
327): void {
328 if (Array.isArray(node)) {
329 for (const child of node) forEachCommand(child, visit, seen);
330 return;
331 }
332 if (!isNode(node) || seen.has(node)) return;
333 seen.add(node);
334 switch (node.type) {
335 case "Command":
336 visit(node as Command);
337 break;
338 case "CommandExpansion":
339 case "ProcessSubstitution": {
340 const { script } = node as Extract<WordPart, { type: "CommandExpansion" }>;
341 if (script && !script.errors?.length && script.source === undefined) {
342 forEachCommand(script.commands, visit, seen);
343 }
344 return;
345 }
346 }
347 // Word parts are lazy getters, which Object.values skips.
348 if ("parts" in node) forEachCommand(node.parts, visit, seen);
349 for (const value of Object.values(node)) {
350 if (typeof value === "object") forEachCommand(value, visit, seen);
351 }
353​
354function programName(word: Word): string {
355 // Bash reads `C:\Python312\python.exe` unquoted as escapes; Windows meant a path.
356 const path = /\\/u.test(word.text) ? word.text.replace(/^["']|["']$/gu, "") : word.value;
357 return (path.split(/[\\/]/u).at(-1) ?? "").toLowerCase().replace(/\.exe$/u, "");
359​
360function interpreterFor(name: string): Interpreter | undefined {
361 if (/^python(?:\d+(?:\.\d+)?)?$|^pypy3?$|^py$/u.test(name)) return PYTHON;
362 return Object.hasOwn(INTERPRETERS, name) ? INTERPRETERS[name] : undefined;
364​
365function programIndex(words: ReadonlyArray<Word>): number {
366 let index = 0;
367 while (index < words.length) {
368 const name = programName(words[index]!);
369 if (!Object.hasOwn(PROGRAM_WRAPPERS, name)) return index;
370 const valueOptions = PROGRAM_WRAPPERS[name]!;
371 const isTimeout = name === "timeout" || name === "gtimeout";
372 index += 1;
373 let optionsEnded = false;
374 while (index < words.length) {
375 const value = words[index]!.value;
376 const isOption = !optionsEnded && value.startsWith("-");
377 if (isOption && value === "--") optionsEnded = true;
378 // `env -- FOO=1 cmd` still takes assignments after the options end.
379 if (isOption || /^[A-Za-z_]\w*=/u.test(value)) {
380 const takesValue =
381 isOption &&
382 (valueOptions.has(value) ||
383 (isTimeout && /^-[fpv]*[ks]$/u.test(value)) ||
384 (name === "env" && /^-[i0v]+[uC]$/u.test(value)) ||
385 (name === "sudo" && /^-[ABEHKNPSVbiklnsv]+[ugCDprtTR]$/u.test(value)));
386 index += takesValue ? 2 : 1;
387 } else {
388 break;
389 }
390 }
391 if (isTimeout) index += 1;
392 }
393 return index;
395​
396function commandScripts(
397 command: Command,
398 source: string,
399): Array<{ language: string; mapped: MappedText }> {
400 if (!command.name) return [];
401 const words = [command.name, ...command.args.filter((arg): arg is Word => arg.type === "Word")];
402 const index = programIndex(words);
403 const program = words[index];
404 if (!program) return [];
405 const name = programName(program);
406 const args = words.slice(index + 1);
407 const interpreter = name === "osascript" && isJxa(args) ? JXA : interpreterFor(name);
408 const scripts: Array<{ language: string; mapped: MappedText }> = [];
409​
410 let readsStdinScript = false;
411 if (interpreter) {
412 const found = interpreterArgs(interpreter, args, name);
413 for (const script of found.scripts) {
414 const mapped = wordText(script.word, source);
415 if (!mapped) continue;
416 scripts.push({ language: interpreter.language, mapped: sliceMapped(mapped, script.start) });
417 }
418 readsStdinScript =
419 interpreter.stdin !== "never" &&
420 (found.useStdin || (found.scripts.length === 0 && !found.scriptFromFile));
421 }
422​
423 const stdinLanguage = readsStdinScript ? interpreter?.language : undefined;
424 const writtenLanguage = writtenFileLanguage(name, command, args);
425 for (const redirect of command.redirects) {
426 const toStdin = isDescriptor(redirect.descriptor, 0);
427 if (redirect.type === "HereString" && toStdin && stdinLanguage && redirect.target) {
428 const mapped = wordText(redirect.target, source);
429 if (mapped) scripts.push({ language: stdinLanguage, mapped });
430 }
431 if (redirect.type === "HereDoc") {
432 const language =
433 (toStdin ? (stdinLanguage ?? writtenLanguage) : undefined) ?? delimiterLanguage(redirect);
434 if (language) scripts.push({ language, mapped: hereDocText(redirect, source) });
435 }
436 }
437 return scripts;
439​
440function isDescriptor(descriptor: HereDoc["descriptor"], fd: number): boolean {
441 return (
442 descriptor === undefined || (descriptor.type === "FileDescriptor" && descriptor.value === fd)
443 );
445​
446interface ScriptArgument {
447 readonly word: Word;
448 readonly start: number;
450​
451function interpreterArgs(
452 interpreter: Interpreter,
453 args: ReadonlyArray<Word>,
454 program: string,
455): { scripts: ScriptArgument[]; scriptFromFile: boolean; useStdin?: boolean } {
456 const positionals: Word[] = [];
457 const scripts: ScriptArgument[] = [];
458 const whole = (word: Word): ScriptArgument => ({ word, start: 0 });
459 let optionsEnded = false;
460 let scriptFromFile = false;
461 let shellInline = false;
462 let useStdin = false;
463 for (let index = 0; index < args.length; index += 1) {
464 const arg = args[index]!;
465 const flag = interpreter.ignoreCase ? arg.value.toLowerCase() : arg.value;
466 if (!optionsEnded && (flag === "--" || (shellInline && flag === "-"))) {
467 optionsEnded = true;
468 continue;
469 }
470 if (
471 !optionsEnded &&
472 (flag.startsWith("-") || (interpreter === SHELL && flag.startsWith("+"))) &&
473 flag !== "-"
474 ) {
475 let [name = flag, value] = flag.startsWith("--") ? flag.split(/=(.*)/su) : [flag];
476 const at = interpreter.shortFlags?.exec(flag)?.[0].length;
477 if (at && at < flag.length) [name, value] = [`-${flag[at]}`, flag.slice(at + 1) || undefined];
478 if (interpreter.scriptFileOptions?.has(name)) {
479 if (!interpreter.repeatable) return { scripts, scriptFromFile: true };
480 const file = value ?? args[index + 1]?.value;
481 if (file === undefined) return { scripts, scriptFromFile: true };
482 if (interpreter.stdinScriptFile && file === "-") useStdin = true;
483 // SQL shells run `-f` files and `-c` statements alike, in order.
484 scriptFromFile = true;
485 if (value === undefined) index += 1;
486 continue;
487 }
488 if (interpreter === SHELL) {
489 // bash, dash, and sh accept `--long` options only before `-c` or `-s`.
490 if ((shellInline || useStdin) && name.startsWith("--") && LONG_OPTIONS_FIRST.has(program)) {
491 return { scripts, scriptFromFile: true };
492 }
493 // zsh and ksh attach `-o` names (`-oshwordsplit`).
494 const opts = program === "zsh" || program === "ksh" ? flag.split("o", 1)[0]! : flag;
495 // `-c` makes the first operand the script, so more options may follow it.
496 if (interpreter.inline(opts)) shellInline = true;
497 // `-s` reads the script from stdin even with operands.
498 if (/^[+-][a-zA-Z]*s[a-zA-Z]*$/u.test(opts)) useStdin = opts[0] === "-";
499 if (value === undefined) index += shellOptionValues(program, flag);
500 continue;
501 }
502 const optionalInline = interpreter.optionalInline?.has(name);
503 if (optionalInline || interpreter.inline(name)) {
504 const next = args[index + 1];
505 if (optionalInline && value === undefined && (!next || next.value.startsWith("-"))) {
506 continue;
507 }
508 if (value !== undefined) scripts.push({ word: arg, start: flag.length - value.length });
509 else if (next) scripts.push(whole(next));
510 else return { scripts, scriptFromFile: true };
511 if (!interpreter.repeatable) return { scripts, scriptFromFile };
512 if (value === undefined) index += 1;
513 continue;
514 }
515 if (value === undefined && interpreter.valueOptions?.has(name)) index += 1;
516 continue;
517 }
518 if (shellInline) return { scripts: [whole(arg)], scriptFromFile: false };
519 positionals.push(arg);
520 if (interpreter.stdin === "without-script-file" && !interpreter.subcommand) break;
521 }
522 if (shellInline) return { scripts, scriptFromFile: true };
523​
524 if (interpreter.subcommand) {
525 if (positionals[0]?.value !== interpreter.subcommand) return { scripts, scriptFromFile: true };
526 return { scripts: positionals.slice(1, 2).map(whole), scriptFromFile: false };
527 }
528 if (interpreter.positionalScript !== undefined) {
529 scripts.push(...positionals.slice(interpreter.positionalScript).map(whole));
530 }
531 // SQL shells take databases as positional arguments, not script files.
532 if (interpreter.stdin === "always" || useStdin) return { scripts, scriptFromFile, useStdin };
533 const first = positionals[0];
534 return { scripts, scriptFromFile: first !== undefined && first.value !== "-" };
536​
537const LONG_OPTIONS_FIRST = new Set(["bash", "dash", "sh"]);
538​
539/** How many following words a shell option consumes as values. */
540function shellOptionValues(program: string, flag: string): number {
541 if (flag.startsWith("--")) {
542 return (program === "bash" || program === "sh") && SHELL.valueOptions?.has(flag) ? 1 : 0;
543 }
544 // zsh and ksh take an `-o` value attached (`-oextendedglob`); other shells read one word per o or O in a bundle (`-oe pipefail`).
545 if (program === "zsh" || program === "ksh") {
546 return /^[-+][a-zA-Z]+$/u.test(flag) && flag.indexOf("o") === flag.length - 1 ? 1 : 0;
547 }
548 return /^[-+][a-zA-Z]+$/u.test(flag) ? (flag.match(/[oO]/gu)?.length ?? 0) : 0;
550​
551function sliceMapped(mapped: MappedText, start: number): MappedText {
552 if (start === 0) return mapped;
553 return {
554 text: mapped.text.slice(start),
555 starts: mapped.starts.slice(start),
556 ends: mapped.ends.slice(start),
557 };
559​
560function writtenFileLanguage(
561 name: string,
562 command: Command,
563 args: ReadonlyArray<Word>,
564): string | undefined {
565 let path: string | undefined;
566 if (name === "cat") {
567 for (const redirect of command.redirects) {
568 if (
569 redirect.type === "Redirect" &&
570 [">", ">>", ">|", "&>", "&>>"].includes(redirect.operator) &&
571 isDescriptor(redirect.descriptor, 1)
572 ) {
573 path = redirect.target?.value;
574 }
575 }
576 } else if (name === "tee") {
577 path = args.find((arg) => !arg.value.startsWith("-"))?.value;
578 }
579 if (!path) return undefined;
580 const language = getFiletypeFromFileName(path);
581 return language === "text" ? undefined : language;
583​
584function delimiterLanguage(hereDoc: HereDoc): string | undefined {
585 const name = hereDoc.delimiter?.value.toLowerCase();
586 return name && Object.hasOwn(DELIMITER_LANGUAGES, name) ? DELIMITER_LANGUAGES[name] : undefined;
588​
589function hereDocText(hereDoc: HereDoc, source: string): MappedText {
590 const { pos, end } = hereDoc.body;
591 const starts = Array.from({ length: end - pos }, (_, index) => pos + index);
592 return {
593 text: source.slice(pos, end),
594 starts,
595 ends: starts.map((start) => start + 1),
596 };
598​
599// Preserve literal expansions; return undefined for unmappable spellings.
600function wordText(word: Word, source: string): MappedText | undefined {
601 const builder = new MappedTextBuilder();
602 const parts: ReadonlyArray<WordPart> = word.parts ?? [
603 { type: "Literal", pos: word.pos, end: word.end, text: word.text, value: word.value },
604 ];
605 for (const part of parts) {
606 switch (part.type) {
607 case "Literal":
608 if (!builder.addEscaped(part, false)) return undefined;
609 break;
610 case "SingleQuoted":
611 builder.addRaw(part.value, part.pos + 1);
612 break;
613 case "DoubleQuoted":
614 case "LocaleString":
615 for (const child of part.parts) {
616 if (!builder.addDoubleQuotedChild(child)) return undefined;
617 }
618 break;
619 case "AnsiCQuoted":
620 // $'…' escapes such as \x41 do not map character for character.
621 if (part.value !== part.text.slice(2, -1)) return undefined;
622 builder.addRaw(part.value, part.pos + 2);
623 break;
624 default:
625 builder.addRaw(source.slice(part.pos, part.end), part.pos);
626 }
627 }
628 return builder.build();
630​
631class MappedTextBuilder {
632 private text = "";
633 private readonly starts: number[] = [];
634 private readonly ends: number[] = [];
635​
636 addRaw(text: string, pos: number) {
637 for (let index = 0; index < text.length; index += 1) this.push(text[index]!, pos + index, 1);
638 }
639​
640 addDoubleQuotedChild(child: DoubleQuotedChild): boolean {
641 if (child.type === "Literal") return this.addEscaped(child, true);
642 this.addRaw(child.text, child.pos);
643 return true;
644 }
645​
646 addEscaped(literal: { pos: number; text: string; value: string }, doubleQuoted: boolean) {
647 const before = this.text.length;
648 const { text, pos } = literal;
649 for (let index = 0; index < text.length; index += 1) {
650 const next = text[index + 1];
651 if (
652 text[index] === "\\" &&
653 next !== undefined &&
654 (!doubleQuoted || '$`"\\\n'.includes(next))
655 ) {
656 // A backslash-newline joins lines and spells nothing.
657 if (next !== "\n") this.push(next, pos + index, 2);
658 index += 1;
659 } else {
660 this.push(text[index]!, pos + index, 1);
661 }
662 }
663 return this.text.slice(before) === literal.value;
664 }
665​
666 build(): MappedText {
667 return { text: this.text, starts: this.starts, ends: this.ends };
668 }
669​
670 private push(character: string, start: number, length: number) {
671 this.text += character;
672 this.starts.push(start);
673 this.ends.push(start + length);
674 }
676​
677export function withEmbeddedScripts(
678 code: string,
679 lines: TokenLines,
680 embedded: ReadonlyArray<EmbeddedScript>,
681 tokenize: (text: string, language: string) => TokenLines,
682): TokenLines {
683 if (embedded.length === 0) return lines;
684 const styles = Array.from<SyntaxToken | undefined>({ length: code.length });
685 for (const token of lines.flat()) {
686 styles.fill(token, token.offset, token.offset + token.content.length);
687 }
688 for (const script of embedded) {
689 let scriptLines: TokenLines;
690 try {
691 scriptLines = tokenize(script.text, script.language);
692 } catch {
693 continue;
694 }
695 for (const token of scriptLines.flat()) {
696 if (token.content === "") continue;
697 const last = token.offset + token.content.length - 1;
698 styles.fill(token, script.starts[token.offset], script.ends[last]);
699 }
700 }
701 return restyledLines(code, styles);
703​
704function restyledLines(
705 code: string,
706 styles: ReadonlyArray<SyntaxToken | undefined>,
707): SyntaxToken[][] {
708 const lines: SyntaxToken[][] = [];
709 let start = 0;
710 for (const lineBreak of [...code.matchAll(/\r?\n/gu), undefined]) {
711 const end = lineBreak?.index ?? code.length;
712 const tokens: SyntaxToken[] = [];
713 for (let index = start; index < end;) {
714 const style = styles[index];
715 let next = index + 1;
716 while (
717 next < end &&
718 styles[next]?.color === style?.color &&
719 styles[next]?.fontStyle === style?.fontStyle
720 ) {
721 next += 1;
722 }
723 tokens.push({
724 content: code.slice(index, next),
725 offset: index,
726 ...(style?.color ? { color: style.color } : {}),
727 ...(style?.fontStyle ? { fontStyle: style.fontStyle } : {}),
728 });
729 index = next;
730 }
731 lines.push(tokens);
732 if (lineBreak) start = lineBreak.index + lineBreak[0].length;
733 }
734 return lines;