-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathi18n-resolver.ts
More file actions
1197 lines (1107 loc) · 42.8 KB
/
Copy pathi18n-resolver.ts
File metadata and controls
1197 lines (1107 loc) · 42.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.
/**
* I18n Resolver
*
* Convention-based label lookup helpers for views and actions.
*
* Developers author plain English `label`s in metadata
* (`*.view.ts`, `*.actions.ts`); these helpers translate at render time using
* the standardized keys:
*
* objects.<object>._views.<view_name>.label
* objects.<object>._views.<view_name>.description
* objects.<object>._actions.<action_name>.label
* objects.<object>._actions.<action_name>.confirmText
* objects.<object>._actions.<action_name>.successMessage
*
* For object-less actions (no `objectName`), helpers fall back to:
*
* globalActions.<action_name>.label / .confirmText / .successMessage
*
* Lookup order: requested locale → each entry of `fallbackChain` (defaults to
* `['en']`) → literal `label` from the metadata. Helpers never throw — they
* always return at minimum the metadata literal so unconfigured languages
* gracefully degrade.
*/
import type { TranslationBundle, TranslationData } from './translation.zod';
/** Minimal view shape consumed by `resolveViewLabel`. */
export interface ViewLike {
name: string;
label?: string;
description?: string;
/** Object the view is bound to. Required for translation lookup. */
objectName?: string;
/** Some view definitions name the bound object via `data.object`. */
data?: { object?: string };
}
/** Minimal action shape consumed by the action resolvers. */
export interface ActionLike {
name: string;
label?: string;
confirmText?: string;
successMessage?: string;
/** When omitted, the action is treated as global. */
objectName?: string;
/** Post-success reveal dialog (see `Action.resultDialog` in ui/action.zod). */
resultDialog?: ResultDialogLike;
}
/** Minimal result-dialog shape consumed by `resolveActionResultDialog`. */
export interface ResultDialogLike {
title?: string;
description?: string;
acknowledge?: string;
fields?: Array<{ path: string; label?: string; [key: string]: unknown }>;
[key: string]: unknown;
}
/** Optional resolver settings. */
export interface ResolveOptions {
/** BCP-47 locale code; defaults to `'en'`. */
locale?: string;
/**
* Ordered fallback locales to consult after `locale` and before returning
* the literal label. Defaults to `['en']`.
*/
fallbackChain?: string[];
}
/**
* Resolve a requested locale code against the locales actually present in a
* bundle, applying BCP-47 fallback so callers that pass a base language
* (e.g. `zh`) or a differently-cased / region-qualified variant still hit the
* available data (e.g. `zh-CN`). Mirrors `resolveLocale` in
* `@objectstack/core` but is inlined here so `@objectstack/spec` stays
* dependency-free.
*
* Order: exact → case-insensitive → base-language → variant-expansion.
* Returns the matched bundle key, or `undefined` when nothing matches.
*/
function resolveBundleLocale(
bundle: Record<string, unknown>,
requested: string,
): string | undefined {
// 1. Exact match (fast path).
if (bundle[requested] !== undefined) return requested;
const available = Object.keys(bundle);
if (available.length === 0) return undefined;
const lower = requested.toLowerCase();
// 2. Case-insensitive match (e.g. `zh-cn` → `zh-CN`).
const caseMatch = available.find((code) => code.toLowerCase() === lower);
if (caseMatch) return caseMatch;
const base = lower.split('-')[0];
// 3. Base-language match (e.g. `zh-CN` → `zh`).
const baseMatch = available.find((code) => code.toLowerCase() === base);
if (baseMatch) return baseMatch;
// 4. Variant expansion (e.g. `zh` → `zh-CN`; first registered variant wins).
const variantMatch = available.find((code) => code.toLowerCase().split('-')[0] === base);
if (variantMatch) return variantMatch;
return undefined;
}
function pickData(
bundle: TranslationBundle | undefined,
locale: string,
): TranslationData | undefined {
if (!bundle) return undefined;
const exact = bundle[locale];
if (exact !== undefined) return exact;
const resolved = resolveBundleLocale(bundle, locale);
return resolved !== undefined ? bundle[resolved] : undefined;
}
function localeChain(opts?: ResolveOptions): string[] {
const locale = opts?.locale ?? 'en';
const fallbacks = opts?.fallbackChain ?? ['en'];
// Preserve order, drop duplicates.
const seen = new Set<string>();
const chain: string[] = [];
for (const code of [locale, ...fallbacks]) {
if (!seen.has(code)) {
seen.add(code);
chain.push(code);
}
}
return chain;
}
function viewObjectName(view: ViewLike): string | undefined {
return view.objectName ?? view.data?.object;
}
/**
* Resolve a translated view label, falling back to the literal `view.label`
* (or `view.name`) when no translation is available.
*/
export function resolveViewLabel(
bundle: TranslationBundle | undefined,
view: ViewLike,
opts?: ResolveOptions,
): string {
const fallback = view.label ?? view.name;
const objectName = viewObjectName(view);
if (!bundle || !objectName) return fallback;
for (const code of localeChain(opts)) {
const data = pickData(bundle, code);
const candidate = data?.objects?.[objectName]?._views?.[view.name]?.label;
if (typeof candidate === 'string' && candidate.length > 0) return candidate;
}
return fallback;
}
/**
* Resolve a translated view description, returning `undefined` when neither a
* translation nor a literal description is set.
*/
export function resolveViewDescription(
bundle: TranslationBundle | undefined,
view: ViewLike,
opts?: ResolveOptions,
): string | undefined {
const objectName = viewObjectName(view);
if (bundle && objectName) {
for (const code of localeChain(opts)) {
const data = pickData(bundle, code);
const candidate =
data?.objects?.[objectName]?._views?.[view.name]?.description;
if (typeof candidate === 'string' && candidate.length > 0) return candidate;
}
}
return view.description;
}
function lookupActionField(
bundle: TranslationBundle | undefined,
action: ActionLike,
field: 'label' | 'confirmText' | 'successMessage',
opts?: ResolveOptions,
): string | undefined {
if (!bundle) return undefined;
for (const code of localeChain(opts)) {
const data = pickData(bundle, code);
if (!data) continue;
const fromObject = action.objectName
? data.objects?.[action.objectName]?._actions?.[action.name]?.[field]
: undefined;
if (typeof fromObject === 'string' && fromObject.length > 0) return fromObject;
const fromGlobal = data.globalActions?.[action.name]?.[field];
if (typeof fromGlobal === 'string' && fromGlobal.length > 0) return fromGlobal;
}
return undefined;
}
/**
* Resolve a translated action label, falling back to the literal `action.label`
* (or `action.name`) when no translation is available.
*/
export function resolveActionLabel(
bundle: TranslationBundle | undefined,
action: ActionLike,
opts?: ResolveOptions,
): string {
return (
lookupActionField(bundle, action, 'label', opts) ??
action.label ??
action.name
);
}
/**
* Resolve a translated confirmation prompt for an action, returning
* `undefined` if neither the bundle nor the action defines one.
*/
export function resolveActionConfirm(
bundle: TranslationBundle | undefined,
action: ActionLike,
opts?: ResolveOptions,
): string | undefined {
return lookupActionField(bundle, action, 'confirmText', opts) ?? action.confirmText;
}
/**
* Look up the translated `resultDialog` node for an action in a single
* locale's data (object-scoped first, then global). The node's `fields`
* record is keyed by the LITERAL result-field path (`"user.email"`), so it
* is indexed directly — never split on `.`.
*/
function lookupActionResultDialogNode(
data: TranslationData | undefined,
action: ActionLike,
): { title?: string; description?: string; acknowledge?: string; fields?: Record<string, string> } | undefined {
if (!data) return undefined;
const fromObject = action.objectName
? data.objects?.[action.objectName]?._actions?.[action.name]?.resultDialog
: undefined;
if (fromObject) return fromObject;
return data.globalActions?.[action.name]?.resultDialog;
}
function lookupActionResultDialogText(
bundle: TranslationBundle | undefined,
action: ActionLike,
pick: (node: NonNullable<ReturnType<typeof lookupActionResultDialogNode>>) => string | undefined,
opts?: ResolveOptions,
): string | undefined {
if (!bundle) return undefined;
for (const code of localeChain(opts)) {
const node = lookupActionResultDialogNode(pickData(bundle, code), action);
if (!node) continue;
const value = pick(node);
if (typeof value === 'string' && value.length > 0) return value;
}
return undefined;
}
/**
* Resolve a translated copy of an action's `resultDialog`, overlaying
* `title` / `description` / `acknowledge` and per-field `label`s (keyed by
* the literal field path) when translations exist. Returns the original
* spec untouched (same reference) when the action has no `resultDialog`;
* otherwise a shallow copy with translated strings merged in.
*/
export function resolveActionResultDialog<T extends ResultDialogLike>(
bundle: TranslationBundle | undefined,
action: ActionLike & { resultDialog?: T },
opts?: ResolveOptions,
): T | undefined {
const spec = action.resultDialog;
if (!spec) return spec;
const title = lookupActionResultDialogText(bundle, action, (n) => n.title, opts) ?? spec.title;
const description =
lookupActionResultDialogText(bundle, action, (n) => n.description, opts) ?? spec.description;
const acknowledge =
lookupActionResultDialogText(bundle, action, (n) => n.acknowledge, opts) ?? spec.acknowledge;
const fields = Array.isArray(spec.fields)
? spec.fields.map((field) => {
if (!field || typeof field.path !== 'string') return field;
const label =
lookupActionResultDialogText(bundle, action, (n) => n.fields?.[field.path], opts) ??
field.label;
return label !== undefined ? { ...field, label } : field;
})
: spec.fields;
return {
...spec,
...(title !== undefined ? { title } : {}),
...(description !== undefined ? { description } : {}),
...(acknowledge !== undefined ? { acknowledge } : {}),
...(fields !== undefined ? { fields } : {}),
};
}
/**
* Resolve a translated success message for an action, returning `undefined`
* if neither the bundle nor the action defines one.
*/
export function resolveActionSuccess(
bundle: TranslationBundle | undefined,
action: ActionLike,
opts?: ResolveOptions,
): string | undefined {
return (
lookupActionField(bundle, action, 'successMessage', opts) ??
action.successMessage
);
}
/**
* Apply the active locale to a view metadata document by overwriting `label`
* and `description` with translated values when available. The original
* document is not mutated; a shallow copy is returned. Useful for translating
* metadata at the API boundary so any client (Studio, app-shell, plain HTTP)
* receives already-localized labels.
*/
export function translateView<T extends ViewLike>(
view: T,
bundle: TranslationBundle | undefined,
opts?: ResolveOptions,
): T {
const label = resolveViewLabel(bundle, view, opts);
const description = resolveViewDescription(bundle, view, opts);
return { ...view, label, ...(description !== undefined ? { description } : {}) };
}
/**
* Apply the active locale to an action metadata document by overwriting
* `label`, `confirmText`, `successMessage`, and the `resultDialog` copy with
* translated values when available. The original document is not mutated; a
* shallow copy is returned.
*/
export function translateAction<T extends ActionLike>(
action: T,
bundle: TranslationBundle | undefined,
opts?: ResolveOptions,
): T {
const label = resolveActionLabel(bundle, action, opts);
const confirmText = resolveActionConfirm(bundle, action, opts);
const successMessage = resolveActionSuccess(bundle, action, opts);
const resultDialog = resolveActionResultDialog(bundle, action, opts);
return {
...action,
label,
...(confirmText !== undefined ? { confirmText } : {}),
...(successMessage !== undefined ? { successMessage } : {}),
...(resultDialog !== undefined ? { resultDialog } : {}),
};
}
/**
* Generic metadata translator: dispatches to `translateView` /
* `translateAction` based on metadata type. Returns the original document
* unchanged for unrecognised types.
*
* @param type Canonical metadata type string (see `MetadataTypeSchema`).
* @param doc The metadata document to translate.
* @param bundle Translation bundle (typically loaded from the i18n service).
* @param opts Locale + fallback chain.
*/
export function translateMetadataDocument(
type: string,
doc: any,
bundle: TranslationBundle | undefined,
opts?: ResolveOptions,
): any {
if (!doc || typeof doc !== 'object') return doc;
if (type === 'view') return translateView(doc, bundle, opts);
if (type === 'action') return translateAction(doc, bundle, opts);
if (type === 'object') return translateObject(doc, bundle, opts);
if (type === 'app') return translateApp(doc, bundle, opts);
if (type === 'dashboard') return translateDashboard(doc, bundle, opts);
return doc;
}
// ────────────────────────────────────────────────────────────────────────────
// App metadata resolvers (label / description / navigation labels)
// ────────────────────────────────────────────────────────────────────────────
/** Minimal navigation-node shape consumed by `translateApp`. */
export interface NavNodeLike {
id?: string;
label?: string;
children?: NavNodeLike[];
[key: string]: any;
}
/** Minimal app metadata shape consumed by `translateApp`. */
export interface AppLike {
name: string;
label?: string;
description?: string;
navigation?: NavNodeLike[];
[key: string]: any;
}
function lookupAppAttr(
bundle: TranslationBundle | undefined,
appName: string,
attr: 'label' | 'description',
opts?: ResolveOptions,
): string | undefined {
if (!bundle) return undefined;
for (const code of localeChain(opts)) {
const candidate = pickData(bundle, code)?.apps?.[appName]?.[attr];
if (typeof candidate === 'string' && candidate.length > 0) return candidate;
}
return undefined;
}
function lookupNavLabel(
bundle: TranslationBundle | undefined,
appName: string,
navId: string,
opts?: ResolveOptions,
): string | undefined {
if (!bundle) return undefined;
for (const code of localeChain(opts)) {
const candidate = pickData(bundle, code)?.apps?.[appName]?.navigation?.[navId]?.label;
if (typeof candidate === 'string' && candidate.length > 0) return candidate;
}
return undefined;
}
/**
* Apply the active locale to an app metadata document — translates the app's
* `label` / `description` and walks the (possibly nested) `navigation` tree,
* replacing each node's `label` with `apps.<app>.navigation.<id>.label` when a
* translation exists. The input document is not mutated.
*
* Translation keys are addressed by the stable navigation-node `id`
* (e.g. `group_overview`, `nav_users`) — the same flat keyspace used by the
* `apps.<app>.navigation` map, regardless of tree depth.
*/
export function translateApp<T extends AppLike>(
doc: T,
bundle: TranslationBundle | undefined,
opts?: ResolveOptions,
): T {
if (!doc || typeof doc !== 'object') return doc;
const appName = doc.name;
if (!appName || !bundle) return doc;
const label = lookupAppAttr(bundle, appName, 'label', opts) ?? doc.label;
const description = lookupAppAttr(bundle, appName, 'description', opts) ?? doc.description;
const translateNav = (node: NavNodeLike): NavNodeLike => {
if (!node || typeof node !== 'object') return node;
const next: NavNodeLike = { ...node };
if (typeof node.id === 'string') {
const translated = lookupNavLabel(bundle, appName, node.id, opts);
if (translated) next.label = translated;
}
if (Array.isArray(node.children)) {
next.children = node.children.map(translateNav);
}
return next;
};
const navigation = Array.isArray(doc.navigation)
? doc.navigation.map(translateNav)
: doc.navigation;
return {
...doc,
...(label !== undefined ? { label } : {}),
...(description !== undefined ? { description } : {}),
...(navigation !== undefined ? { navigation } : {}),
};
}
// ────────────────────────────────────────────────────────────────────────────
// Dashboard metadata resolvers (label / description / widget titles)
// ────────────────────────────────────────────────────────────────────────────
/** Minimal widget shape consumed by `translateDashboard`. */
export interface WidgetLike {
id?: string;
title?: string;
description?: string;
[key: string]: any;
}
/** Minimal dashboard metadata shape consumed by `translateDashboard`. */
export interface DashboardLike {
name: string;
label?: string;
description?: string;
widgets?: WidgetLike[];
[key: string]: any;
}
function lookupDashboardAttr(
bundle: TranslationBundle | undefined,
name: string,
attr: 'label' | 'description',
opts?: ResolveOptions,
): string | undefined {
if (!bundle) return undefined;
for (const code of localeChain(opts)) {
const candidate = pickData(bundle, code)?.dashboards?.[name]?.[attr];
if (typeof candidate === 'string' && candidate.length > 0) return candidate;
}
return undefined;
}
function lookupWidgetAttr(
bundle: TranslationBundle | undefined,
dashboardName: string,
widgetId: string,
attr: 'title' | 'description',
opts?: ResolveOptions,
): string | undefined {
if (!bundle) return undefined;
for (const code of localeChain(opts)) {
const candidate =
pickData(bundle, code)?.dashboards?.[dashboardName]?.widgets?.[widgetId]?.[attr];
if (typeof candidate === 'string' && candidate.length > 0) return candidate;
}
return undefined;
}
/**
* Apply the active locale to a dashboard metadata document — translates the
* dashboard's `label` / `description` and each widget's `title` /
* `description` against `dashboards.<name>.widgets.<id>.*`. The input document
* is not mutated.
*/
export function translateDashboard<T extends DashboardLike>(
doc: T,
bundle: TranslationBundle | undefined,
opts?: ResolveOptions,
): T {
if (!doc || typeof doc !== 'object') return doc;
const name = doc.name;
if (!name || !bundle) return doc;
const label = lookupDashboardAttr(bundle, name, 'label', opts) ?? doc.label;
const description = lookupDashboardAttr(bundle, name, 'description', opts) ?? doc.description;
const widgets = Array.isArray(doc.widgets)
? doc.widgets.map((w) => {
if (!w || typeof w !== 'object' || typeof w.id !== 'string') return w;
const next: WidgetLike = { ...w };
const title = lookupWidgetAttr(bundle, name, w.id, 'title', opts);
if (title) next.title = title;
const desc = lookupWidgetAttr(bundle, name, w.id, 'description', opts);
if (desc) next.description = desc;
return next;
})
: doc.widgets;
return {
...doc,
...(label !== undefined ? { label } : {}),
...(description !== undefined ? { description } : {}),
...(widgets !== undefined ? { widgets } : {}),
};
}
// ────────────────────────────────────────────────────────────────────────────
// Object metadata resolvers (label / pluralLabel / description / fields / options)
// ────────────────────────────────────────────────────────────────────────────
/** Minimal object metadata shape consumed by `translateObject`. */
export interface ObjectLike {
name: string;
label?: string;
pluralLabel?: string;
description?: string;
fields?: Record<string, ObjectFieldLike> | ObjectFieldLike[];
}
export interface ObjectFieldLike {
name?: string;
label?: string;
help?: string;
description?: string;
options?: Array<{ label?: string; value: string | number | boolean }>;
[key: string]: any;
}
function lookupObjectField<K extends 'label' | 'pluralLabel' | 'description'>(
bundle: TranslationBundle | undefined,
objectName: string,
field: K,
opts?: ResolveOptions,
): string | undefined {
if (!bundle) return undefined;
for (const code of localeChain(opts)) {
const data = pickData(bundle, code);
const candidate = data?.objects?.[objectName]?.[field];
if (typeof candidate === 'string' && candidate.length > 0) return candidate;
}
return undefined;
}
function lookupObjectFieldAttr(
bundle: TranslationBundle | undefined,
objectName: string,
fieldName: string,
attr: 'label' | 'help' | 'description',
opts?: ResolveOptions,
): string | undefined {
if (!bundle) return undefined;
for (const code of localeChain(opts)) {
const data = pickData(bundle, code);
const candidate = (data?.objects?.[objectName]?.fields?.[fieldName] as any)?.[attr];
if (typeof candidate === 'string' && candidate.length > 0) return candidate;
}
return undefined;
}
function lookupObjectFieldOption(
bundle: TranslationBundle | undefined,
objectName: string,
fieldName: string,
optionValue: string | number | boolean,
opts?: ResolveOptions,
): string | undefined {
if (!bundle) return undefined;
const key = String(optionValue);
for (const code of localeChain(opts)) {
const data = pickData(bundle, code);
const map = data?.objects?.[objectName]?.fields?.[fieldName]?.options as
| Record<string, string>
| undefined;
const candidate = map?.[key];
if (typeof candidate === 'string' && candidate.length > 0) return candidate;
}
return undefined;
}
/**
* Built-in labels for the platform-injected system fields (the ObjectQL
* registry stamps `owner_id` / `created_*` / `updated_*` onto every object
* with English labels). Custom objects carry no per-object translation
* entries for these, so without a fallback every localized surface — list
* headers, export files, import templates — leaks the English default (e.g.
* an otherwise fully-Chinese import template with an `Owner` column).
*
* Wording matches the generated platform bundles (`*.objects.generated.ts`)
* so a system field reads the same on custom and platform objects.
*/
const SYSTEM_FIELD_LABELS: Record<string, Record<string, string>> = {
owner_id: { en: 'Owner', 'zh-CN': '所有者', 'ja-JP': '所有者', 'es-ES': 'Propietario' },
created_at: { en: 'Created At', 'zh-CN': '创建时间', 'ja-JP': '作成日時', 'es-ES': 'Creado el' },
created_by: { en: 'Created By', 'zh-CN': '创建人', 'ja-JP': '作成者', 'es-ES': 'Creado por' },
updated_at: { en: 'Last Modified At', 'zh-CN': '更新时间', 'ja-JP': '更新日時', 'es-ES': 'Actualizado el' },
updated_by: { en: 'Last Modified By', 'zh-CN': '更新人', 'ja-JP': '更新者', 'es-ES': 'Actualizado por' },
};
/**
* Fallback label for a platform-injected system field, honouring the same
* locale-matching rules as bundle lookup (exact → case-insensitive → base
* language → variant). Applied only when the field still carries its injected
* English default — an author's custom label is never overridden.
*/
function builtinSystemFieldLabel(
fieldName: string,
currentLabel: string | undefined,
opts?: ResolveOptions,
): string | undefined {
const entry = SYSTEM_FIELD_LABELS[fieldName];
if (!entry) return undefined;
if (currentLabel !== undefined && currentLabel !== entry.en) return undefined;
for (const code of localeChain(opts)) {
const resolved = resolveBundleLocale(entry, code);
if (resolved !== undefined) return entry[resolved];
}
return undefined;
}
/**
* Apply the active locale to an object metadata document. Translates the
* object's `label` / `pluralLabel` / `description` and walks each field to
* translate its `label`, `help`, and per-option `label`s. The input document
* is not mutated; a structural clone of the touched branches is returned.
*
* Field maps come in two shapes across the codebase: a `Record<string, Field>`
* (preferred — the canonical authored shape) and an `Array<Field>` (some REST
* responses flatten the record). Both are supported; the function returns the
* same shape it was given.
*/
export function translateObject<T extends ObjectLike>(
doc: T,
bundle: TranslationBundle | undefined,
opts?: ResolveOptions,
): T {
if (!doc || typeof doc !== 'object') return doc;
const objectName = doc.name;
// Proceed even without a bundle: the built-in system-field labels below
// still apply (custom objects typically ship no translation entries).
if (!objectName) return doc;
const label = lookupObjectField(bundle, objectName, 'label', opts) ?? doc.label;
const pluralLabel =
lookupObjectField(bundle, objectName, 'pluralLabel', opts) ?? doc.pluralLabel;
const description =
lookupObjectField(bundle, objectName, 'description', opts) ?? doc.description;
const translateField = (name: string, def: ObjectFieldLike): ObjectFieldLike => {
const next: ObjectFieldLike = { ...def };
const translatedLabel =
lookupObjectFieldAttr(bundle, objectName, name, 'label', opts) ??
builtinSystemFieldLabel(name, def.label, opts);
if (translatedLabel) next.label = translatedLabel;
const translatedHelp = lookupObjectFieldAttr(bundle, objectName, name, 'help', opts);
if (translatedHelp) next.help = translatedHelp;
if (Array.isArray(def.options)) {
next.options = def.options.map((opt) => {
if (!opt || typeof opt !== 'object' || opt.value === undefined) return opt;
const translated = lookupObjectFieldOption(bundle, objectName, name, opt.value, opts);
return translated ? { ...opt, label: translated } : opt;
});
}
return next;
};
let fields: ObjectLike['fields'] = doc.fields;
if (Array.isArray(doc.fields)) {
fields = doc.fields.map((f) => translateField(f.name ?? '', f));
} else if (doc.fields && typeof doc.fields === 'object') {
const next: Record<string, ObjectFieldLike> = {};
for (const [name, def] of Object.entries(doc.fields)) {
next[name] = translateField(name, def);
}
fields = next;
}
return {
...doc,
...(label !== undefined ? { label } : {}),
...(pluralLabel !== undefined ? { pluralLabel } : {}),
...(description !== undefined ? { description } : {}),
...(fields !== undefined ? { fields } : {}),
};
}
// ────────────────────────────────────────────────────────────────────────────
// Settings (SettingsManifest) resolvers
// ────────────────────────────────────────────────────────────────────────────
function pickSettingsEntry(
bundle: TranslationBundle | undefined,
namespace: string,
locale: string,
) {
return pickData(bundle, locale)?.settings?.[namespace];
}
function resolveOptionalString(
bundle: TranslationBundle | undefined,
namespace: string,
pick: (entry: NonNullable<ReturnType<typeof pickSettingsEntry>>) => string | undefined,
opts?: ResolveOptions,
): string | undefined {
if (!bundle) return undefined;
for (const code of localeChain(opts)) {
const entry = pickSettingsEntry(bundle, namespace, code);
if (!entry) continue;
const value = pick(entry);
if (typeof value === 'string' && value.length > 0) return value;
}
return undefined;
}
/** Resolve manifest title; falls back to literal. */
export function resolveSettingsTitle(
bundle: TranslationBundle | undefined,
namespace: string,
fallback: string,
opts?: ResolveOptions,
): string {
return resolveOptionalString(bundle, namespace, (e) => e.title, opts) ?? fallback;
}
/** Resolve manifest description. Returns literal (possibly undefined) when no translation found. */
export function resolveSettingsDescription(
bundle: TranslationBundle | undefined,
namespace: string,
fallback: string | undefined,
opts?: ResolveOptions,
): string | undefined {
return resolveOptionalString(bundle, namespace, (e) => e.description, opts) ?? fallback;
}
/** Resolve a group title under `settings.<namespace>.groups.<group>.title`. */
export function resolveSettingsGroupTitle(
bundle: TranslationBundle | undefined,
namespace: string,
groupKey: string,
fallback: string,
opts?: ResolveOptions,
): string {
return (
resolveOptionalString(bundle, namespace, (e) => e.groups?.[groupKey]?.title, opts)
?? fallback
);
}
export function resolveSettingsGroupDescription(
bundle: TranslationBundle | undefined,
namespace: string,
groupKey: string,
fallback: string | undefined,
opts?: ResolveOptions,
): string | undefined {
return (
resolveOptionalString(bundle, namespace, (e) => e.groups?.[groupKey]?.description, opts)
?? fallback
);
}
/** Resolve a setting field label under `settings.<namespace>.keys.<key>.label`. */
export function resolveSettingsFieldLabel(
bundle: TranslationBundle | undefined,
namespace: string,
key: string,
fallback: string,
opts?: ResolveOptions,
): string {
return (
resolveOptionalString(bundle, namespace, (e) => e.keys?.[key]?.label, opts) ?? fallback
);
}
export function resolveSettingsFieldHelp(
bundle: TranslationBundle | undefined,
namespace: string,
key: string,
fallback: string | undefined,
opts?: ResolveOptions,
): string | undefined {
return (
resolveOptionalString(bundle, namespace, (e) => e.keys?.[key]?.help, opts) ?? fallback
);
}
export function resolveSettingsFieldPlaceholder(
bundle: TranslationBundle | undefined,
namespace: string,
key: string,
fallback: string | undefined,
opts?: ResolveOptions,
): string | undefined {
return (
resolveOptionalString(bundle, namespace, (e) => e.keys?.[key]?.placeholder, opts)
?? fallback
);
}
/** Resolve an enum option label under `settings.<namespace>.keys.<key>.options.<value>`. */
export function resolveSettingsOptionLabel(
bundle: TranslationBundle | undefined,
namespace: string,
key: string,
optionValue: string,
fallback: string,
opts?: ResolveOptions,
): string {
return (
resolveOptionalString(
bundle,
namespace,
(e) => e.keys?.[key]?.options?.[optionValue],
opts,
) ?? fallback
);
}
/** Resolve an action button label under `settings.<namespace>.actions.<actionId>.label`. */
export function resolveSettingsActionLabel(
bundle: TranslationBundle | undefined,
namespace: string,
actionId: string,
fallback: string,
opts?: ResolveOptions,
): string {
return (
resolveOptionalString(bundle, namespace, (e) => e.actions?.[actionId]?.label, opts)
?? fallback
);
}
export function resolveSettingsActionConfirm(
bundle: TranslationBundle | undefined,
namespace: string,
actionId: string,
fallback: string | undefined,
opts?: ResolveOptions,
): string | undefined {
return (
resolveOptionalString(bundle, namespace, (e) => e.actions?.[actionId]?.confirmText, opts)
?? fallback
);
}
export function resolveSettingsActionSuccess(
bundle: TranslationBundle | undefined,
namespace: string,
actionId: string,
fallback: string | undefined,
opts?: ResolveOptions,
): string | undefined {
return (
resolveOptionalString(bundle, namespace, (e) => e.actions?.[actionId]?.successMessage, opts)
?? fallback
);
}
// ────────────────────────────────────────────────────────────────────────────
// SettingsCommon — cross-namespace UI strings (source badges, etc.)
// ────────────────────────────────────────────────────────────────────────────
/**
* Resolve the human label for a `ResolvedSettingValue.source` value.
* Walks the locale chain and falls back to the literal source key
* (capitalised by the caller if desired) when no translation exists.
*/
export function resolveSettingsSourceLabel(
bundle: TranslationBundle | undefined,
source: 'env' | 'global' | 'tenant' | 'user' | 'default',
fallback: string,
opts?: ResolveOptions,
): string {
if (!bundle) return fallback;
for (const code of localeChain(opts)) {
const label = pickData(bundle, code)?.settingsCommon?.sourceLabels?.[source];
if (typeof label === 'string' && label.length > 0) return label;
}
return fallback;
}
// ────────────────────────────────────────────────────────────────────────────
// MetadataForms — metadata-type configuration form resolvers
// ────────────────────────────────────────────────────────────────────────────
//
// Translates the `form` payload returned by `getMetaTypes()` (the editor
// layout for authoring objects/fields/agents/flows/etc.) against the
// `metadataForms.<type>` namespace of the active translation bundle.
//
// Naming conventions:
//
// metadataForms.<type>.label -- type display label
// metadataForms.<type>.description -- type description
// metadataForms.<type>.sections.<section_name>.label -- section header
// metadataForms.<type>.sections.<section_name>.description
// metadataForms.<type>.fields.<field_path>.label -- field label
// metadataForms.<type>.fields.<field_path>.helpText
// metadataForms.<type>.fields.<field_path>.placeholder
//
// `field_path` is dot-notation for nested fields. Top-level form fields use
// just the field name (e.g. `"name"`, `"description"`). Composite and
// repeater children are addressed via parent path:
//
// "capabilities.trackHistory" // composite "capabilities" → "trackHistory"
// "fields.items.label" // repeater "fields" → row → "label"
//
// All helpers are pure (immutable) — they return a new form object with
// the translated branches when matches exist, or the input unchanged when
// no bundle / no locale match.
function lookupMetadataForm(
bundle: TranslationBundle | undefined,
type: string,
opts?: ResolveOptions,
): { entry: any; locale: string } | undefined {
if (!bundle) return undefined;
for (const code of localeChain(opts)) {
const entry = pickData(bundle, code)?.metadataForms?.[type];
if (entry && typeof entry === 'object') return { entry, locale: code };
}
return undefined;
}
function lookupMetadataFormSection(
bundle: TranslationBundle | undefined,
type: string,
sectionName: string,
attr: 'label' | 'description',
opts?: ResolveOptions,
): string | undefined {
if (!bundle) return undefined;
for (const code of localeChain(opts)) {
const candidate = pickData(bundle, code)?.metadataForms?.[type]?.sections?.[sectionName]?.[attr];
if (typeof candidate === 'string' && candidate.length > 0) return candidate;
}
return undefined;
}
function lookupMetadataFormField(
bundle: TranslationBundle | undefined,
type: string,