@oj-module/cli 0.2.64 → 0.2.66

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