stripe-pwa-elements 3.0.0 → 3.0.1

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 (186) hide show
  1. package/dist/cjs/error-FFC4kSs5.js +18 -0
  2. package/dist/cjs/error-FFC4kSs5.js.map +1 -0
  3. package/dist/cjs/factory-Hsw0e7-d.js +3825 -0
  4. package/dist/cjs/factory-Hsw0e7-d.js.map +1 -0
  5. package/dist/cjs/{index-BmB5d_Yj.js → index-Ba1pBePA.js} +4 -4
  6. package/dist/cjs/{index-BmB5d_Yj.js.map → index-Ba1pBePA.js.map} +1 -1
  7. package/dist/cjs/{index-CQkz7IJv.js → index-C1haN5iF.js} +5 -2
  8. package/dist/cjs/index-C1haN5iF.js.map +1 -0
  9. package/dist/cjs/ion-icon.cjs.entry.js +1 -1
  10. package/dist/cjs/loader.cjs.js +2 -2
  11. package/dist/cjs/stripe-address-element.cjs.entry.js +288 -0
  12. package/dist/cjs/stripe-address-element.entry.cjs.js.map +1 -0
  13. package/dist/cjs/stripe-card-element-modal.cjs.entry.js +1 -1
  14. package/dist/cjs/stripe-card-element.stripe-modal.entry.cjs.js.map +1 -1
  15. package/dist/cjs/stripe-card-element_2.cjs.entry.js +48 -3278
  16. package/dist/cjs/stripe-currency-selector.cjs.entry.js +186 -0
  17. package/dist/cjs/stripe-currency-selector.entry.cjs.js.map +1 -0
  18. package/dist/cjs/stripe-elements.cjs.js +2 -2
  19. package/dist/cjs/stripe-express-checkout-element.cjs.entry.js +294 -0
  20. package/dist/cjs/stripe-express-checkout-element.entry.cjs.js.map +1 -0
  21. package/dist/cjs/stripe-link-authentication-element.cjs.entry.js +222 -0
  22. package/dist/cjs/stripe-link-authentication-element.entry.cjs.js.map +1 -0
  23. package/dist/cjs/stripe-payment-element.cjs.entry.js +469 -0
  24. package/dist/cjs/stripe-payment-element.entry.cjs.js.map +1 -0
  25. package/dist/cjs/stripe-payment-request-button.cjs.entry.js +2 -2
  26. package/dist/collection/collection-manifest.json +5 -0
  27. package/dist/collection/components/stripe-address-element/stripe-address-element.css +73 -0
  28. package/dist/collection/components/stripe-address-element/stripe-address-element.js +711 -0
  29. package/dist/collection/components/stripe-address-element/stripe-address-element.js.map +1 -0
  30. package/dist/collection/components/stripe-card-element/stripe-card-element.css +16 -8
  31. package/dist/collection/components/stripe-card-element/stripe-card-element.js +32 -8
  32. package/dist/collection/components/stripe-card-element/stripe-card-element.js.map +1 -1
  33. package/dist/collection/components/stripe-currency-selector/stripe-currency-selector.css +44 -0
  34. package/dist/collection/components/stripe-currency-selector/stripe-currency-selector.js +477 -0
  35. package/dist/collection/components/stripe-currency-selector/stripe-currency-selector.js.map +1 -0
  36. package/dist/collection/components/stripe-express-checkout-element/stripe-express-checkout-element.css +36 -0
  37. package/dist/collection/components/stripe-express-checkout-element/stripe-express-checkout-element.js +787 -0
  38. package/dist/collection/components/stripe-express-checkout-element/stripe-express-checkout-element.js.map +1 -0
  39. package/dist/collection/components/stripe-link-authentication-element/stripe-link-authentication-element.css +49 -0
  40. package/dist/collection/components/stripe-link-authentication-element/stripe-link-authentication-element.js +545 -0
  41. package/dist/collection/components/stripe-link-authentication-element/stripe-link-authentication-element.js.map +1 -0
  42. package/dist/collection/components/stripe-modal/stripe-modal.css +16 -14
  43. package/dist/collection/components/stripe-modal/stripe-modal.js +3 -2
  44. package/dist/collection/components/stripe-modal/stripe-modal.js.map +1 -1
  45. package/dist/collection/components/stripe-payment-element/stripe-payment-element.css +78 -0
  46. package/dist/collection/components/stripe-payment-element/stripe-payment-element.js +979 -0
  47. package/dist/collection/components/stripe-payment-element/stripe-payment-element.js.map +1 -0
  48. package/dist/collection/interfaces.js.map +1 -1
  49. package/dist/collection/services/address-element-manager.js +83 -0
  50. package/dist/collection/services/address-element-manager.js.map +1 -0
  51. package/dist/collection/services/card-element-manager.js +4 -34
  52. package/dist/collection/services/card-element-manager.js.map +1 -1
  53. package/dist/collection/services/currency-selector-element-manager.js +92 -0
  54. package/dist/collection/services/currency-selector-element-manager.js.map +1 -0
  55. package/dist/collection/services/express-checkout-element-manager.js +131 -0
  56. package/dist/collection/services/express-checkout-element-manager.js.map +1 -0
  57. package/dist/collection/services/factory.js +40 -0
  58. package/dist/collection/services/factory.js.map +1 -1
  59. package/dist/collection/services/interfaces.js.map +1 -1
  60. package/dist/collection/services/link-authentication-element-manager.js +93 -0
  61. package/dist/collection/services/link-authentication-element-manager.js.map +1 -0
  62. package/dist/collection/services/payment-element-manager.js +95 -0
  63. package/dist/collection/services/payment-element-manager.js.map +1 -0
  64. package/dist/collection/services/stripe-service.js +51 -2
  65. package/dist/collection/services/stripe-service.js.map +1 -1
  66. package/dist/collection/utils/element-finder.js +32 -0
  67. package/dist/collection/utils/element-finder.js.map +1 -0
  68. package/dist/collection/utils/error.js.map +1 -1
  69. package/dist/collection/utils/i18n.js +2 -2
  70. package/dist/collection/utils/i18n.js.map +1 -1
  71. package/dist/collection/utils/platform.js.map +1 -1
  72. package/dist/collection/utils/utils.js +1 -1
  73. package/dist/collection/utils/utils.js.map +1 -1
  74. package/dist/components/error.js +16 -0
  75. package/dist/components/error.js.map +1 -0
  76. package/dist/components/factory.js +3736 -0
  77. package/dist/components/factory.js.map +1 -0
  78. package/dist/{esm/index-C5QyifTT.js → components/index2.js} +4 -4
  79. package/dist/components/index2.js.map +1 -0
  80. package/dist/components/stripe-address-element.d.ts +11 -0
  81. package/dist/components/stripe-address-element.js +327 -0
  82. package/dist/components/stripe-address-element.js.map +1 -0
  83. package/dist/components/stripe-card-element2.js +37 -3183
  84. package/dist/components/stripe-card-element2.js.map +1 -1
  85. package/dist/components/stripe-currency-selector.d.ts +11 -0
  86. package/dist/components/stripe-currency-selector.js +218 -0
  87. package/dist/components/stripe-currency-selector.js.map +1 -0
  88. package/dist/components/stripe-express-checkout-element.d.ts +11 -0
  89. package/dist/components/stripe-express-checkout-element.js +332 -0
  90. package/dist/components/stripe-express-checkout-element.js.map +1 -0
  91. package/dist/components/stripe-link-authentication-element.d.ts +11 -0
  92. package/dist/components/stripe-link-authentication-element.js +256 -0
  93. package/dist/components/stripe-link-authentication-element.js.map +1 -0
  94. package/dist/components/stripe-modal2.js +4 -3
  95. package/dist/components/stripe-modal2.js.map +1 -1
  96. package/dist/components/stripe-payment-element.d.ts +11 -0
  97. package/dist/components/stripe-payment-element.js +510 -0
  98. package/dist/components/stripe-payment-element.js.map +1 -0
  99. package/dist/components/stripe-payment-request-button2.js +2 -189
  100. package/dist/components/stripe-payment-request-button2.js.map +1 -1
  101. package/dist/components/utils.js.map +1 -1
  102. package/dist/esm/error-XRfh5Wrs.js +16 -0
  103. package/dist/esm/error-XRfh5Wrs.js.map +1 -0
  104. package/dist/esm/factory-Li_TGt9P.js +3821 -0
  105. package/dist/esm/factory-Li_TGt9P.js.map +1 -0
  106. package/dist/esm/index-BHDCxQOb.js +192 -0
  107. package/dist/esm/{index-C5QyifTT.js.map → index-BHDCxQOb.js.map} +1 -1
  108. package/dist/esm/{index-DB2hiILr.js → index-Dkis4t79.js} +5 -2
  109. package/dist/esm/index-Dkis4t79.js.map +1 -0
  110. package/dist/esm/ion-icon.entry.js +1 -1
  111. package/dist/esm/loader.js +3 -3
  112. package/dist/esm/stripe-address-element.entry.js +286 -0
  113. package/dist/esm/stripe-address-element.entry.js.map +1 -0
  114. package/dist/esm/stripe-card-element-modal.entry.js +1 -1
  115. package/dist/esm/stripe-card-element.stripe-modal.entry.js.map +1 -1
  116. package/dist/esm/stripe-card-element_2.entry.js +41 -3271
  117. package/dist/esm/stripe-currency-selector.entry.js +184 -0
  118. package/dist/esm/stripe-currency-selector.entry.js.map +1 -0
  119. package/dist/esm/stripe-elements.js +3 -3
  120. package/dist/esm/stripe-express-checkout-element.entry.js +292 -0
  121. package/dist/esm/stripe-express-checkout-element.entry.js.map +1 -0
  122. package/dist/esm/stripe-link-authentication-element.entry.js +220 -0
  123. package/dist/esm/stripe-link-authentication-element.entry.js.map +1 -0
  124. package/dist/esm/stripe-payment-element.entry.js +467 -0
  125. package/dist/esm/stripe-payment-element.entry.js.map +1 -0
  126. package/dist/esm/stripe-payment-request-button.entry.js +2 -2
  127. package/dist/stripe-elements/{p-b598431f.entry.js → p-01d63033.entry.js} +2 -2
  128. package/dist/stripe-elements/p-1b8f9c7f.entry.js +2 -0
  129. package/dist/stripe-elements/p-1b8f9c7f.entry.js.map +1 -0
  130. package/dist/stripe-elements/{p-5beb3870.entry.js → p-37008853.entry.js} +2 -2
  131. package/dist/stripe-elements/p-5d152193.entry.js +2 -0
  132. package/dist/stripe-elements/p-5d152193.entry.js.map +1 -0
  133. package/dist/stripe-elements/p-623f13e6.entry.js +2 -0
  134. package/dist/stripe-elements/p-623f13e6.entry.js.map +1 -0
  135. package/dist/stripe-elements/p-809c9f2f.entry.js +2 -0
  136. package/dist/stripe-elements/p-809c9f2f.entry.js.map +1 -0
  137. package/dist/stripe-elements/{p-C5QyifTT.js → p-BHDCxQOb.js} +2 -2
  138. package/dist/stripe-elements/{p-C5QyifTT.js.map → p-BHDCxQOb.js.map} +1 -1
  139. package/dist/stripe-elements/p-Dkis4t79.js +3 -0
  140. package/dist/stripe-elements/p-Dkis4t79.js.map +1 -0
  141. package/dist/stripe-elements/p-WnA32N4v.js +2 -0
  142. package/dist/stripe-elements/p-WnA32N4v.js.map +1 -0
  143. package/dist/stripe-elements/p-XRfh5Wrs.js +2 -0
  144. package/dist/stripe-elements/p-XRfh5Wrs.js.map +1 -0
  145. package/dist/stripe-elements/p-ba41e196.entry.js +2 -0
  146. package/dist/stripe-elements/p-ba41e196.entry.js.map +1 -0
  147. package/dist/stripe-elements/{p-bb923a08.entry.js → p-bb1bc49a.entry.js} +2 -2
  148. package/dist/stripe-elements/p-f21ea941.entry.js +2 -0
  149. package/dist/stripe-elements/p-f21ea941.entry.js.map +1 -0
  150. package/dist/stripe-elements/stripe-address-element.entry.esm.js.map +1 -0
  151. package/dist/stripe-elements/stripe-card-element.stripe-modal.entry.esm.js.map +1 -1
  152. package/dist/stripe-elements/stripe-currency-selector.entry.esm.js.map +1 -0
  153. package/dist/stripe-elements/stripe-elements.esm.js +1 -1
  154. package/dist/stripe-elements/stripe-express-checkout-element.entry.esm.js.map +1 -0
  155. package/dist/stripe-elements/stripe-link-authentication-element.entry.esm.js.map +1 -0
  156. package/dist/stripe-elements/stripe-payment-element.entry.esm.js.map +1 -0
  157. package/dist/types/components/stripe-address-element/stripe-address-element.d.ts +195 -0
  158. package/dist/types/components/stripe-card-element/stripe-card-element.d.ts +3 -1
  159. package/dist/types/components/stripe-currency-selector/stripe-currency-selector.d.ts +127 -0
  160. package/dist/types/components/stripe-express-checkout-element/stripe-express-checkout-element.d.ts +232 -0
  161. package/dist/types/components/stripe-link-authentication-element/stripe-link-authentication-element.d.ts +143 -0
  162. package/dist/types/components/stripe-payment-element/stripe-payment-element.d.ts +295 -0
  163. package/dist/types/components.d.ts +836 -6
  164. package/dist/types/interfaces.d.ts +23 -1
  165. package/dist/types/services/address-element-manager.d.ts +44 -0
  166. package/dist/types/services/card-element-manager.d.ts +0 -8
  167. package/dist/types/services/currency-selector-element-manager.d.ts +45 -0
  168. package/dist/types/services/express-checkout-element-manager.d.ts +50 -0
  169. package/dist/types/services/factory.d.ts +26 -1
  170. package/dist/types/services/interfaces.d.ts +263 -2
  171. package/dist/types/services/link-authentication-element-manager.d.ts +51 -0
  172. package/dist/types/services/payment-element-manager.d.ts +46 -0
  173. package/dist/types/services/stripe-service.d.ts +17 -3
  174. package/dist/types/utils/element-finder.d.ts +8 -0
  175. package/dist/types/utils/error.d.ts +1 -1
  176. package/dist/types/utils/platform.d.ts +2 -2
  177. package/package.json +12 -3
  178. package/dist/cjs/index-CQkz7IJv.js.map +0 -1
  179. package/dist/esm/index-DB2hiILr.js.map +0 -1
  180. package/dist/stripe-elements/p-263cf51d.entry.js +0 -2
  181. package/dist/stripe-elements/p-263cf51d.entry.js.map +0 -1
  182. package/dist/stripe-elements/p-DB2hiILr.js +0 -3
  183. package/dist/stripe-elements/p-DB2hiILr.js.map +0 -1
  184. /package/dist/stripe-elements/{p-b598431f.entry.js.map → p-01d63033.entry.js.map} +0 -0
  185. /package/dist/stripe-elements/{p-5beb3870.entry.js.map → p-37008853.entry.js.map} +0 -0
  186. /package/dist/stripe-elements/{p-bb923a08.entry.js.map → p-bb1bc49a.entry.js.map} +0 -0
@@ -1,3264 +1,9 @@
1
- import { d as getRenderingRef, f as forceUpdate, r as registerInstance, c as createEvent, h, g as getElement, H as Host } from './index-DB2hiILr.js';
2
- import { l as loadStripe } from './index-C5QyifTT.js';
1
+ import { r as registerInstance, c as createEvent, h, g as getElement, H as Host } from './index-Dkis4t79.js';
2
+ import { s as serviceFactory, c as checkPlatform, i as i18n } from './factory-Li_TGt9P.js';
3
+ import { S as StripeAPIError } from './error-XRfh5Wrs.js';
4
+ import './index-BHDCxQOb.js';
3
5
 
4
- const getPlatforms = (win) => setupPlatforms(win);
5
- const setupPlatforms = (win = window) => {
6
- if (typeof win === 'undefined') {
7
- return [];
8
- }
9
- win.Ionic = win.Ionic || {};
10
- let platforms = win.Ionic.platforms;
11
- if (platforms == null) {
12
- platforms = win.Ionic.platforms = detectPlatforms(win);
13
- platforms.forEach(p => win.document.documentElement.classList.add(`plt-${p}`));
14
- }
15
- return platforms;
16
- };
17
- const detectPlatforms = (win) => Object.keys(PLATFORMS_MAP).filter(p => PLATFORMS_MAP[p](win));
18
- const isMobileWeb = (win) => isMobile(win) && !isHybrid(win);
19
- const isIpad = (win) => {
20
- // iOS 12 and below
21
- if (testUserAgent(win, /iPad/i)) {
22
- return true;
23
- }
24
- // iOS 13+
25
- if (testUserAgent(win, /Macintosh/i) && isMobile(win)) {
26
- return true;
27
- }
28
- return false;
29
- };
30
- const isIphone = (win) => testUserAgent(win, /iPhone/i);
31
- const isIOS = (win) => testUserAgent(win, /iPhone|iPod/i) || isIpad(win);
32
- const isAndroid = (win) => testUserAgent(win, /android|sink/i);
33
- const isAndroidTablet = (win) => {
34
- return isAndroid(win) && !testUserAgent(win, /mobile/i);
35
- };
36
- const isPhablet = (win) => {
37
- const width = win.innerWidth;
38
- const height = win.innerHeight;
39
- const smallest = Math.min(width, height);
40
- const largest = Math.max(width, height);
41
- return smallest > 390 && smallest < 520 && largest > 620 && largest < 800;
42
- };
43
- const isTablet = (win) => {
44
- const width = win.innerWidth;
45
- const height = win.innerHeight;
46
- const smallest = Math.min(width, height);
47
- const largest = Math.max(width, height);
48
- return isIpad(win) || isAndroidTablet(win) || (smallest > 460 && smallest < 820 && largest > 780 && largest < 1400);
49
- };
50
- const isMobile = (win) => matchMedia(win, '(any-pointer:coarse)');
51
- const isDesktop = (win) => !isMobile(win);
52
- const isHybrid = (win) => isCordova(win) || isCapacitorNative(win);
53
- const isCordova = (win) => !!(win['cordova'] || win['phonegap'] || win['PhoneGap']);
54
- const isCapacitorNative = (win) => {
55
- const capacitor = win['Capacitor'];
56
- return !!(capacitor && capacitor.isNative);
57
- };
58
- const isElectron = (win) => testUserAgent(win, /electron/i);
59
- const isPWA = (win) => !!(win.matchMedia('(display-mode: standalone)').matches || win.navigator.standalone);
60
- const testUserAgent = (win, expr) => expr.test(win.navigator.userAgent);
61
- const matchMedia = (win, query) => win.matchMedia(query).matches;
62
- const PLATFORMS_MAP = {
63
- ipad: isIpad,
64
- iphone: isIphone,
65
- ios: isIOS,
66
- android: isAndroid,
67
- phablet: isPhablet,
68
- tablet: isTablet,
69
- cordova: isCordova,
70
- capacitor: isCapacitorNative,
71
- electron: isElectron,
72
- pwa: isPWA,
73
- mobile: isMobile,
74
- mobileweb: isMobileWeb,
75
- desktop: isDesktop,
76
- hybrid: isHybrid,
77
- };
78
-
79
- const checkPlatform = () => {
80
- const device = getPlatforms();
81
- if (device.includes('ios')) {
82
- return 'ios';
83
- }
84
- if (device.includes('android')) {
85
- return 'android';
86
- }
87
- };
88
-
89
- const isString = obj => typeof obj === 'string';
90
- const defer = () => {
91
- let res;
92
- let rej;
93
- const promise = new Promise((resolve, reject) => {
94
- res = resolve;
95
- rej = reject;
96
- });
97
- promise.resolve = res;
98
- promise.reject = rej;
99
- return promise;
100
- };
101
- const makeString = object => {
102
- if (object == null) return '';
103
- return '' + object;
104
- };
105
- const copy = (a, s, t) => {
106
- a.forEach(m => {
107
- if (s[m]) t[m] = s[m];
108
- });
109
- };
110
- const lastOfPathSeparatorRegExp = /###/g;
111
- const cleanKey = key => key && key.indexOf('###') > -1 ? key.replace(lastOfPathSeparatorRegExp, '.') : key;
112
- const canNotTraverseDeeper = object => !object || isString(object);
113
- const getLastOfPath = (object, path, Empty) => {
114
- const stack = !isString(path) ? path : path.split('.');
115
- let stackIndex = 0;
116
- while (stackIndex < stack.length - 1) {
117
- if (canNotTraverseDeeper(object)) return {};
118
- const key = cleanKey(stack[stackIndex]);
119
- if (!object[key] && Empty) object[key] = new Empty();
120
- if (Object.prototype.hasOwnProperty.call(object, key)) {
121
- object = object[key];
122
- } else {
123
- object = {};
124
- }
125
- ++stackIndex;
126
- }
127
- if (canNotTraverseDeeper(object)) return {};
128
- return {
129
- obj: object,
130
- k: cleanKey(stack[stackIndex])
131
- };
132
- };
133
- const setPath = (object, path, newValue) => {
134
- const {
135
- obj,
136
- k
137
- } = getLastOfPath(object, path, Object);
138
- if (obj !== undefined || path.length === 1) {
139
- obj[k] = newValue;
140
- return;
141
- }
142
- let e = path[path.length - 1];
143
- let p = path.slice(0, path.length - 1);
144
- let last = getLastOfPath(object, p, Object);
145
- while (last.obj === undefined && p.length) {
146
- e = `${p[p.length - 1]}.${e}`;
147
- p = p.slice(0, p.length - 1);
148
- last = getLastOfPath(object, p, Object);
149
- if (last?.obj && typeof last.obj[`${last.k}.${e}`] !== 'undefined') {
150
- last.obj = undefined;
151
- }
152
- }
153
- last.obj[`${last.k}.${e}`] = newValue;
154
- };
155
- const pushPath = (object, path, newValue, concat) => {
156
- const {
157
- obj,
158
- k
159
- } = getLastOfPath(object, path, Object);
160
- obj[k] = obj[k] || [];
161
- obj[k].push(newValue);
162
- };
163
- const getPath = (object, path) => {
164
- const {
165
- obj,
166
- k
167
- } = getLastOfPath(object, path);
168
- if (!obj) return undefined;
169
- if (!Object.prototype.hasOwnProperty.call(obj, k)) return undefined;
170
- return obj[k];
171
- };
172
- const getPathWithDefaults = (data, defaultData, key) => {
173
- const value = getPath(data, key);
174
- if (value !== undefined) {
175
- return value;
176
- }
177
- return getPath(defaultData, key);
178
- };
179
- const deepExtend = (target, source, overwrite) => {
180
- for (const prop in source) {
181
- if (prop !== '__proto__' && prop !== 'constructor') {
182
- if (prop in target) {
183
- if (isString(target[prop]) || target[prop] instanceof String || isString(source[prop]) || source[prop] instanceof String) {
184
- if (overwrite) target[prop] = source[prop];
185
- } else {
186
- deepExtend(target[prop], source[prop], overwrite);
187
- }
188
- } else {
189
- target[prop] = source[prop];
190
- }
191
- }
192
- }
193
- return target;
194
- };
195
- const regexEscape = str => str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, '\\$&');
196
- var _entityMap = {
197
- '&': '&amp;',
198
- '<': '&lt;',
199
- '>': '&gt;',
200
- '"': '&quot;',
201
- "'": '&#39;',
202
- '/': '&#x2F;'
203
- };
204
- const escape = data => {
205
- if (isString(data)) {
206
- return data.replace(/[&<>"'\/]/g, s => _entityMap[s]);
207
- }
208
- return data;
209
- };
210
- class RegExpCache {
211
- constructor(capacity) {
212
- this.capacity = capacity;
213
- this.regExpMap = new Map();
214
- this.regExpQueue = [];
215
- }
216
- getRegExp(pattern) {
217
- const regExpFromCache = this.regExpMap.get(pattern);
218
- if (regExpFromCache !== undefined) {
219
- return regExpFromCache;
220
- }
221
- const regExpNew = new RegExp(pattern);
222
- if (this.regExpQueue.length === this.capacity) {
223
- this.regExpMap.delete(this.regExpQueue.shift());
224
- }
225
- this.regExpMap.set(pattern, regExpNew);
226
- this.regExpQueue.push(pattern);
227
- return regExpNew;
228
- }
229
- }
230
- const chars = [' ', ',', '?', '!', ';'];
231
- const looksLikeObjectPathRegExpCache = new RegExpCache(20);
232
- const looksLikeObjectPath = (key, nsSeparator, keySeparator) => {
233
- nsSeparator = nsSeparator || '';
234
- keySeparator = keySeparator || '';
235
- const possibleChars = chars.filter(c => nsSeparator.indexOf(c) < 0 && keySeparator.indexOf(c) < 0);
236
- if (possibleChars.length === 0) return true;
237
- const r = looksLikeObjectPathRegExpCache.getRegExp(`(${possibleChars.map(c => c === '?' ? '\\?' : c).join('|')})`);
238
- let matched = !r.test(key);
239
- if (!matched) {
240
- const ki = key.indexOf(keySeparator);
241
- if (ki > 0 && !r.test(key.substring(0, ki))) {
242
- matched = true;
243
- }
244
- }
245
- return matched;
246
- };
247
- const deepFind = (obj, path, keySeparator = '.') => {
248
- if (!obj) return undefined;
249
- if (obj[path]) {
250
- if (!Object.prototype.hasOwnProperty.call(obj, path)) return undefined;
251
- return obj[path];
252
- }
253
- const tokens = path.split(keySeparator);
254
- let current = obj;
255
- for (let i = 0; i < tokens.length;) {
256
- if (!current || typeof current !== 'object') {
257
- return undefined;
258
- }
259
- let next;
260
- let nextPath = '';
261
- for (let j = i; j < tokens.length; ++j) {
262
- if (j !== i) {
263
- nextPath += keySeparator;
264
- }
265
- nextPath += tokens[j];
266
- next = current[nextPath];
267
- if (next !== undefined) {
268
- if (['string', 'number', 'boolean'].indexOf(typeof next) > -1 && j < tokens.length - 1) {
269
- continue;
270
- }
271
- i += j - i + 1;
272
- break;
273
- }
274
- }
275
- current = next;
276
- }
277
- return current;
278
- };
279
- const getCleanedCode = code => code?.replace('_', '-');
280
-
281
- const consoleLogger = {
282
- type: 'logger',
283
- log(args) {
284
- this.output('log', args);
285
- },
286
- warn(args) {
287
- this.output('warn', args);
288
- },
289
- error(args) {
290
- this.output('error', args);
291
- },
292
- output(type, args) {
293
- console?.[type]?.apply?.(console, args);
294
- }
295
- };
296
- class Logger {
297
- constructor(concreteLogger, options = {}) {
298
- this.init(concreteLogger, options);
299
- }
300
- init(concreteLogger, options = {}) {
301
- this.prefix = options.prefix || 'i18next:';
302
- this.logger = concreteLogger || consoleLogger;
303
- this.options = options;
304
- this.debug = options.debug;
305
- }
306
- log(...args) {
307
- return this.forward(args, 'log', '', true);
308
- }
309
- warn(...args) {
310
- return this.forward(args, 'warn', '', true);
311
- }
312
- error(...args) {
313
- return this.forward(args, 'error', '');
314
- }
315
- deprecate(...args) {
316
- return this.forward(args, 'warn', 'WARNING DEPRECATED: ', true);
317
- }
318
- forward(args, lvl, prefix, debugOnly) {
319
- if (debugOnly && !this.debug) return null;
320
- if (isString(args[0])) args[0] = `${prefix}${this.prefix} ${args[0]}`;
321
- return this.logger[lvl](args);
322
- }
323
- create(moduleName) {
324
- return new Logger(this.logger, {
325
- ...{
326
- prefix: `${this.prefix}:${moduleName}:`
327
- },
328
- ...this.options
329
- });
330
- }
331
- clone(options) {
332
- options = options || this.options;
333
- options.prefix = options.prefix || this.prefix;
334
- return new Logger(this.logger, options);
335
- }
336
- }
337
- var baseLogger = new Logger();
338
-
339
- class EventEmitter {
340
- constructor() {
341
- this.observers = {};
342
- }
343
- on(events, listener) {
344
- events.split(' ').forEach(event => {
345
- if (!this.observers[event]) this.observers[event] = new Map();
346
- const numListeners = this.observers[event].get(listener) || 0;
347
- this.observers[event].set(listener, numListeners + 1);
348
- });
349
- return this;
350
- }
351
- off(event, listener) {
352
- if (!this.observers[event]) return;
353
- if (!listener) {
354
- delete this.observers[event];
355
- return;
356
- }
357
- this.observers[event].delete(listener);
358
- }
359
- emit(event, ...args) {
360
- if (this.observers[event]) {
361
- const cloned = Array.from(this.observers[event].entries());
362
- cloned.forEach(([observer, numTimesAdded]) => {
363
- for (let i = 0; i < numTimesAdded; i++) {
364
- observer(...args);
365
- }
366
- });
367
- }
368
- if (this.observers['*']) {
369
- const cloned = Array.from(this.observers['*'].entries());
370
- cloned.forEach(([observer, numTimesAdded]) => {
371
- for (let i = 0; i < numTimesAdded; i++) {
372
- observer.apply(observer, [event, ...args]);
373
- }
374
- });
375
- }
376
- }
377
- }
378
-
379
- class ResourceStore extends EventEmitter {
380
- constructor(data, options = {
381
- ns: ['translation'],
382
- defaultNS: 'translation'
383
- }) {
384
- super();
385
- this.data = data || {};
386
- this.options = options;
387
- if (this.options.keySeparator === undefined) {
388
- this.options.keySeparator = '.';
389
- }
390
- if (this.options.ignoreJSONStructure === undefined) {
391
- this.options.ignoreJSONStructure = true;
392
- }
393
- }
394
- addNamespaces(ns) {
395
- if (this.options.ns.indexOf(ns) < 0) {
396
- this.options.ns.push(ns);
397
- }
398
- }
399
- removeNamespaces(ns) {
400
- const index = this.options.ns.indexOf(ns);
401
- if (index > -1) {
402
- this.options.ns.splice(index, 1);
403
- }
404
- }
405
- getResource(lng, ns, key, options = {}) {
406
- const keySeparator = options.keySeparator !== undefined ? options.keySeparator : this.options.keySeparator;
407
- const ignoreJSONStructure = options.ignoreJSONStructure !== undefined ? options.ignoreJSONStructure : this.options.ignoreJSONStructure;
408
- let path;
409
- if (lng.indexOf('.') > -1) {
410
- path = lng.split('.');
411
- } else {
412
- path = [lng, ns];
413
- if (key) {
414
- if (Array.isArray(key)) {
415
- path.push(...key);
416
- } else if (isString(key) && keySeparator) {
417
- path.push(...key.split(keySeparator));
418
- } else {
419
- path.push(key);
420
- }
421
- }
422
- }
423
- const result = getPath(this.data, path);
424
- if (!result && !ns && !key && lng.indexOf('.') > -1) {
425
- lng = path[0];
426
- ns = path[1];
427
- key = path.slice(2).join('.');
428
- }
429
- if (result || !ignoreJSONStructure || !isString(key)) return result;
430
- return deepFind(this.data?.[lng]?.[ns], key, keySeparator);
431
- }
432
- addResource(lng, ns, key, value, options = {
433
- silent: false
434
- }) {
435
- const keySeparator = options.keySeparator !== undefined ? options.keySeparator : this.options.keySeparator;
436
- let path = [lng, ns];
437
- if (key) path = path.concat(keySeparator ? key.split(keySeparator) : key);
438
- if (lng.indexOf('.') > -1) {
439
- path = lng.split('.');
440
- value = ns;
441
- ns = path[1];
442
- }
443
- this.addNamespaces(ns);
444
- setPath(this.data, path, value);
445
- if (!options.silent) this.emit('added', lng, ns, key, value);
446
- }
447
- addResources(lng, ns, resources, options = {
448
- silent: false
449
- }) {
450
- for (const m in resources) {
451
- if (isString(resources[m]) || Array.isArray(resources[m])) this.addResource(lng, ns, m, resources[m], {
452
- silent: true
453
- });
454
- }
455
- if (!options.silent) this.emit('added', lng, ns, resources);
456
- }
457
- addResourceBundle(lng, ns, resources, deep, overwrite, options = {
458
- silent: false,
459
- skipCopy: false
460
- }) {
461
- let path = [lng, ns];
462
- if (lng.indexOf('.') > -1) {
463
- path = lng.split('.');
464
- deep = resources;
465
- resources = ns;
466
- ns = path[1];
467
- }
468
- this.addNamespaces(ns);
469
- let pack = getPath(this.data, path) || {};
470
- if (!options.skipCopy) resources = JSON.parse(JSON.stringify(resources));
471
- if (deep) {
472
- deepExtend(pack, resources, overwrite);
473
- } else {
474
- pack = {
475
- ...pack,
476
- ...resources
477
- };
478
- }
479
- setPath(this.data, path, pack);
480
- if (!options.silent) this.emit('added', lng, ns, resources);
481
- }
482
- removeResourceBundle(lng, ns) {
483
- if (this.hasResourceBundle(lng, ns)) {
484
- delete this.data[lng][ns];
485
- }
486
- this.removeNamespaces(ns);
487
- this.emit('removed', lng, ns);
488
- }
489
- hasResourceBundle(lng, ns) {
490
- return this.getResource(lng, ns) !== undefined;
491
- }
492
- getResourceBundle(lng, ns) {
493
- if (!ns) ns = this.options.defaultNS;
494
- return this.getResource(lng, ns);
495
- }
496
- getDataByLanguage(lng) {
497
- return this.data[lng];
498
- }
499
- hasLanguageSomeTranslations(lng) {
500
- const data = this.getDataByLanguage(lng);
501
- const n = data && Object.keys(data) || [];
502
- return !!n.find(v => data[v] && Object.keys(data[v]).length > 0);
503
- }
504
- toJSON() {
505
- return this.data;
506
- }
507
- }
508
-
509
- var postProcessor = {
510
- processors: {},
511
- addPostProcessor(module) {
512
- this.processors[module.name] = module;
513
- },
514
- handle(processors, value, key, options, translator) {
515
- processors.forEach(processor => {
516
- value = this.processors[processor]?.process(value, key, options, translator) ?? value;
517
- });
518
- return value;
519
- }
520
- };
521
-
522
- const PATH_KEY = Symbol('i18next/PATH_KEY');
523
- function createProxy() {
524
- const state = [];
525
- const handler = Object.create(null);
526
- let proxy;
527
- handler.get = (target, key) => {
528
- proxy?.revoke?.();
529
- if (key === PATH_KEY) return state;
530
- state.push(key);
531
- proxy = Proxy.revocable(target, handler);
532
- return proxy.proxy;
533
- };
534
- return Proxy.revocable(Object.create(null), handler).proxy;
535
- }
536
- function keysFromSelector(selector, opts) {
537
- const {
538
- [PATH_KEY]: path
539
- } = selector(createProxy());
540
- return path.join(opts?.keySeparator ?? '.');
541
- }
542
-
543
- const checkedLoadedFor = {};
544
- const shouldHandleAsObject = res => !isString(res) && typeof res !== 'boolean' && typeof res !== 'number';
545
- class Translator extends EventEmitter {
546
- constructor(services, options = {}) {
547
- super();
548
- copy(['resourceStore', 'languageUtils', 'pluralResolver', 'interpolator', 'backendConnector', 'i18nFormat', 'utils'], services, this);
549
- this.options = options;
550
- if (this.options.keySeparator === undefined) {
551
- this.options.keySeparator = '.';
552
- }
553
- this.logger = baseLogger.create('translator');
554
- }
555
- changeLanguage(lng) {
556
- if (lng) this.language = lng;
557
- }
558
- exists(key, o = {
559
- interpolation: {}
560
- }) {
561
- const opt = {
562
- ...o
563
- };
564
- if (key == null) return false;
565
- const resolved = this.resolve(key, opt);
566
- if (resolved?.res === undefined) return false;
567
- const isObject = shouldHandleAsObject(resolved.res);
568
- if (opt.returnObjects === false && isObject) {
569
- return false;
570
- }
571
- return true;
572
- }
573
- extractFromKey(key, opt) {
574
- let nsSeparator = opt.nsSeparator !== undefined ? opt.nsSeparator : this.options.nsSeparator;
575
- if (nsSeparator === undefined) nsSeparator = ':';
576
- const keySeparator = opt.keySeparator !== undefined ? opt.keySeparator : this.options.keySeparator;
577
- let namespaces = opt.ns || this.options.defaultNS || [];
578
- const wouldCheckForNsInKey = nsSeparator && key.indexOf(nsSeparator) > -1;
579
- const seemsNaturalLanguage = !this.options.userDefinedKeySeparator && !opt.keySeparator && !this.options.userDefinedNsSeparator && !opt.nsSeparator && !looksLikeObjectPath(key, nsSeparator, keySeparator);
580
- if (wouldCheckForNsInKey && !seemsNaturalLanguage) {
581
- const m = key.match(this.interpolator.nestingRegexp);
582
- if (m && m.length > 0) {
583
- return {
584
- key,
585
- namespaces: isString(namespaces) ? [namespaces] : namespaces
586
- };
587
- }
588
- const parts = key.split(nsSeparator);
589
- if (nsSeparator !== keySeparator || nsSeparator === keySeparator && this.options.ns.indexOf(parts[0]) > -1) namespaces = parts.shift();
590
- key = parts.join(keySeparator);
591
- }
592
- return {
593
- key,
594
- namespaces: isString(namespaces) ? [namespaces] : namespaces
595
- };
596
- }
597
- translate(keys, o, lastKey) {
598
- let opt = typeof o === 'object' ? {
599
- ...o
600
- } : o;
601
- if (typeof opt !== 'object' && this.options.overloadTranslationOptionHandler) {
602
- opt = this.options.overloadTranslationOptionHandler(arguments);
603
- }
604
- if (typeof opt === 'object') opt = {
605
- ...opt
606
- };
607
- if (!opt) opt = {};
608
- if (keys == null) return '';
609
- if (typeof keys === 'function') keys = keysFromSelector(keys, {
610
- ...this.options,
611
- ...opt
612
- });
613
- if (!Array.isArray(keys)) keys = [String(keys)];
614
- const returnDetails = opt.returnDetails !== undefined ? opt.returnDetails : this.options.returnDetails;
615
- const keySeparator = opt.keySeparator !== undefined ? opt.keySeparator : this.options.keySeparator;
616
- const {
617
- key,
618
- namespaces
619
- } = this.extractFromKey(keys[keys.length - 1], opt);
620
- const namespace = namespaces[namespaces.length - 1];
621
- let nsSeparator = opt.nsSeparator !== undefined ? opt.nsSeparator : this.options.nsSeparator;
622
- if (nsSeparator === undefined) nsSeparator = ':';
623
- const lng = opt.lng || this.language;
624
- const appendNamespaceToCIMode = opt.appendNamespaceToCIMode || this.options.appendNamespaceToCIMode;
625
- if (lng?.toLowerCase() === 'cimode') {
626
- if (appendNamespaceToCIMode) {
627
- if (returnDetails) {
628
- return {
629
- res: `${namespace}${nsSeparator}${key}`,
630
- usedKey: key,
631
- exactUsedKey: key,
632
- usedLng: lng,
633
- usedNS: namespace,
634
- usedParams: this.getUsedParamsDetails(opt)
635
- };
636
- }
637
- return `${namespace}${nsSeparator}${key}`;
638
- }
639
- if (returnDetails) {
640
- return {
641
- res: key,
642
- usedKey: key,
643
- exactUsedKey: key,
644
- usedLng: lng,
645
- usedNS: namespace,
646
- usedParams: this.getUsedParamsDetails(opt)
647
- };
648
- }
649
- return key;
650
- }
651
- const resolved = this.resolve(keys, opt);
652
- let res = resolved?.res;
653
- const resUsedKey = resolved?.usedKey || key;
654
- const resExactUsedKey = resolved?.exactUsedKey || key;
655
- const noObject = ['[object Number]', '[object Function]', '[object RegExp]'];
656
- const joinArrays = opt.joinArrays !== undefined ? opt.joinArrays : this.options.joinArrays;
657
- const handleAsObjectInI18nFormat = !this.i18nFormat || this.i18nFormat.handleAsObject;
658
- const needsPluralHandling = opt.count !== undefined && !isString(opt.count);
659
- const hasDefaultValue = Translator.hasDefaultValue(opt);
660
- const defaultValueSuffix = needsPluralHandling ? this.pluralResolver.getSuffix(lng, opt.count, opt) : '';
661
- const defaultValueSuffixOrdinalFallback = opt.ordinal && needsPluralHandling ? this.pluralResolver.getSuffix(lng, opt.count, {
662
- ordinal: false
663
- }) : '';
664
- const needsZeroSuffixLookup = needsPluralHandling && !opt.ordinal && opt.count === 0;
665
- const defaultValue = needsZeroSuffixLookup && opt[`defaultValue${this.options.pluralSeparator}zero`] || opt[`defaultValue${defaultValueSuffix}`] || opt[`defaultValue${defaultValueSuffixOrdinalFallback}`] || opt.defaultValue;
666
- let resForObjHndl = res;
667
- if (handleAsObjectInI18nFormat && !res && hasDefaultValue) {
668
- resForObjHndl = defaultValue;
669
- }
670
- const handleAsObject = shouldHandleAsObject(resForObjHndl);
671
- const resType = Object.prototype.toString.apply(resForObjHndl);
672
- if (handleAsObjectInI18nFormat && resForObjHndl && handleAsObject && noObject.indexOf(resType) < 0 && !(isString(joinArrays) && Array.isArray(resForObjHndl))) {
673
- if (!opt.returnObjects && !this.options.returnObjects) {
674
- if (!this.options.returnedObjectHandler) {
675
- this.logger.warn('accessing an object - but returnObjects options is not enabled!');
676
- }
677
- const r = this.options.returnedObjectHandler ? this.options.returnedObjectHandler(resUsedKey, resForObjHndl, {
678
- ...opt,
679
- ns: namespaces
680
- }) : `key '${key} (${this.language})' returned an object instead of string.`;
681
- if (returnDetails) {
682
- resolved.res = r;
683
- resolved.usedParams = this.getUsedParamsDetails(opt);
684
- return resolved;
685
- }
686
- return r;
687
- }
688
- if (keySeparator) {
689
- const resTypeIsArray = Array.isArray(resForObjHndl);
690
- const copy = resTypeIsArray ? [] : {};
691
- const newKeyToUse = resTypeIsArray ? resExactUsedKey : resUsedKey;
692
- for (const m in resForObjHndl) {
693
- if (Object.prototype.hasOwnProperty.call(resForObjHndl, m)) {
694
- const deepKey = `${newKeyToUse}${keySeparator}${m}`;
695
- if (hasDefaultValue && !res) {
696
- copy[m] = this.translate(deepKey, {
697
- ...opt,
698
- defaultValue: shouldHandleAsObject(defaultValue) ? defaultValue[m] : undefined,
699
- ...{
700
- joinArrays: false,
701
- ns: namespaces
702
- }
703
- });
704
- } else {
705
- copy[m] = this.translate(deepKey, {
706
- ...opt,
707
- ...{
708
- joinArrays: false,
709
- ns: namespaces
710
- }
711
- });
712
- }
713
- if (copy[m] === deepKey) copy[m] = resForObjHndl[m];
714
- }
715
- }
716
- res = copy;
717
- }
718
- } else if (handleAsObjectInI18nFormat && isString(joinArrays) && Array.isArray(res)) {
719
- res = res.join(joinArrays);
720
- if (res) res = this.extendTranslation(res, keys, opt, lastKey);
721
- } else {
722
- let usedDefault = false;
723
- let usedKey = false;
724
- if (!this.isValidLookup(res) && hasDefaultValue) {
725
- usedDefault = true;
726
- res = defaultValue;
727
- }
728
- if (!this.isValidLookup(res)) {
729
- usedKey = true;
730
- res = key;
731
- }
732
- const missingKeyNoValueFallbackToKey = opt.missingKeyNoValueFallbackToKey || this.options.missingKeyNoValueFallbackToKey;
733
- const resForMissing = missingKeyNoValueFallbackToKey && usedKey ? undefined : res;
734
- const updateMissing = hasDefaultValue && defaultValue !== res && this.options.updateMissing;
735
- if (usedKey || usedDefault || updateMissing) {
736
- this.logger.log(updateMissing ? 'updateKey' : 'missingKey', lng, namespace, key, updateMissing ? defaultValue : res);
737
- if (keySeparator) {
738
- const fk = this.resolve(key, {
739
- ...opt,
740
- keySeparator: false
741
- });
742
- 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.');
743
- }
744
- let lngs = [];
745
- const fallbackLngs = this.languageUtils.getFallbackCodes(this.options.fallbackLng, opt.lng || this.language);
746
- if (this.options.saveMissingTo === 'fallback' && fallbackLngs && fallbackLngs[0]) {
747
- for (let i = 0; i < fallbackLngs.length; i++) {
748
- lngs.push(fallbackLngs[i]);
749
- }
750
- } else if (this.options.saveMissingTo === 'all') {
751
- lngs = this.languageUtils.toResolveHierarchy(opt.lng || this.language);
752
- } else {
753
- lngs.push(opt.lng || this.language);
754
- }
755
- const send = (l, k, specificDefaultValue) => {
756
- const defaultForMissing = hasDefaultValue && specificDefaultValue !== res ? specificDefaultValue : resForMissing;
757
- if (this.options.missingKeyHandler) {
758
- this.options.missingKeyHandler(l, namespace, k, defaultForMissing, updateMissing, opt);
759
- } else if (this.backendConnector?.saveMissing) {
760
- this.backendConnector.saveMissing(l, namespace, k, defaultForMissing, updateMissing, opt);
761
- }
762
- this.emit('missingKey', l, namespace, k, res);
763
- };
764
- if (this.options.saveMissing) {
765
- if (this.options.saveMissingPlurals && needsPluralHandling) {
766
- lngs.forEach(language => {
767
- const suffixes = this.pluralResolver.getSuffixes(language, opt);
768
- if (needsZeroSuffixLookup && opt[`defaultValue${this.options.pluralSeparator}zero`] && suffixes.indexOf(`${this.options.pluralSeparator}zero`) < 0) {
769
- suffixes.push(`${this.options.pluralSeparator}zero`);
770
- }
771
- suffixes.forEach(suffix => {
772
- send([language], key + suffix, opt[`defaultValue${suffix}`] || defaultValue);
773
- });
774
- });
775
- } else {
776
- send(lngs, key, defaultValue);
777
- }
778
- }
779
- }
780
- res = this.extendTranslation(res, keys, opt, resolved, lastKey);
781
- if (usedKey && res === key && this.options.appendNamespaceToMissingKey) {
782
- res = `${namespace}${nsSeparator}${key}`;
783
- }
784
- if ((usedKey || usedDefault) && this.options.parseMissingKeyHandler) {
785
- res = this.options.parseMissingKeyHandler(this.options.appendNamespaceToMissingKey ? `${namespace}${nsSeparator}${key}` : key, usedDefault ? res : undefined, opt);
786
- }
787
- }
788
- if (returnDetails) {
789
- resolved.res = res;
790
- resolved.usedParams = this.getUsedParamsDetails(opt);
791
- return resolved;
792
- }
793
- return res;
794
- }
795
- extendTranslation(res, key, opt, resolved, lastKey) {
796
- if (this.i18nFormat?.parse) {
797
- res = this.i18nFormat.parse(res, {
798
- ...this.options.interpolation.defaultVariables,
799
- ...opt
800
- }, opt.lng || this.language || resolved.usedLng, resolved.usedNS, resolved.usedKey, {
801
- resolved
802
- });
803
- } else if (!opt.skipInterpolation) {
804
- if (opt.interpolation) this.interpolator.init({
805
- ...opt,
806
- ...{
807
- interpolation: {
808
- ...this.options.interpolation,
809
- ...opt.interpolation
810
- }
811
- }
812
- });
813
- const skipOnVariables = isString(res) && (opt?.interpolation?.skipOnVariables !== undefined ? opt.interpolation.skipOnVariables : this.options.interpolation.skipOnVariables);
814
- let nestBef;
815
- if (skipOnVariables) {
816
- const nb = res.match(this.interpolator.nestingRegexp);
817
- nestBef = nb && nb.length;
818
- }
819
- let data = opt.replace && !isString(opt.replace) ? opt.replace : opt;
820
- if (this.options.interpolation.defaultVariables) data = {
821
- ...this.options.interpolation.defaultVariables,
822
- ...data
823
- };
824
- res = this.interpolator.interpolate(res, data, opt.lng || this.language || resolved.usedLng, opt);
825
- if (skipOnVariables) {
826
- const na = res.match(this.interpolator.nestingRegexp);
827
- const nestAft = na && na.length;
828
- if (nestBef < nestAft) opt.nest = false;
829
- }
830
- if (!opt.lng && resolved && resolved.res) opt.lng = this.language || resolved.usedLng;
831
- if (opt.nest !== false) res = this.interpolator.nest(res, (...args) => {
832
- if (lastKey?.[0] === args[0] && !opt.context) {
833
- this.logger.warn(`It seems you are nesting recursively key: ${args[0]} in key: ${key[0]}`);
834
- return null;
835
- }
836
- return this.translate(...args, key);
837
- }, opt);
838
- if (opt.interpolation) this.interpolator.reset();
839
- }
840
- const postProcess = opt.postProcess || this.options.postProcess;
841
- const postProcessorNames = isString(postProcess) ? [postProcess] : postProcess;
842
- if (res != null && postProcessorNames?.length && opt.applyPostProcessor !== false) {
843
- res = postProcessor.handle(postProcessorNames, res, key, this.options && this.options.postProcessPassResolved ? {
844
- i18nResolved: {
845
- ...resolved,
846
- usedParams: this.getUsedParamsDetails(opt)
847
- },
848
- ...opt
849
- } : opt, this);
850
- }
851
- return res;
852
- }
853
- resolve(keys, opt = {}) {
854
- let found;
855
- let usedKey;
856
- let exactUsedKey;
857
- let usedLng;
858
- let usedNS;
859
- if (isString(keys)) keys = [keys];
860
- keys.forEach(k => {
861
- if (this.isValidLookup(found)) return;
862
- const extracted = this.extractFromKey(k, opt);
863
- const key = extracted.key;
864
- usedKey = key;
865
- let namespaces = extracted.namespaces;
866
- if (this.options.fallbackNS) namespaces = namespaces.concat(this.options.fallbackNS);
867
- const needsPluralHandling = opt.count !== undefined && !isString(opt.count);
868
- const needsZeroSuffixLookup = needsPluralHandling && !opt.ordinal && opt.count === 0;
869
- const needsContextHandling = opt.context !== undefined && (isString(opt.context) || typeof opt.context === 'number') && opt.context !== '';
870
- const codes = opt.lngs ? opt.lngs : this.languageUtils.toResolveHierarchy(opt.lng || this.language, opt.fallbackLng);
871
- namespaces.forEach(ns => {
872
- if (this.isValidLookup(found)) return;
873
- usedNS = ns;
874
- if (!checkedLoadedFor[`${codes[0]}-${ns}`] && this.utils?.hasLoadedNamespace && !this.utils?.hasLoadedNamespace(usedNS)) {
875
- checkedLoadedFor[`${codes[0]}-${ns}`] = true;
876
- 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!!!');
877
- }
878
- codes.forEach(code => {
879
- if (this.isValidLookup(found)) return;
880
- usedLng = code;
881
- const finalKeys = [key];
882
- if (this.i18nFormat?.addLookupKeys) {
883
- this.i18nFormat.addLookupKeys(finalKeys, key, code, ns, opt);
884
- } else {
885
- let pluralSuffix;
886
- if (needsPluralHandling) pluralSuffix = this.pluralResolver.getSuffix(code, opt.count, opt);
887
- const zeroSuffix = `${this.options.pluralSeparator}zero`;
888
- const ordinalPrefix = `${this.options.pluralSeparator}ordinal${this.options.pluralSeparator}`;
889
- if (needsPluralHandling) {
890
- if (opt.ordinal && pluralSuffix.indexOf(ordinalPrefix) === 0) {
891
- finalKeys.push(key + pluralSuffix.replace(ordinalPrefix, this.options.pluralSeparator));
892
- }
893
- finalKeys.push(key + pluralSuffix);
894
- if (needsZeroSuffixLookup) {
895
- finalKeys.push(key + zeroSuffix);
896
- }
897
- }
898
- if (needsContextHandling) {
899
- const contextKey = `${key}${this.options.contextSeparator || '_'}${opt.context}`;
900
- finalKeys.push(contextKey);
901
- if (needsPluralHandling) {
902
- if (opt.ordinal && pluralSuffix.indexOf(ordinalPrefix) === 0) {
903
- finalKeys.push(contextKey + pluralSuffix.replace(ordinalPrefix, this.options.pluralSeparator));
904
- }
905
- finalKeys.push(contextKey + pluralSuffix);
906
- if (needsZeroSuffixLookup) {
907
- finalKeys.push(contextKey + zeroSuffix);
908
- }
909
- }
910
- }
911
- }
912
- let possibleKey;
913
- while (possibleKey = finalKeys.pop()) {
914
- if (!this.isValidLookup(found)) {
915
- exactUsedKey = possibleKey;
916
- found = this.getResource(code, ns, possibleKey, opt);
917
- }
918
- }
919
- });
920
- });
921
- });
922
- return {
923
- res: found,
924
- usedKey,
925
- exactUsedKey,
926
- usedLng,
927
- usedNS
928
- };
929
- }
930
- isValidLookup(res) {
931
- return res !== undefined && !(!this.options.returnNull && res === null) && !(!this.options.returnEmptyString && res === '');
932
- }
933
- getResource(code, ns, key, options = {}) {
934
- if (this.i18nFormat?.getResource) return this.i18nFormat.getResource(code, ns, key, options);
935
- return this.resourceStore.getResource(code, ns, key, options);
936
- }
937
- getUsedParamsDetails(options = {}) {
938
- const optionsKeys = ['defaultValue', 'ordinal', 'context', 'replace', 'lng', 'lngs', 'fallbackLng', 'ns', 'keySeparator', 'nsSeparator', 'returnObjects', 'returnDetails', 'joinArrays', 'postProcess', 'interpolation'];
939
- const useOptionsReplaceForData = options.replace && !isString(options.replace);
940
- let data = useOptionsReplaceForData ? options.replace : options;
941
- if (useOptionsReplaceForData && typeof options.count !== 'undefined') {
942
- data.count = options.count;
943
- }
944
- if (this.options.interpolation.defaultVariables) {
945
- data = {
946
- ...this.options.interpolation.defaultVariables,
947
- ...data
948
- };
949
- }
950
- if (!useOptionsReplaceForData) {
951
- data = {
952
- ...data
953
- };
954
- for (const key of optionsKeys) {
955
- delete data[key];
956
- }
957
- }
958
- return data;
959
- }
960
- static hasDefaultValue(options) {
961
- const prefix = 'defaultValue';
962
- for (const option in options) {
963
- if (Object.prototype.hasOwnProperty.call(options, option) && prefix === option.substring(0, prefix.length) && undefined !== options[option]) {
964
- return true;
965
- }
966
- }
967
- return false;
968
- }
969
- }
970
-
971
- class LanguageUtil {
972
- constructor(options) {
973
- this.options = options;
974
- this.supportedLngs = this.options.supportedLngs || false;
975
- this.logger = baseLogger.create('languageUtils');
976
- }
977
- getScriptPartFromCode(code) {
978
- code = getCleanedCode(code);
979
- if (!code || code.indexOf('-') < 0) return null;
980
- const p = code.split('-');
981
- if (p.length === 2) return null;
982
- p.pop();
983
- if (p[p.length - 1].toLowerCase() === 'x') return null;
984
- return this.formatLanguageCode(p.join('-'));
985
- }
986
- getLanguagePartFromCode(code) {
987
- code = getCleanedCode(code);
988
- if (!code || code.indexOf('-') < 0) return code;
989
- const p = code.split('-');
990
- return this.formatLanguageCode(p[0]);
991
- }
992
- formatLanguageCode(code) {
993
- if (isString(code) && code.indexOf('-') > -1) {
994
- let formattedCode;
995
- try {
996
- formattedCode = Intl.getCanonicalLocales(code)[0];
997
- } catch (e) {}
998
- if (formattedCode && this.options.lowerCaseLng) {
999
- formattedCode = formattedCode.toLowerCase();
1000
- }
1001
- if (formattedCode) return formattedCode;
1002
- if (this.options.lowerCaseLng) {
1003
- return code.toLowerCase();
1004
- }
1005
- return code;
1006
- }
1007
- return this.options.cleanCode || this.options.lowerCaseLng ? code.toLowerCase() : code;
1008
- }
1009
- isSupportedCode(code) {
1010
- if (this.options.load === 'languageOnly' || this.options.nonExplicitSupportedLngs) {
1011
- code = this.getLanguagePartFromCode(code);
1012
- }
1013
- return !this.supportedLngs || !this.supportedLngs.length || this.supportedLngs.indexOf(code) > -1;
1014
- }
1015
- getBestMatchFromCodes(codes) {
1016
- if (!codes) return null;
1017
- let found;
1018
- codes.forEach(code => {
1019
- if (found) return;
1020
- const cleanedLng = this.formatLanguageCode(code);
1021
- if (!this.options.supportedLngs || this.isSupportedCode(cleanedLng)) found = cleanedLng;
1022
- });
1023
- if (!found && this.options.supportedLngs) {
1024
- codes.forEach(code => {
1025
- if (found) return;
1026
- const lngScOnly = this.getScriptPartFromCode(code);
1027
- if (this.isSupportedCode(lngScOnly)) return found = lngScOnly;
1028
- const lngOnly = this.getLanguagePartFromCode(code);
1029
- if (this.isSupportedCode(lngOnly)) return found = lngOnly;
1030
- found = this.options.supportedLngs.find(supportedLng => {
1031
- if (supportedLng === lngOnly) return supportedLng;
1032
- if (supportedLng.indexOf('-') < 0 && lngOnly.indexOf('-') < 0) return;
1033
- if (supportedLng.indexOf('-') > 0 && lngOnly.indexOf('-') < 0 && supportedLng.substring(0, supportedLng.indexOf('-')) === lngOnly) return supportedLng;
1034
- if (supportedLng.indexOf(lngOnly) === 0 && lngOnly.length > 1) return supportedLng;
1035
- });
1036
- });
1037
- }
1038
- if (!found) found = this.getFallbackCodes(this.options.fallbackLng)[0];
1039
- return found;
1040
- }
1041
- getFallbackCodes(fallbacks, code) {
1042
- if (!fallbacks) return [];
1043
- if (typeof fallbacks === 'function') fallbacks = fallbacks(code);
1044
- if (isString(fallbacks)) fallbacks = [fallbacks];
1045
- if (Array.isArray(fallbacks)) return fallbacks;
1046
- if (!code) return fallbacks.default || [];
1047
- let found = fallbacks[code];
1048
- if (!found) found = fallbacks[this.getScriptPartFromCode(code)];
1049
- if (!found) found = fallbacks[this.formatLanguageCode(code)];
1050
- if (!found) found = fallbacks[this.getLanguagePartFromCode(code)];
1051
- if (!found) found = fallbacks.default;
1052
- return found || [];
1053
- }
1054
- toResolveHierarchy(code, fallbackCode) {
1055
- const fallbackCodes = this.getFallbackCodes((fallbackCode === false ? [] : fallbackCode) || this.options.fallbackLng || [], code);
1056
- const codes = [];
1057
- const addCode = c => {
1058
- if (!c) return;
1059
- if (this.isSupportedCode(c)) {
1060
- codes.push(c);
1061
- } else {
1062
- this.logger.warn(`rejecting language code not found in supportedLngs: ${c}`);
1063
- }
1064
- };
1065
- if (isString(code) && (code.indexOf('-') > -1 || code.indexOf('_') > -1)) {
1066
- if (this.options.load !== 'languageOnly') addCode(this.formatLanguageCode(code));
1067
- if (this.options.load !== 'languageOnly' && this.options.load !== 'currentOnly') addCode(this.getScriptPartFromCode(code));
1068
- if (this.options.load !== 'currentOnly') addCode(this.getLanguagePartFromCode(code));
1069
- } else if (isString(code)) {
1070
- addCode(this.formatLanguageCode(code));
1071
- }
1072
- fallbackCodes.forEach(fc => {
1073
- if (codes.indexOf(fc) < 0) addCode(this.formatLanguageCode(fc));
1074
- });
1075
- return codes;
1076
- }
1077
- }
1078
-
1079
- const suffixesOrder = {
1080
- zero: 0,
1081
- one: 1,
1082
- two: 2,
1083
- few: 3,
1084
- many: 4,
1085
- other: 5
1086
- };
1087
- const dummyRule = {
1088
- select: count => count === 1 ? 'one' : 'other',
1089
- resolvedOptions: () => ({
1090
- pluralCategories: ['one', 'other']
1091
- })
1092
- };
1093
- class PluralResolver {
1094
- constructor(languageUtils, options = {}) {
1095
- this.languageUtils = languageUtils;
1096
- this.options = options;
1097
- this.logger = baseLogger.create('pluralResolver');
1098
- this.pluralRulesCache = {};
1099
- }
1100
- addRule(lng, obj) {
1101
- this.rules[lng] = obj;
1102
- }
1103
- clearCache() {
1104
- this.pluralRulesCache = {};
1105
- }
1106
- getRule(code, options = {}) {
1107
- const cleanedCode = getCleanedCode(code === 'dev' ? 'en' : code);
1108
- const type = options.ordinal ? 'ordinal' : 'cardinal';
1109
- const cacheKey = JSON.stringify({
1110
- cleanedCode,
1111
- type
1112
- });
1113
- if (cacheKey in this.pluralRulesCache) {
1114
- return this.pluralRulesCache[cacheKey];
1115
- }
1116
- let rule;
1117
- try {
1118
- rule = new Intl.PluralRules(cleanedCode, {
1119
- type
1120
- });
1121
- } catch (err) {
1122
- if (!Intl) {
1123
- this.logger.error('No Intl support, please use an Intl polyfill!');
1124
- return dummyRule;
1125
- }
1126
- if (!code.match(/-|_/)) return dummyRule;
1127
- const lngPart = this.languageUtils.getLanguagePartFromCode(code);
1128
- rule = this.getRule(lngPart, options);
1129
- }
1130
- this.pluralRulesCache[cacheKey] = rule;
1131
- return rule;
1132
- }
1133
- needsPlural(code, options = {}) {
1134
- let rule = this.getRule(code, options);
1135
- if (!rule) rule = this.getRule('dev', options);
1136
- return rule?.resolvedOptions().pluralCategories.length > 1;
1137
- }
1138
- getPluralFormsOfKey(code, key, options = {}) {
1139
- return this.getSuffixes(code, options).map(suffix => `${key}${suffix}`);
1140
- }
1141
- getSuffixes(code, options = {}) {
1142
- let rule = this.getRule(code, options);
1143
- if (!rule) rule = this.getRule('dev', options);
1144
- if (!rule) return [];
1145
- return rule.resolvedOptions().pluralCategories.sort((pluralCategory1, pluralCategory2) => suffixesOrder[pluralCategory1] - suffixesOrder[pluralCategory2]).map(pluralCategory => `${this.options.prepend}${options.ordinal ? `ordinal${this.options.prepend}` : ''}${pluralCategory}`);
1146
- }
1147
- getSuffix(code, count, options = {}) {
1148
- const rule = this.getRule(code, options);
1149
- if (rule) {
1150
- return `${this.options.prepend}${options.ordinal ? `ordinal${this.options.prepend}` : ''}${rule.select(count)}`;
1151
- }
1152
- this.logger.warn(`no plural rule found for: ${code}`);
1153
- return this.getSuffix('dev', count, options);
1154
- }
1155
- }
1156
-
1157
- const deepFindWithDefaults = (data, defaultData, key, keySeparator = '.', ignoreJSONStructure = true) => {
1158
- let path = getPathWithDefaults(data, defaultData, key);
1159
- if (!path && ignoreJSONStructure && isString(key)) {
1160
- path = deepFind(data, key, keySeparator);
1161
- if (path === undefined) path = deepFind(defaultData, key, keySeparator);
1162
- }
1163
- return path;
1164
- };
1165
- const regexSafe = val => val.replace(/\$/g, '$$$$');
1166
- class Interpolator {
1167
- constructor(options = {}) {
1168
- this.logger = baseLogger.create('interpolator');
1169
- this.options = options;
1170
- this.format = options?.interpolation?.format || (value => value);
1171
- this.init(options);
1172
- }
1173
- init(options = {}) {
1174
- if (!options.interpolation) options.interpolation = {
1175
- escapeValue: true
1176
- };
1177
- const {
1178
- escape: escape$1,
1179
- escapeValue,
1180
- useRawValueToEscape,
1181
- prefix,
1182
- prefixEscaped,
1183
- suffix,
1184
- suffixEscaped,
1185
- formatSeparator,
1186
- unescapeSuffix,
1187
- unescapePrefix,
1188
- nestingPrefix,
1189
- nestingPrefixEscaped,
1190
- nestingSuffix,
1191
- nestingSuffixEscaped,
1192
- nestingOptionsSeparator,
1193
- maxReplaces,
1194
- alwaysFormat
1195
- } = options.interpolation;
1196
- this.escape = escape$1 !== undefined ? escape$1 : escape;
1197
- this.escapeValue = escapeValue !== undefined ? escapeValue : true;
1198
- this.useRawValueToEscape = useRawValueToEscape !== undefined ? useRawValueToEscape : false;
1199
- this.prefix = prefix ? regexEscape(prefix) : prefixEscaped || '{{';
1200
- this.suffix = suffix ? regexEscape(suffix) : suffixEscaped || '}}';
1201
- this.formatSeparator = formatSeparator || ',';
1202
- this.unescapePrefix = unescapeSuffix ? '' : unescapePrefix || '-';
1203
- this.unescapeSuffix = this.unescapePrefix ? '' : unescapeSuffix || '';
1204
- this.nestingPrefix = nestingPrefix ? regexEscape(nestingPrefix) : nestingPrefixEscaped || regexEscape('$t(');
1205
- this.nestingSuffix = nestingSuffix ? regexEscape(nestingSuffix) : nestingSuffixEscaped || regexEscape(')');
1206
- this.nestingOptionsSeparator = nestingOptionsSeparator || ',';
1207
- this.maxReplaces = maxReplaces || 1000;
1208
- this.alwaysFormat = alwaysFormat !== undefined ? alwaysFormat : false;
1209
- this.resetRegExp();
1210
- }
1211
- reset() {
1212
- if (this.options) this.init(this.options);
1213
- }
1214
- resetRegExp() {
1215
- const getOrResetRegExp = (existingRegExp, pattern) => {
1216
- if (existingRegExp?.source === pattern) {
1217
- existingRegExp.lastIndex = 0;
1218
- return existingRegExp;
1219
- }
1220
- return new RegExp(pattern, 'g');
1221
- };
1222
- this.regexp = getOrResetRegExp(this.regexp, `${this.prefix}(.+?)${this.suffix}`);
1223
- this.regexpUnescape = getOrResetRegExp(this.regexpUnescape, `${this.prefix}${this.unescapePrefix}(.+?)${this.unescapeSuffix}${this.suffix}`);
1224
- this.nestingRegexp = getOrResetRegExp(this.nestingRegexp, `${this.nestingPrefix}((?:[^()"']+|"[^"]*"|'[^']*'|\\((?:[^()]|"[^"]*"|'[^']*')*\\))*?)${this.nestingSuffix}`);
1225
- }
1226
- interpolate(str, data, lng, options) {
1227
- let match;
1228
- let value;
1229
- let replaces;
1230
- const defaultData = this.options && this.options.interpolation && this.options.interpolation.defaultVariables || {};
1231
- const handleFormat = key => {
1232
- if (key.indexOf(this.formatSeparator) < 0) {
1233
- const path = deepFindWithDefaults(data, defaultData, key, this.options.keySeparator, this.options.ignoreJSONStructure);
1234
- return this.alwaysFormat ? this.format(path, undefined, lng, {
1235
- ...options,
1236
- ...data,
1237
- interpolationkey: key
1238
- }) : path;
1239
- }
1240
- const p = key.split(this.formatSeparator);
1241
- const k = p.shift().trim();
1242
- const f = p.join(this.formatSeparator).trim();
1243
- return this.format(deepFindWithDefaults(data, defaultData, k, this.options.keySeparator, this.options.ignoreJSONStructure), f, lng, {
1244
- ...options,
1245
- ...data,
1246
- interpolationkey: k
1247
- });
1248
- };
1249
- this.resetRegExp();
1250
- const missingInterpolationHandler = options?.missingInterpolationHandler || this.options.missingInterpolationHandler;
1251
- const skipOnVariables = options?.interpolation?.skipOnVariables !== undefined ? options.interpolation.skipOnVariables : this.options.interpolation.skipOnVariables;
1252
- const todos = [{
1253
- regex: this.regexpUnescape,
1254
- safeValue: val => regexSafe(val)
1255
- }, {
1256
- regex: this.regexp,
1257
- safeValue: val => this.escapeValue ? regexSafe(this.escape(val)) : regexSafe(val)
1258
- }];
1259
- todos.forEach(todo => {
1260
- replaces = 0;
1261
- while (match = todo.regex.exec(str)) {
1262
- const matchedVar = match[1].trim();
1263
- value = handleFormat(matchedVar);
1264
- if (value === undefined) {
1265
- if (typeof missingInterpolationHandler === 'function') {
1266
- const temp = missingInterpolationHandler(str, match, options);
1267
- value = isString(temp) ? temp : '';
1268
- } else if (options && Object.prototype.hasOwnProperty.call(options, matchedVar)) {
1269
- value = '';
1270
- } else if (skipOnVariables) {
1271
- value = match[0];
1272
- continue;
1273
- } else {
1274
- this.logger.warn(`missed to pass in variable ${matchedVar} for interpolating ${str}`);
1275
- value = '';
1276
- }
1277
- } else if (!isString(value) && !this.useRawValueToEscape) {
1278
- value = makeString(value);
1279
- }
1280
- const safeValue = todo.safeValue(value);
1281
- str = str.replace(match[0], safeValue);
1282
- if (skipOnVariables) {
1283
- todo.regex.lastIndex += value.length;
1284
- todo.regex.lastIndex -= match[0].length;
1285
- } else {
1286
- todo.regex.lastIndex = 0;
1287
- }
1288
- replaces++;
1289
- if (replaces >= this.maxReplaces) {
1290
- break;
1291
- }
1292
- }
1293
- });
1294
- return str;
1295
- }
1296
- nest(str, fc, options = {}) {
1297
- let match;
1298
- let value;
1299
- let clonedOptions;
1300
- const handleHasOptions = (key, inheritedOptions) => {
1301
- const sep = this.nestingOptionsSeparator;
1302
- if (key.indexOf(sep) < 0) return key;
1303
- const c = key.split(new RegExp(`${sep}[ ]*{`));
1304
- let optionsString = `{${c[1]}`;
1305
- key = c[0];
1306
- optionsString = this.interpolate(optionsString, clonedOptions);
1307
- const matchedSingleQuotes = optionsString.match(/'/g);
1308
- const matchedDoubleQuotes = optionsString.match(/"/g);
1309
- if ((matchedSingleQuotes?.length ?? 0) % 2 === 0 && !matchedDoubleQuotes || matchedDoubleQuotes.length % 2 !== 0) {
1310
- optionsString = optionsString.replace(/'/g, '"');
1311
- }
1312
- try {
1313
- clonedOptions = JSON.parse(optionsString);
1314
- if (inheritedOptions) clonedOptions = {
1315
- ...inheritedOptions,
1316
- ...clonedOptions
1317
- };
1318
- } catch (e) {
1319
- this.logger.warn(`failed parsing options string in nesting for key ${key}`, e);
1320
- return `${key}${sep}${optionsString}`;
1321
- }
1322
- if (clonedOptions.defaultValue && clonedOptions.defaultValue.indexOf(this.prefix) > -1) delete clonedOptions.defaultValue;
1323
- return key;
1324
- };
1325
- while (match = this.nestingRegexp.exec(str)) {
1326
- let formatters = [];
1327
- clonedOptions = {
1328
- ...options
1329
- };
1330
- clonedOptions = clonedOptions.replace && !isString(clonedOptions.replace) ? clonedOptions.replace : clonedOptions;
1331
- clonedOptions.applyPostProcessor = false;
1332
- delete clonedOptions.defaultValue;
1333
- const keyEndIndex = /{.*}/.test(match[1]) ? match[1].lastIndexOf('}') + 1 : match[1].indexOf(this.formatSeparator);
1334
- if (keyEndIndex !== -1) {
1335
- formatters = match[1].slice(keyEndIndex).split(this.formatSeparator).map(elem => elem.trim()).filter(Boolean);
1336
- match[1] = match[1].slice(0, keyEndIndex);
1337
- }
1338
- value = fc(handleHasOptions.call(this, match[1].trim(), clonedOptions), clonedOptions);
1339
- if (value && match[0] === str && !isString(value)) return value;
1340
- if (!isString(value)) value = makeString(value);
1341
- if (!value) {
1342
- this.logger.warn(`missed to resolve ${match[1]} for nesting ${str}`);
1343
- value = '';
1344
- }
1345
- if (formatters.length) {
1346
- value = formatters.reduce((v, f) => this.format(v, f, options.lng, {
1347
- ...options,
1348
- interpolationkey: match[1].trim()
1349
- }), value.trim());
1350
- }
1351
- str = str.replace(match[0], value);
1352
- this.regexp.lastIndex = 0;
1353
- }
1354
- return str;
1355
- }
1356
- }
1357
-
1358
- const parseFormatStr = formatStr => {
1359
- let formatName = formatStr.toLowerCase().trim();
1360
- const formatOptions = {};
1361
- if (formatStr.indexOf('(') > -1) {
1362
- const p = formatStr.split('(');
1363
- formatName = p[0].toLowerCase().trim();
1364
- const optStr = p[1].substring(0, p[1].length - 1);
1365
- if (formatName === 'currency' && optStr.indexOf(':') < 0) {
1366
- if (!formatOptions.currency) formatOptions.currency = optStr.trim();
1367
- } else if (formatName === 'relativetime' && optStr.indexOf(':') < 0) {
1368
- if (!formatOptions.range) formatOptions.range = optStr.trim();
1369
- } else {
1370
- const opts = optStr.split(';');
1371
- opts.forEach(opt => {
1372
- if (opt) {
1373
- const [key, ...rest] = opt.split(':');
1374
- const val = rest.join(':').trim().replace(/^'+|'+$/g, '');
1375
- const trimmedKey = key.trim();
1376
- if (!formatOptions[trimmedKey]) formatOptions[trimmedKey] = val;
1377
- if (val === 'false') formatOptions[trimmedKey] = false;
1378
- if (val === 'true') formatOptions[trimmedKey] = true;
1379
- if (!isNaN(val)) formatOptions[trimmedKey] = parseInt(val, 10);
1380
- }
1381
- });
1382
- }
1383
- }
1384
- return {
1385
- formatName,
1386
- formatOptions
1387
- };
1388
- };
1389
- const createCachedFormatter = fn => {
1390
- const cache = {};
1391
- return (v, l, o) => {
1392
- let optForCache = o;
1393
- if (o && o.interpolationkey && o.formatParams && o.formatParams[o.interpolationkey] && o[o.interpolationkey]) {
1394
- optForCache = {
1395
- ...optForCache,
1396
- [o.interpolationkey]: undefined
1397
- };
1398
- }
1399
- const key = l + JSON.stringify(optForCache);
1400
- let frm = cache[key];
1401
- if (!frm) {
1402
- frm = fn(getCleanedCode(l), o);
1403
- cache[key] = frm;
1404
- }
1405
- return frm(v);
1406
- };
1407
- };
1408
- const createNonCachedFormatter = fn => (v, l, o) => fn(getCleanedCode(l), o)(v);
1409
- class Formatter {
1410
- constructor(options = {}) {
1411
- this.logger = baseLogger.create('formatter');
1412
- this.options = options;
1413
- this.init(options);
1414
- }
1415
- init(services, options = {
1416
- interpolation: {}
1417
- }) {
1418
- this.formatSeparator = options.interpolation.formatSeparator || ',';
1419
- const cf = options.cacheInBuiltFormats ? createCachedFormatter : createNonCachedFormatter;
1420
- this.formats = {
1421
- number: cf((lng, opt) => {
1422
- const formatter = new Intl.NumberFormat(lng, {
1423
- ...opt
1424
- });
1425
- return val => formatter.format(val);
1426
- }),
1427
- currency: cf((lng, opt) => {
1428
- const formatter = new Intl.NumberFormat(lng, {
1429
- ...opt,
1430
- style: 'currency'
1431
- });
1432
- return val => formatter.format(val);
1433
- }),
1434
- datetime: cf((lng, opt) => {
1435
- const formatter = new Intl.DateTimeFormat(lng, {
1436
- ...opt
1437
- });
1438
- return val => formatter.format(val);
1439
- }),
1440
- relativetime: cf((lng, opt) => {
1441
- const formatter = new Intl.RelativeTimeFormat(lng, {
1442
- ...opt
1443
- });
1444
- return val => formatter.format(val, opt.range || 'day');
1445
- }),
1446
- list: cf((lng, opt) => {
1447
- const formatter = new Intl.ListFormat(lng, {
1448
- ...opt
1449
- });
1450
- return val => formatter.format(val);
1451
- })
1452
- };
1453
- }
1454
- add(name, fc) {
1455
- this.formats[name.toLowerCase().trim()] = fc;
1456
- }
1457
- addCached(name, fc) {
1458
- this.formats[name.toLowerCase().trim()] = createCachedFormatter(fc);
1459
- }
1460
- format(value, format, lng, options = {}) {
1461
- const formats = format.split(this.formatSeparator);
1462
- if (formats.length > 1 && formats[0].indexOf('(') > 1 && formats[0].indexOf(')') < 0 && formats.find(f => f.indexOf(')') > -1)) {
1463
- const lastIndex = formats.findIndex(f => f.indexOf(')') > -1);
1464
- formats[0] = [formats[0], ...formats.splice(1, lastIndex)].join(this.formatSeparator);
1465
- }
1466
- const result = formats.reduce((mem, f) => {
1467
- const {
1468
- formatName,
1469
- formatOptions
1470
- } = parseFormatStr(f);
1471
- if (this.formats[formatName]) {
1472
- let formatted = mem;
1473
- try {
1474
- const valOptions = options?.formatParams?.[options.interpolationkey] || {};
1475
- const l = valOptions.locale || valOptions.lng || options.locale || options.lng || lng;
1476
- formatted = this.formats[formatName](mem, l, {
1477
- ...formatOptions,
1478
- ...options,
1479
- ...valOptions
1480
- });
1481
- } catch (error) {
1482
- this.logger.warn(error);
1483
- }
1484
- return formatted;
1485
- } else {
1486
- this.logger.warn(`there was no format function for ${formatName}`);
1487
- }
1488
- return mem;
1489
- }, value);
1490
- return result;
1491
- }
1492
- }
1493
-
1494
- const removePending = (q, name) => {
1495
- if (q.pending[name] !== undefined) {
1496
- delete q.pending[name];
1497
- q.pendingCount--;
1498
- }
1499
- };
1500
- class Connector extends EventEmitter {
1501
- constructor(backend, store, services, options = {}) {
1502
- super();
1503
- this.backend = backend;
1504
- this.store = store;
1505
- this.services = services;
1506
- this.languageUtils = services.languageUtils;
1507
- this.options = options;
1508
- this.logger = baseLogger.create('backendConnector');
1509
- this.waitingReads = [];
1510
- this.maxParallelReads = options.maxParallelReads || 10;
1511
- this.readingCalls = 0;
1512
- this.maxRetries = options.maxRetries >= 0 ? options.maxRetries : 5;
1513
- this.retryTimeout = options.retryTimeout >= 1 ? options.retryTimeout : 350;
1514
- this.state = {};
1515
- this.queue = [];
1516
- this.backend?.init?.(services, options.backend, options);
1517
- }
1518
- queueLoad(languages, namespaces, options, callback) {
1519
- const toLoad = {};
1520
- const pending = {};
1521
- const toLoadLanguages = {};
1522
- const toLoadNamespaces = {};
1523
- languages.forEach(lng => {
1524
- let hasAllNamespaces = true;
1525
- namespaces.forEach(ns => {
1526
- const name = `${lng}|${ns}`;
1527
- if (!options.reload && this.store.hasResourceBundle(lng, ns)) {
1528
- this.state[name] = 2;
1529
- } else if (this.state[name] < 0) ; else if (this.state[name] === 1) {
1530
- if (pending[name] === undefined) pending[name] = true;
1531
- } else {
1532
- this.state[name] = 1;
1533
- hasAllNamespaces = false;
1534
- if (pending[name] === undefined) pending[name] = true;
1535
- if (toLoad[name] === undefined) toLoad[name] = true;
1536
- if (toLoadNamespaces[ns] === undefined) toLoadNamespaces[ns] = true;
1537
- }
1538
- });
1539
- if (!hasAllNamespaces) toLoadLanguages[lng] = true;
1540
- });
1541
- if (Object.keys(toLoad).length || Object.keys(pending).length) {
1542
- this.queue.push({
1543
- pending,
1544
- pendingCount: Object.keys(pending).length,
1545
- loaded: {},
1546
- errors: [],
1547
- callback
1548
- });
1549
- }
1550
- return {
1551
- toLoad: Object.keys(toLoad),
1552
- pending: Object.keys(pending),
1553
- toLoadLanguages: Object.keys(toLoadLanguages),
1554
- toLoadNamespaces: Object.keys(toLoadNamespaces)
1555
- };
1556
- }
1557
- loaded(name, err, data) {
1558
- const s = name.split('|');
1559
- const lng = s[0];
1560
- const ns = s[1];
1561
- if (err) this.emit('failedLoading', lng, ns, err);
1562
- if (!err && data) {
1563
- this.store.addResourceBundle(lng, ns, data, undefined, undefined, {
1564
- skipCopy: true
1565
- });
1566
- }
1567
- this.state[name] = err ? -1 : 2;
1568
- if (err && data) this.state[name] = 0;
1569
- const loaded = {};
1570
- this.queue.forEach(q => {
1571
- pushPath(q.loaded, [lng], ns);
1572
- removePending(q, name);
1573
- if (err) q.errors.push(err);
1574
- if (q.pendingCount === 0 && !q.done) {
1575
- Object.keys(q.loaded).forEach(l => {
1576
- if (!loaded[l]) loaded[l] = {};
1577
- const loadedKeys = q.loaded[l];
1578
- if (loadedKeys.length) {
1579
- loadedKeys.forEach(n => {
1580
- if (loaded[l][n] === undefined) loaded[l][n] = true;
1581
- });
1582
- }
1583
- });
1584
- q.done = true;
1585
- if (q.errors.length) {
1586
- q.callback(q.errors);
1587
- } else {
1588
- q.callback();
1589
- }
1590
- }
1591
- });
1592
- this.emit('loaded', loaded);
1593
- this.queue = this.queue.filter(q => !q.done);
1594
- }
1595
- read(lng, ns, fcName, tried = 0, wait = this.retryTimeout, callback) {
1596
- if (!lng.length) return callback(null, {});
1597
- if (this.readingCalls >= this.maxParallelReads) {
1598
- this.waitingReads.push({
1599
- lng,
1600
- ns,
1601
- fcName,
1602
- tried,
1603
- wait,
1604
- callback
1605
- });
1606
- return;
1607
- }
1608
- this.readingCalls++;
1609
- const resolver = (err, data) => {
1610
- this.readingCalls--;
1611
- if (this.waitingReads.length > 0) {
1612
- const next = this.waitingReads.shift();
1613
- this.read(next.lng, next.ns, next.fcName, next.tried, next.wait, next.callback);
1614
- }
1615
- if (err && data && tried < this.maxRetries) {
1616
- setTimeout(() => {
1617
- this.read.call(this, lng, ns, fcName, tried + 1, wait * 2, callback);
1618
- }, wait);
1619
- return;
1620
- }
1621
- callback(err, data);
1622
- };
1623
- const fc = this.backend[fcName].bind(this.backend);
1624
- if (fc.length === 2) {
1625
- try {
1626
- const r = fc(lng, ns);
1627
- if (r && typeof r.then === 'function') {
1628
- r.then(data => resolver(null, data)).catch(resolver);
1629
- } else {
1630
- resolver(null, r);
1631
- }
1632
- } catch (err) {
1633
- resolver(err);
1634
- }
1635
- return;
1636
- }
1637
- return fc(lng, ns, resolver);
1638
- }
1639
- prepareLoading(languages, namespaces, options = {}, callback) {
1640
- if (!this.backend) {
1641
- this.logger.warn('No backend was added via i18next.use. Will not load resources.');
1642
- return callback && callback();
1643
- }
1644
- if (isString(languages)) languages = this.languageUtils.toResolveHierarchy(languages);
1645
- if (isString(namespaces)) namespaces = [namespaces];
1646
- const toLoad = this.queueLoad(languages, namespaces, options, callback);
1647
- if (!toLoad.toLoad.length) {
1648
- if (!toLoad.pending.length) callback();
1649
- return null;
1650
- }
1651
- toLoad.toLoad.forEach(name => {
1652
- this.loadOne(name);
1653
- });
1654
- }
1655
- load(languages, namespaces, callback) {
1656
- this.prepareLoading(languages, namespaces, {}, callback);
1657
- }
1658
- reload(languages, namespaces, callback) {
1659
- this.prepareLoading(languages, namespaces, {
1660
- reload: true
1661
- }, callback);
1662
- }
1663
- loadOne(name, prefix = '') {
1664
- const s = name.split('|');
1665
- const lng = s[0];
1666
- const ns = s[1];
1667
- this.read(lng, ns, 'read', undefined, undefined, (err, data) => {
1668
- if (err) this.logger.warn(`${prefix}loading namespace ${ns} for language ${lng} failed`, err);
1669
- if (!err && data) this.logger.log(`${prefix}loaded namespace ${ns} for language ${lng}`, data);
1670
- this.loaded(name, err, data);
1671
- });
1672
- }
1673
- saveMissing(languages, namespace, key, fallbackValue, isUpdate, options = {}, clb = () => {}) {
1674
- if (this.services?.utils?.hasLoadedNamespace && !this.services?.utils?.hasLoadedNamespace(namespace)) {
1675
- 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!!!');
1676
- return;
1677
- }
1678
- if (key === undefined || key === null || key === '') return;
1679
- if (this.backend?.create) {
1680
- const opts = {
1681
- ...options,
1682
- isUpdate
1683
- };
1684
- const fc = this.backend.create.bind(this.backend);
1685
- if (fc.length < 6) {
1686
- try {
1687
- let r;
1688
- if (fc.length === 5) {
1689
- r = fc(languages, namespace, key, fallbackValue, opts);
1690
- } else {
1691
- r = fc(languages, namespace, key, fallbackValue);
1692
- }
1693
- if (r && typeof r.then === 'function') {
1694
- r.then(data => clb(null, data)).catch(clb);
1695
- } else {
1696
- clb(null, r);
1697
- }
1698
- } catch (err) {
1699
- clb(err);
1700
- }
1701
- } else {
1702
- fc(languages, namespace, key, fallbackValue, clb, opts);
1703
- }
1704
- }
1705
- if (!languages || !languages[0]) return;
1706
- this.store.addResource(languages[0], namespace, key, fallbackValue);
1707
- }
1708
- }
1709
-
1710
- const get = () => ({
1711
- debug: false,
1712
- initAsync: true,
1713
- ns: ['translation'],
1714
- defaultNS: ['translation'],
1715
- fallbackLng: ['dev'],
1716
- fallbackNS: false,
1717
- supportedLngs: false,
1718
- nonExplicitSupportedLngs: false,
1719
- load: 'all',
1720
- preload: false,
1721
- simplifyPluralSuffix: true,
1722
- keySeparator: '.',
1723
- nsSeparator: ':',
1724
- pluralSeparator: '_',
1725
- contextSeparator: '_',
1726
- partialBundledLanguages: false,
1727
- saveMissing: false,
1728
- updateMissing: false,
1729
- saveMissingTo: 'fallback',
1730
- saveMissingPlurals: true,
1731
- missingKeyHandler: false,
1732
- missingInterpolationHandler: false,
1733
- postProcess: false,
1734
- postProcessPassResolved: false,
1735
- returnNull: false,
1736
- returnEmptyString: true,
1737
- returnObjects: false,
1738
- joinArrays: false,
1739
- returnedObjectHandler: false,
1740
- parseMissingKeyHandler: false,
1741
- appendNamespaceToMissingKey: false,
1742
- appendNamespaceToCIMode: false,
1743
- overloadTranslationOptionHandler: args => {
1744
- let ret = {};
1745
- if (typeof args[1] === 'object') ret = args[1];
1746
- if (isString(args[1])) ret.defaultValue = args[1];
1747
- if (isString(args[2])) ret.tDescription = args[2];
1748
- if (typeof args[2] === 'object' || typeof args[3] === 'object') {
1749
- const options = args[3] || args[2];
1750
- Object.keys(options).forEach(key => {
1751
- ret[key] = options[key];
1752
- });
1753
- }
1754
- return ret;
1755
- },
1756
- interpolation: {
1757
- escapeValue: true,
1758
- format: value => value,
1759
- prefix: '{{',
1760
- suffix: '}}',
1761
- formatSeparator: ',',
1762
- unescapePrefix: '-',
1763
- nestingPrefix: '$t(',
1764
- nestingSuffix: ')',
1765
- nestingOptionsSeparator: ',',
1766
- maxReplaces: 1000,
1767
- skipOnVariables: true
1768
- },
1769
- cacheInBuiltFormats: true
1770
- });
1771
- const transformOptions = options => {
1772
- if (isString(options.ns)) options.ns = [options.ns];
1773
- if (isString(options.fallbackLng)) options.fallbackLng = [options.fallbackLng];
1774
- if (isString(options.fallbackNS)) options.fallbackNS = [options.fallbackNS];
1775
- if (options.supportedLngs?.indexOf?.('cimode') < 0) {
1776
- options.supportedLngs = options.supportedLngs.concat(['cimode']);
1777
- }
1778
- if (typeof options.initImmediate === 'boolean') options.initAsync = options.initImmediate;
1779
- return options;
1780
- };
1781
-
1782
- const noop = () => {};
1783
- const bindMemberFunctions = inst => {
1784
- const mems = Object.getOwnPropertyNames(Object.getPrototypeOf(inst));
1785
- mems.forEach(mem => {
1786
- if (typeof inst[mem] === 'function') {
1787
- inst[mem] = inst[mem].bind(inst);
1788
- }
1789
- });
1790
- };
1791
- class I18n extends EventEmitter {
1792
- constructor(options = {}, callback) {
1793
- super();
1794
- this.options = transformOptions(options);
1795
- this.services = {};
1796
- this.logger = baseLogger;
1797
- this.modules = {
1798
- external: []
1799
- };
1800
- bindMemberFunctions(this);
1801
- if (callback && !this.isInitialized && !options.isClone) {
1802
- if (!this.options.initAsync) {
1803
- this.init(options, callback);
1804
- return this;
1805
- }
1806
- setTimeout(() => {
1807
- this.init(options, callback);
1808
- }, 0);
1809
- }
1810
- }
1811
- init(options = {}, callback) {
1812
- this.isInitializing = true;
1813
- if (typeof options === 'function') {
1814
- callback = options;
1815
- options = {};
1816
- }
1817
- if (options.defaultNS == null && options.ns) {
1818
- if (isString(options.ns)) {
1819
- options.defaultNS = options.ns;
1820
- } else if (options.ns.indexOf('translation') < 0) {
1821
- options.defaultNS = options.ns[0];
1822
- }
1823
- }
1824
- const defOpts = get();
1825
- this.options = {
1826
- ...defOpts,
1827
- ...this.options,
1828
- ...transformOptions(options)
1829
- };
1830
- this.options.interpolation = {
1831
- ...defOpts.interpolation,
1832
- ...this.options.interpolation
1833
- };
1834
- if (options.keySeparator !== undefined) {
1835
- this.options.userDefinedKeySeparator = options.keySeparator;
1836
- }
1837
- if (options.nsSeparator !== undefined) {
1838
- this.options.userDefinedNsSeparator = options.nsSeparator;
1839
- }
1840
- const createClassOnDemand = ClassOrObject => {
1841
- if (!ClassOrObject) return null;
1842
- if (typeof ClassOrObject === 'function') return new ClassOrObject();
1843
- return ClassOrObject;
1844
- };
1845
- if (!this.options.isClone) {
1846
- if (this.modules.logger) {
1847
- baseLogger.init(createClassOnDemand(this.modules.logger), this.options);
1848
- } else {
1849
- baseLogger.init(null, this.options);
1850
- }
1851
- let formatter;
1852
- if (this.modules.formatter) {
1853
- formatter = this.modules.formatter;
1854
- } else {
1855
- formatter = Formatter;
1856
- }
1857
- const lu = new LanguageUtil(this.options);
1858
- this.store = new ResourceStore(this.options.resources, this.options);
1859
- const s = this.services;
1860
- s.logger = baseLogger;
1861
- s.resourceStore = this.store;
1862
- s.languageUtils = lu;
1863
- s.pluralResolver = new PluralResolver(lu, {
1864
- prepend: this.options.pluralSeparator,
1865
- simplifyPluralSuffix: this.options.simplifyPluralSuffix
1866
- });
1867
- const usingLegacyFormatFunction = this.options.interpolation.format && this.options.interpolation.format !== defOpts.interpolation.format;
1868
- if (usingLegacyFormatFunction) {
1869
- this.logger.deprecate(`init: you are still using the legacy format function, please use the new approach: https://www.i18next.com/translation-function/formatting`);
1870
- }
1871
- if (formatter && (!this.options.interpolation.format || this.options.interpolation.format === defOpts.interpolation.format)) {
1872
- s.formatter = createClassOnDemand(formatter);
1873
- if (s.formatter.init) s.formatter.init(s, this.options);
1874
- this.options.interpolation.format = s.formatter.format.bind(s.formatter);
1875
- }
1876
- s.interpolator = new Interpolator(this.options);
1877
- s.utils = {
1878
- hasLoadedNamespace: this.hasLoadedNamespace.bind(this)
1879
- };
1880
- s.backendConnector = new Connector(createClassOnDemand(this.modules.backend), s.resourceStore, s, this.options);
1881
- s.backendConnector.on('*', (event, ...args) => {
1882
- this.emit(event, ...args);
1883
- });
1884
- if (this.modules.languageDetector) {
1885
- s.languageDetector = createClassOnDemand(this.modules.languageDetector);
1886
- if (s.languageDetector.init) s.languageDetector.init(s, this.options.detection, this.options);
1887
- }
1888
- if (this.modules.i18nFormat) {
1889
- s.i18nFormat = createClassOnDemand(this.modules.i18nFormat);
1890
- if (s.i18nFormat.init) s.i18nFormat.init(this);
1891
- }
1892
- this.translator = new Translator(this.services, this.options);
1893
- this.translator.on('*', (event, ...args) => {
1894
- this.emit(event, ...args);
1895
- });
1896
- this.modules.external.forEach(m => {
1897
- if (m.init) m.init(this);
1898
- });
1899
- }
1900
- this.format = this.options.interpolation.format;
1901
- if (!callback) callback = noop;
1902
- if (this.options.fallbackLng && !this.services.languageDetector && !this.options.lng) {
1903
- const codes = this.services.languageUtils.getFallbackCodes(this.options.fallbackLng);
1904
- if (codes.length > 0 && codes[0] !== 'dev') this.options.lng = codes[0];
1905
- }
1906
- if (!this.services.languageDetector && !this.options.lng) {
1907
- this.logger.warn('init: no languageDetector is used and no lng is defined');
1908
- }
1909
- const storeApi = ['getResource', 'hasResourceBundle', 'getResourceBundle', 'getDataByLanguage'];
1910
- storeApi.forEach(fcName => {
1911
- this[fcName] = (...args) => this.store[fcName](...args);
1912
- });
1913
- const storeApiChained = ['addResource', 'addResources', 'addResourceBundle', 'removeResourceBundle'];
1914
- storeApiChained.forEach(fcName => {
1915
- this[fcName] = (...args) => {
1916
- this.store[fcName](...args);
1917
- return this;
1918
- };
1919
- });
1920
- const deferred = defer();
1921
- const load = () => {
1922
- const finish = (err, t) => {
1923
- this.isInitializing = false;
1924
- if (this.isInitialized && !this.initializedStoreOnce) this.logger.warn('init: i18next is already initialized. You should call init just once!');
1925
- this.isInitialized = true;
1926
- if (!this.options.isClone) this.logger.log('initialized', this.options);
1927
- this.emit('initialized', this.options);
1928
- deferred.resolve(t);
1929
- callback(err, t);
1930
- };
1931
- if (this.languages && !this.isInitialized) return finish(null, this.t.bind(this));
1932
- this.changeLanguage(this.options.lng, finish);
1933
- };
1934
- if (this.options.resources || !this.options.initAsync) {
1935
- load();
1936
- } else {
1937
- setTimeout(load, 0);
1938
- }
1939
- return deferred;
1940
- }
1941
- loadResources(language, callback = noop) {
1942
- let usedCallback = callback;
1943
- const usedLng = isString(language) ? language : this.language;
1944
- if (typeof language === 'function') usedCallback = language;
1945
- if (!this.options.resources || this.options.partialBundledLanguages) {
1946
- if (usedLng?.toLowerCase() === 'cimode' && (!this.options.preload || this.options.preload.length === 0)) return usedCallback();
1947
- const toLoad = [];
1948
- const append = lng => {
1949
- if (!lng) return;
1950
- if (lng === 'cimode') return;
1951
- const lngs = this.services.languageUtils.toResolveHierarchy(lng);
1952
- lngs.forEach(l => {
1953
- if (l === 'cimode') return;
1954
- if (toLoad.indexOf(l) < 0) toLoad.push(l);
1955
- });
1956
- };
1957
- if (!usedLng) {
1958
- const fallbacks = this.services.languageUtils.getFallbackCodes(this.options.fallbackLng);
1959
- fallbacks.forEach(l => append(l));
1960
- } else {
1961
- append(usedLng);
1962
- }
1963
- this.options.preload?.forEach?.(l => append(l));
1964
- this.services.backendConnector.load(toLoad, this.options.ns, e => {
1965
- if (!e && !this.resolvedLanguage && this.language) this.setResolvedLanguage(this.language);
1966
- usedCallback(e);
1967
- });
1968
- } else {
1969
- usedCallback(null);
1970
- }
1971
- }
1972
- reloadResources(lngs, ns, callback) {
1973
- const deferred = defer();
1974
- if (typeof lngs === 'function') {
1975
- callback = lngs;
1976
- lngs = undefined;
1977
- }
1978
- if (typeof ns === 'function') {
1979
- callback = ns;
1980
- ns = undefined;
1981
- }
1982
- if (!lngs) lngs = this.languages;
1983
- if (!ns) ns = this.options.ns;
1984
- if (!callback) callback = noop;
1985
- this.services.backendConnector.reload(lngs, ns, err => {
1986
- deferred.resolve();
1987
- callback(err);
1988
- });
1989
- return deferred;
1990
- }
1991
- use(module) {
1992
- if (!module) throw new Error('You are passing an undefined module! Please check the object you are passing to i18next.use()');
1993
- if (!module.type) throw new Error('You are passing a wrong module! Please check the object you are passing to i18next.use()');
1994
- if (module.type === 'backend') {
1995
- this.modules.backend = module;
1996
- }
1997
- if (module.type === 'logger' || module.log && module.warn && module.error) {
1998
- this.modules.logger = module;
1999
- }
2000
- if (module.type === 'languageDetector') {
2001
- this.modules.languageDetector = module;
2002
- }
2003
- if (module.type === 'i18nFormat') {
2004
- this.modules.i18nFormat = module;
2005
- }
2006
- if (module.type === 'postProcessor') {
2007
- postProcessor.addPostProcessor(module);
2008
- }
2009
- if (module.type === 'formatter') {
2010
- this.modules.formatter = module;
2011
- }
2012
- if (module.type === '3rdParty') {
2013
- this.modules.external.push(module);
2014
- }
2015
- return this;
2016
- }
2017
- setResolvedLanguage(l) {
2018
- if (!l || !this.languages) return;
2019
- if (['cimode', 'dev'].indexOf(l) > -1) return;
2020
- for (let li = 0; li < this.languages.length; li++) {
2021
- const lngInLngs = this.languages[li];
2022
- if (['cimode', 'dev'].indexOf(lngInLngs) > -1) continue;
2023
- if (this.store.hasLanguageSomeTranslations(lngInLngs)) {
2024
- this.resolvedLanguage = lngInLngs;
2025
- break;
2026
- }
2027
- }
2028
- if (!this.resolvedLanguage && this.languages.indexOf(l) < 0 && this.store.hasLanguageSomeTranslations(l)) {
2029
- this.resolvedLanguage = l;
2030
- this.languages.unshift(l);
2031
- }
2032
- }
2033
- changeLanguage(lng, callback) {
2034
- this.isLanguageChangingTo = lng;
2035
- const deferred = defer();
2036
- this.emit('languageChanging', lng);
2037
- const setLngProps = l => {
2038
- this.language = l;
2039
- this.languages = this.services.languageUtils.toResolveHierarchy(l);
2040
- this.resolvedLanguage = undefined;
2041
- this.setResolvedLanguage(l);
2042
- };
2043
- const done = (err, l) => {
2044
- if (l) {
2045
- if (this.isLanguageChangingTo === lng) {
2046
- setLngProps(l);
2047
- this.translator.changeLanguage(l);
2048
- this.isLanguageChangingTo = undefined;
2049
- this.emit('languageChanged', l);
2050
- this.logger.log('languageChanged', l);
2051
- }
2052
- } else {
2053
- this.isLanguageChangingTo = undefined;
2054
- }
2055
- deferred.resolve((...args) => this.t(...args));
2056
- if (callback) callback(err, (...args) => this.t(...args));
2057
- };
2058
- const setLng = lngs => {
2059
- if (!lng && !lngs && this.services.languageDetector) lngs = [];
2060
- const fl = isString(lngs) ? lngs : lngs && lngs[0];
2061
- const l = this.store.hasLanguageSomeTranslations(fl) ? fl : this.services.languageUtils.getBestMatchFromCodes(isString(lngs) ? [lngs] : lngs);
2062
- if (l) {
2063
- if (!this.language) {
2064
- setLngProps(l);
2065
- }
2066
- if (!this.translator.language) this.translator.changeLanguage(l);
2067
- this.services.languageDetector?.cacheUserLanguage?.(l);
2068
- }
2069
- this.loadResources(l, err => {
2070
- done(err, l);
2071
- });
2072
- };
2073
- if (!lng && this.services.languageDetector && !this.services.languageDetector.async) {
2074
- setLng(this.services.languageDetector.detect());
2075
- } else if (!lng && this.services.languageDetector && this.services.languageDetector.async) {
2076
- if (this.services.languageDetector.detect.length === 0) {
2077
- this.services.languageDetector.detect().then(setLng);
2078
- } else {
2079
- this.services.languageDetector.detect(setLng);
2080
- }
2081
- } else {
2082
- setLng(lng);
2083
- }
2084
- return deferred;
2085
- }
2086
- getFixedT(lng, ns, keyPrefix) {
2087
- const fixedT = (key, opts, ...rest) => {
2088
- let o;
2089
- if (typeof opts !== 'object') {
2090
- o = this.options.overloadTranslationOptionHandler([key, opts].concat(rest));
2091
- } else {
2092
- o = {
2093
- ...opts
2094
- };
2095
- }
2096
- o.lng = o.lng || fixedT.lng;
2097
- o.lngs = o.lngs || fixedT.lngs;
2098
- o.ns = o.ns || fixedT.ns;
2099
- if (o.keyPrefix !== '') o.keyPrefix = o.keyPrefix || keyPrefix || fixedT.keyPrefix;
2100
- const keySeparator = this.options.keySeparator || '.';
2101
- let resultKey;
2102
- if (o.keyPrefix && Array.isArray(key)) {
2103
- resultKey = key.map(k => {
2104
- if (typeof k === 'function') k = keysFromSelector(k, {
2105
- ...this.options,
2106
- ...opts
2107
- });
2108
- return `${o.keyPrefix}${keySeparator}${k}`;
2109
- });
2110
- } else {
2111
- if (typeof key === 'function') key = keysFromSelector(key, {
2112
- ...this.options,
2113
- ...opts
2114
- });
2115
- resultKey = o.keyPrefix ? `${o.keyPrefix}${keySeparator}${key}` : key;
2116
- }
2117
- return this.t(resultKey, o);
2118
- };
2119
- if (isString(lng)) {
2120
- fixedT.lng = lng;
2121
- } else {
2122
- fixedT.lngs = lng;
2123
- }
2124
- fixedT.ns = ns;
2125
- fixedT.keyPrefix = keyPrefix;
2126
- return fixedT;
2127
- }
2128
- t(...args) {
2129
- return this.translator?.translate(...args);
2130
- }
2131
- exists(...args) {
2132
- return this.translator?.exists(...args);
2133
- }
2134
- setDefaultNamespace(ns) {
2135
- this.options.defaultNS = ns;
2136
- }
2137
- hasLoadedNamespace(ns, options = {}) {
2138
- if (!this.isInitialized) {
2139
- this.logger.warn('hasLoadedNamespace: i18next was not initialized', this.languages);
2140
- return false;
2141
- }
2142
- if (!this.languages || !this.languages.length) {
2143
- this.logger.warn('hasLoadedNamespace: i18n.languages were undefined or empty', this.languages);
2144
- return false;
2145
- }
2146
- const lng = options.lng || this.resolvedLanguage || this.languages[0];
2147
- const fallbackLng = this.options ? this.options.fallbackLng : false;
2148
- const lastLng = this.languages[this.languages.length - 1];
2149
- if (lng.toLowerCase() === 'cimode') return true;
2150
- const loadNotPending = (l, n) => {
2151
- const loadState = this.services.backendConnector.state[`${l}|${n}`];
2152
- return loadState === -1 || loadState === 0 || loadState === 2;
2153
- };
2154
- if (options.precheck) {
2155
- const preResult = options.precheck(this, loadNotPending);
2156
- if (preResult !== undefined) return preResult;
2157
- }
2158
- if (this.hasResourceBundle(lng, ns)) return true;
2159
- if (!this.services.backendConnector.backend || this.options.resources && !this.options.partialBundledLanguages) return true;
2160
- if (loadNotPending(lng, ns) && (!fallbackLng || loadNotPending(lastLng, ns))) return true;
2161
- return false;
2162
- }
2163
- loadNamespaces(ns, callback) {
2164
- const deferred = defer();
2165
- if (!this.options.ns) {
2166
- if (callback) callback();
2167
- return Promise.resolve();
2168
- }
2169
- if (isString(ns)) ns = [ns];
2170
- ns.forEach(n => {
2171
- if (this.options.ns.indexOf(n) < 0) this.options.ns.push(n);
2172
- });
2173
- this.loadResources(err => {
2174
- deferred.resolve();
2175
- if (callback) callback(err);
2176
- });
2177
- return deferred;
2178
- }
2179
- loadLanguages(lngs, callback) {
2180
- const deferred = defer();
2181
- if (isString(lngs)) lngs = [lngs];
2182
- const preloaded = this.options.preload || [];
2183
- const newLngs = lngs.filter(lng => preloaded.indexOf(lng) < 0 && this.services.languageUtils.isSupportedCode(lng));
2184
- if (!newLngs.length) {
2185
- if (callback) callback();
2186
- return Promise.resolve();
2187
- }
2188
- this.options.preload = preloaded.concat(newLngs);
2189
- this.loadResources(err => {
2190
- deferred.resolve();
2191
- if (callback) callback(err);
2192
- });
2193
- return deferred;
2194
- }
2195
- dir(lng) {
2196
- if (!lng) lng = this.resolvedLanguage || (this.languages?.length > 0 ? this.languages[0] : this.language);
2197
- if (!lng) return 'rtl';
2198
- try {
2199
- const l = new Intl.Locale(lng);
2200
- if (l && l.getTextInfo) {
2201
- const ti = l.getTextInfo();
2202
- if (ti && ti.direction) return ti.direction;
2203
- }
2204
- } catch (e) {}
2205
- 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'];
2206
- const languageUtils = this.services?.languageUtils || new LanguageUtil(get());
2207
- if (lng.toLowerCase().indexOf('-latn') > 1) return 'ltr';
2208
- return rtlLngs.indexOf(languageUtils.getLanguagePartFromCode(lng)) > -1 || lng.toLowerCase().indexOf('-arab') > 1 ? 'rtl' : 'ltr';
2209
- }
2210
- static createInstance(options = {}, callback) {
2211
- const instance = new I18n(options, callback);
2212
- instance.createInstance = I18n.createInstance;
2213
- return instance;
2214
- }
2215
- cloneInstance(options = {}, callback = noop) {
2216
- const forkResourceStore = options.forkResourceStore;
2217
- if (forkResourceStore) delete options.forkResourceStore;
2218
- const mergedOptions = {
2219
- ...this.options,
2220
- ...options,
2221
- ...{
2222
- isClone: true
2223
- }
2224
- };
2225
- const clone = new I18n(mergedOptions);
2226
- if (options.debug !== undefined || options.prefix !== undefined) {
2227
- clone.logger = clone.logger.clone(options);
2228
- }
2229
- const membersToCopy = ['store', 'services', 'language'];
2230
- membersToCopy.forEach(m => {
2231
- clone[m] = this[m];
2232
- });
2233
- clone.services = {
2234
- ...this.services
2235
- };
2236
- clone.services.utils = {
2237
- hasLoadedNamespace: clone.hasLoadedNamespace.bind(clone)
2238
- };
2239
- if (forkResourceStore) {
2240
- const clonedData = Object.keys(this.store.data).reduce((prev, l) => {
2241
- prev[l] = {
2242
- ...this.store.data[l]
2243
- };
2244
- prev[l] = Object.keys(prev[l]).reduce((acc, n) => {
2245
- acc[n] = {
2246
- ...prev[l][n]
2247
- };
2248
- return acc;
2249
- }, prev[l]);
2250
- return prev;
2251
- }, {});
2252
- clone.store = new ResourceStore(clonedData, mergedOptions);
2253
- clone.services.resourceStore = clone.store;
2254
- }
2255
- clone.translator = new Translator(clone.services, mergedOptions);
2256
- clone.translator.on('*', (event, ...args) => {
2257
- clone.emit(event, ...args);
2258
- });
2259
- clone.init(mergedOptions, callback);
2260
- clone.translator.options = mergedOptions;
2261
- clone.translator.backendConnector.services.utils = {
2262
- hasLoadedNamespace: clone.hasLoadedNamespace.bind(clone)
2263
- };
2264
- return clone;
2265
- }
2266
- toJSON() {
2267
- return {
2268
- options: this.options,
2269
- store: this.store,
2270
- language: this.language,
2271
- languages: this.languages,
2272
- resolvedLanguage: this.resolvedLanguage
2273
- };
2274
- }
2275
- }
2276
- const instance = I18n.createInstance();
2277
-
2278
- const {
2279
- slice,
2280
- forEach
2281
- } = [];
2282
- function defaults(obj) {
2283
- forEach.call(slice.call(arguments, 1), source => {
2284
- if (source) {
2285
- for (const prop in source) {
2286
- if (obj[prop] === undefined) obj[prop] = source[prop];
2287
- }
2288
- }
2289
- });
2290
- return obj;
2291
- }
2292
- function hasXSS(input) {
2293
- if (typeof input !== 'string') return false;
2294
-
2295
- // Common XSS attack patterns
2296
- const xssPatterns = [/<\s*script.*?>/i, /<\s*\/\s*script\s*>/i, /<\s*img.*?on\w+\s*=/i, /<\s*\w+\s*on\w+\s*=.*?>/i, /javascript\s*:/i, /vbscript\s*:/i, /expression\s*\(/i, /eval\s*\(/i, /alert\s*\(/i, /document\.cookie/i, /document\.write\s*\(/i, /window\.location/i, /innerHTML/i];
2297
- return xssPatterns.some(pattern => pattern.test(input));
2298
- }
2299
-
2300
- // eslint-disable-next-line no-control-regex
2301
- const fieldContentRegExp = /^[\u0009\u0020-\u007e\u0080-\u00ff]+$/;
2302
- const serializeCookie = function (name, val) {
2303
- let options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {
2304
- path: '/'
2305
- };
2306
- const opt = options;
2307
- const value = encodeURIComponent(val);
2308
- let str = `${name}=${value}`;
2309
- if (opt.maxAge > 0) {
2310
- const maxAge = opt.maxAge - 0;
2311
- if (Number.isNaN(maxAge)) throw new Error('maxAge should be a Number');
2312
- str += `; Max-Age=${Math.floor(maxAge)}`;
2313
- }
2314
- if (opt.domain) {
2315
- if (!fieldContentRegExp.test(opt.domain)) {
2316
- throw new TypeError('option domain is invalid');
2317
- }
2318
- str += `; Domain=${opt.domain}`;
2319
- }
2320
- if (opt.path) {
2321
- if (!fieldContentRegExp.test(opt.path)) {
2322
- throw new TypeError('option path is invalid');
2323
- }
2324
- str += `; Path=${opt.path}`;
2325
- }
2326
- if (opt.expires) {
2327
- if (typeof opt.expires.toUTCString !== 'function') {
2328
- throw new TypeError('option expires is invalid');
2329
- }
2330
- str += `; Expires=${opt.expires.toUTCString()}`;
2331
- }
2332
- if (opt.httpOnly) str += '; HttpOnly';
2333
- if (opt.secure) str += '; Secure';
2334
- if (opt.sameSite) {
2335
- const sameSite = typeof opt.sameSite === 'string' ? opt.sameSite.toLowerCase() : opt.sameSite;
2336
- switch (sameSite) {
2337
- case true:
2338
- str += '; SameSite=Strict';
2339
- break;
2340
- case 'lax':
2341
- str += '; SameSite=Lax';
2342
- break;
2343
- case 'strict':
2344
- str += '; SameSite=Strict';
2345
- break;
2346
- case 'none':
2347
- str += '; SameSite=None';
2348
- break;
2349
- default:
2350
- throw new TypeError('option sameSite is invalid');
2351
- }
2352
- }
2353
- if (opt.partitioned) str += '; Partitioned';
2354
- return str;
2355
- };
2356
- const cookie = {
2357
- create(name, value, minutes, domain) {
2358
- let cookieOptions = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : {
2359
- path: '/',
2360
- sameSite: 'strict'
2361
- };
2362
- if (minutes) {
2363
- cookieOptions.expires = new Date();
2364
- cookieOptions.expires.setTime(cookieOptions.expires.getTime() + minutes * 60 * 1000);
2365
- }
2366
- if (domain) cookieOptions.domain = domain;
2367
- document.cookie = serializeCookie(name, value, cookieOptions);
2368
- },
2369
- read(name) {
2370
- const nameEQ = `${name}=`;
2371
- const ca = document.cookie.split(';');
2372
- for (let i = 0; i < ca.length; i++) {
2373
- let c = ca[i];
2374
- while (c.charAt(0) === ' ') c = c.substring(1, c.length);
2375
- if (c.indexOf(nameEQ) === 0) return c.substring(nameEQ.length, c.length);
2376
- }
2377
- return null;
2378
- },
2379
- remove(name, domain) {
2380
- this.create(name, '', -1, domain);
2381
- }
2382
- };
2383
- var cookie$1 = {
2384
- name: 'cookie',
2385
- // Deconstruct the options object and extract the lookupCookie property
2386
- lookup(_ref) {
2387
- let {
2388
- lookupCookie
2389
- } = _ref;
2390
- if (lookupCookie && typeof document !== 'undefined') {
2391
- return cookie.read(lookupCookie) || undefined;
2392
- }
2393
- return undefined;
2394
- },
2395
- // Deconstruct the options object and extract the lookupCookie, cookieMinutes, cookieDomain, and cookieOptions properties
2396
- cacheUserLanguage(lng, _ref2) {
2397
- let {
2398
- lookupCookie,
2399
- cookieMinutes,
2400
- cookieDomain,
2401
- cookieOptions
2402
- } = _ref2;
2403
- if (lookupCookie && typeof document !== 'undefined') {
2404
- cookie.create(lookupCookie, lng, cookieMinutes, cookieDomain, cookieOptions);
2405
- }
2406
- }
2407
- };
2408
-
2409
- var querystring = {
2410
- name: 'querystring',
2411
- // Deconstruct the options object and extract the lookupQuerystring property
2412
- lookup(_ref) {
2413
- let {
2414
- lookupQuerystring
2415
- } = _ref;
2416
- let found;
2417
- if (typeof window !== 'undefined') {
2418
- let {
2419
- search
2420
- } = window.location;
2421
- if (!window.location.search && window.location.hash?.indexOf('?') > -1) {
2422
- search = window.location.hash.substring(window.location.hash.indexOf('?'));
2423
- }
2424
- const query = search.substring(1);
2425
- const params = query.split('&');
2426
- for (let i = 0; i < params.length; i++) {
2427
- const pos = params[i].indexOf('=');
2428
- if (pos > 0) {
2429
- const key = params[i].substring(0, pos);
2430
- if (key === lookupQuerystring) {
2431
- found = params[i].substring(pos + 1);
2432
- }
2433
- }
2434
- }
2435
- }
2436
- return found;
2437
- }
2438
- };
2439
-
2440
- var hash = {
2441
- name: 'hash',
2442
- // Deconstruct the options object and extract the lookupHash property and the lookupFromHashIndex property
2443
- lookup(_ref) {
2444
- let {
2445
- lookupHash,
2446
- lookupFromHashIndex
2447
- } = _ref;
2448
- let found;
2449
- if (typeof window !== 'undefined') {
2450
- const {
2451
- hash
2452
- } = window.location;
2453
- if (hash && hash.length > 2) {
2454
- const query = hash.substring(1);
2455
- if (lookupHash) {
2456
- const params = query.split('&');
2457
- for (let i = 0; i < params.length; i++) {
2458
- const pos = params[i].indexOf('=');
2459
- if (pos > 0) {
2460
- const key = params[i].substring(0, pos);
2461
- if (key === lookupHash) {
2462
- found = params[i].substring(pos + 1);
2463
- }
2464
- }
2465
- }
2466
- }
2467
- if (found) return found;
2468
- if (!found && lookupFromHashIndex > -1) {
2469
- const language = hash.match(/\/([a-zA-Z-]*)/g);
2470
- if (!Array.isArray(language)) return undefined;
2471
- const index = typeof lookupFromHashIndex === 'number' ? lookupFromHashIndex : 0;
2472
- return language[index]?.replace('/', '');
2473
- }
2474
- }
2475
- }
2476
- return found;
2477
- }
2478
- };
2479
-
2480
- let hasLocalStorageSupport = null;
2481
- const localStorageAvailable = () => {
2482
- if (hasLocalStorageSupport !== null) return hasLocalStorageSupport;
2483
- try {
2484
- hasLocalStorageSupport = typeof window !== 'undefined' && window.localStorage !== null;
2485
- if (!hasLocalStorageSupport) {
2486
- return false;
2487
- }
2488
- const testKey = 'i18next.translate.boo';
2489
- window.localStorage.setItem(testKey, 'foo');
2490
- window.localStorage.removeItem(testKey);
2491
- } catch (e) {
2492
- hasLocalStorageSupport = false;
2493
- }
2494
- return hasLocalStorageSupport;
2495
- };
2496
- var localStorage = {
2497
- name: 'localStorage',
2498
- // Deconstruct the options object and extract the lookupLocalStorage property
2499
- lookup(_ref) {
2500
- let {
2501
- lookupLocalStorage
2502
- } = _ref;
2503
- if (lookupLocalStorage && localStorageAvailable()) {
2504
- return window.localStorage.getItem(lookupLocalStorage) || undefined; // Undefined ensures type consistency with the previous version of this function
2505
- }
2506
- return undefined;
2507
- },
2508
- // Deconstruct the options object and extract the lookupLocalStorage property
2509
- cacheUserLanguage(lng, _ref2) {
2510
- let {
2511
- lookupLocalStorage
2512
- } = _ref2;
2513
- if (lookupLocalStorage && localStorageAvailable()) {
2514
- window.localStorage.setItem(lookupLocalStorage, lng);
2515
- }
2516
- }
2517
- };
2518
-
2519
- let hasSessionStorageSupport = null;
2520
- const sessionStorageAvailable = () => {
2521
- if (hasSessionStorageSupport !== null) return hasSessionStorageSupport;
2522
- try {
2523
- hasSessionStorageSupport = typeof window !== 'undefined' && window.sessionStorage !== null;
2524
- if (!hasSessionStorageSupport) {
2525
- return false;
2526
- }
2527
- const testKey = 'i18next.translate.boo';
2528
- window.sessionStorage.setItem(testKey, 'foo');
2529
- window.sessionStorage.removeItem(testKey);
2530
- } catch (e) {
2531
- hasSessionStorageSupport = false;
2532
- }
2533
- return hasSessionStorageSupport;
2534
- };
2535
- var sessionStorage = {
2536
- name: 'sessionStorage',
2537
- lookup(_ref) {
2538
- let {
2539
- lookupSessionStorage
2540
- } = _ref;
2541
- if (lookupSessionStorage && sessionStorageAvailable()) {
2542
- return window.sessionStorage.getItem(lookupSessionStorage) || undefined;
2543
- }
2544
- return undefined;
2545
- },
2546
- cacheUserLanguage(lng, _ref2) {
2547
- let {
2548
- lookupSessionStorage
2549
- } = _ref2;
2550
- if (lookupSessionStorage && sessionStorageAvailable()) {
2551
- window.sessionStorage.setItem(lookupSessionStorage, lng);
2552
- }
2553
- }
2554
- };
2555
-
2556
- var navigator$1 = {
2557
- name: 'navigator',
2558
- lookup(options) {
2559
- const found = [];
2560
- if (typeof navigator !== 'undefined') {
2561
- const {
2562
- languages,
2563
- userLanguage,
2564
- language
2565
- } = navigator;
2566
- if (languages) {
2567
- // chrome only; not an array, so can't use .push.apply instead of iterating
2568
- for (let i = 0; i < languages.length; i++) {
2569
- found.push(languages[i]);
2570
- }
2571
- }
2572
- if (userLanguage) {
2573
- found.push(userLanguage);
2574
- }
2575
- if (language) {
2576
- found.push(language);
2577
- }
2578
- }
2579
- return found.length > 0 ? found : undefined;
2580
- }
2581
- };
2582
-
2583
- var htmlTag = {
2584
- name: 'htmlTag',
2585
- // Deconstruct the options object and extract the htmlTag property
2586
- lookup(_ref) {
2587
- let {
2588
- htmlTag
2589
- } = _ref;
2590
- let found;
2591
- const internalHtmlTag = htmlTag || (typeof document !== 'undefined' ? document.documentElement : null);
2592
- if (internalHtmlTag && typeof internalHtmlTag.getAttribute === 'function') {
2593
- found = internalHtmlTag.getAttribute('lang');
2594
- }
2595
- return found;
2596
- }
2597
- };
2598
-
2599
- var path = {
2600
- name: 'path',
2601
- // Deconstruct the options object and extract the lookupFromPathIndex property
2602
- lookup(_ref) {
2603
- let {
2604
- lookupFromPathIndex
2605
- } = _ref;
2606
- if (typeof window === 'undefined') return undefined;
2607
- const language = window.location.pathname.match(/\/([a-zA-Z-]*)/g);
2608
- if (!Array.isArray(language)) return undefined;
2609
- const index = typeof lookupFromPathIndex === 'number' ? lookupFromPathIndex : 0;
2610
- return language[index]?.replace('/', '');
2611
- }
2612
- };
2613
-
2614
- var subdomain = {
2615
- name: 'subdomain',
2616
- lookup(_ref) {
2617
- let {
2618
- lookupFromSubdomainIndex
2619
- } = _ref;
2620
- // If given get the subdomain index else 1
2621
- const internalLookupFromSubdomainIndex = typeof lookupFromSubdomainIndex === 'number' ? lookupFromSubdomainIndex + 1 : 1;
2622
- // get all matches if window.location. is existing
2623
- // first item of match is the match itself and the second is the first group match which should be the first subdomain match
2624
- // is the hostname no public domain get the or option of localhost
2625
- const language = typeof window !== 'undefined' && window.location?.hostname?.match(/^(\w{2,5})\.(([a-z0-9-]{1,63}\.[a-z]{2,6})|localhost)/i);
2626
-
2627
- // if there is no match (null) return undefined
2628
- if (!language) return undefined;
2629
- // return the given group match
2630
- return language[internalLookupFromSubdomainIndex];
2631
- }
2632
- };
2633
-
2634
- // some environments, throws when accessing document.cookie
2635
- let canCookies = false;
2636
- try {
2637
- canCookies = true;
2638
- // eslint-disable-next-line no-empty
2639
- } catch (e) {}
2640
- const order = ['querystring', 'cookie', 'localStorage', 'sessionStorage', 'navigator', 'htmlTag'];
2641
- if (!canCookies) order.splice(1, 1);
2642
- const getDefaults = () => ({
2643
- order,
2644
- lookupQuerystring: 'lng',
2645
- lookupCookie: 'i18next',
2646
- lookupLocalStorage: 'i18nextLng',
2647
- lookupSessionStorage: 'i18nextLng',
2648
- // cache user language
2649
- caches: ['localStorage'],
2650
- excludeCacheFor: ['cimode'],
2651
- // cookieMinutes: 10,
2652
- // cookieDomain: 'myDomain'
2653
-
2654
- convertDetectedLanguage: l => l
2655
- });
2656
- class Browser {
2657
- constructor(services) {
2658
- let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
2659
- this.type = 'languageDetector';
2660
- this.detectors = {};
2661
- this.init(services, options);
2662
- }
2663
- init() {
2664
- let services = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {
2665
- languageUtils: {}
2666
- };
2667
- let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
2668
- let i18nOptions = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
2669
- this.services = services;
2670
- this.options = defaults(options, this.options || {}, getDefaults());
2671
- if (typeof this.options.convertDetectedLanguage === 'string' && this.options.convertDetectedLanguage.indexOf('15897') > -1) {
2672
- this.options.convertDetectedLanguage = l => l.replace('-', '_');
2673
- }
2674
-
2675
- // backwards compatibility
2676
- if (this.options.lookupFromUrlIndex) this.options.lookupFromPathIndex = this.options.lookupFromUrlIndex;
2677
- this.i18nOptions = i18nOptions;
2678
- this.addDetector(cookie$1);
2679
- this.addDetector(querystring);
2680
- this.addDetector(localStorage);
2681
- this.addDetector(sessionStorage);
2682
- this.addDetector(navigator$1);
2683
- this.addDetector(htmlTag);
2684
- this.addDetector(path);
2685
- this.addDetector(subdomain);
2686
- this.addDetector(hash);
2687
- }
2688
- addDetector(detector) {
2689
- this.detectors[detector.name] = detector;
2690
- return this;
2691
- }
2692
- detect() {
2693
- let detectionOrder = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : this.options.order;
2694
- let detected = [];
2695
- detectionOrder.forEach(detectorName => {
2696
- if (this.detectors[detectorName]) {
2697
- let lookup = this.detectors[detectorName].lookup(this.options);
2698
- if (lookup && typeof lookup === 'string') lookup = [lookup];
2699
- if (lookup) detected = detected.concat(lookup);
2700
- }
2701
- });
2702
- detected = detected.filter(d => d !== undefined && d !== null && !hasXSS(d)).map(d => this.options.convertDetectedLanguage(d));
2703
- if (this.services && this.services.languageUtils && this.services.languageUtils.getBestMatchFromCodes) return detected; // new i18next v19.5.0
2704
- return detected.length > 0 ? detected[0] : null; // a little backward compatibility
2705
- }
2706
- cacheUserLanguage(lng) {
2707
- let caches = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : this.options.caches;
2708
- if (!caches) return;
2709
- if (this.options.excludeCacheFor && this.options.excludeCacheFor.indexOf(lng) > -1) return;
2710
- caches.forEach(cacheName => {
2711
- if (this.detectors[cacheName]) this.detectors[cacheName].cacheUserLanguage(lng, this.options);
2712
- });
2713
- }
2714
- }
2715
- Browser.type = 'languageDetector';
2716
-
2717
- instance.use(Browser).init({
2718
- fallbackLng: 'en',
2719
- debug: false,
2720
- resources: {
2721
- en: {
2722
- translation: {},
2723
- },
2724
- ja: {
2725
- translation: {
2726
- 'Pay': '支払う',
2727
- 'Failed to load Stripe': 'ライブラリの読み込みに失敗しました。',
2728
- 'Add your payment information': '支払情報を追加',
2729
- 'Add card': 'カードを追加',
2730
- 'Add a card': 'カードを追加',
2731
- 'Add': '追加',
2732
- 'Card information': 'カード情報',
2733
- 'Card Number': 'カード番号',
2734
- 'MM / YY': '月 / 年',
2735
- 'CVC': 'セキュリティコード(CVC)',
2736
- 'Country or region': '地域',
2737
- 'Postal Code': '郵便番号',
2738
- },
2739
- },
2740
- 'pt-BR': {
2741
- translation: {
2742
- 'Pay': 'Pagar',
2743
- 'Failed to load Stripe': 'Falha ao ler Stripe',
2744
- 'Add your payment information': 'Informações do seu Pagamento',
2745
- 'Add card': 'Adicionar Cartão',
2746
- 'Add a card': 'Adicionar um Cartão',
2747
- 'Add': 'Adicionar',
2748
- 'Card information': 'Informações do Cartão',
2749
- 'Card Number': 'Número do Cartão',
2750
- 'MM / YY': 'MM / AA',
2751
- 'CVC': 'Número de Segurança(CVC)',
2752
- 'Country or region': 'País ou região',
2753
- 'Postal Code': 'Cep',
2754
- },
2755
- },
2756
- },
2757
- });
2758
- const i18n = instance;
2759
-
2760
- const appendToMap = (map, propName, value) => {
2761
- const items = map.get(propName);
2762
- if (!items) {
2763
- map.set(propName, [value]);
2764
- }
2765
- else if (!items.includes(value)) {
2766
- items.push(value);
2767
- }
2768
- };
2769
- const debounce = (fn, ms) => {
2770
- let timeoutId;
2771
- return (...args) => {
2772
- if (timeoutId) {
2773
- clearTimeout(timeoutId);
2774
- }
2775
- timeoutId = setTimeout(() => {
2776
- timeoutId = 0;
2777
- fn(...args);
2778
- }, ms);
2779
- };
2780
- };
2781
-
2782
- /**
2783
- * Check if a possible element isConnected.
2784
- * The property might not be there, so we check for it.
2785
- *
2786
- * We want it to return true if isConnected is not a property,
2787
- * otherwise we would remove these elements and would not update.
2788
- *
2789
- * Better leak in Edge than to be useless.
2790
- */
2791
- const isConnected = (maybeElement) => !('isConnected' in maybeElement) || maybeElement.isConnected;
2792
- const cleanupElements = debounce((map) => {
2793
- for (let key of map.keys()) {
2794
- map.set(key, map.get(key).filter(isConnected));
2795
- }
2796
- }, 2_000);
2797
- const stencilSubscription = () => {
2798
- if (typeof getRenderingRef !== 'function') {
2799
- // If we are not in a stencil project, we do nothing.
2800
- // This function is not really exported by @stencil/core.
2801
- return {};
2802
- }
2803
- const elmsToUpdate = new Map();
2804
- return {
2805
- dispose: () => elmsToUpdate.clear(),
2806
- get: (propName) => {
2807
- const elm = getRenderingRef();
2808
- if (elm) {
2809
- appendToMap(elmsToUpdate, propName, elm);
2810
- }
2811
- },
2812
- set: (propName) => {
2813
- const elements = elmsToUpdate.get(propName);
2814
- if (elements) {
2815
- elmsToUpdate.set(propName, elements.filter(forceUpdate));
2816
- }
2817
- cleanupElements(elmsToUpdate);
2818
- },
2819
- reset: () => {
2820
- elmsToUpdate.forEach((elms) => elms.forEach(forceUpdate));
2821
- cleanupElements(elmsToUpdate);
2822
- },
2823
- };
2824
- };
2825
-
2826
- const unwrap = (val) => (typeof val === 'function' ? val() : val);
2827
- const createObservableMap = (defaultState, shouldUpdate = (a, b) => a !== b) => {
2828
- const unwrappedState = unwrap(defaultState);
2829
- let states = new Map(Object.entries(unwrappedState ?? {}));
2830
- const handlers = {
2831
- dispose: [],
2832
- get: [],
2833
- set: [],
2834
- reset: [],
2835
- };
2836
- // Track onChange listeners to enable removeListener functionality
2837
- const changeListeners = new Map();
2838
- const reset = () => {
2839
- // When resetting the state, the default state may be a function - unwrap it to invoke it.
2840
- // otherwise, the state won't be properly reset
2841
- states = new Map(Object.entries(unwrap(defaultState) ?? {}));
2842
- handlers.reset.forEach((cb) => cb());
2843
- };
2844
- const dispose = () => {
2845
- // Call first dispose as resetting the state would
2846
- // cause less updates ;)
2847
- handlers.dispose.forEach((cb) => cb());
2848
- reset();
2849
- };
2850
- const get = (propName) => {
2851
- handlers.get.forEach((cb) => cb(propName));
2852
- return states.get(propName);
2853
- };
2854
- const set = (propName, value) => {
2855
- const oldValue = states.get(propName);
2856
- if (shouldUpdate(value, oldValue, propName)) {
2857
- states.set(propName, value);
2858
- handlers.set.forEach((cb) => cb(propName, value, oldValue));
2859
- }
2860
- };
2861
- const state = (typeof Proxy === 'undefined'
2862
- ? {}
2863
- : new Proxy(unwrappedState, {
2864
- get(_, propName) {
2865
- return get(propName);
2866
- },
2867
- ownKeys(_) {
2868
- return Array.from(states.keys());
2869
- },
2870
- getOwnPropertyDescriptor() {
2871
- return {
2872
- enumerable: true,
2873
- configurable: true,
2874
- };
2875
- },
2876
- has(_, propName) {
2877
- return states.has(propName);
2878
- },
2879
- set(_, propName, value) {
2880
- set(propName, value);
2881
- return true;
2882
- },
2883
- }));
2884
- const on = (eventName, callback) => {
2885
- handlers[eventName].push(callback);
2886
- return () => {
2887
- removeFromArray(handlers[eventName], callback);
2888
- };
2889
- };
2890
- const onChange = (propName, cb) => {
2891
- const setHandler = (key, newValue) => {
2892
- if (key === propName) {
2893
- cb(newValue);
2894
- }
2895
- };
2896
- const resetHandler = () => cb(unwrap(defaultState)[propName]);
2897
- // Register the handlers
2898
- const unSet = on('set', setHandler);
2899
- const unReset = on('reset', resetHandler);
2900
- // Track the relationship between the user callback and internal handlers
2901
- changeListeners.set(cb, { setHandler, resetHandler, propName });
2902
- return () => {
2903
- unSet();
2904
- unReset();
2905
- changeListeners.delete(cb);
2906
- };
2907
- };
2908
- const use = (...subscriptions) => {
2909
- const unsubs = subscriptions.reduce((unsubs, subscription) => {
2910
- if (subscription.set) {
2911
- unsubs.push(on('set', subscription.set));
2912
- }
2913
- if (subscription.get) {
2914
- unsubs.push(on('get', subscription.get));
2915
- }
2916
- if (subscription.reset) {
2917
- unsubs.push(on('reset', subscription.reset));
2918
- }
2919
- if (subscription.dispose) {
2920
- unsubs.push(on('dispose', subscription.dispose));
2921
- }
2922
- return unsubs;
2923
- }, []);
2924
- return () => unsubs.forEach((unsub) => unsub());
2925
- };
2926
- const forceUpdate = (key) => {
2927
- const oldValue = states.get(key);
2928
- handlers.set.forEach((cb) => cb(key, oldValue, oldValue));
2929
- };
2930
- const removeListener = (propName, listener) => {
2931
- const listenerInfo = changeListeners.get(listener);
2932
- if (listenerInfo && listenerInfo.propName === propName) {
2933
- // Remove the specific handlers that were created for this listener
2934
- removeFromArray(handlers.set, listenerInfo.setHandler);
2935
- removeFromArray(handlers.reset, listenerInfo.resetHandler);
2936
- changeListeners.delete(listener);
2937
- }
2938
- };
2939
- return {
2940
- state,
2941
- get,
2942
- set,
2943
- on,
2944
- onChange,
2945
- use,
2946
- dispose,
2947
- reset,
2948
- forceUpdate,
2949
- removeListener,
2950
- };
2951
- };
2952
- const removeFromArray = (array, item) => {
2953
- const index = array.indexOf(item);
2954
- if (index >= 0) {
2955
- array[index] = array[array.length - 1];
2956
- array.length--;
2957
- }
2958
- };
2959
-
2960
- const createStore = (defaultState, shouldUpdate) => {
2961
- const map = createObservableMap(defaultState, shouldUpdate);
2962
- map.use(stencilSubscription());
2963
- return map;
2964
- };
2965
-
2966
- /**
2967
- * Core Stripe Service
2968
- * Manages Stripe.js initialization and Elements instance only
2969
- * Does NOT manage specific element types (Card, Payment, etc.)
2970
- */
2971
- class StripeServiceClass {
2972
- constructor() {
2973
- this.store = createStore({
2974
- loadStripeStatus: '',
2975
- applicationName: 'stripe-pwa-elements',
2976
- });
2977
- this.changeListeners = new Map();
2978
- }
2979
- /**
2980
- * Get the reactive state object
2981
- * Components can use this directly in render() for automatic reactivity
2982
- */
2983
- get state() {
2984
- return this.store.state;
2985
- }
2986
- /**
2987
- * Register a callback for when a specific state property changes
2988
- * @param key - The state property to watch
2989
- * @param callback - Function to call when the property changes
2990
- * @returns Unsubscribe function
2991
- */
2992
- onChange(key, callback) {
2993
- const dispose = this.store.onChange(key, callback);
2994
- // Track listeners for cleanup
2995
- if (!this.changeListeners.has(key)) {
2996
- this.changeListeners.set(key, []);
2997
- }
2998
- this.changeListeners.get(key).push(dispose);
2999
- return dispose;
3000
- }
3001
- /**
3002
- * Initialize Stripe.js client
3003
- * @param publishableKey - Your Stripe publishable API key
3004
- * @param options - Optional configuration
3005
- */
3006
- async initialize(publishableKey, options) {
3007
- // Update configuration
3008
- this.store.state.publishableKey = publishableKey;
3009
- if (options === null || options === void 0 ? void 0 : options.stripeAccount) {
3010
- this.store.state.stripeAccount = options.stripeAccount;
3011
- }
3012
- if (options === null || options === void 0 ? void 0 : options.applicationName) {
3013
- this.store.state.applicationName = options.applicationName;
3014
- }
3015
- // If Stripe.js already loaded with same config, do nothing
3016
- if (this.store.state.stripe && this.store.state.publishableKey === publishableKey && this.store.state.stripeAccount === (options === null || options === void 0 ? void 0 : options.stripeAccount)) {
3017
- return;
3018
- }
3019
- this.store.state.loadStripeStatus = 'loading';
3020
- try {
3021
- const stripe = await loadStripe(publishableKey, {
3022
- stripeAccount: options === null || options === void 0 ? void 0 : options.stripeAccount,
3023
- });
3024
- // Register app info
3025
- stripe.registerAppInfo({
3026
- name: this.store.state.applicationName,
3027
- });
3028
- this.store.state.stripe = stripe;
3029
- this.store.state.elements = stripe.elements();
3030
- this.store.state.loadStripeStatus = 'success';
3031
- }
3032
- catch (e) {
3033
- console.error('Failed to load Stripe.js:', e);
3034
- this.store.state.loadStripeStatus = 'failure';
3035
- }
3036
- }
3037
- /**
3038
- * Get the current Stripe instance
3039
- */
3040
- getStripe() {
3041
- return this.store.state.stripe;
3042
- }
3043
- /**
3044
- * Get the current Elements instance
3045
- */
3046
- getElements() {
3047
- return this.store.state.elements;
3048
- }
3049
- /**
3050
- * Reset the service to initial state
3051
- * Useful for testing and cleanup
3052
- */
3053
- reset() {
3054
- this.store.reset();
3055
- }
3056
- /**
3057
- * Dispose of all listeners and reset state
3058
- * Should be called in test cleanup
3059
- */
3060
- dispose() {
3061
- // Dispose all onChange listeners
3062
- this.changeListeners.forEach(listeners => {
3063
- listeners.forEach(dispose => dispose());
3064
- });
3065
- this.changeListeners.clear();
3066
- // Dispose the store
3067
- this.store.dispose();
3068
- }
3069
- }
3070
- /**
3071
- * Singleton instance of StripeService (for backward compatibility)
3072
- * New code should use ServiceFactory for better testability
3073
- *
3074
- * @deprecated Use ServiceFactory.createStripeService() for better DI support
3075
- */
3076
- new StripeServiceClass();
3077
-
3078
- /**
3079
- * Card Element Manager
3080
- * Manages Stripe Card Elements (cardNumber, cardExpiry, cardCvc)
3081
- * with dependency injection of StripeService
3082
- */
3083
- class CardElementManager {
3084
- /**
3085
- * Constructor with dependency injection
3086
- * @param stripeService - Injected Stripe service instance
3087
- */
3088
- constructor(stripeService) {
3089
- this.stripeService = stripeService;
3090
- this.store = createStore({
3091
- errorMessage: '',
3092
- errorSource: undefined,
3093
- });
3094
- }
3095
- /**
3096
- * Get current card element state (reactive)
3097
- */
3098
- getState() {
3099
- return this.store.state;
3100
- }
3101
- /**
3102
- * Initialize and mount card elements to DOM
3103
- * @param containerElement - Parent element containing mount points
3104
- * @returns Promise resolving to card element instances
3105
- */
3106
- async initialize(containerElement) {
3107
- const elements = this.stripeService.getElements();
3108
- if (!elements) {
3109
- throw new Error('StripeService not initialized. Call StripeService.initialize() first.');
3110
- }
3111
- // Unmount if already initialized
3112
- if (this.cardElements) {
3113
- this.unmount();
3114
- }
3115
- // Create and mount card number element
3116
- const cardNumber = elements.create('cardNumber', {
3117
- placeholder: i18n.t('Card Number'),
3118
- });
3119
- const cardNumberElement = await this.findElement(containerElement, '#card-number');
3120
- cardNumber.mount(cardNumberElement);
3121
- cardNumber.on('change', this.handleCardError('cardNumber'));
3122
- // Create and mount card expiry element
3123
- const cardExpiry = elements.create('cardExpiry');
3124
- const cardExpiryElement = await this.findElement(containerElement, '#card-expiry');
3125
- cardExpiry.mount(cardExpiryElement);
3126
- cardExpiry.on('change', this.handleCardError('cardExpiry'));
3127
- // Create and mount card CVC element
3128
- const cardCVC = elements.create('cardCvc');
3129
- const cardCVCElement = await this.findElement(containerElement, '#card-cvc');
3130
- cardCVC.mount(cardCVCElement);
3131
- cardCVC.on('change', this.handleCardError('cardCvc'));
3132
- this.cardElements = {
3133
- cardNumber,
3134
- cardExpiry,
3135
- cardCVC,
3136
- };
3137
- return this.cardElements;
3138
- }
3139
- /**
3140
- * Get mounted card element instances
3141
- */
3142
- getElements() {
3143
- return this.cardElements;
3144
- }
3145
- /**
3146
- * Set error message (triggers reactivity)
3147
- */
3148
- setError(message) {
3149
- this.store.set('errorMessage', message);
3150
- }
3151
- /**
3152
- * Clear error message (triggers reactivity)
3153
- */
3154
- clearError() {
3155
- this.store.set('errorMessage', '');
3156
- this.store.set('errorSource', undefined);
3157
- }
3158
- /**
3159
- * Unmount all card elements
3160
- */
3161
- unmount() {
3162
- var _a, _b, _c;
3163
- if (!this.cardElements) {
3164
- return;
3165
- }
3166
- (_a = this.cardElements.cardNumber) === null || _a === void 0 ? void 0 : _a.unmount();
3167
- (_b = this.cardElements.cardExpiry) === null || _b === void 0 ? void 0 : _b.unmount();
3168
- (_c = this.cardElements.cardCVC) === null || _c === void 0 ? void 0 : _c.unmount();
3169
- this.cardElements = undefined;
3170
- }
3171
- /**
3172
- * Handle card element errors
3173
- * Only clears error if it's from the same element type
3174
- * Uses store.set() to trigger reactivity
3175
- */
3176
- handleCardError(elementType) {
3177
- return ({ error }) => {
3178
- if (error) {
3179
- this.store.set('errorMessage', error.message);
3180
- this.store.set('errorSource', elementType);
3181
- return;
3182
- }
3183
- // Only clear error if it originated from the same element
3184
- if (this.store.state.errorSource === elementType) {
3185
- this.store.set('errorMessage', '');
3186
- this.store.set('errorSource', undefined);
3187
- }
3188
- };
3189
- }
3190
- /**
3191
- * Wait for an element to appear in the DOM
3192
- * @param containerElement - Parent element to search in
3193
- * @param selector - CSS selector
3194
- * @param timeout - Timeout in milliseconds (default: 5000ms)
3195
- * @returns Promise that resolves to the found element or rejects on timeout
3196
- */
3197
- findElement(containerElement, selector, timeout = 5000) {
3198
- return new Promise((resolve, reject) => {
3199
- const elem = containerElement.querySelector(selector);
3200
- if (elem) {
3201
- return resolve(elem);
3202
- }
3203
- const timeoutId = setTimeout(() => {
3204
- observer.disconnect();
3205
- reject(new Error(`Element "${selector}" not found within ${timeout}ms`));
3206
- }, timeout);
3207
- const observer = new MutationObserver(() => {
3208
- const elem = containerElement.querySelector(selector);
3209
- if (elem) {
3210
- clearTimeout(timeoutId);
3211
- observer.disconnect();
3212
- resolve(elem);
3213
- }
3214
- });
3215
- observer.observe(containerElement, {
3216
- childList: true,
3217
- subtree: true,
3218
- });
3219
- });
3220
- }
3221
- }
3222
-
3223
- /**
3224
- * Service Factory
3225
- * Creates service instances with proper dependency injection
3226
- * Can be mocked in tests for better testability
3227
- */
3228
- class ServiceFactory {
3229
- /**
3230
- * Create a new StripeService instance
3231
- */
3232
- createStripeService() {
3233
- return new StripeServiceClass();
3234
- }
3235
- /**
3236
- * Create a new CardElementManager instance
3237
- * @param stripeService - Injected StripeService dependency
3238
- */
3239
- createCardElementManager(stripeService) {
3240
- return new CardElementManager(stripeService);
3241
- }
3242
- }
3243
- /**
3244
- * Default factory instance
3245
- * Can be replaced with a mock in tests
3246
- */
3247
- const serviceFactory = new ServiceFactory();
3248
-
3249
- class StripeAPIError extends Error {
3250
- constructor(error) {
3251
- super(error.message);
3252
- this.code = error.code;
3253
- this.docUrl = error.doc_url;
3254
- this.message = error.message;
3255
- this.param = error.param;
3256
- this.requestLogUrl = error.request_log_url;
3257
- this.type = error.type;
3258
- }
3259
- }
3260
-
3261
- const stripeCardElementCss = ":root{--color-label:#565656;--color-placeholder:#acacac;--color-heading-text:#333;--color-text-error:#ef4444;--color-input-border:#e4e4e6;--color-button-text:rgba(255, 255, 255, 0.95);--color-button-text-disabled:rgba(255, 255, 255, 0.4);--color-primary:#0074d4}.stripe-payment-sheet-wrap{}.stripe-payment-sheet-wrap *:where(:not(iframe,canvas,img,svg,video):not(svg *)){all:unset;display:revert;background:none;border:none;font-family:\"Roboto\", sans-serif;box-sizing:border-box}.stripe-payment-sheet-wrap button{cursor:pointer}.stripe-payment-sheet-wrap{display:block;width:100%;background:#fff;padding:32px 16px}.stripe-payment-sheet-wrap .StripeElement{padding:8px 16px;min-height:64px;border-bottom:1px solid var(--color-input-border);border-radius:4px;display:flex;justify-content:center;align-items:center}.stripe-payment-sheet-wrap .StripeElement>.__PrivateStripeElement{width:100%}.stripe-payment-sheet-wrap .stripe-input-box{background-color:#fff;border-radius:2px;filter:drop-shadow(0 0 1px var(--color-input-border))}.stripe-payment-sheet-wrap .stripe-input-column .StripeElement{border-right:1px solid var(--color-input-border)}.stripe-payment-sheet-wrap .stripe-input-column .StripeElement:last-child{border-right:none}.stripe-payment-sheet-wrap .stripe-heading{font-size:24px;font-weight:bold;color:var(--color-heading-text);margin-bottom:24px}.stripe-payment-sheet-wrap .stripe-section-title{font-size:14px;font-weight:bold;color:var(--color-label);margin-bottom:8px}.stripe-payment-sheet-wrap .payment-info label{color:var(--color-label)}.stripe-payment-sheet-wrap .stripe-element-errors{margin-top:8px;font-size:14px;color:var(--color-text-error)}.stripe-payment-sheet-wrap button{display:block;color:var(--color-button-text);background-color:var(--color-primary);width:100%;text-align:center;padding:16px 16px;font-size:18px;border-radius:8px;min-height:42px}.stripe-payment-sheet-wrap button:disabled{color:var(--color-button-text-disabled)}";
6
+ const stripeCardElementCss = ":root{--color-label:#565656;--color-placeholder:#acacac;--color-heading-text:#333;--color-text-error:#ef4444;--color-input-border:#e4e4e6;--color-input-border-shadow:rgba(228, 228, 230, 0.6);--color-button-text:rgba(255, 255, 255, 0.95);--color-button-text-disabled:rgba(255, 255, 255, 0.4);--color-primary:#0074d4}.stripe-payment-sheet-wrap{box-sizing:border-box}.stripe-payment-sheet-wrap *:where(:not(iframe,canvas,img,svg,video):not(svg *)){all:unset;display:revert;background:none;border:none;font-family:\"Roboto\", sans-serif;box-sizing:border-box}.stripe-payment-sheet-wrap button{cursor:pointer}.stripe-payment-sheet-wrap{display:block;width:100%;background:#fff;padding:32px 16px}.stripe-payment-sheet-wrap .StripeElement{padding:8px 16px;min-height:64px;display:flex;justify-content:center;align-items:center}.stripe-payment-sheet-wrap .StripeElement>.__PrivateStripeElement{width:100%}.stripe-payment-sheet-wrap .stripe-input-box{background-color:#fff;border-radius:6px;border:1px solid var(--color-input-border);overflow:hidden;filter:drop-shadow(0 0 2px var(--color-input-border-shadow))}.stripe-payment-sheet-wrap .stripe-input-box>*{border-bottom:1px solid var(--color-input-border)}.stripe-payment-sheet-wrap .stripe-input-box>*:last-child{border-bottom:none}.stripe-payment-sheet-wrap .stripe-input-column>*{border-right:1px solid var(--color-input-border)}.stripe-payment-sheet-wrap .stripe-input-column>*:last-child{border-right:none}.stripe-payment-sheet-wrap .stripe-heading{font-size:24px;font-weight:bold;color:var(--color-heading-text);margin-bottom:24px}.stripe-payment-sheet-wrap .stripe-section-title{font-size:14px;font-weight:bold;color:var(--color-label);margin-bottom:8px}.stripe-payment-sheet-wrap .payment-info label{color:var(--color-label)}.stripe-payment-sheet-wrap .stripe-element-errors{margin-top:8px;font-size:14px;color:var(--color-text-error)}.stripe-payment-sheet-wrap button{display:block;color:var(--color-button-text);background-color:var(--color-primary);width:100%;text-align:center;padding:16px 16px;font-size:18px;border-radius:6px;min-height:42px}.stripe-payment-sheet-wrap button:disabled{color:var(--color-button-text-disabled)}";
3262
7
 
3263
8
  const StripeCardElement = class {
3264
9
  /**
@@ -3354,13 +99,18 @@ const StripeCardElement = class {
3354
99
  }
3355
100
  updatePublishableKey(publishableKey) {
3356
101
  const options = {};
3357
- options.stripeAccount = this.stripeService.state.stripeAccount;
3358
- const hasOptionValue = Object.values(options).filter(Boolean).length > 0;
3359
- this.initStripe(publishableKey, hasOptionValue ? options : undefined);
102
+ if (this.stripeAccount) {
103
+ options.stripeAccount = this.stripeAccount;
104
+ }
105
+ this.initStripe(publishableKey, Object.keys(options).length ? options : undefined);
3360
106
  }
3361
107
  updateStripeAccountId(stripeAccount) {
3362
- this.initStripe(this.stripeService.state.publishableKey, {
3363
- stripeAccount: stripeAccount,
108
+ const publishableKey = this.stripeService.state.publishableKey || this.publishableKey;
109
+ if (!publishableKey) {
110
+ return;
111
+ }
112
+ this.initStripe(publishableKey, {
113
+ stripeAccount,
3364
114
  });
3365
115
  }
3366
116
  /**
@@ -3398,7 +148,7 @@ const StripeCardElement = class {
3398
148
  async defaultFormSubmitResultHandler(result) {
3399
149
  this.defaultFormSubmitResult.emit(result);
3400
150
  }
3401
- componentWillUpdate() {
151
+ componentWillRender() {
3402
152
  if (!this.stripeService.state.publishableKey) {
3403
153
  return;
3404
154
  }
@@ -3408,7 +158,6 @@ const StripeCardElement = class {
3408
158
  this.initStripe(this.stripeService.state.publishableKey, {
3409
159
  stripeAccount: this.stripeService.state.stripeAccount,
3410
160
  });
3411
- this.createPaymentRequestButton();
3412
161
  }
3413
162
  /**
3414
163
  * Default form submit action (just call a confirmCardPayment).
@@ -3450,6 +199,8 @@ const StripeCardElement = class {
3450
199
  this.stripeLoaded = createEvent(this, "stripeLoaded");
3451
200
  this.formSubmit = createEvent(this, "formSubmit");
3452
201
  this.defaultFormSubmitResult = createEvent(this, "defaultFormSubmitResult");
202
+ // Track if payment request button has been created to prevent duplicates
203
+ this.paymentRequestButtonCreated = false;
3453
204
  /**
3454
205
  * Default submit handle type.
3455
206
  * If you want to use `setupIntent`, should update this attribute.
@@ -3563,6 +314,13 @@ const StripeCardElement = class {
3563
314
  componentDidLoad() {
3564
315
  this.el.classList.add(checkPlatform());
3565
316
  }
317
+ componentDidRender() {
318
+ // Safely create payment request button after DOM is ready
319
+ // Only runs if conditions are met and button hasn't been created yet
320
+ if (this.showPaymentRequestButton && this.paymentRequestOption && !this.paymentRequestButtonCreated) {
321
+ this.createPaymentRequestButton();
322
+ }
323
+ }
3566
324
  disconnectedCallback() {
3567
325
  this.cardElementManager.unmount();
3568
326
  }
@@ -3572,6 +330,10 @@ const StripeCardElement = class {
3572
330
  */
3573
331
  createPaymentRequestButton() {
3574
332
  const { showPaymentRequestButton, paymentRequestOption } = this;
333
+ // Guard: prevent duplicate creation
334
+ if (this.paymentRequestButtonCreated) {
335
+ return null;
336
+ }
3575
337
  if (!showPaymentRequestButton || !paymentRequestOption) {
3576
338
  return null;
3577
339
  }
@@ -3583,6 +345,11 @@ const StripeCardElement = class {
3583
345
  console.error('Target element #stripe-payment-request-button not found');
3584
346
  return null;
3585
347
  }
348
+ // Check if button already exists in DOM to prevent duplicates
349
+ if (targetElement.querySelector('stripe-payment-request-button')) {
350
+ this.paymentRequestButtonCreated = true;
351
+ return null;
352
+ }
3586
353
  const stripePaymentRequestElement = document.createElement('stripe-payment-request-button');
3587
354
  targetElement.appendChild(stripePaymentRequestElement);
3588
355
  const { paymentRequestPaymentMethodHandler, paymentRequestShippingOptionChangeHandler, paymentRequestShippingAddressChangeHandler } = paymentRequestOption;
@@ -3599,6 +366,8 @@ const StripeCardElement = class {
3599
366
  }
3600
367
  return stripePaymentRequestElement.initStripe(this.publishableKey);
3601
368
  });
369
+ // Mark as created
370
+ this.paymentRequestButtonCreated = true;
3602
371
  }
3603
372
  render() {
3604
373
  const { loadStripeStatus } = this.stripeService.state;
@@ -3607,7 +376,7 @@ const StripeCardElement = class {
3607
376
  return h("p", null, i18n.t('Failed to load Stripe'));
3608
377
  }
3609
378
  const disabled = this.progress === 'loading';
3610
- return (h("div", { class: "stripe-payment-sheet-wrap" }, h("form", { id: "stripe-card-element" }, h("div", { class: "stripe-heading" }, i18n.t(this.sheetTitle)), h("div", { id: "stripe-payment-request-button" }), h("div", null, h("div", { class: "stripe-section-title" }, i18n.t('Card information'))), h("div", { class: "payment-info card visible" }, h("fieldset", { class: "stripe-input-box" }, h("div", null, h("label", null, this.showLabel ? h("lenged", null, i18n.t('Card Number')) : null, h("div", { id: "card-number" }))), h("div", { class: "stripe-input-column", style: { display: 'flex' } }, h("label", { style: { width: '50%' } }, this.showLabel ? h("lenged", null, i18n.t('MM / YY')) : null, h("div", { id: "card-expiry" })), h("label", { style: { width: '50%' } }, this.showLabel ? h("lenged", null, i18n.t('CVC')) : null, h("div", { id: "card-cvc" }))))), h("div", { id: "card-errors", class: "stripe-element-errors" }, errorMessage), this.zip ? (h("div", { style: { marginTop: '1.5rem' } }, h("div", { class: "stripe-section-title" }, i18n.t('Country or region')))) : null, this.zip ? (h("div", { class: "payment-info card visible" }, h("fieldset", { class: "stripe-input-box" }, h("div", null, h("label", null, this.showLabel ? h("lenged", null, i18n.t('Postal Code')) : null, h("input", { id: "zip", name: "zip", type: "text", inputmode: "numeric", class: "stripe-input-box StripeElement", style: { width: '100%' }, placeholder: i18n.t('Postal Code'), value: this.zipCode, onInput: e => {
379
+ return (h("div", { class: "stripe-payment-sheet-wrap" }, h("form", { id: "stripe-card-element" }, h("div", { class: "stripe-heading" }, i18n.t(this.sheetTitle)), h("div", { id: "stripe-payment-request-button" }), h("div", null, h("div", { class: "stripe-section-title" }, i18n.t('Card information'))), h("div", { class: "payment-info card visible" }, h("fieldset", { class: "stripe-input-box" }, h("div", null, h("label", null, this.showLabel ? h("lenged", null, i18n.t('Card Number')) : null, h("div", { id: "card-number" }))), h("div", { class: "stripe-input-column", style: { display: 'flex' } }, h("label", { style: { width: '50%' } }, this.showLabel ? h("lenged", null, i18n.t('MM / YY')) : null, h("div", { id: "card-expiry" })), h("label", { style: { width: '50%' } }, this.showLabel ? h("lenged", null, i18n.t('CVC')) : null, h("div", { id: "card-cvc" }))))), h("div", { id: "card-errors", class: "stripe-element-errors" }, errorMessage), this.zip ? (h("div", { style: { marginTop: '1.5rem' } }, h("div", { class: "stripe-section-title" }, i18n.t('Country or region')))) : null, this.zip ? (h("div", { class: "payment-info card visible" }, h("fieldset", { class: "stripe-input-box" }, h("div", null, h("label", null, this.showLabel ? h("lenged", null, i18n.t('Postal Code')) : null, h("input", { id: "zip", name: "zip", type: "text", inputmode: "numeric", class: "StripeElement", style: { width: '100%' }, placeholder: i18n.t('Postal Code'), value: this.zipCode, onInput: e => {
3611
380
  this.zipCode = e.target.value;
3612
381
  } })))))) : null, h("div", { style: { marginTop: '32px' } }, h("button", { type: "submit", disabled: disabled }, this.progress === 'loading' ? i18n.t('Loading') : i18n.t(this.buttonLabel))))));
3613
382
  }
@@ -3619,7 +388,7 @@ const StripeCardElement = class {
3619
388
  };
3620
389
  StripeCardElement.style = stripeCardElementCss;
3621
390
 
3622
- const stripeModalCss = "*:where(:not(iframe,canvas,img,svg,video):not(svg *)){all:unset;display:revert;background:none;border:none;font-family:\"Roboto\", sans-serif;box-sizing:border-box}button{cursor:pointer}:root{--color-label:#565656;--color-placeholder:#acacac;--color-heading-text:#333;--color-text-error:#ef4444;--color-input-border:#e4e4e6;--color-button-text:rgba(255, 255, 255, 0.95);--color-button-text-disabled:rgba(255, 255, 255, 0.4);--color-primary:#0074d4}:host{display:block}.modal-row{display:none}.modal-row.open{position:fixed;top:0;left:0;width:100%;height:100%;display:flex;flex-direction:column;align-items:center;justify-content:flex-end;gap:1ch;background:rgba(0, 0, 0, 0.3)}.modal-child{padding:1.5rem;background-color:#fff;width:100%}.modal-close-button-wrap{padding-left:8px}.modal-close-button-wrap .modal-close-button{width:32px;display:block;fill:var(--color-label);cursor:pointer}";
391
+ const stripeModalCss = ":root{--color-label:#565656;--color-placeholder:#acacac;--color-heading-text:#333;--color-text-error:#ef4444;--color-input-border:#e4e4e6;--color-input-border-shadow:rgba(228, 228, 230, 0.6);--color-button-text:rgba(255, 255, 255, 0.95);--color-button-text-disabled:rgba(255, 255, 255, 0.4);--color-primary:#0074d4}:host{box-sizing:border-box}:host *:where(:not(iframe,canvas,img,svg,video):not(svg *)){all:unset;display:revert;background:none;border:none;font-family:\"Roboto\", sans-serif;box-sizing:border-box}:host button{cursor:pointer}:host{display:block}.modal-row{display:none}.modal-row.open{position:fixed;top:0;left:0;width:100%;height:100%;display:flex;flex-direction:column;align-items:center;justify-content:flex-end;gap:1ch;background:rgba(0, 0, 0, 0.3)}.modal-child{padding:1.5rem;background-color:#fff;width:100%}.modal-close-button-wrap{padding-left:8px}.modal-close-button-wrap .modal-close-button{width:32px;display:block;fill:var(--color-label);cursor:pointer}";
3623
392
 
3624
393
  const StripeModal = class {
3625
394
  constructor(hostRef) {
@@ -3659,12 +428,13 @@ const StripeModal = class {
3659
428
  }
3660
429
  componentDidLoad() {
3661
430
  const platformName = checkPlatform();
3662
- if (platformName)
431
+ if (platformName) {
3663
432
  this.el.classList.add(platformName);
433
+ }
3664
434
  }
3665
435
  render() {
3666
436
  const { open, showCloseButton } = this;
3667
- return (h(Host, { key: '9546b5a9b619977c8040aa2f249d40f8be3f781f' }, h("div", { key: '7a8aa0e76c1887f8233dab951e601970a3479a3a', class: `modal-row${open ? ' open' : ''}`, onClick: () => this.closeModal() }, h("div", { key: '857748624c7a151fb24aa1f895a247fde51337b6', class: "modal-child", onClick: e => e.stopPropagation() }, showCloseButton ? (h("div", { class: "modal-close-button-wrap" }, h("ion-icon", { name: "close", size: "large", class: "modal-close-button", onClick: () => this.closeModal() }))) : null, h("slot", { key: '72e8d7f32992a47a8c77f704b331f1e445f66054' })))));
437
+ return (h(Host, { key: 'dfa78b7d698fdd6acc64744ab439174e848e7a85' }, h("div", { key: '74059148e192ea487da5031c1c91a22fe145f25e', class: `modal-row${open ? ' open' : ''}`, onClick: () => this.closeModal() }, h("div", { key: '269150f5de77e1a0bedc036bec089246c61082c9', class: "modal-child", onClick: e => e.stopPropagation() }, showCloseButton ? (h("div", { class: "modal-close-button-wrap" }, h("ion-icon", { name: "close", size: "large", class: "modal-close-button", onClick: () => this.closeModal() }))) : null, h("slot", { key: 'cf4545695cab28ddd5d72122a8f550d046c8c710' })))));
3668
438
  }
3669
439
  get el() { return getElement(this); }
3670
440
  };