All files / v5/rename-hydrate rename-hydrate.js

0% Statements 0/18
0% Branches 0/4
0% Functions 0/3
0% Lines 0/18

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56                                                                                                               
module.exports = (file, api) => {
  const jscodeshift = api.jscodeshift
  const root = jscodeshift(file.source)
 
  const importSpecifiers = root
    .find(jscodeshift.ImportDeclaration, {
      source: {
        value: '@tanstack/react-query',
      },
    })
    .find(jscodeshift.ImportSpecifier, {
      imported: {
        name: 'Hydrate',
      },
    })
 
  if (importSpecifiers.length > 0) {
    const names = {
      searched: 'Hydrate', // By default, we want to replace the `Hydrate` usages.
      target: 'HydrationBoundary', // We want to replace them with `HydrationBoundary`.
    }
 
    importSpecifiers.replaceWith(({ node: mutableNode }) => {
      /**
       * When the local and imported names match which means the code doesn't contain import aliases, we need
       * to replace only the import specifier.
       * @type {boolean}
       */
      const usesDefaultImport =
        mutableNode.local.name === mutableNode.imported.name
 
      if (!usesDefaultImport) {
        // If the code uses import aliases, we must re-use the alias.
        names.searched = mutableNode.local.name
        names.target = mutableNode.local.name
      }
 
      // Override the import specifier.
      mutableNode.imported.name = 'HydrationBoundary'
 
      return mutableNode
    })
 
    root
      .findJSXElements(names.searched)
      .replaceWith(({ node: mutableNode }) => {
        mutableNode.openingElement.name.name = names.target
        mutableNode.closingElement.name.name = names.target
 
        return mutableNode
      })
  }
 
  return root.toSource({ quote: 'single', lineTerminator: '\n' })
}