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

source.ts

518 lines18.6 KB

1import ts from 'typescript'
2import { MigrationImports } from './imports'
3import type { Schema } from './schema'
4​
5export const OLD_PACKAGE = '@tanstack/angular-query-experimental'
6export const CORE_PACKAGE = '@tanstack/query-core'
7​
8// The experimental helpers used two different injector argument shapes.
9const injectorArguments: Record<
10 string,
11 { index: number; kind: 'injector' | 'options' } | undefined
12> = {
13 injectQueries: { index: 1, kind: 'injector' },
14 injectQuery: { index: 1, kind: 'options' },
15 injectInfiniteQuery: { index: 1, kind: 'options' },
16 injectMutation: { index: 1, kind: 'options' },
17 injectMutationState: { index: 1, kind: 'options' },
18 injectIsFetching: { index: 1, kind: 'options' },
19 injectIsMutating: { index: 1, kind: 'options' },
20 injectIsRestoring: { index: 0, kind: 'options' },
21 injectDevtoolsPanel: { index: 1, kind: 'options' },
23const removedInjectorOptions = new Set([
24 'InjectQueryOptions',
25 'InjectInfiniteQueryOptions',
26 'InjectMutationOptions',
27 'InjectMutationStateOptions',
28 'InjectIsFetchingOptions',
29 'InjectIsMutatingOptions',
30 'InjectDevtoolsPanelOptions',
31])
32const removedApis: Record<string, string | undefined> = {
33 provideIsRestoring:
34 'Restoration is managed by withPersistQueryClient. Review custom restoration providers.',
35 queryFeature:
36 'Custom feature construction is no longer public. Use the supported with* features.',
37 QueryFeatures: 'Use the non-generic QueryFeature type.',
38 DevtoolsFeature: 'Use the non-generic QueryFeature type.',
39 PersistQueryClientFeature: 'Use the non-generic QueryFeature type.',
40 CreateBaseQueryOptions: 'Use CreateQueryOptions and review typed wrappers.',
42​
43/** Source edits preserve untouched formatting; symbols protect shadowed local names. */
44export function migrateSource(
45 text: string,
46 path: string,
47 packageName: string,
48 devtoolsPackageName: string,
49 report: (message: string) => void,
50 options: Schema = {},
51) {
52 const result = { needsDevtools: false }
53 const source = ts.createSourceFile(path, text, ts.ScriptTarget.Latest, true)
54 // Binding symbols distinguish imports from identically named local parameters.
55 const host = ts.createCompilerHost({ noLib: true })
56 host.getSourceFile = (name) => (name === path ? source : undefined)
57 const checker = ts
58 .createProgram([path], { noLib: true, noResolve: true }, host)
59 .getTypeChecker()
60 const bindings = new Map<ts.Symbol, string>()
61 const namespaces = new Set<ts.Symbol>()
62 const edits: Array<{ start: number; end: number; text: string }> = []
63 const replace = (node: ts.Node, value: string) => {
64 const start = node.getStart(source)
65 // A whole-import removal supersedes its earlier module-specifier edit.
66 for (let index = edits.length - 1; index >= 0; index--) {
67 if (edits[index]!.start >= start && edits[index]!.end <= node.end)
68 edits.splice(index, 1)
69 }
70 edits.push({ start, end: node.end, text: value })
71 }
72 const warn = (node: ts.Node, message: string) =>
73 report(
74 `${path}:${source.getLineAndCharacterOfPosition(node.getStart(source)).line + 1}: ${message}`,
75 )
76 const renames: Record<string, string> = {
77 provideAngularQuery: 'provideTanStackQuery',
78 provideQueryClient: 'provideTanStackQuery',
79 }
80 const imports = new MigrationImports(source, checker, (module) =>
81 module === OLD_PACKAGE ||
82 module === `${OLD_PACKAGE}/inject-queries-experimental` ||
83 (options.migrateQueryCoreImports && module === CORE_PACKAGE)
84 ? packageName
85 : module,
86 )
87​
88 function migrateImports() {
89 for (const statement of source.statements) {
90 if (
91 (!ts.isImportDeclaration(statement) &&
92 !ts.isExportDeclaration(statement)) ||
93 !statement.moduleSpecifier ||
94 !ts.isStringLiteral(statement.moduleSpecifier)
95 )
96 continue
97 const module = statement.moduleSpecifier.text
98 const isCore = options.migrateQueryCoreImports && module === CORE_PACKAGE
99 const targets: Record<string, string | undefined> = {
100 [OLD_PACKAGE]: packageName,
101 [`${OLD_PACKAGE}/inject-queries-experimental`]: packageName,
102 [`${OLD_PACKAGE}/devtools`]: devtoolsPackageName,
103 [`${OLD_PACKAGE}/devtools/production`]: `${devtoolsPackageName}/production`,
104 [`${OLD_PACKAGE}/devtools-panel`]: `${devtoolsPackageName}/devtools-panel`,
105 [`${OLD_PACKAGE}/devtools-panel/production`]: `${devtoolsPackageName}/devtools-panel/production`,
106 }
107 if (isCore) targets[CORE_PACKAGE] = packageName
108 const target = targets[module]
109 const isDevtools =
110 target?.startsWith(devtoolsPackageName) ||
111 module === devtoolsPackageName ||
112 module.startsWith(`${devtoolsPackageName}/`)
113 if (isDevtools) result.needsDevtools = true
114 if (target) replace(statement.moduleSpecifier, JSON.stringify(target))
115 else if (module.startsWith(`${OLD_PACKAGE}/`))
116 warn(
117 statement,
118 'Unrecognized experimental entrypoint. Update this package reference manually.',
119 )
120 if (
121 module !== OLD_PACKAGE &&
122 module !== packageName &&
123 module !== `${OLD_PACKAGE}/inject-queries-experimental` &&
124 !isCore &&
125 !isDevtools
126 )
127 continue
128 if (ts.isExportDeclaration(statement)) {
129 warn(
130 statement,
131 'Review re-exported APIs and migrate their consumers manually.',
132 )
133 if (
134 statement.exportClause &&
135 ts.isNamedExports(statement.exportClause)
136 ) {
137 for (const element of statement.exportClause.elements)
138 warnRemovedApi(element, (element.propertyName ?? element.name).text)
139 }
140 continue
141 }
142 const named = statement.importClause?.namedBindings
143 if (!named) continue
144 if (ts.isNamespaceImport(named)) {
145 const symbol = checker.getSymbolAtLocation(named.name)
146 if (symbol) namespaces.add(symbol)
147 } else {
148 const specifiers: Array<string> = []
149 for (const element of named.elements) {
150 const name = (element.propertyName ?? element.name).text
151 const symbol = checker.getSymbolAtLocation(element.name)
152 if (symbol) bindings.set(symbol, name)
153 warnRemovedApi(element, name)
154 const removable =
155 name === 'injectQueryClient' && canRemoveHelperImport(element)
156 if (!removable)
157 specifiers.push(
158 !isDevtools && renames[name]
159 ? `${element.isTypeOnly ? 'type ' : ''}${renames[name]} as ${element.name.text}`
160 : element.getText(source),
161 )
162 if (name === 'injectQueryClient' && !removable)
163 warn(
164 element,
165 'Review non-call references or arguments to removed injectQueryClient; its import requires manual removal.',
166 )
167 }
168 if (
169 specifiers.join(', ') !==
170 named.elements.map((element) => element.getText(source)).join(', ')
171 ) {
172 if (specifiers.length === 0 && !statement.importClause.name)
173 replace(statement, '')
174 else replace(named, `{ ${specifiers.join(', ')} }`)
175 }
176 }
177 }
178 }
179​
180 function warnRemovedApi(node: ts.Node, name: string) {
181 if (removedInjectorOptions.has(name))
182 warn(
183 node,
184 `${name} was removed. Review typed wrappers and move injector handling to runInInjectionContext.`,
185 )
186 else if (removedApis[name])
187 warn(node, `${name} was removed. ${removedApis[name]}`)
188 }
189​
190 function canRemoveHelperImport(element: ts.ImportSpecifier) {
191 const symbol = checker.getSymbolAtLocation(element.name)
192 if (!symbol) return false
193 function hasUnsupportedReference(node: ts.Node): boolean {
194 if (
195 ts.isIdentifier(node) &&
196 checker.getSymbolAtLocation(node) === symbol &&
197 node !== element.name &&
198 node !== element.propertyName
199 ) {
200 return (
201 !ts.isCallExpression(node.parent) ||
202 node.parent.expression !== node ||
203 node.parent.arguments.length !== 0
204 )
205 }
206 return ts.forEachChild(node, hasUnsupportedReference) ?? false
207 }
208 return !hasUnsupportedReference(source)
209 }
210​
211 const apiName = (
212 expression: ts.Expression | ts.EntityName,
213 ): string | undefined => {
214 if (ts.isIdentifier(expression)) {
215 const symbol = checker.getSymbolAtLocation(expression)
216 return symbol && bindings.get(symbol)
217 }
218 if (ts.isPropertyAccessExpression(expression)) {
219 const symbol = checker.getSymbolAtLocation(expression.expression)
220 if (symbol && namespaces.has(symbol)) return expression.name.text
221 }
222 if (ts.isQualifiedName(expression)) {
223 const symbol = checker.getSymbolAtLocation(expression.left)
224 if (symbol && namespaces.has(symbol)) return expression.right.text
225 }
226 return undefined
227 }
228 function migrateCall(node: ts.CallExpression) {
229 const name = apiName(node.expression)
230 if (name) warnAboutInjectorArgument(node, name)
231 switch (name) {
232 case 'provideTanStackQuery':
233 case 'provideAngularQuery':
234 case 'provideQueryClient':
235 migrateProvider(node)
236 break
237 case 'injectQueryClient':
238 migrateClientInjection(node)
239 break
240 case 'injectIsFetching':
241 case 'injectIsMutating':
242 migrateActivityFilter(node)
243 break
244 }
245 if (
246 name &&
247 [
248 'injectQuery',
249 'injectInfiniteQuery',
250 'injectMutation',
251 'queryOptions',
252 'infiniteQueryOptions',
253 'mutationOptions',
254 ].includes(name)
255 )
256 warnAboutObserverOptions(node.arguments[0])
257 if (name === 'withDevtools') {
258 warnAboutOption(
259 node.arguments[1],
260 'deps',
261 'withDevtools no longer accepts deps. Call inject() inside the devtools options callback and remove deps.',
262 )
263 }
264 }
265​
266 function warnAboutInjectorArgument(node: ts.CallExpression, name: string) {
267 const argument = injectorArguments[name]
268 if (!argument) return
269 if (node.arguments.some(ts.isSpreadElement)) {
270 warn(
271 node,
272 `Review spread arguments to ${name}; the stable helper no longer accepts an injector argument or injector options.`,
273 )
274 return
275 }
276 if (node.arguments.length <= argument.index) return
277 const guidance =
278 argument.kind === 'injector'
279 ? 'Pass the old injector argument to runInInjectionContext'
280 : 'Pass the old options.injector to runInInjectionContext (not the options object itself)'
281 warn(
282 node,
283 `${name} no longer accepts ${argument.kind === 'injector' ? 'an injector argument' : 'injector options'}. ${guidance}, call ${name} inside its callback, and remove the old argument. If it is undefined or contains no injector, remove it and ensure the call is in an injection context.`,
284 )
285 }
286​
287 function migrateProvider(node: ts.CallExpression) {
288 const first = node.arguments[0]
289 const expression = first && unwrap(first)
290 if (
291 first &&
292 expression &&
293 ts.isNewExpression(expression) &&
294 apiName(expression.expression) === 'QueryClient'
295 ) {
296 edits.push({
297 start: first.getStart(source),
298 end: first.getStart(source),
299 text: '() => ',
300 })
301 } else if (
302 first &&
303 expression &&
304 !ts.isArrowFunction(expression) &&
305 !ts.isFunctionExpression(expression)
306 ) {
307 if (
308 options.unsafeWrapClientReferences &&
309 (ts.isIdentifier(expression) ||
310 ts.isPropertyAccessExpression(expression) ||
311 ts.isElementAccessExpression(expression))
312 ) {
313 edits.push({
314 start: first.getStart(source),
315 end: first.getStart(source),
316 text: '() => ',
317 })
318 warn(
319 first,
320 'Unsafe conversion: wrapped this client reference in a factory. Verify it returns a QueryClient; existing factories must not be wrapped, and injection tokens need () => inject(token).',
321 )
322 } else
323 warn(
324 first,
325 'Client reference may be an instance, token, or factory; provide a client factory manually. Use --unsafe-wrap-client-references only after checking the argument is a QueryClient instance.',
326 )
327 }
328 if (ts.isSpreadElement(node.parent))
329 edits.push({
330 start: node.parent.getStart(source),
331 end: node.getStart(source),
332 text: '',
333 })
334 warn(
335 node,
336 'Verify this provider is in an environment injector; review default SSR hydration and PendingTasks behavior.',
337 )
338 }
339​
340 function unwrap(node: ts.Expression): ts.Expression {
341 return ts.isParenthesizedExpression(node) ||
342 ts.isAsExpression(node) ||
343 ts.isSatisfiesExpression(node) ||
344 ts.isNonNullExpression(node)
345 ? unwrap(node.expression)
346 : node
347 }
348​
349 function property(node: ts.Expression | undefined, name: string) {
350 if (!node) return undefined
351 node = unwrap(node)
352 if (!ts.isObjectLiteralExpression(node)) return undefined
353 return node.properties.find(
354 (
355 entry,
356 ): entry is ts.PropertyAssignment | ts.ShorthandPropertyAssignment =>
357 (ts.isPropertyAssignment(entry) ||
358 ts.isShorthandPropertyAssignment(entry)) &&
359 (ts.isIdentifier(entry.name) || ts.isStringLiteral(entry.name)) &&
360 entry.name.text === name,
361 )
362 }
363​
364 function propertyValue(node: ts.Expression | undefined, name: string) {
365 const entry = property(node, name)
366 return (
367 entry && (ts.isPropertyAssignment(entry) ? entry.initializer : entry.name)
368 )
369 }
370​
371 function warnAboutOption(
372 node: ts.Expression | undefined,
373 name: string,
374 message: string,
375 ) {
376 const entry = property(node, name)
377 if (entry) warn(entry, message)
378 }
379​
380 function warnAboutObserverOptions(node: ts.Expression | undefined) {
381 if (!node) return
382 node = unwrap(node)
383 if (ts.isArrowFunction(node) || ts.isFunctionExpression(node)) {
384 if (ts.isBlock(node.body)) {
385 const returns = (child: ts.Node) => {
386 if (ts.isReturnStatement(child))
387 warnAboutObserverOptions(child.expression)
388 else if (!ts.isFunctionLike(child)) ts.forEachChild(child, returns)
389 }
390 ts.forEachChild(node.body, returns)
391 } else warnAboutObserverOptions(node.body)
392 } else if (ts.isConditionalExpression(node)) {
393 warnAboutObserverOptions(node.whenTrue)
394 warnAboutObserverOptions(node.whenFalse)
395 } else
396 warnAboutOption(
397 node,
398 'throwOnError',
399 'Observer throwOnError was removed. Read the error signal or configure an ErrorHandler through cache callbacks. Imperative refetch throwOnError remains supported.',
400 )
401 }
402​
403 function warnAboutIndirectReference(node: ts.Expression, name: string) {
404 if (ts.isCallExpression(node.parent) && node.parent.expression === node)
405 return
406 if (name === 'injectQueryClient')
407 warn(
408 node,
409 'injectQueryClient was removed. Replace this indirect reference with a function that calls inject(QueryClient), and review its consumers.',
410 )
411 else if (name === 'provideTanStackQuery' || renames[name])
412 warn(
413 node,
414 'Review consumers of this provider reference: provideTanStackQuery expects a QueryClient factory and returns one EnvironmentProviders value.',
415 )
416 else if (injectorArguments[name])
417 warn(
418 node,
419 `Review consumers of this ${name} reference for removed injector arguments${name === 'injectIsFetching' || name === 'injectIsMutating' ? ' and callback-based filters' : ''}.`,
420 )
421 }
422​
423 function migrateClientInjection(node: ts.CallExpression) {
424 if (node.arguments.length !== 0) {
425 warn(
426 node,
427 'Migrate injectQueryClient arguments manually using Angular inject or runInInjectionContext.',
428 )
429 return
430 }
431 const inject = imports.reference('inject', '@angular/core', node)
432 const client = imports.reference('QueryClient', packageName, node)
433 replace(node, `${inject}(${client})`)
434 }
435​
436 function migrateActivityFilter(node: ts.CallExpression) {
437 const first = node.arguments[0]
438 if (!first) return
439 if (ts.isObjectLiteralExpression(first)) {
440 edits.push(
441 {
442 start: first.getStart(source),
443 end: first.getStart(source),
444 text: '() => (',
445 },
446 { start: first.end, end: first.end, text: ')' },
447 )
448 } else if (!ts.isArrowFunction(first) && !ts.isFunctionExpression(first))
449 warn(first, 'Review activity filter: the stable API expects a callback.')
450 }
451​
452 function visit(node: ts.Node) {
453 if (
454 ts.isStringLiteral(node) &&
455 (node.text.startsWith(OLD_PACKAGE) ||
456 (options.migrateQueryCoreImports &&
457 node.text.startsWith(CORE_PACKAGE))) &&
458 !ts.isImportDeclaration(node.parent) &&
459 !ts.isExportDeclaration(node.parent)
460 ) {
461 warn(
462 node,
463 'Review this package reference manually (for example, a dynamic import or require).',
464 )
465 }
466 if (ts.isCallExpression(node)) migrateCall(node)
467 if (ts.isPropertyAccessExpression(node) || ts.isQualifiedName(node)) {
468 const name = apiName(node)
469 if (name) {
470 warnRemovedApi(node, name)
471 if (ts.isPropertyAccessExpression(node)) {
472 if (renames[name]) replace(node.name, renames[name])
473 warnAboutIndirectReference(node, name)
474 }
475 }
476 }
477 if (
478 ts.isIdentifier(node) &&
479 !ts.isImportSpecifier(node.parent) &&
480 !ts.isPropertyAccessExpression(node.parent) &&
481 !ts.isQualifiedName(node.parent) &&
482 !ts.isTypeReferenceNode(node.parent)
483 ) {
484 const name = apiName(node)
485 if (name) warnAboutIndirectReference(node, name)
486 }
487 if (
488 ts.isTypeReferenceNode(node) &&
489 apiName(node.typeName) === 'QueryFeature' &&
490 node.typeArguments?.length
491 )
492 warn(
493 node,
494 'QueryFeature is no longer generic. Remove its type arguments and use features returned by the supported with* functions.',
495 )
496 if (
497 ts.isNewExpression(node) &&
498 apiName(node.expression) === 'QueryClient'
499 ) {
500 const defaults = propertyValue(node.arguments?.[0], 'defaultOptions')
501 warnAboutObserverOptions(propertyValue(defaults, 'queries'))
502 warnAboutObserverOptions(propertyValue(defaults, 'mutations'))
503 }
504 ts.forEachChild(node, visit)
505 }
506 migrateImports()
507 visit(source)
508 const newImports = imports.render()
509 if (newImports) {
510 // Insert after existing statements' leading comments (and a possible shebang).
511 const position = source.statements[0]?.getStart(source) ?? text.length
512 edits.push({ start: position, end: position, text: newImports })
513 }
514 let output = text
515 for (const edit of edits.sort((a, b) => b.start - a.start || b.end - a.end))
516 output = output.slice(0, edit.start) + edit.text + output.slice(edit.end)
517 return { text: output, needsDevtools: result.needsDevtools }