@intlayer/design-system 5.7.6 → 5.7.7
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.
- package/README.md +3 -0
- package/dist/Form-CriPBaZk.js.map +1 -1
- package/dist/Form-DJrUK3mm.cjs.map +1 -1
- package/dist/better-auth.8zoxzg-F-BEBqzpjz.cjs.map +1 -1
- package/dist/better-auth.8zoxzg-F-D8e0X4ys.js.map +1 -1
- package/dist/components/Accordion/Accordion.cjs.map +1 -1
- package/dist/components/Accordion/Accordion.mjs.map +1 -1
- package/dist/components/Avatar/index.cjs.map +1 -1
- package/dist/components/Avatar/index.mjs.map +1 -1
- package/dist/components/Badge/index.cjs.map +1 -1
- package/dist/components/Badge/index.mjs.map +1 -1
- package/dist/components/Breadcrumb/breadcrumb.content.cjs.map +1 -1
- package/dist/components/Breadcrumb/breadcrumb.content.mjs.map +1 -1
- package/dist/components/Breadcrumb/index.cjs.map +1 -1
- package/dist/components/Breadcrumb/index.mjs.map +1 -1
- package/dist/components/Button/Button.cjs.map +1 -1
- package/dist/components/Button/Button.mjs.map +1 -1
- package/dist/components/ClickOutsideDiv/index.cjs.map +1 -1
- package/dist/components/ClickOutsideDiv/index.mjs.map +1 -1
- package/dist/components/Command/index.cjs.map +1 -1
- package/dist/components/Command/index.mjs.map +1 -1
- package/dist/components/Container/index.cjs.map +1 -1
- package/dist/components/Container/index.mjs.map +1 -1
- package/dist/components/ContentEditor/ContentEditor.cjs.map +1 -1
- package/dist/components/ContentEditor/ContentEditor.mjs.map +1 -1
- package/dist/components/ContentEditor/ContentEditorInput.cjs.map +1 -1
- package/dist/components/ContentEditor/ContentEditorInput.mjs.map +1 -1
- package/dist/components/ContentEditor/ContentEditorTextArea.cjs.map +1 -1
- package/dist/components/ContentEditor/ContentEditorTextArea.mjs.map +1 -1
- package/dist/components/ContentSelector/ContentSelector.cjs.map +1 -1
- package/dist/components/CopyButton/index.cjs.map +1 -1
- package/dist/components/CopyButton/index.mjs.map +1 -1
- package/dist/components/CopyToClipboard/index.cjs.map +1 -1
- package/dist/components/CopyToClipboard/index.mjs.map +1 -1
- package/dist/components/DictionaryEditor/DictionaryEditor.cjs.map +1 -1
- package/dist/components/DictionaryEditor/DictionaryEditor.mjs.map +1 -1
- package/dist/components/DictionaryEditor/ItemLayout.cjs.map +1 -1
- package/dist/components/DictionaryEditor/ItemLayout.mjs.map +1 -1
- package/dist/components/DictionaryEditor/NodeWrapper/FileWrapper.cjs.map +1 -1
- package/dist/components/DictionaryEditor/NodeWrapper/FileWrapper.mjs.map +1 -1
- package/dist/components/DictionaryEditor/NodeWrapper/StringWrapper.cjs.map +1 -1
- package/dist/components/DictionaryEditor/NodeWrapper/StringWrapper.mjs.map +1 -1
- package/dist/components/DictionaryFieldEditor/ContentEditor.cjs.map +1 -1
- package/dist/components/DictionaryFieldEditor/ContentEditor.mjs.map +1 -1
- package/dist/components/DictionaryFieldEditor/ContentEditorView/TextEditor.cjs.map +1 -1
- package/dist/components/DictionaryFieldEditor/ContentEditorView/TextEditor.mjs.map +1 -1
- package/dist/components/DictionaryFieldEditor/DictionaryCreationForm/DictionaryCreationForm.cjs.map +1 -1
- package/dist/components/DictionaryFieldEditor/DictionaryCreationForm/DictionaryCreationForm.mjs.map +1 -1
- package/dist/components/DictionaryFieldEditor/DictionaryCreationForm/dictionaryCreationForm.content.cjs.map +1 -1
- package/dist/components/DictionaryFieldEditor/DictionaryCreationForm/dictionaryCreationForm.content.mjs.map +1 -1
- package/dist/components/DictionaryFieldEditor/DictionaryCreationForm/useDictionaryFormSchema.cjs.map +1 -1
- package/dist/components/DictionaryFieldEditor/DictionaryCreationForm/useDictionaryFormSchema.content.cjs.map +1 -1
- package/dist/components/DictionaryFieldEditor/DictionaryCreationForm/useDictionaryFormSchema.content.mjs.map +1 -1
- package/dist/components/DictionaryFieldEditor/DictionaryCreationForm/useDictionaryFormSchema.mjs.map +1 -1
- package/dist/components/DictionaryFieldEditor/DictionaryDetails/DictionaryDetailsForm.cjs.map +1 -1
- package/dist/components/DictionaryFieldEditor/DictionaryDetails/DictionaryDetailsForm.mjs.map +1 -1
- package/dist/components/DictionaryFieldEditor/DictionaryDetails/dictionaryDetails.content.cjs.map +1 -1
- package/dist/components/DictionaryFieldEditor/DictionaryDetails/dictionaryDetails.content.mjs.map +1 -1
- package/dist/components/DictionaryFieldEditor/DictionaryDetails/useDictionaryDetailsSchema.cjs.map +1 -1
- package/dist/components/DictionaryFieldEditor/DictionaryDetails/useDictionaryDetailsSchema.content.cjs.map +1 -1
- package/dist/components/DictionaryFieldEditor/DictionaryDetails/useDictionaryDetailsSchema.content.mjs.map +1 -1
- package/dist/components/DictionaryFieldEditor/DictionaryDetails/useDictionaryDetailsSchema.mjs.map +1 -1
- package/dist/components/DictionaryFieldEditor/DictionaryFieldEditor.cjs.map +1 -1
- package/dist/components/DictionaryFieldEditor/DictionaryFieldEditor.mjs.map +1 -1
- package/dist/components/DictionaryFieldEditor/EnumKeyInput.cjs.map +1 -1
- package/dist/components/DictionaryFieldEditor/EnumKeyInput.mjs.map +1 -1
- package/dist/components/DictionaryFieldEditor/JSONEditor.cjs.map +1 -1
- package/dist/components/DictionaryFieldEditor/JSONEditor.mjs.map +1 -1
- package/dist/components/DictionaryFieldEditor/KeyPathBreadcrumb.cjs.map +1 -1
- package/dist/components/DictionaryFieldEditor/KeyPathBreadcrumb.mjs.map +1 -1
- package/dist/components/DictionaryFieldEditor/NavigationView/NavigationViewNode.cjs.map +1 -1
- package/dist/components/DictionaryFieldEditor/NavigationView/NavigationViewNode.mjs.map +1 -1
- package/dist/components/DictionaryFieldEditor/NavigationView/navigationViewNode.content.cjs.map +1 -1
- package/dist/components/DictionaryFieldEditor/NavigationView/navigationViewNode.content.mjs.map +1 -1
- package/dist/components/DictionaryFieldEditor/NodeTypeSelector.cjs.map +1 -1
- package/dist/components/DictionaryFieldEditor/NodeTypeSelector.mjs.map +1 -1
- package/dist/components/DictionaryFieldEditor/SaveForm/SaveForm.cjs.map +1 -1
- package/dist/components/DictionaryFieldEditor/SaveForm/SaveForm.mjs.map +1 -1
- package/dist/components/DictionaryFieldEditor/SaveForm/saveForm.content.cjs.map +1 -1
- package/dist/components/DictionaryFieldEditor/SaveForm/saveForm.content.mjs.map +1 -1
- package/dist/components/DictionaryFieldEditor/StructureEditor.cjs.map +1 -1
- package/dist/components/DictionaryFieldEditor/StructureEditor.mjs.map +1 -1
- package/dist/components/DictionaryFieldEditor/StructureView/StructureView.cjs.map +1 -1
- package/dist/components/DictionaryFieldEditor/StructureView/StructureView.mjs.map +1 -1
- package/dist/components/DictionaryFieldEditor/StructureView/structureView.content.cjs.map +1 -1
- package/dist/components/DictionaryFieldEditor/StructureView/structureView.content.mjs.map +1 -1
- package/dist/components/DictionaryFieldEditor/VersionSwitcherDropDown/VersionSwitcher.cjs.map +1 -1
- package/dist/components/DictionaryFieldEditor/VersionSwitcherDropDown/VersionSwitcher.mjs.map +1 -1
- package/dist/components/DictionaryFieldEditor/VersionSwitcherDropDown/VersionSwitcherContext.cjs.map +1 -1
- package/dist/components/DictionaryFieldEditor/VersionSwitcherDropDown/VersionSwitcherContext.mjs.map +1 -1
- package/dist/components/DictionaryFieldEditor/VersionSwitcherDropDown/versionSwitcherDropDown.content.cjs.map +1 -1
- package/dist/components/DictionaryFieldEditor/VersionSwitcherDropDown/versionSwitcherDropDown.content.mjs.map +1 -1
- package/dist/components/DictionaryFieldEditor/dictionaryFieldEditor.content.cjs.map +1 -1
- package/dist/components/DictionaryFieldEditor/dictionaryFieldEditor.content.mjs.map +1 -1
- package/dist/components/DictionaryFieldEditor/getIsEditableSection.cjs.map +1 -1
- package/dist/components/DictionaryFieldEditor/getIsEditableSection.mjs.map +1 -1
- package/dist/components/DictionaryFieldEditor/nodeTypeSelector.content.cjs.map +1 -1
- package/dist/components/DictionaryFieldEditor/nodeTypeSelector.content.mjs.map +1 -1
- package/dist/components/DropDown/index.cjs.map +1 -1
- package/dist/components/DropDown/index.mjs.map +1 -1
- package/dist/components/EditableField/EditableFieldInput.cjs.map +1 -1
- package/dist/components/EditableField/EditableFieldInput.mjs.map +1 -1
- package/dist/components/EditableField/EditableFieldLayout.cjs.map +1 -1
- package/dist/components/EditableField/EditableFieldLayout.mjs.map +1 -1
- package/dist/components/EditableField/EditableFieldTextArea.cjs.map +1 -1
- package/dist/components/EditableField/EditableFieldTextArea.mjs.map +1 -1
- package/dist/components/Flags/Flag.cjs.map +1 -1
- package/dist/components/Flags/Flag.mjs.map +1 -1
- package/dist/components/Footer/index.cjs.map +1 -1
- package/dist/components/Footer/index.mjs.map +1 -1
- package/dist/components/Form/FormBase.cjs.map +1 -1
- package/dist/components/Form/FormBase.mjs.map +1 -1
- package/dist/components/Form/FormControl.cjs.map +1 -1
- package/dist/components/Form/FormControl.mjs.map +1 -1
- package/dist/components/Form/FormDescription.cjs.map +1 -1
- package/dist/components/Form/FormDescription.mjs.map +1 -1
- package/dist/components/Form/FormField.cjs.map +1 -1
- package/dist/components/Form/FormField.mjs.map +1 -1
- package/dist/components/Form/FormItem.cjs.map +1 -1
- package/dist/components/Form/FormItem.mjs.map +1 -1
- package/dist/components/Form/FormLabel.cjs.map +1 -1
- package/dist/components/Form/FormLabel.mjs.map +1 -1
- package/dist/components/Form/FormMessage.cjs.map +1 -1
- package/dist/components/Form/FormMessage.mjs.map +1 -1
- package/dist/components/Form/elements/FormElementWrapper.cjs.map +1 -1
- package/dist/components/Form/elements/FormElementWrapper.mjs.map +1 -1
- package/dist/components/Form/layout/FormLabelLayout.cjs.map +1 -1
- package/dist/components/Form/layout/FormLabelLayout.mjs.map +1 -1
- package/dist/components/Form/layout/RequiredStar.cjs.map +1 -1
- package/dist/components/Form/layout/RequiredStar.mjs.map +1 -1
- package/dist/components/Headers/SectionScroller.cjs.map +1 -1
- package/dist/components/Headers/SectionScroller.mjs.map +1 -1
- package/dist/components/Headers/index.cjs.map +1 -1
- package/dist/components/Headers/index.mjs.map +1 -1
- package/dist/components/HeightResizer/index.cjs.map +1 -1
- package/dist/components/HeightResizer/index.mjs.map +1 -1
- package/dist/components/IDE/Code.cjs.map +1 -1
- package/dist/components/IDE/Code.mjs.map +1 -1
- package/dist/components/IDE/CodeBlockClient.cjs.map +1 -1
- package/dist/components/IDE/CodeBlockClient.mjs.map +1 -1
- package/dist/components/IDE/CodeBlockServer.cjs.map +1 -1
- package/dist/components/IDE/CodeBlockServer.mjs.map +1 -1
- package/dist/components/IDE/CodeConditionalRenderer.cjs.map +1 -1
- package/dist/components/IDE/CodeConditionalRenderer.mjs.map +1 -1
- package/dist/components/IDE/CodeContext.cjs.map +1 -1
- package/dist/components/IDE/CodeContext.mjs.map +1 -1
- package/dist/components/IDE/CodeFormatSelector.cjs.map +1 -1
- package/dist/components/IDE/CodeFormatSelector.mjs.map +1 -1
- package/dist/components/IDE/ContentDeclarationFormatSelector.cjs.map +1 -1
- package/dist/components/IDE/ContentDeclarationFormatSelector.mjs.map +1 -1
- package/dist/components/IDE/CopyButton.content.cjs.map +1 -1
- package/dist/components/IDE/CopyButton.content.mjs.map +1 -1
- package/dist/components/IDE/CopyCode.cjs.map +1 -1
- package/dist/components/IDE/CopyCode.mjs.map +1 -1
- package/dist/components/IDE/FileList.cjs.map +1 -1
- package/dist/components/IDE/FileList.mjs.map +1 -1
- package/dist/components/IDE/FileTree.cjs.map +1 -1
- package/dist/components/IDE/FileTree.mjs.map +1 -1
- package/dist/components/IDE/IDE.cjs.map +1 -1
- package/dist/components/IDE/IDE.mjs.map +1 -1
- package/dist/components/IDE/MarkDownRender.cjs.map +1 -1
- package/dist/components/IDE/MarkDownRender.mjs.map +1 -1
- package/dist/components/IDE/MonacoCode.cjs.map +1 -1
- package/dist/components/IDE/MonacoCode.mjs.map +1 -1
- package/dist/components/IDE/PackageManagerSelector.cjs.map +1 -1
- package/dist/components/IDE/PackageManagerSelector.mjs.map +1 -1
- package/dist/components/IDE/code.content.cjs.map +1 -1
- package/dist/components/IDE/code.content.mjs.map +1 -1
- package/dist/components/IDE/copyCode.content.cjs.map +1 -1
- package/dist/components/IDE/copyCode.content.mjs.map +1 -1
- package/dist/components/IDE/createFileTree.cjs.map +1 -1
- package/dist/components/IDE/createFileTree.mjs.map +1 -1
- package/dist/components/InformationTag/index.cjs.map +1 -1
- package/dist/components/InformationTag/index.mjs.map +1 -1
- package/dist/components/Input/Checkbox.cjs.map +1 -1
- package/dist/components/Input/Checkbox.mjs.map +1 -1
- package/dist/components/Input/Input.cjs.map +1 -1
- package/dist/components/Input/Input.mjs.map +1 -1
- package/dist/components/Input/InputPassword.cjs.map +1 -1
- package/dist/components/Input/InputPassword.mjs.map +1 -1
- package/dist/components/KeyboardScreenAdapter/index.cjs.map +1 -1
- package/dist/components/KeyboardScreenAdapter/index.mjs.map +1 -1
- package/dist/components/Label/index.cjs.map +1 -1
- package/dist/components/Link/Link.cjs.map +1 -1
- package/dist/components/Link/Link.mjs.map +1 -1
- package/dist/components/Loader/index.cjs.map +1 -1
- package/dist/components/Loader/index.content.cjs.map +1 -1
- package/dist/components/Loader/index.content.mjs.map +1 -1
- package/dist/components/Loader/index.mjs.map +1 -1
- package/dist/components/Loader/spinner.cjs.map +1 -1
- package/dist/components/Loader/spinner.mjs.map +1 -1
- package/dist/components/LocaleSwitcherContentDropDown/LocaleSwitcherContent.cjs.map +1 -1
- package/dist/components/LocaleSwitcherContentDropDown/LocaleSwitcherContent.mjs.map +1 -1
- package/dist/components/LocaleSwitcherContentDropDown/LocaleSwitcherContentContext.cjs.map +1 -1
- package/dist/components/LocaleSwitcherContentDropDown/LocaleSwitcherContentContext.mjs.map +1 -1
- package/dist/components/LocaleSwitcherContentDropDown/localeSwitcher.content.cjs.map +1 -1
- package/dist/components/LocaleSwitcherContentDropDown/localeSwitcher.content.mjs.map +1 -1
- package/dist/components/LocaleSwitcherDropDown/LocaleSwitcher.cjs.map +1 -1
- package/dist/components/LocaleSwitcherDropDown/LocaleSwitcher.mjs.map +1 -1
- package/dist/components/LocaleSwitcherDropDown/localeSwitcher.content.cjs.map +1 -1
- package/dist/components/LocaleSwitcherDropDown/localeSwitcher.content.mjs.map +1 -1
- package/dist/components/Logo/Logo.cjs.map +1 -1
- package/dist/components/Logo/Logo.mjs.map +1 -1
- package/dist/components/Logo/LogoTextOnly.cjs.map +1 -1
- package/dist/components/Logo/LogoTextOnly.mjs.map +1 -1
- package/dist/components/Logo/LogoWithText.cjs.map +1 -1
- package/dist/components/Logo/LogoWithText.mjs.map +1 -1
- package/dist/components/Logo/LogoWithTextBelow.cjs.map +1 -1
- package/dist/components/Logo/LogoWithTextBelow.mjs.map +1 -1
- package/dist/components/MarkDownRender/index.cjs.map +1 -1
- package/dist/components/MarkDownRender/index.mjs.map +1 -1
- package/dist/components/MaxHeightSmoother/index.cjs.map +1 -1
- package/dist/components/MaxHeightSmoother/index.mjs.map +1 -1
- package/dist/components/MaxWidthSmoother/index.cjs.map +1 -1
- package/dist/components/MaxWidthSmoother/index.mjs.map +1 -1
- package/dist/components/Modal/Modal.cjs.map +1 -1
- package/dist/components/Modal/Modal.mjs.map +1 -1
- package/dist/components/Navbar/Burger.cjs.map +1 -1
- package/dist/components/Navbar/Burger.mjs.map +1 -1
- package/dist/components/Navbar/DesktopNavbar.cjs.map +1 -1
- package/dist/components/Navbar/DesktopNavbar.mjs.map +1 -1
- package/dist/components/Navbar/MobileNavbar.cjs.map +1 -1
- package/dist/components/Navbar/MobileNavbar.mjs.map +1 -1
- package/dist/components/Navbar/index.cjs.map +1 -1
- package/dist/components/Navbar/index.mjs.map +1 -1
- package/dist/components/Navbar/useNavigation.cjs.map +1 -1
- package/dist/components/Navbar/useNavigation.mjs.map +1 -1
- package/dist/components/Pattern/DotPattern.cjs.map +1 -1
- package/dist/components/Pattern/DotPattern.mjs.map +1 -1
- package/dist/components/Pattern/GridPattern.cjs.map +1 -1
- package/dist/components/Pattern/GridPattern.mjs.map +1 -1
- package/dist/components/Pattern/SpotLight.cjs.map +1 -1
- package/dist/components/Pattern/SpotLight.mjs.map +1 -1
- package/dist/components/Popover/index.cjs.map +1 -1
- package/dist/components/Popover/index.mjs.map +1 -1
- package/dist/components/PressableSpan/PressableSpan.cjs.map +1 -1
- package/dist/components/PressableSpan/PressableSpan.mjs.map +1 -1
- package/dist/components/RightDrawer/RightDrawer.cjs.map +1 -1
- package/dist/components/RightDrawer/RightDrawer.mjs.map +1 -1
- package/dist/components/RightDrawer/isElementAtTopAndNotCovered.cjs.map +1 -1
- package/dist/components/RightDrawer/isElementAtTopAndNotCovered.mjs.map +1 -1
- package/dist/components/RightDrawer/useRightDrawerStore.cjs.map +1 -1
- package/dist/components/RightDrawer/useRightDrawerStore.mjs.map +1 -1
- package/dist/components/Select/Multiselect.cjs.map +1 -1
- package/dist/components/Select/Multiselect.mjs.map +1 -1
- package/dist/components/Select/Select.cjs.map +1 -1
- package/dist/components/Select/Select.mjs.map +1 -1
- package/dist/components/SocialNetworks/DiscordLogo.cjs.map +1 -1
- package/dist/components/SocialNetworks/DiscordLogo.mjs.map +1 -1
- package/dist/components/SocialNetworks/FacebookLogo.cjs.map +1 -1
- package/dist/components/SocialNetworks/FacebookLogo.mjs.map +1 -1
- package/dist/components/SocialNetworks/InstagramLogo.cjs.map +1 -1
- package/dist/components/SocialNetworks/InstagramLogo.mjs.map +1 -1
- package/dist/components/SocialNetworks/LinkedInLogo.cjs.map +1 -1
- package/dist/components/SocialNetworks/LinkedInLogo.mjs.map +1 -1
- package/dist/components/SocialNetworks/ProductHuntLogo.cjs.map +1 -1
- package/dist/components/SocialNetworks/ProductHuntLogo.mjs.map +1 -1
- package/dist/components/SocialNetworks/TiktokLogo.cjs.map +1 -1
- package/dist/components/SocialNetworks/TiktokLogo.mjs.map +1 -1
- package/dist/components/SocialNetworks/XLogo.cjs.map +1 -1
- package/dist/components/SocialNetworks/XLogo.mjs.map +1 -1
- package/dist/components/SocialNetworks/YoutubeLogo.cjs.map +1 -1
- package/dist/components/SocialNetworks/YoutubeLogo.mjs.map +1 -1
- package/dist/components/SocialNetworks/index.cjs.map +1 -1
- package/dist/components/SocialNetworks/index.mjs.map +1 -1
- package/dist/components/SwitchSelector/index.cjs.map +1 -1
- package/dist/components/SwitchSelector/index.mjs.map +1 -1
- package/dist/components/TabSelector/TabSelector.cjs.map +1 -1
- package/dist/components/TabSelector/TabSelector.mjs.map +1 -1
- package/dist/components/Tag/index.cjs.map +1 -1
- package/dist/components/Tag/index.mjs.map +1 -1
- package/dist/components/TextArea/AutoSizeTextArea.cjs.map +1 -1
- package/dist/components/TextArea/AutoSizeTextArea.mjs.map +1 -1
- package/dist/components/TextArea/AutocompleteTextArea.cjs.map +1 -1
- package/dist/components/TextArea/AutocompleteTextArea.mjs.map +1 -1
- package/dist/components/TextArea/TextArea.cjs.map +1 -1
- package/dist/components/TextArea/TextArea.mjs.map +1 -1
- package/dist/components/ThemeSwitcherDropDown/DesktopThemeSwitcher.cjs.map +1 -1
- package/dist/components/ThemeSwitcherDropDown/DesktopThemeSwitcher.mjs.map +1 -1
- package/dist/components/ThemeSwitcherDropDown/MobileThemeSwitcher.cjs.map +1 -1
- package/dist/components/ThemeSwitcherDropDown/MobileThemeSwitcher.mjs.map +1 -1
- package/dist/components/ThemeSwitcherDropDown/types.cjs.map +1 -1
- package/dist/components/ThemeSwitcherDropDown/types.mjs.map +1 -1
- package/dist/components/Toaster/Toast.cjs.map +1 -1
- package/dist/components/Toaster/Toast.mjs.map +1 -1
- package/dist/components/Toaster/Toaster.cjs.map +1 -1
- package/dist/components/Toaster/Toaster.mjs.map +1 -1
- package/dist/components/Toaster/useToast.cjs.map +1 -1
- package/dist/components/Toaster/useToast.mjs.map +1 -1
- package/dist/components/WithResizer/index.cjs.map +1 -1
- package/dist/components/WithResizer/index.mjs.map +1 -1
- package/dist/hooks/auth.cjs.map +1 -1
- package/dist/hooks/auth.mjs.map +1 -1
- package/dist/hooks/intlayerAPIHooks.cjs.map +1 -1
- package/dist/hooks/intlayerAPIHooks.mjs.map +1 -1
- package/dist/hooks/useAsync/useAsync.cjs.map +1 -1
- package/dist/hooks/useAsync/useAsync.mjs.map +1 -1
- package/dist/hooks/useAsync/useAsyncStateStore.cjs.map +1 -1
- package/dist/hooks/useAsync/useAsyncStateStore.mjs.map +1 -1
- package/dist/hooks/useAsync/useAsyncWrapper.cjs.map +1 -1
- package/dist/hooks/useAsync/useAsyncWrapper.mjs.map +1 -1
- package/dist/hooks/useAuth/useAuth.cjs.map +1 -1
- package/dist/hooks/useAuth/useAuth.mjs.map +1 -1
- package/dist/hooks/useAuth/useOAuth2.cjs.map +1 -1
- package/dist/hooks/useAuth/useOAuth2.mjs.map +1 -1
- package/dist/hooks/useAuth/useSession.cjs.map +1 -1
- package/dist/hooks/useAuth/useSession.mjs.map +1 -1
- package/dist/hooks/useDevice.cjs.map +1 -1
- package/dist/hooks/useDevice.mjs.map +1 -1
- package/dist/hooks/useGetAllDictionaries.cjs.map +1 -1
- package/dist/hooks/useGetAllDictionaries.mjs.map +1 -1
- package/dist/hooks/useGetElementOrWindow.cjs.map +1 -1
- package/dist/hooks/useGetElementOrWindow.mjs.map +1 -1
- package/dist/hooks/useIntlayerAPI.cjs.map +1 -1
- package/dist/hooks/useIntlayerAPI.mjs.map +1 -1
- package/dist/hooks/useIsDarkMode.cjs.map +1 -1
- package/dist/hooks/useIsDarkMode.mjs.map +1 -1
- package/dist/hooks/useIsMounted.cjs.map +1 -1
- package/dist/hooks/useIsMounted.mjs.map +1 -1
- package/dist/hooks/useItemSelector.cjs.map +1 -1
- package/dist/hooks/useItemSelector.mjs.map +1 -1
- package/dist/hooks/useKeyboardDetector.cjs.map +1 -1
- package/dist/hooks/useKeyboardDetector.mjs.map +1 -1
- package/dist/hooks/usePersistedStore.cjs.map +1 -1
- package/dist/hooks/usePersistedStore.mjs.map +1 -1
- package/dist/hooks/useScreenWidth.cjs.map +1 -1
- package/dist/hooks/useScreenWidth.mjs.map +1 -1
- package/dist/hooks/useScrollBlockage/useScrollBlockageStore.cjs.map +1 -1
- package/dist/hooks/useScrollBlockage/useScrollBlockageStore.mjs.map +1 -1
- package/dist/hooks/useScrollDetection.cjs.map +1 -1
- package/dist/hooks/useScrollDetection.mjs.map +1 -1
- package/dist/hooks/useUser/index.cjs.map +1 -1
- package/dist/hooks/useUser/index.mjs.map +1 -1
- package/dist/index-BCuMWKyy.js.map +1 -1
- package/dist/index-BYzBot7l.cjs.map +1 -1
- package/dist/index-DW4Wnns5.cjs.map +1 -1
- package/dist/index-aPP3MzPT.js.map +1 -1
- package/dist/parse-BJVwmz92.cjs.map +1 -1
- package/dist/parse-pnJgclyf.js.map +1 -1
- package/dist/schemas-BIuxHDyZ.js.map +1 -1
- package/dist/schemas-Q6C7ZNs3.cjs.map +1 -1
- package/dist/tailwind.config.cjs.map +1 -1
- package/dist/tailwind.config.mjs.map +1 -1
- package/dist/utils/camelCase.cjs.map +1 -1
- package/dist/utils/camelCase.mjs.map +1 -1
- package/dist/utils/capitalize.cjs.map +1 -1
- package/dist/utils/capitalize.mjs.map +1 -1
- package/dist/utils/object.cjs.map +1 -1
- package/dist/utils/object.mjs.map +1 -1
- package/dist/zod-D4WapgbL.js.map +1 -1
- package/dist/zod-K7y5gPX4.cjs.map +1 -1
- package/package.json +15 -15
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"intlayerAPIHooks.cjs","sources":["../../src/hooks/intlayerAPIHooks.ts"],"sourcesContent":["'use client';\n\nimport type { IntlayerAPI } from '@intlayer/api';\nimport { useConfiguration } from '@intlayer/editor-react';\nimport { useToast } from '../components/Toaster';\nimport { getAuthAPI } from './auth';\nimport { type UseAsyncOptions, useAsync } from './useAsync/useAsync';\nimport { useAuth } from './useAuth';\nimport { useIntlayerAuth, useIntlayerOAuth } from './useIntlayerAPI';\n\nconst formatErrorCode = (errorCode: string) => errorCode.split('_').join(' ');\n\n/**\n * Hook to handle error logging and toast notifications\n */\nconst useErrorHandling = <T extends UseAsyncOptions<any>>(options: T): T => {\n const { toast } = useToast();\n\n return {\n ...options,\n onError: (errorMessage) => {\n let error;\n\n // If json is valid, parse it\n try {\n if (typeof errorMessage === 'undefined') return;\n\n error = JSON.parse(errorMessage);\n } catch (e) {\n // If json is not valid, set error to the original errorMessage\n\n error = errorMessage;\n }\n\n // render toast for each error if there is more than one\n // otherwise render the toast with the error message\n [error]\n .flatMap((error) => error)\n .forEach((error) =>\n toast({\n title: formatErrorCode(\n (process.env.NODE_ENV === 'production'\n ? error.title\n : error.code) ?? 'Error'\n ),\n description: error.message ?? errorMessage ?? 'An error occurred',\n variant: 'error',\n })\n );\n options.onError?.(errorMessage);\n },\n onSuccess: (data) => {\n if (data?.error) {\n toast({\n title: formatErrorCode(\n data.error.title ?? data.error.code ?? 'Error'\n ),\n description:\n data.error.message ?? data.error.code ?? 'An error occurred',\n variant: 'error',\n });\n }\n\n if (data?.message)\n toast({\n title: data.message,\n description: data.description,\n variant: 'success',\n });\n options.onSuccess?.(data);\n },\n };\n};\n\ntype AuthEnableOptions = {\n requireUser?: boolean;\n requireProject?: boolean;\n requireOrganization?: boolean;\n};\n\n/**\n * Hook to enable authentication\n */\nconst useAuthEnable = <T extends UseAsyncOptions<any>>(\n options: T,\n { requireUser, requireProject, requireOrganization }: AuthEnableOptions = {}\n): T => {\n const configuration = useConfiguration();\n const { oAuth2AccessToken, session } = useAuth({\n intlayerConfiguration: configuration,\n });\n\n const isEnabledOption = options?.enable ?? true;\n const user = session ? session.user : oAuth2AccessToken?.user;\n\n const organization = session\n ? session.organization\n : oAuth2AccessToken?.organization;\n\n const project = session ? session.project : oAuth2AccessToken?.project;\n\n const isUserEnabled = requireUser ? Boolean(user) : true;\n\n const isProjectEnabled = requireProject ? Boolean(project) : true;\n\n const isOrganizationEnabled = requireOrganization\n ? Boolean(organization)\n : true;\n\n const isEnabled =\n isEnabledOption &&\n isUserEnabled &&\n isProjectEnabled &&\n isOrganizationEnabled;\n\n return {\n ...options,\n enable: isEnabled,\n };\n};\n\nconst useAppAsync = <\n U extends string,\n T extends (...args: any[]) => Promise<any>,\n>(\n key: U,\n asyncFunction: T,\n options?: UseAsyncOptions<T>,\n authOptions?: AuthEnableOptions\n) => {\n // Enhance options using custom hooks\n const optionsWithAuth = useAuthEnable(options ?? {}, authOptions);\n\n const optionsWithErrorHandling = useErrorHandling(optionsWithAuth);\n\n // Call the main useAsync hook with enhanced options\n return useAsync(key, asyncFunction, optionsWithErrorHandling);\n};\n\nconst useEditorAsync = <\n U extends string,\n T extends (...args: any[]) => Promise<any>,\n>(\n key: U,\n asyncFunction: T,\n options?: UseAsyncOptions<T>\n) => {\n const optionsWithErrorHandling = useErrorHandling(options ?? {});\n\n // Call the main useAsync hook with enhanced options\n return useAsync(key, asyncFunction, optionsWithErrorHandling);\n};\n\n/**\n * Auth\n */\n\nexport const useLogin = (\n args?: UseAsyncOptions<ReturnType<typeof getAuthAPI>['signInEmail']>\n) =>\n useAppAsync('login', useIntlayerAuth().signInEmail, {\n invalidateQueries: ['getSession'],\n ...args,\n });\n\nexport const useGetVerifyEmailStatus = (\n args?: UseAsyncOptions<ReturnType<typeof getAuthAPI>['verifyEmailSession']>\n) =>\n useAppAsync(\n 'getVerifyEmailStatus',\n useIntlayerAuth().verifyEmailSession,\n args\n );\n\nexport const useRegister = (\n args?: UseAsyncOptions<ReturnType<typeof getAuthAPI>['signUpEmail']>\n) =>\n useAppAsync('register', useIntlayerAuth().signUpEmail, {\n invalidateQueries: ['getSession'],\n ...args,\n });\n\nexport const useLogout = (\n args?: UseAsyncOptions<ReturnType<typeof getAuthAPI>['signOut']>\n) =>\n useAppAsync('logout', useIntlayerAuth().signOut, {\n ...args,\n });\n\nexport const useChangePassword = (\n args?: UseAsyncOptions<ReturnType<typeof getAuthAPI>['changePasswordSession']>\n) =>\n useAppAsync('changePassword', useIntlayerAuth().changePasswordSession, args);\n\nexport const useAskResetPassword = (\n args?: UseAsyncOptions<\n ReturnType<typeof getAuthAPI>['requestPasswordResetSession']\n >\n) =>\n useAppAsync(\n 'askResetPassword',\n useIntlayerAuth().requestPasswordResetSession,\n args\n );\n\nexport const useResetPassword = (\n args?: UseAsyncOptions<ReturnType<typeof getAuthAPI>['resetPassword']>\n) => useAppAsync('resetPassword', useIntlayerAuth().resetPassword, args);\n\nexport const useVerifyEmail = (\n args?: UseAsyncOptions<ReturnType<typeof getAuthAPI>['verifyEmailSession']>\n) => useAppAsync('verifyEmail', useIntlayerAuth().verifyEmailSession, args);\n\nexport const useGetUserByAccount = (\n args?: UseAsyncOptions<ReturnType<typeof getAuthAPI>['accountInfo']>\n) => useAppAsync('getUserByAccount', useIntlayerAuth().accountInfo, args);\n\n/**\n * User\n */\n\nexport const useGetUsers = (\n args?: UseAsyncOptions<IntlayerAPI['user']['getUsers']>\n) =>\n useAppAsync(\n 'getUsers',\n useIntlayerOAuth().user.getUsers,\n {\n cache: true,\n store: true,\n retryLimit: 3,\n autoFetch: true,\n revalidateTime: 5 * 60 * 1000, // 5 minutes\n ...args,\n },\n {\n requireUser: true,\n }\n );\n\nexport const useCreateUser = (\n args?: UseAsyncOptions<ReturnType<typeof getAuthAPI>['updateUser']>\n) =>\n useAppAsync('createUser', useIntlayerAuth().updateUser, {\n invalidateQueries: ['getUsers'],\n ...args,\n });\n\nexport const useUpdateUser = (\n args?: UseAsyncOptions<IntlayerAPI['user']['updateUser']>\n) =>\n useAppAsync('updateUser', useIntlayerOAuth().user.updateUser, {\n invalidateQueries: ['getSession'],\n ...args,\n });\n\nexport const useDeleteUser = (\n args?: UseAsyncOptions<IntlayerAPI['user']['deleteUser']>\n) =>\n useAppAsync('deleteUser', useIntlayerOAuth().user.deleteUser, {\n invalidateQueries: ['getUsers'],\n ...args,\n });\n\n/**\n * Organization\n */\n\nexport const useGetOrganizations = (\n args?: UseAsyncOptions<IntlayerAPI['organization']['getOrganizations']>\n) =>\n useAppAsync(\n 'getOrganizations',\n useIntlayerOAuth().organization.getOrganizations,\n {\n cache: true,\n store: true,\n retryLimit: 3,\n autoFetch: true,\n revalidation: true,\n revalidateTime: 5 * 60 * 1000, // 5 minutes\n ...args,\n },\n {\n requireUser: true,\n }\n );\n\nexport const useAddOrganization = (\n args?: UseAsyncOptions<IntlayerAPI['organization']['addOrganization']>\n) =>\n useAppAsync(\n 'addOrganization',\n useIntlayerOAuth().organization.addOrganization,\n {\n invalidateQueries: ['getOrganizations'],\n ...args,\n }\n );\n\nexport const useUpdateOrganization = (\n args?: UseAsyncOptions<IntlayerAPI['organization']['updateOrganization']>\n) =>\n useAppAsync(\n 'updateOrganization',\n useIntlayerOAuth().organization.updateOrganization,\n {\n invalidateQueries: ['getSession'],\n ...args,\n }\n );\n\nexport const useUpdateOrganizationMembers = (\n args?: UseAsyncOptions<\n IntlayerAPI['organization']['updateOrganizationMembers']\n >\n) =>\n useAppAsync(\n 'updateOrganizationMembers',\n useIntlayerOAuth().organization.updateOrganizationMembers,\n {\n invalidateQueries: ['getOrganizations', 'getSession'],\n ...args,\n }\n );\n\nexport const useAddOrganizationMember = (\n args?: UseAsyncOptions<IntlayerAPI['organization']['addOrganizationMember']>\n) =>\n useAppAsync(\n 'addOrganizationMember',\n useIntlayerOAuth().organization.addOrganizationMember,\n {\n invalidateQueries: ['getOrganizations', 'getSession'],\n ...args,\n }\n );\n\nexport const useDeleteOrganization = (\n args?: UseAsyncOptions<IntlayerAPI['organization']['deleteOrganization']>\n) =>\n useAppAsync(\n 'deleteOrganization',\n useIntlayerOAuth().organization.deleteOrganization,\n {\n invalidateQueries: ['getOrganizations', 'getSession'],\n ...args,\n }\n );\n\nexport const useSelectOrganization = (\n args?: UseAsyncOptions<IntlayerAPI['organization']['selectOrganization']>\n) =>\n useAppAsync(\n 'selectOrganization',\n useIntlayerOAuth().organization.selectOrganization,\n {\n invalidateQueries: ['getSession'],\n ...args,\n }\n );\n\nexport const useUnselectOrganization = (\n args?: UseAsyncOptions<IntlayerAPI['organization']['unselectOrganization']>\n) =>\n useAppAsync(\n 'unselectOrganization',\n useIntlayerOAuth().organization.unselectOrganization,\n {\n invalidateQueries: ['getSession'],\n ...args,\n }\n );\n\n/**\n * Project\n */\n\nexport const useGetProjects = (\n args?: UseAsyncOptions<IntlayerAPI['project']['getProjects']>\n) =>\n useAppAsync(\n 'getProjects',\n useIntlayerOAuth().project.getProjects,\n {\n cache: true,\n store: true,\n retryLimit: 3,\n autoFetch: true,\n revalidation: true,\n revalidateTime: 5 * 60 * 1000, // 5 minutes\n ...args,\n },\n {\n requireUser: true,\n requireOrganization: true,\n }\n );\n\nexport const useAddProject = (\n args?: UseAsyncOptions<IntlayerAPI['project']['addProject']>\n) =>\n useAppAsync('addProject', useIntlayerOAuth().project.addProject, {\n invalidateQueries: ['getProjects'],\n ...args,\n });\n\nexport const useUpdateProject = (\n args?: UseAsyncOptions<IntlayerAPI['project']['updateProject']>\n) =>\n useAppAsync('updateProject', useIntlayerOAuth().project.updateProject, {\n invalidateQueries: ['getSession'],\n ...args,\n });\n\nexport const useUpdateProjectMembers = (\n args?: UseAsyncOptions<IntlayerAPI['project']['updateProjectMembers']>\n) =>\n useAppAsync(\n 'updateProjectMembers',\n useIntlayerOAuth().project.updateProjectMembers,\n {\n invalidateQueries: ['getSession'],\n ...args,\n }\n );\n\nexport const useDeleteProject = (\n args?: UseAsyncOptions<IntlayerAPI['project']['deleteProject']>\n) =>\n useAppAsync('deleteProject', useIntlayerOAuth().project.deleteProject, {\n invalidateQueries: ['getProjects', 'getSession'],\n ...args,\n });\n\nexport const useSelectProject = (\n args?: UseAsyncOptions<IntlayerAPI['project']['selectProject']>\n) =>\n useAppAsync('selectProject', useIntlayerOAuth().project.selectProject, {\n invalidateQueries: ['getSession'],\n ...args,\n });\n\nexport const useUnselectProject = (\n args?: UseAsyncOptions<IntlayerAPI['project']['unselectProject']>\n) =>\n useAppAsync('unselectProject', useIntlayerOAuth().project.unselectProject, {\n invalidateQueries: ['getSession'],\n ...args,\n });\n\nexport const useAddNewAccessKey = (\n args?: UseAsyncOptions<IntlayerAPI['project']['addNewAccessKey']>\n) =>\n useAppAsync('addNewAccessKey', useIntlayerOAuth().project.addNewAccessKey, {\n invalidateQueries: ['getSession'],\n ...args,\n });\n\nexport const useDeleteAccessKey = (\n args?: UseAsyncOptions<IntlayerAPI['project']['deleteAccessKey']>\n) =>\n useAppAsync('deleteAccessKey', useIntlayerOAuth().project.deleteAccessKey, {\n invalidateQueries: ['getSession'],\n ...args,\n });\n\nexport const useRefreshAccessKey = (\n args?: UseAsyncOptions<IntlayerAPI['project']['refreshAccessKey']>\n) =>\n useAppAsync('refreshAccessKey', useIntlayerOAuth().project.refreshAccessKey, {\n invalidateQueries: ['getSession'],\n ...args,\n });\n\n/**\n * Dictionary\n */\n\nexport const useGetDictionaries = (\n args?: UseAsyncOptions<IntlayerAPI['dictionary']['getDictionaries']>\n) =>\n useAppAsync(\n 'getDictionaries',\n useIntlayerOAuth().dictionary.getDictionaries,\n {\n cache: true,\n store: true,\n retryLimit: 3,\n autoFetch: true,\n revalidation: true,\n revalidateTime: 5 * 60 * 1000, // 5 minutes\n ...args,\n },\n {\n requireUser: true,\n requireOrganization: true,\n requireProject: true,\n }\n );\n\nexport const useGetDictionariesKeys = (\n args?: UseAsyncOptions<IntlayerAPI['dictionary']['getDictionariesKeys']>\n) =>\n useAppAsync(\n 'getDictionariesKeys',\n useIntlayerOAuth().dictionary.getDictionariesKeys,\n {\n cache: true,\n store: true,\n retryLimit: 3,\n autoFetch: true,\n revalidation: true,\n revalidateTime: 5 * 60 * 1000, // 5 minutes\n ...args,\n },\n {\n requireUser: true,\n requireOrganization: true,\n requireProject: true,\n }\n );\n\nexport const useGetDictionary = (\n args?: UseAsyncOptions<IntlayerAPI['dictionary']['getDictionary']>\n) =>\n useAppAsync(\n 'getDictionary',\n useIntlayerOAuth().dictionary.getDictionary,\n {\n cache: true,\n store: true,\n retryLimit: 3,\n revalidation: true,\n revalidateTime: 5 * 60 * 1000, // 5 minutes\n ...args,\n },\n {\n requireUser: true,\n requireOrganization: true,\n requireProject: true,\n }\n );\n\nexport const useAddDictionary = (\n args?: UseAsyncOptions<IntlayerAPI['dictionary']['addDictionary']>\n) =>\n useAppAsync('addDictionary', useIntlayerOAuth().dictionary.addDictionary, {\n invalidateQueries: ['getDictionaries', 'getDictionariesKeys'],\n ...args,\n });\n\nexport const usePushDictionaries = (\n args?: UseAsyncOptions<IntlayerAPI['dictionary']['pushDictionaries']>\n) =>\n useAppAsync(\n 'pushDictionaries',\n useIntlayerOAuth().dictionary.pushDictionaries,\n {\n invalidateQueries: [\n 'getDictionaries',\n 'getDictionary',\n 'getDictionariesKeys',\n ],\n ...args,\n }\n );\n\nexport const useUpdateDictionary = (\n args?: UseAsyncOptions<IntlayerAPI['dictionary']['updateDictionary']>\n) =>\n useAppAsync(\n 'updateDictionary',\n useIntlayerOAuth().dictionary.updateDictionary,\n {\n invalidateQueries: ['getDictionaries', 'getDictionary'],\n ...args,\n }\n );\n\nexport const useDeleteDictionary = (\n args?: UseAsyncOptions<IntlayerAPI['dictionary']['deleteDictionary']>\n) =>\n useAppAsync(\n 'deleteDictionary',\n useIntlayerOAuth().dictionary.deleteDictionary,\n {\n invalidateQueries: [\n 'getDictionaries',\n 'getDictionary',\n 'getDictionariesKeys',\n ],\n ...args,\n }\n );\n\n/**\n * Tag\n */\n\nexport const useGetTags = (\n args?: UseAsyncOptions<IntlayerAPI['tag']['getTags']>\n) =>\n useAppAsync(\n 'getTags',\n useIntlayerOAuth().tag.getTags,\n {\n cache: true,\n store: true,\n retryLimit: 3,\n autoFetch: true,\n revalidation: true,\n revalidateTime: 5 * 60 * 1000, // 5 minutes\n ...args,\n },\n {\n requireUser: true,\n requireOrganization: true,\n }\n );\n\nexport const useAddTag = (\n args?: UseAsyncOptions<IntlayerAPI['tag']['addTag']>\n) =>\n useAppAsync('addTag', useIntlayerOAuth().tag.addTag, {\n invalidateQueries: ['getTags'],\n ...args,\n });\n\nexport const useUpdateTag = (\n args?: UseAsyncOptions<IntlayerAPI['tag']['updateTag']>\n) =>\n useAppAsync('updateTag', useIntlayerOAuth().tag.updateTag, {\n invalidateQueries: ['getTags'],\n ...args,\n });\n\nexport const useDeleteTag = (\n args?: UseAsyncOptions<IntlayerAPI['tag']['deleteTag']>\n) =>\n useAppAsync('deleteTag', useIntlayerOAuth().tag.deleteTag, {\n invalidateQueries: ['getTags'],\n ...args,\n });\n\n/**\n * Stripe\n */\n\nexport const useGetPricing = (\n args?: UseAsyncOptions<IntlayerAPI['stripe']['getPricing']>\n) =>\n useAppAsync('getPricing', useIntlayerOAuth().stripe.getPricing, {\n store: true,\n cache: true,\n ...args,\n });\n\nexport const useGetSubscription = (\n args?: UseAsyncOptions<IntlayerAPI['stripe']['getSubscription']>\n) =>\n useAppAsync(\n 'getSubscription',\n useIntlayerOAuth().stripe.getSubscription,\n args,\n {\n requireUser: true,\n requireOrganization: true,\n }\n );\n\nexport const useCancelSubscription = (\n args?: UseAsyncOptions<IntlayerAPI['stripe']['cancelSubscription']>\n) =>\n useAppAsync(\n 'cancelSubscription',\n useIntlayerOAuth().stripe.cancelSubscription,\n { invalidateQueries: ['getSession'], ...args },\n {\n requireUser: true,\n requireOrganization: true,\n }\n );\n\n/**\n * AI\n */\n\nexport const useTranslateJSONDeclaration = (\n args?: UseAsyncOptions<IntlayerAPI['ai']['translateJSON']>\n) =>\n useAppAsync('translateJSON', useIntlayerOAuth().ai.translateJSON, args, {\n requireUser: true,\n requireOrganization: true,\n requireProject: true,\n });\n\nexport const useAuditContentDeclaration = (\n args?: UseAsyncOptions<IntlayerAPI['ai']['auditContentDeclaration']>\n) =>\n useAppAsync(\n 'auditContentDeclaration',\n useIntlayerOAuth().ai.auditContentDeclaration,\n args,\n {\n requireUser: true,\n requireOrganization: true,\n requireProject: true,\n }\n );\n\nexport const useAuditContentDeclarationMetadata = (\n args?: UseAsyncOptions<IntlayerAPI['ai']['auditContentDeclarationMetadata']>\n) =>\n useAppAsync(\n 'auditContentDeclaration',\n useIntlayerOAuth().ai.auditContentDeclarationMetadata,\n args,\n {\n requireUser: true,\n requireOrganization: true,\n requireProject: true,\n }\n );\n\nexport const useAuditContentDeclarationField = (\n args?: UseAsyncOptions<IntlayerAPI['ai']['auditContentDeclarationField']>\n) =>\n useAppAsync(\n 'auditContentDeclarationField',\n useIntlayerOAuth().ai.auditContentDeclarationField,\n args,\n {\n requireUser: true,\n requireOrganization: true,\n requireProject: true,\n }\n );\n\nexport const useAuditTag = (\n args?: UseAsyncOptions<IntlayerAPI['ai']['auditTag']>\n) =>\n useAppAsync('auditTag', useIntlayerOAuth().ai.auditTag, args, {\n requireUser: true,\n requireOrganization: true,\n requireProject: true,\n });\n\nexport const useAskDocQuestion = (\n args?: UseAsyncOptions<IntlayerAPI['ai']['askDocQuestion']>\n) => useAppAsync('askDocQuestion', useIntlayerOAuth().ai.askDocQuestion, args);\n\nexport const useAutocomplete = (\n args?: UseAsyncOptions<IntlayerAPI['ai']['autocomplete']>\n) => useAppAsync('autocomplete', useIntlayerOAuth().ai.autocomplete, args);\n\n/**\n * Search\n */\n\nexport const useSearchDoc = (\n args?: UseAsyncOptions<IntlayerAPI['search']['searchDoc']>\n) => useAppAsync('searchDoc', useIntlayerOAuth().search.searchDoc, args);\n\n/**\n * Newsletter\n */\n\nexport const useSubscribeToNewsletter = (\n args?: UseAsyncOptions<IntlayerAPI['newsletter']['subscribeToNewsletter']>\n) =>\n useAppAsync(\n 'subscribeToNewsletter',\n useIntlayerOAuth().newsletter.subscribeToNewsletter,\n args\n );\n\nexport const useUnsubscribeFromNewsletter = (\n args?: UseAsyncOptions<IntlayerAPI['newsletter']['unsubscribeFromNewsletter']>\n) =>\n useAppAsync(\n 'unsubscribeFromNewsletter',\n useIntlayerOAuth().newsletter.unsubscribeFromNewsletter,\n args\n );\n\nexport const useGetNewsletterStatus = (\n args?: UseAsyncOptions<IntlayerAPI['newsletter']['getNewsletterStatus']>\n) =>\n useAppAsync(\n 'getNewsletterStatus',\n useIntlayerOAuth().newsletter.getNewsletterStatus,\n args\n );\n\n/**\n * Editor\n */\n\nexport const useWriteDictionary = (\n args?: UseAsyncOptions<IntlayerAPI['editor']['writeDictionary']>\n) =>\n useEditorAsync(\n 'writeDictionary',\n useIntlayerOAuth().editor.writeDictionary,\n args\n );\n\nexport const useGetEditorDictionaries = (\n args?: UseAsyncOptions<IntlayerAPI['editor']['getDictionaries']>\n) =>\n useEditorAsync('getDictionaries', useIntlayerOAuth().editor.getDictionaries, {\n store: true,\n cache: true,\n ...args,\n });\n"],"names":["useToast","error","useConfiguration","useAuth","useAsync","useIntlayerAuth","useIntlayerOAuth"],"mappings":";;;;;;;;;;;;;;;AAUA,MAAM,kBAAkB,CAAC,cAAsB,UAAU,MAAM,GAAG,EAAE,KAAK,GAAG;AAK5E,MAAM,mBAAmB,CAAiC,YAAkB;AACpE,QAAA,EAAE,MAAM,IAAIA,qCAAS;AAEpB,SAAA;AAAA,IACL,GAAG;AAAA,IACH,SAAS,CAAC,iBAAiB;AACrB,UAAA;AAGA,UAAA;AACE,YAAA,OAAO,iBAAiB,YAAa;AAEjC,gBAAA,KAAK,MAAM,YAAY;AAAA,eACxB,GAAG;AAGF,gBAAA;AAAA,MAAA;AAKV,OAAC,KAAK,EACH,QAAQ,CAACC,WAAUA,MAAK,EACxB;AAAA,QAAQ,CAACA,WACR,MAAM;AAAA,UACJ,OAAO;AAAA,aACJ,2BAAY,aAAa,eACtBA,OAAM,QACNA,OAAM,SAAS;AAAA,UACrB;AAAA,UACA,aAAaA,OAAM,WAAW,gBAAgB;AAAA,UAC9C,SAAS;AAAA,QACV,CAAA;AAAA,MACH;AACF,cAAQ,UAAU,YAAY;AAAA,IAChC;AAAA,IACA,WAAW,CAAC,SAAS;AACnB,UAAI,MAAM,OAAO;AACT,cAAA;AAAA,UACJ,OAAO;AAAA,YACL,KAAK,MAAM,SAAS,KAAK,MAAM,QAAQ;AAAA,UACzC;AAAA,UACA,aACE,KAAK,MAAM,WAAW,KAAK,MAAM,QAAQ;AAAA,UAC3C,SAAS;AAAA,QAAA,CACV;AAAA,MAAA;AAGH,UAAI,MAAM;AACF,cAAA;AAAA,UACJ,OAAO,KAAK;AAAA,UACZ,aAAa,KAAK;AAAA,UAClB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yB,CACpC,SAEA;AAAA,EACE;AAAA,EACAA,qBAAA,iBAAA,EAAmB,WAAW;AAAA,EAC9B;AACF;AAMW,MAAA,qBAAqB,CAChC,SAEA;AAAA,EACE;AAAA,EACAA,qBAAA,iBAAA,EAAmB,OAAO;AAAA,EAC1B;AACF;AAEW,MAAA,2BAA2B,CACtC,SAEA,eAAe,mBAAmBA,sCAAiB,EAAE,OAAO,iBAAiB;AAAA,EAC3E,OAAO;AAAA,EACP,OAAO;AAAA,EACP,GAAG;AACL,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"}
|
|
1
|
+
{"version":3,"file":"intlayerAPIHooks.cjs","sources":["../../src/hooks/intlayerAPIHooks.ts"],"sourcesContent":["'use client';\n\nimport type { IntlayerAPI } from '@intlayer/api';\nimport { useConfiguration } from '@intlayer/editor-react';\nimport { useToast } from '../components/Toaster';\nimport { getAuthAPI } from './auth';\nimport { type UseAsyncOptions, useAsync } from './useAsync/useAsync';\nimport { useAuth } from './useAuth';\nimport { useIntlayerAuth, useIntlayerOAuth } from './useIntlayerAPI';\n\nconst formatErrorCode = (errorCode: string) => errorCode.split('_').join(' ');\n\n/**\n * Hook to handle error logging and toast notifications\n */\nconst useErrorHandling = <T extends UseAsyncOptions<any>>(options: T): T => {\n const { toast } = useToast();\n\n return {\n ...options,\n onError: (errorMessage) => {\n let error;\n\n // If json is valid, parse it\n try {\n if (typeof errorMessage === 'undefined') return;\n\n error = JSON.parse(errorMessage);\n } catch (e) {\n // If json is not valid, set error to the original errorMessage\n\n error = errorMessage;\n }\n\n // render toast for each error if there is more than one\n // otherwise render the toast with the error message\n [error]\n .flatMap((error) => error)\n .forEach((error) =>\n toast({\n title: formatErrorCode(\n (process.env.NODE_ENV === 'production'\n ? error.title\n : error.code) ?? 'Error'\n ),\n description: error.message ?? errorMessage ?? 'An error occurred',\n variant: 'error',\n })\n );\n options.onError?.(errorMessage);\n },\n onSuccess: (data) => {\n if (data?.error) {\n toast({\n title: formatErrorCode(\n data.error.title ?? data.error.code ?? 'Error'\n ),\n description:\n data.error.message ?? data.error.code ?? 'An error occurred',\n variant: 'error',\n });\n }\n\n if (data?.message)\n toast({\n title: data.message,\n description: data.description,\n variant: 'success',\n });\n options.onSuccess?.(data);\n },\n };\n};\n\ntype AuthEnableOptions = {\n requireUser?: boolean;\n requireProject?: boolean;\n requireOrganization?: boolean;\n};\n\n/**\n * Hook to enable authentication\n */\nconst useAuthEnable = <T extends UseAsyncOptions<any>>(\n options: T,\n { requireUser, requireProject, requireOrganization }: AuthEnableOptions = {}\n): T => {\n const configuration = useConfiguration();\n const { oAuth2AccessToken, session } = useAuth({\n intlayerConfiguration: configuration,\n });\n\n const isEnabledOption = options?.enable ?? true;\n const user = session ? session.user : oAuth2AccessToken?.user;\n\n const organization = session\n ? session.organization\n : oAuth2AccessToken?.organization;\n\n const project = session ? session.project : oAuth2AccessToken?.project;\n\n const isUserEnabled = requireUser ? Boolean(user) : true;\n\n const isProjectEnabled = requireProject ? Boolean(project) : true;\n\n const isOrganizationEnabled = requireOrganization\n ? Boolean(organization)\n : true;\n\n const isEnabled =\n isEnabledOption &&\n isUserEnabled &&\n isProjectEnabled &&\n isOrganizationEnabled;\n\n return {\n ...options,\n enable: isEnabled,\n };\n};\n\nconst useAppAsync = <\n U extends string,\n T extends (...args: any[]) => Promise<any>,\n>(\n key: U,\n asyncFunction: T,\n options?: UseAsyncOptions<T>,\n authOptions?: AuthEnableOptions\n) => {\n // Enhance options using custom hooks\n const optionsWithAuth = useAuthEnable(options ?? {}, authOptions);\n\n const optionsWithErrorHandling = useErrorHandling(optionsWithAuth);\n\n // Call the main useAsync hook with enhanced options\n return useAsync(key, asyncFunction, optionsWithErrorHandling);\n};\n\nconst useEditorAsync = <\n U extends string,\n T extends (...args: any[]) => Promise<any>,\n>(\n key: U,\n asyncFunction: T,\n options?: UseAsyncOptions<T>\n) => {\n const optionsWithErrorHandling = useErrorHandling(options ?? {});\n\n // Call the main useAsync hook with enhanced options\n return useAsync(key, asyncFunction, optionsWithErrorHandling);\n};\n\n/**\n * Auth\n */\n\nexport const useLogin = (\n args?: UseAsyncOptions<ReturnType<typeof getAuthAPI>['signInEmail']>\n) =>\n useAppAsync('login', useIntlayerAuth().signInEmail, {\n invalidateQueries: ['getSession'],\n ...args,\n });\n\nexport const useGetVerifyEmailStatus = (\n args?: UseAsyncOptions<ReturnType<typeof getAuthAPI>['verifyEmailSession']>\n) =>\n useAppAsync(\n 'getVerifyEmailStatus',\n useIntlayerAuth().verifyEmailSession,\n args\n );\n\nexport const useRegister = (\n args?: UseAsyncOptions<ReturnType<typeof getAuthAPI>['signUpEmail']>\n) =>\n useAppAsync('register', useIntlayerAuth().signUpEmail, {\n invalidateQueries: ['getSession'],\n ...args,\n });\n\nexport const useLogout = (\n args?: UseAsyncOptions<ReturnType<typeof getAuthAPI>['signOut']>\n) =>\n useAppAsync('logout', useIntlayerAuth().signOut, {\n ...args,\n });\n\nexport const useChangePassword = (\n args?: UseAsyncOptions<ReturnType<typeof getAuthAPI>['changePasswordSession']>\n) =>\n useAppAsync('changePassword', useIntlayerAuth().changePasswordSession, args);\n\nexport const useAskResetPassword = (\n args?: UseAsyncOptions<\n ReturnType<typeof getAuthAPI>['requestPasswordResetSession']\n >\n) =>\n useAppAsync(\n 'askResetPassword',\n useIntlayerAuth().requestPasswordResetSession,\n args\n );\n\nexport const useResetPassword = (\n args?: UseAsyncOptions<ReturnType<typeof getAuthAPI>['resetPassword']>\n) => useAppAsync('resetPassword', useIntlayerAuth().resetPassword, args);\n\nexport const useVerifyEmail = (\n args?: UseAsyncOptions<ReturnType<typeof getAuthAPI>['verifyEmailSession']>\n) => useAppAsync('verifyEmail', useIntlayerAuth().verifyEmailSession, args);\n\nexport const useGetUserByAccount = (\n args?: UseAsyncOptions<ReturnType<typeof getAuthAPI>['accountInfo']>\n) => useAppAsync('getUserByAccount', useIntlayerAuth().accountInfo, args);\n\n/**\n * User\n */\n\nexport const useGetUsers = (\n args?: UseAsyncOptions<IntlayerAPI['user']['getUsers']>\n) =>\n useAppAsync(\n 'getUsers',\n useIntlayerOAuth().user.getUsers,\n {\n cache: true,\n store: true,\n retryLimit: 3,\n autoFetch: true,\n revalidateTime: 5 * 60 * 1000, // 5 minutes\n ...args,\n },\n {\n requireUser: true,\n }\n );\n\nexport const useCreateUser = (\n args?: UseAsyncOptions<ReturnType<typeof getAuthAPI>['updateUser']>\n) =>\n useAppAsync('createUser', useIntlayerAuth().updateUser, {\n invalidateQueries: ['getUsers'],\n ...args,\n });\n\nexport const useUpdateUser = (\n args?: UseAsyncOptions<IntlayerAPI['user']['updateUser']>\n) =>\n useAppAsync('updateUser', useIntlayerOAuth().user.updateUser, {\n invalidateQueries: ['getSession'],\n ...args,\n });\n\nexport const useDeleteUser = (\n args?: UseAsyncOptions<IntlayerAPI['user']['deleteUser']>\n) =>\n useAppAsync('deleteUser', useIntlayerOAuth().user.deleteUser, {\n invalidateQueries: ['getUsers'],\n ...args,\n });\n\n/**\n * Organization\n */\n\nexport const useGetOrganizations = (\n args?: UseAsyncOptions<IntlayerAPI['organization']['getOrganizations']>\n) =>\n useAppAsync(\n 'getOrganizations',\n useIntlayerOAuth().organization.getOrganizations,\n {\n cache: true,\n store: true,\n retryLimit: 3,\n autoFetch: true,\n revalidation: true,\n revalidateTime: 5 * 60 * 1000, // 5 minutes\n ...args,\n },\n {\n requireUser: true,\n }\n );\n\nexport const useAddOrganization = (\n args?: UseAsyncOptions<IntlayerAPI['organization']['addOrganization']>\n) =>\n useAppAsync(\n 'addOrganization',\n useIntlayerOAuth().organization.addOrganization,\n {\n invalidateQueries: ['getOrganizations'],\n ...args,\n }\n );\n\nexport const useUpdateOrganization = (\n args?: UseAsyncOptions<IntlayerAPI['organization']['updateOrganization']>\n) =>\n useAppAsync(\n 'updateOrganization',\n useIntlayerOAuth().organization.updateOrganization,\n {\n invalidateQueries: ['getSession'],\n ...args,\n }\n );\n\nexport const useUpdateOrganizationMembers = (\n args?: UseAsyncOptions<\n IntlayerAPI['organization']['updateOrganizationMembers']\n >\n) =>\n useAppAsync(\n 'updateOrganizationMembers',\n useIntlayerOAuth().organization.updateOrganizationMembers,\n {\n invalidateQueries: ['getOrganizations', 'getSession'],\n ...args,\n }\n );\n\nexport const useAddOrganizationMember = (\n args?: UseAsyncOptions<IntlayerAPI['organization']['addOrganizationMember']>\n) =>\n useAppAsync(\n 'addOrganizationMember',\n useIntlayerOAuth().organization.addOrganizationMember,\n {\n invalidateQueries: ['getOrganizations', 'getSession'],\n ...args,\n }\n );\n\nexport const useDeleteOrganization = (\n args?: UseAsyncOptions<IntlayerAPI['organization']['deleteOrganization']>\n) =>\n useAppAsync(\n 'deleteOrganization',\n useIntlayerOAuth().organization.deleteOrganization,\n {\n invalidateQueries: ['getOrganizations', 'getSession'],\n ...args,\n }\n );\n\nexport const useSelectOrganization = (\n args?: UseAsyncOptions<IntlayerAPI['organization']['selectOrganization']>\n) =>\n useAppAsync(\n 'selectOrganization',\n useIntlayerOAuth().organization.selectOrganization,\n {\n invalidateQueries: ['getSession'],\n ...args,\n }\n );\n\nexport const useUnselectOrganization = (\n args?: UseAsyncOptions<IntlayerAPI['organization']['unselectOrganization']>\n) =>\n useAppAsync(\n 'unselectOrganization',\n useIntlayerOAuth().organization.unselectOrganization,\n {\n invalidateQueries: ['getSession'],\n ...args,\n }\n );\n\n/**\n * Project\n */\n\nexport const useGetProjects = (\n args?: UseAsyncOptions<IntlayerAPI['project']['getProjects']>\n) =>\n useAppAsync(\n 'getProjects',\n useIntlayerOAuth().project.getProjects,\n {\n cache: true,\n store: true,\n retryLimit: 3,\n autoFetch: true,\n revalidation: true,\n revalidateTime: 5 * 60 * 1000, // 5 minutes\n ...args,\n },\n {\n requireUser: true,\n requireOrganization: true,\n }\n );\n\nexport const useAddProject = (\n args?: UseAsyncOptions<IntlayerAPI['project']['addProject']>\n) =>\n useAppAsync('addProject', useIntlayerOAuth().project.addProject, {\n invalidateQueries: ['getProjects'],\n ...args,\n });\n\nexport const useUpdateProject = (\n args?: UseAsyncOptions<IntlayerAPI['project']['updateProject']>\n) =>\n useAppAsync('updateProject', useIntlayerOAuth().project.updateProject, {\n invalidateQueries: ['getSession'],\n ...args,\n });\n\nexport const useUpdateProjectMembers = (\n args?: UseAsyncOptions<IntlayerAPI['project']['updateProjectMembers']>\n) =>\n useAppAsync(\n 'updateProjectMembers',\n useIntlayerOAuth().project.updateProjectMembers,\n {\n invalidateQueries: ['getSession'],\n ...args,\n }\n );\n\nexport const useDeleteProject = (\n args?: UseAsyncOptions<IntlayerAPI['project']['deleteProject']>\n) =>\n useAppAsync('deleteProject', useIntlayerOAuth().project.deleteProject, {\n invalidateQueries: ['getProjects', 'getSession'],\n ...args,\n });\n\nexport const useSelectProject = (\n args?: UseAsyncOptions<IntlayerAPI['project']['selectProject']>\n) =>\n useAppAsync('selectProject', useIntlayerOAuth().project.selectProject, {\n invalidateQueries: ['getSession'],\n ...args,\n });\n\nexport const useUnselectProject = (\n args?: UseAsyncOptions<IntlayerAPI['project']['unselectProject']>\n) =>\n useAppAsync('unselectProject', useIntlayerOAuth().project.unselectProject, {\n invalidateQueries: ['getSession'],\n ...args,\n });\n\nexport const useAddNewAccessKey = (\n args?: UseAsyncOptions<IntlayerAPI['project']['addNewAccessKey']>\n) =>\n useAppAsync('addNewAccessKey', useIntlayerOAuth().project.addNewAccessKey, {\n invalidateQueries: ['getSession'],\n ...args,\n });\n\nexport const useDeleteAccessKey = (\n args?: UseAsyncOptions<IntlayerAPI['project']['deleteAccessKey']>\n) =>\n useAppAsync('deleteAccessKey', useIntlayerOAuth().project.deleteAccessKey, {\n invalidateQueries: ['getSession'],\n ...args,\n });\n\nexport const useRefreshAccessKey = (\n args?: UseAsyncOptions<IntlayerAPI['project']['refreshAccessKey']>\n) =>\n useAppAsync('refreshAccessKey', useIntlayerOAuth().project.refreshAccessKey, {\n invalidateQueries: ['getSession'],\n ...args,\n });\n\n/**\n * Dictionary\n */\n\nexport const useGetDictionaries = (\n args?: UseAsyncOptions<IntlayerAPI['dictionary']['getDictionaries']>\n) =>\n useAppAsync(\n 'getDictionaries',\n useIntlayerOAuth().dictionary.getDictionaries,\n {\n cache: true,\n store: true,\n retryLimit: 3,\n autoFetch: true,\n revalidation: true,\n revalidateTime: 5 * 60 * 1000, // 5 minutes\n ...args,\n },\n {\n requireUser: true,\n requireOrganization: true,\n requireProject: true,\n }\n );\n\nexport const useGetDictionariesKeys = (\n args?: UseAsyncOptions<IntlayerAPI['dictionary']['getDictionariesKeys']>\n) =>\n useAppAsync(\n 'getDictionariesKeys',\n useIntlayerOAuth().dictionary.getDictionariesKeys,\n {\n cache: true,\n store: true,\n retryLimit: 3,\n autoFetch: true,\n revalidation: true,\n revalidateTime: 5 * 60 * 1000, // 5 minutes\n ...args,\n },\n {\n requireUser: true,\n requireOrganization: true,\n requireProject: true,\n }\n );\n\nexport const useGetDictionary = (\n args?: UseAsyncOptions<IntlayerAPI['dictionary']['getDictionary']>\n) =>\n useAppAsync(\n 'getDictionary',\n useIntlayerOAuth().dictionary.getDictionary,\n {\n cache: true,\n store: true,\n retryLimit: 3,\n revalidation: true,\n revalidateTime: 5 * 60 * 1000, // 5 minutes\n ...args,\n },\n {\n requireUser: true,\n requireOrganization: true,\n requireProject: true,\n }\n );\n\nexport const useAddDictionary = (\n args?: UseAsyncOptions<IntlayerAPI['dictionary']['addDictionary']>\n) =>\n useAppAsync('addDictionary', useIntlayerOAuth().dictionary.addDictionary, {\n invalidateQueries: ['getDictionaries', 'getDictionariesKeys'],\n ...args,\n });\n\nexport const usePushDictionaries = (\n args?: UseAsyncOptions<IntlayerAPI['dictionary']['pushDictionaries']>\n) =>\n useAppAsync(\n 'pushDictionaries',\n useIntlayerOAuth().dictionary.pushDictionaries,\n {\n invalidateQueries: [\n 'getDictionaries',\n 'getDictionary',\n 'getDictionariesKeys',\n ],\n ...args,\n }\n );\n\nexport const useUpdateDictionary = (\n args?: UseAsyncOptions<IntlayerAPI['dictionary']['updateDictionary']>\n) =>\n useAppAsync(\n 'updateDictionary',\n useIntlayerOAuth().dictionary.updateDictionary,\n {\n invalidateQueries: ['getDictionaries', 'getDictionary'],\n ...args,\n }\n );\n\nexport const useDeleteDictionary = (\n args?: UseAsyncOptions<IntlayerAPI['dictionary']['deleteDictionary']>\n) =>\n useAppAsync(\n 'deleteDictionary',\n useIntlayerOAuth().dictionary.deleteDictionary,\n {\n invalidateQueries: [\n 'getDictionaries',\n 'getDictionary',\n 'getDictionariesKeys',\n ],\n ...args,\n }\n );\n\n/**\n * Tag\n */\n\nexport const useGetTags = (\n args?: UseAsyncOptions<IntlayerAPI['tag']['getTags']>\n) =>\n useAppAsync(\n 'getTags',\n useIntlayerOAuth().tag.getTags,\n {\n cache: true,\n store: true,\n retryLimit: 3,\n autoFetch: true,\n revalidation: true,\n revalidateTime: 5 * 60 * 1000, // 5 minutes\n ...args,\n },\n {\n requireUser: true,\n requireOrganization: true,\n }\n );\n\nexport const useAddTag = (\n args?: UseAsyncOptions<IntlayerAPI['tag']['addTag']>\n) =>\n useAppAsync('addTag', useIntlayerOAuth().tag.addTag, {\n invalidateQueries: ['getTags'],\n ...args,\n });\n\nexport const useUpdateTag = (\n args?: UseAsyncOptions<IntlayerAPI['tag']['updateTag']>\n) =>\n useAppAsync('updateTag', useIntlayerOAuth().tag.updateTag, {\n invalidateQueries: ['getTags'],\n ...args,\n });\n\nexport const useDeleteTag = (\n args?: UseAsyncOptions<IntlayerAPI['tag']['deleteTag']>\n) =>\n useAppAsync('deleteTag', useIntlayerOAuth().tag.deleteTag, {\n invalidateQueries: ['getTags'],\n ...args,\n });\n\n/**\n * Stripe\n */\n\nexport const useGetPricing = (\n args?: UseAsyncOptions<IntlayerAPI['stripe']['getPricing']>\n) =>\n useAppAsync('getPricing', useIntlayerOAuth().stripe.getPricing, {\n store: true,\n cache: true,\n ...args,\n });\n\nexport const useGetSubscription = (\n args?: UseAsyncOptions<IntlayerAPI['stripe']['getSubscription']>\n) =>\n useAppAsync(\n 'getSubscription',\n useIntlayerOAuth().stripe.getSubscription,\n args,\n {\n requireUser: true,\n requireOrganization: true,\n }\n );\n\nexport const useCancelSubscription = (\n args?: UseAsyncOptions<IntlayerAPI['stripe']['cancelSubscription']>\n) =>\n useAppAsync(\n 'cancelSubscription',\n useIntlayerOAuth().stripe.cancelSubscription,\n { invalidateQueries: ['getSession'], ...args },\n {\n requireUser: true,\n requireOrganization: true,\n }\n );\n\n/**\n * AI\n */\n\nexport const useTranslateJSONDeclaration = (\n args?: UseAsyncOptions<IntlayerAPI['ai']['translateJSON']>\n) =>\n useAppAsync('translateJSON', useIntlayerOAuth().ai.translateJSON, args, {\n requireUser: true,\n requireOrganization: true,\n requireProject: true,\n });\n\nexport const useAuditContentDeclaration = (\n args?: UseAsyncOptions<IntlayerAPI['ai']['auditContentDeclaration']>\n) =>\n useAppAsync(\n 'auditContentDeclaration',\n useIntlayerOAuth().ai.auditContentDeclaration,\n args,\n {\n requireUser: true,\n requireOrganization: true,\n requireProject: true,\n }\n );\n\nexport const useAuditContentDeclarationMetadata = (\n args?: UseAsyncOptions<IntlayerAPI['ai']['auditContentDeclarationMetadata']>\n) =>\n useAppAsync(\n 'auditContentDeclaration',\n useIntlayerOAuth().ai.auditContentDeclarationMetadata,\n args,\n {\n requireUser: true,\n requireOrganization: true,\n requireProject: true,\n }\n );\n\nexport const useAuditContentDeclarationField = (\n args?: UseAsyncOptions<IntlayerAPI['ai']['auditContentDeclarationField']>\n) =>\n useAppAsync(\n 'auditContentDeclarationField',\n useIntlayerOAuth().ai.auditContentDeclarationField,\n args,\n {\n requireUser: true,\n requireOrganization: true,\n requireProject: true,\n }\n );\n\nexport const useAuditTag = (\n args?: UseAsyncOptions<IntlayerAPI['ai']['auditTag']>\n) =>\n useAppAsync('auditTag', useIntlayerOAuth().ai.auditTag, args, {\n requireUser: true,\n requireOrganization: true,\n requireProject: true,\n });\n\nexport const useAskDocQuestion = (\n args?: UseAsyncOptions<IntlayerAPI['ai']['askDocQuestion']>\n) => useAppAsync('askDocQuestion', useIntlayerOAuth().ai.askDocQuestion, args);\n\nexport const useAutocomplete = (\n args?: UseAsyncOptions<IntlayerAPI['ai']['autocomplete']>\n) => useAppAsync('autocomplete', useIntlayerOAuth().ai.autocomplete, args);\n\n/**\n * Search\n */\n\nexport const useSearchDoc = (\n args?: UseAsyncOptions<IntlayerAPI['search']['searchDoc']>\n) => useAppAsync('searchDoc', useIntlayerOAuth().search.searchDoc, args);\n\n/**\n * Newsletter\n */\n\nexport const useSubscribeToNewsletter = (\n args?: UseAsyncOptions<IntlayerAPI['newsletter']['subscribeToNewsletter']>\n) =>\n useAppAsync(\n 'subscribeToNewsletter',\n useIntlayerOAuth().newsletter.subscribeToNewsletter,\n args\n );\n\nexport const useUnsubscribeFromNewsletter = (\n args?: UseAsyncOptions<IntlayerAPI['newsletter']['unsubscribeFromNewsletter']>\n) =>\n useAppAsync(\n 'unsubscribeFromNewsletter',\n useIntlayerOAuth().newsletter.unsubscribeFromNewsletter,\n args\n );\n\nexport const useGetNewsletterStatus = (\n args?: UseAsyncOptions<IntlayerAPI['newsletter']['getNewsletterStatus']>\n) =>\n useAppAsync(\n 'getNewsletterStatus',\n useIntlayerOAuth().newsletter.getNewsletterStatus,\n args\n );\n\n/**\n * Editor\n */\n\nexport const useWriteDictionary = (\n args?: UseAsyncOptions<IntlayerAPI['editor']['writeDictionary']>\n) =>\n useEditorAsync(\n 'writeDictionary',\n useIntlayerOAuth().editor.writeDictionary,\n args\n );\n\nexport const useGetEditorDictionaries = (\n args?: UseAsyncOptions<IntlayerAPI['editor']['getDictionaries']>\n) =>\n useEditorAsync('getDictionaries', useIntlayerOAuth().editor.getDictionaries, {\n store: true,\n cache: true,\n ...args,\n });\n"],"names":["useToast","error","useConfiguration","useAuth","useAsync","useIntlayerAuth","useIntlayerOAuth"],"mappings":";;;;;;;;;;;;;;;AAUA,MAAM,kBAAkB,CAAC,cAAsB,UAAU,MAAM,GAAG,EAAE,KAA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B,OAAO,iBAAiB;AAAA,EAC3E,OAAO;AAAA,EACP,OAAO;AAAA,EACP,GAAG;AACL,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"intlayerAPIHooks.mjs","sources":["../../src/hooks/intlayerAPIHooks.ts"],"sourcesContent":["'use client';\n\nimport type { IntlayerAPI } from '@intlayer/api';\nimport { useConfiguration } from '@intlayer/editor-react';\nimport { useToast } from '../components/Toaster';\nimport { getAuthAPI } from './auth';\nimport { type UseAsyncOptions, useAsync } from './useAsync/useAsync';\nimport { useAuth } from './useAuth';\nimport { useIntlayerAuth, useIntlayerOAuth } from './useIntlayerAPI';\n\nconst formatErrorCode = (errorCode: string) => errorCode.split('_').join(' ');\n\n/**\n * Hook to handle error logging and toast notifications\n */\nconst useErrorHandling = <T extends UseAsyncOptions<any>>(options: T): T => {\n const { toast } = useToast();\n\n return {\n ...options,\n onError: (errorMessage) => {\n let error;\n\n // If json is valid, parse it\n try {\n if (typeof errorMessage === 'undefined') return;\n\n error = JSON.parse(errorMessage);\n } catch (e) {\n // If json is not valid, set error to the original errorMessage\n\n error = errorMessage;\n }\n\n // render toast for each error if there is more than one\n // otherwise render the toast with the error message\n [error]\n .flatMap((error) => error)\n .forEach((error) =>\n toast({\n title: formatErrorCode(\n (process.env.NODE_ENV === 'production'\n ? error.title\n : error.code) ?? 'Error'\n ),\n description: error.message ?? errorMessage ?? 'An error occurred',\n variant: 'error',\n })\n );\n options.onError?.(errorMessage);\n },\n onSuccess: (data) => {\n if (data?.error) {\n toast({\n title: formatErrorCode(\n data.error.title ?? data.error.code ?? 'Error'\n ),\n description:\n data.error.message ?? data.error.code ?? 'An error occurred',\n variant: 'error',\n });\n }\n\n if (data?.message)\n toast({\n title: data.message,\n description: data.description,\n variant: 'success',\n });\n options.onSuccess?.(data);\n },\n };\n};\n\ntype AuthEnableOptions = {\n requireUser?: boolean;\n requireProject?: boolean;\n requireOrganization?: boolean;\n};\n\n/**\n * Hook to enable authentication\n */\nconst useAuthEnable = <T extends UseAsyncOptions<any>>(\n options: T,\n { requireUser, requireProject, requireOrganization }: AuthEnableOptions = {}\n): T => {\n const configuration = useConfiguration();\n const { oAuth2AccessToken, session } = useAuth({\n intlayerConfiguration: configuration,\n });\n\n const isEnabledOption = options?.enable ?? true;\n const user = session ? session.user : oAuth2AccessToken?.user;\n\n const organization = session\n ? session.organization\n : oAuth2AccessToken?.organization;\n\n const project = session ? session.project : oAuth2AccessToken?.project;\n\n const isUserEnabled = requireUser ? Boolean(user) : true;\n\n const isProjectEnabled = requireProject ? Boolean(project) : true;\n\n const isOrganizationEnabled = requireOrganization\n ? Boolean(organization)\n : true;\n\n const isEnabled =\n isEnabledOption &&\n isUserEnabled &&\n isProjectEnabled &&\n isOrganizationEnabled;\n\n return {\n ...options,\n enable: isEnabled,\n };\n};\n\nconst useAppAsync = <\n U extends string,\n T extends (...args: any[]) => Promise<any>,\n>(\n key: U,\n asyncFunction: T,\n options?: UseAsyncOptions<T>,\n authOptions?: AuthEnableOptions\n) => {\n // Enhance options using custom hooks\n const optionsWithAuth = useAuthEnable(options ?? {}, authOptions);\n\n const optionsWithErrorHandling = useErrorHandling(optionsWithAuth);\n\n // Call the main useAsync hook with enhanced options\n return useAsync(key, asyncFunction, optionsWithErrorHandling);\n};\n\nconst useEditorAsync = <\n U extends string,\n T extends (...args: any[]) => Promise<any>,\n>(\n key: U,\n asyncFunction: T,\n options?: UseAsyncOptions<T>\n) => {\n const optionsWithErrorHandling = useErrorHandling(options ?? {});\n\n // Call the main useAsync hook with enhanced options\n return useAsync(key, asyncFunction, optionsWithErrorHandling);\n};\n\n/**\n * Auth\n */\n\nexport const useLogin = (\n args?: UseAsyncOptions<ReturnType<typeof getAuthAPI>['signInEmail']>\n) =>\n useAppAsync('login', useIntlayerAuth().signInEmail, {\n invalidateQueries: ['getSession'],\n ...args,\n });\n\nexport const useGetVerifyEmailStatus = (\n args?: UseAsyncOptions<ReturnType<typeof getAuthAPI>['verifyEmailSession']>\n) =>\n useAppAsync(\n 'getVerifyEmailStatus',\n useIntlayerAuth().verifyEmailSession,\n args\n );\n\nexport const useRegister = (\n args?: UseAsyncOptions<ReturnType<typeof getAuthAPI>['signUpEmail']>\n) =>\n useAppAsync('register', useIntlayerAuth().signUpEmail, {\n invalidateQueries: ['getSession'],\n ...args,\n });\n\nexport const useLogout = (\n args?: UseAsyncOptions<ReturnType<typeof getAuthAPI>['signOut']>\n) =>\n useAppAsync('logout', useIntlayerAuth().signOut, {\n ...args,\n });\n\nexport const useChangePassword = (\n args?: UseAsyncOptions<ReturnType<typeof getAuthAPI>['changePasswordSession']>\n) =>\n useAppAsync('changePassword', useIntlayerAuth().changePasswordSession, args);\n\nexport const useAskResetPassword = (\n args?: UseAsyncOptions<\n ReturnType<typeof getAuthAPI>['requestPasswordResetSession']\n >\n) =>\n useAppAsync(\n 'askResetPassword',\n useIntlayerAuth().requestPasswordResetSession,\n args\n );\n\nexport const useResetPassword = (\n args?: UseAsyncOptions<ReturnType<typeof getAuthAPI>['resetPassword']>\n) => useAppAsync('resetPassword', useIntlayerAuth().resetPassword, args);\n\nexport const useVerifyEmail = (\n args?: UseAsyncOptions<ReturnType<typeof getAuthAPI>['verifyEmailSession']>\n) => useAppAsync('verifyEmail', useIntlayerAuth().verifyEmailSession, args);\n\nexport const useGetUserByAccount = (\n args?: UseAsyncOptions<ReturnType<typeof getAuthAPI>['accountInfo']>\n) => useAppAsync('getUserByAccount', useIntlayerAuth().accountInfo, args);\n\n/**\n * User\n */\n\nexport const useGetUsers = (\n args?: UseAsyncOptions<IntlayerAPI['user']['getUsers']>\n) =>\n useAppAsync(\n 'getUsers',\n useIntlayerOAuth().user.getUsers,\n {\n cache: true,\n store: true,\n retryLimit: 3,\n autoFetch: true,\n revalidateTime: 5 * 60 * 1000, // 5 minutes\n ...args,\n },\n {\n requireUser: true,\n }\n );\n\nexport const useCreateUser = (\n args?: UseAsyncOptions<ReturnType<typeof getAuthAPI>['updateUser']>\n) =>\n useAppAsync('createUser', useIntlayerAuth().updateUser, {\n invalidateQueries: ['getUsers'],\n ...args,\n });\n\nexport const useUpdateUser = (\n args?: UseAsyncOptions<IntlayerAPI['user']['updateUser']>\n) =>\n useAppAsync('updateUser', useIntlayerOAuth().user.updateUser, {\n invalidateQueries: ['getSession'],\n ...args,\n });\n\nexport const useDeleteUser = (\n args?: UseAsyncOptions<IntlayerAPI['user']['deleteUser']>\n) =>\n useAppAsync('deleteUser', useIntlayerOAuth().user.deleteUser, {\n invalidateQueries: ['getUsers'],\n ...args,\n });\n\n/**\n * Organization\n */\n\nexport const useGetOrganizations = (\n args?: UseAsyncOptions<IntlayerAPI['organization']['getOrganizations']>\n) =>\n useAppAsync(\n 'getOrganizations',\n useIntlayerOAuth().organization.getOrganizations,\n {\n cache: true,\n store: true,\n retryLimit: 3,\n autoFetch: true,\n revalidation: true,\n revalidateTime: 5 * 60 * 1000, // 5 minutes\n ...args,\n },\n {\n requireUser: true,\n }\n );\n\nexport const useAddOrganization = (\n args?: UseAsyncOptions<IntlayerAPI['organization']['addOrganization']>\n) =>\n useAppAsync(\n 'addOrganization',\n useIntlayerOAuth().organization.addOrganization,\n {\n invalidateQueries: ['getOrganizations'],\n ...args,\n }\n );\n\nexport const useUpdateOrganization = (\n args?: UseAsyncOptions<IntlayerAPI['organization']['updateOrganization']>\n) =>\n useAppAsync(\n 'updateOrganization',\n useIntlayerOAuth().organization.updateOrganization,\n {\n invalidateQueries: ['getSession'],\n ...args,\n }\n );\n\nexport const useUpdateOrganizationMembers = (\n args?: UseAsyncOptions<\n IntlayerAPI['organization']['updateOrganizationMembers']\n >\n) =>\n useAppAsync(\n 'updateOrganizationMembers',\n useIntlayerOAuth().organization.updateOrganizationMembers,\n {\n invalidateQueries: ['getOrganizations', 'getSession'],\n ...args,\n }\n );\n\nexport const useAddOrganizationMember = (\n args?: UseAsyncOptions<IntlayerAPI['organization']['addOrganizationMember']>\n) =>\n useAppAsync(\n 'addOrganizationMember',\n useIntlayerOAuth().organization.addOrganizationMember,\n {\n invalidateQueries: ['getOrganizations', 'getSession'],\n ...args,\n }\n );\n\nexport const useDeleteOrganization = (\n args?: UseAsyncOptions<IntlayerAPI['organization']['deleteOrganization']>\n) =>\n useAppAsync(\n 'deleteOrganization',\n useIntlayerOAuth().organization.deleteOrganization,\n {\n invalidateQueries: ['getOrganizations', 'getSession'],\n ...args,\n }\n );\n\nexport const useSelectOrganization = (\n args?: UseAsyncOptions<IntlayerAPI['organization']['selectOrganization']>\n) =>\n useAppAsync(\n 'selectOrganization',\n useIntlayerOAuth().organization.selectOrganization,\n {\n invalidateQueries: ['getSession'],\n ...args,\n }\n );\n\nexport const useUnselectOrganization = (\n args?: UseAsyncOptions<IntlayerAPI['organization']['unselectOrganization']>\n) =>\n useAppAsync(\n 'unselectOrganization',\n useIntlayerOAuth().organization.unselectOrganization,\n {\n invalidateQueries: ['getSession'],\n ...args,\n }\n );\n\n/**\n * Project\n */\n\nexport const useGetProjects = (\n args?: UseAsyncOptions<IntlayerAPI['project']['getProjects']>\n) =>\n useAppAsync(\n 'getProjects',\n useIntlayerOAuth().project.getProjects,\n {\n cache: true,\n store: true,\n retryLimit: 3,\n autoFetch: true,\n revalidation: true,\n revalidateTime: 5 * 60 * 1000, // 5 minutes\n ...args,\n },\n {\n requireUser: true,\n requireOrganization: true,\n }\n );\n\nexport const useAddProject = (\n args?: UseAsyncOptions<IntlayerAPI['project']['addProject']>\n) =>\n useAppAsync('addProject', useIntlayerOAuth().project.addProject, {\n invalidateQueries: ['getProjects'],\n ...args,\n });\n\nexport const useUpdateProject = (\n args?: UseAsyncOptions<IntlayerAPI['project']['updateProject']>\n) =>\n useAppAsync('updateProject', useIntlayerOAuth().project.updateProject, {\n invalidateQueries: ['getSession'],\n ...args,\n });\n\nexport const useUpdateProjectMembers = (\n args?: UseAsyncOptions<IntlayerAPI['project']['updateProjectMembers']>\n) =>\n useAppAsync(\n 'updateProjectMembers',\n useIntlayerOAuth().project.updateProjectMembers,\n {\n invalidateQueries: ['getSession'],\n ...args,\n }\n );\n\nexport const useDeleteProject = (\n args?: UseAsyncOptions<IntlayerAPI['project']['deleteProject']>\n) =>\n useAppAsync('deleteProject', useIntlayerOAuth().project.deleteProject, {\n invalidateQueries: ['getProjects', 'getSession'],\n ...args,\n });\n\nexport const useSelectProject = (\n args?: UseAsyncOptions<IntlayerAPI['project']['selectProject']>\n) =>\n useAppAsync('selectProject', useIntlayerOAuth().project.selectProject, {\n invalidateQueries: ['getSession'],\n ...args,\n });\n\nexport const useUnselectProject = (\n args?: UseAsyncOptions<IntlayerAPI['project']['unselectProject']>\n) =>\n useAppAsync('unselectProject', useIntlayerOAuth().project.unselectProject, {\n invalidateQueries: ['getSession'],\n ...args,\n });\n\nexport const useAddNewAccessKey = (\n args?: UseAsyncOptions<IntlayerAPI['project']['addNewAccessKey']>\n) =>\n useAppAsync('addNewAccessKey', useIntlayerOAuth().project.addNewAccessKey, {\n invalidateQueries: ['getSession'],\n ...args,\n });\n\nexport const useDeleteAccessKey = (\n args?: UseAsyncOptions<IntlayerAPI['project']['deleteAccessKey']>\n) =>\n useAppAsync('deleteAccessKey', useIntlayerOAuth().project.deleteAccessKey, {\n invalidateQueries: ['getSession'],\n ...args,\n });\n\nexport const useRefreshAccessKey = (\n args?: UseAsyncOptions<IntlayerAPI['project']['refreshAccessKey']>\n) =>\n useAppAsync('refreshAccessKey', useIntlayerOAuth().project.refreshAccessKey, {\n invalidateQueries: ['getSession'],\n ...args,\n });\n\n/**\n * Dictionary\n */\n\nexport const useGetDictionaries = (\n args?: UseAsyncOptions<IntlayerAPI['dictionary']['getDictionaries']>\n) =>\n useAppAsync(\n 'getDictionaries',\n useIntlayerOAuth().dictionary.getDictionaries,\n {\n cache: true,\n store: true,\n retryLimit: 3,\n autoFetch: true,\n revalidation: true,\n revalidateTime: 5 * 60 * 1000, // 5 minutes\n ...args,\n },\n {\n requireUser: true,\n requireOrganization: true,\n requireProject: true,\n }\n );\n\nexport const useGetDictionariesKeys = (\n args?: UseAsyncOptions<IntlayerAPI['dictionary']['getDictionariesKeys']>\n) =>\n useAppAsync(\n 'getDictionariesKeys',\n useIntlayerOAuth().dictionary.getDictionariesKeys,\n {\n cache: true,\n store: true,\n retryLimit: 3,\n autoFetch: true,\n revalidation: true,\n revalidateTime: 5 * 60 * 1000, // 5 minutes\n ...args,\n },\n {\n requireUser: true,\n requireOrganization: true,\n requireProject: true,\n }\n );\n\nexport const useGetDictionary = (\n args?: UseAsyncOptions<IntlayerAPI['dictionary']['getDictionary']>\n) =>\n useAppAsync(\n 'getDictionary',\n useIntlayerOAuth().dictionary.getDictionary,\n {\n cache: true,\n store: true,\n retryLimit: 3,\n revalidation: true,\n revalidateTime: 5 * 60 * 1000, // 5 minutes\n ...args,\n },\n {\n requireUser: true,\n requireOrganization: true,\n requireProject: true,\n }\n );\n\nexport const useAddDictionary = (\n args?: UseAsyncOptions<IntlayerAPI['dictionary']['addDictionary']>\n) =>\n useAppAsync('addDictionary', useIntlayerOAuth().dictionary.addDictionary, {\n invalidateQueries: ['getDictionaries', 'getDictionariesKeys'],\n ...args,\n });\n\nexport const usePushDictionaries = (\n args?: UseAsyncOptions<IntlayerAPI['dictionary']['pushDictionaries']>\n) =>\n useAppAsync(\n 'pushDictionaries',\n useIntlayerOAuth().dictionary.pushDictionaries,\n {\n invalidateQueries: [\n 'getDictionaries',\n 'getDictionary',\n 'getDictionariesKeys',\n ],\n ...args,\n }\n );\n\nexport const useUpdateDictionary = (\n args?: UseAsyncOptions<IntlayerAPI['dictionary']['updateDictionary']>\n) =>\n useAppAsync(\n 'updateDictionary',\n useIntlayerOAuth().dictionary.updateDictionary,\n {\n invalidateQueries: ['getDictionaries', 'getDictionary'],\n ...args,\n }\n );\n\nexport const useDeleteDictionary = (\n args?: UseAsyncOptions<IntlayerAPI['dictionary']['deleteDictionary']>\n) =>\n useAppAsync(\n 'deleteDictionary',\n useIntlayerOAuth().dictionary.deleteDictionary,\n {\n invalidateQueries: [\n 'getDictionaries',\n 'getDictionary',\n 'getDictionariesKeys',\n ],\n ...args,\n }\n );\n\n/**\n * Tag\n */\n\nexport const useGetTags = (\n args?: UseAsyncOptions<IntlayerAPI['tag']['getTags']>\n) =>\n useAppAsync(\n 'getTags',\n useIntlayerOAuth().tag.getTags,\n {\n cache: true,\n store: true,\n retryLimit: 3,\n autoFetch: true,\n revalidation: true,\n revalidateTime: 5 * 60 * 1000, // 5 minutes\n ...args,\n },\n {\n requireUser: true,\n requireOrganization: true,\n }\n );\n\nexport const useAddTag = (\n args?: UseAsyncOptions<IntlayerAPI['tag']['addTag']>\n) =>\n useAppAsync('addTag', useIntlayerOAuth().tag.addTag, {\n invalidateQueries: ['getTags'],\n ...args,\n });\n\nexport const useUpdateTag = (\n args?: UseAsyncOptions<IntlayerAPI['tag']['updateTag']>\n) =>\n useAppAsync('updateTag', useIntlayerOAuth().tag.updateTag, {\n invalidateQueries: ['getTags'],\n ...args,\n });\n\nexport const useDeleteTag = (\n args?: UseAsyncOptions<IntlayerAPI['tag']['deleteTag']>\n) =>\n useAppAsync('deleteTag', useIntlayerOAuth().tag.deleteTag, {\n invalidateQueries: ['getTags'],\n ...args,\n });\n\n/**\n * Stripe\n */\n\nexport const useGetPricing = (\n args?: UseAsyncOptions<IntlayerAPI['stripe']['getPricing']>\n) =>\n useAppAsync('getPricing', useIntlayerOAuth().stripe.getPricing, {\n store: true,\n cache: true,\n ...args,\n });\n\nexport const useGetSubscription = (\n args?: UseAsyncOptions<IntlayerAPI['stripe']['getSubscription']>\n) =>\n useAppAsync(\n 'getSubscription',\n useIntlayerOAuth().stripe.getSubscription,\n args,\n {\n requireUser: true,\n requireOrganization: true,\n }\n );\n\nexport const useCancelSubscription = (\n args?: UseAsyncOptions<IntlayerAPI['stripe']['cancelSubscription']>\n) =>\n useAppAsync(\n 'cancelSubscription',\n useIntlayerOAuth().stripe.cancelSubscription,\n { invalidateQueries: ['getSession'], ...args },\n {\n requireUser: true,\n requireOrganization: true,\n }\n );\n\n/**\n * AI\n */\n\nexport const useTranslateJSONDeclaration = (\n args?: UseAsyncOptions<IntlayerAPI['ai']['translateJSON']>\n) =>\n useAppAsync('translateJSON', useIntlayerOAuth().ai.translateJSON, args, {\n requireUser: true,\n requireOrganization: true,\n requireProject: true,\n });\n\nexport const useAuditContentDeclaration = (\n args?: UseAsyncOptions<IntlayerAPI['ai']['auditContentDeclaration']>\n) =>\n useAppAsync(\n 'auditContentDeclaration',\n useIntlayerOAuth().ai.auditContentDeclaration,\n args,\n {\n requireUser: true,\n requireOrganization: true,\n requireProject: true,\n }\n );\n\nexport const useAuditContentDeclarationMetadata = (\n args?: UseAsyncOptions<IntlayerAPI['ai']['auditContentDeclarationMetadata']>\n) =>\n useAppAsync(\n 'auditContentDeclaration',\n useIntlayerOAuth().ai.auditContentDeclarationMetadata,\n args,\n {\n requireUser: true,\n requireOrganization: true,\n requireProject: true,\n }\n );\n\nexport const useAuditContentDeclarationField = (\n args?: UseAsyncOptions<IntlayerAPI['ai']['auditContentDeclarationField']>\n) =>\n useAppAsync(\n 'auditContentDeclarationField',\n useIntlayerOAuth().ai.auditContentDeclarationField,\n args,\n {\n requireUser: true,\n requireOrganization: true,\n requireProject: true,\n }\n );\n\nexport const useAuditTag = (\n args?: UseAsyncOptions<IntlayerAPI['ai']['auditTag']>\n) =>\n useAppAsync('auditTag', useIntlayerOAuth().ai.auditTag, args, {\n requireUser: true,\n requireOrganization: true,\n requireProject: true,\n });\n\nexport const useAskDocQuestion = (\n args?: UseAsyncOptions<IntlayerAPI['ai']['askDocQuestion']>\n) => useAppAsync('askDocQuestion', useIntlayerOAuth().ai.askDocQuestion, args);\n\nexport const useAutocomplete = (\n args?: UseAsyncOptions<IntlayerAPI['ai']['autocomplete']>\n) => useAppAsync('autocomplete', useIntlayerOAuth().ai.autocomplete, args);\n\n/**\n * Search\n */\n\nexport const useSearchDoc = (\n args?: UseAsyncOptions<IntlayerAPI['search']['searchDoc']>\n) => useAppAsync('searchDoc', useIntlayerOAuth().search.searchDoc, args);\n\n/**\n * Newsletter\n */\n\nexport const useSubscribeToNewsletter = (\n args?: UseAsyncOptions<IntlayerAPI['newsletter']['subscribeToNewsletter']>\n) =>\n useAppAsync(\n 'subscribeToNewsletter',\n useIntlayerOAuth().newsletter.subscribeToNewsletter,\n args\n );\n\nexport const useUnsubscribeFromNewsletter = (\n args?: UseAsyncOptions<IntlayerAPI['newsletter']['unsubscribeFromNewsletter']>\n) =>\n useAppAsync(\n 'unsubscribeFromNewsletter',\n useIntlayerOAuth().newsletter.unsubscribeFromNewsletter,\n args\n );\n\nexport const useGetNewsletterStatus = (\n args?: UseAsyncOptions<IntlayerAPI['newsletter']['getNewsletterStatus']>\n) =>\n useAppAsync(\n 'getNewsletterStatus',\n useIntlayerOAuth().newsletter.getNewsletterStatus,\n args\n );\n\n/**\n * Editor\n */\n\nexport const useWriteDictionary = (\n args?: UseAsyncOptions<IntlayerAPI['editor']['writeDictionary']>\n) =>\n useEditorAsync(\n 'writeDictionary',\n useIntlayerOAuth().editor.writeDictionary,\n args\n );\n\nexport const useGetEditorDictionaries = (\n args?: UseAsyncOptions<IntlayerAPI['editor']['getDictionaries']>\n) =>\n useEditorAsync('getDictionaries', useIntlayerOAuth().editor.getDictionaries, {\n store: true,\n cache: true,\n ...args,\n });\n"],"names":["error"],"mappings":";;;;;;;;;;;;;AAUA,MAAM,kBAAkB,CAAC,cAAsB,UAAU,MAAM,GAAG,EAAE,KAAK,GAAG;AAK5E,MAAM,mBAAmB,CAAiC,YAAkB;AACpE,QAAA,EAAE,MAAM,IAAI,SAAS;AAEpB,SAAA;AAAA,IACL,GAAG;AAAA,IACH,SAAS,CAAC,iBAAiB;AACrB,UAAA;AAGA,UAAA;AACE,YAAA,OAAO,iBAAiB,YAAa;AAEjC,gBAAA,KAAK,MAAM,YAAY;AAAA,eACxB,GAAG;AAGF,gBAAA;AAAA,MAAA;AAK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,aAAa,mBAAmB,OAAO,WAAW,IAAI;AAM1D,MAAA,2BAA2B,CACtC,SAEA;AAAA,EACE;AAAA,EACA,iBAAA,EAAmB,WAAW;AAAA,EAC9B;AACF;AAEW,MAAA,+BAA+B,CAC1C,SAEA;AAAA,EACE;AAAA,EACA,iBAAA,EAAmB,WAAW;AAAA,EAC9B;AACF;AAEW,MAAA,yBAAyB,CACpC,SAEA;AAAA,EACE;AAAA,EACA,iBAAA,EAAmB,WAAW;AAAA,EAC9B;AACF;AAMW,MAAA,qBAAqB,CAChC,SAEA;AAAA,EACE;AAAA,EACA,iBAAA,EAAmB,OAAO;AAAA,EAC1B;AACF;AAEW,MAAA,2BAA2B,CACtC,SAEA,eAAe,mBAAmB,iBAAiB,EAAE,OAAO,iBAAiB;AAAA,EAC3E,OAAO;AAAA,EACP,OAAO;AAAA,EACP,GAAG;AACL,CAAC;"}
|
|
1
|
+
{"version":3,"file":"intlayerAPIHooks.mjs","sources":["../../src/hooks/intlayerAPIHooks.ts"],"sourcesContent":["'use client';\n\nimport type { IntlayerAPI } from '@intlayer/api';\nimport { useConfiguration } from '@intlayer/editor-react';\nimport { useToast } from '../components/Toaster';\nimport { getAuthAPI } from './auth';\nimport { type UseAsyncOptions, useAsync } from './useAsync/useAsync';\nimport { useAuth } from './useAuth';\nimport { useIntlayerAuth, useIntlayerOAuth } from './useIntlayerAPI';\n\nconst formatErrorCode = (errorCode: string) => errorCode.split('_').join(' ');\n\n/**\n * Hook to handle error logging and toast notifications\n */\nconst useErrorHandling = <T extends UseAsyncOptions<any>>(options: T): T => {\n const { toast } = useToast();\n\n return {\n ...options,\n onError: (errorMessage) => {\n let error;\n\n // If json is valid, parse it\n try {\n if (typeof errorMessage === 'undefined') return;\n\n error = JSON.parse(errorMessage);\n } catch (e) {\n // If json is not valid, set error to the original errorMessage\n\n error = errorMessage;\n }\n\n // render toast for each error if there is more than one\n // otherwise render the toast with the error message\n [error]\n .flatMap((error) => error)\n .forEach((error) =>\n toast({\n title: formatErrorCode(\n (process.env.NODE_ENV === 'production'\n ? error.title\n : error.code) ?? 'Error'\n ),\n description: error.message ?? errorMessage ?? 'An error occurred',\n variant: 'error',\n })\n );\n options.onError?.(errorMessage);\n },\n onSuccess: (data) => {\n if (data?.error) {\n toast({\n title: formatErrorCode(\n data.error.title ?? data.error.code ?? 'Error'\n ),\n description:\n data.error.message ?? data.error.code ?? 'An error occurred',\n variant: 'error',\n });\n }\n\n if (data?.message)\n toast({\n title: data.message,\n description: data.description,\n variant: 'success',\n });\n options.onSuccess?.(data);\n },\n };\n};\n\ntype AuthEnableOptions = {\n requireUser?: boolean;\n requireProject?: boolean;\n requireOrganization?: boolean;\n};\n\n/**\n * Hook to enable authentication\n */\nconst useAuthEnable = <T extends UseAsyncOptions<any>>(\n options: T,\n { requireUser, requireProject, requireOrganization }: AuthEnableOptions = {}\n): T => {\n const configuration = useConfiguration();\n const { oAuth2AccessToken, session } = useAuth({\n intlayerConfiguration: configuration,\n });\n\n const isEnabledOption = options?.enable ?? true;\n const user = session ? session.user : oAuth2AccessToken?.user;\n\n const organization = session\n ? session.organization\n : oAuth2AccessToken?.organization;\n\n const project = session ? session.project : oAuth2AccessToken?.project;\n\n const isUserEnabled = requireUser ? Boolean(user) : true;\n\n const isProjectEnabled = requireProject ? Boolean(project) : true;\n\n const isOrganizationEnabled = requireOrganization\n ? Boolean(organization)\n : true;\n\n const isEnabled =\n isEnabledOption &&\n isUserEnabled &&\n isProjectEnabled &&\n isOrganizationEnabled;\n\n return {\n ...options,\n enable: isEnabled,\n };\n};\n\nconst useAppAsync = <\n U extends string,\n T extends (...args: any[]) => Promise<any>,\n>(\n key: U,\n asyncFunction: T,\n options?: UseAsyncOptions<T>,\n authOptions?: AuthEnableOptions\n) => {\n // Enhance options using custom hooks\n const optionsWithAuth = useAuthEnable(options ?? {}, authOptions);\n\n const optionsWithErrorHandling = useErrorHandling(optionsWithAuth);\n\n // Call the main useAsync hook with enhanced options\n return useAsync(key, asyncFunction, optionsWithErrorHandling);\n};\n\nconst useEditorAsync = <\n U extends string,\n T extends (...args: any[]) => Promise<any>,\n>(\n key: U,\n asyncFunction: T,\n options?: UseAsyncOptions<T>\n) => {\n const optionsWithErrorHandling = useErrorHandling(options ?? {});\n\n // Call the main useAsync hook with enhanced options\n return useAsync(key, asyncFunction, optionsWithErrorHandling);\n};\n\n/**\n * Auth\n */\n\nexport const useLogin = (\n args?: UseAsyncOptions<ReturnType<typeof getAuthAPI>['signInEmail']>\n) =>\n useAppAsync('login', useIntlayerAuth().signInEmail, {\n invalidateQueries: ['getSession'],\n ...args,\n });\n\nexport const useGetVerifyEmailStatus = (\n args?: UseAsyncOptions<ReturnType<typeof getAuthAPI>['verifyEmailSession']>\n) =>\n useAppAsync(\n 'getVerifyEmailStatus',\n useIntlayerAuth().verifyEmailSession,\n args\n );\n\nexport const useRegister = (\n args?: UseAsyncOptions<ReturnType<typeof getAuthAPI>['signUpEmail']>\n) =>\n useAppAsync('register', useIntlayerAuth().signUpEmail, {\n invalidateQueries: ['getSession'],\n ...args,\n });\n\nexport const useLogout = (\n args?: UseAsyncOptions<ReturnType<typeof getAuthAPI>['signOut']>\n) =>\n useAppAsync('logout', useIntlayerAuth().signOut, {\n ...args,\n });\n\nexport const useChangePassword = (\n args?: UseAsyncOptions<ReturnType<typeof getAuthAPI>['changePasswordSession']>\n) =>\n useAppAsync('changePassword', useIntlayerAuth().changePasswordSession, args);\n\nexport const useAskResetPassword = (\n args?: UseAsyncOptions<\n ReturnType<typeof getAuthAPI>['requestPasswordResetSession']\n >\n) =>\n useAppAsync(\n 'askResetPassword',\n useIntlayerAuth().requestPasswordResetSession,\n args\n );\n\nexport const useResetPassword = (\n args?: UseAsyncOptions<ReturnType<typeof getAuthAPI>['resetPassword']>\n) => useAppAsync('resetPassword', useIntlayerAuth().resetPassword, args);\n\nexport const useVerifyEmail = (\n args?: UseAsyncOptions<ReturnType<typeof getAuthAPI>['verifyEmailSession']>\n) => useAppAsync('verifyEmail', useIntlayerAuth().verifyEmailSession, args);\n\nexport const useGetUserByAccount = (\n args?: UseAsyncOptions<ReturnType<typeof getAuthAPI>['accountInfo']>\n) => useAppAsync('getUserByAccount', useIntlayerAuth().accountInfo, args);\n\n/**\n * User\n */\n\nexport const useGetUsers = (\n args?: UseAsyncOptions<IntlayerAPI['user']['getUsers']>\n) =>\n useAppAsync(\n 'getUsers',\n useIntlayerOAuth().user.getUsers,\n {\n cache: true,\n store: true,\n retryLimit: 3,\n autoFetch: true,\n revalidateTime: 5 * 60 * 1000, // 5 minutes\n ...args,\n },\n {\n requireUser: true,\n }\n );\n\nexport const useCreateUser = (\n args?: UseAsyncOptions<ReturnType<typeof getAuthAPI>['updateUser']>\n) =>\n useAppAsync('createUser', useIntlayerAuth().updateUser, {\n invalidateQueries: ['getUsers'],\n ...args,\n });\n\nexport const useUpdateUser = (\n args?: UseAsyncOptions<IntlayerAPI['user']['updateUser']>\n) =>\n useAppAsync('updateUser', useIntlayerOAuth().user.updateUser, {\n invalidateQueries: ['getSession'],\n ...args,\n });\n\nexport const useDeleteUser = (\n args?: UseAsyncOptions<IntlayerAPI['user']['deleteUser']>\n) =>\n useAppAsync('deleteUser', useIntlayerOAuth().user.deleteUser, {\n invalidateQueries: ['getUsers'],\n ...args,\n });\n\n/**\n * Organization\n */\n\nexport const useGetOrganizations = (\n args?: UseAsyncOptions<IntlayerAPI['organization']['getOrganizations']>\n) =>\n useAppAsync(\n 'getOrganizations',\n useIntlayerOAuth().organization.getOrganizations,\n {\n cache: true,\n store: true,\n retryLimit: 3,\n autoFetch: true,\n revalidation: true,\n revalidateTime: 5 * 60 * 1000, // 5 minutes\n ...args,\n },\n {\n requireUser: true,\n }\n );\n\nexport const useAddOrganization = (\n args?: UseAsyncOptions<IntlayerAPI['organization']['addOrganization']>\n) =>\n useAppAsync(\n 'addOrganization',\n useIntlayerOAuth().organization.addOrganization,\n {\n invalidateQueries: ['getOrganizations'],\n ...args,\n }\n );\n\nexport const useUpdateOrganization = (\n args?: UseAsyncOptions<IntlayerAPI['organization']['updateOrganization']>\n) =>\n useAppAsync(\n 'updateOrganization',\n useIntlayerOAuth().organization.updateOrganization,\n {\n invalidateQueries: ['getSession'],\n ...args,\n }\n );\n\nexport const useUpdateOrganizationMembers = (\n args?: UseAsyncOptions<\n IntlayerAPI['organization']['updateOrganizationMembers']\n >\n) =>\n useAppAsync(\n 'updateOrganizationMembers',\n useIntlayerOAuth().organization.updateOrganizationMembers,\n {\n invalidateQueries: ['getOrganizations', 'getSession'],\n ...args,\n }\n );\n\nexport const useAddOrganizationMember = (\n args?: UseAsyncOptions<IntlayerAPI['organization']['addOrganizationMember']>\n) =>\n useAppAsync(\n 'addOrganizationMember',\n useIntlayerOAuth().organization.addOrganizationMember,\n {\n invalidateQueries: ['getOrganizations', 'getSession'],\n ...args,\n }\n );\n\nexport const useDeleteOrganization = (\n args?: UseAsyncOptions<IntlayerAPI['organization']['deleteOrganization']>\n) =>\n useAppAsync(\n 'deleteOrganization',\n useIntlayerOAuth().organization.deleteOrganization,\n {\n invalidateQueries: ['getOrganizations', 'getSession'],\n ...args,\n }\n );\n\nexport const useSelectOrganization = (\n args?: UseAsyncOptions<IntlayerAPI['organization']['selectOrganization']>\n) =>\n useAppAsync(\n 'selectOrganization',\n useIntlayerOAuth().organization.selectOrganization,\n {\n invalidateQueries: ['getSession'],\n ...args,\n }\n );\n\nexport const useUnselectOrganization = (\n args?: UseAsyncOptions<IntlayerAPI['organization']['unselectOrganization']>\n) =>\n useAppAsync(\n 'unselectOrganization',\n useIntlayerOAuth().organization.unselectOrganization,\n {\n invalidateQueries: ['getSession'],\n ...args,\n }\n );\n\n/**\n * Project\n */\n\nexport const useGetProjects = (\n args?: UseAsyncOptions<IntlayerAPI['project']['getProjects']>\n) =>\n useAppAsync(\n 'getProjects',\n useIntlayerOAuth().project.getProjects,\n {\n cache: true,\n store: true,\n retryLimit: 3,\n autoFetch: true,\n revalidation: true,\n revalidateTime: 5 * 60 * 1000, // 5 minutes\n ...args,\n },\n {\n requireUser: true,\n requireOrganization: true,\n }\n );\n\nexport const useAddProject = (\n args?: UseAsyncOptions<IntlayerAPI['project']['addProject']>\n) =>\n useAppAsync('addProject', useIntlayerOAuth().project.addProject, {\n invalidateQueries: ['getProjects'],\n ...args,\n });\n\nexport const useUpdateProject = (\n args?: UseAsyncOptions<IntlayerAPI['project']['updateProject']>\n) =>\n useAppAsync('updateProject', useIntlayerOAuth().project.updateProject, {\n invalidateQueries: ['getSession'],\n ...args,\n });\n\nexport const useUpdateProjectMembers = (\n args?: UseAsyncOptions<IntlayerAPI['project']['updateProjectMembers']>\n) =>\n useAppAsync(\n 'updateProjectMembers',\n useIntlayerOAuth().project.updateProjectMembers,\n {\n invalidateQueries: ['getSession'],\n ...args,\n }\n );\n\nexport const useDeleteProject = (\n args?: UseAsyncOptions<IntlayerAPI['project']['deleteProject']>\n) =>\n useAppAsync('deleteProject', useIntlayerOAuth().project.deleteProject, {\n invalidateQueries: ['getProjects', 'getSession'],\n ...args,\n });\n\nexport const useSelectProject = (\n args?: UseAsyncOptions<IntlayerAPI['project']['selectProject']>\n) =>\n useAppAsync('selectProject', useIntlayerOAuth().project.selectProject, {\n invalidateQueries: ['getSession'],\n ...args,\n });\n\nexport const useUnselectProject = (\n args?: UseAsyncOptions<IntlayerAPI['project']['unselectProject']>\n) =>\n useAppAsync('unselectProject', useIntlayerOAuth().project.unselectProject, {\n invalidateQueries: ['getSession'],\n ...args,\n });\n\nexport const useAddNewAccessKey = (\n args?: UseAsyncOptions<IntlayerAPI['project']['addNewAccessKey']>\n) =>\n useAppAsync('addNewAccessKey', useIntlayerOAuth().project.addNewAccessKey, {\n invalidateQueries: ['getSession'],\n ...args,\n });\n\nexport const useDeleteAccessKey = (\n args?: UseAsyncOptions<IntlayerAPI['project']['deleteAccessKey']>\n) =>\n useAppAsync('deleteAccessKey', useIntlayerOAuth().project.deleteAccessKey, {\n invalidateQueries: ['getSession'],\n ...args,\n });\n\nexport const useRefreshAccessKey = (\n args?: UseAsyncOptions<IntlayerAPI['project']['refreshAccessKey']>\n) =>\n useAppAsync('refreshAccessKey', useIntlayerOAuth().project.refreshAccessKey, {\n invalidateQueries: ['getSession'],\n ...args,\n });\n\n/**\n * Dictionary\n */\n\nexport const useGetDictionaries = (\n args?: UseAsyncOptions<IntlayerAPI['dictionary']['getDictionaries']>\n) =>\n useAppAsync(\n 'getDictionaries',\n useIntlayerOAuth().dictionary.getDictionaries,\n {\n cache: true,\n store: true,\n retryLimit: 3,\n autoFetch: true,\n revalidation: true,\n revalidateTime: 5 * 60 * 1000, // 5 minutes\n ...args,\n },\n {\n requireUser: true,\n requireOrganization: true,\n requireProject: true,\n }\n );\n\nexport const useGetDictionariesKeys = (\n args?: UseAsyncOptions<IntlayerAPI['dictionary']['getDictionariesKeys']>\n) =>\n useAppAsync(\n 'getDictionariesKeys',\n useIntlayerOAuth().dictionary.getDictionariesKeys,\n {\n cache: true,\n store: true,\n retryLimit: 3,\n autoFetch: true,\n revalidation: true,\n revalidateTime: 5 * 60 * 1000, // 5 minutes\n ...args,\n },\n {\n requireUser: true,\n requireOrganization: true,\n requireProject: true,\n }\n );\n\nexport const useGetDictionary = (\n args?: UseAsyncOptions<IntlayerAPI['dictionary']['getDictionary']>\n) =>\n useAppAsync(\n 'getDictionary',\n useIntlayerOAuth().dictionary.getDictionary,\n {\n cache: true,\n store: true,\n retryLimit: 3,\n revalidation: true,\n revalidateTime: 5 * 60 * 1000, // 5 minutes\n ...args,\n },\n {\n requireUser: true,\n requireOrganization: true,\n requireProject: true,\n }\n );\n\nexport const useAddDictionary = (\n args?: UseAsyncOptions<IntlayerAPI['dictionary']['addDictionary']>\n) =>\n useAppAsync('addDictionary', useIntlayerOAuth().dictionary.addDictionary, {\n invalidateQueries: ['getDictionaries', 'getDictionariesKeys'],\n ...args,\n });\n\nexport const usePushDictionaries = (\n args?: UseAsyncOptions<IntlayerAPI['dictionary']['pushDictionaries']>\n) =>\n useAppAsync(\n 'pushDictionaries',\n useIntlayerOAuth().dictionary.pushDictionaries,\n {\n invalidateQueries: [\n 'getDictionaries',\n 'getDictionary',\n 'getDictionariesKeys',\n ],\n ...args,\n }\n );\n\nexport const useUpdateDictionary = (\n args?: UseAsyncOptions<IntlayerAPI['dictionary']['updateDictionary']>\n) =>\n useAppAsync(\n 'updateDictionary',\n useIntlayerOAuth().dictionary.updateDictionary,\n {\n invalidateQueries: ['getDictionaries', 'getDictionary'],\n ...args,\n }\n );\n\nexport const useDeleteDictionary = (\n args?: UseAsyncOptions<IntlayerAPI['dictionary']['deleteDictionary']>\n) =>\n useAppAsync(\n 'deleteDictionary',\n useIntlayerOAuth().dictionary.deleteDictionary,\n {\n invalidateQueries: [\n 'getDictionaries',\n 'getDictionary',\n 'getDictionariesKeys',\n ],\n ...args,\n }\n );\n\n/**\n * Tag\n */\n\nexport const useGetTags = (\n args?: UseAsyncOptions<IntlayerAPI['tag']['getTags']>\n) =>\n useAppAsync(\n 'getTags',\n useIntlayerOAuth().tag.getTags,\n {\n cache: true,\n store: true,\n retryLimit: 3,\n autoFetch: true,\n revalidation: true,\n revalidateTime: 5 * 60 * 1000, // 5 minutes\n ...args,\n },\n {\n requireUser: true,\n requireOrganization: true,\n }\n );\n\nexport const useAddTag = (\n args?: UseAsyncOptions<IntlayerAPI['tag']['addTag']>\n) =>\n useAppAsync('addTag', useIntlayerOAuth().tag.addTag, {\n invalidateQueries: ['getTags'],\n ...args,\n });\n\nexport const useUpdateTag = (\n args?: UseAsyncOptions<IntlayerAPI['tag']['updateTag']>\n) =>\n useAppAsync('updateTag', useIntlayerOAuth().tag.updateTag, {\n invalidateQueries: ['getTags'],\n ...args,\n });\n\nexport const useDeleteTag = (\n args?: UseAsyncOptions<IntlayerAPI['tag']['deleteTag']>\n) =>\n useAppAsync('deleteTag', useIntlayerOAuth().tag.deleteTag, {\n invalidateQueries: ['getTags'],\n ...args,\n });\n\n/**\n * Stripe\n */\n\nexport const useGetPricing = (\n args?: UseAsyncOptions<IntlayerAPI['stripe']['getPricing']>\n) =>\n useAppAsync('getPricing', useIntlayerOAuth().stripe.getPricing, {\n store: true,\n cache: true,\n ...args,\n });\n\nexport const useGetSubscription = (\n args?: UseAsyncOptions<IntlayerAPI['stripe']['getSubscription']>\n) =>\n useAppAsync(\n 'getSubscription',\n useIntlayerOAuth().stripe.getSubscription,\n args,\n {\n requireUser: true,\n requireOrganization: true,\n }\n );\n\nexport const useCancelSubscription = (\n args?: UseAsyncOptions<IntlayerAPI['stripe']['cancelSubscription']>\n) =>\n useAppAsync(\n 'cancelSubscription',\n useIntlayerOAuth().stripe.cancelSubscription,\n { invalidateQueries: ['getSession'], ...args },\n {\n requireUser: true,\n requireOrganization: true,\n }\n );\n\n/**\n * AI\n */\n\nexport const useTranslateJSONDeclaration = (\n args?: UseAsyncOptions<IntlayerAPI['ai']['translateJSON']>\n) =>\n useAppAsync('translateJSON', useIntlayerOAuth().ai.translateJSON, args, {\n requireUser: true,\n requireOrganization: true,\n requireProject: true,\n });\n\nexport const useAuditContentDeclaration = (\n args?: UseAsyncOptions<IntlayerAPI['ai']['auditContentDeclaration']>\n) =>\n useAppAsync(\n 'auditContentDeclaration',\n useIntlayerOAuth().ai.auditContentDeclaration,\n args,\n {\n requireUser: true,\n requireOrganization: true,\n requireProject: true,\n }\n );\n\nexport const useAuditContentDeclarationMetadata = (\n args?: UseAsyncOptions<IntlayerAPI['ai']['auditContentDeclarationMetadata']>\n) =>\n useAppAsync(\n 'auditContentDeclaration',\n useIntlayerOAuth().ai.auditContentDeclarationMetadata,\n args,\n {\n requireUser: true,\n requireOrganization: true,\n requireProject: true,\n }\n );\n\nexport const useAuditContentDeclarationField = (\n args?: UseAsyncOptions<IntlayerAPI['ai']['auditContentDeclarationField']>\n) =>\n useAppAsync(\n 'auditContentDeclarationField',\n useIntlayerOAuth().ai.auditContentDeclarationField,\n args,\n {\n requireUser: true,\n requireOrganization: true,\n requireProject: true,\n }\n );\n\nexport const useAuditTag = (\n args?: UseAsyncOptions<IntlayerAPI['ai']['auditTag']>\n) =>\n useAppAsync('auditTag', useIntlayerOAuth().ai.auditTag, args, {\n requireUser: true,\n requireOrganization: true,\n requireProject: true,\n });\n\nexport const useAskDocQuestion = (\n args?: UseAsyncOptions<IntlayerAPI['ai']['askDocQuestion']>\n) => useAppAsync('askDocQuestion', useIntlayerOAuth().ai.askDocQuestion, args);\n\nexport const useAutocomplete = (\n args?: UseAsyncOptions<IntlayerAPI['ai']['autocomplete']>\n) => useAppAsync('autocomplete', useIntlayerOAuth().ai.autocomplete, args);\n\n/**\n * Search\n */\n\nexport const useSearchDoc = (\n args?: UseAsyncOptions<IntlayerAPI['search']['searchDoc']>\n) => useAppAsync('searchDoc', useIntlayerOAuth().search.searchDoc, args);\n\n/**\n * Newsletter\n */\n\nexport const useSubscribeToNewsletter = (\n args?: UseAsyncOptions<IntlayerAPI['newsletter']['subscribeToNewsletter']>\n) =>\n useAppAsync(\n 'subscribeToNewsletter',\n useIntlayerOAuth().newsletter.subscribeToNewsletter,\n args\n );\n\nexport const useUnsubscribeFromNewsletter = (\n args?: UseAsyncOptions<IntlayerAPI['newsletter']['unsubscribeFromNewsletter']>\n) =>\n useAppAsync(\n 'unsubscribeFromNewsletter',\n useIntlayerOAuth().newsletter.unsubscribeFromNewsletter,\n args\n );\n\nexport const useGetNewsletterStatus = (\n args?: UseAsyncOptions<IntlayerAPI['newsletter']['getNewsletterStatus']>\n) =>\n useAppAsync(\n 'getNewsletterStatus',\n useIntlayerOAuth().newsletter.getNewsletterStatus,\n args\n );\n\n/**\n * Editor\n */\n\nexport const useWriteDictionary = (\n args?: UseAsyncOptions<IntlayerAPI['editor']['writeDictionary']>\n) =>\n useEditorAsync(\n 'writeDictionary',\n useIntlayerOAuth().editor.writeDictionary,\n args\n );\n\nexport const useGetEditorDictionaries = (\n args?: UseAsyncOptions<IntlayerAPI['editor']['getDictionaries']>\n) =>\n useEditorAsync('getDictionaries', useIntlayerOAuth().editor.getDictionaries, {\n store: true,\n cache: true,\n ...args,\n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AAA,EACtB;AAAA,EACA;AAAA,IACE,aAAa;AAAA,IACb,qBAAqB;AAAA,IACrB,gBAAgB;AAAA,EAAA;AAEpB;AAEK,MAAM,cAAc,CACzB,SAEA,YAAY,YAAY,mBAAmB,GAAG,UAAU,MAAM;AAAA,EAC5D,aAAa;AAAA,EACb,qBAAqB;AAAA,EACrB,gBAAgB;AAClB,CAAC;AAEI,MAAM,oBAAoB,CAC/B,SACG,YAAY,kBAAkB,mBAAmB,GAAG,gBAAgB,IAAI;AAEtE,MAAM,kBAAkB,CAC7B,SACG,YAAY,gBAAgB,mBAAmB,GAAG,cAAc,IAAI;AAMlE,MAAM,eAAe,CAC1B,SACG,YAAY,aAAa,mBAAmB,OAAO,WAAW,IAAI;AAMhE,MAAM,2BAA2B,CACtC,SAEA;AAAA,EACE;AAAA,EACA,iBAAA,EAAmB,WAAW;AAAA,EAC9B;AACF;AAEK,MAAM,+BAA+B,CAC1C,SAEA;AAAA,EACE;AAAA,EACA,iBAAA,EAAmB,WAAW;AAAA,EAC9B;AACF;AAEK,MAAM,yBAAyB,CACpC,SAEA;AAAA,EACE;AAAA,EACA,iBAAA,EAAmB,WAAW;AAAA,EAC9B;AACF;AAMK,MAAM,qBAAqB,CAChC,SAEA;AAAA,EACE;AAAA,EACA,iBAAA,EAAmB,OAAO;AAAA,EAC1B;AACF;AAEK,MAAM,2BAA2B,CACtC,SAEA,eAAe,mBAAmB,iBAAA,EAAmB,OAAO,iBAAiB;AAAA,EAC3E,OAAO;AAAA,EACP,OAAO;AAAA,EACP,GAAG;AACL,CAAC;"}
|
|
@@ -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 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 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,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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;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.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 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 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,IAAA;AAsC5B,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,CAAA;AAEjD,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;AAEzB,QAAM,aAAa,SAAS,cAAc;AAC1C,QAAM,YAAY,SAAS,aAAa;AACxC,QAAM,YAAY,SAAS,aAAa;AACxC,QAAM,eAAe,SAAS,SAAS;AACvC,QAAM,eAAe,SAAS,SAAS;AACvC,QAAM,UAAU,SAAS,UAAU;AACnC,QAAM,sBACJ,SAAS,gBAAgB;AAC3B,QAAM,iBAAiB,SAAS,kBAAkB;AAClD,QAAM,gBAAgB,SAAS,iBAAiB,CAAA;AAChD,QAAM,oBAAoB,SAAS,qBAAqB,CAAA;AACxD,QAAM,YAAY,SAAS;AAC3B,QAAM,UAAU,SAAS;AACzB,QAAM,OAAO,QAAQ,SAAS,QAAQ,CAAA,CAAE;AAGxC,QAAM,EAAE,WAAW,eAAe,iBAAiB,iBAAA,IACjDA,kCAAAA,cAAA;AAGF,QAAM,gBAAgBC,aAAAA,OAAc,IAAI;AAExC,QAAM,gBAAgBA,aAAAA,OAA+B,IAAI;AAGzD,QAAM,cAAc,eAAe,KAAK,cAAc,OAAO;AAG7D,Q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c,SAAS;AACzB,oBAAc,QAAQ,MAAA;AAAA,IACxB;AAAA,EACF;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,EAAA;AAGFD,eAAAA;AAAAA,IACE,MAAM,MAAM;AAEV,UAAI,cAAc,SAAS;AACzB,sBAAc,QAAQ,MAAA;AAAA,MACxB;AAAA,IACF;AAAA,IACA,CAAA;AAAA,EAAC;AAIH,SAAO;AACT;;"}
|
|
@@ -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 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 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,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,UAAU;AAC7B,QAAA,sBACJ,SAAS,gBAAgB;AACrB,QAAA,iBAAiB,SAAS,kBAAk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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,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 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,IAAA;AAsC5B,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,CAAA;AAEjD,MAAM,iBAAiB,CAAC,KAAa,SACnC,QAAQ,IAAI,EAAE,SAAS,IAAI,GAAG,GAAG,IAAI,KAAK,UAAU,IAAI,CAAC,KAAK;AAwCzD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,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EAAA,CACD;AAOD,YAAU,MAAM;AACd,QAAI,CAAC,uBAAuB,kBAAkB,EAAG;AACjD,QAAI,CAAC,aAAa,CAAC,QAAS;AAC5B,QAAI,UAAW;AACf,QAAI,CAAC,aAAa,CAAC,gBAAiB;AAEpC,UAAM,UAAU,WAAW,MAAM;AAC/B,YAAM,GAAG,cAAc,OAAO;AAAA,IAChC,GAAG,cAAc;AAEjB,WAAO,MAAM,aAAa,OAAO;AAAA,EACnC,GAAG;AAAA,IACD;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EAAA,CACD;AAGD,QAAM,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,MAAA;AAAA,IACxB;AAAA,EACF;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,EAAA;AAGF;AAAA,IACE,MAAM,MAAM;AAEV,UAAI,cAAc,SAAS;AACzB,sBAAc,QAAQ,MAAA;AAAA,MACxB;AAAA,IACF;AAAA,IACA,CAAA;AAAA,EAAC;AAIH,SAAO;AACT;"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useAsyncStateStore.cjs","sources":["../../../src/hooks/useAsync/useAsyncStateStore.tsx"],"sourcesContent":["'use client';\n\nimport {\n type PropsWithChildren,\n createContext,\n useContext,\n useReducer,\n} from 'react';\n\n/**\n * Represents the states for a given key in the asynchronous state management.\n * This includes flags for loading, fetched, invalidation, and success/error status.\n * It also keeps track of the fetched datetime, retry counts, the data itself, and whether queries are enabled.\n */\ntype States<T> = {\n isLoading: boolean;\n isFetched: boolean;\n isInvalidated: boolean;\n fetchedDateTime: null | Date;\n error: string | null;\n isSuccess: boolean;\n data: T | null;\n errorCount: number;\n isEnabled: boolean;\n};\n\n/**\n * Holds a mapping from a key (string) to its associated state.\n */\ntype StateSlice<T> = {\n [key: string]: States<T>;\n};\n\n/**\n * Describes all the possible actions that can be dispatched to the reducer.\n * These actions allow setting or updating states for specific keys or multiple keys at once,\n * handling errors, and resetting states.\n */\ntype Actions<T> =\n | { type: 'SET_QUERY_STATE'; key: string; value: Partial<States<T>> }\n | { type: 'MAKE_QUERY_IN_ERROR'; key: string; error: string }\n | { type: 'SET_QUERIES_STATE'; keys: string[]; value: Partial<States<T>> }\n | { type: 'RESET_KEY_STATE'; keys: string[] }\n | { type: 'RESET_STATE'; excludeKeys: string[] };\n\n/**\n * The shape of the entire asynchronous state, holding all states in a single object.\n */\ntype AsyncState<T> = {\n states: StateSlice<T>;\n};\n\n/**\n * Creates a default state object with initial values. This is useful when a key\n * has not been initialized yet or when resetting a state back to defaults.\n */\nconst createDefaultStates = <T,>(): States<T> => ({\n isFetched: false,\n fetchedDateTime: null,\n isLoading: false,\n isInvalidated: false,\n error: null,\n isSuccess: false,\n data: null,\n errorCount: 0,\n isEnabled: true,\n});\n\n/**\n * Given a list of selector keys and a list of keys that may contain arguments,\n * this function returns all keys that match the selectors. Matching is determined\n * by comparing the initial part (split by \"/\") of the key.\n *\n * For example:\n * selectorsKeys = [\"user\", \"posts\"]\n * keysWithArgs = [\"user/123\", \"posts/active\", \"comments/42\"]\n * Result = [\"user/123\", \"posts/active\"]\n */\nconst getMatchKeys = (\n selectorsKeys: string[],\n keysWithArgs: string[]\n): string[] =>\n keysWithArgs.filter((key) => selectorsKeys.includes(key.split('/')[0]));\n\n/**\n * The reducer function handling all state transitions. It takes the current state and an action,\n * and returns a new state based on the type of the action.\n *\n * Actions include:\n * - SET_QUERY_STATE: Update a single key with partial new state.\n * - MAKE_QUERY_IN_ERROR: Mark a single key as errored and update related flags.\n * - SET_QUERIES_STATE: Update multiple keys at once with partial new state.\n * - RESET_KEY_STATE: Reset certain keys to their default states.\n * - RESET_STATE: Reset all keys to their default states except those excluded.\n */\nconst reducer = <T,>(\n state: AsyncState<T>,\n action: Actions<T>\n): AsyncState<T> => {\n switch (action.type) {\n case 'SET_QUERY_STATE': {\n const { key, value } = action;\n return {\n ...state,\n states: {\n ...state.states,\n [key]: {\n // Merge existing state for the key or default state if not present\n ...(state.states[key] ?? createDefaultStates<T>()),\n ...value,\n },\n },\n };\n }\n case 'MAKE_QUERY_IN_ERROR': {\n const { key, error } = action;\n return {\n ...state,\n states: {\n ...state.states,\n [key]: {\n // Merge existing state or default if not found\n ...(state.states[key] ?? createDefaultStates<T>()),\n // Explicitly set error and related flags\n error,\n isFetched: true,\n isSuccess: false,\n errorCount: (state.states[key]?.errorCount ?? 0) + 1,\n isLoading: false,\n isInvalidated: false,\n },\n },\n };\n }\n case 'SET_QUERIES_STATE': {\n const { keys, value } = action;\n const keyArray = [keys].flat();\n\n // Find all keys that match the given selectors\n const allKeys = Object.keys(state.states);\n const matchedKeys = getMatchKeys(keyArray, allKeys);\n if (matchedKeys.length === 0) return state;\n\n // Update multiple keys in a single action\n const updatedStates = structuredClone(state.states);\n matchedKeys.forEach((key) => {\n updatedStates[key] = {\n ...(state.states[key] ?? createDefaultStates<T>()),\n ...value,\n };\n });\n\n return {\n ...state,\n states: updatedStates,\n };\n }\n case 'RESET_KEY_STATE': {\n const { keys } = action;\n const keyArray = [keys].flat();\n if (keyArray.length === 0) return state;\n\n // Find all keys that match the given selectors\n const allKeys = Object.keys(state.states);\n const matchedKeys = getMatchKeys(keyArray, allKeys);\n if (matchedKeys.length === 0) return state;\n\n // Reset the matched keys back to default states\n const resetStates = { ...state.states };\n matchedKeys.forEach((key) => {\n resetStates[key] = createDefaultStates<T>();\n });\n\n return {\n ...state,\n states: resetStates,\n };\n }\n case 'RESET_STATE': {\n const excludeArray = [action.excludeKeys].flat();\n const allKeys = Object.keys(state.states);\n\n const matchedKeys = getMatchKeys(excludeArray, allKeys);\n\n // Reset all states except those that match the exclude keys\n const newStates: StateSlice<T> = {};\n allKeys.forEach((key) => {\n newStates[key] = matchedKeys.includes(key)\n ? state.states[key]\n : createDefaultStates<T>();\n });\n\n return {\n ...state,\n states: newStates,\n };\n }\n default:\n return state;\n }\n};\n\n/**\n * The context type that will be provided to consumers.\n * It exposes a set of functions for interacting with the asynchronous state:\n * - getStates: Retrieve the current state for a given key.\n * - setQueryState: Partially update a single key's state.\n * - setQueriesState: Partially update multiple keys' states.\n * - makeQueryInError: Set a particular key into an error state.\n * - resetKeyState: Reset certain keys to their default states.\n * - resetState: Reset all keys to their default states except a set of excluded ones.\n */\ntype AsyncStateContextType<T> = {\n getStates: (key: string) => States<T>;\n setQueryState: (key: string, value: Partial<States<T>>) => void;\n setQueriesState: (keys: string[], value: Partial<States<T>>) => void;\n makeQueryInError: (key: string, error: string) => void;\n resetKeyState: (keys: string[]) => void;\n resetState: (excludedKeys: string[]) => void;\n};\n\n/**\n * Creates a React context for asynchronous state management.\n * This context will be provided by the AsyncStateProvider and consumed by hooks like useAsyncState.\n */\nconst AsyncStateContext = createContext<AsyncStateContextType<unknown> | null>(\n null\n);\n\n/**\n * A provider component that wraps its children and provides the asynchronous\n * state context. It uses the reducer to manage states and dispatch actions\n * based on consumer interactions.\n *\n * @param children The React children elements that should have access to this context.\n */\nexport const AsyncStateProvider = ({ children }: PropsWithChildren<{}>) => {\n // Initialize the reducer with an empty state object\n const [asyncState, dispatch] = useReducer(reducer, { states: {} });\n\n /**\n * Retrieve the state associated with a given key. If no state exists for that key,\n * return a default state.\n *\n * @param key The key for which to retrieve the state.\n */\n const getStates = (key: string) =>\n asyncState.states[key] ?? createDefaultStates<unknown>();\n\n /**\n * Partially update the state for a given key.\n *\n * @param key The key to update.\n * @param value A partial state object to merge with the existing state.\n */\n const setQueryState = (key: string, value: Partial<States<unknown>>) => {\n dispatch({ type: 'SET_QUERY_STATE', key, value });\n };\n\n /**\n * Partially update the state for multiple keys at once.\n *\n * @param keys An array of keys to update.\n * @param value A partial state object to merge with each key's existing state.\n */\n const setQueriesState = (keys: string[], value: Partial<States<unknown>>) => {\n dispatch({ type: 'SET_QUERIES_STATE', keys, value });\n };\n\n /**\n * Mark a given query as having encountered an error.\n *\n * @param key The key associated with the query.\n * @param error The error message to set.\n */\n const makeQueryInError = (key: string, error: string) => {\n dispatch({ type: 'MAKE_QUERY_IN_ERROR', key, error });\n };\n\n /**\n * Reset certain keys back to their default states.\n *\n * @param keys The keys to reset.\n */\n const resetKeyState = (keys: string[]) => {\n dispatch({ type: 'RESET_KEY_STATE', keys });\n };\n\n /**\n * Reset the entire state back to defaults, except for keys that match the excluded ones.\n *\n * @param excludedKeys Keys that should not be reset.\n */\n const resetState = (excludedKeys: string[]) => {\n dispatch({ type: 'RESET_STATE', excludeKeys: excludedKeys });\n };\n\n return (\n <AsyncStateContext.Provider\n value={{\n getStates,\n setQueryState,\n setQueriesState,\n makeQueryInError,\n resetKeyState,\n resetState,\n }}\n >\n {children}\n </AsyncStateContext.Provider>\n );\n};\n\n/**\n * A custom hook for accessing the asynchronous state context. It throws an error if used\n * outside of a provider.\n *\n * @returns The asynchronous state context value.\n */\nexport const useAsyncState = () => {\n const context = useContext(AsyncStateContext);\n if (!context) {\n throw new Error('useAsyncState must be used within an AsyncStateProvider');\n }\n return context;\n};\n"],"names":["createContext","useReducer","jsx","useContext"],"mappings":";;;;;AAwDA,MAAM,sBAAsB,OAAsB;AAAA,EAChD,WAAW;AAAA,EACX,iBAAiB;AAAA,EACjB,WAAW;AAAA,EACX,eAAe;AAAA,EACf,OAAO;AAAA,EACP,WAAW;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AAY,CAAC,QACjB,WAAW,OAAO,GAAG,KAAK,oBAA6B;AAQnD,QAAA,gBAAgB,CAAC,KAAa,UAAoC;AACtE,aAAS,EAAE,MAAM,mBAAmB,KAAK,OAAO;AAAA,EAClD;AAQM,QAAA,kBAAkB,CAAC,MAAgB,UAAoC;AAC3E,aAAS,EAAE,MAAM,qBAAqB,MAAM,OAAO;AAAA,EACrD;AAQM,QAAA,mBAAmB,CAAC,KAAa,UAAkB;AACvD,aAAS,EAAE,MAAM,uBAAuB,KAAK,OAAO;AAAA,EACtD;AAOM,QAAA,gBAAgB,CAAC,SAAmB;AACxC,aAAS,EAAE,MAAM,mBAAmB,KAAA,CAAM;AAAA,EAC5C;AAOM,QAAA,aAAa,CAAC,iBAA2B;AAC7C,aAAS,EAAE,MAAM,eAAe,aAAa,cAAc;AAAA,EAC7D;AAGE,SAAAC,2BAAA;AAAA,IAAC,kBAAkB;AAAA,IAAlB;AAAA,MACC,OAAO;AAAA,QACL;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,MACF;AAAA,MAEC;AAAA,IAAA;AAAA,EACH;AAEJ;AAQO,MAAM,gBAAgB,MAAM;AAC3B,QAAA,UAAUC,wBAAW,iBAAiB;AAC5C,MAAI,CAAC,SAAS;AACN,UAAA,IAAI,MAAM,yDAAyD;AAAA,EAAA;AAEpE,SAAA;AACT;;;"}
|
|
1
|
+
{"version":3,"file":"useAsyncStateStore.cjs","sources":["../../../src/hooks/useAsync/useAsyncStateStore.tsx"],"sourcesContent":["'use client';\n\nimport {\n type PropsWithChildren,\n createContext,\n useContext,\n useReducer,\n} from 'react';\n\n/**\n * Represents the states for a given key in the asynchronous state management.\n * This includes flags for loading, fetched, invalidation, and success/error status.\n * It also keeps track of the fetched datetime, retry counts, the data itself, and whether queries are enabled.\n */\ntype States<T> = {\n isLoading: boolean;\n isFetched: boolean;\n isInvalidated: boolean;\n fetchedDateTime: null | Date;\n error: string | null;\n isSuccess: boolean;\n data: T | null;\n errorCount: number;\n isEnabled: boolean;\n};\n\n/**\n * Holds a mapping from a key (string) to its associated state.\n */\ntype StateSlice<T> = {\n [key: string]: States<T>;\n};\n\n/**\n * Describes all the possible actions that can be dispatched to the reducer.\n * These actions allow setting or updating states for specific keys or multiple keys at once,\n * handling errors, and resetting states.\n */\ntype Actions<T> =\n | { type: 'SET_QUERY_STATE'; key: string; value: Partial<States<T>> }\n | { type: 'MAKE_QUERY_IN_ERROR'; key: string; error: string }\n | { type: 'SET_QUERIES_STATE'; keys: string[]; value: Partial<States<T>> }\n | { type: 'RESET_KEY_STATE'; keys: string[] }\n | { type: 'RESET_STATE'; excludeKeys: string[] };\n\n/**\n * The shape of the entire asynchronous state, holding all states in a single object.\n */\ntype AsyncState<T> = {\n states: StateSlice<T>;\n};\n\n/**\n * Creates a default state object with initial values. This is useful when a key\n * has not been initialized yet or when resetting a state back to defaults.\n */\nconst createDefaultStates = <T,>(): States<T> => ({\n isFetched: false,\n fetchedDateTime: null,\n isLoading: false,\n isInvalidated: false,\n error: null,\n isSuccess: false,\n data: null,\n errorCount: 0,\n isEnabled: true,\n});\n\n/**\n * Given a list of selector keys and a list of keys that may contain arguments,\n * this function returns all keys that match the selectors. Matching is determined\n * by comparing the initial part (split by \"/\") of the key.\n *\n * For example:\n * selectorsKeys = [\"user\", \"posts\"]\n * keysWithArgs = [\"user/123\", \"posts/active\", \"comments/42\"]\n * Result = [\"user/123\", \"posts/active\"]\n */\nconst getMatchKeys = (\n selectorsKeys: string[],\n keysWithArgs: string[]\n): string[] =>\n keysWithArgs.filter((key) => selectorsKeys.includes(key.split('/')[0]));\n\n/**\n * The reducer function handling all state transitions. It takes the current state and an action,\n * and returns a new state based on the type of the action.\n *\n * Actions include:\n * - SET_QUERY_STATE: Update a single key with partial new state.\n * - MAKE_QUERY_IN_ERROR: Mark a single key as errored and update related flags.\n * - SET_QUERIES_STATE: Update multiple keys at once with partial new state.\n * - RESET_KEY_STATE: Reset certain keys to their default states.\n * - RESET_STATE: Reset all keys to their default states except those excluded.\n */\nconst reducer = <T,>(\n state: AsyncState<T>,\n action: Actions<T>\n): AsyncState<T> => {\n switch (action.type) {\n case 'SET_QUERY_STATE': {\n const { key, value } = action;\n return {\n ...state,\n states: {\n ...state.states,\n [key]: {\n // Merge existing state for the key or default state if not present\n ...(state.states[key] ?? createDefaultStates<T>()),\n ...value,\n },\n },\n };\n }\n case 'MAKE_QUERY_IN_ERROR': {\n const { key, error } = action;\n return {\n ...state,\n states: {\n ...state.states,\n [key]: {\n // Merge existing state or default if not found\n ...(state.states[key] ?? createDefaultStates<T>()),\n // Explicitly set error and related flags\n error,\n isFetched: true,\n isSuccess: false,\n errorCount: (state.states[key]?.errorCount ?? 0) + 1,\n isLoading: false,\n isInvalidated: false,\n },\n },\n };\n }\n case 'SET_QUERIES_STATE': {\n const { keys, value } = action;\n const keyArray = [keys].flat();\n\n // Find all keys that match the given selectors\n const allKeys = Object.keys(state.states);\n const matchedKeys = getMatchKeys(keyArray, allKeys);\n if (matchedKeys.length === 0) return state;\n\n // Update multiple keys in a single action\n const updatedStates = structuredClone(state.states);\n matchedKeys.forEach((key) => {\n updatedStates[key] = {\n ...(state.states[key] ?? createDefaultStates<T>()),\n ...value,\n };\n });\n\n return {\n ...state,\n states: updatedStates,\n };\n }\n case 'RESET_KEY_STATE': {\n const { keys } = action;\n const keyArray = [keys].flat();\n if (keyArray.length === 0) return state;\n\n // Find all keys that match the given selectors\n const allKeys = Object.keys(state.states);\n const matchedKeys = getMatchKeys(keyArray, allKeys);\n if (matchedKeys.length === 0) return state;\n\n // Reset the matched keys back to default states\n const resetStates = { ...state.states };\n matchedKeys.forEach((key) => {\n resetStates[key] = createDefaultStates<T>();\n });\n\n return {\n ...state,\n states: resetStates,\n };\n }\n case 'RESET_STATE': {\n const excludeArray = [action.excludeKeys].flat();\n const allKeys = Object.keys(state.states);\n\n const matchedKeys = getMatchKeys(excludeArray, allKeys);\n\n // Reset all states except those that match the exclude keys\n const newStates: StateSlice<T> = {};\n allKeys.forEach((key) => {\n newStates[key] = matchedKeys.includes(key)\n ? state.states[key]\n : createDefaultStates<T>();\n });\n\n return {\n ...state,\n states: newStates,\n };\n }\n default:\n return state;\n }\n};\n\n/**\n * The context type that will be provided to consumers.\n * It exposes a set of functions for interacting with the asynchronous state:\n * - getStates: Retrieve the current state for a given key.\n * - setQueryState: Partially update a single key's state.\n * - setQueriesState: Partially update multiple keys' states.\n * - makeQueryInError: Set a particular key into an error state.\n * - resetKeyState: Reset certain keys to their default states.\n * - resetState: Reset all keys to their default states except a set of excluded ones.\n */\ntype AsyncStateContextType<T> = {\n getStates: (key: string) => States<T>;\n setQueryState: (key: string, value: Partial<States<T>>) => void;\n setQueriesState: (keys: string[], value: Partial<States<T>>) => void;\n makeQueryInError: (key: string, error: string) => void;\n resetKeyState: (keys: string[]) => void;\n resetState: (excludedKeys: string[]) => void;\n};\n\n/**\n * Creates a React context for asynchronous state management.\n * This context will be provided by the AsyncStateProvider and consumed by hooks like useAsyncState.\n */\nconst AsyncStateContext = createContext<AsyncStateContextType<unknown> | null>(\n null\n);\n\n/**\n * A provider component that wraps its children and provides the asynchronous\n * state context. It uses the reducer to manage states and dispatch actions\n * based on consumer interactions.\n *\n * @param children The React children elements that should have access to this context.\n */\nexport const AsyncStateProvider = ({ children }: PropsWithChildren<{}>) => {\n // Initialize the reducer with an empty state object\n const [asyncState, dispatch] = useReducer(reducer, { states: {} });\n\n /**\n * Retrieve the state associated with a given key. If no state exists for that key,\n * return a default state.\n *\n * @param key The key for which to retrieve the state.\n */\n const getStates = (key: string) =>\n asyncState.states[key] ?? createDefaultStates<unknown>();\n\n /**\n * Partially update the state for a given key.\n *\n * @param key The key to update.\n * @param value A partial state object to merge with the existing state.\n */\n const setQueryState = (key: string, value: Partial<States<unknown>>) => {\n dispatch({ type: 'SET_QUERY_STATE', key, value });\n };\n\n /**\n * Partially update the state for multiple keys at once.\n *\n * @param keys An array of keys to update.\n * @param value A partial state object to merge with each key's existing state.\n */\n const setQueriesState = (keys: string[], value: Partial<States<unknown>>) => {\n dispatch({ type: 'SET_QUERIES_STATE', keys, value });\n };\n\n /**\n * Mark a given query as having encountered an error.\n *\n * @param key The key associated with the query.\n * @param error The error message to set.\n */\n const makeQueryInError = (key: string, error: string) => {\n dispatch({ type: 'MAKE_QUERY_IN_ERROR', key, error });\n };\n\n /**\n * Reset certain keys back to their default states.\n *\n * @param keys The keys to reset.\n */\n const resetKeyState = (keys: string[]) => {\n dispatch({ type: 'RESET_KEY_STATE', keys });\n };\n\n /**\n * Reset the entire state back to defaults, except for keys that match the excluded ones.\n *\n * @param excludedKeys Keys that should not be reset.\n */\n const resetState = (excludedKeys: string[]) => {\n dispatch({ type: 'RESET_STATE', excludeKeys: excludedKeys });\n };\n\n return (\n <AsyncStateContext.Provider\n value={{\n getStates,\n setQueryState,\n setQueriesState,\n makeQueryInError,\n resetKeyState,\n resetState,\n }}\n >\n {children}\n </AsyncStateContext.Provider>\n );\n};\n\n/**\n * A custom hook for accessing the asynchronous state context. It throws an error if used\n * outside of a provider.\n *\n * @returns The asynchronous state context value.\n */\nexport const useAsyncState = () => {\n const context = useContext(AsyncStateContext);\n if (!context) {\n throw new Error('useAsyncState must be used within an AsyncStateProvider');\n }\n return context;\n};\n"],"names":["createContext","useReducer","jsx","useContext"],"mappings":";;;;;AAwDA,MAAM,sBAAsB,OAAsB;AAAA,EAChD,WAAW;AAAA,EACX,iBAAiB;AAAA,EACjB,WAAW;AAAA,EACX,eAAe;AAAA,EACf,OAAO;AAAA,EACP,WAAW;AAAA,EACX,MAAM;AAAA,EACN,YAAY;AAAA,EACZ,WAAW;AACb;AAYA,MAAM,eAAe,CACnB,eACA,iBAEA,aAAa,OAAO,CAAC,QAAQ,cAAc,SAAS,IAAI,MAAM,GAAG,EAAE,CAAC,CAAC,CAAC;AAaxE,MAAM,UAAU,CACd,OACA,WACkB;AAClB,UAAQ,OAAO,MAAA;AAAA,IACb,KAAK,mBAAmB;AACtB,YAAM,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