@aidc-toolkit/gs1 1.0.23-beta → 1.0.24-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 (131) hide show
  1. package/dist/index.cjs +4624 -0
  2. package/dist/index.cjs.map +1 -0
  3. package/dist/index.d.cts +1588 -0
  4. package/dist/index.d.ts +1588 -36
  5. package/dist/index.js +4541 -19
  6. package/dist/index.js.map +1 -1
  7. package/package.json +4 -8
  8. package/src/character-set.ts +16 -1
  9. package/src/check.ts +2 -2
  10. package/src/gtin-creator.ts +4 -4
  11. package/src/gtin-validator.ts +6 -6
  12. package/src/identifier-creator.ts +3 -3
  13. package/src/identifier-validator.ts +4 -4
  14. package/src/index.ts +19 -19
  15. package/src/locale/i18n.ts +3 -5
  16. package/src/locale/i18next.d.ts +1 -1
  17. package/src/non-gtin-numeric-identifier-creator.ts +4 -4
  18. package/src/non-gtin-numeric-identifier-validator.ts +3 -3
  19. package/src/non-numeric-identifier-creator.ts +6 -6
  20. package/src/non-numeric-identifier-validator.ts +6 -6
  21. package/src/numeric-identifier-creator.ts +3 -3
  22. package/src/numeric-identifier-validator.ts +5 -5
  23. package/src/prefix-manager.ts +16 -16
  24. package/src/prefix-provider.ts +1 -1
  25. package/src/prefix-validator.ts +2 -2
  26. package/src/serializable-numeric-identifier-creator.ts +4 -4
  27. package/src/serializable-numeric-identifier-validator.ts +5 -5
  28. package/test/creator.test.ts +3 -3
  29. package/test/gtin-creator.ts +1 -1
  30. package/test/gtin-validator.test.ts +1 -1
  31. package/test/identifier-creator.ts +4 -4
  32. package/test/non-gtin-numeric-identifier-creator.ts +1 -1
  33. package/test/non-gtin-numeric-identifier-validator.ts +1 -1
  34. package/test/non-numeric-identifier-validator.ts +2 -2
  35. package/test/numeric-identifier-creator.ts +1 -1
  36. package/test/numeric-identifier-validator.ts +1 -1
  37. package/test/prefix-manager.test.ts +1 -1
  38. package/test/serializable-numeric-identifier-creator.ts +1 -1
  39. package/test/serializable-numeric-identifier-validator.ts +2 -2
  40. package/test/validator.test.ts +4 -4
  41. package/tsup.config.ts +3 -0
  42. package/typedoc.json +1 -3
  43. package/dist/character-set.d.ts +0 -22
  44. package/dist/character-set.d.ts.map +0 -1
  45. package/dist/character-set.js +0 -36
  46. package/dist/character-set.js.map +0 -1
  47. package/dist/check.d.ts +0 -81
  48. package/dist/check.d.ts.map +0 -1
  49. package/dist/check.js +0 -218
  50. package/dist/check.js.map +0 -1
  51. package/dist/gtin-creator.d.ts +0 -68
  52. package/dist/gtin-creator.d.ts.map +0 -1
  53. package/dist/gtin-creator.js +0 -158
  54. package/dist/gtin-creator.js.map +0 -1
  55. package/dist/gtin-validator.d.ts +0 -202
  56. package/dist/gtin-validator.d.ts.map +0 -1
  57. package/dist/gtin-validator.js +0 -470
  58. package/dist/gtin-validator.js.map +0 -1
  59. package/dist/identifier-creator.d.ts +0 -72
  60. package/dist/identifier-creator.d.ts.map +0 -1
  61. package/dist/identifier-creator.js +0 -50
  62. package/dist/identifier-creator.js.map +0 -1
  63. package/dist/identifier-type.d.ts +0 -58
  64. package/dist/identifier-type.d.ts.map +0 -1
  65. package/dist/identifier-type.js +0 -54
  66. package/dist/identifier-type.js.map +0 -1
  67. package/dist/identifier-validator.d.ts +0 -174
  68. package/dist/identifier-validator.d.ts.map +0 -1
  69. package/dist/identifier-validator.js +0 -145
  70. package/dist/identifier-validator.js.map +0 -1
  71. package/dist/index.d.ts.map +0 -1
  72. package/dist/locale/en/locale-resources.d.ts +0 -43
  73. package/dist/locale/en/locale-resources.d.ts.map +0 -1
  74. package/dist/locale/en/locale-resources.js +0 -42
  75. package/dist/locale/en/locale-resources.js.map +0 -1
  76. package/dist/locale/fr/locale-resources.d.ts +0 -43
  77. package/dist/locale/fr/locale-resources.d.ts.map +0 -1
  78. package/dist/locale/fr/locale-resources.js +0 -42
  79. package/dist/locale/fr/locale-resources.js.map +0 -1
  80. package/dist/locale/i18n.d.ts +0 -27
  81. package/dist/locale/i18n.d.ts.map +0 -1
  82. package/dist/locale/i18n.js +0 -37
  83. package/dist/locale/i18n.js.map +0 -1
  84. package/dist/non-gtin-numeric-identifier-creator.d.ts +0 -30
  85. package/dist/non-gtin-numeric-identifier-creator.d.ts.map +0 -1
  86. package/dist/non-gtin-numeric-identifier-creator.js +0 -30
  87. package/dist/non-gtin-numeric-identifier-creator.js.map +0 -1
  88. package/dist/non-gtin-numeric-identifier-validator.d.ts +0 -41
  89. package/dist/non-gtin-numeric-identifier-validator.d.ts.map +0 -1
  90. package/dist/non-gtin-numeric-identifier-validator.js +0 -40
  91. package/dist/non-gtin-numeric-identifier-validator.js.map +0 -1
  92. package/dist/non-numeric-identifier-creator.d.ts +0 -55
  93. package/dist/non-numeric-identifier-creator.d.ts.map +0 -1
  94. package/dist/non-numeric-identifier-creator.js +0 -93
  95. package/dist/non-numeric-identifier-creator.js.map +0 -1
  96. package/dist/non-numeric-identifier-validator.d.ts +0 -78
  97. package/dist/non-numeric-identifier-validator.d.ts.map +0 -1
  98. package/dist/non-numeric-identifier-validator.js +0 -95
  99. package/dist/non-numeric-identifier-validator.js.map +0 -1
  100. package/dist/numeric-identifier-creator.d.ts +0 -121
  101. package/dist/numeric-identifier-creator.d.ts.map +0 -1
  102. package/dist/numeric-identifier-creator.js +0 -135
  103. package/dist/numeric-identifier-creator.js.map +0 -1
  104. package/dist/numeric-identifier-validator.d.ts +0 -76
  105. package/dist/numeric-identifier-validator.d.ts.map +0 -1
  106. package/dist/numeric-identifier-validator.js +0 -84
  107. package/dist/numeric-identifier-validator.js.map +0 -1
  108. package/dist/prefix-manager.d.ts +0 -224
  109. package/dist/prefix-manager.d.ts.map +0 -1
  110. package/dist/prefix-manager.js +0 -369
  111. package/dist/prefix-manager.js.map +0 -1
  112. package/dist/prefix-provider.d.ts +0 -27
  113. package/dist/prefix-provider.d.ts.map +0 -1
  114. package/dist/prefix-provider.js +0 -2
  115. package/dist/prefix-provider.js.map +0 -1
  116. package/dist/prefix-type.d.ts +0 -22
  117. package/dist/prefix-type.d.ts.map +0 -1
  118. package/dist/prefix-type.js +0 -18
  119. package/dist/prefix-type.js.map +0 -1
  120. package/dist/prefix-validator.d.ts +0 -58
  121. package/dist/prefix-validator.d.ts.map +0 -1
  122. package/dist/prefix-validator.js +0 -154
  123. package/dist/prefix-validator.js.map +0 -1
  124. package/dist/serializable-numeric-identifier-creator.d.ts +0 -86
  125. package/dist/serializable-numeric-identifier-creator.d.ts.map +0 -1
  126. package/dist/serializable-numeric-identifier-creator.js +0 -116
  127. package/dist/serializable-numeric-identifier-creator.js.map +0 -1
  128. package/dist/serializable-numeric-identifier-validator.d.ts +0 -79
  129. package/dist/serializable-numeric-identifier-validator.d.ts.map +0 -1
  130. package/dist/serializable-numeric-identifier-validator.js +0 -99
  131. package/dist/serializable-numeric-identifier-validator.js.map +0 -1
package/dist/index.cjs ADDED
@@ -0,0 +1,4624 @@
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
+ AI39_CREATOR: () => AI39_CREATOR,
24
+ AI39_VALIDATOR: () => AI39_VALIDATOR,
25
+ AI64_VALIDATOR: () => AI64_VALIDATOR,
26
+ AI82_CREATOR: () => AI82_CREATOR,
27
+ AI82_VALIDATOR: () => AI82_VALIDATOR,
28
+ AbstractIdentifierCreator: () => AbstractIdentifierCreator,
29
+ AbstractIdentifierValidator: () => AbstractIdentifierValidator,
30
+ AbstractNumericIdentifierCreator: () => AbstractNumericIdentifierCreator,
31
+ AbstractNumericIdentifierValidator: () => AbstractNumericIdentifierValidator,
32
+ CPID_VALIDATOR: () => CPID_VALIDATOR,
33
+ ContentCharacterSets: () => ContentCharacterSets,
34
+ GCN_VALIDATOR: () => GCN_VALIDATOR,
35
+ GDTI_VALIDATOR: () => GDTI_VALIDATOR,
36
+ GIAI_VALIDATOR: () => GIAI_VALIDATOR,
37
+ GINC_VALIDATOR: () => GINC_VALIDATOR,
38
+ GLN_VALIDATOR: () => GLN_VALIDATOR,
39
+ GMN_VALIDATOR: () => GMN_VALIDATOR,
40
+ GRAI_VALIDATOR: () => GRAI_VALIDATOR,
41
+ GSIN_VALIDATOR: () => GSIN_VALIDATOR,
42
+ GSRN_VALIDATOR: () => GSRN_VALIDATOR,
43
+ GTIN12_VALIDATOR: () => GTIN12_VALIDATOR,
44
+ GTIN13_VALIDATOR: () => GTIN13_VALIDATOR,
45
+ GTIN8_VALIDATOR: () => GTIN8_VALIDATOR,
46
+ GTINCreator: () => GTINCreator,
47
+ GTINLevels: () => GTINLevels,
48
+ GTINTypes: () => GTINTypes,
49
+ GTINValidator: () => GTINValidator,
50
+ GTIN_VALIDATORS: () => GTIN_VALIDATORS,
51
+ IdentifierTypes: () => IdentifierTypes,
52
+ LeaderTypes: () => LeaderTypes,
53
+ NonGTINNumericIdentifierCreator: () => NonGTINNumericIdentifierCreator,
54
+ NonGTINNumericIdentifierValidator: () => NonGTINNumericIdentifierValidator,
55
+ NonNumericIdentifierCreator: () => NonNumericIdentifierCreator,
56
+ NonNumericIdentifierValidator: () => NonNumericIdentifierValidator,
57
+ PrefixManager: () => PrefixManager,
58
+ PrefixTypes: () => PrefixTypes,
59
+ PrefixValidator: () => PrefixValidator,
60
+ SSCC_VALIDATOR: () => SSCC_VALIDATOR,
61
+ SerializableNumericIdentifierCreator: () => SerializableNumericIdentifierCreator,
62
+ SerializableNumericIdentifierValidator: () => SerializableNumericIdentifierValidator,
63
+ checkCharacterPair: () => checkCharacterPair,
64
+ checkDigit: () => checkDigit,
65
+ checkDigitSum: () => checkDigitSum,
66
+ gs1NS: () => gs1NS,
67
+ gs1Resources: () => gs1Resources,
68
+ hasValidCheckCharacterPair: () => hasValidCheckCharacterPair,
69
+ hasValidCheckDigit: () => hasValidCheckDigit,
70
+ i18nGS1Init: () => i18nGS1Init,
71
+ i18nextGS1: () => i18nextGS1,
72
+ isValidPriceOrWeightCheckDigit: () => isValidPriceOrWeightCheckDigit,
73
+ priceOrWeightCheckDigit: () => priceOrWeightCheckDigit
74
+ });
75
+ module.exports = __toCommonJS(index_exports);
76
+
77
+ // src/locale/i18n.ts
78
+ var import_core = require("@aidc-toolkit/core");
79
+ var import_utility = require("@aidc-toolkit/utility");
80
+
81
+ // node_modules/i18next/dist/esm/i18next.js
82
+ var isString = (obj) => typeof obj === "string";
83
+ var defer = () => {
84
+ let res;
85
+ let rej;
86
+ const promise = new Promise((resolve, reject) => {
87
+ res = resolve;
88
+ rej = reject;
89
+ });
90
+ promise.resolve = res;
91
+ promise.reject = rej;
92
+ return promise;
93
+ };
94
+ var makeString = (object) => {
95
+ if (object == null) return "";
96
+ return "" + object;
97
+ };
98
+ var copy = (a, s, t2) => {
99
+ a.forEach((m) => {
100
+ if (s[m]) t2[m] = s[m];
101
+ });
102
+ };
103
+ var lastOfPathSeparatorRegExp = /###/g;
104
+ var cleanKey = (key) => key && key.indexOf("###") > -1 ? key.replace(lastOfPathSeparatorRegExp, ".") : key;
105
+ var canNotTraverseDeeper = (object) => !object || isString(object);
106
+ var getLastOfPath = (object, path, Empty) => {
107
+ const stack = !isString(path) ? path : path.split(".");
108
+ let stackIndex = 0;
109
+ while (stackIndex < stack.length - 1) {
110
+ if (canNotTraverseDeeper(object)) return {};
111
+ const key = cleanKey(stack[stackIndex]);
112
+ if (!object[key] && Empty) object[key] = new Empty();
113
+ if (Object.prototype.hasOwnProperty.call(object, key)) {
114
+ object = object[key];
115
+ } else {
116
+ object = {};
117
+ }
118
+ ++stackIndex;
119
+ }
120
+ if (canNotTraverseDeeper(object)) return {};
121
+ return {
122
+ obj: object,
123
+ k: cleanKey(stack[stackIndex])
124
+ };
125
+ };
126
+ var setPath = (object, path, newValue) => {
127
+ const {
128
+ obj,
129
+ k
130
+ } = getLastOfPath(object, path, Object);
131
+ if (obj !== void 0 || path.length === 1) {
132
+ obj[k] = newValue;
133
+ return;
134
+ }
135
+ let e = path[path.length - 1];
136
+ let p = path.slice(0, path.length - 1);
137
+ let last = getLastOfPath(object, p, Object);
138
+ while (last.obj === void 0 && p.length) {
139
+ e = `${p[p.length - 1]}.${e}`;
140
+ p = p.slice(0, p.length - 1);
141
+ last = getLastOfPath(object, p, Object);
142
+ if (last?.obj && typeof last.obj[`${last.k}.${e}`] !== "undefined") {
143
+ last.obj = void 0;
144
+ }
145
+ }
146
+ last.obj[`${last.k}.${e}`] = newValue;
147
+ };
148
+ var pushPath = (object, path, newValue, concat) => {
149
+ const {
150
+ obj,
151
+ k
152
+ } = getLastOfPath(object, path, Object);
153
+ obj[k] = obj[k] || [];
154
+ obj[k].push(newValue);
155
+ };
156
+ var getPath = (object, path) => {
157
+ const {
158
+ obj,
159
+ k
160
+ } = getLastOfPath(object, path);
161
+ if (!obj) return void 0;
162
+ if (!Object.prototype.hasOwnProperty.call(obj, k)) return void 0;
163
+ return obj[k];
164
+ };
165
+ var getPathWithDefaults = (data, defaultData, key) => {
166
+ const value = getPath(data, key);
167
+ if (value !== void 0) {
168
+ return value;
169
+ }
170
+ return getPath(defaultData, key);
171
+ };
172
+ var deepExtend = (target, source, overwrite) => {
173
+ for (const prop in source) {
174
+ if (prop !== "__proto__" && prop !== "constructor") {
175
+ if (prop in target) {
176
+ if (isString(target[prop]) || target[prop] instanceof String || isString(source[prop]) || source[prop] instanceof String) {
177
+ if (overwrite) target[prop] = source[prop];
178
+ } else {
179
+ deepExtend(target[prop], source[prop], overwrite);
180
+ }
181
+ } else {
182
+ target[prop] = source[prop];
183
+ }
184
+ }
185
+ }
186
+ return target;
187
+ };
188
+ var regexEscape = (str) => str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
189
+ var _entityMap = {
190
+ "&": "&amp;",
191
+ "<": "&lt;",
192
+ ">": "&gt;",
193
+ '"': "&quot;",
194
+ "'": "&#39;",
195
+ "/": "&#x2F;"
196
+ };
197
+ var escape = (data) => {
198
+ if (isString(data)) {
199
+ return data.replace(/[&<>"'\/]/g, (s) => _entityMap[s]);
200
+ }
201
+ return data;
202
+ };
203
+ var RegExpCache = class {
204
+ constructor(capacity) {
205
+ this.capacity = capacity;
206
+ this.regExpMap = /* @__PURE__ */ new Map();
207
+ this.regExpQueue = [];
208
+ }
209
+ getRegExp(pattern) {
210
+ const regExpFromCache = this.regExpMap.get(pattern);
211
+ if (regExpFromCache !== void 0) {
212
+ return regExpFromCache;
213
+ }
214
+ const regExpNew = new RegExp(pattern);
215
+ if (this.regExpQueue.length === this.capacity) {
216
+ this.regExpMap.delete(this.regExpQueue.shift());
217
+ }
218
+ this.regExpMap.set(pattern, regExpNew);
219
+ this.regExpQueue.push(pattern);
220
+ return regExpNew;
221
+ }
222
+ };
223
+ var chars = [" ", ",", "?", "!", ";"];
224
+ var looksLikeObjectPathRegExpCache = new RegExpCache(20);
225
+ var looksLikeObjectPath = (key, nsSeparator, keySeparator) => {
226
+ nsSeparator = nsSeparator || "";
227
+ keySeparator = keySeparator || "";
228
+ const possibleChars = chars.filter((c) => nsSeparator.indexOf(c) < 0 && keySeparator.indexOf(c) < 0);
229
+ if (possibleChars.length === 0) return true;
230
+ const r = looksLikeObjectPathRegExpCache.getRegExp(`(${possibleChars.map((c) => c === "?" ? "\\?" : c).join("|")})`);
231
+ let matched = !r.test(key);
232
+ if (!matched) {
233
+ const ki = key.indexOf(keySeparator);
234
+ if (ki > 0 && !r.test(key.substring(0, ki))) {
235
+ matched = true;
236
+ }
237
+ }
238
+ return matched;
239
+ };
240
+ var deepFind = (obj, path, keySeparator = ".") => {
241
+ if (!obj) return void 0;
242
+ if (obj[path]) {
243
+ if (!Object.prototype.hasOwnProperty.call(obj, path)) return void 0;
244
+ return obj[path];
245
+ }
246
+ const tokens = path.split(keySeparator);
247
+ let current = obj;
248
+ for (let i = 0; i < tokens.length; ) {
249
+ if (!current || typeof current !== "object") {
250
+ return void 0;
251
+ }
252
+ let next;
253
+ let nextPath = "";
254
+ for (let j = i; j < tokens.length; ++j) {
255
+ if (j !== i) {
256
+ nextPath += keySeparator;
257
+ }
258
+ nextPath += tokens[j];
259
+ next = current[nextPath];
260
+ if (next !== void 0) {
261
+ if (["string", "number", "boolean"].indexOf(typeof next) > -1 && j < tokens.length - 1) {
262
+ continue;
263
+ }
264
+ i += j - i + 1;
265
+ break;
266
+ }
267
+ }
268
+ current = next;
269
+ }
270
+ return current;
271
+ };
272
+ var getCleanedCode = (code) => code?.replace("_", "-");
273
+ var consoleLogger = {
274
+ type: "logger",
275
+ log(args) {
276
+ this.output("log", args);
277
+ },
278
+ warn(args) {
279
+ this.output("warn", args);
280
+ },
281
+ error(args) {
282
+ this.output("error", args);
283
+ },
284
+ output(type, args) {
285
+ console?.[type]?.apply?.(console, args);
286
+ }
287
+ };
288
+ var Logger = class _Logger {
289
+ constructor(concreteLogger, options = {}) {
290
+ this.init(concreteLogger, options);
291
+ }
292
+ init(concreteLogger, options = {}) {
293
+ this.prefix = options.prefix || "i18next:";
294
+ this.logger = concreteLogger || consoleLogger;
295
+ this.options = options;
296
+ this.debug = options.debug;
297
+ }
298
+ log(...args) {
299
+ return this.forward(args, "log", "", true);
300
+ }
301
+ warn(...args) {
302
+ return this.forward(args, "warn", "", true);
303
+ }
304
+ error(...args) {
305
+ return this.forward(args, "error", "");
306
+ }
307
+ deprecate(...args) {
308
+ return this.forward(args, "warn", "WARNING DEPRECATED: ", true);
309
+ }
310
+ forward(args, lvl, prefix, debugOnly) {
311
+ if (debugOnly && !this.debug) return null;
312
+ if (isString(args[0])) args[0] = `${prefix}${this.prefix} ${args[0]}`;
313
+ return this.logger[lvl](args);
314
+ }
315
+ create(moduleName) {
316
+ return new _Logger(this.logger, {
317
+ ...{
318
+ prefix: `${this.prefix}:${moduleName}:`
319
+ },
320
+ ...this.options
321
+ });
322
+ }
323
+ clone(options) {
324
+ options = options || this.options;
325
+ options.prefix = options.prefix || this.prefix;
326
+ return new _Logger(this.logger, options);
327
+ }
328
+ };
329
+ var baseLogger = new Logger();
330
+ var EventEmitter = class {
331
+ constructor() {
332
+ this.observers = {};
333
+ }
334
+ on(events, listener) {
335
+ events.split(" ").forEach((event) => {
336
+ if (!this.observers[event]) this.observers[event] = /* @__PURE__ */ new Map();
337
+ const numListeners = this.observers[event].get(listener) || 0;
338
+ this.observers[event].set(listener, numListeners + 1);
339
+ });
340
+ return this;
341
+ }
342
+ off(event, listener) {
343
+ if (!this.observers[event]) return;
344
+ if (!listener) {
345
+ delete this.observers[event];
346
+ return;
347
+ }
348
+ this.observers[event].delete(listener);
349
+ }
350
+ emit(event, ...args) {
351
+ if (this.observers[event]) {
352
+ const cloned = Array.from(this.observers[event].entries());
353
+ cloned.forEach(([observer, numTimesAdded]) => {
354
+ for (let i = 0; i < numTimesAdded; i++) {
355
+ observer(...args);
356
+ }
357
+ });
358
+ }
359
+ if (this.observers["*"]) {
360
+ const cloned = Array.from(this.observers["*"].entries());
361
+ cloned.forEach(([observer, numTimesAdded]) => {
362
+ for (let i = 0; i < numTimesAdded; i++) {
363
+ observer.apply(observer, [event, ...args]);
364
+ }
365
+ });
366
+ }
367
+ }
368
+ };
369
+ var ResourceStore = class extends EventEmitter {
370
+ constructor(data, options = {
371
+ ns: ["translation"],
372
+ defaultNS: "translation"
373
+ }) {
374
+ super();
375
+ this.data = data || {};
376
+ this.options = options;
377
+ if (this.options.keySeparator === void 0) {
378
+ this.options.keySeparator = ".";
379
+ }
380
+ if (this.options.ignoreJSONStructure === void 0) {
381
+ this.options.ignoreJSONStructure = true;
382
+ }
383
+ }
384
+ addNamespaces(ns) {
385
+ if (this.options.ns.indexOf(ns) < 0) {
386
+ this.options.ns.push(ns);
387
+ }
388
+ }
389
+ removeNamespaces(ns) {
390
+ const index = this.options.ns.indexOf(ns);
391
+ if (index > -1) {
392
+ this.options.ns.splice(index, 1);
393
+ }
394
+ }
395
+ getResource(lng, ns, key, options = {}) {
396
+ const keySeparator = options.keySeparator !== void 0 ? options.keySeparator : this.options.keySeparator;
397
+ const ignoreJSONStructure = options.ignoreJSONStructure !== void 0 ? options.ignoreJSONStructure : this.options.ignoreJSONStructure;
398
+ let path;
399
+ if (lng.indexOf(".") > -1) {
400
+ path = lng.split(".");
401
+ } else {
402
+ path = [lng, ns];
403
+ if (key) {
404
+ if (Array.isArray(key)) {
405
+ path.push(...key);
406
+ } else if (isString(key) && keySeparator) {
407
+ path.push(...key.split(keySeparator));
408
+ } else {
409
+ path.push(key);
410
+ }
411
+ }
412
+ }
413
+ const result = getPath(this.data, path);
414
+ if (!result && !ns && !key && lng.indexOf(".") > -1) {
415
+ lng = path[0];
416
+ ns = path[1];
417
+ key = path.slice(2).join(".");
418
+ }
419
+ if (result || !ignoreJSONStructure || !isString(key)) return result;
420
+ return deepFind(this.data?.[lng]?.[ns], key, keySeparator);
421
+ }
422
+ addResource(lng, ns, key, value, options = {
423
+ silent: false
424
+ }) {
425
+ const keySeparator = options.keySeparator !== void 0 ? options.keySeparator : this.options.keySeparator;
426
+ let path = [lng, ns];
427
+ if (key) path = path.concat(keySeparator ? key.split(keySeparator) : key);
428
+ if (lng.indexOf(".") > -1) {
429
+ path = lng.split(".");
430
+ value = ns;
431
+ ns = path[1];
432
+ }
433
+ this.addNamespaces(ns);
434
+ setPath(this.data, path, value);
435
+ if (!options.silent) this.emit("added", lng, ns, key, value);
436
+ }
437
+ addResources(lng, ns, resources, options = {
438
+ silent: false
439
+ }) {
440
+ for (const m in resources) {
441
+ if (isString(resources[m]) || Array.isArray(resources[m])) this.addResource(lng, ns, m, resources[m], {
442
+ silent: true
443
+ });
444
+ }
445
+ if (!options.silent) this.emit("added", lng, ns, resources);
446
+ }
447
+ addResourceBundle(lng, ns, resources, deep, overwrite, options = {
448
+ silent: false,
449
+ skipCopy: false
450
+ }) {
451
+ let path = [lng, ns];
452
+ if (lng.indexOf(".") > -1) {
453
+ path = lng.split(".");
454
+ deep = resources;
455
+ resources = ns;
456
+ ns = path[1];
457
+ }
458
+ this.addNamespaces(ns);
459
+ let pack = getPath(this.data, path) || {};
460
+ if (!options.skipCopy) resources = JSON.parse(JSON.stringify(resources));
461
+ if (deep) {
462
+ deepExtend(pack, resources, overwrite);
463
+ } else {
464
+ pack = {
465
+ ...pack,
466
+ ...resources
467
+ };
468
+ }
469
+ setPath(this.data, path, pack);
470
+ if (!options.silent) this.emit("added", lng, ns, resources);
471
+ }
472
+ removeResourceBundle(lng, ns) {
473
+ if (this.hasResourceBundle(lng, ns)) {
474
+ delete this.data[lng][ns];
475
+ }
476
+ this.removeNamespaces(ns);
477
+ this.emit("removed", lng, ns);
478
+ }
479
+ hasResourceBundle(lng, ns) {
480
+ return this.getResource(lng, ns) !== void 0;
481
+ }
482
+ getResourceBundle(lng, ns) {
483
+ if (!ns) ns = this.options.defaultNS;
484
+ return this.getResource(lng, ns);
485
+ }
486
+ getDataByLanguage(lng) {
487
+ return this.data[lng];
488
+ }
489
+ hasLanguageSomeTranslations(lng) {
490
+ const data = this.getDataByLanguage(lng);
491
+ const n = data && Object.keys(data) || [];
492
+ return !!n.find((v) => data[v] && Object.keys(data[v]).length > 0);
493
+ }
494
+ toJSON() {
495
+ return this.data;
496
+ }
497
+ };
498
+ var postProcessor = {
499
+ processors: {},
500
+ addPostProcessor(module2) {
501
+ this.processors[module2.name] = module2;
502
+ },
503
+ handle(processors, value, key, options, translator) {
504
+ processors.forEach((processor) => {
505
+ value = this.processors[processor]?.process(value, key, options, translator) ?? value;
506
+ });
507
+ return value;
508
+ }
509
+ };
510
+ var PATH_KEY = Symbol("i18next/PATH_KEY");
511
+ function createProxy() {
512
+ const state = [];
513
+ const handler = /* @__PURE__ */ Object.create(null);
514
+ let proxy;
515
+ handler.get = (target, key) => {
516
+ proxy?.revoke?.();
517
+ if (key === PATH_KEY) return state;
518
+ state.push(key);
519
+ proxy = Proxy.revocable(target, handler);
520
+ return proxy.proxy;
521
+ };
522
+ return Proxy.revocable(/* @__PURE__ */ Object.create(null), handler).proxy;
523
+ }
524
+ function keysFromSelector(selector, opts) {
525
+ const {
526
+ [PATH_KEY]: path
527
+ } = selector(createProxy());
528
+ return path.join(opts?.keySeparator ?? ".");
529
+ }
530
+ var checkedLoadedFor = {};
531
+ var shouldHandleAsObject = (res) => !isString(res) && typeof res !== "boolean" && typeof res !== "number";
532
+ var Translator = class _Translator extends EventEmitter {
533
+ constructor(services, options = {}) {
534
+ super();
535
+ copy(["resourceStore", "languageUtils", "pluralResolver", "interpolator", "backendConnector", "i18nFormat", "utils"], services, this);
536
+ this.options = options;
537
+ if (this.options.keySeparator === void 0) {
538
+ this.options.keySeparator = ".";
539
+ }
540
+ this.logger = baseLogger.create("translator");
541
+ }
542
+ changeLanguage(lng) {
543
+ if (lng) this.language = lng;
544
+ }
545
+ exists(key, o = {
546
+ interpolation: {}
547
+ }) {
548
+ const opt = {
549
+ ...o
550
+ };
551
+ if (key == null) return false;
552
+ const resolved = this.resolve(key, opt);
553
+ if (resolved?.res === void 0) return false;
554
+ const isObject = shouldHandleAsObject(resolved.res);
555
+ if (opt.returnObjects === false && isObject) {
556
+ return false;
557
+ }
558
+ return true;
559
+ }
560
+ extractFromKey(key, opt) {
561
+ let nsSeparator = opt.nsSeparator !== void 0 ? opt.nsSeparator : this.options.nsSeparator;
562
+ if (nsSeparator === void 0) nsSeparator = ":";
563
+ const keySeparator = opt.keySeparator !== void 0 ? opt.keySeparator : this.options.keySeparator;
564
+ let namespaces = opt.ns || this.options.defaultNS || [];
565
+ const wouldCheckForNsInKey = nsSeparator && key.indexOf(nsSeparator) > -1;
566
+ const seemsNaturalLanguage = !this.options.userDefinedKeySeparator && !opt.keySeparator && !this.options.userDefinedNsSeparator && !opt.nsSeparator && !looksLikeObjectPath(key, nsSeparator, keySeparator);
567
+ if (wouldCheckForNsInKey && !seemsNaturalLanguage) {
568
+ const m = key.match(this.interpolator.nestingRegexp);
569
+ if (m && m.length > 0) {
570
+ return {
571
+ key,
572
+ namespaces: isString(namespaces) ? [namespaces] : namespaces
573
+ };
574
+ }
575
+ const parts = key.split(nsSeparator);
576
+ if (nsSeparator !== keySeparator || nsSeparator === keySeparator && this.options.ns.indexOf(parts[0]) > -1) namespaces = parts.shift();
577
+ key = parts.join(keySeparator);
578
+ }
579
+ return {
580
+ key,
581
+ namespaces: isString(namespaces) ? [namespaces] : namespaces
582
+ };
583
+ }
584
+ translate(keys, o, lastKey) {
585
+ let opt = typeof o === "object" ? {
586
+ ...o
587
+ } : o;
588
+ if (typeof opt !== "object" && this.options.overloadTranslationOptionHandler) {
589
+ opt = this.options.overloadTranslationOptionHandler(arguments);
590
+ }
591
+ if (typeof opt === "object") opt = {
592
+ ...opt
593
+ };
594
+ if (!opt) opt = {};
595
+ if (keys == null) return "";
596
+ if (typeof keys === "function") keys = keysFromSelector(keys, {
597
+ ...this.options,
598
+ ...opt
599
+ });
600
+ if (!Array.isArray(keys)) keys = [String(keys)];
601
+ const returnDetails = opt.returnDetails !== void 0 ? opt.returnDetails : this.options.returnDetails;
602
+ const keySeparator = opt.keySeparator !== void 0 ? opt.keySeparator : this.options.keySeparator;
603
+ const {
604
+ key,
605
+ namespaces
606
+ } = this.extractFromKey(keys[keys.length - 1], opt);
607
+ const namespace = namespaces[namespaces.length - 1];
608
+ let nsSeparator = opt.nsSeparator !== void 0 ? opt.nsSeparator : this.options.nsSeparator;
609
+ if (nsSeparator === void 0) nsSeparator = ":";
610
+ const lng = opt.lng || this.language;
611
+ const appendNamespaceToCIMode = opt.appendNamespaceToCIMode || this.options.appendNamespaceToCIMode;
612
+ if (lng?.toLowerCase() === "cimode") {
613
+ if (appendNamespaceToCIMode) {
614
+ if (returnDetails) {
615
+ return {
616
+ res: `${namespace}${nsSeparator}${key}`,
617
+ usedKey: key,
618
+ exactUsedKey: key,
619
+ usedLng: lng,
620
+ usedNS: namespace,
621
+ usedParams: this.getUsedParamsDetails(opt)
622
+ };
623
+ }
624
+ return `${namespace}${nsSeparator}${key}`;
625
+ }
626
+ if (returnDetails) {
627
+ return {
628
+ res: key,
629
+ usedKey: key,
630
+ exactUsedKey: key,
631
+ usedLng: lng,
632
+ usedNS: namespace,
633
+ usedParams: this.getUsedParamsDetails(opt)
634
+ };
635
+ }
636
+ return key;
637
+ }
638
+ const resolved = this.resolve(keys, opt);
639
+ let res = resolved?.res;
640
+ const resUsedKey = resolved?.usedKey || key;
641
+ const resExactUsedKey = resolved?.exactUsedKey || key;
642
+ const noObject = ["[object Number]", "[object Function]", "[object RegExp]"];
643
+ const joinArrays = opt.joinArrays !== void 0 ? opt.joinArrays : this.options.joinArrays;
644
+ const handleAsObjectInI18nFormat = !this.i18nFormat || this.i18nFormat.handleAsObject;
645
+ const needsPluralHandling = opt.count !== void 0 && !isString(opt.count);
646
+ const hasDefaultValue = _Translator.hasDefaultValue(opt);
647
+ const defaultValueSuffix = needsPluralHandling ? this.pluralResolver.getSuffix(lng, opt.count, opt) : "";
648
+ const defaultValueSuffixOrdinalFallback = opt.ordinal && needsPluralHandling ? this.pluralResolver.getSuffix(lng, opt.count, {
649
+ ordinal: false
650
+ }) : "";
651
+ const needsZeroSuffixLookup = needsPluralHandling && !opt.ordinal && opt.count === 0;
652
+ const defaultValue = needsZeroSuffixLookup && opt[`defaultValue${this.options.pluralSeparator}zero`] || opt[`defaultValue${defaultValueSuffix}`] || opt[`defaultValue${defaultValueSuffixOrdinalFallback}`] || opt.defaultValue;
653
+ let resForObjHndl = res;
654
+ if (handleAsObjectInI18nFormat && !res && hasDefaultValue) {
655
+ resForObjHndl = defaultValue;
656
+ }
657
+ const handleAsObject = shouldHandleAsObject(resForObjHndl);
658
+ const resType = Object.prototype.toString.apply(resForObjHndl);
659
+ if (handleAsObjectInI18nFormat && resForObjHndl && handleAsObject && noObject.indexOf(resType) < 0 && !(isString(joinArrays) && Array.isArray(resForObjHndl))) {
660
+ if (!opt.returnObjects && !this.options.returnObjects) {
661
+ if (!this.options.returnedObjectHandler) {
662
+ this.logger.warn("accessing an object - but returnObjects options is not enabled!");
663
+ }
664
+ const r = this.options.returnedObjectHandler ? this.options.returnedObjectHandler(resUsedKey, resForObjHndl, {
665
+ ...opt,
666
+ ns: namespaces
667
+ }) : `key '${key} (${this.language})' returned an object instead of string.`;
668
+ if (returnDetails) {
669
+ resolved.res = r;
670
+ resolved.usedParams = this.getUsedParamsDetails(opt);
671
+ return resolved;
672
+ }
673
+ return r;
674
+ }
675
+ if (keySeparator) {
676
+ const resTypeIsArray = Array.isArray(resForObjHndl);
677
+ const copy2 = resTypeIsArray ? [] : {};
678
+ const newKeyToUse = resTypeIsArray ? resExactUsedKey : resUsedKey;
679
+ for (const m in resForObjHndl) {
680
+ if (Object.prototype.hasOwnProperty.call(resForObjHndl, m)) {
681
+ const deepKey = `${newKeyToUse}${keySeparator}${m}`;
682
+ if (hasDefaultValue && !res) {
683
+ copy2[m] = this.translate(deepKey, {
684
+ ...opt,
685
+ defaultValue: shouldHandleAsObject(defaultValue) ? defaultValue[m] : void 0,
686
+ ...{
687
+ joinArrays: false,
688
+ ns: namespaces
689
+ }
690
+ });
691
+ } else {
692
+ copy2[m] = this.translate(deepKey, {
693
+ ...opt,
694
+ ...{
695
+ joinArrays: false,
696
+ ns: namespaces
697
+ }
698
+ });
699
+ }
700
+ if (copy2[m] === deepKey) copy2[m] = resForObjHndl[m];
701
+ }
702
+ }
703
+ res = copy2;
704
+ }
705
+ } else if (handleAsObjectInI18nFormat && isString(joinArrays) && Array.isArray(res)) {
706
+ res = res.join(joinArrays);
707
+ if (res) res = this.extendTranslation(res, keys, opt, lastKey);
708
+ } else {
709
+ let usedDefault = false;
710
+ let usedKey = false;
711
+ if (!this.isValidLookup(res) && hasDefaultValue) {
712
+ usedDefault = true;
713
+ res = defaultValue;
714
+ }
715
+ if (!this.isValidLookup(res)) {
716
+ usedKey = true;
717
+ res = key;
718
+ }
719
+ const missingKeyNoValueFallbackToKey = opt.missingKeyNoValueFallbackToKey || this.options.missingKeyNoValueFallbackToKey;
720
+ const resForMissing = missingKeyNoValueFallbackToKey && usedKey ? void 0 : res;
721
+ const updateMissing = hasDefaultValue && defaultValue !== res && this.options.updateMissing;
722
+ if (usedKey || usedDefault || updateMissing) {
723
+ this.logger.log(updateMissing ? "updateKey" : "missingKey", lng, namespace, key, updateMissing ? defaultValue : res);
724
+ if (keySeparator) {
725
+ const fk = this.resolve(key, {
726
+ ...opt,
727
+ keySeparator: false
728
+ });
729
+ 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.");
730
+ }
731
+ let lngs = [];
732
+ const fallbackLngs = this.languageUtils.getFallbackCodes(this.options.fallbackLng, opt.lng || this.language);
733
+ if (this.options.saveMissingTo === "fallback" && fallbackLngs && fallbackLngs[0]) {
734
+ for (let i = 0; i < fallbackLngs.length; i++) {
735
+ lngs.push(fallbackLngs[i]);
736
+ }
737
+ } else if (this.options.saveMissingTo === "all") {
738
+ lngs = this.languageUtils.toResolveHierarchy(opt.lng || this.language);
739
+ } else {
740
+ lngs.push(opt.lng || this.language);
741
+ }
742
+ const send = (l, k, specificDefaultValue) => {
743
+ const defaultForMissing = hasDefaultValue && specificDefaultValue !== res ? specificDefaultValue : resForMissing;
744
+ if (this.options.missingKeyHandler) {
745
+ this.options.missingKeyHandler(l, namespace, k, defaultForMissing, updateMissing, opt);
746
+ } else if (this.backendConnector?.saveMissing) {
747
+ this.backendConnector.saveMissing(l, namespace, k, defaultForMissing, updateMissing, opt);
748
+ }
749
+ this.emit("missingKey", l, namespace, k, res);
750
+ };
751
+ if (this.options.saveMissing) {
752
+ if (this.options.saveMissingPlurals && needsPluralHandling) {
753
+ lngs.forEach((language) => {
754
+ const suffixes = this.pluralResolver.getSuffixes(language, opt);
755
+ if (needsZeroSuffixLookup && opt[`defaultValue${this.options.pluralSeparator}zero`] && suffixes.indexOf(`${this.options.pluralSeparator}zero`) < 0) {
756
+ suffixes.push(`${this.options.pluralSeparator}zero`);
757
+ }
758
+ suffixes.forEach((suffix) => {
759
+ send([language], key + suffix, opt[`defaultValue${suffix}`] || defaultValue);
760
+ });
761
+ });
762
+ } else {
763
+ send(lngs, key, defaultValue);
764
+ }
765
+ }
766
+ }
767
+ res = this.extendTranslation(res, keys, opt, resolved, lastKey);
768
+ if (usedKey && res === key && this.options.appendNamespaceToMissingKey) {
769
+ res = `${namespace}${nsSeparator}${key}`;
770
+ }
771
+ if ((usedKey || usedDefault) && this.options.parseMissingKeyHandler) {
772
+ res = this.options.parseMissingKeyHandler(this.options.appendNamespaceToMissingKey ? `${namespace}${nsSeparator}${key}` : key, usedDefault ? res : void 0, opt);
773
+ }
774
+ }
775
+ if (returnDetails) {
776
+ resolved.res = res;
777
+ resolved.usedParams = this.getUsedParamsDetails(opt);
778
+ return resolved;
779
+ }
780
+ return res;
781
+ }
782
+ extendTranslation(res, key, opt, resolved, lastKey) {
783
+ if (this.i18nFormat?.parse) {
784
+ res = this.i18nFormat.parse(res, {
785
+ ...this.options.interpolation.defaultVariables,
786
+ ...opt
787
+ }, opt.lng || this.language || resolved.usedLng, resolved.usedNS, resolved.usedKey, {
788
+ resolved
789
+ });
790
+ } else if (!opt.skipInterpolation) {
791
+ if (opt.interpolation) this.interpolator.init({
792
+ ...opt,
793
+ ...{
794
+ interpolation: {
795
+ ...this.options.interpolation,
796
+ ...opt.interpolation
797
+ }
798
+ }
799
+ });
800
+ const skipOnVariables = isString(res) && (opt?.interpolation?.skipOnVariables !== void 0 ? opt.interpolation.skipOnVariables : this.options.interpolation.skipOnVariables);
801
+ let nestBef;
802
+ if (skipOnVariables) {
803
+ const nb = res.match(this.interpolator.nestingRegexp);
804
+ nestBef = nb && nb.length;
805
+ }
806
+ let data = opt.replace && !isString(opt.replace) ? opt.replace : opt;
807
+ if (this.options.interpolation.defaultVariables) data = {
808
+ ...this.options.interpolation.defaultVariables,
809
+ ...data
810
+ };
811
+ res = this.interpolator.interpolate(res, data, opt.lng || this.language || resolved.usedLng, opt);
812
+ if (skipOnVariables) {
813
+ const na = res.match(this.interpolator.nestingRegexp);
814
+ const nestAft = na && na.length;
815
+ if (nestBef < nestAft) opt.nest = false;
816
+ }
817
+ if (!opt.lng && resolved && resolved.res) opt.lng = this.language || resolved.usedLng;
818
+ if (opt.nest !== false) res = this.interpolator.nest(res, (...args) => {
819
+ if (lastKey?.[0] === args[0] && !opt.context) {
820
+ this.logger.warn(`It seems you are nesting recursively key: ${args[0]} in key: ${key[0]}`);
821
+ return null;
822
+ }
823
+ return this.translate(...args, key);
824
+ }, opt);
825
+ if (opt.interpolation) this.interpolator.reset();
826
+ }
827
+ const postProcess = opt.postProcess || this.options.postProcess;
828
+ const postProcessorNames = isString(postProcess) ? [postProcess] : postProcess;
829
+ if (res != null && postProcessorNames?.length && opt.applyPostProcessor !== false) {
830
+ res = postProcessor.handle(postProcessorNames, res, key, this.options && this.options.postProcessPassResolved ? {
831
+ i18nResolved: {
832
+ ...resolved,
833
+ usedParams: this.getUsedParamsDetails(opt)
834
+ },
835
+ ...opt
836
+ } : opt, this);
837
+ }
838
+ return res;
839
+ }
840
+ resolve(keys, opt = {}) {
841
+ let found;
842
+ let usedKey;
843
+ let exactUsedKey;
844
+ let usedLng;
845
+ let usedNS;
846
+ if (isString(keys)) keys = [keys];
847
+ keys.forEach((k) => {
848
+ if (this.isValidLookup(found)) return;
849
+ const extracted = this.extractFromKey(k, opt);
850
+ const key = extracted.key;
851
+ usedKey = key;
852
+ let namespaces = extracted.namespaces;
853
+ if (this.options.fallbackNS) namespaces = namespaces.concat(this.options.fallbackNS);
854
+ const needsPluralHandling = opt.count !== void 0 && !isString(opt.count);
855
+ const needsZeroSuffixLookup = needsPluralHandling && !opt.ordinal && opt.count === 0;
856
+ const needsContextHandling = opt.context !== void 0 && (isString(opt.context) || typeof opt.context === "number") && opt.context !== "";
857
+ const codes = opt.lngs ? opt.lngs : this.languageUtils.toResolveHierarchy(opt.lng || this.language, opt.fallbackLng);
858
+ namespaces.forEach((ns) => {
859
+ if (this.isValidLookup(found)) return;
860
+ usedNS = ns;
861
+ if (!checkedLoadedFor[`${codes[0]}-${ns}`] && this.utils?.hasLoadedNamespace && !this.utils?.hasLoadedNamespace(usedNS)) {
862
+ checkedLoadedFor[`${codes[0]}-${ns}`] = true;
863
+ 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!!!");
864
+ }
865
+ codes.forEach((code) => {
866
+ if (this.isValidLookup(found)) return;
867
+ usedLng = code;
868
+ const finalKeys = [key];
869
+ if (this.i18nFormat?.addLookupKeys) {
870
+ this.i18nFormat.addLookupKeys(finalKeys, key, code, ns, opt);
871
+ } else {
872
+ let pluralSuffix;
873
+ if (needsPluralHandling) pluralSuffix = this.pluralResolver.getSuffix(code, opt.count, opt);
874
+ const zeroSuffix = `${this.options.pluralSeparator}zero`;
875
+ const ordinalPrefix = `${this.options.pluralSeparator}ordinal${this.options.pluralSeparator}`;
876
+ if (needsPluralHandling) {
877
+ if (opt.ordinal && pluralSuffix.indexOf(ordinalPrefix) === 0) {
878
+ finalKeys.push(key + pluralSuffix.replace(ordinalPrefix, this.options.pluralSeparator));
879
+ }
880
+ finalKeys.push(key + pluralSuffix);
881
+ if (needsZeroSuffixLookup) {
882
+ finalKeys.push(key + zeroSuffix);
883
+ }
884
+ }
885
+ if (needsContextHandling) {
886
+ const contextKey = `${key}${this.options.contextSeparator || "_"}${opt.context}`;
887
+ finalKeys.push(contextKey);
888
+ if (needsPluralHandling) {
889
+ if (opt.ordinal && pluralSuffix.indexOf(ordinalPrefix) === 0) {
890
+ finalKeys.push(contextKey + pluralSuffix.replace(ordinalPrefix, this.options.pluralSeparator));
891
+ }
892
+ finalKeys.push(contextKey + pluralSuffix);
893
+ if (needsZeroSuffixLookup) {
894
+ finalKeys.push(contextKey + zeroSuffix);
895
+ }
896
+ }
897
+ }
898
+ }
899
+ let possibleKey;
900
+ while (possibleKey = finalKeys.pop()) {
901
+ if (!this.isValidLookup(found)) {
902
+ exactUsedKey = possibleKey;
903
+ found = this.getResource(code, ns, possibleKey, opt);
904
+ }
905
+ }
906
+ });
907
+ });
908
+ });
909
+ return {
910
+ res: found,
911
+ usedKey,
912
+ exactUsedKey,
913
+ usedLng,
914
+ usedNS
915
+ };
916
+ }
917
+ isValidLookup(res) {
918
+ return res !== void 0 && !(!this.options.returnNull && res === null) && !(!this.options.returnEmptyString && res === "");
919
+ }
920
+ getResource(code, ns, key, options = {}) {
921
+ if (this.i18nFormat?.getResource) return this.i18nFormat.getResource(code, ns, key, options);
922
+ return this.resourceStore.getResource(code, ns, key, options);
923
+ }
924
+ getUsedParamsDetails(options = {}) {
925
+ const optionsKeys = ["defaultValue", "ordinal", "context", "replace", "lng", "lngs", "fallbackLng", "ns", "keySeparator", "nsSeparator", "returnObjects", "returnDetails", "joinArrays", "postProcess", "interpolation"];
926
+ const useOptionsReplaceForData = options.replace && !isString(options.replace);
927
+ let data = useOptionsReplaceForData ? options.replace : options;
928
+ if (useOptionsReplaceForData && typeof options.count !== "undefined") {
929
+ data.count = options.count;
930
+ }
931
+ if (this.options.interpolation.defaultVariables) {
932
+ data = {
933
+ ...this.options.interpolation.defaultVariables,
934
+ ...data
935
+ };
936
+ }
937
+ if (!useOptionsReplaceForData) {
938
+ data = {
939
+ ...data
940
+ };
941
+ for (const key of optionsKeys) {
942
+ delete data[key];
943
+ }
944
+ }
945
+ return data;
946
+ }
947
+ static hasDefaultValue(options) {
948
+ const prefix = "defaultValue";
949
+ for (const option in options) {
950
+ if (Object.prototype.hasOwnProperty.call(options, option) && prefix === option.substring(0, prefix.length) && void 0 !== options[option]) {
951
+ return true;
952
+ }
953
+ }
954
+ return false;
955
+ }
956
+ };
957
+ var LanguageUtil = class {
958
+ constructor(options) {
959
+ this.options = options;
960
+ this.supportedLngs = this.options.supportedLngs || false;
961
+ this.logger = baseLogger.create("languageUtils");
962
+ }
963
+ getScriptPartFromCode(code) {
964
+ code = getCleanedCode(code);
965
+ if (!code || code.indexOf("-") < 0) return null;
966
+ const p = code.split("-");
967
+ if (p.length === 2) return null;
968
+ p.pop();
969
+ if (p[p.length - 1].toLowerCase() === "x") return null;
970
+ return this.formatLanguageCode(p.join("-"));
971
+ }
972
+ getLanguagePartFromCode(code) {
973
+ code = getCleanedCode(code);
974
+ if (!code || code.indexOf("-") < 0) return code;
975
+ const p = code.split("-");
976
+ return this.formatLanguageCode(p[0]);
977
+ }
978
+ formatLanguageCode(code) {
979
+ if (isString(code) && code.indexOf("-") > -1) {
980
+ let formattedCode;
981
+ try {
982
+ formattedCode = Intl.getCanonicalLocales(code)[0];
983
+ } catch (e) {
984
+ }
985
+ if (formattedCode && this.options.lowerCaseLng) {
986
+ formattedCode = formattedCode.toLowerCase();
987
+ }
988
+ if (formattedCode) return formattedCode;
989
+ if (this.options.lowerCaseLng) {
990
+ return code.toLowerCase();
991
+ }
992
+ return code;
993
+ }
994
+ return this.options.cleanCode || this.options.lowerCaseLng ? code.toLowerCase() : code;
995
+ }
996
+ isSupportedCode(code) {
997
+ if (this.options.load === "languageOnly" || this.options.nonExplicitSupportedLngs) {
998
+ code = this.getLanguagePartFromCode(code);
999
+ }
1000
+ return !this.supportedLngs || !this.supportedLngs.length || this.supportedLngs.indexOf(code) > -1;
1001
+ }
1002
+ getBestMatchFromCodes(codes) {
1003
+ if (!codes) return null;
1004
+ let found;
1005
+ codes.forEach((code) => {
1006
+ if (found) return;
1007
+ const cleanedLng = this.formatLanguageCode(code);
1008
+ if (!this.options.supportedLngs || this.isSupportedCode(cleanedLng)) found = cleanedLng;
1009
+ });
1010
+ if (!found && this.options.supportedLngs) {
1011
+ codes.forEach((code) => {
1012
+ if (found) return;
1013
+ const lngScOnly = this.getScriptPartFromCode(code);
1014
+ if (this.isSupportedCode(lngScOnly)) return found = lngScOnly;
1015
+ const lngOnly = this.getLanguagePartFromCode(code);
1016
+ if (this.isSupportedCode(lngOnly)) return found = lngOnly;
1017
+ found = this.options.supportedLngs.find((supportedLng) => {
1018
+ if (supportedLng === lngOnly) return supportedLng;
1019
+ if (supportedLng.indexOf("-") < 0 && lngOnly.indexOf("-") < 0) return;
1020
+ if (supportedLng.indexOf("-") > 0 && lngOnly.indexOf("-") < 0 && supportedLng.substring(0, supportedLng.indexOf("-")) === lngOnly) return supportedLng;
1021
+ if (supportedLng.indexOf(lngOnly) === 0 && lngOnly.length > 1) return supportedLng;
1022
+ });
1023
+ });
1024
+ }
1025
+ if (!found) found = this.getFallbackCodes(this.options.fallbackLng)[0];
1026
+ return found;
1027
+ }
1028
+ getFallbackCodes(fallbacks, code) {
1029
+ if (!fallbacks) return [];
1030
+ if (typeof fallbacks === "function") fallbacks = fallbacks(code);
1031
+ if (isString(fallbacks)) fallbacks = [fallbacks];
1032
+ if (Array.isArray(fallbacks)) return fallbacks;
1033
+ if (!code) return fallbacks.default || [];
1034
+ let found = fallbacks[code];
1035
+ if (!found) found = fallbacks[this.getScriptPartFromCode(code)];
1036
+ if (!found) found = fallbacks[this.formatLanguageCode(code)];
1037
+ if (!found) found = fallbacks[this.getLanguagePartFromCode(code)];
1038
+ if (!found) found = fallbacks.default;
1039
+ return found || [];
1040
+ }
1041
+ toResolveHierarchy(code, fallbackCode) {
1042
+ const fallbackCodes = this.getFallbackCodes((fallbackCode === false ? [] : fallbackCode) || this.options.fallbackLng || [], code);
1043
+ const codes = [];
1044
+ const addCode = (c) => {
1045
+ if (!c) return;
1046
+ if (this.isSupportedCode(c)) {
1047
+ codes.push(c);
1048
+ } else {
1049
+ this.logger.warn(`rejecting language code not found in supportedLngs: ${c}`);
1050
+ }
1051
+ };
1052
+ if (isString(code) && (code.indexOf("-") > -1 || code.indexOf("_") > -1)) {
1053
+ if (this.options.load !== "languageOnly") addCode(this.formatLanguageCode(code));
1054
+ if (this.options.load !== "languageOnly" && this.options.load !== "currentOnly") addCode(this.getScriptPartFromCode(code));
1055
+ if (this.options.load !== "currentOnly") addCode(this.getLanguagePartFromCode(code));
1056
+ } else if (isString(code)) {
1057
+ addCode(this.formatLanguageCode(code));
1058
+ }
1059
+ fallbackCodes.forEach((fc) => {
1060
+ if (codes.indexOf(fc) < 0) addCode(this.formatLanguageCode(fc));
1061
+ });
1062
+ return codes;
1063
+ }
1064
+ };
1065
+ var suffixesOrder = {
1066
+ zero: 0,
1067
+ one: 1,
1068
+ two: 2,
1069
+ few: 3,
1070
+ many: 4,
1071
+ other: 5
1072
+ };
1073
+ var dummyRule = {
1074
+ select: (count) => count === 1 ? "one" : "other",
1075
+ resolvedOptions: () => ({
1076
+ pluralCategories: ["one", "other"]
1077
+ })
1078
+ };
1079
+ var PluralResolver = class {
1080
+ constructor(languageUtils, options = {}) {
1081
+ this.languageUtils = languageUtils;
1082
+ this.options = options;
1083
+ this.logger = baseLogger.create("pluralResolver");
1084
+ this.pluralRulesCache = {};
1085
+ }
1086
+ addRule(lng, obj) {
1087
+ this.rules[lng] = obj;
1088
+ }
1089
+ clearCache() {
1090
+ this.pluralRulesCache = {};
1091
+ }
1092
+ getRule(code, options = {}) {
1093
+ const cleanedCode = getCleanedCode(code === "dev" ? "en" : code);
1094
+ const type = options.ordinal ? "ordinal" : "cardinal";
1095
+ const cacheKey = JSON.stringify({
1096
+ cleanedCode,
1097
+ type
1098
+ });
1099
+ if (cacheKey in this.pluralRulesCache) {
1100
+ return this.pluralRulesCache[cacheKey];
1101
+ }
1102
+ let rule;
1103
+ try {
1104
+ rule = new Intl.PluralRules(cleanedCode, {
1105
+ type
1106
+ });
1107
+ } catch (err) {
1108
+ if (!Intl) {
1109
+ this.logger.error("No Intl support, please use an Intl polyfill!");
1110
+ return dummyRule;
1111
+ }
1112
+ if (!code.match(/-|_/)) return dummyRule;
1113
+ const lngPart = this.languageUtils.getLanguagePartFromCode(code);
1114
+ rule = this.getRule(lngPart, options);
1115
+ }
1116
+ this.pluralRulesCache[cacheKey] = rule;
1117
+ return rule;
1118
+ }
1119
+ needsPlural(code, options = {}) {
1120
+ let rule = this.getRule(code, options);
1121
+ if (!rule) rule = this.getRule("dev", options);
1122
+ return rule?.resolvedOptions().pluralCategories.length > 1;
1123
+ }
1124
+ getPluralFormsOfKey(code, key, options = {}) {
1125
+ return this.getSuffixes(code, options).map((suffix) => `${key}${suffix}`);
1126
+ }
1127
+ getSuffixes(code, options = {}) {
1128
+ let rule = this.getRule(code, options);
1129
+ if (!rule) rule = this.getRule("dev", options);
1130
+ if (!rule) return [];
1131
+ return rule.resolvedOptions().pluralCategories.sort((pluralCategory1, pluralCategory2) => suffixesOrder[pluralCategory1] - suffixesOrder[pluralCategory2]).map((pluralCategory) => `${this.options.prepend}${options.ordinal ? `ordinal${this.options.prepend}` : ""}${pluralCategory}`);
1132
+ }
1133
+ getSuffix(code, count, options = {}) {
1134
+ const rule = this.getRule(code, options);
1135
+ if (rule) {
1136
+ return `${this.options.prepend}${options.ordinal ? `ordinal${this.options.prepend}` : ""}${rule.select(count)}`;
1137
+ }
1138
+ this.logger.warn(`no plural rule found for: ${code}`);
1139
+ return this.getSuffix("dev", count, options);
1140
+ }
1141
+ };
1142
+ var deepFindWithDefaults = (data, defaultData, key, keySeparator = ".", ignoreJSONStructure = true) => {
1143
+ let path = getPathWithDefaults(data, defaultData, key);
1144
+ if (!path && ignoreJSONStructure && isString(key)) {
1145
+ path = deepFind(data, key, keySeparator);
1146
+ if (path === void 0) path = deepFind(defaultData, key, keySeparator);
1147
+ }
1148
+ return path;
1149
+ };
1150
+ var regexSafe = (val) => val.replace(/\$/g, "$$$$");
1151
+ var Interpolator = class {
1152
+ constructor(options = {}) {
1153
+ this.logger = baseLogger.create("interpolator");
1154
+ this.options = options;
1155
+ this.format = options?.interpolation?.format || ((value) => value);
1156
+ this.init(options);
1157
+ }
1158
+ init(options = {}) {
1159
+ if (!options.interpolation) options.interpolation = {
1160
+ escapeValue: true
1161
+ };
1162
+ const {
1163
+ escape: escape$1,
1164
+ escapeValue,
1165
+ useRawValueToEscape,
1166
+ prefix,
1167
+ prefixEscaped,
1168
+ suffix,
1169
+ suffixEscaped,
1170
+ formatSeparator,
1171
+ unescapeSuffix,
1172
+ unescapePrefix,
1173
+ nestingPrefix,
1174
+ nestingPrefixEscaped,
1175
+ nestingSuffix,
1176
+ nestingSuffixEscaped,
1177
+ nestingOptionsSeparator,
1178
+ maxReplaces,
1179
+ alwaysFormat
1180
+ } = options.interpolation;
1181
+ this.escape = escape$1 !== void 0 ? escape$1 : escape;
1182
+ this.escapeValue = escapeValue !== void 0 ? escapeValue : true;
1183
+ this.useRawValueToEscape = useRawValueToEscape !== void 0 ? useRawValueToEscape : false;
1184
+ this.prefix = prefix ? regexEscape(prefix) : prefixEscaped || "{{";
1185
+ this.suffix = suffix ? regexEscape(suffix) : suffixEscaped || "}}";
1186
+ this.formatSeparator = formatSeparator || ",";
1187
+ this.unescapePrefix = unescapeSuffix ? "" : unescapePrefix || "-";
1188
+ this.unescapeSuffix = this.unescapePrefix ? "" : unescapeSuffix || "";
1189
+ this.nestingPrefix = nestingPrefix ? regexEscape(nestingPrefix) : nestingPrefixEscaped || regexEscape("$t(");
1190
+ this.nestingSuffix = nestingSuffix ? regexEscape(nestingSuffix) : nestingSuffixEscaped || regexEscape(")");
1191
+ this.nestingOptionsSeparator = nestingOptionsSeparator || ",";
1192
+ this.maxReplaces = maxReplaces || 1e3;
1193
+ this.alwaysFormat = alwaysFormat !== void 0 ? alwaysFormat : false;
1194
+ this.resetRegExp();
1195
+ }
1196
+ reset() {
1197
+ if (this.options) this.init(this.options);
1198
+ }
1199
+ resetRegExp() {
1200
+ const getOrResetRegExp = (existingRegExp, pattern) => {
1201
+ if (existingRegExp?.source === pattern) {
1202
+ existingRegExp.lastIndex = 0;
1203
+ return existingRegExp;
1204
+ }
1205
+ return new RegExp(pattern, "g");
1206
+ };
1207
+ this.regexp = getOrResetRegExp(this.regexp, `${this.prefix}(.+?)${this.suffix}`);
1208
+ this.regexpUnescape = getOrResetRegExp(this.regexpUnescape, `${this.prefix}${this.unescapePrefix}(.+?)${this.unescapeSuffix}${this.suffix}`);
1209
+ this.nestingRegexp = getOrResetRegExp(this.nestingRegexp, `${this.nestingPrefix}((?:[^()"']+|"[^"]*"|'[^']*'|\\((?:[^()]|"[^"]*"|'[^']*')*\\))*?)${this.nestingSuffix}`);
1210
+ }
1211
+ interpolate(str, data, lng, options) {
1212
+ let match;
1213
+ let value;
1214
+ let replaces;
1215
+ const defaultData = this.options && this.options.interpolation && this.options.interpolation.defaultVariables || {};
1216
+ const handleFormat = (key) => {
1217
+ if (key.indexOf(this.formatSeparator) < 0) {
1218
+ const path = deepFindWithDefaults(data, defaultData, key, this.options.keySeparator, this.options.ignoreJSONStructure);
1219
+ return this.alwaysFormat ? this.format(path, void 0, lng, {
1220
+ ...options,
1221
+ ...data,
1222
+ interpolationkey: key
1223
+ }) : path;
1224
+ }
1225
+ const p = key.split(this.formatSeparator);
1226
+ const k = p.shift().trim();
1227
+ const f = p.join(this.formatSeparator).trim();
1228
+ return this.format(deepFindWithDefaults(data, defaultData, k, this.options.keySeparator, this.options.ignoreJSONStructure), f, lng, {
1229
+ ...options,
1230
+ ...data,
1231
+ interpolationkey: k
1232
+ });
1233
+ };
1234
+ this.resetRegExp();
1235
+ const missingInterpolationHandler = options?.missingInterpolationHandler || this.options.missingInterpolationHandler;
1236
+ const skipOnVariables = options?.interpolation?.skipOnVariables !== void 0 ? options.interpolation.skipOnVariables : this.options.interpolation.skipOnVariables;
1237
+ const todos = [{
1238
+ regex: this.regexpUnescape,
1239
+ safeValue: (val) => regexSafe(val)
1240
+ }, {
1241
+ regex: this.regexp,
1242
+ safeValue: (val) => this.escapeValue ? regexSafe(this.escape(val)) : regexSafe(val)
1243
+ }];
1244
+ todos.forEach((todo) => {
1245
+ replaces = 0;
1246
+ while (match = todo.regex.exec(str)) {
1247
+ const matchedVar = match[1].trim();
1248
+ value = handleFormat(matchedVar);
1249
+ if (value === void 0) {
1250
+ if (typeof missingInterpolationHandler === "function") {
1251
+ const temp = missingInterpolationHandler(str, match, options);
1252
+ value = isString(temp) ? temp : "";
1253
+ } else if (options && Object.prototype.hasOwnProperty.call(options, matchedVar)) {
1254
+ value = "";
1255
+ } else if (skipOnVariables) {
1256
+ value = match[0];
1257
+ continue;
1258
+ } else {
1259
+ this.logger.warn(`missed to pass in variable ${matchedVar} for interpolating ${str}`);
1260
+ value = "";
1261
+ }
1262
+ } else if (!isString(value) && !this.useRawValueToEscape) {
1263
+ value = makeString(value);
1264
+ }
1265
+ const safeValue = todo.safeValue(value);
1266
+ str = str.replace(match[0], safeValue);
1267
+ if (skipOnVariables) {
1268
+ todo.regex.lastIndex += value.length;
1269
+ todo.regex.lastIndex -= match[0].length;
1270
+ } else {
1271
+ todo.regex.lastIndex = 0;
1272
+ }
1273
+ replaces++;
1274
+ if (replaces >= this.maxReplaces) {
1275
+ break;
1276
+ }
1277
+ }
1278
+ });
1279
+ return str;
1280
+ }
1281
+ nest(str, fc, options = {}) {
1282
+ let match;
1283
+ let value;
1284
+ let clonedOptions;
1285
+ const handleHasOptions = (key, inheritedOptions) => {
1286
+ const sep = this.nestingOptionsSeparator;
1287
+ if (key.indexOf(sep) < 0) return key;
1288
+ const c = key.split(new RegExp(`${sep}[ ]*{`));
1289
+ let optionsString = `{${c[1]}`;
1290
+ key = c[0];
1291
+ optionsString = this.interpolate(optionsString, clonedOptions);
1292
+ const matchedSingleQuotes = optionsString.match(/'/g);
1293
+ const matchedDoubleQuotes = optionsString.match(/"/g);
1294
+ if ((matchedSingleQuotes?.length ?? 0) % 2 === 0 && !matchedDoubleQuotes || matchedDoubleQuotes.length % 2 !== 0) {
1295
+ optionsString = optionsString.replace(/'/g, '"');
1296
+ }
1297
+ try {
1298
+ clonedOptions = JSON.parse(optionsString);
1299
+ if (inheritedOptions) clonedOptions = {
1300
+ ...inheritedOptions,
1301
+ ...clonedOptions
1302
+ };
1303
+ } catch (e) {
1304
+ this.logger.warn(`failed parsing options string in nesting for key ${key}`, e);
1305
+ return `${key}${sep}${optionsString}`;
1306
+ }
1307
+ if (clonedOptions.defaultValue && clonedOptions.defaultValue.indexOf(this.prefix) > -1) delete clonedOptions.defaultValue;
1308
+ return key;
1309
+ };
1310
+ while (match = this.nestingRegexp.exec(str)) {
1311
+ let formatters = [];
1312
+ clonedOptions = {
1313
+ ...options
1314
+ };
1315
+ clonedOptions = clonedOptions.replace && !isString(clonedOptions.replace) ? clonedOptions.replace : clonedOptions;
1316
+ clonedOptions.applyPostProcessor = false;
1317
+ delete clonedOptions.defaultValue;
1318
+ const keyEndIndex = /{.*}/.test(match[1]) ? match[1].lastIndexOf("}") + 1 : match[1].indexOf(this.formatSeparator);
1319
+ if (keyEndIndex !== -1) {
1320
+ formatters = match[1].slice(keyEndIndex).split(this.formatSeparator).map((elem) => elem.trim()).filter(Boolean);
1321
+ match[1] = match[1].slice(0, keyEndIndex);
1322
+ }
1323
+ value = fc(handleHasOptions.call(this, match[1].trim(), clonedOptions), clonedOptions);
1324
+ if (value && match[0] === str && !isString(value)) return value;
1325
+ if (!isString(value)) value = makeString(value);
1326
+ if (!value) {
1327
+ this.logger.warn(`missed to resolve ${match[1]} for nesting ${str}`);
1328
+ value = "";
1329
+ }
1330
+ if (formatters.length) {
1331
+ value = formatters.reduce((v, f) => this.format(v, f, options.lng, {
1332
+ ...options,
1333
+ interpolationkey: match[1].trim()
1334
+ }), value.trim());
1335
+ }
1336
+ str = str.replace(match[0], value);
1337
+ this.regexp.lastIndex = 0;
1338
+ }
1339
+ return str;
1340
+ }
1341
+ };
1342
+ var parseFormatStr = (formatStr) => {
1343
+ let formatName = formatStr.toLowerCase().trim();
1344
+ const formatOptions = {};
1345
+ if (formatStr.indexOf("(") > -1) {
1346
+ const p = formatStr.split("(");
1347
+ formatName = p[0].toLowerCase().trim();
1348
+ const optStr = p[1].substring(0, p[1].length - 1);
1349
+ if (formatName === "currency" && optStr.indexOf(":") < 0) {
1350
+ if (!formatOptions.currency) formatOptions.currency = optStr.trim();
1351
+ } else if (formatName === "relativetime" && optStr.indexOf(":") < 0) {
1352
+ if (!formatOptions.range) formatOptions.range = optStr.trim();
1353
+ } else {
1354
+ const opts = optStr.split(";");
1355
+ opts.forEach((opt) => {
1356
+ if (opt) {
1357
+ const [key, ...rest] = opt.split(":");
1358
+ const val = rest.join(":").trim().replace(/^'+|'+$/g, "");
1359
+ const trimmedKey = key.trim();
1360
+ if (!formatOptions[trimmedKey]) formatOptions[trimmedKey] = val;
1361
+ if (val === "false") formatOptions[trimmedKey] = false;
1362
+ if (val === "true") formatOptions[trimmedKey] = true;
1363
+ if (!isNaN(val)) formatOptions[trimmedKey] = parseInt(val, 10);
1364
+ }
1365
+ });
1366
+ }
1367
+ }
1368
+ return {
1369
+ formatName,
1370
+ formatOptions
1371
+ };
1372
+ };
1373
+ var createCachedFormatter = (fn) => {
1374
+ const cache = {};
1375
+ return (v, l, o) => {
1376
+ let optForCache = o;
1377
+ if (o && o.interpolationkey && o.formatParams && o.formatParams[o.interpolationkey] && o[o.interpolationkey]) {
1378
+ optForCache = {
1379
+ ...optForCache,
1380
+ [o.interpolationkey]: void 0
1381
+ };
1382
+ }
1383
+ const key = l + JSON.stringify(optForCache);
1384
+ let frm = cache[key];
1385
+ if (!frm) {
1386
+ frm = fn(getCleanedCode(l), o);
1387
+ cache[key] = frm;
1388
+ }
1389
+ return frm(v);
1390
+ };
1391
+ };
1392
+ var createNonCachedFormatter = (fn) => (v, l, o) => fn(getCleanedCode(l), o)(v);
1393
+ var Formatter = class {
1394
+ constructor(options = {}) {
1395
+ this.logger = baseLogger.create("formatter");
1396
+ this.options = options;
1397
+ this.init(options);
1398
+ }
1399
+ init(services, options = {
1400
+ interpolation: {}
1401
+ }) {
1402
+ this.formatSeparator = options.interpolation.formatSeparator || ",";
1403
+ const cf = options.cacheInBuiltFormats ? createCachedFormatter : createNonCachedFormatter;
1404
+ this.formats = {
1405
+ number: cf((lng, opt) => {
1406
+ const formatter = new Intl.NumberFormat(lng, {
1407
+ ...opt
1408
+ });
1409
+ return (val) => formatter.format(val);
1410
+ }),
1411
+ currency: cf((lng, opt) => {
1412
+ const formatter = new Intl.NumberFormat(lng, {
1413
+ ...opt,
1414
+ style: "currency"
1415
+ });
1416
+ return (val) => formatter.format(val);
1417
+ }),
1418
+ datetime: cf((lng, opt) => {
1419
+ const formatter = new Intl.DateTimeFormat(lng, {
1420
+ ...opt
1421
+ });
1422
+ return (val) => formatter.format(val);
1423
+ }),
1424
+ relativetime: cf((lng, opt) => {
1425
+ const formatter = new Intl.RelativeTimeFormat(lng, {
1426
+ ...opt
1427
+ });
1428
+ return (val) => formatter.format(val, opt.range || "day");
1429
+ }),
1430
+ list: cf((lng, opt) => {
1431
+ const formatter = new Intl.ListFormat(lng, {
1432
+ ...opt
1433
+ });
1434
+ return (val) => formatter.format(val);
1435
+ })
1436
+ };
1437
+ }
1438
+ add(name, fc) {
1439
+ this.formats[name.toLowerCase().trim()] = fc;
1440
+ }
1441
+ addCached(name, fc) {
1442
+ this.formats[name.toLowerCase().trim()] = createCachedFormatter(fc);
1443
+ }
1444
+ format(value, format, lng, options = {}) {
1445
+ const formats = format.split(this.formatSeparator);
1446
+ if (formats.length > 1 && formats[0].indexOf("(") > 1 && formats[0].indexOf(")") < 0 && formats.find((f) => f.indexOf(")") > -1)) {
1447
+ const lastIndex = formats.findIndex((f) => f.indexOf(")") > -1);
1448
+ formats[0] = [formats[0], ...formats.splice(1, lastIndex)].join(this.formatSeparator);
1449
+ }
1450
+ const result = formats.reduce((mem, f) => {
1451
+ const {
1452
+ formatName,
1453
+ formatOptions
1454
+ } = parseFormatStr(f);
1455
+ if (this.formats[formatName]) {
1456
+ let formatted = mem;
1457
+ try {
1458
+ const valOptions = options?.formatParams?.[options.interpolationkey] || {};
1459
+ const l = valOptions.locale || valOptions.lng || options.locale || options.lng || lng;
1460
+ formatted = this.formats[formatName](mem, l, {
1461
+ ...formatOptions,
1462
+ ...options,
1463
+ ...valOptions
1464
+ });
1465
+ } catch (error) {
1466
+ this.logger.warn(error);
1467
+ }
1468
+ return formatted;
1469
+ } else {
1470
+ this.logger.warn(`there was no format function for ${formatName}`);
1471
+ }
1472
+ return mem;
1473
+ }, value);
1474
+ return result;
1475
+ }
1476
+ };
1477
+ var removePending = (q, name) => {
1478
+ if (q.pending[name] !== void 0) {
1479
+ delete q.pending[name];
1480
+ q.pendingCount--;
1481
+ }
1482
+ };
1483
+ var Connector = class extends EventEmitter {
1484
+ constructor(backend, store, services, options = {}) {
1485
+ super();
1486
+ this.backend = backend;
1487
+ this.store = store;
1488
+ this.services = services;
1489
+ this.languageUtils = services.languageUtils;
1490
+ this.options = options;
1491
+ this.logger = baseLogger.create("backendConnector");
1492
+ this.waitingReads = [];
1493
+ this.maxParallelReads = options.maxParallelReads || 10;
1494
+ this.readingCalls = 0;
1495
+ this.maxRetries = options.maxRetries >= 0 ? options.maxRetries : 5;
1496
+ this.retryTimeout = options.retryTimeout >= 1 ? options.retryTimeout : 350;
1497
+ this.state = {};
1498
+ this.queue = [];
1499
+ this.backend?.init?.(services, options.backend, options);
1500
+ }
1501
+ queueLoad(languages, namespaces, options, callback) {
1502
+ const toLoad = {};
1503
+ const pending = {};
1504
+ const toLoadLanguages = {};
1505
+ const toLoadNamespaces = {};
1506
+ languages.forEach((lng) => {
1507
+ let hasAllNamespaces = true;
1508
+ namespaces.forEach((ns) => {
1509
+ const name = `${lng}|${ns}`;
1510
+ if (!options.reload && this.store.hasResourceBundle(lng, ns)) {
1511
+ this.state[name] = 2;
1512
+ } else if (this.state[name] < 0) ;
1513
+ else if (this.state[name] === 1) {
1514
+ if (pending[name] === void 0) pending[name] = true;
1515
+ } else {
1516
+ this.state[name] = 1;
1517
+ hasAllNamespaces = false;
1518
+ if (pending[name] === void 0) pending[name] = true;
1519
+ if (toLoad[name] === void 0) toLoad[name] = true;
1520
+ if (toLoadNamespaces[ns] === void 0) toLoadNamespaces[ns] = true;
1521
+ }
1522
+ });
1523
+ if (!hasAllNamespaces) toLoadLanguages[lng] = true;
1524
+ });
1525
+ if (Object.keys(toLoad).length || Object.keys(pending).length) {
1526
+ this.queue.push({
1527
+ pending,
1528
+ pendingCount: Object.keys(pending).length,
1529
+ loaded: {},
1530
+ errors: [],
1531
+ callback
1532
+ });
1533
+ }
1534
+ return {
1535
+ toLoad: Object.keys(toLoad),
1536
+ pending: Object.keys(pending),
1537
+ toLoadLanguages: Object.keys(toLoadLanguages),
1538
+ toLoadNamespaces: Object.keys(toLoadNamespaces)
1539
+ };
1540
+ }
1541
+ loaded(name, err, data) {
1542
+ const s = name.split("|");
1543
+ const lng = s[0];
1544
+ const ns = s[1];
1545
+ if (err) this.emit("failedLoading", lng, ns, err);
1546
+ if (!err && data) {
1547
+ this.store.addResourceBundle(lng, ns, data, void 0, void 0, {
1548
+ skipCopy: true
1549
+ });
1550
+ }
1551
+ this.state[name] = err ? -1 : 2;
1552
+ if (err && data) this.state[name] = 0;
1553
+ const loaded = {};
1554
+ this.queue.forEach((q) => {
1555
+ pushPath(q.loaded, [lng], ns);
1556
+ removePending(q, name);
1557
+ if (err) q.errors.push(err);
1558
+ if (q.pendingCount === 0 && !q.done) {
1559
+ Object.keys(q.loaded).forEach((l) => {
1560
+ if (!loaded[l]) loaded[l] = {};
1561
+ const loadedKeys = q.loaded[l];
1562
+ if (loadedKeys.length) {
1563
+ loadedKeys.forEach((n) => {
1564
+ if (loaded[l][n] === void 0) loaded[l][n] = true;
1565
+ });
1566
+ }
1567
+ });
1568
+ q.done = true;
1569
+ if (q.errors.length) {
1570
+ q.callback(q.errors);
1571
+ } else {
1572
+ q.callback();
1573
+ }
1574
+ }
1575
+ });
1576
+ this.emit("loaded", loaded);
1577
+ this.queue = this.queue.filter((q) => !q.done);
1578
+ }
1579
+ read(lng, ns, fcName, tried = 0, wait = this.retryTimeout, callback) {
1580
+ if (!lng.length) return callback(null, {});
1581
+ if (this.readingCalls >= this.maxParallelReads) {
1582
+ this.waitingReads.push({
1583
+ lng,
1584
+ ns,
1585
+ fcName,
1586
+ tried,
1587
+ wait,
1588
+ callback
1589
+ });
1590
+ return;
1591
+ }
1592
+ this.readingCalls++;
1593
+ const resolver = (err, data) => {
1594
+ this.readingCalls--;
1595
+ if (this.waitingReads.length > 0) {
1596
+ const next = this.waitingReads.shift();
1597
+ this.read(next.lng, next.ns, next.fcName, next.tried, next.wait, next.callback);
1598
+ }
1599
+ if (err && data && tried < this.maxRetries) {
1600
+ setTimeout(() => {
1601
+ this.read.call(this, lng, ns, fcName, tried + 1, wait * 2, callback);
1602
+ }, wait);
1603
+ return;
1604
+ }
1605
+ callback(err, data);
1606
+ };
1607
+ const fc = this.backend[fcName].bind(this.backend);
1608
+ if (fc.length === 2) {
1609
+ try {
1610
+ const r = fc(lng, ns);
1611
+ if (r && typeof r.then === "function") {
1612
+ r.then((data) => resolver(null, data)).catch(resolver);
1613
+ } else {
1614
+ resolver(null, r);
1615
+ }
1616
+ } catch (err) {
1617
+ resolver(err);
1618
+ }
1619
+ return;
1620
+ }
1621
+ return fc(lng, ns, resolver);
1622
+ }
1623
+ prepareLoading(languages, namespaces, options = {}, callback) {
1624
+ if (!this.backend) {
1625
+ this.logger.warn("No backend was added via i18next.use. Will not load resources.");
1626
+ return callback && callback();
1627
+ }
1628
+ if (isString(languages)) languages = this.languageUtils.toResolveHierarchy(languages);
1629
+ if (isString(namespaces)) namespaces = [namespaces];
1630
+ const toLoad = this.queueLoad(languages, namespaces, options, callback);
1631
+ if (!toLoad.toLoad.length) {
1632
+ if (!toLoad.pending.length) callback();
1633
+ return null;
1634
+ }
1635
+ toLoad.toLoad.forEach((name) => {
1636
+ this.loadOne(name);
1637
+ });
1638
+ }
1639
+ load(languages, namespaces, callback) {
1640
+ this.prepareLoading(languages, namespaces, {}, callback);
1641
+ }
1642
+ reload(languages, namespaces, callback) {
1643
+ this.prepareLoading(languages, namespaces, {
1644
+ reload: true
1645
+ }, callback);
1646
+ }
1647
+ loadOne(name, prefix = "") {
1648
+ const s = name.split("|");
1649
+ const lng = s[0];
1650
+ const ns = s[1];
1651
+ this.read(lng, ns, "read", void 0, void 0, (err, data) => {
1652
+ if (err) this.logger.warn(`${prefix}loading namespace ${ns} for language ${lng} failed`, err);
1653
+ if (!err && data) this.logger.log(`${prefix}loaded namespace ${ns} for language ${lng}`, data);
1654
+ this.loaded(name, err, data);
1655
+ });
1656
+ }
1657
+ saveMissing(languages, namespace, key, fallbackValue, isUpdate, options = {}, clb = () => {
1658
+ }) {
1659
+ if (this.services?.utils?.hasLoadedNamespace && !this.services?.utils?.hasLoadedNamespace(namespace)) {
1660
+ 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!!!");
1661
+ return;
1662
+ }
1663
+ if (key === void 0 || key === null || key === "") return;
1664
+ if (this.backend?.create) {
1665
+ const opts = {
1666
+ ...options,
1667
+ isUpdate
1668
+ };
1669
+ const fc = this.backend.create.bind(this.backend);
1670
+ if (fc.length < 6) {
1671
+ try {
1672
+ let r;
1673
+ if (fc.length === 5) {
1674
+ r = fc(languages, namespace, key, fallbackValue, opts);
1675
+ } else {
1676
+ r = fc(languages, namespace, key, fallbackValue);
1677
+ }
1678
+ if (r && typeof r.then === "function") {
1679
+ r.then((data) => clb(null, data)).catch(clb);
1680
+ } else {
1681
+ clb(null, r);
1682
+ }
1683
+ } catch (err) {
1684
+ clb(err);
1685
+ }
1686
+ } else {
1687
+ fc(languages, namespace, key, fallbackValue, clb, opts);
1688
+ }
1689
+ }
1690
+ if (!languages || !languages[0]) return;
1691
+ this.store.addResource(languages[0], namespace, key, fallbackValue);
1692
+ }
1693
+ };
1694
+ var get = () => ({
1695
+ debug: false,
1696
+ initAsync: true,
1697
+ ns: ["translation"],
1698
+ defaultNS: ["translation"],
1699
+ fallbackLng: ["dev"],
1700
+ fallbackNS: false,
1701
+ supportedLngs: false,
1702
+ nonExplicitSupportedLngs: false,
1703
+ load: "all",
1704
+ preload: false,
1705
+ simplifyPluralSuffix: true,
1706
+ keySeparator: ".",
1707
+ nsSeparator: ":",
1708
+ pluralSeparator: "_",
1709
+ contextSeparator: "_",
1710
+ partialBundledLanguages: false,
1711
+ saveMissing: false,
1712
+ updateMissing: false,
1713
+ saveMissingTo: "fallback",
1714
+ saveMissingPlurals: true,
1715
+ missingKeyHandler: false,
1716
+ missingInterpolationHandler: false,
1717
+ postProcess: false,
1718
+ postProcessPassResolved: false,
1719
+ returnNull: false,
1720
+ returnEmptyString: true,
1721
+ returnObjects: false,
1722
+ joinArrays: false,
1723
+ returnedObjectHandler: false,
1724
+ parseMissingKeyHandler: false,
1725
+ appendNamespaceToMissingKey: false,
1726
+ appendNamespaceToCIMode: false,
1727
+ overloadTranslationOptionHandler: (args) => {
1728
+ let ret = {};
1729
+ if (typeof args[1] === "object") ret = args[1];
1730
+ if (isString(args[1])) ret.defaultValue = args[1];
1731
+ if (isString(args[2])) ret.tDescription = args[2];
1732
+ if (typeof args[2] === "object" || typeof args[3] === "object") {
1733
+ const options = args[3] || args[2];
1734
+ Object.keys(options).forEach((key) => {
1735
+ ret[key] = options[key];
1736
+ });
1737
+ }
1738
+ return ret;
1739
+ },
1740
+ interpolation: {
1741
+ escapeValue: true,
1742
+ format: (value) => value,
1743
+ prefix: "{{",
1744
+ suffix: "}}",
1745
+ formatSeparator: ",",
1746
+ unescapePrefix: "-",
1747
+ nestingPrefix: "$t(",
1748
+ nestingSuffix: ")",
1749
+ nestingOptionsSeparator: ",",
1750
+ maxReplaces: 1e3,
1751
+ skipOnVariables: true
1752
+ },
1753
+ cacheInBuiltFormats: true
1754
+ });
1755
+ var transformOptions = (options) => {
1756
+ if (isString(options.ns)) options.ns = [options.ns];
1757
+ if (isString(options.fallbackLng)) options.fallbackLng = [options.fallbackLng];
1758
+ if (isString(options.fallbackNS)) options.fallbackNS = [options.fallbackNS];
1759
+ if (options.supportedLngs?.indexOf?.("cimode") < 0) {
1760
+ options.supportedLngs = options.supportedLngs.concat(["cimode"]);
1761
+ }
1762
+ if (typeof options.initImmediate === "boolean") options.initAsync = options.initImmediate;
1763
+ return options;
1764
+ };
1765
+ var noop = () => {
1766
+ };
1767
+ var bindMemberFunctions = (inst) => {
1768
+ const mems = Object.getOwnPropertyNames(Object.getPrototypeOf(inst));
1769
+ mems.forEach((mem) => {
1770
+ if (typeof inst[mem] === "function") {
1771
+ inst[mem] = inst[mem].bind(inst);
1772
+ }
1773
+ });
1774
+ };
1775
+ var I18n = class _I18n extends EventEmitter {
1776
+ constructor(options = {}, callback) {
1777
+ super();
1778
+ this.options = transformOptions(options);
1779
+ this.services = {};
1780
+ this.logger = baseLogger;
1781
+ this.modules = {
1782
+ external: []
1783
+ };
1784
+ bindMemberFunctions(this);
1785
+ if (callback && !this.isInitialized && !options.isClone) {
1786
+ if (!this.options.initAsync) {
1787
+ this.init(options, callback);
1788
+ return this;
1789
+ }
1790
+ setTimeout(() => {
1791
+ this.init(options, callback);
1792
+ }, 0);
1793
+ }
1794
+ }
1795
+ init(options = {}, callback) {
1796
+ this.isInitializing = true;
1797
+ if (typeof options === "function") {
1798
+ callback = options;
1799
+ options = {};
1800
+ }
1801
+ if (options.defaultNS == null && options.ns) {
1802
+ if (isString(options.ns)) {
1803
+ options.defaultNS = options.ns;
1804
+ } else if (options.ns.indexOf("translation") < 0) {
1805
+ options.defaultNS = options.ns[0];
1806
+ }
1807
+ }
1808
+ const defOpts = get();
1809
+ this.options = {
1810
+ ...defOpts,
1811
+ ...this.options,
1812
+ ...transformOptions(options)
1813
+ };
1814
+ this.options.interpolation = {
1815
+ ...defOpts.interpolation,
1816
+ ...this.options.interpolation
1817
+ };
1818
+ if (options.keySeparator !== void 0) {
1819
+ this.options.userDefinedKeySeparator = options.keySeparator;
1820
+ }
1821
+ if (options.nsSeparator !== void 0) {
1822
+ this.options.userDefinedNsSeparator = options.nsSeparator;
1823
+ }
1824
+ const createClassOnDemand = (ClassOrObject) => {
1825
+ if (!ClassOrObject) return null;
1826
+ if (typeof ClassOrObject === "function") return new ClassOrObject();
1827
+ return ClassOrObject;
1828
+ };
1829
+ if (!this.options.isClone) {
1830
+ if (this.modules.logger) {
1831
+ baseLogger.init(createClassOnDemand(this.modules.logger), this.options);
1832
+ } else {
1833
+ baseLogger.init(null, this.options);
1834
+ }
1835
+ let formatter;
1836
+ if (this.modules.formatter) {
1837
+ formatter = this.modules.formatter;
1838
+ } else {
1839
+ formatter = Formatter;
1840
+ }
1841
+ const lu = new LanguageUtil(this.options);
1842
+ this.store = new ResourceStore(this.options.resources, this.options);
1843
+ const s = this.services;
1844
+ s.logger = baseLogger;
1845
+ s.resourceStore = this.store;
1846
+ s.languageUtils = lu;
1847
+ s.pluralResolver = new PluralResolver(lu, {
1848
+ prepend: this.options.pluralSeparator,
1849
+ simplifyPluralSuffix: this.options.simplifyPluralSuffix
1850
+ });
1851
+ const usingLegacyFormatFunction = this.options.interpolation.format && this.options.interpolation.format !== defOpts.interpolation.format;
1852
+ if (usingLegacyFormatFunction) {
1853
+ this.logger.deprecate(`init: you are still using the legacy format function, please use the new approach: https://www.i18next.com/translation-function/formatting`);
1854
+ }
1855
+ if (formatter && (!this.options.interpolation.format || this.options.interpolation.format === defOpts.interpolation.format)) {
1856
+ s.formatter = createClassOnDemand(formatter);
1857
+ if (s.formatter.init) s.formatter.init(s, this.options);
1858
+ this.options.interpolation.format = s.formatter.format.bind(s.formatter);
1859
+ }
1860
+ s.interpolator = new Interpolator(this.options);
1861
+ s.utils = {
1862
+ hasLoadedNamespace: this.hasLoadedNamespace.bind(this)
1863
+ };
1864
+ s.backendConnector = new Connector(createClassOnDemand(this.modules.backend), s.resourceStore, s, this.options);
1865
+ s.backendConnector.on("*", (event, ...args) => {
1866
+ this.emit(event, ...args);
1867
+ });
1868
+ if (this.modules.languageDetector) {
1869
+ s.languageDetector = createClassOnDemand(this.modules.languageDetector);
1870
+ if (s.languageDetector.init) s.languageDetector.init(s, this.options.detection, this.options);
1871
+ }
1872
+ if (this.modules.i18nFormat) {
1873
+ s.i18nFormat = createClassOnDemand(this.modules.i18nFormat);
1874
+ if (s.i18nFormat.init) s.i18nFormat.init(this);
1875
+ }
1876
+ this.translator = new Translator(this.services, this.options);
1877
+ this.translator.on("*", (event, ...args) => {
1878
+ this.emit(event, ...args);
1879
+ });
1880
+ this.modules.external.forEach((m) => {
1881
+ if (m.init) m.init(this);
1882
+ });
1883
+ }
1884
+ this.format = this.options.interpolation.format;
1885
+ if (!callback) callback = noop;
1886
+ if (this.options.fallbackLng && !this.services.languageDetector && !this.options.lng) {
1887
+ const codes = this.services.languageUtils.getFallbackCodes(this.options.fallbackLng);
1888
+ if (codes.length > 0 && codes[0] !== "dev") this.options.lng = codes[0];
1889
+ }
1890
+ if (!this.services.languageDetector && !this.options.lng) {
1891
+ this.logger.warn("init: no languageDetector is used and no lng is defined");
1892
+ }
1893
+ const storeApi = ["getResource", "hasResourceBundle", "getResourceBundle", "getDataByLanguage"];
1894
+ storeApi.forEach((fcName) => {
1895
+ this[fcName] = (...args) => this.store[fcName](...args);
1896
+ });
1897
+ const storeApiChained = ["addResource", "addResources", "addResourceBundle", "removeResourceBundle"];
1898
+ storeApiChained.forEach((fcName) => {
1899
+ this[fcName] = (...args) => {
1900
+ this.store[fcName](...args);
1901
+ return this;
1902
+ };
1903
+ });
1904
+ const deferred = defer();
1905
+ const load = () => {
1906
+ const finish = (err, t2) => {
1907
+ this.isInitializing = false;
1908
+ if (this.isInitialized && !this.initializedStoreOnce) this.logger.warn("init: i18next is already initialized. You should call init just once!");
1909
+ this.isInitialized = true;
1910
+ if (!this.options.isClone) this.logger.log("initialized", this.options);
1911
+ this.emit("initialized", this.options);
1912
+ deferred.resolve(t2);
1913
+ callback(err, t2);
1914
+ };
1915
+ if (this.languages && !this.isInitialized) return finish(null, this.t.bind(this));
1916
+ this.changeLanguage(this.options.lng, finish);
1917
+ };
1918
+ if (this.options.resources || !this.options.initAsync) {
1919
+ load();
1920
+ } else {
1921
+ setTimeout(load, 0);
1922
+ }
1923
+ return deferred;
1924
+ }
1925
+ loadResources(language, callback = noop) {
1926
+ let usedCallback = callback;
1927
+ const usedLng = isString(language) ? language : this.language;
1928
+ if (typeof language === "function") usedCallback = language;
1929
+ if (!this.options.resources || this.options.partialBundledLanguages) {
1930
+ if (usedLng?.toLowerCase() === "cimode" && (!this.options.preload || this.options.preload.length === 0)) return usedCallback();
1931
+ const toLoad = [];
1932
+ const append = (lng) => {
1933
+ if (!lng) return;
1934
+ if (lng === "cimode") return;
1935
+ const lngs = this.services.languageUtils.toResolveHierarchy(lng);
1936
+ lngs.forEach((l) => {
1937
+ if (l === "cimode") return;
1938
+ if (toLoad.indexOf(l) < 0) toLoad.push(l);
1939
+ });
1940
+ };
1941
+ if (!usedLng) {
1942
+ const fallbacks = this.services.languageUtils.getFallbackCodes(this.options.fallbackLng);
1943
+ fallbacks.forEach((l) => append(l));
1944
+ } else {
1945
+ append(usedLng);
1946
+ }
1947
+ this.options.preload?.forEach?.((l) => append(l));
1948
+ this.services.backendConnector.load(toLoad, this.options.ns, (e) => {
1949
+ if (!e && !this.resolvedLanguage && this.language) this.setResolvedLanguage(this.language);
1950
+ usedCallback(e);
1951
+ });
1952
+ } else {
1953
+ usedCallback(null);
1954
+ }
1955
+ }
1956
+ reloadResources(lngs, ns, callback) {
1957
+ const deferred = defer();
1958
+ if (typeof lngs === "function") {
1959
+ callback = lngs;
1960
+ lngs = void 0;
1961
+ }
1962
+ if (typeof ns === "function") {
1963
+ callback = ns;
1964
+ ns = void 0;
1965
+ }
1966
+ if (!lngs) lngs = this.languages;
1967
+ if (!ns) ns = this.options.ns;
1968
+ if (!callback) callback = noop;
1969
+ this.services.backendConnector.reload(lngs, ns, (err) => {
1970
+ deferred.resolve();
1971
+ callback(err);
1972
+ });
1973
+ return deferred;
1974
+ }
1975
+ use(module2) {
1976
+ if (!module2) throw new Error("You are passing an undefined module! Please check the object you are passing to i18next.use()");
1977
+ if (!module2.type) throw new Error("You are passing a wrong module! Please check the object you are passing to i18next.use()");
1978
+ if (module2.type === "backend") {
1979
+ this.modules.backend = module2;
1980
+ }
1981
+ if (module2.type === "logger" || module2.log && module2.warn && module2.error) {
1982
+ this.modules.logger = module2;
1983
+ }
1984
+ if (module2.type === "languageDetector") {
1985
+ this.modules.languageDetector = module2;
1986
+ }
1987
+ if (module2.type === "i18nFormat") {
1988
+ this.modules.i18nFormat = module2;
1989
+ }
1990
+ if (module2.type === "postProcessor") {
1991
+ postProcessor.addPostProcessor(module2);
1992
+ }
1993
+ if (module2.type === "formatter") {
1994
+ this.modules.formatter = module2;
1995
+ }
1996
+ if (module2.type === "3rdParty") {
1997
+ this.modules.external.push(module2);
1998
+ }
1999
+ return this;
2000
+ }
2001
+ setResolvedLanguage(l) {
2002
+ if (!l || !this.languages) return;
2003
+ if (["cimode", "dev"].indexOf(l) > -1) return;
2004
+ for (let li = 0; li < this.languages.length; li++) {
2005
+ const lngInLngs = this.languages[li];
2006
+ if (["cimode", "dev"].indexOf(lngInLngs) > -1) continue;
2007
+ if (this.store.hasLanguageSomeTranslations(lngInLngs)) {
2008
+ this.resolvedLanguage = lngInLngs;
2009
+ break;
2010
+ }
2011
+ }
2012
+ if (!this.resolvedLanguage && this.languages.indexOf(l) < 0 && this.store.hasLanguageSomeTranslations(l)) {
2013
+ this.resolvedLanguage = l;
2014
+ this.languages.unshift(l);
2015
+ }
2016
+ }
2017
+ changeLanguage(lng, callback) {
2018
+ this.isLanguageChangingTo = lng;
2019
+ const deferred = defer();
2020
+ this.emit("languageChanging", lng);
2021
+ const setLngProps = (l) => {
2022
+ this.language = l;
2023
+ this.languages = this.services.languageUtils.toResolveHierarchy(l);
2024
+ this.resolvedLanguage = void 0;
2025
+ this.setResolvedLanguage(l);
2026
+ };
2027
+ const done = (err, l) => {
2028
+ if (l) {
2029
+ if (this.isLanguageChangingTo === lng) {
2030
+ setLngProps(l);
2031
+ this.translator.changeLanguage(l);
2032
+ this.isLanguageChangingTo = void 0;
2033
+ this.emit("languageChanged", l);
2034
+ this.logger.log("languageChanged", l);
2035
+ }
2036
+ } else {
2037
+ this.isLanguageChangingTo = void 0;
2038
+ }
2039
+ deferred.resolve((...args) => this.t(...args));
2040
+ if (callback) callback(err, (...args) => this.t(...args));
2041
+ };
2042
+ const setLng = (lngs) => {
2043
+ if (!lng && !lngs && this.services.languageDetector) lngs = [];
2044
+ const fl = isString(lngs) ? lngs : lngs && lngs[0];
2045
+ const l = this.store.hasLanguageSomeTranslations(fl) ? fl : this.services.languageUtils.getBestMatchFromCodes(isString(lngs) ? [lngs] : lngs);
2046
+ if (l) {
2047
+ if (!this.language) {
2048
+ setLngProps(l);
2049
+ }
2050
+ if (!this.translator.language) this.translator.changeLanguage(l);
2051
+ this.services.languageDetector?.cacheUserLanguage?.(l);
2052
+ }
2053
+ this.loadResources(l, (err) => {
2054
+ done(err, l);
2055
+ });
2056
+ };
2057
+ if (!lng && this.services.languageDetector && !this.services.languageDetector.async) {
2058
+ setLng(this.services.languageDetector.detect());
2059
+ } else if (!lng && this.services.languageDetector && this.services.languageDetector.async) {
2060
+ if (this.services.languageDetector.detect.length === 0) {
2061
+ this.services.languageDetector.detect().then(setLng);
2062
+ } else {
2063
+ this.services.languageDetector.detect(setLng);
2064
+ }
2065
+ } else {
2066
+ setLng(lng);
2067
+ }
2068
+ return deferred;
2069
+ }
2070
+ getFixedT(lng, ns, keyPrefix) {
2071
+ const fixedT = (key, opts, ...rest) => {
2072
+ let o;
2073
+ if (typeof opts !== "object") {
2074
+ o = this.options.overloadTranslationOptionHandler([key, opts].concat(rest));
2075
+ } else {
2076
+ o = {
2077
+ ...opts
2078
+ };
2079
+ }
2080
+ o.lng = o.lng || fixedT.lng;
2081
+ o.lngs = o.lngs || fixedT.lngs;
2082
+ o.ns = o.ns || fixedT.ns;
2083
+ if (o.keyPrefix !== "") o.keyPrefix = o.keyPrefix || keyPrefix || fixedT.keyPrefix;
2084
+ const keySeparator = this.options.keySeparator || ".";
2085
+ let resultKey;
2086
+ if (o.keyPrefix && Array.isArray(key)) {
2087
+ resultKey = key.map((k) => {
2088
+ if (typeof k === "function") k = keysFromSelector(k, {
2089
+ ...this.options,
2090
+ ...opts
2091
+ });
2092
+ return `${o.keyPrefix}${keySeparator}${k}`;
2093
+ });
2094
+ } else {
2095
+ if (typeof key === "function") key = keysFromSelector(key, {
2096
+ ...this.options,
2097
+ ...opts
2098
+ });
2099
+ resultKey = o.keyPrefix ? `${o.keyPrefix}${keySeparator}${key}` : key;
2100
+ }
2101
+ return this.t(resultKey, o);
2102
+ };
2103
+ if (isString(lng)) {
2104
+ fixedT.lng = lng;
2105
+ } else {
2106
+ fixedT.lngs = lng;
2107
+ }
2108
+ fixedT.ns = ns;
2109
+ fixedT.keyPrefix = keyPrefix;
2110
+ return fixedT;
2111
+ }
2112
+ t(...args) {
2113
+ return this.translator?.translate(...args);
2114
+ }
2115
+ exists(...args) {
2116
+ return this.translator?.exists(...args);
2117
+ }
2118
+ setDefaultNamespace(ns) {
2119
+ this.options.defaultNS = ns;
2120
+ }
2121
+ hasLoadedNamespace(ns, options = {}) {
2122
+ if (!this.isInitialized) {
2123
+ this.logger.warn("hasLoadedNamespace: i18next was not initialized", this.languages);
2124
+ return false;
2125
+ }
2126
+ if (!this.languages || !this.languages.length) {
2127
+ this.logger.warn("hasLoadedNamespace: i18n.languages were undefined or empty", this.languages);
2128
+ return false;
2129
+ }
2130
+ const lng = options.lng || this.resolvedLanguage || this.languages[0];
2131
+ const fallbackLng = this.options ? this.options.fallbackLng : false;
2132
+ const lastLng = this.languages[this.languages.length - 1];
2133
+ if (lng.toLowerCase() === "cimode") return true;
2134
+ const loadNotPending = (l, n) => {
2135
+ const loadState = this.services.backendConnector.state[`${l}|${n}`];
2136
+ return loadState === -1 || loadState === 0 || loadState === 2;
2137
+ };
2138
+ if (options.precheck) {
2139
+ const preResult = options.precheck(this, loadNotPending);
2140
+ if (preResult !== void 0) return preResult;
2141
+ }
2142
+ if (this.hasResourceBundle(lng, ns)) return true;
2143
+ if (!this.services.backendConnector.backend || this.options.resources && !this.options.partialBundledLanguages) return true;
2144
+ if (loadNotPending(lng, ns) && (!fallbackLng || loadNotPending(lastLng, ns))) return true;
2145
+ return false;
2146
+ }
2147
+ loadNamespaces(ns, callback) {
2148
+ const deferred = defer();
2149
+ if (!this.options.ns) {
2150
+ if (callback) callback();
2151
+ return Promise.resolve();
2152
+ }
2153
+ if (isString(ns)) ns = [ns];
2154
+ ns.forEach((n) => {
2155
+ if (this.options.ns.indexOf(n) < 0) this.options.ns.push(n);
2156
+ });
2157
+ this.loadResources((err) => {
2158
+ deferred.resolve();
2159
+ if (callback) callback(err);
2160
+ });
2161
+ return deferred;
2162
+ }
2163
+ loadLanguages(lngs, callback) {
2164
+ const deferred = defer();
2165
+ if (isString(lngs)) lngs = [lngs];
2166
+ const preloaded = this.options.preload || [];
2167
+ const newLngs = lngs.filter((lng) => preloaded.indexOf(lng) < 0 && this.services.languageUtils.isSupportedCode(lng));
2168
+ if (!newLngs.length) {
2169
+ if (callback) callback();
2170
+ return Promise.resolve();
2171
+ }
2172
+ this.options.preload = preloaded.concat(newLngs);
2173
+ this.loadResources((err) => {
2174
+ deferred.resolve();
2175
+ if (callback) callback(err);
2176
+ });
2177
+ return deferred;
2178
+ }
2179
+ dir(lng) {
2180
+ if (!lng) lng = this.resolvedLanguage || (this.languages?.length > 0 ? this.languages[0] : this.language);
2181
+ if (!lng) return "rtl";
2182
+ try {
2183
+ const l = new Intl.Locale(lng);
2184
+ if (l && l.getTextInfo) {
2185
+ const ti = l.getTextInfo();
2186
+ if (ti && ti.direction) return ti.direction;
2187
+ }
2188
+ } catch (e) {
2189
+ }
2190
+ 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"];
2191
+ const languageUtils = this.services?.languageUtils || new LanguageUtil(get());
2192
+ if (lng.toLowerCase().indexOf("-latn") > 1) return "ltr";
2193
+ return rtlLngs.indexOf(languageUtils.getLanguagePartFromCode(lng)) > -1 || lng.toLowerCase().indexOf("-arab") > 1 ? "rtl" : "ltr";
2194
+ }
2195
+ static createInstance(options = {}, callback) {
2196
+ const instance2 = new _I18n(options, callback);
2197
+ instance2.createInstance = _I18n.createInstance;
2198
+ return instance2;
2199
+ }
2200
+ cloneInstance(options = {}, callback = noop) {
2201
+ const forkResourceStore = options.forkResourceStore;
2202
+ if (forkResourceStore) delete options.forkResourceStore;
2203
+ const mergedOptions = {
2204
+ ...this.options,
2205
+ ...options,
2206
+ ...{
2207
+ isClone: true
2208
+ }
2209
+ };
2210
+ const clone = new _I18n(mergedOptions);
2211
+ if (options.debug !== void 0 || options.prefix !== void 0) {
2212
+ clone.logger = clone.logger.clone(options);
2213
+ }
2214
+ const membersToCopy = ["store", "services", "language"];
2215
+ membersToCopy.forEach((m) => {
2216
+ clone[m] = this[m];
2217
+ });
2218
+ clone.services = {
2219
+ ...this.services
2220
+ };
2221
+ clone.services.utils = {
2222
+ hasLoadedNamespace: clone.hasLoadedNamespace.bind(clone)
2223
+ };
2224
+ if (forkResourceStore) {
2225
+ const clonedData = Object.keys(this.store.data).reduce((prev, l) => {
2226
+ prev[l] = {
2227
+ ...this.store.data[l]
2228
+ };
2229
+ prev[l] = Object.keys(prev[l]).reduce((acc, n) => {
2230
+ acc[n] = {
2231
+ ...prev[l][n]
2232
+ };
2233
+ return acc;
2234
+ }, prev[l]);
2235
+ return prev;
2236
+ }, {});
2237
+ clone.store = new ResourceStore(clonedData, mergedOptions);
2238
+ clone.services.resourceStore = clone.store;
2239
+ }
2240
+ if (options.interpolation) clone.services.interpolator = new Interpolator(mergedOptions);
2241
+ clone.translator = new Translator(clone.services, mergedOptions);
2242
+ clone.translator.on("*", (event, ...args) => {
2243
+ clone.emit(event, ...args);
2244
+ });
2245
+ clone.init(mergedOptions, callback);
2246
+ clone.translator.options = mergedOptions;
2247
+ clone.translator.backendConnector.services.utils = {
2248
+ hasLoadedNamespace: clone.hasLoadedNamespace.bind(clone)
2249
+ };
2250
+ return clone;
2251
+ }
2252
+ toJSON() {
2253
+ return {
2254
+ options: this.options,
2255
+ store: this.store,
2256
+ language: this.language,
2257
+ languages: this.languages,
2258
+ resolvedLanguage: this.resolvedLanguage
2259
+ };
2260
+ }
2261
+ };
2262
+ var instance = I18n.createInstance();
2263
+ var createInstance = instance.createInstance;
2264
+ var dir = instance.dir;
2265
+ var init = instance.init;
2266
+ var loadResources = instance.loadResources;
2267
+ var reloadResources = instance.reloadResources;
2268
+ var use = instance.use;
2269
+ var changeLanguage = instance.changeLanguage;
2270
+ var getFixedT = instance.getFixedT;
2271
+ var t = instance.t;
2272
+ var exists = instance.exists;
2273
+ var setDefaultNamespace = instance.setDefaultNamespace;
2274
+ var hasLoadedNamespace = instance.hasLoadedNamespace;
2275
+ var loadNamespaces = instance.loadNamespaces;
2276
+ var loadLanguages = instance.loadLanguages;
2277
+
2278
+ // src/locale/en/locale-resources.ts
2279
+ var locale_resources_default = {
2280
+ Check: {
2281
+ lengthOfStringForPriceOrWeightMustBeExactly: "Length {{length, number}} of string for price or weight must be 4 or 5",
2282
+ priceOrWeightComponent: "price or weight",
2283
+ lengthOfStringForCheckCharacterPairMustBeLessThanOrEqualTo: "Length {{length, number}} of string for check character pair must be less than or equal to {{maximumLength, number}}"
2284
+ },
2285
+ Identifier: {
2286
+ identifierTypeLength: "{{identifierType}} must be {{length, number}} digits long",
2287
+ invalidCheckDigit: "Invalid check digit",
2288
+ invalidGTINLength: "GTIN must be 13, 12, 8, or 14 digits long",
2289
+ invalidGTIN14Length: "GTIN must be 14 digits long",
2290
+ invalidZeroSuppressedGTIN12: "Invalid zero-suppressed GTIN-12",
2291
+ invalidZeroSuppressibleGTIN12: "GTIN-12 not zero-suppressible",
2292
+ invalidZeroSuppressedGTIN12AsGTIN13: "Invalid zero-suppressed GTIN-12 as GTIN-13",
2293
+ invalidZeroSuppressedGTIN12AsGTIN14: "Invalid zero-suppressed GTIN-12 as GTIN-14",
2294
+ invalidGTIN13AtRetail: "GTIN-13 at retail consumer trade item level can't start with zero",
2295
+ invalidGTINAtRetail: "GTIN not supported at retail consumer trade item level",
2296
+ invalidGTINAtOtherThanRetail: "GTIN not supported at other than retail consumer trade item level",
2297
+ invalidRCNLength: "RCN length must match format length",
2298
+ invalidVariableMeasureRCNFormat: "Invalid variable measure RCN format",
2299
+ invalidVariableMeasureRCNPrefix: "Invalid variable measure RCN prefix",
2300
+ invalidVariableMeasurePriceOrWeight: "Invalid variable measure price or weight",
2301
+ indicatorDigit: "indicator digit",
2302
+ serialComponent: "serial component",
2303
+ reference: "reference",
2304
+ referenceCantBeAllNumeric: "Reference can't be all-numeric",
2305
+ invalidCheckCharacterPair: "Invalid check character pair"
2306
+ },
2307
+ Prefix: {
2308
+ gs1CompanyPrefix: "GS1 Company Prefix",
2309
+ upcCompanyPrefix: "U.P.C. Company Prefix",
2310
+ gs18Prefix: "GS1-8 Prefix",
2311
+ invalidPrefixType: "Invalid prefix type",
2312
+ gs1CompanyPrefixCantStartWith0: `GS1 Company Prefix can't start with "0"`,
2313
+ gs1CompanyPrefixCantStartWith00000: `GS1 Company Prefix can't start with "00000"`,
2314
+ gs1CompanyPrefixCantStartWith000000: `GS1 Company Prefix can't start with "000000"`,
2315
+ upcCompanyPrefixCantStartWith0000: `U.P.C. Company Prefix can't start with "0000"`,
2316
+ gs18PrefixCantStartWith0: `GS1-8 Prefix can't start with "0"`,
2317
+ identifierTypeNotSupportedByGS18Prefix: "{{identifierType}} not supported by GS1-8 Prefix"
2318
+ }
2319
+ };
2320
+
2321
+ // src/locale/fr/locale-resources.ts
2322
+ var locale_resources_default2 = {
2323
+ Check: {
2324
+ lengthOfStringForPriceOrWeightMustBeExactly: "La longueur {{length, number}} de la cha\xEEne pour le prix ou le poids doit \xEAtre 4 ou 5",
2325
+ priceOrWeightComponent: "prix ou poids",
2326
+ lengthOfStringForCheckCharacterPairMustBeLessThanOrEqualTo: "La longueur {{length, number}} de la cha\xEEne pour la paire de caract\xE8res de v\xE9rification doit \xEAtre inf\xE9rieure ou \xE9gale \xE0 {{maximumLength, number}}"
2327
+ },
2328
+ Identifier: {
2329
+ identifierTypeLength: "{{identifierType}} doit comporter {{length, number}} chiffres",
2330
+ invalidCheckDigit: "Chiffre de contr\xF4le non valide",
2331
+ invalidGTINLength: "Le GTIN doit comporter 13, 12, 8 ou 14 chiffres",
2332
+ invalidGTIN14Length: "Le GTIN doit comporter 14 chiffres",
2333
+ invalidZeroSuppressedGTIN12: "Code GTIN-12 non valide avec z\xE9ro supprim\xE9",
2334
+ invalidZeroSuppressibleGTIN12: "Le GTIN-12 ne peut pas \xEAtre supprim\xE9 par z\xE9ro",
2335
+ invalidZeroSuppressedGTIN12AsGTIN13: "GTIN-12 non valide avec z\xE9ro supprim\xE9 en tant que GTIN-13",
2336
+ invalidZeroSuppressedGTIN12AsGTIN14: "GTIN-12 non valide avec z\xE9ro supprim\xE9 en tant que GTIN-14",
2337
+ invalidGTIN13AtRetail: "Le GTIN-13 au niveau des articles de consommation au d\xE9tail ne peut pas commencer par z\xE9ro",
2338
+ invalidGTINAtRetail: "Le GTIN n'est pas pris en charge au niveau des articles de consommation au d\xE9tail",
2339
+ invalidGTINAtOtherThanRetail: "Le GTIN n'est pas pris en charge \xE0 d'autres niveaux que ceux des articles de consommation au d\xE9tail",
2340
+ invalidRCNLength: "La longueur du RCN doit correspondre \xE0 la longueur du format",
2341
+ invalidVariableMeasureRCNFormat: "Format RCN de mesure variable non valide",
2342
+ invalidVariableMeasureRCNPrefix: "Pr\xE9fixe RCN de mesure variable non valide",
2343
+ invalidVariableMeasurePriceOrWeight: "Mesure variable invalide : prix ou poids",
2344
+ indicatorDigit: "chiffre indicateur",
2345
+ serialComponent: "composant s\xE9rie",
2346
+ reference: "r\xE9f\xE9rence",
2347
+ referenceCantBeAllNumeric: "La r\xE9f\xE9rence ne peut pas \xEAtre enti\xE8rement num\xE9rique",
2348
+ invalidCheckCharacterPair: "Paire de caract\xE8res de contr\xF4le non valide"
2349
+ },
2350
+ Prefix: {
2351
+ gs1CompanyPrefix: "Pr\xE9fixe de l'entreprise GS1",
2352
+ upcCompanyPrefix: "Pr\xE9fixe de l'entreprise U.P.C.",
2353
+ gs18Prefix: "Pr\xE9fixe GS1-8",
2354
+ invalidPrefixType: "Type de pr\xE9fixe invalide",
2355
+ gs1CompanyPrefixCantStartWith0: `Le pr\xE9fixe de l'entreprise GS1 ne peut pas commencer par "0"`,
2356
+ gs1CompanyPrefixCantStartWith00000: `Le pr\xE9fixe de l'entreprise GS1 ne peut pas commencer par "00000"`,
2357
+ gs1CompanyPrefixCantStartWith000000: `Le pr\xE9fixe de l'entreprise GS1 ne peut pas commencer par "000000"`,
2358
+ upcCompanyPrefixCantStartWith0000: `Le pr\xE9fixe de l'entreprise U.P.C. ne peut pas commencer par "0000"`,
2359
+ gs18PrefixCantStartWith0: 'Le pr\xE9fixe GS1-8 ne peut pas commencer par "0"',
2360
+ identifierTypeNotSupportedByGS18Prefix: "{{identifierType}} non pris en charge par le pr\xE9fixe GS1-8"
2361
+ }
2362
+ };
2363
+
2364
+ // src/locale/i18n.ts
2365
+ var gs1NS = "aidct_gs1";
2366
+ var gs1Resources = {
2367
+ en: {
2368
+ aidct_gs1: locale_resources_default
2369
+ },
2370
+ fr: {
2371
+ aidct_gs1: locale_resources_default2
2372
+ }
2373
+ };
2374
+ var i18nextGS1 = instance.createInstance();
2375
+ async function i18nGS1Init(environment, debug = false) {
2376
+ await (0, import_utility.i18nUtilityInit)(environment, debug);
2377
+ await (0, import_core.i18nCoreInit)(i18nextGS1, environment, debug, gs1NS, import_utility.utilityResources, gs1Resources);
2378
+ }
2379
+
2380
+ // src/character-set.ts
2381
+ var import_utility2 = require("@aidc-toolkit/utility");
2382
+ var AI82_CREATOR = new import_utility2.CharacterSetCreator([
2383
+ "!",
2384
+ '"',
2385
+ "%",
2386
+ "&",
2387
+ "'",
2388
+ "(",
2389
+ ")",
2390
+ "*",
2391
+ "+",
2392
+ ",",
2393
+ "-",
2394
+ ".",
2395
+ "/",
2396
+ "0",
2397
+ "1",
2398
+ "2",
2399
+ "3",
2400
+ "4",
2401
+ "5",
2402
+ "6",
2403
+ "7",
2404
+ "8",
2405
+ "9",
2406
+ ":",
2407
+ ";",
2408
+ "<",
2409
+ "=",
2410
+ ">",
2411
+ "?",
2412
+ "A",
2413
+ "B",
2414
+ "C",
2415
+ "D",
2416
+ "E",
2417
+ "F",
2418
+ "G",
2419
+ "H",
2420
+ "I",
2421
+ "J",
2422
+ "K",
2423
+ "L",
2424
+ "M",
2425
+ "N",
2426
+ "O",
2427
+ "P",
2428
+ "Q",
2429
+ "R",
2430
+ "S",
2431
+ "T",
2432
+ "U",
2433
+ "V",
2434
+ "W",
2435
+ "X",
2436
+ "Y",
2437
+ "Z",
2438
+ "_",
2439
+ "a",
2440
+ "b",
2441
+ "c",
2442
+ "d",
2443
+ "e",
2444
+ "f",
2445
+ "g",
2446
+ "h",
2447
+ "i",
2448
+ "j",
2449
+ "k",
2450
+ "l",
2451
+ "m",
2452
+ "n",
2453
+ "o",
2454
+ "p",
2455
+ "q",
2456
+ "r",
2457
+ "s",
2458
+ "t",
2459
+ "u",
2460
+ "v",
2461
+ "w",
2462
+ "x",
2463
+ "y",
2464
+ "z"
2465
+ ], import_utility2.Exclusions.AllNumeric);
2466
+ var AI82_VALIDATOR = AI82_CREATOR;
2467
+ var AI39_CREATOR = new import_utility2.CharacterSetCreator([
2468
+ "#",
2469
+ "-",
2470
+ "/",
2471
+ "0",
2472
+ "1",
2473
+ "2",
2474
+ "3",
2475
+ "4",
2476
+ "5",
2477
+ "6",
2478
+ "7",
2479
+ "8",
2480
+ "9",
2481
+ "A",
2482
+ "B",
2483
+ "C",
2484
+ "D",
2485
+ "E",
2486
+ "F",
2487
+ "G",
2488
+ "H",
2489
+ "I",
2490
+ "J",
2491
+ "K",
2492
+ "L",
2493
+ "M",
2494
+ "N",
2495
+ "O",
2496
+ "P",
2497
+ "Q",
2498
+ "R",
2499
+ "S",
2500
+ "T",
2501
+ "U",
2502
+ "V",
2503
+ "W",
2504
+ "X",
2505
+ "Y",
2506
+ "Z"
2507
+ ], import_utility2.Exclusions.AllNumeric);
2508
+ var AI39_VALIDATOR = AI39_CREATOR;
2509
+ var AI64_VALIDATOR = new import_utility2.CharacterSetValidator([
2510
+ "-",
2511
+ "0",
2512
+ "1",
2513
+ "2",
2514
+ "3",
2515
+ "4",
2516
+ "5",
2517
+ "6",
2518
+ "7",
2519
+ "8",
2520
+ "9",
2521
+ "=",
2522
+ "A",
2523
+ "B",
2524
+ "C",
2525
+ "D",
2526
+ "E",
2527
+ "F",
2528
+ "G",
2529
+ "H",
2530
+ "I",
2531
+ "J",
2532
+ "K",
2533
+ "L",
2534
+ "M",
2535
+ "N",
2536
+ "O",
2537
+ "P",
2538
+ "Q",
2539
+ "R",
2540
+ "S",
2541
+ "T",
2542
+ "U",
2543
+ "V",
2544
+ "W",
2545
+ "X",
2546
+ "Y",
2547
+ "Z",
2548
+ "_",
2549
+ "a",
2550
+ "b",
2551
+ "c",
2552
+ "d",
2553
+ "e",
2554
+ "f",
2555
+ "g",
2556
+ "h",
2557
+ "i",
2558
+ "j",
2559
+ "k",
2560
+ "l",
2561
+ "m",
2562
+ "n",
2563
+ "o",
2564
+ "p",
2565
+ "q",
2566
+ "r",
2567
+ "s",
2568
+ "t",
2569
+ "u",
2570
+ "v",
2571
+ "w",
2572
+ "x",
2573
+ "y",
2574
+ "z"
2575
+ ]);
2576
+
2577
+ // src/check.ts
2578
+ var import_utility3 = require("@aidc-toolkit/utility");
2579
+ var THREE_WEIGHT_RESULTS = [
2580
+ 0,
2581
+ 3,
2582
+ 6,
2583
+ 9,
2584
+ 12,
2585
+ 15,
2586
+ 18,
2587
+ 21,
2588
+ 24,
2589
+ 27
2590
+ ];
2591
+ var TWO_MINUS_WEIGHT_RESULTS = [
2592
+ 0,
2593
+ 2,
2594
+ 4,
2595
+ 6,
2596
+ 8,
2597
+ 9,
2598
+ 1,
2599
+ 3,
2600
+ 5,
2601
+ 7
2602
+ ];
2603
+ var FIVE_PLUS_WEIGHT_RESULTS = [
2604
+ 0,
2605
+ 5,
2606
+ 1,
2607
+ 6,
2608
+ 2,
2609
+ 7,
2610
+ 3,
2611
+ 8,
2612
+ 4,
2613
+ 9
2614
+ ];
2615
+ var FIVE_MINUS_WEIGHT_RESULTS = [
2616
+ 0,
2617
+ 5,
2618
+ 9,
2619
+ 4,
2620
+ 8,
2621
+ 3,
2622
+ 7,
2623
+ 2,
2624
+ 6,
2625
+ 1
2626
+ ];
2627
+ var INVERSE_FIVE_MINUS_WEIGHT_RESULTS = [
2628
+ 0,
2629
+ 9,
2630
+ 7,
2631
+ 5,
2632
+ 3,
2633
+ 1,
2634
+ 8,
2635
+ 6,
2636
+ 4,
2637
+ 2
2638
+ ];
2639
+ function checkDigitSum(exchangeWeights, s) {
2640
+ let weight3 = (s.length + Number(exchangeWeights)) % 2 === 0;
2641
+ return import_utility3.NUMERIC_CREATOR.characterIndexes(s).reduce((accumulator, characterIndex, index) => {
2642
+ if (characterIndex === void 0) {
2643
+ throw new RangeError(i18nextGS1.t("CharacterSetValidator.invalidCharacterAtPosition", {
2644
+ ns: import_utility3.utilityNS,
2645
+ c: s.charAt(index),
2646
+ position: index + 1
2647
+ }));
2648
+ }
2649
+ weight3 = !weight3;
2650
+ return accumulator + (weight3 ? THREE_WEIGHT_RESULTS[characterIndex] : characterIndex);
2651
+ }, 0);
2652
+ }
2653
+ function checkDigit(s) {
2654
+ return import_utility3.NUMERIC_CREATOR.character(9 - (checkDigitSum(false, s) + 9) % 10);
2655
+ }
2656
+ function hasValidCheckDigit(s) {
2657
+ return checkDigitSum(true, s) % 10 === 0;
2658
+ }
2659
+ function priceOrWeightSum(weightsResults, s) {
2660
+ return import_utility3.NUMERIC_CREATOR.characterIndexes(s).reduce((accumulator, characterIndex, index) => {
2661
+ if (characterIndex === void 0) {
2662
+ throw new RangeError(i18nextGS1.t("CharacterSetValidator.invalidCharacterAtPositionOfComponent", {
2663
+ ns: import_utility3.utilityNS,
2664
+ c: s.charAt(index),
2665
+ position: index + 1,
2666
+ component: i18nextGS1.t("Check.priceOrWeightComponent")
2667
+ }));
2668
+ }
2669
+ return accumulator + weightsResults[index][characterIndex];
2670
+ }, 0);
2671
+ }
2672
+ function priceOrWeightCheckDigit(s) {
2673
+ let checkDigit2;
2674
+ switch (s.length) {
2675
+ case 4:
2676
+ checkDigit2 = import_utility3.NUMERIC_CREATOR.character(priceOrWeightSum([TWO_MINUS_WEIGHT_RESULTS, TWO_MINUS_WEIGHT_RESULTS, THREE_WEIGHT_RESULTS, FIVE_MINUS_WEIGHT_RESULTS], s) * 3 % 10);
2677
+ break;
2678
+ case 5:
2679
+ checkDigit2 = import_utility3.NUMERIC_CREATOR.character(INVERSE_FIVE_MINUS_WEIGHT_RESULTS[9 - (priceOrWeightSum([FIVE_PLUS_WEIGHT_RESULTS, TWO_MINUS_WEIGHT_RESULTS, FIVE_MINUS_WEIGHT_RESULTS, FIVE_PLUS_WEIGHT_RESULTS, TWO_MINUS_WEIGHT_RESULTS], s) + 9) % 10]);
2680
+ break;
2681
+ default:
2682
+ throw new RangeError(i18nextGS1.t("Check.lengthOfStringForPriceOrWeightMustBeExactly", {
2683
+ length: s.length
2684
+ }));
2685
+ }
2686
+ return checkDigit2;
2687
+ }
2688
+ function isValidPriceOrWeightCheckDigit(s, checkDigit2) {
2689
+ return priceOrWeightCheckDigit(s) === checkDigit2;
2690
+ }
2691
+ var CHECK_CHARACTER_WEIGHTS = [
2692
+ 107,
2693
+ 103,
2694
+ 101,
2695
+ 97,
2696
+ 89,
2697
+ 83,
2698
+ 79,
2699
+ 73,
2700
+ 71,
2701
+ 67,
2702
+ 61,
2703
+ 59,
2704
+ 53,
2705
+ 47,
2706
+ 43,
2707
+ 41,
2708
+ 37,
2709
+ 31,
2710
+ 29,
2711
+ 23,
2712
+ 19,
2713
+ 17,
2714
+ 13,
2715
+ 11,
2716
+ 7,
2717
+ 5,
2718
+ 3,
2719
+ 2
2720
+ ];
2721
+ var CHECK_CHARACTERS = [
2722
+ "2",
2723
+ "3",
2724
+ "4",
2725
+ "5",
2726
+ "6",
2727
+ "7",
2728
+ "8",
2729
+ "9",
2730
+ "A",
2731
+ "B",
2732
+ "C",
2733
+ "D",
2734
+ "E",
2735
+ "F",
2736
+ "G",
2737
+ "H",
2738
+ "J",
2739
+ "K",
2740
+ "L",
2741
+ "M",
2742
+ "N",
2743
+ "P",
2744
+ "Q",
2745
+ "R",
2746
+ "S",
2747
+ "T",
2748
+ "U",
2749
+ "V",
2750
+ "W",
2751
+ "X",
2752
+ "Y",
2753
+ "Z"
2754
+ ];
2755
+ function checkCharacterPair(s) {
2756
+ const weightIndexStart = CHECK_CHARACTER_WEIGHTS.length - s.length;
2757
+ if (weightIndexStart < 0) {
2758
+ throw new RangeError(i18nextGS1.t("Check.lengthOfStringForCheckCharacterPairMustBeLessThanOrEqualTo", {
2759
+ length: s.length,
2760
+ maximumLength: CHECK_CHARACTER_WEIGHTS.length
2761
+ }));
2762
+ }
2763
+ const checkCharacterPairSum = AI82_CREATOR.characterIndexes(s).reduce((accumulator, characterIndex, index) => {
2764
+ if (characterIndex === void 0) {
2765
+ throw new RangeError(i18nextGS1.t("CharacterSetValidator.invalidCharacterAtPosition", {
2766
+ ns: import_utility3.utilityNS,
2767
+ c: s.charAt(index),
2768
+ position: index + 1
2769
+ }));
2770
+ }
2771
+ return accumulator + characterIndex * CHECK_CHARACTER_WEIGHTS[weightIndexStart + index];
2772
+ }, 0) % 1021;
2773
+ const checkCharacterPairSumMod32 = checkCharacterPairSum % 32;
2774
+ return CHECK_CHARACTERS[(checkCharacterPairSum - checkCharacterPairSumMod32) / 32] + CHECK_CHARACTERS[checkCharacterPairSumMod32];
2775
+ }
2776
+ function hasValidCheckCharacterPair(s) {
2777
+ const checkCharacterPairIndex = s.length - 2;
2778
+ return checkCharacterPair(s.substring(0, checkCharacterPairIndex)) === s.substring(checkCharacterPairIndex);
2779
+ }
2780
+
2781
+ // src/prefix-type.ts
2782
+ var PrefixTypes = {
2783
+ /**
2784
+ * GS1 Company Prefix.
2785
+ */
2786
+ GS1CompanyPrefix: "GS1 Company Prefix",
2787
+ /**
2788
+ * U.P.C. Company Prefix.
2789
+ */
2790
+ UPCCompanyPrefix: "U.P.C. Company Prefix",
2791
+ /**
2792
+ * GS1-8 Prefix.
2793
+ */
2794
+ GS18Prefix: "GS1-8 Prefix"
2795
+ };
2796
+
2797
+ // src/prefix-validator.ts
2798
+ var import_utility4 = require("@aidc-toolkit/utility");
2799
+ var GS1_COMPANY_PREFIX_MINIMUM_LENGTH = 4;
2800
+ var GS1_COMPANY_PREFIX_MAXIMUM_LENGTH = 12;
2801
+ var UPC_COMPANY_PREFIX_MINIMUM_LENGTH = 6;
2802
+ var UPC_COMPANY_PREFIX_MAXIMUM_LENGTH = 11;
2803
+ var GS1_8_PREFIX_MINIMUM_LENGTH = 2;
2804
+ var GS1_8_PREFIX_MAXIMUM_LENGTH = 7;
2805
+ var GS1_COMPANY_PREFIX_VALIDATION = {
2806
+ minimumLength: GS1_COMPANY_PREFIX_MINIMUM_LENGTH,
2807
+ maximumLength: GS1_COMPANY_PREFIX_MAXIMUM_LENGTH,
2808
+ component: () => i18nextGS1.t("Prefix.gs1CompanyPrefix")
2809
+ };
2810
+ var UPC_COMPANY_PREFIX_AS_GS1_COMPANY_PREFIX_VALIDATION = {
2811
+ minimumLength: UPC_COMPANY_PREFIX_MINIMUM_LENGTH + 1,
2812
+ maximumLength: UPC_COMPANY_PREFIX_MAXIMUM_LENGTH + 1,
2813
+ component: () => i18nextGS1.t("Prefix.gs1CompanyPrefix")
2814
+ };
2815
+ var GS1_8_PREFIX_AS_GS1_COMPANY_PREFIX_VALIDATION = {
2816
+ minimumLength: GS1_8_PREFIX_MINIMUM_LENGTH + 5,
2817
+ maximumLength: GS1_8_PREFIX_MAXIMUM_LENGTH + 5,
2818
+ component: () => i18nextGS1.t("Prefix.gs1CompanyPrefix")
2819
+ };
2820
+ var UPC_COMPANY_PREFIX_VALIDATION = {
2821
+ minimumLength: UPC_COMPANY_PREFIX_MINIMUM_LENGTH,
2822
+ maximumLength: UPC_COMPANY_PREFIX_MAXIMUM_LENGTH,
2823
+ component: () => i18nextGS1.t("Prefix.upcCompanyPrefix")
2824
+ };
2825
+ var GS1_8_PREFIX_VALIDATION = {
2826
+ minimumLength: GS1_8_PREFIX_MINIMUM_LENGTH,
2827
+ maximumLength: GS1_8_PREFIX_MAXIMUM_LENGTH,
2828
+ component: () => i18nextGS1.t("Prefix.gs18Prefix")
2829
+ };
2830
+ function validate(prefixType, allowUPCCompanyPrefix, allowGS18Prefix, prefix, isFromIdentifier = false, isNumericIdentifier = false, positionOffset) {
2831
+ let baseValidation;
2832
+ switch (prefixType) {
2833
+ case PrefixTypes.GS1CompanyPrefix:
2834
+ if (!prefix.startsWith("0")) {
2835
+ baseValidation = GS1_COMPANY_PREFIX_VALIDATION;
2836
+ } else if (!prefix.startsWith("00000")) {
2837
+ if (!allowUPCCompanyPrefix) {
2838
+ throw new RangeError(i18nextGS1.t("Prefix.gs1CompanyPrefixCantStartWith0"));
2839
+ }
2840
+ baseValidation = UPC_COMPANY_PREFIX_AS_GS1_COMPANY_PREFIX_VALIDATION;
2841
+ } else if (!prefix.startsWith("000000")) {
2842
+ if (!allowGS18Prefix) {
2843
+ throw new RangeError(i18nextGS1.t("Prefix.gs1CompanyPrefixCantStartWith00000"));
2844
+ }
2845
+ baseValidation = GS1_8_PREFIX_AS_GS1_COMPANY_PREFIX_VALIDATION;
2846
+ } else {
2847
+ throw new RangeError(i18nextGS1.t("Prefix.gs1CompanyPrefixCantStartWith000000"));
2848
+ }
2849
+ break;
2850
+ case PrefixTypes.UPCCompanyPrefix:
2851
+ if (prefix.startsWith("0000")) {
2852
+ throw new RangeError(i18nextGS1.t("Prefix.upcCompanyPrefixCantStartWith0000"));
2853
+ }
2854
+ baseValidation = UPC_COMPANY_PREFIX_VALIDATION;
2855
+ break;
2856
+ case PrefixTypes.GS18Prefix:
2857
+ if (prefix.startsWith("0")) {
2858
+ throw new RangeError(i18nextGS1.t("Prefix.gs18PrefixCantStartWith0"));
2859
+ }
2860
+ baseValidation = GS1_8_PREFIX_VALIDATION;
2861
+ break;
2862
+ }
2863
+ const mergedValidation = {
2864
+ ...baseValidation,
2865
+ positionOffset
2866
+ };
2867
+ if (!isFromIdentifier) {
2868
+ import_utility4.NUMERIC_CREATOR.validate(prefix, mergedValidation);
2869
+ } else if (!isNumericIdentifier) {
2870
+ import_utility4.NUMERIC_CREATOR.validate(prefix.substring(0, Math.min(mergedValidation.minimumLength, prefix.length - 1)), mergedValidation);
2871
+ }
2872
+ }
2873
+ var PrefixValidator = {
2874
+ GS1_COMPANY_PREFIX_MINIMUM_LENGTH,
2875
+ GS1_COMPANY_PREFIX_MAXIMUM_LENGTH,
2876
+ UPC_COMPANY_PREFIX_MINIMUM_LENGTH,
2877
+ UPC_COMPANY_PREFIX_MAXIMUM_LENGTH,
2878
+ GS1_8_PREFIX_MINIMUM_LENGTH,
2879
+ GS1_8_PREFIX_MAXIMUM_LENGTH,
2880
+ validate
2881
+ };
2882
+
2883
+ // src/identifier-type.ts
2884
+ var IdentifierTypes = {
2885
+ /**
2886
+ * Global Trade Item Number.
2887
+ */
2888
+ GTIN: "GTIN",
2889
+ /**
2890
+ * Global Location Number.
2891
+ */
2892
+ GLN: "GLN",
2893
+ /**
2894
+ * Serial Shipping Container Code.
2895
+ */
2896
+ SSCC: "SSCC",
2897
+ /**
2898
+ * Global Returnable Asset Identifier.
2899
+ */
2900
+ GRAI: "GRAI",
2901
+ /**
2902
+ * Global Individual Asset Identifier.
2903
+ */
2904
+ GIAI: "GIAI",
2905
+ /**
2906
+ * Global Service Relation Number.
2907
+ */
2908
+ GSRN: "GSRN",
2909
+ /**
2910
+ * Global Document Type Identifier.
2911
+ */
2912
+ GDTI: "GDTI",
2913
+ /**
2914
+ * Global Identification Number for Consignment.
2915
+ */
2916
+ GINC: "GINC",
2917
+ /**
2918
+ * Global Shipment Identification Number.
2919
+ */
2920
+ GSIN: "GSIN",
2921
+ /**
2922
+ * Global Coupon Number.
2923
+ */
2924
+ GCN: "GCN",
2925
+ /**
2926
+ * Component/Part Identifier.
2927
+ */
2928
+ CPID: "CPID",
2929
+ /**
2930
+ * Global Model Number.
2931
+ */
2932
+ GMN: "GMN"
2933
+ };
2934
+
2935
+ // src/identifier-validator.ts
2936
+ var import_utility5 = require("@aidc-toolkit/utility");
2937
+ var ContentCharacterSets = {
2938
+ /**
2939
+ * Numeric.
2940
+ */
2941
+ Numeric: "Numeric",
2942
+ /**
2943
+ * GS1 AI encodable character set 82.
2944
+ */
2945
+ AI82: "AI82",
2946
+ /**
2947
+ * GS1 AI encodable character set 39.
2948
+ */
2949
+ AI39: "AI39"
2950
+ };
2951
+ var AbstractIdentifierValidator = class _AbstractIdentifierValidator {
2952
+ static CHARACTER_SET_CREATORS = {
2953
+ [ContentCharacterSets.Numeric]: import_utility5.NUMERIC_CREATOR,
2954
+ [ContentCharacterSets.AI82]: AI82_CREATOR,
2955
+ [ContentCharacterSets.AI39]: AI39_CREATOR
2956
+ };
2957
+ /**
2958
+ * Identifier type.
2959
+ */
2960
+ _identifierType;
2961
+ /**
2962
+ * Prefix type.
2963
+ */
2964
+ _prefixType;
2965
+ /**
2966
+ * Length.
2967
+ */
2968
+ _length;
2969
+ /**
2970
+ * Reference character set.
2971
+ */
2972
+ _referenceCharacterSet;
2973
+ /**
2974
+ * Reference creator.
2975
+ */
2976
+ _referenceCreator;
2977
+ /**
2978
+ * Get the character set creator for a character set.
2979
+ *
2980
+ * @param characterSet
2981
+ * Character set.
2982
+ *
2983
+ * @returns
2984
+ * Character set creator.
2985
+ */
2986
+ static creatorFor(characterSet) {
2987
+ return _AbstractIdentifierValidator.CHARACTER_SET_CREATORS[characterSet];
2988
+ }
2989
+ /**
2990
+ * Constructor.
2991
+ *
2992
+ * @param identifierType
2993
+ * Identifier type.
2994
+ *
2995
+ * @param prefixType
2996
+ * Prefix type.
2997
+ *
2998
+ * @param length
2999
+ * Length.
3000
+ *
3001
+ * @param referenceCharacterSet
3002
+ * Reference character set.
3003
+ */
3004
+ constructor(identifierType, prefixType, length, referenceCharacterSet) {
3005
+ this._identifierType = identifierType;
3006
+ this._prefixType = prefixType;
3007
+ this._length = length;
3008
+ this._referenceCharacterSet = referenceCharacterSet;
3009
+ this._referenceCreator = _AbstractIdentifierValidator.creatorFor(referenceCharacterSet);
3010
+ }
3011
+ /**
3012
+ * @inheritDoc
3013
+ */
3014
+ get identifierType() {
3015
+ return this._identifierType;
3016
+ }
3017
+ /**
3018
+ * @inheritDoc
3019
+ */
3020
+ get prefixType() {
3021
+ return this._prefixType;
3022
+ }
3023
+ /**
3024
+ * @inheritDoc
3025
+ */
3026
+ get length() {
3027
+ return this._length;
3028
+ }
3029
+ /**
3030
+ * @inheritDoc
3031
+ */
3032
+ get referenceCharacterSet() {
3033
+ return this._referenceCharacterSet;
3034
+ }
3035
+ /**
3036
+ * @inheritDoc
3037
+ */
3038
+ get referenceCreator() {
3039
+ return this._referenceCreator;
3040
+ }
3041
+ /**
3042
+ * Pad an identifier on the left with zero-value character for validation purposes. This is done to align an
3043
+ * identifier with a position offset for any error message that may be thrown by the reference validator.
3044
+ *
3045
+ * @param identifier
3046
+ * Identifier.
3047
+ *
3048
+ * @param validation
3049
+ * Identifier validation parameters.
3050
+ *
3051
+ * @returns
3052
+ * Padded identifier.
3053
+ */
3054
+ padIdentifier(identifier, validation) {
3055
+ return validation?.positionOffset === void 0 ? identifier : this.referenceCreator.character(0).repeat(validation.positionOffset).concat(identifier);
3056
+ }
3057
+ /**
3058
+ * Validate the prefix within an identifier.
3059
+ *
3060
+ * @param partialIdentifier
3061
+ * Partial identifier.
3062
+ *
3063
+ * @param positionOffset
3064
+ * Position offset within a larger string.
3065
+ */
3066
+ validatePrefix(partialIdentifier, positionOffset) {
3067
+ PrefixValidator.validate(this.prefixType, true, false, partialIdentifier, true, this.referenceCharacterSet === ContentCharacterSets.Numeric, positionOffset);
3068
+ }
3069
+ };
3070
+
3071
+ // src/numeric-identifier-validator.ts
3072
+ var LeaderTypes = {
3073
+ /**
3074
+ * No leader.
3075
+ */
3076
+ None: "None",
3077
+ /**
3078
+ * Indicator digit (GTIN only).
3079
+ */
3080
+ IndicatorDigit: "Indicator digit",
3081
+ /**
3082
+ * Extension digit (SSCC only).
3083
+ */
3084
+ ExtensionDigit: "Extension digit"
3085
+ };
3086
+ var AbstractNumericIdentifierValidator = class extends AbstractIdentifierValidator {
3087
+ /**
3088
+ * Leader type.
3089
+ */
3090
+ _leaderType;
3091
+ /**
3092
+ * Prefix position, determined by the leader type.
3093
+ */
3094
+ _prefixPosition;
3095
+ /**
3096
+ * Constructor.
3097
+ *
3098
+ * @param identifierType
3099
+ * Identifier type.
3100
+ *
3101
+ * @param prefixType
3102
+ * Prefix type.
3103
+ *
3104
+ * @param length
3105
+ * Length.
3106
+ *
3107
+ * @param leaderType
3108
+ * Leader type.
3109
+ */
3110
+ constructor(identifierType, prefixType, length, leaderType) {
3111
+ super(identifierType, prefixType, length, ContentCharacterSets.Numeric);
3112
+ this._leaderType = leaderType;
3113
+ this._prefixPosition = Number(this.leaderType === LeaderTypes.ExtensionDigit);
3114
+ }
3115
+ /**
3116
+ * @inheritDoc
3117
+ */
3118
+ get leaderType() {
3119
+ return this._leaderType;
3120
+ }
3121
+ /**
3122
+ * @inheritDoc
3123
+ */
3124
+ validate(identifier, validation) {
3125
+ if (this._prefixPosition === 0) {
3126
+ super.validatePrefix(identifier, validation?.positionOffset);
3127
+ } else {
3128
+ super.validatePrefix(identifier.substring(this._prefixPosition), validation?.positionOffset === void 0 ? this._prefixPosition : validation.positionOffset + this._prefixPosition);
3129
+ }
3130
+ if (identifier.length !== this.length) {
3131
+ throw new RangeError(i18nextGS1.t("Identifier.identifierTypeLength", {
3132
+ identifierType: this.identifierType,
3133
+ length: this.length
3134
+ }));
3135
+ }
3136
+ if (!hasValidCheckDigit(this.padIdentifier(identifier, validation))) {
3137
+ throw new RangeError(i18nextGS1.t("Identifier.invalidCheckDigit"));
3138
+ }
3139
+ }
3140
+ };
3141
+
3142
+ // src/gtin-validator.ts
3143
+ var import_utility6 = require("@aidc-toolkit/utility");
3144
+ var GTINTypes = {
3145
+ /**
3146
+ * GTIN-13.
3147
+ */
3148
+ GTIN13: 13,
3149
+ /**
3150
+ * GTIN-12.
3151
+ */
3152
+ GTIN12: 12,
3153
+ /**
3154
+ * GTIN-8.
3155
+ */
3156
+ GTIN8: 8,
3157
+ /**
3158
+ * GTIN-14.
3159
+ */
3160
+ GTIN14: 14
3161
+ };
3162
+ var GTINLevels = {
3163
+ /**
3164
+ * Any level (level is ignored).
3165
+ */
3166
+ Any: 0,
3167
+ /**
3168
+ * Retail consumer trade item level, supporting GTIN-13, GTIN-12 (optionally zero-suppressed), and GTIN-8.
3169
+ */
3170
+ RetailConsumer: 1,
3171
+ /**
3172
+ * Other than retail consumer trade item level, supporting GTIN-13, GTIN-12 (not zero-suppressed), and GTIN-14.
3173
+ */
3174
+ OtherThanRetailConsumer: 2
3175
+ };
3176
+ var GTINValidator = class _GTINValidator extends AbstractNumericIdentifierValidator {
3177
+ /**
3178
+ * Validation parameters for optional indicator digit.
3179
+ */
3180
+ static OPTIONAL_INDICATOR_DIGIT_VALIDATION = {
3181
+ minimumLength: 0,
3182
+ maximumLength: 1,
3183
+ component: () => i18nextGS1.t("Identifier.indicatorDigit")
3184
+ };
3185
+ /**
3186
+ * Validation parameters for zero-suppressed GTIN-12.
3187
+ */
3188
+ static ZERO_SUPPRESSED_GTIN12_VALIDATION = {
3189
+ minimumLength: 8,
3190
+ maximumLength: 8
3191
+ };
3192
+ /**
3193
+ * Constructor.
3194
+ *
3195
+ * @param gtinType
3196
+ * GTIN type.
3197
+ */
3198
+ constructor(gtinType) {
3199
+ let prefixType;
3200
+ switch (gtinType) {
3201
+ case GTINTypes.GTIN13:
3202
+ prefixType = PrefixTypes.GS1CompanyPrefix;
3203
+ break;
3204
+ case GTINTypes.GTIN12:
3205
+ prefixType = PrefixTypes.UPCCompanyPrefix;
3206
+ break;
3207
+ case GTINTypes.GTIN8:
3208
+ prefixType = PrefixTypes.GS18Prefix;
3209
+ break;
3210
+ default:
3211
+ throw new Error("Not supported");
3212
+ }
3213
+ super(IdentifierTypes.GTIN, prefixType, gtinType, LeaderTypes.IndicatorDigit);
3214
+ }
3215
+ /**
3216
+ * @inheritDoc
3217
+ */
3218
+ get gtinType() {
3219
+ return this.length;
3220
+ }
3221
+ /**
3222
+ * @inheritDoc
3223
+ */
3224
+ validatePrefix(partialIdentifier, positionOffset) {
3225
+ PrefixValidator.validate(this.prefixType, false, false, partialIdentifier, true, true, positionOffset);
3226
+ }
3227
+ /**
3228
+ * Zero suppress a GTIN-12.
3229
+ *
3230
+ * @param gtin12
3231
+ * GTIN-12.
3232
+ *
3233
+ * @returns
3234
+ * Zero-suppressed GTIN-12.
3235
+ */
3236
+ static zeroSuppress(gtin12) {
3237
+ GTIN12_VALIDATOR.validate(gtin12);
3238
+ const d = Array.from(gtin12);
3239
+ let zeroSuppressedGTIN12;
3240
+ if (d[0] === "0" && d[6] === "0" && d[7] === "0") {
3241
+ if (d[10] >= "5" && d[8] === "0" && d[9] === "0" && d[5] !== "0") {
3242
+ zeroSuppressedGTIN12 = `0${d[1]}${d[2]}${d[3]}${d[4]}${d[5]}${d[10]}${d[11]}`;
3243
+ } else if (d[5] === "0" && d[8] === "0" && d[9] === "0" && d[4] !== "0") {
3244
+ zeroSuppressedGTIN12 = `0${d[1]}${d[2]}${d[3]}${d[4]}${d[10]}4${d[11]}`;
3245
+ } else if (d[3] <= "2" && d[4] === "0" && d[5] === "0") {
3246
+ zeroSuppressedGTIN12 = `0${d[1]}${d[2]}${d[8]}${d[9]}${d[10]}${d[3]}${d[11]}`;
3247
+ } else if (d[3] >= "3" && d[4] === "0" && d[5] === "0" && d[8] === "0") {
3248
+ zeroSuppressedGTIN12 = `0${d[1]}${d[2]}${d[3]}${d[9]}${d[10]}3${d[11]}`;
3249
+ }
3250
+ }
3251
+ if (zeroSuppressedGTIN12 === void 0) {
3252
+ throw new RangeError(i18nextGS1.t("Identifier.invalidZeroSuppressibleGTIN12"));
3253
+ }
3254
+ return zeroSuppressedGTIN12;
3255
+ }
3256
+ /**
3257
+ * Zero expand a zero-suppressed GTIN-12.
3258
+ *
3259
+ * @param zeroSuppressedGTIN12
3260
+ * Zero-suppressed GTIN-12.
3261
+ *
3262
+ * @returns
3263
+ * GTIN-12.
3264
+ */
3265
+ static zeroExpand(zeroSuppressedGTIN12) {
3266
+ import_utility6.NUMERIC_CREATOR.validate(zeroSuppressedGTIN12, _GTINValidator.ZERO_SUPPRESSED_GTIN12_VALIDATION);
3267
+ const d = Array.from(zeroSuppressedGTIN12);
3268
+ let gtin12;
3269
+ if (d[0] === "0") {
3270
+ if (d[6] >= "5" && d[5] !== "0") {
3271
+ gtin12 = `0${d[1]}${d[2]}${d[3]}${d[4]}${d[5]}0000${d[6]}${d[7]}`;
3272
+ } else if (d[6] === "4" && d[4] !== "0") {
3273
+ gtin12 = `0${d[1]}${d[2]}${d[3]}${d[4]}00000${d[5]}${d[7]}`;
3274
+ } else if (d[6] <= "2") {
3275
+ gtin12 = `0${d[1]}${d[2]}${d[6]}0000${d[3]}${d[4]}${d[5]}${d[7]}`;
3276
+ } else if (d[6] === "3" && d[3] >= "3") {
3277
+ gtin12 = `0${d[1]}${d[2]}${d[3]}00000${d[4]}${d[5]}${d[7]}`;
3278
+ }
3279
+ }
3280
+ if (gtin12 === void 0) {
3281
+ throw new RangeError(i18nextGS1.t("Identifier.invalidZeroSuppressedGTIN12"));
3282
+ }
3283
+ GTIN12_VALIDATOR.validate(gtin12);
3284
+ return gtin12;
3285
+ }
3286
+ /**
3287
+ * Convert a GTIN of any length to a GTIN-14 with an optional indicator digit.
3288
+ *
3289
+ * @param indicatorDigit
3290
+ * Indicator digit. If blank, assumes "0" if the GTIN is not already a GTIN-14.
3291
+ *
3292
+ * @param gtin
3293
+ * GTIN.
3294
+ *
3295
+ * @returns
3296
+ * GTIN-14.
3297
+ */
3298
+ static convertToGTIN14(indicatorDigit, gtin) {
3299
+ _GTINValidator.validateAny(gtin);
3300
+ import_utility6.NUMERIC_CREATOR.validate(indicatorDigit, _GTINValidator.OPTIONAL_INDICATOR_DIGIT_VALIDATION);
3301
+ let gtin14 = gtin.padStart(GTINTypes.GTIN14, "0");
3302
+ if (indicatorDigit.length !== 0 && indicatorDigit !== gtin14.charAt(0)) {
3303
+ const partialGTIN14 = indicatorDigit + gtin14.substring(1, GTINTypes.GTIN14 - 1);
3304
+ gtin14 = partialGTIN14 + checkDigit(partialGTIN14);
3305
+ }
3306
+ return gtin14;
3307
+ }
3308
+ /**
3309
+ * Normalize a GTIN of any length.
3310
+ * - A GTIN-14 that starts with six zeros or a GTIN-13 that starts with five zeros is normalized to GTIN-8.
3311
+ * - A GTIN-14 that starts with two zeros or a GTIN-13 that starts with one zero is normalized to GTIN-12.
3312
+ * - A GTIN-14 that starts with one zero is normalized to GTIN-13.
3313
+ * - Otherwise, the GTIN is unchanged.
3314
+ *
3315
+ * @param gtin
3316
+ * GTIN.
3317
+ *
3318
+ * @returns
3319
+ * Normalized GTIN.
3320
+ */
3321
+ static normalize(gtin) {
3322
+ const gtinLength = gtin.length;
3323
+ let normalizedGTIN;
3324
+ switch (gtinLength) {
3325
+ case GTINTypes.GTIN13:
3326
+ if (!gtin.startsWith("0")) {
3327
+ normalizedGTIN = gtin;
3328
+ } else if (!gtin.startsWith("00000")) {
3329
+ normalizedGTIN = gtin.substring(1);
3330
+ } else if (!gtin.startsWith("000000")) {
3331
+ normalizedGTIN = gtin.substring(5);
3332
+ } else {
3333
+ throw new RangeError(i18nextGS1.t("Identifier.invalidZeroSuppressedGTIN12AsGTIN13"));
3334
+ }
3335
+ break;
3336
+ case GTINTypes.GTIN12:
3337
+ normalizedGTIN = gtin;
3338
+ break;
3339
+ case GTINTypes.GTIN8:
3340
+ if (!gtin.startsWith("0")) {
3341
+ normalizedGTIN = gtin;
3342
+ } else {
3343
+ normalizedGTIN = _GTINValidator.zeroExpand(gtin);
3344
+ }
3345
+ break;
3346
+ case GTINTypes.GTIN14:
3347
+ if (!gtin.startsWith("0")) {
3348
+ normalizedGTIN = gtin;
3349
+ } else if (!gtin.startsWith("00")) {
3350
+ normalizedGTIN = gtin.substring(1);
3351
+ } else if (!gtin.startsWith("000000")) {
3352
+ normalizedGTIN = gtin.substring(2);
3353
+ } else if (!gtin.startsWith("0000000")) {
3354
+ normalizedGTIN = gtin.substring(6);
3355
+ } else {
3356
+ throw new RangeError(i18nextGS1.t("Identifier.invalidZeroSuppressedGTIN12AsGTIN14"));
3357
+ }
3358
+ break;
3359
+ default:
3360
+ throw new RangeError(i18nextGS1.t("Identifier.invalidGTINLength"));
3361
+ }
3362
+ _GTINValidator.validateAny(normalizedGTIN);
3363
+ return normalizedGTIN;
3364
+ }
3365
+ /**
3366
+ * Validate any GTIN, optionally against a level.
3367
+ *
3368
+ * @param gtin
3369
+ * GTIN.
3370
+ *
3371
+ * @param gtinLevel
3372
+ * Level at which GTIN is to be validated.
3373
+ */
3374
+ static validateAny(gtin, gtinLevel = GTINLevels.Any) {
3375
+ let lengthValidatedGTIN = gtin;
3376
+ let gtinLevelRestriction;
3377
+ switch (gtin.length) {
3378
+ case GTINTypes.GTIN13:
3379
+ if (gtin.startsWith("0")) {
3380
+ throw new RangeError(i18nextGS1.t("Identifier.invalidGTIN13AtRetail"));
3381
+ }
3382
+ PrefixValidator.validate(PrefixTypes.GS1CompanyPrefix, false, false, gtin, true, true);
3383
+ gtinLevelRestriction = GTINLevels.Any;
3384
+ break;
3385
+ case GTINTypes.GTIN12:
3386
+ PrefixValidator.validate(PrefixTypes.UPCCompanyPrefix, false, false, gtin, true, true);
3387
+ gtinLevelRestriction = GTINLevels.Any;
3388
+ break;
3389
+ case GTINTypes.GTIN8:
3390
+ if (!gtin.startsWith("0")) {
3391
+ PrefixValidator.validate(PrefixTypes.GS18Prefix, false, false, gtin, true, true);
3392
+ } else {
3393
+ lengthValidatedGTIN = _GTINValidator.zeroExpand(gtin);
3394
+ }
3395
+ gtinLevelRestriction = GTINLevels.RetailConsumer;
3396
+ break;
3397
+ case GTINTypes.GTIN14:
3398
+ PrefixValidator.validate(PrefixTypes.GS1CompanyPrefix, true, true, gtin.substring(1), true, true);
3399
+ gtinLevelRestriction = GTINLevels.OtherThanRetailConsumer;
3400
+ break;
3401
+ default:
3402
+ throw new RangeError(i18nextGS1.t("Identifier.invalidGTINLength"));
3403
+ }
3404
+ if (!hasValidCheckDigit(lengthValidatedGTIN)) {
3405
+ throw new RangeError(i18nextGS1.t("Identifier.invalidCheckDigit"));
3406
+ }
3407
+ if (gtinLevel !== GTINLevels.Any && gtinLevelRestriction !== GTINLevels.Any && gtinLevelRestriction !== gtinLevel) {
3408
+ throw new RangeError(i18nextGS1.t(gtinLevel === GTINLevels.RetailConsumer ? "Identifier.invalidGTINAtRetail" : "Identifier.invalidGTINAtOtherThanRetail"));
3409
+ }
3410
+ }
3411
+ /**
3412
+ * Validate a GTIN-14.
3413
+ *
3414
+ * @param gtin14
3415
+ * GTIN-14.
3416
+ */
3417
+ static validateGTIN14(gtin14) {
3418
+ if (gtin14.length !== GTINTypes.GTIN14) {
3419
+ throw new RangeError(i18nextGS1.t("Identifier.invalidGTIN14Length"));
3420
+ }
3421
+ _GTINValidator.validateAny(gtin14);
3422
+ }
3423
+ /**
3424
+ * Parse a Restricted Circulation Number (RCN) using a variable measure trade item format. The format is a 12- or
3425
+ * 13-character string (for RCN-12 or RCN-13 respectively), containing the following:
3426
+ *
3427
+ * - '2' - The first character of the RCN.
3428
+ * - '0'-'9' - The second character of the RCN (RCN-13 only).
3429
+ * - 'I' - One or more, in sequence, for the item reference.
3430
+ * - 'P' - One or more, in sequence, for the price or weight.
3431
+ * - 'V' - Zero or one, for the price or weight check digit.
3432
+ * - 'C' - The check digit of the entire RCN.
3433
+ *
3434
+ * The 'I', 'P', and 'V' formats may be in any order.
3435
+ *
3436
+ * Some examples:
3437
+ *
3438
+ * - 2IIIIIVPPPPC - RCN-12 with a five-digit item reference, a price or weight check digit, and a four-digit price
3439
+ * or weight.
3440
+ * - 23IIIIVPPPPPC - RCN-13 with a four-digit item reference, a price or weight check digit, and a five-digit price
3441
+ * or weight.
3442
+ * - 2IIIIIIPPPPC - RCN-12 with a six-digit item reference and a four-digit price or eight.
3443
+ * - 29IIIIIPPPPPC - RCN-13 with a five-digit item reference and a five-digit price or weight.
3444
+ *
3445
+ * @param format
3446
+ * Format.
3447
+ *
3448
+ * @param rcn
3449
+ * RCN.
3450
+ *
3451
+ * @returns
3452
+ * RCN reference.
3453
+ */
3454
+ static parseVariableMeasureRCN(format, rcn) {
3455
+ const formatLength = format.length;
3456
+ if (rcn.length !== formatLength) {
3457
+ throw new RangeError(i18nextGS1.t("Identifier.invalidRCNLength"));
3458
+ }
3459
+ let validFormat = formatLength === 12 || formatLength === 13;
3460
+ let validRCNPrefix = true;
3461
+ let buildingItemReference = false;
3462
+ let itemReference = "";
3463
+ let buildingPriceOrWeight = false;
3464
+ let priceOrWeight = "";
3465
+ let priceOrWeightCheckDigit2 = "";
3466
+ for (let index = 0; validFormat && index < formatLength; index++) {
3467
+ const formatChar = format.charAt(index);
3468
+ const rcnChar = rcn.charAt(index);
3469
+ if (index === 0) {
3470
+ validFormat = formatChar === "2";
3471
+ validRCNPrefix = rcnChar === "2";
3472
+ } else if (formatLength === 13 && index === 1) {
3473
+ validFormat = import_utility6.NUMERIC_CREATOR.characterIndex(formatChar) !== void 0;
3474
+ validRCNPrefix = rcnChar === formatChar;
3475
+ } else if (index === formatLength - 1) {
3476
+ validFormat = formatChar === "C";
3477
+ } else {
3478
+ switch (formatChar) {
3479
+ case "I":
3480
+ if (!buildingItemReference) {
3481
+ validFormat = itemReference === "";
3482
+ buildingItemReference = true;
3483
+ buildingPriceOrWeight = false;
3484
+ }
3485
+ itemReference += rcnChar;
3486
+ break;
3487
+ case "P":
3488
+ if (!buildingPriceOrWeight) {
3489
+ validFormat = priceOrWeight === "";
3490
+ buildingPriceOrWeight = true;
3491
+ buildingItemReference = false;
3492
+ }
3493
+ priceOrWeight += rcnChar;
3494
+ break;
3495
+ case "V":
3496
+ validFormat = priceOrWeightCheckDigit2 === "";
3497
+ buildingItemReference = false;
3498
+ buildingPriceOrWeight = false;
3499
+ priceOrWeightCheckDigit2 = rcnChar;
3500
+ break;
3501
+ default:
3502
+ validFormat = false;
3503
+ break;
3504
+ }
3505
+ }
3506
+ }
3507
+ validFormat &&= itemReference !== "" && priceOrWeight !== "";
3508
+ if (!validFormat) {
3509
+ throw new RangeError(i18nextGS1.t("Identifier.invalidVariableMeasureRCNFormat"));
3510
+ }
3511
+ if (!validRCNPrefix) {
3512
+ throw new RangeError(i18nextGS1.t("Identifier.invalidVariableMeasureRCNPrefix"));
3513
+ }
3514
+ if (priceOrWeightCheckDigit2 !== "" && !isValidPriceOrWeightCheckDigit(priceOrWeight, priceOrWeightCheckDigit2)) {
3515
+ throw new RangeError(i18nextGS1.t("Identifier.invalidVariableMeasurePriceOrWeight"));
3516
+ }
3517
+ if (!hasValidCheckDigit(rcn)) {
3518
+ throw new RangeError(i18nextGS1.t("Identifier.invalidCheckDigit"));
3519
+ }
3520
+ return {
3521
+ itemReference: Number(itemReference),
3522
+ priceOrWeight: Number(priceOrWeight)
3523
+ };
3524
+ }
3525
+ };
3526
+ var GTIN13_VALIDATOR = new GTINValidator(GTINTypes.GTIN13);
3527
+ var GTIN12_VALIDATOR = new GTINValidator(GTINTypes.GTIN12);
3528
+ var GTIN8_VALIDATOR = new GTINValidator(GTINTypes.GTIN8);
3529
+ var GTIN_VALIDATORS = {
3530
+ [PrefixTypes.GS1CompanyPrefix]: GTIN13_VALIDATOR,
3531
+ [PrefixTypes.UPCCompanyPrefix]: GTIN12_VALIDATOR,
3532
+ [PrefixTypes.GS18Prefix]: GTIN8_VALIDATOR
3533
+ };
3534
+
3535
+ // src/non-gtin-numeric-identifier-validator.ts
3536
+ var NonGTINNumericIdentifierValidator = class extends AbstractNumericIdentifierValidator {
3537
+ /**
3538
+ * Constructor.
3539
+ *
3540
+ * @param identifierType
3541
+ * Identifier type.
3542
+ *
3543
+ * @param length
3544
+ * Length.
3545
+ *
3546
+ * @param leaderType
3547
+ * Leader type.
3548
+ */
3549
+ constructor(identifierType, length, leaderType = LeaderTypes.None) {
3550
+ super(identifierType, PrefixTypes.GS1CompanyPrefix, length, leaderType);
3551
+ }
3552
+ };
3553
+ var GLN_VALIDATOR = new NonGTINNumericIdentifierValidator(IdentifierTypes.GLN, 13);
3554
+ var SSCC_VALIDATOR = new NonGTINNumericIdentifierValidator(IdentifierTypes.SSCC, 18, LeaderTypes.ExtensionDigit);
3555
+ var GSRN_VALIDATOR = new NonGTINNumericIdentifierValidator(IdentifierTypes.GSRN, 18);
3556
+ var GSIN_VALIDATOR = new NonGTINNumericIdentifierValidator(IdentifierTypes.GSIN, 17);
3557
+
3558
+ // src/serializable-numeric-identifier-validator.ts
3559
+ var SerializableNumericIdentifierValidator = class _SerializableNumericIdentifierValidator extends NonGTINNumericIdentifierValidator {
3560
+ /**
3561
+ * Serial component length.
3562
+ */
3563
+ _serialComponentLength;
3564
+ /**
3565
+ * Serial component character set.
3566
+ */
3567
+ _serialComponentCharacterSet;
3568
+ /**
3569
+ * Serial component validation parameters.
3570
+ */
3571
+ _serialComponentValidation;
3572
+ /**
3573
+ * Serial component creator.
3574
+ */
3575
+ _serialComponentCreator;
3576
+ /**
3577
+ * Constructor.
3578
+ *
3579
+ * @param identifierType
3580
+ * Identifier type.
3581
+ *
3582
+ * @param length
3583
+ * Length.
3584
+ *
3585
+ * @param serialComponentLength
3586
+ * Serial component length.
3587
+ *
3588
+ * @param serialComponentCharacterSet
3589
+ * Serial component character set.
3590
+ */
3591
+ constructor(identifierType, length, serialComponentLength, serialComponentCharacterSet) {
3592
+ super(identifierType, length, LeaderTypes.None);
3593
+ this._serialComponentLength = serialComponentLength;
3594
+ this._serialComponentCharacterSet = serialComponentCharacterSet;
3595
+ this._serialComponentValidation = {
3596
+ minimumLength: 1,
3597
+ maximumLength: serialComponentLength,
3598
+ component: () => i18nextGS1.t("Identifier.serialComponent")
3599
+ };
3600
+ this._serialComponentCreator = _SerializableNumericIdentifierValidator.creatorFor(serialComponentCharacterSet);
3601
+ }
3602
+ /**
3603
+ * Get the serial component length.
3604
+ */
3605
+ get serialComponentLength() {
3606
+ return this._serialComponentLength;
3607
+ }
3608
+ /**
3609
+ * Get the serial component character set.
3610
+ */
3611
+ get serialComponentCharacterSet() {
3612
+ return this._serialComponentCharacterSet;
3613
+ }
3614
+ /**
3615
+ * Get the serial component validation parameters.
3616
+ */
3617
+ get serialComponentValidation() {
3618
+ return this._serialComponentValidation;
3619
+ }
3620
+ /**
3621
+ * Get the serial component creator.
3622
+ */
3623
+ get serialComponentCreator() {
3624
+ return this._serialComponentCreator;
3625
+ }
3626
+ /**
3627
+ * @inheritDoc
3628
+ */
3629
+ validate(identifier, validation) {
3630
+ super.validate(identifier.substring(0, this.length), validation);
3631
+ if (identifier.length > this.length) {
3632
+ this.serialComponentCreator.validate(identifier.substring(this.length), this._serialComponentValidation);
3633
+ }
3634
+ }
3635
+ };
3636
+ var GRAI_VALIDATOR = new SerializableNumericIdentifierValidator(IdentifierTypes.GRAI, 13, 16, ContentCharacterSets.AI82);
3637
+ var GDTI_VALIDATOR = new SerializableNumericIdentifierValidator(IdentifierTypes.GDTI, 13, 17, ContentCharacterSets.AI82);
3638
+ var GCN_VALIDATOR = new SerializableNumericIdentifierValidator(IdentifierTypes.GCN, 13, 12, ContentCharacterSets.Numeric);
3639
+
3640
+ // src/non-numeric-identifier-validator.ts
3641
+ var import_utility7 = require("@aidc-toolkit/utility");
3642
+ var NonNumericIdentifierValidator = class _NonNumericIdentifierValidator extends AbstractIdentifierValidator {
3643
+ /**
3644
+ * Validator to ensure that an identifier (minus check character pair) is not all numeric.
3645
+ */
3646
+ static NOT_ALL_NUMERIC_VALIDATOR = new class extends import_utility7.RegExpValidator {
3647
+ /**
3648
+ * @inheritDoc
3649
+ */
3650
+ createErrorMessage(_s) {
3651
+ return i18nextGS1.t("Identifier.referenceCantBeAllNumeric");
3652
+ }
3653
+ }(/\D/);
3654
+ /**
3655
+ * True if the identifier requires a check character pair.
3656
+ */
3657
+ _requiresCheckCharacterPair;
3658
+ /**
3659
+ * Constructor.
3660
+ *
3661
+ * @param identifierType
3662
+ * Identifier type.
3663
+ *
3664
+ * @param length
3665
+ * Length.
3666
+ *
3667
+ * @param referenceCharacterSet
3668
+ * Reference character set.
3669
+ *
3670
+ * @param requiresCheckCharacterPair
3671
+ * True if the identifier requires a check character pair.
3672
+ */
3673
+ constructor(identifierType, length, referenceCharacterSet, requiresCheckCharacterPair = false) {
3674
+ super(identifierType, PrefixTypes.GS1CompanyPrefix, length, referenceCharacterSet);
3675
+ this._requiresCheckCharacterPair = requiresCheckCharacterPair;
3676
+ }
3677
+ /**
3678
+ * Determine if the identifier requires a check character pair.
3679
+ */
3680
+ get requiresCheckCharacterPair() {
3681
+ return this._requiresCheckCharacterPair;
3682
+ }
3683
+ /**
3684
+ * Validate a non-numeric identifier and throw an error if validation fails.
3685
+ *
3686
+ * @param identifier
3687
+ * Identifier.
3688
+ *
3689
+ * @param validation
3690
+ * Validation parameters.
3691
+ */
3692
+ validate(identifier, validation) {
3693
+ const partialIdentifier = this.requiresCheckCharacterPair ? identifier.substring(0, identifier.length - 2) : identifier;
3694
+ super.validatePrefix(partialIdentifier, validation?.positionOffset);
3695
+ if (!this.requiresCheckCharacterPair) {
3696
+ this.referenceCreator.validate(identifier, {
3697
+ maximumLength: this.length,
3698
+ positionOffset: validation?.positionOffset
3699
+ });
3700
+ } else if (!hasValidCheckCharacterPair(this.padIdentifier(identifier, validation))) {
3701
+ throw new RangeError(i18nextGS1.t("Identifier.invalidCheckCharacterPair"));
3702
+ }
3703
+ if (validation?.exclusion === import_utility7.Exclusions.AllNumeric) {
3704
+ _NonNumericIdentifierValidator.NOT_ALL_NUMERIC_VALIDATOR.validate(partialIdentifier);
3705
+ }
3706
+ }
3707
+ };
3708
+ var GIAI_VALIDATOR = new NonNumericIdentifierValidator(IdentifierTypes.GIAI, 30, ContentCharacterSets.AI82);
3709
+ var GINC_VALIDATOR = new NonNumericIdentifierValidator(IdentifierTypes.GINC, 30, ContentCharacterSets.AI82);
3710
+ var CPID_VALIDATOR = new NonNumericIdentifierValidator(IdentifierTypes.CPID, 30, ContentCharacterSets.AI39);
3711
+ var GMN_VALIDATOR = new NonNumericIdentifierValidator(IdentifierTypes.GMN, 25, ContentCharacterSets.AI82, true);
3712
+
3713
+ // src/identifier-creator.ts
3714
+ var AbstractIdentifierCreator = class {
3715
+ /**
3716
+ * Prefix provider.
3717
+ */
3718
+ _prefixProvider;
3719
+ /**
3720
+ * Reference length.
3721
+ */
3722
+ _referenceLength;
3723
+ /**
3724
+ * Initialize the prefix manager. This method is in lieu of a constructor due to the mixin architecture.
3725
+ *
3726
+ * @param prefixProvider
3727
+ * Prefix provider.
3728
+ *
3729
+ * @param prefix
3730
+ * Prefix within prefix manager to use to calculate reference length.
3731
+ *
3732
+ * @param checkAllowance
3733
+ * Number of characters to allow for check digit or check character pair.
3734
+ */
3735
+ init(prefixProvider, prefix, checkAllowance) {
3736
+ this._prefixProvider = prefixProvider;
3737
+ this._referenceLength = this.length - prefix.length - checkAllowance;
3738
+ }
3739
+ /**
3740
+ * @inheritDoc
3741
+ */
3742
+ get prefixProvider() {
3743
+ return this._prefixProvider;
3744
+ }
3745
+ /**
3746
+ * @inheritDoc
3747
+ */
3748
+ get prefix() {
3749
+ return this.prefixProvider.gs1CompanyPrefix;
3750
+ }
3751
+ /**
3752
+ * @inheritDoc
3753
+ */
3754
+ get referenceLength() {
3755
+ return this._referenceLength;
3756
+ }
3757
+ };
3758
+
3759
+ // src/numeric-identifier-creator.ts
3760
+ var import_utility8 = require("@aidc-toolkit/utility");
3761
+ var AbstractNumericIdentifierCreator = class _AbstractNumericIdentifierCreator extends AbstractIdentifierCreator {
3762
+ /**
3763
+ * Capacity.
3764
+ */
3765
+ _capacity;
3766
+ /**
3767
+ * Tweak for sparse creation.
3768
+ */
3769
+ _tweak = 0n;
3770
+ /**
3771
+ * Initialize the prefix provider. This method is in lieu of a constructor due to the mixin architecture.
3772
+ *
3773
+ * @param prefixProvider
3774
+ * Prefix provider.
3775
+ *
3776
+ * @param prefix
3777
+ * Prefix within prefix manager to use to calculate reference length.
3778
+ */
3779
+ init(prefixProvider, prefix) {
3780
+ super.init(prefixProvider, prefix, 1);
3781
+ this._capacity = Number(import_utility8.CharacterSetCreator.powerOf10(this.referenceLength));
3782
+ }
3783
+ /**
3784
+ * @inheritDoc
3785
+ */
3786
+ get capacity() {
3787
+ return this._capacity;
3788
+ }
3789
+ /**
3790
+ * Get the tweak for sparse creation.
3791
+ */
3792
+ get tweak() {
3793
+ return this._tweak;
3794
+ }
3795
+ /**
3796
+ * Set the tweak for sparse creation.
3797
+ */
3798
+ set tweak(value) {
3799
+ this._tweak = value;
3800
+ }
3801
+ /**
3802
+ * Build an identifier from a reference by merging it with the prefix and adding the check digit.
3803
+ *
3804
+ * @param reference
3805
+ * Identifier reference.
3806
+ *
3807
+ * @returns
3808
+ * Identifier.
3809
+ */
3810
+ buildIdentifier(reference) {
3811
+ const partialIdentifier = this.leaderType === LeaderTypes.ExtensionDigit ? reference.substring(0, 1) + this.prefix + reference.substring(1) : this.prefix + reference;
3812
+ return partialIdentifier + checkDigit(partialIdentifier);
3813
+ }
3814
+ /**
3815
+ * @inheritDoc
3816
+ */
3817
+ create(valueOrValues, sparse = false) {
3818
+ return import_utility8.NUMERIC_CREATOR.create(this.referenceLength, valueOrValues, import_utility8.Exclusions.None, sparse ? this.tweak : void 0, (reference) => this.buildIdentifier(reference));
3819
+ }
3820
+ /**
3821
+ * Create all identifiers from a partial identifier. Call is recursive until remaining reference
3822
+ * length is 0.
3823
+ *
3824
+ * @param partialIdentifier
3825
+ * Partial identifier. Initial value is `this.prefix`.
3826
+ *
3827
+ * @param remainingReferenceLength
3828
+ * Remaining reference length. Initial value is `this.referenceLength`.
3829
+ *
3830
+ * @param extensionWeight
3831
+ * If this value is not zero, the identifier has an extension digit, this call is setting it, and this value
3832
+ * is applied to the calculation of the check digit.
3833
+ *
3834
+ * @param weight
3835
+ * If the extension weight is zero, this value is applied to the calculation of the check digit.
3836
+ *
3837
+ * @param partialCheckDigitSum
3838
+ * Partial check digit sum for the partial identifier.
3839
+ *
3840
+ * @yields
3841
+ * Identifier.
3842
+ */
3843
+ static *createAllPartial(partialIdentifier, remainingReferenceLength, extensionWeight, weight, partialCheckDigitSum) {
3844
+ if (remainingReferenceLength === 0) {
3845
+ yield partialIdentifier + import_utility8.NUMERIC_CREATOR.character(9 - (partialCheckDigitSum + 9) % 10);
3846
+ } else {
3847
+ const nextRemainingReferenceLength = remainingReferenceLength - 1;
3848
+ let nextPartialCheckDigitSum = partialCheckDigitSum;
3849
+ if (extensionWeight !== 0) {
3850
+ for (const c of import_utility8.NUMERIC_CREATOR.characterSet) {
3851
+ yield* _AbstractNumericIdentifierCreator.createAllPartial(c + partialIdentifier, nextRemainingReferenceLength, 0, weight, nextPartialCheckDigitSum);
3852
+ nextPartialCheckDigitSum += extensionWeight;
3853
+ }
3854
+ } else {
3855
+ const nextWeight = 4 - weight;
3856
+ for (const c of import_utility8.NUMERIC_CREATOR.characterSet) {
3857
+ yield* _AbstractNumericIdentifierCreator.createAllPartial(partialIdentifier + c, nextRemainingReferenceLength, 0, nextWeight, nextPartialCheckDigitSum);
3858
+ nextPartialCheckDigitSum += weight;
3859
+ }
3860
+ }
3861
+ }
3862
+ }
3863
+ /**
3864
+ * @inheritDoc
3865
+ */
3866
+ createAll() {
3867
+ const hasExtensionDigit = this.leaderType === LeaderTypes.ExtensionDigit;
3868
+ const prefix = this.prefix;
3869
+ const length = this.length;
3870
+ const referenceLength = this.referenceLength;
3871
+ const startWeight = 3 - 2 * ((referenceLength + 1 - Number(hasExtensionDigit)) % 2);
3872
+ return {
3873
+ [Symbol.iterator]() {
3874
+ return _AbstractNumericIdentifierCreator.createAllPartial(prefix, referenceLength, hasExtensionDigit ? 3 - 2 * length % 2 : 0, startWeight, checkDigitSum(startWeight === 3, prefix));
3875
+ }
3876
+ };
3877
+ }
3878
+ };
3879
+
3880
+ // src/gtin-creator.ts
3881
+ var import_utility9 = require("@aidc-toolkit/utility");
3882
+ var import_ts_mixer = require("ts-mixer");
3883
+ var GTINCreator = class _GTINCreator extends (0, import_ts_mixer.Mixin)(GTINValidator, AbstractNumericIdentifierCreator) {
3884
+ /**
3885
+ * Validation parameters for required indicator digit.
3886
+ */
3887
+ static REQUIRED_INDICATOR_DIGIT_VALIDATION = {
3888
+ minimumLength: 1,
3889
+ maximumLength: 1,
3890
+ component: () => i18nextGS1.t("Identifier.indicatorDigit")
3891
+ };
3892
+ /**
3893
+ * Constructor. Typically called internally by a prefix manager but may be called by other code with another prefix
3894
+ * provider type.
3895
+ *
3896
+ * @param prefixProvider
3897
+ * Prefix provider.
3898
+ *
3899
+ * @param gtinType
3900
+ * GTIN type.
3901
+ */
3902
+ constructor(prefixProvider, gtinType) {
3903
+ super(gtinType);
3904
+ this.init(prefixProvider, prefixProvider.prefix);
3905
+ }
3906
+ /**
3907
+ * @inheritDoc
3908
+ */
3909
+ get prefix() {
3910
+ return this.prefixProvider.prefix;
3911
+ }
3912
+ /**
3913
+ * Create GTIN-14(s) with an indicator digit and reference(s) based on numeric value(s). The value(s) is/are
3914
+ * converted to reference(s) of the appropriate length using {@linkcode NUMERIC_CREATOR}.
3915
+ *
3916
+ * @template TTransformerInput
3917
+ * Transformer input type.
3918
+ *
3919
+ * @param indicatorDigit
3920
+ * Indicator digit.
3921
+ *
3922
+ * @param valueOrValues
3923
+ * Numeric value(s).
3924
+ *
3925
+ * @param sparse
3926
+ * If true, the value(s) is/are mapped to a sparse sequence resistant to discovery. Default is false.
3927
+ *
3928
+ * @returns
3929
+ * GTIN-14(s).
3930
+ */
3931
+ createGTIN14(indicatorDigit, valueOrValues, sparse = false) {
3932
+ import_utility9.NUMERIC_CREATOR.validate(indicatorDigit, _GTINCreator.REQUIRED_INDICATOR_DIGIT_VALIDATION);
3933
+ return import_utility9.NUMERIC_CREATOR.create(GTINTypes.GTIN13 - this.prefixProvider.gs1CompanyPrefix.length - 1, valueOrValues, import_utility9.Exclusions.None, sparse ? this.tweak : void 0, (reference) => {
3934
+ const partialIdentifier = indicatorDigit + this.prefixProvider.gs1CompanyPrefix + reference;
3935
+ return partialIdentifier + checkDigit(partialIdentifier);
3936
+ });
3937
+ }
3938
+ /**
3939
+ * Create a Restricted Circulation Number (RCN) using a variable measure trade item format. See {@linkcode
3940
+ * GTINValidator.parseVariableMeasureRCN} for format details.
3941
+ *
3942
+ * @param format
3943
+ * Format.
3944
+ *
3945
+ * @param itemReference
3946
+ * Item reference.
3947
+ *
3948
+ * @param priceOrWeight
3949
+ * Price or weight (whole number only).
3950
+ *
3951
+ * @returns
3952
+ * RCN-12 or RCN-13.
3953
+ */
3954
+ static createVariableMeasureRCN(format, itemReference, priceOrWeight) {
3955
+ const formatLength = format.length;
3956
+ let validFormat = formatLength === 12 || formatLength === 13;
3957
+ let rcnPrefix = "";
3958
+ let buildingItemReference = false;
3959
+ let itemReferenceString = "";
3960
+ let itemReferenceLength = 0;
3961
+ let buildingPriceOrWeight = false;
3962
+ let priceOrWeightString = "";
3963
+ let priceOrWeightLength = 0;
3964
+ let calculatePriceOrWeightCheckDigit = false;
3965
+ const rcnPrefixBuilder = (partialRCN) => partialRCN + rcnPrefix;
3966
+ const itemReferenceBuilder = (partialRCN) => partialRCN + itemReferenceString;
3967
+ const priceOrWeightBuilder = (partialRCN) => partialRCN + priceOrWeightString;
3968
+ const priceOrWeightCheckDigitBuilder = (partialRCN) => partialRCN + priceOrWeightCheckDigit(priceOrWeightString);
3969
+ const checkDigitBuilder = (partialRCN) => partialRCN + checkDigit(partialRCN);
3970
+ const rcnBuilders = [rcnPrefixBuilder];
3971
+ for (let index = 0; validFormat && index < formatLength; index++) {
3972
+ const formatChar = format.charAt(index);
3973
+ if (index === 0) {
3974
+ validFormat = formatChar === "2";
3975
+ rcnPrefix = formatChar;
3976
+ } else if (formatLength === 13 && index === 1) {
3977
+ validFormat = import_utility9.NUMERIC_CREATOR.characterIndex(formatChar) !== void 0;
3978
+ rcnPrefix += formatChar;
3979
+ } else if (index === formatLength - 1) {
3980
+ validFormat = formatChar === "C";
3981
+ } else {
3982
+ switch (formatChar) {
3983
+ case "I":
3984
+ if (!buildingItemReference) {
3985
+ validFormat = itemReferenceLength === 0;
3986
+ buildingItemReference = true;
3987
+ buildingPriceOrWeight = false;
3988
+ rcnBuilders.push(itemReferenceBuilder);
3989
+ }
3990
+ itemReferenceLength++;
3991
+ break;
3992
+ case "P":
3993
+ if (!buildingPriceOrWeight) {
3994
+ validFormat = priceOrWeightLength === 0;
3995
+ buildingPriceOrWeight = true;
3996
+ buildingItemReference = false;
3997
+ rcnBuilders.push(priceOrWeightBuilder);
3998
+ }
3999
+ priceOrWeightLength++;
4000
+ break;
4001
+ case "V":
4002
+ validFormat = !calculatePriceOrWeightCheckDigit;
4003
+ buildingItemReference = false;
4004
+ buildingPriceOrWeight = false;
4005
+ calculatePriceOrWeightCheckDigit = true;
4006
+ rcnBuilders.push(priceOrWeightCheckDigitBuilder);
4007
+ break;
4008
+ default:
4009
+ validFormat = false;
4010
+ break;
4011
+ }
4012
+ }
4013
+ }
4014
+ validFormat &&= itemReferenceLength !== 0 && priceOrWeightLength !== 0;
4015
+ if (!validFormat) {
4016
+ throw new RangeError(i18nextGS1.t("Identifier.invalidVariableMeasureRCNFormat"));
4017
+ }
4018
+ itemReferenceString = import_utility9.NUMERIC_CREATOR.create(itemReferenceLength, itemReference);
4019
+ priceOrWeightString = import_utility9.NUMERIC_CREATOR.create(priceOrWeightLength, priceOrWeight);
4020
+ rcnBuilders.push(checkDigitBuilder);
4021
+ return rcnBuilders.reduce((partialRCN, rcnBuilder) => rcnBuilder(partialRCN), "");
4022
+ }
4023
+ };
4024
+
4025
+ // src/non-gtin-numeric-identifier-creator.ts
4026
+ var import_ts_mixer2 = require("ts-mixer");
4027
+ var NonGTINNumericIdentifierCreator = class extends (0, import_ts_mixer2.Mixin)(NonGTINNumericIdentifierValidator, AbstractNumericIdentifierCreator) {
4028
+ /**
4029
+ * Constructor. Typically called internally by a prefix manager but may be called by other code with another prefix
4030
+ * provider type.
4031
+ *
4032
+ * @param prefixProvider
4033
+ * Prefix provider.
4034
+ *
4035
+ * @param identifierType
4036
+ * Identifier type.
4037
+ *
4038
+ * @param length
4039
+ * Length.
4040
+ *
4041
+ * @param leaderType
4042
+ * Leader type.
4043
+ */
4044
+ constructor(prefixProvider, identifierType, length, leaderType = LeaderTypes.None) {
4045
+ super(identifierType, length, leaderType);
4046
+ this.init(prefixProvider, prefixProvider.gs1CompanyPrefix);
4047
+ }
4048
+ };
4049
+
4050
+ // src/serializable-numeric-identifier-creator.ts
4051
+ var import_utility10 = require("@aidc-toolkit/utility");
4052
+ var import_ts_mixer3 = require("ts-mixer");
4053
+ var SerializableNumericIdentifierCreator = class extends (0, import_ts_mixer3.Mixin)(SerializableNumericIdentifierValidator, AbstractNumericIdentifierCreator) {
4054
+ /**
4055
+ * Constructor. Typically called internally by a prefix manager but may be called by other code with another prefix
4056
+ * provider type.
4057
+ *
4058
+ * @param prefixProvider
4059
+ * Prefix provider.
4060
+ *
4061
+ * @param identifierType
4062
+ * Identifier type.
4063
+ *
4064
+ * @param length
4065
+ * Length.
4066
+ *
4067
+ * @param serialComponentLength
4068
+ * Serial component length.
4069
+ *
4070
+ * @param serialComponentCharacterSet
4071
+ * Serial component character set.
4072
+ */
4073
+ constructor(prefixProvider, identifierType, length, serialComponentLength, serialComponentCharacterSet) {
4074
+ super(identifierType, length, serialComponentLength, serialComponentCharacterSet);
4075
+ this.init(prefixProvider, prefixProvider.gs1CompanyPrefix);
4076
+ }
4077
+ /**
4078
+ * Concatenate a validated base identifier with serial component(s).
4079
+ *
4080
+ * @template TTransformerInput
4081
+ * Transformer input type.
4082
+ *
4083
+ * @param baseIdentifier
4084
+ * Base identifier.
4085
+ *
4086
+ * @param serialComponentOrComponents
4087
+ * Serial component(s).
4088
+ *
4089
+ * @returns
4090
+ * Serialized identifier(s).
4091
+ */
4092
+ concatenateValidated(baseIdentifier, serialComponentOrComponents) {
4093
+ let result;
4094
+ const serialComponentCreator = this.serialComponentCreator;
4095
+ const serialComponentValidation = this.serialComponentValidation;
4096
+ function validateAndConcatenate(serialComponent) {
4097
+ serialComponentCreator.validate(serialComponent, serialComponentValidation);
4098
+ return baseIdentifier + serialComponent;
4099
+ }
4100
+ if (typeof serialComponentOrComponents !== "object") {
4101
+ result = validateAndConcatenate(serialComponentOrComponents);
4102
+ } else {
4103
+ result = (0, import_utility10.mapIterable)(serialComponentOrComponents, validateAndConcatenate);
4104
+ }
4105
+ return result;
4106
+ }
4107
+ /**
4108
+ * Create serialized identifier(s) with a reference based on a numeric value concatenated with serial component(s).
4109
+ * The value is converted to a reference of the appropriate length using a numeric creator.
4110
+ *
4111
+ * @template TTransformerInput
4112
+ * Transformer input type.
4113
+ *
4114
+ * @param value
4115
+ * Numeric value of the reference.
4116
+ *
4117
+ * @param serialComponentOrComponents
4118
+ * Serial component(s).
4119
+ *
4120
+ * @param sparse
4121
+ * If true, the value is mapped to a sparse sequence resistant to discovery. Default is false.
4122
+ *
4123
+ * @returns
4124
+ * Serialized identifiers.
4125
+ */
4126
+ createSerialized(value, serialComponentOrComponents, sparse) {
4127
+ return this.concatenateValidated(this.create(value, sparse), serialComponentOrComponents);
4128
+ }
4129
+ /**
4130
+ * Concatenate a base identifier with serial component(s).
4131
+ *
4132
+ * @template TTransformerInput
4133
+ * Transformer input type.
4134
+ *
4135
+ * @param baseIdentifier
4136
+ * Base identifier.
4137
+ *
4138
+ * @param serialComponentOrComponents
4139
+ * Serial component(s).
4140
+ *
4141
+ * @returns
4142
+ * Serialized identifier(s).
4143
+ */
4144
+ concatenate(baseIdentifier, serialComponentOrComponents) {
4145
+ this.validate(baseIdentifier);
4146
+ return this.concatenateValidated(baseIdentifier, serialComponentOrComponents);
4147
+ }
4148
+ };
4149
+
4150
+ // src/non-numeric-identifier-creator.ts
4151
+ var import_utility11 = require("@aidc-toolkit/utility");
4152
+ var import_ts_mixer4 = require("ts-mixer");
4153
+ var NonNumericIdentifierCreator = class extends (0, import_ts_mixer4.Mixin)(NonNumericIdentifierValidator, AbstractIdentifierCreator) {
4154
+ /**
4155
+ * Reference validation parameters.
4156
+ */
4157
+ _referenceValidation;
4158
+ /**
4159
+ * Constructor. Typically called internally by a prefix manager but may be called by other code with another prefix
4160
+ * provider type.
4161
+ *
4162
+ * @param prefixProvider
4163
+ * Prefix provider.
4164
+ *
4165
+ * @param identifierType
4166
+ * Identifier type.
4167
+ *
4168
+ * @param length
4169
+ * Length.
4170
+ *
4171
+ * @param referenceCharacterSet
4172
+ * Reference character set.
4173
+ *
4174
+ * @param requiresCheckCharacterPair
4175
+ * True if the identifier requires a check character pair.
4176
+ */
4177
+ constructor(prefixProvider, identifierType, length, referenceCharacterSet, requiresCheckCharacterPair = false) {
4178
+ super(identifierType, length, referenceCharacterSet, requiresCheckCharacterPair);
4179
+ this.init(prefixProvider, prefixProvider.gs1CompanyPrefix, 2 * Number(requiresCheckCharacterPair));
4180
+ this._referenceValidation = {
4181
+ minimumLength: 1,
4182
+ // Maximum reference length has to account for prefix and check character pair.
4183
+ maximumLength: this.referenceLength,
4184
+ component: () => i18nextGS1.t("Identifier.reference")
4185
+ };
4186
+ }
4187
+ /**
4188
+ * Get the reference validation parameters.
4189
+ */
4190
+ get referenceValidation() {
4191
+ return this._referenceValidation;
4192
+ }
4193
+ /**
4194
+ * Create identifier(s) with reference(s).
4195
+ *
4196
+ * @template TTransformerInput
4197
+ * Transformer input type.
4198
+ *
4199
+ * @param referenceOrReferences
4200
+ * Reference(s).
4201
+ *
4202
+ * @returns
4203
+ * Identifier(s).
4204
+ */
4205
+ create(referenceOrReferences) {
4206
+ let result;
4207
+ const referenceCreator = this.referenceCreator;
4208
+ const referenceValidation = this.referenceValidation;
4209
+ const prefix = this.prefix;
4210
+ const requiresCheckCharacterPair = this.requiresCheckCharacterPair;
4211
+ function validateAndCreate(reference) {
4212
+ referenceCreator.validate(reference, referenceValidation);
4213
+ const partialIdentifier = prefix + reference;
4214
+ return requiresCheckCharacterPair ? partialIdentifier + checkCharacterPair(partialIdentifier) : partialIdentifier;
4215
+ }
4216
+ if (typeof referenceOrReferences !== "object") {
4217
+ result = validateAndCreate(referenceOrReferences);
4218
+ } else {
4219
+ result = (0, import_utility11.mapIterable)(referenceOrReferences, validateAndCreate);
4220
+ }
4221
+ return result;
4222
+ }
4223
+ };
4224
+
4225
+ // src/prefix-manager.ts
4226
+ var PrefixManager = class _PrefixManager {
4227
+ /**
4228
+ * Cached prefix managers, keyed by GS1 Company Prefix.
4229
+ */
4230
+ static PREFIX_MANAGERS_MAP = /* @__PURE__ */ new Map();
4231
+ /**
4232
+ * Creator tweak factors. Different numeric identifier types have different tweak factors so that sparse creation
4233
+ * generates different sequences for each.
4234
+ */
4235
+ static CREATOR_TWEAK_FACTORS = {
4236
+ GTIN: 1987n,
4237
+ GLN: 4241n,
4238
+ SSCC: 8087n,
4239
+ GRAI: 3221n,
4240
+ GSRN: 2341n,
4241
+ GDTI: 7333n,
4242
+ GSIN: 5623n,
4243
+ GCN: 6869n
4244
+ };
4245
+ /**
4246
+ * Normalized prefix type.
4247
+ */
4248
+ _prefixType;
4249
+ /**
4250
+ * Normalized prefix.
4251
+ */
4252
+ _prefix;
4253
+ /**
4254
+ * Prefix as GS1 Company Prefix.
4255
+ */
4256
+ _gs1CompanyPrefix;
4257
+ /**
4258
+ * U.P.C. Company Prefix if prefix type is {@link PrefixTypes.UPCCompanyPrefix}.
4259
+ */
4260
+ _upcCompanyPrefix;
4261
+ /**
4262
+ * GS1-8 Prefix if prefix type is {@link PrefixTypes.GS18Prefix}.
4263
+ */
4264
+ _gs18Prefix;
4265
+ /**
4266
+ * Default tweak factor.
4267
+ */
4268
+ _defaultTweakFactor;
4269
+ /**
4270
+ * Tweak factor.
4271
+ */
4272
+ _tweakFactor = 0n;
4273
+ /**
4274
+ * Cached identifier creators.
4275
+ */
4276
+ _identifierCreators = {};
4277
+ /**
4278
+ * Constructor.
4279
+ *
4280
+ * @param gs1CompanyPrefix
4281
+ * GS1 Company Prefix.
4282
+ */
4283
+ constructor(gs1CompanyPrefix) {
4284
+ this._gs1CompanyPrefix = gs1CompanyPrefix;
4285
+ if (!gs1CompanyPrefix.startsWith("0")) {
4286
+ this._prefixType = PrefixTypes.GS1CompanyPrefix;
4287
+ this._prefix = this._gs1CompanyPrefix;
4288
+ } else if (!gs1CompanyPrefix.startsWith("00000")) {
4289
+ this._prefixType = PrefixTypes.UPCCompanyPrefix;
4290
+ this._upcCompanyPrefix = gs1CompanyPrefix.substring(1);
4291
+ this._prefix = this._upcCompanyPrefix;
4292
+ } else {
4293
+ this._prefixType = PrefixTypes.GS18Prefix;
4294
+ this._gs18Prefix = gs1CompanyPrefix.substring(5);
4295
+ this._prefix = this._gs18Prefix;
4296
+ }
4297
+ this._defaultTweakFactor = BigInt(`1${this.gs1CompanyPrefix}`);
4298
+ this.resetTweakFactor();
4299
+ }
4300
+ /**
4301
+ * Get the prefix type.
4302
+ */
4303
+ get prefixType() {
4304
+ return this._prefixType;
4305
+ }
4306
+ /**
4307
+ * Get the prefix.
4308
+ */
4309
+ get prefix() {
4310
+ return this._prefix;
4311
+ }
4312
+ /**
4313
+ * Get the GS1 Company Prefix.
4314
+ */
4315
+ get gs1CompanyPrefix() {
4316
+ return this._gs1CompanyPrefix;
4317
+ }
4318
+ /**
4319
+ * Get the U.P.C. Company Prefix if prefix type is {@link PrefixTypes.UPCCompanyPrefix} or undefined if not.
4320
+ */
4321
+ get upcCompanyPrefix() {
4322
+ return this._upcCompanyPrefix;
4323
+ }
4324
+ /**
4325
+ * Get the GS1-8 Prefix if prefix type is {@link PrefixTypes.GS18Prefix} or undefined if not.
4326
+ */
4327
+ get gs18Prefix() {
4328
+ return this._gs18Prefix;
4329
+ }
4330
+ /**
4331
+ * Set the tweak for an identifier creator if it's a numeric identifier creator.
4332
+ *
4333
+ * @param creator
4334
+ * Identifier creator.
4335
+ */
4336
+ setCreatorTweak(creator) {
4337
+ if (creator.identifierType in _PrefixManager.CREATOR_TWEAK_FACTORS) {
4338
+ const creatorTweakFactor = _PrefixManager.CREATOR_TWEAK_FACTORS[creator.identifierType];
4339
+ creator.tweak = this.tweakFactor * creatorTweakFactor;
4340
+ }
4341
+ }
4342
+ /**
4343
+ * Get the tweak factor.
4344
+ */
4345
+ get tweakFactor() {
4346
+ return this._tweakFactor;
4347
+ }
4348
+ /**
4349
+ * Set the tweak factor.
4350
+ *
4351
+ * @param value
4352
+ * Tweak factor.
4353
+ */
4354
+ set tweakFactor(value) {
4355
+ const tweakFactor = BigInt(value);
4356
+ if (this._tweakFactor !== tweakFactor) {
4357
+ this._tweakFactor = tweakFactor;
4358
+ for (const creator of Object.values(this._identifierCreators)) {
4359
+ this.setCreatorTweak(creator);
4360
+ }
4361
+ }
4362
+ }
4363
+ /**
4364
+ * Reset the tweak factor to its default (numeric value of the GS1 Company Prefix preceded by '1').
4365
+ */
4366
+ resetTweakFactor() {
4367
+ this.tweakFactor = this._defaultTweakFactor;
4368
+ }
4369
+ /**
4370
+ * Get a prefix manager.
4371
+ *
4372
+ * @param prefixType
4373
+ * Prefix type.
4374
+ *
4375
+ * @param prefix
4376
+ * Prefix.
4377
+ *
4378
+ * @returns
4379
+ * Prefix manager with normalized prefix type and prefix.
4380
+ */
4381
+ static get(prefixType, prefix) {
4382
+ PrefixValidator.validate(prefixType, true, true, prefix);
4383
+ let gs1CompanyPrefix;
4384
+ switch (prefixType) {
4385
+ case PrefixTypes.GS1CompanyPrefix:
4386
+ gs1CompanyPrefix = prefix;
4387
+ break;
4388
+ case PrefixTypes.UPCCompanyPrefix:
4389
+ gs1CompanyPrefix = "0" + prefix;
4390
+ break;
4391
+ case PrefixTypes.GS18Prefix:
4392
+ gs1CompanyPrefix = "00000" + prefix;
4393
+ break;
4394
+ // eslint-disable-next-line @typescript-eslint/switch-exhaustiveness-check -- Method may be called by unsafe means.
4395
+ default:
4396
+ throw new RangeError(i18nextGS1.t("Prefix.invalidPrefixType"));
4397
+ }
4398
+ let prefixManager = _PrefixManager.PREFIX_MANAGERS_MAP.get(gs1CompanyPrefix);
4399
+ if (prefixManager === void 0) {
4400
+ prefixManager = new _PrefixManager(gs1CompanyPrefix);
4401
+ _PrefixManager.PREFIX_MANAGERS_MAP.set(gs1CompanyPrefix, prefixManager);
4402
+ }
4403
+ return prefixManager;
4404
+ }
4405
+ /**
4406
+ * Get an identifier creator.
4407
+ *
4408
+ * @param identifierType
4409
+ * Identifier type.
4410
+ *
4411
+ * @param constructorCallback
4412
+ * Constructor callback.
4413
+ *
4414
+ * @returns
4415
+ * Identifier creator.
4416
+ */
4417
+ getIdentifierCreator(identifierType, constructorCallback) {
4418
+ let creator = this._identifierCreators[identifierType];
4419
+ if (creator === void 0) {
4420
+ if (this.prefixType === PrefixTypes.GS18Prefix && identifierType !== IdentifierTypes.GTIN) {
4421
+ throw new RangeError(i18nextGS1.t("Prefix.identifierTypeNotSupportedByGS18Prefix", {
4422
+ identifierType
4423
+ }));
4424
+ }
4425
+ creator = constructorCallback();
4426
+ this.setCreatorTweak(creator);
4427
+ this._identifierCreators[identifierType] = creator;
4428
+ }
4429
+ return creator;
4430
+ }
4431
+ /**
4432
+ * Get non-GTIN numeric identifier creator.
4433
+ *
4434
+ * @param validator
4435
+ * Validator on which identifier creator is based.
4436
+ *
4437
+ * @returns
4438
+ * Identifier creator.
4439
+ */
4440
+ getNonGTINNumericIdentifierCreator(validator) {
4441
+ return this.getIdentifierCreator(validator.identifierType, () => new NonGTINNumericIdentifierCreator(this, validator.identifierType, validator.length, validator.leaderType));
4442
+ }
4443
+ /**
4444
+ * Get serialized numeric identifier creator.
4445
+ *
4446
+ * @param validator
4447
+ * Validator on which identifier creator is based.
4448
+ *
4449
+ * @returns
4450
+ * Identifier creator.
4451
+ */
4452
+ getSerializableNumericIdentifierCreator(validator) {
4453
+ return this.getIdentifierCreator(validator.identifierType, () => new SerializableNumericIdentifierCreator(this, validator.identifierType, validator.length, validator.serialComponentLength, validator.serialComponentCharacterSet));
4454
+ }
4455
+ /**
4456
+ * Get non-numeric identifier creator.
4457
+ *
4458
+ * @param validator
4459
+ * Validator on which identifier creator is based.
4460
+ *
4461
+ * @returns
4462
+ * Identifier creator.
4463
+ */
4464
+ getNonNumericIdentifierCreator(validator) {
4465
+ return this.getIdentifierCreator(validator.identifierType, () => new NonNumericIdentifierCreator(this, validator.identifierType, validator.length, validator.referenceCharacterSet, validator.requiresCheckCharacterPair));
4466
+ }
4467
+ /**
4468
+ * Get GTIN creator.
4469
+ */
4470
+ get gtinCreator() {
4471
+ return this.getIdentifierCreator(IdentifierTypes.GTIN, () => {
4472
+ let gtinType;
4473
+ switch (this.prefixType) {
4474
+ case PrefixTypes.GS1CompanyPrefix:
4475
+ gtinType = GTINTypes.GTIN13;
4476
+ break;
4477
+ case PrefixTypes.UPCCompanyPrefix:
4478
+ gtinType = GTINTypes.GTIN12;
4479
+ break;
4480
+ case PrefixTypes.GS18Prefix:
4481
+ gtinType = GTINTypes.GTIN8;
4482
+ break;
4483
+ }
4484
+ return new GTINCreator(this, gtinType);
4485
+ });
4486
+ }
4487
+ /**
4488
+ * Get GLN creator.
4489
+ */
4490
+ get glnCreator() {
4491
+ return this.getNonGTINNumericIdentifierCreator(GLN_VALIDATOR);
4492
+ }
4493
+ /**
4494
+ * Get SSCC creator.
4495
+ */
4496
+ get ssccCreator() {
4497
+ return this.getNonGTINNumericIdentifierCreator(SSCC_VALIDATOR);
4498
+ }
4499
+ /**
4500
+ * Get GRAI creator.
4501
+ */
4502
+ get graiCreator() {
4503
+ return this.getSerializableNumericIdentifierCreator(GRAI_VALIDATOR);
4504
+ }
4505
+ /**
4506
+ * Get GIAI creator.
4507
+ */
4508
+ get giaiCreator() {
4509
+ return this.getNonNumericIdentifierCreator(GIAI_VALIDATOR);
4510
+ }
4511
+ /**
4512
+ * Get GSRN creator.
4513
+ */
4514
+ get gsrnCreator() {
4515
+ return this.getNonGTINNumericIdentifierCreator(GSRN_VALIDATOR);
4516
+ }
4517
+ /**
4518
+ * Get GDTI creator.
4519
+ */
4520
+ get gdtiCreator() {
4521
+ return this.getSerializableNumericIdentifierCreator(GDTI_VALIDATOR);
4522
+ }
4523
+ /**
4524
+ * Get GINC creator.
4525
+ */
4526
+ get gincCreator() {
4527
+ return this.getNonNumericIdentifierCreator(GINC_VALIDATOR);
4528
+ }
4529
+ /**
4530
+ * Get GSIN creator.
4531
+ */
4532
+ get gsinCreator() {
4533
+ return this.getNonGTINNumericIdentifierCreator(GSIN_VALIDATOR);
4534
+ }
4535
+ /**
4536
+ * Get GCN creator.
4537
+ */
4538
+ get gcnCreator() {
4539
+ return this.getSerializableNumericIdentifierCreator(GCN_VALIDATOR);
4540
+ }
4541
+ /**
4542
+ * Get CPID creator.
4543
+ */
4544
+ get cpidCreator() {
4545
+ return this.getNonNumericIdentifierCreator(CPID_VALIDATOR);
4546
+ }
4547
+ /**
4548
+ * Get GMN creator.
4549
+ */
4550
+ get gmnCreator() {
4551
+ return this.getNonNumericIdentifierCreator(GMN_VALIDATOR);
4552
+ }
4553
+ };
4554
+ // Annotate the CommonJS export names for ESM import in node:
4555
+ 0 && (module.exports = {
4556
+ AI39_CREATOR,
4557
+ AI39_VALIDATOR,
4558
+ AI64_VALIDATOR,
4559
+ AI82_CREATOR,
4560
+ AI82_VALIDATOR,
4561
+ AbstractIdentifierCreator,
4562
+ AbstractIdentifierValidator,
4563
+ AbstractNumericIdentifierCreator,
4564
+ AbstractNumericIdentifierValidator,
4565
+ CPID_VALIDATOR,
4566
+ ContentCharacterSets,
4567
+ GCN_VALIDATOR,
4568
+ GDTI_VALIDATOR,
4569
+ GIAI_VALIDATOR,
4570
+ GINC_VALIDATOR,
4571
+ GLN_VALIDATOR,
4572
+ GMN_VALIDATOR,
4573
+ GRAI_VALIDATOR,
4574
+ GSIN_VALIDATOR,
4575
+ GSRN_VALIDATOR,
4576
+ GTIN12_VALIDATOR,
4577
+ GTIN13_VALIDATOR,
4578
+ GTIN8_VALIDATOR,
4579
+ GTINCreator,
4580
+ GTINLevels,
4581
+ GTINTypes,
4582
+ GTINValidator,
4583
+ GTIN_VALIDATORS,
4584
+ IdentifierTypes,
4585
+ LeaderTypes,
4586
+ NonGTINNumericIdentifierCreator,
4587
+ NonGTINNumericIdentifierValidator,
4588
+ NonNumericIdentifierCreator,
4589
+ NonNumericIdentifierValidator,
4590
+ PrefixManager,
4591
+ PrefixTypes,
4592
+ PrefixValidator,
4593
+ SSCC_VALIDATOR,
4594
+ SerializableNumericIdentifierCreator,
4595
+ SerializableNumericIdentifierValidator,
4596
+ checkCharacterPair,
4597
+ checkDigit,
4598
+ checkDigitSum,
4599
+ gs1NS,
4600
+ gs1Resources,
4601
+ hasValidCheckCharacterPair,
4602
+ hasValidCheckDigit,
4603
+ i18nGS1Init,
4604
+ i18nextGS1,
4605
+ isValidPriceOrWeightCheckDigit,
4606
+ priceOrWeightCheckDigit
4607
+ });
4608
+ /*!
4609
+ * Copyright © 2024-2025 Dolphin Data Development Ltd. and AIDC Toolkit
4610
+ * contributors
4611
+ *
4612
+ * Licensed under the Apache License, Version 2.0 (the "License");
4613
+ * you may not use this file except in compliance with the License.
4614
+ * You may obtain a copy of the License at
4615
+ *
4616
+ * https://www.apache.org/licenses/LICENSE-2.0
4617
+ *
4618
+ * Unless required by applicable law or agreed to in writing, software
4619
+ * distributed under the License is distributed on an "AS IS" BASIS,
4620
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
4621
+ * See the License for the specific language governing permissions and
4622
+ * limitations under the License.
4623
+ */
4624
+ //# sourceMappingURL=index.cjs.map