@vertesia/ui 0.79.0 → 0.79.2
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/lib/esm/core/components/Panel.js +8 -0
- package/lib/esm/core/components/Panel.js.map +1 -0
- package/lib/esm/core/components/SelectBox.js +1 -1
- package/lib/esm/core/components/SelectBox.js.map +1 -1
- package/lib/esm/core/components/SidePanel.js +2 -2
- package/lib/esm/core/components/SidePanel.js.map +1 -1
- package/lib/esm/core/components/TagsInput.js +194 -0
- package/lib/esm/core/components/TagsInput.js.map +1 -0
- package/lib/esm/core/components/index.js +2 -1
- package/lib/esm/core/components/index.js.map +1 -1
- package/lib/esm/core/components/shadcn/breadcrumb.js +29 -8
- package/lib/esm/core/components/shadcn/breadcrumb.js.map +1 -1
- package/lib/esm/core/components/shadcn/button.js +3 -2
- package/lib/esm/core/components/shadcn/button.js.map +1 -1
- package/lib/esm/core/components/shadcn/filters/filterBar.js +2 -2
- package/lib/esm/core/components/shadcn/filters/filterBar.js.map +1 -1
- package/lib/esm/core/components/shadcn/index.js +1 -0
- package/lib/esm/core/components/shadcn/index.js.map +1 -1
- package/lib/esm/core/components/shadcn/input.js +4 -1
- package/lib/esm/core/components/shadcn/input.js.map +1 -1
- package/lib/esm/core/components/shadcn/popover.js +1 -1
- package/lib/esm/core/components/shadcn/popover.js.map +1 -1
- package/lib/esm/core/components/shadcn/resizeable.js +2 -2
- package/lib/esm/core/components/shadcn/resizeable.js.map +1 -1
- package/lib/esm/core/components/shadcn/selectBox.js +15 -9
- package/lib/esm/core/components/shadcn/selectBox.js.map +1 -1
- package/lib/esm/core/components/shadcn/tabs.js +10 -3
- package/lib/esm/core/components/shadcn/tabs.js.map +1 -1
- package/lib/esm/core/components/shadcn/textarea.js +7 -0
- package/lib/esm/core/components/shadcn/textarea.js.map +1 -0
- package/lib/esm/core/hooks/CompositeState.js +139 -1
- package/lib/esm/core/hooks/CompositeState.js.map +1 -1
- package/lib/esm/core/hooks/index.js +1 -0
- package/lib/esm/core/hooks/index.js.map +1 -1
- package/lib/esm/core/hooks/useScrollableSearch.js +92 -0
- package/lib/esm/core/hooks/useScrollableSearch.js.map +1 -0
- package/lib/esm/env/index.js +2 -2
- package/lib/esm/env/index.js.map +1 -1
- package/lib/esm/features/agent/PayloadBuilder.js +80 -55
- package/lib/esm/features/agent/PayloadBuilder.js.map +1 -1
- package/lib/esm/features/agent/chat/ModernAgentConversation.js +22 -24
- package/lib/esm/features/agent/chat/ModernAgentConversation.js.map +1 -1
- package/lib/esm/features/agent/chat/ModernAgentOutput/AllMessagesMixed.js +2 -3
- package/lib/esm/features/agent/chat/ModernAgentOutput/AllMessagesMixed.js.map +1 -1
- package/lib/esm/features/agent/chat/ModernAgentOutput/Header.js +2 -2
- package/lib/esm/features/agent/chat/ModernAgentOutput/Header.js.map +1 -1
- package/lib/esm/features/agent/chat/ModernAgentOutput/InlineSlidingPlanPanel.js +15 -20
- package/lib/esm/features/agent/chat/ModernAgentOutput/InlineSlidingPlanPanel.js.map +1 -1
- package/lib/esm/features/agent/chat/ModernAgentOutput/PlanPanel.js +1 -0
- package/lib/esm/features/agent/chat/ModernAgentOutput/PlanPanel.js.map +1 -1
- package/lib/esm/features/agent/chat/ModernAgentOutput/SlidingPlanPanel.js +3 -3
- package/lib/esm/features/agent/chat/ModernAgentOutput/SlidingPlanPanel.js.map +1 -1
- package/lib/esm/features/agent/chat/ModernAgentOutput/WorkstreamTabs.js +6 -6
- package/lib/esm/features/agent/chat/ModernAgentOutput/WorkstreamTabs.js.map +1 -1
- package/lib/esm/features/facets/CollectionsFacetsNav.js +19 -0
- package/lib/esm/features/facets/CollectionsFacetsNav.js.map +1 -1
- package/lib/esm/features/facets/InteractionsFacetsNav.js +9 -3
- package/lib/esm/features/facets/InteractionsFacetsNav.js.map +1 -1
- package/lib/esm/features/facets/utils/VTypeFacet.js +4 -1
- package/lib/esm/features/facets/utils/VTypeFacet.js.map +1 -1
- package/lib/esm/features/layout/GenericPageNavHeader.js +58 -5
- package/lib/esm/features/layout/GenericPageNavHeader.js.map +1 -1
- package/lib/esm/features/store/collections/BrowseCollectionView.js +3 -0
- package/lib/esm/features/store/collections/BrowseCollectionView.js.map +1 -1
- package/lib/esm/features/store/collections/CreateCollection.js +2 -2
- package/lib/esm/features/store/collections/CreateCollection.js.map +1 -1
- package/lib/esm/features/store/collections/EditCollectionView.js +39 -29
- package/lib/esm/features/store/collections/EditCollectionView.js.map +1 -1
- package/lib/esm/features/store/collections/SelectCollection.js +82 -16
- package/lib/esm/features/store/collections/SelectCollection.js.map +1 -1
- package/lib/esm/features/store/collections/SharedPropsEditor.js +40 -0
- package/lib/esm/features/store/collections/SharedPropsEditor.js.map +1 -0
- package/lib/esm/features/store/collections/SyncMemberHeadsToggle.js +35 -0
- package/lib/esm/features/store/collections/SyncMemberHeadsToggle.js.map +1 -0
- package/lib/esm/features/store/collections/index.js +2 -0
- package/lib/esm/features/store/collections/index.js.map +1 -1
- package/lib/esm/features/store/objects/DocumentSearchResults.js +35 -9
- package/lib/esm/features/store/objects/DocumentSearchResults.js.map +1 -1
- package/lib/esm/features/store/objects/DocumentTable.js +6 -6
- package/lib/esm/features/store/objects/DocumentTable.js.map +1 -1
- package/lib/esm/features/store/objects/components/ContentOverview.js +158 -114
- package/lib/esm/features/store/objects/components/ContentOverview.js.map +1 -1
- package/lib/esm/features/store/objects/components/DocumentIcon.js +5 -3
- package/lib/esm/features/store/objects/components/DocumentIcon.js.map +1 -1
- package/lib/esm/features/store/objects/components/SaveVersionConfirmModal.js +11 -2
- package/lib/esm/features/store/objects/components/SaveVersionConfirmModal.js.map +1 -1
- package/lib/esm/features/store/objects/components/useDownloadObject.js +2 -2
- package/lib/esm/features/store/objects/components/useDownloadObject.js.map +1 -1
- package/lib/esm/features/store/objects/layout/DocumentTableColumn.js +13 -1
- package/lib/esm/features/store/objects/layout/DocumentTableColumn.js.map +1 -1
- package/lib/esm/features/store/objects/layout/documentLayout.js +5 -5
- package/lib/esm/features/store/objects/layout/documentLayout.js.map +1 -1
- package/lib/esm/features/store/objects/layout/renderers.js +28 -12
- package/lib/esm/features/store/objects/layout/renderers.js.map +1 -1
- package/lib/esm/features/store/objects/search/DocumentSearchContext.js +5 -1
- package/lib/esm/features/store/objects/search/DocumentSearchContext.js.map +1 -1
- package/lib/esm/features/store/objects/search/DocumentSearchProvider.js +1 -1
- package/lib/esm/features/store/objects/search/DocumentSearchProvider.js.map +1 -1
- package/lib/esm/features/store/objects/selection/ObjectsActionContext.js +3 -2
- package/lib/esm/features/store/objects/selection/ObjectsActionContext.js.map +1 -1
- package/lib/esm/features/store/objects/selection/SelectionActions.js +2 -0
- package/lib/esm/features/store/objects/selection/SelectionActions.js.map +1 -1
- package/lib/esm/features/store/objects/selection/actions/AddToCollectionAction.js +10 -2
- package/lib/esm/features/store/objects/selection/actions/AddToCollectionAction.js.map +1 -1
- package/lib/esm/features/store/objects/selection/actions/DeleteObjectsAction.js +20 -2
- package/lib/esm/features/store/objects/selection/actions/DeleteObjectsAction.js.map +1 -1
- package/lib/esm/features/store/objects/upload/DocumentUploadModal.js +15 -7
- package/lib/esm/features/store/objects/upload/DocumentUploadModal.js.map +1 -1
- package/lib/esm/features/store/objects/upload/useSmartFileUploadProcessing.js +10 -9
- package/lib/esm/features/store/objects/upload/useSmartFileUploadProcessing.js.map +1 -1
- package/lib/esm/features/store/types/CreateOrUpdateTypeModal.js +1 -1
- package/lib/esm/features/store/types/CreateOrUpdateTypeModal.js.map +1 -1
- package/lib/esm/features/user/UserInfo.js +2 -0
- package/lib/esm/features/user/UserInfo.js.map +1 -1
- package/lib/esm/router/HistoryNavigator.js +25 -2
- package/lib/esm/router/HistoryNavigator.js.map +1 -1
- package/lib/esm/router/Nav.js +3 -3
- package/lib/esm/router/Nav.js.map +1 -1
- package/lib/esm/session/UserSession.js +1 -0
- package/lib/esm/session/UserSession.js.map +1 -1
- package/lib/esm/session/UserSessionProvider.js +9 -2
- package/lib/esm/session/UserSessionProvider.js.map +1 -1
- package/lib/esm/session/auth/composable.js +66 -67
- package/lib/esm/session/auth/composable.js.map +1 -1
- package/lib/esm/shell/apps/AppProjectSelector.js +2 -2
- package/lib/esm/shell/apps/AppProjectSelector.js.map +1 -1
- package/lib/esm/widgets/form/Form.js +17 -30
- package/lib/esm/widgets/form/Form.js.map +1 -1
- package/lib/esm/widgets/form/FormContext.js +4 -2
- package/lib/esm/widgets/form/FormContext.js.map +1 -1
- package/lib/esm/widgets/form/ManagedObject.js +4 -0
- package/lib/esm/widgets/form/ManagedObject.js.map +1 -1
- package/lib/esm/widgets/form/fields.js +4 -3
- package/lib/esm/widgets/form/fields.js.map +1 -1
- package/lib/esm/widgets/form/inputs.js +2 -0
- package/lib/esm/widgets/form/inputs.js.map +1 -1
- package/lib/tsconfig.tsbuildinfo +1 -1
- package/lib/types/core/components/Panel.d.ts +11 -0
- package/lib/types/core/components/Panel.d.ts.map +1 -0
- package/lib/types/core/components/SidePanel.d.ts.map +1 -1
- package/lib/types/core/components/TagsInput.d.ts +16 -0
- package/lib/types/core/components/TagsInput.d.ts.map +1 -0
- package/lib/types/core/components/index.d.ts +2 -1
- package/lib/types/core/components/index.d.ts.map +1 -1
- package/lib/types/core/components/shadcn/breadcrumb.d.ts +3 -2
- package/lib/types/core/components/shadcn/breadcrumb.d.ts.map +1 -1
- package/lib/types/core/components/shadcn/button.d.ts.map +1 -1
- package/lib/types/core/components/shadcn/filters/filterBar.d.ts.map +1 -1
- package/lib/types/core/components/shadcn/index.d.ts +1 -0
- package/lib/types/core/components/shadcn/index.d.ts.map +1 -1
- package/lib/types/core/components/shadcn/input.d.ts.map +1 -1
- package/lib/types/core/components/shadcn/popover.d.ts +7 -0
- package/lib/types/core/components/shadcn/popover.d.ts.map +1 -1
- package/lib/types/core/components/shadcn/selectBox.d.ts +3 -2
- package/lib/types/core/components/shadcn/selectBox.d.ts.map +1 -1
- package/lib/types/core/components/shadcn/tabs.d.ts.map +1 -1
- package/lib/types/core/components/shadcn/textarea.d.ts +4 -0
- package/lib/types/core/components/shadcn/textarea.d.ts.map +1 -0
- package/lib/types/core/hooks/CompositeState.d.ts +115 -6
- package/lib/types/core/hooks/CompositeState.d.ts.map +1 -1
- package/lib/types/core/hooks/index.d.ts +1 -0
- package/lib/types/core/hooks/index.d.ts.map +1 -1
- package/lib/types/core/hooks/useScrollableSearch.d.ts +82 -0
- package/lib/types/core/hooks/useScrollableSearch.d.ts.map +1 -0
- package/lib/types/env/index.d.ts +3 -1
- package/lib/types/env/index.d.ts.map +1 -1
- package/lib/types/features/agent/PayloadBuilder.d.ts +11 -19
- package/lib/types/features/agent/PayloadBuilder.d.ts.map +1 -1
- package/lib/types/features/agent/chat/ModernAgentConversation.d.ts.map +1 -1
- package/lib/types/features/agent/chat/ModernAgentOutput/AllMessagesMixed.d.ts +1 -1
- package/lib/types/features/agent/chat/ModernAgentOutput/AllMessagesMixed.d.ts.map +1 -1
- package/lib/types/features/agent/chat/ModernAgentOutput/Header.d.ts.map +1 -1
- package/lib/types/features/agent/chat/ModernAgentOutput/InlineSlidingPlanPanel.d.ts.map +1 -1
- package/lib/types/features/agent/chat/ModernAgentOutput/PlanPanel.d.ts.map +1 -1
- package/lib/types/features/facets/CollectionsFacetsNav.d.ts.map +1 -1
- package/lib/types/features/facets/InteractionsFacetsNav.d.ts +1 -0
- package/lib/types/features/facets/InteractionsFacetsNav.d.ts.map +1 -1
- package/lib/types/features/facets/utils/SearchInterface.d.ts +6 -1
- package/lib/types/features/facets/utils/SearchInterface.d.ts.map +1 -1
- package/lib/types/features/facets/utils/VTypeFacet.d.ts +2 -1
- package/lib/types/features/facets/utils/VTypeFacet.d.ts.map +1 -1
- package/lib/types/features/layout/GenericPageNavHeader.d.ts +2 -1
- package/lib/types/features/layout/GenericPageNavHeader.d.ts.map +1 -1
- package/lib/types/features/store/collections/BrowseCollectionView.d.ts.map +1 -1
- package/lib/types/features/store/collections/CreateCollection.d.ts.map +1 -1
- package/lib/types/features/store/collections/EditCollectionView.d.ts.map +1 -1
- package/lib/types/features/store/collections/SelectCollection.d.ts +6 -3
- package/lib/types/features/store/collections/SelectCollection.d.ts.map +1 -1
- package/lib/types/features/store/collections/SharedPropsEditor.d.ts +7 -0
- package/lib/types/features/store/collections/SharedPropsEditor.d.ts.map +1 -0
- package/lib/types/features/store/collections/SyncMemberHeadsToggle.d.ts +7 -0
- package/lib/types/features/store/collections/SyncMemberHeadsToggle.d.ts.map +1 -0
- package/lib/types/features/store/collections/index.d.ts +2 -0
- package/lib/types/features/store/collections/index.d.ts.map +1 -1
- package/lib/types/features/store/objects/DocumentSearchResults.d.ts.map +1 -1
- package/lib/types/features/store/objects/DocumentTable.d.ts +4 -0
- package/lib/types/features/store/objects/DocumentTable.d.ts.map +1 -1
- package/lib/types/features/store/objects/components/ContentOverview.d.ts.map +1 -1
- package/lib/types/features/store/objects/components/DocumentIcon.d.ts +3 -1
- package/lib/types/features/store/objects/components/DocumentIcon.d.ts.map +1 -1
- package/lib/types/features/store/objects/components/SaveVersionConfirmModal.d.ts.map +1 -1
- package/lib/types/features/store/objects/components/useDownloadObject.d.ts +1 -1
- package/lib/types/features/store/objects/components/useDownloadObject.d.ts.map +1 -1
- package/lib/types/features/store/objects/layout/DocumentTableColumn.d.ts +2 -1
- package/lib/types/features/store/objects/layout/DocumentTableColumn.d.ts.map +1 -1
- package/lib/types/features/store/objects/layout/documentLayout.d.ts +4 -2
- package/lib/types/features/store/objects/layout/documentLayout.d.ts.map +1 -1
- package/lib/types/features/store/objects/layout/renderers.d.ts +1 -1
- package/lib/types/features/store/objects/layout/renderers.d.ts.map +1 -1
- package/lib/types/features/store/objects/search/DocumentSearchContext.d.ts +1 -0
- package/lib/types/features/store/objects/search/DocumentSearchContext.d.ts.map +1 -1
- package/lib/types/features/store/objects/selection/ObjectsActionContext.d.ts.map +1 -1
- package/lib/types/features/store/objects/selection/SelectionActions.d.ts.map +1 -1
- package/lib/types/features/store/objects/selection/actions/DeleteObjectsAction.d.ts +1 -0
- package/lib/types/features/store/objects/selection/actions/DeleteObjectsAction.d.ts.map +1 -1
- package/lib/types/features/store/objects/upload/DocumentUploadModal.d.ts.map +1 -1
- package/lib/types/features/store/objects/upload/useSmartFileUploadProcessing.d.ts.map +1 -1
- package/lib/types/features/user/UserInfo.d.ts.map +1 -1
- package/lib/types/router/HistoryNavigator.d.ts.map +1 -1
- package/lib/types/router/Nav.d.ts +2 -1
- package/lib/types/router/Nav.d.ts.map +1 -1
- package/lib/types/session/UserSession.d.ts.map +1 -1
- package/lib/types/session/UserSessionProvider.d.ts.map +1 -1
- package/lib/types/session/auth/composable.d.ts.map +1 -1
- package/lib/types/widgets/form/Form.d.ts +2 -1
- package/lib/types/widgets/form/Form.d.ts.map +1 -1
- package/lib/types/widgets/form/FormContext.d.ts +5 -2
- package/lib/types/widgets/form/FormContext.d.ts.map +1 -1
- package/lib/types/widgets/form/ManagedObject.d.ts.map +1 -1
- package/lib/types/widgets/form/fields.d.ts +2 -2
- package/lib/types/widgets/form/fields.d.ts.map +1 -1
- package/lib/types/widgets/form/inputs.d.ts.map +1 -1
- package/lib/vertesia-ui-core.js +1 -1
- package/lib/vertesia-ui-core.js.map +1 -1
- package/lib/vertesia-ui-env.js +1 -1
- package/lib/vertesia-ui-env.js.map +1 -1
- package/lib/vertesia-ui-features.js +1 -1
- package/lib/vertesia-ui-features.js.map +1 -1
- package/lib/vertesia-ui-router.js +1 -1
- package/lib/vertesia-ui-router.js.map +1 -1
- package/lib/vertesia-ui-session.js +1 -1
- package/lib/vertesia-ui-session.js.map +1 -1
- package/lib/vertesia-ui-shell.js +1 -1
- package/lib/vertesia-ui-shell.js.map +1 -1
- package/lib/vertesia-ui-widgets.js +1 -1
- package/lib/vertesia-ui-widgets.js.map +1 -1
- package/package.json +4 -4
- package/src/core/components/Panel.tsx +34 -0
- package/src/core/components/SidePanel.tsx +5 -3
- package/src/core/components/index.ts +1 -1
- package/src/core/components/shadcn/breadcrumb.tsx +49 -30
- package/src/core/components/shadcn/button.tsx +3 -2
- package/src/core/components/shadcn/filters/filterBar.tsx +3 -3
- package/src/core/components/shadcn/index.ts +2 -1
- package/src/core/components/shadcn/input.tsx +10 -7
- package/src/core/components/shadcn/resizeable.tsx +4 -4
- package/src/core/components/shadcn/selectBox.tsx +87 -67
- package/src/core/components/shadcn/tabs.tsx +10 -3
- package/src/core/components/shadcn/textarea.tsx +21 -0
- package/src/core/hooks/index.ts +1 -0
- package/src/core/hooks/useScrollableSearch.tsx +193 -0
- package/src/env/index.ts +1 -1
- package/src/features/agent/chat/ModernAgentConversation.tsx +109 -118
- package/src/features/agent/chat/ModernAgentOutput/AllMessagesMixed.tsx +2 -22
- package/src/features/agent/chat/ModernAgentOutput/Header.tsx +1 -9
- package/src/features/agent/chat/ModernAgentOutput/InlineSlidingPlanPanel.tsx +39 -55
- package/src/features/agent/chat/ModernAgentOutput/PlanPanel.tsx +1 -0
- package/src/features/agent/chat/ModernAgentOutput/SlidingPlanPanel.tsx +8 -8
- package/src/features/agent/chat/ModernAgentOutput/WorkstreamTabs.tsx +8 -8
- package/src/features/facets/CollectionsFacetsNav.tsx +21 -0
- package/src/features/facets/InteractionsFacetsNav.tsx +13 -3
- package/src/features/facets/utils/SearchInterface.tsx +5 -1
- package/src/features/facets/utils/VTypeFacet.tsx +6 -2
- package/src/features/layout/GenericPageNavHeader.tsx +73 -10
- package/src/features/store/collections/BrowseCollectionView.tsx +4 -0
- package/src/features/store/collections/CreateCollection.tsx +3 -4
- package/src/features/store/collections/EditCollectionView.tsx +91 -85
- package/src/features/store/collections/SelectCollection.tsx +105 -49
- package/src/features/store/objects/DocumentSearchResults.tsx +117 -51
- package/src/features/store/objects/DocumentTable.tsx +14 -4
- package/src/features/store/objects/components/ContentOverview.tsx +208 -110
- package/src/features/store/objects/components/DocumentIcon.tsx +11 -12
- package/src/features/store/objects/components/SaveVersionConfirmModal.tsx +12 -2
- package/src/features/store/objects/layout/DocumentTableColumn.tsx +16 -1
- package/src/features/store/objects/layout/documentLayout.tsx +7 -5
- package/src/features/store/objects/layout/knowledge.md +10 -10
- package/src/features/store/objects/layout/renderers.tsx +39 -18
- package/src/features/store/objects/search/DocumentSearchContext.ts +6 -1
- package/src/features/store/objects/search/DocumentSearchProvider.tsx +1 -1
- package/src/features/store/objects/selection/ObjectsActionContext.tsx +3 -2
- package/src/features/store/objects/selection/SelectionActions.tsx +2 -0
- package/src/features/store/objects/selection/actions/AddToCollectionAction.tsx +8 -2
- package/src/features/store/objects/selection/actions/DeleteObjectsAction.tsx +22 -2
- package/src/features/store/objects/upload/DocumentUploadModal.tsx +18 -9
- package/src/features/store/objects/upload/useSmartFileUploadProcessing.ts +11 -10
- package/src/features/store/types/CreateOrUpdateTypeModal.tsx +1 -1
- package/src/router/HistoryNavigator.ts +33 -2
- package/src/router/Nav.tsx +4 -3
- package/src/widgets/form/Form.tsx +19 -43
- package/src/widgets/form/FormContext.ts +5 -2
- package/src/widgets/form/fields.tsx +8 -6
- package/src/widgets/form/inputs.tsx +1 -0
- package/lib/esm/core/components/Textarea.js +0 -15
- package/lib/esm/core/components/Textarea.js.map +0 -1
- package/lib/types/core/components/Textarea.d.ts +0 -8
- package/lib/types/core/components/Textarea.d.ts.map +0 -1
- package/src/core/components/Textarea.tsx +0 -25
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"vertesia-ui-session.js","sources":["esm/session/constants.js","esm/session/auth/firebase.js","esm/session/auth/composable.js","esm/session/auth/useCurrentTenant.js","esm/session/TypeRegistry.js","esm/session/UserSession.js","esm/session/auth/useAuthState.js","esm/session/UserSessionProvider.js","esm/session/useUXTracking.js"],"sourcesContent":["export const LastSelectedAccountId_KEY = 'composableai.lastSelectedAccountId';\nexport const LastSelectedProjectId_KEY = 'composableai.lastSelectedProjectId';\n//# sourceMappingURL=constants.js.map","import { Env } from \"@vertesia/ui/env\";\nimport { getAnalytics } from \"firebase/analytics\";\nimport { initializeApp } from \"firebase/app\";\nimport { getAuth } from \"firebase/auth\";\n// Use lazy initialization to avoid accessing Env before it's initialized\nlet _firebaseApp = null;\nlet _analytics = null;\nlet _firebaseAuth = null;\n// Getters that lazily initialize Firebase components when first accessed\nexport function getFirebaseApp() {\n if (!_firebaseApp) {\n try {\n if (!Env.firebase) {\n throw new Error(\"Firebase configuration is not available in the environment\");\n }\n _firebaseApp = initializeApp(Env.firebase);\n }\n catch (error) {\n console.error(\"Failed to initialize Firebase app:\", error);\n throw new Error(\"Firebase initialization failed - environment may not be properly initialized\");\n }\n }\n return _firebaseApp;\n}\nexport function getFirebaseAnalytics() {\n if (!_analytics) {\n _analytics = getAnalytics(getFirebaseApp());\n }\n return _analytics;\n}\nexport function getFirebaseAuth() {\n if (!_firebaseAuth) {\n _firebaseAuth = getAuth(getFirebaseApp());\n }\n return _firebaseAuth;\n}\nexport async function setFirebaseTenant(tenantEmail) {\n if (!tenantEmail) {\n console.log(\"No tenant name or email specified, skipping tenant setup\");\n return;\n }\n if (!Env.firebase) {\n console.log(\"Firebase configuration is not available in the environment\");\n return;\n }\n try {\n if (tenantEmail)\n console.log(`Resolving tenant ID from email: ${tenantEmail}`);\n // Add retry logic with exponential backoff\n let retries = 3;\n let retryDelay = 250; // Start with 250ms delay\n while (retries > 0) {\n try {\n // Call the API endpoint to resolve the tenant ID\n const response = await fetch(\"/api/resolve-tenant\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({\n tenantEmail: tenantEmail,\n }),\n // Add timeout to prevent hanging requests\n signal: AbortSignal.timeout(5000),\n });\n // Check for network errors\n if (!response) {\n throw new Error(\"No response received from tenant API\");\n }\n // Handle HTTP error responses\n if (!response.ok) {\n // Try to parse the error response\n try {\n const errorData = await response.json();\n console.error(\"Failed to resolve tenant ID:\", errorData.error);\n }\n catch (parseError) {\n console.error(`Failed to resolve tenant ID: HTTP ${response.status}`);\n }\n // If the error is 404 Not Found, no need to retry\n if (response.status === 404) {\n console.warn(`Tenant not found for ${tenantEmail}`);\n return;\n }\n throw new Error(`HTTP error ${response.status}`);\n }\n // Successfully got a response, parse it\n const data = (await response.json());\n if (data && data.firebaseTenantId) {\n const auth = getFirebaseAuth();\n auth.tenantId = data.firebaseTenantId;\n Env.firebase.providerType = data.provider ?? \"oidc\";\n console.log(`Tenant ID set to ${auth.tenantId}`);\n return data;\n }\n else {\n console.error(`Invalid response format, missing tenantId for ${tenantEmail}`);\n return; // No need to retry for invalid response format\n }\n }\n catch (fetchError) {\n // Only retry for network-related errors\n if (retries > 1) {\n console.warn(`Tenant resolution failed, retrying in ${retryDelay}ms...`, fetchError);\n await new Promise((resolve) => setTimeout(resolve, retryDelay));\n retryDelay *= 2; // Exponential backoff\n retries--;\n }\n else {\n throw fetchError; // Last retry failed, propagate error\n }\n }\n }\n }\n catch (error) {\n // Final error handler\n console.error(\"Error setting Firebase tenant:\", error instanceof Error ? error.message : \"Unknown error\");\n // Continue without tenant ID - authentication will work without multi-tenancy\n // but the user will access the default tenant\n }\n}\nexport async function getFirebaseAuthToken(refresh) {\n const auth = getFirebaseAuth();\n const user = auth.currentUser;\n if (user) {\n return user\n .getIdToken(refresh)\n .then((token) => {\n Env.logger.info(\"Got Firebase token\", {\n vertesia: {\n user_email: user.email,\n user_name: user.displayName,\n user_id: user.uid,\n refresh: refresh,\n },\n });\n return token;\n })\n .catch((err) => {\n Env.logger.error(\"Failed to get Firebase token\", {\n vertesia: {\n user_email: user.email,\n user_name: user.displayName,\n user_id: user.uid,\n refresh: refresh,\n error: err,\n },\n });\n console.error(\"Failed to get access token\", err);\n return null;\n });\n }\n else {\n Env.logger.warn(\"No user found\");\n return Promise.resolve(null);\n }\n}\n//# sourceMappingURL=firebase.js.map","import { jwtDecode } from \"jwt-decode\";\nimport { Env } from '@vertesia/ui/env';\nimport { LastSelectedAccountId_KEY, LastSelectedProjectId_KEY } from '../constants';\nimport { getFirebaseAuth, getFirebaseAuthToken } from './firebase';\nlet AUTH_TOKEN_RAW;\nlet AUTH_TOKEN;\nexport async function fetchComposableToken(getIdToken, accountId, projectId, ttl) {\n console.log(`Getting/refreshing composable token for account ${accountId} and project ${projectId} `);\n Env.logger.info('Getting/refreshing composable token', {\n vertesia: {\n account_id: accountId,\n project_id: projectId,\n },\n });\n const idToken = await getIdToken(); //get from firebase\n if (!idToken) {\n console.log('No id token found - using cookie auth');\n throw new Error('No id token found');\n }\n console.log('Fetching composable token from ' + Env.endpoints.studio);\n Env.logger.info('Fetching composable token from' + Env.endpoints.studio, {\n vertesia: {\n account_id: accountId,\n project_id: projectId,\n },\n });\n const url = new URL(Env.endpoints.studio + '/auth/token');\n if (accountId)\n url.searchParams.set('accountId', accountId);\n if (projectId)\n url.searchParams.set('projectId', projectId);\n if (ttl)\n url.searchParams.set('ttl', String(ttl));\n console.log(`Getting composable token for account ${accountId} and project ${projectId}`);\n Env.logger.info('Getting composable token', {\n vertesia: {\n account_id: accountId,\n project_id: projectId,\n },\n });\n const res = await fetch(url, {\n method: 'GET',\n headers: {\n 'Content-Type': 'application/json',\n 'Authorization': `Bearer ${idToken}`\n }\n }).catch(err => {\n localStorage.removeItem(LastSelectedAccountId_KEY);\n localStorage.removeItem(LastSelectedProjectId_KEY);\n console.error('Failed to get composable token', err);\n Env.logger.error('Failed to get composable token', {\n vertesia: {\n account_id: accountId,\n project_id: projectId,\n error: err,\n },\n });\n throw new Error('Failed to get composable token');\n });\n if (idToken && res?.status === 412) {\n console.log(\"412: auth succeeded but user doesn't exist - signup required\", res?.status);\n Env.logger.error(\"412: auth succeeded but user doesn't exist - signup required\", {\n vertesia: {\n account_id: accountId,\n project_id: projectId,\n status: res?.status\n },\n });\n const idTokenDecoded = jwtDecode(idToken);\n if (!idTokenDecoded?.email) {\n Env.logger.error('No email found in id token');\n throw new Error('No email found in id token');\n }\n Env.logger.error('User not found', {\n vertesia: {\n account_id: accountId,\n project_id: projectId,\n email: idTokenDecoded.email\n }\n });\n throw new UserNotFoundError('User not found', idTokenDecoded.email);\n }\n if (!res || !res.ok) {\n console.error('Failed to get composable token', res);\n Env.logger.error('Failed to get composable token', {\n vertesia: {\n account_id: accountId,\n project_id: projectId,\n status: res?.status,\n },\n });\n throw new Error('Failed to get composable token');\n }\n const { token } = await res.json().catch(err => {\n Env.logger.error('Failed to parse composable token', {\n vertesia: {\n account_id: accountId,\n project_id: projectId,\n error: err,\n },\n });\n console.error('Failed to parse composable token', err);\n });\n return token;\n}\n/**\n *\n * @param accountId\n * @param projectId\n * @param ttl time to live for the token in seconds\n * @returns\n */\nexport async function fetchComposableTokenFromFirebaseToken(accountId, projectId, ttl) {\n return fetchComposableToken(getFirebaseAuthToken, accountId, projectId, ttl);\n}\nexport async function getComposableToken(accountId, projectId, initToken, forceRefresh = false, useInternalAuth = false) {\n const selectedAccount = accountId ?? localStorage.getItem(LastSelectedAccountId_KEY) ?? undefined;\n const selectedProject = projectId ?? localStorage.getItem(LastSelectedProjectId_KEY + '-' + selectedAccount) ?? undefined;\n //token is still valid for more than 5 minutes\n if (!forceRefresh && AUTH_TOKEN_RAW && AUTH_TOKEN && AUTH_TOKEN.exp > (Date.now() / 1000 + 300)) {\n return { rawToken: AUTH_TOKEN_RAW, token: AUTH_TOKEN, error: false };\n }\n //token is close to expire, refresh it\n if (!useInternalAuth && getFirebaseAuth().currentUser) {\n //we have a firebase user, get the token from there\n AUTH_TOKEN_RAW = await fetchComposableTokenFromFirebaseToken(selectedAccount, selectedProject);\n }\n else if (initToken || AUTH_TOKEN_RAW) {\n // we have a token already and no firebase user, refresh it\n AUTH_TOKEN_RAW = await fetchComposableToken(() => Promise.resolve(initToken ?? AUTH_TOKEN_RAW), selectedAccount, selectedProject);\n }\n if (!AUTH_TOKEN_RAW) {\n Env.logger.error('Cannot acquire a composable token', {\n vertesia: {\n account_id: selectedAccount,\n project_id: selectedProject,\n },\n });\n throw new Error('Cannot acquire a composable token');\n }\n AUTH_TOKEN = jwtDecode(AUTH_TOKEN_RAW);\n if (!AUTH_TOKEN || !AUTH_TOKEN.exp || !AUTH_TOKEN_RAW) {\n console.error('Invalid composable token', AUTH_TOKEN);\n Env.logger.error('Invalid composable token', {\n vertesia: {\n account_id: selectedAccount,\n project_id: selectedProject,\n },\n });\n throw new Error('Invalid composable token');\n }\n return { rawToken: AUTH_TOKEN_RAW, token: AUTH_TOKEN, error: false };\n}\nexport class UserNotFoundError extends Error {\n email;\n constructor(message, email) {\n super(message);\n this.name = 'UserNotFoundError';\n this.email = email;\n }\n}\n//# sourceMappingURL=composable.js.map","import { useState, useEffect } from 'react';\nimport { useUserSession } from \"@vertesia/ui/session\";\nexport function useCurrentTenant() {\n const { user } = useUserSession();\n const [currentTenant, setCurrentTenant] = useState(null);\n const [isLoading, setIsLoading] = useState(true);\n const [error, setError] = useState(null);\n useEffect(() => {\n const loadCurrentTenant = async () => {\n if (!user?.email) {\n setCurrentTenant(null);\n setIsLoading(false);\n return;\n }\n try {\n const response = await fetch('/api/resolve-tenant', {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({\n tenantEmail: user.email\n })\n });\n if (response.ok) {\n const tenantData = await response.json();\n if (tenantData) {\n // Convert the resolved tenant data to our TenantConfig format\n setCurrentTenant({\n tenantKey: tenantData.name || 'unknown',\n name: tenantData.label || tenantData.name || 'Unknown',\n domain: tenantData.domain || [],\n firebaseTenantId: tenantData.firebaseTenantId,\n provider: tenantData.provider,\n logo: tenantData.logo\n });\n }\n else {\n setCurrentTenant(null);\n }\n }\n else {\n setCurrentTenant(null);\n }\n }\n catch (error) {\n console.error('Error loading current tenant:', error);\n setError('Failed to load tenant configuration');\n setCurrentTenant(null);\n }\n finally {\n setIsLoading(false);\n }\n };\n loadCurrentTenant();\n }, [user?.email]);\n return {\n currentTenant,\n isLoading,\n error\n };\n}\n//# sourceMappingURL=useCurrentTenant.js.map","export class TypeRegistry {\n types;\n map = {};\n constructor(types) {\n this.types = types;\n //sort types\n types.sort((a, b) => a.name.localeCompare(b.name));\n for (const type of types) {\n this.map[type.id] = type;\n }\n }\n getType(id) {\n return this.map[id];\n }\n getTypeLayout(id) {\n const type = this.map[id];\n return type ? type.table_layout : undefined;\n }\n getTypeName(id) {\n const type = this.map[id];\n return type ? type.name : undefined;\n }\n}\n//# sourceMappingURL=TypeRegistry.js.map","import { jwtDecode } from 'jwt-decode';\nimport { createContext, useContext } from 'react';\nimport { VertesiaClient } from '@vertesia/client';\nimport { Env } from '@vertesia/ui/env';\nimport { getComposableToken } from './auth/composable';\nimport { getFirebaseAuth } from './auth/firebase';\nimport { TypeRegistry } from './TypeRegistry';\nimport { LastSelectedAccountId_KEY, LastSelectedProjectId_KEY } from './constants';\nexport { LastSelectedAccountId_KEY, LastSelectedProjectId_KEY };\nclass UserSession {\n isLoading = true;\n client;\n authError;\n authToken;\n typeRegistry;\n setSession;\n lastSelectedAccount;\n lastSelectedProject;\n onboardingComplete;\n constructor(client, setSession) {\n if (client) {\n this.client = client;\n }\n else {\n this.client = new VertesiaClient({\n serverUrl: Env.endpoints.studio,\n storeUrl: Env.endpoints.zeno,\n });\n }\n if (setSession) {\n this.setSession = setSession;\n }\n this.logout = this.logout.bind(this);\n }\n get store() {\n return this.client.store;\n }\n get user() {\n return this.authToken;\n }\n get account() {\n return this.authToken?.account;\n }\n get project() {\n return this.authToken?.project;\n }\n get accounts() {\n return this.authToken?.accounts;\n }\n get authCallback() {\n return this.rawAuthToken.then(token => `Bearer ${token}`);\n }\n get rawAuthToken() {\n return getComposableToken().then(res => {\n const token = res?.rawToken;\n if (!token) {\n throw new Error('No token available');\n }\n this.authToken = jwtDecode(token);\n return token;\n });\n }\n signOut() {\n this.logout();\n }\n getAccount() {\n return this.authToken?.account;\n }\n async login(token) {\n this.authError = undefined;\n this.isLoading = false;\n this.client.withAuthCallback(() => this.authCallback);\n this.authToken = jwtDecode(token);\n console.log(`Logging in as ${this.authToken?.name} with account ${this.authToken?.account.name} (${this.authToken?.account.id}, and project ${this.authToken?.project?.name} (${this.authToken?.project?.id})`);\n //store selected account in local storage\n localStorage.setItem(LastSelectedAccountId_KEY, this.authToken.account.id);\n localStorage.setItem(LastSelectedProjectId_KEY + '-' + this.authToken.account.id, this.authToken.project?.id ?? '');\n // notify the host app of the login\n Env.onLogin?.(this.authToken);\n // Independent async calls\n await Promise.all([\n this._loadTypes(),\n this.fetchOnboardingStatus(),\n ]);\n return Promise.resolve();\n }\n isLoggedIn() {\n return !!this.authToken;\n }\n logout() {\n console.log('Logging out');\n if (this.authToken) {\n getFirebaseAuth().signOut();\n }\n this.authError = undefined;\n this.isLoading = false;\n this.authToken = undefined;\n this.typeRegistry = undefined;\n this.setSession = undefined;\n this.client.withAuthCallback(undefined);\n }\n async switchAccount(targetAccountId) {\n localStorage.setItem(LastSelectedAccountId_KEY, targetAccountId);\n if (this) {\n if (this.account && this.project) {\n localStorage.setItem(LastSelectedProjectId_KEY + '-' + this.account.id, this.project.id);\n }\n else if (this.account) {\n localStorage.removeItem(LastSelectedProjectId_KEY + '-' + this.account.id);\n }\n }\n window.location.replace('/?a=' + targetAccountId);\n }\n async switchProject(targetProjectId) {\n if (this.account) {\n localStorage.setItem(LastSelectedProjectId_KEY + '-' + this.account.id, targetProjectId);\n }\n window.location.replace('/?a=' + this.account?.id + '&p=' + targetProjectId);\n }\n async _loadTypes() {\n if (this.project) {\n return this.store.types.list({}, { layout: true }).then(types => this.typeRegistry = new TypeRegistry(types)).catch(err => {\n console.error('Failed to fetch object types', err);\n throw err;\n });\n }\n else {\n console.log('No project selected');\n }\n }\n async reloadTypes() {\n return this._loadTypes().then(() => {\n this.setSession?.(this.clone());\n });\n }\n async fetchAccounts() {\n return this.client.accounts.list().then(accounts => {\n if (!this.authToken) {\n throw new Error('No token available');\n }\n this.authToken.accounts = accounts;\n this.setSession?.(this.clone());\n }).catch(err => {\n console.error('Failed to fetch accounts', err);\n throw err;\n });\n }\n async fetchOnboardingStatus() {\n if (this.onboardingComplete) {\n console.log('Onboarding already completed');\n return false;\n }\n const previousStatus = this.onboardingComplete;\n try {\n const onboarding = await this.client.account.onboardingProgress();\n this.onboardingComplete = Object.values(onboarding).every(value => value === true);\n if (previousStatus !== this.onboardingComplete) {\n return true;\n }\n this.setSession?.(this.clone());\n }\n catch (error) {\n console.error('Error fetching onboarding status:', error);\n this.onboardingComplete = false;\n this.setSession?.(this.clone());\n }\n return false;\n }\n clone() {\n const session = new UserSession(this.client);\n session.isLoading = this.isLoading;\n session.authError = this.authError;\n session.authToken = this.authToken;\n session.setSession = this.setSession;\n session.lastSelectedAccount = this.lastSelectedAccount;\n session.switchAccount = this.switchAccount;\n session.typeRegistry = this.typeRegistry;\n session.onboardingComplete = this.onboardingComplete;\n return session;\n }\n}\nconst UserSessionContext = createContext(undefined);\nexport function useUserSession() {\n const session = useContext(UserSessionContext);\n if (!session) {\n throw new Error('useUserSession must be used within a UserSessionProvider');\n }\n return session;\n}\nexport { UserSession, UserSessionContext };\n//# sourceMappingURL=UserSession.js.map","/**\n * This hook is used to generate and verify state for OAuth2 authorization requests.\n * @returns\n */\nimport { useCallback } from \"react\";\nconst AUTH_STATE_KEY = 'auth_state';\nconst STATE_EXPIRY_KEY = 'auth_state_expiry';\nconst STATE_TTL = 5 * 60 * 1000; // 5 min\nexport function useAuthState() {\n // Generate new state\n const generateState = useCallback(() => {\n const state = crypto.randomUUID();\n const expiryTime = Date.now() + STATE_TTL;\n // Store state and expiry\n sessionStorage.setItem(AUTH_STATE_KEY, state);\n sessionStorage.setItem(STATE_EXPIRY_KEY, expiryTime.toString());\n return state;\n }, []);\n // Verify returned state\n const verifyState = useCallback((returnedState) => {\n if (!returnedState) {\n return 'Missing state';\n }\n const savedState = sessionStorage.getItem(AUTH_STATE_KEY);\n const expiryTime = parseInt(sessionStorage.getItem(STATE_EXPIRY_KEY) || '0');\n let reason;\n // Verify state matches and hasn't expired\n if (savedState !== returnedState) {\n reason = `State mismatched (${savedState} !== ${returnedState})`;\n }\n else if (Date.now() > expiryTime) {\n reason = 'State expired';\n }\n else {\n reason = undefined; // No errors\n }\n return reason;\n }, []);\n // Clear state (useful for cleanup)\n const clearState = useCallback(() => {\n sessionStorage.removeItem(AUTH_STATE_KEY);\n sessionStorage.removeItem(STATE_EXPIRY_KEY);\n }, []);\n return { generateState, verifyState, clearState };\n}\n//# sourceMappingURL=useAuthState.js.map","import { jsx as _jsx } from \"react/jsx-runtime\";\nimport { onAuthStateChanged } from \"firebase/auth\";\nimport { useEffect, useState } from \"react\";\nimport { UserNotFoundError, getComposableToken } from \"./auth/composable\";\nimport { getFirebaseAuth } from \"./auth/firebase\";\nimport { useAuthState } from \"./auth/useAuthState\";\nimport { Env } from \"@vertesia/ui/env\";\nimport { LastSelectedAccountId_KEY, LastSelectedProjectId_KEY, UserSession, UserSessionContext } from \"./UserSession\";\nconst devDomains = [\".composable.sh\", \".vertesia.dev\", \"vertesia.app\"];\nconst CENTRAL_AUTH_REDIRECT = \"https://internal-auth.vertesia.app/\";\nfunction shouldRedirectToCentralAuth() {\n // Authentication is not supported in Docker environment.\n // See https://github.com/vertesia/studio/wiki/Composable-UI-Hosting-Options\n if (Env.isDocker) {\n return true;\n }\n return devDomains.some((domain) => window.location.hostname.endsWith(domain));\n}\nexport function UserSessionProvider({ children }) {\n const hashParams = new URLSearchParams(location.hash.substring(1));\n const token = hashParams.get(\"token\");\n const state = hashParams.get(\"state\");\n const [session, setSession] = useState(new UserSession());\n const { generateState, verifyState, clearState } = useAuthState();\n const redirectToCentralAuth = (projectId, accountId) => {\n const url = new URL(CENTRAL_AUTH_REDIRECT);\n const currentUrl = new URL(window.location.href);\n currentUrl.hash = \"\";\n if (projectId)\n currentUrl.searchParams.set(\"p\", projectId);\n if (accountId)\n currentUrl.searchParams.set(\"a\", accountId);\n url.searchParams.set(\"redirect_uri\", currentUrl.toString());\n url.searchParams.set(\"state\", generateState());\n location.replace(url.toString());\n };\n useEffect(() => {\n console.log(\"Auth: starting auth flow\");\n Env.logger.info(\"Starting auth flow\");\n const currentUrl = new URL(window.location.href);\n const selectedAccount = currentUrl.searchParams.get(\"a\") ?? localStorage.getItem(LastSelectedAccountId_KEY) ?? undefined;\n const selectedProject = currentUrl.searchParams.get(\"p\") ??\n localStorage.getItem(LastSelectedProjectId_KEY + \"-\" + selectedAccount) ??\n undefined;\n console.log(\"Auth: selected account\", selectedAccount);\n console.log(\"Auth: selected project\", selectedProject);\n Env.logger.info(\"Selected account and project\", {\n vertesia: {\n account_id: selectedAccount,\n project_id: selectedProject,\n },\n });\n if (token && state) {\n const validationError = verifyState(state);\n if (validationError) {\n console.error(`Auth: invalid state: ${validationError}`);\n Env.logger.error(`Invalid state: ${validationError}`, {\n vertesia: {\n state: state,\n },\n });\n redirectToCentralAuth();\n }\n else {\n clearState();\n }\n getComposableToken(selectedAccount, selectedProject, token, false, shouldRedirectToCentralAuth())\n .then((res) => {\n session.login(res.rawToken).then(() => {\n setSession(session.clone());\n //cleanup the hash\n window.location.hash = \"\";\n });\n })\n .catch((err) => {\n console.error(\"Failed to fetch user token from studio, redirecting to central auth\", err);\n Env.logger.error(\"Failed to fetch user token from studio, redirecting to central auth\", {\n vertesia: {\n error: err,\n },\n });\n redirectToCentralAuth();\n });\n return;\n }\n else {\n //if on a dev domain and not logged in, redirect to central auth\n if (!session.isLoggedIn()) {\n console.log(\"Auth: not logged in & no token/state\");\n Env.logger.info(\"Not logged in & no token/state\", {\n vertesia: {\n account_id: selectedAccount,\n project_id: selectedProject,\n },\n });\n if (shouldRedirectToCentralAuth()) {\n console.log(\"Auth: on dev domain, redirecting to central auth with selection\", selectedAccount, selectedProject);\n Env.logger.info(\"Redirecting to central auth with selection\", {\n vertesia: {\n account_id: selectedAccount,\n project_id: selectedProject,\n },\n });\n redirectToCentralAuth();\n }\n else {\n console.log(\"Auth: not on dev domain\");\n Env.logger.info(\"Not on dev domain\", {\n vertesia: {\n account_id: selectedAccount,\n project_id: selectedProject,\n },\n });\n }\n }\n }\n return onAuthStateChanged(getFirebaseAuth(), async (firebaseUser) => {\n if (firebaseUser) {\n console.log(\"Auth: successful login with firebase\");\n Env.logger.info(\"Successful login with firebase\", {\n vertesia: {\n account_id: selectedAccount,\n project_id: selectedProject,\n },\n });\n session.setSession = setSession;\n await getComposableToken(selectedAccount, selectedProject, undefined, false, shouldRedirectToCentralAuth())\n .then((res) => {\n session.login(res.rawToken).then(() => setSession(session.clone()));\n })\n .catch((err) => {\n console.error(\"Failed to fetch user token from studio\", err);\n Env.logger.error(\"Failed to fetch user token from studio\", {\n vertesia: {\n account_id: selectedAccount,\n project_id: selectedProject,\n error: err,\n },\n });\n if (!(err instanceof UserNotFoundError))\n session.logout();\n session.isLoading = false;\n session.authError = err;\n setSession(session.clone());\n });\n }\n else {\n // anonymous user\n console.log(\"Auth: using anonymous user\");\n Env.logger.info(\"Using anonymous user\", {\n vertesia: {\n account_id: selectedAccount,\n project_id: selectedProject,\n },\n });\n session.client.withAuthCallback(undefined);\n session.logout();\n setSession(session.clone());\n }\n });\n }, []);\n return _jsx(UserSessionContext.Provider, { value: session, children: children });\n}\n//# sourceMappingURL=UserSessionProvider.js.map","import { Env } from '@vertesia/ui/env';\nimport { logEvent } from \"firebase/analytics\";\nimport { getFirebaseAnalytics } from \"./auth/firebase\";\nexport function useUXTracking() {\n //identify user in monitoring and UX systems\n const tagUserSession = async (user) => {\n const signupData = window.localStorage.getItem(\"composableSignupData\");\n if (!user) {\n console.error('No user found -- skipping tagging');\n return;\n }\n if (signupData) {\n window.localStorage.removeItem(\"composableSignupData\");\n }\n };\n //send event to analytics and UX systems\n const trackEvent = (eventName, eventProperties) => {\n if (!Env.isProd) {\n console.debug('track event', eventName, eventProperties);\n }\n //GA via firebase\n logEvent(getFirebaseAnalytics(), eventName, { ...eventProperties, debug_mode: !Env.isProd });\n };\n return {\n tagUserSession,\n trackEvent\n };\n}\n//# sourceMappingURL=useUXTracking.js.map"],"names":["LastSelectedAccountId_KEY","LastSelectedProjectId_KEY","AUTH_TOKEN_RAW","AUTH_TOKEN","_firebaseApp","_analytics","_firebaseAuth","getFirebaseApp","Env","firebase","Error","initializeApp","error","console","getFirebaseAnalytics","getAnalytics","getFirebaseAuth","getAuth","async","setFirebaseTenant","tenantEmail","log","retries","retryDelay","response","fetch","method","headers","body","JSON","stringify","signal","AbortSignal","timeout","ok","errorData","json","parseError","status","warn","data","firebaseTenantId","auth","tenantId","providerType","provider","fetchError","Promise","resolve","setTimeout","message","getFirebaseAuthToken","refresh","user","currentUser","getIdToken","then","token","logger","info","vertesia","user_email","email","user_name","displayName","user_id","uid","catch","err","fetchComposableToken","accountId","projectId","ttl","account_id","project_id","idToken","endpoints","studio","url","URL","searchParams","set","String","res","Authorization","localStorage","removeItem","idTokenDecoded","jwtDecode","UserNotFoundError","fetchComposableTokenFromFirebaseToken","getComposableToken","initToken","forceRefresh","useInternalAuth","selectedAccount","getItem","undefined","selectedProject","exp","Date","now","rawToken","constructor","super","this","name","useCurrentTenant","useUserSession","currentTenant","setCurrentTenant","useState","isLoading","setIsLoading","setError","useEffect","tenantData","tenantKey","label","domain","logo","loadCurrentTenant","TypeRegistry","types","map","sort","a","b","localeCompare","type","id","getType","getTypeLayout","table_layout","getTypeName","UserSession","client","authError","authToken","typeRegistry","setSession","lastSelectedAccount","lastSelectedProject","onboardingComplete","VertesiaClient","serverUrl","storeUrl","zeno","logout","bind","store","account","project","accounts","authCallback","rawAuthToken","signOut","getAccount","login","withAuthCallback","setItem","onLogin","all","_loadTypes","fetchOnboardingStatus","isLoggedIn","switchAccount","targetAccountId","window","location","replace","switchProject","targetProjectId","list","layout","reloadTypes","clone","fetchAccounts","previousStatus","onboarding","onboardingProgress","Object","values","every","value","session","UserSessionContext","createContext","useContext","AUTH_STATE_KEY","STATE_EXPIRY_KEY","devDomains","shouldRedirectToCentralAuth","isDocker","some","hostname","endsWith","UserSessionProvider","children","hashParams","URLSearchParams","hash","substring","get","state","generateState","verifyState","clearState","useCallback","crypto","randomUUID","expiryTime","sessionStorage","toString","returnedState","savedState","parseInt","reason","redirectToCentralAuth","currentUrl","href","validationError","onAuthStateChanged","firebaseUser","_jsx","Provider","useUXTracking","tagUserSession","signupData","trackEvent","eventName","eventProperties","isProd","debug","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AAa5D,OAAOnF,aAAaW,QAAQ,wBAC1C3C,EAID+K,GACA5D,OAAOnF,aAAaC,WAAW,wBAJ/BzE,QAAQD,MAAM,sCAiBlByN,WATe,CAACC,EAAWC,KACtB/N,EAAIgO,QACL3N,QAAQ4N,MAAM,cAAeH,EAAWC,GAG5CG,EAAS5N,IAAwBwN,EAAW,IAAKC,EAAiBI,YAAanO,EAAIgO,UAM3F"}
|
|
1
|
+
{"version":3,"file":"vertesia-ui-session.js","sources":["esm/session/constants.js","esm/session/auth/firebase.js","esm/session/auth/composable.js","esm/session/auth/useCurrentTenant.js","esm/session/TypeRegistry.js","esm/session/UserSession.js","esm/session/auth/useAuthState.js","esm/session/UserSessionProvider.js","esm/session/useUXTracking.js"],"sourcesContent":["export const LastSelectedAccountId_KEY = 'composableai.lastSelectedAccountId';\nexport const LastSelectedProjectId_KEY = 'composableai.lastSelectedProjectId';\n//# sourceMappingURL=constants.js.map","import { Env } from \"@vertesia/ui/env\";\nimport { getAnalytics } from \"firebase/analytics\";\nimport { initializeApp } from \"firebase/app\";\nimport { getAuth } from \"firebase/auth\";\n// Use lazy initialization to avoid accessing Env before it's initialized\nlet _firebaseApp = null;\nlet _analytics = null;\nlet _firebaseAuth = null;\n// Getters that lazily initialize Firebase components when first accessed\nexport function getFirebaseApp() {\n if (!_firebaseApp) {\n try {\n if (!Env.firebase) {\n throw new Error(\"Firebase configuration is not available in the environment\");\n }\n _firebaseApp = initializeApp(Env.firebase);\n }\n catch (error) {\n console.error(\"Failed to initialize Firebase app:\", error);\n throw new Error(\"Firebase initialization failed - environment may not be properly initialized\");\n }\n }\n return _firebaseApp;\n}\nexport function getFirebaseAnalytics() {\n if (!_analytics) {\n _analytics = getAnalytics(getFirebaseApp());\n }\n return _analytics;\n}\nexport function getFirebaseAuth() {\n if (!_firebaseAuth) {\n _firebaseAuth = getAuth(getFirebaseApp());\n }\n return _firebaseAuth;\n}\nexport async function setFirebaseTenant(tenantEmail) {\n if (!tenantEmail) {\n console.log(\"No tenant name or email specified, skipping tenant setup\");\n return;\n }\n if (!Env.firebase) {\n console.log(\"Firebase configuration is not available in the environment\");\n return;\n }\n try {\n if (tenantEmail)\n console.log(`Resolving tenant ID from email: ${tenantEmail}`);\n // Add retry logic with exponential backoff\n let retries = 3;\n let retryDelay = 250; // Start with 250ms delay\n while (retries > 0) {\n try {\n // Call the API endpoint to resolve the tenant ID\n const response = await fetch(\"/api/resolve-tenant\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({\n tenantEmail: tenantEmail,\n }),\n // Add timeout to prevent hanging requests\n signal: AbortSignal.timeout(5000),\n });\n // Check for network errors\n if (!response) {\n throw new Error(\"No response received from tenant API\");\n }\n // Handle HTTP error responses\n if (!response.ok) {\n // Try to parse the error response\n try {\n const errorData = await response.json();\n console.error(\"Failed to resolve tenant ID:\", errorData.error);\n }\n catch (parseError) {\n console.error(`Failed to resolve tenant ID: HTTP ${response.status}`);\n }\n // If the error is 404 Not Found, no need to retry\n if (response.status === 404) {\n console.warn(`Tenant not found for ${tenantEmail}`);\n return;\n }\n throw new Error(`HTTP error ${response.status}`);\n }\n // Successfully got a response, parse it\n const data = (await response.json());\n if (data && data.firebaseTenantId) {\n const auth = getFirebaseAuth();\n auth.tenantId = data.firebaseTenantId;\n Env.firebase.providerType = data.provider ?? \"oidc\";\n console.log(`Tenant ID set to ${auth.tenantId}`);\n return data;\n }\n else {\n console.error(`Invalid response format, missing tenantId for ${tenantEmail}`);\n return; // No need to retry for invalid response format\n }\n }\n catch (fetchError) {\n // Only retry for network-related errors\n if (retries > 1) {\n console.warn(`Tenant resolution failed, retrying in ${retryDelay}ms...`, fetchError);\n await new Promise((resolve) => setTimeout(resolve, retryDelay));\n retryDelay *= 2; // Exponential backoff\n retries--;\n }\n else {\n throw fetchError; // Last retry failed, propagate error\n }\n }\n }\n }\n catch (error) {\n // Final error handler\n console.error(\"Error setting Firebase tenant:\", error instanceof Error ? error.message : \"Unknown error\");\n // Continue without tenant ID - authentication will work without multi-tenancy\n // but the user will access the default tenant\n }\n}\nexport async function getFirebaseAuthToken(refresh) {\n const auth = getFirebaseAuth();\n const user = auth.currentUser;\n if (user) {\n return user\n .getIdToken(refresh)\n .then((token) => {\n Env.logger.info(\"Got Firebase token\", {\n vertesia: {\n user_email: user.email,\n user_name: user.displayName,\n user_id: user.uid,\n refresh: refresh,\n },\n });\n return token;\n })\n .catch((err) => {\n Env.logger.error(\"Failed to get Firebase token\", {\n vertesia: {\n user_email: user.email,\n user_name: user.displayName,\n user_id: user.uid,\n refresh: refresh,\n error: err,\n },\n });\n console.error(\"Failed to get access token\", err);\n return null;\n });\n }\n else {\n Env.logger.warn(\"No user found\");\n return Promise.resolve(null);\n }\n}\n//# sourceMappingURL=firebase.js.map","import { jwtDecode } from \"jwt-decode\";\nimport { Env } from '@vertesia/ui/env';\nimport { LastSelectedAccountId_KEY, LastSelectedProjectId_KEY } from '../constants';\nimport { getFirebaseAuth, getFirebaseAuthToken } from './firebase';\nlet AUTH_TOKEN_RAW;\nlet AUTH_TOKEN;\nexport async function fetchComposableToken(getIdToken, accountId, projectId, ttl) {\n console.log(`Getting/refreshing composable token for account ${accountId} and project ${projectId} `);\n Env.logger.info('Getting/refreshing composable token', {\n vertesia: {\n account_id: accountId,\n project_id: projectId,\n },\n });\n const idToken = await getIdToken(); //get from firebase\n if (!idToken) {\n console.log('No id token found - using cookie auth');\n throw new Error('No id token found');\n }\n // Use STS endpoint - either configured or default to sts.vertesia.io\n const stsEndpoint = Env.endpoints.sts;\n console.log('Using STS for token generation:', stsEndpoint);\n Env.logger.info('Using STS for token generation', {\n vertesia: {\n account_id: accountId,\n project_id: projectId,\n sts_url: stsEndpoint,\n },\n });\n try {\n // Call STS to generate a user token\n const stsUrl = new URL(stsEndpoint + '/token/issue');\n const requestBody = {\n type: 'user',\n account_id: accountId,\n project_id: projectId,\n expires_at: ttl ? Math.floor(Date.now() / 1000) + ttl : undefined,\n };\n const stsRes = await fetch(stsUrl, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'Authorization': `Bearer ${idToken}` // Firebase token for authentication\n },\n body: JSON.stringify(requestBody)\n });\n if (idToken && stsRes?.status === 412) {\n console.log(\"412: auth succeeded but user doesn't exist - signup required\", stsRes?.status);\n Env.logger.error(\"412: auth succeeded but user doesn't exist - signup required\", {\n vertesia: {\n account_id: accountId,\n project_id: projectId,\n status: stsRes?.status\n },\n });\n const idTokenDecoded = jwtDecode(idToken);\n if (!idTokenDecoded?.email) {\n Env.logger.error('No email found in id token');\n throw new Error('No email found in id token');\n }\n Env.logger.error('User not found', {\n vertesia: {\n account_id: accountId,\n project_id: projectId,\n email: idTokenDecoded.email\n }\n });\n throw new UserNotFoundError('User not found', idTokenDecoded.email);\n }\n if (!stsRes.ok) {\n const errorText = await stsRes.text();\n console.error('STS token generation failed:', stsRes.status, errorText);\n Env.logger.error('STS token generation failed', {\n vertesia: {\n status: stsRes.status,\n error: errorText,\n account_id: accountId,\n project_id: projectId,\n },\n });\n throw new Error(`Failed to get token from STS: ${stsRes.status}`);\n }\n const { token } = await stsRes.json();\n console.log('Successfully got token from STS');\n Env.logger.info('Successfully got token from STS');\n return token;\n }\n catch (error) {\n if (error instanceof UserNotFoundError) {\n throw error; // Re-throw UserNotFoundError\n }\n localStorage.removeItem(LastSelectedAccountId_KEY);\n localStorage.removeItem(LastSelectedProjectId_KEY);\n console.error('Failed to get composable token from STS', error);\n Env.logger.error('Failed to get composable token from STS', {\n vertesia: {\n account_id: accountId,\n project_id: projectId,\n error: error,\n },\n });\n throw new Error('Failed to get composable token');\n }\n}\n/**\n *\n * @param accountId\n * @param projectId\n * @param ttl time to live for the token in seconds\n * @returns\n */\nexport async function fetchComposableTokenFromFirebaseToken(accountId, projectId, ttl) {\n return fetchComposableToken(getFirebaseAuthToken, accountId, projectId, ttl);\n}\nexport async function getComposableToken(accountId, projectId, initToken, forceRefresh = false, useInternalAuth = false) {\n const selectedAccount = accountId ?? localStorage.getItem(LastSelectedAccountId_KEY) ?? undefined;\n const selectedProject = projectId ?? localStorage.getItem(LastSelectedProjectId_KEY + '-' + selectedAccount) ?? undefined;\n //token is still valid for more than 5 minutes\n if (!forceRefresh && AUTH_TOKEN_RAW && AUTH_TOKEN && AUTH_TOKEN.exp > (Date.now() / 1000 + 300)) {\n return { rawToken: AUTH_TOKEN_RAW, token: AUTH_TOKEN, error: false };\n }\n //token is close to expire, refresh it\n if (!useInternalAuth && getFirebaseAuth().currentUser) {\n //we have a firebase user, get the token from there\n AUTH_TOKEN_RAW = await fetchComposableTokenFromFirebaseToken(selectedAccount, selectedProject);\n }\n else if (initToken || AUTH_TOKEN_RAW) {\n // we have a token already and no firebase user, refresh it\n AUTH_TOKEN_RAW = await fetchComposableToken(() => Promise.resolve(initToken ?? AUTH_TOKEN_RAW), selectedAccount, selectedProject);\n }\n if (!AUTH_TOKEN_RAW) {\n Env.logger.error('Cannot acquire a composable token', {\n vertesia: {\n account_id: selectedAccount,\n project_id: selectedProject,\n },\n });\n throw new Error('Cannot acquire a composable token');\n }\n AUTH_TOKEN = jwtDecode(AUTH_TOKEN_RAW);\n if (!AUTH_TOKEN || !AUTH_TOKEN.exp || !AUTH_TOKEN_RAW) {\n console.error('Invalid composable token', AUTH_TOKEN);\n Env.logger.error('Invalid composable token', {\n vertesia: {\n account_id: selectedAccount,\n project_id: selectedProject,\n },\n });\n throw new Error('Invalid composable token');\n }\n return { rawToken: AUTH_TOKEN_RAW, token: AUTH_TOKEN, error: false };\n}\nexport class UserNotFoundError extends Error {\n email;\n constructor(message, email) {\n super(message);\n this.name = 'UserNotFoundError';\n this.email = email;\n }\n}\n//# sourceMappingURL=composable.js.map","import { useState, useEffect } from 'react';\nimport { useUserSession } from \"@vertesia/ui/session\";\nexport function useCurrentTenant() {\n const { user } = useUserSession();\n const [currentTenant, setCurrentTenant] = useState(null);\n const [isLoading, setIsLoading] = useState(true);\n const [error, setError] = useState(null);\n useEffect(() => {\n const loadCurrentTenant = async () => {\n if (!user?.email) {\n setCurrentTenant(null);\n setIsLoading(false);\n return;\n }\n try {\n const response = await fetch('/api/resolve-tenant', {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({\n tenantEmail: user.email\n })\n });\n if (response.ok) {\n const tenantData = await response.json();\n if (tenantData) {\n // Convert the resolved tenant data to our TenantConfig format\n setCurrentTenant({\n tenantKey: tenantData.name || 'unknown',\n name: tenantData.label || tenantData.name || 'Unknown',\n domain: tenantData.domain || [],\n firebaseTenantId: tenantData.firebaseTenantId,\n provider: tenantData.provider,\n logo: tenantData.logo\n });\n }\n else {\n setCurrentTenant(null);\n }\n }\n else {\n setCurrentTenant(null);\n }\n }\n catch (error) {\n console.error('Error loading current tenant:', error);\n setError('Failed to load tenant configuration');\n setCurrentTenant(null);\n }\n finally {\n setIsLoading(false);\n }\n };\n loadCurrentTenant();\n }, [user?.email]);\n return {\n currentTenant,\n isLoading,\n error\n };\n}\n//# sourceMappingURL=useCurrentTenant.js.map","export class TypeRegistry {\n types;\n map = {};\n constructor(types) {\n this.types = types;\n //sort types\n types.sort((a, b) => a.name.localeCompare(b.name));\n for (const type of types) {\n this.map[type.id] = type;\n }\n }\n getType(id) {\n return this.map[id];\n }\n getTypeLayout(id) {\n const type = this.map[id];\n return type ? type.table_layout : undefined;\n }\n getTypeName(id) {\n const type = this.map[id];\n return type ? type.name : undefined;\n }\n}\n//# sourceMappingURL=TypeRegistry.js.map","import { jwtDecode } from 'jwt-decode';\nimport { createContext, useContext } from 'react';\nimport { VertesiaClient } from '@vertesia/client';\nimport { Env } from '@vertesia/ui/env';\nimport { getComposableToken } from './auth/composable';\nimport { getFirebaseAuth } from './auth/firebase';\nimport { TypeRegistry } from './TypeRegistry';\nimport { LastSelectedAccountId_KEY, LastSelectedProjectId_KEY } from './constants';\nexport { LastSelectedAccountId_KEY, LastSelectedProjectId_KEY };\nclass UserSession {\n isLoading = true;\n client;\n authError;\n authToken;\n typeRegistry;\n setSession;\n lastSelectedAccount;\n lastSelectedProject;\n onboardingComplete;\n constructor(client, setSession) {\n if (client) {\n this.client = client;\n }\n else {\n this.client = new VertesiaClient({\n serverUrl: Env.endpoints.studio,\n storeUrl: Env.endpoints.zeno,\n tokenServerUrl: Env.endpoints.sts\n });\n }\n if (setSession) {\n this.setSession = setSession;\n }\n this.logout = this.logout.bind(this);\n }\n get store() {\n return this.client.store;\n }\n get user() {\n return this.authToken;\n }\n get account() {\n return this.authToken?.account;\n }\n get project() {\n return this.authToken?.project;\n }\n get accounts() {\n return this.authToken?.accounts;\n }\n get authCallback() {\n return this.rawAuthToken.then(token => `Bearer ${token}`);\n }\n get rawAuthToken() {\n return getComposableToken().then(res => {\n const token = res?.rawToken;\n if (!token) {\n throw new Error('No token available');\n }\n this.authToken = jwtDecode(token);\n return token;\n });\n }\n signOut() {\n this.logout();\n }\n getAccount() {\n return this.authToken?.account;\n }\n async login(token) {\n this.authError = undefined;\n this.isLoading = false;\n this.client.withAuthCallback(() => this.authCallback);\n this.authToken = jwtDecode(token);\n console.log(`Logging in as ${this.authToken?.name} with account ${this.authToken?.account.name} (${this.authToken?.account.id}, and project ${this.authToken?.project?.name} (${this.authToken?.project?.id})`);\n //store selected account in local storage\n localStorage.setItem(LastSelectedAccountId_KEY, this.authToken.account.id);\n localStorage.setItem(LastSelectedProjectId_KEY + '-' + this.authToken.account.id, this.authToken.project?.id ?? '');\n // notify the host app of the login\n Env.onLogin?.(this.authToken);\n // Independent async calls\n await Promise.all([\n this._loadTypes(),\n this.fetchOnboardingStatus(),\n ]);\n return Promise.resolve();\n }\n isLoggedIn() {\n return !!this.authToken;\n }\n logout() {\n console.log('Logging out');\n if (this.authToken) {\n getFirebaseAuth().signOut();\n }\n this.authError = undefined;\n this.isLoading = false;\n this.authToken = undefined;\n this.typeRegistry = undefined;\n this.setSession = undefined;\n this.client.withAuthCallback(undefined);\n }\n async switchAccount(targetAccountId) {\n localStorage.setItem(LastSelectedAccountId_KEY, targetAccountId);\n if (this) {\n if (this.account && this.project) {\n localStorage.setItem(LastSelectedProjectId_KEY + '-' + this.account.id, this.project.id);\n }\n else if (this.account) {\n localStorage.removeItem(LastSelectedProjectId_KEY + '-' + this.account.id);\n }\n }\n window.location.replace('/?a=' + targetAccountId);\n }\n async switchProject(targetProjectId) {\n if (this.account) {\n localStorage.setItem(LastSelectedProjectId_KEY + '-' + this.account.id, targetProjectId);\n }\n window.location.replace('/?a=' + this.account?.id + '&p=' + targetProjectId);\n }\n async _loadTypes() {\n if (this.project) {\n return this.store.types.list({}, { layout: true }).then(types => this.typeRegistry = new TypeRegistry(types)).catch(err => {\n console.error('Failed to fetch object types', err);\n throw err;\n });\n }\n else {\n console.log('No project selected');\n }\n }\n async reloadTypes() {\n return this._loadTypes().then(() => {\n this.setSession?.(this.clone());\n });\n }\n async fetchAccounts() {\n return this.client.accounts.list().then(accounts => {\n if (!this.authToken) {\n throw new Error('No token available');\n }\n this.authToken.accounts = accounts;\n this.setSession?.(this.clone());\n }).catch(err => {\n console.error('Failed to fetch accounts', err);\n throw err;\n });\n }\n async fetchOnboardingStatus() {\n if (this.onboardingComplete) {\n console.log('Onboarding already completed');\n return false;\n }\n const previousStatus = this.onboardingComplete;\n try {\n const onboarding = await this.client.account.onboardingProgress();\n this.onboardingComplete = Object.values(onboarding).every(value => value === true);\n if (previousStatus !== this.onboardingComplete) {\n return true;\n }\n this.setSession?.(this.clone());\n }\n catch (error) {\n console.error('Error fetching onboarding status:', error);\n this.onboardingComplete = false;\n this.setSession?.(this.clone());\n }\n return false;\n }\n clone() {\n const session = new UserSession(this.client);\n session.isLoading = this.isLoading;\n session.authError = this.authError;\n session.authToken = this.authToken;\n session.setSession = this.setSession;\n session.lastSelectedAccount = this.lastSelectedAccount;\n session.switchAccount = this.switchAccount;\n session.typeRegistry = this.typeRegistry;\n session.onboardingComplete = this.onboardingComplete;\n return session;\n }\n}\nconst UserSessionContext = createContext(undefined);\nexport function useUserSession() {\n const session = useContext(UserSessionContext);\n if (!session) {\n throw new Error('useUserSession must be used within a UserSessionProvider');\n }\n return session;\n}\nexport { UserSession, UserSessionContext };\n//# sourceMappingURL=UserSession.js.map","/**\n * This hook is used to generate and verify state for OAuth2 authorization requests.\n * @returns\n */\nimport { useCallback } from \"react\";\nconst AUTH_STATE_KEY = 'auth_state';\nconst STATE_EXPIRY_KEY = 'auth_state_expiry';\nconst STATE_TTL = 5 * 60 * 1000; // 5 min\nexport function useAuthState() {\n // Generate new state\n const generateState = useCallback(() => {\n const state = crypto.randomUUID();\n const expiryTime = Date.now() + STATE_TTL;\n // Store state and expiry\n sessionStorage.setItem(AUTH_STATE_KEY, state);\n sessionStorage.setItem(STATE_EXPIRY_KEY, expiryTime.toString());\n return state;\n }, []);\n // Verify returned state\n const verifyState = useCallback((returnedState) => {\n if (!returnedState) {\n return 'Missing state';\n }\n const savedState = sessionStorage.getItem(AUTH_STATE_KEY);\n const expiryTime = parseInt(sessionStorage.getItem(STATE_EXPIRY_KEY) || '0');\n let reason;\n // Verify state matches and hasn't expired\n if (savedState !== returnedState) {\n reason = `State mismatched (${savedState} !== ${returnedState})`;\n }\n else if (Date.now() > expiryTime) {\n reason = 'State expired';\n }\n else {\n reason = undefined; // No errors\n }\n return reason;\n }, []);\n // Clear state (useful for cleanup)\n const clearState = useCallback(() => {\n sessionStorage.removeItem(AUTH_STATE_KEY);\n sessionStorage.removeItem(STATE_EXPIRY_KEY);\n }, []);\n return { generateState, verifyState, clearState };\n}\n//# sourceMappingURL=useAuthState.js.map","import { jsx as _jsx } from \"react/jsx-runtime\";\nimport { onAuthStateChanged } from \"firebase/auth\";\nimport { useEffect, useRef, useState } from \"react\";\nimport { UserNotFoundError, getComposableToken } from \"./auth/composable\";\nimport { getFirebaseAuth } from \"./auth/firebase\";\nimport { useAuthState } from \"./auth/useAuthState\";\nimport { Env } from \"@vertesia/ui/env\";\nimport { LastSelectedAccountId_KEY, LastSelectedProjectId_KEY, UserSession, UserSessionContext } from \"./UserSession\";\nconst devDomains = [\".composable.sh\", \".vertesia.dev\", \"vertesia.app\"];\nconst CENTRAL_AUTH_REDIRECT = \"https://internal-auth.vertesia.app/\";\nfunction shouldRedirectToCentralAuth() {\n // Authentication is not supported in Docker environment.\n // See https://github.com/vertesia/studio/wiki/Composable-UI-Hosting-Options\n if (Env.isDocker) {\n return true;\n }\n return devDomains.some((domain) => window.location.hostname.endsWith(domain));\n}\nexport function UserSessionProvider({ children }) {\n const hashParams = new URLSearchParams(location.hash.substring(1));\n const token = hashParams.get(\"token\");\n const state = hashParams.get(\"state\");\n const [session, setSession] = useState(new UserSession());\n const { generateState, verifyState, clearState } = useAuthState();\n const hasInitiatedAuthRef = useRef(false);\n const redirectToCentralAuth = (projectId, accountId) => {\n const url = new URL(`${CENTRAL_AUTH_REDIRECT}?sts=${Env.endpoints.sts ?? \"https://sts.vertesia.io\"}`);\n const currentUrl = new URL(window.location.href);\n currentUrl.hash = \"\";\n if (projectId)\n currentUrl.searchParams.set(\"p\", projectId);\n if (accountId)\n currentUrl.searchParams.set(\"a\", accountId);\n url.searchParams.set(\"redirect_uri\", currentUrl.toString());\n url.searchParams.set(\"state\", generateState());\n location.replace(url.toString());\n };\n useEffect(() => {\n // Make this effect idempotent - only run auth flow once\n if (hasInitiatedAuthRef.current) {\n console.log(\"Auth: skipping duplicate auth flow initiation\");\n return;\n }\n hasInitiatedAuthRef.current = true;\n console.log(\"Auth: starting auth flow\");\n Env.logger.info(\"Starting auth flow\");\n const currentUrl = new URL(window.location.href);\n const selectedAccount = currentUrl.searchParams.get(\"a\") ?? localStorage.getItem(LastSelectedAccountId_KEY) ?? undefined;\n const selectedProject = currentUrl.searchParams.get(\"p\") ??\n localStorage.getItem(LastSelectedProjectId_KEY + \"-\" + selectedAccount) ??\n undefined;\n console.log(\"Auth: selected account\", selectedAccount);\n console.log(\"Auth: selected project\", selectedProject);\n Env.logger.info(\"Selected account and project\", {\n vertesia: {\n account_id: selectedAccount,\n project_id: selectedProject,\n },\n });\n if (token && state) {\n const validationError = verifyState(state);\n if (validationError) {\n console.error(`Auth: invalid state: ${validationError}`);\n Env.logger.error(`Invalid state: ${validationError}`, {\n vertesia: {\n state: state,\n },\n });\n redirectToCentralAuth();\n }\n else {\n clearState();\n }\n getComposableToken(selectedAccount, selectedProject, token, false, shouldRedirectToCentralAuth())\n .then((res) => {\n session.login(res.rawToken).then(() => {\n setSession(session.clone());\n //cleanup the hash\n window.location.hash = \"\";\n });\n })\n .catch((err) => {\n console.error(\"Failed to fetch user token from studio, redirecting to central auth\", err);\n Env.logger.error(\"Failed to fetch user token from studio, redirecting to central auth\", {\n vertesia: {\n error: err,\n },\n });\n redirectToCentralAuth();\n });\n return;\n }\n else {\n //if on a dev domain and not logged in, redirect to central auth\n if (!session.isLoggedIn()) {\n console.log(\"Auth: not logged in & no token/state\");\n Env.logger.info(\"Not logged in & no token/state\", {\n vertesia: {\n account_id: selectedAccount,\n project_id: selectedProject,\n },\n });\n if (shouldRedirectToCentralAuth()) {\n console.log(\"Auth: on dev domain, redirecting to central auth with selection\", selectedAccount, selectedProject);\n Env.logger.info(\"Redirecting to central auth with selection\", {\n vertesia: {\n account_id: selectedAccount,\n project_id: selectedProject,\n },\n });\n redirectToCentralAuth();\n }\n else {\n console.log(\"Auth: not on dev domain\");\n Env.logger.info(\"Not on dev domain\", {\n vertesia: {\n account_id: selectedAccount,\n project_id: selectedProject,\n },\n });\n }\n }\n }\n return onAuthStateChanged(getFirebaseAuth(), async (firebaseUser) => {\n if (firebaseUser) {\n console.log(\"Auth: successful login with firebase\");\n Env.logger.info(\"Successful login with firebase\", {\n vertesia: {\n account_id: selectedAccount,\n project_id: selectedProject,\n },\n });\n session.setSession = setSession;\n await getComposableToken(selectedAccount, selectedProject, undefined, false, shouldRedirectToCentralAuth())\n .then((res) => {\n session.login(res.rawToken).then(() => setSession(session.clone()));\n })\n .catch((err) => {\n console.error(\"Failed to fetch user token from studio\", err);\n Env.logger.error(\"Failed to fetch user token from studio\", {\n vertesia: {\n account_id: selectedAccount,\n project_id: selectedProject,\n error: err,\n },\n });\n if (!(err instanceof UserNotFoundError))\n session.logout();\n session.isLoading = false;\n session.authError = err;\n setSession(session.clone());\n });\n }\n else {\n // anonymous user\n console.log(\"Auth: using anonymous user\");\n Env.logger.info(\"Using anonymous user\", {\n vertesia: {\n account_id: selectedAccount,\n project_id: selectedProject,\n },\n });\n session.client.withAuthCallback(undefined);\n session.logout();\n setSession(session.clone());\n }\n });\n }, []);\n return _jsx(UserSessionContext.Provider, { value: session, children: children });\n}\n//# sourceMappingURL=UserSessionProvider.js.map","import { Env } from '@vertesia/ui/env';\nimport { logEvent } from \"firebase/analytics\";\nimport { getFirebaseAnalytics } from \"./auth/firebase\";\nexport function useUXTracking() {\n //identify user in monitoring and UX systems\n const tagUserSession = async (user) => {\n const signupData = window.localStorage.getItem(\"composableSignupData\");\n if (!user) {\n console.error('No user found -- skipping tagging');\n return;\n }\n if (signupData) {\n window.localStorage.removeItem(\"composableSignupData\");\n }\n };\n //send event to analytics and UX systems\n const trackEvent = (eventName, eventProperties) => {\n if (!Env.isProd) {\n console.debug('track event', eventName, eventProperties);\n }\n //GA via firebase\n logEvent(getFirebaseAnalytics(), eventName, { ...eventProperties, debug_mode: !Env.isProd });\n };\n return {\n tagUserSession,\n trackEvent\n };\n}\n//# sourceMappingURL=useUXTracking.js.map"],"names":["LastSelectedAccountId_KEY","LastSelectedProjectId_KEY","AUTH_TOKEN_RAW","AUTH_TOKEN","_firebaseApp","_analytics","_firebaseAuth","getFirebaseApp","Env","firebase","Error","initializeApp","error","console","getFirebaseAnalytics","getAnalytics","getFirebaseAuth","getAuth","async","setFirebaseTenant","tenantEmail","log","retries","retryDelay","response","fetch","method","headers","body","JSON","stringify","signal","AbortSignal","timeout","ok","errorData","json","parseError","status","warn","data","firebaseTenantId","auth","tenantId","providerType","provider","fetchError","Promise","resolve","setTimeout","message","getFirebaseAuthToken","refresh","user","currentUser","getIdToken","then","token","logger","info","vertesia","user_email","email","user_name","displayName","user_id","uid","catch","err","fetchComposableToken","accountId","projectId","ttl","account_id","project_id","idToken","stsEndpoint","endpoints","sts","sts_url","stsUrl","URL","requestBody","type","expires_at","Math","floor","Date","now","undefined","stsRes","Authorization","idTokenDecoded","jwtDecode","UserNotFoundError","errorText","text","localStorage","removeItem","fetchComposableTokenFromFirebaseToken","getComposableToken","initToken","forceRefresh","useInternalAuth","selectedAccount","getItem","selectedProject","exp","rawToken","constructor","super","this","name","useCurrentTenant","useUserSession","currentTenant","setCurrentTenant","useState","isLoading","setIsLoading","setError","useEffect","tenantData","tenantKey","label","domain","logo","loadCurrentTenant","TypeRegistry","types","map","sort","a","b","localeCompare","id","getType","getTypeLayout","table_layout","getTypeName","UserSession","client","authError","authToken","typeRegistry","setSession","lastSelectedAccount","lastSelectedProject","onboardingComplete","VertesiaClient","serverUrl","studio","storeUrl","zeno","tokenServerUrl","logout","bind","store","account","project","accounts","authCallback","rawAuthToken","res","signOut","getAccount","login","withAuthCallback","setItem","onLogin","all","_loadTypes","fetchOnboardingStatus","isLoggedIn","switchAccount","targetAccountId","window","location","replace","switchProject","targetProjectId","list","layout","reloadTypes","clone","fetchAccounts","previousStatus","onboarding","onboardingProgress","Object","values","every","value","session","UserSessionContext","createContext","useContext","AUTH_STATE_KEY","STATE_EXPIRY_KEY","devDomains","shouldRedirectToCentralAuth","isDocker","some","hostname","endsWith","UserSessionProvider","children","hashParams","URLSearchParams","hash","substring","get","state","generateState","verifyState","clearState","useCallback","crypto","randomUUID","expiryTime","sessionStorage","toString","returnedState","savedState","parseInt","reason","hasInitiatedAuthRef","useRef","redirectToCentralAuth","url","currentUrl","href","searchParams","set","current","validationError","onAuthStateChanged","firebaseUser","_jsx","Provider","useUXTracking","tagUserSession","signupData","trackEvent","eventName","eventProperties","isProd","debug","logEvent","debug_mode"],"mappings":"2fAAY,MAACA,EAA4B,qCAC5BC,EAA4B,qCCIzC,ICDIC,EACAC,EDAAC,EAAe,KACfC,EAAa,KACbC,EAAgB,KAEb,SAASC,IACZ,IA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O/E,aAAaQ,QAAQ,wBAC1CpD,EAID6L,GACAlE,OAAO/E,aAAaC,WAAW,wBAJ/BrF,QAAQD,MAAM,sCAiBlBuO,WATe,CAACC,EAAWC,KACtB7O,EAAI8O,QACLzO,QAAQ0O,MAAM,cAAeH,EAAWC,GAG5CG,EAAS1O,IAAwBsO,EAAW,IAAKC,EAAiBI,YAAajP,EAAI8O,UAM3F"}
|
package/lib/vertesia-ui-shell.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{jsxs as e,jsx as t,Fragment as n}from"react/jsx-runtime";import{Button as i,VModal as a,VModalTitle as o,VModalBody as r,useToast as l,Input as c,Spinner as s,SelectStack as d,VSelectBox as m,useSafeLayoutEffect as u,ErrorBox as h,Center as p,useFetch as f,SelectBox as g,Modal as v,ModalTitle as x,ModalBody as y,ModalFooter as b,VTabs as N,VTabsBar as w,VTabsPanel as k,VTooltip as C,Avatar as j,ModeToggle as S,MenuList as P,ToastProvider as z,ThemeProvider as L}from"@vertesia/ui/core";import{useState as I,useEffect as T,Fragment as A,createContext as _,useContext as U}from"react";import{useUserSession as E,useUXTracking as O,setFirebaseTenant as D,getFirebaseAuth as W,UserNotFoundError as q,fetchComposableTokenFromFirebaseToken as M,UserSessionProvider as R,LastSelectedAccountId_KEY as F,LastSelectedProjectId_KEY as Y}from"@vertesia/ui/session";import{Env as G}from"@vertesia/ui/env";import V from"clsx";import{signInWithRedirect as B,OAuthProvider as J,GoogleAuthProvider as H,GithubAuthProvider as $,getAuth as K}from"firebase/auth";import{useLocation as Q}from"@vertesia/ui/router";import{Popover as X}from"@vertesia/ui/widgets";import{getTenantIdFromProject as Z}from"@vertesia/common";import{Check as ee,CopyIcon as te,LockIcon as ne}from"lucide-react";import{UserPermissionProvider as ie}from"@vertesia/ui/features";import{Transition as ae}from"@headlessui/react";function oe(){const n=E(),{client:l,account:c}=n,[s,d]=I(!1),[m,u]=I([]);T((()=>{l.account.listInvites().then((e=>{if(e.length>0){const t=e.filter((e=>e.data.account));if(0===t.length)return void console.log("No valid invites found, closing modal");console.log("Found valid invites",t.length),d(!0),u(t)}else console.log("No invites found, closing modal"),d(!1)})).catch((e=>{console.error("Error fetching invites",e)}))}),[c?.id]);const h=()=>d(!1),p=m.map((a=>a.data.account?e("div",{className:"flex flex-row w-full justify-between border rounded-sm px-2 py-2 ",children:[e("div",{className:"flex flex-col",children:[t("div",{className:"w-full font-semibold",children:a.data.account.name??a.data.account}),a.data.project&&e("div",{className:"w-full text-base",children:["- ",a.data.project.name]}),e("div",{className:"text-xs",children:["Role: ",a.data.role]}),a.data.invited_by&&e("div",{className:"text-xs",children:["by ",a.data.invited_by.name??a.data.invited_by]})]}),e("div",{className:"flex flex-col gap-4",children:[t(i,{size:"xs",onClick:()=>(async e=>{await l.account.acceptInvite(e.id),await n.fetchAccounts();const t=m.filter((t=>t.id!==e.id)).filter((e=>e.data.account));t.length>0?u(t):h()})(a),children:"Accept"})," ",t(i,{size:"xs",variant:"secondary",onClick:()=>(async e=>{await l.account.rejectInvite(e.id);const t=m.filter((t=>t.id!==e.id));u(t),0===t.length&&h()})(a),children:"Reject"})]})]},a.id):(console.warn("Invite has no account data",a),null)));return t("div",{children:e(a,{isOpen:s,onClose:h,children:[t(o,{children:"Review Invites"}),e(r,{children:[t("div",{className:"text-sm pb-4",children:"You have received the following invites to join other accounts. Please review and accept or declined them."}),p]})]})})}function re({redirectTo:a}){const[o,r]=I(!1),{trackEvent:d}=O(),[m,u]=I(""),h=l();return e(n,{children:[t(c,{value:m,onChange:u,placeholder:"Enter your enterprise email",type:"email"}),o?t("div",{className:"w-full flex justify-center",children:t(s,{})}):t(i,{variant:"outline",onClick:async()=>{if(!m)return;/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(m)?(r(!0),D(m).then((e=>{if(!e)return h({title:"Tenant not found",status:"error",duration:5e3}),void r(!1);localStorage.setItem("tenantName",e.name??"");const t=function(e){if(!G.firebase)throw new Error("Firebase configuration is not available in the environment");switch(G.firebase.providerType){case"oidc":default:return new J("oidc.main");case"google":{let t=e||window.location.pathname||"/";"/"!==t[0]&&(t="/"+t);const n=new H;return n.addScope("profile"),n.addScope("email"),n.setCustomParameters({prompt:"select_account",redirect_uri:window.location.origin+t}),n}case"microsoft":return new J("microsoft.com");case"github":return new J("github.com")}}(a);d("enterprise_signin",{firebaseTenantName:e.name}),G.logger.info("Enterprise single sign-in",{vertesia:{email:m,firebaseTenantName:e.name,firebaseTenantId:e.firebaseTenantId}}),B(W(),t),r(!1)}))):h({title:"Invalid email address",status:"error",duration:5e3})},className:"w-full mt-2 py-4 flex rounded-lg hover:shadow-sm transition duration-150 text-center",children:t("span",{className:"text-sm font-semibold",children:"Continue with Enterprise SSO"})})]})}function le({}){return e(i,{variant:"outline",onClick:()=>{localStorage.removeItem("tenantName");let e="https://dengenlabs.firebaseapp.com/__/auth/handler"+window.location.pathname;"/"!==e[0]&&(e="/"+e);const t=new $;t.addScope("profile"),t.addScope("email"),B(W(),t)},className:"w-full py-5 flex rounded-lg hover:shadow-sm transition duration-150 text-center mb-2",children:[t("img",{className:"size-6 bg-white rounded-full",src:"https://www.svgrepo.com/show/503359/github.svg",loading:"lazy",alt:"github logo"}),t("span",{className:"text-sm font-semibold",children:"Continue with GitHub"})]})}function ce({redirectTo:n}){return e(i,{variant:"outline",onClick:()=>{localStorage.removeItem("tenantName");let e=n||window.location.pathname||"/";"/"!==e[0]&&(e="/"+e);const t=new H;t.addScope("profile"),t.addScope("email"),t.setCustomParameters({prompt:"select_account",redirect_uri:window.location.origin+e}),B(W(),t)},className:"w-full py-5 flex rounded-lg hover:shadow-sm transition duration-150 text-center mb-2",children:[t("img",{className:"size-6",src:"https://www.svgrepo.com/show/475656/google-color.svg",loading:"lazy",alt:"google logo"}),t("span",{className:"text-sm font-semibold",children:"Continue with Google"})]})}function se({redirectTo:n}){return e(i,{variant:"outline",onClick:()=>{localStorage.removeItem("tenantName");let e=n||window.location.pathname||"/";"/"!==e[0]&&(e="/"+e);const t=new J("microsoft.com");t.addScope("profile"),t.addScope("email"),B(W(),t)},className:"w-full py-5 flex rounded-lg hover:shadow-sm transition duration-150 text-center",children:[t("img",{className:"size-6",src:"https://learn.microsoft.com/en-us/entra/identity-platform/media/howto-add-branding-in-apps/ms-symbollockup_mssymbol_19.svg",loading:"lazy",alt:"microsoft logo"}),t("span",{className:"text-sm font-semibold",children:"Continue with Microsoft"})]})}const de=[{id:1,label:"1-10 employees"},{id:11,label:"11-100 employees"},{id:101,label:"101-1000 employees"},{id:1001,label:"1001-5000 employees"},{id:5001,label:"5000+ employees"}],me=[{id:"personal",label:"Personal",description:"For personal use, or for a small team."},{id:"company",label:"Company",description:"For a company or organization."}],ue=[{id:"testing",label:"Just Testing or Evaluating LLMs"},{id:"exploring",label:"Actively Exploring LLMs on a Project"},{id:"using",label:"Already Using LLMs in Production"},{id:"migrating",label:"Migrating to different LLMs"},{id:"other",label:"Other"}];function he({onSignup:a,goBack:o}){const[r,l]=I(void 0),[s,u]=I(void 0),[h,p]=I(void 0),[f,g]=I(void 0),[v,x]=I(void 0),[y,b]=I(void 0),[N,w]=I(void 0),k="company"===r;T((()=>{const e=K().currentUser;e?b(e):console.error("No user found")}),[y]);return e("div",{className:"flex flex-col space-y-2",children:[e("div",{className:"prose",children:[e("p",{className:"prose text-sm text-muted pt-4",children:["Welcome to Vertesia, ",y?.displayName," (",y?.email,"). Please tell us a little bit about yourself and you'll be on your way. No credit card is required."]}),N&&t("div",{className:"text-destructive",children:N})]}),t(pe,{label:"Account Type",children:t(d,{options:me,selected:me.find((e=>e.id===r)),onSelect:e=>l(e.id)})}),k&&e(n,{children:[t(pe,{label:"Company Size",children:t(m,{className:"w-full border border-accent bg-muted",value:s,options:de,onChange:u,optionLabel:e=>e?.label,placeholder:"Select Company Size"})}),t(pe,{label:"Company Name",children:t(c,{value:h,onChange:p,type:"text",required:!0})}),t(pe,{label:"Company Website",children:t(c,{value:f,onChange:g,type:"text"})})]}),t(pe,{label:"Project Maturity",children:t(m,{className:"w-full border border-accent bg-muted",options:ue,value:ue.find((e=>e.id===v)),optionLabel:e=>e?.label,placeholder:"Select Project Maturity",onChange:e=>x(e?.id)})}),e("div",{className:"pt-8 flex flex-col",children:[t(i,{variant:"primary",onClick:async()=>{if(!(r?k&&!h?(w("Please enter an organization name"),0):!k||s||(w("Please select a company size"),0):(w("Please select an account type"),0)))return;if(!r)return;const e={accountType:r,companyName:h,companySize:s?.id,companyWebsite:f,maturity:v};window.localStorage.setItem("composableSignupData",JSON.stringify(e));const t=await(K().currentUser?.getIdToken());console.log("Got firebase token",K(),t),t?a(e,t):console.error("No firebase token found")},size:"xl",children:t("span",{className:"text-lg",children:"Sign Up"})}),t(i,{variant:"ghost",size:"xl",className:"mt-4",onClick:o,children:t("span",{className:"",children:"Wrong account, go back"})})]})]})}function pe({label:n,children:i}){return e("div",{className:"flex flex-col space-y-2 pt-4",children:[t("div",{className:"text-sm text-muted",children:n}),i]})}function fe({allowedPrefix:e,isNested:n=!1,lightLogo:i,darkLogo:a}){const[o,r]=I(!1);return u((()=>{e&&r(window.location.href.startsWith(e))}),[]),o?null:t(ge,{isNested:n,lightLogo:i,darkLogo:a})}function ge({isNested:n=!1,lightLogo:i,darkLogo:a}){const{isLoading:o,user:r,authError:l}=E();return o||r?null:t("div",{style:{zIndex:999998},className:(n?"absolute":"fixed")+"overflow-y-auto ",children:e("div",{className:V("flex flex-col items-center justify-center py-14 px-4"),children:[t(ve,{authError:l,lightLogo:i,darkLogo:a}),e("div",{className:"flex gap-x-6 mt-10 justify-center text-muted",children:[t("a",{href:"https://vertesiahq.com/privacy",className:"text-sm",children:"Privacy Policy"}),t("a",{href:"https://vertesiahq.com/terms",className:"text-sm",children:"Terms of Service"})]})]})})}function ve({authError:a,darkLogo:o,lightLogo:r}){const[l,c]=I(void 0),[s,d]=I(!1),{signOut:m}=E(),{trackEvent:u}=O();history.replaceState({},"","/");const h=()=>{c(void 0),d(!0)};T((()=>{a instanceof q&&(console.log("User not found, redirecting to signup"),h())}),[a]);return e(n,{children:[r&&t("img",{src:r,alt:"logo",className:"h-15 block dark:hidden"}),o&&t("img",{src:o,alt:"logo",className:"h-15 hidden dark:block"}),l&&e("div",{className:"my-6",children:["Need to make a change?"," ",t(i,{onClick:h,children:" Go back"})]}),t("div",{className:"flex flex-col space-y-2",children:s&&!localStorage.getItem("tenantName")?t(he,{onSignup:(e,t)=>{console.log("Got Signup data",e),c(e);const n={signupData:e,firebaseToken:t};fetch(G.endpoints.studio+"/auth/signup",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)}).then((e=>{console.log("Signup successful",n,e),u("sign_up"),window.location.href="/"}))},goBack:()=>{console.log("Going back, signing out"),c(void 0),d(!1),m()}}):e("div",{className:"flex flex-col",children:[t("div",{className:"my-4",children:t("h2",{className:"text-2xl font-bold text-center",children:"Log in or Sign up"})}),e("div",{className:"max-w-2xl text-center my-2 px-2",children:["First time here? No problem, it's free to try!",t("br",{}),"We'll just ask you a couple of questions next and you'll be on your way."]}),e("div",{className:"flex items-center flex-col",children:[e("div",{className:"py-4 w-70",children:[t(ce,{}),t(le,{}),t(se,{})]}),e("div",{className:"flex items-center flex-row w-70 text-muted",children:[t("hr",{className:"w-full"}),t("div",{className:"px-2 text-xs",children:"OR"}),t("hr",{className:"w-full"})]}),t("div",{className:"py-4 w-70",children:t(re,{})})]}),a&&t("div",{className:"text-center",children:e("div",{className:"",children:["Sorry, we have not been able to sign you in.",t("br",{}),"Please try again or contact",t("a",{className:"text-info mx-1",href:"mailto:support@vertesiahq.com",children:"support@vertesiahq.com"}),"if it persists.",e("pre",{className:"mt-2",children:["Error: ",a.message]})]})})]})})]})}function xe(){const[e,n]=I(),[i,a]=I(),o=function(e){const t=new URLSearchParams(e.search);let n=t.get("redirect_uri");const i=t.get("code");return n&&i?(n=decodeURI(n),n.startsWith("http://127.0.0.1:")||n.startsWith("http://localhost:")?{redirect:n,code:i,profile:t.get("profile")??"default",project:t.get("project")??void 0,account:t.get("account")??void 0}:null):null}(Q()),r=l(),c=async e=>{if(!o)return;if(!e.profile)return void r({title:"Profile is required",description:"Please enter a profile name to save the client authorization",status:"error",duration:2e3});if(!e.account)return void r({title:"Account is required",description:"Please select an account to authorize the client to access the ComposablePrompts servers",status:"error",duration:2e3});if(!e.project)return void r({title:"Project is required",description:"Please select a project to authorize the client to access the ComposablePrompts servers",status:"error",duration:2e3});let t;try{const i=await M(e.account,e.project,86400);i?(t={...e,studio_server_url:G.endpoints.studio,zeno_server_url:G.endpoints.zeno,token:i},await fetch(o.redirect,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)}),n(t)):r({title:"Failed to get composable token",status:"error",duration:5e3})}catch(e){t?(a(e),n(t)):r({title:"Error authorizing client",description:e.message,status:"error",duration:5e3})}},s=o?e?t(be,{payload:e,error:i}):t(ye,{clientInfo:o,onAccept:c}):t(h,{title:"Invalid request",children:"This page should be called by a terminal client to authenticate against the ComposablePrompts servers"});return t("div",{className:"w-full flex flex-col items-center gap-4 mt-24",children:s})}function ye({onAccept:i,clientInfo:a}){const{client:o,user:r}=E(),{data:l,error:c}=f((()=>r?o.projects.list():Promise.resolve([])),[r]);if(c)return t(h,{title:"Error loading projects",children:c.message});const d=G.isLocalDev?"Local Dev":G.isDev?"Staging":"Production";return r&&l?e(n,{children:[e("div",{className:"w-1/3",children:[e("div",{className:"mb-4 text-xl font-semibold text-gray-800",children:["Authorizing client on ",d," environment."]}),e("div",{className:"mb-2 text-md text-gray-800",children:[t("div",{children:"A client app wants authorization to access the composable prompt servers in your name."}),e("div",{children:["The client app code is ",t("b",{children:a.code}),". You can check if the code is correct in the terminal."]})]}),e("div",{className:"mb-2 text-sm text-gray-600",children:[t("div",{children:"You must choose the target account and project for the client to access."}),t("div",{children:"Also, enter a profile name that will be used to save the authorization in your client configuration."})]})]}),t(Ne,{onAccept:i,allProjects:l,data:a})]}):t(s,{size:"lg"})}function be({payload:n,error:a}){const o=l();return e("div",{children:[a?e("div",{children:[e(h,{title:"Failed to send the authorization token to the cli tool",children:['This can happen due to security checks on Safari. The error is "',a.message,'"']}),t("div",{children:"Don't worry, you can still authenticate the cli tool by pasting the authentication token in the terminal. You can close this page."})]}):t("div",{children:"The client is authenticated. You can close this page."}),t(p,{className:"mt-4",children:t(i,{variant:"secondary",onClick:()=>{n&&(navigator.clipboard.writeText(JSON.stringify(n)),o({title:"Authentication Payload copied",description:a?"You can paste the authentication payload in the terminal to authenticate the client.":"You can close the page now.",status:"success",duration:5e3}))},children:"Copy the Authentication Payload"})})]})}function Ne({allProjects:n,data:a,onAccept:o}){const{accounts:r,account:l,project:s}=E(),[d,m]=I((()=>({profile:a.profile,account:a.account??l?.id,project:a.project??s?.id}))),u=n.filter((e=>e.account===d.account));return e("div",{className:"w-1/3",children:[e("div",{className:"mb-4 flex flex-col gap-2",children:[t("span",{className:"font-semibold text-gray-600",children:"Profile Name"}),t(c,{type:"text",value:d.profile,onChange:e=>{m({...d,profile:e})}})]}),e("div",{className:"mb-4 flex flex-col gap-2",children:[t("span",{className:"font-semibold text-gray-600",children:"Account"}),t(we,{value:d.account,onChange:e=>{m({...d,account:e.id,project:void 0})},accounts:r||[]})]}),e("div",{className:"mb-4 flex flex-col gap-2",children:[t("span",{className:"font-semibold text-gray-600",children:"Project"}),t(ke,{value:d.project,onChange:e=>{m({...d,project:e.id})},projects:u})]}),t("div",{className:"pt-2",children:t(i,{size:"xl",onClick:()=>o(d),children:"Authorize Client"})})]})}function we({value:e,accounts:n,onChange:i}){return t(g,{options:n,value:n?.find((t=>t.id===e)),onChange:e=>{i(e)},by:"id",optionLabel:e=>e.name,placeholder:"Select Account"})}function ke({value:e,projects:n,onChange:i}){return t(g,{by:"id",value:n.find((t=>t.id===e)),options:n,optionLabel:e=>e.name,placeholder:"Select Project",onChange:e=>{i(e)}})}function Ce({isOpen:n,onClose:a}){return e(v,{isOpen:n,onClose:a,children:[t(x,{children:"Sign In"}),e(y,{className:"flex justify-center",children:[t(ce,{}),t(le,{}),t(se,{})]}),t(b,{justify:"end",children:t(i,{variant:"ghost",onClick:a,children:"Cancel"})})]})}function je({title:n,value:i}){const[a,o]=I(!1);return e("div",{className:"w-full flex justify-between items-center mb-1",children:[e("div",{className:"flex flex-col w-[calc(100%-3rem)]",children:[t("div",{className:"text-sm px-2 dark:text-slate-200",children:n}),t(C,{description:i,size:"xs",placement:"left",children:e("div",{className:"text-xs truncate text-muted w-full text-left px-2",children:[i," "]})})]}),a?t(ee,{className:"size-4 cursor-pointer text-success"}):t(te,{className:"size-4 cursor-pointer text-gray-400 dark:text-slate-400",onClick:()=>function(e){navigator.clipboard.writeText(e),o(!0),setTimeout((()=>o(!1)),2e3)}(i)})]})}function Se(){const n=E(),{account:i,project:a,client:o,authToken:r}=n,l=new URL(o.baseUrl).hostname,c=new URL(o.store.baseUrl).hostname,s=a?Z(a):"",d=[{name:"user",label:"User",content:e("div",{className:"space-y-1 p-2",children:[t(je,{title:"Organization ID",value:i?.id??"Unknown"}),t(je,{title:"Project ID",value:a?.id??"Unknown"}),t(je,{title:"User ID",value:r?.sub??"Unknown"}),t(je,{title:"Organization Roles",value:r?.account_roles?.join(",")??"Unknown"}),t(je,{title:"Project Roles",value:r?.project_roles?.join(",")??"Unknown"})]})},{name:"environment",label:"Environment",content:e("div",{className:"space-y-1 p-2",children:[t(je,{title:"Tenant ID",value:s}),t(je,{title:"Environment",value:G.type}),t(je,{title:"Server",value:l}),t(je,{title:"Store",value:c}),t(je,{title:"App Version",value:G.version})]})}];return t("div",{className:"w-full",children:e(N,{defaultValue:"user",tabs:d,fullWidth:!0,updateHash:!1,children:[t(w,{}),t(k,{})]})})}function Pe({}){const{user:a,isLoading:o}=E(),[r,l]=I(!1);return o?t(s,{}):a?t("div",{className:"px-3",children:t(ze,{asMenuTrigger:!0})}):e(n,{children:[t(i,{onClick:()=>l(!0),children:"Sign In"}),t(Ce,{isOpen:r,onClose:()=>l(!1)})]})}function ze({className:n,asMenuTrigger:i=!1}){const a=E(),{user:o}=a;return a&&o?e(X,{strategy:"fixed",placement:"bottom-start",zIndex:100,children:[t(X.Trigger,{click:!0,children:t("div",{className:V(n,"flex items-center justify-start",i&&"cursor-pointer"),children:t(j,{size:"sm",color:"bg-amber-500",shape:"circle",name:o?.name})})}),t(X.Content,{className:"w-[280px] mx-2 my-1",children:t("div",{className:"bg-white dark:bg-slate-900 shadow-lg rounded-md ring-1 ring-gray-200 dark:ring-slate-700",children:e("div",{className:"divide-y divide-gray-200 dark:divide-slate-700",children:[e("div",{className:"py-2 pl-2",children:[t("p",{className:"px-4 dark:text-white mb-1",children:o?.name??"Unknown"}),t("p",{className:"px-4 text-xs text-gray-500",children:o?.email??""})]}),t("div",{className:"w-full p-1",children:t(Se,{})}),t("div",{className:"py-2 pl-2",children:t(S,{})}),t("div",{className:"py-2",children:t(P,{children:t(P.Item,{className:"px-2",onClick:()=>a.logout(),children:"Sign out"})})})]})})})]}):null}function Le(e){return!!e&&(e.endsWith("@vertesiahq.com")||e.endsWith("@becomposable.com")||e.endsWith("@composableprompts.com"))}function Ie({icon:e}){const{isLoading:n}=E(),[i,a]=I(!0);return T((()=>{n||a(!1)}),[n]),t(ae,{appear:!0,show:i,as:A,unmount:!0,leave:"transition ease-in duration-500",leaveFrom:"opacity-100",leaveTo:"opacity-0",children:t("div",{style:{zIndex:999999},className:"fixed inset-x-0 inset-y-0",children:t("div",{className:"flex w-full h-full items-center justify-center",children:t("div",{className:"animate-[spin_4s_linear_infinite]",children:t("div",{className:"animate-pulse rounded-full bg-transparent",children:e||t(Te,{})})})})})})}function Te(){return e("svg",{className:"w-8 h-8 text-indigo-600",viewBox:"0 0 50 50",xmlns:"http://www.w3.org/2000/svg",children:[t("defs",{children:e("linearGradient",{id:"spinner-gradient",x1:"1",y1:"0",x2:"0",y2:"1",children:[t("stop",{offset:"0%",stopColor:"currentColor",stopOpacity:"1"}),t("stop",{offset:"100%",stopColor:"currentColor",stopOpacity:"0"})]})}),t("circle",{cx:"25",cy:"25",r:"20",stroke:"url(#spinner-gradient)",strokeWidth:"5",fill:"none",strokeLinecap:"round"})]})}function Ae({children:n,lightLogo:i,darkLogo:a,loadingIcon:o}){return t(z,{children:t(R,{children:e(L,{defaultTheme:"system",storageKey:"vite-ui-theme",children:[t(Ie,{icon:o}),t(fe,{allowedPrefix:"/shared/",lightLogo:i,darkLogo:a}),t(ie,{children:n})]})})})}const _e=_(null);function Ue({installation:e,children:n}){return t(_e.Provider,{value:e,children:n})}function Ee(){return U(_e)}function Oe({app:n,onChange:i,placeholder:a}){const{client:o,project:r}=E(),{data:l,error:c}=f((()=>o.apps.getAppInstallationProjects(n)),[n.id,n.name]);return c?e("span",{className:"text-red-600",children:["Error: failed to fetch projects: ",c.message]}):t(De,{placeholder:a,initialValue:r?.id,projects:l||[],onChange:e=>{i&&!i(e)||(localStorage.setItem(F,e.account),localStorage.setItem(Y+"-"+e.account,e.id),window.location.reload())}})}function De({initialValue:e,projects:n,onChange:i,placeholder:a="Select Project"}){const[o,r]=I();let l=!o&&e?n.find((t=>t.id===e)):o;return t(g,{by:"id",value:l,options:n,optionLabel:e=>e.name,placeholder:a,onChange:e=>{r(e),i(e)}})}function We({name:e,AccessDenied:n=Me,children:i}){return e?t(qe,{name:e,AccessDenied:n,children:i}):t(Re,{})}function qe({name:e,AccessDenied:n=Me,children:i}){const{authToken:a,client:o}=E(),[r,l]=I(null),[c,s]=I("loading");return T((()=>{if(a){a.apps.includes(e)?o.apps.getAppInstallationByName(e).then((t=>{t?(s("loaded"),l(t)):(console.log(`App ${e} not found!`),s("error"))})):s("error")}else s("loading")}),[e,a]),"loading"===c?null:"error"===c?t(n,{name:e}):r?t(Ue,{installation:r,children:i}):void 0}function Me({name:n}){const{project:i}=E();return e(p,{className:"pt-10 flex flex-col items-center text-center text-gray-700",children:[t(ne,{className:"w-10 h-10 mb-4 text-gray-500"}),t("div",{className:"text-xl font-semibold",children:"Access Denied"}),e("div",{className:"mt-2 text-sm text-gray-500",children:["You don't have permission to view the ",t("span",{className:"font-semibold",children:n})," app in project: ",e("span",{className:"font-semibold",children:["«",i?.name,"»"]}),"."]}),t("div",{className:"mt-4",children:t(Oe,{app:{name:n},onChange:e=>{localStorage.setItem(F,e.account),localStorage.setItem(Y+"-"+e.account,e.id),window.location.reload()}})})]})}function Re(){return e(p,{className:"pt-10 flex flex-col items-center text-center text-gray-700",children:[t(ne,{className:"w-10 h-10 mb-4 text-gray-500"}),t("div",{className:"text-xl font-semibold",children:"Application not registered"}),e("div",{className:"mt-2 text-sm text-gray-500",children:["Before starting to code a Vertesia application you must register an application manifest in Vertesia Studio then install it in one or more projects.",t("p",{}),"Then use the created app name as a parameter to ",t("code",{children:'<StandaloneApp name="your-app-name">'})," in the ",t("code",{children:"src/main.tsx"})," file."]})]})}export{_e as AppInstallationContext,Ue as AppInstallationProvider,Oe as AppProjectSelector,oe as InviteAcceptModal,fe as SigninScreen,We as StandaloneApp,qe as StandaloneAppImpl,xe as TerminalLogin,Pe as UserSessionMenu,Ae as VertesiaShell,Le as isVertesiaEmail,Ee as useAppInstallation};
|
|
1
|
+
import{jsxs as e,jsx as t,Fragment as n}from"react/jsx-runtime";import{Button as i,VModal as a,VModalTitle as o,VModalBody as r,useToast as l,Input as c,Spinner as s,SelectStack as d,VSelectBox as m,useSafeLayoutEffect as u,ErrorBox as h,Center as p,useFetch as f,SelectBox as g,Modal as v,ModalTitle as x,ModalBody as y,ModalFooter as b,VTabs as N,VTabsBar as w,VTabsPanel as k,VTooltip as C,Avatar as j,ModeToggle as S,MenuList as P,ToastProvider as z,ThemeProvider as L}from"@vertesia/ui/core";import{useState as I,useEffect as T,Fragment as A,createContext as _,useContext as U}from"react";import{useUserSession as E,useUXTracking as O,setFirebaseTenant as D,getFirebaseAuth as W,UserNotFoundError as q,fetchComposableTokenFromFirebaseToken as M,UserSessionProvider as R,LastSelectedAccountId_KEY as F,LastSelectedProjectId_KEY as Y}from"@vertesia/ui/session";import{Env as G}from"@vertesia/ui/env";import V from"clsx";import{signInWithRedirect as B,OAuthProvider as J,GoogleAuthProvider as H,GithubAuthProvider as $,getAuth as K}from"firebase/auth";import{useLocation as Q}from"@vertesia/ui/router";import{Popover as X}from"@vertesia/ui/widgets";import{getTenantIdFromProject as Z}from"@vertesia/common";import{Check as ee,CopyIcon as te,LockIcon as ne}from"lucide-react";import{UserPermissionProvider as ie}from"@vertesia/ui/features";import{Transition as ae}from"@headlessui/react";function oe(){const n=E(),{client:l,account:c}=n,[s,d]=I(!1),[m,u]=I([]);T((()=>{l.account.listInvites().then((e=>{if(e.length>0){const t=e.filter((e=>e.data.account));if(0===t.length)return void console.log("No valid invites found, closing modal");console.log("Found valid invites",t.length),d(!0),u(t)}else console.log("No invites found, closing modal"),d(!1)})).catch((e=>{console.error("Error fetching invites",e)}))}),[c?.id]);const h=()=>d(!1),p=m.map((a=>a.data.account?e("div",{className:"flex flex-row w-full justify-between border rounded-sm px-2 py-2 ",children:[e("div",{className:"flex flex-col",children:[t("div",{className:"w-full font-semibold",children:a.data.account.name??a.data.account}),a.data.project&&e("div",{className:"w-full text-base",children:["- ",a.data.project.name]}),e("div",{className:"text-xs",children:["Role: ",a.data.role]}),a.data.invited_by&&e("div",{className:"text-xs",children:["by ",a.data.invited_by.name??a.data.invited_by]})]}),e("div",{className:"flex flex-col gap-4",children:[t(i,{size:"xs",onClick:()=>(async e=>{await l.account.acceptInvite(e.id),await n.fetchAccounts();const t=m.filter((t=>t.id!==e.id)).filter((e=>e.data.account));t.length>0?u(t):h()})(a),children:"Accept"})," ",t(i,{size:"xs",variant:"secondary",onClick:()=>(async e=>{await l.account.rejectInvite(e.id);const t=m.filter((t=>t.id!==e.id));u(t),0===t.length&&h()})(a),children:"Reject"})]})]},a.id):(console.warn("Invite has no account data",a),null)));return t("div",{children:e(a,{isOpen:s,onClose:h,children:[t(o,{children:"Review Invites"}),e(r,{children:[t("div",{className:"text-sm pb-4",children:"You have received the following invites to join other accounts. Please review and accept or declined them."}),p]})]})})}function re({redirectTo:a}){const[o,r]=I(!1),{trackEvent:d}=O(),[m,u]=I(""),h=l();return e(n,{children:[t(c,{value:m,onChange:u,placeholder:"Enter your enterprise email",type:"email"}),o?t("div",{className:"w-full flex justify-center",children:t(s,{})}):t(i,{variant:"outline",onClick:async()=>{if(!m)return;/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(m)?(r(!0),D(m).then((e=>{if(!e)return h({title:"Tenant not found",status:"error",duration:5e3}),void r(!1);localStorage.setItem("tenantName",e.name??"");const t=function(e){if(!G.firebase)throw new Error("Firebase configuration is not available in the environment");switch(G.firebase.providerType){case"oidc":default:return new J("oidc.main");case"google":{let t=e||window.location.pathname||"/";"/"!==t[0]&&(t="/"+t);const n=new H;return n.addScope("profile"),n.addScope("email"),n.setCustomParameters({prompt:"select_account",redirect_uri:window.location.origin+t}),n}case"microsoft":return new J("microsoft.com");case"github":return new J("github.com")}}(a);d("enterprise_signin",{firebaseTenantName:e.name}),G.logger.info("Enterprise single sign-in",{vertesia:{email:m,firebaseTenantName:e.name,firebaseTenantId:e.firebaseTenantId}}),B(W(),t),r(!1)}))):h({title:"Invalid email address",status:"error",duration:5e3})},className:"w-full mt-2 py-4 flex rounded-lg hover:shadow-sm transition duration-150 text-center",children:t("span",{className:"text-sm font-semibold",children:"Continue with Enterprise SSO"})})]})}function le({}){return e(i,{variant:"outline",onClick:()=>{localStorage.removeItem("tenantName");let e="https://dengenlabs.firebaseapp.com/__/auth/handler"+window.location.pathname;"/"!==e[0]&&(e="/"+e);const t=new $;t.addScope("profile"),t.addScope("email"),B(W(),t)},className:"w-full py-5 flex rounded-lg hover:shadow-sm transition duration-150 text-center mb-2",children:[t("img",{className:"size-6 bg-white rounded-full",src:"https://www.svgrepo.com/show/503359/github.svg",loading:"lazy",alt:"github logo"}),t("span",{className:"text-sm font-semibold",children:"Continue with GitHub"})]})}function ce({redirectTo:n}){return e(i,{variant:"outline",onClick:()=>{localStorage.removeItem("tenantName");let e=n||window.location.pathname||"/";"/"!==e[0]&&(e="/"+e);const t=new H;t.addScope("profile"),t.addScope("email"),t.setCustomParameters({prompt:"select_account",redirect_uri:window.location.origin+e}),B(W(),t)},className:"w-full py-5 flex rounded-lg hover:shadow-sm transition duration-150 text-center mb-2",children:[t("img",{className:"size-6",src:"https://www.svgrepo.com/show/475656/google-color.svg",loading:"lazy",alt:"google logo"}),t("span",{className:"text-sm font-semibold",children:"Continue with Google"})]})}function se({redirectTo:n}){return e(i,{variant:"outline",onClick:()=>{localStorage.removeItem("tenantName");let e=n||window.location.pathname||"/";"/"!==e[0]&&(e="/"+e);const t=new J("microsoft.com");t.addScope("profile"),t.addScope("email"),B(W(),t)},className:"w-full py-5 flex rounded-lg hover:shadow-sm transition duration-150 text-center",children:[t("img",{className:"size-6",src:"https://learn.microsoft.com/en-us/entra/identity-platform/media/howto-add-branding-in-apps/ms-symbollockup_mssymbol_19.svg",loading:"lazy",alt:"microsoft logo"}),t("span",{className:"text-sm font-semibold",children:"Continue with Microsoft"})]})}const de=[{id:1,label:"1-10 employees"},{id:11,label:"11-100 employees"},{id:101,label:"101-1000 employees"},{id:1001,label:"1001-5000 employees"},{id:5001,label:"5000+ employees"}],me=[{id:"personal",label:"Personal",description:"For personal use, or for a small team."},{id:"company",label:"Company",description:"For a company or organization."}],ue=[{id:"testing",label:"Just Testing or Evaluating LLMs"},{id:"exploring",label:"Actively Exploring LLMs on a Project"},{id:"using",label:"Already Using LLMs in Production"},{id:"migrating",label:"Migrating to different LLMs"},{id:"other",label:"Other"}];function he({onSignup:a,goBack:o}){const[r,l]=I(void 0),[s,u]=I(void 0),[h,p]=I(void 0),[f,g]=I(void 0),[v,x]=I(void 0),[y,b]=I(void 0),[N,w]=I(void 0),k="company"===r;T((()=>{const e=K().currentUser;e?b(e):console.error("No user found")}),[y]);return e("div",{className:"flex flex-col space-y-2",children:[e("div",{className:"prose",children:[e("p",{className:"prose text-sm text-muted pt-4",children:["Welcome to Vertesia, ",y?.displayName," (",y?.email,"). Please tell us a little bit about yourself and you'll be on your way. No credit card is required."]}),N&&t("div",{className:"text-destructive",children:N})]}),t(pe,{label:"Account Type",children:t(d,{options:me,selected:me.find((e=>e.id===r)),onSelect:e=>l(e.id)})}),k&&e(n,{children:[t(pe,{label:"Company Size",children:t(m,{className:"w-full border border-accent bg-muted",value:s,options:de,onChange:u,optionLabel:e=>e?.label,placeholder:"Select Company Size"})}),t(pe,{label:"Company Name",children:t(c,{value:h,onChange:p,type:"text",required:!0})}),t(pe,{label:"Company Website",children:t(c,{value:f,onChange:g,type:"text"})})]}),t(pe,{label:"Project Maturity",children:t(m,{className:"w-full border border-accent bg-muted",options:ue,value:ue.find((e=>e.id===v)),optionLabel:e=>e?.label,placeholder:"Select Project Maturity",onChange:e=>x(e?.id)})}),e("div",{className:"pt-8 flex flex-col",children:[t(i,{variant:"primary",onClick:async()=>{if(!(r?k&&!h?(w("Please enter an organization name"),0):!k||s||(w("Please select a company size"),0):(w("Please select an account type"),0)))return;if(!r)return;const e={accountType:r,companyName:h,companySize:s?.id,companyWebsite:f,maturity:v};window.localStorage.setItem("composableSignupData",JSON.stringify(e));const t=await(K().currentUser?.getIdToken());console.log("Got firebase token",K(),t),t?a(e,t):console.error("No firebase token found")},size:"xl",children:t("span",{className:"text-lg",children:"Sign Up"})}),t(i,{variant:"ghost",size:"xl",className:"mt-4",onClick:o,children:t("span",{className:"",children:"Wrong account, go back"})})]})]})}function pe({label:n,children:i}){return e("div",{className:"flex flex-col space-y-2 pt-4",children:[t("div",{className:"text-sm text-muted",children:n}),i]})}function fe({allowedPrefix:e,isNested:n=!1,lightLogo:i,darkLogo:a}){const[o,r]=I(!1);return u((()=>{e&&r(window.location.href.startsWith(e))}),[]),o?null:t(ge,{isNested:n,lightLogo:i,darkLogo:a})}function ge({isNested:n=!1,lightLogo:i,darkLogo:a}){const{isLoading:o,user:r,authError:l}=E();return o||r?null:t("div",{style:{zIndex:999998},className:(n?"absolute":"fixed")+"overflow-y-auto ",children:e("div",{className:V("flex flex-col items-center justify-center py-14 px-4"),children:[t(ve,{authError:l,lightLogo:i,darkLogo:a}),e("div",{className:"flex gap-x-6 mt-10 justify-center text-muted",children:[t("a",{href:"https://vertesiahq.com/privacy",className:"text-sm",children:"Privacy Policy"}),t("a",{href:"https://vertesiahq.com/terms",className:"text-sm",children:"Terms of Service"})]})]})})}function ve({authError:a,darkLogo:o,lightLogo:r}){const[l,c]=I(void 0),[s,d]=I(!1),{signOut:m}=E(),{trackEvent:u}=O();history.replaceState({},"","/");const h=()=>{c(void 0),d(!0)};T((()=>{a instanceof q&&(console.log("User not found, redirecting to signup"),h())}),[a]);return e(n,{children:[r&&t("img",{src:r,alt:"logo",className:"h-15 block dark:hidden"}),o&&t("img",{src:o,alt:"logo",className:"h-15 hidden dark:block"}),l&&e("div",{className:"my-6",children:["Need to make a change?"," ",t(i,{onClick:h,children:" Go back"})]}),t("div",{className:"flex flex-col space-y-2",children:s&&!localStorage.getItem("tenantName")?t(he,{onSignup:(e,t)=>{console.log("Got Signup data",e),c(e);const n={signupData:e,firebaseToken:t};fetch(G.endpoints.studio+"/auth/signup",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)}).then((e=>{console.log("Signup successful",n,e),u("sign_up"),window.location.href="/"}))},goBack:()=>{console.log("Going back, signing out"),c(void 0),d(!1),m()}}):e("div",{className:"flex flex-col",children:[t("div",{className:"my-4",children:t("h2",{className:"text-2xl font-bold text-center",children:"Log in or Sign up"})}),e("div",{className:"max-w-2xl text-center my-2 px-2",children:["First time here? No problem, it's free to try!",t("br",{}),"We'll just ask you a couple of questions next and you'll be on your way."]}),e("div",{className:"flex items-center flex-col",children:[e("div",{className:"py-4 w-70",children:[t(ce,{}),t(le,{}),t(se,{})]}),e("div",{className:"flex items-center flex-row w-70 text-muted",children:[t("hr",{className:"w-full"}),t("div",{className:"px-2 text-xs",children:"OR"}),t("hr",{className:"w-full"})]}),t("div",{className:"py-4 w-70",children:t(re,{})})]}),a&&t("div",{className:"text-center",children:e("div",{className:"",children:["Sorry, we have not been able to sign you in.",t("br",{}),"Please try again or contact",t("a",{className:"text-info mx-1",href:"mailto:support@vertesiahq.com",children:"support@vertesiahq.com"}),"if it persists.",e("pre",{className:"mt-2",children:["Error: ",a.message]})]})})]})})]})}function xe(){const[e,n]=I(),[i,a]=I(),o=function(e){const t=new URLSearchParams(e.search);let n=t.get("redirect_uri");const i=t.get("code");return n&&i?(n=decodeURI(n),n.startsWith("http://127.0.0.1:")||n.startsWith("http://localhost:")?{redirect:n,code:i,profile:t.get("profile")??"default",project:t.get("project")??void 0,account:t.get("account")??void 0}:null):null}(Q()),r=l(),c=async e=>{if(!o)return;if(!e.profile)return void r({title:"Profile is required",description:"Please enter a profile name to save the client authorization",status:"error",duration:2e3});if(!e.account)return void r({title:"Account is required",description:"Please select an account to authorize the client to access the ComposablePrompts servers",status:"error",duration:2e3});if(!e.project)return void r({title:"Project is required",description:"Please select a project to authorize the client to access the ComposablePrompts servers",status:"error",duration:2e3});let t;try{const i=await M(e.account,e.project,86400);i?(t={...e,studio_server_url:G.endpoints.studio,zeno_server_url:G.endpoints.zeno,token:i},await fetch(o.redirect,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)}),n(t)):r({title:"Failed to get composable token",status:"error",duration:5e3})}catch(e){t?(a(e),n(t)):r({title:"Error authorizing client",description:e.message,status:"error",duration:5e3})}},s=o?e?t(be,{payload:e,error:i}):t(ye,{clientInfo:o,onAccept:c}):t(h,{title:"Invalid request",children:"This page should be called by a terminal client to authenticate against the ComposablePrompts servers"});return t("div",{className:"w-full flex flex-col items-center gap-4 mt-24",children:s})}function ye({onAccept:i,clientInfo:a}){const{client:o,user:r}=E(),{data:l,error:c}=f((()=>r?o.projects.list():Promise.resolve([])),[r]);if(c)return t(h,{title:"Error loading projects",children:c.message});const d=G.isLocalDev?"Local Dev":G.isDev?"Staging":"Production";return r&&l?e(n,{children:[e("div",{className:"w-1/3",children:[e("div",{className:"mb-4 text-xl font-semibold text-gray-800",children:["Authorizing client on ",d," environment."]}),e("div",{className:"mb-2 text-md text-gray-800",children:[t("div",{children:"A client app wants authorization to access the composable prompt servers in your name."}),e("div",{children:["The client app code is ",t("b",{children:a.code}),". You can check if the code is correct in the terminal."]})]}),e("div",{className:"mb-2 text-sm text-gray-600",children:[t("div",{children:"You must choose the target account and project for the client to access."}),t("div",{children:"Also, enter a profile name that will be used to save the authorization in your client configuration."})]})]}),t(Ne,{onAccept:i,allProjects:l,data:a})]}):t(s,{size:"lg"})}function be({payload:n,error:a}){const o=l();return e("div",{children:[a?e("div",{children:[e(h,{title:"Failed to send the authorization token to the cli tool",children:['This can happen due to security checks on Safari. The error is "',a.message,'"']}),t("div",{children:"Don't worry, you can still authenticate the cli tool by pasting the authentication token in the terminal. You can close this page."})]}):t("div",{children:"The client is authenticated. You can close this page."}),t(p,{className:"mt-4",children:t(i,{variant:"secondary",onClick:()=>{n&&(navigator.clipboard.writeText(JSON.stringify(n)),o({title:"Authentication Payload copied",description:a?"You can paste the authentication payload in the terminal to authenticate the client.":"You can close the page now.",status:"success",duration:5e3}))},children:"Copy the Authentication Payload"})})]})}function Ne({allProjects:n,data:a,onAccept:o}){const{accounts:r,account:l,project:s}=E(),[d,m]=I((()=>({profile:a.profile,account:a.account??l?.id,project:a.project??s?.id}))),u=n.filter((e=>e.account===d.account));return e("div",{className:"w-1/3",children:[e("div",{className:"mb-4 flex flex-col gap-2",children:[t("span",{className:"font-semibold text-gray-600",children:"Profile Name"}),t(c,{type:"text",value:d.profile,onChange:e=>{m({...d,profile:e})}})]}),e("div",{className:"mb-4 flex flex-col gap-2",children:[t("span",{className:"font-semibold text-gray-600",children:"Account"}),t(we,{value:d.account,onChange:e=>{m({...d,account:e.id,project:void 0})},accounts:r||[]})]}),e("div",{className:"mb-4 flex flex-col gap-2",children:[t("span",{className:"font-semibold text-gray-600",children:"Project"}),t(ke,{value:d.project,onChange:e=>{m({...d,project:e.id})},projects:u})]}),t("div",{className:"pt-2",children:t(i,{size:"xl",onClick:()=>o(d),children:"Authorize Client"})})]})}function we({value:e,accounts:n,onChange:i}){return t(g,{options:n,value:n?.find((t=>t.id===e)),onChange:e=>{i(e)},by:"id",optionLabel:e=>e.name,placeholder:"Select Account"})}function ke({value:e,projects:n,onChange:i}){return t(g,{by:"id",value:n.find((t=>t.id===e)),options:n,optionLabel:e=>e.name,placeholder:"Select Project",onChange:e=>{i(e)}})}function Ce({isOpen:n,onClose:a}){return e(v,{isOpen:n,onClose:a,children:[t(x,{children:"Sign In"}),e(y,{className:"flex justify-center",children:[t(ce,{}),t(le,{}),t(se,{})]}),t(b,{justify:"end",children:t(i,{variant:"ghost",onClick:a,children:"Cancel"})})]})}function je({title:n,value:i}){const[a,o]=I(!1);return e("div",{className:"w-full flex justify-between items-center mb-1",children:[e("div",{className:"flex flex-col w-[calc(100%-3rem)]",children:[t("div",{className:"text-sm px-2 dark:text-slate-200",children:n}),t(C,{description:i,size:"xs",placement:"left",children:e("div",{className:"text-xs truncate text-muted w-full text-left px-2",children:[i," "]})})]}),a?t(ee,{className:"size-4 cursor-pointer text-success"}):t(te,{className:"size-4 cursor-pointer text-gray-400 dark:text-slate-400",onClick:()=>function(e){navigator.clipboard.writeText(e),o(!0),setTimeout((()=>o(!1)),2e3)}(i)})]})}function Se(){const n=E(),{account:i,project:a,client:o,authToken:r}=n,l=new URL(o.baseUrl).hostname,c=new URL(o.store.baseUrl).hostname,s=a?Z(a):"",d=[{name:"user",label:"User",content:e("div",{className:"space-y-1 p-2",children:[t(je,{title:"Organization ID",value:i?.id??"Unknown"}),t(je,{title:"Project ID",value:a?.id??"Unknown"}),t(je,{title:"User ID",value:r?.sub??"Unknown"}),t(je,{title:"Organization Roles",value:r?.account_roles?.join(",")??"Unknown"}),t(je,{title:"Project Roles",value:r?.project_roles?.join(",")??"Unknown"})]})},{name:"environment",label:"Environment",content:e("div",{className:"space-y-1 p-2",children:[t(je,{title:"Tenant ID",value:s}),t(je,{title:"Environment",value:G.type}),t(je,{title:"Server",value:l}),t(je,{title:"Store",value:c}),t(je,{title:"App Version",value:G.version})]})}];return t("div",{className:"w-full",children:e(N,{defaultValue:"user",tabs:d,fullWidth:!0,updateHash:!1,children:[t(w,{}),t(k,{})]})})}function Pe({}){const{user:a,isLoading:o}=E(),[r,l]=I(!1);return o?t(s,{}):a?t("div",{className:"px-3",children:t(ze,{asMenuTrigger:!0})}):e(n,{children:[t(i,{onClick:()=>l(!0),children:"Sign In"}),t(Ce,{isOpen:r,onClose:()=>l(!1)})]})}function ze({className:n,asMenuTrigger:i=!1}){const a=E(),{user:o}=a;return a&&o?e(X,{strategy:"fixed",placement:"bottom-start",zIndex:100,children:[t(X.Trigger,{click:!0,children:t("div",{className:V(n,"flex items-center justify-start",i&&"cursor-pointer"),children:t(j,{size:"sm",color:"bg-amber-500",shape:"circle",name:o?.name})})}),t(X.Content,{className:"w-[280px] mx-2 my-1",children:t("div",{className:"bg-white dark:bg-slate-900 shadow-lg rounded-md ring-1 ring-gray-200 dark:ring-slate-700",children:e("div",{className:"divide-y divide-gray-200 dark:divide-slate-700",children:[e("div",{className:"py-2 pl-2",children:[t("p",{className:"px-4 dark:text-white mb-1",children:o?.name??"Unknown"}),t("p",{className:"px-4 text-xs text-gray-500",children:o?.email??""})]}),t("div",{className:"w-full p-1",children:t(Se,{})}),t("div",{className:"py-2 pl-2",children:t(S,{})}),t("div",{className:"py-2",children:t(P,{children:t(P.Item,{className:"px-2",onClick:()=>a.logout(),children:"Sign out"})})})]})})})]}):null}function Le(e){return!!e&&(e.endsWith("@vertesiahq.com")||e.endsWith("@becomposable.com")||e.endsWith("@composableprompts.com"))}function Ie({icon:e}){const{isLoading:n}=E(),[i,a]=I(!0);return T((()=>{n||a(!1)}),[n]),t(ae,{appear:!0,show:i,as:A,unmount:!0,leave:"transition ease-in duration-500",leaveFrom:"opacity-100",leaveTo:"opacity-0",children:t("div",{style:{zIndex:999999},className:"fixed inset-x-0 inset-y-0",children:t("div",{className:"flex w-full h-full items-center justify-center",children:t("div",{className:"animate-[spin_4s_linear_infinite]",children:t("div",{className:"animate-pulse rounded-full bg-transparent",children:e||t(Te,{})})})})})})}function Te(){return e("svg",{className:"w-8 h-8 text-indigo-600",viewBox:"0 0 50 50",xmlns:"http://www.w3.org/2000/svg",children:[t("defs",{children:e("linearGradient",{id:"spinner-gradient",x1:"1",y1:"0",x2:"0",y2:"1",children:[t("stop",{offset:"0%",stopColor:"currentColor",stopOpacity:"1"}),t("stop",{offset:"100%",stopColor:"currentColor",stopOpacity:"0"})]})}),t("circle",{cx:"25",cy:"25",r:"20",stroke:"url(#spinner-gradient)",strokeWidth:"5",fill:"none",strokeLinecap:"round"})]})}function Ae({children:n,lightLogo:i,darkLogo:a,loadingIcon:o}){return t(z,{children:t(R,{children:e(L,{defaultTheme:"system",storageKey:"vite-ui-theme",children:[t(Ie,{icon:o}),t(fe,{allowedPrefix:"/shared/",lightLogo:i,darkLogo:a}),t(ie,{children:n})]})})})}const _e=_(null);function Ue({installation:e,children:n}){return t(_e.Provider,{value:e,children:n})}function Ee(){return U(_e)}function Oe({app:n,onChange:i,placeholder:a}){const{client:o,project:r}=E(),{data:l,error:c}=f((()=>o.apps.getAppInstallationProjects(n)),[n.id,n.name]);return c?e("span",{className:"text-red-600",children:["Error: failed to fetch projects: ",c.message]}):t(De,{placeholder:a,initialValue:r?.id,projects:l||[],onChange:e=>{i&&!i(e)||(localStorage.setItem(F,e.account),localStorage.setItem(Y+"-"+e.account,e.id),window.location.reload())}})}function De({initialValue:e,projects:n,onChange:i,placeholder:a="Select Project"}){const[o,r]=I();let l=!o&&e?n.find((t=>t.id===e)):o;return t(m,{by:"id",value:l,options:n,optionLabel:e=>e.name,placeholder:a,onChange:e=>{r(e),i(e)}})}function We({name:e,AccessDenied:n=Me,children:i}){return e?t(qe,{name:e,AccessDenied:n,children:i}):t(Re,{})}function qe({name:e,AccessDenied:n=Me,children:i}){const{authToken:a,client:o}=E(),[r,l]=I(null),[c,s]=I("loading");return T((()=>{if(a){a.apps.includes(e)?o.apps.getAppInstallationByName(e).then((t=>{t?(s("loaded"),l(t)):(console.log(`App ${e} not found!`),s("error"))})):s("error")}else s("loading")}),[e,a]),"loading"===c?null:"error"===c?t(n,{name:e}):r?t(Ue,{installation:r,children:i}):void 0}function Me({name:n}){const{project:i}=E();return e(p,{className:"pt-10 flex flex-col items-center text-center text-gray-700",children:[t(ne,{className:"w-10 h-10 mb-4 text-gray-500"}),t("div",{className:"text-xl font-semibold",children:"Access Denied"}),e("div",{className:"mt-2 text-sm text-gray-500",children:["You don't have permission to view the ",t("span",{className:"font-semibold",children:n})," app in project: ",e("span",{className:"font-semibold",children:["«",i?.name,"»"]}),"."]}),t("div",{className:"mt-4",children:t(Oe,{app:{name:n},onChange:e=>{localStorage.setItem(F,e.account),localStorage.setItem(Y+"-"+e.account,e.id),window.location.reload()}})})]})}function Re(){return e(p,{className:"pt-10 flex flex-col items-center text-center text-gray-700",children:[t(ne,{className:"w-10 h-10 mb-4 text-gray-500"}),t("div",{className:"text-xl font-semibold",children:"Application not registered"}),e("div",{className:"mt-2 text-sm text-gray-500",children:["Before starting to code a Vertesia application you must register an application manifest in Vertesia Studio then install it in one or more projects.",t("p",{}),"Then use the created app name as a parameter to ",t("code",{children:'<StandaloneApp name="your-app-name">'})," in the ",t("code",{children:"src/main.tsx"})," file."]})]})}export{_e as AppInstallationContext,Ue as AppInstallationProvider,Oe as AppProjectSelector,oe as InviteAcceptModal,fe as SigninScreen,We as StandaloneApp,qe as StandaloneAppImpl,xe as TerminalLogin,Pe as UserSessionMenu,Ae as VertesiaShell,Le as isVertesiaEmail,Ee as useAppInstallation};
|
|
2
2
|
//# sourceMappingURL=vertesia-ui-shell.js.map
|