generated from polymech/site-template
73 lines
2.4 KiB
TypeScript
73 lines
2.4 KiB
TypeScript
import * as path from 'path'
|
|
import { resolve } from '@polymech/commons'
|
|
import { sync as exists } from '@polymech/fs/exists'
|
|
|
|
import type { IOptions } from '@polymech/i18n'
|
|
import { CONFIG_DEFAULT } from '@polymech/commons'
|
|
import {
|
|
I18N_ASSET_PATH,
|
|
I18N_CACHE,
|
|
I18N_SOURCE_LANGUAGE,
|
|
PRODUCT_SPECS,
|
|
RETAIL_LOG_LEVEL_I18N_PRODUCT_ASSETS
|
|
} from 'config/config.js'
|
|
|
|
import { translateXLS } from '@polymech/i18n/translate_xls'
|
|
import { I18N_STORE, OSR_ROOT } from 'config/config.js'
|
|
import { translateText } from '@polymech/i18n/translate_text'
|
|
import { logger } from './index.js'
|
|
|
|
export type { IOptions } from '@polymech/i18n'
|
|
|
|
export const translate = async (text: string, srcLanguage = 'en', targetLanguage, opts = {}) => {
|
|
if (!targetLanguage) {
|
|
return text
|
|
}
|
|
try {
|
|
const store = I18N_STORE(OSR_ROOT(), targetLanguage)
|
|
let translation = text
|
|
translation = await translateText(text, srcLanguage, targetLanguage, {
|
|
store,
|
|
...opts
|
|
})
|
|
return translation
|
|
} catch (e) {
|
|
logger.error(`Failed to translate text: ${text} from ${srcLanguage} to ${targetLanguage} : ${e.message}`)
|
|
}
|
|
return text
|
|
}
|
|
export const translateSheets = async (product, language) => {
|
|
const config: any = CONFIG_DEFAULT()
|
|
if (language === I18N_SOURCE_LANGUAGE) {
|
|
return
|
|
}
|
|
const i18nOptions: IOptions = {
|
|
srcLang: I18N_SOURCE_LANGUAGE,
|
|
dstLang: language,
|
|
src: PRODUCT_SPECS(product),
|
|
store: I18N_STORE(OSR_ROOT(), language),
|
|
dst: I18N_ASSET_PATH,
|
|
query: "$[*][0,1,2,3]",
|
|
cache: I18N_CACHE,
|
|
api_key: config.deepl.auth_key,
|
|
logLevel: RETAIL_LOG_LEVEL_I18N_PRODUCT_ASSETS
|
|
}
|
|
const src = `${PRODUCT_SPECS(product)}`
|
|
const srcParts = path.parse(src)
|
|
const dst = path.resolve(resolve(I18N_ASSET_PATH, false, {
|
|
SRC_DIR: srcParts.dir,
|
|
SRC_NAME: srcParts.name,
|
|
SRC_EXT: srcParts.ext,
|
|
DST_LANG: language
|
|
}))
|
|
if (I18N_CACHE && exists(dst)) {
|
|
return dst
|
|
}
|
|
logger.debug(`Translate assets ${src} to ${language}`)
|
|
try {
|
|
return await translateXLS(path.resolve(src), dst, i18nOptions)
|
|
} catch (e) {
|
|
logger.error(`Failed to translate assets ${src} to ${language}`, e.message)
|
|
}
|
|
}
|