@aidc-toolkit/utility 1.0.24-beta → 1.0.26-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.
Files changed (72) hide show
  1. package/dist/character-set.d.ts +308 -0
  2. package/dist/character-set.d.ts.map +1 -0
  3. package/dist/character-set.js +564 -0
  4. package/dist/character-set.js.map +1 -0
  5. package/dist/exclusion.d.ts +26 -0
  6. package/dist/exclusion.d.ts.map +1 -0
  7. package/dist/exclusion.js +18 -0
  8. package/dist/exclusion.js.map +1 -0
  9. package/dist/index.d.ts +26 -947
  10. package/dist/index.d.ts.map +1 -0
  11. package/dist/index.js +8 -3504
  12. package/dist/index.js.map +1 -1
  13. package/dist/iterable-utility.d.ts +39 -0
  14. package/dist/iterable-utility.d.ts.map +1 -0
  15. package/dist/iterable-utility.js +35 -0
  16. package/dist/iterable-utility.js.map +1 -0
  17. package/dist/locale/en/locale-resources.d.ts +33 -0
  18. package/dist/locale/en/locale-resources.d.ts.map +1 -0
  19. package/dist/locale/en/locale-resources.js +32 -0
  20. package/dist/locale/en/locale-resources.js.map +1 -0
  21. package/dist/locale/fr/locale-resources.d.ts +33 -0
  22. package/dist/locale/fr/locale-resources.d.ts.map +1 -0
  23. package/dist/locale/fr/locale-resources.js +32 -0
  24. package/dist/locale/fr/locale-resources.js.map +1 -0
  25. package/dist/locale/i18n.d.ts +27 -0
  26. package/dist/locale/i18n.d.ts.map +1 -0
  27. package/dist/locale/i18n.js +34 -0
  28. package/dist/locale/i18n.js.map +1 -0
  29. package/dist/record.d.ts +44 -0
  30. package/dist/record.d.ts.map +1 -0
  31. package/dist/record.js +58 -0
  32. package/dist/record.js.map +1 -0
  33. package/dist/reg-exp.d.ts +43 -0
  34. package/dist/reg-exp.d.ts.map +1 -0
  35. package/dist/reg-exp.js +55 -0
  36. package/dist/reg-exp.js.map +1 -0
  37. package/dist/sequence.d.ts +68 -0
  38. package/dist/sequence.d.ts.map +1 -0
  39. package/dist/sequence.js +96 -0
  40. package/dist/sequence.js.map +1 -0
  41. package/dist/string.d.ts +25 -0
  42. package/dist/string.d.ts.map +1 -0
  43. package/dist/string.js +2 -0
  44. package/dist/string.js.map +1 -0
  45. package/dist/transformer.d.ts +347 -0
  46. package/dist/transformer.d.ts.map +1 -0
  47. package/dist/transformer.js +457 -0
  48. package/dist/transformer.js.map +1 -0
  49. package/package.json +11 -7
  50. package/src/character-set.ts +20 -19
  51. package/src/exclusion.ts +6 -1
  52. package/src/index.ts +9 -9
  53. package/src/locale/i18n.ts +3 -3
  54. package/src/locale/i18next.d.ts +1 -1
  55. package/src/record.ts +2 -2
  56. package/src/reg-exp.ts +7 -7
  57. package/src/string.ts +3 -3
  58. package/src/transformer.ts +19 -18
  59. package/test/character-set.test.ts +1 -1
  60. package/test/record.test.ts +4 -2
  61. package/test/reg-exp.test.ts +1 -1
  62. package/test/sequence.test.ts +1 -1
  63. package/test/setup.ts +1 -1
  64. package/test/transformer.test.ts +1 -1
  65. package/tsconfig-config.json +4 -0
  66. package/tsconfig-src.json +8 -0
  67. package/tsconfig-test.json +9 -0
  68. package/tsconfig.json +12 -1
  69. package/tsup.config.ts +3 -2
  70. package/dist/index.cjs +0 -3569
  71. package/dist/index.cjs.map +0 -1
  72. package/dist/index.d.cts +0 -947
package/dist/index.cjs DELETED
@@ -1,3569 +0,0 @@
1
- "use strict";
2
- var __defProp = Object.defineProperty;
3
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
- var __getOwnPropNames = Object.getOwnPropertyNames;
5
- var __hasOwnProp = Object.prototype.hasOwnProperty;
6
- var __export = (target, all) => {
7
- for (var name in all)
8
- __defProp(target, name, { get: all[name], enumerable: true });
9
- };
10
- var __copyProps = (to, from, except, desc) => {
11
- if (from && typeof from === "object" || typeof from === "function") {
12
- for (let key of __getOwnPropNames(from))
13
- if (!__hasOwnProp.call(to, key) && key !== except)
14
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
- }
16
- return to;
17
- };
18
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
-
20
- // src/index.ts
21
- var index_exports = {};
22
- __export(index_exports, {
23
- ALPHABETIC_CREATOR: () => ALPHABETIC_CREATOR,
24
- ALPHABETIC_VALIDATOR: () => ALPHABETIC_VALIDATOR,
25
- ALPHANUMERIC_CREATOR: () => ALPHANUMERIC_CREATOR,
26
- ALPHANUMERIC_VALIDATOR: () => ALPHANUMERIC_VALIDATOR,
27
- CharacterSetCreator: () => CharacterSetCreator,
28
- CharacterSetValidator: () => CharacterSetValidator,
29
- EncryptionTransformer: () => EncryptionTransformer,
30
- Exclusions: () => Exclusions,
31
- HEXADECIMAL_CREATOR: () => HEXADECIMAL_CREATOR,
32
- HEXADECIMAL_VALIDATOR: () => HEXADECIMAL_VALIDATOR,
33
- IdentityTransformer: () => IdentityTransformer,
34
- NUMERIC_CREATOR: () => NUMERIC_CREATOR,
35
- NUMERIC_VALIDATOR: () => NUMERIC_VALIDATOR,
36
- RecordValidator: () => RecordValidator,
37
- RegExpValidator: () => RegExpValidator,
38
- Sequence: () => Sequence,
39
- Transformer: () => Transformer,
40
- i18nUtilityInit: () => i18nUtilityInit,
41
- i18nextUtility: () => i18nextUtility,
42
- mapIterable: () => mapIterable,
43
- utilityNS: () => utilityNS,
44
- utilityResources: () => utilityResources
45
- });
46
- module.exports = __toCommonJS(index_exports);
47
-
48
- // src/locale/i18n.ts
49
- var import_core = require("@aidc-toolkit/core");
50
-
51
- // node_modules/i18next/dist/esm/i18next.js
52
- var isString = (obj) => typeof obj === "string";
53
- var defer = () => {
54
- let res;
55
- let rej;
56
- const promise = new Promise((resolve, reject) => {
57
- res = resolve;
58
- rej = reject;
59
- });
60
- promise.resolve = res;
61
- promise.reject = rej;
62
- return promise;
63
- };
64
- var makeString = (object) => {
65
- if (object == null) return "";
66
- return "" + object;
67
- };
68
- var copy = (a, s, t2) => {
69
- a.forEach((m) => {
70
- if (s[m]) t2[m] = s[m];
71
- });
72
- };
73
- var lastOfPathSeparatorRegExp = /###/g;
74
- var cleanKey = (key) => key && key.indexOf("###") > -1 ? key.replace(lastOfPathSeparatorRegExp, ".") : key;
75
- var canNotTraverseDeeper = (object) => !object || isString(object);
76
- var getLastOfPath = (object, path, Empty) => {
77
- const stack = !isString(path) ? path : path.split(".");
78
- let stackIndex = 0;
79
- while (stackIndex < stack.length - 1) {
80
- if (canNotTraverseDeeper(object)) return {};
81
- const key = cleanKey(stack[stackIndex]);
82
- if (!object[key] && Empty) object[key] = new Empty();
83
- if (Object.prototype.hasOwnProperty.call(object, key)) {
84
- object = object[key];
85
- } else {
86
- object = {};
87
- }
88
- ++stackIndex;
89
- }
90
- if (canNotTraverseDeeper(object)) return {};
91
- return {
92
- obj: object,
93
- k: cleanKey(stack[stackIndex])
94
- };
95
- };
96
- var setPath = (object, path, newValue) => {
97
- const {
98
- obj,
99
- k
100
- } = getLastOfPath(object, path, Object);
101
- if (obj !== void 0 || path.length === 1) {
102
- obj[k] = newValue;
103
- return;
104
- }
105
- let e = path[path.length - 1];
106
- let p = path.slice(0, path.length - 1);
107
- let last = getLastOfPath(object, p, Object);
108
- while (last.obj === void 0 && p.length) {
109
- e = `${p[p.length - 1]}.${e}`;
110
- p = p.slice(0, p.length - 1);
111
- last = getLastOfPath(object, p, Object);
112
- if (last?.obj && typeof last.obj[`${last.k}.${e}`] !== "undefined") {
113
- last.obj = void 0;
114
- }
115
- }
116
- last.obj[`${last.k}.${e}`] = newValue;
117
- };
118
- var pushPath = (object, path, newValue, concat) => {
119
- const {
120
- obj,
121
- k
122
- } = getLastOfPath(object, path, Object);
123
- obj[k] = obj[k] || [];
124
- obj[k].push(newValue);
125
- };
126
- var getPath = (object, path) => {
127
- const {
128
- obj,
129
- k
130
- } = getLastOfPath(object, path);
131
- if (!obj) return void 0;
132
- if (!Object.prototype.hasOwnProperty.call(obj, k)) return void 0;
133
- return obj[k];
134
- };
135
- var getPathWithDefaults = (data, defaultData, key) => {
136
- const value = getPath(data, key);
137
- if (value !== void 0) {
138
- return value;
139
- }
140
- return getPath(defaultData, key);
141
- };
142
- var deepExtend = (target, source, overwrite) => {
143
- for (const prop in source) {
144
- if (prop !== "__proto__" && prop !== "constructor") {
145
- if (prop in target) {
146
- if (isString(target[prop]) || target[prop] instanceof String || isString(source[prop]) || source[prop] instanceof String) {
147
- if (overwrite) target[prop] = source[prop];
148
- } else {
149
- deepExtend(target[prop], source[prop], overwrite);
150
- }
151
- } else {
152
- target[prop] = source[prop];
153
- }
154
- }
155
- }
156
- return target;
157
- };
158
- var regexEscape = (str) => str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
159
- var _entityMap = {
160
- "&": "&amp;",
161
- "<": "&lt;",
162
- ">": "&gt;",
163
- '"': "&quot;",
164
- "'": "&#39;",
165
- "/": "&#x2F;"
166
- };
167
- var escape = (data) => {
168
- if (isString(data)) {
169
- return data.replace(/[&<>"'\/]/g, (s) => _entityMap[s]);
170
- }
171
- return data;
172
- };
173
- var RegExpCache = class {
174
- constructor(capacity) {
175
- this.capacity = capacity;
176
- this.regExpMap = /* @__PURE__ */ new Map();
177
- this.regExpQueue = [];
178
- }
179
- getRegExp(pattern) {
180
- const regExpFromCache = this.regExpMap.get(pattern);
181
- if (regExpFromCache !== void 0) {
182
- return regExpFromCache;
183
- }
184
- const regExpNew = new RegExp(pattern);
185
- if (this.regExpQueue.length === this.capacity) {
186
- this.regExpMap.delete(this.regExpQueue.shift());
187
- }
188
- this.regExpMap.set(pattern, regExpNew);
189
- this.regExpQueue.push(pattern);
190
- return regExpNew;
191
- }
192
- };
193
- var chars = [" ", ",", "?", "!", ";"];
194
- var looksLikeObjectPathRegExpCache = new RegExpCache(20);
195
- var looksLikeObjectPath = (key, nsSeparator, keySeparator) => {
196
- nsSeparator = nsSeparator || "";
197
- keySeparator = keySeparator || "";
198
- const possibleChars = chars.filter((c) => nsSeparator.indexOf(c) < 0 && keySeparator.indexOf(c) < 0);
199
- if (possibleChars.length === 0) return true;
200
- const r = looksLikeObjectPathRegExpCache.getRegExp(`(${possibleChars.map((c) => c === "?" ? "\\?" : c).join("|")})`);
201
- let matched = !r.test(key);
202
- if (!matched) {
203
- const ki = key.indexOf(keySeparator);
204
- if (ki > 0 && !r.test(key.substring(0, ki))) {
205
- matched = true;
206
- }
207
- }
208
- return matched;
209
- };
210
- var deepFind = (obj, path, keySeparator = ".") => {
211
- if (!obj) return void 0;
212
- if (obj[path]) {
213
- if (!Object.prototype.hasOwnProperty.call(obj, path)) return void 0;
214
- return obj[path];
215
- }
216
- const tokens = path.split(keySeparator);
217
- let current = obj;
218
- for (let i = 0; i < tokens.length; ) {
219
- if (!current || typeof current !== "object") {
220
- return void 0;
221
- }
222
- let next;
223
- let nextPath = "";
224
- for (let j = i; j < tokens.length; ++j) {
225
- if (j !== i) {
226
- nextPath += keySeparator;
227
- }
228
- nextPath += tokens[j];
229
- next = current[nextPath];
230
- if (next !== void 0) {
231
- if (["string", "number", "boolean"].indexOf(typeof next) > -1 && j < tokens.length - 1) {
232
- continue;
233
- }
234
- i += j - i + 1;
235
- break;
236
- }
237
- }
238
- current = next;
239
- }
240
- return current;
241
- };
242
- var getCleanedCode = (code) => code?.replace("_", "-");
243
- var consoleLogger = {
244
- type: "logger",
245
- log(args) {
246
- this.output("log", args);
247
- },
248
- warn(args) {
249
- this.output("warn", args);
250
- },
251
- error(args) {
252
- this.output("error", args);
253
- },
254
- output(type, args) {
255
- console?.[type]?.apply?.(console, args);
256
- }
257
- };
258
- var Logger = class _Logger {
259
- constructor(concreteLogger, options = {}) {
260
- this.init(concreteLogger, options);
261
- }
262
- init(concreteLogger, options = {}) {
263
- this.prefix = options.prefix || "i18next:";
264
- this.logger = concreteLogger || consoleLogger;
265
- this.options = options;
266
- this.debug = options.debug;
267
- }
268
- log(...args) {
269
- return this.forward(args, "log", "", true);
270
- }
271
- warn(...args) {
272
- return this.forward(args, "warn", "", true);
273
- }
274
- error(...args) {
275
- return this.forward(args, "error", "");
276
- }
277
- deprecate(...args) {
278
- return this.forward(args, "warn", "WARNING DEPRECATED: ", true);
279
- }
280
- forward(args, lvl, prefix, debugOnly) {
281
- if (debugOnly && !this.debug) return null;
282
- if (isString(args[0])) args[0] = `${prefix}${this.prefix} ${args[0]}`;
283
- return this.logger[lvl](args);
284
- }
285
- create(moduleName) {
286
- return new _Logger(this.logger, {
287
- ...{
288
- prefix: `${this.prefix}:${moduleName}:`
289
- },
290
- ...this.options
291
- });
292
- }
293
- clone(options) {
294
- options = options || this.options;
295
- options.prefix = options.prefix || this.prefix;
296
- return new _Logger(this.logger, options);
297
- }
298
- };
299
- var baseLogger = new Logger();
300
- var EventEmitter = class {
301
- constructor() {
302
- this.observers = {};
303
- }
304
- on(events, listener) {
305
- events.split(" ").forEach((event) => {
306
- if (!this.observers[event]) this.observers[event] = /* @__PURE__ */ new Map();
307
- const numListeners = this.observers[event].get(listener) || 0;
308
- this.observers[event].set(listener, numListeners + 1);
309
- });
310
- return this;
311
- }
312
- off(event, listener) {
313
- if (!this.observers[event]) return;
314
- if (!listener) {
315
- delete this.observers[event];
316
- return;
317
- }
318
- this.observers[event].delete(listener);
319
- }
320
- emit(event, ...args) {
321
- if (this.observers[event]) {
322
- const cloned = Array.from(this.observers[event].entries());
323
- cloned.forEach(([observer, numTimesAdded]) => {
324
- for (let i = 0; i < numTimesAdded; i++) {
325
- observer(...args);
326
- }
327
- });
328
- }
329
- if (this.observers["*"]) {
330
- const cloned = Array.from(this.observers["*"].entries());
331
- cloned.forEach(([observer, numTimesAdded]) => {
332
- for (let i = 0; i < numTimesAdded; i++) {
333
- observer.apply(observer, [event, ...args]);
334
- }
335
- });
336
- }
337
- }
338
- };
339
- var ResourceStore = class extends EventEmitter {
340
- constructor(data, options = {
341
- ns: ["translation"],
342
- defaultNS: "translation"
343
- }) {
344
- super();
345
- this.data = data || {};
346
- this.options = options;
347
- if (this.options.keySeparator === void 0) {
348
- this.options.keySeparator = ".";
349
- }
350
- if (this.options.ignoreJSONStructure === void 0) {
351
- this.options.ignoreJSONStructure = true;
352
- }
353
- }
354
- addNamespaces(ns) {
355
- if (this.options.ns.indexOf(ns) < 0) {
356
- this.options.ns.push(ns);
357
- }
358
- }
359
- removeNamespaces(ns) {
360
- const index = this.options.ns.indexOf(ns);
361
- if (index > -1) {
362
- this.options.ns.splice(index, 1);
363
- }
364
- }
365
- getResource(lng, ns, key, options = {}) {
366
- const keySeparator = options.keySeparator !== void 0 ? options.keySeparator : this.options.keySeparator;
367
- const ignoreJSONStructure = options.ignoreJSONStructure !== void 0 ? options.ignoreJSONStructure : this.options.ignoreJSONStructure;
368
- let path;
369
- if (lng.indexOf(".") > -1) {
370
- path = lng.split(".");
371
- } else {
372
- path = [lng, ns];
373
- if (key) {
374
- if (Array.isArray(key)) {
375
- path.push(...key);
376
- } else if (isString(key) && keySeparator) {
377
- path.push(...key.split(keySeparator));
378
- } else {
379
- path.push(key);
380
- }
381
- }
382
- }
383
- const result = getPath(this.data, path);
384
- if (!result && !ns && !key && lng.indexOf(".") > -1) {
385
- lng = path[0];
386
- ns = path[1];
387
- key = path.slice(2).join(".");
388
- }
389
- if (result || !ignoreJSONStructure || !isString(key)) return result;
390
- return deepFind(this.data?.[lng]?.[ns], key, keySeparator);
391
- }
392
- addResource(lng, ns, key, value, options = {
393
- silent: false
394
- }) {
395
- const keySeparator = options.keySeparator !== void 0 ? options.keySeparator : this.options.keySeparator;
396
- let path = [lng, ns];
397
- if (key) path = path.concat(keySeparator ? key.split(keySeparator) : key);
398
- if (lng.indexOf(".") > -1) {
399
- path = lng.split(".");
400
- value = ns;
401
- ns = path[1];
402
- }
403
- this.addNamespaces(ns);
404
- setPath(this.data, path, value);
405
- if (!options.silent) this.emit("added", lng, ns, key, value);
406
- }
407
- addResources(lng, ns, resources, options = {
408
- silent: false
409
- }) {
410
- for (const m in resources) {
411
- if (isString(resources[m]) || Array.isArray(resources[m])) this.addResource(lng, ns, m, resources[m], {
412
- silent: true
413
- });
414
- }
415
- if (!options.silent) this.emit("added", lng, ns, resources);
416
- }
417
- addResourceBundle(lng, ns, resources, deep, overwrite, options = {
418
- silent: false,
419
- skipCopy: false
420
- }) {
421
- let path = [lng, ns];
422
- if (lng.indexOf(".") > -1) {
423
- path = lng.split(".");
424
- deep = resources;
425
- resources = ns;
426
- ns = path[1];
427
- }
428
- this.addNamespaces(ns);
429
- let pack = getPath(this.data, path) || {};
430
- if (!options.skipCopy) resources = JSON.parse(JSON.stringify(resources));
431
- if (deep) {
432
- deepExtend(pack, resources, overwrite);
433
- } else {
434
- pack = {
435
- ...pack,
436
- ...resources
437
- };
438
- }
439
- setPath(this.data, path, pack);
440
- if (!options.silent) this.emit("added", lng, ns, resources);
441
- }
442
- removeResourceBundle(lng, ns) {
443
- if (this.hasResourceBundle(lng, ns)) {
444
- delete this.data[lng][ns];
445
- }
446
- this.removeNamespaces(ns);
447
- this.emit("removed", lng, ns);
448
- }
449
- hasResourceBundle(lng, ns) {
450
- return this.getResource(lng, ns) !== void 0;
451
- }
452
- getResourceBundle(lng, ns) {
453
- if (!ns) ns = this.options.defaultNS;
454
- return this.getResource(lng, ns);
455
- }
456
- getDataByLanguage(lng) {
457
- return this.data[lng];
458
- }
459
- hasLanguageSomeTranslations(lng) {
460
- const data = this.getDataByLanguage(lng);
461
- const n = data && Object.keys(data) || [];
462
- return !!n.find((v) => data[v] && Object.keys(data[v]).length > 0);
463
- }
464
- toJSON() {
465
- return this.data;
466
- }
467
- };
468
- var postProcessor = {
469
- processors: {},
470
- addPostProcessor(module2) {
471
- this.processors[module2.name] = module2;
472
- },
473
- handle(processors, value, key, options, translator) {
474
- processors.forEach((processor) => {
475
- value = this.processors[processor]?.process(value, key, options, translator) ?? value;
476
- });
477
- return value;
478
- }
479
- };
480
- var PATH_KEY = Symbol("i18next/PATH_KEY");
481
- function createProxy() {
482
- const state = [];
483
- const handler = /* @__PURE__ */ Object.create(null);
484
- let proxy;
485
- handler.get = (target, key) => {
486
- proxy?.revoke?.();
487
- if (key === PATH_KEY) return state;
488
- state.push(key);
489
- proxy = Proxy.revocable(target, handler);
490
- return proxy.proxy;
491
- };
492
- return Proxy.revocable(/* @__PURE__ */ Object.create(null), handler).proxy;
493
- }
494
- function keysFromSelector(selector, opts) {
495
- const {
496
- [PATH_KEY]: path
497
- } = selector(createProxy());
498
- return path.join(opts?.keySeparator ?? ".");
499
- }
500
- var checkedLoadedFor = {};
501
- var shouldHandleAsObject = (res) => !isString(res) && typeof res !== "boolean" && typeof res !== "number";
502
- var Translator = class _Translator extends EventEmitter {
503
- constructor(services, options = {}) {
504
- super();
505
- copy(["resourceStore", "languageUtils", "pluralResolver", "interpolator", "backendConnector", "i18nFormat", "utils"], services, this);
506
- this.options = options;
507
- if (this.options.keySeparator === void 0) {
508
- this.options.keySeparator = ".";
509
- }
510
- this.logger = baseLogger.create("translator");
511
- }
512
- changeLanguage(lng) {
513
- if (lng) this.language = lng;
514
- }
515
- exists(key, o = {
516
- interpolation: {}
517
- }) {
518
- const opt = {
519
- ...o
520
- };
521
- if (key == null) return false;
522
- const resolved = this.resolve(key, opt);
523
- if (resolved?.res === void 0) return false;
524
- const isObject = shouldHandleAsObject(resolved.res);
525
- if (opt.returnObjects === false && isObject) {
526
- return false;
527
- }
528
- return true;
529
- }
530
- extractFromKey(key, opt) {
531
- let nsSeparator = opt.nsSeparator !== void 0 ? opt.nsSeparator : this.options.nsSeparator;
532
- if (nsSeparator === void 0) nsSeparator = ":";
533
- const keySeparator = opt.keySeparator !== void 0 ? opt.keySeparator : this.options.keySeparator;
534
- let namespaces = opt.ns || this.options.defaultNS || [];
535
- const wouldCheckForNsInKey = nsSeparator && key.indexOf(nsSeparator) > -1;
536
- const seemsNaturalLanguage = !this.options.userDefinedKeySeparator && !opt.keySeparator && !this.options.userDefinedNsSeparator && !opt.nsSeparator && !looksLikeObjectPath(key, nsSeparator, keySeparator);
537
- if (wouldCheckForNsInKey && !seemsNaturalLanguage) {
538
- const m = key.match(this.interpolator.nestingRegexp);
539
- if (m && m.length > 0) {
540
- return {
541
- key,
542
- namespaces: isString(namespaces) ? [namespaces] : namespaces
543
- };
544
- }
545
- const parts = key.split(nsSeparator);
546
- if (nsSeparator !== keySeparator || nsSeparator === keySeparator && this.options.ns.indexOf(parts[0]) > -1) namespaces = parts.shift();
547
- key = parts.join(keySeparator);
548
- }
549
- return {
550
- key,
551
- namespaces: isString(namespaces) ? [namespaces] : namespaces
552
- };
553
- }
554
- translate(keys, o, lastKey) {
555
- let opt = typeof o === "object" ? {
556
- ...o
557
- } : o;
558
- if (typeof opt !== "object" && this.options.overloadTranslationOptionHandler) {
559
- opt = this.options.overloadTranslationOptionHandler(arguments);
560
- }
561
- if (typeof opt === "object") opt = {
562
- ...opt
563
- };
564
- if (!opt) opt = {};
565
- if (keys == null) return "";
566
- if (typeof keys === "function") keys = keysFromSelector(keys, {
567
- ...this.options,
568
- ...opt
569
- });
570
- if (!Array.isArray(keys)) keys = [String(keys)];
571
- const returnDetails = opt.returnDetails !== void 0 ? opt.returnDetails : this.options.returnDetails;
572
- const keySeparator = opt.keySeparator !== void 0 ? opt.keySeparator : this.options.keySeparator;
573
- const {
574
- key,
575
- namespaces
576
- } = this.extractFromKey(keys[keys.length - 1], opt);
577
- const namespace = namespaces[namespaces.length - 1];
578
- let nsSeparator = opt.nsSeparator !== void 0 ? opt.nsSeparator : this.options.nsSeparator;
579
- if (nsSeparator === void 0) nsSeparator = ":";
580
- const lng = opt.lng || this.language;
581
- const appendNamespaceToCIMode = opt.appendNamespaceToCIMode || this.options.appendNamespaceToCIMode;
582
- if (lng?.toLowerCase() === "cimode") {
583
- if (appendNamespaceToCIMode) {
584
- if (returnDetails) {
585
- return {
586
- res: `${namespace}${nsSeparator}${key}`,
587
- usedKey: key,
588
- exactUsedKey: key,
589
- usedLng: lng,
590
- usedNS: namespace,
591
- usedParams: this.getUsedParamsDetails(opt)
592
- };
593
- }
594
- return `${namespace}${nsSeparator}${key}`;
595
- }
596
- if (returnDetails) {
597
- return {
598
- res: key,
599
- usedKey: key,
600
- exactUsedKey: key,
601
- usedLng: lng,
602
- usedNS: namespace,
603
- usedParams: this.getUsedParamsDetails(opt)
604
- };
605
- }
606
- return key;
607
- }
608
- const resolved = this.resolve(keys, opt);
609
- let res = resolved?.res;
610
- const resUsedKey = resolved?.usedKey || key;
611
- const resExactUsedKey = resolved?.exactUsedKey || key;
612
- const noObject = ["[object Number]", "[object Function]", "[object RegExp]"];
613
- const joinArrays = opt.joinArrays !== void 0 ? opt.joinArrays : this.options.joinArrays;
614
- const handleAsObjectInI18nFormat = !this.i18nFormat || this.i18nFormat.handleAsObject;
615
- const needsPluralHandling = opt.count !== void 0 && !isString(opt.count);
616
- const hasDefaultValue = _Translator.hasDefaultValue(opt);
617
- const defaultValueSuffix = needsPluralHandling ? this.pluralResolver.getSuffix(lng, opt.count, opt) : "";
618
- const defaultValueSuffixOrdinalFallback = opt.ordinal && needsPluralHandling ? this.pluralResolver.getSuffix(lng, opt.count, {
619
- ordinal: false
620
- }) : "";
621
- const needsZeroSuffixLookup = needsPluralHandling && !opt.ordinal && opt.count === 0;
622
- const defaultValue = needsZeroSuffixLookup && opt[`defaultValue${this.options.pluralSeparator}zero`] || opt[`defaultValue${defaultValueSuffix}`] || opt[`defaultValue${defaultValueSuffixOrdinalFallback}`] || opt.defaultValue;
623
- let resForObjHndl = res;
624
- if (handleAsObjectInI18nFormat && !res && hasDefaultValue) {
625
- resForObjHndl = defaultValue;
626
- }
627
- const handleAsObject = shouldHandleAsObject(resForObjHndl);
628
- const resType = Object.prototype.toString.apply(resForObjHndl);
629
- if (handleAsObjectInI18nFormat && resForObjHndl && handleAsObject && noObject.indexOf(resType) < 0 && !(isString(joinArrays) && Array.isArray(resForObjHndl))) {
630
- if (!opt.returnObjects && !this.options.returnObjects) {
631
- if (!this.options.returnedObjectHandler) {
632
- this.logger.warn("accessing an object - but returnObjects options is not enabled!");
633
- }
634
- const r = this.options.returnedObjectHandler ? this.options.returnedObjectHandler(resUsedKey, resForObjHndl, {
635
- ...opt,
636
- ns: namespaces
637
- }) : `key '${key} (${this.language})' returned an object instead of string.`;
638
- if (returnDetails) {
639
- resolved.res = r;
640
- resolved.usedParams = this.getUsedParamsDetails(opt);
641
- return resolved;
642
- }
643
- return r;
644
- }
645
- if (keySeparator) {
646
- const resTypeIsArray = Array.isArray(resForObjHndl);
647
- const copy2 = resTypeIsArray ? [] : {};
648
- const newKeyToUse = resTypeIsArray ? resExactUsedKey : resUsedKey;
649
- for (const m in resForObjHndl) {
650
- if (Object.prototype.hasOwnProperty.call(resForObjHndl, m)) {
651
- const deepKey = `${newKeyToUse}${keySeparator}${m}`;
652
- if (hasDefaultValue && !res) {
653
- copy2[m] = this.translate(deepKey, {
654
- ...opt,
655
- defaultValue: shouldHandleAsObject(defaultValue) ? defaultValue[m] : void 0,
656
- ...{
657
- joinArrays: false,
658
- ns: namespaces
659
- }
660
- });
661
- } else {
662
- copy2[m] = this.translate(deepKey, {
663
- ...opt,
664
- ...{
665
- joinArrays: false,
666
- ns: namespaces
667
- }
668
- });
669
- }
670
- if (copy2[m] === deepKey) copy2[m] = resForObjHndl[m];
671
- }
672
- }
673
- res = copy2;
674
- }
675
- } else if (handleAsObjectInI18nFormat && isString(joinArrays) && Array.isArray(res)) {
676
- res = res.join(joinArrays);
677
- if (res) res = this.extendTranslation(res, keys, opt, lastKey);
678
- } else {
679
- let usedDefault = false;
680
- let usedKey = false;
681
- if (!this.isValidLookup(res) && hasDefaultValue) {
682
- usedDefault = true;
683
- res = defaultValue;
684
- }
685
- if (!this.isValidLookup(res)) {
686
- usedKey = true;
687
- res = key;
688
- }
689
- const missingKeyNoValueFallbackToKey = opt.missingKeyNoValueFallbackToKey || this.options.missingKeyNoValueFallbackToKey;
690
- const resForMissing = missingKeyNoValueFallbackToKey && usedKey ? void 0 : res;
691
- const updateMissing = hasDefaultValue && defaultValue !== res && this.options.updateMissing;
692
- if (usedKey || usedDefault || updateMissing) {
693
- this.logger.log(updateMissing ? "updateKey" : "missingKey", lng, namespace, key, updateMissing ? defaultValue : res);
694
- if (keySeparator) {
695
- const fk = this.resolve(key, {
696
- ...opt,
697
- keySeparator: false
698
- });
699
- 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.");
700
- }
701
- let lngs = [];
702
- const fallbackLngs = this.languageUtils.getFallbackCodes(this.options.fallbackLng, opt.lng || this.language);
703
- if (this.options.saveMissingTo === "fallback" && fallbackLngs && fallbackLngs[0]) {
704
- for (let i = 0; i < fallbackLngs.length; i++) {
705
- lngs.push(fallbackLngs[i]);
706
- }
707
- } else if (this.options.saveMissingTo === "all") {
708
- lngs = this.languageUtils.toResolveHierarchy(opt.lng || this.language);
709
- } else {
710
- lngs.push(opt.lng || this.language);
711
- }
712
- const send = (l, k, specificDefaultValue) => {
713
- const defaultForMissing = hasDefaultValue && specificDefaultValue !== res ? specificDefaultValue : resForMissing;
714
- if (this.options.missingKeyHandler) {
715
- this.options.missingKeyHandler(l, namespace, k, defaultForMissing, updateMissing, opt);
716
- } else if (this.backendConnector?.saveMissing) {
717
- this.backendConnector.saveMissing(l, namespace, k, defaultForMissing, updateMissing, opt);
718
- }
719
- this.emit("missingKey", l, namespace, k, res);
720
- };
721
- if (this.options.saveMissing) {
722
- if (this.options.saveMissingPlurals && needsPluralHandling) {
723
- lngs.forEach((language) => {
724
- const suffixes = this.pluralResolver.getSuffixes(language, opt);
725
- if (needsZeroSuffixLookup && opt[`defaultValue${this.options.pluralSeparator}zero`] && suffixes.indexOf(`${this.options.pluralSeparator}zero`) < 0) {
726
- suffixes.push(`${this.options.pluralSeparator}zero`);
727
- }
728
- suffixes.forEach((suffix) => {
729
- send([language], key + suffix, opt[`defaultValue${suffix}`] || defaultValue);
730
- });
731
- });
732
- } else {
733
- send(lngs, key, defaultValue);
734
- }
735
- }
736
- }
737
- res = this.extendTranslation(res, keys, opt, resolved, lastKey);
738
- if (usedKey && res === key && this.options.appendNamespaceToMissingKey) {
739
- res = `${namespace}${nsSeparator}${key}`;
740
- }
741
- if ((usedKey || usedDefault) && this.options.parseMissingKeyHandler) {
742
- res = this.options.parseMissingKeyHandler(this.options.appendNamespaceToMissingKey ? `${namespace}${nsSeparator}${key}` : key, usedDefault ? res : void 0, opt);
743
- }
744
- }
745
- if (returnDetails) {
746
- resolved.res = res;
747
- resolved.usedParams = this.getUsedParamsDetails(opt);
748
- return resolved;
749
- }
750
- return res;
751
- }
752
- extendTranslation(res, key, opt, resolved, lastKey) {
753
- if (this.i18nFormat?.parse) {
754
- res = this.i18nFormat.parse(res, {
755
- ...this.options.interpolation.defaultVariables,
756
- ...opt
757
- }, opt.lng || this.language || resolved.usedLng, resolved.usedNS, resolved.usedKey, {
758
- resolved
759
- });
760
- } else if (!opt.skipInterpolation) {
761
- if (opt.interpolation) this.interpolator.init({
762
- ...opt,
763
- ...{
764
- interpolation: {
765
- ...this.options.interpolation,
766
- ...opt.interpolation
767
- }
768
- }
769
- });
770
- const skipOnVariables = isString(res) && (opt?.interpolation?.skipOnVariables !== void 0 ? opt.interpolation.skipOnVariables : this.options.interpolation.skipOnVariables);
771
- let nestBef;
772
- if (skipOnVariables) {
773
- const nb = res.match(this.interpolator.nestingRegexp);
774
- nestBef = nb && nb.length;
775
- }
776
- let data = opt.replace && !isString(opt.replace) ? opt.replace : opt;
777
- if (this.options.interpolation.defaultVariables) data = {
778
- ...this.options.interpolation.defaultVariables,
779
- ...data
780
- };
781
- res = this.interpolator.interpolate(res, data, opt.lng || this.language || resolved.usedLng, opt);
782
- if (skipOnVariables) {
783
- const na = res.match(this.interpolator.nestingRegexp);
784
- const nestAft = na && na.length;
785
- if (nestBef < nestAft) opt.nest = false;
786
- }
787
- if (!opt.lng && resolved && resolved.res) opt.lng = this.language || resolved.usedLng;
788
- if (opt.nest !== false) res = this.interpolator.nest(res, (...args) => {
789
- if (lastKey?.[0] === args[0] && !opt.context) {
790
- this.logger.warn(`It seems you are nesting recursively key: ${args[0]} in key: ${key[0]}`);
791
- return null;
792
- }
793
- return this.translate(...args, key);
794
- }, opt);
795
- if (opt.interpolation) this.interpolator.reset();
796
- }
797
- const postProcess = opt.postProcess || this.options.postProcess;
798
- const postProcessorNames = isString(postProcess) ? [postProcess] : postProcess;
799
- if (res != null && postProcessorNames?.length && opt.applyPostProcessor !== false) {
800
- res = postProcessor.handle(postProcessorNames, res, key, this.options && this.options.postProcessPassResolved ? {
801
- i18nResolved: {
802
- ...resolved,
803
- usedParams: this.getUsedParamsDetails(opt)
804
- },
805
- ...opt
806
- } : opt, this);
807
- }
808
- return res;
809
- }
810
- resolve(keys, opt = {}) {
811
- let found;
812
- let usedKey;
813
- let exactUsedKey;
814
- let usedLng;
815
- let usedNS;
816
- if (isString(keys)) keys = [keys];
817
- keys.forEach((k) => {
818
- if (this.isValidLookup(found)) return;
819
- const extracted = this.extractFromKey(k, opt);
820
- const key = extracted.key;
821
- usedKey = key;
822
- let namespaces = extracted.namespaces;
823
- if (this.options.fallbackNS) namespaces = namespaces.concat(this.options.fallbackNS);
824
- const needsPluralHandling = opt.count !== void 0 && !isString(opt.count);
825
- const needsZeroSuffixLookup = needsPluralHandling && !opt.ordinal && opt.count === 0;
826
- const needsContextHandling = opt.context !== void 0 && (isString(opt.context) || typeof opt.context === "number") && opt.context !== "";
827
- const codes = opt.lngs ? opt.lngs : this.languageUtils.toResolveHierarchy(opt.lng || this.language, opt.fallbackLng);
828
- namespaces.forEach((ns) => {
829
- if (this.isValidLookup(found)) return;
830
- usedNS = ns;
831
- if (!checkedLoadedFor[`${codes[0]}-${ns}`] && this.utils?.hasLoadedNamespace && !this.utils?.hasLoadedNamespace(usedNS)) {
832
- checkedLoadedFor[`${codes[0]}-${ns}`] = true;
833
- 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!!!");
834
- }
835
- codes.forEach((code) => {
836
- if (this.isValidLookup(found)) return;
837
- usedLng = code;
838
- const finalKeys = [key];
839
- if (this.i18nFormat?.addLookupKeys) {
840
- this.i18nFormat.addLookupKeys(finalKeys, key, code, ns, opt);
841
- } else {
842
- let pluralSuffix;
843
- if (needsPluralHandling) pluralSuffix = this.pluralResolver.getSuffix(code, opt.count, opt);
844
- const zeroSuffix = `${this.options.pluralSeparator}zero`;
845
- const ordinalPrefix = `${this.options.pluralSeparator}ordinal${this.options.pluralSeparator}`;
846
- if (needsPluralHandling) {
847
- if (opt.ordinal && pluralSuffix.indexOf(ordinalPrefix) === 0) {
848
- finalKeys.push(key + pluralSuffix.replace(ordinalPrefix, this.options.pluralSeparator));
849
- }
850
- finalKeys.push(key + pluralSuffix);
851
- if (needsZeroSuffixLookup) {
852
- finalKeys.push(key + zeroSuffix);
853
- }
854
- }
855
- if (needsContextHandling) {
856
- const contextKey = `${key}${this.options.contextSeparator || "_"}${opt.context}`;
857
- finalKeys.push(contextKey);
858
- if (needsPluralHandling) {
859
- if (opt.ordinal && pluralSuffix.indexOf(ordinalPrefix) === 0) {
860
- finalKeys.push(contextKey + pluralSuffix.replace(ordinalPrefix, this.options.pluralSeparator));
861
- }
862
- finalKeys.push(contextKey + pluralSuffix);
863
- if (needsZeroSuffixLookup) {
864
- finalKeys.push(contextKey + zeroSuffix);
865
- }
866
- }
867
- }
868
- }
869
- let possibleKey;
870
- while (possibleKey = finalKeys.pop()) {
871
- if (!this.isValidLookup(found)) {
872
- exactUsedKey = possibleKey;
873
- found = this.getResource(code, ns, possibleKey, opt);
874
- }
875
- }
876
- });
877
- });
878
- });
879
- return {
880
- res: found,
881
- usedKey,
882
- exactUsedKey,
883
- usedLng,
884
- usedNS
885
- };
886
- }
887
- isValidLookup(res) {
888
- return res !== void 0 && !(!this.options.returnNull && res === null) && !(!this.options.returnEmptyString && res === "");
889
- }
890
- getResource(code, ns, key, options = {}) {
891
- if (this.i18nFormat?.getResource) return this.i18nFormat.getResource(code, ns, key, options);
892
- return this.resourceStore.getResource(code, ns, key, options);
893
- }
894
- getUsedParamsDetails(options = {}) {
895
- const optionsKeys = ["defaultValue", "ordinal", "context", "replace", "lng", "lngs", "fallbackLng", "ns", "keySeparator", "nsSeparator", "returnObjects", "returnDetails", "joinArrays", "postProcess", "interpolation"];
896
- const useOptionsReplaceForData = options.replace && !isString(options.replace);
897
- let data = useOptionsReplaceForData ? options.replace : options;
898
- if (useOptionsReplaceForData && typeof options.count !== "undefined") {
899
- data.count = options.count;
900
- }
901
- if (this.options.interpolation.defaultVariables) {
902
- data = {
903
- ...this.options.interpolation.defaultVariables,
904
- ...data
905
- };
906
- }
907
- if (!useOptionsReplaceForData) {
908
- data = {
909
- ...data
910
- };
911
- for (const key of optionsKeys) {
912
- delete data[key];
913
- }
914
- }
915
- return data;
916
- }
917
- static hasDefaultValue(options) {
918
- const prefix = "defaultValue";
919
- for (const option in options) {
920
- if (Object.prototype.hasOwnProperty.call(options, option) && prefix === option.substring(0, prefix.length) && void 0 !== options[option]) {
921
- return true;
922
- }
923
- }
924
- return false;
925
- }
926
- };
927
- var LanguageUtil = class {
928
- constructor(options) {
929
- this.options = options;
930
- this.supportedLngs = this.options.supportedLngs || false;
931
- this.logger = baseLogger.create("languageUtils");
932
- }
933
- getScriptPartFromCode(code) {
934
- code = getCleanedCode(code);
935
- if (!code || code.indexOf("-") < 0) return null;
936
- const p = code.split("-");
937
- if (p.length === 2) return null;
938
- p.pop();
939
- if (p[p.length - 1].toLowerCase() === "x") return null;
940
- return this.formatLanguageCode(p.join("-"));
941
- }
942
- getLanguagePartFromCode(code) {
943
- code = getCleanedCode(code);
944
- if (!code || code.indexOf("-") < 0) return code;
945
- const p = code.split("-");
946
- return this.formatLanguageCode(p[0]);
947
- }
948
- formatLanguageCode(code) {
949
- if (isString(code) && code.indexOf("-") > -1) {
950
- let formattedCode;
951
- try {
952
- formattedCode = Intl.getCanonicalLocales(code)[0];
953
- } catch (e) {
954
- }
955
- if (formattedCode && this.options.lowerCaseLng) {
956
- formattedCode = formattedCode.toLowerCase();
957
- }
958
- if (formattedCode) return formattedCode;
959
- if (this.options.lowerCaseLng) {
960
- return code.toLowerCase();
961
- }
962
- return code;
963
- }
964
- return this.options.cleanCode || this.options.lowerCaseLng ? code.toLowerCase() : code;
965
- }
966
- isSupportedCode(code) {
967
- if (this.options.load === "languageOnly" || this.options.nonExplicitSupportedLngs) {
968
- code = this.getLanguagePartFromCode(code);
969
- }
970
- return !this.supportedLngs || !this.supportedLngs.length || this.supportedLngs.indexOf(code) > -1;
971
- }
972
- getBestMatchFromCodes(codes) {
973
- if (!codes) return null;
974
- let found;
975
- codes.forEach((code) => {
976
- if (found) return;
977
- const cleanedLng = this.formatLanguageCode(code);
978
- if (!this.options.supportedLngs || this.isSupportedCode(cleanedLng)) found = cleanedLng;
979
- });
980
- if (!found && this.options.supportedLngs) {
981
- codes.forEach((code) => {
982
- if (found) return;
983
- const lngScOnly = this.getScriptPartFromCode(code);
984
- if (this.isSupportedCode(lngScOnly)) return found = lngScOnly;
985
- const lngOnly = this.getLanguagePartFromCode(code);
986
- if (this.isSupportedCode(lngOnly)) return found = lngOnly;
987
- found = this.options.supportedLngs.find((supportedLng) => {
988
- if (supportedLng === lngOnly) return supportedLng;
989
- if (supportedLng.indexOf("-") < 0 && lngOnly.indexOf("-") < 0) return;
990
- if (supportedLng.indexOf("-") > 0 && lngOnly.indexOf("-") < 0 && supportedLng.substring(0, supportedLng.indexOf("-")) === lngOnly) return supportedLng;
991
- if (supportedLng.indexOf(lngOnly) === 0 && lngOnly.length > 1) return supportedLng;
992
- });
993
- });
994
- }
995
- if (!found) found = this.getFallbackCodes(this.options.fallbackLng)[0];
996
- return found;
997
- }
998
- getFallbackCodes(fallbacks, code) {
999
- if (!fallbacks) return [];
1000
- if (typeof fallbacks === "function") fallbacks = fallbacks(code);
1001
- if (isString(fallbacks)) fallbacks = [fallbacks];
1002
- if (Array.isArray(fallbacks)) return fallbacks;
1003
- if (!code) return fallbacks.default || [];
1004
- let found = fallbacks[code];
1005
- if (!found) found = fallbacks[this.getScriptPartFromCode(code)];
1006
- if (!found) found = fallbacks[this.formatLanguageCode(code)];
1007
- if (!found) found = fallbacks[this.getLanguagePartFromCode(code)];
1008
- if (!found) found = fallbacks.default;
1009
- return found || [];
1010
- }
1011
- toResolveHierarchy(code, fallbackCode) {
1012
- const fallbackCodes = this.getFallbackCodes((fallbackCode === false ? [] : fallbackCode) || this.options.fallbackLng || [], code);
1013
- const codes = [];
1014
- const addCode = (c) => {
1015
- if (!c) return;
1016
- if (this.isSupportedCode(c)) {
1017
- codes.push(c);
1018
- } else {
1019
- this.logger.warn(`rejecting language code not found in supportedLngs: ${c}`);
1020
- }
1021
- };
1022
- if (isString(code) && (code.indexOf("-") > -1 || code.indexOf("_") > -1)) {
1023
- if (this.options.load !== "languageOnly") addCode(this.formatLanguageCode(code));
1024
- if (this.options.load !== "languageOnly" && this.options.load !== "currentOnly") addCode(this.getScriptPartFromCode(code));
1025
- if (this.options.load !== "currentOnly") addCode(this.getLanguagePartFromCode(code));
1026
- } else if (isString(code)) {
1027
- addCode(this.formatLanguageCode(code));
1028
- }
1029
- fallbackCodes.forEach((fc) => {
1030
- if (codes.indexOf(fc) < 0) addCode(this.formatLanguageCode(fc));
1031
- });
1032
- return codes;
1033
- }
1034
- };
1035
- var suffixesOrder = {
1036
- zero: 0,
1037
- one: 1,
1038
- two: 2,
1039
- few: 3,
1040
- many: 4,
1041
- other: 5
1042
- };
1043
- var dummyRule = {
1044
- select: (count) => count === 1 ? "one" : "other",
1045
- resolvedOptions: () => ({
1046
- pluralCategories: ["one", "other"]
1047
- })
1048
- };
1049
- var PluralResolver = class {
1050
- constructor(languageUtils, options = {}) {
1051
- this.languageUtils = languageUtils;
1052
- this.options = options;
1053
- this.logger = baseLogger.create("pluralResolver");
1054
- this.pluralRulesCache = {};
1055
- }
1056
- addRule(lng, obj) {
1057
- this.rules[lng] = obj;
1058
- }
1059
- clearCache() {
1060
- this.pluralRulesCache = {};
1061
- }
1062
- getRule(code, options = {}) {
1063
- const cleanedCode = getCleanedCode(code === "dev" ? "en" : code);
1064
- const type = options.ordinal ? "ordinal" : "cardinal";
1065
- const cacheKey = JSON.stringify({
1066
- cleanedCode,
1067
- type
1068
- });
1069
- if (cacheKey in this.pluralRulesCache) {
1070
- return this.pluralRulesCache[cacheKey];
1071
- }
1072
- let rule;
1073
- try {
1074
- rule = new Intl.PluralRules(cleanedCode, {
1075
- type
1076
- });
1077
- } catch (err) {
1078
- if (!Intl) {
1079
- this.logger.error("No Intl support, please use an Intl polyfill!");
1080
- return dummyRule;
1081
- }
1082
- if (!code.match(/-|_/)) return dummyRule;
1083
- const lngPart = this.languageUtils.getLanguagePartFromCode(code);
1084
- rule = this.getRule(lngPart, options);
1085
- }
1086
- this.pluralRulesCache[cacheKey] = rule;
1087
- return rule;
1088
- }
1089
- needsPlural(code, options = {}) {
1090
- let rule = this.getRule(code, options);
1091
- if (!rule) rule = this.getRule("dev", options);
1092
- return rule?.resolvedOptions().pluralCategories.length > 1;
1093
- }
1094
- getPluralFormsOfKey(code, key, options = {}) {
1095
- return this.getSuffixes(code, options).map((suffix) => `${key}${suffix}`);
1096
- }
1097
- getSuffixes(code, options = {}) {
1098
- let rule = this.getRule(code, options);
1099
- if (!rule) rule = this.getRule("dev", options);
1100
- if (!rule) return [];
1101
- return rule.resolvedOptions().pluralCategories.sort((pluralCategory1, pluralCategory2) => suffixesOrder[pluralCategory1] - suffixesOrder[pluralCategory2]).map((pluralCategory) => `${this.options.prepend}${options.ordinal ? `ordinal${this.options.prepend}` : ""}${pluralCategory}`);
1102
- }
1103
- getSuffix(code, count, options = {}) {
1104
- const rule = this.getRule(code, options);
1105
- if (rule) {
1106
- return `${this.options.prepend}${options.ordinal ? `ordinal${this.options.prepend}` : ""}${rule.select(count)}`;
1107
- }
1108
- this.logger.warn(`no plural rule found for: ${code}`);
1109
- return this.getSuffix("dev", count, options);
1110
- }
1111
- };
1112
- var deepFindWithDefaults = (data, defaultData, key, keySeparator = ".", ignoreJSONStructure = true) => {
1113
- let path = getPathWithDefaults(data, defaultData, key);
1114
- if (!path && ignoreJSONStructure && isString(key)) {
1115
- path = deepFind(data, key, keySeparator);
1116
- if (path === void 0) path = deepFind(defaultData, key, keySeparator);
1117
- }
1118
- return path;
1119
- };
1120
- var regexSafe = (val) => val.replace(/\$/g, "$$$$");
1121
- var Interpolator = class {
1122
- constructor(options = {}) {
1123
- this.logger = baseLogger.create("interpolator");
1124
- this.options = options;
1125
- this.format = options?.interpolation?.format || ((value) => value);
1126
- this.init(options);
1127
- }
1128
- init(options = {}) {
1129
- if (!options.interpolation) options.interpolation = {
1130
- escapeValue: true
1131
- };
1132
- const {
1133
- escape: escape$1,
1134
- escapeValue,
1135
- useRawValueToEscape,
1136
- prefix,
1137
- prefixEscaped,
1138
- suffix,
1139
- suffixEscaped,
1140
- formatSeparator,
1141
- unescapeSuffix,
1142
- unescapePrefix,
1143
- nestingPrefix,
1144
- nestingPrefixEscaped,
1145
- nestingSuffix,
1146
- nestingSuffixEscaped,
1147
- nestingOptionsSeparator,
1148
- maxReplaces,
1149
- alwaysFormat
1150
- } = options.interpolation;
1151
- this.escape = escape$1 !== void 0 ? escape$1 : escape;
1152
- this.escapeValue = escapeValue !== void 0 ? escapeValue : true;
1153
- this.useRawValueToEscape = useRawValueToEscape !== void 0 ? useRawValueToEscape : false;
1154
- this.prefix = prefix ? regexEscape(prefix) : prefixEscaped || "{{";
1155
- this.suffix = suffix ? regexEscape(suffix) : suffixEscaped || "}}";
1156
- this.formatSeparator = formatSeparator || ",";
1157
- this.unescapePrefix = unescapeSuffix ? "" : unescapePrefix || "-";
1158
- this.unescapeSuffix = this.unescapePrefix ? "" : unescapeSuffix || "";
1159
- this.nestingPrefix = nestingPrefix ? regexEscape(nestingPrefix) : nestingPrefixEscaped || regexEscape("$t(");
1160
- this.nestingSuffix = nestingSuffix ? regexEscape(nestingSuffix) : nestingSuffixEscaped || regexEscape(")");
1161
- this.nestingOptionsSeparator = nestingOptionsSeparator || ",";
1162
- this.maxReplaces = maxReplaces || 1e3;
1163
- this.alwaysFormat = alwaysFormat !== void 0 ? alwaysFormat : false;
1164
- this.resetRegExp();
1165
- }
1166
- reset() {
1167
- if (this.options) this.init(this.options);
1168
- }
1169
- resetRegExp() {
1170
- const getOrResetRegExp = (existingRegExp, pattern) => {
1171
- if (existingRegExp?.source === pattern) {
1172
- existingRegExp.lastIndex = 0;
1173
- return existingRegExp;
1174
- }
1175
- return new RegExp(pattern, "g");
1176
- };
1177
- this.regexp = getOrResetRegExp(this.regexp, `${this.prefix}(.+?)${this.suffix}`);
1178
- this.regexpUnescape = getOrResetRegExp(this.regexpUnescape, `${this.prefix}${this.unescapePrefix}(.+?)${this.unescapeSuffix}${this.suffix}`);
1179
- this.nestingRegexp = getOrResetRegExp(this.nestingRegexp, `${this.nestingPrefix}((?:[^()"']+|"[^"]*"|'[^']*'|\\((?:[^()]|"[^"]*"|'[^']*')*\\))*?)${this.nestingSuffix}`);
1180
- }
1181
- interpolate(str, data, lng, options) {
1182
- let match;
1183
- let value;
1184
- let replaces;
1185
- const defaultData = this.options && this.options.interpolation && this.options.interpolation.defaultVariables || {};
1186
- const handleFormat = (key) => {
1187
- if (key.indexOf(this.formatSeparator) < 0) {
1188
- const path = deepFindWithDefaults(data, defaultData, key, this.options.keySeparator, this.options.ignoreJSONStructure);
1189
- return this.alwaysFormat ? this.format(path, void 0, lng, {
1190
- ...options,
1191
- ...data,
1192
- interpolationkey: key
1193
- }) : path;
1194
- }
1195
- const p = key.split(this.formatSeparator);
1196
- const k = p.shift().trim();
1197
- const f = p.join(this.formatSeparator).trim();
1198
- return this.format(deepFindWithDefaults(data, defaultData, k, this.options.keySeparator, this.options.ignoreJSONStructure), f, lng, {
1199
- ...options,
1200
- ...data,
1201
- interpolationkey: k
1202
- });
1203
- };
1204
- this.resetRegExp();
1205
- const missingInterpolationHandler = options?.missingInterpolationHandler || this.options.missingInterpolationHandler;
1206
- const skipOnVariables = options?.interpolation?.skipOnVariables !== void 0 ? options.interpolation.skipOnVariables : this.options.interpolation.skipOnVariables;
1207
- const todos = [{
1208
- regex: this.regexpUnescape,
1209
- safeValue: (val) => regexSafe(val)
1210
- }, {
1211
- regex: this.regexp,
1212
- safeValue: (val) => this.escapeValue ? regexSafe(this.escape(val)) : regexSafe(val)
1213
- }];
1214
- todos.forEach((todo) => {
1215
- replaces = 0;
1216
- while (match = todo.regex.exec(str)) {
1217
- const matchedVar = match[1].trim();
1218
- value = handleFormat(matchedVar);
1219
- if (value === void 0) {
1220
- if (typeof missingInterpolationHandler === "function") {
1221
- const temp = missingInterpolationHandler(str, match, options);
1222
- value = isString(temp) ? temp : "";
1223
- } else if (options && Object.prototype.hasOwnProperty.call(options, matchedVar)) {
1224
- value = "";
1225
- } else if (skipOnVariables) {
1226
- value = match[0];
1227
- continue;
1228
- } else {
1229
- this.logger.warn(`missed to pass in variable ${matchedVar} for interpolating ${str}`);
1230
- value = "";
1231
- }
1232
- } else if (!isString(value) && !this.useRawValueToEscape) {
1233
- value = makeString(value);
1234
- }
1235
- const safeValue = todo.safeValue(value);
1236
- str = str.replace(match[0], safeValue);
1237
- if (skipOnVariables) {
1238
- todo.regex.lastIndex += value.length;
1239
- todo.regex.lastIndex -= match[0].length;
1240
- } else {
1241
- todo.regex.lastIndex = 0;
1242
- }
1243
- replaces++;
1244
- if (replaces >= this.maxReplaces) {
1245
- break;
1246
- }
1247
- }
1248
- });
1249
- return str;
1250
- }
1251
- nest(str, fc, options = {}) {
1252
- let match;
1253
- let value;
1254
- let clonedOptions;
1255
- const handleHasOptions = (key, inheritedOptions) => {
1256
- const sep = this.nestingOptionsSeparator;
1257
- if (key.indexOf(sep) < 0) return key;
1258
- const c = key.split(new RegExp(`${sep}[ ]*{`));
1259
- let optionsString = `{${c[1]}`;
1260
- key = c[0];
1261
- optionsString = this.interpolate(optionsString, clonedOptions);
1262
- const matchedSingleQuotes = optionsString.match(/'/g);
1263
- const matchedDoubleQuotes = optionsString.match(/"/g);
1264
- if ((matchedSingleQuotes?.length ?? 0) % 2 === 0 && !matchedDoubleQuotes || matchedDoubleQuotes.length % 2 !== 0) {
1265
- optionsString = optionsString.replace(/'/g, '"');
1266
- }
1267
- try {
1268
- clonedOptions = JSON.parse(optionsString);
1269
- if (inheritedOptions) clonedOptions = {
1270
- ...inheritedOptions,
1271
- ...clonedOptions
1272
- };
1273
- } catch (e) {
1274
- this.logger.warn(`failed parsing options string in nesting for key ${key}`, e);
1275
- return `${key}${sep}${optionsString}`;
1276
- }
1277
- if (clonedOptions.defaultValue && clonedOptions.defaultValue.indexOf(this.prefix) > -1) delete clonedOptions.defaultValue;
1278
- return key;
1279
- };
1280
- while (match = this.nestingRegexp.exec(str)) {
1281
- let formatters = [];
1282
- clonedOptions = {
1283
- ...options
1284
- };
1285
- clonedOptions = clonedOptions.replace && !isString(clonedOptions.replace) ? clonedOptions.replace : clonedOptions;
1286
- clonedOptions.applyPostProcessor = false;
1287
- delete clonedOptions.defaultValue;
1288
- const keyEndIndex = /{.*}/.test(match[1]) ? match[1].lastIndexOf("}") + 1 : match[1].indexOf(this.formatSeparator);
1289
- if (keyEndIndex !== -1) {
1290
- formatters = match[1].slice(keyEndIndex).split(this.formatSeparator).map((elem) => elem.trim()).filter(Boolean);
1291
- match[1] = match[1].slice(0, keyEndIndex);
1292
- }
1293
- value = fc(handleHasOptions.call(this, match[1].trim(), clonedOptions), clonedOptions);
1294
- if (value && match[0] === str && !isString(value)) return value;
1295
- if (!isString(value)) value = makeString(value);
1296
- if (!value) {
1297
- this.logger.warn(`missed to resolve ${match[1]} for nesting ${str}`);
1298
- value = "";
1299
- }
1300
- if (formatters.length) {
1301
- value = formatters.reduce((v, f) => this.format(v, f, options.lng, {
1302
- ...options,
1303
- interpolationkey: match[1].trim()
1304
- }), value.trim());
1305
- }
1306
- str = str.replace(match[0], value);
1307
- this.regexp.lastIndex = 0;
1308
- }
1309
- return str;
1310
- }
1311
- };
1312
- var parseFormatStr = (formatStr) => {
1313
- let formatName = formatStr.toLowerCase().trim();
1314
- const formatOptions = {};
1315
- if (formatStr.indexOf("(") > -1) {
1316
- const p = formatStr.split("(");
1317
- formatName = p[0].toLowerCase().trim();
1318
- const optStr = p[1].substring(0, p[1].length - 1);
1319
- if (formatName === "currency" && optStr.indexOf(":") < 0) {
1320
- if (!formatOptions.currency) formatOptions.currency = optStr.trim();
1321
- } else if (formatName === "relativetime" && optStr.indexOf(":") < 0) {
1322
- if (!formatOptions.range) formatOptions.range = optStr.trim();
1323
- } else {
1324
- const opts = optStr.split(";");
1325
- opts.forEach((opt) => {
1326
- if (opt) {
1327
- const [key, ...rest] = opt.split(":");
1328
- const val = rest.join(":").trim().replace(/^'+|'+$/g, "");
1329
- const trimmedKey = key.trim();
1330
- if (!formatOptions[trimmedKey]) formatOptions[trimmedKey] = val;
1331
- if (val === "false") formatOptions[trimmedKey] = false;
1332
- if (val === "true") formatOptions[trimmedKey] = true;
1333
- if (!isNaN(val)) formatOptions[trimmedKey] = parseInt(val, 10);
1334
- }
1335
- });
1336
- }
1337
- }
1338
- return {
1339
- formatName,
1340
- formatOptions
1341
- };
1342
- };
1343
- var createCachedFormatter = (fn) => {
1344
- const cache = {};
1345
- return (v, l, o) => {
1346
- let optForCache = o;
1347
- if (o && o.interpolationkey && o.formatParams && o.formatParams[o.interpolationkey] && o[o.interpolationkey]) {
1348
- optForCache = {
1349
- ...optForCache,
1350
- [o.interpolationkey]: void 0
1351
- };
1352
- }
1353
- const key = l + JSON.stringify(optForCache);
1354
- let frm = cache[key];
1355
- if (!frm) {
1356
- frm = fn(getCleanedCode(l), o);
1357
- cache[key] = frm;
1358
- }
1359
- return frm(v);
1360
- };
1361
- };
1362
- var createNonCachedFormatter = (fn) => (v, l, o) => fn(getCleanedCode(l), o)(v);
1363
- var Formatter = class {
1364
- constructor(options = {}) {
1365
- this.logger = baseLogger.create("formatter");
1366
- this.options = options;
1367
- this.init(options);
1368
- }
1369
- init(services, options = {
1370
- interpolation: {}
1371
- }) {
1372
- this.formatSeparator = options.interpolation.formatSeparator || ",";
1373
- const cf = options.cacheInBuiltFormats ? createCachedFormatter : createNonCachedFormatter;
1374
- this.formats = {
1375
- number: cf((lng, opt) => {
1376
- const formatter = new Intl.NumberFormat(lng, {
1377
- ...opt
1378
- });
1379
- return (val) => formatter.format(val);
1380
- }),
1381
- currency: cf((lng, opt) => {
1382
- const formatter = new Intl.NumberFormat(lng, {
1383
- ...opt,
1384
- style: "currency"
1385
- });
1386
- return (val) => formatter.format(val);
1387
- }),
1388
- datetime: cf((lng, opt) => {
1389
- const formatter = new Intl.DateTimeFormat(lng, {
1390
- ...opt
1391
- });
1392
- return (val) => formatter.format(val);
1393
- }),
1394
- relativetime: cf((lng, opt) => {
1395
- const formatter = new Intl.RelativeTimeFormat(lng, {
1396
- ...opt
1397
- });
1398
- return (val) => formatter.format(val, opt.range || "day");
1399
- }),
1400
- list: cf((lng, opt) => {
1401
- const formatter = new Intl.ListFormat(lng, {
1402
- ...opt
1403
- });
1404
- return (val) => formatter.format(val);
1405
- })
1406
- };
1407
- }
1408
- add(name, fc) {
1409
- this.formats[name.toLowerCase().trim()] = fc;
1410
- }
1411
- addCached(name, fc) {
1412
- this.formats[name.toLowerCase().trim()] = createCachedFormatter(fc);
1413
- }
1414
- format(value, format, lng, options = {}) {
1415
- const formats = format.split(this.formatSeparator);
1416
- if (formats.length > 1 && formats[0].indexOf("(") > 1 && formats[0].indexOf(")") < 0 && formats.find((f) => f.indexOf(")") > -1)) {
1417
- const lastIndex = formats.findIndex((f) => f.indexOf(")") > -1);
1418
- formats[0] = [formats[0], ...formats.splice(1, lastIndex)].join(this.formatSeparator);
1419
- }
1420
- const result = formats.reduce((mem, f) => {
1421
- const {
1422
- formatName,
1423
- formatOptions
1424
- } = parseFormatStr(f);
1425
- if (this.formats[formatName]) {
1426
- let formatted = mem;
1427
- try {
1428
- const valOptions = options?.formatParams?.[options.interpolationkey] || {};
1429
- const l = valOptions.locale || valOptions.lng || options.locale || options.lng || lng;
1430
- formatted = this.formats[formatName](mem, l, {
1431
- ...formatOptions,
1432
- ...options,
1433
- ...valOptions
1434
- });
1435
- } catch (error) {
1436
- this.logger.warn(error);
1437
- }
1438
- return formatted;
1439
- } else {
1440
- this.logger.warn(`there was no format function for ${formatName}`);
1441
- }
1442
- return mem;
1443
- }, value);
1444
- return result;
1445
- }
1446
- };
1447
- var removePending = (q, name) => {
1448
- if (q.pending[name] !== void 0) {
1449
- delete q.pending[name];
1450
- q.pendingCount--;
1451
- }
1452
- };
1453
- var Connector = class extends EventEmitter {
1454
- constructor(backend, store, services, options = {}) {
1455
- super();
1456
- this.backend = backend;
1457
- this.store = store;
1458
- this.services = services;
1459
- this.languageUtils = services.languageUtils;
1460
- this.options = options;
1461
- this.logger = baseLogger.create("backendConnector");
1462
- this.waitingReads = [];
1463
- this.maxParallelReads = options.maxParallelReads || 10;
1464
- this.readingCalls = 0;
1465
- this.maxRetries = options.maxRetries >= 0 ? options.maxRetries : 5;
1466
- this.retryTimeout = options.retryTimeout >= 1 ? options.retryTimeout : 350;
1467
- this.state = {};
1468
- this.queue = [];
1469
- this.backend?.init?.(services, options.backend, options);
1470
- }
1471
- queueLoad(languages, namespaces, options, callback) {
1472
- const toLoad = {};
1473
- const pending = {};
1474
- const toLoadLanguages = {};
1475
- const toLoadNamespaces = {};
1476
- languages.forEach((lng) => {
1477
- let hasAllNamespaces = true;
1478
- namespaces.forEach((ns) => {
1479
- const name = `${lng}|${ns}`;
1480
- if (!options.reload && this.store.hasResourceBundle(lng, ns)) {
1481
- this.state[name] = 2;
1482
- } else if (this.state[name] < 0) ;
1483
- else if (this.state[name] === 1) {
1484
- if (pending[name] === void 0) pending[name] = true;
1485
- } else {
1486
- this.state[name] = 1;
1487
- hasAllNamespaces = false;
1488
- if (pending[name] === void 0) pending[name] = true;
1489
- if (toLoad[name] === void 0) toLoad[name] = true;
1490
- if (toLoadNamespaces[ns] === void 0) toLoadNamespaces[ns] = true;
1491
- }
1492
- });
1493
- if (!hasAllNamespaces) toLoadLanguages[lng] = true;
1494
- });
1495
- if (Object.keys(toLoad).length || Object.keys(pending).length) {
1496
- this.queue.push({
1497
- pending,
1498
- pendingCount: Object.keys(pending).length,
1499
- loaded: {},
1500
- errors: [],
1501
- callback
1502
- });
1503
- }
1504
- return {
1505
- toLoad: Object.keys(toLoad),
1506
- pending: Object.keys(pending),
1507
- toLoadLanguages: Object.keys(toLoadLanguages),
1508
- toLoadNamespaces: Object.keys(toLoadNamespaces)
1509
- };
1510
- }
1511
- loaded(name, err, data) {
1512
- const s = name.split("|");
1513
- const lng = s[0];
1514
- const ns = s[1];
1515
- if (err) this.emit("failedLoading", lng, ns, err);
1516
- if (!err && data) {
1517
- this.store.addResourceBundle(lng, ns, data, void 0, void 0, {
1518
- skipCopy: true
1519
- });
1520
- }
1521
- this.state[name] = err ? -1 : 2;
1522
- if (err && data) this.state[name] = 0;
1523
- const loaded = {};
1524
- this.queue.forEach((q) => {
1525
- pushPath(q.loaded, [lng], ns);
1526
- removePending(q, name);
1527
- if (err) q.errors.push(err);
1528
- if (q.pendingCount === 0 && !q.done) {
1529
- Object.keys(q.loaded).forEach((l) => {
1530
- if (!loaded[l]) loaded[l] = {};
1531
- const loadedKeys = q.loaded[l];
1532
- if (loadedKeys.length) {
1533
- loadedKeys.forEach((n) => {
1534
- if (loaded[l][n] === void 0) loaded[l][n] = true;
1535
- });
1536
- }
1537
- });
1538
- q.done = true;
1539
- if (q.errors.length) {
1540
- q.callback(q.errors);
1541
- } else {
1542
- q.callback();
1543
- }
1544
- }
1545
- });
1546
- this.emit("loaded", loaded);
1547
- this.queue = this.queue.filter((q) => !q.done);
1548
- }
1549
- read(lng, ns, fcName, tried = 0, wait = this.retryTimeout, callback) {
1550
- if (!lng.length) return callback(null, {});
1551
- if (this.readingCalls >= this.maxParallelReads) {
1552
- this.waitingReads.push({
1553
- lng,
1554
- ns,
1555
- fcName,
1556
- tried,
1557
- wait,
1558
- callback
1559
- });
1560
- return;
1561
- }
1562
- this.readingCalls++;
1563
- const resolver = (err, data) => {
1564
- this.readingCalls--;
1565
- if (this.waitingReads.length > 0) {
1566
- const next = this.waitingReads.shift();
1567
- this.read(next.lng, next.ns, next.fcName, next.tried, next.wait, next.callback);
1568
- }
1569
- if (err && data && tried < this.maxRetries) {
1570
- setTimeout(() => {
1571
- this.read.call(this, lng, ns, fcName, tried + 1, wait * 2, callback);
1572
- }, wait);
1573
- return;
1574
- }
1575
- callback(err, data);
1576
- };
1577
- const fc = this.backend[fcName].bind(this.backend);
1578
- if (fc.length === 2) {
1579
- try {
1580
- const r = fc(lng, ns);
1581
- if (r && typeof r.then === "function") {
1582
- r.then((data) => resolver(null, data)).catch(resolver);
1583
- } else {
1584
- resolver(null, r);
1585
- }
1586
- } catch (err) {
1587
- resolver(err);
1588
- }
1589
- return;
1590
- }
1591
- return fc(lng, ns, resolver);
1592
- }
1593
- prepareLoading(languages, namespaces, options = {}, callback) {
1594
- if (!this.backend) {
1595
- this.logger.warn("No backend was added via i18next.use. Will not load resources.");
1596
- return callback && callback();
1597
- }
1598
- if (isString(languages)) languages = this.languageUtils.toResolveHierarchy(languages);
1599
- if (isString(namespaces)) namespaces = [namespaces];
1600
- const toLoad = this.queueLoad(languages, namespaces, options, callback);
1601
- if (!toLoad.toLoad.length) {
1602
- if (!toLoad.pending.length) callback();
1603
- return null;
1604
- }
1605
- toLoad.toLoad.forEach((name) => {
1606
- this.loadOne(name);
1607
- });
1608
- }
1609
- load(languages, namespaces, callback) {
1610
- this.prepareLoading(languages, namespaces, {}, callback);
1611
- }
1612
- reload(languages, namespaces, callback) {
1613
- this.prepareLoading(languages, namespaces, {
1614
- reload: true
1615
- }, callback);
1616
- }
1617
- loadOne(name, prefix = "") {
1618
- const s = name.split("|");
1619
- const lng = s[0];
1620
- const ns = s[1];
1621
- this.read(lng, ns, "read", void 0, void 0, (err, data) => {
1622
- if (err) this.logger.warn(`${prefix}loading namespace ${ns} for language ${lng} failed`, err);
1623
- if (!err && data) this.logger.log(`${prefix}loaded namespace ${ns} for language ${lng}`, data);
1624
- this.loaded(name, err, data);
1625
- });
1626
- }
1627
- saveMissing(languages, namespace, key, fallbackValue, isUpdate, options = {}, clb = () => {
1628
- }) {
1629
- if (this.services?.utils?.hasLoadedNamespace && !this.services?.utils?.hasLoadedNamespace(namespace)) {
1630
- 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!!!");
1631
- return;
1632
- }
1633
- if (key === void 0 || key === null || key === "") return;
1634
- if (this.backend?.create) {
1635
- const opts = {
1636
- ...options,
1637
- isUpdate
1638
- };
1639
- const fc = this.backend.create.bind(this.backend);
1640
- if (fc.length < 6) {
1641
- try {
1642
- let r;
1643
- if (fc.length === 5) {
1644
- r = fc(languages, namespace, key, fallbackValue, opts);
1645
- } else {
1646
- r = fc(languages, namespace, key, fallbackValue);
1647
- }
1648
- if (r && typeof r.then === "function") {
1649
- r.then((data) => clb(null, data)).catch(clb);
1650
- } else {
1651
- clb(null, r);
1652
- }
1653
- } catch (err) {
1654
- clb(err);
1655
- }
1656
- } else {
1657
- fc(languages, namespace, key, fallbackValue, clb, opts);
1658
- }
1659
- }
1660
- if (!languages || !languages[0]) return;
1661
- this.store.addResource(languages[0], namespace, key, fallbackValue);
1662
- }
1663
- };
1664
- var get = () => ({
1665
- debug: false,
1666
- initAsync: true,
1667
- ns: ["translation"],
1668
- defaultNS: ["translation"],
1669
- fallbackLng: ["dev"],
1670
- fallbackNS: false,
1671
- supportedLngs: false,
1672
- nonExplicitSupportedLngs: false,
1673
- load: "all",
1674
- preload: false,
1675
- simplifyPluralSuffix: true,
1676
- keySeparator: ".",
1677
- nsSeparator: ":",
1678
- pluralSeparator: "_",
1679
- contextSeparator: "_",
1680
- partialBundledLanguages: false,
1681
- saveMissing: false,
1682
- updateMissing: false,
1683
- saveMissingTo: "fallback",
1684
- saveMissingPlurals: true,
1685
- missingKeyHandler: false,
1686
- missingInterpolationHandler: false,
1687
- postProcess: false,
1688
- postProcessPassResolved: false,
1689
- returnNull: false,
1690
- returnEmptyString: true,
1691
- returnObjects: false,
1692
- joinArrays: false,
1693
- returnedObjectHandler: false,
1694
- parseMissingKeyHandler: false,
1695
- appendNamespaceToMissingKey: false,
1696
- appendNamespaceToCIMode: false,
1697
- overloadTranslationOptionHandler: (args) => {
1698
- let ret = {};
1699
- if (typeof args[1] === "object") ret = args[1];
1700
- if (isString(args[1])) ret.defaultValue = args[1];
1701
- if (isString(args[2])) ret.tDescription = args[2];
1702
- if (typeof args[2] === "object" || typeof args[3] === "object") {
1703
- const options = args[3] || args[2];
1704
- Object.keys(options).forEach((key) => {
1705
- ret[key] = options[key];
1706
- });
1707
- }
1708
- return ret;
1709
- },
1710
- interpolation: {
1711
- escapeValue: true,
1712
- format: (value) => value,
1713
- prefix: "{{",
1714
- suffix: "}}",
1715
- formatSeparator: ",",
1716
- unescapePrefix: "-",
1717
- nestingPrefix: "$t(",
1718
- nestingSuffix: ")",
1719
- nestingOptionsSeparator: ",",
1720
- maxReplaces: 1e3,
1721
- skipOnVariables: true
1722
- },
1723
- cacheInBuiltFormats: true
1724
- });
1725
- var transformOptions = (options) => {
1726
- if (isString(options.ns)) options.ns = [options.ns];
1727
- if (isString(options.fallbackLng)) options.fallbackLng = [options.fallbackLng];
1728
- if (isString(options.fallbackNS)) options.fallbackNS = [options.fallbackNS];
1729
- if (options.supportedLngs?.indexOf?.("cimode") < 0) {
1730
- options.supportedLngs = options.supportedLngs.concat(["cimode"]);
1731
- }
1732
- if (typeof options.initImmediate === "boolean") options.initAsync = options.initImmediate;
1733
- return options;
1734
- };
1735
- var noop = () => {
1736
- };
1737
- var bindMemberFunctions = (inst) => {
1738
- const mems = Object.getOwnPropertyNames(Object.getPrototypeOf(inst));
1739
- mems.forEach((mem) => {
1740
- if (typeof inst[mem] === "function") {
1741
- inst[mem] = inst[mem].bind(inst);
1742
- }
1743
- });
1744
- };
1745
- var I18n = class _I18n extends EventEmitter {
1746
- constructor(options = {}, callback) {
1747
- super();
1748
- this.options = transformOptions(options);
1749
- this.services = {};
1750
- this.logger = baseLogger;
1751
- this.modules = {
1752
- external: []
1753
- };
1754
- bindMemberFunctions(this);
1755
- if (callback && !this.isInitialized && !options.isClone) {
1756
- if (!this.options.initAsync) {
1757
- this.init(options, callback);
1758
- return this;
1759
- }
1760
- setTimeout(() => {
1761
- this.init(options, callback);
1762
- }, 0);
1763
- }
1764
- }
1765
- init(options = {}, callback) {
1766
- this.isInitializing = true;
1767
- if (typeof options === "function") {
1768
- callback = options;
1769
- options = {};
1770
- }
1771
- if (options.defaultNS == null && options.ns) {
1772
- if (isString(options.ns)) {
1773
- options.defaultNS = options.ns;
1774
- } else if (options.ns.indexOf("translation") < 0) {
1775
- options.defaultNS = options.ns[0];
1776
- }
1777
- }
1778
- const defOpts = get();
1779
- this.options = {
1780
- ...defOpts,
1781
- ...this.options,
1782
- ...transformOptions(options)
1783
- };
1784
- this.options.interpolation = {
1785
- ...defOpts.interpolation,
1786
- ...this.options.interpolation
1787
- };
1788
- if (options.keySeparator !== void 0) {
1789
- this.options.userDefinedKeySeparator = options.keySeparator;
1790
- }
1791
- if (options.nsSeparator !== void 0) {
1792
- this.options.userDefinedNsSeparator = options.nsSeparator;
1793
- }
1794
- const createClassOnDemand = (ClassOrObject) => {
1795
- if (!ClassOrObject) return null;
1796
- if (typeof ClassOrObject === "function") return new ClassOrObject();
1797
- return ClassOrObject;
1798
- };
1799
- if (!this.options.isClone) {
1800
- if (this.modules.logger) {
1801
- baseLogger.init(createClassOnDemand(this.modules.logger), this.options);
1802
- } else {
1803
- baseLogger.init(null, this.options);
1804
- }
1805
- let formatter;
1806
- if (this.modules.formatter) {
1807
- formatter = this.modules.formatter;
1808
- } else {
1809
- formatter = Formatter;
1810
- }
1811
- const lu = new LanguageUtil(this.options);
1812
- this.store = new ResourceStore(this.options.resources, this.options);
1813
- const s = this.services;
1814
- s.logger = baseLogger;
1815
- s.resourceStore = this.store;
1816
- s.languageUtils = lu;
1817
- s.pluralResolver = new PluralResolver(lu, {
1818
- prepend: this.options.pluralSeparator,
1819
- simplifyPluralSuffix: this.options.simplifyPluralSuffix
1820
- });
1821
- const usingLegacyFormatFunction = this.options.interpolation.format && this.options.interpolation.format !== defOpts.interpolation.format;
1822
- if (usingLegacyFormatFunction) {
1823
- this.logger.deprecate(`init: you are still using the legacy format function, please use the new approach: https://www.i18next.com/translation-function/formatting`);
1824
- }
1825
- if (formatter && (!this.options.interpolation.format || this.options.interpolation.format === defOpts.interpolation.format)) {
1826
- s.formatter = createClassOnDemand(formatter);
1827
- if (s.formatter.init) s.formatter.init(s, this.options);
1828
- this.options.interpolation.format = s.formatter.format.bind(s.formatter);
1829
- }
1830
- s.interpolator = new Interpolator(this.options);
1831
- s.utils = {
1832
- hasLoadedNamespace: this.hasLoadedNamespace.bind(this)
1833
- };
1834
- s.backendConnector = new Connector(createClassOnDemand(this.modules.backend), s.resourceStore, s, this.options);
1835
- s.backendConnector.on("*", (event, ...args) => {
1836
- this.emit(event, ...args);
1837
- });
1838
- if (this.modules.languageDetector) {
1839
- s.languageDetector = createClassOnDemand(this.modules.languageDetector);
1840
- if (s.languageDetector.init) s.languageDetector.init(s, this.options.detection, this.options);
1841
- }
1842
- if (this.modules.i18nFormat) {
1843
- s.i18nFormat = createClassOnDemand(this.modules.i18nFormat);
1844
- if (s.i18nFormat.init) s.i18nFormat.init(this);
1845
- }
1846
- this.translator = new Translator(this.services, this.options);
1847
- this.translator.on("*", (event, ...args) => {
1848
- this.emit(event, ...args);
1849
- });
1850
- this.modules.external.forEach((m) => {
1851
- if (m.init) m.init(this);
1852
- });
1853
- }
1854
- this.format = this.options.interpolation.format;
1855
- if (!callback) callback = noop;
1856
- if (this.options.fallbackLng && !this.services.languageDetector && !this.options.lng) {
1857
- const codes = this.services.languageUtils.getFallbackCodes(this.options.fallbackLng);
1858
- if (codes.length > 0 && codes[0] !== "dev") this.options.lng = codes[0];
1859
- }
1860
- if (!this.services.languageDetector && !this.options.lng) {
1861
- this.logger.warn("init: no languageDetector is used and no lng is defined");
1862
- }
1863
- const storeApi = ["getResource", "hasResourceBundle", "getResourceBundle", "getDataByLanguage"];
1864
- storeApi.forEach((fcName) => {
1865
- this[fcName] = (...args) => this.store[fcName](...args);
1866
- });
1867
- const storeApiChained = ["addResource", "addResources", "addResourceBundle", "removeResourceBundle"];
1868
- storeApiChained.forEach((fcName) => {
1869
- this[fcName] = (...args) => {
1870
- this.store[fcName](...args);
1871
- return this;
1872
- };
1873
- });
1874
- const deferred = defer();
1875
- const load = () => {
1876
- const finish = (err, t2) => {
1877
- this.isInitializing = false;
1878
- if (this.isInitialized && !this.initializedStoreOnce) this.logger.warn("init: i18next is already initialized. You should call init just once!");
1879
- this.isInitialized = true;
1880
- if (!this.options.isClone) this.logger.log("initialized", this.options);
1881
- this.emit("initialized", this.options);
1882
- deferred.resolve(t2);
1883
- callback(err, t2);
1884
- };
1885
- if (this.languages && !this.isInitialized) return finish(null, this.t.bind(this));
1886
- this.changeLanguage(this.options.lng, finish);
1887
- };
1888
- if (this.options.resources || !this.options.initAsync) {
1889
- load();
1890
- } else {
1891
- setTimeout(load, 0);
1892
- }
1893
- return deferred;
1894
- }
1895
- loadResources(language, callback = noop) {
1896
- let usedCallback = callback;
1897
- const usedLng = isString(language) ? language : this.language;
1898
- if (typeof language === "function") usedCallback = language;
1899
- if (!this.options.resources || this.options.partialBundledLanguages) {
1900
- if (usedLng?.toLowerCase() === "cimode" && (!this.options.preload || this.options.preload.length === 0)) return usedCallback();
1901
- const toLoad = [];
1902
- const append = (lng) => {
1903
- if (!lng) return;
1904
- if (lng === "cimode") return;
1905
- const lngs = this.services.languageUtils.toResolveHierarchy(lng);
1906
- lngs.forEach((l) => {
1907
- if (l === "cimode") return;
1908
- if (toLoad.indexOf(l) < 0) toLoad.push(l);
1909
- });
1910
- };
1911
- if (!usedLng) {
1912
- const fallbacks = this.services.languageUtils.getFallbackCodes(this.options.fallbackLng);
1913
- fallbacks.forEach((l) => append(l));
1914
- } else {
1915
- append(usedLng);
1916
- }
1917
- this.options.preload?.forEach?.((l) => append(l));
1918
- this.services.backendConnector.load(toLoad, this.options.ns, (e) => {
1919
- if (!e && !this.resolvedLanguage && this.language) this.setResolvedLanguage(this.language);
1920
- usedCallback(e);
1921
- });
1922
- } else {
1923
- usedCallback(null);
1924
- }
1925
- }
1926
- reloadResources(lngs, ns, callback) {
1927
- const deferred = defer();
1928
- if (typeof lngs === "function") {
1929
- callback = lngs;
1930
- lngs = void 0;
1931
- }
1932
- if (typeof ns === "function") {
1933
- callback = ns;
1934
- ns = void 0;
1935
- }
1936
- if (!lngs) lngs = this.languages;
1937
- if (!ns) ns = this.options.ns;
1938
- if (!callback) callback = noop;
1939
- this.services.backendConnector.reload(lngs, ns, (err) => {
1940
- deferred.resolve();
1941
- callback(err);
1942
- });
1943
- return deferred;
1944
- }
1945
- use(module2) {
1946
- if (!module2) throw new Error("You are passing an undefined module! Please check the object you are passing to i18next.use()");
1947
- if (!module2.type) throw new Error("You are passing a wrong module! Please check the object you are passing to i18next.use()");
1948
- if (module2.type === "backend") {
1949
- this.modules.backend = module2;
1950
- }
1951
- if (module2.type === "logger" || module2.log && module2.warn && module2.error) {
1952
- this.modules.logger = module2;
1953
- }
1954
- if (module2.type === "languageDetector") {
1955
- this.modules.languageDetector = module2;
1956
- }
1957
- if (module2.type === "i18nFormat") {
1958
- this.modules.i18nFormat = module2;
1959
- }
1960
- if (module2.type === "postProcessor") {
1961
- postProcessor.addPostProcessor(module2);
1962
- }
1963
- if (module2.type === "formatter") {
1964
- this.modules.formatter = module2;
1965
- }
1966
- if (module2.type === "3rdParty") {
1967
- this.modules.external.push(module2);
1968
- }
1969
- return this;
1970
- }
1971
- setResolvedLanguage(l) {
1972
- if (!l || !this.languages) return;
1973
- if (["cimode", "dev"].indexOf(l) > -1) return;
1974
- for (let li = 0; li < this.languages.length; li++) {
1975
- const lngInLngs = this.languages[li];
1976
- if (["cimode", "dev"].indexOf(lngInLngs) > -1) continue;
1977
- if (this.store.hasLanguageSomeTranslations(lngInLngs)) {
1978
- this.resolvedLanguage = lngInLngs;
1979
- break;
1980
- }
1981
- }
1982
- if (!this.resolvedLanguage && this.languages.indexOf(l) < 0 && this.store.hasLanguageSomeTranslations(l)) {
1983
- this.resolvedLanguage = l;
1984
- this.languages.unshift(l);
1985
- }
1986
- }
1987
- changeLanguage(lng, callback) {
1988
- this.isLanguageChangingTo = lng;
1989
- const deferred = defer();
1990
- this.emit("languageChanging", lng);
1991
- const setLngProps = (l) => {
1992
- this.language = l;
1993
- this.languages = this.services.languageUtils.toResolveHierarchy(l);
1994
- this.resolvedLanguage = void 0;
1995
- this.setResolvedLanguage(l);
1996
- };
1997
- const done = (err, l) => {
1998
- if (l) {
1999
- if (this.isLanguageChangingTo === lng) {
2000
- setLngProps(l);
2001
- this.translator.changeLanguage(l);
2002
- this.isLanguageChangingTo = void 0;
2003
- this.emit("languageChanged", l);
2004
- this.logger.log("languageChanged", l);
2005
- }
2006
- } else {
2007
- this.isLanguageChangingTo = void 0;
2008
- }
2009
- deferred.resolve((...args) => this.t(...args));
2010
- if (callback) callback(err, (...args) => this.t(...args));
2011
- };
2012
- const setLng = (lngs) => {
2013
- if (!lng && !lngs && this.services.languageDetector) lngs = [];
2014
- const fl = isString(lngs) ? lngs : lngs && lngs[0];
2015
- const l = this.store.hasLanguageSomeTranslations(fl) ? fl : this.services.languageUtils.getBestMatchFromCodes(isString(lngs) ? [lngs] : lngs);
2016
- if (l) {
2017
- if (!this.language) {
2018
- setLngProps(l);
2019
- }
2020
- if (!this.translator.language) this.translator.changeLanguage(l);
2021
- this.services.languageDetector?.cacheUserLanguage?.(l);
2022
- }
2023
- this.loadResources(l, (err) => {
2024
- done(err, l);
2025
- });
2026
- };
2027
- if (!lng && this.services.languageDetector && !this.services.languageDetector.async) {
2028
- setLng(this.services.languageDetector.detect());
2029
- } else if (!lng && this.services.languageDetector && this.services.languageDetector.async) {
2030
- if (this.services.languageDetector.detect.length === 0) {
2031
- this.services.languageDetector.detect().then(setLng);
2032
- } else {
2033
- this.services.languageDetector.detect(setLng);
2034
- }
2035
- } else {
2036
- setLng(lng);
2037
- }
2038
- return deferred;
2039
- }
2040
- getFixedT(lng, ns, keyPrefix) {
2041
- const fixedT = (key, opts, ...rest) => {
2042
- let o;
2043
- if (typeof opts !== "object") {
2044
- o = this.options.overloadTranslationOptionHandler([key, opts].concat(rest));
2045
- } else {
2046
- o = {
2047
- ...opts
2048
- };
2049
- }
2050
- o.lng = o.lng || fixedT.lng;
2051
- o.lngs = o.lngs || fixedT.lngs;
2052
- o.ns = o.ns || fixedT.ns;
2053
- if (o.keyPrefix !== "") o.keyPrefix = o.keyPrefix || keyPrefix || fixedT.keyPrefix;
2054
- const keySeparator = this.options.keySeparator || ".";
2055
- let resultKey;
2056
- if (o.keyPrefix && Array.isArray(key)) {
2057
- resultKey = key.map((k) => {
2058
- if (typeof k === "function") k = keysFromSelector(k, {
2059
- ...this.options,
2060
- ...opts
2061
- });
2062
- return `${o.keyPrefix}${keySeparator}${k}`;
2063
- });
2064
- } else {
2065
- if (typeof key === "function") key = keysFromSelector(key, {
2066
- ...this.options,
2067
- ...opts
2068
- });
2069
- resultKey = o.keyPrefix ? `${o.keyPrefix}${keySeparator}${key}` : key;
2070
- }
2071
- return this.t(resultKey, o);
2072
- };
2073
- if (isString(lng)) {
2074
- fixedT.lng = lng;
2075
- } else {
2076
- fixedT.lngs = lng;
2077
- }
2078
- fixedT.ns = ns;
2079
- fixedT.keyPrefix = keyPrefix;
2080
- return fixedT;
2081
- }
2082
- t(...args) {
2083
- return this.translator?.translate(...args);
2084
- }
2085
- exists(...args) {
2086
- return this.translator?.exists(...args);
2087
- }
2088
- setDefaultNamespace(ns) {
2089
- this.options.defaultNS = ns;
2090
- }
2091
- hasLoadedNamespace(ns, options = {}) {
2092
- if (!this.isInitialized) {
2093
- this.logger.warn("hasLoadedNamespace: i18next was not initialized", this.languages);
2094
- return false;
2095
- }
2096
- if (!this.languages || !this.languages.length) {
2097
- this.logger.warn("hasLoadedNamespace: i18n.languages were undefined or empty", this.languages);
2098
- return false;
2099
- }
2100
- const lng = options.lng || this.resolvedLanguage || this.languages[0];
2101
- const fallbackLng = this.options ? this.options.fallbackLng : false;
2102
- const lastLng = this.languages[this.languages.length - 1];
2103
- if (lng.toLowerCase() === "cimode") return true;
2104
- const loadNotPending = (l, n) => {
2105
- const loadState = this.services.backendConnector.state[`${l}|${n}`];
2106
- return loadState === -1 || loadState === 0 || loadState === 2;
2107
- };
2108
- if (options.precheck) {
2109
- const preResult = options.precheck(this, loadNotPending);
2110
- if (preResult !== void 0) return preResult;
2111
- }
2112
- if (this.hasResourceBundle(lng, ns)) return true;
2113
- if (!this.services.backendConnector.backend || this.options.resources && !this.options.partialBundledLanguages) return true;
2114
- if (loadNotPending(lng, ns) && (!fallbackLng || loadNotPending(lastLng, ns))) return true;
2115
- return false;
2116
- }
2117
- loadNamespaces(ns, callback) {
2118
- const deferred = defer();
2119
- if (!this.options.ns) {
2120
- if (callback) callback();
2121
- return Promise.resolve();
2122
- }
2123
- if (isString(ns)) ns = [ns];
2124
- ns.forEach((n) => {
2125
- if (this.options.ns.indexOf(n) < 0) this.options.ns.push(n);
2126
- });
2127
- this.loadResources((err) => {
2128
- deferred.resolve();
2129
- if (callback) callback(err);
2130
- });
2131
- return deferred;
2132
- }
2133
- loadLanguages(lngs, callback) {
2134
- const deferred = defer();
2135
- if (isString(lngs)) lngs = [lngs];
2136
- const preloaded = this.options.preload || [];
2137
- const newLngs = lngs.filter((lng) => preloaded.indexOf(lng) < 0 && this.services.languageUtils.isSupportedCode(lng));
2138
- if (!newLngs.length) {
2139
- if (callback) callback();
2140
- return Promise.resolve();
2141
- }
2142
- this.options.preload = preloaded.concat(newLngs);
2143
- this.loadResources((err) => {
2144
- deferred.resolve();
2145
- if (callback) callback(err);
2146
- });
2147
- return deferred;
2148
- }
2149
- dir(lng) {
2150
- if (!lng) lng = this.resolvedLanguage || (this.languages?.length > 0 ? this.languages[0] : this.language);
2151
- if (!lng) return "rtl";
2152
- try {
2153
- const l = new Intl.Locale(lng);
2154
- if (l && l.getTextInfo) {
2155
- const ti = l.getTextInfo();
2156
- if (ti && ti.direction) return ti.direction;
2157
- }
2158
- } catch (e) {
2159
- }
2160
- 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"];
2161
- const languageUtils = this.services?.languageUtils || new LanguageUtil(get());
2162
- if (lng.toLowerCase().indexOf("-latn") > 1) return "ltr";
2163
- return rtlLngs.indexOf(languageUtils.getLanguagePartFromCode(lng)) > -1 || lng.toLowerCase().indexOf("-arab") > 1 ? "rtl" : "ltr";
2164
- }
2165
- static createInstance(options = {}, callback) {
2166
- const instance2 = new _I18n(options, callback);
2167
- instance2.createInstance = _I18n.createInstance;
2168
- return instance2;
2169
- }
2170
- cloneInstance(options = {}, callback = noop) {
2171
- const forkResourceStore = options.forkResourceStore;
2172
- if (forkResourceStore) delete options.forkResourceStore;
2173
- const mergedOptions = {
2174
- ...this.options,
2175
- ...options,
2176
- ...{
2177
- isClone: true
2178
- }
2179
- };
2180
- const clone = new _I18n(mergedOptions);
2181
- if (options.debug !== void 0 || options.prefix !== void 0) {
2182
- clone.logger = clone.logger.clone(options);
2183
- }
2184
- const membersToCopy = ["store", "services", "language"];
2185
- membersToCopy.forEach((m) => {
2186
- clone[m] = this[m];
2187
- });
2188
- clone.services = {
2189
- ...this.services
2190
- };
2191
- clone.services.utils = {
2192
- hasLoadedNamespace: clone.hasLoadedNamespace.bind(clone)
2193
- };
2194
- if (forkResourceStore) {
2195
- const clonedData = Object.keys(this.store.data).reduce((prev, l) => {
2196
- prev[l] = {
2197
- ...this.store.data[l]
2198
- };
2199
- prev[l] = Object.keys(prev[l]).reduce((acc, n) => {
2200
- acc[n] = {
2201
- ...prev[l][n]
2202
- };
2203
- return acc;
2204
- }, prev[l]);
2205
- return prev;
2206
- }, {});
2207
- clone.store = new ResourceStore(clonedData, mergedOptions);
2208
- clone.services.resourceStore = clone.store;
2209
- }
2210
- if (options.interpolation) clone.services.interpolator = new Interpolator(mergedOptions);
2211
- clone.translator = new Translator(clone.services, mergedOptions);
2212
- clone.translator.on("*", (event, ...args) => {
2213
- clone.emit(event, ...args);
2214
- });
2215
- clone.init(mergedOptions, callback);
2216
- clone.translator.options = mergedOptions;
2217
- clone.translator.backendConnector.services.utils = {
2218
- hasLoadedNamespace: clone.hasLoadedNamespace.bind(clone)
2219
- };
2220
- return clone;
2221
- }
2222
- toJSON() {
2223
- return {
2224
- options: this.options,
2225
- store: this.store,
2226
- language: this.language,
2227
- languages: this.languages,
2228
- resolvedLanguage: this.resolvedLanguage
2229
- };
2230
- }
2231
- };
2232
- var instance = I18n.createInstance();
2233
- var createInstance = instance.createInstance;
2234
- var dir = instance.dir;
2235
- var init = instance.init;
2236
- var loadResources = instance.loadResources;
2237
- var reloadResources = instance.reloadResources;
2238
- var use = instance.use;
2239
- var changeLanguage = instance.changeLanguage;
2240
- var getFixedT = instance.getFixedT;
2241
- var t = instance.t;
2242
- var exists = instance.exists;
2243
- var setDefaultNamespace = instance.setDefaultNamespace;
2244
- var hasLoadedNamespace = instance.hasLoadedNamespace;
2245
- var loadNamespaces = instance.loadNamespaces;
2246
- var loadLanguages = instance.loadLanguages;
2247
-
2248
- // src/locale/en/locale-resources.ts
2249
- var locale_resources_default = {
2250
- Transformer: {
2251
- domainMustBeGreaterThanZero: "Domain {{domain, number}} must be greater than 0",
2252
- tweakMustBeGreaterThanOrEqualToZero: "Tweak {{tweak, number}} must be greater than or equal to 0",
2253
- valueMustBeGreaterThanOrEqualToZero: "Value {{value, number}} must be greater than or equal to 0",
2254
- valueMustBeLessThan: "Value {{value, number}} must be less than {{domain, number}}",
2255
- minimumValueMustBeGreaterThanOrEqualToZero: "Minimum value {{minimumValue, number}} must be greater than or equal to 0",
2256
- maximumValueMustBeLessThan: "Maximum value {{maximumValue, number}} must be less than {{domain, number}}"
2257
- },
2258
- RegExpValidator: {
2259
- stringDoesNotMatchPattern: "String {{s}} does not match pattern"
2260
- },
2261
- CharacterSetValidator: {
2262
- firstZeroFirstCharacter: "Character set must support zero as first character",
2263
- allNumericAllNumericCharacters: "Character set must support all numeric characters in sequence",
2264
- stringMustNotBeAllNumeric: "String must not be all numeric",
2265
- lengthMustBeGreaterThanOrEqualTo: "Length {{length, number}} must be greater than or equal to {{minimumLength, number}}",
2266
- lengthMustBeLessThanOrEqualTo: "Length {{length, number}} must be less than or equal to {{maximumLength, number}}",
2267
- lengthMustBeEqualTo: "Length {{length, number}} must be equal to {{exactLength, number}}",
2268
- lengthOfComponentMustBeGreaterThanOrEqualTo: "Length {{length, number}} of {{component}} must be greater than or equal to {{minimumLength, number}}",
2269
- lengthOfComponentMustBeLessThanOrEqualTo: "Length {{length, number}} of {{component}} must be less than or equal to {{maximumLength, number}}",
2270
- lengthOfComponentMustBeEqualTo: "Length {{length, number}} of {{component}} must be equal to {{exactLength, number}}",
2271
- invalidCharacterAtPosition: "Invalid character '{{c}}' at position {{position, number}}",
2272
- invalidCharacterAtPositionOfComponent: "Invalid character '{{c}}' at position {{position, number}} of {{component}}",
2273
- exclusionNotSupported: "Exclusion value of {{exclusion, number}} is not supported",
2274
- endSequenceValueMustBeLessThanOrEqualTo: "End sequence value (start sequence value + count - 1) must be less than {{domain, number}}"
2275
- },
2276
- RecordValidator: {
2277
- typeNameKeyNotFound: '{{typeName}} "{{key}}" not found'
2278
- }
2279
- };
2280
-
2281
- // src/locale/fr/locale-resources.ts
2282
- var locale_resources_default2 = {
2283
- Transformer: {
2284
- domainMustBeGreaterThanZero: "Le domaine {{domain, number}} doit \xEAtre sup\xE9rieur \xE0 0",
2285
- tweakMustBeGreaterThanOrEqualToZero: "Le r\xE9glage {{tweak, number}} doit \xEAtre sup\xE9rieur ou \xE9gal \xE0 0",
2286
- valueMustBeGreaterThanOrEqualToZero: "La valeur {{value, number}} doit \xEAtre sup\xE9rieure ou \xE9gale \xE0 0",
2287
- valueMustBeLessThan: "La valeur {{value, number}} doit \xEAtre inf\xE9rieure \xE0 {{domain, number}}",
2288
- minimumValueMustBeGreaterThanOrEqualToZero: "La valeur minimale {{minimumValue, number}} doit \xEAtre sup\xE9rieure ou \xE9gale \xE0 0",
2289
- maximumValueMustBeLessThan: "La valeur maximale {{maximumValue, number}} doit \xEAtre inf\xE9rieure \xE0 {{domain, number}}"
2290
- },
2291
- RegExpValidator: {
2292
- stringDoesNotMatchPattern: "La cha\xEEne {{s}} ne correspond pas au mod\xE8le"
2293
- },
2294
- CharacterSetValidator: {
2295
- firstZeroFirstCharacter: "Le jeu de caract\xE8res doit prendre en charge z\xE9ro comme premier caract\xE8re",
2296
- allNumericAllNumericCharacters: "Le jeu de caract\xE8res doit prendre en charge tous les caract\xE8res num\xE9riques en s\xE9quence",
2297
- stringMustNotBeAllNumeric: "La cha\xEEne ne doit pas \xEAtre enti\xE8rement num\xE9rique",
2298
- lengthMustBeGreaterThanOrEqualTo: "La longueur {{length, number}} doit \xEAtre sup\xE9rieure ou \xE9gale \xE0 {{minimumLength, number}}",
2299
- lengthMustBeLessThanOrEqualTo: "La longueur {{length, number}} doit \xEAtre inf\xE9rieure ou \xE9gale \xE0 {{maximumLength, number}}",
2300
- lengthMustBeEqualTo: "La longueur {{length, number}} doit \xEAtre \xE9gale \xE0 {{exactLength, number}}",
2301
- lengthOfComponentMustBeGreaterThanOrEqualTo: "La longueur {{length, number}} de {{component}} doit \xEAtre sup\xE9rieure ou \xE9gale \xE0 {{minimumLength, number}}",
2302
- lengthOfComponentMustBeLessThanOrEqualTo: "La longueur {{length, number}} de {{component}} doit \xEAtre inf\xE9rieure ou \xE9gale \xE0 {{maximumLength, number}}",
2303
- lengthOfComponentMustBeEqualTo: "La longueur {{length, number}} de {{component}} doit \xEAtre \xE9gale \xE0 {{exactLength, number}}",
2304
- invalidCharacterAtPosition: "Caract\xE8re non valide '{{c}}' \xE0 la position {{position, number}}",
2305
- invalidCharacterAtPositionOfComponent: "Caract\xE8re non valide '{{c}}' \xE0 la position {{position, number}} de {{component}}",
2306
- exclusionNotSupported: "La valeur d'exclusion de {{exclusion, number}} n'est pas prise en charge",
2307
- endSequenceValueMustBeLessThanOrEqualTo: "La valeur de la s\xE9quence de fin (valeur de la s\xE9quence de d\xE9but + nombre - 1) doit \xEAtre inf\xE9rieure \xE0 {{domain, number}}"
2308
- },
2309
- RecordValidator: {
2310
- typeNameKeyNotFound: '{{typeName}} "{{key}}" introuvable'
2311
- }
2312
- };
2313
-
2314
- // src/locale/i18n.ts
2315
- var utilityNS = "aidct_utility";
2316
- var utilityResources = {
2317
- en: {
2318
- aidct_utility: locale_resources_default
2319
- },
2320
- fr: {
2321
- aidct_utility: locale_resources_default2
2322
- }
2323
- };
2324
- var i18nextUtility = instance.createInstance();
2325
- async function i18nUtilityInit(environment, debug = false) {
2326
- await (0, import_core.i18nCoreInit)(i18nextUtility, environment, debug, utilityNS, utilityResources);
2327
- }
2328
-
2329
- // src/sequence.ts
2330
- var Sequence = class {
2331
- /**
2332
- * Start value (inclusive).
2333
- */
2334
- _startValue;
2335
- /**
2336
- * End value (exclusive).
2337
- */
2338
- _endValue;
2339
- /**
2340
- * Count of values.
2341
- */
2342
- _count;
2343
- /**
2344
- * Delta to the next value; equal to the sign of the count.
2345
- */
2346
- _nextDelta;
2347
- /**
2348
- * Minimum value (inclusive).
2349
- */
2350
- _minimumValue;
2351
- /**
2352
- * Maximum value (inclusive).
2353
- */
2354
- _maximumValue;
2355
- /**
2356
- * Constructor.
2357
- *
2358
- * @param startValue
2359
- * Start value.
2360
- *
2361
- * @param count
2362
- * Count of values. If count is zero or positive, iteration ascends from start value, otherwise it descends from
2363
- * start value.
2364
- */
2365
- constructor(startValue, count) {
2366
- this._startValue = BigInt(startValue);
2367
- this._endValue = this._startValue + BigInt(count);
2368
- this._count = count;
2369
- if (count >= 0) {
2370
- this._nextDelta = 1n;
2371
- this._minimumValue = this._startValue;
2372
- this._maximumValue = this._endValue - 1n;
2373
- } else {
2374
- this._nextDelta = -1n;
2375
- this._minimumValue = this._endValue + 1n;
2376
- this._maximumValue = this._startValue;
2377
- }
2378
- }
2379
- /**
2380
- * Get the start value (inclusive).
2381
- */
2382
- get startValue() {
2383
- return this._startValue;
2384
- }
2385
- /**
2386
- * Get the end value (exclusive).
2387
- */
2388
- get endValue() {
2389
- return this._endValue;
2390
- }
2391
- /**
2392
- * Get the count of values.
2393
- */
2394
- get count() {
2395
- return this._count;
2396
- }
2397
- /**
2398
- * Get the minimum value (inclusive).
2399
- */
2400
- get minimumValue() {
2401
- return this._minimumValue;
2402
- }
2403
- /**
2404
- * Get the maximum value (inclusive).
2405
- */
2406
- get maximumValue() {
2407
- return this._maximumValue;
2408
- }
2409
- /**
2410
- * Iterable implementation.
2411
- *
2412
- * @yields
2413
- * Next value in sequence.
2414
- */
2415
- *[Symbol.iterator]() {
2416
- for (let value = this._startValue; value !== this._endValue; value += this._nextDelta) {
2417
- yield value;
2418
- }
2419
- }
2420
- };
2421
-
2422
- // src/iterable-utility.ts
2423
- function mapIterable(values, indexedCallback) {
2424
- return {
2425
- /**
2426
- * Iterable implementation.
2427
- *
2428
- * @yields
2429
- * Next output value.
2430
- */
2431
- *[Symbol.iterator]() {
2432
- let index = 0;
2433
- for (const value of values) {
2434
- yield indexedCallback(value, index++);
2435
- }
2436
- }
2437
- };
2438
- }
2439
-
2440
- // src/transformer.ts
2441
- var Transformer = class _Transformer {
2442
- /**
2443
- * Transformers cache, mapping a domain to another map, which maps an optional tweak to a transformer.
2444
- */
2445
- static TRANSFORMER_MAPS_MAP = /* @__PURE__ */ new Map();
2446
- /**
2447
- * Domain.
2448
- */
2449
- _domain;
2450
- /**
2451
- * Constructor.
2452
- *
2453
- * @param domain
2454
- * Domain.
2455
- */
2456
- constructor(domain) {
2457
- this._domain = BigInt(domain);
2458
- if (this._domain <= 0n) {
2459
- throw new RangeError(i18nextUtility.t("Transformer.domainMustBeGreaterThanZero", {
2460
- domain
2461
- }));
2462
- }
2463
- }
2464
- /**
2465
- * Get a transformer, constructing it if necessary. The type returned is {@link IdentityTransformer} if tweak is
2466
- * undefined, {@link EncryptionTransformer} if tweak is defined. Note that although an {@link EncryptionTransformer}
2467
- * with a zero tweak operates as an {@link IdentityTransformer}, {@link EncryptionTransformer} is still the type
2468
- * returned if a zero tweak is explicitly specified.
2469
- *
2470
- * @param domain
2471
- * Domain.
2472
- *
2473
- * @param tweak
2474
- * Tweak.
2475
- *
2476
- * @returns
2477
- * {@link IdentityTransformer} if tweak is undefined, {@link EncryptionTransformer} if tweak is defined.
2478
- */
2479
- static get(domain, tweak) {
2480
- const domainN = BigInt(domain);
2481
- let transformersMap = _Transformer.TRANSFORMER_MAPS_MAP.get(domainN);
2482
- if (transformersMap === void 0) {
2483
- transformersMap = /* @__PURE__ */ new Map();
2484
- _Transformer.TRANSFORMER_MAPS_MAP.set(domainN, transformersMap);
2485
- }
2486
- const tweakN = tweak === void 0 ? void 0 : BigInt(tweak);
2487
- let transformer = transformersMap.get(tweakN);
2488
- if (transformer === void 0) {
2489
- transformer = tweakN === void 0 ? new IdentityTransformer(domainN) : new EncryptionTransformer(domainN, tweakN);
2490
- transformersMap.set(tweakN, transformer);
2491
- }
2492
- return transformer;
2493
- }
2494
- /**
2495
- * Get the domain.
2496
- */
2497
- get domain() {
2498
- return this._domain;
2499
- }
2500
- /**
2501
- * Validate that a value is within the domain.
2502
- *
2503
- * @param value
2504
- * Value.
2505
- */
2506
- validate(value) {
2507
- if (value < 0n) {
2508
- throw new RangeError(i18nextUtility.t("Transformer.valueMustBeGreaterThanOrEqualToZero", {
2509
- value
2510
- }));
2511
- }
2512
- if (value >= this.domain) {
2513
- throw new RangeError(i18nextUtility.t("Transformer.valueMustBeLessThan", {
2514
- value,
2515
- domain: this.domain
2516
- }));
2517
- }
2518
- }
2519
- /**
2520
- * Validate that a value is within the domain and do the work of transforming it forward.
2521
- *
2522
- * @param value
2523
- * Value.
2524
- *
2525
- * @returns
2526
- * Transformed value.
2527
- */
2528
- validateDoForward(value) {
2529
- const valueN = BigInt(value);
2530
- this.validate(valueN);
2531
- return this.doForward(valueN);
2532
- }
2533
- /**
2534
- * Validate that a value is within the domain, do the work of transforming it forward, and apply a callback.
2535
- *
2536
- * @param transformerCallback
2537
- * Called after each value is transformed to convert it to its final value.
2538
- *
2539
- * @param value
2540
- * Value.
2541
- *
2542
- * @param index
2543
- * Index in sequence (0 for single transformation).
2544
- *
2545
- * @returns
2546
- * Transformed value.
2547
- */
2548
- validateDoForwardCallback(transformerCallback, value, index) {
2549
- return transformerCallback(this.validateDoForward(value), index);
2550
- }
2551
- // eslint-disable-next-line jsdoc/require-jsdoc -- Implementation of overloaded signatures.
2552
- forward(valueOrValues, transformerCallback) {
2553
- let result;
2554
- if (typeof valueOrValues !== "object") {
2555
- result = transformerCallback === void 0 ? this.validateDoForward(valueOrValues) : this.validateDoForwardCallback(transformerCallback, valueOrValues);
2556
- } else if (valueOrValues instanceof Sequence) {
2557
- if (valueOrValues.minimumValue < 0n) {
2558
- throw new RangeError(i18nextUtility.t("Transformer.minimumValueMustBeGreaterThanOrEqualToZero", {
2559
- minimumValue: valueOrValues.minimumValue
2560
- }));
2561
- }
2562
- if (valueOrValues.maximumValue >= this.domain) {
2563
- throw new RangeError(i18nextUtility.t("Transformer.maximumValueMustBeLessThan", {
2564
- maximumValue: valueOrValues.maximumValue,
2565
- domain: this.domain
2566
- }));
2567
- }
2568
- result = transformerCallback === void 0 ? mapIterable(valueOrValues, (value) => this.doForward(value)) : mapIterable(valueOrValues, (value, index) => transformerCallback(this.doForward(value), index));
2569
- } else {
2570
- result = transformerCallback === void 0 ? mapIterable(valueOrValues, (value) => this.validateDoForward(value)) : mapIterable(valueOrValues, (value, index) => this.validateDoForwardCallback(transformerCallback, value, index));
2571
- }
2572
- return result;
2573
- }
2574
- /**
2575
- * Transform a value in reverse.
2576
- *
2577
- * @param transformedValue
2578
- * Transformed value.
2579
- *
2580
- * @returns
2581
- * Value.
2582
- */
2583
- reverse(transformedValue) {
2584
- const transformedValueN = BigInt(transformedValue);
2585
- this.validate(transformedValueN);
2586
- return this.doReverse(transformedValueN);
2587
- }
2588
- };
2589
- var IdentityTransformer = class extends Transformer {
2590
- /**
2591
- * @inheritDoc
2592
- */
2593
- doForward(value) {
2594
- return value;
2595
- }
2596
- /**
2597
- * @inheritDoc
2598
- */
2599
- doReverse(transformedValue) {
2600
- return transformedValue;
2601
- }
2602
- };
2603
- var EncryptionTransformer = class _EncryptionTransformer extends Transformer {
2604
- /**
2605
- * Individual bits, pre-calculated for performance.
2606
- */
2607
- static BITS = new Uint8Array([
2608
- 1,
2609
- 2,
2610
- 4,
2611
- 8,
2612
- 16,
2613
- 32,
2614
- 64,
2615
- 128
2616
- ]);
2617
- /**
2618
- * Inverse individual bits, pre-calculated for performance.
2619
- */
2620
- static INVERSE_BITS = new Uint8Array([
2621
- 254,
2622
- 253,
2623
- 251,
2624
- 247,
2625
- 239,
2626
- 223,
2627
- 191,
2628
- 127
2629
- ]);
2630
- /**
2631
- * Number of bytes covered by the domain.
2632
- */
2633
- _domainBytes;
2634
- /**
2635
- * Xor bytes array generated from the domain and tweak.
2636
- */
2637
- _xorBytes;
2638
- /**
2639
- * Bits array generated from the domain and tweak.
2640
- */
2641
- _bits;
2642
- /**
2643
- * Inverse bits array generated from the domain and tweak.
2644
- */
2645
- _inverseBits;
2646
- /**
2647
- * Number of rounds (length of arrays) generated from the domain and tweak.
2648
- */
2649
- _rounds;
2650
- /**
2651
- * Constructor.
2652
- *
2653
- * @param domain
2654
- * Domain.
2655
- *
2656
- * @param tweak
2657
- * Tweak.
2658
- */
2659
- constructor(domain, tweak) {
2660
- super(domain);
2661
- if (tweak < 0n) {
2662
- throw new RangeError(i18nextUtility.t("Transformer.tweakMustBeGreaterThanOrEqualToZero", {
2663
- tweak
2664
- }));
2665
- }
2666
- let domainBytes = 0;
2667
- for (let reducedDomainMinusOne = this.domain - 1n; reducedDomainMinusOne !== 0n; reducedDomainMinusOne >>= 8n) {
2668
- domainBytes++;
2669
- }
2670
- this._domainBytes = domainBytes;
2671
- const xorBytes = new Array();
2672
- const bits = new Array();
2673
- const inverseBits = new Array();
2674
- for (let reducedKey = this.domain * BigInt(tweak) * 603868999n; reducedKey !== 0n; reducedKey >>= 8n) {
2675
- xorBytes.unshift(Number(BigInt.asUintN(8, reducedKey)));
2676
- const bitNumber = Number(BigInt.asUintN(3, reducedKey));
2677
- bits.push(_EncryptionTransformer.BITS[bitNumber]);
2678
- inverseBits.push(_EncryptionTransformer.INVERSE_BITS[bitNumber]);
2679
- }
2680
- if (domainBytes === 1) {
2681
- const domainMask = _EncryptionTransformer.BITS.filter((bit) => bit < domain).reduce((accumulator, bit) => accumulator | bit, 0);
2682
- this._xorBytes = new Uint8Array([xorBytes.reduce((accumulator, xorByte) => accumulator ^ xorByte, 0) & domainMask]);
2683
- this._bits = new Uint8Array([_EncryptionTransformer.BITS[0]]);
2684
- this._inverseBits = new Uint8Array([_EncryptionTransformer.INVERSE_BITS[0]]);
2685
- this._rounds = 1;
2686
- } else {
2687
- this._xorBytes = new Uint8Array(xorBytes);
2688
- this._bits = new Uint8Array(bits);
2689
- this._inverseBits = new Uint8Array(inverseBits);
2690
- this._rounds = xorBytes.length;
2691
- }
2692
- }
2693
- /**
2694
- * Convert a value to a byte array big enough to handle the entire domain.
2695
- *
2696
- * @param value
2697
- * Value.
2698
- *
2699
- * @returns
2700
- * Big-endian byte array equivalent to the value.
2701
- */
2702
- valueToBytes(value) {
2703
- const bytes = new Uint8Array(this._domainBytes);
2704
- for (let index = this._domainBytes - 1, reducedValue = value; index >= 0 && reducedValue !== 0n; index--, reducedValue >>= 8n) {
2705
- bytes[index] = Number(BigInt.asUintN(8, reducedValue));
2706
- }
2707
- return bytes;
2708
- }
2709
- /**
2710
- * Convert a byte array to a value.
2711
- *
2712
- * @param bytes
2713
- * Big-endian byte array equivalent to the value.
2714
- *
2715
- * @returns
2716
- * Value.
2717
- */
2718
- static bytesToValue(bytes) {
2719
- return bytes.reduce((accumulator, byte) => accumulator << 8n | BigInt(byte), 0n);
2720
- }
2721
- /**
2722
- * Shuffle a byte array.
2723
- *
2724
- * The input array to the forward operation (output from the reverse operation) is `bytes` and the output array from
2725
- * the forward operation (input to the reverse operation) is `bytes'`.
2726
- *
2727
- * The shuffle operation starts by testing the bit at `bits[round]` for each `byte` in `bytes`. The indexes for all
2728
- * bytes with that bit set are put into one array (`shuffleIndexes1`) and the rest are put into another
2729
- * (`shuffleIndexes0`). The two arrays are concatenated and used to shuffle the input array, using their values
2730
- * (`shuffleIndex`) and the indexes of those values (`index`) in the concatenated array.
2731
- *
2732
- * Forward shuffling moves the entry at `shuffleIndex` to the `index` position.
2733
- *
2734
- * Reverse shuffling moves the entry at `index` to the `shuffleIndex` position.
2735
- *
2736
- * As each byte is moved, the bit at `bits[round]` is preserved in its original position. This ensures that the
2737
- * process is reversible.
2738
- *
2739
- * @param bytes
2740
- * Byte array.
2741
- *
2742
- * @param round
2743
- * Round number.
2744
- *
2745
- * @param forward
2746
- * True if operating forward (encrypting), false if operating in reverse (decrypting).
2747
- *
2748
- * @returns
2749
- * Shuffled byte array.
2750
- */
2751
- shuffle(bytes, round, forward) {
2752
- const bytesLength = bytes.length;
2753
- const determinants = new Uint8Array(bytesLength);
2754
- const shuffleIndexes1 = new Array();
2755
- const shuffleIndexes0 = new Array();
2756
- const bit = this._bits[round];
2757
- bytes.forEach((byte, index) => {
2758
- const determinant = byte & bit;
2759
- determinants[index] = determinant;
2760
- (determinant !== 0 ? shuffleIndexes1 : shuffleIndexes0).push(index);
2761
- });
2762
- const inverseBit = this._inverseBits[round];
2763
- const shuffleBytes = new Uint8Array(bytesLength);
2764
- [...shuffleIndexes1, ...shuffleIndexes0].forEach((shuffleIndex, index) => {
2765
- if (forward) {
2766
- shuffleBytes[index] = bytes[shuffleIndex] & inverseBit | determinants[index];
2767
- } else {
2768
- shuffleBytes[shuffleIndex] = bytes[index] & inverseBit | determinants[shuffleIndex];
2769
- }
2770
- });
2771
- return shuffleBytes;
2772
- }
2773
- /**
2774
- * Xor a byte array.
2775
- *
2776
- * The input array to the forward operation (output from the reverse operation) is `bytes` and the output array from
2777
- * the forward operation (input to the reverse operation) is `bytes'`.
2778
- *
2779
- * Forward:
2780
- * - `bytes'[0] = bytes[0] ^ xorBytes[round]`
2781
- * - `bytes'[1] = bytes[1] ^ bytes'[0]`
2782
- * - `bytes'[2] = bytes[2] ^ bytes'[1]`
2783
- * - `...`
2784
- * - `bytes'[domainBytes - 1] = bytes[domainBytes - 1] ^ bytes'[domainBytes - 2]`
2785
- *
2786
- * Reverse:
2787
- * - `bytes[0] = bytes'[0] ^ xorBytes[round]`
2788
- * - `bytes[1] = bytes'[1] ^ bytes'[0]`
2789
- * - `bytes[2] = bytes'[2] ^ bytes'[1]`
2790
- * - `...`
2791
- * - `bytes[domainBytes - 1] = bytes'[domainBytes - 1] ^ bytes'[domainBytes - 2]`
2792
- *
2793
- * @param bytes
2794
- * Byte array.
2795
- *
2796
- * @param round
2797
- * Round number.
2798
- *
2799
- * @param forward
2800
- * True if operating forward (encrypting), false if operating in reverse (decrypting).
2801
- *
2802
- * @returns
2803
- * Xored byte array.
2804
- */
2805
- xor(bytes, round, forward) {
2806
- let cumulativeXorByte = this._xorBytes[round];
2807
- return bytes.map((byte) => {
2808
- const xorByte = byte ^ cumulativeXorByte;
2809
- cumulativeXorByte = forward ? xorByte : byte;
2810
- return xorByte;
2811
- });
2812
- }
2813
- /**
2814
- * @inheritDoc
2815
- */
2816
- doForward(value) {
2817
- let bytes = this.valueToBytes(value);
2818
- let transformedValue;
2819
- do {
2820
- for (let round = 0; round < this._rounds; round++) {
2821
- bytes = this.xor(this.shuffle(bytes, round, true), round, true);
2822
- }
2823
- transformedValue = _EncryptionTransformer.bytesToValue(bytes);
2824
- } while (transformedValue >= this.domain);
2825
- return transformedValue;
2826
- }
2827
- /**
2828
- * @inheritDoc
2829
- */
2830
- doReverse(transformedValue) {
2831
- let bytes = this.valueToBytes(transformedValue);
2832
- let value;
2833
- do {
2834
- for (let round = this._rounds - 1; round >= 0; round--) {
2835
- bytes = this.shuffle(this.xor(bytes, round, false), round, false);
2836
- }
2837
- value = _EncryptionTransformer.bytesToValue(bytes);
2838
- } while (value >= this.domain);
2839
- return value;
2840
- }
2841
- };
2842
-
2843
- // src/reg-exp.ts
2844
- var RegExpValidator = class {
2845
- /**
2846
- * Regular expression.
2847
- */
2848
- _regExp;
2849
- /**
2850
- * Constructor.
2851
- *
2852
- * @param regExp
2853
- * Regular expression. See {@link RegExpValidator | class documentation} for notes.
2854
- */
2855
- constructor(regExp) {
2856
- this._regExp = regExp;
2857
- }
2858
- /**
2859
- * Get the regular expression.
2860
- */
2861
- get regExp() {
2862
- return this._regExp;
2863
- }
2864
- /**
2865
- * Create an error message for a string. The generic error message is sufficient for many use cases but a more
2866
- * domain-specific error message, possibly including the pattern itself, is often required.
2867
- *
2868
- * @param s
2869
- * String.
2870
- *
2871
- * @returns
2872
- * Error message.
2873
- */
2874
- createErrorMessage(s) {
2875
- return i18nextUtility.t("RegExpValidator.stringDoesNotMatchPattern", {
2876
- s
2877
- });
2878
- }
2879
- /**
2880
- * @inheritDoc
2881
- */
2882
- validate(s) {
2883
- if (!this._regExp.test(s)) {
2884
- throw new RangeError(this.createErrorMessage(s));
2885
- }
2886
- }
2887
- };
2888
-
2889
- // src/record.ts
2890
- var RecordValidator = class {
2891
- /**
2892
- * Type name for error message.
2893
- */
2894
- _typeName;
2895
- /**
2896
- * Record in which to look up keys.
2897
- */
2898
- _record;
2899
- /**
2900
- * Constructor.
2901
- *
2902
- * @param typeName
2903
- * Type name for error message.
2904
- *
2905
- * @param record
2906
- * Record in which to look up keys.
2907
- */
2908
- constructor(typeName, record) {
2909
- this._typeName = typeName;
2910
- this._record = record;
2911
- }
2912
- /**
2913
- * Get the type name.
2914
- */
2915
- get typeName() {
2916
- return this._typeName;
2917
- }
2918
- /**
2919
- * Get the record.
2920
- */
2921
- get record() {
2922
- return this._record;
2923
- }
2924
- /**
2925
- * Validate a key by looking it up in the record.
2926
- *
2927
- * @param key
2928
- * Record key.
2929
- */
2930
- validate(key) {
2931
- if (!(key in this.record)) {
2932
- throw new RangeError(i18nextUtility.t("RecordValidator.typeNameKeyNotFound", {
2933
- typeName: this.typeName,
2934
- key
2935
- }));
2936
- }
2937
- }
2938
- };
2939
-
2940
- // src/exclusion.ts
2941
- var Exclusions = {
2942
- /**
2943
- * No strings excluded.
2944
- */
2945
- None: 0,
2946
- /**
2947
- * Strings that start with zero ('0') excluded.
2948
- */
2949
- FirstZero: 1,
2950
- /**
2951
- * Strings that are all-numeric (e.g., "123456") excluded.
2952
- */
2953
- AllNumeric: 2
2954
- };
2955
-
2956
- // src/character-set.ts
2957
- var CharacterSetValidator = class _CharacterSetValidator {
2958
- static NOT_ALL_NUMERIC_VALIDATOR = new class extends RegExpValidator {
2959
- /**
2960
- * Create an error message for an all-numeric string.
2961
- *
2962
- * @param _s
2963
- * String.
2964
- *
2965
- * @returns
2966
- * Error message.
2967
- */
2968
- createErrorMessage(_s) {
2969
- return i18nextUtility.t("CharacterSetValidator.stringMustNotBeAllNumeric");
2970
- }
2971
- }(/\D/);
2972
- /**
2973
- * Character set.
2974
- */
2975
- _characterSet;
2976
- /**
2977
- * Character set map, mapping each character in the character set to its index such that
2978
- * `_characterSetMap.get(_characterSet[index]) === index`.
2979
- */
2980
- _characterSetMap;
2981
- /**
2982
- * Exclusions supported by the character set.
2983
- */
2984
- _exclusionSupport;
2985
- /**
2986
- * Constructor.
2987
- *
2988
- * @param characterSet
2989
- * Character set. Each element is a single-character string, unique within the array, that defines the character
2990
- * set.
2991
- *
2992
- * @param exclusionSupport
2993
- * Exclusions supported by the character set. All character sets implicitly support {@link Exclusions.None}.
2994
- */
2995
- constructor(characterSet, ...exclusionSupport) {
2996
- this._characterSet = characterSet;
2997
- const characterSetMap = /* @__PURE__ */ new Map();
2998
- characterSet.forEach((c, index) => {
2999
- characterSetMap.set(c, index);
3000
- });
3001
- this._characterSetMap = characterSetMap;
3002
- this._exclusionSupport = exclusionSupport;
3003
- }
3004
- /**
3005
- * Get the character set.
3006
- */
3007
- get characterSet() {
3008
- return this._characterSet;
3009
- }
3010
- /**
3011
- * Get the character set size.
3012
- */
3013
- get characterSetSize() {
3014
- return this._characterSet.length;
3015
- }
3016
- /**
3017
- * Get the exclusions supported by the character set.
3018
- */
3019
- get exclusionSupport() {
3020
- return this._exclusionSupport;
3021
- }
3022
- /**
3023
- * Get the character at an index.
3024
- *
3025
- * @param index
3026
- * Index into the character set.
3027
- *
3028
- * @returns
3029
- * Character at the index.
3030
- */
3031
- character(index) {
3032
- return this._characterSet[index];
3033
- }
3034
- /**
3035
- * Get the index for a character.
3036
- *
3037
- * @param c
3038
- * Character.
3039
- *
3040
- * @returns
3041
- * Index for the character or undefined if the character is not in the character set.
3042
- */
3043
- characterIndex(c) {
3044
- return this._characterSetMap.get(c);
3045
- }
3046
- /**
3047
- * Get the indexes for all characters in a string.
3048
- *
3049
- * @param s
3050
- * String.
3051
- *
3052
- * @returns
3053
- * Array of indexes for each character or undefined if the character is not in the character set.
3054
- */
3055
- characterIndexes(s) {
3056
- return Array.from(s).map((c) => this._characterSetMap.get(c));
3057
- }
3058
- /**
3059
- * Convert a component definition to a string or undefined. Checks the type of the component and makes the callback
3060
- * if required.
3061
- *
3062
- * @param component
3063
- * Component definition as a string, callback, or undefined.
3064
- *
3065
- * @returns
3066
- * Component as a string or undefined.
3067
- */
3068
- static componentToString(component) {
3069
- return typeof component === "function" ? component() : component;
3070
- }
3071
- /**
3072
- * Validate that an exclusion is supported. If not, an error is thrown.
3073
- *
3074
- * @param exclusion
3075
- * Exclusion.
3076
- */
3077
- validateExclusion(exclusion) {
3078
- if (exclusion !== Exclusions.None && !this._exclusionSupport.includes(exclusion)) {
3079
- throw new RangeError(i18nextUtility.t("CharacterSetValidator.exclusionNotSupported", {
3080
- exclusion
3081
- }));
3082
- }
3083
- }
3084
- /**
3085
- * Validate a string. If the string violates the character set or any of the character set validation parameters, an
3086
- * error is thrown.
3087
- *
3088
- * @param s
3089
- * String.
3090
- *
3091
- * @param validation
3092
- * Character set validation parameters.
3093
- */
3094
- validate(s, validation) {
3095
- const length = s.length;
3096
- const minimumLength = validation?.minimumLength;
3097
- const maximumLength = validation?.maximumLength;
3098
- if (minimumLength !== void 0 && length < minimumLength) {
3099
- let errorMessage;
3100
- if (maximumLength !== void 0 && maximumLength === minimumLength) {
3101
- errorMessage = i18nextUtility.t(validation?.component === void 0 ? "CharacterSetValidator.lengthMustBeEqualTo" : "CharacterSetValidator.lengthOfComponentMustBeEqualTo", {
3102
- component: _CharacterSetValidator.componentToString(validation?.component),
3103
- length,
3104
- exactLength: minimumLength
3105
- });
3106
- } else {
3107
- errorMessage = i18nextUtility.t(validation?.component === void 0 ? "CharacterSetValidator.lengthMustBeGreaterThanOrEqualTo" : "CharacterSetValidator.lengthOfComponentMustBeGreaterThanOrEqualTo", {
3108
- component: _CharacterSetValidator.componentToString(validation?.component),
3109
- length,
3110
- minimumLength
3111
- });
3112
- }
3113
- throw new RangeError(errorMessage);
3114
- }
3115
- if (maximumLength !== void 0 && length > maximumLength) {
3116
- throw new RangeError(i18nextUtility.t(validation?.component === void 0 ? "CharacterSetValidator.lengthMustBeLessThanOrEqualTo" : "CharacterSetValidator.lengthOfComponentMustBeLessThanOrEqualTo", {
3117
- component: _CharacterSetValidator.componentToString(validation?.component),
3118
- length,
3119
- maximumLength
3120
- }));
3121
- }
3122
- const index = this.characterIndexes(s).findIndex((characterIndex) => characterIndex === void 0);
3123
- if (index !== -1) {
3124
- throw new RangeError(i18nextUtility.t(validation?.component === void 0 ? "CharacterSetValidator.invalidCharacterAtPosition" : "CharacterSetValidator.invalidCharacterAtPositionOfComponent", {
3125
- component: _CharacterSetValidator.componentToString(validation?.component),
3126
- c: s.charAt(index),
3127
- position: index + (validation?.positionOffset ?? 0) + 1
3128
- }));
3129
- }
3130
- if (validation?.exclusion !== void 0) {
3131
- this.validateExclusion(validation.exclusion);
3132
- switch (validation.exclusion) {
3133
- case Exclusions.None:
3134
- break;
3135
- case Exclusions.FirstZero:
3136
- if (s.startsWith("0")) {
3137
- throw new RangeError(i18nextUtility.t(validation.component === void 0 ? "CharacterSetValidator.invalidCharacterAtPosition" : "CharacterSetValidator.invalidCharacterAtPositionOfComponent", {
3138
- component: _CharacterSetValidator.componentToString(validation.component),
3139
- c: "0",
3140
- position: (validation.positionOffset ?? 0) + 1
3141
- }));
3142
- }
3143
- break;
3144
- case Exclusions.AllNumeric:
3145
- _CharacterSetValidator.NOT_ALL_NUMERIC_VALIDATOR.validate(s);
3146
- break;
3147
- }
3148
- }
3149
- }
3150
- };
3151
- var CharacterSetCreator = class _CharacterSetCreator extends CharacterSetValidator {
3152
- /**
3153
- * Maximum string length supported.
3154
- */
3155
- static MAXIMUM_STRING_LENGTH = 40;
3156
- /**
3157
- * Powers of 10 from 1 (`10**0`) to `10**MAXIMUM_STRING_LENGTH`.
3158
- */
3159
- static _powersOf10 = _CharacterSetCreator.createPowersOf(10);
3160
- /**
3161
- * Create powers of a given base from 1 (`base**0`) to `base**MAXIMUM_STRING_LENGTH`.
3162
- *
3163
- * @param base
3164
- * Number base.
3165
- *
3166
- * @returns
3167
- * Array of powers of base.
3168
- */
3169
- static createPowersOf(base) {
3170
- const powersOf = new Array(this.MAXIMUM_STRING_LENGTH + 1);
3171
- const baseN = BigInt(base);
3172
- for (let index = 0, powerOf = 1n; index <= this.MAXIMUM_STRING_LENGTH; index++, powerOf *= baseN) {
3173
- powersOf[index] = powerOf;
3174
- }
3175
- return powersOf;
3176
- }
3177
- /**
3178
- * Get a power of 10.
3179
- *
3180
- * @param power
3181
- * Power.
3182
- *
3183
- * @returns
3184
- * `10**power`.
3185
- */
3186
- static powerOf10(power) {
3187
- return this._powersOf10[power];
3188
- }
3189
- /**
3190
- * Character set size as big integer, cached for performance purposes.
3191
- */
3192
- _characterSetSizeN;
3193
- /**
3194
- * Character set size minus 1 as big integer, cached for performance purposes.
3195
- */
3196
- _characterSetSizeMinusOneN;
3197
- /**
3198
- * Domains for every length for every supported {@link Exclusions}.
3199
- */
3200
- _exclusionDomains;
3201
- /**
3202
- * Values that would generate all zeros in the created string.
3203
- */
3204
- _allZerosValues;
3205
- /**
3206
- * Constructor.
3207
- *
3208
- * @param characterSet
3209
- * Character set. Each element is a single-character string, unique within the array, that defines the character
3210
- * set.
3211
- *
3212
- * @param exclusionSupport
3213
- * Exclusions supported by the character set. All character sets implicitly support {@link Exclusions.None}.
3214
- */
3215
- constructor(characterSet, ...exclusionSupport) {
3216
- super(characterSet, ...exclusionSupport);
3217
- this._characterSetSizeN = BigInt(this.characterSetSize);
3218
- this._characterSetSizeMinusOneN = BigInt(this.characterSetSize - 1);
3219
- const exclusionDomains = [];
3220
- const exclusionNoneDomains = _CharacterSetCreator.createPowersOf(this.characterSetSize);
3221
- exclusionDomains[Exclusions.None] = exclusionNoneDomains;
3222
- if (exclusionSupport.includes(Exclusions.FirstZero)) {
3223
- if (characterSet[0] !== "0") {
3224
- throw new RangeError(i18nextUtility.t("CharacterSetValidator.firstZeroFirstCharacter"));
3225
- }
3226
- const exclusionFirstZeroDomains = new Array(_CharacterSetCreator.MAXIMUM_STRING_LENGTH + 1);
3227
- exclusionFirstZeroDomains[0] = 0n;
3228
- for (let index = 1; index <= _CharacterSetCreator.MAXIMUM_STRING_LENGTH; index++) {
3229
- exclusionFirstZeroDomains[index] = this._characterSetSizeMinusOneN * exclusionNoneDomains[index - 1];
3230
- }
3231
- exclusionDomains[Exclusions.FirstZero] = exclusionFirstZeroDomains;
3232
- }
3233
- if (exclusionSupport.includes(Exclusions.AllNumeric)) {
3234
- let validateNumberIndexes2 = function(numberIndexes2) {
3235
- let expectedNumberIndex = numberIndexes2[0];
3236
- for (const numberIndex of numberIndexes2) {
3237
- if (numberIndex === void 0 || numberIndex !== expectedNumberIndex) {
3238
- throw new RangeError(i18nextUtility.t("CharacterSetValidator.allNumericAllNumericCharacters"));
3239
- }
3240
- expectedNumberIndex = numberIndex + 1;
3241
- }
3242
- };
3243
- var validateNumberIndexes = validateNumberIndexes2;
3244
- const exclusionAllNumericDomains = new Array(_CharacterSetCreator.MAXIMUM_STRING_LENGTH + 1);
3245
- const numberIndexes = this.characterIndexes("0123456789");
3246
- validateNumberIndexes2(numberIndexes);
3247
- const zeroIndex = BigInt(numberIndexes[0]);
3248
- const allZerosValues = new Array(_CharacterSetCreator.MAXIMUM_STRING_LENGTH + 1);
3249
- let allZerosValue = 0n;
3250
- for (let index = 0; index <= _CharacterSetCreator.MAXIMUM_STRING_LENGTH; index++) {
3251
- exclusionAllNumericDomains[index] = exclusionNoneDomains[index] - _CharacterSetCreator.powerOf10(index);
3252
- allZerosValues[index] = allZerosValue;
3253
- allZerosValue = allZerosValue * this._characterSetSizeN + zeroIndex;
3254
- }
3255
- this._allZerosValues = allZerosValues;
3256
- exclusionDomains[Exclusions.AllNumeric] = exclusionAllNumericDomains;
3257
- } else {
3258
- this._allZerosValues = [];
3259
- }
3260
- this._exclusionDomains = exclusionDomains;
3261
- }
3262
- /**
3263
- * Get a power of character set size.
3264
- *
3265
- * @param power
3266
- * Power.
3267
- *
3268
- * @returns
3269
- * `characterSetSize**power`.
3270
- */
3271
- powerOfSize(power) {
3272
- return this._exclusionDomains[Exclusions.None][power];
3273
- }
3274
- /**
3275
- * Determine the shift required to skip all all-numeric strings up to the value.
3276
- *
3277
- * @param shiftForward
3278
- * True to shift forward (value to string), false to shift backward (string to value).
3279
- *
3280
- * @param length
3281
- * Length of string for which to get the all-numeric shift.
3282
- *
3283
- * @param value
3284
- * Value for which to get the all-numeric shift.
3285
- *
3286
- * @returns
3287
- * Shift required to skip all all-numeric strings.
3288
- */
3289
- allNumericShift(shiftForward, length, value) {
3290
- let shift;
3291
- if (length === 0) {
3292
- if (!shiftForward && value < 10n) {
3293
- throw new RangeError(i18nextUtility.t("CharacterSetValidator.stringMustNotBeAllNumeric"));
3294
- }
3295
- shift = 10n;
3296
- } else {
3297
- const powerOfSize = this.powerOfSize(length);
3298
- const powerOf10 = _CharacterSetCreator.powerOf10(length);
3299
- const gap = shiftForward ? powerOfSize - powerOf10 : powerOfSize;
3300
- const gaps = value / gap;
3301
- if (gaps >= 10n) {
3302
- shift = _CharacterSetCreator.powerOf10(length + 1);
3303
- } else {
3304
- shift = gaps * powerOf10 + this.allNumericShift(shiftForward, length - 1, value - gaps * gap);
3305
- }
3306
- }
3307
- return shift;
3308
- }
3309
- /**
3310
- * Validate that a length is less than or equal to {@link MAXIMUM_STRING_LENGTH}. If not, an error is thrown.
3311
- *
3312
- * @param length
3313
- * Length.
3314
- */
3315
- validateLength(length) {
3316
- if (length < 0) {
3317
- throw new RangeError(i18nextUtility.t("CharacterSetValidator.lengthMustBeGreaterThanOrEqualTo", {
3318
- length,
3319
- minimumLength: 0
3320
- }));
3321
- }
3322
- if (length > _CharacterSetCreator.MAXIMUM_STRING_LENGTH) {
3323
- throw new RangeError(i18nextUtility.t("CharacterSetValidator.lengthMustBeLessThanOrEqualTo", {
3324
- length,
3325
- maximumLength: _CharacterSetCreator.MAXIMUM_STRING_LENGTH
3326
- }));
3327
- }
3328
- }
3329
- /**
3330
- * Create string(s) by mapping value(s) to the equivalent characters in the character set across the length of the
3331
- * string.
3332
- *
3333
- * @template TTransformerInput
3334
- * Transformer input type.
3335
- *
3336
- * @param length
3337
- * Required string length.
3338
- *
3339
- * @param valueOrValues
3340
- * Numeric value(s) of the string(s).
3341
- *
3342
- * @param exclusion
3343
- * String(s) to be excluded from the range of outputs. See {@link Exclusions} for possible values and their meaning.
3344
- *
3345
- * @param tweak
3346
- * If provided, the numerical value of the string(s) is/are "tweaked" using an {@link EncryptionTransformer |
3347
- * encryption transformer}.
3348
- *
3349
- * @param creatorCallback
3350
- * If provided, called after each string is constructed to create the final value.
3351
- *
3352
- * @returns
3353
- * String(s) created from the value(s).
3354
- */
3355
- create(length, valueOrValues, exclusion = Exclusions.None, tweak, creatorCallback) {
3356
- this.validateLength(length);
3357
- this.validateExclusion(exclusion);
3358
- const allZerosValue = exclusion === Exclusions.AllNumeric ? this._allZerosValues[length] : 0n;
3359
- const transformer = Transformer.get(this._exclusionDomains[exclusion][length], tweak);
3360
- return transformer.forward(valueOrValues, (transformedValue, index) => {
3361
- let s = "";
3362
- if (length !== 0) {
3363
- let convertValue = transformedValue;
3364
- if (exclusion === Exclusions.AllNumeric && convertValue >= allZerosValue) {
3365
- convertValue = convertValue + this.allNumericShift(true, length, convertValue - allZerosValue);
3366
- }
3367
- for (let position = length - 1; position > 0; position--) {
3368
- const nextConvertValue = convertValue / this._characterSetSizeN;
3369
- s = this.character(Number(convertValue - nextConvertValue * this._characterSetSizeN)) + s;
3370
- convertValue = nextConvertValue;
3371
- }
3372
- s = this.character(exclusion === Exclusions.FirstZero ? Number(convertValue % this._characterSetSizeMinusOneN) + 1 : Number(convertValue % this._characterSetSizeN)) + s;
3373
- }
3374
- return creatorCallback === void 0 ? s : creatorCallback(s, index);
3375
- });
3376
- }
3377
- /**
3378
- * Determine the value for a string.
3379
- *
3380
- * @param s
3381
- * String.
3382
- *
3383
- * @param exclusion
3384
- * Strings excluded from the range of inputs. See {@link Exclusions} for possible values and their meaning.
3385
- *
3386
- * @param tweak
3387
- * If provided, the numerical value of the string was "tweaked" using an {@link EncryptionTransformer | encryption
3388
- * transformer}.
3389
- *
3390
- * @returns
3391
- * Numeric value of the string.
3392
- */
3393
- valueFor(s, exclusion = Exclusions.None, tweak) {
3394
- const length = s.length;
3395
- this.validateLength(length);
3396
- this.validateExclusion(exclusion);
3397
- const characterSetSizeN = BigInt(this.characterSetSize);
3398
- let value = this.characterIndexes(s).reduce((accumulator, characterIndex, index) => {
3399
- if (characterIndex === void 0) {
3400
- throw new RangeError(i18nextUtility.t("CharacterSetValidator.invalidCharacterAtPosition", {
3401
- c: s.charAt(index),
3402
- position: index + 1
3403
- }));
3404
- }
3405
- let value2;
3406
- if (index === 0 && exclusion === Exclusions.FirstZero) {
3407
- if (characterIndex === 0) {
3408
- throw new RangeError(i18nextUtility.t("CharacterSetValidator.invalidCharacterAtPosition", {
3409
- c: "0",
3410
- position: 1
3411
- }));
3412
- }
3413
- value2 = BigInt(characterIndex - 1);
3414
- } else {
3415
- value2 = accumulator * characterSetSizeN + BigInt(characterIndex);
3416
- }
3417
- return value2;
3418
- }, 0n);
3419
- if (exclusion === Exclusions.AllNumeric) {
3420
- const allZerosValue = this._allZerosValues[length];
3421
- if (value >= allZerosValue) {
3422
- value -= this.allNumericShift(false, length, value - allZerosValue);
3423
- }
3424
- }
3425
- return Transformer.get(this._exclusionDomains[exclusion][length], tweak).reverse(value);
3426
- }
3427
- };
3428
- var NUMERIC_CREATOR = new CharacterSetCreator([
3429
- "0",
3430
- "1",
3431
- "2",
3432
- "3",
3433
- "4",
3434
- "5",
3435
- "6",
3436
- "7",
3437
- "8",
3438
- "9"
3439
- ], Exclusions.FirstZero);
3440
- var NUMERIC_VALIDATOR = NUMERIC_CREATOR;
3441
- var HEXADECIMAL_CREATOR = new CharacterSetCreator([
3442
- "0",
3443
- "1",
3444
- "2",
3445
- "3",
3446
- "4",
3447
- "5",
3448
- "6",
3449
- "7",
3450
- "8",
3451
- "9",
3452
- "A",
3453
- "B",
3454
- "C",
3455
- "D",
3456
- "E",
3457
- "F"
3458
- ], Exclusions.FirstZero, Exclusions.AllNumeric);
3459
- var HEXADECIMAL_VALIDATOR = HEXADECIMAL_CREATOR;
3460
- var ALPHABETIC_CREATOR = new CharacterSetCreator([
3461
- "A",
3462
- "B",
3463
- "C",
3464
- "D",
3465
- "E",
3466
- "F",
3467
- "G",
3468
- "H",
3469
- "I",
3470
- "J",
3471
- "K",
3472
- "L",
3473
- "M",
3474
- "N",
3475
- "O",
3476
- "P",
3477
- "Q",
3478
- "R",
3479
- "S",
3480
- "T",
3481
- "U",
3482
- "V",
3483
- "W",
3484
- "X",
3485
- "Y",
3486
- "Z"
3487
- ]);
3488
- var ALPHABETIC_VALIDATOR = ALPHABETIC_CREATOR;
3489
- var ALPHANUMERIC_CREATOR = new CharacterSetCreator([
3490
- "0",
3491
- "1",
3492
- "2",
3493
- "3",
3494
- "4",
3495
- "5",
3496
- "6",
3497
- "7",
3498
- "8",
3499
- "9",
3500
- "A",
3501
- "B",
3502
- "C",
3503
- "D",
3504
- "E",
3505
- "F",
3506
- "G",
3507
- "H",
3508
- "I",
3509
- "J",
3510
- "K",
3511
- "L",
3512
- "M",
3513
- "N",
3514
- "O",
3515
- "P",
3516
- "Q",
3517
- "R",
3518
- "S",
3519
- "T",
3520
- "U",
3521
- "V",
3522
- "W",
3523
- "X",
3524
- "Y",
3525
- "Z"
3526
- ], Exclusions.FirstZero, Exclusions.AllNumeric);
3527
- var ALPHANUMERIC_VALIDATOR = ALPHANUMERIC_CREATOR;
3528
- // Annotate the CommonJS export names for ESM import in node:
3529
- 0 && (module.exports = {
3530
- ALPHABETIC_CREATOR,
3531
- ALPHABETIC_VALIDATOR,
3532
- ALPHANUMERIC_CREATOR,
3533
- ALPHANUMERIC_VALIDATOR,
3534
- CharacterSetCreator,
3535
- CharacterSetValidator,
3536
- EncryptionTransformer,
3537
- Exclusions,
3538
- HEXADECIMAL_CREATOR,
3539
- HEXADECIMAL_VALIDATOR,
3540
- IdentityTransformer,
3541
- NUMERIC_CREATOR,
3542
- NUMERIC_VALIDATOR,
3543
- RecordValidator,
3544
- RegExpValidator,
3545
- Sequence,
3546
- Transformer,
3547
- i18nUtilityInit,
3548
- i18nextUtility,
3549
- mapIterable,
3550
- utilityNS,
3551
- utilityResources
3552
- });
3553
- /*!
3554
- * Copyright © 2024-2025 Dolphin Data Development Ltd. and AIDC Toolkit
3555
- * contributors
3556
- *
3557
- * Licensed under the Apache License, Version 2.0 (the "License");
3558
- * you may not use this file except in compliance with the License.
3559
- * You may obtain a copy of the License at
3560
- *
3561
- * https://www.apache.org/licenses/LICENSE-2.0
3562
- *
3563
- * Unless required by applicable law or agreed to in writing, software
3564
- * distributed under the License is distributed on an "AS IS" BASIS,
3565
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
3566
- * See the License for the specific language governing permissions and
3567
- * limitations under the License.
3568
- */
3569
- //# sourceMappingURL=index.cjs.map