@tsdoctor/vfs 0.1.0 → 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.
@@ -0,0 +1,188 @@
1
+ import { createHash } from "node:crypto";
2
+ import { gunzipSync, gzipSync } from "node:zlib";
3
+
4
+ //#region src/TwoslashCache.ts
5
+ /**
6
+ * Persisted Twoslash result cache.
7
+ *
8
+ * Type-checking code blocks is by far the dominant cost of the render phase —
9
+ * measured at ~97% of it, concentrated in the minority of blocks that carry an
10
+ * `@example` (see `render-phase-instrumentation.md`). `@shikijs/twoslash`
11
+ * exposes a first-class `typesCache` seam for exactly this, so the work here is
12
+ * a keying scheme and a store rather than a new interception point.
13
+ *
14
+ * ## Soundness
15
+ *
16
+ * A Twoslash result depends on the code, the compiler options, the declarations
17
+ * it is checked against, and the compiler doing the checking. The keys cover
18
+ * all four: the per-entry key carries the code, its language and the compiler
19
+ * options; {@link twoslashEnvHash} carries the declarations and the TypeScript
20
+ * version.
21
+ *
22
+ * The TypeScript version is load-bearing and easy to overlook — `lib.d.ts`
23
+ * ships with the compiler and inference changes between releases, so an upgrade
24
+ * against unchanged declarations yields different hovers. Omitting it would let
25
+ * a warm cache serve results from the previous compiler and stay wrong until
26
+ * the API's own declarations happened to change.
27
+ *
28
+ * NOT covered, and covered instead by {@link TWOSLASH_CACHE_FORMAT}: the
29
+ * `@shikijs/twoslash` / `twoslash` renderer version, which determines the shape
30
+ * of the stored `nodes`. Bump the format constant when upgrading those, since
31
+ * nothing derives it automatically.
32
+ *
33
+ * ## Invalidation granularity
34
+ *
35
+ * The consequence of that soundness is coarse invalidation: any VFS change
36
+ * discards the whole generation, because a declaration change anywhere can
37
+ * legitimately change any block's inferred types. So this cache makes repeat
38
+ * builds over an UNCHANGED API nearly free — CI re-runs, prose-only edits,
39
+ * theme and config changes, rebuilding a site without touching the library —
40
+ * and does nothing for the build right after an API item changes.
41
+ *
42
+ * Sharpening that would need per-scope type environments, so one package's
43
+ * change stops invalidating every other package's blocks. That is fix (b) in
44
+ * `render-phase-instrumentation.md`, tracked as a correctness fix; it would
45
+ * make this cache substantially more effective on a multi-API site as a side
46
+ * effect.
47
+ *
48
+ * ## Synchronous by necessity
49
+ *
50
+ * `TwoslashTypesCache.read`/`write` are synchronous — they are called from
51
+ * inside Shiki's `preprocess` hook. Persistence is therefore load-once at
52
+ * startup and save-once at the end, against an in-memory map; there is no
53
+ * per-entry I/O. See `TwoslashCacheService`.
54
+ */
55
+ /**
56
+ * Bumped when the stored shape changes, so an older blob is treated as absent
57
+ * rather than deserialized into the wrong shape.
58
+ *
59
+ * Also the manual lever for renderer changes: bump this when upgrading
60
+ * `@shikijs/twoslash` or `twoslash`, whose versions determine the shape of the
61
+ * stored `nodes` and are not derived into any key.
62
+ *
63
+ * @public
64
+ */
65
+ const TWOSLASH_CACHE_FORMAT = 1;
66
+ function sha256(input) {
67
+ return createHash("sha256").update(input).digest("hex");
68
+ }
69
+ /**
70
+ * Fingerprint the type environment a generation is checked against.
71
+ *
72
+ * Covers the declarations (`vfs`) and the compiler that interprets them
73
+ * (`toolchain`). The VFS is hashed over sorted `path\0content` pairs so the
74
+ * digest is stable against map iteration order.
75
+ *
76
+ * `toolchain` must carry the TypeScript version. The declarations alone do not
77
+ * determine the answer: `lib.d.ts` ships with the compiler and inference
78
+ * behaviour changes between releases, so upgrading TypeScript against unchanged
79
+ * declarations produces different hovers. Without the version in the key the
80
+ * warm cache would serve results computed by the previous compiler, and stay
81
+ * wrong until the API's own declarations happened to change.
82
+ *
83
+ * Compiler OPTIONS are deliberately not folded in here — they belong on the
84
+ * per-entry key, so one generation can hold results from the several
85
+ * configurations a multi-API site may declare.
86
+ *
87
+ * @public
88
+ */
89
+ function twoslashEnvHash(vfs, toolchain) {
90
+ const hash = createHash("sha256");
91
+ hash.update(`format:${1}\0toolchain:${toolchain}\0`);
92
+ for (const key of [...vfs.keys()].sort()) hash.update(`${key}\0${vfs.get(key) ?? ""}\0`);
93
+ return hash.digest("hex");
94
+ }
95
+ /** JSON with object keys sorted, so equivalent options hash identically. */
96
+ function stableStringify(value) {
97
+ if (value === null || typeof value !== "object") return JSON.stringify(value) ?? "null";
98
+ if (Array.isArray(value)) return `[${value.map(stableStringify).join(",")}]`;
99
+ return `{${Object.entries(value).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0).map(([k, v]) => `${JSON.stringify(k)}:${stableStringify(v)}`).join(",")}}`;
100
+ }
101
+ /**
102
+ * Per-entry key: the code, its language, and the compiler configuration it is
103
+ * checked under.
104
+ *
105
+ * The configuration matters because two APIs on one site may be documented
106
+ * under different `tsconfig`s — the same source checked under different options
107
+ * can produce different types, so it must not share a cache entry.
108
+ *
109
+ * @public
110
+ */
111
+ function twoslashEntryKey(code, lang, compilerOptions) {
112
+ return sha256(`${lang ?? "ts"}\0${stableStringify(compilerOptions ?? {})}\0${code}`);
113
+ }
114
+ /**
115
+ * The cache key a whole generation is stored under. One blob per environment,
116
+ * so a changed environment reads as a miss rather than serving stale results.
117
+ *
118
+ * @public
119
+ */
120
+ function twoslashBlobKey(envHash) {
121
+ return `twoslash/v${1}/${envHash}`;
122
+ }
123
+ /**
124
+ * Build a synchronous Twoslash cache over an in-memory map, optionally seeded
125
+ * with entries loaded from a previous build.
126
+ *
127
+ * @public
128
+ */
129
+ function makeTwoslashCache(initial) {
130
+ const map = new Map(initial);
131
+ let hits = 0;
132
+ let misses = 0;
133
+ let dirty = false;
134
+ return {
135
+ read: (code, lang, options) => {
136
+ const found = map.get(twoslashEntryKey(code, lang, options?.compilerOptions));
137
+ if (found === void 0) {
138
+ misses += 1;
139
+ return null;
140
+ }
141
+ hits += 1;
142
+ return found;
143
+ },
144
+ write: (code, data, lang, options) => {
145
+ const value = {
146
+ nodes: data.nodes,
147
+ code: data.code,
148
+ ...data.meta?.extension != null ? { meta: { extension: data.meta.extension } } : {}
149
+ };
150
+ map.set(twoslashEntryKey(code, lang, options?.compilerOptions), value);
151
+ dirty = true;
152
+ },
153
+ stats: () => ({
154
+ hits,
155
+ misses,
156
+ entries: map.size,
157
+ dirty
158
+ }),
159
+ entries: () => map
160
+ };
161
+ }
162
+ /** Serialize a generation for storage. Gzipped JSON — hover text compresses well. *
163
+ * @public
164
+ */
165
+ function encodeTwoslashCache(entries) {
166
+ return gzipSync(Buffer.from(JSON.stringify(Object.fromEntries(entries)), "utf-8"));
167
+ }
168
+ /**
169
+ * Deserialize a stored generation.
170
+ *
171
+ * Returns an empty map for anything unreadable — a truncated blob, a format
172
+ * change, a corrupted file. A cache that cannot be read is a cache miss, never
173
+ * a build failure.
174
+ *
175
+ * @public
176
+ */
177
+ function decodeTwoslashCache(blob) {
178
+ try {
179
+ const parsed = JSON.parse(gunzipSync(blob).toString("utf-8"));
180
+ if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) return /* @__PURE__ */ new Map();
181
+ return new Map(Object.entries(parsed));
182
+ } catch {
183
+ return /* @__PURE__ */ new Map();
184
+ }
185
+ }
186
+
187
+ //#endregion
188
+ export { TWOSLASH_CACHE_FORMAT, decodeTwoslashCache, encodeTwoslashCache, makeTwoslashCache, twoslashBlobKey, twoslashEntryKey, twoslashEnvHash };
package/index.d.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  import { CompilerOptions, ProgrammaticCompilerOptions } from "@effected/tsconfig-json";
2
2
  import { Effect, FileSystem, PlatformError, Result, Schema } from "effect";
3
3
  import { VirtualTypeScriptEnvironment } from "@typescript/vfs";
4
+ import { TwoslashTypesCache } from "@shikijs/twoslash";
4
5
  import { PathLike } from "node:fs";
5
6
  //#region src/TypeResolutionOptions.d.ts
6
7
  /**
@@ -252,6 +253,163 @@ declare class TsEnvironment {
252
253
  static make(options: TsEnvironmentOptions): Effect.Effect<VirtualTypeScriptEnvironment, TsEnvironmentError>;
253
254
  }
254
255
  //#endregion
256
+ //#region src/TwoslashCache.d.ts
257
+ /**
258
+ * Persisted Twoslash result cache.
259
+ *
260
+ * Type-checking code blocks is by far the dominant cost of the render phase —
261
+ * measured at ~97% of it, concentrated in the minority of blocks that carry an
262
+ * `@example` (see `render-phase-instrumentation.md`). `@shikijs/twoslash`
263
+ * exposes a first-class `typesCache` seam for exactly this, so the work here is
264
+ * a keying scheme and a store rather than a new interception point.
265
+ *
266
+ * ## Soundness
267
+ *
268
+ * A Twoslash result depends on the code, the compiler options, the declarations
269
+ * it is checked against, and the compiler doing the checking. The keys cover
270
+ * all four: the per-entry key carries the code, its language and the compiler
271
+ * options; {@link twoslashEnvHash} carries the declarations and the TypeScript
272
+ * version.
273
+ *
274
+ * The TypeScript version is load-bearing and easy to overlook — `lib.d.ts`
275
+ * ships with the compiler and inference changes between releases, so an upgrade
276
+ * against unchanged declarations yields different hovers. Omitting it would let
277
+ * a warm cache serve results from the previous compiler and stay wrong until
278
+ * the API's own declarations happened to change.
279
+ *
280
+ * NOT covered, and covered instead by {@link TWOSLASH_CACHE_FORMAT}: the
281
+ * `@shikijs/twoslash` / `twoslash` renderer version, which determines the shape
282
+ * of the stored `nodes`. Bump the format constant when upgrading those, since
283
+ * nothing derives it automatically.
284
+ *
285
+ * ## Invalidation granularity
286
+ *
287
+ * The consequence of that soundness is coarse invalidation: any VFS change
288
+ * discards the whole generation, because a declaration change anywhere can
289
+ * legitimately change any block's inferred types. So this cache makes repeat
290
+ * builds over an UNCHANGED API nearly free — CI re-runs, prose-only edits,
291
+ * theme and config changes, rebuilding a site without touching the library —
292
+ * and does nothing for the build right after an API item changes.
293
+ *
294
+ * Sharpening that would need per-scope type environments, so one package's
295
+ * change stops invalidating every other package's blocks. That is fix (b) in
296
+ * `render-phase-instrumentation.md`, tracked as a correctness fix; it would
297
+ * make this cache substantially more effective on a multi-API site as a side
298
+ * effect.
299
+ *
300
+ * ## Synchronous by necessity
301
+ *
302
+ * `TwoslashTypesCache.read`/`write` are synchronous — they are called from
303
+ * inside Shiki's `preprocess` hook. Persistence is therefore load-once at
304
+ * startup and save-once at the end, against an in-memory map; there is no
305
+ * per-entry I/O. See `TwoslashCacheService`.
306
+ */
307
+ /**
308
+ * Bumped when the stored shape changes, so an older blob is treated as absent
309
+ * rather than deserialized into the wrong shape.
310
+ *
311
+ * Also the manual lever for renderer changes: bump this when upgrading
312
+ * `@shikijs/twoslash` or `twoslash`, whose versions determine the shape of the
313
+ * stored `nodes` and are not derived into any key.
314
+ *
315
+ * @public
316
+ */
317
+ declare const TWOSLASH_CACHE_FORMAT = 1;
318
+ /**
319
+ * The subset of a Twoslash run that Shiki consumes, and all this cache stores.
320
+ *
321
+ * @public
322
+ */
323
+ interface TwoslashCacheValue {
324
+ readonly nodes: unknown;
325
+ readonly code: string;
326
+ readonly meta?: {
327
+ readonly extension?: string;
328
+ };
329
+ }
330
+ /**
331
+ * Hit/miss statistics for one generation.
332
+ *
333
+ * @public
334
+ */
335
+ interface TwoslashCacheStats {
336
+ readonly hits: number;
337
+ readonly misses: number;
338
+ /** Entries currently held, including those loaded from a previous build. */
339
+ readonly entries: number;
340
+ /** True when at least one entry was written this build. */
341
+ readonly dirty: boolean;
342
+ }
343
+ /**
344
+ * The synchronous in-memory cache Shiki reads and writes, plus its statistics.
345
+ *
346
+ * @public
347
+ */
348
+ interface TwoslashResultCache extends TwoslashTypesCache {
349
+ readonly stats: () => TwoslashCacheStats;
350
+ readonly entries: () => ReadonlyMap<string, TwoslashCacheValue>;
351
+ }
352
+ /**
353
+ * Fingerprint the type environment a generation is checked against.
354
+ *
355
+ * Covers the declarations (`vfs`) and the compiler that interprets them
356
+ * (`toolchain`). The VFS is hashed over sorted `path\0content` pairs so the
357
+ * digest is stable against map iteration order.
358
+ *
359
+ * `toolchain` must carry the TypeScript version. The declarations alone do not
360
+ * determine the answer: `lib.d.ts` ships with the compiler and inference
361
+ * behaviour changes between releases, so upgrading TypeScript against unchanged
362
+ * declarations produces different hovers. Without the version in the key the
363
+ * warm cache would serve results computed by the previous compiler, and stay
364
+ * wrong until the API's own declarations happened to change.
365
+ *
366
+ * Compiler OPTIONS are deliberately not folded in here — they belong on the
367
+ * per-entry key, so one generation can hold results from the several
368
+ * configurations a multi-API site may declare.
369
+ *
370
+ * @public
371
+ */
372
+ declare function twoslashEnvHash(vfs: ReadonlyMap<string, string>, toolchain: string): string;
373
+ /**
374
+ * Per-entry key: the code, its language, and the compiler configuration it is
375
+ * checked under.
376
+ *
377
+ * The configuration matters because two APIs on one site may be documented
378
+ * under different `tsconfig`s — the same source checked under different options
379
+ * can produce different types, so it must not share a cache entry.
380
+ *
381
+ * @public
382
+ */
383
+ declare function twoslashEntryKey(code: string, lang: string | undefined, compilerOptions?: unknown): string;
384
+ /**
385
+ * The cache key a whole generation is stored under. One blob per environment,
386
+ * so a changed environment reads as a miss rather than serving stale results.
387
+ *
388
+ * @public
389
+ */
390
+ declare function twoslashBlobKey(envHash: string): string;
391
+ /**
392
+ * Build a synchronous Twoslash cache over an in-memory map, optionally seeded
393
+ * with entries loaded from a previous build.
394
+ *
395
+ * @public
396
+ */
397
+ declare function makeTwoslashCache(initial?: ReadonlyMap<string, TwoslashCacheValue>): TwoslashResultCache;
398
+ /** Serialize a generation for storage. Gzipped JSON — hover text compresses well. *
399
+ * @public
400
+ */
401
+ declare function encodeTwoslashCache(entries: ReadonlyMap<string, TwoslashCacheValue>): Uint8Array;
402
+ /**
403
+ * Deserialize a stored generation.
404
+ *
405
+ * Returns an empty map for anything unreadable — a truncated blob, a format
406
+ * change, a corrupted file. A cache that cannot be read is a cache miss, never
407
+ * a build failure.
408
+ *
409
+ * @public
410
+ */
411
+ declare function decodeTwoslashCache(blob: Uint8Array): Map<string, TwoslashCacheValue>;
412
+ //#endregion
255
413
  //#region src/TypeScriptConfig.d.ts
256
414
  /**
257
415
  * How a caller points at TypeScript configuration: a `tsconfig.json`, inline
@@ -501,5 +659,5 @@ declare class VirtualPackage extends VirtualPackage_base {
501
659
  private toPackageJson;
502
660
  }
503
661
  //#endregion
504
- export { type CompilerOptionsInput, DEFAULT_COMPILER_OPTIONS, TsConfigParseError, TsEnvironment, TsEnvironmentError, type TsEnvironmentOptions, TypeResolutionCompilerOptions, type TypeScriptConfig, type Vfs, VirtualPackage, decodeCompilerOptions, isTypeDefinition, mergeCompilerOptions, mergeVfs, parseTsConfig, prefixVfs, resolveTypeScriptConfig, resolveTypeScriptConfigSingle, resolveTypeScriptConfigSingleAsync, toProgrammaticCompilerOptions };
662
+ export { type CompilerOptionsInput, DEFAULT_COMPILER_OPTIONS, TWOSLASH_CACHE_FORMAT, TsConfigParseError, TsEnvironment, TsEnvironmentError, type TsEnvironmentOptions, type TwoslashCacheStats, type TwoslashCacheValue, type TwoslashResultCache, TypeResolutionCompilerOptions, type TypeScriptConfig, type Vfs, VirtualPackage, decodeCompilerOptions, decodeTwoslashCache, encodeTwoslashCache, isTypeDefinition, makeTwoslashCache, mergeCompilerOptions, mergeVfs, parseTsConfig, prefixVfs, resolveTypeScriptConfig, resolveTypeScriptConfigSingle, resolveTypeScriptConfigSingleAsync, toProgrammaticCompilerOptions, twoslashBlobKey, twoslashEntryKey, twoslashEnvHash };
505
663
  //# sourceMappingURL=index.d.ts.map
package/index.js CHANGED
@@ -2,7 +2,8 @@ import { TypeResolutionCompilerOptions, decodeCompilerOptions, toProgrammaticCom
2
2
  import { TsConfigParseError, parseTsConfig } from "./TsconfigParser.js";
3
3
  import { isTypeDefinition, mergeVfs, prefixVfs } from "./Vfs.js";
4
4
  import { TsEnvironment, TsEnvironmentError } from "./TsEnvironment.js";
5
+ import { TWOSLASH_CACHE_FORMAT, decodeTwoslashCache, encodeTwoslashCache, makeTwoslashCache, twoslashBlobKey, twoslashEntryKey, twoslashEnvHash } from "./TwoslashCache.js";
5
6
  import { DEFAULT_COMPILER_OPTIONS, mergeCompilerOptions, resolveTypeScriptConfig, resolveTypeScriptConfigSingle, resolveTypeScriptConfigSingleAsync } from "./TypeScriptConfig.js";
6
7
  import { VirtualPackage } from "./VirtualPackage.js";
7
8
 
8
- export { DEFAULT_COMPILER_OPTIONS, TsConfigParseError, TsEnvironment, TsEnvironmentError, TypeResolutionCompilerOptions, VirtualPackage, decodeCompilerOptions, isTypeDefinition, mergeCompilerOptions, mergeVfs, parseTsConfig, prefixVfs, resolveTypeScriptConfig, resolveTypeScriptConfigSingle, resolveTypeScriptConfigSingleAsync, toProgrammaticCompilerOptions };
9
+ export { DEFAULT_COMPILER_OPTIONS, TWOSLASH_CACHE_FORMAT, TsConfigParseError, TsEnvironment, TsEnvironmentError, TypeResolutionCompilerOptions, VirtualPackage, decodeCompilerOptions, decodeTwoslashCache, encodeTwoslashCache, isTypeDefinition, makeTwoslashCache, mergeCompilerOptions, mergeVfs, parseTsConfig, prefixVfs, resolveTypeScriptConfig, resolveTypeScriptConfigSingle, resolveTypeScriptConfigSingleAsync, toProgrammaticCompilerOptions, twoslashBlobKey, twoslashEntryKey, twoslashEnvHash };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tsdoctor/vfs",
3
- "version": "0.1.0",
3
+ "version": "0.2.0",
4
4
  "private": false,
5
5
  "description": "Virtual TypeScript projects for documentation tooling: the Vfs currency type, declaration-backed virtual packages, @typescript/vfs environments, and the compiler-option resolution that configures them.",
6
6
  "keywords": [
@@ -38,11 +38,15 @@
38
38
  },
39
39
  "peerDependencies": {
40
40
  "@effected/tsconfig-json": "^0.7.0",
41
+ "@shikijs/twoslash": "^4.4.3",
41
42
  "@typescript/vfs": "^1.6.4",
42
43
  "effect": "4.0.0-rc.109",
43
44
  "typescript": "^6.0.3"
44
45
  },
45
46
  "peerDependenciesMeta": {
47
+ "@shikijs/twoslash": {
48
+ "optional": true
49
+ },
46
50
  "@typescript/vfs": {
47
51
  "optional": true
48
52
  },