Open History to see the last commit
1// Syntax helpers for check-doc-snippets.mjs, with the cases that pin their
2// judgments. `selfTest()` runs on every check, so a change that makes a helper
3// miss a defect, or report a correct example, fails before any doc is read.
4import ts from 'typescript'
5
6const parse = (code, jsx) =>
7 ts.createSourceFile(
8 jsx ? `example.tsx` : `example.ts`,
9 code,
10 ts.ScriptTarget.Latest,
11 true,
12 jsx ? ts.ScriptKind.TSX : ts.ScriptKind.TS,
13 )
14
15const isJsx = (node) =>
16 ts.isJsxElement(node) ||
17 ts.isJsxSelfClosingElement(node) ||
18 ts.isJsxFragment(node)
19
20/**
21 * The tokens of an example, without what formatting changes, so a reformatted
22 * example keeps its baseline entry: spacing, comments, trailing commas,
23 * semicolons, the parentheses around multi-line JSX, and the parentheses
24 * around a single arrow parameter. Other commas and parentheses stay, because
25 * moving one changes what the code calls. The tree, not a token scan, finds JSX: a parenthesis in JSX
26 * text is text.
27 */
28export function fingerprint(code, jsx) {
29 const tokens = []
30 const visit = (node) => {
31 if (ts.isParenthesizedExpression(node) && isJsx(node.expression))
32 return visit(node.expression)
33 const children = node.getChildren()
34 if (children.length === 0) {
35 if (
36 node.kind === ts.SyntaxKind.SemicolonToken ||
37 node.kind === ts.SyntaxKind.EndOfFileToken
38 )
39 return
40 tokens.push(
41 ts.isStringLiteral(node)
42 ? JSON.stringify(node.text)
43 : // Formatting also reflows JSX text and the HTML in a template.
44 node.getText().replace(/\s+/g, ``),
45 )
46 return
47 }
48 const bareParameter =
49 ts.isArrowFunction(node) &&
50 node.parameters.length === 1 &&
51 ts.isIdentifier(node.parameters[0].name) &&
52 !node.parameters[0].type
53 children.forEach((child, index) => {
54 const parameterParen =
55 bareParameter &&
56 (child.kind === ts.SyntaxKind.OpenParenToken ||
57 child.kind === ts.SyntaxKind.CloseParenToken)
58 // A trailing comma ends its list; other commas separate values.
59 const trailingComma =
60 child.kind === ts.SyntaxKind.CommaToken && index === children.length - 1
61 if (!parameterParen && !trailingComma) visit(child)
62 })
63 }
64 visit(parse(code, jsx))
65 return tokens.join(` `)
66}
67
68/**
69 * Whether an example parses. Only syntax counts: a semantic error with a 1xxx
70 * code, such as a missing default export, is still an error to report.
71 */
72export function parses(code, jsx) {
73 const { diagnostics = [] } = ts.transpileModule(code, {
74 reportDiagnostics: true,
75 fileName: jsx ? `example.tsx` : `example.ts`,
76 compilerOptions: { jsx: ts.JsxEmit.Preserve },
77 })
78 return diagnostics.length === 0
79}
80
81/** The names an example imports from a TanStack package, in every form. */
82export function tanstackImports(code, jsx) {
83 const names = []
84 for (const statement of parse(code, jsx).statements) {
85 if (
86 !ts.isImportDeclaration(statement) ||
87 !ts.isStringLiteral(statement.moduleSpecifier) ||
88 !statement.moduleSpecifier.text.startsWith(`@tanstack/`)
89 )
90 continue
91 const clause = statement.importClause
92 if (clause?.name) names.push(clause.name.text)
93 const bindings = clause?.namedBindings
94 if (bindings && ts.isNamedImports(bindings))
95 names.push(...bindings.elements.map((element) => element.name.text))
96 }
97 return names
98}
99
100function editDistance(a, b) {
101 let previous = Array.from({ length: b.length + 1 }, (_, j) => j)
102 for (let i = 1; i <= a.length; i++) {
103 const row = [i]
104 for (let j = 1; j <= b.length; j++)
105 row[j] = Math.min(
106 previous[j] + 1,
107 row[j - 1] + 1,
108 previous[j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1),
109 )
110 previous = row
111 }
112 return previous[b.length]
113}
114
115/**
116 * The imported name that an unknown name misspells, if any. An app's own
117 * names often differ from an import only in case (`collection` and
118 * `Collection`) or by a suffix (`counter` and `count`); those are not typos.
119 */
120export function misspelling(name, imported) {
121 if (name.length < 5) return undefined
122 return imported.find(
123 (candidate) =>
124 candidate.toLowerCase() !== name.toLowerCase() &&
125 !candidate.startsWith(name) &&
126 !name.startsWith(candidate) &&
127 editDistance(name, candidate) <= (name.length >= 8 ? 2 : 1),
128 )
129}
130
131/**
132 * The TypeScript in a Svelte or Vue component example: its `<script>` block
133 * with `lang="ts"`, and the line it starts on, counted from the fence. The
134 * template is not TypeScript and is not checked. Undefined when the component
135 * has no TypeScript script.
136 */
137export function componentScript(code) {
138 const match =
139 /<script\b[^>]*\blang=["']ts["'][^>]*>\n?([\s\S]*?)<\/script>/.exec(code)
140 if (!match) return undefined
141 const start = match.index + match[0].indexOf(`>`) + 1
142 const offset = code.slice(0, start).split(`\n`).length - 1
143 return { code: match[1], offset: code[start] === `\n` ? offset + 1 : offset }
144}
145
146const frameworks = new Set([
147 `angular`,
148 `preact`,
149 `react`,
150 `solid`,
151 `svelte`,
152 `vue`,
153])
154
155/**
156 * The framework a doc or skill file documents, from its path segments: a
157 * `docs/framework/<name>/` directory or a `packages/<name>-db/` package. A
158 * name inside a word, such as `solid` in `consolidation`, does not count.
159 * Other files document React.
160 */
161export function frameworkOf(file) {
162 const segments = file.split(`/`)
163 const name = segments.flatMap((segment, index) =>
164 segments[index - 1] === `framework`
165 ? [segment]
166 : segment.endsWith(`-db`)
167 ? [segment.slice(0, -3)]
168 : [],
169 )
170 return name.find((candidate) => frameworks.has(candidate)) ?? `react`
171}
172
173// Relative ambient module declarations are invalid TypeScript. Only rewrite
174// unresolved app import specifiers, leaving source strings and real modules alone.
175export const externalName = (name) =>
176 name.startsWith(`.`) ? `snippet-app:${name}` : name
177
178export function externalImports(code, missingModules) {
179 const source = parse(code, true)
180 const replacements = []
181 for (const statement of source.statements) {
182 if (
183 !ts.isImportDeclaration(statement) &&
184 !ts.isExportDeclaration(statement)
185 )
186 continue
187 const specifier = statement.moduleSpecifier
188 if (!specifier || !ts.isStringLiteral(specifier)) continue
189 if (!missingModules.has(specifier.text)) continue
190 replacements.push({
191 start: specifier.getStart(source) + 1,
192 end: specifier.getEnd() - 1,
193 text: externalName(specifier.text),
194 })
195 }
196 for (const replacement of replacements.reverse()) {
197 code =
198 code.slice(0, replacement.start) +
199 replacement.text +
200 code.slice(replacement.end)
201 }
202 return code
203}
204
205export function selfTest() {
206 const appImport = `import { api } from './convex/_generated/api'`
207 const literal = `const text = "from './convex/_generated/api'"`
208 const rewritten = externalImports(
209 `${appImport}\n${literal}`,
210 new Set([`./convex/_generated/api`]),
211 )
212 if (
213 rewritten !==
214 `import { api } from 'snippet-app:./convex/_generated/api'\n${literal}`
215 )
216 throw new Error(`App import rewriting changed source outside an import`)
217 if (externalImports(appImport, new Set()) !== appImport)
218 throw new Error(`App import rewriting changed a resolved module`)
219
220 const imports = [
221 `include`,
222 `toArray`,
223 `count`,
224 `Collection`,
225 `QueryClient`,
226 `useLiveQuery`,
227 `eq`,
228 ]
229 const typos = {
230 inclde: `include`,
231 toArry: `toArray`,
232 useLiveQuey: `useLiveQuery`,
233 useLievQuery: `useLiveQuery`,
234 collection: undefined,
235 queryClient: undefined,
236 counter: undefined,
237 counts: undefined,
238 q: undefined,
239 Colection: `Collection`,
240 }
241 for (const [name, expected] of Object.entries(typos)) {
242 const found = misspelling(name, imports)
243 if (found !== expected)
244 throw new Error(
245 `self-test: misspelling(${name}) is ${found}, not ${expected}`,
246 )
247 }
248
249 for (const [code, expected] of [
250 [`import Db from '@tanstack/db'\nDb()`, true],
251 [`const query = useLiveQuery((q) => q.from({ todo })`, false],
252 [`q.from(...)`, false],
253 ])
254 if (parses(code, false) !== expected)
255 throw new Error(`self-test: parses(${code}) is not ${expected}`)
256
257 const component = componentScript(
258 `<!-- A.svelte -->\n<script lang="ts">\nconst a = 1\n</script>\n<p>{a}</p>`,
259 )
260 if (component?.code !== `const a = 1\n` || component.offset !== 2)
261 throw new Error(
262 `self-test: componentScript read ${JSON.stringify(component)}`,
263 )
264 if (componentScript(`<script>\nconst a = 1\n</script>`) !== undefined)
265 throw new Error(
266 `self-test: componentScript read a script without lang="ts"`,
267 )
268 if (componentScript(`<script setup lang="ts">x</script>`)?.code !== `x`)
269 throw new Error(
270 `self-test: componentScript missed <script setup lang="ts">`,
271 )
272
273 for (const [file, expected] of [
274 [`docs/framework/preact/overview.md`, `preact`],
275 [`docs/framework/react/overview.md`, `react`],
276 [`packages/solid-db/skills/solid-db/SKILL.md`, `solid`],
277 [
278 `docs/contributing/oracle-reviews/code-weight-multiset-consolidation.md`,
279 `react`,
280 ],
281 [`docs/guides/live-queries.md`, `react`],
282 ])
283 if (frameworkOf(file) !== expected)
284 throw new Error(`self-test: frameworkOf(${file}) is ${frameworkOf(file)}`)
285
286 const imported = tanstackImports(
287 [
288 `import Default, { inclde, type Colection } from '@tanstack/db'`,
289 `import type { QueryClient } from '@tanstack/query-core'`,
290 `import { notTanStack } from 'other'`,
291 ].join(`\n`),
292 )
293 if (imported.join() !== `Default,inclde,Colection,QueryClient`)
294 throw new Error(`self-test: tanstackImports found ${imported.join()}`)
295
296 // Pairs that formatting can produce must keep one fingerprint.
297 const same = [
298 [`f(a, b,);`, `f(a, b)`],
299 [`const o = { a: 1, b: [1, 2,], }`, `const o = { a: 1, b: [1, 2] }`],
300 [`list.map(x => x.id)`, `list.map((x) => x.id)`],
301 [`return (<p>:)</p>)`, `return <p>:)</p>`],
302 [
303 `return (\n <li key={t.id}>{t.text}</li>\n)`,
304 `return <li key={t.id}>{t.text}</li>`,
305 ],
306 [`q.from({ a })\n .join(x) // why`, `q.from({ a }).join(x)`],
307 ]
308 for (const [a, b] of same)
309 if (fingerprint(a, true) !== fingerprint(b, true))
310 throw new Error(`self-test: fingerprints differ for ${a} and ${b}`)
311
312 // Edits that change what the code does must change the fingerprint.
313 const different = [
314 [`.where(eq(a, b))`, `.where(eq(a), b)`],
315 [`f(a, -b)`, `f(a - b)`],
316 [`eq(a, [b])`, `eq(a[b])`],
317 [`f((a, b) => a)`, `f(a, b => a)`],
318 [`eq(a.id, b.id)`, `eq(a.id, b.userId)`],
319 [`'a b'`, `'ab'`],
320 ]
321 for (const [a, b] of different)
322 if (fingerprint(a, true) === fingerprint(b, true))
323 throw new Error(`self-test: fingerprints match for ${a} and ${b}`)
324}