@itwin/core-i18n 4.0.0-dev.7 → 4.0.0-dev.72

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