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