|
| 1 | +import { getConfig } from "@lingui/conf" |
| 2 | +import { |
| 3 | + createCompiledCatalog, |
| 4 | + getCatalogForFile, |
| 5 | + getCatalogs, |
| 6 | +} from "@lingui/cli/api" |
| 7 | +import type { BabelTransformer, BabelTransformerArgs } from "./types" |
| 8 | + |
| 9 | +export const createLinguiMetroTransformer = ( |
| 10 | + upstreamTransformer: BabelTransformer |
| 11 | +): BabelTransformer["transform"] => { |
| 12 | + return async function linguiMetroTransformer(params) { |
| 13 | + if (!params.filename.endsWith(".po")) { |
| 14 | + return upstreamTransformer.transform(params) |
| 15 | + } |
| 16 | + const jsSource = await transformFile(params) |
| 17 | + return upstreamTransformer.transform({ |
| 18 | + ...params, |
| 19 | + src: jsSource, |
| 20 | + }) |
| 21 | + } |
| 22 | +} |
| 23 | + |
| 24 | +export async function transformFile( |
| 25 | + params: Pick<BabelTransformerArgs, "filename"> |
| 26 | +) { |
| 27 | + const config = getConfig() |
| 28 | + |
| 29 | + const catalogRelativePath = params.filename |
| 30 | + |
| 31 | + const fileCatalog = getCatalogForFile( |
| 32 | + catalogRelativePath, |
| 33 | + await getCatalogs(config) |
| 34 | + ) |
| 35 | + |
| 36 | + if (!fileCatalog) { |
| 37 | + throw new Error( |
| 38 | + `Requested resource ${catalogRelativePath} is not matched to any of your catalogs paths specified in "lingui.config". |
| 39 | +
|
| 40 | +Your catalogs: |
| 41 | +${config.catalogs.map((c) => c.path).join("\n")} |
| 42 | +
|
| 43 | +Working dir is: |
| 44 | +${process.cwd()} |
| 45 | +
|
| 46 | +Please check that \`catalogs.path\` is filled properly and restart the Metro server.\n` |
| 47 | + ) |
| 48 | + } |
| 49 | + |
| 50 | + const { locale, catalog } = fileCatalog |
| 51 | + |
| 52 | + const messages = await catalog.getTranslations(locale, { |
| 53 | + fallbackLocales: config.fallbackLocales, |
| 54 | + sourceLocale: config.sourceLocale, |
| 55 | + }) |
| 56 | + |
| 57 | + const strict = process.env.NODE_ENV !== "production" |
| 58 | + |
| 59 | + return createCompiledCatalog(locale, messages, { |
| 60 | + strict, |
| 61 | + namespace: "es", |
| 62 | + pseudoLocale: config.pseudoLocale, |
| 63 | + }) |
| 64 | +} |
0 commit comments