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