build-lib.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269
  1. const chalk = require('chalk')
  2. const babel = require('@babel/core')
  3. const t = require('@babel/types')
  4. const { promisify } = require('util')
  5. const glob = promisify(require('glob'))
  6. const fs = require('fs')
  7. const path = require('path')
  8. const { mkdir, stat, writeFile } = fs.promises
  9. const PACKAGE_JSON_IMPORT = /^\..*\/package.json$/
  10. const SOURCE = 'packages/{*,@uppy/*}/src/**/*.js?(x)'
  11. // Files not to build (such as tests)
  12. const IGNORE = /\.test\.js$|__mocks__|svelte|angular|companion\//
  13. // Files that should trigger a rebuild of everything on change
  14. const META_FILES = [
  15. 'babel.config.js',
  16. 'package.json',
  17. 'package-lock.json',
  18. 'yarn.lock',
  19. 'bin/build-lib.js',
  20. ]
  21. // Rollup uses get-form-data's ES modules build, and rollup-plugin-commonjs automatically resolves `.default`.
  22. // So, if we are being built using rollup, this require() won't have a `.default` property.
  23. const esPackagesThatNeedSpecialTreatmentForRollupInterop = [
  24. 'get-form-data',
  25. ]
  26. function lastModified (file, createParentDir = false) {
  27. return stat(file).then((s) => s.mtime, async (err) => {
  28. if (err.code === 'ENOENT') {
  29. if (createParentDir) {
  30. await mkdir(path.dirname(file), { recursive: true })
  31. }
  32. return 0
  33. }
  34. throw err
  35. })
  36. }
  37. const moduleTypeCache = new Map()
  38. const versionCache = new Map()
  39. async function isTypeModule (file) {
  40. const packageFolder = file.slice(0, file.indexOf('/src/'))
  41. const cachedValue = moduleTypeCache.get(packageFolder)
  42. if (cachedValue != null) return cachedValue
  43. // eslint-disable-next-line import/no-dynamic-require, global-require
  44. const { type, version } = require(path.join(__dirname, '..', packageFolder, 'package.json'))
  45. const typeModule = type === 'module'
  46. if (process.env.FRESH) {
  47. // in case it hasn't been done before.
  48. await mkdir(path.join(packageFolder, 'lib'), { recursive: true })
  49. }
  50. if (typeModule) {
  51. await writeFile(path.join(packageFolder, 'lib', 'package.json'), '{"type":"commonjs"}')
  52. }
  53. moduleTypeCache.set(packageFolder, typeModule)
  54. versionCache.set(packageFolder, version)
  55. return typeModule
  56. }
  57. // eslint-disable-next-line no-shadow
  58. function ExportAllDeclaration (path) {
  59. const { value } = path.node.source
  60. if (value.endsWith('.jsx') && (value.startsWith('./') || value.startsWith('../'))) {
  61. // Rewrite .jsx imports to .js:
  62. path.node.source.value = value.slice(0, -1) // eslint-disable-line no-param-reassign
  63. }
  64. path.replaceWith(
  65. t.assignmentExpression(
  66. '=',
  67. t.memberExpression(t.identifier('module'), t.identifier('exports')),
  68. t.callExpression(t.identifier('require'), [path.node.source]),
  69. ),
  70. )
  71. }
  72. async function buildLib () {
  73. const metaMtimes = await Promise.all(META_FILES.map((filename) => lastModified(path.join(__dirname, '..', filename))))
  74. const metaMtime = Math.max(...metaMtimes)
  75. const files = await glob(SOURCE)
  76. /* eslint-disable no-continue */
  77. for (const file of files) {
  78. if (IGNORE.test(file)) {
  79. continue
  80. }
  81. const libFile = file.replace('/src/', '/lib/').replace(/\.jsx$/, '.js')
  82. // on a fresh build, rebuild everything.
  83. if (!process.env.FRESH) {
  84. const [srcMtime, libMtime] = await Promise.all([
  85. lastModified(file),
  86. lastModified(libFile, true),
  87. ])
  88. // Skip files that haven't changed
  89. if (srcMtime < libMtime && metaMtime < libMtime) {
  90. continue
  91. }
  92. }
  93. let idCounter = 0 // counter to ensure uniqueness of identifiers created by the build script.
  94. const plugins = await isTypeModule(file) ? [['@babel/plugin-transform-modules-commonjs', {
  95. importInterop: 'none',
  96. }], {
  97. visitor: {
  98. // eslint-disable-next-line no-shadow
  99. ImportDeclaration (path) {
  100. let { value } = path.node.source
  101. if (value.endsWith('.jsx') && (value.startsWith('./') || value.startsWith('../'))) {
  102. // Rewrite .jsx imports to .js:
  103. value = path.node.source.value = value.slice(0, -1) // eslint-disable-line no-param-reassign,no-multi-assign
  104. }
  105. if (PACKAGE_JSON_IMPORT.test(value)
  106. && path.node.specifiers.length === 1
  107. && path.node.specifiers[0].type === 'ImportDefaultSpecifier') {
  108. // Vendor-in version number from package.json files:
  109. const version = versionCache.get(file.slice(0, file.indexOf('/src/')))
  110. if (version != null) {
  111. const [{ local }] = path.node.specifiers
  112. path.replaceWith(
  113. t.variableDeclaration('const', [t.variableDeclarator(local,
  114. t.objectExpression([
  115. t.objectProperty(t.stringLiteral('version'), t.stringLiteral(version)),
  116. ]))]),
  117. )
  118. }
  119. } else if (path.node.specifiers[0].type === 'ImportDefaultSpecifier') {
  120. const [{ local }, ...otherSpecifiers] = path.node.specifiers
  121. if (otherSpecifiers.length === 1 && otherSpecifiers[0].type === 'ImportNamespaceSpecifier') {
  122. // import defaultVal, * as namespaceImport from '@uppy/package'
  123. // is transformed into:
  124. // const defaultVal = require('@uppy/package'); const namespaceImport = defaultVal
  125. path.insertAfter(
  126. t.variableDeclaration('const', [
  127. t.variableDeclarator(
  128. otherSpecifiers[0].local,
  129. local,
  130. ),
  131. ]),
  132. )
  133. } else if (otherSpecifiers.length !== 0) {
  134. // import defaultVal, { exportedVal as importedName, other } from '@uppy/package'
  135. // is transformed into:
  136. // const defaultVal = require('@uppy/package'); const { exportedVal: importedName, other } = defaultVal
  137. path.insertAfter(t.variableDeclaration('const', [t.variableDeclarator(
  138. t.objectPattern(
  139. otherSpecifiers.map(specifier => t.objectProperty(
  140. t.identifier(specifier.imported.name),
  141. specifier.local,
  142. )),
  143. ),
  144. local,
  145. )]))
  146. }
  147. let requireCall = t.callExpression(t.identifier('require'), [
  148. t.stringLiteral(value),
  149. ])
  150. if (esPackagesThatNeedSpecialTreatmentForRollupInterop.includes(value)) {
  151. requireCall = t.logicalExpression('||', t.memberExpression(requireCall, t.identifier('default')), requireCall)
  152. }
  153. path.replaceWith(
  154. t.variableDeclaration('const', [
  155. t.variableDeclarator(
  156. local,
  157. requireCall,
  158. ),
  159. ]),
  160. )
  161. }
  162. },
  163. ExportAllDeclaration,
  164. // eslint-disable-next-line no-shadow,consistent-return
  165. ExportNamedDeclaration (path) {
  166. if (path.node.source != null) {
  167. if (path.node.specifiers.length === 1
  168. && path.node.specifiers[0].local.name === 'default'
  169. && path.node.specifiers[0].exported.name === 'default') return ExportAllDeclaration(path)
  170. if (path.node.specifiers.some(spec => spec.exported.name === 'default')) {
  171. throw new Error('unsupported mix of named and default re-exports')
  172. }
  173. let { value } = path.node.source
  174. if (value.endsWith('.jsx') && (value.startsWith('./') || value.startsWith('../'))) {
  175. // Rewrite .jsx imports to .js:
  176. value = path.node.source.value = value.slice(0, -1) // eslint-disable-line no-param-reassign,no-multi-assign
  177. }
  178. // If there are no default export/import involved, Babel can handle it with no problem.
  179. if (path.node.specifiers.every(spec => spec.local.name !== 'default' && spec.exported.name !== 'default')) return undefined
  180. let requireCall = t.callExpression(t.identifier('require'), [
  181. t.stringLiteral(value),
  182. ])
  183. if (esPackagesThatNeedSpecialTreatmentForRollupInterop.includes(value)) {
  184. requireCall = t.logicalExpression('||', t.memberExpression(requireCall, t.identifier('default')), requireCall)
  185. }
  186. const requireCallIdentifier = t.identifier(`_${idCounter++}`)
  187. const namedExportIdentifiers = path.node.specifiers
  188. .filter(spec => spec.local.name !== 'default')
  189. .map(spec => [
  190. t.identifier(requireCallIdentifier.name + spec.local.name),
  191. t.memberExpression(requireCallIdentifier, spec.local),
  192. spec,
  193. ])
  194. path.insertBefore(
  195. t.variableDeclaration('const', [
  196. t.variableDeclarator(
  197. requireCallIdentifier,
  198. requireCall,
  199. ),
  200. ...namedExportIdentifiers.map(([id, propertyAccessor]) => t.variableDeclarator(id, propertyAccessor)),
  201. ]),
  202. )
  203. path.replaceWith(
  204. t.exportNamedDeclaration(null, path.node.specifiers.map(spec => t.exportSpecifier(
  205. spec.local.name === 'default' ? requireCallIdentifier : namedExportIdentifiers.find(([,, s]) => s === spec)[0],
  206. spec.exported,
  207. ))),
  208. )
  209. }
  210. },
  211. // eslint-disable-next-line no-shadow
  212. ExportDefaultDeclaration (path) {
  213. const moduleExports = t.memberExpression(t.identifier('module'), t.identifier('exports'))
  214. if (!t.isDeclaration(path.node.declaration)) {
  215. path.replaceWith(
  216. t.assignmentExpression('=', moduleExports, path.node.declaration),
  217. )
  218. } else if (path.node.declaration.id != null) {
  219. const { id } = path.node.declaration
  220. path.insertBefore(path.node.declaration)
  221. path.replaceWith(
  222. t.assignmentExpression('=', moduleExports, id),
  223. )
  224. } else {
  225. const id = t.identifier('_default')
  226. path.node.declaration.id = id // eslint-disable-line no-param-reassign
  227. path.insertBefore(path.node.declaration)
  228. path.replaceWith(
  229. t.assignmentExpression('=', moduleExports, id),
  230. )
  231. }
  232. },
  233. },
  234. }] : undefined
  235. const { code, map } = await babel.transformFileAsync(file, { sourceMaps: true, plugins })
  236. await Promise.all([
  237. writeFile(libFile, code),
  238. writeFile(`${libFile}.map`, JSON.stringify(map)),
  239. ])
  240. console.log(chalk.green('Compiled lib:'), chalk.magenta(libFile))
  241. }
  242. /* eslint-enable no-continue */
  243. }
  244. console.log('Using Babel version:', require('@babel/core/package.json').version)
  245. buildLib().catch((err) => {
  246. console.error(err)
  247. process.exit(1)
  248. })