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