Open History to see the last commit
1// Typechecks the TypeScript code examples in the guides and the shipped agent
2// skills against the workspace packages' source.
3//
4// Examples are fragments: they use collections and components they never
5// declare. The check declares each unknown name as `any`, so it reports what
6// an example gets wrong about the TanStack API rather than what it leaves
7// out. An unknown name that a TanStack package exports is reported instead:
8// the example uses it without importing it.
9//
10// node scripts/check-doc-snippets.mjs [--verbose] [--update-baseline]
11//
12// An example that does not parse fails too. Mark a fence ```ts nocheck to
13// skip an example that is not meant to compile.
14//
15// `doc-snippets-baseline.json` lists examples that already failed when the
16// check began, by file and a hash of their code. Editing one changes its
17// hash, so an edited example must pass; reformatting one keeps it. An example that passes must leave the
18// baseline: run with --update-baseline after fixing one.
19//
20// Debugging: SNIPPET_ONLY=<file>:<line> checks one example, and
21// SNIPPET_DUMP=<file>:<line> prints the source the check compiles for it.
22import { createHash } from 'node:crypto'
23import { existsSync, readFileSync, readdirSync, writeFileSync } from 'node:fs'
24import { join, relative } from 'node:path'
25import { fileURLToPath } from 'node:url'
26import prettier from 'prettier'
27import ts from 'typescript'
28import {
29 componentScript,
30 externalImports,
31 externalName,
32 fingerprint,
33 frameworkOf,
34 misspelling,
35 parses,
36 selfTest,
37 tanstackImports,
38} from './doc-snippet-syntax.mjs'
39
40const root = fileURLToPath(new URL(`..`, import.meta.url))
41const verbose = process.argv.includes(`--verbose`)
42const updateBaseline = process.argv.includes(`--update-baseline`)
43const baselinePath = join(root, `scripts`, `doc-snippets-baseline.json`)
44const baseline = existsSync(baselinePath)
45 ? JSON.parse(readFileSync(baselinePath, `utf8`))
46 : {}
47const hashOf = (code) =>
48 createHash(`sha256`).update(code).digest(`hex`).slice(0, 16)
49
50function walk(dir, keep) {
51 if (!existsSync(dir)) return []
52 return readdirSync(dir, { withFileTypes: true }).flatMap((entry) => {
53 const path = join(dir, entry.name)
54 if (entry.isDirectory())
55 return entry.name === `node_modules` || entry.name === `reference`
56 ? []
57 : walk(path, keep)
58 return keep(path) ? [path] : []
59 })
60}
61
62const markdown = [
63 ...walk(join(root, `docs`), (path) => path.endsWith(`.md`)),
64 ...readdirSync(join(root, `packages`)).flatMap((pkg) =>
65 walk(join(root, `packages`, pkg, `skills`), (path) => path.endsWith(`.md`)),
66 ),
67]
68
69// Map each workspace package and its subpath exports to source. CI does not
70// build the packages, so an export that falls through to dist/ is missing.
71const paths = {}
72const declaresTypes = (target) =>
73 typeof target === `object` &&
74 target !== null &&
75 Object.entries(target).some(
76 ([condition, value]) => condition === `types` || declaresTypes(value),
77 )
78for (const pkg of readdirSync(join(root, `packages`))) {
79 const manifest = join(root, `packages`, pkg, `package.json`)
80 if (!existsSync(manifest)) continue
81 const {
82 name,
83 private: unpublished,
84 exports = {},
85 } = JSON.parse(readFileSync(manifest, `utf8`))
86 // Examples document published packages only.
87 if (unpublished) continue
88 for (const [subpath, target] of Object.entries(exports)) {
89 // A typed snippet can import only an export that declares types. Untyped
90 // exports, such as package.json, a WASM file, or a worker script, are
91 // runtime assets with no source to map.
92 if (!declaresTypes(target)) continue
93 // `.` is src/index; `./x` is src/x.ts or src/x/index.ts.
94 const stem = subpath === `.` ? `index` : subpath.slice(2)
95 const entry = [`${stem}.ts`, `${stem}.tsx`, `${stem}/index.ts`]
96 .map((file) => join(`packages`, pkg, `src`, file))
97 .find((file) => existsSync(join(root, file)))
98 if (!entry) throw new Error(`No source for ${name} export ${subpath}`)
99 paths[subpath === `.` ? name : `${name}/${stem}`] = [entry]
100 }
101}
102
103// A fence closes with as many backticks as it opened with, so a ````ts
104// example can hold a ``` block.
105const fence =
106 /^(`{3,})(ts|tsx|typescript|svelte|vue)([^\n]*)\n([\s\S]*?)^\1[ \t]*$/gm
107const snippets = []
108for (const file of markdown) {
109 const text = readFileSync(file, `utf8`)
110 for (const match of text.matchAll(fence)) {
111 if (match[3].includes(`nocheck`)) continue
112 let line = text.slice(0, match.index).split(`\n`).length
113 let code = match[4]
114 // A component example: check its TypeScript script, not its template.
115 if (match[2] === `svelte` || match[2] === `vue`) {
116 const script = componentScript(code)
117 if (!script) continue
118 code = script.code
119 line += script.offset
120 }
121 snippets.push({
122 file: relative(root, file),
123 line,
124 code,
125 name: join(
126 root,
127 `.snippet-check`,
128 `${snippets.length}.${/<\/|<[A-Z][A-Za-z]*[ />]/.test(code) ? `tsx` : `ts`}`,
129 ),
130 })
131 }
132}
133
134selfTest()
135for (const snippet of snippets) {
136 const jsx = snippet.name.endsWith(`.tsx`)
137 snippet.hash = hashOf(fingerprint(snippet.code, jsx))
138 snippet.imports = tanstackImports(snippet.code, jsx)
139}
140
141if (process.env.SNIPPET_ONLY) {
142 const keep = snippets.filter(
143 (s) => `${s.file}:${s.line}` === process.env.SNIPPET_ONLY,
144 )
145 snippets.length = 0
146 snippets.push(...keep)
147}
148
149const options = {
150 strict: true,
151 noUnusedLocals: false,
152 noUncheckedIndexedAccess: false,
153 allowUnreachableCode: true,
154 skipLibCheck: true,
155 noEmit: true,
156 jsx: ts.JsxEmit.ReactJSX,
157 target: ts.ScriptTarget.ES2022,
158 module: ts.ModuleKind.ESNext,
159 moduleResolution: ts.ModuleResolutionKind.Bundler,
160 lib: [`lib.es2022.d.ts`, `lib.dom.d.ts`, `lib.dom.iterable.d.ts`],
161 baseUrl: root,
162 paths,
163}
164
165// Modules an example imports but this repo cannot resolve (app files, other
166// frameworks) are declared `any`, one by one. A wildcard would also erase
167// third-party types that the packages themselves use.
168const ambient = join(root, `.snippet-check`, `ambient.d.ts`)
169const missingModules = new Set()
170const ambientSource = () =>
171 [...missingModules]
172 .map((name) => `declare module ${JSON.stringify(externalName(name))}\n`)
173 .join(``) || `export {}\n`
174
175function check(sources) {
176 const host = ts.createCompilerHost(options)
177 const read = host.readFile
178 host.readFile = (path) => sources.get(path) ?? read(path)
179 const exists = host.fileExists
180 host.fileExists = (path) => sources.has(path) || exists(path)
181 // pnpm keeps an adapter's provider types beside that adapter. A guide's
182 // imports must resolve there before an absent root dependency becomes `any`.
183 host.resolveModuleNames = (names, containingFile) => {
184 const snippet = snippets.find((entry) => entry.name === containingFile)
185 const collection = snippet?.file.match(
186 /^docs\/collections\/(.+)-collection\.md$/,
187 )?.[1]
188 const owner = collection
189 ? join(root, `packages`, `${collection}-db-collection`, `src`, `index.ts`)
190 : undefined
191 return names.map(
192 (name) =>
193 ts.resolveModuleName(name, containingFile, options, host)
194 .resolvedModule ??
195 (owner && !name.startsWith(`.`)
196 ? ts.resolveModuleName(name, owner, options, host).resolvedModule
197 : undefined),
198 )
199 }
200 const program = ts.createProgram([...sources.keys()], options, host)
201 return { program, diagnostics: ts.getPreEmitDiagnostics(program) }
202}
203
204// Names the TanStack packages export, to tell "not imported" from "app code".
205const exported = new Map()
206{
207 const probe = join(root, `.snippet-check`, `exports.ts`)
208 const packages = Object.keys(paths).filter((name) =>
209 name.startsWith(`@tanstack/`),
210 )
211 const imports = packages
212 .map((name, i) => `import * as m${i} from '${name}'`)
213 .join(`\n`)
214 const { program } = check(new Map([[probe, imports + `\n`]]))
215 const checker = program.getTypeChecker()
216 program.getSourceFile(probe).statements.forEach((statement, i) => {
217 const symbol = checker.getSymbolAtLocation(statement.moduleSpecifier)
218 if (!symbol) return
219 for (const item of checker.getExportsOfModule(symbol)) {
220 const owners = exported.get(item.name) ?? []
221 owners.push(packages[i])
222 exported.set(item.name, owners)
223 }
224 })
225}
226
227// The framework a file documents, for names several adapters export.
228function packageFor(name, file) {
229 const owners = exported.get(name)
230 if (owners.length === 1) return owners[0]
231 return (
232 owners.find((owner) => owner === `@tanstack/db`) ??
233 owners.find((owner) => owner === `@tanstack/${frameworkOf(file)}-db`) ??
234 owners[0]
235 )
236}
237
238const importsTanStack = (code) => /from ['"]@tanstack\//.test(code)
239
240function sourceOf(snippet, declared, autoImported) {
241 const byPackage = new Map()
242 for (const name of autoImported) {
243 const pkg = packageFor(name, snippet.file)
244 byPackage.set(pkg, [...(byPackage.get(pkg) ?? []), name])
245 }
246 return (
247 [...byPackage]
248 .map(([pkg, names]) => `import { ${names.join(`, `)} } from '${pkg}'\n`)
249 .join(``) +
250 `import type { Collection as SnippetCollection } from '@tanstack/db'\n` +
251 [...declared]
252 .map(
253 (name) =>
254 `declare const ${name}: ${/collection$/i.test(name) ? `SnippetCollection<Record<string, any>, string | number>` : `any`}\ntype ${name} = any\n`,
255 )
256 .join(``) +
257 externalImports(snippet.code, missingModules) +
258 `\nexport {}\n`
259 )
260}
261
262const declared = snippets.map(() => new Set())
263const unimported = snippets.map(() => new Set())
264const autoImported = snippets.map(() => new Set())
265const misspelled = snippets.map(() => new Map())
266const unknownName = new Set([2304, 2552, 18004, 2749, 2693])
267// Docs often show alternatives side by side in one block, and leave
268// callback parameters unannotated where an app would annotate them.
269const ignored = new Set([2451, 2300, 2393, 7005, 7006, 7019, 7031, 7034, 7053])
270// An unresolvable dependency is declared as an untyped module, whose names
271// cannot be used as types.
272ignored.add(2709)
273let diagnostics = []
274// Declare unknown names until a pass adds none.
275for (let pass = 0; pass < 6; pass++) {
276 const sources = new Map([[ambient, ambientSource()]])
277 snippets.forEach((snippet, i) =>
278 sources.set(snippet.name, sourceOf(snippet, declared[i], autoImported[i])),
279 )
280 diagnostics = check(sources).diagnostics
281 let added = 0
282 for (const diagnostic of diagnostics) {
283 if (
284 diagnostic.code === 2307 &&
285 snippets.some((s) => s.name === diagnostic.file?.fileName)
286 ) {
287 const name = ts
288 .flattenDiagnosticMessageText(diagnostic.messageText, ``)
289 .match(/'([^']+)'/)?.[1]
290 if (name && !missingModules.has(name)) {
291 missingModules.add(name)
292 added++
293 }
294 continue
295 }
296 if (!unknownName.has(diagnostic.code)) continue
297 const index = snippets.findIndex(
298 (s) => s.name === diagnostic.file?.fileName,
299 )
300 if (index < 0) continue
301 const name = ts
302 .flattenDiagnosticMessageText(diagnostic.messageText, ``)
303 .match(/'([^']+)'/)?.[1]
304 if (!name) continue
305 // A near miss of a TanStack name the example imports is a typo, not app
306 // code. TypeScript stops suggesting spellings after a few, so compare here.
307 const suggestion = misspelling(name, snippets[index].imports)
308 if (suggestion !== undefined) misspelled[index].set(name, suggestion)
309 if (exported.has(name)) {
310 if (importsTanStack(snippets[index].code)) unimported[index].add(name)
311 else if (!autoImported[index].has(name)) {
312 autoImported[index].add(name)
313 added++
314 }
315 } else if (!declared[index].has(name)) {
316 declared[index].add(name)
317 added++
318 }
319 }
320 if (added === 0) break
321}
322
323if (process.env.SNIPPET_DUMP) {
324 const i = snippets.findIndex(
325 (s) => `${s.file}:${s.line}` === process.env.SNIPPET_DUMP,
326 )
327 console.log(sourceOf(snippets[i], declared[i], autoImported[i]))
328}
329const failures = []
330let unparsable = 0
331snippets.forEach((snippet, i) => {
332 const ownDiagnostics = diagnostics.filter(
333 (d) => d.file?.fileName === snippet.name,
334 )
335 // An example that does not parse cannot be checked. Pseudo-code, such as
336 // `...` placeholders, is marked nocheck.
337 if (!parses(snippet.code, snippet.name.endsWith(`.tsx`))) {
338 unparsable++
339 failures.push({
340 snippet,
341 text: `${snippet.file}:${snippet.line}\n does not parse; mark the fence nocheck if it is pseudo-code`,
342 })
343 return
344 }
345 const offset =
346 1 +
347 declared[i].size * 2 +
348 new Set([...autoImported[i]].map((n) => packageFor(n, snippet.file))).size
349 const messages = ownDiagnostics
350 .filter((d) => !unknownName.has(d.code) && !ignored.has(d.code))
351 .map((d) => {
352 const { line } = d.file.getLineAndCharacterOfPosition(d.start ?? 0)
353 return ` line ${snippet.line + line - offset}: TS${d.code} ${ts.flattenDiagnosticMessageText(d.messageText, ` `)}`
354 })
355 for (const name of unimported[i])
356 messages.push(` uses \`${name}\` without importing it`)
357 for (const [name, suggestion] of misspelled[i])
358 messages.push(` uses \`${name}\`; did you mean \`${suggestion}\`?`)
359 if (messages.length)
360 failures.push({
361 snippet,
362 text: `${snippet.file}:${snippet.line}\n${messages.join(`\n`)}`,
363 })
364})
365
366const known = (snippet) =>
367 baseline[snippet.file]?.includes(snippet.hash) ?? false
368const newFailures = failures.filter(({ snippet }) => !known(snippet))
369const failing = new Set(
370 failures.map(({ snippet }) => `${snippet.file}#${snippet.hash}`),
371)
372const stale = Object.entries(baseline).flatMap(([file, hashes]) =>
373 hashes
374 .filter((hash) => !failing.has(`${file}#${hash}`))
375 .map((hash) => `${file}#${hash}`),
376)
377
378if (updateBaseline && !process.env.SNIPPET_ONLY) {
379 const next = {}
380 for (const { snippet } of failures)
381 (next[snippet.file] ??= []).push(snippet.hash)
382 for (const hashes of Object.values(next)) hashes.sort()
383 const sorted = Object.fromEntries(
384 Object.entries(next).sort(([a], [b]) => a.localeCompare(b)),
385 )
386 writeFileSync(
387 baselinePath,
388 await prettier.format(JSON.stringify(sorted), {
389 ...(await prettier.resolveConfig(baselinePath)),
390 filepath: baselinePath,
391 }),
392 )
393 console.log(`Baseline: ${failures.length} known failing examples`)
394} else {
395 const shown = verbose ? failures : newFailures
396 if (shown.length) console.log(shown.map(({ text }) => text).join(`\n\n`))
397 if (stale.length && !process.env.SNIPPET_ONLY)
398 console.log(
399 `\n${stale.length} baseline entries now pass or no longer exist; run with --update-baseline:\n${stale.join(`\n`)}`,
400 )
401 console.log(
402 `\n${snippets.length} examples in ${markdown.length} files: ${newFailures.length} new failures, ${failures.length - newFailures.length} known, ${unparsable} of them do not parse`,
403 )
404 process.exitCode =
405 newFailures.length || (stale.length && !process.env.SNIPPET_ONLY) ? 1 : 0
406}