inject.js 8.0 KB

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