Skip to content

Instantly share code, notes, and snippets.

@nandenjin
Created March 31, 2022 07:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nandenjin/92b1428a6f935394982cf46b0f53e4b7 to your computer and use it in GitHub Desktop.
Save nandenjin/92b1428a6f935394982cf46b0f53e4b7 to your computer and use it in GitHub Desktop.
Utilities for FormatJS -> poEdit -> Webpack
/**
* Quick converter from JSON by FormatJS to POT for translation utilities.
* stdin: JSON / stdout: POT
*/
const potHeader = `msgid ""
msgstr ""
"Project-Id-Version: JV-Campus skanda\\n"
"Language: en_US\\n"
"MIME-Version: 1.0\\n"
"Content-Type: text/plain; charset=UTF-8\\n"
"Content-Transfer-Encoding: 8bit\\n"
`
;(() => {
let jsonStr = ''
process.stdin.on('data', (data) => {
jsonStr = data.toString()
})
process.stdin.on('end', () =>
process.stdout.write(convert(JSON.parse(jsonStr)))
)
const convert = (json) => {
let result = ''
for (const [, value] of Object.entries(json)) {
// Replace ids by FormatJS with original message, for convinience in translation.
// (It must be reveted by bundlers)
result += `msgid "${value.defaultMessage}"\n`
result += `msgstr ""\n`
result += `\n`
}
return potHeader + result
}
})()
/**
* A Webpack Loader to load translated PO files
*/
const crypto = require('crypto')
module.exports = (source) => {
// Add a line break to be matched with RegExp
source += '\n'
const result = {}
for (let [, id, str] of source.matchAll(
/msgid "([\s\S]*?)"[\r\n]msgstr "([\s\S]*?)"[\r\n][\r\n]/g
)) {
// Remove double quotations and line break to concat long messages
// (Long messages are separated by translation utilities as double quoted multi lines)
id = id.replace(/"\n"/g, '')
str = str.replace(/"\n"/g, '')
// Replace ids with SHA512-ed string
// (It reverts replacement in json2pot.js)
const hashId = crypto
.createHash('sha512')
.update(id, 'utf8')
.digest('base64')
.substring(0, 6)
result[hashId] = str
}
return `module.exports = ${JSON.stringify(result)}`
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment