@aidc-toolkit/gs1 1.0.25-beta → 1.0.26-beta

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (234) hide show
  1. package/dist/abstract-identifier-creator.d.ts +75 -0
  2. package/dist/abstract-identifier-creator.d.ts.map +1 -0
  3. package/dist/abstract-identifier-creator.js +56 -0
  4. package/dist/abstract-identifier-creator.js.map +1 -0
  5. package/dist/abstract-identifier-validator.d.ts +95 -0
  6. package/dist/abstract-identifier-validator.d.ts.map +1 -0
  7. package/dist/abstract-identifier-validator.js +123 -0
  8. package/dist/abstract-identifier-validator.js.map +1 -0
  9. package/dist/abstract-numeric-identifier-creator.d.ts +92 -0
  10. package/dist/abstract-numeric-identifier-creator.d.ts.map +1 -0
  11. package/dist/abstract-numeric-identifier-creator.js +137 -0
  12. package/dist/abstract-numeric-identifier-creator.js.map +1 -0
  13. package/dist/abstract-numeric-identifier-validator.d.ts +35 -0
  14. package/dist/abstract-numeric-identifier-validator.d.ts.map +1 -0
  15. package/dist/abstract-numeric-identifier-validator.js +61 -0
  16. package/dist/abstract-numeric-identifier-validator.js.map +1 -0
  17. package/dist/character-set.d.ts +27 -0
  18. package/dist/character-set.d.ts.map +1 -0
  19. package/dist/character-set.js +50 -0
  20. package/dist/character-set.js.map +1 -0
  21. package/dist/check.d.ts +81 -0
  22. package/dist/check.d.ts.map +1 -0
  23. package/dist/check.js +218 -0
  24. package/dist/check.js.map +1 -0
  25. package/dist/content-character-set.d.ts +26 -0
  26. package/dist/content-character-set.d.ts.map +1 -0
  27. package/dist/content-character-set.js +18 -0
  28. package/dist/content-character-set.js.map +1 -0
  29. package/dist/creators.d.ts +81 -0
  30. package/dist/creators.d.ts.map +1 -0
  31. package/dist/creators.js +62 -0
  32. package/dist/creators.js.map +1 -0
  33. package/dist/descriptors.d.ts +96 -0
  34. package/dist/descriptors.d.ts.map +1 -0
  35. package/dist/descriptors.js +266 -0
  36. package/dist/descriptors.js.map +1 -0
  37. package/dist/gtin-creator.d.ts +69 -0
  38. package/dist/gtin-creator.d.ts.map +1 -0
  39. package/dist/gtin-creator.js +159 -0
  40. package/dist/gtin-creator.js.map +1 -0
  41. package/dist/gtin-descriptor.d.ts +17 -0
  42. package/dist/gtin-descriptor.d.ts.map +1 -0
  43. package/dist/gtin-descriptor.js +2 -0
  44. package/dist/gtin-descriptor.js.map +1 -0
  45. package/dist/gtin-type.d.ts +39 -0
  46. package/dist/gtin-type.d.ts.map +1 -0
  47. package/dist/gtin-type.js +31 -0
  48. package/dist/gtin-type.js.map +1 -0
  49. package/dist/gtin-validator.d.ts +191 -0
  50. package/dist/gtin-validator.d.ts.map +1 -0
  51. package/dist/gtin-validator.js +450 -0
  52. package/dist/gtin-validator.js.map +1 -0
  53. package/dist/identifier-creator.d.ts +31 -0
  54. package/dist/identifier-creator.d.ts.map +1 -0
  55. package/dist/identifier-creator.js +2 -0
  56. package/dist/identifier-creator.js.map +1 -0
  57. package/dist/identifier-descriptor.d.ts +27 -0
  58. package/dist/identifier-descriptor.d.ts.map +1 -0
  59. package/dist/identifier-descriptor.js +2 -0
  60. package/dist/identifier-descriptor.js.map +1 -0
  61. package/dist/identifier-type.d.ts +62 -0
  62. package/dist/identifier-type.d.ts.map +1 -0
  63. package/dist/identifier-type.js +54 -0
  64. package/dist/identifier-type.js.map +1 -0
  65. package/dist/identifier-validator.d.ts +53 -0
  66. package/dist/identifier-validator.d.ts.map +1 -0
  67. package/dist/identifier-validator.js +2 -0
  68. package/dist/identifier-validator.js.map +1 -0
  69. package/dist/index.d.ts +52 -1949
  70. package/dist/index.d.ts.map +1 -0
  71. package/dist/index.js +21 -4727
  72. package/dist/index.js.map +1 -1
  73. package/dist/locale/en/locale-resources.d.ts +42 -0
  74. package/dist/locale/en/locale-resources.d.ts.map +1 -0
  75. package/dist/locale/en/locale-resources.js +41 -0
  76. package/dist/locale/en/locale-resources.js.map +1 -0
  77. package/dist/locale/fr/locale-resources.d.ts +42 -0
  78. package/dist/locale/fr/locale-resources.d.ts.map +1 -0
  79. package/dist/locale/fr/locale-resources.js +41 -0
  80. package/dist/locale/fr/locale-resources.js.map +1 -0
  81. package/dist/locale/i18n.d.ts +27 -0
  82. package/dist/locale/i18n.d.ts.map +1 -0
  83. package/dist/locale/i18n.js +36 -0
  84. package/dist/locale/i18n.js.map +1 -0
  85. package/dist/non-gtin-numeric-identifier-creator.d.ts +24 -0
  86. package/dist/non-gtin-numeric-identifier-creator.d.ts.map +1 -0
  87. package/dist/non-gtin-numeric-identifier-creator.js +23 -0
  88. package/dist/non-gtin-numeric-identifier-creator.js.map +1 -0
  89. package/dist/non-gtin-numeric-identifier-descriptor.d.ts +22 -0
  90. package/dist/non-gtin-numeric-identifier-descriptor.d.ts.map +1 -0
  91. package/dist/non-gtin-numeric-identifier-descriptor.js +2 -0
  92. package/dist/non-gtin-numeric-identifier-descriptor.js.map +1 -0
  93. package/dist/non-gtin-numeric-identifier-type.d.ts +7 -0
  94. package/dist/non-gtin-numeric-identifier-type.d.ts.map +1 -0
  95. package/dist/non-gtin-numeric-identifier-type.js +2 -0
  96. package/dist/non-gtin-numeric-identifier-type.js.map +1 -0
  97. package/dist/non-gtin-numeric-identifier-validator.d.ts +17 -0
  98. package/dist/non-gtin-numeric-identifier-validator.d.ts.map +1 -0
  99. package/dist/non-gtin-numeric-identifier-validator.js +17 -0
  100. package/dist/non-gtin-numeric-identifier-validator.js.map +1 -0
  101. package/dist/non-numeric-identifier-creator.d.ts +45 -0
  102. package/dist/non-numeric-identifier-creator.d.ts.map +1 -0
  103. package/dist/non-numeric-identifier-creator.js +84 -0
  104. package/dist/non-numeric-identifier-creator.js.map +1 -0
  105. package/dist/non-numeric-identifier-descriptor.d.ts +26 -0
  106. package/dist/non-numeric-identifier-descriptor.d.ts.map +1 -0
  107. package/dist/non-numeric-identifier-descriptor.js +2 -0
  108. package/dist/non-numeric-identifier-descriptor.js.map +1 -0
  109. package/dist/non-numeric-identifier-type.d.ts +7 -0
  110. package/dist/non-numeric-identifier-type.d.ts.map +1 -0
  111. package/dist/non-numeric-identifier-type.js +2 -0
  112. package/dist/non-numeric-identifier-type.js.map +1 -0
  113. package/dist/non-numeric-identifier-validator.d.ts +49 -0
  114. package/dist/non-numeric-identifier-validator.d.ts.map +1 -0
  115. package/dist/non-numeric-identifier-validator.js +69 -0
  116. package/dist/non-numeric-identifier-validator.js.map +1 -0
  117. package/dist/numeric-identifier-creator.d.ts +53 -0
  118. package/dist/numeric-identifier-creator.d.ts.map +1 -0
  119. package/dist/numeric-identifier-creator.js +2 -0
  120. package/dist/numeric-identifier-creator.js.map +1 -0
  121. package/dist/numeric-identifier-descriptor.d.ts +21 -0
  122. package/dist/numeric-identifier-descriptor.d.ts.map +1 -0
  123. package/dist/numeric-identifier-descriptor.js +2 -0
  124. package/dist/numeric-identifier-descriptor.js.map +1 -0
  125. package/dist/numeric-identifier-type.d.ts +31 -0
  126. package/dist/numeric-identifier-type.d.ts.map +1 -0
  127. package/dist/numeric-identifier-type.js +18 -0
  128. package/dist/numeric-identifier-type.js.map +1 -0
  129. package/dist/numeric-identifier-validator.d.ts +24 -0
  130. package/dist/numeric-identifier-validator.d.ts.map +1 -0
  131. package/dist/numeric-identifier-validator.js +2 -0
  132. package/dist/numeric-identifier-validator.js.map +1 -0
  133. package/dist/prefix-manager.d.ts +232 -0
  134. package/dist/prefix-manager.d.ts.map +1 -0
  135. package/dist/prefix-manager.js +334 -0
  136. package/dist/prefix-manager.js.map +1 -0
  137. package/dist/prefix-provider.d.ts +27 -0
  138. package/dist/prefix-provider.d.ts.map +1 -0
  139. package/dist/prefix-provider.js +2 -0
  140. package/dist/prefix-provider.js.map +1 -0
  141. package/dist/prefix-type.d.ts +26 -0
  142. package/dist/prefix-type.d.ts.map +1 -0
  143. package/dist/prefix-type.js +18 -0
  144. package/dist/prefix-type.js.map +1 -0
  145. package/dist/prefix-validator.d.ts +70 -0
  146. package/dist/prefix-validator.d.ts.map +1 -0
  147. package/dist/prefix-validator.js +208 -0
  148. package/dist/prefix-validator.js.map +1 -0
  149. package/dist/serializable-numeric-identifier-creator.d.ts +76 -0
  150. package/dist/serializable-numeric-identifier-creator.d.ts.map +1 -0
  151. package/dist/serializable-numeric-identifier-creator.js +107 -0
  152. package/dist/serializable-numeric-identifier-creator.js.map +1 -0
  153. package/dist/serializable-numeric-identifier-descriptor.d.ts +26 -0
  154. package/dist/serializable-numeric-identifier-descriptor.d.ts.map +1 -0
  155. package/dist/serializable-numeric-identifier-descriptor.js +2 -0
  156. package/dist/serializable-numeric-identifier-descriptor.js.map +1 -0
  157. package/dist/serializable-numeric-identifier-type.d.ts +6 -0
  158. package/dist/serializable-numeric-identifier-type.d.ts.map +1 -0
  159. package/dist/serializable-numeric-identifier-type.js +2 -0
  160. package/dist/serializable-numeric-identifier-type.js.map +1 -0
  161. package/dist/serializable-numeric-identifier-validator.d.ts +56 -0
  162. package/dist/serializable-numeric-identifier-validator.d.ts.map +1 -0
  163. package/dist/serializable-numeric-identifier-validator.js +77 -0
  164. package/dist/serializable-numeric-identifier-validator.js.map +1 -0
  165. package/dist/validators.d.ts +96 -0
  166. package/dist/validators.d.ts.map +1 -0
  167. package/dist/validators.js +140 -0
  168. package/dist/validators.js.map +1 -0
  169. package/package.json +11 -7
  170. package/src/abstract-identifier-creator.ts +4 -4
  171. package/src/abstract-identifier-validator.ts +6 -6
  172. package/src/abstract-numeric-identifier-creator.ts +7 -7
  173. package/src/abstract-numeric-identifier-validator.ts +6 -6
  174. package/src/check.ts +2 -2
  175. package/src/creators.ts +11 -11
  176. package/src/descriptors.ts +14 -14
  177. package/src/gtin-creator.ts +6 -6
  178. package/src/gtin-descriptor.ts +3 -3
  179. package/src/gtin-type.ts +2 -2
  180. package/src/gtin-validator.ts +8 -8
  181. package/src/identifier-creator.ts +3 -3
  182. package/src/identifier-descriptor.ts +3 -3
  183. package/src/identifier-validator.ts +1 -1
  184. package/src/index.ts +44 -43
  185. package/src/locale/i18n.ts +3 -3
  186. package/src/locale/i18next.d.ts +1 -1
  187. package/src/non-gtin-numeric-identifier-creator.ts +5 -5
  188. package/src/non-gtin-numeric-identifier-descriptor.ts +4 -4
  189. package/src/non-gtin-numeric-identifier-type.ts +2 -2
  190. package/src/non-gtin-numeric-identifier-validator.ts +5 -5
  191. package/src/non-numeric-identifier-creator.ts +6 -6
  192. package/src/non-numeric-identifier-descriptor.ts +4 -4
  193. package/src/non-numeric-identifier-type.ts +2 -2
  194. package/src/non-numeric-identifier-validator.ts +7 -7
  195. package/src/numeric-identifier-creator.ts +3 -3
  196. package/src/numeric-identifier-descriptor.ts +3 -3
  197. package/src/numeric-identifier-type.ts +1 -1
  198. package/src/numeric-identifier-validator.ts +2 -2
  199. package/src/prefix-manager.ts +16 -16
  200. package/src/prefix-provider.ts +1 -1
  201. package/src/prefix-validator.ts +3 -3
  202. package/src/serializable-numeric-identifier-creator.ts +4 -4
  203. package/src/serializable-numeric-identifier-descriptor.ts +4 -4
  204. package/src/serializable-numeric-identifier-type.ts +1 -1
  205. package/src/serializable-numeric-identifier-validator.ts +7 -7
  206. package/src/validators.ts +12 -12
  207. package/test/check.test.ts +1 -1
  208. package/test/creator.test.ts +5 -5
  209. package/test/gtin-creator.ts +2 -2
  210. package/test/gtin-validator.test.ts +2 -2
  211. package/test/identifier-creator.ts +5 -5
  212. package/test/identifier-validator.ts +1 -1
  213. package/test/non-gtin-numeric-identifier-creator.ts +3 -3
  214. package/test/non-gtin-numeric-identifier-validator.ts +2 -2
  215. package/test/non-numeric-identifier-creator.ts +1 -1
  216. package/test/non-numeric-identifier-validator.ts +3 -3
  217. package/test/numeric-identifier-creator.ts +2 -2
  218. package/test/numeric-identifier-validator.ts +2 -2
  219. package/test/prefix-manager.test.ts +2 -2
  220. package/test/serializable-numeric-identifier-creator.ts +2 -2
  221. package/test/serializable-numeric-identifier-validator.ts +3 -3
  222. package/test/setup.ts +1 -1
  223. package/test/sparse.test.ts +1 -1
  224. package/test/utility.ts +1 -1
  225. package/test/validator.test.ts +5 -5
  226. package/test/variable-measure-rcn.test.ts +1 -1
  227. package/tsconfig-config.json +4 -0
  228. package/tsconfig-src.json +8 -0
  229. package/tsconfig-test.json +9 -0
  230. package/tsconfig.json +12 -1
  231. package/tsup.config.ts +3 -2
  232. package/dist/index.cjs +0 -4813
  233. package/dist/index.cjs.map +0 -1
  234. package/dist/index.d.cts +0 -1949
package/dist/index.js CHANGED
@@ -1,4730 +1,3 @@
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 = /* @__PURE__ */ 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
- gs1CompanyPrefixCantStartWith0: `GS1 Company Prefix can't start with "0"`,
2236
- gs1CompanyPrefixCantStartWith00000: `GS1 Company Prefix can't start with "00000"`,
2237
- gs1CompanyPrefixCantStartWith000000: `GS1 Company Prefix can't start with "000000"`,
2238
- upcCompanyPrefixCantStartWith0000: `U.P.C. Company Prefix can't start with "0000"`,
2239
- gs18PrefixCantStartWith0: `GS1-8 Prefix can't start with "0"`,
2240
- identifierTypeNotSupportedByGS18Prefix: "{{identifierType}} not supported by GS1-8 Prefix"
2241
- }
2242
- };
2243
-
2244
- // src/locale/fr/locale-resources.ts
2245
- var locale_resources_default2 = {
2246
- Check: {
2247
- lengthOfStringForPriceOrWeightMustBeExactly: "La longueur {{length, number}} de la cha\xEEne pour le prix ou le poids doit \xEAtre 4 ou 5",
2248
- priceOrWeightComponent: "prix ou poids",
2249
- 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}}"
2250
- },
2251
- Identifier: {
2252
- identifierTypeLength: "{{identifierType}} doit comporter {{length, number}} chiffres",
2253
- invalidCheckDigit: "Chiffre de contr\xF4le non valide",
2254
- invalidGTINLength: "Le GTIN doit comporter 13, 12, 8 ou 14 chiffres",
2255
- invalidGTIN14Length: "Le GTIN doit comporter 14 chiffres",
2256
- invalidZeroSuppressedGTIN12: "Code GTIN-12 non valide avec z\xE9ro supprim\xE9",
2257
- invalidZeroSuppressibleGTIN12: "Le GTIN-12 ne peut pas \xEAtre supprim\xE9 par z\xE9ro",
2258
- invalidZeroSuppressedGTIN12AsGTIN13: "GTIN-12 non valide avec z\xE9ro supprim\xE9 en tant que GTIN-13",
2259
- invalidZeroSuppressedGTIN12AsGTIN14: "GTIN-12 non valide avec z\xE9ro supprim\xE9 en tant que GTIN-14",
2260
- invalidGTIN13AtRetail: "Le GTIN-13 au niveau des articles de consommation au d\xE9tail ne peut pas commencer par z\xE9ro",
2261
- invalidGTINAtRetail: "Le GTIN n'est pas pris en charge au niveau des articles de consommation au d\xE9tail",
2262
- invalidGTINAtOtherThanRetail: "Le GTIN n'est pas pris en charge \xE0 d'autres niveaux que ceux des articles de consommation au d\xE9tail",
2263
- invalidRCNLength: "La longueur du RCN doit correspondre \xE0 la longueur du format",
2264
- invalidVariableMeasureRCNFormat: "Format RCN de mesure variable non valide",
2265
- invalidVariableMeasureRCNPrefix: "Pr\xE9fixe RCN de mesure variable non valide",
2266
- invalidVariableMeasurePriceOrWeight: "Mesure variable invalide : prix ou poids",
2267
- indicatorDigit: "chiffre indicateur",
2268
- serialComponent: "composant s\xE9rie",
2269
- reference: "r\xE9f\xE9rence",
2270
- referenceCantBeAllNumeric: "La r\xE9f\xE9rence ne peut pas \xEAtre enti\xE8rement num\xE9rique",
2271
- invalidCheckCharacterPair: "Paire de caract\xE8res de contr\xF4le non valide"
2272
- },
2273
- Prefix: {
2274
- gs1CompanyPrefix: "Pr\xE9fixe de l'entreprise GS1",
2275
- upcCompanyPrefix: "Pr\xE9fixe de l'entreprise U.P.C.",
2276
- gs18Prefix: "Pr\xE9fixe GS1-8",
2277
- gs1CompanyPrefixCantStartWith0: `Le pr\xE9fixe de l'entreprise GS1 ne peut pas commencer par "0"`,
2278
- gs1CompanyPrefixCantStartWith00000: `Le pr\xE9fixe de l'entreprise GS1 ne peut pas commencer par "00000"`,
2279
- gs1CompanyPrefixCantStartWith000000: `Le pr\xE9fixe de l'entreprise GS1 ne peut pas commencer par "000000"`,
2280
- upcCompanyPrefixCantStartWith0000: `Le pr\xE9fixe de l'entreprise U.P.C. ne peut pas commencer par "0000"`,
2281
- gs18PrefixCantStartWith0: 'Le pr\xE9fixe GS1-8 ne peut pas commencer par "0"',
2282
- identifierTypeNotSupportedByGS18Prefix: "{{identifierType}} non pris en charge par le pr\xE9fixe GS1-8"
2283
- }
2284
- };
2285
-
2286
- // src/locale/i18n.ts
2287
- var gs1NS = "aidct_gs1";
2288
- var gs1Resources = {
2289
- en: {
2290
- aidct_gs1: locale_resources_default
2291
- },
2292
- fr: {
2293
- aidct_gs1: locale_resources_default2
2294
- }
2295
- };
2296
- var i18nextGS1 = instance.createInstance();
2297
- async function i18nGS1Init(environment, debug = false) {
2298
- await i18nUtilityInit(environment, debug);
2299
- await i18nCoreInit(i18nextGS1, environment, debug, gs1NS, utilityResources, gs1Resources);
2300
- }
2301
-
2302
- // src/character-set.ts
2303
- import { CharacterSetCreator, CharacterSetValidator, Exclusions } from "@aidc-toolkit/utility";
2304
- var AI82_CREATOR = new CharacterSetCreator([
2305
- "!",
2306
- '"',
2307
- "%",
2308
- "&",
2309
- "'",
2310
- "(",
2311
- ")",
2312
- "*",
2313
- "+",
2314
- ",",
2315
- "-",
2316
- ".",
2317
- "/",
2318
- "0",
2319
- "1",
2320
- "2",
2321
- "3",
2322
- "4",
2323
- "5",
2324
- "6",
2325
- "7",
2326
- "8",
2327
- "9",
2328
- ":",
2329
- ";",
2330
- "<",
2331
- "=",
2332
- ">",
2333
- "?",
2334
- "A",
2335
- "B",
2336
- "C",
2337
- "D",
2338
- "E",
2339
- "F",
2340
- "G",
2341
- "H",
2342
- "I",
2343
- "J",
2344
- "K",
2345
- "L",
2346
- "M",
2347
- "N",
2348
- "O",
2349
- "P",
2350
- "Q",
2351
- "R",
2352
- "S",
2353
- "T",
2354
- "U",
2355
- "V",
2356
- "W",
2357
- "X",
2358
- "Y",
2359
- "Z",
2360
- "_",
2361
- "a",
2362
- "b",
2363
- "c",
2364
- "d",
2365
- "e",
2366
- "f",
2367
- "g",
2368
- "h",
2369
- "i",
2370
- "j",
2371
- "k",
2372
- "l",
2373
- "m",
2374
- "n",
2375
- "o",
2376
- "p",
2377
- "q",
2378
- "r",
2379
- "s",
2380
- "t",
2381
- "u",
2382
- "v",
2383
- "w",
2384
- "x",
2385
- "y",
2386
- "z"
2387
- ], Exclusions.AllNumeric);
2388
- var AI82_VALIDATOR = AI82_CREATOR;
2389
- var AI39_CREATOR = new CharacterSetCreator([
2390
- "#",
2391
- "-",
2392
- "/",
2393
- "0",
2394
- "1",
2395
- "2",
2396
- "3",
2397
- "4",
2398
- "5",
2399
- "6",
2400
- "7",
2401
- "8",
2402
- "9",
2403
- "A",
2404
- "B",
2405
- "C",
2406
- "D",
2407
- "E",
2408
- "F",
2409
- "G",
2410
- "H",
2411
- "I",
2412
- "J",
2413
- "K",
2414
- "L",
2415
- "M",
2416
- "N",
2417
- "O",
2418
- "P",
2419
- "Q",
2420
- "R",
2421
- "S",
2422
- "T",
2423
- "U",
2424
- "V",
2425
- "W",
2426
- "X",
2427
- "Y",
2428
- "Z"
2429
- ], Exclusions.AllNumeric);
2430
- var AI39_VALIDATOR = AI39_CREATOR;
2431
- var AI64_VALIDATOR = new CharacterSetValidator([
2432
- "-",
2433
- "0",
2434
- "1",
2435
- "2",
2436
- "3",
2437
- "4",
2438
- "5",
2439
- "6",
2440
- "7",
2441
- "8",
2442
- "9",
2443
- "=",
2444
- "A",
2445
- "B",
2446
- "C",
2447
- "D",
2448
- "E",
2449
- "F",
2450
- "G",
2451
- "H",
2452
- "I",
2453
- "J",
2454
- "K",
2455
- "L",
2456
- "M",
2457
- "N",
2458
- "O",
2459
- "P",
2460
- "Q",
2461
- "R",
2462
- "S",
2463
- "T",
2464
- "U",
2465
- "V",
2466
- "W",
2467
- "X",
2468
- "Y",
2469
- "Z",
2470
- "_",
2471
- "a",
2472
- "b",
2473
- "c",
2474
- "d",
2475
- "e",
2476
- "f",
2477
- "g",
2478
- "h",
2479
- "i",
2480
- "j",
2481
- "k",
2482
- "l",
2483
- "m",
2484
- "n",
2485
- "o",
2486
- "p",
2487
- "q",
2488
- "r",
2489
- "s",
2490
- "t",
2491
- "u",
2492
- "v",
2493
- "w",
2494
- "x",
2495
- "y",
2496
- "z"
2497
- ]);
2498
-
2499
- // src/check.ts
2500
- import { NUMERIC_CREATOR, utilityNS } from "@aidc-toolkit/utility";
2501
- var THREE_WEIGHT_RESULTS = [
2502
- 0,
2503
- 3,
2504
- 6,
2505
- 9,
2506
- 12,
2507
- 15,
2508
- 18,
2509
- 21,
2510
- 24,
2511
- 27
2512
- ];
2513
- var TWO_MINUS_WEIGHT_RESULTS = [
2514
- 0,
2515
- 2,
2516
- 4,
2517
- 6,
2518
- 8,
2519
- 9,
2520
- 1,
2521
- 3,
2522
- 5,
2523
- 7
2524
- ];
2525
- var FIVE_PLUS_WEIGHT_RESULTS = [
2526
- 0,
2527
- 5,
2528
- 1,
2529
- 6,
2530
- 2,
2531
- 7,
2532
- 3,
2533
- 8,
2534
- 4,
2535
- 9
2536
- ];
2537
- var FIVE_MINUS_WEIGHT_RESULTS = [
2538
- 0,
2539
- 5,
2540
- 9,
2541
- 4,
2542
- 8,
2543
- 3,
2544
- 7,
2545
- 2,
2546
- 6,
2547
- 1
2548
- ];
2549
- var INVERSE_FIVE_MINUS_WEIGHT_RESULTS = [
2550
- 0,
2551
- 9,
2552
- 7,
2553
- 5,
2554
- 3,
2555
- 1,
2556
- 8,
2557
- 6,
2558
- 4,
2559
- 2
2560
- ];
2561
- function checkDigitSum(exchangeWeights, s) {
2562
- let weight3 = (s.length + Number(exchangeWeights)) % 2 === 0;
2563
- return NUMERIC_CREATOR.characterIndexes(s).reduce((accumulator, characterIndex, index) => {
2564
- if (characterIndex === void 0) {
2565
- throw new RangeError(i18nextGS1.t("CharacterSetValidator.invalidCharacterAtPosition", {
2566
- ns: utilityNS,
2567
- c: s.charAt(index),
2568
- position: index + 1
2569
- }));
2570
- }
2571
- weight3 = !weight3;
2572
- return accumulator + (weight3 ? THREE_WEIGHT_RESULTS[characterIndex] : characterIndex);
2573
- }, 0);
2574
- }
2575
- function checkDigit(s) {
2576
- return NUMERIC_CREATOR.character(9 - (checkDigitSum(false, s) + 9) % 10);
2577
- }
2578
- function hasValidCheckDigit(s) {
2579
- return checkDigitSum(true, s) % 10 === 0;
2580
- }
2581
- function priceOrWeightSum(weightsResults, s) {
2582
- return NUMERIC_CREATOR.characterIndexes(s).reduce((accumulator, characterIndex, index) => {
2583
- if (characterIndex === void 0) {
2584
- throw new RangeError(i18nextGS1.t("CharacterSetValidator.invalidCharacterAtPositionOfComponent", {
2585
- ns: utilityNS,
2586
- c: s.charAt(index),
2587
- position: index + 1,
2588
- component: i18nextGS1.t("Check.priceOrWeightComponent")
2589
- }));
2590
- }
2591
- return accumulator + weightsResults[index][characterIndex];
2592
- }, 0);
2593
- }
2594
- function priceOrWeightCheckDigit(s) {
2595
- let checkDigit2;
2596
- switch (s.length) {
2597
- case 4:
2598
- checkDigit2 = NUMERIC_CREATOR.character(priceOrWeightSum([TWO_MINUS_WEIGHT_RESULTS, TWO_MINUS_WEIGHT_RESULTS, THREE_WEIGHT_RESULTS, FIVE_MINUS_WEIGHT_RESULTS], s) * 3 % 10);
2599
- break;
2600
- case 5:
2601
- 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]);
2602
- break;
2603
- default:
2604
- throw new RangeError(i18nextGS1.t("Check.lengthOfStringForPriceOrWeightMustBeExactly", {
2605
- length: s.length
2606
- }));
2607
- }
2608
- return checkDigit2;
2609
- }
2610
- function isValidPriceOrWeightCheckDigit(s, checkDigit2) {
2611
- return priceOrWeightCheckDigit(s) === checkDigit2;
2612
- }
2613
- var CHECK_CHARACTER_WEIGHTS = [
2614
- 107,
2615
- 103,
2616
- 101,
2617
- 97,
2618
- 89,
2619
- 83,
2620
- 79,
2621
- 73,
2622
- 71,
2623
- 67,
2624
- 61,
2625
- 59,
2626
- 53,
2627
- 47,
2628
- 43,
2629
- 41,
2630
- 37,
2631
- 31,
2632
- 29,
2633
- 23,
2634
- 19,
2635
- 17,
2636
- 13,
2637
- 11,
2638
- 7,
2639
- 5,
2640
- 3,
2641
- 2
2642
- ];
2643
- var CHECK_CHARACTERS = [
2644
- "2",
2645
- "3",
2646
- "4",
2647
- "5",
2648
- "6",
2649
- "7",
2650
- "8",
2651
- "9",
2652
- "A",
2653
- "B",
2654
- "C",
2655
- "D",
2656
- "E",
2657
- "F",
2658
- "G",
2659
- "H",
2660
- "J",
2661
- "K",
2662
- "L",
2663
- "M",
2664
- "N",
2665
- "P",
2666
- "Q",
2667
- "R",
2668
- "S",
2669
- "T",
2670
- "U",
2671
- "V",
2672
- "W",
2673
- "X",
2674
- "Y",
2675
- "Z"
2676
- ];
2677
- function checkCharacterPair(s) {
2678
- const weightIndexStart = CHECK_CHARACTER_WEIGHTS.length - s.length;
2679
- if (weightIndexStart < 0) {
2680
- throw new RangeError(i18nextGS1.t("Check.lengthOfStringForCheckCharacterPairMustBeLessThanOrEqualTo", {
2681
- length: s.length,
2682
- maximumLength: CHECK_CHARACTER_WEIGHTS.length
2683
- }));
2684
- }
2685
- const checkCharacterPairSum = AI82_CREATOR.characterIndexes(s).reduce((accumulator, characterIndex, index) => {
2686
- if (characterIndex === void 0) {
2687
- throw new RangeError(i18nextGS1.t("CharacterSetValidator.invalidCharacterAtPosition", {
2688
- ns: utilityNS,
2689
- c: s.charAt(index),
2690
- position: index + 1
2691
- }));
2692
- }
2693
- return accumulator + characterIndex * CHECK_CHARACTER_WEIGHTS[weightIndexStart + index];
2694
- }, 0) % 1021;
2695
- const checkCharacterPairSumMod32 = checkCharacterPairSum % 32;
2696
- return CHECK_CHARACTERS[(checkCharacterPairSum - checkCharacterPairSumMod32) / 32] + CHECK_CHARACTERS[checkCharacterPairSumMod32];
2697
- }
2698
- function hasValidCheckCharacterPair(s) {
2699
- const checkCharacterPairIndex = s.length - 2;
2700
- return checkCharacterPair(s.substring(0, checkCharacterPairIndex)) === s.substring(checkCharacterPairIndex);
2701
- }
2702
-
2703
- // src/prefix-type.ts
2704
- var PrefixTypes = {
2705
- /**
2706
- * GS1 Company Prefix.
2707
- */
2708
- GS1CompanyPrefix: "GS1 Company Prefix",
2709
- /**
2710
- * U.P.C. Company Prefix.
2711
- */
2712
- UPCCompanyPrefix: "U.P.C. Company Prefix",
2713
- /**
2714
- * GS1-8 Prefix.
2715
- */
2716
- GS18Prefix: "GS1-8 Prefix"
2717
- };
2718
-
2719
- // src/prefix-validator.ts
2720
- import { NUMERIC_CREATOR as NUMERIC_CREATOR2 } from "@aidc-toolkit/utility";
2721
- var GS1_COMPANY_PREFIX_MINIMUM_LENGTH = 4;
2722
- var GS1_COMPANY_PREFIX_MAXIMUM_LENGTH = 12;
2723
- var UPC_COMPANY_PREFIX_MINIMUM_LENGTH = 6;
2724
- var UPC_COMPANY_PREFIX_MAXIMUM_LENGTH = 11;
2725
- var GS1_8_PREFIX_MINIMUM_LENGTH = 2;
2726
- var GS1_8_PREFIX_MAXIMUM_LENGTH = 7;
2727
- var GS1_COMPANY_PREFIX_VALIDATION = {
2728
- minimumLength: GS1_COMPANY_PREFIX_MINIMUM_LENGTH,
2729
- maximumLength: GS1_COMPANY_PREFIX_MAXIMUM_LENGTH,
2730
- component: () => i18nextGS1.t("Prefix.gs1CompanyPrefix")
2731
- };
2732
- var UPC_COMPANY_PREFIX_AS_GS1_COMPANY_PREFIX_VALIDATION = {
2733
- minimumLength: UPC_COMPANY_PREFIX_MINIMUM_LENGTH + 1,
2734
- maximumLength: UPC_COMPANY_PREFIX_MAXIMUM_LENGTH + 1,
2735
- component: () => i18nextGS1.t("Prefix.gs1CompanyPrefix")
2736
- };
2737
- var GS1_8_PREFIX_AS_GS1_COMPANY_PREFIX_VALIDATION = {
2738
- minimumLength: GS1_8_PREFIX_MINIMUM_LENGTH + 5,
2739
- maximumLength: GS1_8_PREFIX_MAXIMUM_LENGTH + 5,
2740
- component: () => i18nextGS1.t("Prefix.gs1CompanyPrefix")
2741
- };
2742
- var UPC_COMPANY_PREFIX_VALIDATION = {
2743
- minimumLength: UPC_COMPANY_PREFIX_MINIMUM_LENGTH,
2744
- maximumLength: UPC_COMPANY_PREFIX_MAXIMUM_LENGTH,
2745
- component: () => i18nextGS1.t("Prefix.upcCompanyPrefix")
2746
- };
2747
- var GS1_8_PREFIX_VALIDATION = {
2748
- minimumLength: GS1_8_PREFIX_MINIMUM_LENGTH,
2749
- maximumLength: GS1_8_PREFIX_MAXIMUM_LENGTH,
2750
- component: () => i18nextGS1.t("Prefix.gs18Prefix")
2751
- };
2752
- var PrefixValidator = {
2753
- GS1_COMPANY_PREFIX_MINIMUM_LENGTH,
2754
- GS1_COMPANY_PREFIX_MAXIMUM_LENGTH,
2755
- UPC_COMPANY_PREFIX_MINIMUM_LENGTH,
2756
- UPC_COMPANY_PREFIX_MAXIMUM_LENGTH,
2757
- GS1_8_PREFIX_MINIMUM_LENGTH,
2758
- GS1_8_PREFIX_MAXIMUM_LENGTH,
2759
- /**
2760
- * Validate a prefix.
2761
- *
2762
- * @param prefixType
2763
- * Prefix type.
2764
- *
2765
- * @param allowUPCCompanyPrefix
2766
- * If true, a U.P.C. Company Prefix expressed as a GS1 Company Prefix is permitted.
2767
- *
2768
- * @param allowGS18Prefix
2769
- * If true, a GS1-8 Prefix expressed as a GS1 Company Prefix is permitted.
2770
- *
2771
- * @param prefix
2772
- * Prefix.
2773
- *
2774
- * @param isFromIdentifier
2775
- * If true, the prefix is from an identifier and should be trimmed before its character set is validated.
2776
- *
2777
- * @param isNumericIdentifier
2778
- * If true, the prefix is from a numeric identifier and its character set will be validated by the caller.
2779
- *
2780
- * @param positionOffset
2781
- * Position offset within a larger string.
2782
- */
2783
- validate(prefixType, allowUPCCompanyPrefix, allowGS18Prefix, prefix, isFromIdentifier = false, isNumericIdentifier = false, positionOffset) {
2784
- let baseValidation;
2785
- switch (prefixType) {
2786
- case PrefixTypes.GS1CompanyPrefix:
2787
- if (!prefix.startsWith("0")) {
2788
- baseValidation = GS1_COMPANY_PREFIX_VALIDATION;
2789
- } else if (!prefix.startsWith("00000")) {
2790
- if (!allowUPCCompanyPrefix) {
2791
- throw new RangeError(i18nextGS1.t("Prefix.gs1CompanyPrefixCantStartWith0"));
2792
- }
2793
- baseValidation = UPC_COMPANY_PREFIX_AS_GS1_COMPANY_PREFIX_VALIDATION;
2794
- } else if (!prefix.startsWith("000000")) {
2795
- if (!allowGS18Prefix) {
2796
- throw new RangeError(i18nextGS1.t("Prefix.gs1CompanyPrefixCantStartWith00000"));
2797
- }
2798
- baseValidation = GS1_8_PREFIX_AS_GS1_COMPANY_PREFIX_VALIDATION;
2799
- } else {
2800
- throw new RangeError(i18nextGS1.t("Prefix.gs1CompanyPrefixCantStartWith000000"));
2801
- }
2802
- break;
2803
- case PrefixTypes.UPCCompanyPrefix:
2804
- if (prefix.startsWith("0000")) {
2805
- throw new RangeError(i18nextGS1.t("Prefix.upcCompanyPrefixCantStartWith0000"));
2806
- }
2807
- baseValidation = UPC_COMPANY_PREFIX_VALIDATION;
2808
- break;
2809
- case PrefixTypes.GS18Prefix:
2810
- if (prefix.startsWith("0")) {
2811
- throw new RangeError(i18nextGS1.t("Prefix.gs18PrefixCantStartWith0"));
2812
- }
2813
- baseValidation = GS1_8_PREFIX_VALIDATION;
2814
- break;
2815
- }
2816
- const mergedValidation = {
2817
- ...baseValidation,
2818
- positionOffset
2819
- };
2820
- if (!isFromIdentifier) {
2821
- NUMERIC_CREATOR2.validate(prefix, mergedValidation);
2822
- } else if (!isNumericIdentifier) {
2823
- NUMERIC_CREATOR2.validate(prefix.substring(0, Math.min(mergedValidation.minimumLength, prefix.length - 1)), mergedValidation);
2824
- }
2825
- },
2826
- /**
2827
- * Normalize a prefix.
2828
- *
2829
- * @param prefixType
2830
- * Prefix type.
2831
- *
2832
- * @param prefix
2833
- * Prefix.
2834
- *
2835
- * @returns
2836
- * Prefix provider with normalized prefix type and prefix.
2837
- */
2838
- normalize(prefixType, prefix) {
2839
- this.validate(prefixType, true, true, prefix);
2840
- let gs1CompanyPrefix;
2841
- switch (prefixType) {
2842
- case PrefixTypes.GS1CompanyPrefix:
2843
- gs1CompanyPrefix = prefix;
2844
- break;
2845
- case PrefixTypes.UPCCompanyPrefix:
2846
- gs1CompanyPrefix = "0" + prefix;
2847
- break;
2848
- case PrefixTypes.GS18Prefix:
2849
- gs1CompanyPrefix = "00000" + prefix;
2850
- break;
2851
- }
2852
- let normalizedPrefixType;
2853
- let normalizedPrefix;
2854
- let upcCompanyPrefix = void 0;
2855
- let gs18Prefix = void 0;
2856
- if (!gs1CompanyPrefix.startsWith("0")) {
2857
- normalizedPrefixType = PrefixTypes.GS1CompanyPrefix;
2858
- normalizedPrefix = gs1CompanyPrefix;
2859
- } else if (!gs1CompanyPrefix.startsWith("00000")) {
2860
- normalizedPrefixType = PrefixTypes.UPCCompanyPrefix;
2861
- upcCompanyPrefix = gs1CompanyPrefix.substring(1);
2862
- normalizedPrefix = upcCompanyPrefix;
2863
- } else {
2864
- normalizedPrefixType = PrefixTypes.GS18Prefix;
2865
- gs18Prefix = gs1CompanyPrefix.substring(5);
2866
- normalizedPrefix = gs18Prefix;
2867
- }
2868
- return {
2869
- prefixType: normalizedPrefixType,
2870
- prefix: normalizedPrefix,
2871
- gs1CompanyPrefix,
2872
- upcCompanyPrefix,
2873
- gs18Prefix
2874
- };
2875
- }
2876
- };
2877
-
2878
- // src/content-character-set.ts
2879
- var ContentCharacterSets = {
2880
- /**
2881
- * Numeric.
2882
- */
2883
- Numeric: "Numeric",
2884
- /**
2885
- * GS1 AI encodable character set 82.
2886
- */
2887
- AI82: "AI82",
2888
- /**
2889
- * GS1 AI encodable character set 39.
2890
- */
2891
- AI39: "AI39"
2892
- };
2893
-
2894
- // src/identifier-type.ts
2895
- var IdentifierTypes = {
2896
- /**
2897
- * Global Trade Item Number.
2898
- */
2899
- GTIN: "GTIN",
2900
- /**
2901
- * Global Location Number.
2902
- */
2903
- GLN: "GLN",
2904
- /**
2905
- * Serial Shipping Container Code.
2906
- */
2907
- SSCC: "SSCC",
2908
- /**
2909
- * Global Returnable Asset Identifier.
2910
- */
2911
- GRAI: "GRAI",
2912
- /**
2913
- * Global Individual Asset Identifier.
2914
- */
2915
- GIAI: "GIAI",
2916
- /**
2917
- * Global Service Relation Number.
2918
- */
2919
- GSRN: "GSRN",
2920
- /**
2921
- * Global Document Type Identifier.
2922
- */
2923
- GDTI: "GDTI",
2924
- /**
2925
- * Global Identification Number for Consignment.
2926
- */
2927
- GINC: "GINC",
2928
- /**
2929
- * Global Shipment Identification Number.
2930
- */
2931
- GSIN: "GSIN",
2932
- /**
2933
- * Global Coupon Number.
2934
- */
2935
- GCN: "GCN",
2936
- /**
2937
- * Component/Part Identifier.
2938
- */
2939
- CPID: "CPID",
2940
- /**
2941
- * Global Model Number.
2942
- */
2943
- GMN: "GMN"
2944
- };
2945
-
2946
- // src/numeric-identifier-type.ts
2947
- var LeaderTypes = {
2948
- /**
2949
- * No leader.
2950
- */
2951
- None: "None",
2952
- /**
2953
- * Indicator digit (GTIN only).
2954
- */
2955
- IndicatorDigit: "Indicator digit",
2956
- /**
2957
- * Extension digit (SSCC only).
2958
- */
2959
- ExtensionDigit: "Extension digit"
2960
- };
2961
-
2962
- // src/gtin-type.ts
2963
- var GTINTypes = {
2964
- /**
2965
- * GTIN-13.
2966
- */
2967
- GTIN13: 13,
2968
- /**
2969
- * GTIN-12.
2970
- */
2971
- GTIN12: 12,
2972
- /**
2973
- * GTIN-8.
2974
- */
2975
- GTIN8: 8,
2976
- /**
2977
- * GTIN-14.
2978
- */
2979
- GTIN14: 14
2980
- };
2981
- var GTIN_BASE_TYPES = {
2982
- [PrefixTypes.GS1CompanyPrefix]: GTINTypes.GTIN13,
2983
- [PrefixTypes.UPCCompanyPrefix]: GTINTypes.GTIN12,
2984
- [PrefixTypes.GS18Prefix]: GTINTypes.GTIN8
2985
- };
2986
-
2987
- // src/descriptors.ts
2988
- var GTIN13_DESCRIPTOR = {
2989
- identifierType: IdentifierTypes.GTIN,
2990
- prefixType: PrefixTypes.GS1CompanyPrefix,
2991
- length: GTINTypes.GTIN13,
2992
- referenceCharacterSet: ContentCharacterSets.Numeric,
2993
- leaderType: LeaderTypes.IndicatorDigit
2994
- };
2995
- var GTIN12_DESCRIPTOR = {
2996
- identifierType: IdentifierTypes.GTIN,
2997
- prefixType: PrefixTypes.UPCCompanyPrefix,
2998
- length: GTINTypes.GTIN12,
2999
- referenceCharacterSet: ContentCharacterSets.Numeric,
3000
- leaderType: LeaderTypes.IndicatorDigit
3001
- };
3002
- var GTIN8_DESCRIPTOR = {
3003
- identifierType: IdentifierTypes.GTIN,
3004
- prefixType: PrefixTypes.GS18Prefix,
3005
- length: GTINTypes.GTIN8,
3006
- referenceCharacterSet: ContentCharacterSets.Numeric,
3007
- leaderType: LeaderTypes.IndicatorDigit
3008
- };
3009
- var GTIN_DESCRIPTORS = {
3010
- [GTINTypes.GTIN13]: GTIN13_DESCRIPTOR,
3011
- [GTINTypes.GTIN12]: GTIN12_DESCRIPTOR,
3012
- [GTINTypes.GTIN8]: GTIN8_DESCRIPTOR
3013
- };
3014
- var GLN_DESCRIPTOR = {
3015
- identifierType: IdentifierTypes.GLN,
3016
- prefixType: PrefixTypes.GS1CompanyPrefix,
3017
- length: 13,
3018
- referenceCharacterSet: ContentCharacterSets.Numeric,
3019
- leaderType: LeaderTypes.None
3020
- };
3021
- var SSCC_DESCRIPTOR = {
3022
- identifierType: IdentifierTypes.SSCC,
3023
- prefixType: PrefixTypes.GS1CompanyPrefix,
3024
- length: 18,
3025
- referenceCharacterSet: ContentCharacterSets.Numeric,
3026
- leaderType: LeaderTypes.ExtensionDigit
3027
- };
3028
- var GRAI_DESCRIPTOR = {
3029
- identifierType: IdentifierTypes.GRAI,
3030
- prefixType: PrefixTypes.GS1CompanyPrefix,
3031
- length: 13,
3032
- referenceCharacterSet: ContentCharacterSets.Numeric,
3033
- leaderType: LeaderTypes.None,
3034
- serialComponentLength: 16,
3035
- serialComponentCharacterSet: ContentCharacterSets.AI82
3036
- };
3037
- var GIAI_DESCRIPTOR = {
3038
- identifierType: IdentifierTypes.GIAI,
3039
- prefixType: PrefixTypes.GS1CompanyPrefix,
3040
- length: 30,
3041
- referenceCharacterSet: ContentCharacterSets.AI82,
3042
- requiresCheckCharacterPair: false
3043
- };
3044
- var GSRN_DESCRIPTOR = {
3045
- identifierType: IdentifierTypes.GSRN,
3046
- prefixType: PrefixTypes.GS1CompanyPrefix,
3047
- length: 18,
3048
- referenceCharacterSet: ContentCharacterSets.Numeric,
3049
- leaderType: LeaderTypes.None
3050
- };
3051
- var GDTI_DESCRIPTOR = {
3052
- identifierType: IdentifierTypes.GDTI,
3053
- prefixType: PrefixTypes.GS1CompanyPrefix,
3054
- length: 13,
3055
- referenceCharacterSet: ContentCharacterSets.Numeric,
3056
- leaderType: LeaderTypes.None,
3057
- serialComponentLength: 17,
3058
- serialComponentCharacterSet: ContentCharacterSets.AI82
3059
- };
3060
- var GINC_DESCRIPTOR = {
3061
- identifierType: IdentifierTypes.GINC,
3062
- prefixType: PrefixTypes.GS1CompanyPrefix,
3063
- length: 30,
3064
- referenceCharacterSet: ContentCharacterSets.AI82,
3065
- requiresCheckCharacterPair: false
3066
- };
3067
- var GSIN_DESCRIPTOR = {
3068
- identifierType: IdentifierTypes.GSIN,
3069
- prefixType: PrefixTypes.GS1CompanyPrefix,
3070
- length: 17,
3071
- referenceCharacterSet: ContentCharacterSets.Numeric,
3072
- leaderType: LeaderTypes.None
3073
- };
3074
- var GCN_DESCRIPTOR = {
3075
- identifierType: IdentifierTypes.GCN,
3076
- prefixType: PrefixTypes.GS1CompanyPrefix,
3077
- length: 13,
3078
- referenceCharacterSet: ContentCharacterSets.Numeric,
3079
- leaderType: LeaderTypes.None,
3080
- serialComponentLength: 12,
3081
- serialComponentCharacterSet: ContentCharacterSets.Numeric
3082
- };
3083
- var CPID_DESCRIPTOR = {
3084
- identifierType: IdentifierTypes.CPID,
3085
- prefixType: PrefixTypes.GS1CompanyPrefix,
3086
- length: 30,
3087
- referenceCharacterSet: ContentCharacterSets.AI39,
3088
- requiresCheckCharacterPair: false
3089
- };
3090
- var GMN_DESCRIPTOR = {
3091
- identifierType: IdentifierTypes.GMN,
3092
- prefixType: PrefixTypes.GS1CompanyPrefix,
3093
- length: 25,
3094
- referenceCharacterSet: ContentCharacterSets.AI82,
3095
- requiresCheckCharacterPair: true
3096
- };
3097
- var IdentifierDescriptors = {
3098
- [IdentifierTypes.GTIN]: GTIN_DESCRIPTORS,
3099
- [IdentifierTypes.GLN]: GLN_DESCRIPTOR,
3100
- [IdentifierTypes.SSCC]: SSCC_DESCRIPTOR,
3101
- [IdentifierTypes.GRAI]: GRAI_DESCRIPTOR,
3102
- [IdentifierTypes.GIAI]: GIAI_DESCRIPTOR,
3103
- [IdentifierTypes.GSRN]: GSRN_DESCRIPTOR,
3104
- [IdentifierTypes.GDTI]: GDTI_DESCRIPTOR,
3105
- [IdentifierTypes.GINC]: GINC_DESCRIPTOR,
3106
- [IdentifierTypes.GSIN]: GSIN_DESCRIPTOR,
3107
- [IdentifierTypes.GCN]: GCN_DESCRIPTOR,
3108
- [IdentifierTypes.CPID]: CPID_DESCRIPTOR,
3109
- [IdentifierTypes.GMN]: GMN_DESCRIPTOR
3110
- };
3111
- function isGTINDescriptors(identifierDescriptorsOrDescriptor) {
3112
- return !("identifierType" in identifierDescriptorsOrDescriptor);
3113
- }
3114
- function identifierTypesIncludes(identifierTypes, identifierType) {
3115
- return identifierTypes.includes(identifierType);
3116
- }
3117
- var NUMERIC_IDENTIFIER_TYPES = [IdentifierTypes.GTIN, IdentifierTypes.GLN, IdentifierTypes.SSCC, IdentifierTypes.GRAI, IdentifierTypes.GSRN, IdentifierTypes.GDTI, IdentifierTypes.GSIN, IdentifierTypes.GCN];
3118
- function isNumericIdentifierDescriptor(identifierDescriptor) {
3119
- return identifierTypesIncludes(NUMERIC_IDENTIFIER_TYPES, identifierDescriptor.identifierType);
3120
- }
3121
- function isGTINDescriptor(identifierDescriptor) {
3122
- return identifierDescriptor.identifierType === IdentifierTypes.GTIN;
3123
- }
3124
- function isNonGTINNumericIdentifierDescriptor(identifierDescriptor) {
3125
- return isNumericIdentifierDescriptor(identifierDescriptor) && !isGTINDescriptor(identifierDescriptor);
3126
- }
3127
- var SERIALIZABLE_NUMERIC_IDENTIFIER_TYPES = [IdentifierTypes.GRAI, IdentifierTypes.GDTI, IdentifierTypes.GCN];
3128
- function isSerializableNumericIdentifierDescriptor(identifierDescriptor) {
3129
- return identifierTypesIncludes(SERIALIZABLE_NUMERIC_IDENTIFIER_TYPES, identifierDescriptor.identifierType);
3130
- }
3131
- function isNonNumericIdentifierDescriptor(identifierDescriptor) {
3132
- return !isNumericIdentifierDescriptor(identifierDescriptor);
3133
- }
3134
-
3135
- // src/gtin-validator.ts
3136
- import { NUMERIC_CREATOR as NUMERIC_CREATOR4 } from "@aidc-toolkit/utility";
3137
-
3138
- // src/abstract-identifier-validator.ts
3139
- import { NUMERIC_CREATOR as NUMERIC_CREATOR3 } from "@aidc-toolkit/utility";
3140
- var AbstractIdentifierValidator = class _AbstractIdentifierValidator {
3141
- static CHARACTER_SET_CREATORS = {
3142
- [ContentCharacterSets.Numeric]: NUMERIC_CREATOR3,
3143
- [ContentCharacterSets.AI82]: AI82_CREATOR,
3144
- [ContentCharacterSets.AI39]: AI39_CREATOR
3145
- };
3146
- /**
3147
- * Identifier type.
3148
- */
3149
- _identifierType;
3150
- /**
3151
- * Length.
3152
- */
3153
- _length;
3154
- /**
3155
- * Reference character set.
3156
- */
3157
- _referenceCharacterSet;
3158
- /**
3159
- * Reference creator.
3160
- */
3161
- _referenceCreator;
3162
- /**
3163
- * Get the character set creator for a character set.
3164
- *
3165
- * @param characterSet
3166
- * Character set.
3167
- *
3168
- * @returns
3169
- * Character set creator.
3170
- */
3171
- static creatorFor(characterSet) {
3172
- return _AbstractIdentifierValidator.CHARACTER_SET_CREATORS[characterSet];
3173
- }
3174
- /**
3175
- * Constructor.
3176
- *
3177
- * @param identifierDescriptor
3178
- * Identifier descriptor.
3179
- */
3180
- constructor(identifierDescriptor) {
3181
- this._identifierType = identifierDescriptor.identifierType;
3182
- this._length = identifierDescriptor.length;
3183
- this._referenceCharacterSet = identifierDescriptor.referenceCharacterSet;
3184
- this._referenceCreator = _AbstractIdentifierValidator.creatorFor(identifierDescriptor.referenceCharacterSet);
3185
- }
3186
- /**
3187
- * @inheritDoc
3188
- */
3189
- get identifierType() {
3190
- return this._identifierType;
3191
- }
3192
- /**
3193
- * @inheritDoc
3194
- */
3195
- get prefixType() {
3196
- return PrefixTypes.GS1CompanyPrefix;
3197
- }
3198
- /**
3199
- * @inheritDoc
3200
- */
3201
- get length() {
3202
- return this._length;
3203
- }
3204
- /**
3205
- * @inheritDoc
3206
- */
3207
- get referenceCharacterSet() {
3208
- return this._referenceCharacterSet;
3209
- }
3210
- /**
3211
- * @inheritDoc
3212
- */
3213
- get referenceCreator() {
3214
- return this._referenceCreator;
3215
- }
3216
- /**
3217
- * Pad an identifier on the left with zero-value character for validation purposes. This is done to align an
3218
- * identifier with a position offset for any error message that may be thrown by the reference validator.
3219
- *
3220
- * @param identifier
3221
- * Identifier.
3222
- *
3223
- * @param positionOffset
3224
- * Position offset within a larger string.
3225
- *
3226
- * @returns
3227
- * Padded identifier.
3228
- */
3229
- padIdentifier(identifier, positionOffset) {
3230
- return positionOffset === void 0 ? identifier : this.referenceCreator.character(0).repeat(positionOffset).concat(identifier);
3231
- }
3232
- /**
3233
- * Validate the prefix within an identifier.
3234
- *
3235
- * @param partialIdentifier
3236
- * Partial identifier.
3237
- *
3238
- * @param positionOffset
3239
- * Position offset within a larger string.
3240
- */
3241
- validatePrefix(partialIdentifier, positionOffset) {
3242
- PrefixValidator.validate(this.prefixType, true, false, partialIdentifier, true, this.referenceCharacterSet === ContentCharacterSets.Numeric, positionOffset);
3243
- }
3244
- };
3245
-
3246
- // src/abstract-numeric-identifier-validator.ts
3247
- var AbstractNumericIdentifierValidator = class extends AbstractIdentifierValidator {
3248
- /**
3249
- * Leader type.
3250
- */
3251
- _leaderType;
3252
- /**
3253
- * Prefix position, determined by the leader type.
3254
- */
3255
- _prefixPosition;
3256
- /**
3257
- * Constructor.
3258
- *
3259
- * @param identifierDescriptor
3260
- * Identifier descriptor.
3261
- */
3262
- constructor(identifierDescriptor) {
3263
- super(identifierDescriptor);
3264
- this._leaderType = identifierDescriptor.leaderType;
3265
- this._prefixPosition = Number(this.leaderType === LeaderTypes.ExtensionDigit);
3266
- }
3267
- /**
3268
- * @inheritDoc
3269
- */
3270
- get leaderType() {
3271
- return this._leaderType;
3272
- }
3273
- /**
3274
- * @inheritDoc
3275
- */
3276
- validate(identifier, validation) {
3277
- if (this._prefixPosition === 0) {
3278
- super.validatePrefix(identifier, validation?.positionOffset);
3279
- } else {
3280
- super.validatePrefix(identifier.substring(this._prefixPosition), validation?.positionOffset === void 0 ? this._prefixPosition : validation.positionOffset + this._prefixPosition);
3281
- }
3282
- if (identifier.length !== this.length) {
3283
- throw new RangeError(i18nextGS1.t("Identifier.identifierTypeLength", {
3284
- identifierType: this.identifierType,
3285
- length: this.length
3286
- }));
3287
- }
3288
- if (!hasValidCheckDigit(this.padIdentifier(identifier, validation?.positionOffset))) {
3289
- throw new RangeError(i18nextGS1.t("Identifier.invalidCheckDigit"));
3290
- }
3291
- }
3292
- };
3293
-
3294
- // src/gtin-validator.ts
3295
- var GTINLevels = {
3296
- /**
3297
- * Any level (level is ignored).
3298
- */
3299
- Any: 0,
3300
- /**
3301
- * Retail consumer trade item level, supporting GTIN-13, GTIN-12 (optionally zero-suppressed), and GTIN-8.
3302
- */
3303
- RetailConsumer: 1,
3304
- /**
3305
- * Other than retail consumer trade item level, supporting GTIN-13, GTIN-12 (not zero-suppressed), and GTIN-14.
3306
- */
3307
- OtherThanRetailConsumer: 2
3308
- };
3309
- var GTINValidator = class _GTINValidator extends AbstractNumericIdentifierValidator {
3310
- /**
3311
- * Validation parameters for optional indicator digit.
3312
- */
3313
- static OPTIONAL_INDICATOR_DIGIT_VALIDATION = {
3314
- minimumLength: 0,
3315
- maximumLength: 1,
3316
- component: () => i18nextGS1.t("Identifier.indicatorDigit")
3317
- };
3318
- /**
3319
- * Validation parameters for zero-suppressed GTIN-12.
3320
- */
3321
- static ZERO_SUPPRESSED_GTIN12_VALIDATION = {
3322
- minimumLength: 8,
3323
- maximumLength: 8
3324
- };
3325
- /**
3326
- * Prefix type.
3327
- */
3328
- _prefixType;
3329
- /**
3330
- * Constructor.
3331
- *
3332
- * @param gtinBaseType
3333
- * GTIN base type (all except GTIN-14).
3334
- */
3335
- constructor(gtinBaseType) {
3336
- const identifierDescriptor = IdentifierDescriptors.GTIN[gtinBaseType];
3337
- super(identifierDescriptor);
3338
- this._prefixType = identifierDescriptor.prefixType;
3339
- }
3340
- /**
3341
- * @inheritDoc
3342
- */
3343
- get prefixType() {
3344
- return this._prefixType;
3345
- }
3346
- /**
3347
- * @inheritDoc
3348
- */
3349
- get gtinType() {
3350
- return this.length;
3351
- }
3352
- /**
3353
- * @inheritDoc
3354
- */
3355
- validatePrefix(partialIdentifier, positionOffset) {
3356
- PrefixValidator.validate(this.prefixType, false, false, partialIdentifier, true, true, positionOffset);
3357
- }
3358
- /**
3359
- * Zero suppress a GTIN-12.
3360
- *
3361
- * @param gtin12
3362
- * GTIN-12.
3363
- *
3364
- * @returns
3365
- * Zero-suppressed GTIN-12.
3366
- */
3367
- static zeroSuppress(gtin12) {
3368
- GTIN12_VALIDATOR.validate(gtin12);
3369
- const d = Array.from(gtin12);
3370
- let zeroSuppressedGTIN12;
3371
- if (d[0] === "0" && d[6] === "0" && d[7] === "0") {
3372
- if (d[10] >= "5" && d[8] === "0" && d[9] === "0" && d[5] !== "0") {
3373
- zeroSuppressedGTIN12 = `0${d[1]}${d[2]}${d[3]}${d[4]}${d[5]}${d[10]}${d[11]}`;
3374
- } else if (d[5] === "0" && d[8] === "0" && d[9] === "0" && d[4] !== "0") {
3375
- zeroSuppressedGTIN12 = `0${d[1]}${d[2]}${d[3]}${d[4]}${d[10]}4${d[11]}`;
3376
- } else if (d[3] <= "2" && d[4] === "0" && d[5] === "0") {
3377
- zeroSuppressedGTIN12 = `0${d[1]}${d[2]}${d[8]}${d[9]}${d[10]}${d[3]}${d[11]}`;
3378
- } else if (d[3] >= "3" && d[4] === "0" && d[5] === "0" && d[8] === "0") {
3379
- zeroSuppressedGTIN12 = `0${d[1]}${d[2]}${d[3]}${d[9]}${d[10]}3${d[11]}`;
3380
- }
3381
- }
3382
- if (zeroSuppressedGTIN12 === void 0) {
3383
- throw new RangeError(i18nextGS1.t("Identifier.invalidZeroSuppressibleGTIN12"));
3384
- }
3385
- return zeroSuppressedGTIN12;
3386
- }
3387
- /**
3388
- * Zero expand a zero-suppressed GTIN-12.
3389
- *
3390
- * @param zeroSuppressedGTIN12
3391
- * Zero-suppressed GTIN-12.
3392
- *
3393
- * @returns
3394
- * GTIN-12.
3395
- */
3396
- static zeroExpand(zeroSuppressedGTIN12) {
3397
- NUMERIC_CREATOR4.validate(zeroSuppressedGTIN12, _GTINValidator.ZERO_SUPPRESSED_GTIN12_VALIDATION);
3398
- const d = Array.from(zeroSuppressedGTIN12);
3399
- let gtin12;
3400
- if (d[0] === "0") {
3401
- if (d[6] >= "5" && d[5] !== "0") {
3402
- gtin12 = `0${d[1]}${d[2]}${d[3]}${d[4]}${d[5]}0000${d[6]}${d[7]}`;
3403
- } else if (d[6] === "4" && d[4] !== "0") {
3404
- gtin12 = `0${d[1]}${d[2]}${d[3]}${d[4]}00000${d[5]}${d[7]}`;
3405
- } else if (d[6] <= "2") {
3406
- gtin12 = `0${d[1]}${d[2]}${d[6]}0000${d[3]}${d[4]}${d[5]}${d[7]}`;
3407
- } else if (d[6] === "3" && d[3] >= "3") {
3408
- gtin12 = `0${d[1]}${d[2]}${d[3]}00000${d[4]}${d[5]}${d[7]}`;
3409
- }
3410
- }
3411
- if (gtin12 === void 0) {
3412
- throw new RangeError(i18nextGS1.t("Identifier.invalidZeroSuppressedGTIN12"));
3413
- }
3414
- GTIN12_VALIDATOR.validate(gtin12);
3415
- return gtin12;
3416
- }
3417
- /**
3418
- * Convert a GTIN of any length to a GTIN-14 with an optional indicator digit.
3419
- *
3420
- * @param indicatorDigit
3421
- * Indicator digit. If blank, assumes "0" if the GTIN is not already a GTIN-14.
3422
- *
3423
- * @param gtin
3424
- * GTIN.
3425
- *
3426
- * @returns
3427
- * GTIN-14.
3428
- */
3429
- static convertToGTIN14(indicatorDigit, gtin) {
3430
- _GTINValidator.validateAny(gtin);
3431
- NUMERIC_CREATOR4.validate(indicatorDigit, _GTINValidator.OPTIONAL_INDICATOR_DIGIT_VALIDATION);
3432
- let gtin14 = gtin.padStart(GTINTypes.GTIN14, "0");
3433
- if (indicatorDigit.length !== 0 && indicatorDigit !== gtin14.charAt(0)) {
3434
- const partialGTIN14 = indicatorDigit + gtin14.substring(1, GTINTypes.GTIN14 - 1);
3435
- gtin14 = partialGTIN14 + checkDigit(partialGTIN14);
3436
- }
3437
- return gtin14;
3438
- }
3439
- /**
3440
- * Normalize a GTIN of any length.
3441
- * - A GTIN-14 that starts with six zeros or a GTIN-13 that starts with five zeros is normalized to GTIN-8.
3442
- * - A GTIN-14 that starts with two zeros or a GTIN-13 that starts with one zero is normalized to GTIN-12.
3443
- * - A GTIN-14 that starts with one zero is normalized to GTIN-13.
3444
- * - Otherwise, the GTIN is unchanged.
3445
- *
3446
- * @param gtin
3447
- * GTIN.
3448
- *
3449
- * @returns
3450
- * Normalized GTIN.
3451
- */
3452
- static normalize(gtin) {
3453
- const gtinLength = gtin.length;
3454
- let normalizedGTIN;
3455
- switch (gtinLength) {
3456
- case GTINTypes.GTIN13:
3457
- if (!gtin.startsWith("0")) {
3458
- normalizedGTIN = gtin;
3459
- } else if (!gtin.startsWith("00000")) {
3460
- normalizedGTIN = gtin.substring(1);
3461
- } else if (!gtin.startsWith("000000")) {
3462
- normalizedGTIN = gtin.substring(5);
3463
- } else {
3464
- throw new RangeError(i18nextGS1.t("Identifier.invalidZeroSuppressedGTIN12AsGTIN13"));
3465
- }
3466
- break;
3467
- case GTINTypes.GTIN12:
3468
- normalizedGTIN = gtin;
3469
- break;
3470
- case GTINTypes.GTIN8:
3471
- if (!gtin.startsWith("0")) {
3472
- normalizedGTIN = gtin;
3473
- } else {
3474
- normalizedGTIN = _GTINValidator.zeroExpand(gtin);
3475
- }
3476
- break;
3477
- case GTINTypes.GTIN14:
3478
- if (!gtin.startsWith("0")) {
3479
- normalizedGTIN = gtin;
3480
- } else if (!gtin.startsWith("00")) {
3481
- normalizedGTIN = gtin.substring(1);
3482
- } else if (!gtin.startsWith("000000")) {
3483
- normalizedGTIN = gtin.substring(2);
3484
- } else if (!gtin.startsWith("0000000")) {
3485
- normalizedGTIN = gtin.substring(6);
3486
- } else {
3487
- throw new RangeError(i18nextGS1.t("Identifier.invalidZeroSuppressedGTIN12AsGTIN14"));
3488
- }
3489
- break;
3490
- default:
3491
- throw new RangeError(i18nextGS1.t("Identifier.invalidGTINLength"));
3492
- }
3493
- _GTINValidator.validateAny(normalizedGTIN);
3494
- return normalizedGTIN;
3495
- }
3496
- /**
3497
- * Validate any GTIN, optionally against a level.
3498
- *
3499
- * @param gtin
3500
- * GTIN.
3501
- *
3502
- * @param gtinLevel
3503
- * Level at which GTIN is to be validated.
3504
- */
3505
- static validateAny(gtin, gtinLevel = GTINLevels.Any) {
3506
- let lengthValidatedGTIN = gtin;
3507
- let gtinLevelRestriction;
3508
- switch (gtin.length) {
3509
- case GTINTypes.GTIN13:
3510
- if (gtin.startsWith("0")) {
3511
- throw new RangeError(i18nextGS1.t("Identifier.invalidGTIN13AtRetail"));
3512
- }
3513
- PrefixValidator.validate(PrefixTypes.GS1CompanyPrefix, false, false, gtin, true, true);
3514
- gtinLevelRestriction = GTINLevels.Any;
3515
- break;
3516
- case GTINTypes.GTIN12:
3517
- PrefixValidator.validate(PrefixTypes.UPCCompanyPrefix, false, false, gtin, true, true);
3518
- gtinLevelRestriction = GTINLevels.Any;
3519
- break;
3520
- case GTINTypes.GTIN8:
3521
- if (!gtin.startsWith("0")) {
3522
- PrefixValidator.validate(PrefixTypes.GS18Prefix, false, false, gtin, true, true);
3523
- } else {
3524
- lengthValidatedGTIN = _GTINValidator.zeroExpand(gtin);
3525
- }
3526
- gtinLevelRestriction = GTINLevels.RetailConsumer;
3527
- break;
3528
- case GTINTypes.GTIN14:
3529
- PrefixValidator.validate(PrefixTypes.GS1CompanyPrefix, true, true, gtin.substring(1), true, true);
3530
- gtinLevelRestriction = GTINLevels.OtherThanRetailConsumer;
3531
- break;
3532
- default:
3533
- throw new RangeError(i18nextGS1.t("Identifier.invalidGTINLength"));
3534
- }
3535
- if (!hasValidCheckDigit(lengthValidatedGTIN)) {
3536
- throw new RangeError(i18nextGS1.t("Identifier.invalidCheckDigit"));
3537
- }
3538
- if (gtinLevel !== GTINLevels.Any && gtinLevelRestriction !== GTINLevels.Any && gtinLevelRestriction !== gtinLevel) {
3539
- throw new RangeError(i18nextGS1.t(gtinLevel === GTINLevels.RetailConsumer ? "Identifier.invalidGTINAtRetail" : "Identifier.invalidGTINAtOtherThanRetail"));
3540
- }
3541
- }
3542
- /**
3543
- * Validate a GTIN-14.
3544
- *
3545
- * @param gtin14
3546
- * GTIN-14.
3547
- */
3548
- static validateGTIN14(gtin14) {
3549
- if (gtin14.length !== GTINTypes.GTIN14) {
3550
- throw new RangeError(i18nextGS1.t("Identifier.invalidGTIN14Length"));
3551
- }
3552
- _GTINValidator.validateAny(gtin14);
3553
- }
3554
- /**
3555
- * Parse a Restricted Circulation Number (RCN) using a variable measure trade item format. The format is a 12- or
3556
- * 13-character string (for RCN-12 or RCN-13 respectively), containing the following:
3557
- *
3558
- * - '2' - The first character of the RCN.
3559
- * - '0'-'9' - The second character of the RCN (RCN-13 only).
3560
- * - 'I' - One or more, in sequence, for the item reference.
3561
- * - 'P' - One or more, in sequence, for the price or weight.
3562
- * - 'V' - Zero or one, for the price or weight check digit.
3563
- * - 'C' - The check digit of the entire RCN.
3564
- *
3565
- * The 'I', 'P', and 'V' formats may be in any order.
3566
- *
3567
- * Some examples:
3568
- *
3569
- * - 2IIIIIVPPPPC - RCN-12 with a five-digit item reference, a price or weight check digit, and a four-digit price
3570
- * or weight.
3571
- * - 23IIIIVPPPPPC - RCN-13 with a four-digit item reference, a price or weight check digit, and a five-digit price
3572
- * or weight.
3573
- * - 2IIIIIIPPPPC - RCN-12 with a six-digit item reference and a four-digit price or eight.
3574
- * - 29IIIIIPPPPPC - RCN-13 with a five-digit item reference and a five-digit price or weight.
3575
- *
3576
- * @param format
3577
- * Format.
3578
- *
3579
- * @param rcn
3580
- * RCN.
3581
- *
3582
- * @returns
3583
- * RCN reference.
3584
- */
3585
- static parseVariableMeasureRCN(format, rcn) {
3586
- const formatLength = format.length;
3587
- if (rcn.length !== formatLength) {
3588
- throw new RangeError(i18nextGS1.t("Identifier.invalidRCNLength"));
3589
- }
3590
- let validFormat = formatLength === 12 || formatLength === 13;
3591
- let validRCNPrefix = true;
3592
- let buildingItemReference = false;
3593
- let itemReference = "";
3594
- let buildingPriceOrWeight = false;
3595
- let priceOrWeight = "";
3596
- let priceOrWeightCheckDigit2 = "";
3597
- for (let index = 0; validFormat && index < formatLength; index++) {
3598
- const formatChar = format.charAt(index);
3599
- const rcnChar = rcn.charAt(index);
3600
- if (index === 0) {
3601
- validFormat = formatChar === "2";
3602
- validRCNPrefix = rcnChar === "2";
3603
- } else if (formatLength === 13 && index === 1) {
3604
- validFormat = NUMERIC_CREATOR4.characterIndex(formatChar) !== void 0;
3605
- validRCNPrefix = rcnChar === formatChar;
3606
- } else if (index === formatLength - 1) {
3607
- validFormat = formatChar === "C";
3608
- } else {
3609
- switch (formatChar) {
3610
- case "I":
3611
- if (!buildingItemReference) {
3612
- validFormat = itemReference === "";
3613
- buildingItemReference = true;
3614
- buildingPriceOrWeight = false;
3615
- }
3616
- itemReference += rcnChar;
3617
- break;
3618
- case "P":
3619
- if (!buildingPriceOrWeight) {
3620
- validFormat = priceOrWeight === "";
3621
- buildingPriceOrWeight = true;
3622
- buildingItemReference = false;
3623
- }
3624
- priceOrWeight += rcnChar;
3625
- break;
3626
- case "V":
3627
- validFormat = priceOrWeightCheckDigit2 === "";
3628
- buildingItemReference = false;
3629
- buildingPriceOrWeight = false;
3630
- priceOrWeightCheckDigit2 = rcnChar;
3631
- break;
3632
- default:
3633
- validFormat = false;
3634
- break;
3635
- }
3636
- }
3637
- }
3638
- validFormat &&= itemReference !== "" && priceOrWeight !== "";
3639
- if (!validFormat) {
3640
- throw new RangeError(i18nextGS1.t("Identifier.invalidVariableMeasureRCNFormat"));
3641
- }
3642
- if (!validRCNPrefix) {
3643
- throw new RangeError(i18nextGS1.t("Identifier.invalidVariableMeasureRCNPrefix"));
3644
- }
3645
- if (priceOrWeightCheckDigit2 !== "" && !isValidPriceOrWeightCheckDigit(priceOrWeight, priceOrWeightCheckDigit2)) {
3646
- throw new RangeError(i18nextGS1.t("Identifier.invalidVariableMeasurePriceOrWeight"));
3647
- }
3648
- if (!hasValidCheckDigit(rcn)) {
3649
- throw new RangeError(i18nextGS1.t("Identifier.invalidCheckDigit"));
3650
- }
3651
- return {
3652
- itemReference: Number(itemReference),
3653
- priceOrWeight: Number(priceOrWeight)
3654
- };
3655
- }
3656
- };
3657
- var GTIN13_VALIDATOR = new GTINValidator(GTINTypes.GTIN13);
3658
- var GTIN12_VALIDATOR = new GTINValidator(GTINTypes.GTIN12);
3659
- var GTIN8_VALIDATOR = new GTINValidator(GTINTypes.GTIN8);
3660
- var GTIN_VALIDATORS = {
3661
- [GTINTypes.GTIN13]: GTIN13_VALIDATOR,
3662
- [GTINTypes.GTIN12]: GTIN12_VALIDATOR,
3663
- [GTINTypes.GTIN8]: GTIN8_VALIDATOR
3664
- };
3665
-
3666
- // src/non-gtin-numeric-identifier-validator.ts
3667
- var NonGTINNumericIdentifierValidator = class extends AbstractNumericIdentifierValidator {
3668
- /**
3669
- * Constructor.
3670
- *
3671
- * @param identifierType
3672
- * Identifier type.
3673
- */
3674
- constructor(identifierType) {
3675
- super(IdentifierDescriptors[identifierType]);
3676
- }
3677
- };
3678
-
3679
- // src/serializable-numeric-identifier-validator.ts
3680
- var SerializableNumericIdentifierValidator = class _SerializableNumericIdentifierValidator extends AbstractNumericIdentifierValidator {
3681
- /**
3682
- * Serial component length.
3683
- */
3684
- _serialComponentLength;
3685
- /**
3686
- * Serial component character set.
3687
- */
3688
- _serialComponentCharacterSet;
3689
- /**
3690
- * Serial component validation parameters.
3691
- */
3692
- _serialComponentValidation;
3693
- /**
3694
- * Serial component creator.
3695
- */
3696
- _serialComponentCreator;
3697
- /**
3698
- * Constructor.
3699
- *
3700
- * @param identifierType
3701
- * Identifier type.
3702
- */
3703
- constructor(identifierType) {
3704
- const identifierDescriptor = IdentifierDescriptors[identifierType];
3705
- super(identifierDescriptor);
3706
- this._serialComponentLength = identifierDescriptor.serialComponentLength;
3707
- this._serialComponentCharacterSet = identifierDescriptor.serialComponentCharacterSet;
3708
- this._serialComponentValidation = {
3709
- minimumLength: 1,
3710
- maximumLength: identifierDescriptor.serialComponentLength,
3711
- component: () => i18nextGS1.t("Identifier.serialComponent")
3712
- };
3713
- this._serialComponentCreator = _SerializableNumericIdentifierValidator.creatorFor(identifierDescriptor.serialComponentCharacterSet);
3714
- }
3715
- /**
3716
- * Get the serial component length.
3717
- */
3718
- get serialComponentLength() {
3719
- return this._serialComponentLength;
3720
- }
3721
- /**
3722
- * Get the serial component character set.
3723
- */
3724
- get serialComponentCharacterSet() {
3725
- return this._serialComponentCharacterSet;
3726
- }
3727
- /**
3728
- * Get the serial component validation parameters.
3729
- */
3730
- get serialComponentValidation() {
3731
- return this._serialComponentValidation;
3732
- }
3733
- /**
3734
- * Get the serial component creator.
3735
- */
3736
- get serialComponentCreator() {
3737
- return this._serialComponentCreator;
3738
- }
3739
- /**
3740
- * @inheritDoc
3741
- */
3742
- validate(identifier, validation) {
3743
- super.validate(identifier.substring(0, this.length), validation);
3744
- if (identifier.length > this.length) {
3745
- this.serialComponentCreator.validate(identifier.substring(this.length), this._serialComponentValidation);
3746
- }
3747
- }
3748
- };
3749
-
3750
- // src/non-numeric-identifier-validator.ts
3751
- import { Exclusions as Exclusions2, RegExpValidator } from "@aidc-toolkit/utility";
3752
- var NonNumericIdentifierValidator = class _NonNumericIdentifierValidator extends AbstractIdentifierValidator {
3753
- /**
3754
- * Validator to ensure that an identifier (minus check character pair) is not all numeric.
3755
- */
3756
- static NOT_ALL_NUMERIC_VALIDATOR = new class extends RegExpValidator {
3757
- /**
3758
- * @inheritDoc
3759
- */
3760
- createErrorMessage(_s) {
3761
- return i18nextGS1.t("Identifier.referenceCantBeAllNumeric");
3762
- }
3763
- }(/\D/);
3764
- /**
3765
- * True if the identifier requires a check character pair.
3766
- */
3767
- _requiresCheckCharacterPair;
3768
- /**
3769
- * Constructor.
3770
- *
3771
- * @param identifierType
3772
- * Identifier type.
3773
- */
3774
- constructor(identifierType) {
3775
- const identifierDescriptor = IdentifierDescriptors[identifierType];
3776
- super(identifierDescriptor);
3777
- this._requiresCheckCharacterPair = identifierDescriptor.requiresCheckCharacterPair;
3778
- }
3779
- /**
3780
- * Determine if the identifier requires a check character pair.
3781
- */
3782
- get requiresCheckCharacterPair() {
3783
- return this._requiresCheckCharacterPair;
3784
- }
3785
- /**
3786
- * Validate a non-numeric identifier and throw an error if validation fails.
3787
- *
3788
- * @param identifier
3789
- * Identifier.
3790
- *
3791
- * @param validation
3792
- * Validation parameters.
3793
- */
3794
- validate(identifier, validation) {
3795
- const partialIdentifier = this.requiresCheckCharacterPair ? identifier.substring(0, identifier.length - 2) : identifier;
3796
- super.validatePrefix(partialIdentifier);
3797
- if (!this.requiresCheckCharacterPair) {
3798
- this.referenceCreator.validate(identifier, {
3799
- maximumLength: this.length
3800
- });
3801
- } else if (!hasValidCheckCharacterPair(this.padIdentifier(identifier))) {
3802
- throw new RangeError(i18nextGS1.t("Identifier.invalidCheckCharacterPair"));
3803
- }
3804
- if (validation?.exclusion === Exclusions2.AllNumeric) {
3805
- _NonNumericIdentifierValidator.NOT_ALL_NUMERIC_VALIDATOR.validate(partialIdentifier);
3806
- }
3807
- }
3808
- };
3809
-
3810
- // src/validators.ts
3811
- var GLN_VALIDATOR = new NonGTINNumericIdentifierValidator(IdentifierTypes.GLN);
3812
- var SSCC_VALIDATOR = new NonGTINNumericIdentifierValidator(IdentifierTypes.SSCC);
3813
- var GRAI_VALIDATOR = new SerializableNumericIdentifierValidator(IdentifierTypes.GRAI);
3814
- var GIAI_VALIDATOR = new NonNumericIdentifierValidator(IdentifierTypes.GIAI);
3815
- var GSRN_VALIDATOR = new NonGTINNumericIdentifierValidator(IdentifierTypes.GSRN);
3816
- var GDTI_VALIDATOR = new SerializableNumericIdentifierValidator(IdentifierTypes.GDTI);
3817
- var GINC_VALIDATOR = new NonNumericIdentifierValidator(IdentifierTypes.GINC);
3818
- var GSIN_VALIDATOR = new NonGTINNumericIdentifierValidator(IdentifierTypes.GSIN);
3819
- var GCN_VALIDATOR = new SerializableNumericIdentifierValidator(IdentifierTypes.GCN);
3820
- var CPID_VALIDATOR = new NonNumericIdentifierValidator(IdentifierTypes.CPID);
3821
- var GMN_VALIDATOR = new NonNumericIdentifierValidator(IdentifierTypes.GMN);
3822
- var IdentifierValidators = {
3823
- [IdentifierTypes.GTIN]: GTIN_VALIDATORS,
3824
- [IdentifierTypes.GLN]: GLN_VALIDATOR,
3825
- [IdentifierTypes.SSCC]: SSCC_VALIDATOR,
3826
- [IdentifierTypes.GRAI]: GRAI_VALIDATOR,
3827
- [IdentifierTypes.GIAI]: GIAI_VALIDATOR,
3828
- [IdentifierTypes.GSRN]: GSRN_VALIDATOR,
3829
- [IdentifierTypes.GDTI]: GDTI_VALIDATOR,
3830
- [IdentifierTypes.GINC]: GINC_VALIDATOR,
3831
- [IdentifierTypes.GSIN]: GSIN_VALIDATOR,
3832
- [IdentifierTypes.GCN]: GCN_VALIDATOR,
3833
- [IdentifierTypes.CPID]: CPID_VALIDATOR,
3834
- [IdentifierTypes.GMN]: GMN_VALIDATOR
3835
- };
3836
- function isGTINValidators(identifierValidatorsOrValidator) {
3837
- return isGTINDescriptors(identifierValidatorsOrValidator);
3838
- }
3839
- function isNumericIdentifierValidator(identifierValidator) {
3840
- return isNumericIdentifierDescriptor(identifierValidator);
3841
- }
3842
- function isGTINValidator(identifierValidator) {
3843
- return isGTINDescriptor(identifierValidator);
3844
- }
3845
- function isNonGTINNumericIdentifierValidator(identifierValidator) {
3846
- return isNonGTINNumericIdentifierDescriptor(identifierValidator);
3847
- }
3848
- function isSerializableNumericIdentifierValidator(identifierValidator) {
3849
- return isSerializableNumericIdentifierDescriptor(identifierValidator);
3850
- }
3851
- function isNonNumericIdentifierValidator(identifierValidator) {
3852
- return isNonNumericIdentifierDescriptor(identifierValidator);
3853
- }
3854
-
3855
- // src/gtin-creator.ts
3856
- import {
3857
- Exclusions as Exclusions4,
3858
- NUMERIC_CREATOR as NUMERIC_CREATOR6
3859
- } from "@aidc-toolkit/utility";
3860
- import { Mixin } from "ts-mixer";
3861
-
3862
- // src/abstract-numeric-identifier-creator.ts
3863
- import {
3864
- CharacterSetCreator as CharacterSetCreator2,
3865
- Exclusions as Exclusions3,
3866
- NUMERIC_CREATOR as NUMERIC_CREATOR5
3867
- } from "@aidc-toolkit/utility";
3868
-
3869
- // src/abstract-identifier-creator.ts
3870
- var AbstractIdentifierCreator = class {
3871
- /**
3872
- * Prefix provider.
3873
- */
3874
- _prefixProvider;
3875
- /**
3876
- * Reference length.
3877
- */
3878
- _referenceLength;
3879
- /**
3880
- * Initialize the prefix provider. This method is in lieu of a constructor due to the mixin architecture.
3881
- *
3882
- * @param prefixProvider
3883
- * Prefix provider.
3884
- *
3885
- * @param prefix
3886
- * Prefix within prefix provider to use to calculate reference length.
3887
- *
3888
- * @param checkAllowance
3889
- * Number of characters to allow for check digit or check character pair.
3890
- */
3891
- init(prefixProvider, prefix, checkAllowance) {
3892
- this._prefixProvider = prefixProvider;
3893
- this._referenceLength = this.length - prefix.length - checkAllowance;
3894
- }
3895
- /**
3896
- * @inheritDoc
3897
- */
3898
- get prefixProvider() {
3899
- return this._prefixProvider;
3900
- }
3901
- /**
3902
- * @inheritDoc
3903
- */
3904
- get prefix() {
3905
- return this.prefixProvider.gs1CompanyPrefix;
3906
- }
3907
- /**
3908
- * @inheritDoc
3909
- */
3910
- get referenceLength() {
3911
- return this._referenceLength;
3912
- }
3913
- };
3914
-
3915
- // src/abstract-numeric-identifier-creator.ts
3916
- var AbstractNumericIdentifierCreator = class _AbstractNumericIdentifierCreator extends AbstractIdentifierCreator {
3917
- /**
3918
- * Capacity.
3919
- */
3920
- _capacity;
3921
- /**
3922
- * Tweak for sparse creation.
3923
- */
3924
- _tweak = 0n;
3925
- /**
3926
- * Initialize the prefix provider. This method is in lieu of a constructor due to the mixin architecture.
3927
- *
3928
- * @param prefixProvider
3929
- * Prefix provider.
3930
- *
3931
- * @param prefix
3932
- * Prefix within prefix manager to use to calculate reference length.
3933
- */
3934
- init(prefixProvider, prefix) {
3935
- super.init(prefixProvider, prefix, 1);
3936
- this._capacity = Number(CharacterSetCreator2.powerOf10(this.referenceLength));
3937
- }
3938
- /**
3939
- * @inheritDoc
3940
- */
3941
- get capacity() {
3942
- return this._capacity;
3943
- }
3944
- /**
3945
- * @inheritDoc
3946
- */
3947
- get tweak() {
3948
- return this._tweak;
3949
- }
3950
- /**
3951
- * @inheritDoc
3952
- */
3953
- set tweak(value) {
3954
- this._tweak = value;
3955
- }
3956
- /**
3957
- * Build an identifier from a reference by merging it with the prefix and adding the check digit.
3958
- *
3959
- * @param reference
3960
- * Identifier reference.
3961
- *
3962
- * @returns
3963
- * Identifier.
3964
- */
3965
- buildIdentifier(reference) {
3966
- const partialIdentifier = this.leaderType === LeaderTypes.ExtensionDigit ? reference.substring(0, 1) + this.prefix + reference.substring(1) : this.prefix + reference;
3967
- return partialIdentifier + checkDigit(partialIdentifier);
3968
- }
3969
- /**
3970
- * @inheritDoc
3971
- */
3972
- create(valueOrValues, sparse = false) {
3973
- return NUMERIC_CREATOR5.create(this.referenceLength, valueOrValues, Exclusions3.None, sparse ? this.tweak : void 0, (reference) => this.buildIdentifier(reference));
3974
- }
3975
- /**
3976
- * Create all identifiers from a partial identifier. Call is recursive until remaining reference
3977
- * length is 0.
3978
- *
3979
- * @param partialIdentifier
3980
- * Partial identifier. Initial value is `this.prefix`.
3981
- *
3982
- * @param remainingReferenceLength
3983
- * Remaining reference length. Initial value is `this.referenceLength`.
3984
- *
3985
- * @param extensionWeight
3986
- * If this value is not zero, the identifier has an extension digit, this call is setting it, and this value is
3987
- * applied to the calculation of the check digit.
3988
- *
3989
- * @param weight
3990
- * If the extension weight is zero, this value is applied to the calculation of the check digit.
3991
- *
3992
- * @param partialCheckDigitSum
3993
- * Partial check digit sum for the partial identifier.
3994
- *
3995
- * @yields
3996
- * Identifier.
3997
- */
3998
- static *createAllPartial(partialIdentifier, remainingReferenceLength, extensionWeight, weight, partialCheckDigitSum) {
3999
- if (remainingReferenceLength === 0) {
4000
- yield partialIdentifier + NUMERIC_CREATOR5.character(9 - (partialCheckDigitSum + 9) % 10);
4001
- } else {
4002
- const nextRemainingReferenceLength = remainingReferenceLength - 1;
4003
- let nextPartialCheckDigitSum = partialCheckDigitSum;
4004
- if (extensionWeight !== 0) {
4005
- for (const c of NUMERIC_CREATOR5.characterSet) {
4006
- yield* _AbstractNumericIdentifierCreator.createAllPartial(c + partialIdentifier, nextRemainingReferenceLength, 0, weight, nextPartialCheckDigitSum);
4007
- nextPartialCheckDigitSum += extensionWeight;
4008
- }
4009
- } else {
4010
- const nextWeight = 4 - weight;
4011
- for (const c of NUMERIC_CREATOR5.characterSet) {
4012
- yield* _AbstractNumericIdentifierCreator.createAllPartial(partialIdentifier + c, nextRemainingReferenceLength, 0, nextWeight, nextPartialCheckDigitSum);
4013
- nextPartialCheckDigitSum += weight;
4014
- }
4015
- }
4016
- }
4017
- }
4018
- /**
4019
- * @inheritDoc
4020
- */
4021
- createAll() {
4022
- const hasExtensionDigit = this.leaderType === LeaderTypes.ExtensionDigit;
4023
- const prefix = this.prefix;
4024
- const length = this.length;
4025
- const referenceLength = this.referenceLength;
4026
- const startWeight = 3 - 2 * ((referenceLength + 1 - Number(hasExtensionDigit)) % 2);
4027
- return {
4028
- [Symbol.iterator]() {
4029
- return _AbstractNumericIdentifierCreator.createAllPartial(prefix, referenceLength, hasExtensionDigit ? 3 - 2 * length % 2 : 0, startWeight, checkDigitSum(startWeight === 3, prefix));
4030
- }
4031
- };
4032
- }
4033
- };
4034
-
4035
- // src/gtin-creator.ts
4036
- var GTINCreator = class _GTINCreator extends Mixin(GTINValidator, AbstractNumericIdentifierCreator) {
4037
- /**
4038
- * Validation parameters for required indicator digit.
4039
- */
4040
- static REQUIRED_INDICATOR_DIGIT_VALIDATION = {
4041
- minimumLength: 1,
4042
- maximumLength: 1,
4043
- component: () => i18nextGS1.t("Identifier.indicatorDigit")
4044
- };
4045
- /**
4046
- * Constructor. Typically called internally by a prefix manager but may be called by other code with another prefix
4047
- * provider type.
4048
- *
4049
- * @param prefixProvider
4050
- * Prefix provider.
4051
- *
4052
- * @param gtinBaseType
4053
- * GTIN base type (all except GTIN-14).
4054
- */
4055
- constructor(prefixProvider, gtinBaseType) {
4056
- super(gtinBaseType);
4057
- this.init(prefixProvider, prefixProvider.prefix);
4058
- }
4059
- /**
4060
- * @inheritDoc
4061
- */
4062
- get prefix() {
4063
- return this.prefixProvider.prefix;
4064
- }
4065
- /**
4066
- * Create GTIN-14(s) with an indicator digit and reference(s) based on numeric value(s). The value(s) is/are
4067
- * converted to reference(s) of the appropriate length using {@linkcode NUMERIC_CREATOR}.
4068
- *
4069
- * @template TTransformerInput
4070
- * Transformer input type.
4071
- *
4072
- * @param indicatorDigit
4073
- * Indicator digit.
4074
- *
4075
- * @param valueOrValues
4076
- * Numeric value(s).
4077
- *
4078
- * @param sparse
4079
- * If true, the value(s) is/are mapped to a sparse sequence resistant to discovery. Default is false.
4080
- *
4081
- * @returns
4082
- * GTIN-14(s).
4083
- */
4084
- createGTIN14(indicatorDigit, valueOrValues, sparse = false) {
4085
- NUMERIC_CREATOR6.validate(indicatorDigit, _GTINCreator.REQUIRED_INDICATOR_DIGIT_VALIDATION);
4086
- return NUMERIC_CREATOR6.create(GTINTypes.GTIN13 - this.prefixProvider.gs1CompanyPrefix.length - 1, valueOrValues, Exclusions4.None, sparse ? this.tweak : void 0, (reference) => {
4087
- const partialIdentifier = indicatorDigit + this.prefixProvider.gs1CompanyPrefix + reference;
4088
- return partialIdentifier + checkDigit(partialIdentifier);
4089
- });
4090
- }
4091
- /**
4092
- * Create a Restricted Circulation Number (RCN) using a variable measure trade item format. See {@linkcode
4093
- * GTINValidator.parseVariableMeasureRCN} for format details.
4094
- *
4095
- * @param format
4096
- * Format.
4097
- *
4098
- * @param itemReference
4099
- * Item reference.
4100
- *
4101
- * @param priceOrWeight
4102
- * Price or weight (whole number only).
4103
- *
4104
- * @returns
4105
- * RCN-12 or RCN-13.
4106
- */
4107
- static createVariableMeasureRCN(format, itemReference, priceOrWeight) {
4108
- const formatLength = format.length;
4109
- let validFormat = formatLength === 12 || formatLength === 13;
4110
- let rcnPrefix = "";
4111
- let buildingItemReference = false;
4112
- let itemReferenceString = "";
4113
- let itemReferenceLength = 0;
4114
- let buildingPriceOrWeight = false;
4115
- let priceOrWeightString = "";
4116
- let priceOrWeightLength = 0;
4117
- let calculatePriceOrWeightCheckDigit = false;
4118
- const rcnPrefixBuilder = (partialRCN) => partialRCN + rcnPrefix;
4119
- const itemReferenceBuilder = (partialRCN) => partialRCN + itemReferenceString;
4120
- const priceOrWeightBuilder = (partialRCN) => partialRCN + priceOrWeightString;
4121
- const priceOrWeightCheckDigitBuilder = (partialRCN) => partialRCN + priceOrWeightCheckDigit(priceOrWeightString);
4122
- const checkDigitBuilder = (partialRCN) => partialRCN + checkDigit(partialRCN);
4123
- const rcnBuilders = [rcnPrefixBuilder];
4124
- for (let index = 0; validFormat && index < formatLength; index++) {
4125
- const formatChar = format.charAt(index);
4126
- if (index === 0) {
4127
- validFormat = formatChar === "2";
4128
- rcnPrefix = formatChar;
4129
- } else if (formatLength === 13 && index === 1) {
4130
- validFormat = NUMERIC_CREATOR6.characterIndex(formatChar) !== void 0;
4131
- rcnPrefix += formatChar;
4132
- } else if (index === formatLength - 1) {
4133
- validFormat = formatChar === "C";
4134
- } else {
4135
- switch (formatChar) {
4136
- case "I":
4137
- if (!buildingItemReference) {
4138
- validFormat = itemReferenceLength === 0;
4139
- buildingItemReference = true;
4140
- buildingPriceOrWeight = false;
4141
- rcnBuilders.push(itemReferenceBuilder);
4142
- }
4143
- itemReferenceLength++;
4144
- break;
4145
- case "P":
4146
- if (!buildingPriceOrWeight) {
4147
- validFormat = priceOrWeightLength === 0;
4148
- buildingPriceOrWeight = true;
4149
- buildingItemReference = false;
4150
- rcnBuilders.push(priceOrWeightBuilder);
4151
- }
4152
- priceOrWeightLength++;
4153
- break;
4154
- case "V":
4155
- validFormat = !calculatePriceOrWeightCheckDigit;
4156
- buildingItemReference = false;
4157
- buildingPriceOrWeight = false;
4158
- calculatePriceOrWeightCheckDigit = true;
4159
- rcnBuilders.push(priceOrWeightCheckDigitBuilder);
4160
- break;
4161
- default:
4162
- validFormat = false;
4163
- break;
4164
- }
4165
- }
4166
- }
4167
- validFormat &&= itemReferenceLength !== 0 && priceOrWeightLength !== 0;
4168
- if (!validFormat) {
4169
- throw new RangeError(i18nextGS1.t("Identifier.invalidVariableMeasureRCNFormat"));
4170
- }
4171
- itemReferenceString = NUMERIC_CREATOR6.create(itemReferenceLength, itemReference);
4172
- priceOrWeightString = NUMERIC_CREATOR6.create(priceOrWeightLength, priceOrWeight);
4173
- rcnBuilders.push(checkDigitBuilder);
4174
- return rcnBuilders.reduce((partialRCN, rcnBuilder) => rcnBuilder(partialRCN), "");
4175
- }
4176
- };
4177
-
4178
- // src/non-gtin-numeric-identifier-creator.ts
4179
- import { Mixin as Mixin2 } from "ts-mixer";
4180
- var NonGTINNumericIdentifierCreator = class extends Mixin2(NonGTINNumericIdentifierValidator, AbstractNumericIdentifierCreator) {
4181
- /**
4182
- * Constructor. Typically called internally by a prefix manager but may be called by other code with another prefix
4183
- * provider type.
4184
- *
4185
- * @param prefixProvider
4186
- * Prefix provider.
4187
- *
4188
- * @param identifierType
4189
- * Identifier type.
4190
- */
4191
- constructor(prefixProvider, identifierType) {
4192
- super(identifierType);
4193
- this.init(prefixProvider, prefixProvider.gs1CompanyPrefix);
4194
- }
4195
- };
4196
-
4197
- // src/serializable-numeric-identifier-creator.ts
4198
- import { mapIterable } from "@aidc-toolkit/utility";
4199
- import { Mixin as Mixin3 } from "ts-mixer";
4200
- var SerializableNumericIdentifierCreator = class extends Mixin3(SerializableNumericIdentifierValidator, AbstractNumericIdentifierCreator) {
4201
- /**
4202
- * Constructor. Typically called internally by a prefix manager but may be called by other code with another prefix
4203
- * provider type.
4204
- *
4205
- * @param prefixProvider
4206
- * Prefix provider.
4207
- *
4208
- * @param identifierType
4209
- * Identifier type.
4210
- */
4211
- constructor(prefixProvider, identifierType) {
4212
- super(identifierType);
4213
- this.init(prefixProvider, prefixProvider.gs1CompanyPrefix);
4214
- }
4215
- /**
4216
- * Concatenate a validated base identifier with serial component(s).
4217
- *
4218
- * @template TTransformerInput
4219
- * Transformer input type.
4220
- *
4221
- * @param baseIdentifier
4222
- * Base identifier.
4223
- *
4224
- * @param serialComponentOrComponents
4225
- * Serial component(s).
4226
- *
4227
- * @returns
4228
- * Serialized identifier(s).
4229
- */
4230
- concatenateValidated(baseIdentifier, serialComponentOrComponents) {
4231
- let result;
4232
- const serialComponentCreator = this.serialComponentCreator;
4233
- const serialComponentValidation = this.serialComponentValidation;
4234
- function validateAndConcatenate(serialComponent) {
4235
- serialComponentCreator.validate(serialComponent, serialComponentValidation);
4236
- return baseIdentifier + serialComponent;
4237
- }
4238
- if (typeof serialComponentOrComponents !== "object") {
4239
- result = validateAndConcatenate(serialComponentOrComponents);
4240
- } else {
4241
- result = mapIterable(serialComponentOrComponents, validateAndConcatenate);
4242
- }
4243
- return result;
4244
- }
4245
- /**
4246
- * Create serialized identifier(s) with a reference based on a numeric value concatenated with serial component(s).
4247
- * The value is converted to a reference of the appropriate length using a numeric creator.
4248
- *
4249
- * @template TTransformerInput
4250
- * Transformer input type.
4251
- *
4252
- * @param value
4253
- * Numeric value of the reference.
4254
- *
4255
- * @param serialComponentOrComponents
4256
- * Serial component(s).
4257
- *
4258
- * @param sparse
4259
- * If true, the value is mapped to a sparse sequence resistant to discovery. Default is false.
4260
- *
4261
- * @returns
4262
- * Serialized identifiers.
4263
- */
4264
- createSerialized(value, serialComponentOrComponents, sparse) {
4265
- return this.concatenateValidated(this.create(value, sparse), serialComponentOrComponents);
4266
- }
4267
- /**
4268
- * Concatenate a base identifier with serial component(s).
4269
- *
4270
- * @template TTransformerInput
4271
- * Transformer input type.
4272
- *
4273
- * @param baseIdentifier
4274
- * Base identifier.
4275
- *
4276
- * @param serialComponentOrComponents
4277
- * Serial component(s).
4278
- *
4279
- * @returns
4280
- * Serialized identifier(s).
4281
- */
4282
- concatenate(baseIdentifier, serialComponentOrComponents) {
4283
- this.validate(baseIdentifier);
4284
- return this.concatenateValidated(baseIdentifier, serialComponentOrComponents);
4285
- }
4286
- };
4287
-
4288
- // src/non-numeric-identifier-creator.ts
4289
- import {
4290
- mapIterable as mapIterable2
4291
- } from "@aidc-toolkit/utility";
4292
- import { Mixin as Mixin4 } from "ts-mixer";
4293
- var NonNumericIdentifierCreator = class extends Mixin4(NonNumericIdentifierValidator, AbstractIdentifierCreator) {
4294
- /**
4295
- * Reference validation parameters.
4296
- */
4297
- _referenceValidation;
4298
- /**
4299
- * Constructor. Typically called internally by a prefix manager but may be called by other code with another prefix
4300
- * provider type.
4301
- *
4302
- * @param prefixProvider
4303
- * Prefix provider.
4304
- *
4305
- * @param identifierType
4306
- * Identifier type.
4307
- */
4308
- constructor(prefixProvider, identifierType) {
4309
- super(identifierType);
4310
- this.init(prefixProvider, prefixProvider.gs1CompanyPrefix, 2 * Number(this.requiresCheckCharacterPair));
4311
- this._referenceValidation = {
4312
- minimumLength: 1,
4313
- // Maximum reference length has to account for prefix and check character pair.
4314
- maximumLength: this.referenceLength,
4315
- component: () => i18nextGS1.t("Identifier.reference")
4316
- };
4317
- }
4318
- /**
4319
- * Get the reference validation parameters.
4320
- */
4321
- get referenceValidation() {
4322
- return this._referenceValidation;
4323
- }
4324
- /**
4325
- * Create identifier(s) with reference(s).
4326
- *
4327
- * @template TTransformerInput
4328
- * Transformer input type.
4329
- *
4330
- * @param referenceOrReferences
4331
- * Reference(s).
4332
- *
4333
- * @returns
4334
- * Identifier(s).
4335
- */
4336
- create(referenceOrReferences) {
4337
- let result;
4338
- const referenceCreator = this.referenceCreator;
4339
- const referenceValidation = this.referenceValidation;
4340
- const prefix = this.prefix;
4341
- const requiresCheckCharacterPair = this.requiresCheckCharacterPair;
4342
- function validateAndCreate(reference) {
4343
- referenceCreator.validate(reference, referenceValidation);
4344
- const partialIdentifier = prefix + reference;
4345
- return requiresCheckCharacterPair ? partialIdentifier + checkCharacterPair(partialIdentifier) : partialIdentifier;
4346
- }
4347
- if (typeof referenceOrReferences !== "object") {
4348
- result = validateAndCreate(referenceOrReferences);
4349
- } else {
4350
- result = mapIterable2(referenceOrReferences, validateAndCreate);
4351
- }
4352
- return result;
4353
- }
4354
- };
4355
-
4356
- // src/creators.ts
4357
- function isNumericIdentifierCreator(identifierCreator) {
4358
- return isNumericIdentifierDescriptor(identifierCreator);
4359
- }
4360
- function isGTINCreator(identifierCreator) {
4361
- return isGTINDescriptor(identifierCreator);
4362
- }
4363
- function isNonGTINNumericIdentifierCreator(identifierCreator) {
4364
- return isNonGTINNumericIdentifierDescriptor(identifierCreator);
4365
- }
4366
- function isSerializableNumericIdentifierCreator(identifierCreator) {
4367
- return isSerializableNumericIdentifierDescriptor(identifierCreator);
4368
- }
4369
- function isNonNumericIdentifierCreator(identifierCreator) {
4370
- return isNonNumericIdentifierDescriptor(identifierCreator);
4371
- }
4372
-
4373
- // src/prefix-manager.ts
4374
- var PrefixManager = class _PrefixManager {
4375
- /**
4376
- * Cached prefix managers, keyed by GS1 Company Prefix.
4377
- */
4378
- static PREFIX_MANAGERS_MAP = /* @__PURE__ */ new Map();
4379
- /**
4380
- * Creator tweak factors. Different numeric identifier types have different tweak factors so that sparse creation
4381
- * generates different sequences for each.
4382
- */
4383
- static CREATOR_TWEAK_FACTORS = {
4384
- GTIN: 1987n,
4385
- GLN: 4241n,
4386
- SSCC: 8087n,
4387
- GRAI: 3221n,
4388
- GSRN: 2341n,
4389
- GDTI: 7333n,
4390
- GSIN: 5623n,
4391
- GCN: 6869n
4392
- };
4393
- /**
4394
- * Normalized prefix type.
4395
- */
4396
- _prefixType;
4397
- /**
4398
- * Normalized prefix.
4399
- */
4400
- _prefix;
4401
- /**
4402
- * Prefix as GS1 Company Prefix.
4403
- */
4404
- _gs1CompanyPrefix;
4405
- /**
4406
- * U.P.C. Company Prefix if prefix type is {@linkcode PrefixTypes.UPCCompanyPrefix}.
4407
- */
4408
- _upcCompanyPrefix;
4409
- /**
4410
- * GS1-8 Prefix if prefix type is {@linkcode PrefixTypes.GS18Prefix}.
4411
- */
4412
- _gs18Prefix;
4413
- /**
4414
- * Default tweak factor.
4415
- */
4416
- _defaultTweakFactor;
4417
- /**
4418
- * Tweak factor.
4419
- */
4420
- _tweakFactor = 0n;
4421
- /**
4422
- * Cached identifier creators.
4423
- */
4424
- _identifierCreators = {};
4425
- /**
4426
- * Constructor.
4427
- *
4428
- * @param prefixType
4429
- * Prefix type.
4430
- *
4431
- * @param prefix
4432
- * Prefix.
4433
- */
4434
- constructor(prefixType, prefix) {
4435
- const normalizedPrefixProvider = PrefixValidator.normalize(prefixType, prefix);
4436
- this._prefixType = normalizedPrefixProvider.prefixType;
4437
- this._prefix = normalizedPrefixProvider.prefix;
4438
- this._gs1CompanyPrefix = normalizedPrefixProvider.gs1CompanyPrefix;
4439
- this._upcCompanyPrefix = normalizedPrefixProvider.upcCompanyPrefix;
4440
- this._gs18Prefix = normalizedPrefixProvider.gs18Prefix;
4441
- this._defaultTweakFactor = BigInt(`1${this.gs1CompanyPrefix}`);
4442
- this.resetTweakFactor();
4443
- }
4444
- /**
4445
- * Get the prefix type.
4446
- */
4447
- get prefixType() {
4448
- return this._prefixType;
4449
- }
4450
- /**
4451
- * Get the prefix.
4452
- */
4453
- get prefix() {
4454
- return this._prefix;
4455
- }
4456
- /**
4457
- * Get the GS1 Company Prefix.
4458
- */
4459
- get gs1CompanyPrefix() {
4460
- return this._gs1CompanyPrefix;
4461
- }
4462
- /**
4463
- * Get the U.P.C. Company Prefix if prefix type is {@linkcode PrefixTypes.UPCCompanyPrefix} or undefined if not.
4464
- */
4465
- get upcCompanyPrefix() {
4466
- return this._upcCompanyPrefix;
4467
- }
4468
- /**
4469
- * Get the GS1-8 Prefix if prefix type is {@linkcode PrefixTypes.GS18Prefix} or undefined if not.
4470
- */
4471
- get gs18Prefix() {
4472
- return this._gs18Prefix;
4473
- }
4474
- /**
4475
- * Set the tweak for an identifier creator if it's a numeric identifier creator.
4476
- *
4477
- * @param identifierCreator
4478
- * Identifier creator.
4479
- */
4480
- setCreatorTweak(identifierCreator) {
4481
- if (isNumericIdentifierCreator(identifierCreator)) {
4482
- identifierCreator.tweak = this.tweakFactor * _PrefixManager.CREATOR_TWEAK_FACTORS[identifierCreator.identifierType];
4483
- }
4484
- }
4485
- /**
4486
- * Get the tweak factor.
4487
- */
4488
- get tweakFactor() {
4489
- return this._tweakFactor;
4490
- }
4491
- /**
4492
- * Set the tweak factor.
4493
- *
4494
- * @param value
4495
- * Tweak factor.
4496
- */
4497
- set tweakFactor(value) {
4498
- const tweakFactor = BigInt(value);
4499
- if (this._tweakFactor !== tweakFactor) {
4500
- this._tweakFactor = tweakFactor;
4501
- for (const creator of Object.values(this._identifierCreators)) {
4502
- this.setCreatorTweak(creator);
4503
- }
4504
- }
4505
- }
4506
- /**
4507
- * Reset the tweak factor to its default (numeric value of the GS1 Company Prefix preceded by '1').
4508
- */
4509
- resetTweakFactor() {
4510
- this.tweakFactor = this._defaultTweakFactor;
4511
- }
4512
- /**
4513
- * Get a prefix manager.
4514
- *
4515
- * @param prefixType
4516
- * Prefix type.
4517
- *
4518
- * @param prefix
4519
- * Prefix.
4520
- *
4521
- * @returns
4522
- * Prefix manager with normalized prefix type and prefix.
4523
- */
4524
- static get(prefixType, prefix) {
4525
- const normalizedPrefixProvider = PrefixValidator.normalize(prefixType, prefix);
4526
- let prefixManager = _PrefixManager.PREFIX_MANAGERS_MAP.get(normalizedPrefixProvider.gs1CompanyPrefix);
4527
- if (prefixManager === void 0) {
4528
- prefixManager = new _PrefixManager(normalizedPrefixProvider.prefixType, normalizedPrefixProvider.prefix);
4529
- _PrefixManager.PREFIX_MANAGERS_MAP.set(normalizedPrefixProvider.gs1CompanyPrefix, prefixManager);
4530
- }
4531
- return prefixManager;
4532
- }
4533
- /**
4534
- * Get an identifier creator.
4535
- *
4536
- * @template TIdentifierType
4537
- * Identifier type type.
4538
- *
4539
- * @param identifierType
4540
- * Identifier type used to construct identifier creator.
4541
- *
4542
- * @param constructorParameter
4543
- * Second constructor parameter passed to constructor callback alongside this.
4544
- *
4545
- * @param ConstructorCallback
4546
- * Constructor callback.
4547
- *
4548
- * @returns
4549
- * Identifier creator.
4550
- */
4551
- getIdentifierCreator(identifierType, constructorParameter, ConstructorCallback) {
4552
- let creator = this._identifierCreators[identifierType];
4553
- if (creator === void 0) {
4554
- if (this.prefixType === PrefixTypes.GS18Prefix && identifierType !== IdentifierTypes.GTIN) {
4555
- throw new RangeError(i18nextGS1.t("Prefix.identifierTypeNotSupportedByGS18Prefix", {
4556
- identifierType
4557
- }));
4558
- }
4559
- creator = new ConstructorCallback(this, constructorParameter);
4560
- this.setCreatorTweak(creator);
4561
- this._identifierCreators[identifierType] = creator;
4562
- }
4563
- return creator;
4564
- }
4565
- /**
4566
- * Get non-GTIN numeric identifier creator.
4567
- *
4568
- * @param identifierType
4569
- * Identifier type used to construct identifier creator.
4570
- *
4571
- * @returns
4572
- * Identifier creator.
4573
- */
4574
- getNonGTINNumericIdentifierCreator(identifierType) {
4575
- return this.getIdentifierCreator(identifierType, identifierType, NonGTINNumericIdentifierCreator);
4576
- }
4577
- /**
4578
- * Get serialized numeric identifier creator.
4579
- *
4580
- * @param identifierType
4581
- * Identifier type used to construct identifier creator.
4582
- *
4583
- * @returns
4584
- * Identifier creator.
4585
- */
4586
- getSerializableNumericIdentifierCreator(identifierType) {
4587
- return this.getIdentifierCreator(identifierType, identifierType, SerializableNumericIdentifierCreator);
4588
- }
4589
- /**
4590
- * Get non-numeric identifier creator.
4591
- *
4592
- * @param identifierType
4593
- * Identifier type used to construct identifier creator.
4594
- *
4595
- * @returns
4596
- * Identifier creator.
4597
- */
4598
- getNonNumericIdentifierCreator(identifierType) {
4599
- return this.getIdentifierCreator(identifierType, identifierType, NonNumericIdentifierCreator);
4600
- }
4601
- /**
4602
- * Get GTIN creator.
4603
- */
4604
- get gtinCreator() {
4605
- return this.getIdentifierCreator(IdentifierTypes.GTIN, GTIN_BASE_TYPES[this.prefixType], GTINCreator);
4606
- }
4607
- /**
4608
- * Get GLN creator.
4609
- */
4610
- get glnCreator() {
4611
- return this.getNonGTINNumericIdentifierCreator(IdentifierTypes.GLN);
4612
- }
4613
- /**
4614
- * Get SSCC creator.
4615
- */
4616
- get ssccCreator() {
4617
- return this.getNonGTINNumericIdentifierCreator(IdentifierTypes.SSCC);
4618
- }
4619
- /**
4620
- * Get GRAI creator.
4621
- */
4622
- get graiCreator() {
4623
- return this.getSerializableNumericIdentifierCreator(IdentifierTypes.GRAI);
4624
- }
4625
- /**
4626
- * Get GIAI creator.
4627
- */
4628
- get giaiCreator() {
4629
- return this.getNonNumericIdentifierCreator(IdentifierTypes.GIAI);
4630
- }
4631
- /**
4632
- * Get GSRN creator.
4633
- */
4634
- get gsrnCreator() {
4635
- return this.getNonGTINNumericIdentifierCreator(IdentifierTypes.GSRN);
4636
- }
4637
- /**
4638
- * Get GDTI creator.
4639
- */
4640
- get gdtiCreator() {
4641
- return this.getSerializableNumericIdentifierCreator(IdentifierTypes.GDTI);
4642
- }
4643
- /**
4644
- * Get GINC creator.
4645
- */
4646
- get gincCreator() {
4647
- return this.getNonNumericIdentifierCreator(IdentifierTypes.GINC);
4648
- }
4649
- /**
4650
- * Get GSIN creator.
4651
- */
4652
- get gsinCreator() {
4653
- return this.getNonGTINNumericIdentifierCreator(IdentifierTypes.GSIN);
4654
- }
4655
- /**
4656
- * Get GCN creator.
4657
- */
4658
- get gcnCreator() {
4659
- return this.getSerializableNumericIdentifierCreator(IdentifierTypes.GCN);
4660
- }
4661
- /**
4662
- * Get CPID creator.
4663
- */
4664
- get cpidCreator() {
4665
- return this.getNonNumericIdentifierCreator(IdentifierTypes.CPID);
4666
- }
4667
- /**
4668
- * Get GMN creator.
4669
- */
4670
- get gmnCreator() {
4671
- return this.getNonNumericIdentifierCreator(IdentifierTypes.GMN);
4672
- }
4673
- };
4674
- export {
4675
- AI39_CREATOR,
4676
- AI39_VALIDATOR,
4677
- AI64_VALIDATOR,
4678
- AI82_CREATOR,
4679
- AI82_VALIDATOR,
4680
- ContentCharacterSets,
4681
- GTINCreator,
4682
- GTINLevels,
4683
- GTINTypes,
4684
- GTINValidator,
4685
- GTIN_BASE_TYPES,
4686
- IdentifierDescriptors,
4687
- IdentifierTypes,
4688
- IdentifierValidators,
4689
- LeaderTypes,
4690
- NonGTINNumericIdentifierCreator,
4691
- NonGTINNumericIdentifierValidator,
4692
- NonNumericIdentifierCreator,
4693
- NonNumericIdentifierValidator,
4694
- PrefixManager,
4695
- PrefixTypes,
4696
- PrefixValidator,
4697
- SerializableNumericIdentifierCreator,
4698
- SerializableNumericIdentifierValidator,
4699
- checkCharacterPair,
4700
- checkDigit,
4701
- checkDigitSum,
4702
- gs1NS,
4703
- gs1Resources,
4704
- hasValidCheckCharacterPair,
4705
- hasValidCheckDigit,
4706
- i18nGS1Init,
4707
- i18nextGS1,
4708
- isGTINCreator,
4709
- isGTINDescriptor,
4710
- isGTINDescriptors,
4711
- isGTINValidator,
4712
- isGTINValidators,
4713
- isNonGTINNumericIdentifierCreator,
4714
- isNonGTINNumericIdentifierDescriptor,
4715
- isNonGTINNumericIdentifierValidator,
4716
- isNonNumericIdentifierCreator,
4717
- isNonNumericIdentifierDescriptor,
4718
- isNonNumericIdentifierValidator,
4719
- isNumericIdentifierCreator,
4720
- isNumericIdentifierDescriptor,
4721
- isNumericIdentifierValidator,
4722
- isSerializableNumericIdentifierCreator,
4723
- isSerializableNumericIdentifierDescriptor,
4724
- isSerializableNumericIdentifierValidator,
4725
- isValidPriceOrWeightCheckDigit,
4726
- priceOrWeightCheckDigit
4727
- };
4728
1
  /*!
4729
2
  * Copyright © 2024-2025 Dolphin Data Development Ltd. and AIDC Toolkit
4730
3
  * contributors
@@ -4741,4 +14,25 @@ export {
4741
14
  * See the License for the specific language governing permissions and
4742
15
  * limitations under the License.
4743
16
  */
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 "./content-character-set.js";
23
+ export * from "./identifier-type.js";
24
+ export * from "./numeric-identifier-type.js";
25
+ export * from "./gtin-type.js";
26
+ export * from "./descriptors.js";
27
+ export { GTINLevels, GTINValidator } from "./gtin-validator.js";
28
+ export * from "./non-gtin-numeric-identifier-validator.js";
29
+ export * from "./serializable-numeric-identifier-validator.js";
30
+ export * from "./non-numeric-identifier-validator.js";
31
+ export * from "./validators.js";
32
+ export * from "./gtin-creator.js";
33
+ export * from "./non-gtin-numeric-identifier-creator.js";
34
+ export * from "./serializable-numeric-identifier-creator.js";
35
+ export * from "./non-numeric-identifier-creator.js";
36
+ export * from "./creators.js";
37
+ export * from "./prefix-manager.js";
4744
38
  //# sourceMappingURL=index.js.map