Open History to see the last commit
1import { chain } from '@angular-devkit/schematics'
2import { NodePackageInstallTask } from '@angular-devkit/schematics/tasks'
3import { addRootProvider } from '@schematics/angular/utility'
4import {
5 NodeDependencyType,
6 addPackageJsonDependency,
7} from '@schematics/angular/utility/dependencies'
8import {
9 getAppModulePath,
10 isStandaloneApp,
11} from '@schematics/angular/utility/ng-ast-utils'
12import { findAppConfig } from '@schematics/angular/utility/standalone/app_config'
13import {
14 findBootstrapApplicationCall,
15 getMainFilePath,
16} from '@schematics/angular/utility/standalone/util'
17import ts from 'typescript'
18import type { Rule, Tree } from '@angular-devkit/schematics'
19import type { Schema } from './schema'
20β
21// Replaced with package metadata by scripts/inject-schematic-package-info.js.
22// The published schematic contains literal values and does not read package.json.
23const PACKAGE_NAME = '__ANGULAR_QUERY_PACKAGE_NAME__'
24const DEVTOOLS_PACKAGE_NAME = '__ANGULAR_QUERY_DEVTOOLS_PACKAGE_NAME__'
25const DEVTOOLS_PACKAGE_VERSION = '__ANGULAR_QUERY_DEVTOOLS_PACKAGE_VERSION__'
26β
27function hasPackageDependency(tree: Tree, name: string) {
28 const packageJsonPath = tree.exists('/package.json')
29 ? '/package.json'
30 : 'package.json'
31 const packageJson = JSON.parse(tree.readText(packageJsonPath)) as Record<
32 string,
33 Record<string, string> | undefined
34 >
35β
36 return ['dependencies', 'devDependencies', 'optionalDependencies'].some(
37 (dependencyType) => packageJson[dependencyType]?.[name] !== undefined,
38 )
39}
40β
41function addDevtoolsDependency(): Rule {
42 return (tree, context) => {
43 if (hasPackageDependency(tree, DEVTOOLS_PACKAGE_NAME)) return tree
44β
45 // A caret range lets the devtools update together with the query package.
46 addPackageJsonDependency(tree, {
47 type: NodeDependencyType.Default,
48 name: DEVTOOLS_PACKAGE_NAME,
49 version: `^${DEVTOOLS_PACKAGE_VERSION}`,
50 overwrite: false,
51 })
52 context.addTask(new NodePackageInstallTask())
53 return tree
54 }
55}
56β
57function hasProviderCall(tree: Tree, sourcePath: string) {
58 const source = ts.createSourceFile(
59 sourcePath,
60 tree.readText(sourcePath),
61 ts.ScriptTarget.Latest,
62 true,
63 )
64 const localProviderNames = new Set<string>()
65β
66 for (const statement of source.statements) {
67 if (
68 !ts.isImportDeclaration(statement) ||
69 !ts.isStringLiteral(statement.moduleSpecifier) ||
70 statement.moduleSpecifier.text !== PACKAGE_NAME ||
71 !statement.importClause?.namedBindings ||
72 !ts.isNamedImports(statement.importClause.namedBindings)
73 ) {
74 continue
75 }
76β
77 for (const element of statement.importClause.namedBindings.elements) {
78 if (
79 (element.propertyName ?? element.name).text === 'provideTanStackQuery'
80 ) {
81 localProviderNames.add(element.name.text)
82 }
83 }
84 }
85β
86 if (localProviderNames.size === 0) return false
87β
88 let found = false
89 const visit = (node: ts.Node) => {
90 if (
91 ts.isCallExpression(node) &&
92 ts.isIdentifier(node.expression) &&
93 localProviderNames.has(node.expression.text)
94 ) {
95 found = true
96 return
97 }
98β
99 if (!found) ts.forEachChild(node, visit)
100 }
101 visit(source)
102 return found
103}
104β
105async function hasRootQueryProvider(tree: Tree, projectName: string) {
106 const mainFilePath = await getMainFilePath(tree, projectName)
107 const rootFilePath = isStandaloneApp(tree, mainFilePath)
108 ? (findAppConfig(
109 findBootstrapApplicationCall(tree, mainFilePath),
110 tree,
111 mainFilePath,
112 )?.filePath ?? mainFilePath)
113 : getAppModulePath(tree, mainFilePath)
114β
115 return hasProviderCall(tree, rootFilePath)
116}
117β
118function addQueryProvider(project: string): Rule {
119 return async (tree) => {
120 if (await hasRootQueryProvider(tree, project)) return tree
121β
122 return addRootProvider(
123 project,
124 ({ code, external }) =>
125 code`${external(
126 'provideTanStackQuery',
127 PACKAGE_NAME,
128 )}(() => new ${external(
129 'QueryClient',
130 PACKAGE_NAME,
131 )}(), ${external('withDevtools', DEVTOOLS_PACKAGE_NAME)}())`,
132 )
133 }
134}
135β
136/**
137 * Configures TanStack Query at the application root.
138 *
139 * The QueryClient factory is resolved by each root injector, preventing query
140 * caches from being shared between SSR requests.
141 */
142export function ngAdd(options: Schema): Rule {
143 return chain([addDevtoolsDependency(), addQueryProvider(options.project)])
144}