@openmrs/esm-app-shell 11.0.1-pre.5993 → 11.0.1-pre.6006

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,229 @@
1
+ import { afterEach, beforeAll, describe, expect, it, vi } from 'vitest';
2
+ import { getTranslationOverrides } from '@openmrs/esm-framework/src/internal';
3
+ import {
4
+ disableTranslationInspector,
5
+ enableTranslationInspector,
6
+ matchTranslations,
7
+ } from '../../../framework/esm-translations/src/inspector';
8
+
9
+ const shippedLoginApp = vi.hoisted(() => ({ loginButton: 'Log in' }));
10
+ const importTranslationCalls = vi.hoisted((): Array<string> => []);
11
+
12
+ // `locale` reaches for the framework's config system, which is far more than these tests need. The
13
+ // translation inspector, though, is deliberately the real thing: the point of these tests is that
14
+ // the post-processor `setupI18n` registers really does report what i18next renders.
15
+ vi.mock('@openmrs/esm-framework/src/internal', async () => {
16
+ const inspector = await import('../../../framework/esm-translations/src/inspector');
17
+
18
+ return {
19
+ ...inspector,
20
+ registerTranslationNamespace: vi.fn(),
21
+ getExtensionsConfigStore: () => ({ getState: () => ({ configs: {} }), subscribe: () => () => {} }),
22
+ getExtensionConfigFromStore: () => ({ loaded: false, config: null }),
23
+ getTranslationOverrides: vi.fn(() => Promise.resolve([{}])),
24
+ // One object for every read, as a bundler's cached module would be, so that a test notices if
25
+ // the backend writes overrides into the shipped translations.
26
+ importDynamic: vi.fn(() =>
27
+ Promise.resolve({
28
+ importTranslation: (file: string) => {
29
+ importTranslationCalls.push(file);
30
+ return Promise.resolve(shippedLoginApp);
31
+ },
32
+ }),
33
+ ),
34
+ };
35
+ });
36
+
37
+ // `km` stands in for a locale with no core translation file, which the bundler reports as a module
38
+ // that cannot be found, and `fr` for a shipped file whose chunk fails to download.
39
+ vi.mock('./core-translations', async (importOriginal) => {
40
+ const { importCoreTranslation } = await importOriginal<typeof import('./core-translations')>();
41
+
42
+ return {
43
+ importCoreTranslation: (fileLocale: string) => {
44
+ if (fileLocale === 'km') {
45
+ return Promise.reject(Object.assign(new Error("Cannot find module './km.json'"), { code: 'MODULE_NOT_FOUND' }));
46
+ }
47
+
48
+ if (fileLocale === 'fr') {
49
+ return Promise.reject(Object.assign(new Error('Loading chunk fr.json failed.'), { name: 'ChunkLoadError' }));
50
+ }
51
+
52
+ return importCoreTranslation(fileLocale);
53
+ },
54
+ };
55
+ });
56
+
57
+ const loginApp = '@openmrs/esm-login-app';
58
+ const otherApp = '@openmrs/esm-other-app';
59
+
60
+ beforeAll(async () => {
61
+ const { setupI18n } = await import('./locale');
62
+
63
+ // `setupI18n` freezes the instance onto `window`, so it can only be called once per test file.
64
+ await setupI18n();
65
+
66
+ window.i18next.addResourceBundle('en', loginApp, {
67
+ loginButton: 'Log in',
68
+ locationsHeader: 'Locations',
69
+ });
70
+ window.i18next.addResourceBundle('en', otherApp, {
71
+ alsoLocations: 'Locations',
72
+ itemCount_one: '{{count}} item',
73
+ itemCount_other: '{{count}} items',
74
+ visitCount: '{{count}} visits recorded',
75
+ visitCount_one: '{{count}} visit',
76
+ visitCount_other: '{{count}} visits',
77
+ greeting: 'Welcome',
78
+ greeting_formal: 'Good day to you',
79
+ });
80
+ window.i18next.addResourceBundle('en', `${loginApp}___some-slot___some-extension`, {
81
+ loginButton: 'Sign in',
82
+ });
83
+ });
84
+
85
+ afterEach(() => {
86
+ disableTranslationInspector();
87
+ });
88
+
89
+ describe('the translation inspector post-processor', () => {
90
+ it('records nothing while the inspector is switched off', () => {
91
+ expect(window.i18next.getFixedT('en', loginApp)('loginButton')).toBe('Log in');
92
+ expect(matchTranslations('Log in')).toEqual([]);
93
+ });
94
+
95
+ it('records the namespace and key behind a rendered string', () => {
96
+ enableTranslationInspector();
97
+
98
+ window.i18next.getFixedT('en', loginApp)('loginButton');
99
+
100
+ expect(matchTranslations('Log in')).toEqual([
101
+ { namespace: loginApp, extensionNamespace: undefined, key: 'loginButton', value: 'Log in', hasCount: false },
102
+ ]);
103
+ });
104
+
105
+ it('reports every key that renders the same string', () => {
106
+ enableTranslationInspector();
107
+
108
+ window.i18next.getFixedT('en', loginApp)('locationsHeader');
109
+ window.i18next.getFixedT('en', otherApp)('alsoLocations');
110
+
111
+ expect(matchTranslations('Locations').map((sighting) => sighting.key)).toEqual([
112
+ 'locationsHeader',
113
+ 'alsoLocations',
114
+ ]);
115
+ });
116
+
117
+ it('records the interpolated string and the plural form it came from', () => {
118
+ enableTranslationInspector();
119
+
120
+ const rendered = window.i18next.getFixedT('en', otherApp)('itemCount', { count: 3 });
121
+
122
+ expect(rendered).toBe('3 items');
123
+ expect(matchTranslations('3 items')).toEqual([
124
+ { namespace: otherApp, extensionNamespace: undefined, key: 'itemCount_other', value: '3 items', hasCount: true },
125
+ ]);
126
+ });
127
+
128
+ it('does not flag a lookup as plural when i18next did no plural handling for it', () => {
129
+ enableTranslationInspector();
130
+
131
+ // i18next interpolates a string `count` but resolves the base key.
132
+ const rendered = window.i18next.getFixedT('en', otherApp)('visitCount', { count: '3' } as never);
133
+
134
+ expect(rendered).toBe('3 visits recorded');
135
+ expect(matchTranslations('3 visits recorded')).toEqual([
136
+ expect.objectContaining({ key: 'visitCount', hasCount: false }),
137
+ ]);
138
+ });
139
+
140
+ it('records the key a context lookup resolved', () => {
141
+ enableTranslationInspector();
142
+
143
+ const rendered = window.i18next.getFixedT('en', otherApp)('greeting', { context: 'formal' });
144
+
145
+ expect(rendered).toBe('Good day to you');
146
+ expect(matchTranslations('Good day to you').map((sighting) => sighting.key)).toEqual(['greeting_formal']);
147
+ });
148
+
149
+ it('records the key it was given for a lookup that rendered its default value', () => {
150
+ enableTranslationInspector();
151
+
152
+ window.i18next.getFixedT('en', otherApp)('notInTheFile', 'Default text');
153
+
154
+ expect(matchTranslations('Default text').map((sighting) => sighting.key)).toEqual(['notInTheFile']);
155
+ });
156
+
157
+ it('separates an extension-scoped namespace from the module that owns the key', () => {
158
+ enableTranslationInspector();
159
+
160
+ window.i18next.getFixedT('en', `${loginApp}___some-slot___some-extension`)('loginButton');
161
+
162
+ expect(matchTranslations('Sign in')).toEqual([
163
+ {
164
+ namespace: loginApp,
165
+ extensionNamespace: `${loginApp}___some-slot___some-extension`,
166
+ key: 'loginButton',
167
+ value: 'Sign in',
168
+ hasCount: false,
169
+ },
170
+ ]);
171
+ });
172
+
173
+ it('leaves a translation asked for without a namespace unrecorded', () => {
174
+ enableTranslationInspector();
175
+
176
+ // i18next would report its own `defaultNS` here — `translation`, which this backend refuses to
177
+ // load — so a bogus namespace is worse than none.
178
+ window.i18next.t('loginButton', { ns: undefined, lng: 'en' });
179
+
180
+ expect(matchTranslations('loginButton')).toEqual([]);
181
+ });
182
+ });
183
+
184
+ describe('the translation backend', () => {
185
+ it('renders a Translation overrides config entry in place of the shipped string, and back', async () => {
186
+ vi.mocked(getTranslationOverrides).mockResolvedValueOnce([{ en: { loginButton: 'Sign in' } }]);
187
+ await window.i18next.reloadResources(['en'], [loginApp]);
188
+
189
+ expect(window.i18next.getResource('en', loginApp, 'loginButton')).toBe('Sign in');
190
+
191
+ // Removing the override must bring back the shipped string, not the override merged into it.
192
+ await window.i18next.reloadResources(['en'], [loginApp]);
193
+
194
+ expect(window.i18next.getResource('en', loginApp, 'loginButton')).toBe('Log in');
195
+ expect(shippedLoginApp).toEqual({ loginButton: 'Log in' });
196
+ });
197
+
198
+ it('reads a regional locale from its underscore-named file', async () => {
199
+ await window.i18next.reloadResources(['pt-BR'], ['core', loginApp]);
200
+
201
+ expect(window.i18next.getResource('pt-BR', 'core', 'cancel')).toBe('Cancelar');
202
+ expect(importTranslationCalls).toContain('./pt_BR.json');
203
+ });
204
+
205
+ it('applies core overrides for a locale that has no core translation file', async () => {
206
+ vi.mocked(getTranslationOverrides).mockResolvedValueOnce([{ km: { cancel: 'បោះបង់' } }]);
207
+
208
+ await window.i18next.reloadResources(['km'], ['core']);
209
+
210
+ expect(window.i18next.getResource('km', 'core', 'cancel')).toBe('បោះបង់');
211
+ });
212
+
213
+ it('reports a core translation file that failed to load, rather than loading it as empty', async () => {
214
+ const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {});
215
+ let callbackError: unknown;
216
+
217
+ await window.i18next.reloadResources(['fr'], ['core'], ((error: unknown) => {
218
+ callbackError = error;
219
+ }) as () => void);
220
+
221
+ const state = (window.i18next.services.backendConnector as unknown as { state: Record<string, number> }).state;
222
+
223
+ expect(state['fr|core']).toBeLessThan(0);
224
+ expect(callbackError).toBeTruthy();
225
+ expect(consoleError).toHaveBeenCalled();
226
+ expect(window.i18next.hasResourceBundle('fr', 'core')).toBe(false);
227
+ consoleError.mockRestore();
228
+ });
229
+ });
@@ -26,6 +26,9 @@ vi.mock('@openmrs/esm-framework/src/internal', () => ({
26
26
  getExtensionConfigFromStore: (state: ExtensionsConfigState, slotName: string, extensionId: string) =>
27
27
  state.configs[slotName]?.[extensionId] ?? { loaded: false, config: null },
28
28
  getTranslationOverrides: (_ns: string, slotName?: string) => Promise.resolve(slotName ? [{}, {}] : [{}]),
29
+ extensionNamespaceSeparator: '___',
30
+ isTranslationInspectorRecording: () => false,
31
+ recordTranslationSighting: () => {},
29
32
  }));
30
33
 
31
34
  const namespace = 'ext-module___barSlot___fooExt';
package/src/locale.ts CHANGED
@@ -8,12 +8,19 @@ import {
8
8
  getExtensionsConfigStore,
9
9
  getTranslationOverrides,
10
10
  importDynamic,
11
+ extensionNamespaceSeparator,
12
+ isTranslationInspectorRecording,
13
+ recordTranslationSighting,
11
14
  registerTranslationNamespace,
12
15
  } from '@openmrs/esm-framework/src/internal';
16
+ import { importCoreTranslation } from './core-translations';
13
17
  import { languageDetectionOptions } from './language-detection';
14
18
 
15
19
  registerTranslationNamespace('core');
16
20
 
21
+ /** The name i18next knows the translation inspector's post-processor by. */
22
+ const translationInspectorPostProcessorName = 'openmrsTranslationInspector';
23
+
17
24
  /**
18
25
  * Extension namespaces that were read while their extension was not mounted, so they are missing its
19
26
  * translation overrides, with the languages that were read. See {@link applyPendingExtensionOverrides}.
@@ -54,15 +61,28 @@ export function setupI18n() {
54
61
  } else if (namespace === undefined || language === undefined) {
55
62
  callback(Error(), null);
56
63
  } else if (namespace === 'core') {
57
- Promise.all([
58
- import(/* webpackMode: "lazy" */ `@openmrs/esm-translations/translations/${language}.json`),
64
+ Promise.allSettled([
65
+ importCoreTranslation(toTranslationFileLocale(language)),
59
66
  getTranslationOverrides(namespace),
60
67
  ])
61
- .then(([json, [overrides]]) => {
62
- let translations = json?.default ?? {};
68
+ .then(([jsonResult, overridesResult]) => {
69
+ // A locale with no core translation file still gets its overrides, but a file that failed
70
+ // to load is a failure: treating it as empty would mark the namespace loaded and leave
71
+ // every core string in English.
72
+ if (jsonResult.status === 'rejected' && !isMissingModule(jsonResult.reason)) {
73
+ console.error(`Failed to load the core translations for ${language}`, jsonResult.reason);
74
+ callback(jsonResult.reason, null);
75
+ return;
76
+ }
77
+
78
+ // `merge` mutates its target, and `json.default` is the cached module's own object, so
79
+ // overrides must be merged into a fresh object or they are written into the shipped
80
+ // translations for the life of the page and can never be removed.
81
+ let translations = { ...(jsonResult.status === 'fulfilled' ? (jsonResult.value?.default ?? {}) : {}) };
82
+ const [overrides] = overridesResult.status === 'fulfilled' ? overridesResult.value : [{}];
63
83
 
64
84
  if (language in overrides) {
65
- translations = merge(translations, overrides[language]);
85
+ translations = merge({}, translations, overrides[language]);
66
86
  }
67
87
 
68
88
  callback(null, translations);
@@ -71,7 +91,7 @@ export function setupI18n() {
71
91
  callback(err, null);
72
92
  });
73
93
  } else {
74
- const [ns, slotName, extensionId] = namespace.split('___');
94
+ const [ns, slotName, extensionId] = namespace.split(extensionNamespaceSeparator);
75
95
  let extensionMountedAtRead = true;
76
96
  importDynamic(ns)
77
97
  .then((module) => {
@@ -91,7 +111,7 @@ export function setupI18n() {
91
111
  .then(([jsonResult, overridesResult]) => {
92
112
  // If importTranslation rejects (e.g., no translation file for this locale),
93
113
  // fall back to empty so config-provided overrides can still be applied.
94
- let translations = jsonResult.status === 'fulfilled' ? (jsonResult.value ?? {}) : {};
114
+ let translations = { ...(jsonResult.status === 'fulfilled' ? (jsonResult.value ?? {}) : {}) };
95
115
  const overrides = overridesResult.status === 'fulfilled' ? overridesResult.value : [];
96
116
 
97
117
  // if we have a slotName and extensionId, it means that we're only loading the namespace for that extension
@@ -102,7 +122,7 @@ export function setupI18n() {
102
122
  window.i18next.addResourceBundle(
103
123
  language,
104
124
  ns,
105
- merge(translations, overrides[0][language]),
125
+ merge({}, translations, overrides[0][language]),
106
126
  true,
107
127
  false,
108
128
  );
@@ -111,7 +131,7 @@ export function setupI18n() {
111
131
  }
112
132
  }
113
133
 
114
- translations = merge(translations, ...overrides.filter((o) => language in o).map((o) => o[language]));
134
+ translations = merge({}, translations, ...overrides.filter((o) => language in o).map((o) => o[language]));
115
135
 
116
136
  callback(null, translations);
117
137
 
@@ -133,14 +153,82 @@ export function setupI18n() {
133
153
  }
134
154
  },
135
155
  })
156
+ .use(translationInspector)
136
157
  .use(initReactI18next)
137
158
  .init({
138
159
  detection: languageDetectionOptions,
139
160
  fallbackLng: 'en',
140
161
  nsSeparator: false,
162
+ postProcess: [translationInspectorPostProcessorName],
163
+ // Gives post-processors the key that actually resolved, e.g. `visit_one` for a plural lookup.
164
+ postProcessPassResolved: true,
141
165
  });
142
166
  }
143
167
 
168
+ /**
169
+ * Reports every translated string, and the key behind it, to the framework's translation inspector,
170
+ * which the implementer tools use to tell an implementer which key to override for a given piece of
171
+ * text on screen.
172
+ *
173
+ * i18next applies post-processors last, after interpolation and nesting, so `value` is the finished
174
+ * string rather than the template — which is what lets text found in the DOM be matched back to a
175
+ * key.
176
+ */
177
+ const translationInspector: i18next.PostProcessorModule = {
178
+ type: 'postProcessor',
179
+ name: translationInspectorPostProcessorName,
180
+ process(value, key, options) {
181
+ if (!isTranslationInspectorRecording() || typeof value !== 'string' || value === '') {
182
+ return value;
183
+ }
184
+
185
+ const namespace = resolveNamespace(options);
186
+
187
+ if (namespace) {
188
+ recordTranslationSighting({
189
+ namespace: namespace.split(extensionNamespaceSeparator)[0],
190
+ extensionNamespace: namespace.includes(extensionNamespaceSeparator) ? namespace : undefined,
191
+ key: resolveKey(key, options),
192
+ value,
193
+ // Mirrors i18next, which applies plural handling to any `count` but a string.
194
+ hasCount: options?.count !== undefined && typeof options.count !== 'string',
195
+ });
196
+ }
197
+
198
+ return value;
199
+ },
200
+ };
201
+
202
+ /**
203
+ * The namespace a translation was looked up in. react-i18next binds it through `getFixedT`, and the
204
+ * framework's `translateFrom` and `getCoreTranslation` pass it explicitly, so only a bare
205
+ * `i18n.t(key)` arrives without one. Those are left unrecorded rather than guessed at.
206
+ */
207
+ function resolveNamespace(options: i18next.TOptions) {
208
+ const ns = options?.ns;
209
+
210
+ if (typeof ns === 'string') {
211
+ return ns;
212
+ }
213
+
214
+ return Array.isArray(ns) && typeof ns[0] === 'string' ? ns[0] : undefined;
215
+ }
216
+
217
+ /**
218
+ * The key a translation was read from, which for a plural or context lookup is a suffixed form of the
219
+ * key `t` was given. A lookup that found nothing, and so rendered its default value, reports the key
220
+ * it was given, since that is the one an override would supply.
221
+ */
222
+ function resolveKey(key: string | Array<string>, options: i18next.TOptions): string {
223
+ const resolved = (options as { i18nResolved?: { res?: unknown; exactUsedKey?: string } })?.i18nResolved;
224
+
225
+ if (resolved?.res !== undefined && resolved.exactUsedKey) {
226
+ return resolved.exactUsedKey;
227
+ }
228
+
229
+ return Array.isArray(key) ? key[0] : key;
230
+ }
231
+
144
232
  /**
145
233
  * An extension's translation overrides only exist while it is mounted, but i18next reads a namespace
146
234
  * once per language and never again, e.g. when a language change re-reads the namespace of an
@@ -183,11 +271,9 @@ function getImportPromise(
183
271
 
184
272
  if (!language) {
185
273
  return Promise.resolve({});
186
- } else if (language.includes('-')) {
187
- language = language.replace('-', '_');
188
274
  }
189
275
 
190
- const importPromise = module.importTranslation(`./${language}.json`);
276
+ const importPromise = module.importTranslation(`./${toTranslationFileLocale(language)}.json`);
191
277
 
192
278
  if (!(importPromise instanceof Promise)) {
193
279
  throw Error(
@@ -197,3 +283,16 @@ function getImportPromise(
197
283
 
198
284
  return importPromise;
199
285
  }
286
+
287
+ /** Translation files are named with an underscore for the locale's first hyphen: `pt-BR` is read from `pt_BR.json`. */
288
+ function toTranslationFileLocale(language: string) {
289
+ return language.replace('-', '_');
290
+ }
291
+
292
+ /**
293
+ * Whether an import failed because the bundle has no such file, as opposed to failing to fetch one it
294
+ * does have. The bundler's lazy context reports a missing file with Node's `MODULE_NOT_FOUND` code.
295
+ */
296
+ function isMissingModule(error: unknown) {
297
+ return (error as { code?: unknown } | null)?.code === 'MODULE_NOT_FOUND';
298
+ }