feat(desktop): localize Windows installer with per-language JSON resources

This commit is contained in:
07akioni committed 2026-10-21 16:43:19 +08:00
1 parent 87c4de2e43
commit 9ce74cda96
20 files changed
+314 -90

No files matched your search

@@ -1,7 +1,8 @@
import { readInstallerLocales, renderInstallerStrings } from './installer-locales.mjs'
import { officePackageDirectories } from '../../../scripts/libreoffice-packages.mjs'
import { X509Certificate } from 'node:crypto'
import { readFileSync } from 'node:fs'
import { readFile } from 'node:fs/promises'
import { readFile, writeFile } from 'node:fs/promises'
import { join, relative, sep } from 'node:path'
import { fileURLToPath } from 'node:url'
import { execFile } from 'node:child_process'
@@ -129,6 +130,7 @@ export function createElectronBuilderConfig(
'-OutputDirectory', join(buildPaths.root, 'installer-ui')], {
env: scrubWindowsSigningEnvironment(env), windowsHide: true,
})
await writeFile(join(buildPaths.root, 'installer-ui', 'strings.nsh'), renderInstallerStrings(readInstallerLocales()), 'utf8')
if (windowsSigner !== undefined) {
await windowsSigner({ path: join(buildPaths.root, 'installer-ui', 'window-frame.dll'), hash: 'sha256', isNest: false })
}
@@ -262,7 +264,7 @@ export function createElectronBuilderConfig(
perMachine: false,
allowElevation: false,
allowToChangeInstallationDirectory: false,
installerLanguages: ['en_US', 'zh_CN'],
installerLanguages: readInstallerLocales().map(locale => locale.id),
differentialPackage: true,
},
detectUpdateChannel: false,
@@ -0,0 +1,25 @@
/** One installer language's compiler identifier, UI strings and NSIS Modern UI test expectations. */
export interface InstallerLocale {
/** electron-builder language and resource filename without its suffix. */
id: string
/** NSIS LANG_ constant suffix. */
nsisLanguage: string
/** Custom installer messages, with Windows printf placeholders preserved. */
strings: Record<string, string>
/** Substrings of the upstream Modern UI uninstaller's welcome and finished pages. */
uninstaller: Record<string, string>
}
/**
* Read complete per-language JSON resources and reject inconsistent keys or placeholders.
* @param directory - Resource directory, defaulting to Desktop installer/locales.
* @returns Validated resources, ordered by filename.
*/
export function readInstallerLocales(directory?: string): InstallerLocale[]
/**
* Generate NSIS LangString declarations from validated resources.
* @param locales - All configured languages or one isolated native-test language.
* @returns UTF-8 NSIS source with literal text escaped.
*/
export function renderInstallerStrings(locales: InstallerLocale[]): string
@@ -0,0 +1,75 @@
/** Per-language JSON resources shared by NSIS packaging, native UI tests and the i18n check. */
import { readFileSync, readdirSync } from 'node:fs'
import { fileURLToPath } from 'node:url'
const defaultDirectory = fileURLToPath(new URL('../installer/locales/', import.meta.url))
/**
* Read and validate installer translations before generating compiler input.
* @param {string} directory - Directory containing one JSON file per installer language.
* @returns {{id: string, nsisLanguage: string, strings: Record<string, string>, uninstaller: Record<string, string>}[]} Complete language resources.
*/
export function readInstallerLocales(directory = defaultDirectory) {
const locales = readdirSync(directory).filter(name => name.endsWith('.json')).sort().map(name => {
if (!/^[a-z]{2}_[A-Z]{2}\.json$/u.test(name)) throw new Error(`${name}: invalid installer language filename`)
/** @type {unknown} */
const resource = JSON.parse(readFileSync(`${directory}/${name}`, 'utf8'))
if (typeof resource !== 'object' || resource === null || !('nsisLanguage' in resource)
|| typeof resource.nsisLanguage !== 'string' || !/^[A-Z]+$/u.test(resource.nsisLanguage)) {
throw new Error(`${name}: invalid NSIS language identifier`)
}
/** @param {unknown} value - Parsed JSON dictionary. @returns {Record<string, string>} Nonempty text values. */
const dictionary = (value) => {
if (typeof value !== 'object' || value === null || Array.isArray(value)) throw new Error(`${name}: expected text dictionary`)
/** @type {Record<string, string>} */
const result = {}
for (const [key, text] of Object.entries(value)) {
if (typeof text !== 'string' || text.trim() === '') throw new Error(`${name}: ${key} must be nonempty text`)
result[key] = text
}
return result
}
const strings = dictionary('strings' in resource ? resource.strings : undefined)
if (Object.keys(strings).some(key => !/^INSTALLER_[A-Z_]+$/u.test(key))) throw new Error(`${name}: invalid installer string key`)
return { id: name.slice(0, -5), nsisLanguage: resource.nsisLanguage, strings,
uninstaller: dictionary('uninstaller' in resource ? resource.uninstaller : undefined) }
})
for (const id of ['en_US', 'zh_CN', 'ja_JP']) {
if (!locales.some(locale => locale.id === id)) throw new Error(`installer locales: missing ${id}.json`)
}
const english = locales.find(locale => locale.id === 'en_US')
if (!english || Object.keys(english.strings).length === 0) throw new Error('installer locales: missing English strings')
if (Object.keys(english.uninstaller).sort().join(',') !== 'finished,welcome') throw new Error('installer locales: expected uninstaller welcome and finished text')
const languages = new Set()
for (const locale of locales) {
if (languages.has(locale.nsisLanguage)) throw new Error(`${locale.id}: duplicate NSIS language ${locale.nsisLanguage}`)
languages.add(locale.nsisLanguage)
for (const field of ['strings', 'uninstaller']) {
const expected = english[field]
const actual = locale[field]
if (Object.keys(expected).sort().join(',') !== Object.keys(actual).sort().join(',')) throw new Error(`${locale.id}: ${field} keys differ from English`)
for (const [key, text] of Object.entries(expected)) {
const placeholders = (/** @type {string} */ value) => (value.match(/%.?/gu) ?? []).join(',')
if (placeholders(text) !== placeholders(actual[key])) throw new Error(`${locale.id}: ${key} changes format placeholders`)
}
}
}
return locales
}
/**
* Generate guarded NSIS LangString declarations from validated JSON resources.
* @param {ReturnType<typeof readInstallerLocales>} locales - Resources for all languages or one isolated native-test build.
* @returns {string} UTF-8 NSIS source, with literal dollar signs, quotes and line breaks escaped.
*/
export function renderInstallerStrings(locales) {
const escape = (/** @type {string} */ text) => text.replace(/\$|"|\r|\n/gu, character => ({ '$': '$$', '"': '$\\"', '\r': '$\\r', '\n': '$\\n' })[character])
return '; Generated from installer/locales/*.json.\n' + locales.map(locale =>
`!ifdef LANG_${locale.nsisLanguage}\n` + Object.entries(locale.strings).map(([key, text]) =>
`LangString ${key} \${LANG_${locale.nsisLanguage}} "${escape(text)}"\n`).join('') + '!endif\n').join('')
}
if (import.meta.main) {
const locales = readInstallerLocales()
console.log(`verify-installer-locales: ${locales.length} languages have matching keys and format placeholders.`)
}
+1 -1
View File
@@ -9,7 +9,7 @@ ManifestDPIAware true
!endif
!macro customHeader
!define /ifndef INSTALLER_STRINGS_FILE "${INSTALLER_SOURCE_DIR}\strings.nsh"
!define /ifndef INSTALLER_STRINGS_FILE "${INSTALLER_BUILD_DIR}\strings.nsh"
!include "${INSTALLER_STRINGS_FILE}"
!ifdef BUILD_UNINSTALLER
BrandingText " "
@@ -1,4 +1,5 @@
/** Builds an isolated native payload through the production NSIS configuration and exercises its UI. */
import { readInstallerLocales, renderInstallerStrings } from './installer-locales.mjs'
import { execFile } from 'node:child_process'
import { randomUUID } from 'node:crypto'
import { mkdir, mkdtemp, readFile, writeFile } from 'node:fs/promises'
@@ -107,8 +108,8 @@ SectionEnd
const compiler = await getMakeNsisPath()
await execute(compiler.path, ['/V2', payloadSource], { ...childOptions, env: { ...childOptions.env, ...compiler.env } })
if (sign) await sign({ path: join(payload, `${productName}.exe`), hash: 'sha256', isNest: false })
const sourceStrings = await readFile(join(appRoot, 'installer', 'strings.nsh'), 'utf8')
for (const language of ['en_US', 'zh_CN']) {
for (const locale of readInstallerLocales()) {
const language = locale.id
const config = createElectronBuilderConfig()
if (sign) {
config.win.forceCodeSigning = true
@@ -117,9 +118,7 @@ SectionEnd
const languageOutput = join(output, language)
await mkdir(languageOutput)
const strings = join(languageOutput, 'strings.nsh')
const languageId = language === 'en_US' ? 'ENGLISH' : 'SIMPCHINESE'
await writeFile(strings, sourceStrings.split('\n').filter((line) =>
!line.startsWith('LangString ') || line.includes(`\${LANG_${languageId}}`)).join('\n'))
await writeFile(strings, renderInstallerStrings([locale]), 'utf8')
const include = join(languageOutput, 'include.nsh')
await writeFile(include, `!define INSTALLER_BUILD_DIR "${join(output, 'ui')}"\n!define INSTALLER_STRINGS_FILE "${strings}"\n!include "${join(appRoot, 'scripts', 'installer.nsh')}"\n`)
await build({ projectDir: appRoot, prepackaged: payload, targets: Platform.WINDOWS.createTarget(['nsis'], Arch.x64), publish: 'never',
@@ -132,7 +131,7 @@ SectionEnd
join(appRoot, 'tests', uninstallOnly ? 'windows-uninstall-smoke.ps1' : 'windows-installer-smoke.ps1'),
'-Installer', join(languageOutput, 'installer-test.exe'),
'-ProductName', productName, '-RegistryKey', guid, '-OutputDirectory', languageOutput,
...uninstallOnly ? ['-Language', languageId, '-PackageName', packageName] : []], childOptions)
'-Language', language, ...uninstallOnly ? ['-PackageName', packageName] : []], childOptions)
process.stdout.write(`${language}\n${result.stdout}`)
}
succeeded = true