|
| 1 | +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. |
| 2 | + |
| 3 | +/** |
| 4 | + * # The label table a mail template's `option` holes read |
| 5 | + * |
| 6 | + * `{{ stage | option:opportunity.stage }}` prints a select field's stored |
| 7 | + * value as its option's label, in the RECIPIENT's language (ruling F on the |
| 8 | + * option-label card, parameter 3). `@objectstack/formula`'s `option` |
| 9 | + * formatter only reads a table it is handed (`OptionLabelTable`, keyed by the |
| 10 | + * hole's `object.field`); this module is where the mail renderer builds that |
| 11 | + * table, once per send, before the synchronous render of its three faces. |
| 12 | + * |
| 13 | + * ## One translation path |
| 14 | + * |
| 15 | + * The labels are the ones the object's metadata is served with in the |
| 16 | + * recipient's locale: the SERVED object's declared `options` (a |
| 17 | + * picklist-bound field carries its resolved list there), with the translation |
| 18 | + * bundle laid over them by `translateObject` (`@objectstack/spec/system`) — |
| 19 | + * the function behind `GET /meta/object/:name`, built from the i18n service |
| 20 | + * with the same locale options. It is the path `@objectstack/objectql`'s |
| 21 | + * `readerOptionLabels` (`formula-option-labels.ts`) gives a formula's |
| 22 | + * `label()`, step for step; that module is not reachable from here |
| 23 | + * (`@objectstack/objectql` is only this package's dev dependency), so the |
| 24 | + * steps are taken through the same two published functions, `translateObject` |
| 25 | + * and `declaresOptions`, and `option-label-table.test.ts` holds the two |
| 26 | + * answers equal. ⛔ No translation key is spelled here. |
| 27 | + * |
| 28 | + * ## Which locale |
| 29 | + * |
| 30 | + * The send's own `locale` — the recipient's, which the messaging channels |
| 31 | + * resolve per recipient and hand to `sendTemplate` / `renderTemplate`. Never an |
| 32 | + * execution context's: a scheduled flow runs as the system, with no reader, |
| 33 | + * and still mails each recipient in their own language. A send that names no |
| 34 | + * locale gets the DECLARED labels. |
| 35 | + * |
| 36 | + * ## Refusals |
| 37 | + * |
| 38 | + * Judged against the deployment's served objects with |
| 39 | + * `judgeMailHoleGrammar(face, { objects, liveUniverse: true })`, the sentences |
| 40 | + * the authoring doors show: an object no one serves, a field the object does |
| 41 | + * not have, a field with no options — and, decided here, a field whose served |
| 42 | + * option list is EMPTY, which has no option to label a value with either. |
| 43 | + * Each is `TEMPLATE_INVALID` and refuses the whole send, before any face is |
| 44 | + * rendered. |
| 45 | + */ |
| 46 | + |
| 47 | +import { declaresOptions, judgeMailHoleGrammar, mailHolePattern, parseMailHole } from '@objectstack/formula'; |
| 48 | +import type { OptionLabelTable } from '@objectstack/formula'; |
| 49 | +import { translateObject, type ObjectFieldLike, type TranslationBundle } from '@objectstack/spec/system'; |
| 50 | + |
| 51 | +/** The slice of `II18nService` the labels are translated through — what the metadata route reads. */ |
| 52 | +export interface OptionLabelI18n { |
| 53 | + getLocales?: () => string[]; |
| 54 | + getTranslations?: (locale: string) => Record<string, unknown>; |
| 55 | + getFallbackLocale?: () => string | undefined; |
| 56 | + getDefaultLocale?: () => string | undefined; |
| 57 | +} |
| 58 | + |
| 59 | +/** |
| 60 | + * Where a send's option labels come from, resolved at each send (a service |
| 61 | + * registered after the email plugin is seen): the served object by name |
| 62 | + * (`IDataEngine.getObject`, the registry's answer — what |
| 63 | + * `GET /meta/object/:name` serves before translation) and the i18n service. |
| 64 | + */ |
| 65 | +export interface OptionLabelSources { |
| 66 | + getObject: (name: string) => unknown; |
| 67 | + i18n?: OptionLabelI18n; |
| 68 | +} |
| 69 | + |
| 70 | +/** The `object.field` keys the `option` holes of `faces` name, in first-seen order. */ |
| 71 | +export function optionHoleKeys(faces: ReadonlyArray<string | null | undefined>): Array<{ key: string; object: string; field: string }> { |
| 72 | + const seen = new Map<string, { key: string; object: string; field: string }>(); |
| 73 | + for (const face of faces) { |
| 74 | + if (typeof face !== 'string' || face === '') continue; |
| 75 | + for (const m of face.matchAll(mailHolePattern())) { |
| 76 | + const ref = parseMailHole(m[2], m[0])?.optionField; |
| 77 | + if (!ref) continue; |
| 78 | + const key = `${ref.object}.${ref.field}`; |
| 79 | + if (!seen.has(key)) seen.set(key, { key, object: ref.object, field: ref.field }); |
| 80 | + } |
| 81 | + } |
| 82 | + return [...seen.values()]; |
| 83 | +} |
| 84 | + |
| 85 | +/** The fields of a served object, by name, when it carries a fields map. */ |
| 86 | +function fieldsOf(schema: unknown): Record<string, ObjectFieldLike> | undefined { |
| 87 | + const fields = (schema as { fields?: unknown } | undefined)?.fields; |
| 88 | + if (!fields || typeof fields !== 'object' || Array.isArray(fields)) return undefined; |
| 89 | + return fields as Record<string, ObjectFieldLike>; |
| 90 | +} |
| 91 | + |
| 92 | +/** Stored value (as text) → label, read off one field's option list. */ |
| 93 | +function labelsOf(def: ObjectFieldLike | undefined): Record<string, string> { |
| 94 | + const labels: Record<string, string> = {}; |
| 95 | + for (const option of Array.isArray(def?.options) ? def.options : []) { |
| 96 | + if (!option || typeof option !== 'object' || option.value === undefined || option.value === null) continue; |
| 97 | + if (typeof option.label === 'string' && option.label.length > 0) labels[String(option.value)] = option.label; |
| 98 | + } |
| 99 | + return labels; |
| 100 | +} |
| 101 | + |
| 102 | +/** |
| 103 | + * The bundle the metadata route translates with — every locale the service |
| 104 | + * holds, keyed by locale — or `undefined` when the service holds none. |
| 105 | + */ |
| 106 | +function bundleOf(i18n: OptionLabelI18n): TranslationBundle | undefined { |
| 107 | + if (typeof i18n.getLocales !== 'function' || typeof i18n.getTranslations !== 'function') return undefined; |
| 108 | + const bundle: Record<string, unknown> = {}; |
| 109 | + for (const locale of i18n.getLocales()) { |
| 110 | + const data = i18n.getTranslations(locale); |
| 111 | + if (data && typeof data === 'object') bundle[locale] = data; |
| 112 | + } |
| 113 | + return Object.keys(bundle).length > 0 ? (bundle as TranslationBundle) : undefined; |
| 114 | +} |
| 115 | + |
| 116 | +/** |
| 117 | + * The option-declaring fields of `schema`, translated into `locale` as the |
| 118 | + * object is served in it. No locale, no i18n service, or one holding no |
| 119 | + * translations: the declared fields. A misbehaving service never fails the |
| 120 | + * send — the declared labels stand, as `readerOptionLabels` answers. |
| 121 | + */ |
| 122 | +function servedOptionFields( |
| 123 | + name: string, |
| 124 | + optionFields: Record<string, ObjectFieldLike>, |
| 125 | + locale: string | undefined, |
| 126 | + i18n: OptionLabelI18n | undefined, |
| 127 | +): Record<string, ObjectFieldLike> { |
| 128 | + if (!locale || !i18n || Object.keys(optionFields).length === 0) return optionFields; |
| 129 | + try { |
| 130 | + const bundle = bundleOf(i18n); |
| 131 | + if (!bundle) return optionFields; |
| 132 | + const fallback = typeof i18n.getFallbackLocale === 'function' ? i18n.getFallbackLocale() : undefined; |
| 133 | + const defaultLocale = typeof i18n.getDefaultLocale === 'function' ? i18n.getDefaultLocale() : undefined; |
| 134 | + const translated = translateObject({ name, fields: optionFields }, bundle, { |
| 135 | + locale, |
| 136 | + ...(typeof fallback === 'string' && fallback.length > 0 ? { fallbackChain: [fallback] } : {}), |
| 137 | + ...(typeof defaultLocale === 'string' && defaultLocale.length > 0 ? { defaultLocale } : {}), |
| 138 | + }); |
| 139 | + const fields = fieldsOf(translated); |
| 140 | + return fields ?? optionFields; |
| 141 | + } catch { |
| 142 | + return optionFields; |
| 143 | + } |
| 144 | +} |
| 145 | + |
| 146 | +/** |
| 147 | + * The label table the `option` holes of `faces` read, in `locale` (the |
| 148 | + * recipient's; `undefined` ⇒ the declared labels), or `undefined` when no face |
| 149 | + * has an `option` hole. Throws `TEMPLATE_INVALID: …` when a hole names an |
| 150 | + * object the deployment does not serve, a field that object does not have, or |
| 151 | + * a field with no options (none declared, or an empty list). |
| 152 | + */ |
| 153 | +export function buildOptionLabelTable( |
| 154 | + faces: ReadonlyArray<string | null | undefined>, |
| 155 | + locale: string | undefined, |
| 156 | + sources: OptionLabelSources, |
| 157 | +): OptionLabelTable | undefined { |
| 158 | + const keys = optionHoleKeys(faces); |
| 159 | + if (keys.length === 0) return undefined; |
| 160 | + |
| 161 | + // The served object of every name a hole gives, judged as the live universe: |
| 162 | + // a name nothing serves is unknown here, whatever its prefix. |
| 163 | + const schemas = new Map<string, { name: string; fields: Record<string, ObjectFieldLike> }>(); |
| 164 | + const objects = new Map<string, ReadonlyMap<string, boolean>>(); |
| 165 | + for (const { object } of keys) { |
| 166 | + if (objects.has(object)) continue; |
| 167 | + const schema = sources.getObject(object); |
| 168 | + const fields = schema === undefined || schema === null ? undefined : fieldsOf(schema); |
| 169 | + if (!fields) continue; |
| 170 | + const servedName = (schema as { name?: unknown }).name; |
| 171 | + schemas.set(object, { name: typeof servedName === 'string' && servedName ? servedName : object, fields }); |
| 172 | + // An option list with no option in it labels nothing: judged as a field |
| 173 | + // with no options, so the send is refused rather than print every value |
| 174 | + // as stored under a formatter that promises a label. |
| 175 | + objects.set(object, new Map(Object.entries(fields).map(([field, def]) => [ |
| 176 | + field, |
| 177 | + declaresOptions(def) && Object.keys(labelsOf(def)).length > 0, |
| 178 | + ]))); |
| 179 | + } |
| 180 | + for (const face of faces) { |
| 181 | + if (typeof face !== 'string' || face === '') continue; |
| 182 | + const [finding] = judgeMailHoleGrammar(face, { objects, liveUniverse: true }); |
| 183 | + if (finding) throw new Error(`TEMPLATE_INVALID: ${finding.refusal.message}`); |
| 184 | + } |
| 185 | + |
| 186 | + const table: Record<string, Record<string, string>> = {}; |
| 187 | + const translatedBy = new Map<string, Record<string, ObjectFieldLike>>(); |
| 188 | + for (const { key, object, field } of keys) { |
| 189 | + const schema = schemas.get(object)!; |
| 190 | + let served = translatedBy.get(object); |
| 191 | + if (!served) { |
| 192 | + const optionFields: Record<string, ObjectFieldLike> = {}; |
| 193 | + for (const [name, def] of Object.entries(schema.fields)) if (declaresOptions(def)) optionFields[name] = def; |
| 194 | + served = servedOptionFields(schema.name, optionFields, locale, sources.i18n); |
| 195 | + translatedBy.set(object, served); |
| 196 | + } |
| 197 | + table[key] = labelsOf(served[field]); |
| 198 | + } |
| 199 | + return table; |
| 200 | +} |
0 commit comments