Skip to content
Source
Sign inSign up
TanStack/db
Open History to see the last commit

check-doc-snippets.mjs

402 lines14.7 KB

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 })
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 ),
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 { name, exports = {} } = JSON.parse(readFileSync(manifest, `utf8`))
82 // Publication can be deferred while a package's documented API still needs
83 // source types. Keep private workspace packages in the same export mapping.
84 for (const [subpath, target] of Object.entries(exports)) {
85 // A typed snippet can import only an export that declares types. Untyped
86 // exports, such as package.json, a WASM file, or a worker script, are
87 // runtime assets with no source to map.
88 if (!declaresTypes(target)) continue
89 // `.` is src/index; `./x` is src/x.ts or src/x/index.ts.
90 const stem = subpath === `.` ? `index` : subpath.slice(2)
91 const entry = [`${stem}.ts`, `${stem}.tsx`, `${stem}/index.ts`]
92 .map((file) => join(`packages`, pkg, `src`, file))
93 .find((file) => existsSync(join(root, file)))
94 if (!entry) throw new Error(`No source for ${name} export ${subpath}`)
95 paths[subpath === `.` ? name : `${name}/${stem}`] = [entry]
96 }
98​
99// A fence closes with as many backticks as it opened with, so a ````ts
100// example can hold a ``` block.
101const fence =
102 /^(`{3,})(ts|tsx|typescript|svelte|vue)([^\n]*)\n([\s\S]*?)^\1[ \t]*$/gm
103const snippets = []
104for (const file of markdown) {
105 const text = readFileSync(file, `utf8`)
106 for (const match of text.matchAll(fence)) {
107 if (match[3].includes(`nocheck`)) continue
108 let line = text.slice(0, match.index).split(`\n`).length
109 let code = match[4]
110 // A component example: check its TypeScript script, not its template.
111 if (match[2] === `svelte` || match[2] === `vue`) {
112 const script = componentScript(code)
113 if (!script) continue
114 code = script.code
115 line += script.offset
116 }
117 snippets.push({
118 file: relative(root, file),
119 line,
120 code,
121 name: join(
122 root,
123 `.snippet-check`,
124 `${snippets.length}.${/<\/|<[A-Z][A-Za-z]*[ />]/.test(code) ? `tsx` : `ts`}`,
125 ),
126 })
127 }
129​
130selfTest()
131for (const snippet of snippets) {
132 const jsx = snippet.name.endsWith(`.tsx`)
133 snippet.hash = hashOf(fingerprint(snippet.code, jsx))
134 snippet.imports = tanstackImports(snippet.code, jsx)
136​
137if (process.env.SNIPPET_ONLY) {
138 const keep = snippets.filter(
139 (s) => `${s.file}:${s.line}` === process.env.SNIPPET_ONLY,
140 )
141 snippets.length = 0
142 snippets.push(...keep)
144​
145const options = {
146 strict: true,
147 noUnusedLocals: false,
148 noUncheckedIndexedAccess: false,
149 allowUnreachableCode: true,
150 skipLibCheck: true,
151 noEmit: true,
152 jsx: ts.JsxEmit.ReactJSX,
153 target: ts.ScriptTarget.ES2022,
154 module: ts.ModuleKind.ESNext,
155 moduleResolution: ts.ModuleResolutionKind.Bundler,
156 lib: [`lib.es2022.d.ts`, `lib.dom.d.ts`, `lib.dom.iterable.d.ts`],
157 baseUrl: root,
158 paths,
160​
161// Modules an example imports but this repo cannot resolve (app files, other
162// frameworks) are declared `any`, one by one. A wildcard would also erase
163// third-party types that the packages themselves use.
164const ambient = join(root, `.snippet-check`, `ambient.d.ts`)
165const missingModules = new Set()
166const ambientSource = () =>
167 [...missingModules]
168 .map((name) => `declare module ${JSON.stringify(externalName(name))}\n`)
169 .join(``) || `export {}\n`
170​
171function check(sources) {
172 const host = ts.createCompilerHost(options)
173 const read = host.readFile
174 host.readFile = (path) => sources.get(path) ?? read(path)
175 const exists = host.fileExists
176 host.fileExists = (path) => sources.has(path) || exists(path)
177 // pnpm keeps an adapter's provider types beside that adapter. A guide's
178 // imports must resolve there before an absent root dependency becomes `any`.
179 host.resolveModuleNames = (names, containingFile) => {
180 const snippet = snippets.find((entry) => entry.name === containingFile)
181 const collection = snippet?.file.match(
182 /^docs\/collections\/(.+)-collection\.md$/,
183 )?.[1]
184 const owner = collection
185 ? join(root, `packages`, `${collection}-db-collection`, `src`, `index.ts`)
186 : undefined
187 return names.map(
188 (name) =>
189 ts.resolveModuleName(name, containingFile, options, host)
190 .resolvedModule ??
191 (owner && !name.startsWith(`.`)
192 ? ts.resolveModuleName(name, owner, options, host).resolvedModule
193 : undefined),
194 )
195 }
196 const program = ts.createProgram([...sources.keys()], options, host)
197 return { program, diagnostics: ts.getPreEmitDiagnostics(program) }
199​
200// Names the TanStack packages export, to tell "not imported" from "app code".
201const exported = new Map()
203 const probe = join(root, `.snippet-check`, `exports.ts`)
204 const packages = Object.keys(paths).filter((name) =>
205 name.startsWith(`@tanstack/`),
206 )
207 const imports = packages
208 .map((name, i) => `import * as m${i} from '${name}'`)
209 .join(`\n`)
210 const { program } = check(new Map([[probe, imports + `\n`]]))
211 const checker = program.getTypeChecker()
212 program.getSourceFile(probe).statements.forEach((statement, i) => {
213 const symbol = checker.getSymbolAtLocation(statement.moduleSpecifier)
214 if (!symbol) return
215 for (const item of checker.getExportsOfModule(symbol)) {
216 const owners = exported.get(item.name) ?? []
217 owners.push(packages[i])
218 exported.set(item.name, owners)
219 }
220 })
222​
223// The framework a file documents, for names several adapters export.
224function packageFor(name, file) {
225 const owners = exported.get(name)
226 if (owners.length === 1) return owners[0]
227 return (
228 owners.find((owner) => owner === `@tanstack/db`) ??
229 owners.find((owner) => owner === `@tanstack/${frameworkOf(file)}-db`) ??
230 owners[0]
231 )
233​
234const importsTanStack = (code) => /from ['"]@tanstack\//.test(code)
235​
236function sourceOf(snippet, declared, autoImported) {
237 const byPackage = new Map()
238 for (const name of autoImported) {
239 const pkg = packageFor(name, snippet.file)
240 byPackage.set(pkg, [...(byPackage.get(pkg) ?? []), name])
241 }
242 return (
243 [...byPackage]
244 .map(([pkg, names]) => `import { ${names.join(`, `)} } from '${pkg}'\n`)
245 .join(``) +
246 `import type { Collection as SnippetCollection } from '@tanstack/db'\n` +
247 [...declared]
248 .map(
249 (name) =>
250 `declare const ${name}: ${/collection$/i.test(name) ? `SnippetCollection<Record<string, any>, string | number>` : `any`}\ntype ${name} = any\n`,
251 )
252 .join(``) +
253 externalImports(snippet.code, missingModules) +
254 `\nexport {}\n`
255 )
257​
258const declared = snippets.map(() => new Set())
259const unimported = snippets.map(() => new Set())
260const autoImported = snippets.map(() => new Set())
261const misspelled = snippets.map(() => new Map())
262const unknownName = new Set([2304, 2552, 18004, 2749, 2693])
263// Docs often show alternatives side by side in one block, and leave
264// callback parameters unannotated where an app would annotate them.
265const ignored = new Set([2451, 2300, 2393, 7005, 7006, 7019, 7031, 7034, 7053])
266// An unresolvable dependency is declared as an untyped module, whose names
267// cannot be used as types.
268ignored.add(2709)
269let diagnostics = []
270// Declare unknown names until a pass adds none.
271for (let pass = 0; pass < 6; pass++) {
272 const sources = new Map([[ambient, ambientSource()]])
273 snippets.forEach((snippet, i) =>
274 sources.set(snippet.name, sourceOf(snippet, declared[i], autoImported[i])),
275 )
276 diagnostics = check(sources).diagnostics
277 let added = 0
278 for (const diagnostic of diagnostics) {
279 if (
280 diagnostic.code === 2307 &&
281 snippets.some((s) => s.name === diagnostic.file?.fileName)
282 ) {
283 const name = ts
284 .flattenDiagnosticMessageText(diagnostic.messageText, ``)
285 .match(/'([^']+)'/)?.[1]
286 if (name && !missingModules.has(name)) {
287 missingModules.add(name)
288 added++
289 }
290 continue
291 }
292 if (!unknownName.has(diagnostic.code)) continue
293 const index = snippets.findIndex(
294 (s) => s.name === diagnostic.file?.fileName,
295 )
296 if (index < 0) continue
297 const name = ts
298 .flattenDiagnosticMessageText(diagnostic.messageText, ``)
299 .match(/'([^']+)'/)?.[1]
300 if (!name) continue
301 // A near miss of a TanStack name the example imports is a typo, not app
302 // code. TypeScript stops suggesting spellings after a few, so compare here.
303 const suggestion = misspelling(name, snippets[index].imports)
304 if (suggestion !== undefined) misspelled[index].set(name, suggestion)
305 if (exported.has(name)) {
306 if (importsTanStack(snippets[index].code)) unimported[index].add(name)
307 else if (!autoImported[index].has(name)) {
308 autoImported[index].add(name)
309 added++
310 }
311 } else if (!declared[index].has(name)) {
312 declared[index].add(name)
313 added++
314 }
315 }
316 if (added === 0) break
318​
319if (process.env.SNIPPET_DUMP) {
320 const i = snippets.findIndex(
321 (s) => `${s.file}:${s.line}` === process.env.SNIPPET_DUMP,
322 )
323 console.log(sourceOf(snippets[i], declared[i], autoImported[i]))
325const failures = []
326let unparsable = 0
327snippets.forEach((snippet, i) => {
328 const ownDiagnostics = diagnostics.filter(
329 (d) => d.file?.fileName === snippet.name,
330 )
331 // An example that does not parse cannot be checked. Pseudo-code, such as
332 // `...` placeholders, is marked nocheck.
333 if (!parses(snippet.code, snippet.name.endsWith(`.tsx`))) {
334 unparsable++
335 failures.push({
336 snippet,
337 text: `${snippet.file}:${snippet.line}\n does not parse; mark the fence nocheck if it is pseudo-code`,
338 })
339 return
340 }
341 const offset =
342 1 +
343 declared[i].size * 2 +
344 new Set([...autoImported[i]].map((n) => packageFor(n, snippet.file))).size
345 const messages = ownDiagnostics
346 .filter((d) => !unknownName.has(d.code) && !ignored.has(d.code))
347 .map((d) => {
348 const { line } = d.file.getLineAndCharacterOfPosition(d.start ?? 0)
349 return ` line ${snippet.line + line - offset}: TS${d.code} ${ts.flattenDiagnosticMessageText(d.messageText, ` `)}`
350 })
351 for (const name of unimported[i])
352 messages.push(` uses \`${name}\` without importing it`)
353 for (const [name, suggestion] of misspelled[i])
354 messages.push(` uses \`${name}\`; did you mean \`${suggestion}\`?`)
355 if (messages.length)
356 failures.push({
357 snippet,
358 text: `${snippet.file}:${snippet.line}\n${messages.join(`\n`)}`,
359 })
360})
361​
362const known = (snippet) =>
363 baseline[snippet.file]?.includes(snippet.hash) ?? false
364const newFailures = failures.filter(({ snippet }) => !known(snippet))
365const failing = new Set(
366 failures.map(({ snippet }) => `${snippet.file}#${snippet.hash}`),
368const stale = Object.entries(baseline).flatMap(([file, hashes]) =>
369 hashes
370 .filter((hash) => !failing.has(`${file}#${hash}`))
371 .map((hash) => `${file}#${hash}`),
373​
374if (updateBaseline && !process.env.SNIPPET_ONLY) {
375 const next = {}
376 for (const { snippet } of failures)
377 (next[snippet.file] ??= []).push(snippet.hash)
378 for (const hashes of Object.values(next)) hashes.sort()
379 const sorted = Object.fromEntries(
380 Object.entries(next).sort(([a], [b]) => a.localeCompare(b)),
381 )
382 writeFileSync(
383 baselinePath,
384 await prettier.format(JSON.stringify(sorted), {
385 ...(await prettier.resolveConfig(baselinePath)),
386 filepath: baselinePath,
387 }),
388 )
389 console.log(`Baseline: ${failures.length} known failing examples`)
390} else {
391 const shown = verbose ? failures : newFailures
392 if (shown.length) console.log(shown.map(({ text }) => text).join(`\n\n`))
393 if (stale.length && !process.env.SNIPPET_ONLY)
394 console.log(
395 `\n${stale.length} baseline entries now pass or no longer exist; run with --update-baseline:\n${stale.join(`\n`)}`,
396 )
397 console.log(
398 `\n${snippets.length} examples in ${markdown.length} files: ${newFailures.length} new failures, ${failures.length - newFailures.length} known, ${unparsable} of them do not parse`,
399 )
400 process.exitCode =
401 newFailures.length || (stale.length && !process.env.SNIPPET_ONLY) ? 1 : 0