@aidc-toolkit/gs1 0.9.8-beta → 0.9.9-beta

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.
package/dist/index.js CHANGED
@@ -1,2205 +1,7 @@
1
1
  // src/locale/i18n.ts
2
2
  import { i18nAssertValidResources, i18nCoreInit } from "@aidc-toolkit/core";
3
3
  import { i18nUtilityInit, utilityResources } from "@aidc-toolkit/utility";
4
-
5
- // node_modules/i18next/dist/esm/i18next.js
6
- var isString = (obj) => typeof obj === "string";
7
- var defer = () => {
8
- let res;
9
- let rej;
10
- const promise = new Promise((resolve, reject) => {
11
- res = resolve;
12
- rej = reject;
13
- });
14
- promise.resolve = res;
15
- promise.reject = rej;
16
- return promise;
17
- };
18
- var makeString = (object) => {
19
- if (object == null) return "";
20
- return "" + object;
21
- };
22
- var copy = (a, s, t2) => {
23
- a.forEach((m) => {
24
- if (s[m]) t2[m] = s[m];
25
- });
26
- };
27
- var lastOfPathSeparatorRegExp = /###/g;
28
- var cleanKey = (key) => key && key.indexOf("###") > -1 ? key.replace(lastOfPathSeparatorRegExp, ".") : key;
29
- var canNotTraverseDeeper = (object) => !object || isString(object);
30
- var getLastOfPath = (object, path, Empty) => {
31
- const stack = !isString(path) ? path : path.split(".");
32
- let stackIndex = 0;
33
- while (stackIndex < stack.length - 1) {
34
- if (canNotTraverseDeeper(object)) return {};
35
- const key = cleanKey(stack[stackIndex]);
36
- if (!object[key] && Empty) object[key] = new Empty();
37
- if (Object.prototype.hasOwnProperty.call(object, key)) {
38
- object = object[key];
39
- } else {
40
- object = {};
41
- }
42
- ++stackIndex;
43
- }
44
- if (canNotTraverseDeeper(object)) return {};
45
- return {
46
- obj: object,
47
- k: cleanKey(stack[stackIndex])
48
- };
49
- };
50
- var setPath = (object, path, newValue) => {
51
- const {
52
- obj,
53
- k
54
- } = getLastOfPath(object, path, Object);
55
- if (obj !== void 0 || path.length === 1) {
56
- obj[k] = newValue;
57
- return;
58
- }
59
- let e = path[path.length - 1];
60
- let p = path.slice(0, path.length - 1);
61
- let last = getLastOfPath(object, p, Object);
62
- while (last.obj === void 0 && p.length) {
63
- e = `${p[p.length - 1]}.${e}`;
64
- p = p.slice(0, p.length - 1);
65
- last = getLastOfPath(object, p, Object);
66
- if (last?.obj && typeof last.obj[`${last.k}.${e}`] !== "undefined") {
67
- last.obj = void 0;
68
- }
69
- }
70
- last.obj[`${last.k}.${e}`] = newValue;
71
- };
72
- var pushPath = (object, path, newValue, concat) => {
73
- const {
74
- obj,
75
- k
76
- } = getLastOfPath(object, path, Object);
77
- obj[k] = obj[k] || [];
78
- obj[k].push(newValue);
79
- };
80
- var getPath = (object, path) => {
81
- const {
82
- obj,
83
- k
84
- } = getLastOfPath(object, path);
85
- if (!obj) return void 0;
86
- return obj[k];
87
- };
88
- var getPathWithDefaults = (data, defaultData, key) => {
89
- const value = getPath(data, key);
90
- if (value !== void 0) {
91
- return value;
92
- }
93
- return getPath(defaultData, key);
94
- };
95
- var deepExtend = (target, source, overwrite) => {
96
- for (const prop in source) {
97
- if (prop !== "__proto__" && prop !== "constructor") {
98
- if (prop in target) {
99
- if (isString(target[prop]) || target[prop] instanceof String || isString(source[prop]) || source[prop] instanceof String) {
100
- if (overwrite) target[prop] = source[prop];
101
- } else {
102
- deepExtend(target[prop], source[prop], overwrite);
103
- }
104
- } else {
105
- target[prop] = source[prop];
106
- }
107
- }
108
- }
109
- return target;
110
- };
111
- var regexEscape = (str) => str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
112
- var _entityMap = {
113
- "&": "&amp;",
114
- "<": "&lt;",
115
- ">": "&gt;",
116
- '"': "&quot;",
117
- "'": "&#39;",
118
- "/": "&#x2F;"
119
- };
120
- var escape = (data) => {
121
- if (isString(data)) {
122
- return data.replace(/[&<>"'\/]/g, (s) => _entityMap[s]);
123
- }
124
- return data;
125
- };
126
- var RegExpCache = class {
127
- constructor(capacity) {
128
- this.capacity = capacity;
129
- this.regExpMap = /* @__PURE__ */ new Map();
130
- this.regExpQueue = [];
131
- }
132
- getRegExp(pattern) {
133
- const regExpFromCache = this.regExpMap.get(pattern);
134
- if (regExpFromCache !== void 0) {
135
- return regExpFromCache;
136
- }
137
- const regExpNew = new RegExp(pattern);
138
- if (this.regExpQueue.length === this.capacity) {
139
- this.regExpMap.delete(this.regExpQueue.shift());
140
- }
141
- this.regExpMap.set(pattern, regExpNew);
142
- this.regExpQueue.push(pattern);
143
- return regExpNew;
144
- }
145
- };
146
- var chars = [" ", ",", "?", "!", ";"];
147
- var looksLikeObjectPathRegExpCache = new RegExpCache(20);
148
- var looksLikeObjectPath = (key, nsSeparator, keySeparator) => {
149
- nsSeparator = nsSeparator || "";
150
- keySeparator = keySeparator || "";
151
- const possibleChars = chars.filter((c) => nsSeparator.indexOf(c) < 0 && keySeparator.indexOf(c) < 0);
152
- if (possibleChars.length === 0) return true;
153
- const r = looksLikeObjectPathRegExpCache.getRegExp(`(${possibleChars.map((c) => c === "?" ? "\\?" : c).join("|")})`);
154
- let matched = !r.test(key);
155
- if (!matched) {
156
- const ki = key.indexOf(keySeparator);
157
- if (ki > 0 && !r.test(key.substring(0, ki))) {
158
- matched = true;
159
- }
160
- }
161
- return matched;
162
- };
163
- var deepFind = function(obj, path) {
164
- let keySeparator = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : ".";
165
- if (!obj) return void 0;
166
- if (obj[path]) return obj[path];
167
- const tokens = path.split(keySeparator);
168
- let current = obj;
169
- for (let i = 0; i < tokens.length; ) {
170
- if (!current || typeof current !== "object") {
171
- return void 0;
172
- }
173
- let next;
174
- let nextPath = "";
175
- for (let j = i; j < tokens.length; ++j) {
176
- if (j !== i) {
177
- nextPath += keySeparator;
178
- }
179
- nextPath += tokens[j];
180
- next = current[nextPath];
181
- if (next !== void 0) {
182
- if (["string", "number", "boolean"].indexOf(typeof next) > -1 && j < tokens.length - 1) {
183
- continue;
184
- }
185
- i += j - i + 1;
186
- break;
187
- }
188
- }
189
- current = next;
190
- }
191
- return current;
192
- };
193
- var getCleanedCode = (code) => code?.replace("_", "-");
194
- var consoleLogger = {
195
- type: "logger",
196
- log(args) {
197
- this.output("log", args);
198
- },
199
- warn(args) {
200
- this.output("warn", args);
201
- },
202
- error(args) {
203
- this.output("error", args);
204
- },
205
- output(type, args) {
206
- console?.[type]?.apply?.(console, args);
207
- }
208
- };
209
- var Logger = class _Logger {
210
- constructor(concreteLogger) {
211
- let options = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
212
- this.init(concreteLogger, options);
213
- }
214
- init(concreteLogger) {
215
- let options = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
216
- this.prefix = options.prefix || "i18next:";
217
- this.logger = concreteLogger || consoleLogger;
218
- this.options = options;
219
- this.debug = options.debug;
220
- }
221
- log() {
222
- for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
223
- args[_key] = arguments[_key];
224
- }
225
- return this.forward(args, "log", "", true);
226
- }
227
- warn() {
228
- for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
229
- args[_key2] = arguments[_key2];
230
- }
231
- return this.forward(args, "warn", "", true);
232
- }
233
- error() {
234
- for (var _len3 = arguments.length, args = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {
235
- args[_key3] = arguments[_key3];
236
- }
237
- return this.forward(args, "error", "");
238
- }
239
- deprecate() {
240
- for (var _len4 = arguments.length, args = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) {
241
- args[_key4] = arguments[_key4];
242
- }
243
- return this.forward(args, "warn", "WARNING DEPRECATED: ", true);
244
- }
245
- forward(args, lvl, prefix, debugOnly) {
246
- if (debugOnly && !this.debug) return null;
247
- if (isString(args[0])) args[0] = `${prefix}${this.prefix} ${args[0]}`;
248
- return this.logger[lvl](args);
249
- }
250
- create(moduleName) {
251
- return new _Logger(this.logger, {
252
- ...{
253
- prefix: `${this.prefix}:${moduleName}:`
254
- },
255
- ...this.options
256
- });
257
- }
258
- clone(options) {
259
- options = options || this.options;
260
- options.prefix = options.prefix || this.prefix;
261
- return new _Logger(this.logger, options);
262
- }
263
- };
264
- var baseLogger = new Logger();
265
- var EventEmitter = class {
266
- constructor() {
267
- this.observers = {};
268
- }
269
- on(events, listener) {
270
- events.split(" ").forEach((event) => {
271
- if (!this.observers[event]) this.observers[event] = /* @__PURE__ */ new Map();
272
- const numListeners = this.observers[event].get(listener) || 0;
273
- this.observers[event].set(listener, numListeners + 1);
274
- });
275
- return this;
276
- }
277
- off(event, listener) {
278
- if (!this.observers[event]) return;
279
- if (!listener) {
280
- delete this.observers[event];
281
- return;
282
- }
283
- this.observers[event].delete(listener);
284
- }
285
- emit(event) {
286
- for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
287
- args[_key - 1] = arguments[_key];
288
- }
289
- if (this.observers[event]) {
290
- const cloned = Array.from(this.observers[event].entries());
291
- cloned.forEach((_ref) => {
292
- let [observer, numTimesAdded] = _ref;
293
- for (let i = 0; i < numTimesAdded; i++) {
294
- observer(...args);
295
- }
296
- });
297
- }
298
- if (this.observers["*"]) {
299
- const cloned = Array.from(this.observers["*"].entries());
300
- cloned.forEach((_ref2) => {
301
- let [observer, numTimesAdded] = _ref2;
302
- for (let i = 0; i < numTimesAdded; i++) {
303
- observer.apply(observer, [event, ...args]);
304
- }
305
- });
306
- }
307
- }
308
- };
309
- var ResourceStore = class extends EventEmitter {
310
- constructor(data) {
311
- let options = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {
312
- ns: ["translation"],
313
- defaultNS: "translation"
314
- };
315
- super();
316
- this.data = data || {};
317
- this.options = options;
318
- if (this.options.keySeparator === void 0) {
319
- this.options.keySeparator = ".";
320
- }
321
- if (this.options.ignoreJSONStructure === void 0) {
322
- this.options.ignoreJSONStructure = true;
323
- }
324
- }
325
- addNamespaces(ns) {
326
- if (this.options.ns.indexOf(ns) < 0) {
327
- this.options.ns.push(ns);
328
- }
329
- }
330
- removeNamespaces(ns) {
331
- const index = this.options.ns.indexOf(ns);
332
- if (index > -1) {
333
- this.options.ns.splice(index, 1);
334
- }
335
- }
336
- getResource(lng, ns, key) {
337
- let options = arguments.length > 3 && arguments[3] !== void 0 ? arguments[3] : {};
338
- const keySeparator = options.keySeparator !== void 0 ? options.keySeparator : this.options.keySeparator;
339
- const ignoreJSONStructure = options.ignoreJSONStructure !== void 0 ? options.ignoreJSONStructure : this.options.ignoreJSONStructure;
340
- let path;
341
- if (lng.indexOf(".") > -1) {
342
- path = lng.split(".");
343
- } else {
344
- path = [lng, ns];
345
- if (key) {
346
- if (Array.isArray(key)) {
347
- path.push(...key);
348
- } else if (isString(key) && keySeparator) {
349
- path.push(...key.split(keySeparator));
350
- } else {
351
- path.push(key);
352
- }
353
- }
354
- }
355
- const result = getPath(this.data, path);
356
- if (!result && !ns && !key && lng.indexOf(".") > -1) {
357
- lng = path[0];
358
- ns = path[1];
359
- key = path.slice(2).join(".");
360
- }
361
- if (result || !ignoreJSONStructure || !isString(key)) return result;
362
- return deepFind(this.data?.[lng]?.[ns], key, keySeparator);
363
- }
364
- addResource(lng, ns, key, value) {
365
- let options = arguments.length > 4 && arguments[4] !== void 0 ? arguments[4] : {
366
- silent: false
367
- };
368
- const keySeparator = options.keySeparator !== void 0 ? options.keySeparator : this.options.keySeparator;
369
- let path = [lng, ns];
370
- if (key) path = path.concat(keySeparator ? key.split(keySeparator) : key);
371
- if (lng.indexOf(".") > -1) {
372
- path = lng.split(".");
373
- value = ns;
374
- ns = path[1];
375
- }
376
- this.addNamespaces(ns);
377
- setPath(this.data, path, value);
378
- if (!options.silent) this.emit("added", lng, ns, key, value);
379
- }
380
- addResources(lng, ns, resources) {
381
- let options = arguments.length > 3 && arguments[3] !== void 0 ? arguments[3] : {
382
- silent: false
383
- };
384
- for (const m in resources) {
385
- if (isString(resources[m]) || Array.isArray(resources[m])) this.addResource(lng, ns, m, resources[m], {
386
- silent: true
387
- });
388
- }
389
- if (!options.silent) this.emit("added", lng, ns, resources);
390
- }
391
- addResourceBundle(lng, ns, resources, deep, overwrite) {
392
- let options = arguments.length > 5 && arguments[5] !== void 0 ? arguments[5] : {
393
- silent: false,
394
- skipCopy: false
395
- };
396
- let path = [lng, ns];
397
- if (lng.indexOf(".") > -1) {
398
- path = lng.split(".");
399
- deep = resources;
400
- resources = ns;
401
- ns = path[1];
402
- }
403
- this.addNamespaces(ns);
404
- let pack = getPath(this.data, path) || {};
405
- if (!options.skipCopy) resources = JSON.parse(JSON.stringify(resources));
406
- if (deep) {
407
- deepExtend(pack, resources, overwrite);
408
- } else {
409
- pack = {
410
- ...pack,
411
- ...resources
412
- };
413
- }
414
- setPath(this.data, path, pack);
415
- if (!options.silent) this.emit("added", lng, ns, resources);
416
- }
417
- removeResourceBundle(lng, ns) {
418
- if (this.hasResourceBundle(lng, ns)) {
419
- delete this.data[lng][ns];
420
- }
421
- this.removeNamespaces(ns);
422
- this.emit("removed", lng, ns);
423
- }
424
- hasResourceBundle(lng, ns) {
425
- return this.getResource(lng, ns) !== void 0;
426
- }
427
- getResourceBundle(lng, ns) {
428
- if (!ns) ns = this.options.defaultNS;
429
- return this.getResource(lng, ns);
430
- }
431
- getDataByLanguage(lng) {
432
- return this.data[lng];
433
- }
434
- hasLanguageSomeTranslations(lng) {
435
- const data = this.getDataByLanguage(lng);
436
- const n = data && Object.keys(data) || [];
437
- return !!n.find((v) => data[v] && Object.keys(data[v]).length > 0);
438
- }
439
- toJSON() {
440
- return this.data;
441
- }
442
- };
443
- var postProcessor = {
444
- processors: {},
445
- addPostProcessor(module) {
446
- this.processors[module.name] = module;
447
- },
448
- handle(processors, value, key, options, translator) {
449
- processors.forEach((processor) => {
450
- value = this.processors[processor]?.process(value, key, options, translator) ?? value;
451
- });
452
- return value;
453
- }
454
- };
455
- var checkedLoadedFor = {};
456
- var Translator = class _Translator extends EventEmitter {
457
- constructor(services) {
458
- let options = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
459
- super();
460
- copy(["resourceStore", "languageUtils", "pluralResolver", "interpolator", "backendConnector", "i18nFormat", "utils"], services, this);
461
- this.options = options;
462
- if (this.options.keySeparator === void 0) {
463
- this.options.keySeparator = ".";
464
- }
465
- this.logger = baseLogger.create("translator");
466
- }
467
- changeLanguage(lng) {
468
- if (lng) this.language = lng;
469
- }
470
- exists(key) {
471
- let options = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {
472
- interpolation: {}
473
- };
474
- if (key === void 0 || key === null) {
475
- return false;
476
- }
477
- const resolved = this.resolve(key, options);
478
- return resolved?.res !== void 0;
479
- }
480
- extractFromKey(key, options) {
481
- let nsSeparator = options.nsSeparator !== void 0 ? options.nsSeparator : this.options.nsSeparator;
482
- if (nsSeparator === void 0) nsSeparator = ":";
483
- const keySeparator = options.keySeparator !== void 0 ? options.keySeparator : this.options.keySeparator;
484
- let namespaces = options.ns || this.options.defaultNS || [];
485
- const wouldCheckForNsInKey = nsSeparator && key.indexOf(nsSeparator) > -1;
486
- const seemsNaturalLanguage = !this.options.userDefinedKeySeparator && !options.keySeparator && !this.options.userDefinedNsSeparator && !options.nsSeparator && !looksLikeObjectPath(key, nsSeparator, keySeparator);
487
- if (wouldCheckForNsInKey && !seemsNaturalLanguage) {
488
- const m = key.match(this.interpolator.nestingRegexp);
489
- if (m && m.length > 0) {
490
- return {
491
- key,
492
- namespaces: isString(namespaces) ? [namespaces] : namespaces
493
- };
494
- }
495
- const parts = key.split(nsSeparator);
496
- if (nsSeparator !== keySeparator || nsSeparator === keySeparator && this.options.ns.indexOf(parts[0]) > -1) namespaces = parts.shift();
497
- key = parts.join(keySeparator);
498
- }
499
- return {
500
- key,
501
- namespaces: isString(namespaces) ? [namespaces] : namespaces
502
- };
503
- }
504
- translate(keys, options, lastKey) {
505
- if (typeof options !== "object" && this.options.overloadTranslationOptionHandler) {
506
- options = this.options.overloadTranslationOptionHandler(arguments);
507
- }
508
- if (typeof options === "object") options = {
509
- ...options
510
- };
511
- if (!options) options = {};
512
- if (keys === void 0 || keys === null) return "";
513
- if (!Array.isArray(keys)) keys = [String(keys)];
514
- const returnDetails = options.returnDetails !== void 0 ? options.returnDetails : this.options.returnDetails;
515
- const keySeparator = options.keySeparator !== void 0 ? options.keySeparator : this.options.keySeparator;
516
- const {
517
- key,
518
- namespaces
519
- } = this.extractFromKey(keys[keys.length - 1], options);
520
- const namespace = namespaces[namespaces.length - 1];
521
- const lng = options.lng || this.language;
522
- const appendNamespaceToCIMode = options.appendNamespaceToCIMode || this.options.appendNamespaceToCIMode;
523
- if (lng?.toLowerCase() === "cimode") {
524
- if (appendNamespaceToCIMode) {
525
- const nsSeparator = options.nsSeparator || this.options.nsSeparator;
526
- if (returnDetails) {
527
- return {
528
- res: `${namespace}${nsSeparator}${key}`,
529
- usedKey: key,
530
- exactUsedKey: key,
531
- usedLng: lng,
532
- usedNS: namespace,
533
- usedParams: this.getUsedParamsDetails(options)
534
- };
535
- }
536
- return `${namespace}${nsSeparator}${key}`;
537
- }
538
- if (returnDetails) {
539
- return {
540
- res: key,
541
- usedKey: key,
542
- exactUsedKey: key,
543
- usedLng: lng,
544
- usedNS: namespace,
545
- usedParams: this.getUsedParamsDetails(options)
546
- };
547
- }
548
- return key;
549
- }
550
- const resolved = this.resolve(keys, options);
551
- let res = resolved?.res;
552
- const resUsedKey = resolved?.usedKey || key;
553
- const resExactUsedKey = resolved?.exactUsedKey || key;
554
- const resType = Object.prototype.toString.apply(res);
555
- const noObject = ["[object Number]", "[object Function]", "[object RegExp]"];
556
- const joinArrays = options.joinArrays !== void 0 ? options.joinArrays : this.options.joinArrays;
557
- const handleAsObjectInI18nFormat = !this.i18nFormat || this.i18nFormat.handleAsObject;
558
- const handleAsObject = !isString(res) && typeof res !== "boolean" && typeof res !== "number";
559
- if (handleAsObjectInI18nFormat && res && handleAsObject && noObject.indexOf(resType) < 0 && !(isString(joinArrays) && Array.isArray(res))) {
560
- if (!options.returnObjects && !this.options.returnObjects) {
561
- if (!this.options.returnedObjectHandler) {
562
- this.logger.warn("accessing an object - but returnObjects options is not enabled!");
563
- }
564
- const r = this.options.returnedObjectHandler ? this.options.returnedObjectHandler(resUsedKey, res, {
565
- ...options,
566
- ns: namespaces
567
- }) : `key '${key} (${this.language})' returned an object instead of string.`;
568
- if (returnDetails) {
569
- resolved.res = r;
570
- resolved.usedParams = this.getUsedParamsDetails(options);
571
- return resolved;
572
- }
573
- return r;
574
- }
575
- if (keySeparator) {
576
- const resTypeIsArray = Array.isArray(res);
577
- const copy2 = resTypeIsArray ? [] : {};
578
- const newKeyToUse = resTypeIsArray ? resExactUsedKey : resUsedKey;
579
- for (const m in res) {
580
- if (Object.prototype.hasOwnProperty.call(res, m)) {
581
- const deepKey = `${newKeyToUse}${keySeparator}${m}`;
582
- copy2[m] = this.translate(deepKey, {
583
- ...options,
584
- ...{
585
- joinArrays: false,
586
- ns: namespaces
587
- }
588
- });
589
- if (copy2[m] === deepKey) copy2[m] = res[m];
590
- }
591
- }
592
- res = copy2;
593
- }
594
- } else if (handleAsObjectInI18nFormat && isString(joinArrays) && Array.isArray(res)) {
595
- res = res.join(joinArrays);
596
- if (res) res = this.extendTranslation(res, keys, options, lastKey);
597
- } else {
598
- let usedDefault = false;
599
- let usedKey = false;
600
- const needsPluralHandling = options.count !== void 0 && !isString(options.count);
601
- const hasDefaultValue = _Translator.hasDefaultValue(options);
602
- const defaultValueSuffix = needsPluralHandling ? this.pluralResolver.getSuffix(lng, options.count, options) : "";
603
- const defaultValueSuffixOrdinalFallback = options.ordinal && needsPluralHandling ? this.pluralResolver.getSuffix(lng, options.count, {
604
- ordinal: false
605
- }) : "";
606
- const needsZeroSuffixLookup = needsPluralHandling && !options.ordinal && options.count === 0;
607
- const defaultValue = needsZeroSuffixLookup && options[`defaultValue${this.options.pluralSeparator}zero`] || options[`defaultValue${defaultValueSuffix}`] || options[`defaultValue${defaultValueSuffixOrdinalFallback}`] || options.defaultValue;
608
- if (!this.isValidLookup(res) && hasDefaultValue) {
609
- usedDefault = true;
610
- res = defaultValue;
611
- }
612
- if (!this.isValidLookup(res)) {
613
- usedKey = true;
614
- res = key;
615
- }
616
- const missingKeyNoValueFallbackToKey = options.missingKeyNoValueFallbackToKey || this.options.missingKeyNoValueFallbackToKey;
617
- const resForMissing = missingKeyNoValueFallbackToKey && usedKey ? void 0 : res;
618
- const updateMissing = hasDefaultValue && defaultValue !== res && this.options.updateMissing;
619
- if (usedKey || usedDefault || updateMissing) {
620
- this.logger.log(updateMissing ? "updateKey" : "missingKey", lng, namespace, key, updateMissing ? defaultValue : res);
621
- if (keySeparator) {
622
- const fk = this.resolve(key, {
623
- ...options,
624
- keySeparator: false
625
- });
626
- if (fk && fk.res) this.logger.warn("Seems the loaded translations were in flat JSON format instead of nested. Either set keySeparator: false on init or make sure your translations are published in nested format.");
627
- }
628
- let lngs = [];
629
- const fallbackLngs = this.languageUtils.getFallbackCodes(this.options.fallbackLng, options.lng || this.language);
630
- if (this.options.saveMissingTo === "fallback" && fallbackLngs && fallbackLngs[0]) {
631
- for (let i = 0; i < fallbackLngs.length; i++) {
632
- lngs.push(fallbackLngs[i]);
633
- }
634
- } else if (this.options.saveMissingTo === "all") {
635
- lngs = this.languageUtils.toResolveHierarchy(options.lng || this.language);
636
- } else {
637
- lngs.push(options.lng || this.language);
638
- }
639
- const send = (l, k, specificDefaultValue) => {
640
- const defaultForMissing = hasDefaultValue && specificDefaultValue !== res ? specificDefaultValue : resForMissing;
641
- if (this.options.missingKeyHandler) {
642
- this.options.missingKeyHandler(l, namespace, k, defaultForMissing, updateMissing, options);
643
- } else if (this.backendConnector?.saveMissing) {
644
- this.backendConnector.saveMissing(l, namespace, k, defaultForMissing, updateMissing, options);
645
- }
646
- this.emit("missingKey", l, namespace, k, res);
647
- };
648
- if (this.options.saveMissing) {
649
- if (this.options.saveMissingPlurals && needsPluralHandling) {
650
- lngs.forEach((language) => {
651
- const suffixes = this.pluralResolver.getSuffixes(language, options);
652
- if (needsZeroSuffixLookup && options[`defaultValue${this.options.pluralSeparator}zero`] && suffixes.indexOf(`${this.options.pluralSeparator}zero`) < 0) {
653
- suffixes.push(`${this.options.pluralSeparator}zero`);
654
- }
655
- suffixes.forEach((suffix) => {
656
- send([language], key + suffix, options[`defaultValue${suffix}`] || defaultValue);
657
- });
658
- });
659
- } else {
660
- send(lngs, key, defaultValue);
661
- }
662
- }
663
- }
664
- res = this.extendTranslation(res, keys, options, resolved, lastKey);
665
- if (usedKey && res === key && this.options.appendNamespaceToMissingKey) res = `${namespace}:${key}`;
666
- if ((usedKey || usedDefault) && this.options.parseMissingKeyHandler) {
667
- res = this.options.parseMissingKeyHandler(this.options.appendNamespaceToMissingKey ? `${namespace}:${key}` : key, usedDefault ? res : void 0);
668
- }
669
- }
670
- if (returnDetails) {
671
- resolved.res = res;
672
- resolved.usedParams = this.getUsedParamsDetails(options);
673
- return resolved;
674
- }
675
- return res;
676
- }
677
- extendTranslation(res, key, options, resolved, lastKey) {
678
- var _this = this;
679
- if (this.i18nFormat?.parse) {
680
- res = this.i18nFormat.parse(res, {
681
- ...this.options.interpolation.defaultVariables,
682
- ...options
683
- }, options.lng || this.language || resolved.usedLng, resolved.usedNS, resolved.usedKey, {
684
- resolved
685
- });
686
- } else if (!options.skipInterpolation) {
687
- if (options.interpolation) this.interpolator.init({
688
- ...options,
689
- ...{
690
- interpolation: {
691
- ...this.options.interpolation,
692
- ...options.interpolation
693
- }
694
- }
695
- });
696
- const skipOnVariables = isString(res) && (options?.interpolation?.skipOnVariables !== void 0 ? options.interpolation.skipOnVariables : this.options.interpolation.skipOnVariables);
697
- let nestBef;
698
- if (skipOnVariables) {
699
- const nb = res.match(this.interpolator.nestingRegexp);
700
- nestBef = nb && nb.length;
701
- }
702
- let data = options.replace && !isString(options.replace) ? options.replace : options;
703
- if (this.options.interpolation.defaultVariables) data = {
704
- ...this.options.interpolation.defaultVariables,
705
- ...data
706
- };
707
- res = this.interpolator.interpolate(res, data, options.lng || this.language || resolved.usedLng, options);
708
- if (skipOnVariables) {
709
- const na = res.match(this.interpolator.nestingRegexp);
710
- const nestAft = na && na.length;
711
- if (nestBef < nestAft) options.nest = false;
712
- }
713
- if (!options.lng && resolved && resolved.res) options.lng = this.language || resolved.usedLng;
714
- if (options.nest !== false) res = this.interpolator.nest(res, function() {
715
- for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
716
- args[_key] = arguments[_key];
717
- }
718
- if (lastKey?.[0] === args[0] && !options.context) {
719
- _this.logger.warn(`It seems you are nesting recursively key: ${args[0]} in key: ${key[0]}`);
720
- return null;
721
- }
722
- return _this.translate(...args, key);
723
- }, options);
724
- if (options.interpolation) this.interpolator.reset();
725
- }
726
- const postProcess = options.postProcess || this.options.postProcess;
727
- const postProcessorNames = isString(postProcess) ? [postProcess] : postProcess;
728
- if (res !== void 0 && res !== null && postProcessorNames?.length && options.applyPostProcessor !== false) {
729
- res = postProcessor.handle(postProcessorNames, res, key, this.options && this.options.postProcessPassResolved ? {
730
- i18nResolved: {
731
- ...resolved,
732
- usedParams: this.getUsedParamsDetails(options)
733
- },
734
- ...options
735
- } : options, this);
736
- }
737
- return res;
738
- }
739
- resolve(keys) {
740
- let options = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
741
- let found;
742
- let usedKey;
743
- let exactUsedKey;
744
- let usedLng;
745
- let usedNS;
746
- if (isString(keys)) keys = [keys];
747
- keys.forEach((k) => {
748
- if (this.isValidLookup(found)) return;
749
- const extracted = this.extractFromKey(k, options);
750
- const key = extracted.key;
751
- usedKey = key;
752
- let namespaces = extracted.namespaces;
753
- if (this.options.fallbackNS) namespaces = namespaces.concat(this.options.fallbackNS);
754
- const needsPluralHandling = options.count !== void 0 && !isString(options.count);
755
- const needsZeroSuffixLookup = needsPluralHandling && !options.ordinal && options.count === 0;
756
- const needsContextHandling = options.context !== void 0 && (isString(options.context) || typeof options.context === "number") && options.context !== "";
757
- const codes = options.lngs ? options.lngs : this.languageUtils.toResolveHierarchy(options.lng || this.language, options.fallbackLng);
758
- namespaces.forEach((ns) => {
759
- if (this.isValidLookup(found)) return;
760
- usedNS = ns;
761
- if (!checkedLoadedFor[`${codes[0]}-${ns}`] && this.utils?.hasLoadedNamespace && !this.utils?.hasLoadedNamespace(usedNS)) {
762
- checkedLoadedFor[`${codes[0]}-${ns}`] = true;
763
- this.logger.warn(`key "${usedKey}" for languages "${codes.join(", ")}" won't get resolved as namespace "${usedNS}" was not yet loaded`, "This means something IS WRONG in your setup. You access the t function before i18next.init / i18next.loadNamespace / i18next.changeLanguage was done. Wait for the callback or Promise to resolve before accessing it!!!");
764
- }
765
- codes.forEach((code) => {
766
- if (this.isValidLookup(found)) return;
767
- usedLng = code;
768
- const finalKeys = [key];
769
- if (this.i18nFormat?.addLookupKeys) {
770
- this.i18nFormat.addLookupKeys(finalKeys, key, code, ns, options);
771
- } else {
772
- let pluralSuffix;
773
- if (needsPluralHandling) pluralSuffix = this.pluralResolver.getSuffix(code, options.count, options);
774
- const zeroSuffix = `${this.options.pluralSeparator}zero`;
775
- const ordinalPrefix = `${this.options.pluralSeparator}ordinal${this.options.pluralSeparator}`;
776
- if (needsPluralHandling) {
777
- finalKeys.push(key + pluralSuffix);
778
- if (options.ordinal && pluralSuffix.indexOf(ordinalPrefix) === 0) {
779
- finalKeys.push(key + pluralSuffix.replace(ordinalPrefix, this.options.pluralSeparator));
780
- }
781
- if (needsZeroSuffixLookup) {
782
- finalKeys.push(key + zeroSuffix);
783
- }
784
- }
785
- if (needsContextHandling) {
786
- const contextKey = `${key}${this.options.contextSeparator}${options.context}`;
787
- finalKeys.push(contextKey);
788
- if (needsPluralHandling) {
789
- finalKeys.push(contextKey + pluralSuffix);
790
- if (options.ordinal && pluralSuffix.indexOf(ordinalPrefix) === 0) {
791
- finalKeys.push(contextKey + pluralSuffix.replace(ordinalPrefix, this.options.pluralSeparator));
792
- }
793
- if (needsZeroSuffixLookup) {
794
- finalKeys.push(contextKey + zeroSuffix);
795
- }
796
- }
797
- }
798
- }
799
- let possibleKey;
800
- while (possibleKey = finalKeys.pop()) {
801
- if (!this.isValidLookup(found)) {
802
- exactUsedKey = possibleKey;
803
- found = this.getResource(code, ns, possibleKey, options);
804
- }
805
- }
806
- });
807
- });
808
- });
809
- return {
810
- res: found,
811
- usedKey,
812
- exactUsedKey,
813
- usedLng,
814
- usedNS
815
- };
816
- }
817
- isValidLookup(res) {
818
- return res !== void 0 && !(!this.options.returnNull && res === null) && !(!this.options.returnEmptyString && res === "");
819
- }
820
- getResource(code, ns, key) {
821
- let options = arguments.length > 3 && arguments[3] !== void 0 ? arguments[3] : {};
822
- if (this.i18nFormat?.getResource) return this.i18nFormat.getResource(code, ns, key, options);
823
- return this.resourceStore.getResource(code, ns, key, options);
824
- }
825
- getUsedParamsDetails() {
826
- let options = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {};
827
- const optionsKeys = ["defaultValue", "ordinal", "context", "replace", "lng", "lngs", "fallbackLng", "ns", "keySeparator", "nsSeparator", "returnObjects", "returnDetails", "joinArrays", "postProcess", "interpolation"];
828
- const useOptionsReplaceForData = options.replace && !isString(options.replace);
829
- let data = useOptionsReplaceForData ? options.replace : options;
830
- if (useOptionsReplaceForData && typeof options.count !== "undefined") {
831
- data.count = options.count;
832
- }
833
- if (this.options.interpolation.defaultVariables) {
834
- data = {
835
- ...this.options.interpolation.defaultVariables,
836
- ...data
837
- };
838
- }
839
- if (!useOptionsReplaceForData) {
840
- data = {
841
- ...data
842
- };
843
- for (const key of optionsKeys) {
844
- delete data[key];
845
- }
846
- }
847
- return data;
848
- }
849
- static hasDefaultValue(options) {
850
- const prefix = "defaultValue";
851
- for (const option in options) {
852
- if (Object.prototype.hasOwnProperty.call(options, option) && prefix === option.substring(0, prefix.length) && void 0 !== options[option]) {
853
- return true;
854
- }
855
- }
856
- return false;
857
- }
858
- };
859
- var LanguageUtil = class {
860
- constructor(options) {
861
- this.options = options;
862
- this.supportedLngs = this.options.supportedLngs || false;
863
- this.logger = baseLogger.create("languageUtils");
864
- }
865
- getScriptPartFromCode(code) {
866
- code = getCleanedCode(code);
867
- if (!code || code.indexOf("-") < 0) return null;
868
- const p = code.split("-");
869
- if (p.length === 2) return null;
870
- p.pop();
871
- if (p[p.length - 1].toLowerCase() === "x") return null;
872
- return this.formatLanguageCode(p.join("-"));
873
- }
874
- getLanguagePartFromCode(code) {
875
- code = getCleanedCode(code);
876
- if (!code || code.indexOf("-") < 0) return code;
877
- const p = code.split("-");
878
- return this.formatLanguageCode(p[0]);
879
- }
880
- formatLanguageCode(code) {
881
- if (isString(code) && code.indexOf("-") > -1) {
882
- let formattedCode;
883
- try {
884
- formattedCode = Intl.getCanonicalLocales(code)[0];
885
- } catch (e) {
886
- }
887
- if (formattedCode && this.options.lowerCaseLng) {
888
- formattedCode = formattedCode.toLowerCase();
889
- }
890
- if (formattedCode) return formattedCode;
891
- if (this.options.lowerCaseLng) {
892
- return code.toLowerCase();
893
- }
894
- return code;
895
- }
896
- return this.options.cleanCode || this.options.lowerCaseLng ? code.toLowerCase() : code;
897
- }
898
- isSupportedCode(code) {
899
- if (this.options.load === "languageOnly" || this.options.nonExplicitSupportedLngs) {
900
- code = this.getLanguagePartFromCode(code);
901
- }
902
- return !this.supportedLngs || !this.supportedLngs.length || this.supportedLngs.indexOf(code) > -1;
903
- }
904
- getBestMatchFromCodes(codes) {
905
- if (!codes) return null;
906
- let found;
907
- codes.forEach((code) => {
908
- if (found) return;
909
- const cleanedLng = this.formatLanguageCode(code);
910
- if (!this.options.supportedLngs || this.isSupportedCode(cleanedLng)) found = cleanedLng;
911
- });
912
- if (!found && this.options.supportedLngs) {
913
- codes.forEach((code) => {
914
- if (found) return;
915
- const lngOnly = this.getLanguagePartFromCode(code);
916
- if (this.isSupportedCode(lngOnly)) return found = lngOnly;
917
- found = this.options.supportedLngs.find((supportedLng) => {
918
- if (supportedLng === lngOnly) return supportedLng;
919
- if (supportedLng.indexOf("-") < 0 && lngOnly.indexOf("-") < 0) return;
920
- if (supportedLng.indexOf("-") > 0 && lngOnly.indexOf("-") < 0 && supportedLng.substring(0, supportedLng.indexOf("-")) === lngOnly) return supportedLng;
921
- if (supportedLng.indexOf(lngOnly) === 0 && lngOnly.length > 1) return supportedLng;
922
- });
923
- });
924
- }
925
- if (!found) found = this.getFallbackCodes(this.options.fallbackLng)[0];
926
- return found;
927
- }
928
- getFallbackCodes(fallbacks, code) {
929
- if (!fallbacks) return [];
930
- if (typeof fallbacks === "function") fallbacks = fallbacks(code);
931
- if (isString(fallbacks)) fallbacks = [fallbacks];
932
- if (Array.isArray(fallbacks)) return fallbacks;
933
- if (!code) return fallbacks.default || [];
934
- let found = fallbacks[code];
935
- if (!found) found = fallbacks[this.getScriptPartFromCode(code)];
936
- if (!found) found = fallbacks[this.formatLanguageCode(code)];
937
- if (!found) found = fallbacks[this.getLanguagePartFromCode(code)];
938
- if (!found) found = fallbacks.default;
939
- return found || [];
940
- }
941
- toResolveHierarchy(code, fallbackCode) {
942
- const fallbackCodes = this.getFallbackCodes(fallbackCode || this.options.fallbackLng || [], code);
943
- const codes = [];
944
- const addCode = (c) => {
945
- if (!c) return;
946
- if (this.isSupportedCode(c)) {
947
- codes.push(c);
948
- } else {
949
- this.logger.warn(`rejecting language code not found in supportedLngs: ${c}`);
950
- }
951
- };
952
- if (isString(code) && (code.indexOf("-") > -1 || code.indexOf("_") > -1)) {
953
- if (this.options.load !== "languageOnly") addCode(this.formatLanguageCode(code));
954
- if (this.options.load !== "languageOnly" && this.options.load !== "currentOnly") addCode(this.getScriptPartFromCode(code));
955
- if (this.options.load !== "currentOnly") addCode(this.getLanguagePartFromCode(code));
956
- } else if (isString(code)) {
957
- addCode(this.formatLanguageCode(code));
958
- }
959
- fallbackCodes.forEach((fc) => {
960
- if (codes.indexOf(fc) < 0) addCode(this.formatLanguageCode(fc));
961
- });
962
- return codes;
963
- }
964
- };
965
- var suffixesOrder = {
966
- zero: 0,
967
- one: 1,
968
- two: 2,
969
- few: 3,
970
- many: 4,
971
- other: 5
972
- };
973
- var dummyRule = {
974
- select: (count) => count === 1 ? "one" : "other",
975
- resolvedOptions: () => ({
976
- pluralCategories: ["one", "other"]
977
- })
978
- };
979
- var PluralResolver = class {
980
- constructor(languageUtils) {
981
- let options = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
982
- this.languageUtils = languageUtils;
983
- this.options = options;
984
- this.logger = baseLogger.create("pluralResolver");
985
- this.pluralRulesCache = {};
986
- }
987
- addRule(lng, obj) {
988
- this.rules[lng] = obj;
989
- }
990
- clearCache() {
991
- this.pluralRulesCache = {};
992
- }
993
- getRule(code) {
994
- let options = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
995
- const cleanedCode = getCleanedCode(code === "dev" ? "en" : code);
996
- const type = options.ordinal ? "ordinal" : "cardinal";
997
- const cacheKey = JSON.stringify({
998
- cleanedCode,
999
- type
1000
- });
1001
- if (cacheKey in this.pluralRulesCache) {
1002
- return this.pluralRulesCache[cacheKey];
1003
- }
1004
- let rule;
1005
- try {
1006
- rule = new Intl.PluralRules(cleanedCode, {
1007
- type
1008
- });
1009
- } catch (err) {
1010
- if (!Intl) {
1011
- this.logger.error("No Intl support, please use an Intl polyfill!");
1012
- return dummyRule;
1013
- }
1014
- if (!code.match(/-|_/)) return dummyRule;
1015
- const lngPart = this.languageUtils.getLanguagePartFromCode(code);
1016
- rule = this.getRule(lngPart, options);
1017
- }
1018
- this.pluralRulesCache[cacheKey] = rule;
1019
- return rule;
1020
- }
1021
- needsPlural(code) {
1022
- let options = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
1023
- let rule = this.getRule(code, options);
1024
- if (!rule) rule = this.getRule("dev", options);
1025
- return rule?.resolvedOptions().pluralCategories.length > 1;
1026
- }
1027
- getPluralFormsOfKey(code, key) {
1028
- let options = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : {};
1029
- return this.getSuffixes(code, options).map((suffix) => `${key}${suffix}`);
1030
- }
1031
- getSuffixes(code) {
1032
- let options = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
1033
- let rule = this.getRule(code, options);
1034
- if (!rule) rule = this.getRule("dev", options);
1035
- if (!rule) return [];
1036
- return rule.resolvedOptions().pluralCategories.sort((pluralCategory1, pluralCategory2) => suffixesOrder[pluralCategory1] - suffixesOrder[pluralCategory2]).map((pluralCategory) => `${this.options.prepend}${options.ordinal ? `ordinal${this.options.prepend}` : ""}${pluralCategory}`);
1037
- }
1038
- getSuffix(code, count) {
1039
- let options = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : {};
1040
- const rule = this.getRule(code, options);
1041
- if (rule) {
1042
- return `${this.options.prepend}${options.ordinal ? `ordinal${this.options.prepend}` : ""}${rule.select(count)}`;
1043
- }
1044
- this.logger.warn(`no plural rule found for: ${code}`);
1045
- return this.getSuffix("dev", count, options);
1046
- }
1047
- };
1048
- var deepFindWithDefaults = function(data, defaultData, key) {
1049
- let keySeparator = arguments.length > 3 && arguments[3] !== void 0 ? arguments[3] : ".";
1050
- let ignoreJSONStructure = arguments.length > 4 && arguments[4] !== void 0 ? arguments[4] : true;
1051
- let path = getPathWithDefaults(data, defaultData, key);
1052
- if (!path && ignoreJSONStructure && isString(key)) {
1053
- path = deepFind(data, key, keySeparator);
1054
- if (path === void 0) path = deepFind(defaultData, key, keySeparator);
1055
- }
1056
- return path;
1057
- };
1058
- var regexSafe = (val) => val.replace(/\$/g, "$$$$");
1059
- var Interpolator = class {
1060
- constructor() {
1061
- let options = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {};
1062
- this.logger = baseLogger.create("interpolator");
1063
- this.options = options;
1064
- this.format = options?.interpolation?.format || ((value) => value);
1065
- this.init(options);
1066
- }
1067
- init() {
1068
- let options = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {};
1069
- if (!options.interpolation) options.interpolation = {
1070
- escapeValue: true
1071
- };
1072
- const {
1073
- escape: escape$1,
1074
- escapeValue,
1075
- useRawValueToEscape,
1076
- prefix,
1077
- prefixEscaped,
1078
- suffix,
1079
- suffixEscaped,
1080
- formatSeparator,
1081
- unescapeSuffix,
1082
- unescapePrefix,
1083
- nestingPrefix,
1084
- nestingPrefixEscaped,
1085
- nestingSuffix,
1086
- nestingSuffixEscaped,
1087
- nestingOptionsSeparator,
1088
- maxReplaces,
1089
- alwaysFormat
1090
- } = options.interpolation;
1091
- this.escape = escape$1 !== void 0 ? escape$1 : escape;
1092
- this.escapeValue = escapeValue !== void 0 ? escapeValue : true;
1093
- this.useRawValueToEscape = useRawValueToEscape !== void 0 ? useRawValueToEscape : false;
1094
- this.prefix = prefix ? regexEscape(prefix) : prefixEscaped || "{{";
1095
- this.suffix = suffix ? regexEscape(suffix) : suffixEscaped || "}}";
1096
- this.formatSeparator = formatSeparator || ",";
1097
- this.unescapePrefix = unescapeSuffix ? "" : unescapePrefix || "-";
1098
- this.unescapeSuffix = this.unescapePrefix ? "" : unescapeSuffix || "";
1099
- this.nestingPrefix = nestingPrefix ? regexEscape(nestingPrefix) : nestingPrefixEscaped || regexEscape("$t(");
1100
- this.nestingSuffix = nestingSuffix ? regexEscape(nestingSuffix) : nestingSuffixEscaped || regexEscape(")");
1101
- this.nestingOptionsSeparator = nestingOptionsSeparator || ",";
1102
- this.maxReplaces = maxReplaces || 1e3;
1103
- this.alwaysFormat = alwaysFormat !== void 0 ? alwaysFormat : false;
1104
- this.resetRegExp();
1105
- }
1106
- reset() {
1107
- if (this.options) this.init(this.options);
1108
- }
1109
- resetRegExp() {
1110
- const getOrResetRegExp = (existingRegExp, pattern) => {
1111
- if (existingRegExp?.source === pattern) {
1112
- existingRegExp.lastIndex = 0;
1113
- return existingRegExp;
1114
- }
1115
- return new RegExp(pattern, "g");
1116
- };
1117
- this.regexp = getOrResetRegExp(this.regexp, `${this.prefix}(.+?)${this.suffix}`);
1118
- this.regexpUnescape = getOrResetRegExp(this.regexpUnescape, `${this.prefix}${this.unescapePrefix}(.+?)${this.unescapeSuffix}${this.suffix}`);
1119
- this.nestingRegexp = getOrResetRegExp(this.nestingRegexp, `${this.nestingPrefix}(.+?)${this.nestingSuffix}`);
1120
- }
1121
- interpolate(str, data, lng, options) {
1122
- let match;
1123
- let value;
1124
- let replaces;
1125
- const defaultData = this.options && this.options.interpolation && this.options.interpolation.defaultVariables || {};
1126
- const handleFormat = (key) => {
1127
- if (key.indexOf(this.formatSeparator) < 0) {
1128
- const path = deepFindWithDefaults(data, defaultData, key, this.options.keySeparator, this.options.ignoreJSONStructure);
1129
- return this.alwaysFormat ? this.format(path, void 0, lng, {
1130
- ...options,
1131
- ...data,
1132
- interpolationkey: key
1133
- }) : path;
1134
- }
1135
- const p = key.split(this.formatSeparator);
1136
- const k = p.shift().trim();
1137
- const f = p.join(this.formatSeparator).trim();
1138
- return this.format(deepFindWithDefaults(data, defaultData, k, this.options.keySeparator, this.options.ignoreJSONStructure), f, lng, {
1139
- ...options,
1140
- ...data,
1141
- interpolationkey: k
1142
- });
1143
- };
1144
- this.resetRegExp();
1145
- const missingInterpolationHandler = options?.missingInterpolationHandler || this.options.missingInterpolationHandler;
1146
- const skipOnVariables = options?.interpolation?.skipOnVariables !== void 0 ? options.interpolation.skipOnVariables : this.options.interpolation.skipOnVariables;
1147
- const todos = [{
1148
- regex: this.regexpUnescape,
1149
- safeValue: (val) => regexSafe(val)
1150
- }, {
1151
- regex: this.regexp,
1152
- safeValue: (val) => this.escapeValue ? regexSafe(this.escape(val)) : regexSafe(val)
1153
- }];
1154
- todos.forEach((todo) => {
1155
- replaces = 0;
1156
- while (match = todo.regex.exec(str)) {
1157
- const matchedVar = match[1].trim();
1158
- value = handleFormat(matchedVar);
1159
- if (value === void 0) {
1160
- if (typeof missingInterpolationHandler === "function") {
1161
- const temp = missingInterpolationHandler(str, match, options);
1162
- value = isString(temp) ? temp : "";
1163
- } else if (options && Object.prototype.hasOwnProperty.call(options, matchedVar)) {
1164
- value = "";
1165
- } else if (skipOnVariables) {
1166
- value = match[0];
1167
- continue;
1168
- } else {
1169
- this.logger.warn(`missed to pass in variable ${matchedVar} for interpolating ${str}`);
1170
- value = "";
1171
- }
1172
- } else if (!isString(value) && !this.useRawValueToEscape) {
1173
- value = makeString(value);
1174
- }
1175
- const safeValue = todo.safeValue(value);
1176
- str = str.replace(match[0], safeValue);
1177
- if (skipOnVariables) {
1178
- todo.regex.lastIndex += value.length;
1179
- todo.regex.lastIndex -= match[0].length;
1180
- } else {
1181
- todo.regex.lastIndex = 0;
1182
- }
1183
- replaces++;
1184
- if (replaces >= this.maxReplaces) {
1185
- break;
1186
- }
1187
- }
1188
- });
1189
- return str;
1190
- }
1191
- nest(str, fc) {
1192
- let options = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : {};
1193
- let match;
1194
- let value;
1195
- let clonedOptions;
1196
- const handleHasOptions = (key, inheritedOptions) => {
1197
- const sep = this.nestingOptionsSeparator;
1198
- if (key.indexOf(sep) < 0) return key;
1199
- const c = key.split(new RegExp(`${sep}[ ]*{`));
1200
- let optionsString = `{${c[1]}`;
1201
- key = c[0];
1202
- optionsString = this.interpolate(optionsString, clonedOptions);
1203
- const matchedSingleQuotes = optionsString.match(/'/g);
1204
- const matchedDoubleQuotes = optionsString.match(/"/g);
1205
- if ((matchedSingleQuotes?.length ?? 0) % 2 === 0 && !matchedDoubleQuotes || matchedDoubleQuotes.length % 2 !== 0) {
1206
- optionsString = optionsString.replace(/'/g, '"');
1207
- }
1208
- try {
1209
- clonedOptions = JSON.parse(optionsString);
1210
- if (inheritedOptions) clonedOptions = {
1211
- ...inheritedOptions,
1212
- ...clonedOptions
1213
- };
1214
- } catch (e) {
1215
- this.logger.warn(`failed parsing options string in nesting for key ${key}`, e);
1216
- return `${key}${sep}${optionsString}`;
1217
- }
1218
- if (clonedOptions.defaultValue && clonedOptions.defaultValue.indexOf(this.prefix) > -1) delete clonedOptions.defaultValue;
1219
- return key;
1220
- };
1221
- while (match = this.nestingRegexp.exec(str)) {
1222
- let formatters = [];
1223
- clonedOptions = {
1224
- ...options
1225
- };
1226
- clonedOptions = clonedOptions.replace && !isString(clonedOptions.replace) ? clonedOptions.replace : clonedOptions;
1227
- clonedOptions.applyPostProcessor = false;
1228
- delete clonedOptions.defaultValue;
1229
- let doReduce = false;
1230
- if (match[0].indexOf(this.formatSeparator) !== -1 && !/{.*}/.test(match[1])) {
1231
- const r = match[1].split(this.formatSeparator).map((elem) => elem.trim());
1232
- match[1] = r.shift();
1233
- formatters = r;
1234
- doReduce = true;
1235
- }
1236
- value = fc(handleHasOptions.call(this, match[1].trim(), clonedOptions), clonedOptions);
1237
- if (value && match[0] === str && !isString(value)) return value;
1238
- if (!isString(value)) value = makeString(value);
1239
- if (!value) {
1240
- this.logger.warn(`missed to resolve ${match[1]} for nesting ${str}`);
1241
- value = "";
1242
- }
1243
- if (doReduce) {
1244
- value = formatters.reduce((v, f) => this.format(v, f, options.lng, {
1245
- ...options,
1246
- interpolationkey: match[1].trim()
1247
- }), value.trim());
1248
- }
1249
- str = str.replace(match[0], value);
1250
- this.regexp.lastIndex = 0;
1251
- }
1252
- return str;
1253
- }
1254
- };
1255
- var parseFormatStr = (formatStr) => {
1256
- let formatName = formatStr.toLowerCase().trim();
1257
- const formatOptions = {};
1258
- if (formatStr.indexOf("(") > -1) {
1259
- const p = formatStr.split("(");
1260
- formatName = p[0].toLowerCase().trim();
1261
- const optStr = p[1].substring(0, p[1].length - 1);
1262
- if (formatName === "currency" && optStr.indexOf(":") < 0) {
1263
- if (!formatOptions.currency) formatOptions.currency = optStr.trim();
1264
- } else if (formatName === "relativetime" && optStr.indexOf(":") < 0) {
1265
- if (!formatOptions.range) formatOptions.range = optStr.trim();
1266
- } else {
1267
- const opts = optStr.split(";");
1268
- opts.forEach((opt) => {
1269
- if (opt) {
1270
- const [key, ...rest] = opt.split(":");
1271
- const val = rest.join(":").trim().replace(/^'+|'+$/g, "");
1272
- const trimmedKey = key.trim();
1273
- if (!formatOptions[trimmedKey]) formatOptions[trimmedKey] = val;
1274
- if (val === "false") formatOptions[trimmedKey] = false;
1275
- if (val === "true") formatOptions[trimmedKey] = true;
1276
- if (!isNaN(val)) formatOptions[trimmedKey] = parseInt(val, 10);
1277
- }
1278
- });
1279
- }
1280
- }
1281
- return {
1282
- formatName,
1283
- formatOptions
1284
- };
1285
- };
1286
- var createCachedFormatter = (fn) => {
1287
- const cache = {};
1288
- return (val, lng, options) => {
1289
- let optForCache = options;
1290
- if (options && options.interpolationkey && options.formatParams && options.formatParams[options.interpolationkey] && options[options.interpolationkey]) {
1291
- optForCache = {
1292
- ...optForCache,
1293
- [options.interpolationkey]: void 0
1294
- };
1295
- }
1296
- const key = lng + JSON.stringify(optForCache);
1297
- let formatter = cache[key];
1298
- if (!formatter) {
1299
- formatter = fn(getCleanedCode(lng), options);
1300
- cache[key] = formatter;
1301
- }
1302
- return formatter(val);
1303
- };
1304
- };
1305
- var Formatter = class {
1306
- constructor() {
1307
- let options = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {};
1308
- this.logger = baseLogger.create("formatter");
1309
- this.options = options;
1310
- this.formats = {
1311
- number: createCachedFormatter((lng, opt) => {
1312
- const formatter = new Intl.NumberFormat(lng, {
1313
- ...opt
1314
- });
1315
- return (val) => formatter.format(val);
1316
- }),
1317
- currency: createCachedFormatter((lng, opt) => {
1318
- const formatter = new Intl.NumberFormat(lng, {
1319
- ...opt,
1320
- style: "currency"
1321
- });
1322
- return (val) => formatter.format(val);
1323
- }),
1324
- datetime: createCachedFormatter((lng, opt) => {
1325
- const formatter = new Intl.DateTimeFormat(lng, {
1326
- ...opt
1327
- });
1328
- return (val) => formatter.format(val);
1329
- }),
1330
- relativetime: createCachedFormatter((lng, opt) => {
1331
- const formatter = new Intl.RelativeTimeFormat(lng, {
1332
- ...opt
1333
- });
1334
- return (val) => formatter.format(val, opt.range || "day");
1335
- }),
1336
- list: createCachedFormatter((lng, opt) => {
1337
- const formatter = new Intl.ListFormat(lng, {
1338
- ...opt
1339
- });
1340
- return (val) => formatter.format(val);
1341
- })
1342
- };
1343
- this.init(options);
1344
- }
1345
- init(services) {
1346
- let options = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {
1347
- interpolation: {}
1348
- };
1349
- this.formatSeparator = options.interpolation.formatSeparator || ",";
1350
- }
1351
- add(name, fc) {
1352
- this.formats[name.toLowerCase().trim()] = fc;
1353
- }
1354
- addCached(name, fc) {
1355
- this.formats[name.toLowerCase().trim()] = createCachedFormatter(fc);
1356
- }
1357
- format(value, format, lng) {
1358
- let options = arguments.length > 3 && arguments[3] !== void 0 ? arguments[3] : {};
1359
- const formats = format.split(this.formatSeparator);
1360
- if (formats.length > 1 && formats[0].indexOf("(") > 1 && formats[0].indexOf(")") < 0 && formats.find((f) => f.indexOf(")") > -1)) {
1361
- const lastIndex = formats.findIndex((f) => f.indexOf(")") > -1);
1362
- formats[0] = [formats[0], ...formats.splice(1, lastIndex)].join(this.formatSeparator);
1363
- }
1364
- const result = formats.reduce((mem, f) => {
1365
- const {
1366
- formatName,
1367
- formatOptions
1368
- } = parseFormatStr(f);
1369
- if (this.formats[formatName]) {
1370
- let formatted = mem;
1371
- try {
1372
- const valOptions = options?.formatParams?.[options.interpolationkey] || {};
1373
- const l = valOptions.locale || valOptions.lng || options.locale || options.lng || lng;
1374
- formatted = this.formats[formatName](mem, l, {
1375
- ...formatOptions,
1376
- ...options,
1377
- ...valOptions
1378
- });
1379
- } catch (error) {
1380
- this.logger.warn(error);
1381
- }
1382
- return formatted;
1383
- } else {
1384
- this.logger.warn(`there was no format function for ${formatName}`);
1385
- }
1386
- return mem;
1387
- }, value);
1388
- return result;
1389
- }
1390
- };
1391
- var removePending = (q, name) => {
1392
- if (q.pending[name] !== void 0) {
1393
- delete q.pending[name];
1394
- q.pendingCount--;
1395
- }
1396
- };
1397
- var Connector = class extends EventEmitter {
1398
- constructor(backend, store, services) {
1399
- let options = arguments.length > 3 && arguments[3] !== void 0 ? arguments[3] : {};
1400
- super();
1401
- this.backend = backend;
1402
- this.store = store;
1403
- this.services = services;
1404
- this.languageUtils = services.languageUtils;
1405
- this.options = options;
1406
- this.logger = baseLogger.create("backendConnector");
1407
- this.waitingReads = [];
1408
- this.maxParallelReads = options.maxParallelReads || 10;
1409
- this.readingCalls = 0;
1410
- this.maxRetries = options.maxRetries >= 0 ? options.maxRetries : 5;
1411
- this.retryTimeout = options.retryTimeout >= 1 ? options.retryTimeout : 350;
1412
- this.state = {};
1413
- this.queue = [];
1414
- this.backend?.init?.(services, options.backend, options);
1415
- }
1416
- queueLoad(languages, namespaces, options, callback) {
1417
- const toLoad = {};
1418
- const pending = {};
1419
- const toLoadLanguages = {};
1420
- const toLoadNamespaces = {};
1421
- languages.forEach((lng) => {
1422
- let hasAllNamespaces = true;
1423
- namespaces.forEach((ns) => {
1424
- const name = `${lng}|${ns}`;
1425
- if (!options.reload && this.store.hasResourceBundle(lng, ns)) {
1426
- this.state[name] = 2;
1427
- } else if (this.state[name] < 0) ;
1428
- else if (this.state[name] === 1) {
1429
- if (pending[name] === void 0) pending[name] = true;
1430
- } else {
1431
- this.state[name] = 1;
1432
- hasAllNamespaces = false;
1433
- if (pending[name] === void 0) pending[name] = true;
1434
- if (toLoad[name] === void 0) toLoad[name] = true;
1435
- if (toLoadNamespaces[ns] === void 0) toLoadNamespaces[ns] = true;
1436
- }
1437
- });
1438
- if (!hasAllNamespaces) toLoadLanguages[lng] = true;
1439
- });
1440
- if (Object.keys(toLoad).length || Object.keys(pending).length) {
1441
- this.queue.push({
1442
- pending,
1443
- pendingCount: Object.keys(pending).length,
1444
- loaded: {},
1445
- errors: [],
1446
- callback
1447
- });
1448
- }
1449
- return {
1450
- toLoad: Object.keys(toLoad),
1451
- pending: Object.keys(pending),
1452
- toLoadLanguages: Object.keys(toLoadLanguages),
1453
- toLoadNamespaces: Object.keys(toLoadNamespaces)
1454
- };
1455
- }
1456
- loaded(name, err, data) {
1457
- const s = name.split("|");
1458
- const lng = s[0];
1459
- const ns = s[1];
1460
- if (err) this.emit("failedLoading", lng, ns, err);
1461
- if (!err && data) {
1462
- this.store.addResourceBundle(lng, ns, data, void 0, void 0, {
1463
- skipCopy: true
1464
- });
1465
- }
1466
- this.state[name] = err ? -1 : 2;
1467
- if (err && data) this.state[name] = 0;
1468
- const loaded = {};
1469
- this.queue.forEach((q) => {
1470
- pushPath(q.loaded, [lng], ns);
1471
- removePending(q, name);
1472
- if (err) q.errors.push(err);
1473
- if (q.pendingCount === 0 && !q.done) {
1474
- Object.keys(q.loaded).forEach((l) => {
1475
- if (!loaded[l]) loaded[l] = {};
1476
- const loadedKeys = q.loaded[l];
1477
- if (loadedKeys.length) {
1478
- loadedKeys.forEach((n) => {
1479
- if (loaded[l][n] === void 0) loaded[l][n] = true;
1480
- });
1481
- }
1482
- });
1483
- q.done = true;
1484
- if (q.errors.length) {
1485
- q.callback(q.errors);
1486
- } else {
1487
- q.callback();
1488
- }
1489
- }
1490
- });
1491
- this.emit("loaded", loaded);
1492
- this.queue = this.queue.filter((q) => !q.done);
1493
- }
1494
- read(lng, ns, fcName) {
1495
- let tried = arguments.length > 3 && arguments[3] !== void 0 ? arguments[3] : 0;
1496
- let wait = arguments.length > 4 && arguments[4] !== void 0 ? arguments[4] : this.retryTimeout;
1497
- let callback = arguments.length > 5 ? arguments[5] : void 0;
1498
- if (!lng.length) return callback(null, {});
1499
- if (this.readingCalls >= this.maxParallelReads) {
1500
- this.waitingReads.push({
1501
- lng,
1502
- ns,
1503
- fcName,
1504
- tried,
1505
- wait,
1506
- callback
1507
- });
1508
- return;
1509
- }
1510
- this.readingCalls++;
1511
- const resolver = (err, data) => {
1512
- this.readingCalls--;
1513
- if (this.waitingReads.length > 0) {
1514
- const next = this.waitingReads.shift();
1515
- this.read(next.lng, next.ns, next.fcName, next.tried, next.wait, next.callback);
1516
- }
1517
- if (err && data && tried < this.maxRetries) {
1518
- setTimeout(() => {
1519
- this.read.call(this, lng, ns, fcName, tried + 1, wait * 2, callback);
1520
- }, wait);
1521
- return;
1522
- }
1523
- callback(err, data);
1524
- };
1525
- const fc = this.backend[fcName].bind(this.backend);
1526
- if (fc.length === 2) {
1527
- try {
1528
- const r = fc(lng, ns);
1529
- if (r && typeof r.then === "function") {
1530
- r.then((data) => resolver(null, data)).catch(resolver);
1531
- } else {
1532
- resolver(null, r);
1533
- }
1534
- } catch (err) {
1535
- resolver(err);
1536
- }
1537
- return;
1538
- }
1539
- return fc(lng, ns, resolver);
1540
- }
1541
- prepareLoading(languages, namespaces) {
1542
- let options = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : {};
1543
- let callback = arguments.length > 3 ? arguments[3] : void 0;
1544
- if (!this.backend) {
1545
- this.logger.warn("No backend was added via i18next.use. Will not load resources.");
1546
- return callback && callback();
1547
- }
1548
- if (isString(languages)) languages = this.languageUtils.toResolveHierarchy(languages);
1549
- if (isString(namespaces)) namespaces = [namespaces];
1550
- const toLoad = this.queueLoad(languages, namespaces, options, callback);
1551
- if (!toLoad.toLoad.length) {
1552
- if (!toLoad.pending.length) callback();
1553
- return null;
1554
- }
1555
- toLoad.toLoad.forEach((name) => {
1556
- this.loadOne(name);
1557
- });
1558
- }
1559
- load(languages, namespaces, callback) {
1560
- this.prepareLoading(languages, namespaces, {}, callback);
1561
- }
1562
- reload(languages, namespaces, callback) {
1563
- this.prepareLoading(languages, namespaces, {
1564
- reload: true
1565
- }, callback);
1566
- }
1567
- loadOne(name) {
1568
- let prefix = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : "";
1569
- const s = name.split("|");
1570
- const lng = s[0];
1571
- const ns = s[1];
1572
- this.read(lng, ns, "read", void 0, void 0, (err, data) => {
1573
- if (err) this.logger.warn(`${prefix}loading namespace ${ns} for language ${lng} failed`, err);
1574
- if (!err && data) this.logger.log(`${prefix}loaded namespace ${ns} for language ${lng}`, data);
1575
- this.loaded(name, err, data);
1576
- });
1577
- }
1578
- saveMissing(languages, namespace, key, fallbackValue, isUpdate) {
1579
- let options = arguments.length > 5 && arguments[5] !== void 0 ? arguments[5] : {};
1580
- let clb = arguments.length > 6 && arguments[6] !== void 0 ? arguments[6] : () => {
1581
- };
1582
- if (this.services?.utils?.hasLoadedNamespace && !this.services?.utils?.hasLoadedNamespace(namespace)) {
1583
- this.logger.warn(`did not save key "${key}" as the namespace "${namespace}" was not yet loaded`, "This means something IS WRONG in your setup. You access the t function before i18next.init / i18next.loadNamespace / i18next.changeLanguage was done. Wait for the callback or Promise to resolve before accessing it!!!");
1584
- return;
1585
- }
1586
- if (key === void 0 || key === null || key === "") return;
1587
- if (this.backend?.create) {
1588
- const opts = {
1589
- ...options,
1590
- isUpdate
1591
- };
1592
- const fc = this.backend.create.bind(this.backend);
1593
- if (fc.length < 6) {
1594
- try {
1595
- let r;
1596
- if (fc.length === 5) {
1597
- r = fc(languages, namespace, key, fallbackValue, opts);
1598
- } else {
1599
- r = fc(languages, namespace, key, fallbackValue);
1600
- }
1601
- if (r && typeof r.then === "function") {
1602
- r.then((data) => clb(null, data)).catch(clb);
1603
- } else {
1604
- clb(null, r);
1605
- }
1606
- } catch (err) {
1607
- clb(err);
1608
- }
1609
- } else {
1610
- fc(languages, namespace, key, fallbackValue, clb, opts);
1611
- }
1612
- }
1613
- if (!languages || !languages[0]) return;
1614
- this.store.addResource(languages[0], namespace, key, fallbackValue);
1615
- }
1616
- };
1617
- var get = () => ({
1618
- debug: false,
1619
- initAsync: true,
1620
- ns: ["translation"],
1621
- defaultNS: ["translation"],
1622
- fallbackLng: ["dev"],
1623
- fallbackNS: false,
1624
- supportedLngs: false,
1625
- nonExplicitSupportedLngs: false,
1626
- load: "all",
1627
- preload: false,
1628
- simplifyPluralSuffix: true,
1629
- keySeparator: ".",
1630
- nsSeparator: ":",
1631
- pluralSeparator: "_",
1632
- contextSeparator: "_",
1633
- partialBundledLanguages: false,
1634
- saveMissing: false,
1635
- updateMissing: false,
1636
- saveMissingTo: "fallback",
1637
- saveMissingPlurals: true,
1638
- missingKeyHandler: false,
1639
- missingInterpolationHandler: false,
1640
- postProcess: false,
1641
- postProcessPassResolved: false,
1642
- returnNull: false,
1643
- returnEmptyString: true,
1644
- returnObjects: false,
1645
- joinArrays: false,
1646
- returnedObjectHandler: false,
1647
- parseMissingKeyHandler: false,
1648
- appendNamespaceToMissingKey: false,
1649
- appendNamespaceToCIMode: false,
1650
- overloadTranslationOptionHandler: (args) => {
1651
- let ret = {};
1652
- if (typeof args[1] === "object") ret = args[1];
1653
- if (isString(args[1])) ret.defaultValue = args[1];
1654
- if (isString(args[2])) ret.tDescription = args[2];
1655
- if (typeof args[2] === "object" || typeof args[3] === "object") {
1656
- const options = args[3] || args[2];
1657
- Object.keys(options).forEach((key) => {
1658
- ret[key] = options[key];
1659
- });
1660
- }
1661
- return ret;
1662
- },
1663
- interpolation: {
1664
- escapeValue: true,
1665
- format: (value) => value,
1666
- prefix: "{{",
1667
- suffix: "}}",
1668
- formatSeparator: ",",
1669
- unescapePrefix: "-",
1670
- nestingPrefix: "$t(",
1671
- nestingSuffix: ")",
1672
- nestingOptionsSeparator: ",",
1673
- maxReplaces: 1e3,
1674
- skipOnVariables: true
1675
- }
1676
- });
1677
- var transformOptions = (options) => {
1678
- if (isString(options.ns)) options.ns = [options.ns];
1679
- if (isString(options.fallbackLng)) options.fallbackLng = [options.fallbackLng];
1680
- if (isString(options.fallbackNS)) options.fallbackNS = [options.fallbackNS];
1681
- if (options.supportedLngs?.indexOf?.("cimode") < 0) {
1682
- options.supportedLngs = options.supportedLngs.concat(["cimode"]);
1683
- }
1684
- if (typeof options.initImmediate === "boolean") options.initAsync = options.initImmediate;
1685
- return options;
1686
- };
1687
- var noop = () => {
1688
- };
1689
- var bindMemberFunctions = (inst) => {
1690
- const mems = Object.getOwnPropertyNames(Object.getPrototypeOf(inst));
1691
- mems.forEach((mem) => {
1692
- if (typeof inst[mem] === "function") {
1693
- inst[mem] = inst[mem].bind(inst);
1694
- }
1695
- });
1696
- };
1697
- var I18n = class _I18n extends EventEmitter {
1698
- constructor() {
1699
- let options = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {};
1700
- let callback = arguments.length > 1 ? arguments[1] : void 0;
1701
- super();
1702
- this.options = transformOptions(options);
1703
- this.services = {};
1704
- this.logger = baseLogger;
1705
- this.modules = {
1706
- external: []
1707
- };
1708
- bindMemberFunctions(this);
1709
- if (callback && !this.isInitialized && !options.isClone) {
1710
- if (!this.options.initAsync) {
1711
- this.init(options, callback);
1712
- return this;
1713
- }
1714
- setTimeout(() => {
1715
- this.init(options, callback);
1716
- }, 0);
1717
- }
1718
- }
1719
- init() {
1720
- var _this = this;
1721
- let options = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {};
1722
- let callback = arguments.length > 1 ? arguments[1] : void 0;
1723
- this.isInitializing = true;
1724
- if (typeof options === "function") {
1725
- callback = options;
1726
- options = {};
1727
- }
1728
- if (!options.defaultNS && options.defaultNS !== false && options.ns) {
1729
- if (isString(options.ns)) {
1730
- options.defaultNS = options.ns;
1731
- } else if (options.ns.indexOf("translation") < 0) {
1732
- options.defaultNS = options.ns[0];
1733
- }
1734
- }
1735
- const defOpts = get();
1736
- this.options = {
1737
- ...defOpts,
1738
- ...this.options,
1739
- ...transformOptions(options)
1740
- };
1741
- this.options.interpolation = {
1742
- ...defOpts.interpolation,
1743
- ...this.options.interpolation
1744
- };
1745
- if (options.keySeparator !== void 0) {
1746
- this.options.userDefinedKeySeparator = options.keySeparator;
1747
- }
1748
- if (options.nsSeparator !== void 0) {
1749
- this.options.userDefinedNsSeparator = options.nsSeparator;
1750
- }
1751
- const createClassOnDemand = (ClassOrObject) => {
1752
- if (!ClassOrObject) return null;
1753
- if (typeof ClassOrObject === "function") return new ClassOrObject();
1754
- return ClassOrObject;
1755
- };
1756
- if (!this.options.isClone) {
1757
- if (this.modules.logger) {
1758
- baseLogger.init(createClassOnDemand(this.modules.logger), this.options);
1759
- } else {
1760
- baseLogger.init(null, this.options);
1761
- }
1762
- let formatter;
1763
- if (this.modules.formatter) {
1764
- formatter = this.modules.formatter;
1765
- } else {
1766
- formatter = Formatter;
1767
- }
1768
- const lu = new LanguageUtil(this.options);
1769
- this.store = new ResourceStore(this.options.resources, this.options);
1770
- const s = this.services;
1771
- s.logger = baseLogger;
1772
- s.resourceStore = this.store;
1773
- s.languageUtils = lu;
1774
- s.pluralResolver = new PluralResolver(lu, {
1775
- prepend: this.options.pluralSeparator,
1776
- simplifyPluralSuffix: this.options.simplifyPluralSuffix
1777
- });
1778
- if (formatter && (!this.options.interpolation.format || this.options.interpolation.format === defOpts.interpolation.format)) {
1779
- s.formatter = createClassOnDemand(formatter);
1780
- s.formatter.init(s, this.options);
1781
- this.options.interpolation.format = s.formatter.format.bind(s.formatter);
1782
- }
1783
- s.interpolator = new Interpolator(this.options);
1784
- s.utils = {
1785
- hasLoadedNamespace: this.hasLoadedNamespace.bind(this)
1786
- };
1787
- s.backendConnector = new Connector(createClassOnDemand(this.modules.backend), s.resourceStore, s, this.options);
1788
- s.backendConnector.on("*", function(event) {
1789
- for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
1790
- args[_key - 1] = arguments[_key];
1791
- }
1792
- _this.emit(event, ...args);
1793
- });
1794
- if (this.modules.languageDetector) {
1795
- s.languageDetector = createClassOnDemand(this.modules.languageDetector);
1796
- if (s.languageDetector.init) s.languageDetector.init(s, this.options.detection, this.options);
1797
- }
1798
- if (this.modules.i18nFormat) {
1799
- s.i18nFormat = createClassOnDemand(this.modules.i18nFormat);
1800
- if (s.i18nFormat.init) s.i18nFormat.init(this);
1801
- }
1802
- this.translator = new Translator(this.services, this.options);
1803
- this.translator.on("*", function(event) {
1804
- for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
1805
- args[_key2 - 1] = arguments[_key2];
1806
- }
1807
- _this.emit(event, ...args);
1808
- });
1809
- this.modules.external.forEach((m) => {
1810
- if (m.init) m.init(this);
1811
- });
1812
- }
1813
- this.format = this.options.interpolation.format;
1814
- if (!callback) callback = noop;
1815
- if (this.options.fallbackLng && !this.services.languageDetector && !this.options.lng) {
1816
- const codes = this.services.languageUtils.getFallbackCodes(this.options.fallbackLng);
1817
- if (codes.length > 0 && codes[0] !== "dev") this.options.lng = codes[0];
1818
- }
1819
- if (!this.services.languageDetector && !this.options.lng) {
1820
- this.logger.warn("init: no languageDetector is used and no lng is defined");
1821
- }
1822
- const storeApi = ["getResource", "hasResourceBundle", "getResourceBundle", "getDataByLanguage"];
1823
- storeApi.forEach((fcName) => {
1824
- this[fcName] = function() {
1825
- return _this.store[fcName](...arguments);
1826
- };
1827
- });
1828
- const storeApiChained = ["addResource", "addResources", "addResourceBundle", "removeResourceBundle"];
1829
- storeApiChained.forEach((fcName) => {
1830
- this[fcName] = function() {
1831
- _this.store[fcName](...arguments);
1832
- return _this;
1833
- };
1834
- });
1835
- const deferred = defer();
1836
- const load = () => {
1837
- const finish = (err, t2) => {
1838
- this.isInitializing = false;
1839
- if (this.isInitialized && !this.initializedStoreOnce) this.logger.warn("init: i18next is already initialized. You should call init just once!");
1840
- this.isInitialized = true;
1841
- if (!this.options.isClone) this.logger.log("initialized", this.options);
1842
- this.emit("initialized", this.options);
1843
- deferred.resolve(t2);
1844
- callback(err, t2);
1845
- };
1846
- if (this.languages && !this.isInitialized) return finish(null, this.t.bind(this));
1847
- this.changeLanguage(this.options.lng, finish);
1848
- };
1849
- if (this.options.resources || !this.options.initAsync) {
1850
- load();
1851
- } else {
1852
- setTimeout(load, 0);
1853
- }
1854
- return deferred;
1855
- }
1856
- loadResources(language) {
1857
- let callback = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : noop;
1858
- let usedCallback = callback;
1859
- const usedLng = isString(language) ? language : this.language;
1860
- if (typeof language === "function") usedCallback = language;
1861
- if (!this.options.resources || this.options.partialBundledLanguages) {
1862
- if (usedLng?.toLowerCase() === "cimode" && (!this.options.preload || this.options.preload.length === 0)) return usedCallback();
1863
- const toLoad = [];
1864
- const append = (lng) => {
1865
- if (!lng) return;
1866
- if (lng === "cimode") return;
1867
- const lngs = this.services.languageUtils.toResolveHierarchy(lng);
1868
- lngs.forEach((l) => {
1869
- if (l === "cimode") return;
1870
- if (toLoad.indexOf(l) < 0) toLoad.push(l);
1871
- });
1872
- };
1873
- if (!usedLng) {
1874
- const fallbacks = this.services.languageUtils.getFallbackCodes(this.options.fallbackLng);
1875
- fallbacks.forEach((l) => append(l));
1876
- } else {
1877
- append(usedLng);
1878
- }
1879
- this.options.preload?.forEach?.((l) => append(l));
1880
- this.services.backendConnector.load(toLoad, this.options.ns, (e) => {
1881
- if (!e && !this.resolvedLanguage && this.language) this.setResolvedLanguage(this.language);
1882
- usedCallback(e);
1883
- });
1884
- } else {
1885
- usedCallback(null);
1886
- }
1887
- }
1888
- reloadResources(lngs, ns, callback) {
1889
- const deferred = defer();
1890
- if (typeof lngs === "function") {
1891
- callback = lngs;
1892
- lngs = void 0;
1893
- }
1894
- if (typeof ns === "function") {
1895
- callback = ns;
1896
- ns = void 0;
1897
- }
1898
- if (!lngs) lngs = this.languages;
1899
- if (!ns) ns = this.options.ns;
1900
- if (!callback) callback = noop;
1901
- this.services.backendConnector.reload(lngs, ns, (err) => {
1902
- deferred.resolve();
1903
- callback(err);
1904
- });
1905
- return deferred;
1906
- }
1907
- use(module) {
1908
- if (!module) throw new Error("You are passing an undefined module! Please check the object you are passing to i18next.use()");
1909
- if (!module.type) throw new Error("You are passing a wrong module! Please check the object you are passing to i18next.use()");
1910
- if (module.type === "backend") {
1911
- this.modules.backend = module;
1912
- }
1913
- if (module.type === "logger" || module.log && module.warn && module.error) {
1914
- this.modules.logger = module;
1915
- }
1916
- if (module.type === "languageDetector") {
1917
- this.modules.languageDetector = module;
1918
- }
1919
- if (module.type === "i18nFormat") {
1920
- this.modules.i18nFormat = module;
1921
- }
1922
- if (module.type === "postProcessor") {
1923
- postProcessor.addPostProcessor(module);
1924
- }
1925
- if (module.type === "formatter") {
1926
- this.modules.formatter = module;
1927
- }
1928
- if (module.type === "3rdParty") {
1929
- this.modules.external.push(module);
1930
- }
1931
- return this;
1932
- }
1933
- setResolvedLanguage(l) {
1934
- if (!l || !this.languages) return;
1935
- if (["cimode", "dev"].indexOf(l) > -1) return;
1936
- for (let li = 0; li < this.languages.length; li++) {
1937
- const lngInLngs = this.languages[li];
1938
- if (["cimode", "dev"].indexOf(lngInLngs) > -1) continue;
1939
- if (this.store.hasLanguageSomeTranslations(lngInLngs)) {
1940
- this.resolvedLanguage = lngInLngs;
1941
- break;
1942
- }
1943
- }
1944
- }
1945
- changeLanguage(lng, callback) {
1946
- var _this2 = this;
1947
- this.isLanguageChangingTo = lng;
1948
- const deferred = defer();
1949
- this.emit("languageChanging", lng);
1950
- const setLngProps = (l) => {
1951
- this.language = l;
1952
- this.languages = this.services.languageUtils.toResolveHierarchy(l);
1953
- this.resolvedLanguage = void 0;
1954
- this.setResolvedLanguage(l);
1955
- };
1956
- const done = (err, l) => {
1957
- if (l) {
1958
- setLngProps(l);
1959
- this.translator.changeLanguage(l);
1960
- this.isLanguageChangingTo = void 0;
1961
- this.emit("languageChanged", l);
1962
- this.logger.log("languageChanged", l);
1963
- } else {
1964
- this.isLanguageChangingTo = void 0;
1965
- }
1966
- deferred.resolve(function() {
1967
- return _this2.t(...arguments);
1968
- });
1969
- if (callback) callback(err, function() {
1970
- return _this2.t(...arguments);
1971
- });
1972
- };
1973
- const setLng = (lngs) => {
1974
- if (!lng && !lngs && this.services.languageDetector) lngs = [];
1975
- const l = isString(lngs) ? lngs : this.services.languageUtils.getBestMatchFromCodes(lngs);
1976
- if (l) {
1977
- if (!this.language) {
1978
- setLngProps(l);
1979
- }
1980
- if (!this.translator.language) this.translator.changeLanguage(l);
1981
- this.services.languageDetector?.cacheUserLanguage?.(l);
1982
- }
1983
- this.loadResources(l, (err) => {
1984
- done(err, l);
1985
- });
1986
- };
1987
- if (!lng && this.services.languageDetector && !this.services.languageDetector.async) {
1988
- setLng(this.services.languageDetector.detect());
1989
- } else if (!lng && this.services.languageDetector && this.services.languageDetector.async) {
1990
- if (this.services.languageDetector.detect.length === 0) {
1991
- this.services.languageDetector.detect().then(setLng);
1992
- } else {
1993
- this.services.languageDetector.detect(setLng);
1994
- }
1995
- } else {
1996
- setLng(lng);
1997
- }
1998
- return deferred;
1999
- }
2000
- getFixedT(lng, ns, keyPrefix) {
2001
- var _this3 = this;
2002
- const fixedT = function(key, opts) {
2003
- let options;
2004
- if (typeof opts !== "object") {
2005
- for (var _len3 = arguments.length, rest = new Array(_len3 > 2 ? _len3 - 2 : 0), _key3 = 2; _key3 < _len3; _key3++) {
2006
- rest[_key3 - 2] = arguments[_key3];
2007
- }
2008
- options = _this3.options.overloadTranslationOptionHandler([key, opts].concat(rest));
2009
- } else {
2010
- options = {
2011
- ...opts
2012
- };
2013
- }
2014
- options.lng = options.lng || fixedT.lng;
2015
- options.lngs = options.lngs || fixedT.lngs;
2016
- options.ns = options.ns || fixedT.ns;
2017
- if (options.keyPrefix !== "") options.keyPrefix = options.keyPrefix || keyPrefix || fixedT.keyPrefix;
2018
- const keySeparator = _this3.options.keySeparator || ".";
2019
- let resultKey;
2020
- if (options.keyPrefix && Array.isArray(key)) {
2021
- resultKey = key.map((k) => `${options.keyPrefix}${keySeparator}${k}`);
2022
- } else {
2023
- resultKey = options.keyPrefix ? `${options.keyPrefix}${keySeparator}${key}` : key;
2024
- }
2025
- return _this3.t(resultKey, options);
2026
- };
2027
- if (isString(lng)) {
2028
- fixedT.lng = lng;
2029
- } else {
2030
- fixedT.lngs = lng;
2031
- }
2032
- fixedT.ns = ns;
2033
- fixedT.keyPrefix = keyPrefix;
2034
- return fixedT;
2035
- }
2036
- t() {
2037
- for (var _len4 = arguments.length, args = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) {
2038
- args[_key4] = arguments[_key4];
2039
- }
2040
- return this.translator?.translate(...args);
2041
- }
2042
- exists() {
2043
- for (var _len5 = arguments.length, args = new Array(_len5), _key5 = 0; _key5 < _len5; _key5++) {
2044
- args[_key5] = arguments[_key5];
2045
- }
2046
- return this.translator?.exists(...args);
2047
- }
2048
- setDefaultNamespace(ns) {
2049
- this.options.defaultNS = ns;
2050
- }
2051
- hasLoadedNamespace(ns) {
2052
- let options = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
2053
- if (!this.isInitialized) {
2054
- this.logger.warn("hasLoadedNamespace: i18next was not initialized", this.languages);
2055
- return false;
2056
- }
2057
- if (!this.languages || !this.languages.length) {
2058
- this.logger.warn("hasLoadedNamespace: i18n.languages were undefined or empty", this.languages);
2059
- return false;
2060
- }
2061
- const lng = options.lng || this.resolvedLanguage || this.languages[0];
2062
- const fallbackLng = this.options ? this.options.fallbackLng : false;
2063
- const lastLng = this.languages[this.languages.length - 1];
2064
- if (lng.toLowerCase() === "cimode") return true;
2065
- const loadNotPending = (l, n) => {
2066
- const loadState = this.services.backendConnector.state[`${l}|${n}`];
2067
- return loadState === -1 || loadState === 0 || loadState === 2;
2068
- };
2069
- if (options.precheck) {
2070
- const preResult = options.precheck(this, loadNotPending);
2071
- if (preResult !== void 0) return preResult;
2072
- }
2073
- if (this.hasResourceBundle(lng, ns)) return true;
2074
- if (!this.services.backendConnector.backend || this.options.resources && !this.options.partialBundledLanguages) return true;
2075
- if (loadNotPending(lng, ns) && (!fallbackLng || loadNotPending(lastLng, ns))) return true;
2076
- return false;
2077
- }
2078
- loadNamespaces(ns, callback) {
2079
- const deferred = defer();
2080
- if (!this.options.ns) {
2081
- if (callback) callback();
2082
- return Promise.resolve();
2083
- }
2084
- if (isString(ns)) ns = [ns];
2085
- ns.forEach((n) => {
2086
- if (this.options.ns.indexOf(n) < 0) this.options.ns.push(n);
2087
- });
2088
- this.loadResources((err) => {
2089
- deferred.resolve();
2090
- if (callback) callback(err);
2091
- });
2092
- return deferred;
2093
- }
2094
- loadLanguages(lngs, callback) {
2095
- const deferred = defer();
2096
- if (isString(lngs)) lngs = [lngs];
2097
- const preloaded = this.options.preload || [];
2098
- const newLngs = lngs.filter((lng) => preloaded.indexOf(lng) < 0 && this.services.languageUtils.isSupportedCode(lng));
2099
- if (!newLngs.length) {
2100
- if (callback) callback();
2101
- return Promise.resolve();
2102
- }
2103
- this.options.preload = preloaded.concat(newLngs);
2104
- this.loadResources((err) => {
2105
- deferred.resolve();
2106
- if (callback) callback(err);
2107
- });
2108
- return deferred;
2109
- }
2110
- dir(lng) {
2111
- if (!lng) lng = this.resolvedLanguage || (this.languages?.length > 0 ? this.languages[0] : this.language);
2112
- if (!lng) return "rtl";
2113
- const rtlLngs = ["ar", "shu", "sqr", "ssh", "xaa", "yhd", "yud", "aao", "abh", "abv", "acm", "acq", "acw", "acx", "acy", "adf", "ads", "aeb", "aec", "afb", "ajp", "apc", "apd", "arb", "arq", "ars", "ary", "arz", "auz", "avl", "ayh", "ayl", "ayn", "ayp", "bbz", "pga", "he", "iw", "ps", "pbt", "pbu", "pst", "prp", "prd", "ug", "ur", "ydd", "yds", "yih", "ji", "yi", "hbo", "men", "xmn", "fa", "jpr", "peo", "pes", "prs", "dv", "sam", "ckb"];
2114
- const languageUtils = this.services?.languageUtils || new LanguageUtil(get());
2115
- return rtlLngs.indexOf(languageUtils.getLanguagePartFromCode(lng)) > -1 || lng.toLowerCase().indexOf("-arab") > 1 ? "rtl" : "ltr";
2116
- }
2117
- static createInstance() {
2118
- let options = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {};
2119
- let callback = arguments.length > 1 ? arguments[1] : void 0;
2120
- return new _I18n(options, callback);
2121
- }
2122
- cloneInstance() {
2123
- let options = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {};
2124
- let callback = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : noop;
2125
- const forkResourceStore = options.forkResourceStore;
2126
- if (forkResourceStore) delete options.forkResourceStore;
2127
- const mergedOptions = {
2128
- ...this.options,
2129
- ...options,
2130
- ...{
2131
- isClone: true
2132
- }
2133
- };
2134
- const clone = new _I18n(mergedOptions);
2135
- if (options.debug !== void 0 || options.prefix !== void 0) {
2136
- clone.logger = clone.logger.clone(options);
2137
- }
2138
- const membersToCopy = ["store", "services", "language"];
2139
- membersToCopy.forEach((m) => {
2140
- clone[m] = this[m];
2141
- });
2142
- clone.services = {
2143
- ...this.services
2144
- };
2145
- clone.services.utils = {
2146
- hasLoadedNamespace: clone.hasLoadedNamespace.bind(clone)
2147
- };
2148
- if (forkResourceStore) {
2149
- const clonedData = Object.keys(this.store.data).reduce((prev, l) => {
2150
- prev[l] = {
2151
- ...this.store.data[l]
2152
- };
2153
- return Object.keys(prev[l]).reduce((acc, n) => {
2154
- acc[n] = {
2155
- ...prev[l][n]
2156
- };
2157
- return acc;
2158
- }, {});
2159
- }, {});
2160
- clone.store = new ResourceStore(clonedData, mergedOptions);
2161
- clone.services.resourceStore = clone.store;
2162
- }
2163
- clone.translator = new Translator(clone.services, mergedOptions);
2164
- clone.translator.on("*", function(event) {
2165
- for (var _len6 = arguments.length, args = new Array(_len6 > 1 ? _len6 - 1 : 0), _key6 = 1; _key6 < _len6; _key6++) {
2166
- args[_key6 - 1] = arguments[_key6];
2167
- }
2168
- clone.emit(event, ...args);
2169
- });
2170
- clone.init(mergedOptions, callback);
2171
- clone.translator.options = mergedOptions;
2172
- clone.translator.backendConnector.services.utils = {
2173
- hasLoadedNamespace: clone.hasLoadedNamespace.bind(clone)
2174
- };
2175
- return clone;
2176
- }
2177
- toJSON() {
2178
- return {
2179
- options: this.options,
2180
- store: this.store,
2181
- language: this.language,
2182
- languages: this.languages,
2183
- resolvedLanguage: this.resolvedLanguage
2184
- };
2185
- }
2186
- };
2187
- var instance = I18n.createInstance();
2188
- instance.createInstance = I18n.createInstance;
2189
- var createInstance = instance.createInstance;
2190
- var dir = instance.dir;
2191
- var init = instance.init;
2192
- var loadResources = instance.loadResources;
2193
- var reloadResources = instance.reloadResources;
2194
- var use = instance.use;
2195
- var changeLanguage = instance.changeLanguage;
2196
- var getFixedT = instance.getFixedT;
2197
- var t = instance.t;
2198
- var exists = instance.exists;
2199
- var setDefaultNamespace = instance.setDefaultNamespace;
2200
- var hasLoadedNamespace = instance.hasLoadedNamespace;
2201
- var loadNamespaces = instance.loadNamespaces;
2202
- var loadLanguages = instance.loadLanguages;
4
+ import i18next from "i18next";
2203
5
 
2204
6
  // src/locale/en/locale-strings.ts
2205
7
  var localeStrings = {
@@ -2288,7 +90,7 @@ var gs1Resources = {
2288
90
  aidct_gs1: localeStrings2
2289
91
  }
2290
92
  };
2291
- var i18nextGS1 = instance.createInstance();
93
+ var i18nextGS1 = i18next.createInstance();
2292
94
  async function i18nGS1Init(environment, debug = false) {
2293
95
  await i18nUtilityInit(environment, debug);
2294
96
  await i18nCoreInit(i18nextGS1, environment, debug, gs1NS, utilityResources, gs1Resources);
@@ -4164,3 +1966,19 @@ export {
4164
1966
  i18nGS1Init,
4165
1967
  i18nextGS1
4166
1968
  };
1969
+ /*!
1970
+ * Copyright © 2024-2025 Dolphin Data Development Ltd. and AIDC Toolkit
1971
+ * contributors
1972
+ *
1973
+ * Licensed under the Apache License, Version 2.0 (the "License");
1974
+ * you may not use this file except in compliance with the License.
1975
+ * You may obtain a copy of the License at
1976
+ *
1977
+ * https://www.apache.org/licenses/LICENSE-2.0
1978
+ *
1979
+ * Unless required by applicable law or agreed to in writing, software
1980
+ * distributed under the License is distributed on an "AS IS" BASIS,
1981
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1982
+ * See the License for the specific language governing permissions and
1983
+ * limitations under the License.
1984
+ */