@intlayer/design-system 5.5.10 → 5.6.0

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 (138) hide show
  1. package/README.md +1 -1
  2. package/dist/.vite/manifest.json +86 -51
  3. package/dist/components/Auth/AuthModal/index.cjs +2 -2
  4. package/dist/components/Auth/AuthModal/index.mjs +2 -2
  5. package/dist/components/Auth/useAuth/useCSRF.d.ts +1 -1
  6. package/dist/components/Auth/useAuth/useOAuth2.d.ts +1 -1
  7. package/dist/components/Auth/useUser/index.cjs +2 -2
  8. package/dist/components/Auth/useUser/index.mjs +2 -2
  9. package/dist/components/Container/index.cjs +2 -1
  10. package/dist/components/Container/index.cjs.map +1 -1
  11. package/dist/components/Container/index.d.ts +2 -3
  12. package/dist/components/Container/index.d.ts.map +1 -1
  13. package/dist/components/Container/index.mjs +3 -2
  14. package/dist/components/Container/index.mjs.map +1 -1
  15. package/dist/components/ContentEditor/ContentEditorTextArea.cjs +2 -2
  16. package/dist/components/ContentEditor/ContentEditorTextArea.mjs +2 -2
  17. package/dist/components/{IDE/CopyButton.cjs → CopyButton/index.cjs} +6 -5
  18. package/dist/components/CopyButton/index.cjs.map +1 -0
  19. package/dist/components/{IDE/CopyButton.d.ts → CopyButton/index.d.ts} +3 -2
  20. package/dist/components/CopyButton/index.d.ts.map +1 -0
  21. package/dist/components/{IDE/CopyButton.mjs → CopyButton/index.mjs} +6 -5
  22. package/dist/components/CopyButton/index.mjs.map +1 -0
  23. package/dist/components/DictionaryFieldEditor/ContentEditorView/TextEditor.cjs +2 -2
  24. package/dist/components/DictionaryFieldEditor/ContentEditorView/TextEditor.mjs +2 -2
  25. package/dist/components/DictionaryFieldEditor/DictionaryCreationForm/DictionaryCreationForm.cjs +1 -1
  26. package/dist/components/DictionaryFieldEditor/DictionaryCreationForm/DictionaryCreationForm.mjs +1 -1
  27. package/dist/components/DictionaryFieldEditor/DictionaryDetails/DictionaryDetailsForm.cjs +2 -2
  28. package/dist/components/DictionaryFieldEditor/DictionaryDetails/DictionaryDetailsForm.mjs +2 -2
  29. package/dist/components/DictionaryFieldEditor/DictionaryFieldEditor.cjs +2 -2
  30. package/dist/components/DictionaryFieldEditor/DictionaryFieldEditor.mjs +2 -2
  31. package/dist/components/DictionaryFieldEditor/SaveForm/SaveForm.cjs +2 -2
  32. package/dist/components/DictionaryFieldEditor/SaveForm/SaveForm.mjs +2 -2
  33. package/dist/components/DictionaryFieldEditor/StructureView/StructureView.cjs +2 -2
  34. package/dist/components/DictionaryFieldEditor/StructureView/StructureView.mjs +2 -2
  35. package/dist/components/DictionaryFieldEditor/VersionSwitcherDropDown/VersionSwitcherContext.cjs +2 -2
  36. package/dist/components/DictionaryFieldEditor/VersionSwitcherDropDown/VersionSwitcherContext.mjs +2 -2
  37. package/dist/components/EditableField/EditableFieldTextArea.cjs +2 -2
  38. package/dist/components/EditableField/EditableFieldTextArea.mjs +2 -2
  39. package/dist/components/IDE/Code.cjs +3 -3
  40. package/dist/components/IDE/Code.cjs.map +1 -1
  41. package/dist/components/IDE/Code.d.ts +1 -1
  42. package/dist/components/IDE/Code.d.ts.map +1 -1
  43. package/dist/components/IDE/Code.mjs +3 -3
  44. package/dist/components/IDE/Code.mjs.map +1 -1
  45. package/dist/components/IDE/CodeContext.cjs +2 -2
  46. package/dist/components/IDE/CodeContext.mjs +2 -2
  47. package/dist/components/IDE/CopyCode.cjs +28 -0
  48. package/dist/components/IDE/CopyCode.cjs.map +1 -0
  49. package/dist/components/IDE/CopyCode.d.ts +7 -0
  50. package/dist/components/IDE/CopyCode.d.ts.map +1 -0
  51. package/dist/components/IDE/CopyCode.mjs +28 -0
  52. package/dist/components/IDE/CopyCode.mjs.map +1 -0
  53. package/dist/components/IDE/MonacoCode.cjs +2 -2
  54. package/dist/components/IDE/MonacoCode.cjs.map +1 -1
  55. package/dist/components/IDE/MonacoCode.mjs +1 -1
  56. package/dist/components/IDE/MonacoCode.mjs.map +1 -1
  57. package/dist/components/IDE/code.content.cjs +39 -0
  58. package/dist/components/IDE/code.content.cjs.map +1 -0
  59. package/dist/components/IDE/code.content.d.ts +73 -0
  60. package/dist/components/IDE/code.content.d.ts.map +1 -0
  61. package/dist/components/IDE/code.content.mjs +40 -0
  62. package/dist/components/IDE/code.content.mjs.map +1 -0
  63. package/dist/components/IDE/copyCode.content.cjs +39 -0
  64. package/dist/components/IDE/copyCode.content.cjs.map +1 -0
  65. package/dist/components/IDE/copyCode.content.d.ts +73 -0
  66. package/dist/components/IDE/copyCode.content.d.ts.map +1 -0
  67. package/dist/components/IDE/copyCode.content.mjs +40 -0
  68. package/dist/components/IDE/copyCode.content.mjs.map +1 -0
  69. package/dist/components/Link/Link.cjs.map +1 -1
  70. package/dist/components/Link/Link.d.ts.map +1 -1
  71. package/dist/components/Link/Link.mjs.map +1 -1
  72. package/dist/components/LocaleSwitcherContentDropDown/LocaleSwitcherContent.cjs +2 -2
  73. package/dist/components/LocaleSwitcherContentDropDown/LocaleSwitcherContent.mjs +2 -2
  74. package/dist/components/LocaleSwitcherContentDropDown/LocaleSwitcherContentContext.cjs +2 -2
  75. package/dist/components/LocaleSwitcherContentDropDown/LocaleSwitcherContentContext.mjs +2 -2
  76. package/dist/components/MarkDownRender/index.cjs +27 -1
  77. package/dist/components/MarkDownRender/index.cjs.map +1 -1
  78. package/dist/components/MarkDownRender/index.d.ts +2 -2
  79. package/dist/components/MarkDownRender/index.d.ts.map +1 -1
  80. package/dist/components/MarkDownRender/index.mjs +27 -1
  81. package/dist/components/MarkDownRender/index.mjs.map +1 -1
  82. package/dist/components/Modal/Modal.cjs +4 -4
  83. package/dist/components/Modal/Modal.mjs +4 -4
  84. package/dist/components/Navbar/MobileNavbar.cjs +3 -3
  85. package/dist/components/Navbar/MobileNavbar.mjs +3 -3
  86. package/dist/components/Navbar/index.cjs +5 -5
  87. package/dist/components/Navbar/index.mjs +5 -5
  88. package/dist/components/Popover/index.cjs +59 -15
  89. package/dist/components/Popover/index.cjs.map +1 -1
  90. package/dist/components/Popover/index.d.ts +32 -6
  91. package/dist/components/Popover/index.d.ts.map +1 -1
  92. package/dist/components/Popover/index.mjs +60 -16
  93. package/dist/components/Popover/index.mjs.map +1 -1
  94. package/dist/components/SocialNetworks/index.cjs +1 -1
  95. package/dist/components/SocialNetworks/index.cjs.map +1 -1
  96. package/dist/components/SocialNetworks/index.mjs +1 -1
  97. package/dist/components/SocialNetworks/index.mjs.map +1 -1
  98. package/dist/components/SwitchSelector/index.cjs +3 -3
  99. package/dist/components/SwitchSelector/index.mjs +3 -3
  100. package/dist/components/TabSelector/TabSelector.cjs +3 -3
  101. package/dist/components/TabSelector/TabSelector.mjs +3 -3
  102. package/dist/components/TextArea/AutocompleteTextArea.cjs +2 -2
  103. package/dist/components/TextArea/AutocompleteTextArea.mjs +2 -2
  104. package/dist/components/index.cjs +3 -0
  105. package/dist/components/index.cjs.map +1 -1
  106. package/dist/components/index.d.ts +1 -0
  107. package/dist/components/index.d.ts.map +1 -1
  108. package/dist/components/index.mjs +4 -1
  109. package/dist/components/index.mjs.map +1 -1
  110. package/dist/hooks/index.cjs +25 -23
  111. package/dist/hooks/index.cjs.map +1 -1
  112. package/dist/hooks/index.d.ts +8 -7
  113. package/dist/hooks/index.d.ts.map +1 -1
  114. package/dist/hooks/index.mjs +10 -8
  115. package/dist/hooks/index.mjs.map +1 -1
  116. package/dist/hooks/intlayerAPIHooks.d.ts +54 -54
  117. package/dist/hooks/intlayerAPIHooks.d.ts.map +1 -1
  118. package/dist/hooks/useAsync/useAsync.cjs +10 -11
  119. package/dist/hooks/useAsync/useAsync.cjs.map +1 -1
  120. package/dist/hooks/useAsync/useAsync.mjs +10 -11
  121. package/dist/hooks/useAsync/useAsync.mjs.map +1 -1
  122. package/dist/hooks/useIntlayerAPI.cjs +5 -4
  123. package/dist/hooks/useIntlayerAPI.cjs.map +1 -1
  124. package/dist/hooks/useIntlayerAPI.d.ts +66 -65
  125. package/dist/hooks/useIntlayerAPI.d.ts.map +1 -1
  126. package/dist/hooks/useIntlayerAPI.mjs +5 -4
  127. package/dist/hooks/useIntlayerAPI.mjs.map +1 -1
  128. package/dist/hooks/useScreenWidth.cjs +18 -0
  129. package/dist/hooks/useScreenWidth.cjs.map +1 -0
  130. package/dist/hooks/useScreenWidth.d.ts +4 -0
  131. package/dist/hooks/useScreenWidth.d.ts.map +1 -0
  132. package/dist/hooks/useScreenWidth.mjs +18 -0
  133. package/dist/hooks/useScreenWidth.mjs.map +1 -0
  134. package/dist/tailwind.css +1 -1
  135. package/package.json +18 -18
  136. package/dist/components/IDE/CopyButton.cjs.map +0 -1
  137. package/dist/components/IDE/CopyButton.d.ts.map +0 -1
  138. package/dist/components/IDE/CopyButton.mjs.map +0 -1
@@ -56,7 +56,12 @@ const useAsync = (key, asyncFunction, options) => {
56
56
  const promise = (async () => {
57
57
  setQueryState(keyWithArgs2, { isLoading: true });
58
58
  let response = null;
59
- await asyncFunction(...args2).then((result) => {
59
+ try {
60
+ const asyncResult = asyncFunction(...args2);
61
+ if (!asyncResult || typeof asyncResult.then !== "function") {
62
+ throw new Error("asyncFunction must return a Promise");
63
+ }
64
+ const result = await asyncResult;
60
65
  response = result;
61
66
  setQueryState(keyWithArgs2, {
62
67
  data: result,
@@ -82,14 +87,14 @@ const useAsync = (key, asyncFunction, options) => {
82
87
  if (storeEnabled) {
83
88
  localStorage.setItem(keyWithArgs2, JSON.stringify(result));
84
89
  }
85
- }).catch((error2) => {
90
+ } catch (error2) {
86
91
  console.error({ error: error2 });
87
92
  const msg = error2 instanceof Error ? error2.message : String(error2);
88
93
  makeQueryInError(keyWithArgs2, msg);
89
- onError?.(error2.message);
90
- }).finally(() => {
94
+ onError?.(msg);
95
+ } finally {
91
96
  pendingPromises.delete(keyWithArgs2);
92
- });
97
+ }
93
98
  return response;
94
99
  })();
95
100
  pendingPromises.set(keyWithArgs2, promise);
@@ -161,7 +166,6 @@ const useAsync = (key, asyncFunction, options) => {
161
166
  if (!isEnabled || !enabled) return;
162
167
  if (!isRetryEnabled) return;
163
168
  if (isRetryLimitReached) return;
164
- if (!(cacheEnabled || storeEnabled)) return;
165
169
  if (isLoading) return;
166
170
  if (isSuccess) return;
167
171
  const timeout = setTimeout(() => {
@@ -174,8 +178,6 @@ const useAsync = (key, asyncFunction, options) => {
174
178
  retryLimit,
175
179
  enabled,
176
180
  retryTime,
177
- cacheEnabled,
178
- storeEnabled,
179
181
  isSuccess,
180
182
  isLoading,
181
183
  fetch
@@ -185,7 +187,6 @@ const useAsync = (key, asyncFunction, options) => {
185
187
  if (!isEnabled || !enabled) return;
186
188
  if (isLoading) return;
187
189
  if (!isSuccess || !fetchedDateTime) return;
188
- if (!(cacheEnabled || storeEnabled)) return;
189
190
  const timeout = setTimeout(() => {
190
191
  fetch(...storedArgsRef.current);
191
192
  }, revalidateTime);
@@ -193,8 +194,6 @@ const useAsync = (key, asyncFunction, options) => {
193
194
  }, [
194
195
  revalidationEnabled,
195
196
  revalidateTime,
196
- cacheEnabled,
197
- storeEnabled,
198
197
  isSuccess,
199
198
  fetchedDateTime,
200
199
  isLoading,
@@ -1 +1 @@
1
- {"version":3,"file":"useAsync.cjs","sources":["../../../src/hooks/useAsync/useAsync.ts"],"sourcesContent":["'use client';\n\nimport { useEffect, 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 abort: () => 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 abort?: () => void; // Abort the request\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 const controllerRef = useRef<AbortController | null>(null);\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 = (async (...args) => {\n const keyWithArgs = getKeyWithArgs(key, args);\n\n /**\n * ABORT CONTROLLER\n *\n * cancel an unnecessary request.\n * For example, if a user navigates away from a page or triggers a new request that makes the previous one obsolete, you can abort the previous fetch\n */\n if (controllerRef.current) {\n // Abort the previous request\n controllerRef.current.abort();\n }\n\n // Create a new AbortController\n const controller = new AbortController();\n controllerRef.current = controller;\n\n /**\n * PENDING PROMISES\n *\n * This logic ensures that if two parts of your application trigger the same request simultaneously,\n * only one network call is made, and both receive the same result.\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 console.error({ 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\n /**\n * REVALIDATE FUNCTION\n *\n * Wrap core function to handle revalidation\n * Handle arguments caching\n *\n */\n const revalidate: T = (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\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 = (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 /**\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 = (data: Awaited<ReturnType<T> | null>) => {\n setQueryState(keyWithArgs, {\n data,\n });\n };\n\n const abort = () => {\n if (controllerRef.current) {\n controllerRef.current.abort();\n }\n };\n\n // Memoization to prevent unnecessary re-renders\n const memoResult = {\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 abort,\n };\n\n useEffect(\n () => () => {\n // Clean up the controller on unmount\n if (controllerRef.current) {\n controllerRef.current.abort();\n }\n },\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":["useAsyncState","useRef","args","keyWithArgs","error","useEffect","data"],"mappings":";;;;;AAMA,MAAM,sCAAsB,IAAI;AAsChC,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;AAwCzD,MAAM,WAAW,CAItB,KACA,eACA,YACyB;AAEnB,QAAA,aAAa,SAAS,cAAc;AACpC,QAAA,YAAY,SAAS,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cesContent":["'use client';\n\nimport { useEffect, 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 abort: () => 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 abort?: () => void; // Abort the request\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 const controllerRef = useRef<AbortController | null>(null);\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 = (async (...args) => {\n const keyWithArgs = getKeyWithArgs(key, args);\n\n /**\n * ABORT CONTROLLER\n *\n * cancel an unnecessary request.\n * For example, if a user navigates away from a page or triggers a new request that makes the previous one obsolete, you can abort the previous fetch\n */\n if (controllerRef.current) {\n // Abort the previous request\n controllerRef.current.abort();\n }\n\n // Create a new AbortController\n const controller = new AbortController();\n controllerRef.current = controller;\n\n /**\n * PENDING PROMISES\n *\n * This logic ensures that if two parts of your application trigger the same request simultaneously,\n * only one network call is made, and both receive the same result.\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 try {\n // Ensure asyncFunction returns a Promise\n const asyncResult = asyncFunction(...args);\n\n // Check if the result is a Promise-like object\n if (!asyncResult || typeof asyncResult.then !== 'function') {\n throw new Error('asyncFunction must return a Promise');\n }\n\n const result = await asyncResult;\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 } catch (error) {\n console.error({ error });\n const msg = error instanceof Error ? error.message : String(error);\n\n makeQueryInError(keyWithArgs, msg);\n onError?.(msg);\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\n /**\n * REVALIDATE FUNCTION\n *\n * Wrap core function to handle revalidation\n * Handle arguments caching\n *\n */\n const revalidate: T = (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\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 = (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 /**\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 (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 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\n const timeout = setTimeout(() => {\n fetch(...storedArgsRef.current);\n }, revalidateTime);\n\n return () => clearTimeout(timeout);\n }, [\n revalidationEnabled,\n revalidateTime,\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 = (data: Awaited<ReturnType<T> | null>) => {\n setQueryState(keyWithArgs, {\n data,\n });\n };\n\n const abort = () => {\n if (controllerRef.current) {\n controllerRef.current.abort();\n }\n };\n\n // Memoization to prevent unnecessary re-renders\n const memoResult = {\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 abort,\n };\n\n useEffect(\n () => () => {\n // Clean up the controller on unmount\n if (controllerRef.current) {\n controllerRef.current.abort();\n }\n },\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":["useAsyncState","useRef","args","keyWithArgs","error","useEffect","data"],"mappings":";;;;;AAMA,MAAM,sCAAsB,IAAI;AAsChC,MAAM,wBAAwB;AAC9B,MAAM,wBAAw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AAY,CAAC;AAAA,IACb;AAAA,IACA,eAAe,aAAa,CAAC,aAAa,CAAC;AAAA;AAAA,IAC3C,gBAAgB,aAAa;AAAA;AAAA,IAC7B,CAAC,GAAG,GAAG;AAAA;AAAA,IACP;AAAA,IACA,SAAS;AAAA,IACT;AAAA,EACF;AAEAD,eAAA;AAAA,IACE,MAAM,MAAM;AAEV,UAAI,cAAc,SAAS;AACzB,sBAAc,QAAQ,MAAM;AAAA,MAAA;AAAA,IAEhC;AAAA,IACA,CAAA;AAAA,EACF;AAGO,SAAA;AACT;;"}
@@ -54,7 +54,12 @@ const useAsync = (key, asyncFunction, options) => {
54
54
  const promise = (async () => {
55
55
  setQueryState(keyWithArgs2, { isLoading: true });
56
56
  let response = null;
57
- await asyncFunction(...args2).then((result) => {
57
+ try {
58
+ const asyncResult = asyncFunction(...args2);
59
+ if (!asyncResult || typeof asyncResult.then !== "function") {
60
+ throw new Error("asyncFunction must return a Promise");
61
+ }
62
+ const result = await asyncResult;
58
63
  response = result;
59
64
  setQueryState(keyWithArgs2, {
60
65
  data: result,
@@ -80,14 +85,14 @@ const useAsync = (key, asyncFunction, options) => {
80
85
  if (storeEnabled) {
81
86
  localStorage.setItem(keyWithArgs2, JSON.stringify(result));
82
87
  }
83
- }).catch((error2) => {
88
+ } catch (error2) {
84
89
  console.error({ error: error2 });
85
90
  const msg = error2 instanceof Error ? error2.message : String(error2);
86
91
  makeQueryInError(keyWithArgs2, msg);
87
- onError?.(error2.message);
88
- }).finally(() => {
92
+ onError?.(msg);
93
+ } finally {
89
94
  pendingPromises.delete(keyWithArgs2);
90
- });
95
+ }
91
96
  return response;
92
97
  })();
93
98
  pendingPromises.set(keyWithArgs2, promise);
@@ -159,7 +164,6 @@ const useAsync = (key, asyncFunction, options) => {
159
164
  if (!isEnabled || !enabled) return;
160
165
  if (!isRetryEnabled) return;
161
166
  if (isRetryLimitReached) return;
162
- if (!(cacheEnabled || storeEnabled)) return;
163
167
  if (isLoading) return;
164
168
  if (isSuccess) return;
165
169
  const timeout = setTimeout(() => {
@@ -172,8 +176,6 @@ const useAsync = (key, asyncFunction, options) => {
172
176
  retryLimit,
173
177
  enabled,
174
178
  retryTime,
175
- cacheEnabled,
176
- storeEnabled,
177
179
  isSuccess,
178
180
  isLoading,
179
181
  fetch
@@ -183,7 +185,6 @@ const useAsync = (key, asyncFunction, options) => {
183
185
  if (!isEnabled || !enabled) return;
184
186
  if (isLoading) return;
185
187
  if (!isSuccess || !fetchedDateTime) return;
186
- if (!(cacheEnabled || storeEnabled)) return;
187
188
  const timeout = setTimeout(() => {
188
189
  fetch(...storedArgsRef.current);
189
190
  }, revalidateTime);
@@ -191,8 +192,6 @@ const useAsync = (key, asyncFunction, options) => {
191
192
  }, [
192
193
  revalidationEnabled,
193
194
  revalidateTime,
194
- cacheEnabled,
195
- storeEnabled,
196
195
  isSuccess,
197
196
  fetchedDateTime,
198
197
  isLoading,
@@ -1 +1 @@
1
- {"version":3,"file":"useAsync.mjs","sources":["../../../src/hooks/useAsync/useAsync.ts"],"sourcesContent":["'use client';\n\nimport { useEffect, 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 abort: () => 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 abort?: () => void; // Abort the request\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 const controllerRef = useRef<AbortController | null>(null);\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 = (async (...args) => {\n const keyWithArgs = getKeyWithArgs(key, args);\n\n /**\n * ABORT CONTROLLER\n *\n * cancel an unnecessary request.\n * For example, if a user navigates away from a page or triggers a new request that makes the previous one obsolete, you can abort the previous fetch\n */\n if (controllerRef.current) {\n // Abort the previous request\n controllerRef.current.abort();\n }\n\n // Create a new AbortController\n const controller = new AbortController();\n controllerRef.current = controller;\n\n /**\n * PENDING PROMISES\n *\n * This logic ensures that if two parts of your application trigger the same request simultaneously,\n * only one network call is made, and both receive the same result.\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 console.error({ 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\n /**\n * REVALIDATE FUNCTION\n *\n * Wrap core function to handle revalidation\n * Handle arguments caching\n *\n */\n const revalidate: T = (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\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 = (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 /**\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 = (data: Awaited<ReturnType<T> | null>) => {\n setQueryState(keyWithArgs, {\n data,\n });\n };\n\n const abort = () => {\n if (controllerRef.current) {\n controllerRef.current.abort();\n }\n };\n\n // Memoization to prevent unnecessary re-renders\n const memoResult = {\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 abort,\n };\n\n useEffect(\n () => () => {\n // Clean up the controller on unmount\n if (controllerRef.current) {\n controllerRef.current.abort();\n }\n },\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":";;;AAMA,MAAM,sCAAsB,IAAI;AAsChC,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;AAwCzD,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,SAAS;AACjC,QAAA,eAAe,SAAS,SAAS;AACjC,QAAA,UAAU,SAAS,UA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QAAI,UAAW;AACX,QAAA,CAAC,aAAa,CAAC,gBAAiB;AAChC,QAAA,EAAE,gBAAgB,cAAe;AAE/B,UAAA,UAAU,WAAW,MAAM;AACzB,YAAA,GAAG,cAAc,OAAO;AAAA,OAC7B,cAAc;AAEV,WAAA,MAAM,aAAa,OAAO;AAAA,EAAA,GAChC;AAAA,IACD;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EAAA,CACD;AAGK,QAAA,cAAc,CAACC,UAAwC;AAC3D,kBAAc,aAAa;AAAA,MACzB,MAAAA;AAAAA,IAAA,CACD;AAAA,EACH;AAEA,QAAM,QAAQ,MAAM;AAClB,QAAI,cAAc,SAAS;AACzB,oBAAc,QAAQ,MAAM;AAAA,IAAA;AAAA,EAEhC;AAGA,QAAM,aAAa;AAAA,IACjB;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA,YAAY,CAAC;AAAA,IACb;AAAA,IACA,eAAe,aAAa,CAAC,aAAa,CAAC;AAAA;AAAA,IAC3C,gBAAgB,aAAa;AAAA;AAAA,IAC7B,CAAC,GAAG,GAAG;AAAA;AAAA,IACP;AAAA,IACA,SAAS;AAAA,IACT;AAAA,EACF;AAEA;AAAA,IACE,MAAM,MAAM;AAEV,UAAI,cAAc,SAAS;AACzB,sBAAc,QAAQ,MAAM;AAAA,MAAA;AAAA,IAEhC;AAAA,IACA,CAAA;AAAA,EACF;AAGO,SAAA;AACT;"}
1
+ {"version":3,"file":"useAsync.mjs","sources":["../../../src/hooks/useAsync/useAsync.ts"],"sourcesContent":["'use client';\n\nimport { useEffect, 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 abort: () => 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 abort?: () => void; // Abort the request\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 const controllerRef = useRef<AbortController | null>(null);\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 = (async (...args) => {\n const keyWithArgs = getKeyWithArgs(key, args);\n\n /**\n * ABORT CONTROLLER\n *\n * cancel an unnecessary request.\n * For example, if a user navigates away from a page or triggers a new request that makes the previous one obsolete, you can abort the previous fetch\n */\n if (controllerRef.current) {\n // Abort the previous request\n controllerRef.current.abort();\n }\n\n // Create a new AbortController\n const controller = new AbortController();\n controllerRef.current = controller;\n\n /**\n * PENDING PROMISES\n *\n * This logic ensures that if two parts of your application trigger the same request simultaneously,\n * only one network call is made, and both receive the same result.\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 try {\n // Ensure asyncFunction returns a Promise\n const asyncResult = asyncFunction(...args);\n\n // Check if the result is a Promise-like object\n if (!asyncResult || typeof asyncResult.then !== 'function') {\n throw new Error('asyncFunction must return a Promise');\n }\n\n const result = await asyncResult;\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 } catch (error) {\n console.error({ error });\n const msg = error instanceof Error ? error.message : String(error);\n\n makeQueryInError(keyWithArgs, msg);\n onError?.(msg);\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\n /**\n * REVALIDATE FUNCTION\n *\n * Wrap core function to handle revalidation\n * Handle arguments caching\n *\n */\n const revalidate: T = (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\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 = (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 /**\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 (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 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\n const timeout = setTimeout(() => {\n fetch(...storedArgsRef.current);\n }, revalidateTime);\n\n return () => clearTimeout(timeout);\n }, [\n revalidationEnabled,\n revalidateTime,\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 = (data: Awaited<ReturnType<T> | null>) => {\n setQueryState(keyWithArgs, {\n data,\n });\n };\n\n const abort = () => {\n if (controllerRef.current) {\n controllerRef.current.abort();\n }\n };\n\n // Memoization to prevent unnecessary re-renders\n const memoResult = {\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 abort,\n };\n\n useEffect(\n () => () => {\n // Clean up the controller on unmount\n if (controllerRef.current) {\n controllerRef.current.abort();\n }\n },\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":";;;AAMA,MAAM,sCAAsB,IAAI;AAsChC,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,I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AAQ,MAAM;AAAA,MAAA;AAAA,IAEhC;AAAA,IACA,CAAA;AAAA,EACF;AAGO,SAAA;AACT;"}
@@ -6,13 +6,14 @@ const components_Auth_useAuth_index = require("../components/Auth/useAuth/index.
6
6
  const useIntlayerAuth = (props) => {
7
7
  const configuration = editorReact.useConfiguration();
8
8
  const { csrfToken, oAuth2AccessToken } = components_Auth_useAuth_index.useAuth();
9
- const headers = oAuth2AccessToken?.accessToken ? {
10
- Authorization: `Bearer ${oAuth2AccessToken.accessToken}`
11
- } : void 0;
12
9
  const body = csrfToken ? { csrf_token: csrfToken } : void 0;
13
10
  return api.getIntlayerAPI(
14
11
  {
15
- headers,
12
+ ...oAuth2AccessToken && {
13
+ headers: {
14
+ Authorization: `Bearer ${oAuth2AccessToken}`
15
+ }
16
+ },
16
17
  body,
17
18
  ...props?.options ?? {}
18
19
  },
@@ -1 +1 @@
1
- {"version":3,"file":"useIntlayerAPI.cjs","sources":["../../src/hooks/useIntlayerAPI.ts"],"sourcesContent":["import { getIntlayerAPI, type FetcherOptions } from '@intlayer/api';\nimport { type IntlayerConfig } from '@intlayer/config/client';\nimport { useConfiguration } from '@intlayer/editor-react';\nimport { useAuth } from '../components/Auth/useAuth';\n\ntype UseIntlayerAuthProps = {\n options?: FetcherOptions;\n intlayerConfiguration?: IntlayerConfig;\n};\n\nexport const useIntlayerAuth = (props?: UseIntlayerAuthProps) => {\n const configuration = useConfiguration();\n const { csrfToken, oAuth2AccessToken } = useAuth();\n\n const headers = oAuth2AccessToken?.accessToken\n ? {\n Authorization: `Bearer ${oAuth2AccessToken.accessToken}`,\n }\n : undefined;\n\n const body = csrfToken ? { csrf_token: csrfToken } : undefined;\n\n return getIntlayerAPI(\n {\n headers,\n body,\n ...(props?.options ?? {}),\n },\n props?.intlayerConfiguration ?? configuration\n );\n};\n"],"names":["useConfiguration","useAuth","getIntlayerAPI"],"mappings":";;;;;AAUa,MAAA,kBAAkB,CAAC,UAAiC;AAC/D,QAAM,gBAAgBA,YAAAA,iBAAiB;AACvC,QAAM,EAAE,WAAW,kBAAkB,IAAIC,sCAAQ;AAE3C,QAAA,UAAU,mBAAmB,cAC/B;AAAA,IACE,eAAe,UAAU,kBAAkB,WAAW;AAAA,EAAA,IAExD;AAEJ,QAAM,OAAO,YAAY,EAAE,YAAY,UAAc,IAAA;AAE9C,SAAAC,IAAA;AAAA,IACL;AAAA,MACE;AAAA,MACA;AAAA,MACA,GAAI,OAAO,WAAW,CAAA;AAAA,IACxB;AAAA,IACA,OAAO,yBAAyB;AAAA,EAClC;AACF;;"}
1
+ {"version":3,"file":"useIntlayerAPI.cjs","sources":["../../src/hooks/useIntlayerAPI.ts"],"sourcesContent":["import { getIntlayerAPI, type FetcherOptions } from '@intlayer/api';\nimport { type IntlayerConfig } from '@intlayer/config/client';\nimport { useConfiguration } from '@intlayer/editor-react';\nimport { useAuth } from '../components/Auth/useAuth';\n\ntype UseIntlayerAuthProps = {\n options?: FetcherOptions;\n intlayerConfiguration?: IntlayerConfig;\n};\n\nexport const useIntlayerAuth = (props?: UseIntlayerAuthProps) => {\n const configuration = useConfiguration();\n const { csrfToken, oAuth2AccessToken } = useAuth();\n\n const body = csrfToken ? { csrf_token: csrfToken } : undefined;\n\n return getIntlayerAPI(\n {\n ...(oAuth2AccessToken && {\n headers: {\n Authorization: `Bearer ${oAuth2AccessToken}`,\n },\n }),\n body,\n ...(props?.options ?? {}),\n },\n props?.intlayerConfiguration ?? configuration\n );\n};\n"],"names":["useConfiguration","useAuth","getIntlayerAPI"],"mappings":";;;;;AAUa,MAAA,kBAAkB,CAAC,UAAiC;AAC/D,QAAM,gBAAgBA,YAAAA,iBAAiB;AACvC,QAAM,EAAE,WAAW,kBAAkB,IAAIC,sCAAQ;AAEjD,QAAM,OAAO,YAAY,EAAE,YAAY,UAAc,IAAA;AAE9C,SAAAC,IAAA;AAAA,IACL;AAAA,MACE,GAAI,qBAAqB;AAAA,QACvB,SAAS;AAAA,UACP,eAAe,UAAU,iBAAiB;AAAA,QAAA;AAAA,MAE9C;AAAA,MACA;AAAA,MACA,GAAI,OAAO,WAAW,CAAA;AAAA,IACxB;AAAA,IACA,OAAO,yBAAyB;AAAA,EAClC;AACF;;"}
@@ -6,86 +6,87 @@ type UseIntlayerAuthProps = {
6
6
  };
7
7
  export declare const useIntlayerAuth: (props?: UseIntlayerAuthProps) => {
8
8
  organization: {
9
- getOrganizations: (filters?: GetOrganizationsParams, otherOptions?: FetcherOptions) => Promise<GetOrganizationsResult>;
10
- getOrganization: (organizationId: GetOrganizationParam, otherOptions?: FetcherOptions) => Promise<GetOrganizationResult>;
11
- addOrganization: (organization: AddOrganizationBody, otherOptions?: FetcherOptions) => Promise<AddOrganizationResult>;
12
- addOrganizationMember: (body: AddOrganizationMemberBody, otherOptions?: FetcherOptions) => Promise<AddOrganizationMemberResult>;
13
- updateOrganization: (organization: UpdateOrganizationBody, otherOptions?: FetcherOptions) => Promise<UpdateOrganizationResult>;
14
- updateOrganizationMembers: (body: UpdateOrganizationMembersBody, otherOptions?: FetcherOptions) => Promise<UpdateOrganizationMembersResult>;
15
- deleteOrganization: (otherOptions?: FetcherOptions) => Promise<DeleteOrganizationResult>;
16
- selectOrganization: (organizationId: SelectOrganizationParam, otherOptions?: FetcherOptions) => Promise<SelectOrganizationResult>;
17
- unselectOrganization: (otherOptions?: FetcherOptions) => Promise<UnselectOrganizationResult>;
9
+ getOrganizations: (filters?: import('@intlayer/backend').GetOrganizationsParams, otherOptions?: FetcherOptions) => Promise<import('@intlayer/backend').GetOrganizationsResult>;
10
+ getOrganization: (organizationId: import('@intlayer/backend').GetOrganizationParam["organizationId"], otherOptions?: FetcherOptions) => Promise<import('@intlayer/backend').GetOrganizationResult>;
11
+ addOrganization: (organization: import('@intlayer/backend').AddOrganizationBody, otherOptions?: FetcherOptions) => Promise<import('@intlayer/backend').AddOrganizationResult>;
12
+ addOrganizationMember: (body: import('@intlayer/backend').AddOrganizationMemberBody, otherOptions?: FetcherOptions) => Promise<import('@intlayer/backend').AddOrganizationMemberResult>;
13
+ updateOrganization: (organization: import('@intlayer/backend').UpdateOrganizationBody, otherOptions?: FetcherOptions) => Promise<import('@intlayer/backend').UpdateOrganizationResult>;
14
+ updateOrganizationMembers: (body: import('@intlayer/backend').UpdateOrganizationMembersBody, otherOptions?: FetcherOptions) => Promise<import('@intlayer/backend').UpdateOrganizationMembersResult>;
15
+ deleteOrganization: (otherOptions?: FetcherOptions) => Promise<import('@intlayer/backend').DeleteOrganizationResult>;
16
+ selectOrganization: (organizationId: import('@intlayer/backend').SelectOrganizationParam["organizationId"], otherOptions?: FetcherOptions) => Promise<import('@intlayer/backend').SelectOrganizationResult>;
17
+ unselectOrganization: (otherOptions?: FetcherOptions) => Promise<import('@intlayer/backend').UnselectOrganizationResult>;
18
18
  };
19
19
  project: {
20
- getProjects: (filters?: GetProjectsParams, otherOptions?: FetcherOptions) => Promise<GetProjectsResult>;
21
- addProject: (project: AddProjectBody, otherOptions?: FetcherOptions) => Promise<AddProjectResult>;
22
- updateProject: (project: UpdateProjectBody, otherOptions?: FetcherOptions) => Promise<UpdateProjectResult>;
23
- updateProjectMembers: (body: UpdateProjectMembersBody, otherOptions?: FetcherOptions) => Promise<UpdateProjectMembersResult>;
24
- pushProjectConfiguration: (projectConfiguration: PushProjectConfigurationBody, otherOptions?: FetcherOptions) => Promise<PushProjectConfigurationResult>;
25
- deleteProject: (otherOptions?: FetcherOptions) => Promise<DeleteProjectResult>;
26
- selectProject: (projectId: SelectProjectParam, otherOptions?: FetcherOptions) => Promise<SelectProjectResult>;
27
- unselectProject: (otherOptions?: FetcherOptions) => Promise<UnselectProjectResult>;
28
- addNewAccessKey: (accessKey: AddNewAccessKeyBody, otherOptions?: FetcherOptions) => Promise<AddNewAccessKeyResponse>;
29
- deleteAccessKey: (clientId: DeleteAccessKeyBody, otherOptions?: FetcherOptions) => Promise<DeleteAccessKeyResponse>;
30
- refreshAccessKey: (clientId: RefreshAccessKeyBody, otherOptions?: FetcherOptions) => Promise<RefreshAccessKeyResponse>;
20
+ getProjects: (filters?: import('@intlayer/backend').GetProjectsParams, otherOptions?: FetcherOptions) => Promise<import('@intlayer/backend').GetProjectsResult>;
21
+ addProject: (project: import('@intlayer/backend').AddProjectBody, otherOptions?: FetcherOptions) => Promise<import('@intlayer/backend').AddProjectResult>;
22
+ updateProject: (project: import('@intlayer/backend').UpdateProjectBody, otherOptions?: FetcherOptions) => Promise<import('@intlayer/backend').UpdateProjectResult>;
23
+ updateProjectMembers: (body: import('@intlayer/backend').UpdateProjectMembersBody, otherOptions?: FetcherOptions) => Promise<import('@intlayer/backend').UpdateProjectMembersResult>;
24
+ pushProjectConfiguration: (projectConfiguration: import('@intlayer/backend').PushProjectConfigurationBody, otherOptions?: FetcherOptions) => Promise<import('@intlayer/backend').PushProjectConfigurationResult>;
25
+ deleteProject: (otherOptions?: FetcherOptions) => Promise<import('@intlayer/backend').DeleteProjectResult>;
26
+ selectProject: (projectId: import('@intlayer/backend').SelectProjectParam["projectId"], otherOptions?: FetcherOptions) => Promise<import('@intlayer/backend').SelectProjectResult>;
27
+ unselectProject: (otherOptions?: FetcherOptions) => Promise<import('@intlayer/backend').UnselectProjectResult>;
28
+ addNewAccessKey: (accessKey: import('@intlayer/backend').AddNewAccessKeyBody, otherOptions?: FetcherOptions) => Promise<import('@intlayer/backend').AddNewAccessKeyResponse>;
29
+ deleteAccessKey: (clientId: import('@intlayer/backend').DeleteAccessKeyBody["clientId"], otherOptions?: FetcherOptions) => Promise<import('@intlayer/backend').DeleteAccessKeyResponse>;
30
+ refreshAccessKey: (clientId: import('@intlayer/backend').RefreshAccessKeyBody["clientId"], otherOptions?: FetcherOptions) => Promise<import('@intlayer/backend').RefreshAccessKeyResponse>;
31
31
  };
32
32
  user: {
33
- createUser: (user: CreateUserBody, otherOptions?: FetcherOptions) => Promise<CreateUserResult>;
34
- getUsers: (filters?: GetUsersParams, otherOptions?: FetcherOptions) => Promise<GetUsersResult>;
35
- getUserById: (userId: GetUserByIdParams, otherOptions?: FetcherOptions) => Promise<GetUserByIdResult>;
36
- getUserByAccount: (providerAccountId: GetUserByAccountParams, provider: GetUserByAccountParams, otherOptions?: FetcherOptions) => Promise<GetUserByAccountResult>;
37
- getUserByEmail: (email: GetUserByEmailParams, otherOptions?: FetcherOptions) => Promise<GetUserByEmailResult>;
38
- updateUser: (user: UpdateUserBody, otherOptions?: FetcherOptions) => Promise<UpdateUserResult>;
39
- deleteUser: (userId: string, otherOptions?: FetcherOptions) => Promise<UpdateUserResult>;
33
+ createUser: (user: import('@intlayer/backend').CreateUserBody, otherOptions?: FetcherOptions) => Promise<import('@intlayer/backend').CreateUserResult>;
34
+ getUsers: (filters?: import('@intlayer/backend').GetUsersParams, otherOptions?: FetcherOptions) => Promise<import('@intlayer/backend').GetUsersResult>;
35
+ getUserById: (userId: import('@intlayer/backend').GetUserByIdParams["userId"], otherOptions?: FetcherOptions) => Promise<import('@intlayer/backend').GetUserByIdResult>;
36
+ getUserByAccount: (providerAccountId: import('@intlayer/backend').GetUserByAccountParams["providerAccountId"], provider: import('@intlayer/backend').GetUserByAccountParams["provider"], otherOptions?: FetcherOptions) => Promise<import('@intlayer/backend').GetUserByAccountResult>;
37
+ getUserByEmail: (email: import('@intlayer/backend').GetUserByEmailParams["email"], otherOptions?: FetcherOptions) => Promise<import('@intlayer/backend').GetUserByEmailResult>;
38
+ updateUser: (user: import('@intlayer/backend').UpdateUserBody, otherOptions?: FetcherOptions) => Promise<import('@intlayer/backend').UpdateUserResult>;
39
+ deleteUser: (userId: string, otherOptions?: FetcherOptions) => Promise<import('@intlayer/backend').UpdateUserResult>;
40
40
  };
41
41
  auth: {
42
- login: (user: LoginBody, otherOptions?: FetcherOptions) => Promise<LoginResult>;
43
- getLoginWithGitHubURL: (params: GithubLoginQueryParams) => string;
44
- getLoginWithGoogleURL: (params: GoogleLoginQueryParams) => string;
45
- register: (user: RegisterBody, query?: RegisterQuery, otherOptions?: FetcherOptions) => Promise<RegisterResult>;
42
+ login: (user: import('@intlayer/backend').LoginBody, otherOptions?: FetcherOptions) => Promise<import('@intlayer/backend').LoginResult>;
43
+ getLoginWithGitHubURL: (params: import('@intlayer/backend').GithubLoginQueryParams) => string;
44
+ getLoginWithGoogleURL: (params: import('@intlayer/backend').GoogleLoginQueryParams) => string;
45
+ register: (user: import('@intlayer/backend').RegisterBody, query?: import('@intlayer/backend').RegisterQuery, otherOptions?: FetcherOptions) => Promise<import('@intlayer/backend').RegisterResult>;
46
46
  logout: (otherOptions?: FetcherOptions) => Promise<void>;
47
- defineNewPassword: (data: DefinePasswordBody, otherOptions?: FetcherOptions) => Promise<DefinePasswordResult>;
48
- askResetPassword: (email: AskResetPasswordBody, otherOptions?: FetcherOptions) => Promise<AskResetPasswordResult>;
49
- checkIfUserHasPassword: (otherOptions?: FetcherOptions) => Promise<CheckIfUserHasPasswordResult>;
50
- verifyEmail: ({ userId, secret }: ValidEmailParams, otherOptions?: FetcherOptions) => Promise<ValidEmailResult>;
51
- getVerifyEmailStatusURL: (userId: string | UserAPI) => string;
52
- changePassword: (data: UpdatePasswordBody, otherOptions?: FetcherOptions) => Promise<UpdatePasswordResult>;
53
- createSession: (data: CreateSessionBody, otherOptions?: FetcherOptions) => Promise<CreateSessionResult>;
54
- getSession: (sessionToken?: GetSessionInformationQuery, otherOptions?: FetcherOptions) => Promise<GetSessionInformationResult>;
55
- getCSRFToken: (otherOptions?: FetcherOptions) => Promise<SetCSRFTokenResult>;
56
- getOAuth2AccessToken: (otherOptions?: FetcherOptions) => Promise<GetOAuth2TokenResult>;
47
+ defineNewPassword: (data: import('@intlayer/backend').DefinePasswordBody, otherOptions?: FetcherOptions) => Promise<import('@intlayer/backend').DefinePasswordResult>;
48
+ askResetPassword: (email: import('@intlayer/backend').AskResetPasswordBody["email"], otherOptions?: FetcherOptions) => Promise<import('@intlayer/backend').AskResetPasswordResult>;
49
+ checkIfUserHasPassword: (otherOptions?: FetcherOptions) => Promise<import('@intlayer/backend').CheckIfUserHasPasswordResult>;
50
+ verifyEmail: ({ userId, secret }: import('@intlayer/backend').ValidEmailParams, otherOptions?: FetcherOptions) => Promise<import('@intlayer/backend').ValidEmailResult>;
51
+ getVerifyEmailStatusURL: (userId: string | import('@intlayer/backend').UserAPI["_id"]) => string;
52
+ changePassword: (data: import('@intlayer/backend').UpdatePasswordBody, otherOptions?: FetcherOptions) => Promise<import('@intlayer/backend').UpdatePasswordResult>;
53
+ createSession: (data: import('@intlayer/backend').CreateSessionBody, otherOptions?: FetcherOptions) => Promise<import('@intlayer/backend').CreateSessionResult>;
54
+ getSession: (sessionToken?: import('@intlayer/backend').GetSessionInformationQuery["session_token"], otherOptions?: FetcherOptions) => Promise<import('@intlayer/backend').GetSessionInformationResult>;
55
+ getCSRFToken: (otherOptions?: FetcherOptions) => Promise<import('@intlayer/backend').SetCSRFTokenResult>;
56
+ getOAuth2AccessToken: (otherOptions?: FetcherOptions) => Promise<import('@intlayer/backend').GetOAuth2TokenResult>;
57
57
  };
58
58
  dictionary: {
59
- getDictionaries: (filters?: GetDictionariesParams, otherOptions?: FetcherOptions) => Promise<GetDictionariesResult>;
60
- getDictionariesKeys: (otherOptions?: FetcherOptions) => Promise<GetDictionariesKeysResult>;
61
- getDictionary: (dictionaryKey: GetDictionaryParams, version?: GetDictionaryQuery, otherOptions?: FetcherOptions) => Promise<GetDictionaryResult>;
62
- pushDictionaries: (dictionaries: PushDictionariesBody, otherOptions?: FetcherOptions) => Promise<PushDictionariesResult>;
63
- addDictionary: (body: AddDictionaryBody, otherOptions?: FetcherOptions) => Promise<AddDictionaryResult>;
64
- updateDictionary: (dictionaryId: UpdateDictionaryParam, dictionary: UpdateDictionaryBody, otherOptions?: FetcherOptions) => Promise<UpdateDictionaryResult>;
65
- deleteDictionary: (id: DeleteDictionaryParam, otherOptions?: FetcherOptions) => Promise<DeleteDictionaryResult>;
59
+ getDictionaries: (filters?: import('@intlayer/backend').GetDictionariesParams, otherOptions?: FetcherOptions) => Promise<import('@intlayer/backend').GetDictionariesResult>;
60
+ getDictionariesKeys: (otherOptions?: FetcherOptions) => Promise<import('@intlayer/backend').GetDictionariesKeysResult>;
61
+ getDictionary: (dictionaryKey: import('@intlayer/backend').GetDictionaryParams["dictionaryKey"], version?: import('@intlayer/backend').GetDictionaryQuery["version"], otherOptions?: FetcherOptions) => Promise<import('@intlayer/backend').GetDictionaryResult>;
62
+ pushDictionaries: (dictionaries: import('@intlayer/backend').PushDictionariesBody["dictionaries"], otherOptions?: FetcherOptions) => Promise<import('@intlayer/backend').PushDictionariesResult>;
63
+ addDictionary: (body: import('@intlayer/backend').AddDictionaryBody, otherOptions?: FetcherOptions) => Promise<import('@intlayer/backend').AddDictionaryResult>;
64
+ updateDictionary: (dictionaryId: import('@intlayer/backend').UpdateDictionaryParam["dictionaryId"], dictionary: import('@intlayer/backend').UpdateDictionaryBody, otherOptions?: FetcherOptions) => Promise<import('@intlayer/backend').UpdateDictionaryResult>;
65
+ deleteDictionary: (id: import('@intlayer/backend').DeleteDictionaryParam["dictionaryId"], otherOptions?: FetcherOptions) => Promise<import('@intlayer/backend').DeleteDictionaryResult>;
66
66
  };
67
67
  stripe: {
68
- getPricing: (body?: GetPricingBody, otherOptions?: FetcherOptions) => Promise<GetPricingResult>;
69
- getSubscription: (body?: GetCheckoutSessionBody, otherOptions?: FetcherOptions) => Promise<GetCheckoutSessionResult>;
70
- cancelSubscription: (otherOptions?: FetcherOptions) => Promise<GetCheckoutSessionResult>;
68
+ getPricing: (body?: import('@intlayer/backend').GetPricingBody, otherOptions?: FetcherOptions) => Promise<import('@intlayer/backend').GetPricingResult>;
69
+ getSubscription: (body?: import('@intlayer/backend').GetCheckoutSessionBody, otherOptions?: FetcherOptions) => Promise<import('@intlayer/backend').GetCheckoutSessionResult>;
70
+ cancelSubscription: (otherOptions?: FetcherOptions) => Promise<import('@intlayer/backend').GetCheckoutSessionResult>;
71
71
  };
72
72
  ai: {
73
- translateJSON: (body?: TranslateJSONBody, otherOptions?: FetcherOptions) => Promise<TranslateJSONResult>;
74
- auditContentDeclaration: (body?: AuditContentDeclarationBody, otherOptions?: FetcherOptions) => Promise<AuditContentDeclarationResult>;
75
- auditContentDeclarationField: (body?: AuditContentDeclarationFieldBody, otherOptions?: FetcherOptions) => Promise<AuditContentDeclarationFieldResult>;
76
- auditContentDeclarationMetadata: (body?: AuditContentDeclarationMetadataBody, otherOptions?: FetcherOptions) => Promise<AuditContentDeclarationMetadataResult>;
77
- auditTag: (body?: AuditTagBody, otherOptions?: FetcherOptions) => Promise<AuditTagResult>;
73
+ customQuery: (body?: import('@intlayer/backend').CustomQueryBody, otherOptions?: FetcherOptions) => Promise<import('@intlayer/backend').CustomQueryResult>;
74
+ translateJSON: (body?: import('@intlayer/backend').TranslateJSONBody, otherOptions?: FetcherOptions) => Promise<import('@intlayer/backend').TranslateJSONResult>;
75
+ auditContentDeclaration: (body?: import('@intlayer/backend').AuditContentDeclarationBody, otherOptions?: FetcherOptions) => Promise<import('@intlayer/backend').AuditContentDeclarationResult>;
76
+ auditContentDeclarationField: (body?: import('@intlayer/backend').AuditContentDeclarationFieldBody, otherOptions?: FetcherOptions) => Promise<import('@intlayer/backend').AuditContentDeclarationFieldResult>;
77
+ auditContentDeclarationMetadata: (body?: import('@intlayer/backend').AuditContentDeclarationMetadataBody, otherOptions?: FetcherOptions) => Promise<import('@intlayer/backend').AuditContentDeclarationMetadataResult>;
78
+ auditTag: (body?: import('@intlayer/backend').AuditTagBody, otherOptions?: FetcherOptions) => Promise<import('@intlayer/backend').AuditTagResult>;
78
79
  askDocQuestion: (body?: import('@intlayer/api').AskDocQuestionBody, otherOptions?: FetcherOptions) => Promise<void>;
79
- autocomplete: (body?: AutocompleteBody, otherOptions?: FetcherOptions) => Promise<AutocompleteResponse>;
80
+ autocomplete: (body?: import('@intlayer/backend').AutocompleteBody, otherOptions?: FetcherOptions) => Promise<import('@intlayer/backend').AutocompleteResponse>;
80
81
  };
81
82
  tag: {
82
- getTags: (filters?: GetTagsParams, otherOptions?: FetcherOptions) => Promise<GetTagsResult>;
83
- addTag: (tag: AddTagBody, otherOptions?: FetcherOptions) => Promise<AddTagResult>;
84
- updateTag: (tagId: UpdateTagParams, tag: UpdateTagBody, otherOptions?: FetcherOptions) => Promise<UpdateTagResult>;
85
- deleteTag: (tagId: DeleteTagParams, otherOptions?: FetcherOptions) => Promise<DeleteTagResult>;
83
+ getTags: (filters?: import('@intlayer/backend').GetTagsParams, otherOptions?: FetcherOptions) => Promise<import('@intlayer/backend').GetTagsResult>;
84
+ addTag: (tag: import('@intlayer/backend').AddTagBody, otherOptions?: FetcherOptions) => Promise<import('@intlayer/backend').AddTagResult>;
85
+ updateTag: (tagId: import('@intlayer/backend').UpdateTagParams["tagId"], tag: import('@intlayer/backend').UpdateTagBody, otherOptions?: FetcherOptions) => Promise<import('@intlayer/backend').UpdateTagResult>;
86
+ deleteTag: (tagId: import('@intlayer/backend').DeleteTagParams["tagId"], otherOptions?: FetcherOptions) => Promise<import('@intlayer/backend').DeleteTagResult>;
86
87
  };
87
88
  search: {
88
- searchDoc: (params?: SearchDocUtilParams, otherOptions?: FetcherOptions) => Promise<SearchDocUtilResult>;
89
+ searchDoc: (params?: import('@intlayer/backend').SearchDocUtilParams, otherOptions?: FetcherOptions) => Promise<import('@intlayer/backend').SearchDocUtilResult>;
89
90
  };
90
91
  editor: {
91
92
  getDictionaries: (otherOptions?: FetcherOptions) => Promise<Record<string, any>>;
@@ -93,9 +94,9 @@ export declare const useIntlayerAuth: (props?: UseIntlayerAuthProps) => {
93
94
  writeDictionary: (dictionary: import('intlayer-editor').WriteContentDeclarationBody, otherOptions?: FetcherOptions) => Promise<import('intlayer-editor').WriteContentDeclarationResult>;
94
95
  };
95
96
  newsletter: {
96
- subscribeToNewsletter: (body: NewsletterSubscriptionBody, otherOptions?: FetcherOptions) => Promise<NewsletterSubscriptionResult>;
97
- unsubscribeFromNewsletter: (body: NewsletterUnsubscriptionBody, otherOptions?: FetcherOptions) => Promise<NewsletterSubscriptionResult>;
98
- getNewsletterStatus: (otherOptions?: FetcherOptions) => Promise<NewsletterSubscriptionResult>;
97
+ subscribeToNewsletter: (body: import('@intlayer/backend').NewsletterSubscriptionBody, otherOptions?: FetcherOptions) => Promise<import('@intlayer/backend').NewsletterSubscriptionResult>;
98
+ unsubscribeFromNewsletter: (body: import('@intlayer/backend').NewsletterUnsubscriptionBody, otherOptions?: FetcherOptions) => Promise<import('@intlayer/backend').NewsletterSubscriptionResult>;
99
+ getNewsletterStatus: (otherOptions?: FetcherOptions) => Promise<import('@intlayer/backend').NewsletterSubscriptionResult>;
99
100
  };
100
101
  };
101
102
  export {};
@@ -1 +1 @@
1
- {"version":3,"file":"useIntlayerAPI.d.ts","sourceRoot":"","sources":["../../src/hooks/useIntlayerAPI.ts"],"names":[],"mappings":"AAAA,OAAO,EAAkB,KAAK,cAAc,EAAE,MAAM,eAAe,CAAC;AACpE,OAAO,EAAE,KAAK,cAAc,EAAE,MAAM,yBAAyB,CAAC;AAI9D,KAAK,oBAAoB,GAAG;IAC1B,OAAO,CAAC,EAAE,cAAc,CAAC;IACzB,qBAAqB,CAAC,EAAE,cAAc,CAAC;CACxC,CAAC;AAEF,eAAO,MAAM,eAAe,GAAI,QAAQ,oBAAoB;;kCAJ1D,CAAD,EAAC,sBAAuB,cACd,CAAC,6BACZ,sBAEiB;0CAA6C,oBAC/C,cAAc,CAAC,6BACf,qBAAqB;wCAEb,mBAAoB,cAEnC,CAAP,6BAA8B,qBAAoB;sCAIjD,yBAAuB,cAAc,CAAC,6BAEtC,2BACE;2CAGY,sBACV,cACO,CAAC,6BAA6B,wBAGlC;0CAA4C,6BAA8B,cAAc,CAAC,6BAA6B,+BAA+B;yCAA4C,CAAC,6BAA6B,wBAAwB;6CAA+C,uBAAwB,cAAc,CAAC,6BAA6B,wBAAwB;2CAA8C,CAAC,6BAA6B,0BAA0B;;;6BAAsD,CAAC,EAAC,iBAAkB,cAAc,CAAC,6BAA6B,iBAAiB;8BAAgC,cAAe,cAAc,CAAC,6BAA6B,gBAAgB;i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AAqQ,CAAC;8GAAgM,CAAC;;;yBAAgI,CAAC,0DAA0D,CAAC;8BAA0G,CAAC,kEAAkE,CAAC;yCAA6H,CAAC;;;0BAA+H,CAAC,2DAA2D,CAAC;4BAAyG,CAAC,6DAA6D,CAAC;sCAAqH,CAAC,uEAAuE,CAAC;2CAAoI,CAAC,4EAA4E,CAAC;8CAA4I,CAAC,+EAA+E,CAAC;uBAAwH,CAAC,wDAAwD,CAAC;6BAAuG,CAAC,0DAAiD,CAAC;2BAA+D,CAAC,4DAA4D,CAAC;;;yBAA2H,CAAC,yDAAyD,CAAC;0EAAmJ,CAAC;6IAAqN,CAAC;6FAAwK,CAAC;;;0BAA0H,CAAC,+DAA+D,CAAC;;;sCAA0I,CAAC;uCAA0F,CAAC;yGAAyL,CAAC;;;0GAA0N,CAAC;gHAAwM,CAAC;0CAAkI,CAAC;;CAD9yW,CAAC"}
@@ -4,13 +4,14 @@ import { useAuth } from "../components/Auth/useAuth/index.mjs";
4
4
  const useIntlayerAuth = (props) => {
5
5
  const configuration = useConfiguration();
6
6
  const { csrfToken, oAuth2AccessToken } = useAuth();
7
- const headers = oAuth2AccessToken?.accessToken ? {
8
- Authorization: `Bearer ${oAuth2AccessToken.accessToken}`
9
- } : void 0;
10
7
  const body = csrfToken ? { csrf_token: csrfToken } : void 0;
11
8
  return getIntlayerAPI(
12
9
  {
13
- headers,
10
+ ...oAuth2AccessToken && {
11
+ headers: {
12
+ Authorization: `Bearer ${oAuth2AccessToken}`
13
+ }
14
+ },
14
15
  body,
15
16
  ...props?.options ?? {}
16
17
  },
@@ -1 +1 @@
1
- {"version":3,"file":"useIntlayerAPI.mjs","sources":["../../src/hooks/useIntlayerAPI.ts"],"sourcesContent":["import { getIntlayerAPI, type FetcherOptions } from '@intlayer/api';\nimport { type IntlayerConfig } from '@intlayer/config/client';\nimport { useConfiguration } from '@intlayer/editor-react';\nimport { useAuth } from '../components/Auth/useAuth';\n\ntype UseIntlayerAuthProps = {\n options?: FetcherOptions;\n intlayerConfiguration?: IntlayerConfig;\n};\n\nexport const useIntlayerAuth = (props?: UseIntlayerAuthProps) => {\n const configuration = useConfiguration();\n const { csrfToken, oAuth2AccessToken } = useAuth();\n\n const headers = oAuth2AccessToken?.accessToken\n ? {\n Authorization: `Bearer ${oAuth2AccessToken.accessToken}`,\n }\n : undefined;\n\n const body = csrfToken ? { csrf_token: csrfToken } : undefined;\n\n return getIntlayerAPI(\n {\n headers,\n body,\n ...(props?.options ?? {}),\n },\n props?.intlayerConfiguration ?? configuration\n );\n};\n"],"names":[],"mappings":";;;AAUa,MAAA,kBAAkB,CAAC,UAAiC;AAC/D,QAAM,gBAAgB,iBAAiB;AACvC,QAAM,EAAE,WAAW,kBAAkB,IAAI,QAAQ;AAE3C,QAAA,UAAU,mBAAmB,cAC/B;AAAA,IACE,eAAe,UAAU,kBAAkB,WAAW;AAAA,EAAA,IAExD;AAEJ,QAAM,OAAO,YAAY,EAAE,YAAY,UAAc,IAAA;AAE9C,SAAA;AAAA,IACL;AAAA,MACE;AAAA,MACA;AAAA,MACA,GAAI,OAAO,WAAW,CAAA;AAAA,IACxB;AAAA,IACA,OAAO,yBAAyB;AAAA,EAClC;AACF;"}
1
+ {"version":3,"file":"useIntlayerAPI.mjs","sources":["../../src/hooks/useIntlayerAPI.ts"],"sourcesContent":["import { getIntlayerAPI, type FetcherOptions } from '@intlayer/api';\nimport { type IntlayerConfig } from '@intlayer/config/client';\nimport { useConfiguration } from '@intlayer/editor-react';\nimport { useAuth } from '../components/Auth/useAuth';\n\ntype UseIntlayerAuthProps = {\n options?: FetcherOptions;\n intlayerConfiguration?: IntlayerConfig;\n};\n\nexport const useIntlayerAuth = (props?: UseIntlayerAuthProps) => {\n const configuration = useConfiguration();\n const { csrfToken, oAuth2AccessToken } = useAuth();\n\n const body = csrfToken ? { csrf_token: csrfToken } : undefined;\n\n return getIntlayerAPI(\n {\n ...(oAuth2AccessToken && {\n headers: {\n Authorization: `Bearer ${oAuth2AccessToken}`,\n },\n }),\n body,\n ...(props?.options ?? {}),\n },\n props?.intlayerConfiguration ?? configuration\n );\n};\n"],"names":[],"mappings":";;;AAUa,MAAA,kBAAkB,CAAC,UAAiC;AAC/D,QAAM,gBAAgB,iBAAiB;AACvC,QAAM,EAAE,WAAW,kBAAkB,IAAI,QAAQ;AAEjD,QAAM,OAAO,YAAY,EAAE,YAAY,UAAc,IAAA;AAE9C,SAAA;AAAA,IACL;AAAA,MACE,GAAI,qBAAqB;AAAA,QACvB,SAAS;AAAA,UACP,eAAe,UAAU,iBAAiB;AAAA,QAAA;AAAA,MAE9C;AAAA,MACA;AAAA,MACA,GAAI,OAAO,WAAW,CAAA;AAAA,IACxB;AAAA,IACA,OAAO,yBAAyB;AAAA,EAClC;AACF;"}