reading-stone 0.0.0-stage → 0.2.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.
Files changed (72) hide show
  1. package/LICENSE +201 -0
  2. package/NOTICE +11 -0
  3. package/README.md +274 -2
  4. package/dist/analysis.d.ts +341 -0
  5. package/dist/analysis.js +392 -0
  6. package/dist/cognitive.d.ts +163 -0
  7. package/dist/cognitive.js +380 -0
  8. package/dist/complexity.d.ts +102 -0
  9. package/dist/complexity.js +163 -0
  10. package/dist/coverage.d.ts +78 -0
  11. package/dist/coverage.js +635 -0
  12. package/dist/detector.d.ts +41 -0
  13. package/dist/detector.js +2134 -0
  14. package/dist/discovery.d.ts +330 -0
  15. package/dist/discovery.js +930 -0
  16. package/dist/doc-coverage.d.ts +155 -0
  17. package/dist/doc-coverage.js +543 -0
  18. package/dist/extract.d.ts +209 -0
  19. package/dist/extract.js +498 -0
  20. package/dist/index.d.ts +64 -0
  21. package/dist/index.js +54 -0
  22. package/dist/internal.d.ts +75 -0
  23. package/dist/internal.js +63 -0
  24. package/dist/main.d.ts +8 -0
  25. package/dist/main.js +39 -0
  26. package/dist/models.d.ts +185 -0
  27. package/dist/models.js +170 -0
  28. package/dist/program.d.ts +207 -0
  29. package/dist/program.js +662 -0
  30. package/dist/protocol.d.ts +88 -0
  31. package/dist/protocol.js +74 -0
  32. package/dist/quality/assertions.d.ts +81 -0
  33. package/dist/quality/assertions.js +425 -0
  34. package/dist/quality/collect.d.ts +66 -0
  35. package/dist/quality/collect.js +412 -0
  36. package/dist/quality/inference.d.ts +86 -0
  37. package/dist/quality/inference.js +603 -0
  38. package/dist/quality/matchers.d.ts +129 -0
  39. package/dist/quality/matchers.js +220 -0
  40. package/dist/quality/pairing.d.ts +133 -0
  41. package/dist/quality/pairing.js +770 -0
  42. package/dist/quality/pipeline.d.ts +59 -0
  43. package/dist/quality/pipeline.js +202 -0
  44. package/dist/quality/types.d.ts +127 -0
  45. package/dist/quality/types.js +92 -0
  46. package/dist/safeio.d.ts +107 -0
  47. package/dist/safeio.js +314 -0
  48. package/dist/server.d.ts +19 -0
  49. package/dist/server.js +451 -0
  50. package/dist/signals/adapter.d.ts +103 -0
  51. package/dist/signals/adapter.js +323 -0
  52. package/dist/signals/caller-index.d.ts +117 -0
  53. package/dist/signals/caller-index.js +147 -0
  54. package/dist/signals/caller.d.ts +76 -0
  55. package/dist/signals/caller.js +108 -0
  56. package/dist/signals/evidence.d.ts +233 -0
  57. package/dist/signals/evidence.js +578 -0
  58. package/dist/signals/interface.d.ts +68 -0
  59. package/dist/signals/interface.js +87 -0
  60. package/dist/signals/jsdoc.d.ts +27 -0
  61. package/dist/signals/jsdoc.js +233 -0
  62. package/dist/signals/naming.d.ts +26 -0
  63. package/dist/signals/naming.js +160 -0
  64. package/dist/signals/routing.d.ts +163 -0
  65. package/dist/signals/routing.js +416 -0
  66. package/dist/signals/types.d.ts +146 -0
  67. package/dist/signals/types.js +99 -0
  68. package/dist/signals/visibility.d.ts +23 -0
  69. package/dist/signals/visibility.js +82 -0
  70. package/dist/taxonomy.d.ts +89 -0
  71. package/dist/taxonomy.js +217 -0
  72. package/package.json +61 -4
@@ -0,0 +1,662 @@
1
+ import { lstatSync, statSync } from "node:fs";
2
+ import { createRequire } from "node:module";
3
+ import { basename, dirname, extname, join } from "node:path";
4
+ import { ScriptKind } from "typescript/unstable/ast";
5
+ import { API, DiagnosticCategory, SymbolFlags, } from "typescript/unstable/sync";
6
+ import { relativeUnderBase } from "./internal.js";
7
+ import { readBoundedSync } from "./safeio.js";
8
+ /**
9
+ * The alias-resolution hop bound: a defensive ceiling on the
10
+ * `getAliasedSymbol` loop below. Real import/re-export chains are short
11
+ * (a direct import resolves in one hop; a barrel re-exporting a barrel in
12
+ * two), and TypeScript alias graphs are acyclic — the bound only guards a
13
+ * pathological server response, never real input.
14
+ */
15
+ const ALIAS_HOP_LIMIT = 8;
16
+ /**
17
+ * Resolves a checker-returned symbol to the symbol its references name,
18
+ * following import and re-export aliases to the declaring symbol — the
19
+ * shared checker-safety primitive for declaration matching (spec 004's
20
+ * pairing strategies; Constitution Principle III's price on the unstable
21
+ * surface).
22
+ *
23
+ * `Checker.getAliasedSymbol` PANICS the native compiler server when handed
24
+ * a non-alias argument ("Should only get alias here", verified against
25
+ * 7.0.2 — the src/signals/evidence.ts module header records the same
26
+ * hazard for its single-hop heritage route), so the Alias-flag gate below
27
+ * is a safety requirement, not a stylistic choice. Alias chains (a barrel
28
+ * re-exporting another barrel) resolve hop by hop, bounded by
29
+ * `ALIAS_HOP_LIMIT` — beyond the bound the symbol is treated as unresolved
30
+ * (absence of evidence, never an error). The checker's unknown symbol (an
31
+ * alias whose target cannot be resolved — a name imported from a missing
32
+ * module) identifies nothing and returns null the same way.
33
+ *
34
+ * @param checker The live program-mode type checker.
35
+ * @param symbol The symbol a reference or import specifier resolved to, or
36
+ * undefined when it resolved nowhere.
37
+ * @returns The referenced symbol with aliases followed, or null when
38
+ * nothing resolvable backs the reference.
39
+ */
40
+ export function resolveSymbolAliases(checker, symbol) {
41
+ if (symbol === undefined) {
42
+ return null;
43
+ }
44
+ let current = symbol;
45
+ for (let hops = 0; (current.flags & SymbolFlags.Alias) !== 0; hops += 1) {
46
+ if (hops >= ALIAS_HOP_LIMIT) {
47
+ return null;
48
+ }
49
+ current = checker.getAliasedSymbol(current);
50
+ if (checker.isUnknownSymbol(current)) {
51
+ return null;
52
+ }
53
+ }
54
+ return current;
55
+ }
56
+ /**
57
+ * The explicit script-kind extension map (research R2): deterministic and
58
+ * auditable, not filename inference with version-dependent `.mjs`/`.cjs`
59
+ * behavior. Exactly the six extensions discovery walks, case-sensitively —
60
+ * a file whose extension is absent from this map never reaches the
61
+ * compiler. `.d.ts` names end in `.ts` and map to TS, matching the
62
+ * compiler's own treatment of declaration files.
63
+ */
64
+ const SCRIPT_KIND_BY_EXTENSION = new Map([
65
+ [".ts", ScriptKind.TS],
66
+ [".tsx", ScriptKind.TSX],
67
+ [".js", ScriptKind.JS],
68
+ [".jsx", ScriptKind.JSX],
69
+ [".mjs", ScriptKind.JS],
70
+ [".cjs", ScriptKind.JS],
71
+ ]);
72
+ /**
73
+ * The analyzer's virtual program-mode config, served at
74
+ * `<root>/.reading-stone-tsconfig.json` — a path that never touches disk.
75
+ * Dot-prefixed and `.json`-suffixed so it can never collide with an
76
+ * in-scope source (discovery walks exactly the six compilable extensions),
77
+ * and a sibling of the real tsconfig so the extender's relative `extends`
78
+ * and every base-relative path resolve against the root. A real file
79
+ * planted at that name is shadowed by the served text: the compiler's
80
+ * only filesystem is the delegation callbacks below.
81
+ */
82
+ const VIRTUAL_CONFIG_NAME = ".reading-stone-tsconfig.json";
83
+ /**
84
+ * The analyzer's forced compiler-option adjustments (research R1), layered
85
+ * over the project's own config through the extender's extends-merge
86
+ * precedence: analysis is strictly read-only — no emit, no incremental
87
+ * state — and never fails on library or JavaScript code it must cover.
88
+ * `tsBuildInfoFile` is not here — JSON cannot spell "unset" — so the
89
+ * bootstrap clears it on the parsed options after the build instead.
90
+ */
91
+ const FORCED_COMPILER_OPTIONS = {
92
+ noEmit: true,
93
+ incremental: false,
94
+ composite: false,
95
+ skipLibCheck: true,
96
+ allowJs: true,
97
+ checkJs: false,
98
+ };
99
+ /**
100
+ * The no-inputs config-diagnostic family (research R3): TS18002 (the
101
+ * files list is empty) and TS18003 (include matched nothing). Neither can
102
+ * affect a bootstrap whose root set is its own, so both are excluded from
103
+ * the fallback triggers.
104
+ */
105
+ const NO_INPUTS_CONFIG_ERROR_CODES = new Set([18002, 18003]);
106
+ /** Module-scope `require` for resolving the analyzer's own dependencies. */
107
+ const moduleRequire = createRequire(import.meta.url);
108
+ /**
109
+ * Writes one skip diagnostic line — the safeio template. Shared by every
110
+ * bootstrap skip site so the channel's format stays single-sourced and
111
+ * deterministic (Constitution I). Parse-only sites pass root-relative
112
+ * paths; the program-mode host passes the absolute compiler-resolved
113
+ * paths, matching safeio's own absolute-path diagnostics for those reads.
114
+ *
115
+ * @param stderr Injected diagnostic sink (Testability principle); stdout is
116
+ * never touched.
117
+ * @param path The skipped path, echoed verbatim.
118
+ * @param reason Short, stable skip reason.
119
+ */
120
+ function writeSkipDiagnostic(stderr, path, reason) {
121
+ stderr.write(`reading-stone: skipping ${path}: ${reason}\n`);
122
+ }
123
+ /**
124
+ * Bootstraps the analysis context from the analyzed tree's own pre-read
125
+ * sources (FR-003 through FR-006; research R1, R2, R3).
126
+ *
127
+ * Mode selection: a usable root `tsconfig.json` drives the program arm —
128
+ * the extender-config route and bounded compiler host documented in the
129
+ * module header. Anything else — no tsconfig, an unreadable one, or a
130
+ * config error beyond the no-inputs family (research R3) — falls back to
131
+ * the parse-only arm: one parsed source per in-scope file, keyed by
132
+ * root-relative path, with the absolute `fileName` and pre-read `text`
133
+ * preserved. A tree with no usable in-scope sources bootstraps an empty
134
+ * parse-only context without spawning the compiler at all.
135
+ *
136
+ * @param realRoot Realpath-resolved absolute analysis root (discovery's
137
+ * `resolveRoot` output); in-scope paths join beneath it.
138
+ * @param sourceFiles The in-scope `(relPath, text)` pairs the pipeline
139
+ * pre-read through the async `readBounded` (16 MiB budget — a JSON-free
140
+ * whole-file read). A `null` text excludes its file.
141
+ * @param stderr Injected diagnostic sink for per-file skips; stdout is
142
+ * never touched (it is reserved for JSON-RPC responses).
143
+ * @returns The bootstrapped `ProgramContext` in either mode.
144
+ */
145
+ export function buildProgramContext(realRoot, sourceFiles, stderr) {
146
+ const usable = collectUsableSources(sourceFiles, stderr);
147
+ if (usable.length === 0) {
148
+ return { mode: "parse-only", sources: new Map() };
149
+ }
150
+ // Program mode first (T007): a usable root tsconfig yields the
151
+ // configured program over exactly the in-scope files. A `null` return
152
+ // is the documented fallback, never an error.
153
+ const configured = buildConfiguredProgram(realRoot, usable, stderr);
154
+ if (configured !== null) {
155
+ return configured;
156
+ }
157
+ const api = new API({
158
+ cwd: realRoot,
159
+ fs: createHermeticFileSystem(realRoot, usable),
160
+ });
161
+ try {
162
+ return {
163
+ mode: "parse-only",
164
+ sources: parseSources(api, realRoot, usable, stderr),
165
+ };
166
+ }
167
+ finally {
168
+ // Parsed sources are self-contained binary views (see the module
169
+ // header), so closing the client here strands nothing the returned
170
+ // context (or a later AST walk) needs.
171
+ api.close();
172
+ }
173
+ }
174
+ /**
175
+ * Bootstraps the configured-program arm (FR-003, FR-005; research R1,
176
+ * R3): when a usable `tsconfig.json` sits at the resolved root, spawn the
177
+ * native compiler once, open the extender project over exactly the
178
+ * in-scope files with the analyzer's forced options, and hand the live
179
+ * program and checker to the caller.
180
+ *
181
+ * The classic-API vocabulary of research R1 — `ts.readConfigFile`,
182
+ * `ts.parseJsonConfigFileContent` error checks, `ts.createProgram` with
183
+ * rootNames — maps onto the native surface as: the config text is read
184
+ * through the bounded reader before anything spawns; the project's own
185
+ * config is parsed by the compiler itself as the extender's `extends`
186
+ * base (comments, chained extends, and enum-name options all natively
187
+ * handled); and the extender's `files` list IS the rootNames override.
188
+ *
189
+ * Every fallback trigger is silent, except the bounded reader's skips,
190
+ * which diagnose themselves: a broken config degrades precision, never
191
+ * availability (FR-004).
192
+ *
193
+ * @param realRoot Realpath-resolved absolute analysis root.
194
+ * @param usable The filtered pre-read in-scope pairs (at least one).
195
+ * @param stderr Injected diagnostic sink; stdout is never touched.
196
+ * @returns The program-mode context, or `null` when the parse-only
197
+ * fallback should run (no tsconfig, unreadable config, or a blocking
198
+ * config error).
199
+ */
200
+ function buildConfiguredProgram(realRoot, usable, stderr) {
201
+ const tsconfigPath = join(realRoot, "tsconfig.json");
202
+ // An absent tsconfig is the first-class no-config case, not a skip: no
203
+ // diagnostic, straight to the parse-only fallback.
204
+ if (!pathExists(tsconfigPath)) {
205
+ return null;
206
+ }
207
+ // The config text through the bounded reader (research R1 step 1): a
208
+ // skip — oversized, symlinked, non-regular, undecodable — has already
209
+ // written its one diagnostic and falls back here, before any spawn.
210
+ const tsconfigText = readBoundedSync(tsconfigPath, stderr);
211
+ if (tsconfigText === undefined) {
212
+ return null;
213
+ }
214
+ const extenderPath = join(realRoot, VIRTUAL_CONFIG_NAME);
215
+ const servedTexts = new Map([
216
+ [tsconfigPath, tsconfigText],
217
+ [extenderPath, buildExtenderConfig(realRoot, usable)],
218
+ ]);
219
+ const api = new API({
220
+ cwd: realRoot,
221
+ fs: createProgramFileSystem(realRoot, usable, servedTexts, stderr),
222
+ });
223
+ let handedOff = false;
224
+ try {
225
+ const snapshot = api.updateSnapshot({ openProjects: [extenderPath] });
226
+ const project = snapshot.getProject(extenderPath);
227
+ if (project === undefined ||
228
+ hasBlockingConfigErrors(project.program.getConfigFileParsingDiagnostics())) {
229
+ // Research R3's boundary: no project, or a config error beyond the
230
+ // no-inputs family. The finally below closes this server before
231
+ // the caller re-runs the parse-only fallback on a fresh one.
232
+ return null;
233
+ }
234
+ // The forced `tsBuildInfoFile: undefined` (research R1): extends can
235
+ // only override the value, never unset it, so the inherited path is
236
+ // cleared here on the parsed options object — the client-side mirror
237
+ // of the classic `{...options, tsBuildInfoFile: undefined}` spread.
238
+ // Emit and incremental state are force-disabled in the merged options
239
+ // the server holds too, so the inherited value is inert either way.
240
+ project.compilerOptions.tsBuildInfoFile = undefined;
241
+ handedOff = true;
242
+ let disposed = false;
243
+ return {
244
+ mode: "program",
245
+ program: project.program,
246
+ checker: project.checker,
247
+ dispose: () => {
248
+ // Idempotent: a consumer that disposes twice — or from a cleanup
249
+ // path after an error — never closes a dead channel twice.
250
+ if (disposed) {
251
+ return;
252
+ }
253
+ disposed = true;
254
+ api.close();
255
+ },
256
+ };
257
+ }
258
+ finally {
259
+ // Every path that did not hand the client to a consumer — fallback,
260
+ // or a throw from the snapshot/project calls — closes it here.
261
+ if (!handedOff) {
262
+ api.close();
263
+ }
264
+ }
265
+ }
266
+ /**
267
+ * Renders the virtual extender config — the program-mode statement of
268
+ * research R1's rootNames override and forced options. `extends` pulls
269
+ * the project's own options in verbatim (the compiler resolves the chain,
270
+ * comments and all, through the bounded host); `files` fixes the root set
271
+ * to exactly the in-scope paths; and the empty `include`/`references`
272
+ * arrays REPLACE any the project declared (tsconfig extends substitutes
273
+ * top-level fields), so nothing outside the in-scope override can enter
274
+ * the program through the config.
275
+ *
276
+ * @param realRoot Realpath-resolved absolute analysis root.
277
+ * @param usable The filtered pre-read in-scope pairs (at least one).
278
+ * @returns The serialized config text, deterministic for the same inputs.
279
+ */
280
+ function buildExtenderConfig(realRoot, usable) {
281
+ return JSON.stringify({
282
+ extends: "./tsconfig.json",
283
+ // Absolute paths: the config is served at a virtual path whose
284
+ // directory is the root, but absolute entries remove any ambiguity
285
+ // about the resolution base.
286
+ files: usable.map(([relPath]) => join(realRoot, relPath)),
287
+ include: [],
288
+ references: [],
289
+ compilerOptions: FORCED_COMPILER_OPTIONS,
290
+ });
291
+ }
292
+ /**
293
+ * Research R3's fallback boundary over the extender project's config
294
+ * diagnostics: the extends chain propagates the project config's own
295
+ * parse errors here (verified against typescript 7.0.2), so one check
296
+ * covers both the extender and the config it extends. Only error-category
297
+ * diagnostics gate, and the no-inputs family is excluded — a bootstrap
298
+ * whose root set is its own cannot be affected by an empty files list or
299
+ * an include that matches nothing.
300
+ *
301
+ * @param diagnostics The project's config-file parsing diagnostics.
302
+ * @returns `true` when at least one non-no-inputs error is reported.
303
+ */
304
+ function hasBlockingConfigErrors(diagnostics) {
305
+ for (const diagnostic of diagnostics) {
306
+ if (diagnostic.category !== DiagnosticCategory.Error) {
307
+ continue;
308
+ }
309
+ if (NO_INPUTS_CONFIG_ERROR_CODES.has(diagnostic.code)) {
310
+ continue;
311
+ }
312
+ return true;
313
+ }
314
+ return false;
315
+ }
316
+ /**
317
+ * Filters the pre-read pairs down to the files the compiler will see:
318
+ * `null` texts are excluded (already diagnosed by `readBounded`), and a
319
+ * path whose extension is absent from the explicit map is a diagnosed skip
320
+ * — discovery walks exactly the mapped extensions, so this fires only if
321
+ * the two surfaces drift apart.
322
+ *
323
+ * @param sourceFiles Pre-read pairs, verbatim from the pipeline.
324
+ * @param stderr Injected diagnostic sink for extension skips.
325
+ * @returns The `(relPath, text)` pairs safe to hand to the compiler, in
326
+ * caller order.
327
+ */
328
+ function collectUsableSources(sourceFiles, stderr) {
329
+ const usable = [];
330
+ for (const [relPath, text] of sourceFiles) {
331
+ if (text === null) {
332
+ continue;
333
+ }
334
+ if (!SCRIPT_KIND_BY_EXTENSION.has(extname(relPath))) {
335
+ writeSkipDiagnostic(stderr, relPath, "unsupported extension");
336
+ continue;
337
+ }
338
+ usable.push([relPath, text]);
339
+ }
340
+ return usable;
341
+ }
342
+ /**
343
+ * Indexes the pre-read pairs into the hermetic view. The ancestor walk
344
+ * terminates at the filesystem root (a path's `dirname` chain is finite).
345
+ *
346
+ * @param realRoot Realpath-resolved absolute analysis root.
347
+ * @param sources The filtered pre-read pairs.
348
+ * @returns The in-scope texts and visible directories.
349
+ */
350
+ function buildHermeticView(realRoot, sources) {
351
+ const fileTexts = new Map();
352
+ const directories = new Set([realRoot]);
353
+ for (const [relPath, text] of sources) {
354
+ const absPath = join(realRoot, relPath);
355
+ fileTexts.set(absPath, text);
356
+ for (let dir = dirname(absPath); !directories.has(dir); dir = dirname(dir)) {
357
+ directories.add(dir);
358
+ if (dir === dirname(dir)) {
359
+ break; // Reached the filesystem root: a termination guarantee.
360
+ }
361
+ }
362
+ }
363
+ return { fileTexts, directories };
364
+ }
365
+ /**
366
+ * One hermetic directory listing: the in-scope files and known directories
367
+ * directly inside `dirName`, sorted so the compiler's view is a pure
368
+ * function of the tree, independent of caller pair order (Constitution
369
+ * I). Deliberately NOT the real directory contents — include-style
370
+ * globbing through the compiler (the project config's own, parsed along
371
+ * the extends chain) must never surface files beyond the in-scope set.
372
+ *
373
+ * @param view The hermetic view to list from.
374
+ * @param dirName Directory to list.
375
+ * @returns The sorted files and directories the compiler may see.
376
+ */
377
+ function hermeticDirectoryEntries(view, dirName) {
378
+ return {
379
+ files: [...view.fileTexts.keys()]
380
+ .filter((absPath) => dirname(absPath) === dirName)
381
+ .map((absPath) => basename(absPath))
382
+ .sort(),
383
+ directories: [...view.directories]
384
+ .filter((dir) => dir !== dirName && dirname(dir) === dirName)
385
+ .map((dir) => basename(dir))
386
+ .sort(),
387
+ };
388
+ }
389
+ /**
390
+ * Builds the hermetic filesystem the parse-only compiler client is
391
+ * spawned with — that mode's bounded host (Constitution V). Every
392
+ * callback answers from the pre-read pairs and never returns `undefined`,
393
+ * so the compiler can never fall back to the real filesystem: unknown
394
+ * paths do not exist, and no `writeFile` callback is provided at all.
395
+ * Directory existence is the analysis root plus each source's ancestor
396
+ * directories — enough for the compiler's per-file project resolution,
397
+ * while the on-disk tsconfig stays invisible: with nothing configured to
398
+ * find, every opened file lands in the compiler's single inferred
399
+ * project, exactly the parse-only route's requirement.
400
+ *
401
+ * @param realRoot Realpath-resolved absolute analysis root.
402
+ * @param sources The filtered pre-read pairs.
403
+ * @returns The delegation callbacks for `new API({ cwd, fs })`.
404
+ */
405
+ function createHermeticFileSystem(realRoot, sources) {
406
+ const view = buildHermeticView(realRoot, sources);
407
+ return {
408
+ readFile: (fileName) => {
409
+ // `null` — never `undefined` — so an unknown path does not exist
410
+ // rather than falling back to the real filesystem. An empty-string
411
+ // text is a real empty file and must be served, not skipped.
412
+ const text = view.fileTexts.get(fileName);
413
+ return text === undefined ? null : text;
414
+ },
415
+ fileExists: (fileName) => view.fileTexts.has(fileName),
416
+ directoryExists: (dirName) => view.directories.has(dirName),
417
+ getAccessibleEntries: (dirName) => hermeticDirectoryEntries(view, dirName),
418
+ realpath: (path) => path,
419
+ };
420
+ }
421
+ /**
422
+ * The program mode's bounded compiler host (FR-003; research R1;
423
+ * Constitution Principle V): the delegation callbacks the native server
424
+ * is spawned with. Every route is ordered so the compiler can never fall
425
+ * back to the real filesystem — `undefined` is the fallback signal, and
426
+ * every answer is a text or does-not-exist:
427
+ *
428
+ * 1. The two served config texts (the project's own tsconfig and the
429
+ * virtual extender) and the in-scope pre-read texts come from memory.
430
+ * 2. Reads under the typescript package's own platform lib directory are
431
+ * bounded but exempt from root containment — the analyzer's
432
+ * dependency, not analyzed-tree content.
433
+ * 3. Any other in-root path is probed with lstat (never followed) and,
434
+ * only when present, read through `readBoundedSync`: skipped
435
+ * transitive files resolve as absent modules, their types degrading
436
+ * to `any` for FR-017's ambiguity rules — graceful degradation, never
437
+ * a crash. Absent probes stay silent: routine module-resolution
438
+ * misses (package.json lookups) are not skips.
439
+ * 4. Every other compiler-resolved path outside the analysis root does
440
+ * not exist, with one diagnostic — a config whose typeRoots or paths
441
+ * point outside the root degrades to `any` types rather than reading
442
+ * out-of-root trees.
443
+ *
444
+ * Existence probing mirrors the read routing: out-of-root paths do not
445
+ * exist, in-root paths are probed with lstat, and directory listings are
446
+ * the hermetic in-scope view — include-style globbing can only ever see
447
+ * in-scope files, never widening the program's root set.
448
+ *
449
+ * @param realRoot Realpath-resolved absolute analysis root.
450
+ * @param usable The filtered pre-read in-scope pairs.
451
+ * @param servedTexts The config texts served verbatim, keyed by path —
452
+ * the project tsconfig and the virtual extender.
453
+ * @param stderr Injected diagnostic sink for bounded-read skips.
454
+ * @returns The delegation callbacks for `new API({ cwd, fs })`.
455
+ */
456
+ function createProgramFileSystem(realRoot, usable, servedTexts, stderr) {
457
+ const view = buildHermeticView(realRoot, usable);
458
+ return {
459
+ readFile: (fileName) => {
460
+ const served = servedTexts.get(fileName);
461
+ if (served !== undefined) {
462
+ return served;
463
+ }
464
+ const inScope = view.fileTexts.get(fileName);
465
+ if (inScope !== undefined) {
466
+ return inScope;
467
+ }
468
+ const libDirectory = compilerLibDirectory();
469
+ if (libDirectory !== null && isPathInside(libDirectory, fileName)) {
470
+ return readBoundedSync(fileName, stderr) ?? null;
471
+ }
472
+ if (isPathInside(realRoot, fileName)) {
473
+ // Absent probes are normal resolution traffic, not skips: only
474
+ // an existing file earns a bounded read — and its possible one
475
+ // skip diagnostic (the oversized-transitive-dep case).
476
+ if (!pathExists(fileName)) {
477
+ return null;
478
+ }
479
+ return readBoundedSync(fileName, stderr) ?? null;
480
+ }
481
+ writeSkipDiagnostic(stderr, fileName, "outside analysis root");
482
+ return null;
483
+ },
484
+ fileExists: (fileName) => {
485
+ if (servedTexts.has(fileName) || view.fileTexts.has(fileName)) {
486
+ return true;
487
+ }
488
+ const libDirectory = compilerLibDirectory();
489
+ if ((libDirectory !== null && isPathInside(libDirectory, fileName)) ||
490
+ isPathInside(realRoot, fileName)) {
491
+ return pathExists(fileName);
492
+ }
493
+ return false;
494
+ },
495
+ directoryExists: (dirName) => {
496
+ if (view.directories.has(dirName)) {
497
+ return true;
498
+ }
499
+ if (isPathInside(realRoot, dirName)) {
500
+ try {
501
+ // lstat, never stat: a symlinked directory is not followed —
502
+ // the safeio discipline extends to the compiler's view of the
503
+ // analyzed tree (Constitution V).
504
+ return lstatSync(dirName).isDirectory();
505
+ }
506
+ catch {
507
+ return false;
508
+ }
509
+ }
510
+ return false;
511
+ },
512
+ getAccessibleEntries: (dirName) => hermeticDirectoryEntries(view, dirName),
513
+ realpath: (path) => path,
514
+ };
515
+ }
516
+ /** Memoized result of `computeCompilerLibDirectory` (undefined = unset). */
517
+ let compilerLibDirectoryCache;
518
+ /**
519
+ * The typescript package's platform-specific lib directory — where the
520
+ * native compiler's default libraries (`lib.es2020.full.d.ts` and kin)
521
+ * live — resolved once per process. `null` when it cannot be located, in
522
+ * which case no out-of-root path qualifies as a lib read.
523
+ */
524
+ function compilerLibDirectory() {
525
+ if (compilerLibDirectoryCache === undefined) {
526
+ compilerLibDirectoryCache = computeCompilerLibDirectory();
527
+ }
528
+ return compilerLibDirectoryCache;
529
+ }
530
+ /**
531
+ * Locates the lib directory from the analyzer's own dependency tree: the
532
+ * `typescript` package first, then the
533
+ * `@typescript/typescript-<platform>-<arch>` package that carries the
534
+ * native compiler binary — either hoisted beside it (the npm default) or
535
+ * nested under it. The candidate order is deterministic; both are the
536
+ * same package the `API` client spawns, so a server that spawned at all
537
+ * implies at least one resolves.
538
+ */
539
+ function computeCompilerLibDirectory() {
540
+ let typescriptDirectory;
541
+ try {
542
+ typescriptDirectory = dirname(moduleRequire.resolve("typescript/package.json"));
543
+ }
544
+ catch {
545
+ // Without the typescript package nothing could have spawned the
546
+ // server; treat the lib directory as absent rather than throw.
547
+ return null;
548
+ }
549
+ const platformPackage = `typescript-${process.platform}-${process.arch}`;
550
+ const candidates = [
551
+ join(dirname(typescriptDirectory), "@typescript", platformPackage, "lib"),
552
+ join(typescriptDirectory, "node_modules", "@typescript", platformPackage, "lib"),
553
+ ];
554
+ for (const candidate of candidates) {
555
+ if (isExistingDirectory(candidate)) {
556
+ return candidate;
557
+ }
558
+ }
559
+ return null;
560
+ }
561
+ /**
562
+ * Unlike the analyzed-tree probes, this check follows symlinks (stat, not
563
+ * lstat): the lib directory is the analyzer's own dependency, and package
564
+ * managers legitimately symlink it (pnpm-style stores).
565
+ *
566
+ * @param path Candidate directory.
567
+ * @returns Whether it exists as a directory.
568
+ */
569
+ function isExistingDirectory(path) {
570
+ try {
571
+ return statSync(path).isDirectory();
572
+ }
573
+ catch {
574
+ return false;
575
+ }
576
+ }
577
+ /**
578
+ * Whether a path exists, probed with lstat so the final symlink is never
579
+ * followed — the analyzed tree's own existence question, distinct from
580
+ * the analyzer-dependency probes (which follow). A probe is metadata
581
+ * only: no content is read, so the Constitution V read bounds are not in
582
+ * play.
583
+ *
584
+ * @param path Candidate path.
585
+ * @returns Whether anything exists at the path (any file type).
586
+ */
587
+ function pathExists(path) {
588
+ try {
589
+ lstatSync(path);
590
+ return true;
591
+ }
592
+ catch {
593
+ return false;
594
+ }
595
+ }
596
+ /**
597
+ * Lexical containment: `candidate` is strictly inside `base`, via the
598
+ * shared `relativeUnderBase` helper (src/internal.ts) — the deliberately
599
+ * literal `..` defense included, so even a pathological in-base sibling
600
+ * such as `..hidden.ts` is refused rather than risk an escape.
601
+ *
602
+ * @param base Containing directory.
603
+ * @param candidate Path to test.
604
+ * @returns Whether the candidate is strictly beneath the base.
605
+ */
606
+ function isPathInside(base, candidate) {
607
+ return relativeUnderBase(base, candidate) !== null;
608
+ }
609
+ /**
610
+ * Parses every usable in-scope source through the compiler client's
611
+ * inferred project — the parse-only route (research R2). All files open in
612
+ * one `updateSnapshot` and land in one inferred project; each is fetched
613
+ * back as a self-contained parsed source, verified against the explicit
614
+ * extension map, and keyed by its root-relative path.
615
+ *
616
+ * @param api The spawned compiler client (lifecycle owned by the caller).
617
+ * @param realRoot Realpath-resolved absolute analysis root.
618
+ * @param sources The filtered pre-read pairs.
619
+ * @param stderr Injected diagnostic sink for per-file skips.
620
+ * @returns Parsed sources keyed by root-relative POSIX path, in pair order.
621
+ */
622
+ function parseSources(api, realRoot, sources, stderr) {
623
+ const snapshot = api.updateSnapshot({
624
+ openFiles: sources.map(([relPath]) => join(realRoot, relPath)),
625
+ });
626
+ const parsed = new Map();
627
+ for (const [relPath] of sources) {
628
+ const absPath = join(realRoot, relPath);
629
+ // The mapped kind the compiler must have used. The lookup cannot miss
630
+ // (collectUsableSources rejected unmapped extensions), so a miss
631
+ // collapses into the mismatch comparison below rather than a separate
632
+ // branch.
633
+ const expectedKind = SCRIPT_KIND_BY_EXTENSION.get(extname(relPath));
634
+ try {
635
+ const project = snapshot.getDefaultProjectForFile(absPath);
636
+ const source = project?.program.getSourceFile(absPath);
637
+ if (source === undefined) {
638
+ writeSkipDiagnostic(stderr, relPath, "not present in snapshot");
639
+ continue;
640
+ }
641
+ // Reading scriptKind forces the source-file header decode, so the
642
+ // comparison stays inside the RangeError guard (research R15).
643
+ if (source.scriptKind !== expectedKind) {
644
+ writeSkipDiagnostic(stderr, relPath, "unexpected script kind");
645
+ continue;
646
+ }
647
+ parsed.set(relPath, source);
648
+ }
649
+ catch (error) {
650
+ if (error instanceof RangeError) {
651
+ // Pathological nesting escaping source-file fetch/decode (research
652
+ // R15): the same skip-with-one-diagnostic as a bounded-read skip —
653
+ // the per-file guard isolates the damage, never a request abort.
654
+ writeSkipDiagnostic(stderr, relPath, "parser stack overflow");
655
+ continue;
656
+ }
657
+ throw error;
658
+ }
659
+ }
660
+ return parsed;
661
+ }
662
+ //# sourceMappingURL=program.js.map