esm-check-migration.js 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260
  1. const fs = require('fs')
  2. const path = require('path')
  3. const minimist = require('minimist')
  4. const APP_CODE_PATH = ['app', 'modules']
  5. const {
  6. _: args,
  7. files,
  8. help,
  9. json,
  10. } = minimist(process.argv.slice(2), {
  11. boolean: ['files', 'help', 'json'],
  12. alias: {
  13. files: 'f',
  14. help: 'h',
  15. json: 'j',
  16. },
  17. default: {
  18. _: ['app', 'modules'],
  19. files: false,
  20. help: false,
  21. json: false,
  22. },
  23. })
  24. const paths = args.length > 0 ? args : APP_CODE_PATH
  25. function usage() {
  26. console.error(`Usage: node check-esm-migration.js [OPTS...] dir1 dir2
  27. node check-esm-migration.js file
  28. Usage with directories
  29. ----------------------
  30. When the arguments are a list of directories it prints the status of ES Modules migration within those directories.
  31. When no directory is provided, it checks app/ and modules/, which represent the entire codebase.
  32. With the --files (-f) option, it prints the list of JS files that:
  33. - Are not migrated to ESM
  34. - Are not required by any file that is not migrated yet to ESM (in the entire codebase)
  35. These files should be the most immediate candidates to be migrated.
  36. WARNING: please note that this script only looks up literals in require() statements, so paths
  37. built dynamically (such as those in infrastructure/Modules.js) are not being taken into account.
  38. Usage with a JS file
  39. --------------------
  40. When the argument is a JS file, the script outputs the files that depend on this file that have not been converted
  41. yet to ES Modules.
  42. The files in the list must to be converted to ES Modules before converting the JS file.
  43. Example:
  44. node scrips/check-esm-migration.js --files modules/admin-panel
  45. node scrips/check-esm-migration.js app/src/router.js
  46. Options:
  47. --files Prints the files that are not imported by app code via CommonJS
  48. --json Prints the result in JSON format, including the list of files from --files
  49. --help Prints this help
  50. `)
  51. }
  52. function resolveImportPaths(dir, file) {
  53. const absolutePath = path.resolve(dir, file)
  54. if (fs.existsSync(absolutePath)) {
  55. return absolutePath
  56. } else if (fs.existsSync(absolutePath + '.js')) {
  57. return absolutePath + '.js'
  58. } else if (fs.existsSync(absolutePath + '.mjs')) {
  59. return absolutePath + '.mjs'
  60. } else {
  61. return null
  62. }
  63. }
  64. function collectJsFiles(dir, files = []) {
  65. const items = fs.readdirSync(dir)
  66. items.forEach(item => {
  67. const fullPath = path.join(dir, item)
  68. const stat = fs.statSync(fullPath)
  69. if (stat.isDirectory()) {
  70. const basename = path.basename(fullPath)
  71. // skipping 'test' and 'frontend' directories from search
  72. if (basename !== 'test' && basename !== 'frontend') {
  73. collectJsFiles(fullPath, files)
  74. }
  75. } else if (
  76. stat.isFile() &&
  77. (fullPath.endsWith('.js') || fullPath.endsWith('.mjs'))
  78. ) {
  79. files.push(fullPath)
  80. }
  81. })
  82. return files
  83. }
  84. function extractImports(filePath) {
  85. const fileContent = fs.readFileSync(filePath, 'utf-8')
  86. // not 100% compliant (string escaping, etc.) but does the work here
  87. const contentWithoutComments = fileContent.replace(
  88. /\/\/.*|\/\*[\s\S]*?\*\//g,
  89. ''
  90. )
  91. const requireRegex = /require\s*\(\s*['"](.+?)['"]\s*\)/g
  92. const dependencies = []
  93. while (true) {
  94. const match = requireRegex.exec(contentWithoutComments)
  95. if (!match) {
  96. break
  97. }
  98. dependencies.push(match[1])
  99. }
  100. // build absolute path for the imported file
  101. return dependencies
  102. .map(depPath => resolveImportPaths(path.dirname(filePath), depPath))
  103. .filter(path => path !== null)
  104. }
  105. // Main function to process a list of directories and create the Map of dependencies
  106. function findJSAndImports(directories) {
  107. const fileDependenciesMap = new Map()
  108. directories.forEach(dir => {
  109. if (fs.existsSync(dir)) {
  110. const jsFiles = collectJsFiles(dir)
  111. jsFiles.forEach(filePath => {
  112. const imports = extractImports(filePath)
  113. fileDependenciesMap.set(filePath, imports)
  114. })
  115. } else {
  116. console.error(`Directory not found: ${dir}`)
  117. process.exit(1)
  118. }
  119. })
  120. return fileDependenciesMap
  121. }
  122. function printDirectoriesReport(allFilesAndImports) {
  123. // collect all files that are imported via CommonJS in the entire backend codebase
  124. const filesImportedViaCjs = new Set()
  125. allFilesAndImports.forEach((imports, file) => {
  126. if (!file.endsWith('.mjs')) {
  127. imports.forEach(imprt => filesImportedViaCjs.add(imprt))
  128. }
  129. })
  130. // collect js files from the selected paths
  131. const selectedFiles = Array.from(
  132. findJSAndImports(paths.map(dir => path.resolve(dir))).keys()
  133. )
  134. const nonMigratedFiles = selectedFiles.filter(file => !file.endsWith('.mjs'))
  135. const migratedFileCount = selectedFiles.filter(file =>
  136. file.endsWith('.mjs')
  137. ).length
  138. // collect files in the selected paths that are not imported via CommonJs in the entire backend codebase
  139. const filesNotImportedViaCjs = nonMigratedFiles.filter(
  140. file => !filesImportedViaCjs.has(file)
  141. )
  142. if (json) {
  143. console.log(
  144. JSON.stringify(
  145. {
  146. fileCount: selectedFiles.length,
  147. migratedFileCount,
  148. filesNotImportedViaCjs,
  149. },
  150. null,
  151. 2
  152. )
  153. )
  154. } else {
  155. console.log(`Found ${selectedFiles.length} files in ${paths}:
  156. - ${migratedFileCount} have been migrated to ES Modules (progress=${((migratedFileCount / selectedFiles.length) * 100).toFixed(2)}%)
  157. - ${filesNotImportedViaCjs.length} are ready to migrate (these are not imported via CommonJS in the entire codebase)
  158. `)
  159. if (files) {
  160. console.log(`Files that are ready to migrate:`)
  161. filesNotImportedViaCjs.forEach(file =>
  162. console.log(` - ${file.replace(process.cwd() + '/', '')}`)
  163. )
  164. }
  165. }
  166. }
  167. function printFileReport(allFilesAndImports) {
  168. const filePath = path.resolve(paths[0])
  169. if (filePath.endsWith('.mjs')) {
  170. console.log(`${filePath} is already migrated to ESM`)
  171. return
  172. }
  173. const filePathWithoutExtension = filePath.replace('.js', '')
  174. const importingFiles = []
  175. allFilesAndImports.forEach((imports, file) => {
  176. if (file.endsWith('.mjs')) {
  177. return
  178. }
  179. if (
  180. imports.some(
  181. imprt => imprt === filePath || imprt === filePathWithoutExtension
  182. )
  183. ) {
  184. importingFiles.push(file)
  185. }
  186. })
  187. if (json) {
  188. console.log(
  189. JSON.stringify(
  190. {
  191. importingFiles,
  192. },
  193. null,
  194. 2
  195. )
  196. )
  197. } else {
  198. console.log(`${filePath} is required by ${importingFiles.length} CJS file`)
  199. importingFiles.forEach(file =>
  200. console.log(` - ${file.replace(process.cwd() + '/', '')}`)
  201. )
  202. }
  203. }
  204. function main() {
  205. if (help) {
  206. usage()
  207. process.exit(0)
  208. }
  209. // collect all the js files in the entire backend codebase (app/ + modules/) with its imports
  210. const allFilesAndImports = findJSAndImports(
  211. APP_CODE_PATH.map(dir => path.resolve(dir))
  212. )
  213. const entryPoint = fs.existsSync('app.js') ? 'app.js' : 'app.mjs'
  214. allFilesAndImports.set(path.resolve(entryPoint), extractImports(entryPoint))
  215. const isFileReport = fs.statSync(paths[0]).isFile()
  216. if (isFileReport) {
  217. printFileReport(allFilesAndImports)
  218. } else {
  219. printDirectoriesReport(allFilesAndImports)
  220. }
  221. }
  222. main()