locale-packs.js 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295
  1. const glob = require('glob')
  2. const { ESLint } = require('eslint')
  3. const chalk = require('chalk')
  4. const path = require('path')
  5. const dedent = require('dedent')
  6. const stringifyObject = require('stringify-object')
  7. const fs = require('fs')
  8. const Uppy = require('../packages/@uppy/core')
  9. const uppy = new Uppy()
  10. function getSources (pluginName) {
  11. const dependencies = {
  12. // because 'provider-views' doesn't have its own locale, it uses Core's defaultLocale
  13. core: ['provider-views'],
  14. }
  15. const globPath = path.join(__dirname, '..', 'packages', '@uppy', pluginName, 'lib', '**', '*.js')
  16. let contents = glob.sync(globPath).map((file) => {
  17. return fs.readFileSync(file, 'utf-8')
  18. })
  19. if (dependencies[pluginName]) {
  20. dependencies[pluginName].forEach((addPlugin) => {
  21. contents = contents.concat(getSources(addPlugin))
  22. })
  23. }
  24. return contents
  25. }
  26. function buildPluginsList () {
  27. const plugins = {}
  28. const sources = {}
  29. // Go over all uppy plugins, check if they are constructors
  30. // and instanciate them, check for defaultLocale property,
  31. // then add to plugins object
  32. const packagesGlobPath = path.join(__dirname, '..', 'packages', '@uppy', '*', 'package.json')
  33. const files = glob.sync(packagesGlobPath)
  34. console.log('--> Checked plugins could be instantiated and have defaultLocale in them:\n')
  35. for (const file of files) {
  36. const dirName = path.dirname(file)
  37. const pluginName = path.basename(dirName)
  38. if (pluginName === 'locales'
  39. || pluginName === 'react-native'
  40. || pluginName === 'vue'
  41. || pluginName === 'svelte'
  42. || pluginName === 'angular') {
  43. continue // eslint-disable-line no-continue
  44. }
  45. const Plugin = require(dirName) // eslint-disable-line global-require, import/no-dynamic-require
  46. let plugin
  47. // A few hacks to emulate browser environment because e.g.:
  48. // GoldenRetrieves calls upon MetaDataStore in the constructor, which uses localStorage
  49. // @TODO Consider rewriting constructors so they don't make imperative calls that rely on browser environment
  50. // (OR: just keep this browser mocking, if it's only causing issues for this script, it doesn't matter)
  51. global.location = { protocol: 'https' }
  52. global.navigator = { userAgent: '' }
  53. global.localStorage = {
  54. key: () => { },
  55. getItem: () => { },
  56. }
  57. global.window = {
  58. indexedDB: {
  59. open: () => { return {} },
  60. },
  61. }
  62. global.document = {
  63. createElement: () => {
  64. return { style: {} }
  65. },
  66. get body () { return this.createElement() },
  67. }
  68. try {
  69. if (pluginName === 'provider-views') {
  70. plugin = new Plugin(plugins['drag-drop'], {
  71. companionPattern: '',
  72. companionUrl: 'https://companion.uppy.io',
  73. })
  74. } else if (pluginName === 'store-redux') {
  75. plugin = new Plugin({ store: { dispatch: () => { } } })
  76. } else {
  77. plugin = new Plugin(uppy, {
  78. companionPattern: '',
  79. companionUrl: 'https://companion.uppy.io',
  80. params: {
  81. auth: {
  82. key: 'x',
  83. },
  84. },
  85. })
  86. }
  87. } catch (err) {
  88. if (err.message !== 'Plugin is not a constructor') {
  89. console.error(`--> While trying to instantiate plugin: ${pluginName}, this error was thrown: `)
  90. throw err
  91. }
  92. }
  93. if (plugin && plugin.defaultLocale) {
  94. console.log(`[x] Check plugin: ${pluginName}`)
  95. plugins[pluginName] = plugin
  96. sources[pluginName] = getSources(pluginName)
  97. } else {
  98. console.log(`[ ] Check plugin: ${pluginName}`)
  99. }
  100. }
  101. console.log('')
  102. return { plugins, sources }
  103. }
  104. function addLocaleToPack (localePack, plugin, pluginName) {
  105. const localeStrings = plugin.defaultLocale.strings
  106. for (const key of Object.keys(localeStrings)) {
  107. const valueInPlugin = JSON.stringify(localeStrings[key])
  108. const valueInPack = JSON.stringify(localePack[key])
  109. if (key in localePack && valueInPlugin !== valueInPack) {
  110. console.error(`⚠ Plugin ${chalk.magenta(pluginName)} has a duplicate key: ${chalk.magenta(key)}`)
  111. console.error(` Value in plugin: ${chalk.cyan(valueInPlugin)}`)
  112. console.error(` Value in pack : ${chalk.yellow(valueInPack)}`)
  113. console.error()
  114. throw new Error(`Duplicate locale key: '${key}'`)
  115. }
  116. localePack[key] = localeStrings[key] // eslint-disable-line no-param-reassign
  117. }
  118. }
  119. function checkForUnused (fileContents, pluginName, localePack) {
  120. const buff = fileContents.join('\n')
  121. for (const key of Object.keys(localePack)) {
  122. const regPat = new RegExp(`(i18n|i18nArray)\\([^\\)]*['\`"]${key}['\`"]`, 'g')
  123. if (!buff.match(regPat)) {
  124. console.error(`⚠ defaultLocale key: ${chalk.magenta(key)} not used in plugin: ${chalk.cyan(pluginName)}`)
  125. throw new Error(`Unused locale key: '${key}'`)
  126. }
  127. }
  128. }
  129. function sortObjectAlphabetically (obj) {
  130. return Object.fromEntries(Object.entries(obj).sort(([keyA], [keyB]) => keyA.localeCompare(keyB)))
  131. }
  132. function createTypeScriptLocale (plugin, pluginName) {
  133. const allowedStringTypes = Object.keys(plugin.defaultLocale.strings)
  134. .map(key => ` | '${key}'`)
  135. .join('\n')
  136. const pluginClassName = pluginName === 'core' ? 'Core' : plugin.id
  137. const localePath = path.join(__dirname, '..', 'packages', '@uppy', pluginName, 'types', 'generatedLocale.d.ts')
  138. const localeTypes = dedent`
  139. /* eslint-disable */
  140. import type { Locale } from '@uppy/core'
  141. type ${pluginClassName}Locale = Locale<
  142. ${allowedStringTypes}
  143. >
  144. export default ${pluginClassName}Locale
  145. `
  146. fs.writeFileSync(localePath, localeTypes)
  147. }
  148. async function build () {
  149. let localePack = {}
  150. const { plugins, sources } = buildPluginsList()
  151. for (const [pluginName, plugin] of Object.entries(plugins)) {
  152. addLocaleToPack(localePack, plugin, pluginName)
  153. }
  154. for (const [pluginName, plugin] of Object.entries(plugins)) {
  155. createTypeScriptLocale(plugin, pluginName)
  156. }
  157. localePack = sortObjectAlphabetically(localePack)
  158. for (const [pluginName, source] of Object.entries(sources)) {
  159. checkForUnused(source, pluginName, sortObjectAlphabetically(plugins[pluginName].defaultLocale.strings))
  160. }
  161. const prettyLocale = stringifyObject(localePack, {
  162. indent: ' ',
  163. singleQuotes: true,
  164. inlineCharacterLimit: 12,
  165. })
  166. const localeTemplatePath = path.join(__dirname, '..', 'packages', '@uppy', 'locales', 'template.js')
  167. const template = fs.readFileSync(localeTemplatePath, 'utf-8')
  168. const finalLocale = template.replace('en_US.strings = {}', `en_US.strings = ${prettyLocale}`)
  169. const localePackagePath = path.join(__dirname, '..', 'packages', '@uppy', 'locales', 'src', 'en_US.js')
  170. const linter = new ESLint({
  171. fix: true,
  172. })
  173. const [lintResult] = await linter.lintText(finalLocale, {
  174. filePath: localePackagePath,
  175. })
  176. fs.writeFileSync(localePackagePath, lintResult.output, 'utf8')
  177. console.log(`✅ Written '${localePackagePath}'`)
  178. }
  179. function test () {
  180. const leadingLocaleName = 'en_US'
  181. const followerLocales = {}
  182. const followerValues = {}
  183. const localePackagePath = path.join(__dirname, '..', 'packages', '@uppy', 'locales', 'src', '*.js')
  184. glob.sync(localePackagePath).forEach((localePath) => {
  185. const localeName = path.basename(localePath, '.js')
  186. // Builds array with items like: 'uploadingXFiles'
  187. // We do not check nested items because different languages may have different amounts of plural forms.
  188. // eslint-disable-next-line global-require, import/no-dynamic-require
  189. followerValues[localeName] = require(localePath).strings
  190. followerLocales[localeName] = Object.keys(followerValues[localeName])
  191. })
  192. // Take aside our leading locale: en_US
  193. const leadingLocale = followerLocales[leadingLocaleName]
  194. const leadingValues = followerValues[leadingLocaleName]
  195. delete followerLocales[leadingLocaleName]
  196. // Compare all follower Locales (RU, DE, etc) with our leader en_US
  197. const warnings = []
  198. const fatals = []
  199. for (const [followerName, followerLocale] of Object.entries(followerLocales)) {
  200. const missing = leadingLocale.filter((key) => !followerLocale.includes(key))
  201. const excess = followerLocale.filter((key) => !leadingLocale.includes(key))
  202. missing.forEach((key) => {
  203. // Items missing are a non-fatal warning because we don't want CI to bum out over all languages
  204. // as soon as we add some English
  205. let value = leadingValues[key]
  206. if (typeof value === 'object') {
  207. // For values with plural forms, just take the first one right now
  208. value = value[Object.keys(value)[0]]
  209. }
  210. warnings.push(`${chalk.cyan(followerName)} locale has missing string: '${chalk.red(key)}' that is present in ${chalk.cyan(leadingLocaleName)} with value: ${chalk.yellow(leadingValues[key])}`)
  211. })
  212. excess.forEach((key) => {
  213. // Items in excess are a fatal because we should clean up follower languages once we remove English strings
  214. fatals.push(`${chalk.cyan(followerName)} locale has excess string: '${chalk.yellow(key)}' that is not present in ${chalk.cyan(leadingLocaleName)}. `)
  215. })
  216. }
  217. if (warnings.length) {
  218. console.error('--> Locale warnings: ')
  219. console.error(warnings.join('\n'))
  220. console.error('')
  221. }
  222. if (fatals.length) {
  223. console.error('--> Locale fatal warnings: ')
  224. console.error(fatals.join('\n'))
  225. console.error('')
  226. process.exit(1)
  227. }
  228. if (!warnings.length && !fatals.length) {
  229. console.log(`--> All locale strings have matching keys ${chalk.green(': )')}`)
  230. console.log('')
  231. }
  232. }
  233. async function main () {
  234. console.warn('\n--> Make sure to run `npm run build:lib` for this locale script to work properly. ')
  235. const mode = process.argv[2]
  236. if (mode === 'build') {
  237. await build()
  238. } else if (mode === 'test') {
  239. test()
  240. } else {
  241. throw new Error("First argument must be either 'build' or 'test'")
  242. }
  243. }
  244. main().catch((err) => {
  245. console.error(err)
  246. process.exit(1)
  247. })