import fs from 'fs' ; import { join , dirname } from 'path' ; import jscodeshift , { API , FileInfo , Options } from 'jscodeshift' ; import { addNamedImport } from '@codemods/add-named-import' ; import { getConfig , getRelativePathname } from '@codemods/utils' ; import { getExportMapDeclaration } from './getExportMapDeclaration' ; const cwd = process . cwd ( ) ; export const parser = 'tsx' ; const jj = jscodeshift . withParser ( parser ) ; const empty = ( ) => { } ; const stats = ( name , quantity ) => { quantity = typeof quantity !== 'number' ? 1 : quantity ; console . log ( 'update: ' , { name , quantity } ) ; } ; type ModuleToRelativeConfig = { packageName : string ; indexPath : string ; } ; function transform ( file , api , options ) { const j = api . jscodeshift ; const root = j ( file . source ) ; const printOptions = options . printOptions || { quote : 'single' , trailingComma : false , lineTerminator : '\n' } ; const config = getConfig < ModuleToRelativeConfig > ( options , { } ) ; const indexFile = join ( cwd , config . indexPath ) ; const content = fs . readFileSync ( indexFile ) ; const source = content . toString ( ) ; const exportsMap = getExportMapDeclaration ( { path : indexFile , source } , { jj , jscodeshift : jj , stats : options . dry ? stats : empty , report : ( ) => { } } , { } ) ; root . find ( j . ImportDeclaration ) . filter ( ( path ) => { if ( path . node . source . value === config . packageName ) { return true ; } return false ; } ) . forEach ( ( path ) => { for ( const specifier of path . node . specifiers ) { const imported = specifier . imported . name ; const local = specifier . local . name ; const newImportMap = exportsMap [ imported ] ; const source = join ( dirname ( config . indexPath ) , newImportMap . source ) ; if ( ! newImportMap ) { console . log ( 'export not found: ' , { local , imported } ) ; return ; } const relative = getRelativePathname ( file . path , source , false ) ; if ( newImportMap . local === 'default' ) { addNamedImport ( { root , j , importName : relative , defaultName : imported } ) ; } else { addNamedImport ( { root , j , importName : relative , localName : local , specifier : imported } ) ; } } j ( path ) . remove ( ) ; } ) ; return root . toSource ( printOptions ) ; } export default transform ;