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

generate-docs.ts

1,083 lines36.7 KB

1import { mkdir, readFile, readdir, rm, writeFile } from 'node:fs/promises'
2import { createRequire } from 'node:module'
3import { dirname, resolve } from 'node:path'
4import { fileURLToPath } from 'node:url'
5import ts from 'typescript'
6​
7const __dirname = fileURLToPath(new URL('.', import.meta.url))
8const require = createRequire(import.meta.url)
9const typedocConfigPackageJson =
10 require.resolve('@tanstack/typedoc-config/package.json')
11const typedocConfigRequire = createRequire(typedocConfigPackageJson)
12const TypeDoc = await import(typedocConfigRequire.resolve('typedoc'))
13​
14type PackageReferenceDocsConfig = {
15 entryPoints: Array<string>
16 tsconfig: string
17 outputDir: string
18 exclude?: Array<string>
19 excludeExternals?: boolean
20 simplifyLitQueriesControllerTypes?: boolean
21 trimGeneratedMarkdown?: boolean
22 // Maps a generated page's path (relative to outputDir, no extension) to the flat
23 // `docs/framework/<framework>/reference/<name>.md` URLs it replaced, so old links/bookmarks redirect
24 // instead of falling through to the framework docs index. See https://github.com/TanStack/query/issues/11371
25 redirectFrom?: Record<string, Array<string>>
27​
28type TypeDocReflectionWithSignatures = {
29 name: string
30 children?: Array<TypeDocReflectionWithSignatures>
31 signatures?: Array<{
32 typeParameters?: Array<{
33 name: string
34 default?: unknown
35 }>
36 }>
38​
39function simplifyLitQueriesControllerTypes(
40 project: TypeDocReflectionWithSignatures,
41) {
42 const stack: Array<TypeDocReflectionWithSignatures> = [project]
43​
44 for (const reflection of stack) {
45 stack.push(...(reflection.children ?? []))
46​
47 if (reflection.name !== 'createQueriesController') {
48 continue
49 }
50​
51 for (const signature of reflection.signatures ?? []) {
52 const combinedResult = signature.typeParameters?.find(
53 (typeParameter) => typeParameter.name === 'TCombinedResult',
54 )
55​
56 if (!combinedResult?.default) {
57 continue
58 }
59​
60 const queryOptionsType = TypeDoc.ReferenceType.createBrokenReference(
61 'TQueryOptions',
62 project,
63 undefined,
64 )
65 queryOptionsType.refersToTypeParameter = true
66​
67 // CreateQueriesResults is internal; render it as plain text, not a link.
68 const queriesResultsType = TypeDoc.ReferenceType.createBrokenReference(
69 'CreateQueriesResults',
70 project,
71 undefined,
72 )
73 queriesResultsType.typeArguments = [queryOptionsType]
74​
75 combinedResult.default = queriesResultsType
76 }
77 }
79​
80async function trimTrailingWhitespaceInMarkdown(outputDir: string) {
81 const entries = await readdir(outputDir, { withFileTypes: true })
82​
83 await Promise.all(
84 entries.map(async (entry) => {
85 const path = resolve(outputDir, entry.name)
86​
87 if (entry.isDirectory()) {
88 await trimTrailingWhitespaceInMarkdown(path)
89 return
90 }
91​
92 if (!entry.isFile() || !path.endsWith('.md')) {
93 return
94 }
95​
96 const markdown = await readFile(path, 'utf8')
97 const trimmed = markdown.replace(/[ \t]+$/gm, '')
98​
99 if (trimmed !== markdown) {
100 await writeFile(path, trimmed)
101 }
102 }),
103 )
105​
106async function addRedirectFromToFileFrontmatter(
107 filePath: string,
108 fromPaths: Array<string>,
109) {
110 const markdown = await readFile(filePath, 'utf8')
111​
112 const frontmatterMatch = markdown.match(/^---\n([\s\S]*?)\n---\n/)
113 if (!frontmatterMatch) {
114 throw new Error(`Expected frontmatter in ${filePath}`)
115 }
116​
117 const redirectLines = fromPaths
118 .map((fromPath) => ` - ${fromPath}`)
119 .join('\n')
120 const updatedFrontmatter = `---\n${frontmatterMatch[1]}\nredirect_from:\n${redirectLines}\n---\n`
121​
122 await writeFile(
123 filePath,
124 updatedFrontmatter + markdown.slice(frontmatterMatch[0].length),
125 )
127​
128async function addRedirectFromToFrontmatter(
129 outputDir: string,
130 redirectFrom: Record<string, Array<string>>,
131) {
132 for (const [pagePath, fromPaths] of Object.entries(redirectFrom)) {
133 await addRedirectFromToFileFrontmatter(
134 resolve(outputDir, `${pagePath}.md`),
135 fromPaths,
136 )
137 }
139​
140async function generatePackageReferenceDocs(pkg: PackageReferenceDocsConfig) {
141 const outputDir = pkg.outputDir
142 await rm(outputDir, { recursive: true, force: true })
143 await mkdir(outputDir, { recursive: true })
144​
145 const app = await TypeDoc.Application.bootstrapWithPlugins({
146 plugin: [
147 'typedoc-plugin-markdown',
148 'typedoc-plugin-frontmatter',
149 '@tanstack/typedoc-config/typedoc-custom-settings',
150 ],
151 hideGenerator: true,
152 readme: 'none',
153 entryFileName: 'index',
154 hideBreadcrumbs: true,
155 hidePageHeader: true,
156 hidePageTitle: true,
157 useCodeBlocks: true,
158 // `parametersFormat` and `typeDeclarationFormat` are deliberately left as lists: the first
159 // puts the huge conditional types of `useQueries` into a single cell and drops `@default`
160 // blocks, and the second collapses `@example` code blocks onto one line, which swallows the
161 // following statement into a `//` comment.
162 interfacePropertiesFormat: 'table',
163 typeAliasPropertiesFormat: 'table',
164 tableColumnSettings: {
165 hideInherited: true,
166 hideSources: true,
167 },
168 // Without this, a function property renders as `(data) => TData` β€” the table and list formats
169 // both omit the parameter types otherwise.
170 expandParameters: true,
171 excludePrivate: true,
172 excludeProtected: true,
173 excludeInternal: true,
174 excludeExternals: pkg.excludeExternals,
175 sourceLinkTemplate:
176 'https://github.com/TanStack/query/blob/{gitRevision}/{path}#L{line}',
177 gitRevision: 'main',
178 displayBasePath: resolve(__dirname, '..'),
179 entryPoints: pkg.entryPoints,
180 tsconfig: pkg.tsconfig,
181 ...(pkg.exclude && { exclude: pkg.exclude }),
182 out: outputDir,
183 })
184​
185 // TypeScript flattens an alias out of an intersection, so `Options<T> & QueryKeyWithDataTag<T>`
186 // would render as the members of `Options` followed by the tag. Convert declared intersections from
187 // the source instead, so signatures keep the alias names they were written with.
188 app.converter.on(
189 TypeDoc.Converter.EVENT_CREATE_SIGNATURE,
190 (
191 context: InstanceType<typeof TypeDoc.Context>,
192 signature: InstanceType<typeof TypeDoc.SignatureReflection>,
193 declaration?: ts.Node,
194 ) => {
195 if (!declaration || !ts.isFunctionLike(declaration)) {
196 return
197 }
198 const scope = context.withScope(signature)
199 if (declaration.type && ts.isIntersectionTypeNode(declaration.type)) {
200 signature.type = scope.converter.convertType(scope, declaration.type)
201 }
202 declaration.parameters.forEach((parameter, index) => {
203 const reflection = signature.parameters?.[index]
204 if (
205 reflection &&
206 parameter.type &&
207 ts.isIntersectionTypeNode(parameter.type)
208 ) {
209 reflection.type = scope.converter.convertType(scope, parameter.type)
210 }
211 })
212 },
213 )
214​
215 const project = await app.convert()
216​
217 // `outputDir` was emptied above, so a failed conversion would otherwise leave it that way and
218 // look like every page was intentionally deleted. Fail loudly instead β€” TypeDoc reports the
219 // underlying diagnostics on stderr.
220 //
221 // The most likely cause is TS6305: `angular-query-experimental` reaches `@tanstack/query-devtools`
222 // through a TypeScript project reference, so it consumes that package's emitted `.d.ts` rather than
223 // its source (which is solid-js JSX and cannot be compiled under Angular's tsconfig). The
224 // `generate-docs` script builds it first, so this should only surface if that build was skipped.
225 if (!project) {
226 throw new Error(
227 `TypeDoc failed to convert ${pkg.entryPoints.join(', ')}. See the diagnostics above.`,
228 )
229 }
230​
231 if (pkg.simplifyLitQueriesControllerTypes) {
232 simplifyLitQueriesControllerTypes(project)
233 }
234​
235 await app.generateOutputs(project)
236​
237 if (pkg.trimGeneratedMarkdown) {
238 await trimTrailingWhitespaceInMarkdown(outputDir)
239 }
240​
241 if (pkg.redirectFrom) {
242 await addRedirectFromToFrontmatter(outputDir, pkg.redirectFrom)
243 }
244​
245 await addReferenceDetails(outputDir)
247​
248// Splits the escaped type arguments (`\\<…\\>`) that follow a type name from the rest of the line.
249function splitTypeArguments(rest: string) {
250 if (!rest.startsWith('\\<')) {
251 return { typeArguments: undefined, after: rest }
252 }
253 let depth = 0
254 for (let index = 0; index < rest.length; index++) {
255 if (rest.startsWith('\\<', index)) {
256 depth++
257 } else if (rest.startsWith('\\>', index) && --depth === 0) {
258 return {
259 typeArguments: rest.slice(2, index),
260 after: rest.slice(index + 2),
261 }
262 }
263 }
264 return { typeArguments: undefined, after: rest }
266​
267// The type page a `Parameters`/`Returns` type line refers to when the whole line is that one type
268// (with an optional default value), looking through wrappers that only change how the value is
269// passed, i.e. aliases like `Accessor<T> = () => T` and inline `() => T`.
270// Whether a type alias only changes how its single type argument is passed, e.g. `Accessor<T> = () => T`.
271async function isWrapperAlias(outputDir: string, from: string) {
272 const code = (await readPage(outputDir, from))?.match(
273 /```ts\ntype \w+<(\w+)> = ([^\n]*);\n```/,
274 )
275 return (
276 !!code &&
277 code[2]!
278 .split(' | ')
279 .every((member) => member === code[1] || member === `() => ${code[1]}`)
280 )
282​
283// The type page a `Parameters`/`Returns` type line refers to when the whole line is that one type
284// (with an optional default value), looking through wrappers that only change how the value is
285// passed, i.e. aliases like `Accessor<T> = () => T` and inline `() => T`.
286async function linkedTypePage(outputDir: string, typeLine: string) {
287 let line = typeLine
288 for (;;) {
289 line = line.replace(/^\(\) => /, '')
290 const link = line.match(
291 /^\[`\w+`\]\(\.\.\/((?:interfaces|type-aliases)\/\w+)\.md\)/,
292 )
293 if (!link) {
294 return undefined
295 }
296 const { typeArguments, after } = splitTypeArguments(
297 line.slice(link[0].length),
298 )
299 if (typeArguments && (await isWrapperAlias(outputDir, link[1]!))) {
300 line = typeArguments
301 continue
302 }
303 return after === '' || after.startsWith(' = ') ? link[1] : undefined
304 }
306​
307// The name of the type a signature's code starts with, looking through the same wrappers.
308async function typeNameInCode(outputDir: string, code: string) {
309 let type = code
310 for (;;) {
311 type = type.replace(/^\(\) => /, '')
312 const name = type.match(/^\w+/)?.[0]
313 if (
314 !name ||
315 type[name.length] !== '<' ||
316 !(await isWrapperAlias(outputDir, `type-aliases/${name}`))
317 ) {
318 return name
319 }
320 let depth = 0
321 for (let index = name.length; index < type.length; index++) {
322 if (type[index] === '<') {
323 depth++
324 } else if (
325 type[index] === '>' &&
326 type[index - 1] !== '=' &&
327 --depth === 0
328 ) {
329 type = type.slice(name.length + 1, index)
330 break
331 }
332 }
333 }
335​
336// The parameter and return types of the declaration a call signature's "Defined in" line points to, as
337// written in the source. The rendered code loses aliases that TypeScript flattens into an intersection,
338// e.g. `Options<T> & QueryKeyWithDataTag<T>` becomes the members of `Options` followed by the tag.
339const sourceFiles = new Map<string, ts.SourceFile>()
340async function declaredSignatureTypes(signature: string) {
341 const location = signature.match(/^Defined in: \[([^\]]+):(\d+)\]/m)
342 if (!location) {
343 return undefined
344 }
345 const [, file, line] = location
346 let source = sourceFiles.get(file!)
347 if (!source) {
348 const text = await readFile(resolve(__dirname, '..', file!), 'utf8').catch(
349 () => undefined,
350 )
351 if (text === undefined) {
352 return undefined
353 }
354 source = ts.createSourceFile(file!, text, ts.ScriptTarget.Latest, true)
355 sourceFiles.set(file!, source)
356 }
357 let found: ts.SignatureDeclaration | undefined
358 const visit = (node: ts.Node) => {
359 if (found) {
360 return
361 }
362 if (
363 ts.isFunctionLike(node) &&
364 'parameters' in node &&
365 source.getLineAndCharacterOfPosition(node.getStart()).line ===
366 Number(line) - 1
367 ) {
368 found = node
369 return
370 }
371 ts.forEachChild(node, visit)
372 }
373 visit(source)
374 return found && { parameter: found.parameters[0]?.type, returns: found.type }
376​
377// Types that only transform their first type argument, so a label keeps that argument to stay
378// meaningful, e.g. `Omit<UseMutationOptions>` instead of `Omit`.
379const typeTransforms = new Set([
380 'Awaited',
381 'DistributiveOmit',
382 'NonNullable',
383 'Omit',
384 'OmitKeyof',
385 'Partial',
386 'Readonly',
387 'Required',
388 'ReturnType',
389 'WithRequired',
390])
391​
392// The label of a declared type: the members of an intersection or union joined, a getter's result, the
393// keys of an object type, or the name looked up through the same wrappers as `typeNameInCode`.
394async function declaredTypeLabel(
395 outputDir: string,
396 node: ts.TypeNode,
397): Promise<string | undefined> {
398 if (ts.isParenthesizedTypeNode(node)) {
399 return declaredTypeLabel(outputDir, node.type)
400 }
401 if (ts.isIntersectionTypeNode(node) || ts.isUnionTypeNode(node)) {
402 const members = await Promise.all(
403 node.types.map((member) => declaredTypeLabel(outputDir, member)),
404 )
405 return members.every(Boolean)
406 ? members.join(ts.isIntersectionTypeNode(node) ? ' & ' : ' | ')
407 : undefined
408 }
409 if (ts.isFunctionTypeNode(node) && node.parameters.length === 0) {
410 const result = await declaredTypeLabel(outputDir, node.type)
411 return result && `() => ${result}`
412 }
413 if (ts.isTypeLiteralNode(node)) {
414 const keys = node.members
415 .map((member) => member.name?.getText())
416 .filter(Boolean)
417 return keys.length > 0 ? `{ ${keys.join(', ')} }` : undefined
418 }
419 if (
420 ts.isTypeReferenceNode(node) &&
421 typeTransforms.has(node.typeName.getText()) &&
422 node.typeArguments?.[0]
423 ) {
424 const target = await declaredTypeLabel(outputDir, node.typeArguments[0])
425 return target && `${node.typeName.getText()}<${target}>`
426 }
427 return typeNameInCode(outputDir, node.getText())
429​
430// The property table for the first type line that has one.
431async function findPropertiesTable(
432 outputDir: string,
433 typeLines: Array<string>,
434) {
435 for (const typeLine of typeLines) {
436 const link = await linkedTypePage(outputDir, typeLine)
437 const from = link && (await propertiesPage(outputDir, link))
438 const table = from && (await readPropertiesTable(outputDir, from))
439 if (table) {
440 return table
441 }
442 }
443 const bases = await findBasePages(outputDir, typeLines)
444 if (bases.length) {
445 return `Built from ${bases
446 .map(
447 (base) => `[\`${base.split('/').at(-1)}\`](../${base}.md#properties)`,
448 )
449 .join(', ')}. See the type above for what it changes.`
450 }
451 return undefined
453​
454// Splits a type expression at a top-level separator, outside `<>`, `()`, `{}`, and `[]`.
455function splitTopLevel(type: string, separator: string) {
456 const parts: Array<string> = []
457 let depth = 0
458 let start = 0
459 for (let index = 0; index < type.length; index++) {
460 const char = type[index]!
461 if ('<({['.includes(char)) {
462 depth++
463 } else if (
464 ')}]'.includes(char) ||
465 (char === '>' && type[index - 1] !== '=')
466 ) {
467 depth--
468 } else if (depth === 0 && type.startsWith(separator, index)) {
469 parts.push(type.slice(start, index))
470 start = index + separator.length
471 index += separator.length - 1
472 }
473 }
474 parts.push(type.slice(start))
475 return parts.map((part) => part.trim()).filter(Boolean)
477​
478async function typePage(outputDir: string, name: string) {
479 for (const from of [`interfaces/${name}`, `type-aliases/${name}`]) {
480 if ((await readPage(outputDir, from)) !== undefined) {
481 return from
482 }
483 }
484 return undefined
486​
487// The pages with a `## Properties` table that a type expression without one is built from: every
488// member of an intersection (skipping object literals, which only add properties), and the first type
489// argument of a utility that isn't built from one itself, like `Omit<…>`. Returns nothing unless every part is found.
490async function basePagesOfType(
491 outputDir: string,
492 type: string,
493 seen: Set<string>,
494): Promise<Array<string>> {
495 const expression = splitTopLevel(type, ' = ')[0]!
496 .replace(/^[|&]\s*/, '')
497 .replace(/^\(\) => /, '')
498 .trim()
499 const members = splitTopLevel(expression, ' & ').filter(
500 (member) => member !== 'object' && !member.startsWith('{'),
501 )
502 if (members.length > 1) {
503 const pages: Array<string> = []
504 for (const member of members) {
505 const memberPages = await basePagesOfType(outputDir, member, seen)
506 if (!memberPages.length) {
507 return []
508 }
509 pages.push(...memberPages)
510 }
511 return [...new Set(pages)]
512 }
513 const reference = members[0]?.match(/^(\w+)(?:<([\s\S]*)>)?$/)
514 if (!reference) {
515 return []
516 }
517 const [, name, typeArguments] = reference
518 const [firstTypeArgument] = typeArguments
519 ? splitTopLevel(typeArguments, ',')
520 : []
521 const page = await typePage(outputDir, name!)
522 const pages =
523 page && !(await isWrapperAlias(outputDir, page))
524 ? await basePages(outputDir, page, seen)
525 : []
526 if (pages.length) {
527 return pages
528 }
529 return firstTypeArgument
530 ? basePagesOfType(outputDir, firstTypeArgument, seen)
531 : []
533​
534async function basePages(
535 outputDir: string,
536 from: string,
537 seen: Set<string>,
538): Promise<Array<string>> {
539 if (seen.has(from)) {
540 return []
541 }
542 seen.add(from)
543 const page = await propertiesPage(outputDir, from)
544 if (page) {
545 return [page]
546 }
547 const code = (await readPage(outputDir, from))?.match(
548 /```ts\ntype \w+(?:<[^\n=]*>)? = ([\s\S]*?);\n```/,
549 )?.[1]
550 return code ? basePagesOfType(outputDir, code, seen) : []
552​
553// The base pages of the first type line that has any.
554async function findBasePages(outputDir: string, typeLines: Array<string>) {
555 for (const typeLine of typeLines) {
556 const type = typeLine
557 .replace(/\[`?(\w+)`?\]\([^)]*\)/g, '$1')
558 .replace(/[\\`]/g, '')
559 const pages = await basePagesOfType(outputDir, type, new Set())
560 if (pages.length) {
561 return pages
562 }
563 }
564 return []
566​
567// The type line of each parameter and of the return value in one call signature.
568function signatureTypes(signature: string) {
569 const parametersHeading = signature.match(/\n#{2,3} Parameters\n/)
570 const returnsHeading = signature.match(/\n#{2,3} Returns\n/)
571 const parameters = parametersHeading
572 ? signature.slice(
573 parametersHeading.index! + parametersHeading[0].length - 1,
574 returnsHeading?.index,
575 )
576 : ''
577 // Only the headings one level below `Parameters`, not the properties of an inline object argument.
578 const parameterHeading = '#'.repeat(
579 (parametersHeading?.[0].trim().indexOf(' ') ?? 0) + 1,
580 )
581 return {
582 parameters: new Map(
583 [
584 ...parameters.matchAll(
585 new RegExp(`\\n${parameterHeading} (\\S+)\\n\\n([^\\n]*)`, 'g'),
586 ),
587 ].map(([, name, typeLine]) => [name!, typeLine!]),
588 ),
589 returns: returnsHeading
590 ? signature
591 .slice(returnsHeading.index! + returnsHeading[0].length)
592 .trim()
593 .split('\n')[0]!
594 : undefined,
595 }
597​
598function readPage(outputDir: string, from: string) {
599 return readFile(resolve(outputDir, `${from}.md`), 'utf8').then(
600 (source) => source,
601 () => undefined,
602 )
604​
605// Resolves a type page to the interface pages it stands for: itself when it has a `## Properties`
606// table, or the members of a plain alias or union. Anything else (intersections, `Omit`, `Override`, …)
607// resolves to nothing, since no generated table describes it as-is.
608async function resolveInterfacePages(
609 outputDir: string,
610 from: string,
611): Promise<Array<string> | undefined> {
612 const source = await readPage(outputDir, from)
613 if (source === undefined) {
614 return undefined
615 }
616 if (source.includes('\n## Properties\n')) {
617 return [from]
618 }
619 const code = source.match(
620 /```ts\ntype \w+(?:<[^\n=]*>)? = ([\s\S]*?);\n```/,
621 )?.[1]
622 if (!code) {
623 return undefined
624 }
625 let members = code
626 while (/<[^<>]*>/.test(members)) {
627 members = members.replace(/<[^<>]*>/g, '')
628 }
629 const names = members
630 .split('|')
631 .map((member) => member.trim())
632 .filter(Boolean)
633 if (!names.every((name) => /^\w+$/.test(name))) {
634 return undefined
635 }
636 const pages: Array<string> = []
637 for (const name of names) {
638 const resolved =
639 (await resolveInterfacePages(outputDir, `interfaces/${name}`)) ??
640 (await resolveInterfacePages(outputDir, `type-aliases/${name}`))
641 if (!resolved) {
642 return undefined
643 }
644 pages.push(...resolved)
645 }
646 return pages
648​
649// The page whose `## Properties` table describes the type: the type itself, or the interface every
650// member of a union extends.
651async function propertiesPage(outputDir: string, from: string) {
652 const pages = await resolveInterfacePages(outputDir, from)
653 if (!pages?.length) {
654 return undefined
655 }
656 if (pages.length === 1) {
657 return pages[0]
658 }
659 const bases = new Set<string>()
660 for (const page of pages) {
661 const base = (await readPage(outputDir, page))?.match(
662 /\n## Extends\n\n- \[`\w+`\]\((\w+)\.md\)[^\n]*\n\n##/,
663 )?.[1]
664 if (!base) {
665 return undefined
666 }
667 bases.add(`${dirname(page)}/${base}`)
668 }
669 return bases.size === 1 ? [...bases][0] : undefined
671​
672async function readPropertiesTable(outputDir: string, from: string) {
673 const source = await readPage(outputDir, from)
674 const start = source?.indexOf('\n## Properties\n') ?? -1
675 if (source === undefined || start === -1) {
676 return undefined
677 }
678 const fromDir = dirname(from)
679 return source
680 .slice(start + '\n## Properties\n'.length)
681 .trim()
682 .replace(
683 /\]\((?!https?:|#)([^)]+)\)/g,
684 (_, link: string) =>
685 `](../${link.startsWith('../') ? link.slice(3) : `${fromDir}/${link}`})`,
686 )
688​
689// Adds to every function page without changing what TypeDoc generated: the properties of each
690// argument and of the result, and an `## Overview` of every call signature on overloaded pages. The
691// properties come from the generated page of the type, following plain aliases and, for a union,
692// the interface all of its members extend. Types that override or omit properties get no table.
693async function addReferenceDetails(outputDir: string) {
694 const files = await readdir(resolve(outputDir, 'functions')).catch(
695 () => [] as Array<string>,
696 )
697 for (const file of files.filter((name) => name.endsWith('.md'))) {
698 const pagePath = `functions/${file.slice(0, -3)}`
699 const pageFile = resolve(outputDir, `${pagePath}.md`)
700 const page = await readFile(pageFile, 'utf8')
701 const [head, ...signatures] = page.split('\n## Call Signature\n')
702 const isOverloaded = signatures.length > 1
703 const lastSignature = signatures.at(-1) ?? page
704​
705 // Property tables of the arguments whose type has a `## Properties` table, and of the result.
706 const tables: Array<{
707 id: string
708 title: string
709 table: string
710 parameter?: string
711 }> = []
712 const parametersHeading = lastSignature.match(/\n#{2,3} Parameters\n/)
713 const returnsHeading = lastSignature.match(/\n#{2,3} Returns\n/)
714 const parameters = parametersHeading
715 ? lastSignature.slice(
716 parametersHeading.index! + parametersHeading[0].length - 1,
717 returnsHeading?.index,
718 )
719 : ''
720 // Overloads describe the same arguments with different types, so a table missing from the
721 // last (most general) signature is taken from the latest earlier one that has it.
722 const signatureTypeLines = (signatures.length ? signatures : [page])
723 .map(signatureTypes)
724 .reverse()
725 for (const name of signatureTypeLines[0]!.parameters.keys()) {
726 const table = await findPropertiesTable(
727 outputDir,
728 signatureTypeLines.flatMap((types) => types.parameters.get(name) ?? []),
729 )
730 if (!table) {
731 continue
732 }
733 const argument = name.replace(/\\/g, '').replace(/\?$/, '')
734 const key = argument === '__namedParameters' ? 'props' : argument
735 tables.push({
736 id: `${key}-properties`,
737 title: `\`${key}\` properties`,
738 table,
739 parameter: name,
740 })
741 }
742 const resultTable = await findPropertiesTable(
743 outputDir,
744 signatureTypeLines.flatMap((types) => types.returns ?? []),
745 )
746 if (resultTable) {
747 tables.push({
748 id: 'result-properties',
749 title: 'Result properties',
750 table: resultTable,
751 })
752 }
753​
754 // Property anchors are prefixed with the table's name, so they stay unique when two tables on
755 // the same page list the same properties.
756 const section = (
757 level: number,
758 { id, title, table }: (typeof tables)[number],
759 ) =>
760 `<a id="${id}"></a>\n\n${'#'.repeat(level)} ${title}\n\n${table.replace(
761 /<a id="([^"]+)"><\/a>/g,
762 `<a id="${id.replace(/-properties$/, '')}-$1"></a>`,
763 )}`
764​
765 if (!isOverloaded) {
766 // Put each table at the end of the section it describes, so nothing is repeated.
767 let updated = page.trimEnd()
768 for (const entry of tables) {
769 const heading = entry.parameter
770 ? `\n### ${entry.parameter}\n`
771 : '\n## Returns\n'
772 const level = entry.parameter ? 3 : 2
773 const start = updated.indexOf(heading)
774 if (start === -1) {
775 continue
776 }
777 const next = updated
778 .slice(start + heading.length)
779 .search(new RegExp(`\\n#{1,${level}} `))
780 const insertAt =
781 next === -1 ? updated.length : start + heading.length + next
782 updated = `${updated.slice(0, insertAt).trimEnd()}\n\n${section(level + 1, entry)}\n${updated.slice(insertAt)}`
783 }
784 await writeFile(pageFile, `${updated.trimEnd()}\n`)
785 continue
786 }
787​
788 const entries = await Promise.all(
789 signatures.map(async (signature, index) => {
790 const code = signature.match(/```ts\n([\s\S]*?)\n```/)?.[1] ?? ''
791 const summary = signature
792 .split('\n### ')[0]!
793 .split('\n\n')
794 .map((block) => block.trim())
795 .find(
796 (block) =>
797 block !== '' &&
798 !block.startsWith('```') &&
799 !block.startsWith('Defined in:'),
800 )
801 const declared = await declaredSignatureTypes(signature)
802 const label = (
803 await Promise.all(
804 [
805 [
806 declared?.parameter,
807 code.match(/\((?:\w+\??): ([\s\S]*)/)?.[1],
808 ] as const,
809 [declared?.returns, code.match(/\): ([\s\S]*)/)?.[1]] as const,
810 ].map(async ([node, type]) =>
811 node
812 ? ((await declaredTypeLabel(outputDir, node)) ??
813 (type && typeNameInCode(outputDir, type)))
814 : type && typeNameInCode(outputDir, type),
815 ),
816 )
817 )
818 .filter(Boolean)
819 .map((type) => `\`${type}\``)
820 .join(' β†’ ')
821 return {
822 code,
823 line: `- [${label || `Call signature ${index + 1}`}](#call-signature-${index + 1})${summary ? `: ${summary.replace(/\n/g, ' ')}` : ''}`,
824 }
825 }),
826 )
827 // Repeat the last (most general) signature's `Parameters` and `Returns` once at the end, one
828 // heading level up, with the property tables, so every argument and the result are listed together.
829 const promote = (block: string) => block.replace(/^#(#+) /gm, '$1 ')
830 let parametersSummary = parametersHeading
831 ? `## Parameters\n\n${promote(parameters.trim())}`
832 : ''
833 for (const entry of tables.filter((table) => table.parameter)) {
834 const heading = `\n### ${entry.parameter}\n`
835 const start = parametersSummary.indexOf(heading)
836 if (start === -1) {
837 continue
838 }
839 const next = parametersSummary
840 .slice(start + heading.length)
841 .search(/\n#{1,3} /)
842 const insertAt =
843 next === -1 ? parametersSummary.length : start + heading.length + next
844 parametersSummary = `${parametersSummary.slice(0, insertAt).trimEnd()}\n\n${section(4, entry)}\n${parametersSummary.slice(insertAt)}`
845 }
846 const returnsBlock = returnsHeading
847 ? lastSignature
848 .slice(returnsHeading.index! + returnsHeading[0].length)
849 .split(/\n#{2,3} /)[0]!
850 .trim()
851 : ''
852 const resultEntry = tables.find((table) => !table.parameter)
853 const summaries = [
854 parametersSummary
855 ? `<a id="parameters-summary"></a>\n\n${parametersSummary.trimEnd()}`
856 : '',
857 returnsBlock
858 ? [
859 '<a id="returns-summary"></a>',
860 '',
861 '## Returns',
862 '',
863 returnsBlock,
864 ...(resultEntry ? ['', section(3, resultEntry)] : []),
865 ].join('\n')
866 : '',
867 ].filter(Boolean)
868 const links = [
869 ...(parametersSummary ? ['[Parameters](#parameters-summary)'] : []),
870 ...(returnsBlock ? ['[Returns](#returns-summary)'] : []),
871 ]
872 const overview = [
873 '## Overview',
874 '',
875 '```ts',
876 ...entries.map((entry) => entry.code),
877 '```',
878 '',
879 ...entries.map((entry) => entry.line),
880 ...(links.length > 0 ? ['', `See also: ${links.join(' Β· ')}`] : []),
881 ].join('\n')
882 const body = signatures
883 .map(
884 (signature, index) =>
885 `\n<a id="call-signature-${index + 1}"></a>\n\n## Call Signature\n${signature}`,
886 )
887 .join('')
888 .trimEnd()
889 const appended = summaries.join('\n\n')
890 await writeFile(
891 pageFile,
892 `${head!.trimEnd()}\n\n${overview}\n${body}${appended ? `\n\n${appended}` : ''}\n`,
893 )
894 }
896​
897const packages: Array<PackageReferenceDocsConfig> = [
898 {
899 entryPoints: [
900 resolve(__dirname, '../packages/angular-query-experimental/src/index.ts'),
901 ],
902 tsconfig: resolve(
903 __dirname,
904 '../packages/angular-query-experimental/tsconfig.json',
905 ),
906 outputDir: resolve(__dirname, '../docs/framework/angular/reference'),
907 },
908 {
909 entryPoints: [resolve(__dirname, '../packages/svelte-query/src/index.ts')],
910 tsconfig: resolve(__dirname, '../packages/svelte-query/tsconfig.json'),
911 outputDir: resolve(__dirname, '../docs/framework/svelte/reference'),
912 },
913 {
914 entryPoints: [resolve(__dirname, '../packages/solid-query/src/index.ts')],
915 tsconfig: resolve(__dirname, '../packages/solid-query/tsconfig.json'),
916 outputDir: resolve(__dirname, '../docs/framework/solid/reference'),
917 redirectFrom: {
918 'functions/infiniteQueryOptions': [
919 'framework/solid/reference/infiniteQueryOptions',
920 ],
921 'functions/mutationOptions': [
922 'framework/solid/reference/mutationOptions',
923 ],
924 'functions/queryOptions': ['framework/solid/reference/queryOptions'],
925 'functions/useInfiniteQuery': [
926 'framework/solid/reference/useInfiniteQuery',
927 ],
928 'functions/useIsFetching': ['framework/solid/reference/useIsFetching'],
929 'functions/useIsMutating': ['framework/solid/reference/useIsMutating'],
930 'functions/useMutation': ['framework/solid/reference/useMutation'],
931 'functions/useMutationState': [
932 'framework/solid/reference/useMutationState',
933 ],
934 'functions/useQueries': ['framework/solid/reference/useQueries'],
935 'functions/useQuery': ['framework/solid/reference/useQuery'],
936 },
937 },
938 {
939 entryPoints: [resolve(__dirname, '../packages/vue-query/src/index.ts')],
940 tsconfig: resolve(__dirname, '../packages/vue-query/tsconfig.json'),
941 outputDir: resolve(__dirname, '../docs/framework/vue/reference'),
942 redirectFrom: {
943 'functions/infiniteQueryOptions': [
944 'framework/vue/reference/infiniteQueryOptions',
945 ],
946 'functions/mutationOptions': ['framework/vue/reference/mutationOptions'],
947 'functions/queryOptions': ['framework/vue/reference/queryOptions'],
948 'functions/useInfiniteQuery': [
949 'framework/vue/reference/useInfiniteQuery',
950 ],
951 'functions/useIsFetching': ['framework/vue/reference/useIsFetching'],
952 'functions/useIsMutating': ['framework/vue/reference/useIsMutating'],
953 'functions/useMutation': ['framework/vue/reference/useMutation'],
954 'functions/useMutationState': [
955 'framework/vue/reference/useMutationState',
956 ],
957 'functions/usePrefetchInfiniteQuery': [
958 'framework/vue/reference/usePrefetchInfiniteQuery',
959 ],
960 'functions/usePrefetchQuery': [
961 'framework/vue/reference/usePrefetchQuery',
962 ],
963 'functions/useQueries': ['framework/vue/reference/useQueries'],
964 'functions/useQuery': ['framework/vue/reference/useQuery'],
965 'functions/useQueryClient': ['framework/vue/reference/useQueryClient'],
966 },
967 },
968 {
969 entryPoints: [resolve(__dirname, '../packages/react-query/src/index.ts')],
970 tsconfig: resolve(__dirname, '../packages/react-query/tsconfig.json'),
971 outputDir: resolve(__dirname, '../docs/framework/react/reference'),
972 redirectFrom: {
973 'functions/infiniteQueryOptions': [
974 'framework/react/reference/infiniteQueryOptions',
975 ],
976 'functions/mutationOptions': [
977 'framework/react/reference/mutationOptions',
978 ],
979 'functions/QueryClientProvider': [
980 'framework/react/reference/QueryClientProvider',
981 ],
982 'functions/QueryErrorResetBoundary': [
983 'framework/react/reference/QueryErrorResetBoundary',
984 ],
985 'functions/queryOptions': ['framework/react/reference/queryOptions'],
986 'functions/useInfiniteQuery': [
987 'framework/react/reference/useInfiniteQuery',
988 ],
989 'functions/useIsFetching': ['framework/react/reference/useIsFetching'],
990 'functions/useIsMutating': ['framework/react/reference/useIsMutating'],
991 'functions/useMutation': ['framework/react/reference/useMutation'],
992 'functions/useMutationState': [
993 'framework/react/reference/useMutationState',
994 ],
995 'functions/usePrefetchInfiniteQuery': [
996 'framework/react/reference/usePrefetchInfiniteQuery',
997 ],
998 'functions/usePrefetchQuery': [
999 'framework/react/reference/usePrefetchQuery',
1000 ],
1001 'functions/useQueries': ['framework/react/reference/useQueries'],
1002 'functions/useQuery': ['framework/react/reference/useQuery'],
1003 'functions/useQueryClient': ['framework/react/reference/useQueryClient'],
1004 'functions/useQueryErrorResetBoundary': [
1005 'framework/react/reference/useQueryErrorResetBoundary',
1006 ],
1007 'functions/useSuspenseInfiniteQuery': [
1008 'framework/react/reference/useSuspenseInfiniteQuery',
1009 ],
1010 'functions/useSuspenseQueries': [
1011 'framework/react/reference/useSuspenseQueries',
1012 ],
1013 'functions/useSuspenseQuery': [
1014 'framework/react/reference/useSuspenseQuery',
1015 ],
1016 // Redirects from the legacy hand-written docs/reference/*.md pages, removed in favor of
1017 // this generated reference.
1018 'classes/QueryClient': [
1019 'reference/QueryClient',
1020 'framework/react/reference/QueryClient',
1021 ],
1022 'classes/QueryCache': [
1023 'reference/QueryCache',
1024 'framework/react/reference/QueryCache',
1025 ],
1026 'classes/MutationCache': [
1027 'reference/MutationCache',
1028 'framework/react/reference/MutationCache',
1029 ],
1030 'classes/QueryObserver': [
1031 'reference/QueryObserver',
1032 'framework/react/reference/QueryObserver',
1033 ],
1034 'classes/InfiniteQueryObserver': [
1035 'reference/InfiniteQueryObserver',
1036 'framework/react/reference/InfiniteQueryObserver',
1037 ],
1038 'classes/QueriesObserver': [
1039 'reference/QueriesObserver',
1040 'framework/react/reference/QueriesObserver',
1041 ],
1042 // focusManager/onlineManager/timeoutManager are class instances, not object literals, so
1043 // TypeDoc can't inline their methods onto the `variables/*` instance page β€” the method docs
1044 // that the legacy pages covered now live on the `interfaces/*` page for the class itself.
1045 'interfaces/FocusManager': [
1046 'reference/focusManager',
1047 'framework/react/reference/focusManager',
1048 ],
1049 'interfaces/OnlineManager': [
1050 'reference/onlineManager',
1051 'framework/react/reference/onlineManager',
1052 ],
1053 'interfaces/TimeoutManager': ['reference/timeoutManager'],
1054 'variables/notifyManager': [
1055 'reference/notifyManager',
1056 'framework/react/reference/notifyManager',
1057 ],
1058 'variables/environmentManager': ['reference/environmentManager'],
1059 'functions/experimental_streamedQuery': ['reference/streamedQuery'],
1060 },
1061 },
1063 entryPoints: [resolve(__dirname, '../packages/preact-query/src/index.ts')],
1064 tsconfig: resolve(__dirname, '../packages/preact-query/tsconfig.json'),
1065 outputDir: resolve(__dirname, '../docs/framework/preact/reference'),
1066 },
1068 entryPoints: [resolve(__dirname, '../packages/lit-query/src/index.ts')],
1069 tsconfig: resolve(__dirname, '../packages/lit-query/tsconfig.json'),
1070 outputDir: resolve(__dirname, '../docs/framework/lit/reference'),
1071 excludeExternals: true,
1072 simplifyLitQueriesControllerTypes: true,
1073 trimGeneratedMarkdown: true,
1074 },
1076​
1077for (const pkg of packages) {
1078 await generatePackageReferenceDocs(pkg)
1080​
1081console.log('\nβœ… All markdown files have been processed!')
1082​
1083process.exit(0)