Skip to content
Myr

imports.ts

This file

Path

packages/gate/src/imports.ts

337 lines · 8.2 KiB · TypeScript

Last changed by

Merge build/comments-packages-rest into mainoscabrielbefore adoption38cd503

History of this file

Take it

The walk stopped after 200 commits: lines older than 678c8b8 point at it.

Merge build/comments-packages-rest into mainoscabrielbefore adoption38cd503

lines 1–2why, one step back
1// Stage 1 reads imports from text, with no compiler and no file system. Full
2// resolution (path aliases, `exports` conditions, re-exports) is stage 3's.

Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8

lines 3–25why, one step back
3import type { Policy } from "@repo/protocol/domain/policy";
4import type { RepoPath } from "@repo/protocol/ids";5import { Array, Option } from "effect";67import { matchAny } from "./glob.ts";89export interface ImportSpecifier {10 readonly specifier: string;11 readonly line: number;12}1314type Mode = "code" | "comment" | "block" | "quote" | "template" | "regex";1516// After one of these, a `/` opens a regular expression, not a division.17const OPENS_REGEX = new Set("(,=:[!&|?{};+-*%<>~^");1819// A postfix `++` or `--` ends an operand, so the `/` after it divides.20const POSTFIX = /(?:\+\+|--)$/u;2122const KEYWORD_BEFORE_REGEX =23 /(?:^|[^\w$])(?:return|typeof|case|do|else|in|of|new|delete|void|throw|yield|await)$/u;2425/**

Merge build/comments-packages-rest into mainoscabrielbefore adoption38cd503

lines 26–27why, one step back
26 * A line whose code opens with `*` reads as the inside of a block comment: an
27 * answer's added lines can start after the comment opened.

Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8

lines 28–337why, one step back
28 */
29const maskOf = (text: string): string => {30 let out = "";31 let mode: Mode = "code";32 let quote = "";33 let inClass = false;34 let tail = "";35 let blankLine = true;36 const expressions: number[] = [];3738 const emit = (chars: string, as: "blank" | "fill") => {39 for (const char of chars) {40 if (char === "\n") {41 out += char;42 blankLine = true;43 } else {44 out += as === "blank" ? " " : "_";45 }46 }47 };4849 const keep = (chars: string) => {50 out += chars;51 tail = (tail + chars).slice(-32);52 blankLine = chars.endsWith("\n") || (blankLine && chars.trim() === "");53 };5455 const close = (char: string) => {56 mode = "code";57 keep(char);58 };5960 const inComment = (char: string) => {61 if (char === "\n") {62 mode = "code";63 }6465 emit(char, "blank");6667 return 1;68 };6970 const inBlock = (char: string, next: string) => {71 if (char === "*" && next === "/") {72 mode = "code";73 emit("*/", "blank");7475 return 2;76 }7778 emit(char, "blank");7980 return 1;81 };8283 const inQuote = (char: string, next: string) => {84 if (char === "\\") {85 emit(char + next, "fill");8687 return 2;88 }8990 if (char === quote || char === "\n") {91 close(char);92 } else {93 emit(char, "fill");94 }9596 return 1;97 };9899 const inTemplate = (char: string, next: string) => {100 if (char === "\\") {101 emit(char + next, "fill");102103 return 2;104 }105106 if (char === "$" && next === "{") {107 expressions.push(0);108 close("${");109110 return 2;111 }112113 if (char === "`") {114 close(char);115 } else {116 emit(char, "fill");117 }118119 return 1;120 };121122 const inRegex = (char: string, next: string) => {123 if (char === "\\") {124 emit(char + next, "fill");125126 return 2;127 }128129 if (char === "\n" || (char === "/" && !inClass)) {130 close(char);131 } else {132 inClass = char === "[" || (inClass && char !== "]");133 emit(char, "fill");134 }135136 return 1;137 };138139 const opensRegex = () => {140 const before = tail.trimEnd();141142 return (143 before === "" ||144 (OPENS_REGEX.has(before.slice(-1)) && !POSTFIX.test(before)) ||145 KEYWORD_BEFORE_REGEX.test(before)146 );147 };148149 const opened = (char: string): Mode => {150 if (char === '"' || char === "'") {151 quote = char;152153 return "quote";154 }155156 if (char === "`") {157 return "template";158 }159160 if (char === "/" && opensRegex()) {161 inClass = false;162163 return "regex";164 }165166 return "code";167 };168169 const brace = (char: string) => {170 const open = expressions.pop();171172 if (open === undefined) {173 return;174 }175176 if (char === "}" && open === 0) {177 mode = "template";178 } else {179 expressions.push(open + (char === "{" ? 1 : 0) - (char === "}" ? 1 : 0));180 }181 };182183 const inCode = (char: string, next: string) => {184 if (char === "/" && (next === "/" || next === "*")) {185 mode = next === "/" ? "comment" : "block";186 emit(char + next, "blank");187188 return 2;189 }190191 if (char === "*" && blankLine) {192 mode = "comment";193 emit(char, "blank");194195 return 1;196 }197198 mode = opened(char);199200 if (mode === "code" && (char === "{" || char === "}")) {201 brace(char);202 }203204 keep(char);205206 return 1;207 };208209 const steps = {210 block: inBlock,211 code: inCode,212 comment: inComment,213 quote: inQuote,214 regex: inRegex,215 template: inTemplate,216 } as const satisfies Record<Mode, (char: string, next: string) => number>;217218 let at = 0;219220 while (at < text.length) {221 at += steps[mode](text.charAt(at), text.charAt(at + 1));222 }223224 return out;225};226227// Each form of import, read in the masked text: `… from "x"` (an import or228// re-export, or the last line of one), `import "x"`, `import("x")` and229// `require("x")`. A string's contents read as `_`. A call may also name its230// module by a template with no `${}`, which is as fixed as a string; one with231// a substitution keeps its `${`, so it never matches.232const FORMS = [233 /(?<![\w$.])from\s*(?<quote>["'])(?<contents>_+)\k<quote>/gu,234 /(?<![\w$.])import\s*(?<quote>["'])(?<contents>_+)\k<quote>/gu,235 /(?<![\w$.])import\s*\(\s*(?<quote>["'`])(?<contents>_+)\k<quote>/gu,236 /(?<![\w$.])require\s*\(\s*(?<quote>["'`])(?<contents>_+)\k<quote>/gu,237];238239export const importSpecifiers = (text: string): readonly ImportSpecifier[] => {240 const masked = maskOf(text);241242 return FORMS.flatMap((form) =>243 [...masked.matchAll(form)].map((match) => {244 const contents = match.groups?.contents ?? "";245 // The contents end one character before the match does, at the quote.246 const start = match.index + match[0].length - 1 - contents.length;247248 return {249 line: text.slice(0, start).split("\n").length,250 specifier: text.slice(start, start + contents.length),251 start,252 };253 })254 )255 .toSorted((one, other) => one.start - other.start)256 .map(({ line, specifier }) => ({ line, specifier }));257};258259const RELATIVE = /^\.\.?(?:\/|$)/u;260261const INSIDES = new Set(["src", "test", "internal"]);262263type Module = Policy["modules"][number];264265const moduleOf = (modules: Policy["modules"], path: string) =>266 Array.findFirst(modules, (module) => matchAny(module.paths, path));267268const resolve = (from: string, specifier: string): Option.Option<string> => {269 const parts = from.split("/").slice(0, -1);270271 for (const part of specifier.split("/")) {272 if (part === "..") {273 if (parts.length === 0) {274 return Option.none();275 }276277 parts.pop();278 } else if (part !== "." && part !== "") {279 parts.push(part);280 }281 }282283 return Option.some(parts.join("/"));284};285286const bare = (path: string) =>287 path.replace(/\.[cm]?[jt]sx?$/u, "").replace(/\/index$/u, "");288289const rootsOf = (module: Module) =>290 module.paths.map((glob) =>291 glob.replace(/^\//u, "").replace(/\/(?:\*\*)?$/u, "")292 );293294const isInternal = (module: Module, target: string) =>295 module.publicFiles !== undefined &&296 !rootsOf(module).includes(target) &&297 !module.publicFiles.some((file) => bare(file) === bare(target));298299const relative = (300 from: string,301 specifier: string,302 modules: Policy["modules"]303) =>304 Option.flatMap(resolve(from, specifier), (target) =>305 Option.filter(moduleOf(modules, target), (module) =>306 isInternal(module, target)307 )308 );309310const subpath = (specifier: string, modules: Policy["modules"]) => {311 const segments = specifier.split("/");312 const length = specifier.startsWith("@") ? 2 : 1;313 const name = segments.slice(0, length).join("/");314315 return segments.slice(length).some((segment) => INSIDES.has(segment))316 ? Array.findFirst(modules, (module) => module.module === name)317 : Option.none();318};319320export const reachedInternals = (input: {321 readonly from: RepoPath;322 readonly specifier: string;323 readonly modules: Policy["modules"];324}): Option.Option<{ readonly from: RepoPath; readonly to: string }> => {325 const { from, modules, specifier } = input;326 const own = Option.map(moduleOf(modules, from), (module) => module.module);327328 const reached = RELATIVE.test(specifier)329 ? relative(from, specifier, modules)330 : subpath(specifier, modules);331332 return Option.flatMap(reached, (module) =>333 Option.contains(own, module.module)334 ? Option.none()335 : Option.some({ from, to: specifier })336 );337};