inject.js 9.1 KB

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