@intlayer/design-system 3.5.6 → 3.5.8

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 (258) hide show
  1. package/dist/.vite/manifest.json +92 -168
  2. package/dist/Form-0D7KBafQ.cjs +311 -0
  3. package/dist/Form-0D7KBafQ.cjs.map +1 -0
  4. package/dist/Form-7BqwvjVI.cjs +320 -0
  5. package/dist/Form-7BqwvjVI.cjs.map +1 -0
  6. package/dist/Form-B2UufQRJ.cjs +319 -0
  7. package/dist/Form-B2UufQRJ.cjs.map +1 -0
  8. package/dist/Form-BDcoNTLV.cjs.map +1 -1
  9. package/dist/Form-BTogr-fp.js +312 -0
  10. package/dist/Form-BTogr-fp.js.map +1 -0
  11. package/dist/Form-BVkkvSKP.js +312 -0
  12. package/dist/Form-BVkkvSKP.js.map +1 -0
  13. package/dist/Form-Be6Uhb5-.js +312 -0
  14. package/dist/Form-Be6Uhb5-.js.map +1 -0
  15. package/dist/Form-BmQQnl-6.js +312 -0
  16. package/dist/Form-BmQQnl-6.js.map +1 -0
  17. package/dist/Form-Bp_ubH9I.cjs +311 -0
  18. package/dist/Form-Bp_ubH9I.cjs.map +1 -0
  19. package/dist/Form-BtqRbgLu.cjs +311 -0
  20. package/dist/Form-BtqRbgLu.cjs.map +1 -0
  21. package/dist/Form-COVZyto7.cjs +311 -0
  22. package/dist/Form-COVZyto7.cjs.map +1 -0
  23. package/dist/Form-CVD_3nCD.js +312 -0
  24. package/dist/Form-CVD_3nCD.js.map +1 -0
  25. package/dist/Form-Cfklj1_H.js +320 -0
  26. package/dist/Form-Cfklj1_H.js.map +1 -0
  27. package/dist/Form-ClAAiVNm.cjs +311 -0
  28. package/dist/Form-ClAAiVNm.cjs.map +1 -0
  29. package/dist/Form-DhsgC7kB.js.map +1 -1
  30. package/dist/Form-OK9zfg6E.js +321 -0
  31. package/dist/Form-OK9zfg6E.js.map +1 -0
  32. package/dist/components/Accordion/Accordion.cjs +7 -15
  33. package/dist/components/Accordion/Accordion.cjs.map +1 -1
  34. package/dist/components/Accordion/Accordion.d.ts +0 -1
  35. package/dist/components/Accordion/Accordion.d.ts.map +1 -1
  36. package/dist/components/Accordion/Accordion.mjs +8 -16
  37. package/dist/components/Accordion/Accordion.mjs.map +1 -1
  38. package/dist/components/Auth/ChangePasswordForm/ChangePasswordForm.cjs +1 -1
  39. package/dist/components/Auth/ChangePasswordForm/ChangePasswordForm.mjs +1 -1
  40. package/dist/components/Auth/ChangePasswordForm/useChangePasswordSchema.d.ts +4 -4
  41. package/dist/components/Auth/ExternalsLoginButtons/ExternalsLoginButtons.cjs +3 -3
  42. package/dist/components/Auth/ExternalsLoginButtons/ExternalsLoginButtons.cjs.map +1 -1
  43. package/dist/components/Auth/ExternalsLoginButtons/ExternalsLoginButtons.mjs +1 -1
  44. package/dist/components/Auth/ExternalsLoginButtons/ExternalsLoginButtons.mjs.map +1 -1
  45. package/dist/components/Auth/ResetPasswordForm/ResetPasswordForm.cjs +1 -1
  46. package/dist/components/Auth/ResetPasswordForm/ResetPasswordForm.mjs +1 -1
  47. package/dist/components/Auth/SignInForm/SignInForm.cjs +1 -1
  48. package/dist/components/Auth/SignInForm/SignInForm.mjs +1 -1
  49. package/dist/components/Auth/SignUpForm/SignUpForm.cjs +1 -1
  50. package/dist/components/Auth/SignUpForm/SignUpForm.mjs +1 -1
  51. package/dist/components/Auth/useAuth/useCSRF.cjs +2 -2
  52. package/dist/components/Auth/useAuth/useCSRF.cjs.map +1 -1
  53. package/dist/components/Auth/useAuth/useCSRF.d.ts +1 -1
  54. package/dist/components/Auth/useAuth/useCSRF.mjs +1 -1
  55. package/dist/components/Auth/useAuth/useCSRF.mjs.map +1 -1
  56. package/dist/components/Auth/useAuth/useOAuth2.cjs +2 -2
  57. package/dist/components/Auth/useAuth/useOAuth2.cjs.map +1 -1
  58. package/dist/components/Auth/useAuth/useOAuth2.d.ts +1 -1
  59. package/dist/components/Auth/useAuth/useOAuth2.mjs +1 -1
  60. package/dist/components/Auth/useAuth/useOAuth2.mjs.map +1 -1
  61. package/dist/components/Auth/useAuth/useSession.cjs +2 -2
  62. package/dist/components/Auth/useAuth/useSession.cjs.map +1 -1
  63. package/dist/components/Auth/useAuth/useSession.mjs +1 -1
  64. package/dist/components/Auth/useAuth/useSession.mjs.map +1 -1
  65. package/dist/components/Button/Button.cjs +47 -25
  66. package/dist/components/Button/Button.cjs.map +1 -1
  67. package/dist/components/Button/Button.d.ts +2 -0
  68. package/dist/components/Button/Button.d.ts.map +1 -1
  69. package/dist/components/Button/Button.mjs +47 -25
  70. package/dist/components/Button/Button.mjs.map +1 -1
  71. package/dist/components/Container/index.cjs +1 -1
  72. package/dist/components/Container/index.cjs.map +1 -1
  73. package/dist/components/Container/index.mjs +1 -1
  74. package/dist/components/Container/index.mjs.map +1 -1
  75. package/dist/components/CopyToClipboard/index.cjs +1 -1
  76. package/dist/components/CopyToClipboard/index.cjs.map +1 -1
  77. package/dist/components/CopyToClipboard/index.d.ts.map +1 -1
  78. package/dist/components/CopyToClipboard/index.mjs +1 -1
  79. package/dist/components/CopyToClipboard/index.mjs.map +1 -1
  80. package/dist/components/DictionaryEditor/ItemLayout.cjs +0 -1
  81. package/dist/components/DictionaryEditor/ItemLayout.cjs.map +1 -1
  82. package/dist/components/DictionaryEditor/ItemLayout.d.ts.map +1 -1
  83. package/dist/components/DictionaryEditor/ItemLayout.mjs +0 -1
  84. package/dist/components/DictionaryEditor/ItemLayout.mjs.map +1 -1
  85. package/dist/components/DictionaryEditor/ValidDictionaryChangeButtons.cjs +1 -1
  86. package/dist/components/DictionaryEditor/ValidDictionaryChangeButtons.mjs +1 -1
  87. package/dist/components/DictionaryFieldEditor/DictionariesSelector/DictionariesSelector.cjs +2 -2
  88. package/dist/components/DictionaryFieldEditor/DictionariesSelector/DictionariesSelector.mjs +2 -2
  89. package/dist/components/DictionaryFieldEditor/DictionaryCreationForm/DictionaryCreationForm.cjs +2 -2
  90. package/dist/components/DictionaryFieldEditor/DictionaryCreationForm/DictionaryCreationForm.mjs +2 -2
  91. package/dist/components/DictionaryFieldEditor/DictionaryDetails/DictionaryDetailsForm.cjs +2 -2
  92. package/dist/components/DictionaryFieldEditor/DictionaryDetails/DictionaryDetailsForm.mjs +2 -2
  93. package/dist/components/DictionaryFieldEditor/DictionaryFieldEditor.cjs +2 -2
  94. package/dist/components/DictionaryFieldEditor/DictionaryFieldEditor.cjs.map +1 -1
  95. package/dist/components/DictionaryFieldEditor/DictionaryFieldEditor.d.ts.map +1 -1
  96. package/dist/components/DictionaryFieldEditor/DictionaryFieldEditor.mjs +2 -2
  97. package/dist/components/DictionaryFieldEditor/DictionaryFieldEditor.mjs.map +1 -1
  98. package/dist/components/DictionaryFieldEditor/EditorView/EditorView.cjs +2 -2
  99. package/dist/components/DictionaryFieldEditor/EditorView/EditorView.mjs +2 -2
  100. package/dist/components/DictionaryFieldEditor/EditorView/TextEditor.cjs +14 -13
  101. package/dist/components/DictionaryFieldEditor/EditorView/TextEditor.cjs.map +1 -1
  102. package/dist/components/DictionaryFieldEditor/EditorView/TextEditor.d.ts.map +1 -1
  103. package/dist/components/DictionaryFieldEditor/EditorView/TextEditor.mjs +15 -14
  104. package/dist/components/DictionaryFieldEditor/EditorView/TextEditor.mjs.map +1 -1
  105. package/dist/components/DictionaryFieldEditor/JSONEditor.cjs +2 -2
  106. package/dist/components/DictionaryFieldEditor/JSONEditor.mjs +2 -2
  107. package/dist/components/DictionaryFieldEditor/NavigationView/NavigationViewNode.cjs +6 -10
  108. package/dist/components/DictionaryFieldEditor/NavigationView/NavigationViewNode.cjs.map +1 -1
  109. package/dist/components/DictionaryFieldEditor/NavigationView/NavigationViewNode.d.ts.map +1 -1
  110. package/dist/components/DictionaryFieldEditor/NavigationView/NavigationViewNode.mjs +6 -10
  111. package/dist/components/DictionaryFieldEditor/NavigationView/NavigationViewNode.mjs.map +1 -1
  112. package/dist/components/DictionaryFieldEditor/NodeEditor.cjs +2 -2
  113. package/dist/components/DictionaryFieldEditor/NodeEditor.mjs +2 -2
  114. package/dist/components/DictionaryFieldEditor/NodeTypeSelector.cjs +2 -2
  115. package/dist/components/DictionaryFieldEditor/NodeTypeSelector.mjs +2 -2
  116. package/dist/components/DictionaryFieldEditor/SaveForm/SaveForm.cjs +2 -2
  117. package/dist/components/DictionaryFieldEditor/SaveForm/SaveForm.mjs +2 -2
  118. package/dist/components/DictionaryFieldEditor/VersionSwitcherDropDown/VersionSwitcherContext.cjs +1 -1
  119. package/dist/components/DictionaryFieldEditor/VersionSwitcherDropDown/VersionSwitcherContext.mjs +1 -1
  120. package/dist/components/Form/Form.cjs +1 -1
  121. package/dist/components/Form/Form.d.ts +2 -0
  122. package/dist/components/Form/Form.d.ts.map +1 -1
  123. package/dist/components/Form/Form.mjs +1 -1
  124. package/dist/components/Form/elements/AutoSizeTextAreaElement.cjs +7 -0
  125. package/dist/components/Form/elements/AutoSizeTextAreaElement.cjs.map +1 -0
  126. package/dist/components/Form/elements/AutoSizeTextAreaElement.d.ts +9 -0
  127. package/dist/components/Form/elements/AutoSizeTextAreaElement.d.ts.map +1 -0
  128. package/dist/components/Form/elements/AutoSizeTextAreaElement.mjs +7 -0
  129. package/dist/components/Form/elements/AutoSizeTextAreaElement.mjs.map +1 -0
  130. package/dist/components/Form/elements/CheckboxElement.cjs +1 -1
  131. package/dist/components/Form/elements/CheckboxElement.mjs +1 -1
  132. package/dist/components/Form/elements/EditableFieldInputElement.cjs +1 -1
  133. package/dist/components/Form/elements/EditableFieldInputElement.mjs +1 -1
  134. package/dist/components/Form/elements/EditableFieldTextAreaElement.cjs +1 -1
  135. package/dist/components/Form/elements/EditableFieldTextAreaElement.mjs +1 -1
  136. package/dist/components/Form/elements/FormElement.cjs +1 -1
  137. package/dist/components/Form/elements/FormElement.mjs +1 -1
  138. package/dist/components/Form/elements/InputElement.cjs +1 -1
  139. package/dist/components/Form/elements/InputElement.mjs +1 -1
  140. package/dist/components/Form/elements/InputPasswordElement.cjs +1 -1
  141. package/dist/components/Form/elements/InputPasswordElement.mjs +1 -1
  142. package/dist/components/Form/elements/MultiselectElement.cjs +1 -1
  143. package/dist/components/Form/elements/MultiselectElement.mjs +1 -1
  144. package/dist/components/Form/elements/SelectElement.cjs +1 -1
  145. package/dist/components/Form/elements/SelectElement.mjs +1 -1
  146. package/dist/components/Form/elements/SwitchSelectorElement.cjs +1 -1
  147. package/dist/components/Form/elements/SwitchSelectorElement.mjs +1 -1
  148. package/dist/components/Form/elements/TextAreaElement.cjs +1 -1
  149. package/dist/components/Form/elements/TextAreaElement.mjs +1 -1
  150. package/dist/components/Form/elements/index.cjs +1 -1
  151. package/dist/components/Form/elements/index.mjs +1 -1
  152. package/dist/components/Form/index.cjs +1 -1
  153. package/dist/components/Form/index.mjs +1 -1
  154. package/dist/components/Form/layout/FormItemLayout.cjs +1 -1
  155. package/dist/components/Form/layout/FormItemLayout.d.ts.map +1 -1
  156. package/dist/components/Form/layout/FormItemLayout.mjs +1 -1
  157. package/dist/components/Form/layout/index.cjs +1 -1
  158. package/dist/components/Form/layout/index.mjs +1 -1
  159. package/dist/components/IDE/Code.cjs +1 -1
  160. package/dist/components/IDE/Code.cjs.map +1 -1
  161. package/dist/components/IDE/Code.mjs +1 -1
  162. package/dist/components/IDE/Code.mjs.map +1 -1
  163. package/dist/components/IDE/CodeContext.cjs +1 -1
  164. package/dist/components/IDE/CodeContext.mjs +1 -1
  165. package/dist/components/Link/Link.cjs +3 -4
  166. package/dist/components/Link/Link.cjs.map +1 -1
  167. package/dist/components/Link/Link.d.ts +1 -1
  168. package/dist/components/Link/Link.d.ts.map +1 -1
  169. package/dist/components/Link/Link.mjs +3 -4
  170. package/dist/components/Link/Link.mjs.map +1 -1
  171. package/dist/components/Loader/index.cjs +6 -1
  172. package/dist/components/Loader/index.cjs.map +1 -1
  173. package/dist/components/Loader/index.content.cjs +23 -0
  174. package/dist/components/Loader/index.content.cjs.map +1 -0
  175. package/dist/components/Loader/index.content.d.ts +8 -0
  176. package/dist/components/Loader/index.content.d.ts.map +1 -0
  177. package/dist/components/Loader/index.content.mjs +23 -0
  178. package/dist/components/Loader/index.content.mjs.map +1 -0
  179. package/dist/components/Loader/index.d.ts +2 -2
  180. package/dist/components/Loader/index.d.ts.map +1 -1
  181. package/dist/components/Loader/index.mjs +6 -1
  182. package/dist/components/Loader/index.mjs.map +1 -1
  183. package/dist/components/LocaleSwitcherContentDropDown/LocaleSwitcherContent.cjs +1 -1
  184. package/dist/components/LocaleSwitcherContentDropDown/LocaleSwitcherContent.mjs +1 -1
  185. package/dist/components/LocaleSwitcherContentDropDown/LocaleSwitcherContentContext.cjs +1 -1
  186. package/dist/components/LocaleSwitcherContentDropDown/LocaleSwitcherContentContext.mjs +1 -1
  187. package/dist/components/MarkDownRender/index.cjs +39 -4
  188. package/dist/components/MarkDownRender/index.cjs.map +1 -1
  189. package/dist/components/MarkDownRender/index.d.ts.map +1 -1
  190. package/dist/components/MarkDownRender/index.mjs +40 -5
  191. package/dist/components/MarkDownRender/index.mjs.map +1 -1
  192. package/dist/components/Modal/Modal.cjs +19 -11
  193. package/dist/components/Modal/Modal.cjs.map +1 -1
  194. package/dist/components/Modal/Modal.d.ts +1 -1
  195. package/dist/components/Modal/Modal.d.ts.map +1 -1
  196. package/dist/components/Modal/Modal.mjs +20 -12
  197. package/dist/components/Modal/Modal.mjs.map +1 -1
  198. package/dist/components/Navbar/MobileNavbar.cjs +1 -1
  199. package/dist/components/Navbar/MobileNavbar.mjs +1 -1
  200. package/dist/components/Navbar/index.cjs +1 -1
  201. package/dist/components/Navbar/index.mjs +1 -1
  202. package/dist/components/SwitchSelector/index.cjs +1 -1
  203. package/dist/components/SwitchSelector/index.mjs +1 -1
  204. package/dist/components/TabSelector/TabSelector.cjs +1 -1
  205. package/dist/components/TabSelector/TabSelector.mjs +1 -1
  206. package/dist/components/index.cjs +1 -1
  207. package/dist/components/index.mjs +1 -1
  208. package/dist/hooks/index.cjs +1 -0
  209. package/dist/hooks/index.cjs.map +1 -1
  210. package/dist/hooks/index.mjs +2 -1
  211. package/dist/hooks/intlayerAPIHooks.cjs +2 -0
  212. package/dist/hooks/intlayerAPIHooks.cjs.map +1 -1
  213. package/dist/hooks/intlayerAPIHooks.d.ts +50 -49
  214. package/dist/hooks/intlayerAPIHooks.d.ts.map +1 -1
  215. package/dist/hooks/intlayerAPIHooks.mjs +2 -0
  216. package/dist/hooks/intlayerAPIHooks.mjs.map +1 -1
  217. package/dist/hooks/useAsync/useAsync.cjs +81 -78
  218. package/dist/hooks/useAsync/useAsync.cjs.map +1 -1
  219. package/dist/hooks/useAsync/useAsync.d.ts +5 -25
  220. package/dist/hooks/useAsync/useAsync.d.ts.map +1 -1
  221. package/dist/hooks/useAsync/useAsync.mjs +81 -78
  222. package/dist/hooks/useAsync/useAsync.mjs.map +1 -1
  223. package/dist/hooks/useAsync/useAsyncStateStore.cjs +2 -2
  224. package/dist/hooks/useAsync/useAsyncStateStore.cjs.map +1 -1
  225. package/dist/hooks/useAsync/useAsyncStateStore.d.ts +1 -1
  226. package/dist/hooks/useAsync/useAsyncStateStore.mjs +2 -2
  227. package/dist/hooks/useAsync/useAsyncStateStore.mjs.map +1 -1
  228. package/dist/hooks/useGetAllDictionaries.cjs +2 -2
  229. package/dist/hooks/useGetAllDictionaries.cjs.map +1 -1
  230. package/dist/hooks/useGetAllDictionaries.d.ts +1 -1
  231. package/dist/hooks/useGetAllDictionaries.d.ts.map +1 -1
  232. package/dist/hooks/useGetAllDictionaries.mjs +2 -2
  233. package/dist/hooks/useGetAllDictionaries.mjs.map +1 -1
  234. package/dist/hooks/useIntlayerAPI.cjs +2 -2
  235. package/dist/hooks/useIntlayerAPI.cjs.map +1 -1
  236. package/dist/hooks/useIntlayerAPI.d.ts +59 -58
  237. package/dist/hooks/useIntlayerAPI.d.ts.map +1 -1
  238. package/dist/hooks/useIntlayerAPI.mjs +1 -1
  239. package/dist/hooks/useIntlayerAPI.mjs.map +1 -1
  240. package/dist/hooks/usePersistedStore.cjs +7 -5
  241. package/dist/hooks/usePersistedStore.cjs.map +1 -1
  242. package/dist/hooks/usePersistedStore.d.ts.map +1 -1
  243. package/dist/hooks/usePersistedStore.mjs +7 -5
  244. package/dist/hooks/usePersistedStore.mjs.map +1 -1
  245. package/dist/index-DFc7og1d.cjs +671 -0
  246. package/dist/index-DFc7og1d.cjs.map +1 -0
  247. package/dist/index-DcWYZrJW.js +672 -0
  248. package/dist/index-DcWYZrJW.js.map +1 -0
  249. package/dist/libs/intlayer-api/ai.cjs +11 -1
  250. package/dist/libs/intlayer-api/ai.cjs.map +1 -1
  251. package/dist/libs/intlayer-api/ai.d.ts +3 -1
  252. package/dist/libs/intlayer-api/ai.d.ts.map +1 -1
  253. package/dist/libs/intlayer-api/ai.mjs +11 -1
  254. package/dist/libs/intlayer-api/ai.mjs.map +1 -1
  255. package/dist/libs/intlayer-api/index.d.ts +2 -0
  256. package/dist/libs/intlayer-api/index.d.ts.map +1 -1
  257. package/dist/tailwind.css +1 -1
  258. package/package.json +18 -16
@@ -1 +1 @@
1
- {"version":3,"file":"useAsync.mjs","sources":["../../../src/hooks/useAsync/useAsync.ts"],"sourcesContent":["'use client';\n\n// This is an ESLint directive to disable specific rules.\n/* eslint-disable @typescript-eslint/no-explicit-any */\n\nimport { useCallback, useEffect, useMemo, useRef } from 'react';\nimport { useAsyncState } from './useAsyncStateStore';\n\n// Pending promises cache to prevent parallel requests when multiple components use the hook\nconst pendingPromises = new Map();\n\n// Defines the base structure for the result of the custom hook.\ntype UseAsyncResultBase<T extends (...args: any[]) => Promise<any>> = {\n isFetched: boolean;\n isLoading: boolean;\n isInvalidated: boolean;\n isSuccess: boolean;\n isDisabled: boolean;\n error: string | null;\n data: Awaited<ReturnType<T>> | null;\n retryCount: number;\n revalidate: T;\n setData: (data: Awaited<ReturnType<T> | null>) => void;\n};\n\n// Options type for the hook, allowing customization of behavior.\nexport type UseAsyncOptions<T extends (...args: any[]) => Promise<any>> = {\n retryLimit?: number; // The number of times the hook should retry the function on failure before giving up\n retryTime?: number; // Time in milliseconds for retrying the data\n cache?: boolean; // Cache the result of the function using zustand\n store?: boolean; // Store the result of the function in session storage\n enable?: boolean; // Enable the hook\n autoFetch?: boolean; // Automatically fetch the data when the hook is mounted\n revalidation?: boolean; // Enable revalidation\n revalidateTime?: number; // Time in milliseconds for revalidating the data\n invalidateQueries?: string[]; // Invalidate other queries when the data is updated\n updateQueries?: string[]; // Update other queries when the data is updated\n onSuccess?: (data: Awaited<ReturnType<T>>) => void; // Callback function that is called when the asynchronous function resolves successfully\n onError?: (error: string) => void; // Callback function that is called when the asynchronous function rejects or encounters an error\n args?: Parameters<T>; // Arguments to pass to the asynchronous function\n};\n\n// Default values for the hook's options\nconst DEFAULT_CACHE_ENABLED = false;\nconst DEFAULT_STORE_ENABLED = false;\nconst DEFAULT_ENABLED = true;\nconst DEFAULT_AUTO_FETCH = false;\nconst DEFAULT_RETRY_LIMIT = 1;\nconst DEFAULT_REVALIDATION_ENABLED = false;\nconst DEFAULT_REVALIDATE_TIME = 5 * 60 * 1000; // 5 minutes\nconst DEFAULT_RETRY_TIME = 5 * 60 * 1000; // 5 minutes\n\n// The main hook type that includes the async function along with its additional properties.\nexport type UseAsyncResult<\n U extends string,\n T extends (...args: any[]) => Promise<any>,\n> = UseAsyncResultBase<T> & Record<U, T>;\n\nconst getArgs = (args?: any[]): any[] =>\n args ? (Array.isArray(args) ? args : [args]) : [];\n\nconst getKeyWithArgs = (key: string, args: any[]) =>\n getArgs(args).length > 0 ? `${key}/${JSON.stringify(args)}` : key;\n\n/**\n * A custom React hook that manages asynchronous operations, providing easy-to-use states and controls over fetching, caching, and retry mechanisms.\n * This hook abstracts away the complexity of handling loading, error, and success states for any asynchronous function.\n *\n * @template U - A string type that extends the keys of the async function, used as a key to store and retrieve state.\n * @template T - A function type that must return a Promise, representing the asynchronous operation to be managed.\n *\n * @param {U} key - A unique identifier for the async operation, used to handle state internally and avoid conflicts.\n * @param {T} asyncFunction - The asynchronous function that will be managed by this hook. This function should return a Promise.\n * @param {UseAsyncOptions<T>} [options] - Optional configuration options to customize the behavior of the hook.\n * @returns {UseAsyncResult<U, T>} The states and controls related to the managed async function. Includes states like isLoading, isSuccess, and provides control methods like revalidate and setData.\n *\n * @typedef {Object} UseAsyncOptions\n * @property {number} [retryTime=300000] - Time in milliseconds for retrying the data after an error occurs.\n * @property {number} [retryLimit=1] - The number of times the hook should retry the asynchronous function on failure before giving up.\n * @property {boolean} [revalidation=false] - Enable revalidation.\n * @property {number} [revalidateTime=300000] - Time in milliseconds after which the cached data is considered stale and the async function is re-invoked, if caching is enabled.\n * @property {boolean} [cache=false] - Whether to cache the result of the async function. When enabled, revalidation is controlled by `revalidateTime`.\n * @property {boolean} [store=false] - Store the result of the function in session storage.\n * @property {boolean} [autoFetch=false] - Whether the hook should automatically invoke the asynchronous function on mount.\n * @property {number} [revalidateTime=300000] - Time in milliseconds after which the cached data is considered stale and the async function is re-invoked, if caching is enabled.\n * @property {string[]} [updateQueries=[]] - Update other queries when the data is updated.\n * @property {string[]} [invalidateQueries=[]] - Invalidate other queries when the data is updated.\n * @property {(data: Awaited<ReturnType<T>>) => void} [onSuccess] - Callback function that is called when the asynchronous function resolves successfully.\n * @property {(error: string) => void} [onError] - Callback function that is called when the asynchronous function rejects or encounters an error.\n * @property {Parameters<T>} [args=[]] - Arguments to pass to the asynchronous function.\n *\n *\n * @example\n * // Example of using useAsync to manage fetching user data from an API.\n * const fetchUserData = async (userId) => {\n * const response = await fetch(`/api/users/${userId}`);\n * if (!response.ok) throw new Error('Failed to fetch');\n * return await response.json();\n * };\n *\n * const UserDetails = ({ userId }) => {\n * const {\n * isLoading,\n * data,\n * error,\n * revalidate,\n * } = useAsync('userDetails', fetchUserData, {\n * cache: true,\n * revalidateTime: 60000, // 1 minute\n * autoFetch: true,\n * onSuccess: (data) => console.log('User data fetched successfully:', data),\n * onError: (error) => console.error('Error fetching user data:', error),\n * });\n *\n * if (isLoading) return <div>Loading...</div>;\n * if (error) return <div>Error: {error}</div>;\n * return (\n * <div>\n * <h1>{data.name}</h1>\n * <button onClick={() => revalidate()}>Refresh</button>\n * </div>\n * );\n * };\n */\nexport const useAsync = <\n U extends string,\n T extends (...args: any[]) => Promise<any>,\n>(\n key: U,\n asyncFunction: T,\n options?: UseAsyncOptions<T>\n): UseAsyncResult<U, T> => {\n // Resolving optional parameters with default values\n const retryLimit = options?.retryLimit ?? DEFAULT_RETRY_LIMIT;\n const autoFetch = options?.autoFetch ?? DEFAULT_AUTO_FETCH;\n const retryTime = options?.retryTime ?? DEFAULT_RETRY_TIME;\n const cacheEnabled = options?.cache ?? DEFAULT_CACHE_ENABLED;\n const storeEnabled = options?.store ?? DEFAULT_STORE_ENABLED;\n const enabled = options?.enable ?? DEFAULT_ENABLED;\n const revalidationEnabled =\n options?.revalidation ?? DEFAULT_REVALIDATION_ENABLED;\n const revalidateTime = options?.revalidateTime ?? DEFAULT_REVALIDATE_TIME;\n const updateQueries = options?.updateQueries ?? [];\n const invalidateQueries = options?.invalidateQueries ?? [];\n const onSuccess = options?.onSuccess;\n const onError = options?.onError;\n const args = getArgs(options?.args ?? []);\n\n // Using a custom hook to manage state specific to asynchronous operations\n const { getStates, setQueryState, setQueriesState, makeQueryInError } =\n useAsyncState();\n\n // Storing the last arguments used to call the async function\n const storedArgsRef = useRef<any[]>(args);\n\n // Apply different key for different requests\n const keyWithArgs = getKeyWithArgs(key, storedArgsRef.current);\n\n // Retrieving the current state of async operations using the same custom hook\n const {\n isFetched,\n fetchedDateTime,\n isLoading,\n isEnabled,\n error,\n isSuccess,\n isInvalidated,\n data,\n retryCount: errorCount,\n } = getStates(keyWithArgs);\n\n // The core fetching function, designed to be called directly or automatically based on configuration\n const fetch: T = useCallback<T>(\n (async (...args) => {\n const keyWithArgs = getKeyWithArgs(key, args);\n\n if (pendingPromises.has(keyWithArgs)) {\n // Return the existing pending promise\n return pendingPromises.get(keyWithArgs);\n }\n\n const promise = (async () => {\n setQueryState(keyWithArgs, { isLoading: true });\n let response = null;\n\n await asyncFunction(...args)\n .then((result) => {\n response = result;\n\n setQueryState(keyWithArgs, {\n data: result,\n retryCount: 0,\n isLoading: false,\n isFetched: true,\n isSuccess: true,\n isInvalidated: false,\n error: null,\n });\n\n onSuccess?.(result);\n\n // Invalidate other queries if necessary\n if (invalidateQueries.length > 0) {\n setQueriesState(invalidateQueries, {\n isInvalidated: true,\n });\n }\n\n // Update other queries if necessary\n if (updateQueries.length > 0) {\n setQueriesState(updateQueries, {\n data: result,\n });\n }\n\n // Store the result in session storage\n if (storeEnabled) {\n sessionStorage.setItem(keyWithArgs, JSON.stringify(result));\n }\n })\n .catch((error) => {\n makeQueryInError(keyWithArgs, error.message);\n onError?.(error.message);\n })\n .finally(() => {\n // Remove the pending promise from the cache\n pendingPromises.delete(keyWithArgs);\n });\n\n return response;\n })();\n\n // Store the pending promise in the cache\n pendingPromises.set(keyWithArgs, promise);\n\n return await promise;\n }) as T,\n [asyncFunction, keyWithArgs, storeEnabled, cacheEnabled, onSuccess, onError]\n );\n\n // Wrapped execution function to handle disabled state and check for success before re-fetching\n const execute: T = useCallback<T>(\n (async (...args) => {\n if (!isEnabled || !enabled) return;\n if (isLoading) return;\n if (!isInvalidated && isSuccess && cacheEnabled && data) return data;\n\n if (args) {\n storedArgsRef.current = getArgs(...args);\n }\n\n return await fetch(...args);\n }) as T,\n [\n isEnabled,\n enabled,\n isInvalidated,\n cacheEnabled,\n isSuccess,\n data,\n isLoading,\n fetch,\n ]\n );\n\n // Function to revalidate the data when necessary\n const revalidate: T = useCallback<T>(\n (async (...args) => {\n if (!isEnabled || !enabled) return;\n\n if (args) {\n storedArgsRef.current = getArgs(...args);\n }\n\n const result = await fetch(...storedArgsRef.current);\n\n return result;\n }) as T,\n [isEnabled, enabled, storedArgsRef, fetch]\n );\n\n const autoRevalidate = useCallback(async () => {\n if (!isEnabled || !enabled) return;\n if (isLoading) return;\n if (!(cacheEnabled || storeEnabled)) return;\n if (!isSuccess) return;\n if (!revalidationEnabled || revalidateTime <= 0) return;\n if (!fetchedDateTime) return;\n\n const now = new Date().getTime();\n const lastFetchedTime = new Date(fetchedDateTime).getTime();\n const shouldRevalidate = now - lastFetchedTime >= revalidateTime;\n if (shouldRevalidate) {\n return await fetch(...storedArgsRef.current);\n }\n }, [\n cacheEnabled,\n revalidationEnabled,\n revalidateTime,\n isSuccess,\n fetchedDateTime,\n isLoading,\n isEnabled,\n enabled,\n ]);\n\n useEffect(() => {\n if (enabled !== isEnabled) {\n setQueryState(keyWithArgs, {\n isEnabled,\n });\n }\n }, [enabled, isEnabled, keyWithArgs]);\n\n // Auto-fetch data on hook mount if autoFetch is true\n useEffect(() => {\n if (!autoFetch) return;\n if (!isEnabled || !enabled) return;\n if (isFetched && !isInvalidated) return;\n if (isLoading) return;\n\n fetch(...storedArgsRef.current);\n }, [\n autoFetch,\n isFetched,\n isInvalidated,\n isEnabled,\n enabled,\n isLoading,\n fetch,\n ]);\n\n // Handle retry based on conditions set in options\n useEffect(() => {\n const isRetryEnabled = errorCount > 0 && retryLimit > 0;\n const isRetryLimitReached = errorCount >= retryLimit;\n if (!isEnabled || !enabled) return;\n if (!(cacheEnabled || storeEnabled)) return;\n if (!isRetryEnabled || isRetryLimitReached) return;\n if (isSuccess) return;\n if (isLoading) return;\n\n const timeOut = setTimeout(() => {\n fetch(...storedArgsRef.current);\n }, retryTime);\n\n return () => clearTimeout(timeOut);\n }, [\n fetch,\n errorCount,\n retryLimit,\n retryTime,\n isSuccess,\n isEnabled,\n enabled,\n isLoading,\n cacheEnabled,\n storeEnabled,\n ]);\n\n // Handle periodic revalidation if caching is enabled\n useEffect(() => {\n const interval = setInterval(autoRevalidate, revalidateTime);\n\n return () => clearInterval(interval);\n }, [autoRevalidate, revalidateTime]);\n\n // Load data from session storage if storeEnabled is true\n useEffect(() => {\n if (!isEnabled || !enabled) return;\n if (!storeEnabled) return;\n if (isInvalidated) return;\n if (isFetched) return;\n if (data) return;\n\n const storedData = sessionStorage.getItem(keyWithArgs);\n\n if (storedData && JSON.stringify(storedData) !== JSON.stringify(data)) {\n setQueryState(keyWithArgs, {\n data: JSON.parse(storedData),\n });\n }\n }, [\n storeEnabled,\n keyWithArgs,\n isFetched,\n isInvalidated,\n isEnabled,\n enabled,\n data,\n ]);\n\n // Memoization of the setData function to prevent unnecessary re-renders\n const setDataMemo = useCallback(\n (data: Awaited<ReturnType<T> | null>) => {\n setQueryState(keyWithArgs, {\n data,\n });\n },\n [keyWithArgs]\n );\n\n const memoResult = useMemo(\n () => ({\n isFetched,\n isLoading,\n isInvalidated,\n error,\n isSuccess,\n data,\n retryCount: errorCount,\n isDisabled: !isEnabled,\n isEnabled,\n [key]: execute,\n revalidate,\n setData: setDataMemo,\n }),\n [\n isFetched,\n isLoading,\n isInvalidated,\n error,\n isSuccess,\n data,\n errorCount,\n isEnabled,\n key,\n execute,\n revalidate,\n setDataMemo,\n ]\n );\n\n // Return the hook's result, including all state and control functions\n return memoResult as UseAsyncResultBase<T> & Record<U, T>;\n};\n"],"names":["args","keyWithArgs","error","data"],"mappings":";;;AASA,MAAM,sCAAsB,IAAI;AAkChC,MAAM,wBAAwB;AAC9B,MAAM,wBAAwB;AAC9B,MAAM,kBAAkB;AACxB,MAAM,qBAAqB;AAC3B,MAAM,sBAAsB;AAC5B,MAAM,+BAA+B;AACrC,MAAM,0BAA0B,IAAI,KAAK;AACzC,MAAM,qBAAqB,IAAI,KAAK;AAQpC,MAAM,UAAU,CAAC,SACf,OAAQ,MAAM,QAAQ,IAAI,IAAI,OAAO,CAAC,IAAI,IAAK,CAAC;AAElD,MAAM,iBAAiB,CAAC,KAAa,SACnC,QAAQ,IAAI,EAAE,SAAS,IAAI,GAAG,GAAG,IAAI,KAAK,UAAU,IAAI,CAAC,KAAK;AA8DzD,MAAM,WAAW,CAItB,KACA,eACA,YACyB;AAEnB,QAAA,aAAa,SAAS,cAAc;AACpC,QAAA,YAAY,SAAS,aAAa;AAClC,QAAA,YAAY,SAAS,aAAa;AAClC,QAAA,eAAe,SAAS,S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GO,SAAA;AACT;"}
1
+ {"version":3,"file":"useAsync.mjs","sources":["../../../src/hooks/useAsync/useAsync.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-explicit-any */\n\n'use client';\n\nimport { useCallback, useEffect, useMemo, useRef } from 'react';\nimport { useAsyncState } from './useAsyncStateStore';\n\n// Pending promises cache to prevent parallel requests when multiple components use the hook\nconst pendingPromises = new Map();\n\n// Defines the base structure for the result of the custom hook.\ntype UseAsyncResultBase<T extends (...args: any[]) => Promise<any>> = {\n isFetched: boolean;\n isLoading: boolean;\n isInvalidated: boolean;\n isSuccess: boolean;\n isDisabled: boolean;\n isWaitingData: boolean;\n isRevalidating: boolean;\n error: string | null;\n data: Awaited<ReturnType<T>> | null;\n errorCount: number;\n revalidate: T;\n setData: (data: Awaited<ReturnType<T> | null>) => void;\n};\n\n// Options type for the hook, allowing customization of behavior.\nexport type UseAsyncOptions<T extends (...args: any[]) => Promise<any>> = {\n retryLimit?: number; // The number of times the hook should retry the function on failure before giving up\n retryTime?: number; // Time in milliseconds for retrying the data\n cache?: boolean; // Cache the result of the function\n store?: boolean; // Store the result of the function in local storage\n enable?: boolean; // Enable the hook\n autoFetch?: boolean; // Automatically fetch the data when the hook is mounted\n revalidation?: boolean; // Enable revalidation\n revalidateTime?: number; // Time in milliseconds for revalidating the data\n invalidateQueries?: string[]; // Invalidate other queries when the data is updated\n updateQueries?: string[]; // Update other queries when the data is updated\n onSuccess?: (data: Awaited<ReturnType<T>>) => void; // Callback function that is called when the asynchronous function resolves successfully\n onError?: (error: string) => void; // Callback function that is called when the asynchronous function rejects or encounters an error\n args?: Parameters<T>; // Arguments to pass to the asynchronous function\n};\n\n// Default values for the hook's options\nconst DEFAULT_CACHE_ENABLED = false;\nconst DEFAULT_STORE_ENABLED = false;\nconst DEFAULT_ENABLED = true;\nconst DEFAULT_AUTO_FETCH = false;\nconst DEFAULT_RETRY_LIMIT = 1;\nconst DEFAULT_REVALIDATION_ENABLED = false;\nconst DEFAULT_REVALIDATE_TIME = 5 * 60 * 1000; // 5 minutes\nconst DEFAULT_RETRY_TIME = 5 * 60 * 1000; // 5 minutes\n\n// The main hook type that includes the async function along with its additional properties.\nexport type UseAsyncResult<\n U extends string,\n T extends (...args: any[]) => Promise<any>,\n> = UseAsyncResultBase<T> & Record<U, T>;\n\nconst getArgs = (args?: any[]): any[] =>\n args ? (Array.isArray(args) ? args : [args]) : [];\n\nconst getKeyWithArgs = (key: string, args: any[]) =>\n getArgs(args).length > 0 ? `${key}/${JSON.stringify(args)}` : key;\n\n/**\n * A custom React hook that manages asynchronous operations, providing easy-to-use states and controls over fetching, caching, and retry mechanisms.\n * This hook abstracts away the complexity of handling loading, error, and success states for any asynchronous function.\n *\n *\n * ```tsx\n * // Example of using useAsync to manage fetching user data from an API.\n * const fetchUserData = async (userId) => {\n * const response = await fetch(`/api/users/${userId}`);\n * if (!response.ok) throw new Error('Failed to fetch');\n * return await response.json();\n * };\n *\n * const UserDetails = ({ userId }) => {\n * const {\n * isLoading,\n * data,\n * error,\n * revalidate,\n * } = useAsync('userDetails', fetchUserData, {\n * cache: true,\n * revalidateTime: 60000, // 1 minute\n * autoFetch: true,\n * onSuccess: (data) => console.log('User data fetched successfully:', data),\n * onError: (error) => console.error('Error fetching user data:', error),\n * });\n *\n * if (isLoading) return <div>Loading...</div>;\n * if (error) return <div>Error: {error}</div>;\n * return (\n * <div>\n * <h1>{data.name}</h1>\n * <button onClick={() => revalidate()}>Refresh</button>\n * </div>\n * );\n * };\n * ```\n */\nexport const useAsync = <\n U extends string,\n T extends (...args: any[]) => Promise<any>,\n>(\n key: U,\n asyncFunction: T,\n options?: UseAsyncOptions<T>\n): UseAsyncResult<U, T> => {\n // Resolving optional parameters with default values\n const retryLimit = options?.retryLimit ?? DEFAULT_RETRY_LIMIT;\n const autoFetch = options?.autoFetch ?? DEFAULT_AUTO_FETCH;\n const retryTime = options?.retryTime ?? DEFAULT_RETRY_TIME;\n const cacheEnabled = options?.cache ?? DEFAULT_CACHE_ENABLED;\n const storeEnabled = options?.store ?? DEFAULT_STORE_ENABLED;\n const enabled = options?.enable ?? DEFAULT_ENABLED;\n const revalidationEnabled =\n options?.revalidation ?? DEFAULT_REVALIDATION_ENABLED;\n const revalidateTime = options?.revalidateTime ?? DEFAULT_REVALIDATE_TIME;\n const updateQueries = options?.updateQueries ?? [];\n const invalidateQueries = options?.invalidateQueries ?? [];\n const onSuccess = options?.onSuccess;\n const onError = options?.onError;\n const args = getArgs(options?.args ?? []);\n\n // Using a custom hook to manage state specific to asynchronous operations\n const { getStates, setQueryState, setQueriesState, makeQueryInError } =\n useAsyncState();\n\n // Storing the last arguments used to call the async function\n const storedArgsRef = useRef<any[]>(args);\n\n // Apply different key for different requests\n const keyWithArgs = getKeyWithArgs(key, storedArgsRef.current);\n\n // Retrieving the current state of async operations using the same custom hook\n const {\n isFetched,\n fetchedDateTime,\n isLoading,\n isEnabled,\n error,\n isSuccess,\n isInvalidated,\n data,\n errorCount,\n } = getStates(keyWithArgs);\n\n /**\n * FETCH FUNCTION\n *\n * Manage parallel fetching across multiple instances of the hook\n * Manage state updates on success and error\n * Manage eventual invalidation of other queries\n */\n const fetch: T = useCallback<T>(\n (async (...args) => {\n const keyWithArgs = getKeyWithArgs(key, args);\n\n if (pendingPromises.has(keyWithArgs)) {\n // Return the existing pending promise\n return pendingPromises.get(keyWithArgs);\n }\n\n const promise = (async () => {\n setQueryState(keyWithArgs, { isLoading: true });\n let response = null;\n\n await asyncFunction(...args)\n .then((result) => {\n response = result;\n\n setQueryState(keyWithArgs, {\n data: result,\n errorCount: 0,\n isLoading: false,\n isFetched: true,\n fetchedDateTime: new Date(),\n isSuccess: true,\n isInvalidated: false,\n error: null,\n });\n\n onSuccess?.(result);\n\n // Invalidate other queries if necessary\n if (invalidateQueries.length > 0) {\n setQueriesState(invalidateQueries, {\n isInvalidated: true,\n });\n }\n\n // Update other queries if necessary\n if (updateQueries.length > 0) {\n setQueriesState(updateQueries, {\n data: result,\n });\n }\n\n // Store the result in local storage\n if (storeEnabled) {\n localStorage.setItem(keyWithArgs, JSON.stringify(result));\n }\n })\n .catch((error) => {\n const msg = error instanceof Error ? error.message : String(error);\n\n makeQueryInError(keyWithArgs, msg);\n onError?.(error.message);\n })\n .finally(() => {\n // Remove the pending promise from the cache\n pendingPromises.delete(keyWithArgs);\n });\n\n return response;\n })();\n\n // Store the pending promise in the cache\n pendingPromises.set(keyWithArgs, promise);\n\n return await promise;\n }) as T,\n [asyncFunction, keyWithArgs, storeEnabled, cacheEnabled, onSuccess, onError]\n );\n\n /**\n * REVALIDATE FUNCTION\n *\n * Wrap core function to handle revalidation\n * Handle arguments caching\n *\n */\n const revalidate: T = useCallback<T>(\n (async (...args) => {\n if (!isEnabled || !enabled) return; // Hook is disabled\n\n if (args) {\n // Revalidation arguments can be different from the initial fetch arguments\n // If arguments are provided, store/update them for future periodic revalidation\n\n storedArgsRef.current = getArgs(args);\n }\n\n return await fetch(...storedArgsRef.current);\n }) as T,\n [isEnabled, enabled, storedArgsRef, fetch]\n );\n\n /**\n * EXECUTION FUNCTION\n *\n * Wrap revalidation function\n * If data is valid return it directly to avoid fetching again\n */\n const execute: T = useCallback<T>(\n (async (...args) => {\n if (!isEnabled || !enabled) return; // Hook is disabled\n if (isLoading) return; // Fetch is already in progress\n\n const shouldReturnData =\n !isInvalidated && // If data are invalidated, we should refetch to revalidate the data\n isSuccess &&\n cacheEnabled &&\n data;\n\n if (shouldReturnData) return data; // Data are already fetched and should be returned directly. Avoid fetching again.\n\n return await revalidate(...args);\n }) as T,\n [\n isEnabled,\n enabled,\n isInvalidated,\n cacheEnabled,\n isSuccess,\n data,\n isLoading,\n revalidate,\n ]\n );\n\n /**\n * HANDLE SYNCHRONIZATION HOOKS DISACTIVATION\n *\n * If one instance of the hook is disabled, the other instances should be disabled too.\n * This is to prevent inconsistencies in the state of the hook.\n */\n useEffect(() => {\n if (enabled !== isEnabled) {\n setQueryState(keyWithArgs, {\n isEnabled,\n });\n }\n }, [enabled, isEnabled, keyWithArgs]);\n\n /**\n * HANDLE LOCAL STORAGE LOADING\n *\n * If store is enabled, load data from local storage\n */\n useEffect(() => {\n if (!isEnabled || !enabled) return; // Hook is disabled\n if (!storeEnabled) return; // Hook should not use local storage\n if (isInvalidated || isFetched || data) return; // Hook have been already mounted and fetched or invalidated\n\n const storedData = localStorage.getItem(keyWithArgs);\n\n // Wrap parsing in a try-catch block to handle invalid JSON data\n try {\n if (storedData) {\n setQueryState(keyWithArgs, {\n data: JSON.parse(storedData),\n });\n }\n } catch (error) {\n console.error(error);\n }\n }, [\n storeEnabled,\n keyWithArgs,\n isFetched,\n isInvalidated,\n isEnabled,\n enabled,\n data,\n ]);\n\n /**\n * HANDLE AUTO-FETCH ON HOOK MOUNT\n *\n * If autoFetch is enabled, fetch the data when the hook is mounted\n */\n useEffect(() => {\n if (!autoFetch) return; // Auto-fetch is disabled\n if (!isEnabled || !enabled) return; // Hook is disabled\n if (isFetched && !isInvalidated) return; // Hook have already fetched or invalidated\n if (isLoading) return; // Fetch is already in progress\n\n fetch(...storedArgsRef.current);\n }, [\n autoFetch,\n isEnabled,\n enabled,\n isFetched,\n isInvalidated,\n isLoading,\n fetch,\n ]);\n\n /**\n * HANDLE RETRY\n *\n * If fetching fails, retry the fetch after a certain time\n */\n useEffect(() => {\n const isRetryEnabled = errorCount > 0 && retryLimit > 0;\n const isRetryLimitReached = errorCount > retryLimit;\n\n if (!isEnabled || !enabled) return; // Hook is disabled\n if (!isRetryEnabled) return; // Retry is disabled\n if (isRetryLimitReached) return; // Retry limit has been reached\n if (!(cacheEnabled || storeEnabled)) return; // Useless to retry if caching is disabled\n if (isLoading) return; // Fetch is already in progress\n if (isSuccess) return; // Hook has already fetched successfully\n\n const timeout = setTimeout(() => {\n fetch(...storedArgsRef.current);\n }, retryTime);\n\n return () => clearTimeout(timeout);\n }, [\n isEnabled,\n errorCount,\n retryLimit,\n enabled,\n retryTime,\n cacheEnabled,\n storeEnabled,\n isSuccess,\n isLoading,\n fetch,\n ]);\n\n /**\n * HANDLE PERIODIC REVALIDATION\n *\n * If revalidation is enabled, revalidate the data periodically\n */\n useEffect(() => {\n if (!revalidationEnabled || revalidateTime <= 0) return; // Revalidation is disabled\n if (!isEnabled || !enabled) return; // Hook is disabled\n if (isLoading) return; // Fetch is already in progress\n if (!isSuccess || !fetchedDateTime) return; // Should retry either of revalidate\n if (!(cacheEnabled || storeEnabled)) return; // Useless to revalidate if caching is disabled\n\n const timeout = setTimeout(() => {\n fetch(...storedArgsRef.current);\n }, revalidateTime);\n\n return () => clearTimeout(timeout);\n }, [\n revalidationEnabled,\n revalidateTime,\n cacheEnabled,\n storeEnabled,\n isSuccess,\n fetchedDateTime,\n isLoading,\n isEnabled,\n enabled,\n fetch,\n ]);\n\n // Memoization of the setData function to prevent unnecessary re-renders\n const setDataMemo = useCallback(\n (data: Awaited<ReturnType<T> | null>) => {\n setQueryState(keyWithArgs, {\n data,\n });\n },\n [keyWithArgs]\n );\n\n // Memoization to prevent unnecessary re-renders\n const memoResult = useMemo(\n () => ({\n isFetched,\n isInvalidated,\n error,\n data,\n errorCount,\n isSuccess,\n isEnabled,\n isDisabled: !isEnabled,\n isLoading,\n isWaitingData: isLoading && !isFetched && !data, // Check if the data is still being fetched. Stay at true during revalidation or if data are stored in local storage\n isRevalidating: isLoading && isFetched, // Check if the data is valid and is being revalidated\n [key]: execute, // Name the execute function as the given key to avoid conflicts with other hooks (e.g. `const { fetchUser } = useAsync('fetchUser', () => fetchUserFunction());`)\n revalidate,\n setData: setDataMemo,\n }),\n [\n isFetched,\n isLoading,\n isInvalidated,\n error,\n isSuccess,\n data,\n errorCount,\n isEnabled,\n key,\n execute,\n revalidate,\n setDataMemo,\n ]\n );\n\n // Return the hook's result, including all state and control functions\n return memoResult as UseAsyncResultBase<T> & Record<U, T>;\n};\n"],"names":["args","keyWithArgs","error","data"],"mappings":";;;AAQA,MAAM,sCAAsB,IAAI;AAoChC,MAAM,wBAAwB;AAC9B,MAAM,wBAAwB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MACA;AAAA,MACA;AAAA,MACA,YAAY,CAAC;AAAA,MACb;AAAA,MACA,eAAe,aAAa,CAAC,aAAa,CAAC;AAAA;AAAA,MAC3C,gBAAgB,aAAa;AAAA;AAAA,MAC7B,CAAC,GAAG,GAAG;AAAA;AAAA,MACP;AAAA,MACA,SAAS;AAAA,IAAA;AAAA,IAEX;AAAA,MACE;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,IAAA;AAAA,EAEJ;AAGO,SAAA;AACT;"}
@@ -11,7 +11,7 @@ const createDefaultStates = () => ({
11
11
  error: null,
12
12
  isSuccess: false,
13
13
  data: null,
14
- retryCount: 0,
14
+ errorCount: 0,
15
15
  isEnabled: true
16
16
  });
17
17
  const ensureArray = (value) => {
@@ -52,7 +52,7 @@ const reducer = (state, action) => {
52
52
  error,
53
53
  isFetched: true,
54
54
  isSuccess: false,
55
- retryCount: (state.states[key]?.retryCount ?? 0) + 1,
55
+ errorCount: (state.states[key]?.errorCount ?? 0) + 1,
56
56
  isLoading: false,
57
57
  isInvalidated: false
58
58
  }
@@ -1 +1 @@
1
- {"version":3,"file":"useAsyncStateStore.cjs","sources":["../../../src/hooks/useAsync/useAsyncStateStore.tsx"],"sourcesContent":["'use client';\n\nimport {\n createContext,\n useContext,\n useReducer,\n PropsWithChildren,\n} from 'react';\n\n/**\n * Represents the states for a given key in the asynchronous state management.\n * This includes flags for loading, fetched, invalidation, and success/error status.\n * It also keeps track of the fetched datetime, retry counts, the data itself, and whether queries are enabled.\n */\ntype States<T> = {\n isLoading: boolean;\n isFetched: boolean;\n isInvalidated: boolean;\n fetchedDateTime: null | Date;\n error: string | null;\n isSuccess: boolean;\n data: T | null;\n retryCount: number;\n isEnabled: boolean;\n};\n\n/**\n * Holds a mapping from a key (string) to its associated state.\n */\ntype StateSlice<T> = {\n [key: string]: States<T>;\n};\n\n/**\n * Describes all the possible actions that can be dispatched to the reducer.\n * These actions allow setting or updating states for specific keys or multiple keys at once,\n * handling errors, and resetting states.\n */\ntype Actions<T> =\n | { type: 'SET_QUERY_STATE'; key: string; value: Partial<States<T>> }\n | { type: 'MAKE_QUERY_IN_ERROR'; key: string; error: string }\n | { type: 'SET_QUERIES_STATE'; keys: string[]; value: Partial<States<T>> }\n | { type: 'RESET_KEY_STATE'; keys: string[] }\n | { type: 'RESET_STATE'; excludeKeys: string[] };\n\n/**\n * The shape of the entire asynchronous state, holding all states in a single object.\n */\ntype AsyncState<T> = {\n states: StateSlice<T>;\n};\n\n/**\n * Creates a default state object with initial values. This is useful when a key\n * has not been initialized yet or when resetting a state back to defaults.\n */\nconst createDefaultStates = <T,>(): States<T> => ({\n isFetched: false,\n fetchedDateTime: null,\n isLoading: false,\n isInvalidated: false,\n error: null,\n isSuccess: false,\n data: null,\n retryCount: 0,\n isEnabled: true,\n});\n\n/**\n * Ensures that a given value is returned as an array.\n * If the value is undefined or null, returns an empty array.\n * If the value is not already an array, wraps it in one.\n */\nconst ensureArray = <T,>(value?: T | T[]): T[] => {\n if (!value) {\n // If no value is provided, return an empty array\n return [];\n } else if (Array.isArray(value)) {\n // If it's already an array, just return it\n return value;\n }\n // If it's a single value, wrap it in an array\n return [value];\n};\n\n/**\n * Given a list of selector keys and a list of keys that may contain arguments,\n * this function returns all keys that match the selectors. Matching is determined\n * by comparing the initial part (split by \"/\") of the key.\n *\n * For example:\n * selectorsKeys = [\"user\", \"posts\"]\n * keysWithArgs = [\"user/123\", \"posts/active\", \"comments/42\"]\n * Result = [\"user/123\", \"posts/active\"]\n */\nconst getMatchKeys = (\n selectorsKeys: string[],\n keysWithArgs: string[]\n): string[] =>\n keysWithArgs.filter((key) => selectorsKeys.includes(key.split('/')[0]));\n\n/**\n * The reducer function handling all state transitions. It takes the current state and an action,\n * and returns a new state based on the type of the action.\n *\n * Actions include:\n * - SET_QUERY_STATE: Update a single key with partial new state.\n * - MAKE_QUERY_IN_ERROR: Mark a single key as errored and update related flags.\n * - SET_QUERIES_STATE: Update multiple keys at once with partial new state.\n * - RESET_KEY_STATE: Reset certain keys to their default states.\n * - RESET_STATE: Reset all keys to their default states except those excluded.\n */\nconst reducer = <T,>(\n state: AsyncState<T>,\n action: Actions<T>\n): AsyncState<T> => {\n switch (action.type) {\n case 'SET_QUERY_STATE': {\n const { key, value } = action;\n return {\n ...state,\n states: {\n ...state.states,\n [key]: {\n // Merge existing state for the key or default state if not present\n ...(state.states[key] ?? createDefaultStates<T>()),\n ...value,\n },\n },\n };\n }\n case 'MAKE_QUERY_IN_ERROR': {\n const { key, error } = action;\n return {\n ...state,\n states: {\n ...state.states,\n [key]: {\n // Merge existing state or default if not found\n ...(state.states[key] ?? createDefaultStates<T>()),\n // Explicitly set error and related flags\n error,\n isFetched: true,\n isSuccess: false,\n retryCount: (state.states[key]?.retryCount ?? 0) + 1,\n isLoading: false,\n isInvalidated: false,\n },\n },\n };\n }\n case 'SET_QUERIES_STATE': {\n const { keys, value } = action;\n const keyArray = ensureArray(keys);\n if (keyArray.length === 0) return state;\n\n // Update multiple keys in a single action\n const updatedStates = { ...state.states };\n keyArray.forEach((key) => {\n updatedStates[key] = {\n ...(state.states[key] ?? createDefaultStates<T>()),\n ...value,\n };\n });\n\n return {\n ...state,\n states: updatedStates,\n };\n }\n case 'RESET_KEY_STATE': {\n const { keys } = action;\n const keyArray = ensureArray(keys);\n if (keyArray.length === 0) return state;\n\n // Find all keys that match the given selectors\n const allKeys = Object.keys(state.states);\n const matchedKeys = getMatchKeys(keyArray, allKeys);\n if (matchedKeys.length === 0) return state;\n\n // Reset the matched keys back to default states\n const resetStates = { ...state.states };\n matchedKeys.forEach((key) => {\n resetStates[key] = createDefaultStates<T>();\n });\n\n return {\n ...state,\n states: resetStates,\n };\n }\n case 'RESET_STATE': {\n const excludeArray = ensureArray(action.excludeKeys);\n const allKeys = Object.keys(state.states);\n const matchedKeys = getMatchKeys(excludeArray, allKeys);\n\n // Reset all states except those that match the exclude keys\n const newStates: StateSlice<T> = {};\n allKeys.forEach((key) => {\n newStates[key] = matchedKeys.includes(key)\n ? state.states[key]\n : createDefaultStates<T>();\n });\n\n return {\n ...state,\n states: newStates,\n };\n }\n default:\n return state;\n }\n};\n\n/**\n * The context type that will be provided to consumers.\n * It exposes a set of functions for interacting with the asynchronous state:\n * - getStates: Retrieve the current state for a given key.\n * - setQueryState: Partially update a single key's state.\n * - setQueriesState: Partially update multiple keys' states.\n * - makeQueryInError: Set a particular key into an error state.\n * - resetKeyState: Reset certain keys to their default states.\n * - resetState: Reset all keys to their default states except a set of excluded ones.\n */\ntype AsyncStateContextType<T> = {\n getStates: (key: string) => States<T>;\n setQueryState: (key: string, value: Partial<States<T>>) => void;\n setQueriesState: (keys: string[], value: Partial<States<T>>) => void;\n makeQueryInError: (key: string, error: string) => void;\n resetKeyState: (keys: string[]) => void;\n resetState: (excludedKeys: string[]) => void;\n};\n\n/**\n * Creates a React context for asynchronous state management.\n * This context will be provided by the AsyncStateProvider and consumed by hooks like useAsyncState.\n */\nconst AsyncStateContext = createContext<AsyncStateContextType<unknown> | null>(\n null\n);\n\n/**\n * A provider component that wraps its children and provides the asynchronous\n * state context. It uses the reducer to manage states and dispatch actions\n * based on consumer interactions.\n *\n * @param children The React children elements that should have access to this context.\n */\nexport const AsyncStateProvider = ({ children }: PropsWithChildren<{}>) => {\n // Initialize the reducer with an empty state object\n const [asyncState, dispatch] = useReducer(reducer, { states: {} });\n\n /**\n * Retrieve the state associated with a given key. If no state exists for that key,\n * return a default state.\n *\n * @param key The key for which to retrieve the state.\n */\n const getStates = (key: string) =>\n asyncState.states[key] ?? createDefaultStates<unknown>();\n\n /**\n * Partially update the state for a given key.\n *\n * @param key The key to update.\n * @param value A partial state object to merge with the existing state.\n */\n const setQueryState = (key: string, value: Partial<States<unknown>>) => {\n dispatch({ type: 'SET_QUERY_STATE', key, value });\n };\n\n /**\n * Partially update the state for multiple keys at once.\n *\n * @param keys An array of keys to update.\n * @param value A partial state object to merge with each key's existing state.\n */\n const setQueriesState = (keys: string[], value: Partial<States<unknown>>) => {\n dispatch({ type: 'SET_QUERIES_STATE', keys, value });\n };\n\n /**\n * Mark a given query as having encountered an error.\n *\n * @param key The key associated with the query.\n * @param error The error message to set.\n */\n const makeQueryInError = (key: string, error: string) => {\n dispatch({ type: 'MAKE_QUERY_IN_ERROR', key, error });\n };\n\n /**\n * Reset certain keys back to their default states.\n *\n * @param keys The keys to reset.\n */\n const resetKeyState = (keys: string[]) => {\n dispatch({ type: 'RESET_KEY_STATE', keys });\n };\n\n /**\n * Reset the entire state back to defaults, except for keys that match the excluded ones.\n *\n * @param excludedKeys Keys that should not be reset.\n */\n const resetState = (excludedKeys: string[]) => {\n dispatch({ type: 'RESET_STATE', excludeKeys: excludedKeys });\n };\n\n return (\n <AsyncStateContext.Provider\n value={{\n getStates,\n setQueryState,\n setQueriesState,\n makeQueryInError,\n resetKeyState,\n resetState,\n }}\n >\n {children}\n </AsyncStateContext.Provider>\n );\n};\n\n/**\n * A custom hook for accessing the asynchronous state context. It throws an error if used\n * outside of a provider.\n *\n * @returns The asynchronous state context value.\n */\nexport const useAsyncState = () => {\n const context = useContext(AsyncStateContext);\n if (!context) {\n throw new Error('useAsyncState must be used within an AsyncStateProvider');\n }\n return context;\n};\n"],"names":["createContext","useReducer","jsx","useContext"],"mappings":";;;;;AAwDA,MAAM,sBAAsB,OAAsB;AAAA,EAChD,WAAW;AAAA,EACX,iBAAiB;AAAA,EACjB,WAAW;AAAA,EACX,eAAe;AAAA,EACf,OAAO;AAAA,EACP,WAAW;AAAA,EACX,MAAM;AAAA,EACN,YAAY;AAAA,EACZ,WAAW;AACb;AAOA,MAAM,cAAc,CAAK,UAAyB;AAChD,MAAI,CAAC,OAAO;AAEV,WAAO,CAAC;AAAA,EACC,WAAA,MAAM,QAAQ,KAAK,GAAG;AAExB,WAAA;AAAA,EAAA;AAGT,SAAO,CAAC,KAAK;AACf;AAYA,MAAM,eAAe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AAC3E,aAAS,EAAE,MAAM,qBAAqB,MAAM,OAAO;AAAA,EACrD;AAQM,QAAA,mBAAmB,CAAC,KAAa,UAAkB;AACvD,aAAS,EAAE,MAAM,uBAAuB,KAAK,OAAO;AAAA,EACtD;AAOM,QAAA,gBAAgB,CAAC,SAAmB;AACxC,aAAS,EAAE,MAAM,mBAAmB,KAAA,CAAM;AAAA,EAC5C;AAOM,QAAA,aAAa,CAAC,iBAA2B;AAC7C,aAAS,EAAE,MAAM,eAAe,aAAa,cAAc;AAAA,EAC7D;AAGE,SAAAC,2BAAA,kBAAA;AAAA,IAAC,kBAAkB;AAAA,IAAlB;AAAA,MACC,OAAO;AAAA,QACL;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,MACF;AAAA,MAEC;AAAA,IAAA;AAAA,EACH;AAEJ;AAQO,MAAM,gBAAgB,MAAM;AAC3B,QAAA,UAAUC,sBAAW,iBAAiB;AAC5C,MAAI,CAAC,SAAS;AACN,UAAA,IAAI,MAAM,yDAAyD;AAAA,EAAA;AAEpE,SAAA;AACT;;;"}
1
+ {"version":3,"file":"useAsyncStateStore.cjs","sources":["../../../src/hooks/useAsync/useAsyncStateStore.tsx"],"sourcesContent":["'use client';\n\nimport {\n createContext,\n useContext,\n useReducer,\n PropsWithChildren,\n} from 'react';\n\n/**\n * Represents the states for a given key in the asynchronous state management.\n * This includes flags for loading, fetched, invalidation, and success/error status.\n * It also keeps track of the fetched datetime, retry counts, the data itself, and whether queries are enabled.\n */\ntype States<T> = {\n isLoading: boolean;\n isFetched: boolean;\n isInvalidated: boolean;\n fetchedDateTime: null | Date;\n error: string | null;\n isSuccess: boolean;\n data: T | null;\n errorCount: number;\n isEnabled: boolean;\n};\n\n/**\n * Holds a mapping from a key (string) to its associated state.\n */\ntype StateSlice<T> = {\n [key: string]: States<T>;\n};\n\n/**\n * Describes all the possible actions that can be dispatched to the reducer.\n * These actions allow setting or updating states for specific keys or multiple keys at once,\n * handling errors, and resetting states.\n */\ntype Actions<T> =\n | { type: 'SET_QUERY_STATE'; key: string; value: Partial<States<T>> }\n | { type: 'MAKE_QUERY_IN_ERROR'; key: string; error: string }\n | { type: 'SET_QUERIES_STATE'; keys: string[]; value: Partial<States<T>> }\n | { type: 'RESET_KEY_STATE'; keys: string[] }\n | { type: 'RESET_STATE'; excludeKeys: string[] };\n\n/**\n * The shape of the entire asynchronous state, holding all states in a single object.\n */\ntype AsyncState<T> = {\n states: StateSlice<T>;\n};\n\n/**\n * Creates a default state object with initial values. This is useful when a key\n * has not been initialized yet or when resetting a state back to defaults.\n */\nconst createDefaultStates = <T,>(): States<T> => ({\n isFetched: false,\n fetchedDateTime: null,\n isLoading: false,\n isInvalidated: false,\n error: null,\n isSuccess: false,\n data: null,\n errorCount: 0,\n isEnabled: true,\n});\n\n/**\n * Ensures that a given value is returned as an array.\n * If the value is undefined or null, returns an empty array.\n * If the value is not already an array, wraps it in one.\n */\nconst ensureArray = <T,>(value?: T | T[]): T[] => {\n if (!value) {\n // If no value is provided, return an empty array\n return [];\n } else if (Array.isArray(value)) {\n // If it's already an array, just return it\n return value;\n }\n // If it's a single value, wrap it in an array\n return [value];\n};\n\n/**\n * Given a list of selector keys and a list of keys that may contain arguments,\n * this function returns all keys that match the selectors. Matching is determined\n * by comparing the initial part (split by \"/\") of the key.\n *\n * For example:\n * selectorsKeys = [\"user\", \"posts\"]\n * keysWithArgs = [\"user/123\", \"posts/active\", \"comments/42\"]\n * Result = [\"user/123\", \"posts/active\"]\n */\nconst getMatchKeys = (\n selectorsKeys: string[],\n keysWithArgs: string[]\n): string[] =>\n keysWithArgs.filter((key) => selectorsKeys.includes(key.split('/')[0]));\n\n/**\n * The reducer function handling all state transitions. It takes the current state and an action,\n * and returns a new state based on the type of the action.\n *\n * Actions include:\n * - SET_QUERY_STATE: Update a single key with partial new state.\n * - MAKE_QUERY_IN_ERROR: Mark a single key as errored and update related flags.\n * - SET_QUERIES_STATE: Update multiple keys at once with partial new state.\n * - RESET_KEY_STATE: Reset certain keys to their default states.\n * - RESET_STATE: Reset all keys to their default states except those excluded.\n */\nconst reducer = <T,>(\n state: AsyncState<T>,\n action: Actions<T>\n): AsyncState<T> => {\n switch (action.type) {\n case 'SET_QUERY_STATE': {\n const { key, value } = action;\n return {\n ...state,\n states: {\n ...state.states,\n [key]: {\n // Merge existing state for the key or default state if not present\n ...(state.states[key] ?? createDefaultStates<T>()),\n ...value,\n },\n },\n };\n }\n case 'MAKE_QUERY_IN_ERROR': {\n const { key, error } = action;\n return {\n ...state,\n states: {\n ...state.states,\n [key]: {\n // Merge existing state or default if not found\n ...(state.states[key] ?? createDefaultStates<T>()),\n // Explicitly set error and related flags\n error,\n isFetched: true,\n isSuccess: false,\n errorCount: (state.states[key]?.errorCount ?? 0) + 1,\n isLoading: false,\n isInvalidated: false,\n },\n },\n };\n }\n case 'SET_QUERIES_STATE': {\n const { keys, value } = action;\n const keyArray = ensureArray(keys);\n if (keyArray.length === 0) return state;\n\n // Update multiple keys in a single action\n const updatedStates = { ...state.states };\n keyArray.forEach((key) => {\n updatedStates[key] = {\n ...(state.states[key] ?? createDefaultStates<T>()),\n ...value,\n };\n });\n\n return {\n ...state,\n states: updatedStates,\n };\n }\n case 'RESET_KEY_STATE': {\n const { keys } = action;\n const keyArray = ensureArray(keys);\n if (keyArray.length === 0) return state;\n\n // Find all keys that match the given selectors\n const allKeys = Object.keys(state.states);\n const matchedKeys = getMatchKeys(keyArray, allKeys);\n if (matchedKeys.length === 0) return state;\n\n // Reset the matched keys back to default states\n const resetStates = { ...state.states };\n matchedKeys.forEach((key) => {\n resetStates[key] = createDefaultStates<T>();\n });\n\n return {\n ...state,\n states: resetStates,\n };\n }\n case 'RESET_STATE': {\n const excludeArray = ensureArray(action.excludeKeys);\n const allKeys = Object.keys(state.states);\n const matchedKeys = getMatchKeys(excludeArray, allKeys);\n\n // Reset all states except those that match the exclude keys\n const newStates: StateSlice<T> = {};\n allKeys.forEach((key) => {\n newStates[key] = matchedKeys.includes(key)\n ? state.states[key]\n : createDefaultStates<T>();\n });\n\n return {\n ...state,\n states: newStates,\n };\n }\n default:\n return state;\n }\n};\n\n/**\n * The context type that will be provided to consumers.\n * It exposes a set of functions for interacting with the asynchronous state:\n * - getStates: Retrieve the current state for a given key.\n * - setQueryState: Partially update a single key's state.\n * - setQueriesState: Partially update multiple keys' states.\n * - makeQueryInError: Set a particular key into an error state.\n * - resetKeyState: Reset certain keys to their default states.\n * - resetState: Reset all keys to their default states except a set of excluded ones.\n */\ntype AsyncStateContextType<T> = {\n getStates: (key: string) => States<T>;\n setQueryState: (key: string, value: Partial<States<T>>) => void;\n setQueriesState: (keys: string[], value: Partial<States<T>>) => void;\n makeQueryInError: (key: string, error: string) => void;\n resetKeyState: (keys: string[]) => void;\n resetState: (excludedKeys: string[]) => void;\n};\n\n/**\n * Creates a React context for asynchronous state management.\n * This context will be provided by the AsyncStateProvider and consumed by hooks like useAsyncState.\n */\nconst AsyncStateContext = createContext<AsyncStateContextType<unknown> | null>(\n null\n);\n\n/**\n * A provider component that wraps its children and provides the asynchronous\n * state context. It uses the reducer to manage states and dispatch actions\n * based on consumer interactions.\n *\n * @param children The React children elements that should have access to this context.\n */\nexport const AsyncStateProvider = ({ children }: PropsWithChildren<{}>) => {\n // Initialize the reducer with an empty state object\n const [asyncState, dispatch] = useReducer(reducer, { states: {} });\n\n /**\n * Retrieve the state associated with a given key. If no state exists for that key,\n * return a default state.\n *\n * @param key The key for which to retrieve the state.\n */\n const getStates = (key: string) =>\n asyncState.states[key] ?? createDefaultStates<unknown>();\n\n /**\n * Partially update the state for a given key.\n *\n * @param key The key to update.\n * @param value A partial state object to merge with the existing state.\n */\n const setQueryState = (key: string, value: Partial<States<unknown>>) => {\n dispatch({ type: 'SET_QUERY_STATE', key, value });\n };\n\n /**\n * Partially update the state for multiple keys at once.\n *\n * @param keys An array of keys to update.\n * @param value A partial state object to merge with each key's existing state.\n */\n const setQueriesState = (keys: string[], value: Partial<States<unknown>>) => {\n dispatch({ type: 'SET_QUERIES_STATE', keys, value });\n };\n\n /**\n * Mark a given query as having encountered an error.\n *\n * @param key The key associated with the query.\n * @param error The error message to set.\n */\n const makeQueryInError = (key: string, error: string) => {\n dispatch({ type: 'MAKE_QUERY_IN_ERROR', key, error });\n };\n\n /**\n * Reset certain keys back to their default states.\n *\n * @param keys The keys to reset.\n */\n const resetKeyState = (keys: string[]) => {\n dispatch({ type: 'RESET_KEY_STATE', keys });\n };\n\n /**\n * Reset the entire state back to defaults, except for keys that match the excluded ones.\n *\n * @param excludedKeys Keys that should not be reset.\n */\n const resetState = (excludedKeys: string[]) => {\n dispatch({ type: 'RESET_STATE', excludeKeys: excludedKeys });\n };\n\n return (\n <AsyncStateContext.Provider\n value={{\n getStates,\n setQueryState,\n setQueriesState,\n makeQueryInError,\n resetKeyState,\n resetState,\n }}\n >\n {children}\n </AsyncStateContext.Provider>\n );\n};\n\n/**\n * A custom hook for accessing the asynchronous state context. It throws an error if used\n * outside of a provider.\n *\n * @returns The asynchronous state context value.\n */\nexport const useAsyncState = () => {\n const context = useContext(AsyncStateContext);\n if (!context) {\n throw new Error('useAsyncState must be used within an AsyncStateProvider');\n }\n return context;\n};\n"],"names":["createContext","useReducer","jsx","useContext"],"mappings":";;;;;AAwDA,MAAM,sBAAsB,OAAsB;AAAA,EAChD,WAAW;AAAA,EACX,iBAAiB;AAAA,EACjB,WAAW;AAAA,EACX,eAAe;AAAA,EACf,OAAO;AAAA,EACP,WAAW;AAAA,EACX,MAAM;AAAA,EACN,YAAY;AAAA,EACZ,WAAW;AACb;AAOA,MAAM,cAAc,CAAK,UAAyB;AAChD,MAAI,CAAC,OAAO;AAEV,WAAO,CAAC;AAAA,EACC,WAAA,MAAM,QAAQ,KAAK,GAAG;AAExB,WAAA;AAAA,EAAA;AAGT,SAAO,CAAC,KAAK;AACf;AAYA,MAAM,eAAe,CACnB,eACA,iBAEA,aAAa,OAAO,CAAC,QAAQ,cAAc,SAAS,IAAI,MAAM,GA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BAAmB,CAAC,KAAa,UAAkB;AACvD,aAAS,EAAE,MAAM,uBAAuB,KAAK,OAAO;AAAA,EACtD;AAOM,QAAA,gBAAgB,CAAC,SAAmB;AACxC,aAAS,EAAE,MAAM,mBAAmB,KAAA,CAAM;AAAA,EAC5C;AAOM,QAAA,aAAa,CAAC,iBAA2B;AAC7C,aAAS,EAAE,MAAM,eAAe,aAAa,cAAc;AAAA,EAC7D;AAGE,SAAAC,2BAAA,kBAAA;AAAA,IAAC,kBAAkB;AAAA,IAAlB;AAAA,MACC,OAAO;AAAA,QACL;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,MACF;AAAA,MAEC;AAAA,IAAA;AAAA,EACH;AAEJ;AAQO,MAAM,gBAAgB,MAAM;AAC3B,QAAA,UAAUC,sBAAW,iBAAiB;AAC5C,MAAI,CAAC,SAAS;AACN,UAAA,IAAI,MAAM,yDAAyD;AAAA,EAAA;AAEpE,SAAA;AACT;;;"}
@@ -12,7 +12,7 @@ type States<T> = {
12
12
  error: string | null;
13
13
  isSuccess: boolean;
14
14
  data: T | null;
15
- retryCount: number;
15
+ errorCount: number;
16
16
  isEnabled: boolean;
17
17
  };
18
18
  /**
@@ -9,7 +9,7 @@ const createDefaultStates = () => ({
9
9
  error: null,
10
10
  isSuccess: false,
11
11
  data: null,
12
- retryCount: 0,
12
+ errorCount: 0,
13
13
  isEnabled: true
14
14
  });
15
15
  const ensureArray = (value) => {
@@ -50,7 +50,7 @@ const reducer = (state, action) => {
50
50
  error,
51
51
  isFetched: true,
52
52
  isSuccess: false,
53
- retryCount: (state.states[key]?.retryCount ?? 0) + 1,
53
+ errorCount: (state.states[key]?.errorCount ?? 0) + 1,
54
54
  isLoading: false,
55
55
  isInvalidated: false
56
56
  }
@@ -1 +1 @@
1
- {"version":3,"file":"useAsyncStateStore.mjs","sources":["../../../src/hooks/useAsync/useAsyncStateStore.tsx"],"sourcesContent":["'use client';\n\nimport {\n createContext,\n useContext,\n useReducer,\n PropsWithChildren,\n} from 'react';\n\n/**\n * Represents the states for a given key in the asynchronous state management.\n * This includes flags for loading, fetched, invalidation, and success/error status.\n * It also keeps track of the fetched datetime, retry counts, the data itself, and whether queries are enabled.\n */\ntype States<T> = {\n isLoading: boolean;\n isFetched: boolean;\n isInvalidated: boolean;\n fetchedDateTime: null | Date;\n error: string | null;\n isSuccess: boolean;\n data: T | null;\n retryCount: number;\n isEnabled: boolean;\n};\n\n/**\n * Holds a mapping from a key (string) to its associated state.\n */\ntype StateSlice<T> = {\n [key: string]: States<T>;\n};\n\n/**\n * Describes all the possible actions that can be dispatched to the reducer.\n * These actions allow setting or updating states for specific keys or multiple keys at once,\n * handling errors, and resetting states.\n */\ntype Actions<T> =\n | { type: 'SET_QUERY_STATE'; key: string; value: Partial<States<T>> }\n | { type: 'MAKE_QUERY_IN_ERROR'; key: string; error: string }\n | { type: 'SET_QUERIES_STATE'; keys: string[]; value: Partial<States<T>> }\n | { type: 'RESET_KEY_STATE'; keys: string[] }\n | { type: 'RESET_STATE'; excludeKeys: string[] };\n\n/**\n * The shape of the entire asynchronous state, holding all states in a single object.\n */\ntype AsyncState<T> = {\n states: StateSlice<T>;\n};\n\n/**\n * Creates a default state object with initial values. This is useful when a key\n * has not been initialized yet or when resetting a state back to defaults.\n */\nconst createDefaultStates = <T,>(): States<T> => ({\n isFetched: false,\n fetchedDateTime: null,\n isLoading: false,\n isInvalidated: false,\n error: null,\n isSuccess: false,\n data: null,\n retryCount: 0,\n isEnabled: true,\n});\n\n/**\n * Ensures that a given value is returned as an array.\n * If the value is undefined or null, returns an empty array.\n * If the value is not already an array, wraps it in one.\n */\nconst ensureArray = <T,>(value?: T | T[]): T[] => {\n if (!value) {\n // If no value is provided, return an empty array\n return [];\n } else if (Array.isArray(value)) {\n // If it's already an array, just return it\n return value;\n }\n // If it's a single value, wrap it in an array\n return [value];\n};\n\n/**\n * Given a list of selector keys and a list of keys that may contain arguments,\n * this function returns all keys that match the selectors. Matching is determined\n * by comparing the initial part (split by \"/\") of the key.\n *\n * For example:\n * selectorsKeys = [\"user\", \"posts\"]\n * keysWithArgs = [\"user/123\", \"posts/active\", \"comments/42\"]\n * Result = [\"user/123\", \"posts/active\"]\n */\nconst getMatchKeys = (\n selectorsKeys: string[],\n keysWithArgs: string[]\n): string[] =>\n keysWithArgs.filter((key) => selectorsKeys.includes(key.split('/')[0]));\n\n/**\n * The reducer function handling all state transitions. It takes the current state and an action,\n * and returns a new state based on the type of the action.\n *\n * Actions include:\n * - SET_QUERY_STATE: Update a single key with partial new state.\n * - MAKE_QUERY_IN_ERROR: Mark a single key as errored and update related flags.\n * - SET_QUERIES_STATE: Update multiple keys at once with partial new state.\n * - RESET_KEY_STATE: Reset certain keys to their default states.\n * - RESET_STATE: Reset all keys to their default states except those excluded.\n */\nconst reducer = <T,>(\n state: AsyncState<T>,\n action: Actions<T>\n): AsyncState<T> => {\n switch (action.type) {\n case 'SET_QUERY_STATE': {\n const { key, value } = action;\n return {\n ...state,\n states: {\n ...state.states,\n [key]: {\n // Merge existing state for the key or default state if not present\n ...(state.states[key] ?? createDefaultStates<T>()),\n ...value,\n },\n },\n };\n }\n case 'MAKE_QUERY_IN_ERROR': {\n const { key, error } = action;\n return {\n ...state,\n states: {\n ...state.states,\n [key]: {\n // Merge existing state or default if not found\n ...(state.states[key] ?? createDefaultStates<T>()),\n // Explicitly set error and related flags\n error,\n isFetched: true,\n isSuccess: false,\n retryCount: (state.states[key]?.retryCount ?? 0) + 1,\n isLoading: false,\n isInvalidated: false,\n },\n },\n };\n }\n case 'SET_QUERIES_STATE': {\n const { keys, value } = action;\n const keyArray = ensureArray(keys);\n if (keyArray.length === 0) return state;\n\n // Update multiple keys in a single action\n const updatedStates = { ...state.states };\n keyArray.forEach((key) => {\n updatedStates[key] = {\n ...(state.states[key] ?? createDefaultStates<T>()),\n ...value,\n };\n });\n\n return {\n ...state,\n states: updatedStates,\n };\n }\n case 'RESET_KEY_STATE': {\n const { keys } = action;\n const keyArray = ensureArray(keys);\n if (keyArray.length === 0) return state;\n\n // Find all keys that match the given selectors\n const allKeys = Object.keys(state.states);\n const matchedKeys = getMatchKeys(keyArray, allKeys);\n if (matchedKeys.length === 0) return state;\n\n // Reset the matched keys back to default states\n const resetStates = { ...state.states };\n matchedKeys.forEach((key) => {\n resetStates[key] = createDefaultStates<T>();\n });\n\n return {\n ...state,\n states: resetStates,\n };\n }\n case 'RESET_STATE': {\n const excludeArray = ensureArray(action.excludeKeys);\n const allKeys = Object.keys(state.states);\n const matchedKeys = getMatchKeys(excludeArray, allKeys);\n\n // Reset all states except those that match the exclude keys\n const newStates: StateSlice<T> = {};\n allKeys.forEach((key) => {\n newStates[key] = matchedKeys.includes(key)\n ? state.states[key]\n : createDefaultStates<T>();\n });\n\n return {\n ...state,\n states: newStates,\n };\n }\n default:\n return state;\n }\n};\n\n/**\n * The context type that will be provided to consumers.\n * It exposes a set of functions for interacting with the asynchronous state:\n * - getStates: Retrieve the current state for a given key.\n * - setQueryState: Partially update a single key's state.\n * - setQueriesState: Partially update multiple keys' states.\n * - makeQueryInError: Set a particular key into an error state.\n * - resetKeyState: Reset certain keys to their default states.\n * - resetState: Reset all keys to their default states except a set of excluded ones.\n */\ntype AsyncStateContextType<T> = {\n getStates: (key: string) => States<T>;\n setQueryState: (key: string, value: Partial<States<T>>) => void;\n setQueriesState: (keys: string[], value: Partial<States<T>>) => void;\n makeQueryInError: (key: string, error: string) => void;\n resetKeyState: (keys: string[]) => void;\n resetState: (excludedKeys: string[]) => void;\n};\n\n/**\n * Creates a React context for asynchronous state management.\n * This context will be provided by the AsyncStateProvider and consumed by hooks like useAsyncState.\n */\nconst AsyncStateContext = createContext<AsyncStateContextType<unknown> | null>(\n null\n);\n\n/**\n * A provider component that wraps its children and provides the asynchronous\n * state context. It uses the reducer to manage states and dispatch actions\n * based on consumer interactions.\n *\n * @param children The React children elements that should have access to this context.\n */\nexport const AsyncStateProvider = ({ children }: PropsWithChildren<{}>) => {\n // Initialize the reducer with an empty state object\n const [asyncState, dispatch] = useReducer(reducer, { states: {} });\n\n /**\n * Retrieve the state associated with a given key. If no state exists for that key,\n * return a default state.\n *\n * @param key The key for which to retrieve the state.\n */\n const getStates = (key: string) =>\n asyncState.states[key] ?? createDefaultStates<unknown>();\n\n /**\n * Partially update the state for a given key.\n *\n * @param key The key to update.\n * @param value A partial state object to merge with the existing state.\n */\n const setQueryState = (key: string, value: Partial<States<unknown>>) => {\n dispatch({ type: 'SET_QUERY_STATE', key, value });\n };\n\n /**\n * Partially update the state for multiple keys at once.\n *\n * @param keys An array of keys to update.\n * @param value A partial state object to merge with each key's existing state.\n */\n const setQueriesState = (keys: string[], value: Partial<States<unknown>>) => {\n dispatch({ type: 'SET_QUERIES_STATE', keys, value });\n };\n\n /**\n * Mark a given query as having encountered an error.\n *\n * @param key The key associated with the query.\n * @param error The error message to set.\n */\n const makeQueryInError = (key: string, error: string) => {\n dispatch({ type: 'MAKE_QUERY_IN_ERROR', key, error });\n };\n\n /**\n * Reset certain keys back to their default states.\n *\n * @param keys The keys to reset.\n */\n const resetKeyState = (keys: string[]) => {\n dispatch({ type: 'RESET_KEY_STATE', keys });\n };\n\n /**\n * Reset the entire state back to defaults, except for keys that match the excluded ones.\n *\n * @param excludedKeys Keys that should not be reset.\n */\n const resetState = (excludedKeys: string[]) => {\n dispatch({ type: 'RESET_STATE', excludeKeys: excludedKeys });\n };\n\n return (\n <AsyncStateContext.Provider\n value={{\n getStates,\n setQueryState,\n setQueriesState,\n makeQueryInError,\n resetKeyState,\n resetState,\n }}\n >\n {children}\n </AsyncStateContext.Provider>\n );\n};\n\n/**\n * A custom hook for accessing the asynchronous state context. It throws an error if used\n * outside of a provider.\n *\n * @returns The asynchronous state context value.\n */\nexport const useAsyncState = () => {\n const context = useContext(AsyncStateContext);\n if (!context) {\n throw new Error('useAsyncState must be used within an AsyncStateProvider');\n }\n return context;\n};\n"],"names":["jsx"],"mappings":";;;AAwDA,MAAM,sBAAsB,OAAsB;AAA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,EACxB;AACF;AASO,MAAM,qBAAqB,CAAC,EAAE,eAAsC;AAEnE,QAAA,CAAC,YAAY,QAAQ,IAAI,WAAW,SAAS,EAAE,QAAQ,CAAA,GAAI;AAQjE,QAAM,YAAY,CAAC,QACjB,WAAW,OAAO,GAAG,KAAK,oBAA6B;AAQnD,QAAA,gBAAgB,CAAC,KAAa,UAAoC;AACtE,aAAS,EAAE,MAAM,mBAAmB,KAAK,OAAO;AAAA,EAClD;AAQM,QAAA,kBAAkB,CAAC,MAAgB,UAAoC;AAC3E,aAAS,EAAE,MAAM,qBAAqB,MAAM,OAAO;AAAA,EACrD;AAQM,QAAA,mBAAmB,CAAC,KAAa,UAAkB;AACvD,aAAS,EAAE,MAAM,uBAAuB,KAAK,OAAO;AAAA,EACtD;AAOM,QAAA,gBAAgB,CAAC,SAAmB;AACxC,aAAS,EAAE,MAAM,mBAAmB,KAAA,CAAM;AAAA,EAC5C;AAOM,QAAA,aAAa,CAAC,iBAA2B;AAC7C,aAAS,EAAE,MAAM,eAAe,aAAa,cAAc;AAAA,EAC7D;AAGE,SAAAA,kCAAA;AAAA,IAAC,kBAAkB;AAAA,IAAlB;AAAA,MACC,OAAO;AAAA,QACL;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,MACF;AAAA,MAEC;AAAA,IAAA;AAAA,EACH;AAEJ;AAQO,MAAM,gBAAgB,MAAM;AAC3B,QAAA,UAAU,WAAW,iBAAiB;AAC5C,MAAI,CAAC,SAAS;AACN,UAAA,IAAI,MAAM,yDAAyD;AAAA,EAAA;AAEpE,SAAA;AACT;"}
1
+ {"version":3,"file":"useAsyncStateStore.mjs","sources":["../../../src/hooks/useAsync/useAsyncStateStore.tsx"],"sourcesContent":["'use client';\n\nimport {\n createContext,\n useContext,\n useReducer,\n PropsWithChildren,\n} from 'react';\n\n/**\n * Represents the states for a given key in the asynchronous state management.\n * This includes flags for loading, fetched, invalidation, and success/error status.\n * It also keeps track of the fetched datetime, retry counts, the data itself, and whether queries are enabled.\n */\ntype States<T> = {\n isLoading: boolean;\n isFetched: boolean;\n isInvalidated: boolean;\n fetchedDateTime: null | Date;\n error: string | null;\n isSuccess: boolean;\n data: T | null;\n errorCount: number;\n isEnabled: boolean;\n};\n\n/**\n * Holds a mapping from a key (string) to its associated state.\n */\ntype StateSlice<T> = {\n [key: string]: States<T>;\n};\n\n/**\n * Describes all the possible actions that can be dispatched to the reducer.\n * These actions allow setting or updating states for specific keys or multiple keys at once,\n * handling errors, and resetting states.\n */\ntype Actions<T> =\n | { type: 'SET_QUERY_STATE'; key: string; value: Partial<States<T>> }\n | { type: 'MAKE_QUERY_IN_ERROR'; key: string; error: string }\n | { type: 'SET_QUERIES_STATE'; keys: string[]; value: Partial<States<T>> }\n | { type: 'RESET_KEY_STATE'; keys: string[] }\n | { type: 'RESET_STATE'; excludeKeys: string[] };\n\n/**\n * The shape of the entire asynchronous state, holding all states in a single object.\n */\ntype AsyncState<T> = {\n states: StateSlice<T>;\n};\n\n/**\n * Creates a default state object with initial values. This is useful when a key\n * has not been initialized yet or when resetting a state back to defaults.\n */\nconst createDefaultStates = <T,>(): States<T> => ({\n isFetched: false,\n fetchedDateTime: null,\n isLoading: false,\n isInvalidated: false,\n error: null,\n isSuccess: false,\n data: null,\n errorCount: 0,\n isEnabled: true,\n});\n\n/**\n * Ensures that a given value is returned as an array.\n * If the value is undefined or null, returns an empty array.\n * If the value is not already an array, wraps it in one.\n */\nconst ensureArray = <T,>(value?: T | T[]): T[] => {\n if (!value) {\n // If no value is provided, return an empty array\n return [];\n } else if (Array.isArray(value)) {\n // If it's already an array, just return it\n return value;\n }\n // If it's a single value, wrap it in an array\n return [value];\n};\n\n/**\n * Given a list of selector keys and a list of keys that may contain arguments,\n * this function returns all keys that match the selectors. Matching is determined\n * by comparing the initial part (split by \"/\") of the key.\n *\n * For example:\n * selectorsKeys = [\"user\", \"posts\"]\n * keysWithArgs = [\"user/123\", \"posts/active\", \"comments/42\"]\n * Result = [\"user/123\", \"posts/active\"]\n */\nconst getMatchKeys = (\n selectorsKeys: string[],\n keysWithArgs: string[]\n): string[] =>\n keysWithArgs.filter((key) => selectorsKeys.includes(key.split('/')[0]));\n\n/**\n * The reducer function handling all state transitions. It takes the current state and an action,\n * and returns a new state based on the type of the action.\n *\n * Actions include:\n * - SET_QUERY_STATE: Update a single key with partial new state.\n * - MAKE_QUERY_IN_ERROR: Mark a single key as errored and update related flags.\n * - SET_QUERIES_STATE: Update multiple keys at once with partial new state.\n * - RESET_KEY_STATE: Reset certain keys to their default states.\n * - RESET_STATE: Reset all keys to their default states except those excluded.\n */\nconst reducer = <T,>(\n state: AsyncState<T>,\n action: Actions<T>\n): AsyncState<T> => {\n switch (action.type) {\n case 'SET_QUERY_STATE': {\n const { key, value } = action;\n return {\n ...state,\n states: {\n ...state.states,\n [key]: {\n // Merge existing state for the key or default state if not present\n ...(state.states[key] ?? createDefaultStates<T>()),\n ...value,\n },\n },\n };\n }\n case 'MAKE_QUERY_IN_ERROR': {\n const { key, error } = action;\n return {\n ...state,\n states: {\n ...state.states,\n [key]: {\n // Merge existing state or default if not found\n ...(state.states[key] ?? createDefaultStates<T>()),\n // Explicitly set error and related flags\n error,\n isFetched: true,\n isSuccess: false,\n errorCount: (state.states[key]?.errorCount ?? 0) + 1,\n isLoading: false,\n isInvalidated: false,\n },\n },\n };\n }\n case 'SET_QUERIES_STATE': {\n const { keys, value } = action;\n const keyArray = ensureArray(keys);\n if (keyArray.length === 0) return state;\n\n // Update multiple keys in a single action\n const updatedStates = { ...state.states };\n keyArray.forEach((key) => {\n updatedStates[key] = {\n ...(state.states[key] ?? createDefaultStates<T>()),\n ...value,\n };\n });\n\n return {\n ...state,\n states: updatedStates,\n };\n }\n case 'RESET_KEY_STATE': {\n const { keys } = action;\n const keyArray = ensureArray(keys);\n if (keyArray.length === 0) return state;\n\n // Find all keys that match the given selectors\n const allKeys = Object.keys(state.states);\n const matchedKeys = getMatchKeys(keyArray, allKeys);\n if (matchedKeys.length === 0) return state;\n\n // Reset the matched keys back to default states\n const resetStates = { ...state.states };\n matchedKeys.forEach((key) => {\n resetStates[key] = createDefaultStates<T>();\n });\n\n return {\n ...state,\n states: resetStates,\n };\n }\n case 'RESET_STATE': {\n const excludeArray = ensureArray(action.excludeKeys);\n const allKeys = Object.keys(state.states);\n const matchedKeys = getMatchKeys(excludeArray, allKeys);\n\n // Reset all states except those that match the exclude keys\n const newStates: StateSlice<T> = {};\n allKeys.forEach((key) => {\n newStates[key] = matchedKeys.includes(key)\n ? state.states[key]\n : createDefaultStates<T>();\n });\n\n return {\n ...state,\n states: newStates,\n };\n }\n default:\n return state;\n }\n};\n\n/**\n * The context type that will be provided to consumers.\n * It exposes a set of functions for interacting with the asynchronous state:\n * - getStates: Retrieve the current state for a given key.\n * - setQueryState: Partially update a single key's state.\n * - setQueriesState: Partially update multiple keys' states.\n * - makeQueryInError: Set a particular key into an error state.\n * - resetKeyState: Reset certain keys to their default states.\n * - resetState: Reset all keys to their default states except a set of excluded ones.\n */\ntype AsyncStateContextType<T> = {\n getStates: (key: string) => States<T>;\n setQueryState: (key: string, value: Partial<States<T>>) => void;\n setQueriesState: (keys: string[], value: Partial<States<T>>) => void;\n makeQueryInError: (key: string, error: string) => void;\n resetKeyState: (keys: string[]) => void;\n resetState: (excludedKeys: string[]) => void;\n};\n\n/**\n * Creates a React context for asynchronous state management.\n * This context will be provided by the AsyncStateProvider and consumed by hooks like useAsyncState.\n */\nconst AsyncStateContext = createContext<AsyncStateContextType<unknown> | null>(\n null\n);\n\n/**\n * A provider component that wraps its children and provides the asynchronous\n * state context. It uses the reducer to manage states and dispatch actions\n * based on consumer interactions.\n *\n * @param children The React children elements that should have access to this context.\n */\nexport const AsyncStateProvider = ({ children }: PropsWithChildren<{}>) => {\n // Initialize the reducer with an empty state object\n const [asyncState, dispatch] = useReducer(reducer, { states: {} });\n\n /**\n * Retrieve the state associated with a given key. If no state exists for that key,\n * return a default state.\n *\n * @param key The key for which to retrieve the state.\n */\n const getStates = (key: string) =>\n asyncState.states[key] ?? createDefaultStates<unknown>();\n\n /**\n * Partially update the state for a given key.\n *\n * @param key The key to update.\n * @param value A partial state object to merge with the existing state.\n */\n const setQueryState = (key: string, value: Partial<States<unknown>>) => {\n dispatch({ type: 'SET_QUERY_STATE', key, value });\n };\n\n /**\n * Partially update the state for multiple keys at once.\n *\n * @param keys An array of keys to update.\n * @param value A partial state object to merge with each key's existing state.\n */\n const setQueriesState = (keys: string[], value: Partial<States<unknown>>) => {\n dispatch({ type: 'SET_QUERIES_STATE', keys, value });\n };\n\n /**\n * Mark a given query as having encountered an error.\n *\n * @param key The key associated with the query.\n * @param error The error message to set.\n */\n const makeQueryInError = (key: string, error: string) => {\n dispatch({ type: 'MAKE_QUERY_IN_ERROR', key, error });\n };\n\n /**\n * Reset certain keys back to their default states.\n *\n * @param keys The keys to reset.\n */\n const resetKeyState = (keys: string[]) => {\n dispatch({ type: 'RESET_KEY_STATE', keys });\n };\n\n /**\n * Reset the entire state back to defaults, except for keys that match the excluded ones.\n *\n * @param excludedKeys Keys that should not be reset.\n */\n const resetState = (excludedKeys: string[]) => {\n dispatch({ type: 'RESET_STATE', excludeKeys: excludedKeys });\n };\n\n return (\n <AsyncStateContext.Provider\n value={{\n getStates,\n setQueryState,\n setQueriesState,\n makeQueryInError,\n resetKeyState,\n resetState,\n }}\n >\n {children}\n </AsyncStateContext.Provider>\n );\n};\n\n/**\n * A custom hook for accessing the asynchronous state context. It throws an error if used\n * outside of a provider.\n *\n * @returns The asynchronous state context value.\n */\nexport const useAsyncState = () => {\n const context = useContext(AsyncStateContext);\n if (!context) {\n throw new Error('useAsyncState must be used within an AsyncStateProvider');\n }\n return context;\n};\n"],"names":["jsx"],"mappings":";;;AAwDA,MAAM,sBAAsB,OAAsB;AAAA,EAChD,WAAW;AAAA,EACX,iBAAiB;AAAA,EACjB,WAAW;AAAA,EACX,eAAe;AAAA,EACf,OAAO;AAAA,EACP,WAAW;AAAA,EACX,MAA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AA,GAAI;AAQjE,QAAM,YAAY,CAAC,QACjB,WAAW,OAAO,GAAG,KAAK,oBAA6B;AAQnD,QAAA,gBAAgB,CAAC,KAAa,UAAoC;AACtE,aAAS,EAAE,MAAM,mBAAmB,KAAK,OAAO;AAAA,EAClD;AAQM,QAAA,kBAAkB,CAAC,MAAgB,UAAoC;AAC3E,aAAS,EAAE,MAAM,qBAAqB,MAAM,OAAO;AAAA,EACrD;AAQM,QAAA,mBAAmB,CAAC,KAAa,UAAkB;AACvD,aAAS,EAAE,MAAM,uBAAuB,KAAK,OAAO;AAAA,EACtD;AAOM,QAAA,gBAAgB,CAAC,SAAmB;AACxC,aAAS,EAAE,MAAM,mBAAmB,KAAA,CAAM;AAAA,EAC5C;AAOM,QAAA,aAAa,CAAC,iBAA2B;AAC7C,aAAS,EAAE,MAAM,eAAe,aAAa,cAAc;AAAA,EAC7D;AAGE,SAAAA,kCAAA;AAAA,IAAC,kBAAkB;AAAA,IAAlB;AAAA,MACC,OAAO;AAAA,QACL;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,MACF;AAAA,MAEC;AAAA,IAAA;AAAA,EACH;AAEJ;AAQO,MAAM,gBAAgB,MAAM;AAC3B,QAAA,UAAU,WAAW,iBAAiB;AAC5C,MAAI,CAAC,SAAS;AACN,UAAA,IAAI,MAAM,yDAAyD;AAAA,EAAA;AAEpE,SAAA;AACT;"}
@@ -6,7 +6,7 @@ const merge = require("deepmerge");
6
6
  const require$$0 = require("react");
7
7
  const hooks_intlayerAPIHooks = require("./intlayerAPIHooks.cjs");
8
8
  const useGetAllDictionaries = (...props) => {
9
- const { data: onlineDictionariesAPI, isLoading } = hooks_intlayerAPIHooks.useGetDictionaries(
9
+ const { data: onlineDictionariesAPI, isWaitingData } = hooks_intlayerAPIHooks.useGetDictionaries(
10
10
  ...props
11
11
  );
12
12
  const onlineDictionaries = require$$0.useMemo(
@@ -27,7 +27,7 @@ const useGetAllDictionaries = (...props) => {
27
27
  online: onlineDictionaries,
28
28
  locale: localeDictionaries,
29
29
  all: allDictionaries,
30
- isLoading
30
+ isLoading: isWaitingData
31
31
  };
32
32
  };
33
33
  exports.useGetAllDictionaries = useGetAllDictionaries;
@@ -1 +1 @@
1
- {"version":3,"file":"useGetAllDictionaries.cjs","sources":["../../src/hooks/useGetAllDictionaries.tsx"],"sourcesContent":["'use client';\n\n/**\n * @intlayer/dictionaries-entry is a package that only returns the dictionary entry path.\n * Using an external package allow to alias it in the bundle configuration (such as webpack).\n * The alias allow hot reload the app (such as nextjs) on any dictionary change.\n */\nimport { Dictionary } from '@intlayer/core';\nimport localeDictionaries from '@intlayer/dictionaries-entry';\nimport merge from 'deepmerge';\nimport { useMemo } from 'react';\nimport { useGetDictionaries } from './intlayerAPIHooks';\n\ntype Args = Parameters<typeof useGetDictionaries>;\n\nexport const useGetAllDictionaries = (...props: Args) => {\n const { data: onlineDictionariesAPI, isLoading } = useGetDictionaries(\n ...props\n );\n\n const onlineDictionaries: Record<string, Dictionary> = useMemo(\n () =>\n (onlineDictionariesAPI?.data ?? []).reduce(\n (acc, dictionary) => {\n acc[dictionary.key] = dictionary;\n return acc;\n },\n {} as Record<string, Dictionary>\n ),\n [onlineDictionariesAPI]\n );\n\n const allDictionaries: Record<string, Dictionary> = useMemo(\n () => merge(onlineDictionaries ?? {}, localeDictionaries),\n [onlineDictionaries]\n );\n\n return {\n online: onlineDictionaries,\n locale: localeDictionaries,\n all: allDictionaries,\n isLoading,\n };\n};\n"],"names":["useGetDictionaries","useMemo"],"mappings":";;;;;;;AAea,MAAA,wBAAwB,IAAI,UAAgB;AACvD,QAAM,EAAE,MAAM,uBAAuB,UAAc,IAAAA,uBAAA;AAAA,IACjD,GAAG;AAAA,EACL;AAEA,QAAM,qBAAiDC,WAAA;AAAA,IACrD,OACG,uBAAuB,QAAQ,CAAA,GAAI;AAAA,MAClC,CAAC,KAAK,eAAe;AACf,YAAA,WAAW,GAAG,IAAI;AACf,eAAA;AAAA,MACT;AAAA,MACA,CAAA;AAAA,IACF;AAAA,IACF,CAAC,qBAAqB;AAAA,EACxB;AAEA,QAAM,kBAA8CA,WAAA;AAAA,IAClD,MAAM,MAAM,sBAAsB,IAAI,kBAAkB;AAAA,IACxD,CAAC,kBAAkB;AAAA,EACrB;AAEO,SAAA;AAAA,IACL,QAAQ;AAAA,IACR,QAAQ;AAAA,IACR,KAAK;AAAA,IACL;AAAA,EACF;AACF;;"}
1
+ {"version":3,"file":"useGetAllDictionaries.cjs","sources":["../../src/hooks/useGetAllDictionaries.tsx"],"sourcesContent":["'use client';\n\n/**\n * @intlayer/dictionaries-entry is a package that only returns the dictionary entry path.\n * Using an external package allow to alias it in the bundle configuration (such as webpack).\n * The alias allow hot reload the app (such as nextjs) on any dictionary change.\n */\nimport { Dictionary } from '@intlayer/core';\nimport localeDictionaries from '@intlayer/dictionaries-entry';\nimport merge from 'deepmerge';\nimport { useMemo } from 'react';\nimport { useGetDictionaries } from './intlayerAPIHooks';\n\ntype Args = Parameters<typeof useGetDictionaries>;\n\nexport const useGetAllDictionaries = (...props: Args) => {\n const { data: onlineDictionariesAPI, isWaitingData } = useGetDictionaries(\n ...props\n );\n\n const onlineDictionaries: Record<string, Dictionary> = useMemo(\n () =>\n (onlineDictionariesAPI?.data ?? []).reduce(\n (acc, dictionary) => {\n acc[dictionary.key] = dictionary;\n return acc;\n },\n {} as Record<string, Dictionary>\n ),\n [onlineDictionariesAPI]\n );\n\n const allDictionaries: Record<string, Dictionary> = useMemo(\n () => merge(onlineDictionaries ?? {}, localeDictionaries),\n [onlineDictionaries]\n );\n\n return {\n online: onlineDictionaries,\n locale: localeDictionaries,\n all: allDictionaries,\n isLoading: isWaitingData,\n };\n};\n"],"names":["useGetDictionaries","useMemo"],"mappings":";;;;;;;AAea,MAAA,wBAAwB,IAAI,UAAgB;AACvD,QAAM,EAAE,MAAM,uBAAuB,cAAkB,IAAAA,uBAAA;AAAA,IACrD,GAAG;AAAA,EACL;AAEA,QAAM,qBAAiDC,WAAA;AAAA,IACrD,OACG,uBAAuB,QAAQ,CAAA,GAAI;AAAA,MAClC,CAAC,KAAK,eAAe;AACf,YAAA,WAAW,GAAG,IAAI;AACf,eAAA;AAAA,MACT;AAAA,MACA,CAAA;AAAA,IACF;AAAA,IACF,CAAC,qBAAqB;AAAA,EACxB;AAEA,QAAM,kBAA8CA,WAAA;AAAA,IAClD,MAAM,MAAM,sBAAsB,IAAI,kBAAkB;AAAA,IACxD,CAAC,kBAAkB;AAAA,EACrB;AAEO,SAAA;AAAA,IACL,QAAQ;AAAA,IACR,QAAQ;AAAA,IACR,KAAK;AAAA,IACL,WAAW;AAAA,EACb;AACF;;"}
@@ -1,7 +1,7 @@
1
1
  import { Dictionary } from '@intlayer/core';
2
2
  import { useGetDictionaries } from './intlayerAPIHooks';
3
3
  type Args = Parameters<typeof useGetDictionaries>;
4
- export declare const useGetAllDictionaries: (args?: import('./useAsync').UseAsyncOptions<(filters?: import('@intlayer/backend').GetDictionariesParams, otherOptions?: import('../libs/intlayer-api/fetcher').FetcherOptions) => Promise<import('@intlayer/backend').GetDictionariesResult>> | undefined) => {
4
+ export declare const useGetAllDictionaries: (args?: import('./useAsync').UseAsyncOptions<(filters?: GetDictionariesParams, otherOptions?: import('node_modules/@intlayer/api/dist/types/fetcher').FetcherOptions) => Promise<GetDictionariesResult>> | undefined) => {
5
5
  online: Record<string, Dictionary>;
6
6
  locale: Record<string, Dictionary>;
7
7
  all: Record<string, Dictionary>;
@@ -1 +1 @@
1
- {"version":3,"file":"useGetAllDictionaries.d.ts","sourceRoot":"","sources":["../../src/hooks/useGetAllDictionaries.tsx"],"names":[],"mappings":"AAEA;;;;GAIG;AACH,OAAO,EAAE,UAAU,EAAE,MAAM,gBAAgB,CAAC;AAI5C,OAAO,EAAE,kBAAkB,EAAE,MAAM,oBAAoB,CAAC;AAExD,KAAK,IAAI,GAAG,UAAU,CAAC,OAAO,kBAAkB,CAAC,CAAC;AAElD,eAAO,MAAM,qBAAqB;;;;;CA4BjC,CAAC"}
1
+ {"version":3,"file":"useGetAllDictionaries.d.ts","sourceRoot":"","sources":["../../src/hooks/useGetAllDictionaries.tsx"],"names":[],"mappings":"AAEA;;;;GAIG;AACH,OAAO,EAAE,UAAU,EAAE,MAAM,gBAAgB,CAAC;AAI5C,OAAO,EAAE,kBAAkB,EAAE,MAAM,oBAAoB,CAAC;AAExD,KAAK,IAAI,GAAG,UAAU,CAAC,OAAO,kBAAkB,CAAC,CAAC;AAElD,eAAO,MAAM,qBAAqB,0DA6Bg7U,qBAAsB,oGAA4C,qBAAqB;;;;;CADxiV,CAAC"}
@@ -4,7 +4,7 @@ import merge from "deepmerge";
4
4
  import { useMemo } from "react";
5
5
  import { useGetDictionaries } from "./intlayerAPIHooks.mjs";
6
6
  const useGetAllDictionaries = (...props) => {
7
- const { data: onlineDictionariesAPI, isLoading } = useGetDictionaries(
7
+ const { data: onlineDictionariesAPI, isWaitingData } = useGetDictionaries(
8
8
  ...props
9
9
  );
10
10
  const onlineDictionaries = useMemo(
@@ -25,7 +25,7 @@ const useGetAllDictionaries = (...props) => {
25
25
  online: onlineDictionaries,
26
26
  locale: localeDictionaries,
27
27
  all: allDictionaries,
28
- isLoading
28
+ isLoading: isWaitingData
29
29
  };
30
30
  };
31
31
  export {
@@ -1 +1 @@
1
- {"version":3,"file":"useGetAllDictionaries.mjs","sources":["../../src/hooks/useGetAllDictionaries.tsx"],"sourcesContent":["'use client';\n\n/**\n * @intlayer/dictionaries-entry is a package that only returns the dictionary entry path.\n * Using an external package allow to alias it in the bundle configuration (such as webpack).\n * The alias allow hot reload the app (such as nextjs) on any dictionary change.\n */\nimport { Dictionary } from '@intlayer/core';\nimport localeDictionaries from '@intlayer/dictionaries-entry';\nimport merge from 'deepmerge';\nimport { useMemo } from 'react';\nimport { useGetDictionaries } from './intlayerAPIHooks';\n\ntype Args = Parameters<typeof useGetDictionaries>;\n\nexport const useGetAllDictionaries = (...props: Args) => {\n const { data: onlineDictionariesAPI, isLoading } = useGetDictionaries(\n ...props\n );\n\n const onlineDictionaries: Record<string, Dictionary> = useMemo(\n () =>\n (onlineDictionariesAPI?.data ?? []).reduce(\n (acc, dictionary) => {\n acc[dictionary.key] = dictionary;\n return acc;\n },\n {} as Record<string, Dictionary>\n ),\n [onlineDictionariesAPI]\n );\n\n const allDictionaries: Record<string, Dictionary> = useMemo(\n () => merge(onlineDictionaries ?? {}, localeDictionaries),\n [onlineDictionaries]\n );\n\n return {\n online: onlineDictionaries,\n locale: localeDictionaries,\n all: allDictionaries,\n isLoading,\n };\n};\n"],"names":[],"mappings":";;;;;AAea,MAAA,wBAAwB,IAAI,UAAgB;AACvD,QAAM,EAAE,MAAM,uBAAuB,UAAc,IAAA;AAAA,IACjD,GAAG;AAAA,EACL;AAEA,QAAM,qBAAiD;AAAA,IACrD,OACG,uBAAuB,QAAQ,CAAA,GAAI;AAAA,MAClC,CAAC,KAAK,eAAe;AACf,YAAA,WAAW,GAAG,IAAI;AACf,eAAA;AAAA,MACT;AAAA,MACA,CAAA;AAAA,IACF;AAAA,IACF,CAAC,qBAAqB;AAAA,EACxB;AAEA,QAAM,kBAA8C;AAAA,IAClD,MAAM,MAAM,sBAAsB,IAAI,kBAAkB;AAAA,IACxD,CAAC,kBAAkB;AAAA,EACrB;AAEO,SAAA;AAAA,IACL,QAAQ;AAAA,IACR,QAAQ;AAAA,IACR,KAAK;AAAA,IACL;AAAA,EACF;AACF;"}
1
+ {"version":3,"file":"useGetAllDictionaries.mjs","sources":["../../src/hooks/useGetAllDictionaries.tsx"],"sourcesContent":["'use client';\n\n/**\n * @intlayer/dictionaries-entry is a package that only returns the dictionary entry path.\n * Using an external package allow to alias it in the bundle configuration (such as webpack).\n * The alias allow hot reload the app (such as nextjs) on any dictionary change.\n */\nimport { Dictionary } from '@intlayer/core';\nimport localeDictionaries from '@intlayer/dictionaries-entry';\nimport merge from 'deepmerge';\nimport { useMemo } from 'react';\nimport { useGetDictionaries } from './intlayerAPIHooks';\n\ntype Args = Parameters<typeof useGetDictionaries>;\n\nexport const useGetAllDictionaries = (...props: Args) => {\n const { data: onlineDictionariesAPI, isWaitingData } = useGetDictionaries(\n ...props\n );\n\n const onlineDictionaries: Record<string, Dictionary> = useMemo(\n () =>\n (onlineDictionariesAPI?.data ?? []).reduce(\n (acc, dictionary) => {\n acc[dictionary.key] = dictionary;\n return acc;\n },\n {} as Record<string, Dictionary>\n ),\n [onlineDictionariesAPI]\n );\n\n const allDictionaries: Record<string, Dictionary> = useMemo(\n () => merge(onlineDictionaries ?? {}, localeDictionaries),\n [onlineDictionaries]\n );\n\n return {\n online: onlineDictionaries,\n locale: localeDictionaries,\n all: allDictionaries,\n isLoading: isWaitingData,\n };\n};\n"],"names":[],"mappings":";;;;;AAea,MAAA,wBAAwB,IAAI,UAAgB;AACvD,QAAM,EAAE,MAAM,uBAAuB,cAAkB,IAAA;AAAA,IACrD,GAAG;AAAA,EACL;AAEA,QAAM,qBAAiD;AAAA,IACrD,OACG,uBAAuB,QAAQ,CAAA,GAAI;AAAA,MAClC,CAAC,KAAK,eAAe;AACf,YAAA,WAAW,GAAG,IAAI;AACf,eAAA;AAAA,MACT;AAAA,MACA,CAAA;AAAA,IACF;AAAA,IACF,CAAC,qBAAqB;AAAA,EACxB;AAEA,QAAM,kBAA8C;AAAA,IAClD,MAAM,MAAM,sBAAsB,IAAI,kBAAkB;AAAA,IACxD,CAAC,kBAAkB;AAAA,EACrB;AAEO,SAAA;AAAA,IACL,QAAQ;AAAA,IACR,QAAQ;AAAA,IACR,KAAK;AAAA,IACL,WAAW;AAAA,EACb;AACF;"}
@@ -1,8 +1,8 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
3
  const require$$0 = require("react");
4
+ const index = require("../index-DFc7og1d.cjs");
4
5
  const components_Auth_useAuth_index = require("../components/Auth/useAuth/index.cjs");
5
- const libs_intlayerApi_index = require("../libs/intlayer-api/index.cjs");
6
6
  const useIntlayerAuth = (options) => {
7
7
  const { csrfToken, oAuth2AccessToken } = components_Auth_useAuth_index.useAuth();
8
8
  const headers = require$$0.useMemo(
@@ -16,7 +16,7 @@ const useIntlayerAuth = (options) => {
16
16
  [csrfToken]
17
17
  );
18
18
  return require$$0.useMemo(
19
- () => libs_intlayerApi_index.getIntlayerAPI({
19
+ () => index.getIntlayerAPI({
20
20
  headers,
21
21
  body,
22
22
  ...options
@@ -1 +1 @@
1
- {"version":3,"file":"useIntlayerAPI.cjs","sources":["../../src/hooks/useIntlayerAPI.ts"],"sourcesContent":["import { useMemo } from 'react';\nimport { useAuth } from '../components/Auth/useAuth';\nimport { getIntlayerAPI } from '../libs/intlayer-api';\nimport { FetcherOptions } from '../libs/intlayer-api/fetcher';\n\nexport const useIntlayerAuth = (options?: FetcherOptions) => {\n const { csrfToken, oAuth2AccessToken } = useAuth();\n\n const headers = useMemo(\n () =>\n oAuth2AccessToken?.accessToken\n ? {\n Authorization: `Bearer ${oAuth2AccessToken.accessToken}`,\n }\n : undefined,\n [oAuth2AccessToken?.accessToken]\n );\n\n const body = useMemo(\n () => (csrfToken ? { csrf_token: csrfToken } : undefined),\n [csrfToken]\n );\n\n return useMemo(\n () =>\n getIntlayerAPI({\n headers,\n body,\n ...options,\n }),\n [body, headers]\n );\n};\n"],"names":["useAuth","useMemo","getIntlayerAPI"],"mappings":";;;;;AAKa,MAAA,kBAAkB,CAAC,YAA6B;AAC3D,QAAM,EAAE,WAAW,kBAAkB,IAAIA,sCAAQ;AAEjD,QAAM,UAAUC,WAAA;AAAA,IACd,MACE,mBAAmB,cACf;AAAA,MACE,eAAe,UAAU,kBAAkB,WAAW;AAAA,IAExD,IAAA;AAAA,IACN,CAAC,mBAAmB,WAAW;AAAA,EACjC;AAEA,QAAM,OAAOA,WAAA;AAAA,IACX,MAAO,YAAY,EAAE,YAAY,cAAc;AAAA,IAC/C,CAAC,SAAS;AAAA,EACZ;AAEO,SAAAA,WAAA;AAAA,IACL,MACEC,sCAAe;AAAA,MACb;AAAA,MACA;AAAA,MACA,GAAG;AAAA,IAAA,CACJ;AAAA,IACH,CAAC,MAAM,OAAO;AAAA,EAChB;AACF;;"}
1
+ {"version":3,"file":"useIntlayerAPI.cjs","sources":["../../src/hooks/useIntlayerAPI.ts"],"sourcesContent":["import { useMemo } from 'react';\nimport { getIntlayerAPI } from '../../../api/src';\nimport { FetcherOptions } from '../../../api/src/fetcher';\nimport { useAuth } from '../components/Auth/useAuth';\n\nexport const useIntlayerAuth = (options?: FetcherOptions) => {\n const { csrfToken, oAuth2AccessToken } = useAuth();\n\n const headers = useMemo(\n () =>\n oAuth2AccessToken?.accessToken\n ? {\n Authorization: `Bearer ${oAuth2AccessToken.accessToken}`,\n }\n : undefined,\n [oAuth2AccessToken?.accessToken]\n );\n\n const body = useMemo(\n () => (csrfToken ? { csrf_token: csrfToken } : undefined),\n [csrfToken]\n );\n\n return useMemo(\n () =>\n getIntlayerAPI({\n headers,\n body,\n ...options,\n }),\n [body, headers]\n );\n};\n"],"names":["useAuth","useMemo","getIntlayerAPI"],"mappings":";;;;;AAKa,MAAA,kBAAkB,CAAC,YAA6B;AAC3D,QAAM,EAAE,WAAW,kBAAkB,IAAIA,sCAAQ;AAEjD,QAAM,UAAUC,WAAA;AAAA,IACd,MACE,mBAAmB,cACf;AAAA,MACE,eAAe,UAAU,kBAAkB,WAAW;AAAA,IAExD,IAAA;AAAA,IACN,CAAC,mBAAmB,WAAW;AAAA,EACjC;AAEA,QAAM,OAAOA,WAAA;AAAA,IACX,MAAO,YAAY,EAAE,YAAY,cAAc;AAAA,IAC/C,CAAC,SAAS;AAAA,EACZ;AAEO,SAAAA,WAAA;AAAA,IACL,MACEC,qBAAe;AAAA,MACb;AAAA,MACA;AAAA,MACA,GAAG;AAAA,IAAA,CACJ;AAAA,IACH,CAAC,MAAM,OAAO;AAAA,EAChB;AACF;;"}
@@ -1,78 +1,79 @@
1
- import { FetcherOptions } from '../libs/intlayer-api/fetcher';
1
+ import { FetcherOptions } from '../../../api/src/fetcher';
2
2
  export declare const useIntlayerAuth: (options?: FetcherOptions) => {
3
3
  organization: {
4
- getOrganizations: (filters?: import('@intlayer/backend').GetOrganizationsParams, otherOptions?: FetcherOptions) => Promise<import('@intlayer/backend').GetOrganizationsResult>;
5
- getOrganization: (organizationId: import('@intlayer/backend').GetOrganizationParam["organizationId"], otherOptions?: FetcherOptions) => Promise<import('@intlayer/backend').GetOrganizationResult>;
6
- addOrganization: (organization: import('@intlayer/backend').AddOrganizationBody, otherOptions?: FetcherOptions) => Promise<import('@intlayer/backend').AddOrganizationResult>;
7
- addOrganizationMember: (body: import('@intlayer/backend').AddOrganizationMemberBody, otherOptions?: FetcherOptions) => Promise<import('@intlayer/backend').AddOrganizationMemberResult>;
8
- updateOrganization: (organization: import('@intlayer/backend').UpdateOrganizationBody, otherOptions?: FetcherOptions) => Promise<import('@intlayer/backend').UpdateOrganizationResult>;
9
- updateOrganizationMembers: (body: import('@intlayer/backend').UpdateOrganizationMembersBody, otherOptions?: FetcherOptions) => Promise<import('@intlayer/backend').UpdateOrganizationMembersResult>;
10
- deleteOrganization: (otherOptions?: FetcherOptions) => Promise<import('@intlayer/backend').DeleteOrganizationResult>;
11
- selectOrganization: (organizationId: import('@intlayer/backend').SelectOrganizationParam["organizationId"], otherOptions?: FetcherOptions) => Promise<import('@intlayer/backend').SelectOrganizationResult>;
12
- unselectOrganization: (otherOptions?: FetcherOptions) => Promise<import('@intlayer/backend').UnselectOrganizationResult>;
4
+ getOrganizations: (filters?: GetOrganizationsParams, otherOptions?: FetcherOptions) => Promise<GetOrganizationsResult>;
5
+ getOrganization: (organizationId: GetOrganizationParam, otherOptions?: FetcherOptions) => Promise<GetOrganizationResult>;
6
+ addOrganization: (organization: AddOrganizationBody, otherOptions?: FetcherOptions) => Promise<AddOrganizationResult>;
7
+ addOrganizationMember: (body: AddOrganizationMemberBody, otherOptions?: FetcherOptions) => Promise<AddOrganizationMemberResult>;
8
+ updateOrganization: (organization: UpdateOrganizationBody, otherOptions?: FetcherOptions) => Promise<UpdateOrganizationResult>;
9
+ updateOrganizationMembers: (body: UpdateOrganizationMembersBody, otherOptions?: FetcherOptions) => Promise<UpdateOrganizationMembersResult>;
10
+ deleteOrganization: (otherOptions?: FetcherOptions) => Promise<DeleteOrganizationResult>;
11
+ selectOrganization: (organizationId: SelectOrganizationParam, otherOptions?: FetcherOptions) => Promise<SelectOrganizationResult>;
12
+ unselectOrganization: (otherOptions?: FetcherOptions) => Promise<UnselectOrganizationResult>;
13
13
  };
14
14
  project: {
15
- getProjects: (filters?: import('@intlayer/backend').GetProjectsParams, otherOptions?: FetcherOptions) => Promise<import('@intlayer/backend').GetProjectsResult>;
16
- addProject: (project: import('@intlayer/backend').AddProjectBody, otherOptions?: FetcherOptions) => Promise<import('@intlayer/backend').AddProjectResult>;
17
- updateProject: (project: import('@intlayer/backend').UpdateProjectBody, otherOptions?: FetcherOptions) => Promise<import('@intlayer/backend').UpdateProjectResult>;
18
- updateProjectMembers: (body: import('@intlayer/backend').UpdateProjectMembersBody, otherOptions?: FetcherOptions) => Promise<import('@intlayer/backend').UpdateProjectMembersResult>;
19
- deleteProject: (otherOptions?: FetcherOptions) => Promise<import('@intlayer/backend').DeleteProjectResult>;
20
- selectProject: (projectId: import('@intlayer/backend').SelectProjectParam["projectId"], otherOptions?: FetcherOptions) => Promise<import('@intlayer/backend').SelectProjectResult>;
21
- unselectProject: (otherOptions?: FetcherOptions) => Promise<import('@intlayer/backend').UnselectProjectResult>;
22
- addNewAccessKey: (accessKey: import('@intlayer/backend').AddNewAccessKeyBody, otherOptions?: FetcherOptions) => Promise<import('@intlayer/backend').AddNewAccessKeyResponse>;
23
- deleteAccessKey: (clientId: import('@intlayer/backend').DeleteAccessKeyBody["clientId"], otherOptions?: FetcherOptions) => Promise<import('@intlayer/backend').DeleteAccessKeyResponse>;
24
- refreshAccessKey: (clientId: import('@intlayer/backend').RefreshAccessKeyBody["clientId"], otherOptions?: FetcherOptions) => Promise<import('@intlayer/backend').RefreshAccessKeyResponse>;
15
+ getProjects: (filters?: GetProjectsParams, otherOptions?: FetcherOptions) => Promise<GetProjectsResult>;
16
+ addProject: (project: AddProjectBody, otherOptions?: FetcherOptions) => Promise<AddProjectResult>;
17
+ updateProject: (project: UpdateProjectBody, otherOptions?: FetcherOptions) => Promise<UpdateProjectResult>;
18
+ updateProjectMembers: (body: UpdateProjectMembersBody, otherOptions?: FetcherOptions) => Promise<UpdateProjectMembersResult>;
19
+ deleteProject: (otherOptions?: FetcherOptions) => Promise<DeleteProjectResult>;
20
+ selectProject: (projectId: SelectProjectParam, otherOptions?: FetcherOptions) => Promise<SelectProjectResult>;
21
+ unselectProject: (otherOptions?: FetcherOptions) => Promise<UnselectProjectResult>;
22
+ addNewAccessKey: (accessKey: AddNewAccessKeyBody, otherOptions?: FetcherOptions) => Promise<AddNewAccessKeyResponse>;
23
+ deleteAccessKey: (clientId: DeleteAccessKeyBody, otherOptions?: FetcherOptions) => Promise<DeleteAccessKeyResponse>;
24
+ refreshAccessKey: (clientId: RefreshAccessKeyBody, otherOptions?: FetcherOptions) => Promise<RefreshAccessKeyResponse>;
25
25
  };
26
26
  user: {
27
- createUser: (user: import('@intlayer/backend').CreateUserBody, otherOptions?: FetcherOptions) => Promise<import('@intlayer/backend').CreateUserResult>;
28
- getUsers: (filters?: import('@intlayer/backend').GetUsersParams, otherOptions?: FetcherOptions) => Promise<import('@intlayer/backend').GetUsersResult>;
29
- getUserById: (userId: import('@intlayer/backend').GetUserByIdParams["userId"], otherOptions?: FetcherOptions) => Promise<import('@intlayer/backend').GetUserByIdResult>;
30
- getUserByAccount: (providerAccountId: import('@intlayer/backend').GetUserByAccountParams["providerAccountId"], provider: import('@intlayer/backend').GetUserByAccountParams["provider"], otherOptions?: FetcherOptions) => Promise<import('@intlayer/backend').GetUserByAccountResult>;
31
- getUserByEmail: (email: import('@intlayer/backend').GetUserByEmailParams["email"], otherOptions?: FetcherOptions) => Promise<import('@intlayer/backend').GetUserByEmailResult>;
32
- updateUser: (user: import('@intlayer/backend').UpdateUserBody, otherOptions?: FetcherOptions) => Promise<import('@intlayer/backend').UpdateUserResult>;
33
- deleteUser: (userId: string, otherOptions?: FetcherOptions) => Promise<import('@intlayer/backend').UpdateUserResult>;
27
+ createUser: (user: CreateUserBody, otherOptions?: FetcherOptions) => Promise<CreateUserResult>;
28
+ getUsers: (filters?: GetUsersParams, otherOptions?: FetcherOptions) => Promise<GetUsersResult>;
29
+ getUserById: (userId: GetUserByIdParams, otherOptions?: FetcherOptions) => Promise<GetUserByIdResult>;
30
+ getUserByAccount: (providerAccountId: GetUserByAccountParams, provider: GetUserByAccountParams, otherOptions?: FetcherOptions) => Promise<GetUserByAccountResult>;
31
+ getUserByEmail: (email: GetUserByEmailParams, otherOptions?: FetcherOptions) => Promise<GetUserByEmailResult>;
32
+ updateUser: (user: UpdateUserBody, otherOptions?: FetcherOptions) => Promise<UpdateUserResult>;
33
+ deleteUser: (userId: string, otherOptions?: FetcherOptions) => Promise<UpdateUserResult>;
34
34
  };
35
35
  auth: {
36
- login: (user: import('@intlayer/backend').LoginBody, otherOptions?: FetcherOptions) => Promise<import('@intlayer/backend').LoginResult>;
37
- getLoginWithGitHubURL: (params: import('@intlayer/backend').GithubLoginQueryParams) => string;
38
- getLoginWithGoogleURL: (params: import('@intlayer/backend').GoogleLoginQueryParams) => string;
39
- register: (user: import('@intlayer/backend').RegisterBody, query?: import('@intlayer/backend').RegisterQuery, otherOptions?: FetcherOptions) => Promise<import('@intlayer/backend').RegisterResult>;
36
+ login: (user: LoginBody, otherOptions?: FetcherOptions) => Promise<LoginResult>;
37
+ getLoginWithGitHubURL: (params: GithubLoginQueryParams) => string;
38
+ getLoginWithGoogleURL: (params: GoogleLoginQueryParams) => string;
39
+ register: (user: RegisterBody, query?: RegisterQuery, otherOptions?: FetcherOptions) => Promise<RegisterResult>;
40
40
  logout: (otherOptions?: FetcherOptions) => Promise<void>;
41
- resetPassword: (params: import('@intlayer/backend').ResetPasswordParams, otherOptions?: FetcherOptions) => Promise<import('@intlayer/backend').ResetPasswordResult>;
42
- askResetPassword: (email: import('@intlayer/backend').AskResetPasswordBody["email"], otherOptions?: FetcherOptions) => Promise<import('@intlayer/backend').AskResetPasswordResult>;
43
- checkIfUserHasPassword: (otherOptions?: FetcherOptions) => Promise<import('@intlayer/backend').CheckIfUserHasPasswordResult>;
44
- verifyEmail: ({ userId, secret }: import('@intlayer/backend').ValidEmailParams, otherOptions?: FetcherOptions) => Promise<import('@intlayer/backend').ValidEmailResult>;
45
- getVerifyEmailStatusURL: (userId: string | import('@intlayer/backend').UserAPI["_id"]) => string;
46
- changePassword: (data: import('@intlayer/backend').UpdatePasswordBody, otherOptions?: FetcherOptions) => Promise<import('@intlayer/backend').UpdatePasswordResult>;
47
- createSession: (data: import('@intlayer/backend').CreateSessionBody, otherOptions?: FetcherOptions) => Promise<import('@intlayer/backend').CreateSessionResult>;
48
- getSession: (sessionToken?: import('@intlayer/backend').GetSessionInformationQuery["session_token"], otherOptions?: FetcherOptions) => Promise<import('@intlayer/backend').GetSessionInformationResult>;
49
- getCSRFToken: (otherOptions?: FetcherOptions) => Promise<import('@intlayer/backend').SetCSRFTokenResult>;
50
- getOAuth2AccessToken: (otherOptions?: FetcherOptions) => Promise<import('@intlayer/backend').GetOAuth2TokenResult>;
41
+ resetPassword: (params: ResetPasswordParams, otherOptions?: FetcherOptions) => Promise<ResetPasswordResult>;
42
+ askResetPassword: (email: AskResetPasswordBody, otherOptions?: FetcherOptions) => Promise<AskResetPasswordResult>;
43
+ checkIfUserHasPassword: (otherOptions?: FetcherOptions) => Promise<CheckIfUserHasPasswordResult>;
44
+ verifyEmail: ({ userId, secret }: ValidEmailParams, otherOptions?: FetcherOptions) => Promise<ValidEmailResult>;
45
+ getVerifyEmailStatusURL: (userId: string | UserAPI) => string;
46
+ changePassword: (data: UpdatePasswordBody, otherOptions?: FetcherOptions) => Promise<UpdatePasswordResult>;
47
+ createSession: (data: CreateSessionBody, otherOptions?: FetcherOptions) => Promise<CreateSessionResult>;
48
+ getSession: (sessionToken?: GetSessionInformationQuery, otherOptions?: FetcherOptions) => Promise<GetSessionInformationResult>;
49
+ getCSRFToken: (otherOptions?: FetcherOptions) => Promise<SetCSRFTokenResult>;
50
+ getOAuth2AccessToken: (otherOptions?: FetcherOptions) => Promise<GetOAuth2TokenResult>;
51
51
  };
52
52
  dictionary: {
53
- getDictionaries: (filters?: import('@intlayer/backend').GetDictionariesParams, otherOptions?: FetcherOptions) => Promise<import('@intlayer/backend').GetDictionariesResult>;
54
- getDictionariesKeys: (otherOptions?: FetcherOptions) => Promise<import('@intlayer/backend').GetDictionariesKeysResult>;
55
- getDictionary: (dictionaryKey: import('@intlayer/backend').GetDictionaryParams["dictionaryKey"], version?: import('@intlayer/backend').GetDictionaryQuery["version"], otherOptions?: FetcherOptions) => Promise<import('@intlayer/backend').GetDictionaryResult>;
56
- pushDictionaries: (dictionaries: import('@intlayer/backend').PushDictionariesBody["dictionaries"], otherOptions?: FetcherOptions) => Promise<import('@intlayer/backend').PushDictionariesResult>;
57
- addDictionary: (dictionary: import('@intlayer/backend').AddDictionaryBody, otherOptions?: FetcherOptions) => Promise<import('@intlayer/backend').AddDictionaryResult>;
58
- updateDictionary: (dictionaryId: import('@intlayer/backend').UpdateDictionaryParam["dictionaryId"], dictionary: import('@intlayer/backend').UpdateDictionaryBody, otherOptions?: FetcherOptions) => Promise<import('@intlayer/backend').UpdateDictionaryResult>;
59
- deleteDictionary: (id: import('@intlayer/backend').DeleteDictionaryParam["dictionaryId"], otherOptions?: FetcherOptions) => Promise<import('@intlayer/backend').DeleteDictionaryResult>;
53
+ getDictionaries: (filters?: GetDictionariesParams, otherOptions?: FetcherOptions) => Promise<GetDictionariesResult>;
54
+ getDictionariesKeys: (otherOptions?: FetcherOptions) => Promise<GetDictionariesKeysResult>;
55
+ getDictionary: (dictionaryKey: GetDictionaryParams, version?: GetDictionaryQuery, otherOptions?: FetcherOptions) => Promise<GetDictionaryResult>;
56
+ pushDictionaries: (dictionaries: PushDictionariesBody, otherOptions?: FetcherOptions) => Promise<PushDictionariesResult>;
57
+ addDictionary: (dictionary: AddDictionaryBody, otherOptions?: FetcherOptions) => Promise<AddDictionaryResult>;
58
+ updateDictionary: (dictionaryId: UpdateDictionaryParam, dictionary: UpdateDictionaryBody, otherOptions?: FetcherOptions) => Promise<UpdateDictionaryResult>;
59
+ deleteDictionary: (id: DeleteDictionaryParam, otherOptions?: FetcherOptions) => Promise<DeleteDictionaryResult>;
60
60
  };
61
61
  stripe: {
62
- getSubscription: (body?: import('@intlayer/backend').GetCheckoutSessionBody, otherOptions?: FetcherOptions) => Promise<import('@intlayer/backend').GetCheckoutSessionResult>;
63
- cancelSubscription: (otherOptions?: FetcherOptions) => Promise<import('@intlayer/backend').GetCheckoutSessionResult>;
62
+ getSubscription: (body?: GetCheckoutSessionBody, otherOptions?: FetcherOptions) => Promise<GetCheckoutSessionResult>;
63
+ cancelSubscription: (otherOptions?: FetcherOptions) => Promise<GetCheckoutSessionResult>;
64
64
  };
65
65
  ai: {
66
- auditContentDeclaration: (body?: import('@intlayer/backend').AuditContentDeclarationBody, otherOptions?: FetcherOptions) => Promise<import('@intlayer/backend').AuditContentDeclarationResult>;
67
- auditContentDeclarationField: (body?: import('@intlayer/backend').AuditContentDeclarationFieldBody, otherOptions?: FetcherOptions) => Promise<import('@intlayer/backend').AuditContentDeclarationFieldResult>;
68
- auditContentDeclarationMetadata: (body?: import('@intlayer/backend').AuditContentDeclarationMetadataBody, otherOptions?: FetcherOptions) => Promise<import('@intlayer/backend').AuditContentDeclarationMetadataResult>;
69
- auditTag: (body?: import('@intlayer/backend').AuditTagBody, otherOptions?: FetcherOptions) => Promise<import('@intlayer/backend').AuditTagResult>;
66
+ auditContentDeclaration: (body?: AuditContentDeclarationBody, otherOptions?: FetcherOptions) => Promise<AuditContentDeclarationResult>;
67
+ auditContentDeclarationField: (body?: AuditContentDeclarationFieldBody, otherOptions?: FetcherOptions) => Promise<AuditContentDeclarationFieldResult>;
68
+ auditContentDeclarationMetadata: (body?: AuditContentDeclarationMetadataBody, otherOptions?: FetcherOptions) => Promise<AuditContentDeclarationMetadataResult>;
69
+ auditTag: (body?: AuditTagBody, otherOptions?: FetcherOptions) => Promise<AuditTagResult>;
70
+ askDocQuestion: (body?: AskDocQuestionBody, otherOptions?: FetcherOptions) => Promise<AskDocQuestionResult>;
70
71
  };
71
72
  tag: {
72
- getTags: (filters?: import('@intlayer/backend').GetTagsParams, otherOptions?: FetcherOptions) => Promise<import('@intlayer/backend').GetTagsResult>;
73
- addTag: (tag: import('@intlayer/backend').AddTagBody, otherOptions?: FetcherOptions) => Promise<import('@intlayer/backend').AddTagResult>;
74
- updateTag: (tagId: import('@intlayer/backend').UpdateTagParams["tagId"], tag: import('@intlayer/backend').UpdateTagBody, otherOptions?: FetcherOptions) => Promise<import('@intlayer/backend').UpdateTagResult>;
75
- deleteTag: (tagId: import('@intlayer/backend').DeleteTagParams["tagId"], otherOptions?: FetcherOptions) => Promise<import('@intlayer/backend').DeleteTagResult>;
73
+ getTags: (filters?: GetTagsParams, otherOptions?: FetcherOptions) => Promise<GetTagsResult>;
74
+ addTag: (tag: AddTagBody, otherOptions?: FetcherOptions) => Promise<AddTagResult>;
75
+ updateTag: (tagId: UpdateTagParams, tag: UpdateTagBody, otherOptions?: FetcherOptions) => Promise<UpdateTagResult>;
76
+ deleteTag: (tagId: DeleteTagParams, otherOptions?: FetcherOptions) => Promise<DeleteTagResult>;
76
77
  };
77
78
  };
78
79
  //# sourceMappingURL=useIntlayerAPI.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"useIntlayerAPI.d.ts","sourceRoot":"","sources":["../../src/hooks/useIntlayerAPI.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,cAAc,EAAE,MAAM,8BAA8B,CAAC;AAE9D,eAAO,MAAM,eAAe,aAAc,cAAc;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA2BvD,CAAC"}
1
+ {"version":3,"file":"useIntlayerAPI.d.ts","sourceRoot":"","sources":["../../src/hooks/useIntlayerAPI.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,cAAc,EAAE,MAAM,0BAA0B,CAAC;AAG1D,eAAO,MAAM,eAAe,aAAc,cAAc;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA2BvD,CAAC"}
@@ -1,6 +1,6 @@
1
1
  import { useMemo } from "react";
2
+ import { g as getIntlayerAPI } from "../index-DcWYZrJW.js";
2
3
  import { useAuth } from "../components/Auth/useAuth/index.mjs";
3
- import { getIntlayerAPI } from "../libs/intlayer-api/index.mjs";
4
4
  const useIntlayerAuth = (options) => {
5
5
  const { csrfToken, oAuth2AccessToken } = useAuth();
6
6
  const headers = useMemo(
@@ -1 +1 @@
1
- {"version":3,"file":"useIntlayerAPI.mjs","sources":["../../src/hooks/useIntlayerAPI.ts"],"sourcesContent":["import { useMemo } from 'react';\nimport { useAuth } from '../components/Auth/useAuth';\nimport { getIntlayerAPI } from '../libs/intlayer-api';\nimport { FetcherOptions } from '../libs/intlayer-api/fetcher';\n\nexport const useIntlayerAuth = (options?: FetcherOptions) => {\n const { csrfToken, oAuth2AccessToken } = useAuth();\n\n const headers = useMemo(\n () =>\n oAuth2AccessToken?.accessToken\n ? {\n Authorization: `Bearer ${oAuth2AccessToken.accessToken}`,\n }\n : undefined,\n [oAuth2AccessToken?.accessToken]\n );\n\n const body = useMemo(\n () => (csrfToken ? { csrf_token: csrfToken } : undefined),\n [csrfToken]\n );\n\n return useMemo(\n () =>\n getIntlayerAPI({\n headers,\n body,\n ...options,\n }),\n [body, headers]\n );\n};\n"],"names":[],"mappings":";;;AAKa,MAAA,kBAAkB,CAAC,YAA6B;AAC3D,QAAM,EAAE,WAAW,kBAAkB,IAAI,QAAQ;AAEjD,QAAM,UAAU;AAAA,IACd,MACE,mBAAmB,cACf;AAAA,MACE,eAAe,UAAU,kBAAkB,WAAW;AAAA,IAExD,IAAA;AAAA,IACN,CAAC,mBAAmB,WAAW;AAAA,EACjC;AAEA,QAAM,OAAO;AAAA,IACX,MAAO,YAAY,EAAE,YAAY,cAAc;AAAA,IAC/C,CAAC,SAAS;AAAA,EACZ;AAEO,SAAA;AAAA,IACL,MACE,eAAe;AAAA,MACb;AAAA,MACA;AAAA,MACA,GAAG;AAAA,IAAA,CACJ;AAAA,IACH,CAAC,MAAM,OAAO;AAAA,EAChB;AACF;"}
1
+ {"version":3,"file":"useIntlayerAPI.mjs","sources":["../../src/hooks/useIntlayerAPI.ts"],"sourcesContent":["import { useMemo } from 'react';\nimport { getIntlayerAPI } from '../../../api/src';\nimport { FetcherOptions } from '../../../api/src/fetcher';\nimport { useAuth } from '../components/Auth/useAuth';\n\nexport const useIntlayerAuth = (options?: FetcherOptions) => {\n const { csrfToken, oAuth2AccessToken } = useAuth();\n\n const headers = useMemo(\n () =>\n oAuth2AccessToken?.accessToken\n ? {\n Authorization: `Bearer ${oAuth2AccessToken.accessToken}`,\n }\n : undefined,\n [oAuth2AccessToken?.accessToken]\n );\n\n const body = useMemo(\n () => (csrfToken ? { csrf_token: csrfToken } : undefined),\n [csrfToken]\n );\n\n return useMemo(\n () =>\n getIntlayerAPI({\n headers,\n body,\n ...options,\n }),\n [body, headers]\n );\n};\n"],"names":[],"mappings":";;;AAKa,MAAA,kBAAkB,CAAC,YAA6B;AAC3D,QAAM,EAAE,WAAW,kBAAkB,IAAI,QAAQ;AAEjD,QAAM,UAAU;AAAA,IACd,MACE,mBAAmB,cACf;AAAA,MACE,eAAe,UAAU,kBAAkB,WAAW;AAAA,IAExD,IAAA;AAAA,IACN,CAAC,mBAAmB,WAAW;AAAA,EACjC;AAEA,QAAM,OAAO;AAAA,IACX,MAAO,YAAY,EAAE,YAAY,cAAc;AAAA,IAC/C,CAAC,SAAS;AAAA,EACZ;AAEO,SAAA;AAAA,IACL,MACE,eAAe;AAAA,MACb;AAAA,MACA;AAAA,MACA,GAAG;AAAA,IAAA,CACJ;AAAA,IACH,CAAC,MAAM,OAAO;AAAA,EAChB;AACF;"}