index.mjs 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. /* eslint-disable no-console, prefer-arrow-callback */
  2. import path from 'node:path'
  3. import { readFile, writeFile } from 'node:fs/promises'
  4. import { fileURLToPath } from 'node:url'
  5. import dedent from 'dedent'
  6. import { getLocales, sortObjectAlphabetically } from './helpers.mjs'
  7. const root = fileURLToPath(new URL('../../', import.meta.url))
  8. const localesPath = path.join(root, 'packages', '@uppy', 'locales')
  9. const templatePath = path.join(localesPath, 'template.js')
  10. const englishLocalePath = path.join(localesPath, 'src', 'en_US.js')
  11. async function getLocalesAndCombinedLocale () {
  12. const locales = await getLocales(`${root}/packages/@uppy/**/lib/locale.js`)
  13. const combinedLocale = {}
  14. for (const [pluginName, locale] of Object.entries(locales)) {
  15. for (const [key, value] of Object.entries(locale.strings)) {
  16. if (key in combinedLocale && value !== combinedLocale[key]) {
  17. throw new Error(`'${key}' from ${pluginName} already exists in locale pack.`)
  18. }
  19. combinedLocale[key] = value
  20. }
  21. }
  22. return [locales, sortObjectAlphabetically(combinedLocale)]
  23. }
  24. function generateTypes (pluginName, locale) {
  25. const allowedStringTypes = Object.keys(locale.strings)
  26. .map((key) => ` | '${key}'`)
  27. .join('\n')
  28. const pluginClassName = pluginName
  29. .split('-')
  30. .map((str) => str.replace(/^\w/, (c) => c.toUpperCase()))
  31. .join('')
  32. const localePath = path.join(
  33. root,
  34. 'packages',
  35. '@uppy',
  36. pluginName,
  37. 'types',
  38. 'generatedLocale.d.ts',
  39. )
  40. const localeTypes = dedent`
  41. /* eslint-disable */
  42. import type { Locale } from '@uppy/core'
  43. type ${pluginClassName}Locale = Locale<
  44. ${allowedStringTypes}
  45. >
  46. export default ${pluginClassName}Locale
  47. `
  48. return writeFile(localePath, localeTypes)
  49. }
  50. const [[locales, combinedLocale], fileString] = await Promise.all([
  51. getLocalesAndCombinedLocale(),
  52. readFile(templatePath, 'utf-8'),
  53. ])
  54. const formattedLocale = JSON.stringify(combinedLocale, null, ' ')
  55. await Promise.all([
  56. // Populate template
  57. writeFile(
  58. englishLocalePath,
  59. fileString.replace('en_US.strings = {}', `en_US.strings = ${formattedLocale}`),
  60. ).then(() => console.log(`✅ Generated '${englishLocalePath}'`)),
  61. // Create locale files
  62. ...Object.entries(locales).flatMap(([pluginName, locale]) => [
  63. generateTypes(pluginName, locale).then(() => console.log(`✅ Generated types for ${pluginName}`)),
  64. ]),
  65. ])