zignal-stencil-library 1.1.129 → 1.1.131

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