inject.js 9.0 KB

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