Files
web/apps/scandic-web/i18n/tooling/formatter.ts
2025-04-14 11:30:05 +00:00

100 lines
2.5 KiB
TypeScript

// https://docs.lokalise.com/en/articles/3229161-structured-json
import type { LokaliseMessageDescriptor } from "@/types/intl"
type TranslationEntry = {
translation: string
notes?: string
context?: string
limit?: number
tags?: string[]
}
type CompiledEntries = Record<string, string>
type LokaliseStructuredJson = Record<string, TranslationEntry>
export function format(
msgs: LokaliseMessageDescriptor[]
): LokaliseStructuredJson {
const results: LokaliseStructuredJson = {}
for (const [id, msg] of Object.entries(msgs)) {
const { defaultMessage, description } = msg
if (typeof defaultMessage === "string") {
const entry: TranslationEntry = {
translation: defaultMessage,
}
if (description) {
if (typeof description === "string") {
console.warn(
`Unsupported type for description, expected 'object', got ${typeof context}. Skipping!`,
msg
)
} else {
const { context, limit, tags } = description
if (context) {
if (typeof context === "string") {
entry.context = context
} else {
console.warn(
`Unsupported type for context, expected 'string', got ${typeof context}`,
msg
)
}
}
if (limit) {
if (limit && typeof limit === "number") {
entry.limit = limit
} else {
console.warn(
`Unsupported type for limit, expected 'number', got ${typeof limit}`,
msg
)
}
}
if (tags) {
if (tags && typeof tags === "string") {
const tagArray = tags.split(",").map((s) => s.trim())
if (tagArray.length) {
entry.tags = tagArray
}
} else {
console.warn(
`Unsupported type for tags, expected Array, got ${typeof tags}`,
msg
)
}
}
}
}
results[id] = entry
} else {
console.warn(
`Skipping message, unsupported type for defaultMessage, expected string, got ${typeof defaultMessage}`,
{
id,
msg,
}
)
}
}
return results
}
export function compile(msgs: LokaliseStructuredJson): CompiledEntries {
const results: CompiledEntries = {}
for (const [id, msg] of Object.entries(msgs)) {
results[id] = msg.translation
}
return results
}