index.mjs 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152
  1. #!/usr/bin/env node
  2. /**
  3. * This script can be used to initiate the transition for a plugin from ESM source to
  4. * TS source. It will rename the files, update the imports, and add a `tsconfig.json`.
  5. */
  6. import { opendir, readFile, open, writeFile, rm } from 'node:fs/promises'
  7. import { createRequire } from 'node:module'
  8. import { argv } from 'node:process'
  9. import { basename, extname, join } from 'node:path'
  10. import { existsSync } from 'node:fs'
  11. const packageRoot = new URL(`../../packages/${argv[2]}/`, import.meta.url)
  12. let dir
  13. try {
  14. dir = await opendir(new URL('./src/', packageRoot), { recursive: true })
  15. } catch (cause) {
  16. throw new Error(`Unable to find package "${argv[2]}"`, { cause })
  17. }
  18. const packageJSON = JSON.parse(
  19. await readFile(new URL('./package.json', packageRoot), 'utf-8'),
  20. )
  21. if (packageJSON.type !== 'module') {
  22. throw new Error('Cannot convert non-ESM package to TS')
  23. }
  24. const uppyDeps = new Set(
  25. Object.keys(packageJSON.dependencies || {})
  26. .concat(Object.keys(packageJSON.peerDependencies || {}))
  27. .concat(Object.keys(packageJSON.devDependencies || {}))
  28. .filter((pkg) => pkg.startsWith('@uppy/')),
  29. )
  30. // We want TS to check the source files so it doesn't use outdated (or missing) types:
  31. const paths = Object.fromEntries(
  32. (function* generatePaths() {
  33. const require = createRequire(packageRoot)
  34. for (const pkg of uppyDeps) {
  35. const nickname = pkg.slice('@uppy/'.length)
  36. // eslint-disable-next-line import/no-dynamic-require
  37. const pkgJson = require(`../${nickname}/package.json`)
  38. if (pkgJson.main) {
  39. yield [
  40. pkg,
  41. [`../${nickname}/${pkgJson.main.replace(/^(\.\/)?lib\//, 'src/')}`],
  42. ]
  43. }
  44. yield [`${pkg}/lib/*`, [`../${nickname}/src/*`]]
  45. }
  46. })(),
  47. )
  48. const references = Array.from(uppyDeps, (pkg) => ({
  49. path: `../${pkg.slice('@uppy/'.length)}/tsconfig.build.json`,
  50. }))
  51. const depsNotYetConvertedToTS = references.filter(
  52. (ref) => !existsSync(new URL(ref.path, packageRoot)),
  53. )
  54. if (depsNotYetConvertedToTS.length) {
  55. // We need to first convert the dependencies, otherwise we won't be working with the correct types.
  56. throw new Error('Some dependencies have not yet been converted to TS', {
  57. cause: depsNotYetConvertedToTS.map((ref) =>
  58. ref.path.replace(/^\.\./, '@uppy'),
  59. ),
  60. })
  61. }
  62. let tsConfig
  63. try {
  64. tsConfig = await open(new URL('./tsconfig.json', packageRoot), 'wx')
  65. } catch (cause) {
  66. throw new Error('It seems this package has already been transitioned to TS', {
  67. cause,
  68. })
  69. }
  70. for await (const dirent of dir) {
  71. if (!dirent.isDirectory()) {
  72. const { name } = dirent
  73. const ext = extname(name)
  74. if (ext !== '.js' && ext !== '.jsx') continue // eslint-disable-line no-continue
  75. const filePath =
  76. basename(dirent.path) === name
  77. ? dirent.path // Some versions of Node.js give the full path as dirent.path.
  78. : join(dirent.path, name) // Others supply only the path to the parent.
  79. await writeFile(
  80. `${filePath.slice(0, -ext.length)}${ext.replace('js', 'ts')}`,
  81. (await readFile(filePath, 'utf-8'))
  82. .replace(
  83. // The following regex aims to capture all imports and reexports of local .js(x) files to replace it to .ts(x)
  84. // It's far from perfect and will have false positives and false negatives.
  85. /((?:^|\n)(?:import(?:\s+\w+\s+from)?|export\s*\*\s*from|(?:import|export)\s*(?:\{[^}]*\}|\*\s*as\s+\w+\s)\s*from)\s*["']\.\.?\/[^'"]+\.)js(x?["'])/g, // eslint-disable-line max-len
  86. '$1ts$2',
  87. )
  88. .replace(
  89. // The following regex aims to capture all local package.json imports.
  90. /\nimport \w+ from ['"]..\/([^'"]+\/)*package.json['"]\n/g,
  91. (originalImport) =>
  92. `// eslint-disable-next-line @typescript-eslint/ban-ts-comment\n` +
  93. `// @ts-ignore We don't want TS to generate types for the package.json${originalImport}`,
  94. ),
  95. )
  96. await rm(filePath)
  97. }
  98. }
  99. await tsConfig.writeFile(
  100. `${JSON.stringify(
  101. {
  102. extends: '../../../tsconfig.shared',
  103. compilerOptions: {
  104. emitDeclarationOnly: false,
  105. noEmit: true,
  106. paths,
  107. },
  108. include: ['./package.json', './src/**/*.*'],
  109. references,
  110. },
  111. undefined,
  112. 2,
  113. )}\n`,
  114. )
  115. await tsConfig.close()
  116. await writeFile(
  117. new URL('./tsconfig.build.json', packageRoot),
  118. `${JSON.stringify(
  119. {
  120. extends: '../../../tsconfig.shared',
  121. compilerOptions: {
  122. noImplicitAny: false,
  123. outDir: './lib',
  124. paths,
  125. resolveJsonModule: false,
  126. rootDir: './src',
  127. skipLibCheck: true,
  128. },
  129. include: ['./src/**/*.*'],
  130. exclude: ['./src/**/*.test.ts'],
  131. references,
  132. },
  133. undefined,
  134. 2,
  135. )}\n`,
  136. )
  137. console.log('Done')