inject.js 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272
  1. const fs = require('fs')
  2. const path = require('path')
  3. const chalk = require('chalk')
  4. const { exec } = require('child_process')
  5. const YAML = require('js-yaml')
  6. const { promisify } = require('util')
  7. const gzipSize = require('gzip-size')
  8. const prettierBytes = require('@transloadit/prettier-bytes')
  9. const browserify = require('browserify')
  10. const touch = require('touch')
  11. const glob = require('glob')
  12. const webRoot = __dirname
  13. const uppyRoot = path.join(__dirname, '../packages/uppy')
  14. const robodogRoot = path.join(__dirname, '../packages/@uppy/robodog')
  15. const localesRoot = path.join(__dirname, '../packages/@uppy/locales')
  16. const configPath = path.join(webRoot, '/themes/uppy/_config.yml')
  17. const { version } = require(path.join(uppyRoot, '/package.json'))
  18. const regionalDisplayNames = new Intl.DisplayNames('en-US', { type: 'region' })
  19. const languageDisplayNames = new Intl.DisplayNames('en-US', { type: 'language' })
  20. const defaultConfig = {
  21. comment: 'Auto updated by inject.js',
  22. uppy_version_anchor: '001',
  23. uppy_version: '0.0.1',
  24. uppy_bundle_kb_sizes: {},
  25. config: {},
  26. }
  27. // Keeping a whitelist so utils etc are excluded
  28. // It may be easier to maintain a blacklist instead
  29. const packages = [
  30. // Bundles
  31. 'uppy',
  32. '@uppy/robodog',
  33. // Integrations
  34. '@uppy/react',
  35. // Core
  36. '@uppy/core',
  37. // Plugins -- please keep these sorted alphabetically
  38. '@uppy/aws-s3',
  39. '@uppy/aws-s3-multipart',
  40. '@uppy/dashboard',
  41. '@uppy/drag-drop',
  42. '@uppy/dropbox',
  43. '@uppy/file-input',
  44. '@uppy/form',
  45. '@uppy/golden-retriever',
  46. '@uppy/google-drive',
  47. '@uppy/informer',
  48. '@uppy/instagram',
  49. '@uppy/image-editor',
  50. '@uppy/progress-bar',
  51. '@uppy/screen-capture',
  52. '@uppy/status-bar',
  53. '@uppy/thumbnail-generator',
  54. '@uppy/transloadit',
  55. '@uppy/tus',
  56. '@uppy/url',
  57. '@uppy/webcam',
  58. '@uppy/xhr-upload',
  59. '@uppy/drop-target',
  60. // Stores
  61. '@uppy/store-default',
  62. '@uppy/store-redux',
  63. ]
  64. const excludes = {
  65. '@uppy/react': ['react'],
  66. }
  67. inject().catch((err) => {
  68. console.error(err)
  69. process.exit(1)
  70. })
  71. async function getMinifiedSize (pkg, name) {
  72. const b = browserify(pkg)
  73. const packageJSON = fs.readFileSync(path.join(pkg, 'package.json'))
  74. const version = JSON.parse(packageJSON).version
  75. if (name !== '@uppy/core' && name !== 'uppy') {
  76. b.exclude('@uppy/core')
  77. // Already unconditionally included through @uppy/core
  78. b.exclude('preact')
  79. }
  80. if (excludes[name]) {
  81. b.exclude(excludes[name])
  82. }
  83. b.plugin('tinyify')
  84. const bundle = await promisify(b.bundle).call(b)
  85. const gzipped = await gzipSize(bundle)
  86. return {
  87. minified: bundle.length,
  88. gzipped,
  89. version,
  90. }
  91. }
  92. async function injectSizes (config) {
  93. console.info(chalk.grey('Generating bundle sizes…'))
  94. const padTarget = packages.reduce((max, cur) => Math.max(max, cur.length), 0) + 2
  95. const sizesPromise = Promise.all(
  96. packages.map(async (pkg) => {
  97. const result = await getMinifiedSize(path.join(__dirname, '../packages', pkg), pkg)
  98. console.info(chalk.green(
  99. // ✓ @uppy/pkgname: 10.0 kB min / 2.0 kB gz
  100. ` ✓ ${pkg}: ${' '.repeat(padTarget - pkg.length)}${
  101. `${prettierBytes(result.minified)} min`.padEnd(10)
  102. } / ${prettierBytes(result.gzipped)} gz`
  103. ))
  104. return Object.assign(result, {
  105. prettyMinified: prettierBytes(result.minified),
  106. prettyGzipped: prettierBytes(result.gzipped),
  107. })
  108. })
  109. ).then((list) => {
  110. const map = {}
  111. list.forEach((size, i) => {
  112. map[packages[i]] = size
  113. })
  114. return map
  115. })
  116. config.uppy_bundle_kb_sizes = await sizesPromise
  117. }
  118. async function injectBundles () {
  119. const cmds = [
  120. `mkdir -p ${path.join(webRoot, '/themes/uppy/source/uppy')}`,
  121. `mkdir -p ${path.join(webRoot, '/themes/uppy/source/uppy/locales')}`,
  122. `cp -vfR ${path.join(uppyRoot, '/dist/*')} ${path.join(webRoot, '/themes/uppy/source/uppy/')}`,
  123. `cp -vfR ${path.join(robodogRoot, '/dist/*')} ${path.join(webRoot, '/themes/uppy/source/uppy/')}`,
  124. `cp -vfR ${path.join(localesRoot, '/dist/*')} ${path.join(webRoot, '/themes/uppy/source/uppy/locales')}`,
  125. ].join(' && ')
  126. const { stdout } = await promisify(exec)(cmds)
  127. stdout.trim().split('\n').forEach((line) => {
  128. console.info(chalk.green('✓ injected: '), chalk.grey(line))
  129. })
  130. }
  131. // re-enable after rate limiter issue is fixed
  132. //
  133. async function injectGhStars () {
  134. const opts = {}
  135. if ('GITHUB_TOKEN' in process.env) {
  136. opts.auth = process.env.GITHUB_TOKEN
  137. }
  138. const { Octokit } = require('@octokit/rest')
  139. const octokit = new Octokit(opts)
  140. const { headers, data } = await octokit.repos.get({
  141. owner: 'transloadit',
  142. repo: 'uppy',
  143. })
  144. console.log(`${headers['x-ratelimit-remaining']} requests remaining until we hit GitHub ratelimiter`)
  145. const dstpath = path.join(webRoot, 'themes', 'uppy', 'layout', 'partials', 'generated_stargazers.ejs')
  146. fs.writeFileSync(dstpath, String(data.stargazers_count), 'utf-8')
  147. console.log(`${data.stargazers_count} stargazers written to '${dstpath}'`)
  148. }
  149. async function injectMarkdown () {
  150. const sources = {
  151. '.github/ISSUE_TEMPLATE/integration_help.md': 'src/_template/integration_help.md',
  152. '.github/CONTRIBUTING.md': 'src/_template/contributing.md',
  153. }
  154. for (const src in sources) {
  155. const dst = sources[src]
  156. // strip yaml frontmatter:
  157. const srcpath = path.join(uppyRoot, `/../../${src}`)
  158. const dstpath = path.join(webRoot, dst)
  159. const parts = fs.readFileSync(srcpath, 'utf-8').split(/---\s*\n/)
  160. if (parts.length >= 3) {
  161. parts.shift()
  162. parts.shift()
  163. }
  164. let content = `<!-- WARNING! This file was injected. Please edit in "${src}" instead and run "${path.basename(__filename)}" -->\n\n`
  165. content += parts.join('---\n')
  166. fs.writeFileSync(dstpath, content, 'utf-8')
  167. console.info(chalk.green('✓ injected: '), chalk.grey(srcpath))
  168. }
  169. touch(path.join(webRoot, '/src/support.md'))
  170. }
  171. function injectLocaleList () {
  172. const mdTable = [
  173. `<!-- WARNING! This file was automatically injected. Please run "${path.basename(__filename)}" to re-generate -->\n\n`,
  174. '| %count% Locales | NPM | CDN | Source on GitHub |',
  175. '| --------------- | ------------------ | ------------------- | ---------------- |',
  176. ]
  177. const mdRows = []
  178. const localeList = {}
  179. const localePackagePath = path.join(localesRoot, 'src', '*.js')
  180. const localePackageVersion = require(path.join(localesRoot, 'package.json')).version
  181. glob.sync(localePackagePath).forEach((localePath) => {
  182. const localeName = path.basename(localePath, '.js')
  183. // we renamed the es_GL → gl_ES locale, and kept the old name
  184. // for backwards-compat, see https://github.com/transloadit/uppy/pull/1929
  185. if (localeName === 'es_GL') return
  186. const [languageCode, regionCode, variant] = localeName.split(/[-_]/)
  187. const languageName = languageDisplayNames.of(languageCode)
  188. const regionName = regionalDisplayNames.of(regionCode)
  189. const npmPath = `<code class="raw"><a href="https://www.npmjs.com/package/@uppy/locales">@uppy/locales</a>/lib/${localeName}</code>`
  190. const cdnPath = `[\`${localeName}.min.js\`](https://releases.transloadit.com/uppy/locales/v${localePackageVersion}/${localeName}.min.js)`
  191. const githubSource = `[\`${localeName}.js\`](https://github.com/transloadit/uppy/blob/master/packages/%40uppy/locales/src/${localeName}.js)`
  192. const mdTableRow = `| ${languageName}<br/> <small>${regionName}</small>${variant ? `<br /><small>(${variant})</small>` : ''} | ${npmPath} | ${cdnPath} | ✏️ ${githubSource} |`
  193. mdRows.push(mdTableRow)
  194. localeList[localeName] = `${languageName} (${regionName}${variant ? `, ${variant}` : ''})`
  195. })
  196. const resultingMdTable = mdTable.concat(mdRows.sort()).join('\n').replace('%count%', mdRows.length)
  197. const dstpath = path.join(webRoot, 'src', '_template', 'list_of_locale_packs.md')
  198. const localeListDstPath = path.join(webRoot, 'src', 'examples', 'locale_list.json')
  199. fs.writeFileSync(dstpath, resultingMdTable, 'utf-8')
  200. console.info(chalk.green('✓ injected: '), chalk.grey(dstpath))
  201. fs.writeFileSync(localeListDstPath, JSON.stringify(localeList), 'utf-8')
  202. console.info(chalk.green('✓ injected: '), chalk.grey(localeListDstPath))
  203. }
  204. async function readConfig () {
  205. try {
  206. const buf = await promisify(fs.readFile)(configPath, 'utf8')
  207. return YAML.safeLoad(buf)
  208. } catch (err) {
  209. return {}
  210. }
  211. }
  212. async function inject () {
  213. const config = await readConfig()
  214. await injectGhStars()
  215. await injectMarkdown()
  216. injectLocaleList()
  217. config.uppy_version = version
  218. config.uppy_version_anchor = version.replace(/[^\d]+/g, '')
  219. await injectSizes(config)
  220. const saveConfig = { ...defaultConfig, ...config }
  221. await promisify(fs.writeFile)(configPath, YAML.safeDump(saveConfig), 'utf-8')
  222. console.info(chalk.green('✓ rewritten: '), chalk.grey(configPath))
  223. try {
  224. await injectBundles()
  225. } catch (error) {
  226. console.error(
  227. chalk.red('x failed to inject: '),
  228. chalk.grey(`uppy bundle into site, because: ${error}`)
  229. )
  230. process.exit(1)
  231. }
  232. }