Repository navigation
Expand file tree
/
Copy pathfallbacks.test.ts
More file actions
724 lines (632 loc) · 33.9 KB
/
Copy pathfallbacks.test.ts
File metadata and controls
724 lines (632 loc) · 33.9 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
import { describe, it, expect } from 'vitest';
import { createMemoryCache } from './memory-cache';
import { createMemoryQueue } from './memory-queue';
import { createMemoryJob } from './memory-job';
import { createMemoryI18n, resolveLocale, resolveOfferedLocale } from './memory-i18n';
import { CORE_FALLBACK_FACTORIES } from './index';
import { readServiceSelfInfo } from '@objectstack/spec/api';
import { resolveBundleLocale } from '@objectstack/spec/system';
describe('CORE_FALLBACK_FACTORIES', () => {
// [#10746] `job` is deliberately OFF this list — a fallback must not fake
// capability (maintainer ruling 2026-08-22). `createMemoryJob().schedule()`
// records a job and never fires it, so pre-injecting it made consumers
// treat "a `job` service resolves" as "a working scheduler" and silently
// never run. The factory stays exported for deliberate, explicit use; the
// kernel must not hand it out as if it honoured `schedule()`.
it('should have exactly 4 entries: metadata, cache, queue, i18n — job deliberately absent (#10746)', () => {
expect(Object.keys(CORE_FALLBACK_FACTORIES)).toEqual(['metadata', 'cache', 'queue', 'i18n']);
});
// [#4058] Every kernel fallback must be readable through the ONE standard
// descriptor. They used to carry `_fallback: true`, which `readServiceSelfInfo`
// does not recognize — so each of them was reported as a fully available
// service by both discovery builders.
it('every fallback self-describes via the standard D12 descriptor', () => {
for (const [name, factory] of Object.entries(CORE_FALLBACK_FACTORIES)) {
const info = readServiceSelfInfo(factory());
expect(info, `${name} must carry __serviceInfo`).toBeDefined();
// These are real implementations with reduced capability — never fakes.
expect(info?.status, `${name} status`).toBe('degraded');
expect(info?.message, `${name} message`).toBeTruthy();
}
});
it('should map to factory functions', () => {
for (const factory of Object.values(CORE_FALLBACK_FACTORIES)) {
expect(typeof factory).toBe('function');
}
});
});
describe('createMemoryCache', () => {
// [#4058] Self-describes with the STANDARD D12 descriptor. The old
// `_fallback: true` marker was read by nothing, so discovery reported
// this as fully `available` — the honesty gap D12 exists to close.
it('self-describes as a degraded implementation, not a stub', () => {
const cache = createMemoryCache();
expect(readServiceSelfInfo(cache)?.status).toBe('degraded');
expect(readServiceSelfInfo(cache)?.handlerReady).toBe(false); // no HTTP surface for cache
expect(readServiceSelfInfo(cache)?.message).toBeTruthy();
expect(cache._serviceName).toBe('cache');
});
it('should set and get a value', async () => {
const cache = createMemoryCache();
await cache.set('key1', 'value1');
expect(await cache.get('key1')).toBe('value1');
});
it('should return undefined for missing key', async () => {
const cache = createMemoryCache();
expect(await cache.get('nonexistent')).toBeUndefined();
});
it('should delete a key', async () => {
const cache = createMemoryCache();
await cache.set('key1', 'value1');
expect(await cache.delete('key1')).toBe(true);
expect(await cache.get('key1')).toBeUndefined();
});
it('should check if a key exists with has()', async () => {
const cache = createMemoryCache();
expect(await cache.has('key1')).toBe(false);
await cache.set('key1', 'value1');
expect(await cache.has('key1')).toBe(true);
});
it('should clear all entries', async () => {
const cache = createMemoryCache();
await cache.set('a', 1);
await cache.set('b', 2);
await cache.clear();
expect(await cache.has('a')).toBe(false);
expect(await cache.has('b')).toBe(false);
});
it('should expire entries based on TTL', async () => {
const cache = createMemoryCache();
// Set with very short TTL (0.001 seconds = 1ms)
await cache.set('temp', 'data', 0.001);
// Wait for expiry
await new Promise(r => setTimeout(r, 20));
expect(await cache.get('temp')).toBeUndefined();
});
it('should track hit/miss stats', async () => {
const cache = createMemoryCache();
await cache.set('key1', 'value1');
await cache.get('key1'); // hit
await cache.get('missing'); // miss
const stats = await cache.stats();
expect(stats.hits).toBe(1);
expect(stats.misses).toBe(1);
expect(stats.keyCount).toBe(1);
});
});
describe('createMemoryQueue', () => {
// [#4058] Self-describes with the STANDARD D12 descriptor. The old
// `_fallback: true` marker was read by nothing, so discovery reported
// this as fully `available` — the honesty gap D12 exists to close.
it('self-describes as a degraded implementation, not a stub', () => {
const queue = createMemoryQueue();
expect(readServiceSelfInfo(queue)?.status).toBe('degraded');
expect(readServiceSelfInfo(queue)?.handlerReady).toBe(false); // no HTTP surface for queue
expect(readServiceSelfInfo(queue)?.message).toBeTruthy();
expect(queue._serviceName).toBe('queue');
});
it('should publish and deliver to subscriber synchronously', async () => {
const queue = createMemoryQueue();
const received: any[] = [];
await queue.subscribe('test-q', async (msg: any) => { received.push(msg); });
const id = await queue.publish('test-q', { hello: 'world' });
expect(id).toMatch(/^fallback-msg-/);
expect(received).toHaveLength(1);
expect(received[0].data).toEqual({ hello: 'world' });
});
it('should not deliver to unsubscribed queue', async () => {
const queue = createMemoryQueue();
const received: any[] = [];
await queue.subscribe('q1', async (msg: any) => { received.push(msg); });
await queue.unsubscribe('q1');
await queue.publish('q1', 'data');
expect(received).toHaveLength(0);
});
it('should return queue size of 0', async () => {
const queue = createMemoryQueue();
expect(await queue.getQueueSize()).toBe(0);
});
it('should purge a queue', async () => {
const queue = createMemoryQueue();
const received: any[] = [];
await queue.subscribe('q1', async (msg: any) => { received.push(msg); });
await queue.purge('q1');
await queue.publish('q1', 'data');
expect(received).toHaveLength(0);
});
});
describe('createMemoryJob', () => {
// [#4058] Self-describes with the STANDARD D12 descriptor. The old
// `_fallback: true` marker was read by nothing, so discovery reported
// this as fully `available` — the honesty gap D12 exists to close.
it('self-describes as a degraded implementation, not a stub', () => {
const job = createMemoryJob();
expect(readServiceSelfInfo(job)?.status).toBe('degraded');
expect(readServiceSelfInfo(job)?.handlerReady).toBe(false); // no HTTP surface for job
expect(readServiceSelfInfo(job)?.message).toBeTruthy();
expect(job._serviceName).toBe('job');
});
it('should schedule and list jobs', async () => {
const job = createMemoryJob();
await job.schedule('daily-report', '0 0 * * *', async () => {});
expect(await job.listJobs()).toEqual(['daily-report']);
});
it('should cancel a job', async () => {
const job = createMemoryJob();
await job.schedule('temp-job', '* * * * *', async () => {});
await job.cancel('temp-job');
expect(await job.listJobs()).toEqual([]);
});
it('should trigger a job handler', async () => {
const job = createMemoryJob();
let triggered = false;
await job.schedule('my-job', '* * * * *', async (ctx: any) => {
triggered = true;
expect(ctx.jobId).toBe('my-job');
expect(ctx.data).toEqual({ key: 'val' });
});
await job.trigger('my-job', { key: 'val' });
expect(triggered).toBe(true);
});
it('should return empty executions', async () => {
const job = createMemoryJob();
expect(await job.getExecutions()).toEqual([]);
});
});
describe('createMemoryI18n', () => {
// [#4058] Self-describes with the STANDARD D12 descriptor. The old
// `_fallback: true` marker was read by nothing, so discovery reported
// this as fully `available` — the honesty gap D12 exists to close.
it('self-describes as a degraded implementation, not a stub', () => {
const i18n = createMemoryI18n();
expect(readServiceSelfInfo(i18n)?.status).toBe('degraded');
expect(readServiceSelfInfo(i18n)?.handlerReady).toBe(true); // the dispatcher's /i18n domain serves it
expect(readServiceSelfInfo(i18n)?.message).toBeTruthy();
expect(i18n._serviceName).toBe('i18n');
});
it('should return the key when no translations are loaded', () => {
const i18n = createMemoryI18n();
expect(i18n.t('objects.account.label', 'en')).toBe('objects.account.label');
});
it('should translate after loading translations', () => {
const i18n = createMemoryI18n();
i18n.loadTranslations('en', { objects: { account: { label: 'Account' } } });
expect(i18n.t('objects.account.label', 'en')).toBe('Account');
});
it('should interpolate parameters', () => {
const i18n = createMemoryI18n();
i18n.loadTranslations('en', { greeting: 'Hello, {{name}}!' });
expect(i18n.t('greeting', 'en', { name: 'World' })).toBe('Hello, World!');
});
it('should fall back to default locale', () => {
const i18n = createMemoryI18n();
i18n.loadTranslations('en', { hello: 'Hello' });
// 'fr' has no translations, should fall back to default 'en'
expect(i18n.t('hello', 'fr')).toBe('Hello');
});
it('should get and set default locale', () => {
const i18n = createMemoryI18n();
expect(i18n.getDefaultLocale()).toBe('en');
i18n.setDefaultLocale('zh-CN');
expect(i18n.getDefaultLocale()).toBe('zh-CN');
});
it('should list loaded locales', () => {
const i18n = createMemoryI18n();
expect(i18n.getLocales()).toEqual([]);
i18n.loadTranslations('en', { hello: 'Hello' });
i18n.loadTranslations('zh-CN', { hello: '你好' });
expect(i18n.getLocales()).toEqual(['en', 'zh-CN']);
});
it('should get all translations for a locale', () => {
const i18n = createMemoryI18n();
i18n.loadTranslations('en', { hello: 'Hello', bye: 'Goodbye' });
expect(i18n.getTranslations('en')).toEqual({ hello: 'Hello', bye: 'Goodbye' });
});
it('should return empty object for unknown locale', () => {
const i18n = createMemoryI18n();
expect(i18n.getTranslations('unknown')).toEqual({});
});
it('should merge translations on subsequent loads', () => {
const i18n = createMemoryI18n();
i18n.loadTranslations('en', { hello: 'Hello' });
i18n.loadTranslations('en', { bye: 'Goodbye' });
expect(i18n.getTranslations('en')).toEqual({ hello: 'Hello', bye: 'Goodbye' });
});
});
describe('resolveLocale', () => {
it('should return exact match', () => {
expect(resolveLocale('zh-CN', ['en', 'zh-CN', 'ja'])).toBe('zh-CN');
});
it('should return case-insensitive match', () => {
expect(resolveLocale('zh-cn', ['en', 'zh-CN'])).toBe('zh-CN');
expect(resolveLocale('EN-US', ['en-US', 'zh-CN'])).toBe('en-US');
});
it('should return base language match', () => {
expect(resolveLocale('zh-TW', ['en', 'zh'])).toBe('zh');
});
it('should return variant expansion (zh → zh-CN)', () => {
expect(resolveLocale('zh', ['en', 'zh-CN', 'zh-TW'])).toBe('zh-CN');
});
it('should return undefined for no match', () => {
expect(resolveLocale('fr', ['en', 'zh-CN'])).toBeUndefined();
});
it('should return undefined for empty available locales', () => {
expect(resolveLocale('en', [])).toBeUndefined();
});
it('should handle es → es-ES expansion', () => {
expect(resolveLocale('es', ['en', 'es-ES', 'fr'])).toBe('es-ES');
});
});
// One case list, run against core's `resolveLocale` (a list) and the spec's
// `resolveBundleLocale` (a bundle's keys), so the two server resolvers cannot
// drift. The platform locale table's read aliases decide before any
// base-language or first-variant guess: a Traditional reader reaches a
// registered `zh-Hant`, a Simplified one `zh-CN`, in either registration order.
describe('resolveLocale and resolveBundleLocale — one shared case list', () => {
const CASES: Array<[requested: string, available: string[], expected: string | undefined]> = [
['zh-TW', ['en', 'zh-CN', 'zh-Hant'], 'zh-Hant'],
['zh-TW', ['en', 'zh-Hant', 'zh-CN'], 'zh-Hant'],
['zh-HK', ['en', 'zh-CN', 'zh-Hant'], 'zh-Hant'],
['zh-HK', ['en', 'zh-Hant', 'zh-CN'], 'zh-Hant'],
['zh-MO', ['en', 'zh-CN', 'zh-Hant'], 'zh-Hant'],
['zh-MO', ['en', 'zh-Hant', 'zh-CN'], 'zh-Hant'],
['zh-CN', ['en', 'zh-CN', 'zh-Hant'], 'zh-CN'],
['zh-CN', ['en', 'zh-Hant', 'zh-CN'], 'zh-CN'],
['zh', ['en', 'zh-Hant', 'zh-CN'], 'zh-CN'],
['zh-SG', ['en', 'zh-Hant', 'zh-CN'], 'zh-CN'],
['zh-Hans', ['en', 'zh-Hant', 'zh-CN'], 'zh-CN'],
['zh-TW', ['en', 'zh', 'zh-Hant'], 'zh-Hant'],
// The script-subtag spellings a browser or OS sends are read aliases too.
['zh-Hant-TW', ['en', 'zh-CN', 'zh-Hant'], 'zh-Hant'],
['zh-Hant-TW', ['en', 'zh-Hant', 'zh-CN'], 'zh-Hant'],
['zh-Hant-HK', ['en', 'zh-CN', 'zh-Hant'], 'zh-Hant'],
['zh-Hant-HK', ['en', 'zh-Hant', 'zh-CN'], 'zh-Hant'],
['zh-Hant-MO', ['en', 'zh-CN', 'zh-Hant'], 'zh-Hant'],
['zh-Hant-MO', ['en', 'zh-Hant', 'zh-CN'], 'zh-Hant'],
['zh-Hans-CN', ['en', 'zh-CN', 'zh-Hant'], 'zh-CN'],
['zh-Hans-CN', ['en', 'zh-Hant', 'zh-CN'], 'zh-CN'],
['zh-Hans-SG', ['en', 'zh-CN', 'zh-Hant'], 'zh-CN'],
['zh-Hans-SG', ['en', 'zh-Hant', 'zh-CN'], 'zh-CN'],
['ZH-HANT-tw', ['en', 'zh-CN', 'zh-Hant'], 'zh-Hant'],
['zh-Hant-TW', ['en', 'zh', 'zh-Hant'], 'zh-Hant'],
// ...and so are keys spelled that way: a key counts as the script it names.
['zh-TW', ['en', 'zh-CN', 'zh-Hant-TW'], 'zh-Hant-TW'],
['zh-TW', ['en', 'zh-Hant-TW', 'zh-CN'], 'zh-Hant-TW'],
['zh-Hant', ['en', 'zh-CN', 'zh-Hant-TW'], 'zh-Hant-TW'],
['zh-Hant', ['en', 'zh-Hant-TW', 'zh-CN'], 'zh-Hant-TW'],
['zh-CN', ['en', 'zh-Hant', 'zh-Hans-CN'], 'zh-Hans-CN'],
['zh-CN', ['en', 'zh-Hans-CN', 'zh-Hant'], 'zh-Hans-CN'],
['zh-Hant-TW', ['en', 'zh', 'zh-Hant-HK'], 'zh-Hant-HK'],
['zh-Hant-TW', ['en', 'zh-Hant-HK', 'zh'], 'zh-Hant-HK'],
// One script registered: a related language still beats none.
['zh-Hant-TW', ['en', 'zh-CN'], 'zh-CN'],
// Today's alias-spelled bundles keep answering.
['ja', ['en', 'zh-CN', 'ja-JP', 'es-ES'], 'ja-JP'],
['es', ['en', 'zh-CN', 'ja-JP', 'es-ES'], 'es-ES'],
['zh-TW', ['en', 'zh-CN', 'ja-JP', 'es-ES'], 'zh-CN'],
['zh-TW', ['en', 'zh'], 'zh'],
// A code the table does not know falls back as before.
['es-MX', ['en', 'es-ES'], 'es-ES'],
['en-GB', ['en-US', 'en'], 'en'],
['fr', ['en', 'zh-CN'], undefined],
['zh-TW', [], undefined],
];
it.each(CASES)('resolveLocale(%s, %j) → %s', (requested, available, expected) => {
expect(resolveLocale(requested, available)).toBe(expected);
});
it.each(CASES)('resolveBundleLocale(%j over %j) → %s', (requested, available, expected) => {
const bundle = Object.fromEntries(available.map((code) => [code, {}]));
expect(resolveBundleLocale(bundle, requested)).toBe(expected);
});
it('a zh-HK reader of the in-memory service gets the zh-Hant bundle', () => {
const i18n = createMemoryI18n();
i18n.loadTranslations('en', { settings: 'Settings' });
i18n.loadTranslations('zh-CN', { settings: '设置' });
i18n.loadTranslations('zh-Hant', { settings: '設定' });
expect(i18n.t('settings', 'zh-HK')).toBe('設定');
expect(i18n.t('settings', 'zh')).toBe('设置');
});
it.each<[order: string, loadOrder: string[]]>([
['Simplified loaded first', ['zh-CN', 'zh-Hant']],
['Traditional loaded first', ['zh-Hant', 'zh-CN']],
])('a script-subtag reader of the in-memory service gets its own script (%s)', (_order, loadOrder) => {
const text: Record<string, string> = { 'zh-CN': '设置', 'zh-Hant': '設定' };
const i18n = createMemoryI18n();
i18n.loadTranslations('en', { settings: 'Settings' });
for (const locale of loadOrder) i18n.loadTranslations(locale, { settings: text[locale] });
expect(i18n.t('settings', 'zh-Hant-TW')).toBe('設定');
expect(i18n.t('settings', 'zh-Hant-HK')).toBe('設定');
expect(i18n.t('settings', 'zh-Hans-CN')).toBe('设置');
});
});
describe('createMemoryI18n locale fallback', () => {
it('should resolve translations via locale fallback (zh → zh-CN)', () => {
const i18n = createMemoryI18n();
i18n.loadTranslations('zh-CN', { hello: '你好' });
expect(i18n.getTranslations('zh')).toEqual({ hello: '你好' });
});
it('should resolve translations via case-insensitive fallback (zh-cn → zh-CN)', () => {
const i18n = createMemoryI18n();
i18n.loadTranslations('zh-CN', { hello: '你好' });
expect(i18n.getTranslations('zh-cn')).toEqual({ hello: '你好' });
});
it('should translate via locale fallback (zh → zh-CN)', () => {
const i18n = createMemoryI18n();
i18n.loadTranslations('zh-CN', { greeting: '你好世界' });
expect(i18n.t('greeting', 'zh')).toBe('你好世界');
});
it('should still fall back to default locale when no locale match at all', () => {
const i18n = createMemoryI18n();
i18n.loadTranslations('en', { hello: 'Hello' });
expect(i18n.t('hello', 'ja')).toBe('Hello');
});
});
describe('createMemoryI18n supportedLocales narrowing (#7679)', () => {
// `GET /i18n/locales` advertised four locales on an app declaring two.
// Nothing was wrong with what was LOADED — every platform plugin ships an
// `en/zh-CN/ja-JP/es-ES` bundle and pushes it at `kernel:ready`, which is
// correct. What was wrong is that the loaded set was REPORTED as the set
// the app offers, so a picker built from the route handed users locales in
// which only `sys_*` metadata is translated.
/** The four-locale platform reality this fix has to narrow. */
function loadedFourLocales() {
const i18n = createMemoryI18n();
i18n.loadTranslations('en', { objects: { sys_user: { label: 'User' } } });
i18n.loadTranslations('zh-CN', { objects: { sys_user: { label: '用户' } } });
i18n.loadTranslations('ja-JP', { objects: { sys_user: { label: 'ユーザー' } } });
i18n.loadTranslations('es-ES', { objects: { sys_user: { label: 'Usuario' } } });
return i18n;
}
it('reports only the declared locales — the #7679 repro', () => {
const i18n = loadedFourLocales();
expect(i18n.getLocales().sort()).toEqual(['en', 'es-ES', 'ja-JP', 'zh-CN']);
i18n.setSupportedLocales(['en', 'zh-CN']);
expect(i18n.getLocales()).toEqual(['en', 'zh-CN']);
});
it('narrows what is REPORTED, not what is LOADED — undeclared locales stay servable', () => {
// Explicitly out of scope for #7679, and pinned so nobody "completes"
// the fix by unloading the bundles. `sys_*` translations for a locale
// the app does not advertise cost nothing sitting in the map, and
// anything that already asked for them by code keeps working.
const i18n = loadedFourLocales();
i18n.setSupportedLocales(['en', 'zh-CN']);
expect(i18n.getLocales()).not.toContain('ja-JP');
expect(i18n.getTranslations('ja-JP')).toEqual({ objects: { sys_user: { label: 'ユーザー' } } });
expect(i18n.t('objects.sys_user.label', 'ja-JP')).toBe('ユーザー');
});
it('applies at READ time, so bundles loaded AFTER the declaration are narrowed too', () => {
// The ordering that makes a one-shot prune wrong: `AppPlugin` declares
// the set during its own setup, and the platform plugins push their
// bundles later, at `kernel:ready`. A prune would narrow only whatever
// had loaded first and the rest would grow straight back.
const i18n = createMemoryI18n();
i18n.setSupportedLocales(['en', 'zh-CN']);
i18n.loadTranslations('en', { a: 'a' });
i18n.loadTranslations('ja-JP', { a: 'あ' });
expect(i18n.getLocales()).toEqual(['en', 'zh-CN']);
});
it('DECISION 1 — an app that declares nothing reports every loaded locale', () => {
const i18n = loadedFourLocales();
expect(i18n.getLocales().sort()).toEqual(['en', 'es-ES', 'ja-JP', 'zh-CN']);
// Same answer for an explicit clear and for a declaration carrying no
// usable code: absent is "no narrowing", never "narrow to nothing".
i18n.setSupportedLocales(undefined);
expect(i18n.getLocales().sort()).toEqual(['en', 'es-ES', 'ja-JP', 'zh-CN']);
i18n.setSupportedLocales([]);
expect(i18n.getLocales().sort()).toEqual(['en', 'es-ES', 'ja-JP', 'zh-CN']);
});
it('DECISION 2 — a declared locale with no bundle is REPORTED, not dropped', () => {
// Declared-but-unserved. The declaration is the app's statement of
// intent and the client is entitled to see it; a silently shortened
// list leaves the authoring gap invisible on both sides. Reads degrade
// to the default locale exactly the way a half-translated bundle does.
const i18n = loadedFourLocales();
i18n.setSupportedLocales(['en', 'zh-CN', 'fr-FR']);
expect(i18n.getLocales()).toEqual(['en', 'zh-CN', 'fr-FR']);
expect(i18n.getTranslations('fr-FR')).toEqual({});
expect(i18n.t('objects.sys_user.label', 'fr-FR')).toBe('User');
});
it('a declaration can be replaced, and clearing restores the loaded set', () => {
const i18n = loadedFourLocales();
i18n.setSupportedLocales(['en']);
expect(i18n.getLocales()).toEqual(['en']);
i18n.setSupportedLocales(['zh-CN', 'en']);
expect(i18n.getLocales()).toEqual(['zh-CN', 'en']);
i18n.setSupportedLocales(undefined);
expect(i18n.getLocales().sort()).toEqual(['en', 'es-ES', 'ja-JP', 'zh-CN']);
});
it('the caller cannot mutate the stored declaration through the array it passed or got back', () => {
const i18n = loadedFourLocales();
const declared = ['en', 'zh-CN'];
i18n.setSupportedLocales(declared);
declared.push('ja-JP');
expect(i18n.getLocales()).toEqual(['en', 'zh-CN']);
i18n.getLocales().push('es-ES');
expect(i18n.getLocales()).toEqual(['en', 'zh-CN']);
});
it('narrows the authored overlay too — authored-only locales are not a bypass', () => {
// `getLocales()` unions the static and authored maps, so a locale that
// exists only as runtime-authored `translation` metadata (#2591) would
// otherwise slip past the declaration.
const i18n = loadedFourLocales();
i18n.replaceAuthoredTranslations({ 'ko-KR': { objects: { sys_user: { label: '사용자' } } } });
expect(i18n.getLocales()).toContain('ko-KR');
i18n.setSupportedLocales(['en', 'zh-CN']);
expect(i18n.getLocales()).toEqual(['en', 'zh-CN']);
});
});
describe('createMemoryI18n declared fallbackLocale (#15694)', () => {
// WHAT WENT WRONG
//
// `i18n.fallbackLocale` is authorable (`TranslationConfigSchema`) and
// `FileI18nAdapter` has always honoured it — both boot paths construct it
// with `fallbackLocale || defaultLocale || 'en'`. The kernel's
// in-memory fallback is constructed with nothing and had no setter, so on a
// stack running it the declaration was INERT: `t()` consulted the requested
// locale and, only if that locale had NO bundle at all, `defaultLocale`.
//
// A stack declaring `defaultLocale: 'zh-CN'` with `fallbackLocale: 'en'`
// therefore answered a missing `zh-CN` key from `en` under
// `I18nServicePlugin` and from `zh-CN` — i.e. not at all — under the
// fallback. One declaration, two providers, two answers. The provider
// self-declaring `degraded` licenses FEWER capabilities, not a different
// answer to the same declared key.
//
// The contrast surface (`FileI18nAdapter.t()`'s second leg) is pinned in
// service-i18n's own suite and is deliberately untouched here.
/** The card's scenario: `en` carries a key the `zh-CN` bundle never got. */
function bootDeclaredStack() {
const i18n = createMemoryI18n();
i18n.loadTranslations('en', { objects: { property: { label: 'Property', tip: 'Only in English' } } });
i18n.loadTranslations('zh-CN', { objects: { property: { label: '房源' } } });
i18n.setDefaultLocale('zh-CN');
i18n.setFallbackLocale('en');
return i18n;
}
it('a key missing in the requested locale is answered from the DECLARED fallback', () => {
// The whole card in one assertion. Pre-fix this returned the key
// itself: the `zh-CN` bundle exists, so the old whole-bundle swap never
// fired, and nothing else was ever consulted.
expect(bootDeclaredStack().t('objects.property.tip', 'zh-CN')).toBe('Only in English');
});
it('the requested locale still wins where it HAS the key', () => {
// The fallback is a second leg, never a preference: a translated key
// must not start answering in English because a fallback was declared.
expect(bootDeclaredStack().t('objects.property.label', 'zh-CN')).toBe('房源');
});
it('a key in NEITHER locale is still the key itself', () => {
expect(bootDeclaredStack().t('objects.property.missing', 'zh-CN')).toBe('objects.property.missing');
});
it('per KEY, not per bundle — a bundle that exists but lacks the key still reaches the fallback', () => {
// Stated separately because this is the exact shape the old code got
// wrong. `resolveTranslations(locale) ?? mergedLocale(defaultLocale)`
// picks ONE bundle and then looks the key up in it, so the fallback
// could only ever fire for a locale with no bundle at all — which is
// never the interesting case.
const i18n = createMemoryI18n();
i18n.loadTranslations('en', { greeting: 'Hello' });
i18n.loadTranslations('ja-JP', { farewell: 'さようなら' });
i18n.setFallbackLocale('en');
expect(i18n.t('farewell', 'ja-JP')).toBe('さようなら');
expect(i18n.t('greeting', 'ja-JP')).toBe('Hello');
});
it('DECISION — an app that declared no fallbackLocale keeps today\'s behaviour exactly', () => {
// The compatibility half, and the reason the setter is guarded rather
// than defaulted: every stack written before this declared nothing, and
// a fallback nobody asked for is a new chain, not a fix.
const i18n = createMemoryI18n();
i18n.loadTranslations('en', { objects: { property: { tip: 'Only in English' } } });
i18n.loadTranslations('zh-CN', { objects: { property: { label: '房源' } } });
i18n.setDefaultLocale('zh-CN');
expect(i18n.t('objects.property.tip', 'zh-CN')).toBe('objects.property.tip');
});
it('the pre-existing whole-bundle fall to defaultLocale is untouched', () => {
// A requested locale with NO bundle still lands on `defaultLocale`,
// declared fallback or not — that leg is older than this card.
const i18n = createMemoryI18n();
i18n.loadTranslations('zh-CN', { objects: { property: { label: '房源' } } });
i18n.setDefaultLocale('zh-CN');
i18n.setFallbackLocale('en');
expect(i18n.t('objects.property.label', 'fr-FR')).toBe('房源');
});
it('a fallback equal to the requested locale does not re-ask the lookup that just failed', () => {
const i18n = createMemoryI18n();
i18n.loadTranslations('en', { greeting: 'Hello' });
i18n.setFallbackLocale('en');
expect(i18n.t('greeting', 'en')).toBe('Hello');
expect(i18n.t('missing', 'en')).toBe('missing');
});
it('interpolation applies to a value resolved from the fallback', () => {
const i18n = createMemoryI18n();
i18n.loadTranslations('en', { welcome: 'Welcome, {{name}}' });
i18n.loadTranslations('zh-CN', {});
i18n.setFallbackLocale('en');
expect(i18n.t('welcome', 'zh-CN', { name: 'Ada' })).toBe('Welcome, Ada');
});
it('the fallback leg sees the AUTHORED overlay, not just the static bundle', () => {
// #2591's authored layer wins on read for the requested locale, so it
// must win on the fallback leg too — otherwise a key authored at
// runtime resolves for one locale and not for the locale that falls
// back to it.
const i18n = createMemoryI18n();
i18n.loadTranslations('en', { greeting: 'Hello' });
i18n.loadTranslations('zh-CN', { other: '其他' });
i18n.replaceAuthoredTranslations({ en: { greeting: 'Hi there' } });
i18n.setFallbackLocale('en');
expect(i18n.t('greeting', 'zh-CN')).toBe('Hi there');
});
it('the fallback leg resolves a locale CODE the way the requested leg does', () => {
const i18n = createMemoryI18n();
i18n.loadTranslations('en-US', { greeting: 'Hello' });
i18n.loadTranslations('zh-CN', { other: '其他' });
i18n.setFallbackLocale('en');
expect(i18n.t('greeting', 'zh-CN')).toBe('Hello');
});
it('⛔ the SETTER exists and the ACCESSOR deliberately does not (#14882)', () => {
// The fence, pinned so the next reader does not "complete" this by
// adding the accessor. `setFallbackLocale` is what the provider is
// TOLD; `getFallbackLocale` is what the serving layer ASKS it when it
// builds the metadata-document translators' fallback chain. Answering
// the second from `defaultLocale` — the only value always available
// here — would settle the default-locale contract question #14882
// leaves deliberately open, from a degraded provider. Those reads keep
// the resolvers' own default instead, which is known and intentional.
const i18n = createMemoryI18n() as Record<string, unknown>;
expect(typeof i18n.setFallbackLocale).toBe('function');
expect(i18n.getFallbackLocale).toBeUndefined();
});
// #33634 — the source-locale pair: unlike the fallback pair, both halves
// exist, because the accessor answers only what it was told.
it('getSourceLocale answers undefined until setSourceLocale is called, then exactly what it was told', () => {
const i18n = createMemoryI18n();
i18n.setDefaultLocale('zh-CN');
// Never derived from `defaultLocale`: that collapse is the caller's.
expect(i18n.getSourceLocale()).toBeUndefined();
i18n.setSourceLocale('en');
expect(i18n.getSourceLocale()).toBe('en');
expect(i18n.getDefaultLocale()).toBe('zh-CN');
});
it('setSourceLocale changes no t() lookup', () => {
const i18n = createMemoryI18n();
i18n.setDefaultLocale('zh-CN');
i18n.loadTranslations('en', { greeting: 'Hello' });
i18n.loadTranslations('zh-CN', { other: '其他' });
const before = [i18n.t('greeting', 'zh-CN'), i18n.t('greeting', 'en'), i18n.t('other', 'en')];
i18n.setSourceLocale('en');
expect([i18n.t('greeting', 'zh-CN'), i18n.t('greeting', 'en'), i18n.t('other', 'en')]).toEqual(before);
});
});
// #30456: the one matcher for "is this locale offered here, and as which code",
// shared by Setup's default language and the IdP locale claim.
describe('resolveOfferedLocale', () => {
it('answers what resolveLocale answers, on the shared case list too', () => {
for (const [requested, available] of [
['zh-TW', ['en', 'zh-CN', 'zh-Hant']],
['zh', ['en', 'zh-Hant', 'zh-CN']],
['zh-HK', ['zh-TW', 'zh-Hant']],
['es-MX', ['en', 'es-ES']],
['fr', ['en', 'zh-CN']],
] as Array<[string, string[]]>) {
expect(resolveOfferedLocale(requested, available)).toBe(resolveLocale(requested, available));
}
});
it('takes resolveLocale\'s exact and case-insensitive steps first', () => {
expect(resolveOfferedLocale('zh-CN', ['en', 'zh-CN'])).toBe('zh-CN');
expect(resolveOfferedLocale('zh-cn', ['en', 'zh-CN'])).toBe('zh-CN');
});
it('then the platform table\'s language, so a script or region lands on its own script', () => {
// resolveOfferedLocale is resolveLocale: one ladder, so both answer by script.
expect(resolveLocale('zh-TW', ['zh-Hans', 'zh-Hant'])).toBe('zh-Hant');
expect(resolveOfferedLocale('zh-TW', ['zh-Hans', 'zh-Hant'])).toBe('zh-Hant');
expect(resolveOfferedLocale('zh-CN', ['zh-Hant', 'zh-Hans'])).toBe('zh-Hans');
expect(resolveOfferedLocale('en-US', ['zh-CN', 'en'])).toBe('en');
});
it('then resolveLocale\'s base-language and variant steps', () => {
expect(resolveOfferedLocale('fr-FR', ['en', 'fr'])).toBe('fr');
expect(resolveOfferedLocale('fr', ['en', 'fr-FR'])).toBe('fr-FR');
});
it('answers undefined for a language not offered, and for an empty list', () => {
expect(resolveOfferedLocale('de-DE', ['en', 'fr'])).toBeUndefined();
expect(resolveOfferedLocale('en', [])).toBeUndefined();
});
});