๐Ÿ“ฆ langgenius / dify

๐Ÿ“„ check-i18n.js ยท 335 lines
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335import fs from 'node:fs'
import path from 'node:path'
import { fileURLToPath } from 'node:url'
import data from '../i18n-config/languages'

const __filename = fileURLToPath(import.meta.url)
const __dirname = path.dirname(__filename)

const targetLanguage = 'en-US'

const languages = data.languages.filter(language => language.supported).map(language => language.value)

function parseArgs(argv) {
  const args = {
    files: [],
    languages: [],
    autoRemove: false,
    help: false,
    errors: [],
  }

  const collectValues = (startIndex) => {
    const values = []
    let cursor = startIndex + 1
    while (cursor < argv.length && !argv[cursor].startsWith('--')) {
      const value = argv[cursor].trim()
      if (value)
        values.push(value)
      cursor++
    }
    return { values, nextIndex: cursor - 1 }
  }

  const validateList = (values, flag) => {
    if (!values.length) {
      args.errors.push(`${flag} requires at least one value. Example: ${flag} app billing`)
      return false
    }

    const invalid = values.find(value => value.includes(','))
    if (invalid) {
      args.errors.push(`${flag} expects space-separated values. Example: ${flag} app billing`)
      return false
    }

    return true
  }

  for (let index = 2; index < argv.length; index++) {
    const arg = argv[index]

    if (arg === '--auto-remove') {
      args.autoRemove = true
      continue
    }

    if (arg === '--help' || arg === '-h') {
      args.help = true
      break
    }

    if (arg.startsWith('--file=')) {
      args.errors.push('--file expects space-separated values. Example: --file app billing')
      continue
    }

    if (arg === '--file') {
      const { values, nextIndex } = collectValues(index)
      if (validateList(values, '--file'))
        args.files.push(...values)
      index = nextIndex
      continue
    }

    if (arg.startsWith('--lang=')) {
      args.errors.push('--lang expects space-separated values. Example: --lang zh-Hans ja-JP')
      continue
    }

    if (arg === '--lang') {
      const { values, nextIndex } = collectValues(index)
      if (validateList(values, '--lang'))
        args.languages.push(...values)
      index = nextIndex
      continue
    }
  }

  return args
}

function printHelp() {
  console.log(`Usage: pnpm run i18n:check [options]

Options:
  --file <name...>  Check only specific files; provide space-separated names and repeat --file if needed
  --lang <locale>   Check only specific locales; provide space-separated locales and repeat --lang if needed
  --auto-remove     Remove extra keys automatically
  -h, --help        Show help

Examples:
  pnpm run i18n:check --file app billing --lang zh-Hans ja-JP
  pnpm run i18n:check --auto-remove
`)
}

async function getKeysFromLanguage(language) {
  return new Promise((resolve, reject) => {
    const folderPath = path.resolve(__dirname, '../i18n', language)
    const allKeys = []
    fs.readdir(folderPath, (err, files) => {
      if (err) {
        console.error('Error reading folder:', err)
        reject(err)
        return
      }

      // Filter only .json files
      const translationFiles = files.filter(file => /\.json$/.test(file))

      translationFiles.forEach((file) => {
        const filePath = path.join(folderPath, file)
        const fileName = file.replace(/\.json$/, '') // Remove file extension
        const camelCaseFileName = fileName.replace(/[-_](.)/g, (_, c) =>
          c.toUpperCase()) // Convert to camel case

        try {
          const content = fs.readFileSync(filePath, 'utf8')
          const translationObj = JSON.parse(content)

          if (!translationObj || typeof translationObj !== 'object') {
            console.error(`Error parsing file: ${filePath}`)
            reject(new Error(`Error parsing file: ${filePath}`))
            return
          }

          // Flat structure: just get all keys directly
          const fileKeys = Object.keys(translationObj).map(key => `${camelCaseFileName}.${key}`)
          allKeys.push(...fileKeys)
        }
        catch (error) {
          console.error(`Error processing file ${filePath}:`, error.message)
          reject(error)
        }
      })
      resolve(allKeys)
    })
  })
}

async function removeExtraKeysFromFile(language, fileName, extraKeys) {
  const filePath = path.resolve(__dirname, '../i18n', language, `${fileName}.json`)

  if (!fs.existsSync(filePath)) {
    console.log(`โš ๏ธ  File not found: ${filePath}`)
    return false
  }

  try {
    // Filter keys that belong to this file
    const camelCaseFileName = fileName.replace(/[-_](.)/g, (_, c) => c.toUpperCase())
    const fileSpecificKeys = extraKeys
      .filter(key => key.startsWith(`${camelCaseFileName}.`))
      .map(key => key.substring(camelCaseFileName.length + 1)) // Remove file prefix

    if (fileSpecificKeys.length === 0)
      return false

    console.log(`๐Ÿ”„ Processing file: ${filePath}`)

    // Read and parse JSON
    const content = fs.readFileSync(filePath, 'utf8')
    const translationObj = JSON.parse(content)

    let modified = false

    // Remove each extra key (flat structure - direct property deletion)
    for (const keyToRemove of fileSpecificKeys) {
      if (keyToRemove in translationObj) {
        delete translationObj[keyToRemove]
        console.log(`๐Ÿ—‘๏ธ  Removed key: ${keyToRemove}`)
        modified = true
      }
      else {
        console.log(`โš ๏ธ  Could not find key: ${keyToRemove}`)
      }
    }

    if (modified) {
      // Write back to file
      const newContent = `${JSON.stringify(translationObj, null, 2)}\n`
      fs.writeFileSync(filePath, newContent)
      console.log(`๐Ÿ’พ Updated file: ${filePath}`)
      return true
    }

    return false
  }
  catch (error) {
    console.error(`Error processing file ${filePath}:`, error.message)
    return false
  }
}

// Add command line argument support
const args = parseArgs(process.argv)
const targetFiles = Array.from(new Set(args.files))
const targetLangs = Array.from(new Set(args.languages))
const autoRemove = args.autoRemove

async function main() {
  const compareKeysCount = async () => {
    let hasDiff = false
    const allTargetKeys = await getKeysFromLanguage(targetLanguage)

    // Filter target keys by file if specified
    const camelTargetFiles = targetFiles.map(file => file.replace(/[-_](.)/g, (_, c) => c.toUpperCase()))
    const targetKeys = targetFiles.length
      ? allTargetKeys.filter(key => camelTargetFiles.some(file => key.startsWith(`${file}.`)))
      : allTargetKeys

    // Filter languages by target language if specified
    const languagesToProcess = targetLangs.length ? targetLangs : languages

    const allLanguagesKeys = await Promise.all(languagesToProcess.map(language => getKeysFromLanguage(language)))

    // Filter language keys by file if specified
    const languagesKeys = targetFiles.length
      ? allLanguagesKeys.map(keys => keys.filter(key => camelTargetFiles.some(file => key.startsWith(`${file}.`))))
      : allLanguagesKeys

    const keysCount = languagesKeys.map(keys => keys.length)
    const targetKeysCount = targetKeys.length

    const comparison = languagesToProcess.reduce((result, language, index) => {
      const languageKeysCount = keysCount[index]
      const difference = targetKeysCount - languageKeysCount
      result[language] = difference
      return result
    }, {})

    console.log(comparison)

    // Print missing keys and extra keys
    for (let index = 0; index < languagesToProcess.length; index++) {
      const language = languagesToProcess[index]
      const languageKeys = languagesKeys[index]
      const missingKeys = targetKeys.filter(key => !languageKeys.includes(key))
      const extraKeys = languageKeys.filter(key => !targetKeys.includes(key))

      console.log(`Missing keys in ${language}:`, missingKeys)
      if (missingKeys.length > 0)
        hasDiff = true

      // Show extra keys only when there are extra keys (negative difference)
      if (extraKeys.length > 0) {
        console.log(`Extra keys in ${language} (not in ${targetLanguage}):`, extraKeys)

        // Auto-remove extra keys if flag is set
        if (autoRemove) {
          console.log(`\n๐Ÿค– Auto-removing extra keys from ${language}...`)

          // Get all translation files
          const i18nFolder = path.resolve(__dirname, '../i18n', language)
          const files = fs.readdirSync(i18nFolder)
            .filter(file => /\.json$/.test(file))
            .map(file => file.replace(/\.json$/, ''))
            .filter(f => targetFiles.length === 0 || targetFiles.includes(f))

          let totalRemoved = 0
          for (const fileName of files) {
            const removed = await removeExtraKeysFromFile(language, fileName, extraKeys)
            if (removed)
              totalRemoved++
          }

          console.log(`โœ… Auto-removal completed for ${language}. Modified ${totalRemoved} files.`)
        }
        else {
          hasDiff = true
        }
      }
    }

    return hasDiff
  }

  console.log('๐Ÿš€ Starting i18n:check script...')
  if (targetFiles.length)
    console.log(`๐Ÿ“ Checking files: ${targetFiles.join(', ')}`)

  if (targetLangs.length)
    console.log(`๐ŸŒ Checking languages: ${targetLangs.join(', ')}`)

  if (autoRemove)
    console.log('๐Ÿค– Auto-remove mode: ENABLED')

  const hasDiff = await compareKeysCount()
  if (hasDiff) {
    console.error('\nโŒ i18n keys are not aligned. Fix issues above.')
    process.exitCode = 1
  }
  else {
    console.log('\nโœ… All i18n files are in sync')
  }
}

async function bootstrap() {
  if (args.help) {
    printHelp()
    return
  }

  if (args.errors.length) {
    args.errors.forEach(message => console.error(`โŒ ${message}`))
    printHelp()
    process.exit(1)
    return
  }

  const unknownLangs = targetLangs.filter(lang => !languages.includes(lang))
  if (unknownLangs.length) {
    console.error(`โŒ Unsupported languages: ${unknownLangs.join(', ')}`)
    process.exit(1)
    return
  }

  await main()
}

bootstrap().catch((error) => {
  console.error('โŒ Unexpected error:', error.message)
  process.exit(1)
})