Skip to content
Source
Sign inSign up
fuko/trytanstackdb-v2
Open History to see the last commit

source-regions.ts

58 lines2.2 KB

1/**
2 * Guide snippets are quoted from the app's real source, so they can't drift
3 * from the code. A quotable part of a file is wrapped in region comments:
4 *
5 * // #region notes-collection
6 * export const notesCollection = …
7 * // #endregion notes-collection
8 *
9 * `extractRegion` returns the lines in between, without their common
10 * indentation and without the markers of any regions nested inside.
11 */
12​
13const REGION_START = /^\s*\/\/ #region (\S+)\s*$/;
14const REGION_END = /^\s*\/\/ #endregion(?: (\S+))?\s*$/;
15​
16/** Every region in a file, by name, with the line range of its contents. */
17export function listRegions(source: string): Map<string, { start: number; end: number }> {
18 const lines = source.split("\n");
19 const regions = new Map<string, { start: number; end: number }>();
20 const open: { name: string; start: number }[] = [];
21 lines.forEach((line, index) => {
22 const start = REGION_START.exec(line);
23 if (start) {
24 const name = start[1]!;
25 if (regions.has(name) || open.some((region) => region.name === name)) {
26 throw new Error(`Region "${name}" is defined twice.`);
27 }
28 open.push({ name, start: index + 1 });
29 return;
30 }
31 const end = REGION_END.exec(line);
32 if (!end) return;
33 const region = open.pop();
34 if (!region) throw new Error(`#endregion on line ${index + 1} has no #region.`);
35 if (end[1] !== undefined && end[1] !== region.name) {
36 throw new Error(`#endregion ${end[1]} on line ${index + 1} closes region "${region.name}".`);
37 }
38 regions.set(region.name, { start: region.start, end: index });
39 });
40 if (open.length > 0) throw new Error(`Region "${open.at(-1)!.name}" is never closed.`);
41 return regions;
43​
44export function extractRegion(source: string, name: string): string {
45 const region = listRegions(source).get(name);
46 if (!region) throw new Error(`No region named "${name}".`);
47 const lines = source
48 .split("\n")
49 .slice(region.start, region.end)
50 .filter((line) => !REGION_START.test(line) && !REGION_END.test(line));
51 const indent = Math.min(
52 ...lines.filter((line) => line.trim() !== "").map((line) => /^ */.exec(line)![0].length),
53 );
54 return lines
55 .map((line) => line.slice(indent))
56 .join("\n")
57 .trim();