@itwin/core-i18n 4.0.0-dev.8 → 4.0.0-dev.81

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.
@@ -1,232 +1,230 @@
1
- "use strict";
2
- /*---------------------------------------------------------------------------------------------
3
- * Copyright (c) Bentley Systems, Incorporated. All rights reserved.
4
- * See LICENSE.md in the project root for license terms and full copyright notice.
5
- *--------------------------------------------------------------------------------------------*/
6
- /** @packageDocumentation
7
- * @module Localization
8
- */
9
- var __importDefault = (this && this.__importDefault) || function (mod) {
10
- return (mod && mod.__esModule) ? mod : { "default": mod };
11
- };
12
- Object.defineProperty(exports, "__esModule", { value: true });
13
- exports.ITwinLocalization = void 0;
14
- const i18next_1 = __importDefault(require("i18next"));
15
- const i18next_browser_languagedetector_1 = __importDefault(require("i18next-browser-languagedetector"));
16
- const i18next_http_backend_1 = __importDefault(require("i18next-http-backend"));
17
- const core_bentley_1 = require("@itwin/core-bentley");
18
- const DEFAULT_MAX_RETRIES = 1; // a low number prevents wasted time and potential timeouts when requesting localization files throws an error
19
- /** Supplies localizations for iTwin.js
20
- * @note this class uses the [i18next](https://www.i18next.com/) package.
21
- * @public
22
- */
23
- class ITwinLocalization {
24
- constructor(options) {
25
- var _a, _b, _c;
26
- this._namespaces = new Map();
27
- this.i18next = i18next_1.default.createInstance();
28
- this._backendOptions = {
29
- loadPath: (_a = options === null || options === void 0 ? void 0 : options.urlTemplate) !== null && _a !== void 0 ? _a : "locales/{{lng}}/{{ns}}.json",
30
- crossDomain: true,
31
- ...options === null || options === void 0 ? void 0 : options.backendHttpOptions,
32
- };
33
- this._detectionOptions = {
34
- order: ["querystring", "navigator", "htmlTag"],
35
- lookupQuerystring: "lng",
36
- caches: [],
37
- ...options === null || options === void 0 ? void 0 : options.detectorOptions,
38
- };
39
- this._initOptions = {
40
- interpolation: { escapeValue: true },
41
- fallbackLng: "en",
42
- maxRetries: DEFAULT_MAX_RETRIES,
43
- backend: this._backendOptions,
44
- detection: this._detectionOptions,
45
- ...options === null || options === void 0 ? void 0 : options.initOptions,
46
- };
47
- this.i18next
48
- .use((_b = options === null || options === void 0 ? void 0 : options.detectorPlugin) !== null && _b !== void 0 ? _b : i18next_browser_languagedetector_1.default)
49
- .use((_c = options === null || options === void 0 ? void 0 : options.backendPlugin) !== null && _c !== void 0 ? _c : i18next_http_backend_1.default)
50
- .use(TranslationLogger);
51
- }
52
- async initialize(namespaces) {
53
- var _a;
54
- // Also consider namespaces passed into constructor
55
- const initNamespaces = [this._initOptions.ns || []].flat();
56
- const combinedNamespaces = new Set([...namespaces, ...initNamespaces]); // without duplicates
57
- const defaultNamespace = (_a = this._initOptions.defaultNS) !== null && _a !== void 0 ? _a : namespaces[0];
58
- if (defaultNamespace)
59
- combinedNamespaces.add(defaultNamespace); // Make sure default namespace is in namespaces list
60
- const initOptions = {
61
- ...this._initOptions,
62
- defaultNS: defaultNamespace,
63
- ns: [...combinedNamespaces],
64
- };
65
- // if in a development environment, set debugging
66
- if (process.env.NODE_ENV === "development")
67
- initOptions.debug = true;
68
- const initPromise = this.i18next.init(initOptions);
69
- for (const ns of namespaces)
70
- this._namespaces.set(ns, initPromise);
71
- return initPromise;
72
- }
73
- /** Replace all instances of `%{key}` within a string with the translations of those keys.
74
- * For example:
75
- * ``` ts
76
- * "MyKeys": {
77
- * "Key1": "First value",
78
- * "Key2": "Second value"
79
- * }
80
- * ```
81
- *
82
- * ``` ts
83
- * i18.translateKeys("string with %{MyKeys.Key1} followed by %{MyKeys.Key2}!"") // returns "string with First Value followed by Second Value!"
84
- * ```
85
- * @param line The input line, potentially containing %{keys}.
86
- * @returns The line with all %{keys} translated
87
- * @public
88
- */
89
- getLocalizedKeys(line) {
90
- return line.replace(/\%\{(.+?)\}/g, (_match, tag) => this.getLocalizedString(tag));
91
- }
92
- /** Return the translated value of a key.
93
- * @param key - the key that matches a property in the JSON localization file.
94
- * @note The key includes the namespace, which identifies the particular localization file that contains the property,
95
- * followed by a colon, followed by the property in the JSON file.
96
- * For example:
97
- * ``` ts
98
- * const dataString: string = IModelApp.localization.getLocalizedString("iModelJs:BackgroundMap.BingDataAttribution");
99
- * ```
100
- * assigns to dataString the string with property BackgroundMap.BingDataAttribution from the iModelJs.json localization file.
101
- * @returns The string corresponding to the first key that resolves.
102
- * @throws Error if no keys resolve to a string.
103
- * @public
104
- */
105
- getLocalizedString(key, options) {
106
- if ((options === null || options === void 0 ? void 0 : options.returnDetails) || (options === null || options === void 0 ? void 0 : options.returnObjects)) {
107
- throw new Error("Translation key must map to a string, but the given options will result in an object");
108
- }
109
- const value = this.i18next.t(key, options);
110
- if (typeof value !== "string") {
111
- throw new Error("Translation key(s) string not found");
112
- }
113
- return value;
114
- }
115
- /** Similar to `getLocalizedString` but the default namespace is a separate parameter and the key does not need
116
- * to include a namespace. If a key includes a namespace, that namespace will be used for interpolating that key.
117
- * @param namespace - the namespace that identifies the particular localization file that contains the property.
118
- * @param key - the key that matches a property in the JSON localization file.
119
- * @returns The string corresponding to the first key that resolves.
120
- * @throws Error if no keys resolve to a string.
121
- * @internal
122
- */
123
- getLocalizedStringWithNamespace(namespace, key, options) {
124
- let fullKey = "";
125
- if (typeof key === "string") {
126
- fullKey = `${namespace}:${key}`;
127
- }
128
- else {
129
- fullKey = key.map((subKey) => {
130
- return `${namespace}:${subKey}`;
131
- });
132
- }
133
- return this.getLocalizedString(fullKey, options);
134
- }
135
- /** Gets the English translation.
136
- * @param namespace - the namespace that identifies the particular localization file that contains the property.
137
- * @param key - the key that matches a property in the JSON localization file.
138
- * @returns The string corresponding to the first key that resolves.
139
- * @throws Error if no keys resolve to a string.
140
- * @internal
141
- */
142
- getEnglishString(namespace, key, options) {
143
- if ((options === null || options === void 0 ? void 0 : options.returnDetails) || (options === null || options === void 0 ? void 0 : options.returnObjects)) {
144
- throw new Error("Translation key must map to a string, but the given options will result in an object");
145
- }
146
- options = {
147
- ...options,
148
- ns: namespace, // ensure namespace argument is used
149
- };
150
- const en = this.i18next.getFixedT("en", namespace);
151
- const str = en(key, options);
152
- if (typeof str !== "string")
153
- throw new Error("Translation key(s) not found");
154
- return str;
155
- }
156
- /** Get the promise for an already registered Namespace.
157
- * @param name - the name of the namespace
158
- * @public
159
- */
160
- getNamespacePromise(name) {
161
- return this._namespaces.get(name);
162
- }
163
- /** @internal */
164
- getLanguageList() {
165
- return this.i18next.languages;
166
- }
167
- /** override the language detected in the browser */
168
- async changeLanguage(language) {
169
- return this.i18next.changeLanguage(language);
170
- }
171
- /** Register a new Namespace and return it. If the namespace is already registered, it will be returned.
172
- * @param name - the name of the namespace, which is the base name of the JSON file that contains the localization properties.
173
- * @note - The registerNamespace method starts fetching the appropriate version of the JSON localization file from the server,
174
- * based on the current locale. To make sure that fetch is complete before performing translations from this namespace, await
175
- * fulfillment of the readPromise Promise property of the returned LocalizationNamespace.
176
- * @see [Localization in iTwin.js]($docs/learning/frontend/Localization.md)
177
- * @public
178
- */
179
- async registerNamespace(name) {
180
- const existing = this._namespaces.get(name);
181
- if (existing !== undefined)
182
- return existing;
183
- const theReadPromise = new Promise((resolve) => {
184
- // eslint-disable-next-line @typescript-eslint/no-floating-promises
185
- this.i18next.loadNamespaces(name, (err) => {
186
- if (!err)
187
- return resolve();
188
- // Here we got a non-null err object.
189
- // This method is called when the system has attempted to load the resources for the namespaces for each possible locale.
190
- // For example 'fr-ca' might be the most specific locale, in which case 'fr' and 'en' are fallback locales.
191
- // Using Backend from i18next-http-backend, err will be an array of strings of each namespace it tried to read and its locale.
192
- // There might be errs for some other namespaces as well as this one. We resolve the promise unless there's an error for each possible locale.
193
- let locales = this.getLanguageList().map((thisLocale) => `/${thisLocale}/`);
194
- try {
195
- for (const thisError of err) {
196
- if (typeof thisError === "string")
197
- locales = locales.filter((thisLocale) => !thisError.includes(thisLocale));
198
- }
199
- }
200
- catch (e) {
201
- locales = [];
202
- }
203
- // if we removed every locale from the array, it wasn't loaded.
204
- if (locales.length === 0)
205
- core_bentley_1.Logger.logError("i18n", `No resources for namespace ${name} could be loaded`);
206
- resolve();
207
- });
208
- });
209
- this._namespaces.set(name, theReadPromise);
210
- return theReadPromise;
211
- }
212
- /** @internal */
213
- unregisterNamespace(name) {
214
- this._namespaces.delete(name);
215
- }
216
- }
217
- exports.ITwinLocalization = ITwinLocalization;
218
- class TranslationLogger {
219
- log(args) { core_bentley_1.Logger.logInfo("i18n", this.createLogMessage(args)); }
220
- warn(args) { core_bentley_1.Logger.logWarning("i18n", this.createLogMessage(args)); }
221
- error(args) { core_bentley_1.Logger.logError("i18n", this.createLogMessage(args)); }
222
- createLogMessage(args) {
223
- let message = args[0];
224
- for (let i = 1; i < args.length; ++i) {
225
- if (typeof args[i] === "string")
226
- message += `\n ${args[i]}`;
227
- }
228
- return message;
229
- }
230
- }
231
- TranslationLogger.type = "logger";
1
+ "use strict";
2
+ /*---------------------------------------------------------------------------------------------
3
+ * Copyright (c) Bentley Systems, Incorporated. All rights reserved.
4
+ * See LICENSE.md in the project root for license terms and full copyright notice.
5
+ *--------------------------------------------------------------------------------------------*/
6
+ /** @packageDocumentation
7
+ * @module Localization
8
+ */
9
+ var __importDefault = (this && this.__importDefault) || function (mod) {
10
+ return (mod && mod.__esModule) ? mod : { "default": mod };
11
+ };
12
+ Object.defineProperty(exports, "__esModule", { value: true });
13
+ exports.ITwinLocalization = void 0;
14
+ const i18next_1 = __importDefault(require("i18next"));
15
+ const i18next_browser_languagedetector_1 = __importDefault(require("i18next-browser-languagedetector"));
16
+ const i18next_http_backend_1 = __importDefault(require("i18next-http-backend"));
17
+ const core_bentley_1 = require("@itwin/core-bentley");
18
+ const DEFAULT_MAX_RETRIES = 1; // a low number prevents wasted time and potential timeouts when requesting localization files throws an error
19
+ /** Supplies localizations for iTwin.js
20
+ * @note this class uses the [i18next](https://www.i18next.com/) package.
21
+ * @public
22
+ */
23
+ class ITwinLocalization {
24
+ constructor(options) {
25
+ this._namespaces = new Map();
26
+ this.i18next = i18next_1.default.createInstance();
27
+ this._backendOptions = {
28
+ loadPath: options?.urlTemplate ?? "locales/{{lng}}/{{ns}}.json",
29
+ crossDomain: true,
30
+ ...options?.backendHttpOptions,
31
+ };
32
+ this._detectionOptions = {
33
+ order: ["querystring", "navigator", "htmlTag"],
34
+ lookupQuerystring: "lng",
35
+ caches: [],
36
+ ...options?.detectorOptions,
37
+ };
38
+ this._initOptions = {
39
+ interpolation: { escapeValue: true },
40
+ fallbackLng: "en",
41
+ maxRetries: DEFAULT_MAX_RETRIES,
42
+ backend: this._backendOptions,
43
+ detection: this._detectionOptions,
44
+ ...options?.initOptions,
45
+ };
46
+ this.i18next
47
+ .use(options?.detectorPlugin ?? i18next_browser_languagedetector_1.default)
48
+ .use(options?.backendPlugin ?? i18next_http_backend_1.default)
49
+ .use(TranslationLogger);
50
+ }
51
+ async initialize(namespaces) {
52
+ // Also consider namespaces passed into constructor
53
+ const initNamespaces = [this._initOptions.ns || []].flat();
54
+ const combinedNamespaces = new Set([...namespaces, ...initNamespaces]); // without duplicates
55
+ const defaultNamespace = this._initOptions.defaultNS ?? namespaces[0];
56
+ if (defaultNamespace)
57
+ combinedNamespaces.add(defaultNamespace); // Make sure default namespace is in namespaces list
58
+ const initOptions = {
59
+ ...this._initOptions,
60
+ defaultNS: defaultNamespace,
61
+ ns: [...combinedNamespaces],
62
+ };
63
+ // if in a development environment, set debugging
64
+ if (process.env.NODE_ENV === "development")
65
+ initOptions.debug = true;
66
+ const initPromise = this.i18next.init(initOptions);
67
+ for (const ns of namespaces)
68
+ this._namespaces.set(ns, initPromise);
69
+ return initPromise;
70
+ }
71
+ /** Replace all instances of `%{key}` within a string with the translations of those keys.
72
+ * For example:
73
+ * ``` ts
74
+ * "MyKeys": {
75
+ * "Key1": "First value",
76
+ * "Key2": "Second value"
77
+ * }
78
+ * ```
79
+ *
80
+ * ``` ts
81
+ * i18.translateKeys("string with %{MyKeys.Key1} followed by %{MyKeys.Key2}!"") // returns "string with First Value followed by Second Value!"
82
+ * ```
83
+ * @param line The input line, potentially containing %{keys}.
84
+ * @returns The line with all %{keys} translated
85
+ * @public
86
+ */
87
+ getLocalizedKeys(line) {
88
+ return line.replace(/\%\{(.+?)\}/g, (_match, tag) => this.getLocalizedString(tag));
89
+ }
90
+ /** Return the translated value of a key.
91
+ * @param key - the key that matches a property in the JSON localization file.
92
+ * @note The key includes the namespace, which identifies the particular localization file that contains the property,
93
+ * followed by a colon, followed by the property in the JSON file.
94
+ * For example:
95
+ * ``` ts
96
+ * const dataString: string = IModelApp.localization.getLocalizedString("iModelJs:BackgroundMap.BingDataAttribution");
97
+ * ```
98
+ * assigns to dataString the string with property BackgroundMap.BingDataAttribution from the iModelJs.json localization file.
99
+ * @returns The string corresponding to the first key that resolves.
100
+ * @throws Error if no keys resolve to a string.
101
+ * @public
102
+ */
103
+ getLocalizedString(key, options) {
104
+ if (options?.returnDetails || options?.returnObjects) {
105
+ throw new Error("Translation key must map to a string, but the given options will result in an object");
106
+ }
107
+ const value = this.i18next.t(key, options);
108
+ if (typeof value !== "string") {
109
+ throw new Error("Translation key(s) string not found");
110
+ }
111
+ return value;
112
+ }
113
+ /** Similar to `getLocalizedString` but the default namespace is a separate parameter and the key does not need
114
+ * to include a namespace. If a key includes a namespace, that namespace will be used for interpolating that key.
115
+ * @param namespace - the namespace that identifies the particular localization file that contains the property.
116
+ * @param key - the key that matches a property in the JSON localization file.
117
+ * @returns The string corresponding to the first key that resolves.
118
+ * @throws Error if no keys resolve to a string.
119
+ * @internal
120
+ */
121
+ getLocalizedStringWithNamespace(namespace, key, options) {
122
+ let fullKey = "";
123
+ if (typeof key === "string") {
124
+ fullKey = `${namespace}:${key}`;
125
+ }
126
+ else {
127
+ fullKey = key.map((subKey) => {
128
+ return `${namespace}:${subKey}`;
129
+ });
130
+ }
131
+ return this.getLocalizedString(fullKey, options);
132
+ }
133
+ /** Gets the English translation.
134
+ * @param namespace - the namespace that identifies the particular localization file that contains the property.
135
+ * @param key - the key that matches a property in the JSON localization file.
136
+ * @returns The string corresponding to the first key that resolves.
137
+ * @throws Error if no keys resolve to a string.
138
+ * @internal
139
+ */
140
+ getEnglishString(namespace, key, options) {
141
+ if (options?.returnDetails || options?.returnObjects) {
142
+ throw new Error("Translation key must map to a string, but the given options will result in an object");
143
+ }
144
+ options = {
145
+ ...options,
146
+ ns: namespace, // ensure namespace argument is used
147
+ };
148
+ const en = this.i18next.getFixedT("en", namespace);
149
+ const str = en(key, options);
150
+ if (typeof str !== "string")
151
+ throw new Error("Translation key(s) not found");
152
+ return str;
153
+ }
154
+ /** Get the promise for an already registered Namespace.
155
+ * @param name - the name of the namespace
156
+ * @public
157
+ */
158
+ getNamespacePromise(name) {
159
+ return this._namespaces.get(name);
160
+ }
161
+ /** @internal */
162
+ getLanguageList() {
163
+ return this.i18next.languages;
164
+ }
165
+ /** override the language detected in the browser */
166
+ async changeLanguage(language) {
167
+ return this.i18next.changeLanguage(language);
168
+ }
169
+ /** Register a new Namespace and return it. If the namespace is already registered, it will be returned.
170
+ * @param name - the name of the namespace, which is the base name of the JSON file that contains the localization properties.
171
+ * @note - The registerNamespace method starts fetching the appropriate version of the JSON localization file from the server,
172
+ * based on the current locale. To make sure that fetch is complete before performing translations from this namespace, await
173
+ * fulfillment of the readPromise Promise property of the returned LocalizationNamespace.
174
+ * @see [Localization in iTwin.js]($docs/learning/frontend/Localization.md)
175
+ * @public
176
+ */
177
+ async registerNamespace(name) {
178
+ const existing = this._namespaces.get(name);
179
+ if (existing !== undefined)
180
+ return existing;
181
+ const theReadPromise = new Promise((resolve) => {
182
+ // eslint-disable-next-line @typescript-eslint/no-floating-promises
183
+ this.i18next.loadNamespaces(name, (err) => {
184
+ if (!err)
185
+ return resolve();
186
+ // Here we got a non-null err object.
187
+ // This method is called when the system has attempted to load the resources for the namespaces for each possible locale.
188
+ // For example 'fr-ca' might be the most specific locale, in which case 'fr' and 'en' are fallback locales.
189
+ // Using Backend from i18next-http-backend, err will be an array of strings of each namespace it tried to read and its locale.
190
+ // There might be errs for some other namespaces as well as this one. We resolve the promise unless there's an error for each possible locale.
191
+ let locales = this.getLanguageList().map((thisLocale) => `/${thisLocale}/`);
192
+ try {
193
+ for (const thisError of err) {
194
+ if (typeof thisError === "string")
195
+ locales = locales.filter((thisLocale) => !thisError.includes(thisLocale));
196
+ }
197
+ }
198
+ catch (e) {
199
+ locales = [];
200
+ }
201
+ // if we removed every locale from the array, it wasn't loaded.
202
+ if (locales.length === 0)
203
+ core_bentley_1.Logger.logError("i18n", `No resources for namespace ${name} could be loaded`);
204
+ resolve();
205
+ });
206
+ });
207
+ this._namespaces.set(name, theReadPromise);
208
+ return theReadPromise;
209
+ }
210
+ /** @internal */
211
+ unregisterNamespace(name) {
212
+ this._namespaces.delete(name);
213
+ }
214
+ }
215
+ exports.ITwinLocalization = ITwinLocalization;
216
+ class TranslationLogger {
217
+ log(args) { core_bentley_1.Logger.logInfo("i18n", this.createLogMessage(args)); }
218
+ warn(args) { core_bentley_1.Logger.logWarning("i18n", this.createLogMessage(args)); }
219
+ error(args) { core_bentley_1.Logger.logError("i18n", this.createLogMessage(args)); }
220
+ createLogMessage(args) {
221
+ let message = args[0];
222
+ for (let i = 1; i < args.length; ++i) {
223
+ if (typeof args[i] === "string")
224
+ message += `\n ${args[i]}`;
225
+ }
226
+ return message;
227
+ }
228
+ }
229
+ TranslationLogger.type = "logger";
232
230
  //# sourceMappingURL=ITwinLocalization.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"ITwinLocalization.js","sourceRoot":"","sources":["../../src/ITwinLocalization.ts"],"names":[],"mappings":";AAAA;;;+FAG+F;AAC/F;;GAEG;;;;;;AAEH,sDAA2E;AAC3E,wGAAmG;AACnG,gFAA+D;AAC/D,sDAA6C;AAG7C,MAAM,mBAAmB,GAAW,CAAC,CAAC,CAAC,8GAA8G;AAcrJ;;;GAGG;AACH,MAAa,iBAAiB;IAO5B,YAAmB,OAA6B;;QAF/B,gBAAW,GAAG,IAAI,GAAG,EAAyB,CAAC;QAG9D,IAAI,CAAC,OAAO,GAAG,iBAAO,CAAC,c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------\r\n* Copyright (c) Bentley Systems, Incorporated. All rights reserved.\r\n* See LICENSE.md in the project root for license terms and full copyright notice.\r\n*--------------------------------------------------------------------------------------------*/\r\n/** @packageDocumentation\r\n * @module Localization\r\n */\r\n\r\nimport i18next, { i18n, InitOptions, Module, TOptionsBase } from \"i18next\";\r\nimport i18nextBrowserLanguageDetector, { DetectorOptions } from \"i18next-browser-languagedetector\";\r\nimport Backend, { BackendOptions } from \"i18next-http-backend\";\r\nimport { Logger } from \"@itwin/core-bentley\";\r\nimport type { Localization } from \"@itwin/core-common\";\r\n\r\nconst DEFAULT_MAX_RETRIES: number = 1; // a low number prevents wasted time and potential timeouts when requesting localization files throws an error\r\n\r\n/** Options for ITwinLocalization\r\n * @public\r\n */\r\nexport interface LocalizationOptions {\r\n urlTemplate?: string;\r\n backendPlugin?: Module;\r\n detectorPlugin?: Module;\r\n initOptions?: InitOptions;\r\n backendHttpOptions?: BackendOptions;\r\n detectorOptions?: DetectorOptions;\r\n}\r\n\r\n/** Supplies localizations for iTwin.js\r\n * @note this class uses the [i18next](https://www.i18next.com/) package.\r\n * @public\r\n */\r\nexport class ITwinLocalization implements Localization {\r\n public i18next: i18n;\r\n private readonly _initOptions: InitOptions;\r\n private readonly _backendOptions: BackendOptions;\r\n private readonly _detectionOptions: DetectorOptions;\r\n private readonly _namespaces = new Map<string, Promise<void>>();\r\n\r\n public constructor(options?: LocalizationOptions) {\r\n this.i18next = i18next.createInstance();\r\n\r\n this._backendOptions = {\r\n loadPath: options?.urlTemplate ?? \"locales/{{lng}}/{{ns}}.json\",\r\n crossDomain: true,\r\n ...options?.backendHttpOptions,\r\n };\r\n\r\n this._detectionOptions = {\r\n order: [\"querystring\", \"navigator\", \"htmlTag\"],\r\n lookupQuerystring: \"lng\",\r\n caches: [],\r\n ...options?.detectorOptions,\r\n };\r\n\r\n this._initOptions = {\r\n interpolation: { escapeValue: true },\r\n fallbackLng: \"en\",\r\n maxRetries: DEFAULT_MAX_RETRIES,\r\n backend: this._backendOptions,\r\n detection: this._detectionOptions,\r\n ...options?.initOptions,\r\n };\r\n\r\n this.i18next\r\n .use(options?.detectorPlugin ?? i18nextBrowserLanguageDetector)\r\n .use(options?.backendPlugin ?? Backend)\r\n .use(TranslationLogger);\r\n }\r\n\r\n public async initialize(namespaces: string[]): Promise<void> {\r\n\r\n // Also consider namespaces passed into constructor\r\n const initNamespaces: string[] = [this._initOptions.ns || []].flat();\r\n const combinedNamespaces: Set<string> = new Set([...namespaces, ...initNamespaces]); // without duplicates\r\n\r\n const defaultNamespace: string | false | readonly string[] = this._initOptions.defaultNS ?? namespaces[0];\r\n if (defaultNamespace)\r\n combinedNamespaces.add(defaultNamespace as string); // Make sure default namespace is in namespaces list\r\n\r\n const initOptions: InitOptions = {\r\n ...this._initOptions,\r\n defaultNS: defaultNamespace,\r\n ns: [...combinedNamespaces],\r\n };\r\n\r\n // if in a development environment, set debugging\r\n if (process.env.NODE_ENV === \"development\")\r\n initOptions.debug = true;\r\n\r\n const initPromise = this.i18next.init(initOptions) as unknown as Promise<void>;\r\n\r\n for (const ns of namespaces)\r\n this._namespaces.set(ns, initPromise);\r\n\r\n return initPromise;\r\n }\r\n\r\n /** Replace all instances of `%{key}` within a string with the translations of those keys.\r\n * For example:\r\n * ``` ts\r\n * \"MyKeys\": {\r\n * \"Key1\": \"First value\",\r\n * \"Key2\": \"Second value\"\r\n * }\r\n * ```\r\n *\r\n * ``` ts\r\n * i18.translateKeys(\"string with %{MyKeys.Key1} followed by %{MyKeys.Key2}!\"\") // returns \"string with First Value followed by Second Value!\"\r\n * ```\r\n * @param line The input line, potentially containing %{keys}.\r\n * @returns The line with all %{keys} translated\r\n * @public\r\n */\r\n public getLocalizedKeys(line: string): string {\r\n return line.replace(/\\%\\{(.+?)\\}/g, (_match, tag) => this.getLocalizedString(tag));\r\n }\r\n\r\n /** Return the translated value of a key.\r\n * @param key - the key that matches a property in the JSON localization file.\r\n * @note The key includes the namespace, which identifies the particular localization file that contains the property,\r\n * followed by a colon, followed by the property in the JSON file.\r\n * For example:\r\n * ``` ts\r\n * const dataString: string = IModelApp.localization.getLocalizedString(\"iModelJs:BackgroundMap.BingDataAttribution\");\r\n * ```\r\n * assigns to dataString the string with property BackgroundMap.BingDataAttribution from the iModelJs.json localization file.\r\n * @returns The string corresponding to the first key that resolves.\r\n * @throws Error if no keys resolve to a string.\r\n * @public\r\n */\r\n public getLocalizedString(key: string | string[], options?: TOptionsBase): string {\r\n if (options?.returnDetails || options?.returnObjects) {\r\n throw new Error(\"Translation key must map to a string, but the given options will result in an object\");\r\n }\r\n\r\n const value = this.i18next.t(key, options);\r\n\r\n if (typeof value !== \"string\") {\r\n throw new Error(\"Translation key(s) string not found\");\r\n }\r\n\r\n return value;\r\n }\r\n\r\n /** Similar to `getLocalizedString` but the default namespace is a separate parameter and the key does not need\r\n * to include a namespace. If a key includes a namespace, that namespace will be used for interpolating that key.\r\n * @param namespace - the namespace that identifies the particular localization file that contains the property.\r\n * @param key - the key that matches a property in the JSON localization file.\r\n * @returns The string corresponding to the first key that resolves.\r\n * @throws Error if no keys resolve to a string.\r\n * @internal\r\n */\r\n public getLocalizedStringWithNamespace(namespace: string, key: string | string[], options?: TOptionsBase): string {\r\n let fullKey: string | string[] = \"\";\r\n\r\n if (typeof key === \"string\") {\r\n fullKey = `${namespace}:${key}`;\r\n } else {\r\n fullKey = key.map((subKey: string) => {\r\n return `${namespace}:${subKey}`;\r\n });\r\n }\r\n\r\n return this.getLocalizedString(fullKey, options);\r\n }\r\n\r\n /** Gets the English translation.\r\n * @param namespace - the namespace that identifies the particular localization file that contains the property.\r\n * @param key - the key that matches a property in the JSON localization file.\r\n * @returns The string corresponding to the first key that resolves.\r\n * @throws Error if no keys resolve to a string.\r\n * @internal\r\n */\r\n public getEnglishString(namespace: string, key: string | string[], options?: TOptionsBase): string {\r\n if (options?.returnDetails || options?.returnObjects) {\r\n throw new Error(\"Translation key must map to a string, but the given options will result in an object\");\r\n }\r\n\r\n options = {\r\n ...options,\r\n ns: namespace, // ensure namespace argument is used\r\n };\r\n\r\n const en = this.i18next.getFixedT(\"en\", namespace);\r\n const str = en(key, options);\r\n if (typeof str !== \"string\")\r\n throw new Error(\"Translation key(s) not found\");\r\n\r\n return str;\r\n }\r\n\r\n /** Get the promise for an already registered Namespace.\r\n * @param name - the name of the namespace\r\n * @public\r\n */\r\n public getNamespacePromise(name: string): Promise<void> | undefined {\r\n return this._namespaces.get(name);\r\n }\r\n\r\n /** @internal */\r\n public getLanguageList(): readonly string[] {\r\n return this.i18next.languages;\r\n }\r\n\r\n /** override the language detected in the browser */\r\n public async changeLanguage(language: string) {\r\n return this.i18next.changeLanguage(language) as unknown as Promise<void>;\r\n }\r\n\r\n /** Register a new Namespace and return it. If the namespace is already registered, it will be returned.\r\n * @param name - the name of the namespace, which is the base name of the JSON file that contains the localization properties.\r\n * @note - The registerNamespace method starts fetching the appropriate version of the JSON localization file from the server,\r\n * based on the current locale. To make sure that fetch is complete before performing translations from this namespace, await\r\n * fulfillment of the readPromise Promise property of the returned LocalizationNamespace.\r\n * @see [Localization in iTwin.js]($docs/learning/frontend/Localization.md)\r\n * @public\r\n */\r\n public async registerNamespace(name: string): Promise<void> {\r\n const existing = this._namespaces.get(name);\r\n if (existing !== undefined)\r\n return existing;\r\n\r\n const theReadPromise = new Promise<void>((resolve) => {\r\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\r\n this.i18next.loadNamespaces(name, (err) => {\r\n if (!err)\r\n return resolve();\r\n\r\n // Here we got a non-null err object.\r\n // This method is called when the system has attempted to load the resources for the namespaces for each possible locale.\r\n // For example 'fr-ca' might be the most specific locale, in which case 'fr' and 'en' are fallback locales.\r\n // Using Backend from i18next-http-backend, err will be an array of strings of each namespace it tried to read and its locale.\r\n // There might be errs for some other namespaces as well as this one. We resolve the promise unless there's an error for each possible locale.\r\n let locales = this.getLanguageList().map((thisLocale: any) => `/${thisLocale}/`);\r\n\r\n try {\r\n for (const thisError of err) {\r\n if (typeof thisError === \"string\")\r\n locales = locales.filter((thisLocale) => !thisError.includes(thisLocale));\r\n }\r\n } catch (e) {\r\n locales = [];\r\n }\r\n // if we removed every locale from the array, it wasn't loaded.\r\n if (locales.length === 0)\r\n Logger.logError(\"i18n\", `No resources for namespace ${name} could be loaded`);\r\n\r\n resolve();\r\n });\r\n });\r\n this._namespaces.set(name, theReadPromise);\r\n return theReadPromise;\r\n }\r\n\r\n /** @internal */\r\n public unregisterNamespace(name: string): void {\r\n this._namespaces.delete(name);\r\n }\r\n}\r\n\r\nclass TranslationLogger {\r\n public static readonly type = \"logger\";\r\n public log(args: string[]) { Logger.logInfo(\"i18n\", this.createLogMessage(args)); }\r\n public warn(args: string[]) { Logger.logWarning(\"i18n\", this.createLogMessage(args)); }\r\n public error(args: string[]) { Logger.logError(\"i18n\", this.createLogMessage(args)); }\r\n private createLogMessage(args: string[]) {\r\n let message = args[0];\r\n for (let i = 1; i < args.length; ++i) {\r\n if (typeof args[i] === \"string\")\r\n message += `\\n ${args[i]}`;\r\n }\r\n return message;\r\n }\r\n}\r\n"]}
1
+ {"version":3,"file":"ITwinLocalization.js","sourceRoot":"","sources":["../../src/ITwinLocalization.ts"],"names":[],"mappings":";AAAA;;;+FAG+F;AAC/F;;GAEG;;;;;;AAEH,sDAA2E;AAC3E,wGAAmG;AACnG,gFAA+D;AAC/D,sDAA6C;AAG7C,MAAM,mBAAmB,GAAW,CAAC,CAAC,CAAC,8GAA8G;AAcrJ;;;GAGG;AACH,MAAa,iBAAiB;IAO5B,YAAmB,OAA6B;QAF/B,gBAAW,GAAG,IAAI,GAAG,EAAyB,CAAC;QAG9D,IAAI,CAAC,OAAO,GAAG,iBAAO,CAAC,cAAc,EAAE,CAAC;QAExC,IAAI,CAAC,eAAe,GAAG;YACrB,QAAQ,EAAE,OAAO,EAAE,WAAW,IAAI,6BAA6B;YAC/D,WAAW,EAAE,IAAI;YACjB,GAAG,OAAO,EAAE,kBAAkB;SAC/B,CAAC;QAEF,IAAI,CAAC,iBAAiB,G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IAAI,CAAC,gBAAgB,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC;IAC5E,IAAI,CAAC,IAAc,IAAI,qBAAM,CAAC,UAAU,CAAC,MAAM,EAAE,IAAI,CAAC,gBAAgB,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC;IAChF,KAAK,CAAC,IAAc,IAAI,qBAAM,CAAC,QAAQ,CAAC,MAAM,EAAE,IAAI,CAAC,gBAAgB,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC;IAC9E,gBAAgB,CAAC,IAAc;QACrC,IAAI,OAAO,GAAG,IAAI,CAAC,CAAC,CAAC,CAAC;QACtB,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,IAAI,CAAC,MAAM,EAAE,EAAE,CAAC,EAAE;YACpC,IAAI,OAAO,IAAI,CAAC,CAAC,CAAC,KAAK,QAAQ;gBAC7B,OAAO,IAAI,OAAO,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC;SAC/B;QACD,OAAO,OAAO,CAAC;IACjB,CAAC;;AAXsB,sBAAI,GAAG,QAAQ,CAAC","sourcesContent":["/*---------------------------------------------------------------------------------------------\r\n* Copyright (c) Bentley Systems, Incorporated. All rights reserved.\r\n* See LICENSE.md in the project root for license terms and full copyright notice.\r\n*--------------------------------------------------------------------------------------------*/\r\n/** @packageDocumentation\r\n * @module Localization\r\n */\r\n\r\nimport i18next, { i18n, InitOptions, Module, TOptionsBase } from \"i18next\";\r\nimport i18nextBrowserLanguageDetector, { DetectorOptions } from \"i18next-browser-languagedetector\";\r\nimport Backend, { BackendOptions } from \"i18next-http-backend\";\r\nimport { Logger } from \"@itwin/core-bentley\";\r\nimport type { Localization } from \"@itwin/core-common\";\r\n\r\nconst DEFAULT_MAX_RETRIES: number = 1; // a low number prevents wasted time and potential timeouts when requesting localization files throws an error\r\n\r\n/** Options for ITwinLocalization\r\n * @public\r\n */\r\nexport interface LocalizationOptions {\r\n urlTemplate?: string;\r\n backendPlugin?: Module;\r\n detectorPlugin?: Module;\r\n initOptions?: InitOptions;\r\n backendHttpOptions?: BackendOptions;\r\n detectorOptions?: DetectorOptions;\r\n}\r\n\r\n/** Supplies localizations for iTwin.js\r\n * @note this class uses the [i18next](https://www.i18next.com/) package.\r\n * @public\r\n */\r\nexport class ITwinLocalization implements Localization {\r\n public i18next: i18n;\r\n private readonly _initOptions: InitOptions;\r\n private readonly _backendOptions: BackendOptions;\r\n private readonly _detectionOptions: DetectorOptions;\r\n private readonly _namespaces = new Map<string, Promise<void>>();\r\n\r\n public constructor(options?: LocalizationOptions) {\r\n this.i18next = i18next.createInstance();\r\n\r\n this._backendOptions = {\r\n loadPath: options?.urlTemplate ?? \"locales/{{lng}}/{{ns}}.json\",\r\n crossDomain: true,\r\n ...options?.backendHttpOptions,\r\n };\r\n\r\n this._detectionOptions = {\r\n order: [\"querystring\", \"navigator\", \"htmlTag\"],\r\n lookupQuerystring: \"lng\",\r\n caches: [],\r\n ...options?.detectorOptions,\r\n };\r\n\r\n this._initOptions = {\r\n interpolation: { escapeValue: true },\r\n fallbackLng: \"en\",\r\n maxRetries: DEFAULT_MAX_RETRIES,\r\n backend: this._backendOptions,\r\n detection: this._detectionOptions,\r\n ...options?.initOptions,\r\n };\r\n\r\n this.i18next\r\n .use(options?.detectorPlugin ?? i18nextBrowserLanguageDetector)\r\n .use(options?.backendPlugin ?? Backend)\r\n .use(TranslationLogger);\r\n }\r\n\r\n public async initialize(namespaces: string[]): Promise<void> {\r\n\r\n // Also consider namespaces passed into constructor\r\n const initNamespaces: string[] = [this._initOptions.ns || []].flat();\r\n const combinedNamespaces: Set<string> = new Set([...namespaces, ...initNamespaces]); // without duplicates\r\n\r\n const defaultNamespace: string | false | readonly string[] = this._initOptions.defaultNS ?? namespaces[0];\r\n if (defaultNamespace)\r\n combinedNamespaces.add(defaultNamespace as string); // Make sure default namespace is in namespaces list\r\n\r\n const initOptions: InitOptions = {\r\n ...this._initOptions,\r\n defaultNS: defaultNamespace,\r\n ns: [...combinedNamespaces],\r\n };\r\n\r\n // if in a development environment, set debugging\r\n if (process.env.NODE_ENV === \"development\")\r\n initOptions.debug = true;\r\n\r\n const initPromise = this.i18next.init(initOptions) as unknown as Promise<void>;\r\n\r\n for (const ns of namespaces)\r\n this._namespaces.set(ns, initPromise);\r\n\r\n return initPromise;\r\n }\r\n\r\n /** Replace all instances of `%{key}` within a string with the translations of those keys.\r\n * For example:\r\n * ``` ts\r\n * \"MyKeys\": {\r\n * \"Key1\": \"First value\",\r\n * \"Key2\": \"Second value\"\r\n * }\r\n * ```\r\n *\r\n * ``` ts\r\n * i18.translateKeys(\"string with %{MyKeys.Key1} followed by %{MyKeys.Key2}!\"\") // returns \"string with First Value followed by Second Value!\"\r\n * ```\r\n * @param line The input line, potentially containing %{keys}.\r\n * @returns The line with all %{keys} translated\r\n * @public\r\n */\r\n public getLocalizedKeys(line: string): string {\r\n return line.replace(/\\%\\{(.+?)\\}/g, (_match, tag) => this.getLocalizedString(tag));\r\n }\r\n\r\n /** Return the translated value of a key.\r\n * @param key - the key that matches a property in the JSON localization file.\r\n * @note The key includes the namespace, which identifies the particular localization file that contains the property,\r\n * followed by a colon, followed by the property in the JSON file.\r\n * For example:\r\n * ``` ts\r\n * const dataString: string = IModelApp.localization.getLocalizedString(\"iModelJs:BackgroundMap.BingDataAttribution\");\r\n * ```\r\n * assigns to dataString the string with property BackgroundMap.BingDataAttribution from the iModelJs.json localization file.\r\n * @returns The string corresponding to the first key that resolves.\r\n * @throws Error if no keys resolve to a string.\r\n * @public\r\n */\r\n public getLocalizedString(key: string | string[], options?: TOptionsBase): string {\r\n if (options?.returnDetails || options?.returnObjects) {\r\n throw new Error(\"Translation key must map to a string, but the given options will result in an object\");\r\n }\r\n\r\n const value = this.i18next.t(key, options);\r\n\r\n if (typeof value !== \"string\") {\r\n throw new Error(\"Translation key(s) string not found\");\r\n }\r\n\r\n return value;\r\n }\r\n\r\n /** Similar to `getLocalizedString` but the default namespace is a separate parameter and the key does not need\r\n * to include a namespace. If a key includes a namespace, that namespace will be used for interpolating that key.\r\n * @param namespace - the namespace that identifies the particular localization file that contains the property.\r\n * @param key - the key that matches a property in the JSON localization file.\r\n * @returns The string corresponding to the first key that resolves.\r\n * @throws Error if no keys resolve to a string.\r\n * @internal\r\n */\r\n public getLocalizedStringWithNamespace(namespace: string, key: string | string[], options?: TOptionsBase): string {\r\n let fullKey: string | string[] = \"\";\r\n\r\n if (typeof key === \"string\") {\r\n fullKey = `${namespace}:${key}`;\r\n } else {\r\n fullKey = key.map((subKey: string) => {\r\n return `${namespace}:${subKey}`;\r\n });\r\n }\r\n\r\n return this.getLocalizedString(fullKey, options);\r\n }\r\n\r\n /** Gets the English translation.\r\n * @param namespace - the namespace that identifies the particular localization file that contains the property.\r\n * @param key - the key that matches a property in the JSON localization file.\r\n * @returns The string corresponding to the first key that resolves.\r\n * @throws Error if no keys resolve to a string.\r\n * @internal\r\n */\r\n public getEnglishString(namespace: string, key: string | string[], options?: TOptionsBase): string {\r\n if (options?.returnDetails || options?.returnObjects) {\r\n throw new Error(\"Translation key must map to a string, but the given options will result in an object\");\r\n }\r\n\r\n options = {\r\n ...options,\r\n ns: namespace, // ensure namespace argument is used\r\n };\r\n\r\n const en = this.i18next.getFixedT(\"en\", namespace);\r\n const str = en(key, options);\r\n if (typeof str !== \"string\")\r\n throw new Error(\"Translation key(s) not found\");\r\n\r\n return str;\r\n }\r\n\r\n /** Get the promise for an already registered Namespace.\r\n * @param name - the name of the namespace\r\n * @public\r\n */\r\n public getNamespacePromise(name: string): Promise<void> | undefined {\r\n return this._namespaces.get(name);\r\n }\r\n\r\n /** @internal */\r\n public getLanguageList(): readonly string[] {\r\n return this.i18next.languages;\r\n }\r\n\r\n /** override the language detected in the browser */\r\n public async changeLanguage(language: string) {\r\n return this.i18next.changeLanguage(language) as unknown as Promise<void>;\r\n }\r\n\r\n /** Register a new Namespace and return it. If the namespace is already registered, it will be returned.\r\n * @param name - the name of the namespace, which is the base name of the JSON file that contains the localization properties.\r\n * @note - The registerNamespace method starts fetching the appropriate version of the JSON localization file from the server,\r\n * based on the current locale. To make sure that fetch is complete before performing translations from this namespace, await\r\n * fulfillment of the readPromise Promise property of the returned LocalizationNamespace.\r\n * @see [Localization in iTwin.js]($docs/learning/frontend/Localization.md)\r\n * @public\r\n */\r\n public async registerNamespace(name: string): Promise<void> {\r\n const existing = this._namespaces.get(name);\r\n if (existing !== undefined)\r\n return existing;\r\n\r\n const theReadPromise = new Promise<void>((resolve) => {\r\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\r\n this.i18next.loadNamespaces(name, (err) => {\r\n if (!err)\r\n return resolve();\r\n\r\n // Here we got a non-null err object.\r\n // This method is called when the system has attempted to load the resources for the namespaces for each possible locale.\r\n // For example 'fr-ca' might be the most specific locale, in which case 'fr' and 'en' are fallback locales.\r\n // Using Backend from i18next-http-backend, err will be an array of strings of each namespace it tried to read and its locale.\r\n // There might be errs for some other namespaces as well as this one. We resolve the promise unless there's an error for each possible locale.\r\n let locales = this.getLanguageList().map((thisLocale: any) => `/${thisLocale}/`);\r\n\r\n try {\r\n for (const thisError of err) {\r\n if (typeof thisError === \"string\")\r\n locales = locales.filter((thisLocale) => !thisError.includes(thisLocale));\r\n }\r\n } catch (e) {\r\n locales = [];\r\n }\r\n // if we removed every locale from the array, it wasn't loaded.\r\n if (locales.length === 0)\r\n Logger.logError(\"i18n\", `No resources for namespace ${name} could be loaded`);\r\n\r\n resolve();\r\n });\r\n });\r\n this._namespaces.set(name, theReadPromise);\r\n return theReadPromise;\r\n }\r\n\r\n /** @internal */\r\n public unregisterNamespace(name: string): void {\r\n this._namespaces.delete(name);\r\n }\r\n}\r\n\r\nclass TranslationLogger {\r\n public static readonly type = \"logger\";\r\n public log(args: string[]) { Logger.logInfo(\"i18n\", this.createLogMessage(args)); }\r\n public warn(args: string[]) { Logger.logWarning(\"i18n\", this.createLogMessage(args)); }\r\n public error(args: string[]) { Logger.logError(\"i18n\", this.createLogMessage(args)); }\r\n private createLogMessage(args: string[]) {\r\n let message = args[0];\r\n for (let i = 1; i < args.length; ++i) {\r\n if (typeof args[i] === \"string\")\r\n message += `\\n ${args[i]}`;\r\n }\r\n return message;\r\n }\r\n}\r\n"]}
@@ -1,8 +1,8 @@
1
- export * from "./ITwinLocalization";
2
- /** @docs-package-description
3
- * The core-i18n package contains classes related to internationalization and localization.
4
- */
5
- /** @docs-group-description Localization
6
- * Classes for internationalization and localization of your app.
7
- */
1
+ export * from "./ITwinLocalization";
2
+ /** @docs-package-description
3
+ * The core-i18n package contains classes related to internationalization and localization.
4
+ */
5
+ /** @docs-group-description Localization
6
+ * Classes for internationalization and localization of your app.
7
+ */
8
8
  //# sourceMappingURL=core-i18n.d.ts.map