mirror of
https://github.com/docmost/docmost.git
synced 2026-08-27 08:47:06 +08:00
Compare commits
55
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0f0ebdd0bf | ||
|
|
c093c18bf3 | ||
|
|
8ba4792e25 | ||
|
|
06d7e24676 | ||
|
|
3219bd7160 | ||
|
|
8b73343b6c | ||
|
|
809f6eb3be | ||
|
|
5d8e9fde8b | ||
|
|
dacaaf5629 | ||
|
|
1dd7d79453 | ||
|
|
ecc6b974b5 | ||
|
|
defc1f4ba5 | ||
|
|
50e81ade57 | ||
|
|
228fe14cd8 | ||
|
|
2fe13daa09 | ||
|
|
44086cbb01 | ||
|
|
a81e5c42ec | ||
|
|
65af1cc2a4 | ||
|
|
231f0deeb0 | ||
|
|
b9d8612ecd | ||
|
|
e76c138e4c | ||
|
|
e146cfd075 | ||
|
|
efcca2e4fd | ||
|
|
3b57ce7c89 | ||
|
|
86687d2bf2 | ||
|
|
15f893184e | ||
|
|
dc3f7b0be4 | ||
|
|
88e057c76e | ||
|
|
89bf9f3078 | ||
|
|
b0f7c11fb3 | ||
|
|
feb5167771 | ||
|
|
97a1248818 | ||
|
|
b7d7ad4521 | ||
|
|
79df1229cb | ||
|
|
812d0765b5 | ||
|
|
234bd13453 | ||
|
|
affd2e6740 | ||
|
|
37e652ade5 | ||
|
|
38a847f305 | ||
|
|
7c80688698 | ||
|
|
0320e07bb1 | ||
|
|
1982a0ed1e | ||
|
|
fcb2b08cf3 | ||
|
|
e5ff58a73a | ||
|
|
d3bb105366 | ||
|
|
bbb1b5eb26 | ||
|
|
3e66aff1e2 | ||
|
|
89442f5154 | ||
|
|
12ef426541 | ||
|
|
93ff3f43b7 | ||
|
|
cbf03fc956 | ||
|
|
68309247b5 | ||
|
|
474ff6c629 | ||
|
|
c5e9be6b36 | ||
|
|
00e8c53852 |
@@ -51,17 +51,6 @@ DRAWIO_URL=
|
|||||||
# Gotenberg URL for server-side PDF export
|
# Gotenberg URL for server-side PDF export
|
||||||
GOTENBERG_URL=
|
GOTENBERG_URL=
|
||||||
|
|
||||||
# Integration OAuth apps (create one per provider you enable)
|
|
||||||
INTEGRATION_GITHUB_CLIENT_ID=
|
|
||||||
INTEGRATION_GITHUB_CLIENT_SECRET=
|
|
||||||
# Set only for GitHub Enterprise Server, e.g https://github.example.com
|
|
||||||
INTEGRATION_GITHUB_BASE_URL=
|
|
||||||
|
|
||||||
INTEGRATION_GITLAB_CLIENT_ID=
|
|
||||||
INTEGRATION_GITLAB_CLIENT_SECRET=
|
|
||||||
# Set only for self-hosted GitLab, e.g https://gitlab.example.com
|
|
||||||
INTEGRATION_GITLAB_BASE_URL=
|
|
||||||
|
|
||||||
DISABLE_TELEMETRY=false
|
DISABLE_TELEMETRY=false
|
||||||
|
|
||||||
# Allow other sites to embed Docmost in an iframe.
|
# Allow other sites to embed Docmost in an iframe.
|
||||||
|
|||||||
@@ -14,7 +14,6 @@
|
|||||||
"Are you sure you want to remove this user from the group? The user will lose access to resources this group has access to.": "Are you sure you want to remove this user from the group? The user will lose access to resources this group has access to.",
|
"Are you sure you want to remove this user from the group? The user will lose access to resources this group has access to.": "Are you sure you want to remove this user from the group? The user will lose access to resources this group has access to.",
|
||||||
"Are you sure you want to remove this user from the space? The user will lose all access to this space.": "Are you sure you want to remove this user from the space? The user will lose all access to this space.",
|
"Are you sure you want to remove this user from the space? The user will lose all access to this space.": "Are you sure you want to remove this user from the space? The user will lose all access to this space.",
|
||||||
"Are you sure you want to restore this version? Any changes not versioned will be lost.": "Are you sure you want to restore this version? Any changes not versioned will be lost.",
|
"Are you sure you want to restore this version? Any changes not versioned will be lost.": "Are you sure you want to restore this version? Any changes not versioned will be lost.",
|
||||||
"Assigned to {{name}}": "Assigned to {{name}}",
|
|
||||||
"Can become members of groups and spaces in workspace": "Can become members of groups and spaces in workspace",
|
"Can become members of groups and spaces in workspace": "Can become members of groups and spaces in workspace",
|
||||||
"Can create and edit pages in space.": "Can create and edit pages in space.",
|
"Can create and edit pages in space.": "Can create and edit pages in space.",
|
||||||
"Can edit": "Can edit",
|
"Can edit": "Can edit",
|
||||||
@@ -23,7 +22,7 @@
|
|||||||
"Can view": "Can view",
|
"Can view": "Can view",
|
||||||
"Can view pages in space but not edit.": "Can view pages in space but not edit.",
|
"Can view pages in space but not edit.": "Can view pages in space but not edit.",
|
||||||
"Cancel": "Cancel",
|
"Cancel": "Cancel",
|
||||||
"Card": "Card",
|
"Cancelled": "Cancelled",
|
||||||
"Change email": "Change email",
|
"Change email": "Change email",
|
||||||
"Change password": "Change password",
|
"Change password": "Change password",
|
||||||
"Change photo": "Change photo",
|
"Change photo": "Change photo",
|
||||||
@@ -31,9 +30,9 @@
|
|||||||
"Choose your preferred color scheme.": "Choose your preferred color scheme.",
|
"Choose your preferred color scheme.": "Choose your preferred color scheme.",
|
||||||
"Choose your preferred interface language.": "Choose your preferred interface language.",
|
"Choose your preferred interface language.": "Choose your preferred interface language.",
|
||||||
"Choose your preferred page width.": "Choose your preferred page width.",
|
"Choose your preferred page width.": "Choose your preferred page width.",
|
||||||
|
"Completed": "Completed",
|
||||||
"Confirm": "Confirm",
|
"Confirm": "Confirm",
|
||||||
"Connect to {{name}} to preview": "Connect to {{name}} to preview",
|
"Confluence site": "Confluence site",
|
||||||
"Connected as {{label}}": "Connected as {{label}}",
|
|
||||||
"Copy as Markdown": "Copy as Markdown",
|
"Copy as Markdown": "Copy as Markdown",
|
||||||
"Copy link": "Copy link",
|
"Copy link": "Copy link",
|
||||||
"Create": "Create",
|
"Create": "Create",
|
||||||
@@ -45,16 +44,6 @@
|
|||||||
"Dark": "Dark",
|
"Dark": "Dark",
|
||||||
"Date": "Date",
|
"Date": "Date",
|
||||||
"Delete": "Delete",
|
"Delete": "Delete",
|
||||||
"Initiative": "Initiative",
|
|
||||||
"Last modified by {{name}}": "Last modified by {{name}}",
|
|
||||||
"Open in Slack": "Open in Slack",
|
|
||||||
"Paid": "Paid",
|
|
||||||
"Paste as": "Paste as",
|
|
||||||
"Project": "Project",
|
|
||||||
"Uninstall {{name}}": "Uninstall {{name}}",
|
|
||||||
"Disconnect {{name}}": "Disconnect {{name}}",
|
|
||||||
"This disconnects your {{name}} account. Links are not enriched for you until you reconnect.": "This disconnects your {{name}} account. Links are not enriched for you until you reconnect.",
|
|
||||||
"This disables the {{name}} integration for the entire workspace. Members' connections are removed and links are not enriched.": "This disables the {{name}} integration for the entire workspace. Members' connections are removed and links are not enriched.",
|
|
||||||
"Remove from page": "Remove from page",
|
"Remove from page": "Remove from page",
|
||||||
"Base options": "Base options",
|
"Base options": "Base options",
|
||||||
"Delete group": "Delete group",
|
"Delete group": "Delete group",
|
||||||
@@ -71,6 +60,10 @@
|
|||||||
"e.g Space for product team": "e.g Space for product team",
|
"e.g Space for product team": "e.g Space for product team",
|
||||||
"e.g Space for sales team to collaborate": "e.g Space for sales team to collaborate",
|
"e.g Space for sales team to collaborate": "e.g Space for sales team to collaborate",
|
||||||
"Edit": "Edit",
|
"Edit": "Edit",
|
||||||
|
"Everyone with access to this space": "Everyone with access to this space",
|
||||||
|
"Failed": "Failed",
|
||||||
|
"Import details": "Import details",
|
||||||
|
"Permissions": "Permissions",
|
||||||
"Read": "Read",
|
"Read": "Read",
|
||||||
"Edit group": "Edit group",
|
"Edit group": "Edit group",
|
||||||
"Email": "Email",
|
"Email": "Email",
|
||||||
@@ -90,6 +83,7 @@
|
|||||||
"Failed to restore page": "Failed to restore page",
|
"Failed to restore page": "Failed to restore page",
|
||||||
"Failed to fetch recent pages": "Failed to fetch recent pages",
|
"Failed to fetch recent pages": "Failed to fetch recent pages",
|
||||||
"Failed to import pages": "Failed to import pages",
|
"Failed to import pages": "Failed to import pages",
|
||||||
|
"Failed to load comments. An error occurred.": "Failed to load comments. An error occurred.",
|
||||||
"Failed to load page. An error occurred.": "Failed to load page. An error occurred.",
|
"Failed to load page. An error occurred.": "Failed to load page. An error occurred.",
|
||||||
"Failed to update data": "Failed to update data",
|
"Failed to update data": "Failed to update data",
|
||||||
"Failed to create base": "Failed to create base",
|
"Failed to create base": "Failed to create base",
|
||||||
@@ -164,8 +158,9 @@
|
|||||||
"page": "page",
|
"page": "page",
|
||||||
"Page deleted successfully": "Page deleted successfully",
|
"Page deleted successfully": "Page deleted successfully",
|
||||||
"Page history": "Page history",
|
"Page history": "Page history",
|
||||||
"replies": "replies",
|
"Restricted pages": "Restricted pages",
|
||||||
"reply": "reply",
|
"Restrictions": "Restrictions",
|
||||||
|
"Running": "Running",
|
||||||
"Select version": "Select version",
|
"Select version": "Select version",
|
||||||
"Highlight changes": "Highlight changes",
|
"Highlight changes": "Highlight changes",
|
||||||
"Page import is in progress. Please do not close this tab.": "Page import is in progress. Please do not close this tab.",
|
"Page import is in progress. Please do not close this tab.": "Page import is in progress. Please do not close this tab.",
|
||||||
@@ -200,10 +195,9 @@
|
|||||||
"Invitation sent": "Invitation sent",
|
"Invitation sent": "Invitation sent",
|
||||||
"Settings": "Settings",
|
"Settings": "Settings",
|
||||||
"Setup workspace": "Setup workspace",
|
"Setup workspace": "Setup workspace",
|
||||||
"show less": "show less",
|
|
||||||
"show more": "show more",
|
|
||||||
"Sign In": "Sign In",
|
"Sign In": "Sign In",
|
||||||
"Sign Up": "Sign Up",
|
"Sign Up": "Sign Up",
|
||||||
|
"Site": "Site",
|
||||||
"Slug": "Slug",
|
"Slug": "Slug",
|
||||||
"Space": "Space",
|
"Space": "Space",
|
||||||
"Space description": "Space description",
|
"Space description": "Space description",
|
||||||
@@ -212,10 +206,13 @@
|
|||||||
"Space settings": "Space settings",
|
"Space settings": "Space settings",
|
||||||
"Space slug": "Space slug",
|
"Space slug": "Space slug",
|
||||||
"Spaces": "Spaces",
|
"Spaces": "Spaces",
|
||||||
|
"spaces": "spaces",
|
||||||
"Spaces you belong to": "Spaces you belong to",
|
"Spaces you belong to": "Spaces you belong to",
|
||||||
"No space found": "No space found",
|
"No space found": "No space found",
|
||||||
"Search for spaces": "Search for spaces",
|
"Search for spaces": "Search for spaces",
|
||||||
"Start typing to search...": "Start typing to search...",
|
"Start typing to search...": "Start typing to search...",
|
||||||
|
"Started at": "Started at",
|
||||||
|
"Started by": "Started by",
|
||||||
"Status": "Status",
|
"Status": "Status",
|
||||||
"Successfully imported": "Successfully imported",
|
"Successfully imported": "Successfully imported",
|
||||||
"Successfully restored": "Successfully restored",
|
"Successfully restored": "Successfully restored",
|
||||||
@@ -224,13 +221,13 @@
|
|||||||
"Theme": "Theme",
|
"Theme": "Theme",
|
||||||
"To change your email, you have to enter your password and new email.": "To change your email, you have to enter your password and new email.",
|
"To change your email, you have to enter your password and new email.": "To change your email, you have to enter your password and new email.",
|
||||||
"Toggle full page width": "Toggle full page width",
|
"Toggle full page width": "Toggle full page width",
|
||||||
"Toggle {{name}} integration": "Toggle {{name}} integration",
|
|
||||||
"Unable to import pages. Please try again.": "Unable to import pages. Please try again.",
|
"Unable to import pages. Please try again.": "Unable to import pages. Please try again.",
|
||||||
"Unassigned": "Unassigned",
|
|
||||||
"untitled": "untitled",
|
"untitled": "untitled",
|
||||||
"Untitled": "Untitled",
|
"Untitled": "Untitled",
|
||||||
"Updated successfully": "Updated successfully",
|
"Updated successfully": "Updated successfully",
|
||||||
"User": "User",
|
"User": "User",
|
||||||
|
"Users": "Users",
|
||||||
|
"users": "users",
|
||||||
"Workspace": "Workspace",
|
"Workspace": "Workspace",
|
||||||
"Workspace Name": "Workspace Name",
|
"Workspace Name": "Workspace Name",
|
||||||
"Workspace settings": "Workspace settings",
|
"Workspace settings": "Workspace settings",
|
||||||
|
|||||||
@@ -38,9 +38,6 @@ import SpaceTrash from "@/pages/space/space-trash.tsx";
|
|||||||
import UserApiKeys from "@/ee/api-key/pages/user-api-keys";
|
import UserApiKeys from "@/ee/api-key/pages/user-api-keys";
|
||||||
import WorkspaceApiKeys from "@/ee/api-key/pages/workspace-api-keys";
|
import WorkspaceApiKeys from "@/ee/api-key/pages/workspace-api-keys";
|
||||||
import AiSettings from "@/ee/ai/pages/ai-settings.tsx";
|
import AiSettings from "@/ee/ai/pages/ai-settings.tsx";
|
||||||
import Integrations from "@/features/integration/pages/integrations.tsx";
|
|
||||||
import Connections from "@/features/integration/pages/connections.tsx";
|
|
||||||
import SlackLinkPage from "@/features/integration/pages/slack-link.tsx";
|
|
||||||
import BasePage from "@/ee/base/pages/base-page.tsx";
|
import BasePage from "@/ee/base/pages/base-page.tsx";
|
||||||
import AuditLogs from "@/ee/audit/pages/audit-logs.tsx";
|
import AuditLogs from "@/ee/audit/pages/audit-logs.tsx";
|
||||||
import VerifiedPages from "@/ee/page-verification/pages/verified-pages.tsx";
|
import VerifiedPages from "@/ee/page-verification/pages/verified-pages.tsx";
|
||||||
@@ -50,6 +47,7 @@ import FavoritesPage from "@/pages/favorites/favorites-page";
|
|||||||
import AiChat from "@/ee/ai-chat/pages/ai-chat.tsx";
|
import AiChat from "@/ee/ai-chat/pages/ai-chat.tsx";
|
||||||
import VerifyEmail from "@/ee/pages/verify-email.tsx";
|
import VerifyEmail from "@/ee/pages/verify-email.tsx";
|
||||||
import LabelPage from "@/pages/label/label-page";
|
import LabelPage from "@/pages/label/label-page";
|
||||||
|
import ConfluenceImportPage from "@/ee/confluence-import/pages/confluence-import.tsx";
|
||||||
|
|
||||||
export default function App() {
|
export default function App() {
|
||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
@@ -90,7 +88,6 @@ export default function App() {
|
|||||||
<Route path={"/pdf-render/:pageId"} element={<PdfRenderPage />} />
|
<Route path={"/pdf-render/:pageId"} element={<PdfRenderPage />} />
|
||||||
<Route path={"/share/:shareId"} element={<ShareRedirect />} />
|
<Route path={"/share/:shareId"} element={<ShareRedirect />} />
|
||||||
<Route path={"/p/:pageSlug"} element={<PageRedirect />} />
|
<Route path={"/p/:pageSlug"} element={<PageRedirect />} />
|
||||||
<Route path={"/integrations/slack/link"} element={<SlackLinkPage />} />
|
|
||||||
|
|
||||||
<Route element={<Layout />}>
|
<Route element={<Layout />}>
|
||||||
<Route path={"/home"} element={<Home />} />
|
<Route path={"/home"} element={<Home />} />
|
||||||
@@ -120,7 +117,6 @@ export default function App() {
|
|||||||
element={<AccountPreferences />}
|
element={<AccountPreferences />}
|
||||||
/>
|
/>
|
||||||
<Route path={"account/api-keys"} element={<UserApiKeys />} />
|
<Route path={"account/api-keys"} element={<UserApiKeys />} />
|
||||||
<Route path={"account/connections"} element={<Connections />} />
|
|
||||||
<Route path={"workspace"} element={<WorkspaceSettings />} />
|
<Route path={"workspace"} element={<WorkspaceSettings />} />
|
||||||
<Route path={"members"} element={<WorkspaceMembers />} />
|
<Route path={"members"} element={<WorkspaceMembers />} />
|
||||||
<Route path={"api-keys"} element={<WorkspaceApiKeys />} />
|
<Route path={"api-keys"} element={<WorkspaceApiKeys />} />
|
||||||
@@ -133,7 +129,10 @@ export default function App() {
|
|||||||
<Route path={"ai/mcp"} element={<AiSettings />} />
|
<Route path={"ai/mcp"} element={<AiSettings />} />
|
||||||
<Route path={"audit"} element={<AuditLogs />} />
|
<Route path={"audit"} element={<AuditLogs />} />
|
||||||
<Route path={"verifications"} element={<VerifiedPages />} />
|
<Route path={"verifications"} element={<VerifiedPages />} />
|
||||||
<Route path={"integrations"} element={<Integrations />} />
|
<Route
|
||||||
|
path={"import/confluence"}
|
||||||
|
element={<ConfluenceImportPage />}
|
||||||
|
/>
|
||||||
{!isCloud() && <Route path={"license"} element={<License />} />}
|
{!isCloud() && <Route path={"license"} element={<License />} />}
|
||||||
{isCloud() && <Route path={"billing"} element={<Billing />} />}
|
{isCloud() && <Route path={"billing"} element={<Billing />} />}
|
||||||
</Route>
|
</Route>
|
||||||
|
|||||||
@@ -1,22 +0,0 @@
|
|||||||
import { rem } from '@mantine/core';
|
|
||||||
|
|
||||||
interface Props {
|
|
||||||
size?: number | string;
|
|
||||||
}
|
|
||||||
|
|
||||||
export function GithubIcon({ size }: Props) {
|
|
||||||
return (
|
|
||||||
<svg
|
|
||||||
xmlns="http://www.w3.org/2000/svg"
|
|
||||||
viewBox="0 0 512 512"
|
|
||||||
style={{ width: rem(size), height: rem(size) }}
|
|
||||||
>
|
|
||||||
<path
|
|
||||||
fill="currentColor"
|
|
||||||
fillRule="evenodd"
|
|
||||||
clipRule="evenodd"
|
|
||||||
d="M256 6.3C114.6 6.3 0 120.9 0 262.3c0 113.3 73.3 209 175 242.9 12.8 2.2 17.6-5.4 17.6-12.2 0-6.1-.3-26.2-.3-47.7-64.3 11.8-81-15.7-86.1-30.1-2.9-7.4-15.4-30.1-26.2-36.2-9-4.8-21.8-16.6-.3-17 20.2-.3 34.6 18.6 39.4 26.2 23 38.7 59.8 27.8 74.6 21.1 2.2-16.6 9-27.8 16.3-34.2-57-6.4-116.5-28.5-116.5-126.4 0-27.8 9.9-50.9 26.2-68.8-2.6-6.4-11.5-32.6 2.6-67.8 0 0 21.4-6.7 70.4 26.2 20.5-5.8 42.2-8.6 64-8.6s43.5 2.9 64 8.6c49-33.3 70.4-26.2 70.4-26.2 14.1 35.2 5.1 61.4 2.6 67.8 16.3 17.9 26.2 40.6 26.2 68.8 0 98.2-59.8 120-116.8 126.4 9.3 8 17.3 23.4 17.3 47.4 0 34.2-.3 61.8-.3 70.4 0 6.7 4.8 14.7 17.6 12.2C438.7 471.3 512 375.3 512 262.3c0-141.4-114.6-256-256-256"
|
|
||||||
/>
|
|
||||||
</svg>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -1,32 +0,0 @@
|
|||||||
import { rem } from '@mantine/core';
|
|
||||||
|
|
||||||
interface Props {
|
|
||||||
size?: number | string;
|
|
||||||
}
|
|
||||||
|
|
||||||
export function GitlabIcon({ size }: Props) {
|
|
||||||
return (
|
|
||||||
<svg
|
|
||||||
xmlns="http://www.w3.org/2000/svg"
|
|
||||||
viewBox="93.97 97.52 192.05 184.99"
|
|
||||||
style={{ width: rem(size), height: rem(size) }}
|
|
||||||
>
|
|
||||||
<path
|
|
||||||
fill="#e24329"
|
|
||||||
d="m282.83 170.73-.27-.69-26.14-68.22a6.8 6.8 0 0 0-2.69-3.24 7 7 0 0 0-8 .43 7 7 0 0 0-2.32 3.52l-17.65 54h-71.47l-17.65-54a6.86 6.86 0 0 0-2.32-3.53 7 7 0 0 0-8-.43 6.87 6.87 0 0 0-2.69 3.24L97.44 170l-.26.69a48.54 48.54 0 0 0 16.1 56.1l.09.07.24.17 39.82 29.82 19.7 14.91 12 9.06a8.07 8.07 0 0 0 9.76 0l12-9.06 19.7-14.91 40.06-30 .1-.08a48.56 48.56 0 0 0 16.08-56.04"
|
|
||||||
/>
|
|
||||||
<path
|
|
||||||
fill="#fc6d26"
|
|
||||||
d="m282.83 170.73-.27-.69a88.3 88.3 0 0 0-35.15 15.8L190 229.25c19.55 14.79 36.57 27.64 36.57 27.64l40.06-30 .1-.08a48.56 48.56 0 0 0 16.1-56.08"
|
|
||||||
/>
|
|
||||||
<path
|
|
||||||
fill="#fca326"
|
|
||||||
d="m153.43 256.89 19.7 14.91 12 9.06a8.07 8.07 0 0 0 9.76 0l12-9.06 19.7-14.91S209.55 244 190 229.25c-19.55 14.75-36.57 27.64-36.57 27.64"
|
|
||||||
/>
|
|
||||||
<path
|
|
||||||
fill="#fc6d26"
|
|
||||||
d="M132.58 185.84A88.2 88.2 0 0 0 97.44 170l-.26.69a48.54 48.54 0 0 0 16.1 56.1l.09.07.24.17 39.82 29.82L190 229.21Z"
|
|
||||||
/>
|
|
||||||
</svg>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -1,28 +0,0 @@
|
|||||||
import { rem } from '@mantine/core';
|
|
||||||
|
|
||||||
interface Props {
|
|
||||||
size?: number | string;
|
|
||||||
}
|
|
||||||
|
|
||||||
export function GoogleDocsIcon({ size }: Props) {
|
|
||||||
return (
|
|
||||||
<svg
|
|
||||||
xmlns="http://www.w3.org/2000/svg"
|
|
||||||
viewBox="0 0 47 65"
|
|
||||||
style={{ width: rem(size), height: rem(size) }}
|
|
||||||
>
|
|
||||||
<path
|
|
||||||
fill="#4285F4"
|
|
||||||
d="M29.375 0H4.406C1.983 0 0 1.994 0 4.432v56.136C0 63.006 1.983 65 4.406 65h38.188C45.017 65 47 63.006 47 60.568v-42.84L36.719 10.34z"
|
|
||||||
/>
|
|
||||||
<path
|
|
||||||
fill="#A1C2FA"
|
|
||||||
d="M29.375 0v13.295c0 2.449 1.972 4.432 4.406 4.432H47z"
|
|
||||||
/>
|
|
||||||
<path
|
|
||||||
fill="#F1F1F1"
|
|
||||||
d="M11.75 47.273h23.5v-2.955h-23.5zm0 5.909h17.625v-2.955H11.75zm0-20.682v2.955h23.5V32.5zm0 8.864h23.5v-2.955h-23.5z"
|
|
||||||
/>
|
|
||||||
</svg>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -1,16 +1,10 @@
|
|||||||
export { AirtableIcon } from "./airtable-icon.tsx";
|
export { AirtableIcon } from "./airtable-icon.tsx";
|
||||||
export { FigmaIcon } from "./figma-icon.tsx";
|
export { FigmaIcon } from "./figma-icon.tsx";
|
||||||
export { GithubIcon } from "./github-icon.tsx";
|
|
||||||
export { GitlabIcon } from "./gitlab-icon.tsx";
|
|
||||||
export { GoogleDocsIcon } from "./google-docs-icon.tsx";
|
|
||||||
export { GoogleDriveIcon } from "./google-drive-icon.tsx";
|
|
||||||
export { GoogleSheetsIcon } from "./google-sheets-icon.tsx";
|
|
||||||
export { JiraIcon } from "./jira-icon.tsx";
|
|
||||||
export { LinearIcon } from "./linear-icon.tsx";
|
|
||||||
export { TypeformIcon } from "./typeform-icon.tsx";
|
export { TypeformIcon } from "./typeform-icon.tsx";
|
||||||
export { VimeoIcon } from "./vimeo-icon.tsx";
|
export { VimeoIcon } from "./vimeo-icon.tsx";
|
||||||
export { MiroIcon } from "./miro-icon.tsx";
|
export { MiroIcon } from "./miro-icon.tsx";
|
||||||
export { SlackIcon } from "./slack-icon.tsx";
|
export { GoogleDriveIcon } from "./google-drive-icon.tsx";
|
||||||
|
export { GoogleSheetsIcon } from "./google-sheets-icon.tsx";
|
||||||
export { FramerIcon } from "./framer-icon.tsx";
|
export { FramerIcon } from "./framer-icon.tsx";
|
||||||
export { LoomIcon } from "./loom-icon.tsx";
|
export { LoomIcon } from "./loom-icon.tsx";
|
||||||
export { YoutubeIcon } from "./youtube-icon.tsx";
|
export { YoutubeIcon } from "./youtube-icon.tsx";
|
||||||
|
|||||||
@@ -1,38 +0,0 @@
|
|||||||
import { rem } from '@mantine/core';
|
|
||||||
|
|
||||||
interface Props {
|
|
||||||
size?: number | string;
|
|
||||||
}
|
|
||||||
|
|
||||||
export function JiraIcon({ size }: Props) {
|
|
||||||
return (
|
|
||||||
<svg
|
|
||||||
xmlns="http://www.w3.org/2000/svg"
|
|
||||||
viewBox="0 0 512 512"
|
|
||||||
style={{ width: rem(size), height: rem(size) }}
|
|
||||||
>
|
|
||||||
<defs>
|
|
||||||
<linearGradient id="jira-a" x1="380.896" x2="279.145" y1="390.609" y2="282.574" gradientTransform="matrix(1 0 0 -1 0 514)" gradientUnits="userSpaceOnUse">
|
|
||||||
<stop offset=".176" stopColor="#0052cc" />
|
|
||||||
<stop offset="1" stopColor="#2684ff" />
|
|
||||||
</linearGradient>
|
|
||||||
<linearGradient id="jira-b" x1="265.965" x2="148.117" y1="270.661" y2="152.607" gradientTransform="matrix(1 0 0 -1 0 514)" gradientUnits="userSpaceOnUse">
|
|
||||||
<stop offset=".176" stopColor="#0052cc" />
|
|
||||||
<stop offset="1" stopColor="#2684ff" />
|
|
||||||
</linearGradient>
|
|
||||||
</defs>
|
|
||||||
<path
|
|
||||||
fill="#2684ff"
|
|
||||||
d="M490.6 7.4H243.9c0 59.6 49.9 108 111.2 108h45.6v42.2c0 59.6 49.9 108 111.2 108V28.1c.1-11.7-9.2-20.7-21.3-20.7"
|
|
||||||
/>
|
|
||||||
<path
|
|
||||||
fill="url(#jira-a)"
|
|
||||||
d="M368.7 126.5H121.9c0 59.6 49.9 108 111.2 108h45.6v42.9c0 59.6 49.9 108 111.2 108V147.3c.2-11.1-9.1-20.8-21.2-20.8"
|
|
||||||
/>
|
|
||||||
<path
|
|
||||||
fill="url(#jira-b)"
|
|
||||||
d="M246.7 246.3H0c0 59.6 49.9 108 111.2 108h45.6v42.2c0 59.6 49.9 108 111.2 108V267.1c.1-11.8-9.9-20.8-21.3-20.8"
|
|
||||||
/>
|
|
||||||
</svg>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -1,21 +0,0 @@
|
|||||||
import { rem } from '@mantine/core';
|
|
||||||
|
|
||||||
interface Props {
|
|
||||||
size?: number | string;
|
|
||||||
}
|
|
||||||
|
|
||||||
export function LinearIcon({ size }: Props) {
|
|
||||||
return (
|
|
||||||
<svg
|
|
||||||
xmlns="http://www.w3.org/2000/svg"
|
|
||||||
fill="none"
|
|
||||||
viewBox="0 0 100 100"
|
|
||||||
style={{ width: rem(size), height: rem(size) }}
|
|
||||||
>
|
|
||||||
<path
|
|
||||||
fill="currentColor"
|
|
||||||
d="M1.22541 61.5228c-.2225-.9485.90748-1.5459 1.59638-.857L39.3342 97.1782c.6889.6889.0915 1.8189-.857 1.5964C20.0515 94.4522 5.54779 79.9485 1.22541 61.5228ZM.00189135 46.8891c-.01764375.2833.08887215.5599.28957165.7606L52.3503 99.7085c.2007.2007.4773.3075.7606.2896 2.3692-.1476 4.6938-.46 6.9624-.9259.7645-.157 1.0301-1.0963.4782-1.6481L2.57595 39.4485c-.55186-.5519-1.49117-.2863-1.648174.4782-.465915 2.2686-.77832 4.5932-.92588465 6.9624ZM4.21093 29.7054c-.16649.3738-.08169.8106.20765 1.1l64.77602 64.776c.2894.2894.7262.3742 1.1.2077 1.7861-.7956 3.5171-1.6927 5.1855-2.684.5521-.328.6373-1.0867.1832-1.5407L8.43566 24.3367c-.45409-.4541-1.21271-.3689-1.54074.1832-.99132 1.6684-1.88843 3.3994-2.68399 5.1855ZM12.6587 18.074c-.3701-.3701-.393-.9637-.0443-1.3541C21.7795 6.45931 35.1114 0 49.9519 0 77.5927 0 100 22.4073 100 50.0481c0 14.8405-6.4593 28.1724-16.7199 37.3375-.3903.3487-.984.3258-1.3542-.0443L12.6587 18.074Z"
|
|
||||||
/>
|
|
||||||
</svg>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -8,20 +8,11 @@ export function MiroIcon({ size }: Props) {
|
|||||||
return (
|
return (
|
||||||
<svg
|
<svg
|
||||||
xmlns="http://www.w3.org/2000/svg"
|
xmlns="http://www.w3.org/2000/svg"
|
||||||
fill="none"
|
viewBox="0 0 24 24"
|
||||||
viewBox="3 2 395 395"
|
|
||||||
style={{ width: rem(size), height: rem(size) }}
|
style={{ width: rem(size), height: rem(size) }}
|
||||||
>
|
>
|
||||||
<path
|
<path
|
||||||
fill="#FFDD33"
|
d="M17.392 0H13.9L17 4.808 10.444 0H6.949l3.102 6.3L3.494 0H0l3.05 8.131L0 24h3.494L10.05 6.985 6.949 24h3.494L17 5.494 13.899 24h3.493L24 3.672 17.392 0z" />
|
||||||
d="M3 100.754C3 46.2604 47.2435 2 101.754 2H299.246C353.756 2 398 46.2435 398 100.754V298.246C398 352.756 353.756 397 299.246 397H101.754C47.2435 397 3 352.756 3 298.246V100.754Z"
|
|
||||||
/>
|
|
||||||
<path
|
|
||||||
fill="#1C1C1E"
|
|
||||||
fillRule="evenodd"
|
|
||||||
clipRule="evenodd"
|
|
||||||
d="M265.573 77.3491H229.74L259.629 129.85L193.906 77.3491H158.072L190.934 141.468L122.238 77.3491H86.4041L122.238 159.031L86.4041 322.377H122.238L190.934 147.396L158.072 322.377H193.906L259.629 135.693L229.74 322.377H265.573L331.297 118.232L265.573 77.4335V77.3491Z"
|
|
||||||
/>
|
|
||||||
</svg>
|
</svg>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,32 +0,0 @@
|
|||||||
import { rem } from '@mantine/core';
|
|
||||||
|
|
||||||
interface Props {
|
|
||||||
size?: number | string;
|
|
||||||
}
|
|
||||||
|
|
||||||
export function SlackIcon({ size }: Props) {
|
|
||||||
return (
|
|
||||||
<svg
|
|
||||||
xmlns="http://www.w3.org/2000/svg"
|
|
||||||
viewBox="0 0 512 512"
|
|
||||||
style={{ width: rem(size), height: rem(size) }}
|
|
||||||
>
|
|
||||||
<path
|
|
||||||
d="M107.9 323.6c0 29.7-24 53.8-53.8 53.8S.3 353.4.3 323.6c0-29.7 24-53.8 53.8-53.8h53.8zm26.9 0c0-29.7 24-53.8 53.8-53.8s53.8 24 53.8 53.8V458c0 29.7-24 53.8-53.8 53.8s-53.8-24-53.8-53.8z"
|
|
||||||
fill="#e01e5a"
|
|
||||||
/>
|
|
||||||
<path
|
|
||||||
d="M188.6 107.7c-29.7 0-53.8-24-53.8-53.8S158.8.1 188.6.1s53.8 24 53.8 53.8v53.8zm0 27.3c29.7 0 53.8 24 53.8 53.8s-24 53.8-53.8 53.8H53.8C24 242.6 0 218.5 0 188.8S24 135 53.8 135z"
|
|
||||||
fill="#36c5f0"
|
|
||||||
/>
|
|
||||||
<path
|
|
||||||
d="M404.1 188.8c0-29.7 24-53.8 53.8-53.8s53.8 24 53.8 53.8-24 53.8-53.8 53.8h-53.8zm-26.9 0c0 29.7-24 53.8-53.8 53.8-29.7 0-53.8-24-53.8-53.8V54c0-29.7 24-53.8 53.8-53.8s53.8 24 53.8 53.8z"
|
|
||||||
fill="#2eb67d"
|
|
||||||
/>
|
|
||||||
<path
|
|
||||||
d="M323.4 404.3c29.7 0 53.8 24 53.8 53.8 0 29.7-24 53.8-53.8 53.8-29.7 0-53.8-24-53.8-53.8v-53.8zm0-26.9c-29.7 0-53.8-24-53.8-53.8s24-53.8 53.8-53.8h134.8c29.7 0 53.8 24 53.8 53.8 0 29.7-24 53.8-53.8 53.8z"
|
|
||||||
fill="#ecb22e"
|
|
||||||
/>
|
|
||||||
</svg>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -1,6 +1,7 @@
|
|||||||
import { ActionIcon, Box, Group, ScrollArea, Title, Tooltip } from "@mantine/core";
|
import { ActionIcon, Box, Group, ScrollArea, Title, Tooltip } from "@mantine/core";
|
||||||
import { IconX } from "@tabler/icons-react";
|
import { IconX } from "@tabler/icons-react";
|
||||||
import CommentListWithTabs from "@/features/comment/components/comment-list-with-tabs.tsx";
|
import CommentListWithTabs from "@/features/comment/components/comment-list-with-tabs.tsx";
|
||||||
|
import { CommentErrorBoundary } from "@/features/comment/components/comment-error-boundary.tsx";
|
||||||
import { useAtom } from "jotai";
|
import { useAtom } from "jotai";
|
||||||
import { asideStateAtom } from "@/components/layouts/global/hooks/atoms/sidebar-atom.ts";
|
import { asideStateAtom } from "@/components/layouts/global/hooks/atoms/sidebar-atom.ts";
|
||||||
import React, { ReactNode, useEffect } from "react";
|
import React, { ReactNode, useEffect } from "react";
|
||||||
@@ -28,7 +29,11 @@ export default function Aside() {
|
|||||||
|
|
||||||
switch (tab) {
|
switch (tab) {
|
||||||
case "comments":
|
case "comments":
|
||||||
component = <CommentListWithTabs />;
|
component = (
|
||||||
|
<CommentErrorBoundary>
|
||||||
|
<CommentListWithTabs />
|
||||||
|
</CommentErrorBoundary>
|
||||||
|
);
|
||||||
title = "Comments";
|
title = "Comments";
|
||||||
break;
|
break;
|
||||||
case "toc":
|
case "toc":
|
||||||
|
|||||||
@@ -13,14 +13,14 @@ import {
|
|||||||
IconKey,
|
IconKey,
|
||||||
IconWorld,
|
IconWorld,
|
||||||
IconSparkles,
|
IconSparkles,
|
||||||
IconPlug,
|
|
||||||
IconHistory,
|
IconHistory,
|
||||||
IconShieldCheck,
|
IconShieldCheck,
|
||||||
|
IconFileImport,
|
||||||
} from "@tabler/icons-react";
|
} from "@tabler/icons-react";
|
||||||
import { Link, useLocation } from "react-router-dom";
|
import { Link, useLocation } from "react-router-dom";
|
||||||
import classes from "./settings.module.css";
|
import classes from "./settings.module.css";
|
||||||
import { useTranslation } from "react-i18next";
|
import { useTranslation } from "react-i18next";
|
||||||
import { isCloud } from "@/lib/config.ts";
|
import { isBetaConfluenceImporter, isCloud } from "@/lib/config.ts";
|
||||||
import useUserRole from "@/hooks/use-user-role.tsx";
|
import useUserRole from "@/hooks/use-user-role.tsx";
|
||||||
import { useAtom } from "jotai";
|
import { useAtom } from "jotai";
|
||||||
import { entitlementAtom } from "@/ee/entitlement/entitlement-atom";
|
import { entitlementAtom } from "@/ee/entitlement/entitlement-atom";
|
||||||
@@ -52,6 +52,7 @@ type DataItem = {
|
|||||||
feature?: string;
|
feature?: string;
|
||||||
role?: "admin" | "owner";
|
role?: "admin" | "owner";
|
||||||
env?: "cloud" | "selfhosted";
|
env?: "cloud" | "selfhosted";
|
||||||
|
show?: () => boolean;
|
||||||
};
|
};
|
||||||
|
|
||||||
type DataGroup = {
|
type DataGroup = {
|
||||||
@@ -75,11 +76,6 @@ const groupedData: DataGroup[] = [
|
|||||||
path: "/settings/account/api-keys",
|
path: "/settings/account/api-keys",
|
||||||
feature: Feature.API_KEYS,
|
feature: Feature.API_KEYS,
|
||||||
},
|
},
|
||||||
{
|
|
||||||
label: "Connections",
|
|
||||||
icon: IconPlug,
|
|
||||||
path: "/settings/account/connections",
|
|
||||||
},
|
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -132,10 +128,12 @@ const groupedData: DataGroup[] = [
|
|||||||
env: "selfhosted",
|
env: "selfhosted",
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
label: "Integrations",
|
label: "Import",
|
||||||
icon: IconPlug,
|
icon: IconFileImport,
|
||||||
path: "/settings/integrations",
|
path: "/settings/import/confluence",
|
||||||
|
feature: Feature.CONFLUENCE_API_IMPORT,
|
||||||
role: "admin",
|
role: "admin",
|
||||||
|
show: () => isBetaConfluenceImporter(),
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
@@ -170,6 +168,7 @@ export default function SettingsSidebar() {
|
|||||||
entitlements?.features?.includes(f) ?? false;
|
entitlements?.features?.includes(f) ?? false;
|
||||||
|
|
||||||
const canShowItem = (item: DataItem) => {
|
const canShowItem = (item: DataItem) => {
|
||||||
|
if (item.show && !item.show()) return false;
|
||||||
if (item.env === "cloud" && !isCloud()) return false;
|
if (item.env === "cloud" && !isCloud()) return false;
|
||||||
if (item.env === "selfhosted" && isCloud()) return false;
|
if (item.env === "selfhosted" && isCloud()) return false;
|
||||||
if (item.role === "admin" && !isAdmin) return false;
|
if (item.role === "admin" && !isAdmin) return false;
|
||||||
|
|||||||
@@ -0,0 +1,340 @@
|
|||||||
|
import { useMemo, useState } from "react";
|
||||||
|
import {
|
||||||
|
Badge,
|
||||||
|
Group,
|
||||||
|
Loader,
|
||||||
|
Modal,
|
||||||
|
Progress,
|
||||||
|
Skeleton,
|
||||||
|
Stack,
|
||||||
|
Table,
|
||||||
|
Text,
|
||||||
|
Tooltip,
|
||||||
|
} from "@mantine/core";
|
||||||
|
import { IconAlertCircle, IconCheck, IconX } from "@tabler/icons-react";
|
||||||
|
import { useTranslation } from "react-i18next";
|
||||||
|
import {
|
||||||
|
ConfluenceImportHistoryItem,
|
||||||
|
ConfluenceImportStatus,
|
||||||
|
} from "@/ee/confluence-import/types/confluence-import.types";
|
||||||
|
import { CustomAvatar } from "@/components/ui/custom-avatar";
|
||||||
|
import { formattedDate } from "@/lib/time";
|
||||||
|
import NoTableResults from "@/components/common/no-table-results";
|
||||||
|
import { useConfluenceImportsQuery } from "@/ee/confluence-import/queries/confluence-import-queries";
|
||||||
|
|
||||||
|
const BADGE_STYLES = {
|
||||||
|
root: { flexShrink: 0 },
|
||||||
|
label: { overflow: "visible" as const },
|
||||||
|
};
|
||||||
|
|
||||||
|
function statusBadge(
|
||||||
|
status: ConfluenceImportStatus,
|
||||||
|
cancelled: boolean,
|
||||||
|
t: (key: string) => string,
|
||||||
|
) {
|
||||||
|
if (cancelled) {
|
||||||
|
return (
|
||||||
|
<Badge
|
||||||
|
color="gray"
|
||||||
|
variant="light"
|
||||||
|
leftSection={<IconX size={12} />}
|
||||||
|
styles={BADGE_STYLES}
|
||||||
|
>
|
||||||
|
{t("Cancelled")}
|
||||||
|
</Badge>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if (status === "processing") {
|
||||||
|
return (
|
||||||
|
<Badge
|
||||||
|
color="blue"
|
||||||
|
variant="light"
|
||||||
|
leftSection={<Loader size={10} />}
|
||||||
|
styles={BADGE_STYLES}
|
||||||
|
>
|
||||||
|
{t("Running")}
|
||||||
|
</Badge>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if (status === "success") {
|
||||||
|
return (
|
||||||
|
<Badge
|
||||||
|
color="teal"
|
||||||
|
variant="light"
|
||||||
|
leftSection={<IconCheck size={12} />}
|
||||||
|
styles={BADGE_STYLES}
|
||||||
|
>
|
||||||
|
{t("Completed")}
|
||||||
|
</Badge>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return (
|
||||||
|
<Badge
|
||||||
|
color="red"
|
||||||
|
variant="light"
|
||||||
|
leftSection={<IconAlertCircle size={12} />}
|
||||||
|
styles={BADGE_STYLES}
|
||||||
|
>
|
||||||
|
{t("Failed")}
|
||||||
|
</Badge>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function phaseLabel(phase: string | null, t: (key: string) => string): string {
|
||||||
|
if (!phase) return "—";
|
||||||
|
return t(phase.charAt(0).toUpperCase() + phase.slice(1));
|
||||||
|
}
|
||||||
|
|
||||||
|
function progressValue(item: ConfluenceImportHistoryItem) {
|
||||||
|
if (item.status === "success") return 100;
|
||||||
|
if (item.totalPages > 0) {
|
||||||
|
return Math.min(
|
||||||
|
100,
|
||||||
|
Math.round((item.importedPages / item.totalPages) * 100),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return item.status === "processing" ? 5 : 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
function ProgressCell({ item }: { item: ConfluenceImportHistoryItem }) {
|
||||||
|
const { t } = useTranslation();
|
||||||
|
const value = progressValue(item);
|
||||||
|
const color =
|
||||||
|
item.status === "failed"
|
||||||
|
? "red"
|
||||||
|
: item.status === "success"
|
||||||
|
? "teal"
|
||||||
|
: "blue";
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Stack gap={4}>
|
||||||
|
<Progress value={value} color={color} size="xs" animated={item.status === "processing"} />
|
||||||
|
<Group gap="xs" wrap="nowrap">
|
||||||
|
<Text fz="xs" c="dimmed" style={{ whiteSpace: "nowrap" }}>
|
||||||
|
{item.importedPages}/{item.totalPages || "?"} {t("pages")}
|
||||||
|
</Text>
|
||||||
|
<Text fz="xs" c="dimmed" style={{ whiteSpace: "nowrap" }}>
|
||||||
|
· {item.importedSpaces}/{item.totalSpaces || "?"} {t("spaces")}
|
||||||
|
</Text>
|
||||||
|
<Text fz="xs" c="dimmed" style={{ whiteSpace: "nowrap" }}>
|
||||||
|
· {item.importedUsers}/{item.totalUsers || "?"} {t("users")}
|
||||||
|
</Text>
|
||||||
|
</Group>
|
||||||
|
</Stack>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function ImportStatsModal({
|
||||||
|
item,
|
||||||
|
onClose,
|
||||||
|
}: {
|
||||||
|
item: ConfluenceImportHistoryItem | null;
|
||||||
|
onClose: () => void;
|
||||||
|
}) {
|
||||||
|
const { t } = useTranslation();
|
||||||
|
|
||||||
|
const stats = item
|
||||||
|
? [
|
||||||
|
{
|
||||||
|
label: t("Spaces"),
|
||||||
|
imported: item.importedSpaces,
|
||||||
|
total: item.totalSpaces,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
label: t("Pages"),
|
||||||
|
imported: item.importedPages,
|
||||||
|
total: item.totalPages,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
label: t("Users"),
|
||||||
|
imported: item.importedUsers,
|
||||||
|
total: item.totalUsers,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
label: t("Groups"),
|
||||||
|
imported: item.importedGroups,
|
||||||
|
total: item.totalGroups,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
label: t("Attachments"),
|
||||||
|
imported: item.importedAttachments,
|
||||||
|
total: item.totalAttachments,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
label: t("Labels"),
|
||||||
|
imported: item.importedLabels,
|
||||||
|
total: item.totalLabels,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
label: t("Restricted pages"),
|
||||||
|
imported: item.importedRestrictedPages,
|
||||||
|
total: item.totalRestrictedPages,
|
||||||
|
},
|
||||||
|
]
|
||||||
|
: [];
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Modal
|
||||||
|
opened={!!item}
|
||||||
|
onClose={onClose}
|
||||||
|
title={t("Import details")}
|
||||||
|
size="md"
|
||||||
|
>
|
||||||
|
{item && (
|
||||||
|
<Stack gap="sm">
|
||||||
|
<div>
|
||||||
|
<Text fz="sm" c="dimmed">
|
||||||
|
{t("Confluence site")}
|
||||||
|
</Text>
|
||||||
|
<Text fz="sm" fw={500} lineClamp={1}>
|
||||||
|
{item.siteUrl}
|
||||||
|
</Text>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<Text fz="sm" c="dimmed">
|
||||||
|
{t("Started at")}
|
||||||
|
</Text>
|
||||||
|
<Text fz="sm">{formattedDate(new Date(item.createdAt))}</Text>
|
||||||
|
</div>
|
||||||
|
<Table verticalSpacing="xs" fz="sm">
|
||||||
|
<Table.Tbody>
|
||||||
|
{stats.map((stat) => (
|
||||||
|
<Table.Tr key={stat.label}>
|
||||||
|
<Table.Td>
|
||||||
|
<Text fz="sm">{stat.label}</Text>
|
||||||
|
</Table.Td>
|
||||||
|
<Table.Td>
|
||||||
|
<Text fz="sm" ta="right">
|
||||||
|
{stat.imported} / {stat.total}
|
||||||
|
</Text>
|
||||||
|
</Table.Td>
|
||||||
|
</Table.Tr>
|
||||||
|
))}
|
||||||
|
</Table.Tbody>
|
||||||
|
</Table>
|
||||||
|
</Stack>
|
||||||
|
)}
|
||||||
|
</Modal>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function TableSkeleton() {
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
{Array.from({ length: 3 }).map((_, i) => (
|
||||||
|
<Table.Tr key={i}>
|
||||||
|
<Table.Td>
|
||||||
|
<Skeleton height={14} width={120} />
|
||||||
|
</Table.Td>
|
||||||
|
<Table.Td>
|
||||||
|
<Skeleton height={14} width={180} />
|
||||||
|
</Table.Td>
|
||||||
|
<Table.Td>
|
||||||
|
<Skeleton height={14} width={80} />
|
||||||
|
</Table.Td>
|
||||||
|
<Table.Td>
|
||||||
|
<Skeleton height={14} width={140} />
|
||||||
|
</Table.Td>
|
||||||
|
<Table.Td>
|
||||||
|
<Skeleton height={14} width={120} />
|
||||||
|
</Table.Td>
|
||||||
|
<Table.Td>
|
||||||
|
<Skeleton height={14} width={120} />
|
||||||
|
</Table.Td>
|
||||||
|
</Table.Tr>
|
||||||
|
))}
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function ConfluenceImportHistory() {
|
||||||
|
const { t } = useTranslation();
|
||||||
|
const { data, isLoading } = useConfluenceImportsQuery();
|
||||||
|
const [selectedItem, setSelectedItem] =
|
||||||
|
useState<ConfluenceImportHistoryItem | null>(null);
|
||||||
|
|
||||||
|
const items = useMemo(() => data?.items ?? [], [data]);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Table.ScrollContainer minWidth={720}>
|
||||||
|
<Table verticalSpacing="xs" highlightOnHover>
|
||||||
|
<Table.Thead>
|
||||||
|
<Table.Tr>
|
||||||
|
<Table.Th>{t("Status")}</Table.Th>
|
||||||
|
<Table.Th>{t("Site")}</Table.Th>
|
||||||
|
<Table.Th>{t("Phase")}</Table.Th>
|
||||||
|
<Table.Th>{t("Progress")}</Table.Th>
|
||||||
|
<Table.Th>{t("Started by")}</Table.Th>
|
||||||
|
<Table.Th>{t("Started at")}</Table.Th>
|
||||||
|
</Table.Tr>
|
||||||
|
</Table.Thead>
|
||||||
|
|
||||||
|
<Table.Tbody>
|
||||||
|
{isLoading ? (
|
||||||
|
<TableSkeleton />
|
||||||
|
) : items.length > 0 ? (
|
||||||
|
items.map((item) => (
|
||||||
|
<Table.Tr
|
||||||
|
key={item.fileTaskId}
|
||||||
|
onClick={() => setSelectedItem(item)}
|
||||||
|
style={{ cursor: "pointer" }}
|
||||||
|
>
|
||||||
|
<Table.Td>
|
||||||
|
{statusBadge(item.status, item.cancelled, t)}
|
||||||
|
{item.status === "failed" && item.errorMessage && (
|
||||||
|
<Tooltip label={item.errorMessage} multiline w={320}>
|
||||||
|
<Text fz="xs" c="red" lineClamp={1} maw={180}>
|
||||||
|
{item.errorMessage}
|
||||||
|
</Text>
|
||||||
|
</Tooltip>
|
||||||
|
)}
|
||||||
|
</Table.Td>
|
||||||
|
<Table.Td>
|
||||||
|
<Text fz="sm" lineClamp={1} maw={240}>
|
||||||
|
{item.siteUrl}
|
||||||
|
</Text>
|
||||||
|
</Table.Td>
|
||||||
|
<Table.Td>
|
||||||
|
<Text fz="sm">{phaseLabel(item.currentPhase, t)}</Text>
|
||||||
|
</Table.Td>
|
||||||
|
<Table.Td>
|
||||||
|
<ProgressCell item={item} />
|
||||||
|
</Table.Td>
|
||||||
|
<Table.Td>
|
||||||
|
{item.creatorName ? (
|
||||||
|
<Group gap="sm" wrap="nowrap">
|
||||||
|
<CustomAvatar
|
||||||
|
avatarUrl={item.creatorAvatarUrl}
|
||||||
|
name={item.creatorName}
|
||||||
|
size={24}
|
||||||
|
/>
|
||||||
|
<Text fz="sm" lineClamp={1}>
|
||||||
|
{item.creatorName}
|
||||||
|
</Text>
|
||||||
|
</Group>
|
||||||
|
) : (
|
||||||
|
<Text fz="sm" c="dimmed">
|
||||||
|
—
|
||||||
|
</Text>
|
||||||
|
)}
|
||||||
|
</Table.Td>
|
||||||
|
<Table.Td>
|
||||||
|
<Text fz="sm" style={{ whiteSpace: "nowrap" }}>
|
||||||
|
{formattedDate(new Date(item.createdAt))}
|
||||||
|
</Text>
|
||||||
|
</Table.Td>
|
||||||
|
</Table.Tr>
|
||||||
|
))
|
||||||
|
) : (
|
||||||
|
<NoTableResults colSpan={6} />
|
||||||
|
)}
|
||||||
|
</Table.Tbody>
|
||||||
|
</Table>
|
||||||
|
|
||||||
|
<ImportStatsModal
|
||||||
|
item={selectedItem}
|
||||||
|
onClose={() => setSelectedItem(null)}
|
||||||
|
/>
|
||||||
|
</Table.ScrollContainer>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,445 @@
|
|||||||
|
import React, { useEffect, useMemo, useState } from "react";
|
||||||
|
import {
|
||||||
|
Alert,
|
||||||
|
Button,
|
||||||
|
Checkbox,
|
||||||
|
Group,
|
||||||
|
Modal,
|
||||||
|
PasswordInput,
|
||||||
|
ScrollArea,
|
||||||
|
SegmentedControl,
|
||||||
|
Stack,
|
||||||
|
Stepper,
|
||||||
|
Text,
|
||||||
|
TextInput,
|
||||||
|
} from "@mantine/core";
|
||||||
|
import {
|
||||||
|
IconAlertCircle,
|
||||||
|
IconCheck,
|
||||||
|
IconCloudCheck,
|
||||||
|
IconPlug,
|
||||||
|
} from "@tabler/icons-react";
|
||||||
|
import { useTranslation } from "react-i18next";
|
||||||
|
import { useForm } from "@mantine/form";
|
||||||
|
import { notifications } from "@mantine/notifications";
|
||||||
|
import { useQueryClient } from "@tanstack/react-query";
|
||||||
|
import {
|
||||||
|
listConfluenceSpaces,
|
||||||
|
startConfluenceImport,
|
||||||
|
testConfluenceConnection,
|
||||||
|
} from "@/ee/confluence-import/services/confluence-import-service";
|
||||||
|
import {
|
||||||
|
ConfluenceAuthType,
|
||||||
|
ConfluenceCredentials,
|
||||||
|
ConfluenceSpaceSummary,
|
||||||
|
} from "@/ee/confluence-import/types/confluence-import.types";
|
||||||
|
import { confluenceImportsQueryKey } from "@/ee/confluence-import/queries/confluence-import-queries";
|
||||||
|
|
||||||
|
type ConfluenceEditionChoice = "cloud" | "server";
|
||||||
|
|
||||||
|
type CredentialsFormValues = {
|
||||||
|
edition: ConfluenceEditionChoice;
|
||||||
|
authType: ConfluenceAuthType;
|
||||||
|
siteUrl: string;
|
||||||
|
email: string;
|
||||||
|
token: string;
|
||||||
|
username: string;
|
||||||
|
password: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
type Props = {
|
||||||
|
opened: boolean;
|
||||||
|
onClose: () => void;
|
||||||
|
};
|
||||||
|
|
||||||
|
export default function ConfluenceImportModal({ opened, onClose }: Props) {
|
||||||
|
const { t } = useTranslation();
|
||||||
|
const queryClient = useQueryClient();
|
||||||
|
const [active, setActive] = useState(0);
|
||||||
|
const [loading, setLoading] = useState(false);
|
||||||
|
const [error, setError] = useState<string | null>(null);
|
||||||
|
const [spaces, setSpaces] = useState<ConfluenceSpaceSummary[]>([]);
|
||||||
|
const [selectedKeys, setSelectedKeys] = useState<string[]>([]);
|
||||||
|
const [importAll, setImportAll] = useState(true);
|
||||||
|
|
||||||
|
const form = useForm<CredentialsFormValues>({
|
||||||
|
initialValues: {
|
||||||
|
edition: "server",
|
||||||
|
authType: "pat",
|
||||||
|
siteUrl: "",
|
||||||
|
email: "",
|
||||||
|
token: "",
|
||||||
|
username: "",
|
||||||
|
password: "",
|
||||||
|
},
|
||||||
|
validate: {
|
||||||
|
siteUrl: (value) =>
|
||||||
|
!value?.trim()
|
||||||
|
? t("Site URL is required")
|
||||||
|
: !/^https?:\/\//i.test(value.trim())
|
||||||
|
? t("Site URL must start with http:// or https://")
|
||||||
|
: null,
|
||||||
|
email: (value, values) =>
|
||||||
|
values.edition === "cloud" && !value?.trim()
|
||||||
|
? t("Email is required")
|
||||||
|
: null,
|
||||||
|
token: (value, values) =>
|
||||||
|
(values.authType === "cloud_token" || values.authType === "pat") &&
|
||||||
|
!value?.trim()
|
||||||
|
? t("API token is required")
|
||||||
|
: null,
|
||||||
|
username: (value, values) =>
|
||||||
|
values.authType === "basic" && !value?.trim()
|
||||||
|
? t("Username is required")
|
||||||
|
: null,
|
||||||
|
password: (value, values) =>
|
||||||
|
values.authType === "basic" && !value?.trim()
|
||||||
|
? t("Password is required")
|
||||||
|
: null,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!opened) {
|
||||||
|
setActive(0);
|
||||||
|
setError(null);
|
||||||
|
setSpaces([]);
|
||||||
|
setSelectedKeys([]);
|
||||||
|
setImportAll(true);
|
||||||
|
setLoading(false);
|
||||||
|
form.reset();
|
||||||
|
}
|
||||||
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||||
|
}, [opened]);
|
||||||
|
|
||||||
|
const credentials: ConfluenceCredentials = useMemo(() => {
|
||||||
|
const values = form.values;
|
||||||
|
return {
|
||||||
|
siteUrl: values.siteUrl.trim().replace(/\/+$/, ""),
|
||||||
|
authType: values.authType,
|
||||||
|
email: values.email?.trim() || undefined,
|
||||||
|
token: values.token?.trim() || undefined,
|
||||||
|
username: values.username?.trim() || undefined,
|
||||||
|
password: values.password || undefined,
|
||||||
|
};
|
||||||
|
}, [form.values]);
|
||||||
|
|
||||||
|
const handleEditionChange = (edition: ConfluenceEditionChoice) => {
|
||||||
|
form.setFieldValue("edition", edition);
|
||||||
|
if (edition === "cloud") {
|
||||||
|
form.setFieldValue("authType", "cloud_token");
|
||||||
|
} else if (form.values.authType === "cloud_token") {
|
||||||
|
form.setFieldValue("authType", "pat");
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleNextFromCredentials = async () => {
|
||||||
|
if ((await form.validate()).hasErrors) return;
|
||||||
|
setLoading(true);
|
||||||
|
setError(null);
|
||||||
|
try {
|
||||||
|
const test = await testConfluenceConnection(credentials);
|
||||||
|
if (!test.success) {
|
||||||
|
setError(test.error || t("Connection failed"));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const list = await listConfluenceSpaces(credentials);
|
||||||
|
if (!list.success || !list.spaces) {
|
||||||
|
setError(list.error || t("Failed to load spaces"));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
setSpaces(list.spaces);
|
||||||
|
setSelectedKeys(list.spaces.map((s) => s.key));
|
||||||
|
setImportAll(true);
|
||||||
|
setActive(1);
|
||||||
|
} catch (err: any) {
|
||||||
|
setError(
|
||||||
|
err?.response?.data?.message || err?.message || t("Unexpected error"),
|
||||||
|
);
|
||||||
|
} finally {
|
||||||
|
setLoading(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const toggleSpace = (key: string, checked: boolean) => {
|
||||||
|
setSelectedKeys((prev) =>
|
||||||
|
checked
|
||||||
|
? Array.from(new Set([...prev, key]))
|
||||||
|
: prev.filter((k) => k !== key),
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
const toggleAll = (checked: boolean) => {
|
||||||
|
setImportAll(checked);
|
||||||
|
setSelectedKeys(checked ? spaces.map((s) => s.key) : []);
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleStartImport = async () => {
|
||||||
|
const spaceKeys = importAll ? [] : selectedKeys;
|
||||||
|
if (!importAll && spaceKeys.length === 0) {
|
||||||
|
setError(t("Select at least one space to import"));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
setLoading(true);
|
||||||
|
setError(null);
|
||||||
|
try {
|
||||||
|
const result = await startConfluenceImport({
|
||||||
|
...credentials,
|
||||||
|
spaceKeys,
|
||||||
|
});
|
||||||
|
if (!result.success || !result.fileTaskId) {
|
||||||
|
setError(result.error || t("Failed to start import"));
|
||||||
|
setLoading(false);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
await queryClient.invalidateQueries({
|
||||||
|
queryKey: confluenceImportsQueryKey,
|
||||||
|
});
|
||||||
|
|
||||||
|
notifications.show({
|
||||||
|
title: t("Confluence import started"),
|
||||||
|
message: t("Track progress below. This runs in the background."),
|
||||||
|
color: "blue",
|
||||||
|
icon: <IconCheck size={18} />,
|
||||||
|
autoClose: 4000,
|
||||||
|
});
|
||||||
|
|
||||||
|
onClose();
|
||||||
|
} catch (err: any) {
|
||||||
|
setError(
|
||||||
|
err?.response?.data?.message || err?.message || t("Unexpected error"),
|
||||||
|
);
|
||||||
|
setLoading(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleCancelFlow = async () => {
|
||||||
|
onClose();
|
||||||
|
};
|
||||||
|
|
||||||
|
const editionSegment = (
|
||||||
|
<SegmentedControl
|
||||||
|
value={form.values.edition}
|
||||||
|
onChange={(val) => handleEditionChange(val as ConfluenceEditionChoice)}
|
||||||
|
data={[
|
||||||
|
{ value: "server", label: t("Data Center / Server") },
|
||||||
|
{ value: "cloud", label: t("Cloud") },
|
||||||
|
]}
|
||||||
|
fullWidth
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
|
||||||
|
const authTypeSegment = form.values.edition === "server" && (
|
||||||
|
<SegmentedControl
|
||||||
|
value={form.values.authType}
|
||||||
|
onChange={(val) =>
|
||||||
|
form.setFieldValue("authType", val as ConfluenceAuthType)
|
||||||
|
}
|
||||||
|
data={[
|
||||||
|
{ value: "pat", label: t("Personal Access Token") },
|
||||||
|
{ value: "basic", label: t("Username + password") },
|
||||||
|
]}
|
||||||
|
fullWidth
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
|
||||||
|
const selectedCount = importAll ? spaces.length : selectedKeys.length;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Modal
|
||||||
|
opened={opened}
|
||||||
|
onClose={onClose}
|
||||||
|
title={t("Import from Confluence")}
|
||||||
|
size={720}
|
||||||
|
centered
|
||||||
|
closeOnClickOutside={!loading}
|
||||||
|
closeOnEscape={!loading}
|
||||||
|
>
|
||||||
|
<Stepper active={active} size="sm" mb="md" allowNextStepsSelect={false}>
|
||||||
|
<Stepper.Step
|
||||||
|
label={t("Connect")}
|
||||||
|
description={t("Credentials")}
|
||||||
|
icon={<IconPlug size={18} />}
|
||||||
|
/>
|
||||||
|
<Stepper.Step
|
||||||
|
label={t("Select spaces")}
|
||||||
|
description={t("Choose what to import")}
|
||||||
|
icon={<IconCloudCheck size={18} />}
|
||||||
|
/>
|
||||||
|
</Stepper>
|
||||||
|
|
||||||
|
{active === 0 && (
|
||||||
|
<Stack>
|
||||||
|
<Text size="sm" c="dimmed">
|
||||||
|
{t(
|
||||||
|
"Enter your Confluence URL and credentials. We'll validate the connection before continuing.",
|
||||||
|
)}
|
||||||
|
</Text>
|
||||||
|
{editionSegment}
|
||||||
|
{authTypeSegment}
|
||||||
|
<TextInput
|
||||||
|
label={t("Site URL")}
|
||||||
|
placeholder={
|
||||||
|
form.values.edition === "cloud"
|
||||||
|
? "https://your-site.atlassian.net/wiki"
|
||||||
|
: "https://confluence.example.com"
|
||||||
|
}
|
||||||
|
required
|
||||||
|
{...form.getInputProps("siteUrl")}
|
||||||
|
/>
|
||||||
|
|
||||||
|
{form.values.edition === "cloud" && (
|
||||||
|
<>
|
||||||
|
<TextInput
|
||||||
|
label={t("Email")}
|
||||||
|
placeholder="you@company.com"
|
||||||
|
required
|
||||||
|
{...form.getInputProps("email")}
|
||||||
|
/>
|
||||||
|
<PasswordInput
|
||||||
|
label={t("API token")}
|
||||||
|
description={t(
|
||||||
|
"Create at id.atlassian.com/manage-profile/security/api-tokens",
|
||||||
|
)}
|
||||||
|
required
|
||||||
|
{...form.getInputProps("token")}
|
||||||
|
/>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{form.values.edition === "server" &&
|
||||||
|
form.values.authType === "pat" && (
|
||||||
|
<>
|
||||||
|
<TextInput
|
||||||
|
label={t("Email")}
|
||||||
|
placeholder="you@company.com"
|
||||||
|
{...form.getInputProps("email")}
|
||||||
|
/>
|
||||||
|
<PasswordInput
|
||||||
|
label={t("Personal Access Token")}
|
||||||
|
required
|
||||||
|
{...form.getInputProps("token")}
|
||||||
|
/>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{form.values.edition === "server" &&
|
||||||
|
form.values.authType === "basic" && (
|
||||||
|
<>
|
||||||
|
<TextInput
|
||||||
|
label={t("Username")}
|
||||||
|
required
|
||||||
|
{...form.getInputProps("username")}
|
||||||
|
/>
|
||||||
|
<PasswordInput
|
||||||
|
label={t("Password")}
|
||||||
|
required
|
||||||
|
{...form.getInputProps("password")}
|
||||||
|
/>
|
||||||
|
<TextInput
|
||||||
|
label={t("Email (optional)")}
|
||||||
|
placeholder="you@company.com"
|
||||||
|
{...form.getInputProps("email")}
|
||||||
|
/>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{error && (
|
||||||
|
<Alert color="red" icon={<IconAlertCircle size={18} />}>
|
||||||
|
{error}
|
||||||
|
</Alert>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<Group justify="flex-end">
|
||||||
|
<Button
|
||||||
|
variant="default"
|
||||||
|
onClick={handleCancelFlow}
|
||||||
|
disabled={loading}
|
||||||
|
>
|
||||||
|
{t("Cancel")}
|
||||||
|
</Button>
|
||||||
|
<Button onClick={handleNextFromCredentials} loading={loading}>
|
||||||
|
{t("Test & continue")}
|
||||||
|
</Button>
|
||||||
|
</Group>
|
||||||
|
</Stack>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{active === 1 && (
|
||||||
|
<Stack>
|
||||||
|
<Text size="sm" c="dimmed">
|
||||||
|
{t(
|
||||||
|
"Pages, comments, page labels, users, groups, spaces and permissions will be imported.",
|
||||||
|
)}
|
||||||
|
</Text>
|
||||||
|
|
||||||
|
<Checkbox
|
||||||
|
label={t("Import all spaces ({{count}})", {
|
||||||
|
count: spaces.length,
|
||||||
|
})}
|
||||||
|
checked={importAll}
|
||||||
|
onChange={(e) => toggleAll(e.currentTarget.checked)}
|
||||||
|
/>
|
||||||
|
|
||||||
|
<ScrollArea h={320} type="auto" offsetScrollbars>
|
||||||
|
<Stack gap="xs">
|
||||||
|
{spaces.map((space) => (
|
||||||
|
<Checkbox
|
||||||
|
key={space.id}
|
||||||
|
label={
|
||||||
|
<Group gap={6} wrap="nowrap">
|
||||||
|
<Text fw={500}>{space.name}</Text>
|
||||||
|
<Text size="xs" c="dimmed">
|
||||||
|
({space.key})
|
||||||
|
</Text>
|
||||||
|
</Group>
|
||||||
|
}
|
||||||
|
checked={importAll || selectedKeys.includes(space.key)}
|
||||||
|
disabled={importAll}
|
||||||
|
onChange={(e) =>
|
||||||
|
toggleSpace(space.key, e.currentTarget.checked)
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
))}
|
||||||
|
{spaces.length === 0 && (
|
||||||
|
<Text c="dimmed" ta="center" py="lg">
|
||||||
|
{t("No spaces found for this account.")}
|
||||||
|
</Text>
|
||||||
|
)}
|
||||||
|
</Stack>
|
||||||
|
</ScrollArea>
|
||||||
|
|
||||||
|
{error && (
|
||||||
|
<Alert color="red" icon={<IconAlertCircle size={18} />}>
|
||||||
|
{error}
|
||||||
|
</Alert>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<Group justify="space-between">
|
||||||
|
<Text size="sm" c="dimmed">
|
||||||
|
{t("{{count}} selected", { count: selectedCount })}
|
||||||
|
</Text>
|
||||||
|
<Group>
|
||||||
|
<Button
|
||||||
|
variant="default"
|
||||||
|
onClick={() => setActive(0)}
|
||||||
|
disabled={loading}
|
||||||
|
>
|
||||||
|
{t("Back")}
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
onClick={handleStartImport}
|
||||||
|
loading={loading}
|
||||||
|
disabled={!importAll && selectedKeys.length === 0}
|
||||||
|
>
|
||||||
|
{t("Start import")}
|
||||||
|
</Button>
|
||||||
|
</Group>
|
||||||
|
</Group>
|
||||||
|
</Stack>
|
||||||
|
)}
|
||||||
|
</Modal>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,67 @@
|
|||||||
|
import { Helmet } from "react-helmet-async";
|
||||||
|
import { useTranslation } from "react-i18next";
|
||||||
|
import {
|
||||||
|
Button,
|
||||||
|
Divider,
|
||||||
|
Group,
|
||||||
|
Paper,
|
||||||
|
Stack,
|
||||||
|
Text,
|
||||||
|
Tooltip,
|
||||||
|
} from "@mantine/core";
|
||||||
|
import { useDisclosure } from "@mantine/hooks";
|
||||||
|
import SettingsTitle from "@/components/settings/settings-title";
|
||||||
|
import { ConfluenceIcon } from "@/components/icons/confluence-icon";
|
||||||
|
import ConfluenceImportModal from "@/ee/confluence-import/components/confluence-import-modal";
|
||||||
|
import ConfluenceImportHistory from "@/ee/confluence-import/components/confluence-import-history";
|
||||||
|
import { getAppName } from "@/lib/config";
|
||||||
|
import { useHasFeature } from "@/ee/hooks/use-feature";
|
||||||
|
import { Feature } from "@/ee/features";
|
||||||
|
import { useUpgradeLabel } from "@/ee/hooks/use-upgrade-label";
|
||||||
|
|
||||||
|
export default function ConfluenceImportPage() {
|
||||||
|
const { t } = useTranslation();
|
||||||
|
const [opened, { open, close }] = useDisclosure(false);
|
||||||
|
const hasConfluenceImport = useHasFeature(Feature.CONFLUENCE_API_IMPORT);
|
||||||
|
const upgradeLabel = useUpgradeLabel();
|
||||||
|
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<Helmet>
|
||||||
|
<title>
|
||||||
|
{t("Import from Confluence")} - {getAppName()}
|
||||||
|
</title>
|
||||||
|
</Helmet>
|
||||||
|
|
||||||
|
<SettingsTitle title={t("Import from Confluence")} />
|
||||||
|
|
||||||
|
<Paper withBorder p="lg" radius="md" mb="lg">
|
||||||
|
<Group align="flex-start" justify="space-between" wrap="nowrap">
|
||||||
|
<Group align="flex-start" wrap="nowrap">
|
||||||
|
<ConfluenceIcon size={32} />
|
||||||
|
<Stack gap={4}>
|
||||||
|
<Text fw={600}>{t("Confluence API import")}</Text>
|
||||||
|
<Text size="sm" c="dimmed" maw={560}>
|
||||||
|
{t(
|
||||||
|
"Connect to Confluence Cloud or Data Center to import spaces, pages, attachments, comments, users, groups and permissions directly via the API.",
|
||||||
|
)}
|
||||||
|
</Text>
|
||||||
|
</Stack>
|
||||||
|
</Group>
|
||||||
|
|
||||||
|
<Tooltip label={upgradeLabel} disabled={hasConfluenceImport}>
|
||||||
|
<Button onClick={open} disabled={!hasConfluenceImport}>
|
||||||
|
{t("Start import")}
|
||||||
|
</Button>
|
||||||
|
</Tooltip>
|
||||||
|
</Group>
|
||||||
|
</Paper>
|
||||||
|
|
||||||
|
<Divider my="md" label={t("Import history")} labelPosition="left" />
|
||||||
|
|
||||||
|
<ConfluenceImportHistory />
|
||||||
|
|
||||||
|
<ConfluenceImportModal opened={opened} onClose={close} />
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
import { useQuery } from "@tanstack/react-query";
|
||||||
|
import { listConfluenceImports } from "@/ee/confluence-import/services/confluence-import-service";
|
||||||
|
|
||||||
|
export const confluenceImportsQueryKey = ["confluence-imports"] as const;
|
||||||
|
|
||||||
|
export function useConfluenceImportsQuery() {
|
||||||
|
return useQuery({
|
||||||
|
queryKey: confluenceImportsQueryKey,
|
||||||
|
queryFn: listConfluenceImports,
|
||||||
|
refetchInterval: (query) => {
|
||||||
|
const hasRunning = query.state.data?.items?.some(
|
||||||
|
(i) => i.status === "processing",
|
||||||
|
);
|
||||||
|
return hasRunning ? 3000 : false;
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -0,0 +1,64 @@
|
|||||||
|
import api from "@/lib/api-client";
|
||||||
|
import {
|
||||||
|
ConfluenceCredentials,
|
||||||
|
ImportStatusResponse,
|
||||||
|
ListImportsResponse,
|
||||||
|
ListSpacesResponse,
|
||||||
|
StartImportResponse,
|
||||||
|
TestConnectionResponse,
|
||||||
|
} from "@/ee/confluence-import/types/confluence-import.types";
|
||||||
|
|
||||||
|
export async function testConfluenceConnection(
|
||||||
|
data: ConfluenceCredentials,
|
||||||
|
): Promise<TestConnectionResponse> {
|
||||||
|
const req = await api.post<TestConnectionResponse>(
|
||||||
|
"/confluence-import/test-connection",
|
||||||
|
data,
|
||||||
|
);
|
||||||
|
return req.data;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function listConfluenceSpaces(
|
||||||
|
data: ConfluenceCredentials,
|
||||||
|
): Promise<ListSpacesResponse> {
|
||||||
|
const req = await api.post<ListSpacesResponse>(
|
||||||
|
"/confluence-import/spaces",
|
||||||
|
data,
|
||||||
|
);
|
||||||
|
return req.data;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function startConfluenceImport(
|
||||||
|
data: ConfluenceCredentials & { spaceKeys?: string[] },
|
||||||
|
): Promise<StartImportResponse> {
|
||||||
|
const req = await api.post<StartImportResponse>(
|
||||||
|
"/confluence-import/start",
|
||||||
|
data,
|
||||||
|
);
|
||||||
|
return req.data;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function getConfluenceImportStatus(
|
||||||
|
fileTaskId: string,
|
||||||
|
): Promise<ImportStatusResponse> {
|
||||||
|
const req = await api.post<ImportStatusResponse>(
|
||||||
|
"/confluence-import/status",
|
||||||
|
{ fileTaskId },
|
||||||
|
);
|
||||||
|
return req.data;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function listConfluenceImports(): Promise<ListImportsResponse> {
|
||||||
|
const req = await api.post<ListImportsResponse>("/confluence-import/history");
|
||||||
|
return req.data;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function cancelConfluenceImport(
|
||||||
|
fileTaskId: string,
|
||||||
|
): Promise<{ success: boolean }> {
|
||||||
|
const req = await api.post<{ success: boolean }>(
|
||||||
|
"/confluence-import/cancel",
|
||||||
|
{ fileTaskId },
|
||||||
|
);
|
||||||
|
return req.data;
|
||||||
|
}
|
||||||
@@ -0,0 +1,92 @@
|
|||||||
|
export type ConfluenceAuthType = "cloud_token" | "pat" | "basic";
|
||||||
|
|
||||||
|
export type ConfluenceCredentials = {
|
||||||
|
siteUrl: string;
|
||||||
|
authType: ConfluenceAuthType;
|
||||||
|
email?: string;
|
||||||
|
token?: string;
|
||||||
|
username?: string;
|
||||||
|
password?: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type ConfluenceSpaceSummary = {
|
||||||
|
id: string;
|
||||||
|
key: string;
|
||||||
|
name: string;
|
||||||
|
type?: string;
|
||||||
|
status?: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type TestConnectionResponse = {
|
||||||
|
success: boolean;
|
||||||
|
edition?: string;
|
||||||
|
spaceCount?: number;
|
||||||
|
error?: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type ListSpacesResponse = {
|
||||||
|
success: boolean;
|
||||||
|
spaces?: ConfluenceSpaceSummary[];
|
||||||
|
error?: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type StartImportResponse = {
|
||||||
|
success: boolean;
|
||||||
|
fileTaskId?: string;
|
||||||
|
error?: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type ConfluenceImportStatus = "processing" | "success" | "failed";
|
||||||
|
|
||||||
|
export type ImportStatusResponse = {
|
||||||
|
fileTaskId?: string;
|
||||||
|
status?: ConfluenceImportStatus;
|
||||||
|
errorMessage?: string | null;
|
||||||
|
currentPhase?: string | null;
|
||||||
|
totalSpaces?: number;
|
||||||
|
importedSpaces?: number;
|
||||||
|
totalPages?: number;
|
||||||
|
importedPages?: number;
|
||||||
|
totalUsers?: number;
|
||||||
|
importedUsers?: number;
|
||||||
|
totalGroups?: number;
|
||||||
|
importedGroups?: number;
|
||||||
|
totalRestrictedPages?: number;
|
||||||
|
importedRestrictedPages?: number;
|
||||||
|
createdAt?: string;
|
||||||
|
updatedAt?: string;
|
||||||
|
error?: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type ConfluenceImportHistoryItem = {
|
||||||
|
fileTaskId: string;
|
||||||
|
siteUrl: string;
|
||||||
|
status: ConfluenceImportStatus;
|
||||||
|
errorMessage: string | null;
|
||||||
|
currentPhase: string | null;
|
||||||
|
totalSpaces: number;
|
||||||
|
importedSpaces: number;
|
||||||
|
totalPages: number;
|
||||||
|
importedPages: number;
|
||||||
|
totalUsers: number;
|
||||||
|
importedUsers: number;
|
||||||
|
totalGroups: number;
|
||||||
|
importedGroups: number;
|
||||||
|
totalAttachments: number;
|
||||||
|
importedAttachments: number;
|
||||||
|
totalLabels: number;
|
||||||
|
importedLabels: number;
|
||||||
|
totalRestrictedPages: number;
|
||||||
|
importedRestrictedPages: number;
|
||||||
|
cancelled: boolean;
|
||||||
|
spaceKeys: string[];
|
||||||
|
createdAt: string;
|
||||||
|
updatedAt: string;
|
||||||
|
creatorId: string | null;
|
||||||
|
creatorName: string | null;
|
||||||
|
creatorAvatarUrl: string | null;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type ListImportsResponse = {
|
||||||
|
items: ConfluenceImportHistoryItem[];
|
||||||
|
};
|
||||||
@@ -7,6 +7,7 @@ export const Feature = {
|
|||||||
PAGE_PERMISSIONS: 'page:permissions',
|
PAGE_PERMISSIONS: 'page:permissions',
|
||||||
AI: 'ai',
|
AI: 'ai',
|
||||||
CONFLUENCE_IMPORT: 'import:confluence',
|
CONFLUENCE_IMPORT: 'import:confluence',
|
||||||
|
CONFLUENCE_API_IMPORT: 'import:confluence-api',
|
||||||
DOCX_IMPORT: 'import:docx',
|
DOCX_IMPORT: 'import:docx',
|
||||||
PDF_IMPORT: 'import:pdf',
|
PDF_IMPORT: 'import:pdf',
|
||||||
ATTACHMENT_INDEXING: 'attachment:indexing',
|
ATTACHMENT_INDEXING: 'attachment:indexing',
|
||||||
@@ -22,5 +23,4 @@ export const Feature = {
|
|||||||
PERSONAL_SPACES: 'spaces:personal',
|
PERSONAL_SPACES: 'spaces:personal',
|
||||||
DOCX_EXPORT: 'export:docx',
|
DOCX_EXPORT: 'export:docx',
|
||||||
BASES: 'bases',
|
BASES: 'bases',
|
||||||
INTEGRATIONS: 'integrations',
|
|
||||||
} as const;
|
} as const;
|
||||||
|
|||||||
@@ -53,7 +53,14 @@ export function PagePermissionItem({
|
|||||||
{isCurrentUser && <Text span c="dimmed"> ({t("You")})</Text>}
|
{isCurrentUser && <Text span c="dimmed"> ({t("You")})</Text>}
|
||||||
</AutoTooltipText>
|
</AutoTooltipText>
|
||||||
<AutoTooltipText fz="xs" c="dimmed">
|
<AutoTooltipText fz="xs" c="dimmed">
|
||||||
{member.type === "user" ? member.email : formatMemberCount(member.memberCount, t)}
|
{member.type === "user"
|
||||||
|
? member.email
|
||||||
|
: member.isDefault
|
||||||
|
? // Page access still requires space membership, so the
|
||||||
|
// workspace-wide member count would overstate who can
|
||||||
|
// actually see the page.
|
||||||
|
t("Everyone with access to this space")
|
||||||
|
: formatMemberCount(member.memberCount, t)}
|
||||||
</AutoTooltipText>
|
</AutoTooltipText>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -166,6 +166,18 @@ export default function useAuth() {
|
|||||||
const handleLogout = async () => {
|
const handleLogout = async () => {
|
||||||
setCurrentUser(RESET);
|
setCurrentUser(RESET);
|
||||||
await logout();
|
await logout();
|
||||||
|
|
||||||
|
try {
|
||||||
|
if (typeof indexedDB?.databases === "function") {
|
||||||
|
const dbs = await indexedDB.databases();
|
||||||
|
dbs
|
||||||
|
.filter((db) => db.name?.startsWith("page."))
|
||||||
|
.forEach((db) => indexedDB.deleteDatabase(db.name!));
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
//
|
||||||
|
}
|
||||||
|
|
||||||
window.location.replace(`${APP_ROUTE.AUTH.LOGIN}?logout=1`);
|
window.location.replace(`${APP_ROUTE.AUTH.LOGIN}?logout=1`);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@@ -11,6 +11,7 @@ import {
|
|||||||
} from "@/features/comment/atoms/comment-atom";
|
} from "@/features/comment/atoms/comment-atom";
|
||||||
import CommentEditor from "@/features/comment/components/comment-editor";
|
import CommentEditor from "@/features/comment/components/comment-editor";
|
||||||
import CommentActions from "@/features/comment/components/comment-actions";
|
import CommentActions from "@/features/comment/components/comment-actions";
|
||||||
|
import { CommentErrorBoundary } from "@/features/comment/components/comment-error-boundary";
|
||||||
import { currentUserAtom } from "@/features/user/atoms/current-user-atom";
|
import { currentUserAtom } from "@/features/user/atoms/current-user-atom";
|
||||||
import { useCreateCommentMutation } from "@/features/comment/queries/comment-query";
|
import { useCreateCommentMutation } from "@/features/comment/queries/comment-query";
|
||||||
import { asideStateAtom } from "@/components/layouts/global/hooks/atoms/sidebar-atom";
|
import { asideStateAtom } from "@/components/layouts/global/hooks/atoms/sidebar-atom";
|
||||||
@@ -170,14 +171,16 @@ function CommentDialog({ editor, pageId, readOnly }: CommentDialogProps) {
|
|||||||
</div>
|
</div>
|
||||||
</Group>
|
</Group>
|
||||||
|
|
||||||
<CommentEditor
|
<CommentErrorBoundary>
|
||||||
onUpdate={handleCommentEditorChange}
|
<CommentEditor
|
||||||
onSave={handleAddComment}
|
onUpdate={handleCommentEditorChange}
|
||||||
placeholder={t("Write a comment")}
|
onSave={handleAddComment}
|
||||||
editable={true}
|
placeholder={t("Write a comment")}
|
||||||
autofocus={true}
|
editable={true}
|
||||||
/>
|
autofocus={true}
|
||||||
<CommentActions onSave={handleAddComment} isLoading={isPending} />
|
/>
|
||||||
|
<CommentActions onSave={handleAddComment} isLoading={isPending} />
|
||||||
|
</CommentErrorBoundary>
|
||||||
</Stack>
|
</Stack>
|
||||||
</Dialog>
|
</Dialog>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -1,7 +1,8 @@
|
|||||||
import { EditorContent, ReactNodeViewRenderer, useEditor } from "@tiptap/react";
|
import { EditorContent, ReactNodeViewRenderer, useEditor } from "@tiptap/react";
|
||||||
import { Placeholder } from "@tiptap/extension-placeholder";
|
import { Placeholder } from "@tiptap/extension-placeholder";
|
||||||
import { StarterKit } from "@tiptap/starter-kit";
|
import { StarterKit } from "@tiptap/starter-kit";
|
||||||
import { Mention, LinkExtension } from "@docmost/editor-ext";
|
import { TextStyle } from "@tiptap/extension-text-style";
|
||||||
|
import { Mention, LinkExtension, Color } from "@docmost/editor-ext";
|
||||||
import classes from "./comment.module.css";
|
import classes from "./comment.module.css";
|
||||||
import { useFocusWithin } from "@mantine/hooks";
|
import { useFocusWithin } from "@mantine/hooks";
|
||||||
import clsx from "clsx";
|
import clsx from "clsx";
|
||||||
@@ -11,6 +12,8 @@ import EmojiCommand from "@/features/editor/extensions/emoji-command";
|
|||||||
import mentionRenderItems from "@/features/editor/components/mention/mention-suggestion";
|
import mentionRenderItems from "@/features/editor/components/mention/mention-suggestion";
|
||||||
import MentionView from "@/features/editor/components/mention/mention-view";
|
import MentionView from "@/features/editor/components/mention/mention-view";
|
||||||
import { platformModifierKey } from "@/lib";
|
import { platformModifierKey } from "@/lib";
|
||||||
|
import { TableKit } from "@tiptap/extension-table";
|
||||||
|
import { TaskList, TaskItem } from "@tiptap/extension-list";
|
||||||
|
|
||||||
interface CommentEditorProps {
|
interface CommentEditorProps {
|
||||||
defaultContent?: any;
|
defaultContent?: any;
|
||||||
@@ -49,6 +52,8 @@ const CommentEditor = forwardRef(
|
|||||||
placeholder: placeholder || t("Reply..."),
|
placeholder: placeholder || t("Reply..."),
|
||||||
}),
|
}),
|
||||||
LinkExtension,
|
LinkExtension,
|
||||||
|
TextStyle,
|
||||||
|
Color,
|
||||||
EmojiCommand,
|
EmojiCommand,
|
||||||
Mention.configure({
|
Mention.configure({
|
||||||
suggestion: {
|
suggestion: {
|
||||||
@@ -66,6 +71,11 @@ const CommentEditor = forwardRef(
|
|||||||
return ReactNodeViewRenderer(MentionView);
|
return ReactNodeViewRenderer(MentionView);
|
||||||
},
|
},
|
||||||
}),
|
}),
|
||||||
|
TableKit,
|
||||||
|
TaskList,
|
||||||
|
TaskItem.configure({
|
||||||
|
nested: true,
|
||||||
|
}),
|
||||||
],
|
],
|
||||||
editorProps: {
|
editorProps: {
|
||||||
attributes: {
|
attributes: {
|
||||||
@@ -113,7 +123,12 @@ const CommentEditor = forwardRef(
|
|||||||
// websocket on another browser). Skip for editable editors to avoid
|
// websocket on another browser). Skip for editable editors to avoid
|
||||||
// resetting the cursor position on every keystroke.
|
// resetting the cursor position on every keystroke.
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!editable && commentEditor && !commentEditor.isDestroyed && defaultContent) {
|
if (
|
||||||
|
!editable &&
|
||||||
|
commentEditor &&
|
||||||
|
!commentEditor.isDestroyed &&
|
||||||
|
defaultContent
|
||||||
|
) {
|
||||||
commentEditor.commands.setContent(defaultContent);
|
commentEditor.commands.setContent(defaultContent);
|
||||||
}
|
}
|
||||||
}, [defaultContent, editable, commentEditor]);
|
}, [defaultContent, editable, commentEditor]);
|
||||||
|
|||||||
@@ -0,0 +1,38 @@
|
|||||||
|
import { ReactNode } from "react";
|
||||||
|
import { ErrorBoundary } from "react-error-boundary";
|
||||||
|
import { Button } from "@mantine/core";
|
||||||
|
import { IconAlertTriangle } from "@tabler/icons-react";
|
||||||
|
import { useTranslation } from "react-i18next";
|
||||||
|
import { EmptyState } from "@/components/ui/empty-state.tsx";
|
||||||
|
|
||||||
|
type CommentErrorBoundaryProps = {
|
||||||
|
children: ReactNode;
|
||||||
|
};
|
||||||
|
|
||||||
|
// Contain comment-editor render throws (e.g. schema errors) so they don't unmount the whole app.
|
||||||
|
export function CommentErrorBoundary({ children }: CommentErrorBoundaryProps) {
|
||||||
|
const { t } = useTranslation();
|
||||||
|
|
||||||
|
return (
|
||||||
|
<ErrorBoundary
|
||||||
|
fallbackRender={({ resetErrorBoundary }) => (
|
||||||
|
<EmptyState
|
||||||
|
icon={IconAlertTriangle}
|
||||||
|
title={t("Failed to load comments. An error occurred.")}
|
||||||
|
action={
|
||||||
|
<Button
|
||||||
|
variant="default"
|
||||||
|
size="sm"
|
||||||
|
mt="xs"
|
||||||
|
onClick={resetErrorBoundary}
|
||||||
|
>
|
||||||
|
{t("Try again")}
|
||||||
|
</Button>
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
{children}
|
||||||
|
</ErrorBoundary>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -53,6 +53,10 @@
|
|||||||
margin-block-end: 0;
|
margin-block-end: 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.ProseMirror :global(.tableWrapper) table {
|
||||||
|
min-width: 100% !important;
|
||||||
|
}
|
||||||
|
|
||||||
.actions {
|
.actions {
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,10 +5,6 @@ import { uploadPdfAction } from "../pdf/upload-pdf-action";
|
|||||||
import { createMentionAction } from "@/features/editor/components/link/internal-link-paste.ts";
|
import { createMentionAction } from "@/features/editor/components/link/internal-link-paste.ts";
|
||||||
import { INTERNAL_LINK_REGEX } from "@/lib/constants.ts";
|
import { INTERNAL_LINK_REGEX } from "@/lib/constants.ts";
|
||||||
import { Editor } from "@tiptap/core";
|
import { Editor } from "@tiptap/core";
|
||||||
import { matchIntegrationLink } from "@docmost/editor-ext";
|
|
||||||
import { integrationPasteMenuKey } from "@/features/editor/extensions/integration-paste-menu";
|
|
||||||
import { queryClient } from "@/main.tsx";
|
|
||||||
import { Integration } from "@/features/integration/types/integration.types";
|
|
||||||
import {
|
import {
|
||||||
getAttachmentInfo,
|
getAttachmentInfo,
|
||||||
uploadFile,
|
uploadFile,
|
||||||
@@ -26,16 +22,6 @@ const ATTACHMENT_NODE_TYPES = [
|
|||||||
|
|
||||||
const ATTACHMENT_URL_RE = /\/api\/files\/([0-9a-f-]+)\//;
|
const ATTACHMENT_URL_RE = /\/api\/files\/([0-9a-f-]+)\//;
|
||||||
|
|
||||||
// Only installed providers get card treatment; anything else pastes as an
|
|
||||||
// ordinary link. The cache is prefetched when the page editor mounts;
|
|
||||||
// a cold cache also means ordinary link.
|
|
||||||
function isIntegrationInstalled(provider: string): boolean {
|
|
||||||
const installed = queryClient.getQueryData<Integration[]>([
|
|
||||||
"installed-integrations",
|
|
||||||
]);
|
|
||||||
return Boolean(installed?.some((i) => i.type === provider));
|
|
||||||
}
|
|
||||||
|
|
||||||
export const handlePaste = (
|
export const handlePaste = (
|
||||||
editor: Editor,
|
editor: Editor,
|
||||||
event: ClipboardEvent,
|
event: ClipboardEvent,
|
||||||
@@ -44,59 +30,6 @@ export const handlePaste = (
|
|||||||
) => {
|
) => {
|
||||||
const clipboardData = event.clipboardData.getData("text/plain");
|
const clipboardData = event.clipboardData.getData("text/plain");
|
||||||
|
|
||||||
const integrationMatch = matchIntegrationLink(clipboardData.trim());
|
|
||||||
if (
|
|
||||||
integrationMatch &&
|
|
||||||
editor.state.selection.empty &&
|
|
||||||
isIntegrationInstalled(integrationMatch.provider)
|
|
||||||
) {
|
|
||||||
event.preventDefault();
|
|
||||||
const pastedUrl = clipboardData.trim();
|
|
||||||
editor
|
|
||||||
.chain()
|
|
||||||
.focus()
|
|
||||||
.setIntegrationLink({
|
|
||||||
url: pastedUrl,
|
|
||||||
provider: integrationMatch.provider,
|
|
||||||
})
|
|
||||||
// Anchor the "Paste as" menu to the inserted node, in the SAME
|
|
||||||
// transaction: BubbleMenu ignores meta-only transactions (it only
|
|
||||||
// re-evaluates when the doc or selection changed). Locate the node via
|
|
||||||
// the range this transaction's own steps touched, never by url, so a
|
|
||||||
// duplicate of the same link elsewhere in the doc can't steal the menu.
|
|
||||||
.command(({ tr }) => {
|
|
||||||
let start: number | null = null;
|
|
||||||
let end: number | null = null;
|
|
||||||
tr.mapping.maps.forEach((map, index) => {
|
|
||||||
const rest = tr.mapping.slice(index + 1);
|
|
||||||
map.forEach((_oldStart, _oldEnd, newStart, newEnd) => {
|
|
||||||
const mappedStart = rest.map(newStart, -1);
|
|
||||||
const mappedEnd = rest.map(newEnd, 1);
|
|
||||||
start = start === null ? mappedStart : Math.min(start, mappedStart);
|
|
||||||
end = end === null ? mappedEnd : Math.max(end, mappedEnd);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
if (start === null || end === null) return true;
|
|
||||||
|
|
||||||
let pastedPos: number | null = null;
|
|
||||||
tr.doc.nodesBetween(
|
|
||||||
start,
|
|
||||||
Math.min(end, tr.doc.content.size),
|
|
||||||
(node, pos) => {
|
|
||||||
if (node.type.name === "integrationLink") {
|
|
||||||
pastedPos = pos;
|
|
||||||
}
|
|
||||||
},
|
|
||||||
);
|
|
||||||
if (pastedPos !== null) {
|
|
||||||
tr.setMeta(integrationPasteMenuKey, { pos: pastedPos });
|
|
||||||
}
|
|
||||||
return true;
|
|
||||||
})
|
|
||||||
.run();
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (INTERNAL_LINK_REGEX.test(clipboardData)) {
|
if (INTERNAL_LINK_REGEX.test(clipboardData)) {
|
||||||
// we have to do this validation here to allow the default link extension to takeover if needs be
|
// we have to do this validation here to allow the default link extension to takeover if needs be
|
||||||
event.preventDefault();
|
event.preventDefault();
|
||||||
|
|||||||
@@ -1,49 +0,0 @@
|
|||||||
// Light-scheme text per hue, measured to pass 4.5:1 on the light-variant
|
|
||||||
// badge background; hexes are darkened .9 shades for hues whose scale
|
|
||||||
// never gets dark enough.
|
|
||||||
const BADGE_TEXT_LIGHT: Record<string, string> = {
|
|
||||||
dark: "var(--mantine-color-dark-9)",
|
|
||||||
gray: "var(--mantine-color-gray-9)",
|
|
||||||
red: "var(--mantine-color-red-9)",
|
|
||||||
pink: "var(--mantine-color-pink-9)",
|
|
||||||
grape: "var(--mantine-color-grape-9)",
|
|
||||||
violet: "var(--mantine-color-violet-9)",
|
|
||||||
indigo: "var(--mantine-color-indigo-9)",
|
|
||||||
blue: "var(--mantine-color-blue-9)",
|
|
||||||
cyan: "var(--mantine-color-cyan-9)",
|
|
||||||
teal: "var(--mantine-color-teal-9)",
|
|
||||||
green: "#277c38",
|
|
||||||
lime: "#4e7e0b",
|
|
||||||
yellow: "#ad5900",
|
|
||||||
orange: "#c3410e",
|
|
||||||
};
|
|
||||||
|
|
||||||
export function badgeTextColor(color?: string): string | undefined {
|
|
||||||
if (!color) return undefined;
|
|
||||||
const light = BADGE_TEXT_LIGHT[color];
|
|
||||||
if (!light) return undefined;
|
|
||||||
// Dark scheme keeps Mantine's own light-variant text.
|
|
||||||
return `light-dark(${light}, var(--mantine-color-${color}-light-color))`;
|
|
||||||
}
|
|
||||||
|
|
||||||
export function toBadgeColor(raw?: string): string {
|
|
||||||
if (!raw) return "gray";
|
|
||||||
const hex = raw.toLowerCase().replace("#", "");
|
|
||||||
if (/^[0-9a-f]{6}$/.test(hex)) {
|
|
||||||
const r = parseInt(hex.slice(0, 2), 16);
|
|
||||||
const g = parseInt(hex.slice(2, 4), 16);
|
|
||||||
const b = parseInt(hex.slice(4, 6), 16);
|
|
||||||
const max = Math.max(r, g, b);
|
|
||||||
const min = Math.min(r, g, b);
|
|
||||||
const l = (max + min) / 2 / 255;
|
|
||||||
if (max - min < 30) return l > 0.6 ? "gray" : "dark";
|
|
||||||
if (r > g && r > b) return g > 160 ? "orange" : "red";
|
|
||||||
if (g > r && g > b) return r > 160 ? "lime" : "green";
|
|
||||||
if (b > r && b > g) return r > 100 ? "violet" : "blue";
|
|
||||||
if (r > 200 && g > 200) return "yellow";
|
|
||||||
if (r > 200 && b > 200) return "pink";
|
|
||||||
if (g > 200 && b > 200) return "cyan";
|
|
||||||
return "gray";
|
|
||||||
}
|
|
||||||
return raw;
|
|
||||||
}
|
|
||||||
-65
@@ -1,65 +0,0 @@
|
|||||||
.card {
|
|
||||||
max-width: 100%;
|
|
||||||
cursor: pointer;
|
|
||||||
transition: background-color 150ms ease;
|
|
||||||
margin: 4px 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
.card:hover {
|
|
||||||
background-color: var(--mantine-color-gray-0);
|
|
||||||
}
|
|
||||||
|
|
||||||
:global([data-mantine-color-scheme="dark"]) .card:hover {
|
|
||||||
background-color: var(--mantine-color-dark-5);
|
|
||||||
}
|
|
||||||
|
|
||||||
.thumbnail {
|
|
||||||
display: block;
|
|
||||||
width: 100%;
|
|
||||||
max-height: 320px;
|
|
||||||
object-fit: cover;
|
|
||||||
background-color: var(--mantine-color-gray-0);
|
|
||||||
}
|
|
||||||
|
|
||||||
:global([data-mantine-color-scheme="dark"]) .thumbnail {
|
|
||||||
background-color: var(--mantine-color-dark-6);
|
|
||||||
}
|
|
||||||
|
|
||||||
.mention {
|
|
||||||
display: inline-flex;
|
|
||||||
align-items: center;
|
|
||||||
gap: 4px;
|
|
||||||
max-width: 100%;
|
|
||||||
vertical-align: text-bottom;
|
|
||||||
text-decoration: none;
|
|
||||||
color: inherit;
|
|
||||||
border-radius: var(--mantine-radius-sm);
|
|
||||||
}
|
|
||||||
|
|
||||||
:global(.node-integrationMention) .mention {
|
|
||||||
border-bottom: none !important;
|
|
||||||
font-weight: 400;
|
|
||||||
}
|
|
||||||
|
|
||||||
.mention:hover {
|
|
||||||
background-color: var(--mantine-color-gray-0);
|
|
||||||
}
|
|
||||||
|
|
||||||
:global([data-mantine-color-scheme="dark"]) .mention:hover {
|
|
||||||
background-color: var(--mantine-color-dark-5);
|
|
||||||
}
|
|
||||||
|
|
||||||
.mentionText {
|
|
||||||
text-decoration: underline;
|
|
||||||
text-decoration-color: var(--mantine-color-gray-4);
|
|
||||||
text-underline-offset: 3px;
|
|
||||||
white-space: nowrap;
|
|
||||||
overflow: hidden;
|
|
||||||
text-overflow: ellipsis;
|
|
||||||
max-width: 340px;
|
|
||||||
font-weight: 500;
|
|
||||||
}
|
|
||||||
|
|
||||||
.mentionIcon {
|
|
||||||
flex-shrink: 0;
|
|
||||||
}
|
|
||||||
-525
@@ -1,525 +0,0 @@
|
|||||||
import { NodeViewWrapper } from "@tiptap/react";
|
|
||||||
import {
|
|
||||||
Card,
|
|
||||||
Group,
|
|
||||||
Text,
|
|
||||||
Badge,
|
|
||||||
Avatar,
|
|
||||||
Skeleton,
|
|
||||||
Anchor,
|
|
||||||
Stack,
|
|
||||||
Button,
|
|
||||||
} from "@mantine/core";
|
|
||||||
import { useCallback, useState, memo } from "react";
|
|
||||||
import { useTranslation } from "react-i18next";
|
|
||||||
import { notifications } from "@mantine/notifications";
|
|
||||||
import { describeIntegrationLink } from "@docmost/editor-ext";
|
|
||||||
import { getIntegrationIcon } from "@/features/integration/components/integration-icons";
|
|
||||||
import { getOAuthAuthorizeUrl } from "@/features/integration/services/integration-service";
|
|
||||||
import { timeAgo } from "@/lib/time";
|
|
||||||
import { useUnfurl } from "./use-unfurl";
|
|
||||||
import { badgeTextColor, toBadgeColor } from "./badge-color";
|
|
||||||
import classes from "./integration-link-view.module.css";
|
|
||||||
|
|
||||||
const SLACK_TEXT_CLAMP_LINES = 4;
|
|
||||||
|
|
||||||
function SlackMessageCard({
|
|
||||||
url,
|
|
||||||
unfurlData,
|
|
||||||
}: {
|
|
||||||
url: string;
|
|
||||||
unfurlData: Record<string, any>;
|
|
||||||
}) {
|
|
||||||
const { t } = useTranslation();
|
|
||||||
const [expanded, setExpanded] = useState(false);
|
|
||||||
|
|
||||||
const meta = unfurlData.metadata ?? {};
|
|
||||||
const postedAt = meta.ts ? new Date(parseFloat(meta.ts) * 1000) : null;
|
|
||||||
const text: string = unfurlData.description ?? "";
|
|
||||||
const isLong =
|
|
||||||
text.length > 280 || text.split("\n").length > SLACK_TEXT_CLAMP_LINES;
|
|
||||||
|
|
||||||
const footer = [
|
|
||||||
meta.replyCount
|
|
||||||
? `${meta.replyCount} ${meta.replyCount === 1 ? t("reply") : t("replies")}`
|
|
||||||
: null,
|
|
||||||
unfurlData.status,
|
|
||||||
meta.teamName,
|
|
||||||
]
|
|
||||||
.filter(Boolean)
|
|
||||||
.join(" • ");
|
|
||||||
|
|
||||||
return (
|
|
||||||
<NodeViewWrapper data-drag-handle="">
|
|
||||||
<Card className={classes.card} withBorder padding="sm" radius="sm">
|
|
||||||
<Group gap="sm" wrap="nowrap" align="flex-start">
|
|
||||||
<Avatar
|
|
||||||
src={unfurlData.authorAvatarUrl}
|
|
||||||
size={28}
|
|
||||||
radius="xl"
|
|
||||||
style={{ flexShrink: 0 }}
|
|
||||||
>
|
|
||||||
{(unfurlData.author ?? "?").charAt(0)}
|
|
||||||
</Avatar>
|
|
||||||
|
|
||||||
<Stack gap={4} style={{ flex: 1, minWidth: 0 }}>
|
|
||||||
<Group gap={6} wrap="nowrap">
|
|
||||||
<Text size="sm" fw={600} truncate>
|
|
||||||
{unfurlData.author}
|
|
||||||
</Text>
|
|
||||||
{postedAt && (
|
|
||||||
<Text size="xs" c="dimmed" style={{ flexShrink: 0 }}>
|
|
||||||
{timeAgo(postedAt)}
|
|
||||||
</Text>
|
|
||||||
)}
|
|
||||||
</Group>
|
|
||||||
|
|
||||||
{text && (
|
|
||||||
<Text
|
|
||||||
size="sm"
|
|
||||||
lineClamp={expanded ? undefined : SLACK_TEXT_CLAMP_LINES}
|
|
||||||
style={{ whiteSpace: "pre-wrap" }}
|
|
||||||
>
|
|
||||||
{text}
|
|
||||||
</Text>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{isLong && (
|
|
||||||
<Text
|
|
||||||
size="xs"
|
|
||||||
fw={600}
|
|
||||||
role="button"
|
|
||||||
tabIndex={0}
|
|
||||||
aria-expanded={expanded}
|
|
||||||
style={{ cursor: "pointer", width: "fit-content" }}
|
|
||||||
onClick={() => setExpanded((v) => !v)}
|
|
||||||
onKeyDown={(event) => {
|
|
||||||
if (event.key === "Enter" || event.key === " ") {
|
|
||||||
event.preventDefault();
|
|
||||||
setExpanded((v) => !v);
|
|
||||||
}
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
{expanded ? t("show less") : t("show more")}
|
|
||||||
</Text>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{footer && (
|
|
||||||
<Text size="xs" c="dimmed" truncate>
|
|
||||||
{footer}
|
|
||||||
</Text>
|
|
||||||
)}
|
|
||||||
</Stack>
|
|
||||||
|
|
||||||
<Anchor
|
|
||||||
href={url}
|
|
||||||
target="_blank"
|
|
||||||
rel="noopener"
|
|
||||||
aria-label={t("Open in Slack")}
|
|
||||||
style={{ flexShrink: 0, lineHeight: 0 }}
|
|
||||||
>
|
|
||||||
{getIntegrationIcon("slack", 18)}
|
|
||||||
</Anchor>
|
|
||||||
</Group>
|
|
||||||
</Card>
|
|
||||||
</NodeViewWrapper>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
function JiraIssueCard({
|
|
||||||
url,
|
|
||||||
unfurlData,
|
|
||||||
}: {
|
|
||||||
url: string;
|
|
||||||
unfurlData: Record<string, any>;
|
|
||||||
}) {
|
|
||||||
const { t } = useTranslation();
|
|
||||||
const meta = unfurlData.metadata ?? {};
|
|
||||||
|
|
||||||
const infoLine = [
|
|
||||||
meta.issueKey,
|
|
||||||
unfurlData.author
|
|
||||||
? t("Assigned to {{name}}", { name: unfurlData.author })
|
|
||||||
: t("Unassigned"),
|
|
||||||
meta.updatedAt
|
|
||||||
? t("Updated {{time}}", { time: timeAgo(new Date(meta.updatedAt)) })
|
|
||||||
: null,
|
|
||||||
]
|
|
||||||
.filter(Boolean)
|
|
||||||
.join(" • ");
|
|
||||||
|
|
||||||
return (
|
|
||||||
<NodeViewWrapper data-drag-handle="">
|
|
||||||
<Card
|
|
||||||
className={classes.card}
|
|
||||||
withBorder
|
|
||||||
padding="sm"
|
|
||||||
radius="sm"
|
|
||||||
component="a"
|
|
||||||
href={url}
|
|
||||||
target="_blank"
|
|
||||||
rel="noopener"
|
|
||||||
style={{ textDecoration: "none", color: "inherit" }}
|
|
||||||
>
|
|
||||||
<Group gap="sm" wrap="nowrap">
|
|
||||||
{unfurlData.authorAvatarUrl ? (
|
|
||||||
<Avatar
|
|
||||||
src={unfurlData.authorAvatarUrl}
|
|
||||||
size={28}
|
|
||||||
radius="xl"
|
|
||||||
style={{ flexShrink: 0 }}
|
|
||||||
/>
|
|
||||||
) : (
|
|
||||||
<div style={{ flexShrink: 0 }}>{getIntegrationIcon("jira", 28)}</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
<Stack gap={2} style={{ flex: 1, minWidth: 0 }}>
|
|
||||||
<Group gap="xs" wrap="nowrap">
|
|
||||||
<Text size="sm" fw={600} truncate>
|
|
||||||
{unfurlData.title}
|
|
||||||
</Text>
|
|
||||||
{unfurlData.status && (
|
|
||||||
<Badge
|
|
||||||
size="xs"
|
|
||||||
variant="light"
|
|
||||||
color={toBadgeColor(unfurlData.statusColor)}
|
|
||||||
c={badgeTextColor(toBadgeColor(unfurlData.statusColor))}
|
|
||||||
style={{ flexShrink: 0 }}
|
|
||||||
>
|
|
||||||
{unfurlData.status}
|
|
||||||
</Badge>
|
|
||||||
)}
|
|
||||||
</Group>
|
|
||||||
|
|
||||||
<Group gap={4} wrap="nowrap">
|
|
||||||
{meta.issueTypeIconUrl && (
|
|
||||||
<img
|
|
||||||
src={meta.issueTypeIconUrl}
|
|
||||||
width={14}
|
|
||||||
height={14}
|
|
||||||
alt=""
|
|
||||||
style={{ flexShrink: 0 }}
|
|
||||||
/>
|
|
||||||
)}
|
|
||||||
<Text size="xs" c="dimmed" truncate>
|
|
||||||
{infoLine}
|
|
||||||
</Text>
|
|
||||||
</Group>
|
|
||||||
</Stack>
|
|
||||||
|
|
||||||
<div style={{ flexShrink: 0, alignSelf: "center" }}>
|
|
||||||
{getIntegrationIcon("jira", 18)}
|
|
||||||
</div>
|
|
||||||
</Group>
|
|
||||||
</Card>
|
|
||||||
</NodeViewWrapper>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
function FigmaFileCard({
|
|
||||||
url,
|
|
||||||
unfurlData,
|
|
||||||
}: {
|
|
||||||
url: string;
|
|
||||||
unfurlData: Record<string, any>;
|
|
||||||
}) {
|
|
||||||
const { t } = useTranslation();
|
|
||||||
// Figma thumbnail links are pre-signed and expire; drop the preview rather
|
|
||||||
// than render a broken image.
|
|
||||||
const [thumbnailFailed, setThumbnailFailed] = useState(false);
|
|
||||||
const meta = unfurlData.metadata ?? {};
|
|
||||||
const thumbnailUrl: string | undefined = meta.thumbnailUrl;
|
|
||||||
const showThumbnail = Boolean(thumbnailUrl) && !thumbnailFailed;
|
|
||||||
|
|
||||||
const subtitle = [
|
|
||||||
unfurlData.author
|
|
||||||
? t("Last modified by {{name}}", { name: unfurlData.author })
|
|
||||||
: unfurlData.description,
|
|
||||||
meta.lastModified ? timeAgo(new Date(meta.lastModified)) : null,
|
|
||||||
]
|
|
||||||
.filter(Boolean)
|
|
||||||
.join(" • ");
|
|
||||||
|
|
||||||
return (
|
|
||||||
<NodeViewWrapper data-drag-handle="">
|
|
||||||
<Card
|
|
||||||
className={classes.card}
|
|
||||||
withBorder
|
|
||||||
padding="sm"
|
|
||||||
radius="sm"
|
|
||||||
component="a"
|
|
||||||
href={url}
|
|
||||||
target="_blank"
|
|
||||||
rel="noopener"
|
|
||||||
style={{ textDecoration: "none", color: "inherit" }}
|
|
||||||
>
|
|
||||||
{showThumbnail && (
|
|
||||||
<Card.Section withBorder>
|
|
||||||
<img
|
|
||||||
src={thumbnailUrl}
|
|
||||||
alt=""
|
|
||||||
loading="lazy"
|
|
||||||
className={classes.thumbnail}
|
|
||||||
onError={() => setThumbnailFailed(true)}
|
|
||||||
/>
|
|
||||||
</Card.Section>
|
|
||||||
)}
|
|
||||||
|
|
||||||
<Group gap="sm" wrap="nowrap" mt={showThumbnail ? "sm" : undefined}>
|
|
||||||
<Avatar
|
|
||||||
src={unfurlData.authorAvatarUrl}
|
|
||||||
size={28}
|
|
||||||
radius="xl"
|
|
||||||
style={{ flexShrink: 0 }}
|
|
||||||
>
|
|
||||||
{(unfurlData.author ?? unfurlData.title ?? "F").charAt(0)}
|
|
||||||
</Avatar>
|
|
||||||
|
|
||||||
<Stack gap={2} style={{ flex: 1, minWidth: 0 }}>
|
|
||||||
<Text size="sm" fw={600} truncate>
|
|
||||||
{unfurlData.title}
|
|
||||||
</Text>
|
|
||||||
{subtitle && (
|
|
||||||
<Text size="xs" c="dimmed" truncate>
|
|
||||||
{subtitle}
|
|
||||||
</Text>
|
|
||||||
)}
|
|
||||||
</Stack>
|
|
||||||
|
|
||||||
<div style={{ flexShrink: 0, alignSelf: "center" }}>
|
|
||||||
{getIntegrationIcon("figma", 18)}
|
|
||||||
</div>
|
|
||||||
</Group>
|
|
||||||
</Card>
|
|
||||||
</NodeViewWrapper>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
function IntegrationLinkView(props: any) {
|
|
||||||
const { node } = props;
|
|
||||||
const { url, provider } = node.attrs;
|
|
||||||
const { t } = useTranslation();
|
|
||||||
|
|
||||||
const unfurl = useUnfurl(url);
|
|
||||||
const [connecting, setConnecting] = useState(false);
|
|
||||||
|
|
||||||
const needsConnection =
|
|
||||||
unfurl.state === "needsConnection" ? unfurl.needsConnection : null;
|
|
||||||
|
|
||||||
const handleConnect = useCallback(
|
|
||||||
async (event: React.MouseEvent) => {
|
|
||||||
event.preventDefault();
|
|
||||||
event.stopPropagation();
|
|
||||||
if (!needsConnection) return;
|
|
||||||
|
|
||||||
setConnecting(true);
|
|
||||||
try {
|
|
||||||
const result = await getOAuthAuthorizeUrl({
|
|
||||||
integrationId: needsConnection.integrationId,
|
|
||||||
returnPath: window.location.pathname,
|
|
||||||
});
|
|
||||||
window.location.href = result.authorizationUrl;
|
|
||||||
} catch (error) {
|
|
||||||
setConnecting(false);
|
|
||||||
notifications.show({
|
|
||||||
message:
|
|
||||||
error?.["response"]?.data?.message ||
|
|
||||||
t("Failed to start OAuth connection"),
|
|
||||||
color: "red",
|
|
||||||
});
|
|
||||||
}
|
|
||||||
},
|
|
||||||
[needsConnection, t],
|
|
||||||
);
|
|
||||||
|
|
||||||
if (needsConnection) {
|
|
||||||
return (
|
|
||||||
<NodeViewWrapper data-drag-handle="">
|
|
||||||
<Card
|
|
||||||
className={classes.card}
|
|
||||||
withBorder
|
|
||||||
padding="sm"
|
|
||||||
radius="sm"
|
|
||||||
component="a"
|
|
||||||
href={url}
|
|
||||||
target="_blank"
|
|
||||||
rel="noopener"
|
|
||||||
style={{ textDecoration: "none", color: "inherit" }}
|
|
||||||
>
|
|
||||||
<Group gap="sm" wrap="nowrap">
|
|
||||||
<div style={{ flexShrink: 0 }}>
|
|
||||||
{getIntegrationIcon(provider, 28)}
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<Stack gap={2} style={{ flex: 1, minWidth: 0 }}>
|
|
||||||
<Text size="sm" fw={600} truncate>
|
|
||||||
{needsConnection.title}
|
|
||||||
</Text>
|
|
||||||
{needsConnection.description && (
|
|
||||||
<Text size="xs" c="dimmed" lineClamp={1}>
|
|
||||||
{needsConnection.description}
|
|
||||||
</Text>
|
|
||||||
)}
|
|
||||||
</Stack>
|
|
||||||
|
|
||||||
{needsConnection.oauthConnect ? (
|
|
||||||
<Button
|
|
||||||
size="xs"
|
|
||||||
variant="filled"
|
|
||||||
color="dark"
|
|
||||||
loading={connecting}
|
|
||||||
onClick={handleConnect}
|
|
||||||
style={{ flexShrink: 0 }}
|
|
||||||
>
|
|
||||||
{t("Connect to {{name}} to preview", {
|
|
||||||
name: needsConnection.integrationName,
|
|
||||||
})}
|
|
||||||
</Button>
|
|
||||||
) : (
|
|
||||||
<Text size="xs" c="dimmed" style={{ flexShrink: 0 }}>
|
|
||||||
{t("Use")} <code>/docmost help</code> {t("in")}{" "}
|
|
||||||
{needsConnection.integrationName} {t("to link your account.")}
|
|
||||||
</Text>
|
|
||||||
)}
|
|
||||||
</Group>
|
|
||||||
</Card>
|
|
||||||
</NodeViewWrapper>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (unfurl.state === "loading") {
|
|
||||||
return (
|
|
||||||
<NodeViewWrapper data-drag-handle="">
|
|
||||||
<Card className={classes.card} withBorder padding="sm" radius="sm">
|
|
||||||
<Group gap="sm">
|
|
||||||
<Skeleton circle height={24} />
|
|
||||||
<Stack gap={4} style={{ flex: 1 }}>
|
|
||||||
<Skeleton height={14} width="60%" />
|
|
||||||
<Skeleton height={10} width="80%" />
|
|
||||||
</Stack>
|
|
||||||
</Group>
|
|
||||||
</Card>
|
|
||||||
</NodeViewWrapper>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (unfurl.state !== "loaded") {
|
|
||||||
// anonymous or error: no third-party data, only what the url itself says
|
|
||||||
const described = describeIntegrationLink(url);
|
|
||||||
if (described) {
|
|
||||||
return (
|
|
||||||
<NodeViewWrapper data-drag-handle="">
|
|
||||||
<Card
|
|
||||||
className={classes.card}
|
|
||||||
withBorder
|
|
||||||
padding="sm"
|
|
||||||
radius="sm"
|
|
||||||
component="a"
|
|
||||||
href={url}
|
|
||||||
target="_blank"
|
|
||||||
rel="noopener"
|
|
||||||
style={{ textDecoration: "none", color: "inherit" }}
|
|
||||||
>
|
|
||||||
<Group gap="sm" wrap="nowrap">
|
|
||||||
<div style={{ flexShrink: 0 }}>
|
|
||||||
{getIntegrationIcon(provider, 28)}
|
|
||||||
</div>
|
|
||||||
<Stack gap={2} style={{ flex: 1, minWidth: 0 }}>
|
|
||||||
<Text size="sm" fw={600} truncate>
|
|
||||||
{described.title}
|
|
||||||
</Text>
|
|
||||||
{described.description && (
|
|
||||||
<Text size="xs" c="dimmed" lineClamp={1}>
|
|
||||||
{described.description}
|
|
||||||
</Text>
|
|
||||||
)}
|
|
||||||
</Stack>
|
|
||||||
</Group>
|
|
||||||
</Card>
|
|
||||||
</NodeViewWrapper>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
return (
|
|
||||||
<NodeViewWrapper data-drag-handle="">
|
|
||||||
<Card className={classes.card} withBorder padding="sm" radius="sm">
|
|
||||||
<Anchor href={url} target="_blank" rel="noopener" size="sm">
|
|
||||||
{url}
|
|
||||||
</Anchor>
|
|
||||||
</Card>
|
|
||||||
</NodeViewWrapper>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
const unfurlData = unfurl.data;
|
|
||||||
|
|
||||||
// metadata.ts marks legacy message unfurls stored before metadata.type existed.
|
|
||||||
const slackMeta = provider === "slack" ? unfurlData.metadata : null;
|
|
||||||
if (slackMeta?.type === "message" || (slackMeta && !slackMeta.type && slackMeta.ts)) {
|
|
||||||
return <SlackMessageCard url={url} unfurlData={unfurlData} />;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (provider === "jira" && unfurlData.metadata?.issueKey) {
|
|
||||||
return <JiraIssueCard url={url} unfurlData={unfurlData} />;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (provider === "figma") {
|
|
||||||
return <FigmaFileCard url={url} unfurlData={unfurlData} />;
|
|
||||||
}
|
|
||||||
|
|
||||||
return (
|
|
||||||
<NodeViewWrapper data-drag-handle="">
|
|
||||||
<Card
|
|
||||||
className={classes.card}
|
|
||||||
withBorder
|
|
||||||
padding="sm"
|
|
||||||
radius="sm"
|
|
||||||
component="a"
|
|
||||||
href={url}
|
|
||||||
target="_blank"
|
|
||||||
rel="noopener"
|
|
||||||
style={{ textDecoration: "none", color: "inherit" }}
|
|
||||||
>
|
|
||||||
<Group gap="sm" wrap="nowrap">
|
|
||||||
{unfurlData.authorAvatarUrl ? (
|
|
||||||
<Avatar src={unfurlData.authorAvatarUrl} size={28} radius="xl" style={{ flexShrink: 0 }} />
|
|
||||||
) : (
|
|
||||||
<div style={{ flexShrink: 0 }}>{getIntegrationIcon(provider, 28)}</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
<Stack gap={2} style={{ flex: 1, minWidth: 0 }}>
|
|
||||||
<Group gap="xs" wrap="nowrap">
|
|
||||||
<Text size="sm" fw={600} truncate>
|
|
||||||
{unfurlData.title}
|
|
||||||
</Text>
|
|
||||||
{unfurlData.status && (
|
|
||||||
<Badge
|
|
||||||
size="xs"
|
|
||||||
variant="light"
|
|
||||||
color={toBadgeColor(unfurlData.statusColor)}
|
|
||||||
c={badgeTextColor(toBadgeColor(unfurlData.statusColor))}
|
|
||||||
style={{ flexShrink: 0 }}
|
|
||||||
>
|
|
||||||
{unfurlData.status}
|
|
||||||
</Badge>
|
|
||||||
)}
|
|
||||||
</Group>
|
|
||||||
|
|
||||||
{unfurlData.description && (
|
|
||||||
<Text size="xs" c="dimmed" lineClamp={1}>
|
|
||||||
{unfurlData.description}
|
|
||||||
</Text>
|
|
||||||
)}
|
|
||||||
</Stack>
|
|
||||||
|
|
||||||
{provider && (
|
|
||||||
<div style={{ flexShrink: 0, alignSelf: "center" }}>
|
|
||||||
{getIntegrationIcon(provider, 18)}
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</Group>
|
|
||||||
</Card>
|
|
||||||
</NodeViewWrapper>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
export default memo(IntegrationLinkView);
|
|
||||||
-253
@@ -1,253 +0,0 @@
|
|||||||
import { NodeViewWrapper } from "@tiptap/react";
|
|
||||||
import {
|
|
||||||
Avatar,
|
|
||||||
Badge,
|
|
||||||
Button,
|
|
||||||
Group,
|
|
||||||
HoverCard,
|
|
||||||
Stack,
|
|
||||||
Text,
|
|
||||||
} from "@mantine/core";
|
|
||||||
import { memo, useCallback, useState } from "react";
|
|
||||||
import { useTranslation } from "react-i18next";
|
|
||||||
import { notifications } from "@mantine/notifications";
|
|
||||||
import { describeIntegrationLink } from "@docmost/editor-ext";
|
|
||||||
import { getIntegrationIcon } from "@/features/integration/components/integration-icons";
|
|
||||||
import { getOAuthAuthorizeUrl } from "@/features/integration/services/integration-service";
|
|
||||||
import { useUnfurl } from "./use-unfurl";
|
|
||||||
import { badgeTextColor, toBadgeColor } from "./badge-color";
|
|
||||||
import classes from "./integration-link-view.module.css";
|
|
||||||
|
|
||||||
function shortUrl(url: string): string {
|
|
||||||
try {
|
|
||||||
const parsed = new URL(url);
|
|
||||||
return `${parsed.host}${parsed.pathname}`;
|
|
||||||
} catch {
|
|
||||||
return url;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function IntegrationMentionView(props: any) {
|
|
||||||
const { node } = props;
|
|
||||||
const { url, provider } = node.attrs;
|
|
||||||
const { t } = useTranslation();
|
|
||||||
|
|
||||||
const unfurl = useUnfurl(url);
|
|
||||||
const data = unfurl.state === "loaded" ? unfurl.data : null;
|
|
||||||
const needsConnection =
|
|
||||||
unfurl.state === "needsConnection" ? unfurl.needsConnection : null;
|
|
||||||
const [connecting, setConnecting] = useState(false);
|
|
||||||
|
|
||||||
const handleConnect = useCallback(
|
|
||||||
async (event: React.MouseEvent) => {
|
|
||||||
event.preventDefault();
|
|
||||||
event.stopPropagation();
|
|
||||||
if (!needsConnection) return;
|
|
||||||
|
|
||||||
setConnecting(true);
|
|
||||||
try {
|
|
||||||
const result = await getOAuthAuthorizeUrl({
|
|
||||||
integrationId: needsConnection.integrationId,
|
|
||||||
returnPath: window.location.pathname,
|
|
||||||
});
|
|
||||||
window.location.href = result.authorizationUrl;
|
|
||||||
} catch (error) {
|
|
||||||
setConnecting(false);
|
|
||||||
notifications.show({
|
|
||||||
message:
|
|
||||||
error?.["response"]?.data?.message ||
|
|
||||||
t("Failed to start OAuth connection"),
|
|
||||||
color: "red",
|
|
||||||
});
|
|
||||||
}
|
|
||||||
},
|
|
||||||
[needsConnection, t],
|
|
||||||
);
|
|
||||||
const meta = data?.metadata ?? {};
|
|
||||||
const isSlackMessage =
|
|
||||||
provider === "slack" && (meta.type === "message" || (!meta.type && meta.ts));
|
|
||||||
const issueNumber = meta.iid ?? meta.number;
|
|
||||||
const typeLabel =
|
|
||||||
meta.type === "project"
|
|
||||||
? t("Project")
|
|
||||||
: meta.type === "initiative"
|
|
||||||
? t("Initiative")
|
|
||||||
: null;
|
|
||||||
|
|
||||||
const statusBadge = data?.status ? (
|
|
||||||
<Badge
|
|
||||||
size="xs"
|
|
||||||
variant="light"
|
|
||||||
color={toBadgeColor(data.statusColor)}
|
|
||||||
c={badgeTextColor(toBadgeColor(data.statusColor))}
|
|
||||||
className={classes.mentionIcon}
|
|
||||||
>
|
|
||||||
{data.status}
|
|
||||||
</Badge>
|
|
||||||
) : null;
|
|
||||||
|
|
||||||
let content;
|
|
||||||
if (!data) {
|
|
||||||
// anonymous / loading / error / needs-connection: a compact link chip.
|
|
||||||
// With no unfurl response, fall back to what the url text itself says.
|
|
||||||
content = (
|
|
||||||
<>
|
|
||||||
{getIntegrationIcon(provider, 14)}
|
|
||||||
<span className={classes.mentionText}>
|
|
||||||
{needsConnection?.title ??
|
|
||||||
describeIntegrationLink(url)?.title ??
|
|
||||||
shortUrl(url)}
|
|
||||||
</span>
|
|
||||||
</>
|
|
||||||
);
|
|
||||||
} else if (isSlackMessage) {
|
|
||||||
content = (
|
|
||||||
<>
|
|
||||||
<Avatar
|
|
||||||
src={data.authorAvatarUrl}
|
|
||||||
size={16}
|
|
||||||
radius="xl"
|
|
||||||
className={classes.mentionIcon}
|
|
||||||
>
|
|
||||||
{(data.author ?? "?").charAt(0)}
|
|
||||||
</Avatar>
|
|
||||||
{data.author && (
|
|
||||||
<Text component="span" size="sm" c="dimmed">
|
|
||||||
{data.author}
|
|
||||||
</Text>
|
|
||||||
)}
|
|
||||||
<span className={classes.mentionText}>
|
|
||||||
{(data.description ?? "").split("\n")[0] || shortUrl(url)}
|
|
||||||
</span>
|
|
||||||
{getIntegrationIcon("slack", 14)}
|
|
||||||
{data.status && (
|
|
||||||
<Badge
|
|
||||||
size="xs"
|
|
||||||
variant="light"
|
|
||||||
color="gray"
|
|
||||||
c={badgeTextColor("gray")}
|
|
||||||
tt="none"
|
|
||||||
className={classes.mentionIcon}
|
|
||||||
>
|
|
||||||
{data.status}
|
|
||||||
</Badge>
|
|
||||||
)}
|
|
||||||
</>
|
|
||||||
);
|
|
||||||
} else if (meta.issueKey) {
|
|
||||||
// Jira: type icon leads, provider icon trails.
|
|
||||||
content = (
|
|
||||||
<>
|
|
||||||
{meta.issueTypeIconUrl ? (
|
|
||||||
<img
|
|
||||||
src={meta.issueTypeIconUrl}
|
|
||||||
width={14}
|
|
||||||
height={14}
|
|
||||||
alt=""
|
|
||||||
className={classes.mentionIcon}
|
|
||||||
/>
|
|
||||||
) : (
|
|
||||||
getIntegrationIcon(provider, 14)
|
|
||||||
)}
|
|
||||||
<Text component="span" size="sm" c="dimmed">
|
|
||||||
{meta.issueKey}
|
|
||||||
</Text>
|
|
||||||
<span className={classes.mentionText}>{data.title}</span>
|
|
||||||
{statusBadge}
|
|
||||||
{meta.issueTypeIconUrl && getIntegrationIcon(provider, 14)}
|
|
||||||
</>
|
|
||||||
);
|
|
||||||
} else if (issueNumber) {
|
|
||||||
content = (
|
|
||||||
<>
|
|
||||||
{getIntegrationIcon(provider, 14)}
|
|
||||||
<Text component="span" size="sm" c="dimmed">
|
|
||||||
#{issueNumber}
|
|
||||||
</Text>
|
|
||||||
<span className={classes.mentionText}>{data.title}</span>
|
|
||||||
{statusBadge}
|
|
||||||
</>
|
|
||||||
);
|
|
||||||
} else if (typeLabel) {
|
|
||||||
content = (
|
|
||||||
<>
|
|
||||||
{getIntegrationIcon(provider, 14)}
|
|
||||||
<Text component="span" size="sm" c="dimmed">
|
|
||||||
{typeLabel}
|
|
||||||
</Text>
|
|
||||||
<span className={classes.mentionText}>{data.title}</span>
|
|
||||||
{statusBadge}
|
|
||||||
</>
|
|
||||||
);
|
|
||||||
} else {
|
|
||||||
content = (
|
|
||||||
<>
|
|
||||||
{getIntegrationIcon(provider, 14)}
|
|
||||||
<span className={classes.mentionText}>{data.title || shortUrl(url)}</span>
|
|
||||||
{statusBadge}
|
|
||||||
</>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
const anchor = (
|
|
||||||
<a
|
|
||||||
href={url}
|
|
||||||
target="_blank"
|
|
||||||
rel="noopener"
|
|
||||||
title={url}
|
|
||||||
className={classes.mention}
|
|
||||||
>
|
|
||||||
{content}
|
|
||||||
</a>
|
|
||||||
);
|
|
||||||
|
|
||||||
return (
|
|
||||||
<NodeViewWrapper as="span" style={{ display: "inline" }}>
|
|
||||||
{needsConnection ? (
|
|
||||||
<HoverCard
|
|
||||||
position="bottom-start"
|
|
||||||
shadow="md"
|
|
||||||
radius="md"
|
|
||||||
openDelay={150}
|
|
||||||
closeDelay={150}
|
|
||||||
>
|
|
||||||
<HoverCard.Target>{anchor}</HoverCard.Target>
|
|
||||||
<HoverCard.Dropdown p="sm">
|
|
||||||
<Stack gap="xs">
|
|
||||||
<Group gap={6} wrap="nowrap">
|
|
||||||
{getIntegrationIcon(provider, 16)}
|
|
||||||
<Text size="sm" fw={500}>
|
|
||||||
{needsConnection.integrationName}
|
|
||||||
</Text>
|
|
||||||
</Group>
|
|
||||||
{needsConnection.oauthConnect ? (
|
|
||||||
<Button
|
|
||||||
size="xs"
|
|
||||||
variant="filled"
|
|
||||||
color="dark"
|
|
||||||
leftSection={getIntegrationIcon(provider, 16)}
|
|
||||||
loading={connecting}
|
|
||||||
onClick={handleConnect}
|
|
||||||
>
|
|
||||||
{t("Connect to {{name}} to preview", {
|
|
||||||
name: needsConnection.integrationName,
|
|
||||||
})}
|
|
||||||
</Button>
|
|
||||||
) : (
|
|
||||||
<Text size="xs" c="dimmed">
|
|
||||||
{t("Use")} <code>/docmost help</code> {t("in")}{" "}
|
|
||||||
{needsConnection.integrationName}{" "}
|
|
||||||
{t("to link your account.")}
|
|
||||||
</Text>
|
|
||||||
)}
|
|
||||||
</Stack>
|
|
||||||
</HoverCard.Dropdown>
|
|
||||||
</HoverCard>
|
|
||||||
) : (
|
|
||||||
anchor
|
|
||||||
)}
|
|
||||||
</NodeViewWrapper>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
export default memo(IntegrationMentionView);
|
|
||||||
-205
@@ -1,205 +0,0 @@
|
|||||||
import { BubbleMenu as BaseBubbleMenu } from "@tiptap/react/menus";
|
|
||||||
import { posToDOMRect, useEditorState } from "@tiptap/react";
|
|
||||||
import { useCallback, useEffect, useState } from "react";
|
|
||||||
import {
|
|
||||||
Button,
|
|
||||||
Paper,
|
|
||||||
Stack,
|
|
||||||
Text,
|
|
||||||
VisuallyHidden,
|
|
||||||
} from "@mantine/core";
|
|
||||||
import { useTranslation } from "react-i18next";
|
|
||||||
import { EditorMenuProps } from "@/features/editor/components/table/types/types.ts";
|
|
||||||
import { integrationPasteMenuKey } from "@/features/editor/extensions/integration-paste-menu";
|
|
||||||
|
|
||||||
const INTEGRATION_NODE_TYPES = ["integrationLink", "integrationMention"];
|
|
||||||
|
|
||||||
type PasteTarget = "card" | "mention" | "url";
|
|
||||||
|
|
||||||
const PASTE_OPTIONS: { target: PasteTarget; label: string }[] = [
|
|
||||||
{ target: "card", label: "Card" },
|
|
||||||
{ target: "mention", label: "Mention" },
|
|
||||||
{ target: "url", label: "URL" },
|
|
||||||
];
|
|
||||||
|
|
||||||
export function IntegrationPasteMenu({ editor }: EditorMenuProps) {
|
|
||||||
const { t } = useTranslation();
|
|
||||||
const [selectedIndex, setSelectedIndex] = useState(0);
|
|
||||||
|
|
||||||
const menuState = useEditorState({
|
|
||||||
editor,
|
|
||||||
selector: (ctx) => {
|
|
||||||
if (!ctx.editor) return null;
|
|
||||||
return integrationPasteMenuKey.getState(ctx.editor.state) ?? null;
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
const findTarget = useCallback(() => {
|
|
||||||
const state = integrationPasteMenuKey.getState(editor.state);
|
|
||||||
if (!state) return null;
|
|
||||||
const node = editor.state.doc.nodeAt(state.pos);
|
|
||||||
if (!node || !INTEGRATION_NODE_TYPES.includes(node.type.name)) return null;
|
|
||||||
return { node, pos: state.pos };
|
|
||||||
}, [editor]);
|
|
||||||
|
|
||||||
const shouldShow = useCallback(() => Boolean(findTarget()), [findTarget]);
|
|
||||||
|
|
||||||
const getReferencedVirtualElement = useCallback(() => {
|
|
||||||
const target = findTarget();
|
|
||||||
if (!target) return undefined;
|
|
||||||
const dom = editor.view.nodeDOM(target.pos) as HTMLElement | null;
|
|
||||||
const domRect =
|
|
||||||
dom?.getBoundingClientRect?.() ??
|
|
||||||
posToDOMRect(
|
|
||||||
editor.view,
|
|
||||||
target.pos,
|
|
||||||
target.pos + target.node.nodeSize,
|
|
||||||
);
|
|
||||||
return {
|
|
||||||
getBoundingClientRect: () => domRect,
|
|
||||||
getClientRects: () => [domRect],
|
|
||||||
};
|
|
||||||
}, [editor, findTarget]);
|
|
||||||
|
|
||||||
const dismiss = useCallback(() => {
|
|
||||||
editor.view.dispatch(
|
|
||||||
editor.state.tr.setMeta(integrationPasteMenuKey, null),
|
|
||||||
);
|
|
||||||
}, [editor]);
|
|
||||||
|
|
||||||
const convert = useCallback(
|
|
||||||
(target: PasteTarget) => {
|
|
||||||
const found = findTarget();
|
|
||||||
if (!found) {
|
|
||||||
dismiss();
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
const { node, pos } = found;
|
|
||||||
const attrs = { ...node.attrs };
|
|
||||||
const from = pos;
|
|
||||||
const to = pos + node.nodeSize;
|
|
||||||
const isBlock = node.type.name === "integrationLink";
|
|
||||||
|
|
||||||
// Always replace, even when the node is already in the requested form:
|
|
||||||
// the menu closes via the doc change, and BubbleMenu never re-evaluates
|
|
||||||
// on meta-only transactions, so a bare dismiss would leave it stuck.
|
|
||||||
let content: Record<string, any>;
|
|
||||||
if (target === "card") {
|
|
||||||
content = { type: "integrationLink", attrs };
|
|
||||||
} else if (target === "mention") {
|
|
||||||
const mention = { type: "integrationMention", attrs };
|
|
||||||
content = isBlock
|
|
||||||
? {
|
|
||||||
type: "paragraph",
|
|
||||||
content: [mention, { type: "text", text: " " }],
|
|
||||||
}
|
|
||||||
: mention;
|
|
||||||
} else {
|
|
||||||
const linkText = {
|
|
||||||
type: "text",
|
|
||||||
text: attrs.url,
|
|
||||||
marks: [{ type: "link", attrs: { href: attrs.url } }],
|
|
||||||
};
|
|
||||||
content = isBlock
|
|
||||||
? { type: "paragraph", content: [linkText] }
|
|
||||||
: linkText;
|
|
||||||
}
|
|
||||||
|
|
||||||
editor
|
|
||||||
.chain()
|
|
||||||
.focus(undefined, { scrollIntoView: false })
|
|
||||||
.deleteRange({ from, to })
|
|
||||||
.insertContentAt(from, content)
|
|
||||||
.run();
|
|
||||||
},
|
|
||||||
[editor, findTarget, dismiss],
|
|
||||||
);
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
if (menuState) setSelectedIndex(0);
|
|
||||||
}, [menuState]);
|
|
||||||
|
|
||||||
// DOM focus stays in the editor (as with the slash menu); keys are handled
|
|
||||||
// here. Capture phase, because ProseMirror itself consumes arrow keys next
|
|
||||||
// to atom nodes (gap cursor / node selection) before they would bubble.
|
|
||||||
useEffect(() => {
|
|
||||||
if (!menuState) return;
|
|
||||||
const onKeyDown = (event: KeyboardEvent) => {
|
|
||||||
if (event.key === "Escape") {
|
|
||||||
event.preventDefault();
|
|
||||||
event.stopPropagation();
|
|
||||||
dismiss();
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
if (event.key === "ArrowDown" || event.key === "ArrowUp") {
|
|
||||||
event.preventDefault();
|
|
||||||
event.stopPropagation();
|
|
||||||
const delta = event.key === "ArrowDown" ? 1 : -1;
|
|
||||||
setSelectedIndex(
|
|
||||||
(prev) =>
|
|
||||||
(prev + delta + PASTE_OPTIONS.length) % PASTE_OPTIONS.length,
|
|
||||||
);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
if (event.key === "Enter") {
|
|
||||||
event.preventDefault();
|
|
||||||
event.stopPropagation();
|
|
||||||
convert(PASTE_OPTIONS[selectedIndex].target);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
window.addEventListener("keydown", onKeyDown, true);
|
|
||||||
return () => window.removeEventListener("keydown", onKeyDown, true);
|
|
||||||
}, [menuState, dismiss, convert, selectedIndex]);
|
|
||||||
|
|
||||||
return (
|
|
||||||
<BaseBubbleMenu
|
|
||||||
editor={editor}
|
|
||||||
pluginKey="integration-paste-menu"
|
|
||||||
updateDelay={0}
|
|
||||||
getReferencedVirtualElement={getReferencedVirtualElement}
|
|
||||||
options={{ placement: "bottom-start", flip: true }}
|
|
||||||
shouldShow={shouldShow}
|
|
||||||
>
|
|
||||||
{/* Content is gated on the plugin state too: meta-only dismissals
|
|
||||||
(Escape) are invisible to BubbleMenu's update cycle. */}
|
|
||||||
{menuState ? (
|
|
||||||
<Paper
|
|
||||||
shadow="md"
|
|
||||||
radius="md"
|
|
||||||
withBorder
|
|
||||||
p={4}
|
|
||||||
miw={140}
|
|
||||||
role="listbox"
|
|
||||||
aria-label={t("Paste as")}
|
|
||||||
aria-activedescendant={`integration-paste-option-${PASTE_OPTIONS[selectedIndex].target}`}
|
|
||||||
>
|
|
||||||
<VisuallyHidden role="status" aria-live="polite" aria-atomic="true">
|
|
||||||
{t(PASTE_OPTIONS[selectedIndex].label)}
|
|
||||||
</VisuallyHidden>
|
|
||||||
<Text size="xs" c="dimmed" px={8} py={4}>
|
|
||||||
{t("Paste as")}
|
|
||||||
</Text>
|
|
||||||
<Stack gap={2}>
|
|
||||||
{PASTE_OPTIONS.map((option, index) => (
|
|
||||||
<Button
|
|
||||||
key={option.target}
|
|
||||||
id={`integration-paste-option-${option.target}`}
|
|
||||||
role="option"
|
|
||||||
aria-selected={index === selectedIndex}
|
|
||||||
variant={index === selectedIndex ? "light" : "subtle"}
|
|
||||||
color="gray"
|
|
||||||
size="compact-sm"
|
|
||||||
fullWidth
|
|
||||||
justify="flex-start"
|
|
||||||
onMouseEnter={() => setSelectedIndex(index)}
|
|
||||||
onClick={() => convert(option.target)}
|
|
||||||
>
|
|
||||||
{t(option.label)}
|
|
||||||
</Button>
|
|
||||||
))}
|
|
||||||
</Stack>
|
|
||||||
</Paper>
|
|
||||||
) : null}
|
|
||||||
</BaseBubbleMenu>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -1,119 +0,0 @@
|
|||||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
|
||||||
import { renderHook, waitFor } from "@testing-library/react";
|
|
||||||
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
|
||||||
import { createStore, Provider } from "jotai";
|
|
||||||
import { ReactNode } from "react";
|
|
||||||
import { useUnfurl } from "./use-unfurl";
|
|
||||||
import { currentUserAtom } from "@/features/user/atoms/current-user-atom";
|
|
||||||
import { unfurlUrl } from "@/features/integration/services/integration-service";
|
|
||||||
import {
|
|
||||||
UnfurlNeedsConnection,
|
|
||||||
UnfurlResult,
|
|
||||||
} from "@/features/integration/types/integration.types";
|
|
||||||
|
|
||||||
vi.mock("@/features/integration/services/integration-service", () => ({
|
|
||||||
unfurlUrl: vi.fn(),
|
|
||||||
}));
|
|
||||||
|
|
||||||
const mockedUnfurlUrl = vi.mocked(unfurlUrl);
|
|
||||||
|
|
||||||
const ISSUE_URL = "https://github.com/acme/repo/issues/42";
|
|
||||||
|
|
||||||
const loadedResult: UnfurlResult = {
|
|
||||||
title: "Fix race condition in file watcher",
|
|
||||||
url: ISSUE_URL,
|
|
||||||
provider: "github",
|
|
||||||
status: "open",
|
|
||||||
};
|
|
||||||
|
|
||||||
const needsConnectionResult: UnfurlNeedsConnection = {
|
|
||||||
needsConnection: true,
|
|
||||||
integrationId: "int-1",
|
|
||||||
integrationType: "github",
|
|
||||||
integrationName: "GitHub",
|
|
||||||
oauthConnect: true,
|
|
||||||
title: "GitHub link",
|
|
||||||
description: "github.com/acme/repo/issues/42",
|
|
||||||
};
|
|
||||||
|
|
||||||
function createWrapper(loggedIn: boolean) {
|
|
||||||
const store = createStore();
|
|
||||||
if (loggedIn) {
|
|
||||||
store.set(currentUserAtom, { user: { id: "user-1" } } as any);
|
|
||||||
}
|
|
||||||
const queryClient = new QueryClient({
|
|
||||||
defaultOptions: { queries: { retry: false } },
|
|
||||||
});
|
|
||||||
return ({ children }: { children: ReactNode }) => (
|
|
||||||
<Provider store={store}>
|
|
||||||
<QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
|
|
||||||
</Provider>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
describe("useUnfurl", () => {
|
|
||||||
beforeEach(() => {
|
|
||||||
localStorage.clear();
|
|
||||||
vi.resetAllMocks();
|
|
||||||
});
|
|
||||||
|
|
||||||
it("never fetches for anonymous viewers and reports anonymous", () => {
|
|
||||||
const { result } = renderHook(() => useUnfurl(ISSUE_URL), {
|
|
||||||
wrapper: createWrapper(false),
|
|
||||||
});
|
|
||||||
|
|
||||||
expect(result.current.state).toBe("anonymous");
|
|
||||||
expect(mockedUnfurlUrl).not.toHaveBeenCalled();
|
|
||||||
});
|
|
||||||
|
|
||||||
it("starts loading then exposes the unfurl result", async () => {
|
|
||||||
mockedUnfurlUrl.mockResolvedValue(loadedResult);
|
|
||||||
|
|
||||||
const { result } = renderHook(() => useUnfurl(ISSUE_URL), {
|
|
||||||
wrapper: createWrapper(true),
|
|
||||||
});
|
|
||||||
|
|
||||||
expect(result.current.state).toBe("loading");
|
|
||||||
await waitFor(() => expect(result.current.state).toBe("loaded"));
|
|
||||||
expect(
|
|
||||||
result.current.state === "loaded" && result.current.data,
|
|
||||||
).toEqual(loadedResult);
|
|
||||||
expect(mockedUnfurlUrl).toHaveBeenCalledWith({ url: ISSUE_URL });
|
|
||||||
});
|
|
||||||
|
|
||||||
it("maps a needsConnection response without treating it as an error", async () => {
|
|
||||||
mockedUnfurlUrl.mockResolvedValue(needsConnectionResult);
|
|
||||||
|
|
||||||
const { result } = renderHook(() => useUnfurl(ISSUE_URL), {
|
|
||||||
wrapper: createWrapper(true),
|
|
||||||
});
|
|
||||||
|
|
||||||
await waitFor(() =>
|
|
||||||
expect(result.current.state).toBe("needsConnection"),
|
|
||||||
);
|
|
||||||
expect(
|
|
||||||
result.current.state === "needsConnection" &&
|
|
||||||
result.current.needsConnection,
|
|
||||||
).toEqual(needsConnectionResult);
|
|
||||||
});
|
|
||||||
|
|
||||||
it("maps a null result (no matching provider) to error", async () => {
|
|
||||||
mockedUnfurlUrl.mockResolvedValue(null);
|
|
||||||
|
|
||||||
const { result } = renderHook(() => useUnfurl(ISSUE_URL), {
|
|
||||||
wrapper: createWrapper(true),
|
|
||||||
});
|
|
||||||
|
|
||||||
await waitFor(() => expect(result.current.state).toBe("error"));
|
|
||||||
});
|
|
||||||
|
|
||||||
it("maps a rejected request to error", async () => {
|
|
||||||
mockedUnfurlUrl.mockRejectedValue(new Error("boom"));
|
|
||||||
|
|
||||||
const { result } = renderHook(() => useUnfurl(ISSUE_URL), {
|
|
||||||
wrapper: createWrapper(true),
|
|
||||||
});
|
|
||||||
|
|
||||||
await waitFor(() => expect(result.current.state).toBe("error"));
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@@ -1,47 +0,0 @@
|
|||||||
import { useQuery } from "@tanstack/react-query";
|
|
||||||
import { useAtomValue } from "jotai";
|
|
||||||
import { currentUserAtom } from "@/features/user/atoms/current-user-atom";
|
|
||||||
import { unfurlUrl } from "@/features/integration/services/integration-service";
|
|
||||||
import {
|
|
||||||
UnfurlNeedsConnection,
|
|
||||||
UnfurlResult,
|
|
||||||
} from "@/features/integration/types/integration.types";
|
|
||||||
|
|
||||||
const UNFURL_STALE_TIME = 5 * 60 * 1000; // mirrors the server-side Redis TTL
|
|
||||||
|
|
||||||
export type UnfurlState =
|
|
||||||
| { state: "anonymous" }
|
|
||||||
| { state: "loading" }
|
|
||||||
| { state: "error" }
|
|
||||||
| { state: "needsConnection"; needsConnection: UnfurlNeedsConnection }
|
|
||||||
| { state: "loaded"; data: UnfurlResult };
|
|
||||||
|
|
||||||
// Resolves the unfurl per viewer at render time. Nothing is written back into
|
|
||||||
// the document, so third-party permissions are enforced on every view:
|
|
||||||
// unconnected viewers get needsConnection and anonymous viewers never fetch.
|
|
||||||
export function useUnfurl(url: string): UnfurlState {
|
|
||||||
const currentUser = useAtomValue(currentUserAtom);
|
|
||||||
const isAuthenticated = Boolean(currentUser?.user);
|
|
||||||
|
|
||||||
const query = useQuery({
|
|
||||||
queryKey: ["unfurl", url],
|
|
||||||
queryFn: () => unfurlUrl({ url }),
|
|
||||||
enabled: isAuthenticated && Boolean(url),
|
|
||||||
staleTime: UNFURL_STALE_TIME,
|
|
||||||
retry: false,
|
|
||||||
});
|
|
||||||
|
|
||||||
if (!isAuthenticated || !url) {
|
|
||||||
return { state: "anonymous" };
|
|
||||||
}
|
|
||||||
if (query.isPending) {
|
|
||||||
return { state: "loading" };
|
|
||||||
}
|
|
||||||
if (query.isError || !query.data) {
|
|
||||||
return { state: "error" };
|
|
||||||
}
|
|
||||||
if ("needsConnection" in query.data) {
|
|
||||||
return { state: "needsConnection", needsConnection: query.data };
|
|
||||||
}
|
|
||||||
return { state: "loaded", data: query.data };
|
|
||||||
}
|
|
||||||
@@ -10,7 +10,6 @@ import { Superscript } from "@tiptap/extension-superscript";
|
|||||||
import SubScript from "@tiptap/extension-subscript";
|
import SubScript from "@tiptap/extension-subscript";
|
||||||
import { Typography } from "@tiptap/extension-typography";
|
import { Typography } from "@tiptap/extension-typography";
|
||||||
import { TextStyle } from "@tiptap/extension-text-style";
|
import { TextStyle } from "@tiptap/extension-text-style";
|
||||||
import { Color } from "@tiptap/extension-color";
|
|
||||||
import { Youtube } from "@tiptap/extension-youtube";
|
import { Youtube } from "@tiptap/extension-youtube";
|
||||||
import SlashCommand, {
|
import SlashCommand, {
|
||||||
SlashCommandExtension as Command,
|
SlashCommandExtension as Command,
|
||||||
@@ -54,11 +53,10 @@ import {
|
|||||||
Subpages,
|
Subpages,
|
||||||
Heading,
|
Heading,
|
||||||
Highlight,
|
Highlight,
|
||||||
|
Color,
|
||||||
Indent,
|
Indent,
|
||||||
UniqueID,
|
UniqueID,
|
||||||
SharedStorage,
|
SharedStorage,
|
||||||
IntegrationLink,
|
|
||||||
IntegrationMention,
|
|
||||||
Columns,
|
Columns,
|
||||||
Column,
|
Column,
|
||||||
Status,
|
Status,
|
||||||
@@ -97,9 +95,6 @@ import ExcalidrawView from "@/features/editor/components/excalidraw/excalidraw-v
|
|||||||
import EmbedView from "@/features/editor/components/embed/embed-view.tsx";
|
import EmbedView from "@/features/editor/components/embed/embed-view.tsx";
|
||||||
import PdfView from "@/features/editor/components/pdf/pdf-view.tsx";
|
import PdfView from "@/features/editor/components/pdf/pdf-view.tsx";
|
||||||
import SubpagesView from "@/features/editor/components/subpages/subpages-view.tsx";
|
import SubpagesView from "@/features/editor/components/subpages/subpages-view.tsx";
|
||||||
import IntegrationLinkView from "@/features/editor/components/integration-link/integration-link-view.tsx";
|
|
||||||
import IntegrationMentionView from "@/features/editor/components/integration-link/integration-mention-view.tsx";
|
|
||||||
import { IntegrationPasteMenuExtension } from "@/features/editor/extensions/integration-paste-menu";
|
|
||||||
import TransclusionView from "@/features/editor/components/transclusion/transclusion-view.tsx";
|
import TransclusionView from "@/features/editor/components/transclusion/transclusion-view.tsx";
|
||||||
import TransclusionReferenceView from "@/features/editor/components/transclusion/transclusion-reference-view.tsx";
|
import TransclusionReferenceView from "@/features/editor/components/transclusion/transclusion-reference-view.tsx";
|
||||||
import { BaseEmbedView } from "@/features/editor/components/base-embed/base-embed-view.tsx";
|
import { BaseEmbedView } from "@/features/editor/components/base-embed/base-embed-view.tsx";
|
||||||
@@ -392,13 +387,6 @@ export const mainExtensions = [
|
|||||||
Subpages.configure({
|
Subpages.configure({
|
||||||
view: SubpagesView,
|
view: SubpagesView,
|
||||||
}),
|
}),
|
||||||
IntegrationLink.configure({
|
|
||||||
view: IntegrationLinkView,
|
|
||||||
}),
|
|
||||||
IntegrationMention.configure({
|
|
||||||
view: IntegrationMentionView,
|
|
||||||
}),
|
|
||||||
IntegrationPasteMenuExtension,
|
|
||||||
Status.configure({
|
Status.configure({
|
||||||
view: StatusView,
|
view: StatusView,
|
||||||
}),
|
}),
|
||||||
|
|||||||
@@ -1,44 +0,0 @@
|
|||||||
import { Extension } from "@tiptap/core";
|
|
||||||
import { Plugin, PluginKey } from "@tiptap/pm/state";
|
|
||||||
|
|
||||||
export type IntegrationPasteMenuState = { pos: number } | null;
|
|
||||||
|
|
||||||
export const integrationPasteMenuKey = new PluginKey<IntegrationPasteMenuState>(
|
|
||||||
"integrationPasteMenu",
|
|
||||||
);
|
|
||||||
|
|
||||||
// Holds the position of a just-pasted integration node so the "Paste as"
|
|
||||||
// menu can anchor to it. Any other edit or selection change dismisses it.
|
|
||||||
export const IntegrationPasteMenuExtension = Extension.create({
|
|
||||||
name: "integrationPasteMenu",
|
|
||||||
|
|
||||||
addProseMirrorPlugins() {
|
|
||||||
return [
|
|
||||||
new Plugin({
|
|
||||||
key: integrationPasteMenuKey,
|
|
||||||
state: {
|
|
||||||
init: (): IntegrationPasteMenuState => null,
|
|
||||||
apply(tr, prev): IntegrationPasteMenuState {
|
|
||||||
const meta = tr.getMeta(integrationPasteMenuKey);
|
|
||||||
if (meta !== undefined) return meta;
|
|
||||||
if (!prev) return null;
|
|
||||||
// Clicking or typing elsewhere dismisses.
|
|
||||||
if (tr.selectionSet) return null;
|
|
||||||
// Structural follow-ups (unique-id assignment, trailing node)
|
|
||||||
// keep the menu anchored: remap and re-validate the position.
|
|
||||||
if (tr.docChanged) {
|
|
||||||
const pos = tr.mapping.map(prev.pos);
|
|
||||||
const node = tr.doc.nodeAt(pos);
|
|
||||||
const isIntegrationNode =
|
|
||||||
node &&
|
|
||||||
(node.type.name === "integrationLink" ||
|
|
||||||
node.type.name === "integrationMention");
|
|
||||||
return isIntegrationNode ? { pos } : null;
|
|
||||||
}
|
|
||||||
return prev;
|
|
||||||
},
|
|
||||||
},
|
|
||||||
}),
|
|
||||||
];
|
|
||||||
},
|
|
||||||
});
|
|
||||||
@@ -75,8 +75,6 @@ import { useEditorScroll } from "./hooks/use-editor-scroll";
|
|||||||
import { EditorAiMenu } from "@/ee/ai/components/editor/ai-menu/ai-menu";
|
import { EditorAiMenu } from "@/ee/ai/components/editor/ai-menu/ai-menu";
|
||||||
import { EditorLinkMenu } from "@/features/editor/components/link/link-menu";
|
import { EditorLinkMenu } from "@/features/editor/components/link/link-menu";
|
||||||
import ColumnsMenu from "@/features/editor/components/columns/columns-menu.tsx";
|
import ColumnsMenu from "@/features/editor/components/columns/columns-menu.tsx";
|
||||||
import { IntegrationPasteMenu } from "@/features/editor/components/integration-link/integration-paste-menu.tsx";
|
|
||||||
import { getInstalledIntegrations } from "@/features/integration/services/integration-service";
|
|
||||||
import { TransclusionLookupProvider } from "@/features/editor/components/transclusion/transclusion-lookup-context";
|
import { TransclusionLookupProvider } from "@/features/editor/components/transclusion/transclusion-lookup-context";
|
||||||
import { useTranslation } from "react-i18next";
|
import { useTranslation } from "react-i18next";
|
||||||
import {
|
import {
|
||||||
@@ -328,18 +326,6 @@ function CollabPageEditor({
|
|||||||
[pageId, editable, extensions],
|
[pageId, editable, extensions],
|
||||||
);
|
);
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
// Warm the cache the paste handler reads to decide whether a pasted
|
|
||||||
// integration url becomes a card or stays an ordinary link. gcTime
|
|
||||||
// Infinity: no observer holds this query, and the default 5-minute gc
|
|
||||||
// would evict it mid-session, silently downgrading pastes to plain links.
|
|
||||||
queryClient.prefetchQuery({
|
|
||||||
queryKey: ["installed-integrations"],
|
|
||||||
queryFn: getInstalledIntegrations,
|
|
||||||
gcTime: Infinity,
|
|
||||||
});
|
|
||||||
}, []);
|
|
||||||
|
|
||||||
useLayoutEffect(() => {
|
useLayoutEffect(() => {
|
||||||
if (editor && !editor.isDestroyed) {
|
if (editor && !editor.isDestroyed) {
|
||||||
// @ts-ignore
|
// @ts-ignore
|
||||||
@@ -468,7 +454,6 @@ function CollabPageEditor({
|
|||||||
<ExcalidrawMenu editor={editor} />
|
<ExcalidrawMenu editor={editor} />
|
||||||
<DrawioMenu editor={editor} />
|
<DrawioMenu editor={editor} />
|
||||||
<ColumnsMenu editor={editor} />
|
<ColumnsMenu editor={editor} />
|
||||||
<IntegrationPasteMenu editor={editor} />
|
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
{editor && !editorIsEditable && (editable || canComment) && (
|
{editor && !editorIsEditable && (editable || canComment) && (
|
||||||
|
|||||||
@@ -1,6 +1,46 @@
|
|||||||
/* Highlight colors with dark mode support */
|
/* Highlight colors with dark mode support */
|
||||||
|
|
||||||
.ProseMirror {
|
.ProseMirror {
|
||||||
|
@mixin dark {
|
||||||
|
/* Arbitrary (imported) colors have no hand-tuned dark variant, so derive
|
||||||
|
one: cap lightness and chroma so the fill sits on the dark surface.
|
||||||
|
Our own palette opts out and keeps the values below. */
|
||||||
|
mark[data-color]:not(
|
||||||
|
[data-color="#98d8f2" i],
|
||||||
|
[data-color="#7edb6c" i],
|
||||||
|
[data-color="#e0d6ed" i],
|
||||||
|
[data-color="#ffc6c2" i],
|
||||||
|
[data-color="#faf594" i],
|
||||||
|
[data-color="#f5c8a9" i],
|
||||||
|
[data-color="#f5cfe0" i],
|
||||||
|
[data-color="#dfdfd7" i],
|
||||||
|
[data-color="#d7c4b7" i]
|
||||||
|
) {
|
||||||
|
background-color: oklch(
|
||||||
|
from var(--mark-bg, #fff) min(l, clamp(0.28, calc(1.22 - l), 0.45))
|
||||||
|
min(calc(c * 1.8), 0.09) h
|
||||||
|
) !important;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Imported text colors are picked for a light page and go unreadable on
|
||||||
|
the dark surface, so lift their lightness. */
|
||||||
|
span[data-text-color]:not(
|
||||||
|
[data-text-color="#2563EB" i],
|
||||||
|
[data-text-color="#008A00" i],
|
||||||
|
[data-text-color="#9333EA" i],
|
||||||
|
[data-text-color="#E00000" i],
|
||||||
|
[data-text-color="#EAB308" i],
|
||||||
|
[data-text-color="#FFA500" i],
|
||||||
|
[data-text-color="#BA4081" i],
|
||||||
|
[data-text-color="#A8A29E" i],
|
||||||
|
[data-text-color="#92400E" i]
|
||||||
|
) {
|
||||||
|
color: oklch(
|
||||||
|
from var(--text-color, currentcolor) max(l, 0.72) min(c, 0.16) h
|
||||||
|
) !important;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/* Blue */
|
/* Blue */
|
||||||
mark[data-color="#98d8f2"] {
|
mark[data-color="#98d8f2"] {
|
||||||
background-color: light-dark(
|
background-color: light-dark(
|
||||||
|
|||||||
@@ -86,6 +86,16 @@
|
|||||||
.ProseMirror {
|
.ProseMirror {
|
||||||
table {
|
table {
|
||||||
@mixin dark {
|
@mixin dark {
|
||||||
|
/* Arbitrary (imported) colors: derive a dark variant; the hand-tuned
|
||||||
|
palette rules below override this for native colors. */
|
||||||
|
td[data-background-color],
|
||||||
|
th[data-background-color] {
|
||||||
|
background-color: oklch(
|
||||||
|
from var(--cell-bg, #fff) min(l, clamp(0.28, calc(1.22 - l), 0.45))
|
||||||
|
min(calc(c * 1.8), 0.09) h
|
||||||
|
) !important;
|
||||||
|
}
|
||||||
|
|
||||||
/* Blue */
|
/* Blue */
|
||||||
td[data-background-color="#b4d5ff"],
|
td[data-background-color="#b4d5ff"],
|
||||||
th[data-background-color="#b4d5ff"] {
|
th[data-background-color="#b4d5ff"] {
|
||||||
|
|||||||
@@ -1,93 +0,0 @@
|
|||||||
import { Group, Text, Button, Box } from "@mantine/core";
|
|
||||||
import { useTranslation } from "react-i18next";
|
|
||||||
import { IntegrationDefinition, UserConnection } from "../types/integration.types";
|
|
||||||
import { getIntegrationIcon } from "./integration-icons";
|
|
||||||
|
|
||||||
type ConnectionRowProps = {
|
|
||||||
definition: IntegrationDefinition;
|
|
||||||
connection?: UserConnection;
|
|
||||||
onConnect: (type: string) => void;
|
|
||||||
onDisconnect: (integrationId: string) => void;
|
|
||||||
disconnectingId?: string;
|
|
||||||
};
|
|
||||||
|
|
||||||
export default function ConnectionRow({
|
|
||||||
definition,
|
|
||||||
connection,
|
|
||||||
onConnect,
|
|
||||||
onDisconnect,
|
|
||||||
disconnectingId,
|
|
||||||
}: ConnectionRowProps) {
|
|
||||||
const { t } = useTranslation();
|
|
||||||
const connectedLabel =
|
|
||||||
connection?.providerDisplayName || connection?.providerUserId;
|
|
||||||
|
|
||||||
return (
|
|
||||||
<Box
|
|
||||||
py="sm"
|
|
||||||
px="xs"
|
|
||||||
style={{
|
|
||||||
borderBottom: "1px solid var(--mantine-color-default-border)",
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
<Group justify="space-between" wrap="nowrap">
|
|
||||||
<Group gap="sm" wrap="nowrap">
|
|
||||||
{getIntegrationIcon(definition.type, 28)}
|
|
||||||
<div>
|
|
||||||
<Text size="sm" fw={500}>
|
|
||||||
{definition.name}
|
|
||||||
</Text>
|
|
||||||
<Text size="xs" c="dimmed">
|
|
||||||
{definition.description}
|
|
||||||
</Text>
|
|
||||||
</div>
|
|
||||||
</Group>
|
|
||||||
|
|
||||||
<Group gap="sm" wrap="nowrap" style={{ flexShrink: 0 }}>
|
|
||||||
{connection ? (
|
|
||||||
<>
|
|
||||||
{connection.invalidatedAt ? (
|
|
||||||
<>
|
|
||||||
<Text size="xs" c="orange">
|
|
||||||
{t("Connection expired")}
|
|
||||||
</Text>
|
|
||||||
<Button
|
|
||||||
size="xs"
|
|
||||||
variant="light"
|
|
||||||
color="orange"
|
|
||||||
onClick={() => onConnect(definition.type)}
|
|
||||||
>
|
|
||||||
{t("Reconnect")}
|
|
||||||
</Button>
|
|
||||||
</>
|
|
||||||
) : (
|
|
||||||
<Text size="xs" c="green">
|
|
||||||
{connectedLabel
|
|
||||||
? t("Connected as {{label}}", { label: connectedLabel })
|
|
||||||
: t("Connected")}
|
|
||||||
</Text>
|
|
||||||
)}
|
|
||||||
<Button
|
|
||||||
size="xs"
|
|
||||||
variant="subtle"
|
|
||||||
color="red"
|
|
||||||
onClick={() => onDisconnect(connection.integrationId)}
|
|
||||||
loading={disconnectingId === connection.integrationId}
|
|
||||||
>
|
|
||||||
{t("Disconnect")}
|
|
||||||
</Button>
|
|
||||||
</>
|
|
||||||
) : (
|
|
||||||
<Button
|
|
||||||
size="xs"
|
|
||||||
variant="light"
|
|
||||||
onClick={() => onConnect(definition.type)}
|
|
||||||
>
|
|
||||||
{t("Connect")}
|
|
||||||
</Button>
|
|
||||||
)}
|
|
||||||
</Group>
|
|
||||||
</Group>
|
|
||||||
</Box>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -1,30 +0,0 @@
|
|||||||
import { ReactNode } from "react";
|
|
||||||
import {
|
|
||||||
FigmaIcon,
|
|
||||||
GithubIcon,
|
|
||||||
GitlabIcon,
|
|
||||||
GoogleDocsIcon,
|
|
||||||
JiraIcon,
|
|
||||||
LinearIcon,
|
|
||||||
SlackIcon,
|
|
||||||
} from "@/components/icons";
|
|
||||||
import { IconPuzzle } from "@tabler/icons-react";
|
|
||||||
|
|
||||||
const integrationIconMap: Record<string, (size: number) => ReactNode> = {
|
|
||||||
github: (size) => <GithubIcon size={size} />,
|
|
||||||
gitlab: (size) => <GitlabIcon size={size} />,
|
|
||||||
slack: (size) => <SlackIcon size={size} />,
|
|
||||||
linear: (size) => <LinearIcon size={size} />,
|
|
||||||
jira: (size) => <JiraIcon size={size} />,
|
|
||||||
figma: (size) => <FigmaIcon size={size} />,
|
|
||||||
google_docs: (size) => <GoogleDocsIcon size={size} />,
|
|
||||||
};
|
|
||||||
|
|
||||||
export function getIntegrationIcon(
|
|
||||||
type: string,
|
|
||||||
size: number,
|
|
||||||
): ReactNode {
|
|
||||||
const renderIcon = integrationIconMap[type];
|
|
||||||
if (renderIcon) return renderIcon(size);
|
|
||||||
return <IconPuzzle size={size} stroke={1.5} />;
|
|
||||||
}
|
|
||||||
@@ -1,66 +0,0 @@
|
|||||||
import { Box, Group, Skeleton, Stack } from "@mantine/core";
|
|
||||||
|
|
||||||
const TITLE_WIDTHS = [64, 52, 60, 44, 58, 96, 56];
|
|
||||||
const DESCRIPTION_WIDTHS = [300, 250, 320, 180, 290, 270, 260];
|
|
||||||
|
|
||||||
type IntegrationListSkeletonProps = {
|
|
||||||
rows?: number;
|
|
||||||
withBadges?: boolean;
|
|
||||||
};
|
|
||||||
|
|
||||||
export default function IntegrationListSkeleton({
|
|
||||||
rows = 7,
|
|
||||||
withBadges = true,
|
|
||||||
}: IntegrationListSkeletonProps) {
|
|
||||||
return (
|
|
||||||
<Stack gap={0} aria-hidden="true">
|
|
||||||
{Array.from({ length: rows }, (_, index) => (
|
|
||||||
<Box
|
|
||||||
key={index}
|
|
||||||
py="sm"
|
|
||||||
px="xs"
|
|
||||||
style={{
|
|
||||||
borderBottom: "1px solid var(--mantine-color-default-border)",
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
<Group justify="space-between" wrap="nowrap">
|
|
||||||
<Group gap="sm" wrap="nowrap" style={{ flex: 1, minWidth: 0 }}>
|
|
||||||
<Skeleton height={28} circle style={{ flexShrink: 0 }} />
|
|
||||||
<Stack gap={2} style={{ minWidth: 0 }}>
|
|
||||||
<Group gap="xs" wrap="nowrap" h={20}>
|
|
||||||
<Skeleton
|
|
||||||
height={12}
|
|
||||||
width={TITLE_WIDTHS[index % TITLE_WIDTHS.length]}
|
|
||||||
radius="xs"
|
|
||||||
/>
|
|
||||||
{withBadges && (
|
|
||||||
<>
|
|
||||||
<Skeleton height={16} width={52} radius="xl" />
|
|
||||||
<Skeleton height={16} width={52} radius="xl" />
|
|
||||||
</>
|
|
||||||
)}
|
|
||||||
</Group>
|
|
||||||
<Group h={17}>
|
|
||||||
<Skeleton
|
|
||||||
height={10}
|
|
||||||
width={
|
|
||||||
DESCRIPTION_WIDTHS[index % DESCRIPTION_WIDTHS.length]
|
|
||||||
}
|
|
||||||
maw="100%"
|
|
||||||
radius="xs"
|
|
||||||
/>
|
|
||||||
</Group>
|
|
||||||
</Stack>
|
|
||||||
</Group>
|
|
||||||
<Skeleton
|
|
||||||
height={30}
|
|
||||||
width={64}
|
|
||||||
radius="sm"
|
|
||||||
style={{ flexShrink: 0 }}
|
|
||||||
/>
|
|
||||||
</Group>
|
|
||||||
</Box>
|
|
||||||
))}
|
|
||||||
</Stack>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -1,93 +0,0 @@
|
|||||||
import {
|
|
||||||
Group,
|
|
||||||
Text,
|
|
||||||
Badge,
|
|
||||||
Button,
|
|
||||||
Box,
|
|
||||||
Stack,
|
|
||||||
Tooltip,
|
|
||||||
} from "@mantine/core";
|
|
||||||
import { useTranslation } from "react-i18next";
|
|
||||||
import {
|
|
||||||
IntegrationDefinition,
|
|
||||||
Integration,
|
|
||||||
} from "../types/integration.types";
|
|
||||||
import { getIntegrationIcon } from "./integration-icons";
|
|
||||||
import { useHasFeature } from "@/ee/hooks/use-feature";
|
|
||||||
import { Feature } from "@/ee/features";
|
|
||||||
import { useUpgradeLabel } from "@/ee/hooks/use-upgrade-label";
|
|
||||||
|
|
||||||
type IntegrationRowProps = {
|
|
||||||
definition: IntegrationDefinition;
|
|
||||||
installation?: Integration;
|
|
||||||
onInstall: (type: string) => void;
|
|
||||||
onUninstall: (integrationId: string) => void;
|
|
||||||
};
|
|
||||||
|
|
||||||
export default function IntegrationRow({
|
|
||||||
definition,
|
|
||||||
installation,
|
|
||||||
onInstall,
|
|
||||||
onUninstall,
|
|
||||||
}: IntegrationRowProps) {
|
|
||||||
const { t } = useTranslation();
|
|
||||||
const isInstalled = !!installation;
|
|
||||||
const hasAccess = useHasFeature(Feature.INTEGRATIONS);
|
|
||||||
const locked = !!definition.requiresLicense && !hasAccess;
|
|
||||||
const upgradeLabel = useUpgradeLabel();
|
|
||||||
|
|
||||||
return (
|
|
||||||
<Box
|
|
||||||
py="sm"
|
|
||||||
px="xs"
|
|
||||||
style={{
|
|
||||||
borderBottom: "1px solid var(--mantine-color-default-border)",
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
<Group justify="space-between" wrap="nowrap">
|
|
||||||
<Group gap="sm" wrap="nowrap" style={{ flex: 1, minWidth: 0 }}>
|
|
||||||
{getIntegrationIcon(definition.type, 28)}
|
|
||||||
<Stack gap={2} style={{ minWidth: 0 }}>
|
|
||||||
<Group gap="xs" wrap="nowrap">
|
|
||||||
<Text size="sm" fw={500}>
|
|
||||||
{definition.name}
|
|
||||||
</Text>
|
|
||||||
{locked && (
|
|
||||||
<Badge size="xs" variant="light" color="violet">
|
|
||||||
{t("Paid")}
|
|
||||||
</Badge>
|
|
||||||
)}
|
|
||||||
</Group>
|
|
||||||
<Text size="xs" c="dimmed" truncate>
|
|
||||||
{definition.description}
|
|
||||||
</Text>
|
|
||||||
</Stack>
|
|
||||||
</Group>
|
|
||||||
|
|
||||||
<Group gap="sm" wrap="nowrap" style={{ flexShrink: 0 }}>
|
|
||||||
{isInstalled ? (
|
|
||||||
<Button
|
|
||||||
size="xs"
|
|
||||||
variant="subtle"
|
|
||||||
color="red"
|
|
||||||
onClick={() => onUninstall(installation.id)}
|
|
||||||
>
|
|
||||||
{t("Uninstall")}
|
|
||||||
</Button>
|
|
||||||
) : (
|
|
||||||
<Tooltip label={upgradeLabel} disabled={!locked}>
|
|
||||||
<Button
|
|
||||||
size="xs"
|
|
||||||
variant="light"
|
|
||||||
disabled={locked}
|
|
||||||
onClick={() => onInstall(definition.type)}
|
|
||||||
>
|
|
||||||
{t("Install")}
|
|
||||||
</Button>
|
|
||||||
</Tooltip>
|
|
||||||
)}
|
|
||||||
</Group>
|
|
||||||
</Group>
|
|
||||||
</Box>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -1,134 +0,0 @@
|
|||||||
import { Text, Alert, Stack } from "@mantine/core";
|
|
||||||
import { modals } from "@mantine/modals";
|
|
||||||
import { Helmet } from "react-helmet-async";
|
|
||||||
import { useTranslation } from "react-i18next";
|
|
||||||
import { notifications } from "@mantine/notifications";
|
|
||||||
import { getAppName } from "@/lib/config";
|
|
||||||
import SettingsTitle from "@/components/settings/settings-title";
|
|
||||||
import ConnectionRow from "../components/connection-row";
|
|
||||||
import IntegrationListSkeleton from "../components/integration-list-skeleton";
|
|
||||||
import {
|
|
||||||
useAvailableIntegrations,
|
|
||||||
useInstalledIntegrations,
|
|
||||||
useMyConnections,
|
|
||||||
useDisconnectIntegration,
|
|
||||||
} from "../queries/integration-query";
|
|
||||||
import * as integrationService from "../services/integration-service";
|
|
||||||
|
|
||||||
export default function Connections() {
|
|
||||||
const { t } = useTranslation();
|
|
||||||
const { data: available, isLoading: loadingAvailable } =
|
|
||||||
useAvailableIntegrations();
|
|
||||||
const { data: installed, isLoading: loadingInstalled } =
|
|
||||||
useInstalledIntegrations();
|
|
||||||
const { data: myConnections, isLoading: loadingConnections } =
|
|
||||||
useMyConnections();
|
|
||||||
const disconnectMutation = useDisconnectIntegration();
|
|
||||||
|
|
||||||
const isLoading = loadingAvailable || loadingInstalled || loadingConnections;
|
|
||||||
|
|
||||||
const handleConnect = async (type: string) => {
|
|
||||||
const integration = installed?.find((i) => i.type === type);
|
|
||||||
if (!integration) return;
|
|
||||||
|
|
||||||
try {
|
|
||||||
// Workspace-scoped providers default the OAuth return to the admin
|
|
||||||
// integrations page; members connecting here must come back here.
|
|
||||||
const result = await integrationService.getOAuthAuthorizeUrl({
|
|
||||||
integrationId: integration.id,
|
|
||||||
returnPath: "/settings/account/connections",
|
|
||||||
});
|
|
||||||
window.location.href = result.authorizationUrl;
|
|
||||||
} catch (error) {
|
|
||||||
const errorMessage = error["response"]?.data?.message;
|
|
||||||
notifications.show({
|
|
||||||
message: errorMessage || t("Failed to start OAuth connection"),
|
|
||||||
color: "red",
|
|
||||||
});
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleDisconnect = (integrationId: string) => {
|
|
||||||
const installation = installed?.find((i) => i.id === integrationId);
|
|
||||||
const name =
|
|
||||||
available?.find((d) => d.type === installation?.type)?.name ??
|
|
||||||
installation?.type ??
|
|
||||||
"";
|
|
||||||
modals.openConfirmModal({
|
|
||||||
title: t("Disconnect {{name}}", { name }),
|
|
||||||
centered: true,
|
|
||||||
children: (
|
|
||||||
<Text size="sm">
|
|
||||||
{t(
|
|
||||||
"This disconnects your {{name}} account. Links are not enriched for you until you reconnect.",
|
|
||||||
{ name },
|
|
||||||
)}
|
|
||||||
</Text>
|
|
||||||
),
|
|
||||||
labels: { confirm: t("Disconnect"), cancel: t("Cancel") },
|
|
||||||
confirmProps: { color: "red" },
|
|
||||||
onConfirm: () => disconnectMutation.mutate({ integrationId }),
|
|
||||||
});
|
|
||||||
};
|
|
||||||
|
|
||||||
// Only the row being disconnected shows a loader; isPending alone is shared by every row.
|
|
||||||
const disconnectingId = disconnectMutation.isPending
|
|
||||||
? disconnectMutation.variables?.integrationId
|
|
||||||
: undefined;
|
|
||||||
|
|
||||||
const error = new URLSearchParams(window.location.search).get("error");
|
|
||||||
|
|
||||||
return (
|
|
||||||
<>
|
|
||||||
<Helmet>
|
|
||||||
<title>
|
|
||||||
{t("Connections")} - {getAppName()}
|
|
||||||
</title>
|
|
||||||
</Helmet>
|
|
||||||
|
|
||||||
<SettingsTitle title={t("Connections")} />
|
|
||||||
|
|
||||||
<Text size="sm" c="dimmed" mb="md">
|
|
||||||
{t("Manage the apps you have connected to your account.")}
|
|
||||||
</Text>
|
|
||||||
|
|
||||||
{error === "oauth_failed" && (
|
|
||||||
<Alert color="red" mb="md">
|
|
||||||
{t("OAuth connection failed. Please try again.")}
|
|
||||||
</Alert>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{isLoading ? (
|
|
||||||
<IntegrationListSkeleton rows={3} withBadges={false} />
|
|
||||||
) : !available?.length ? (
|
|
||||||
<Text c="dimmed" size="sm">
|
|
||||||
{t("No integrations available.")}
|
|
||||||
</Text>
|
|
||||||
) : (
|
|
||||||
<Stack gap={0}>
|
|
||||||
{available
|
|
||||||
.filter((def) => {
|
|
||||||
if (!def.capabilities.includes("oauth")) return false;
|
|
||||||
return installed?.some((i) => i.type === def.type);
|
|
||||||
})
|
|
||||||
.map((def) => {
|
|
||||||
const connection = myConnections?.find(
|
|
||||||
(c) => c.type === def.type,
|
|
||||||
);
|
|
||||||
|
|
||||||
return (
|
|
||||||
<ConnectionRow
|
|
||||||
key={def.type}
|
|
||||||
definition={def}
|
|
||||||
connection={connection}
|
|
||||||
onConnect={handleConnect}
|
|
||||||
onDisconnect={handleDisconnect}
|
|
||||||
disconnectingId={disconnectingId}
|
|
||||||
/>
|
|
||||||
);
|
|
||||||
})}
|
|
||||||
</Stack>
|
|
||||||
)}
|
|
||||||
</>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -1,126 +0,0 @@
|
|||||||
import { Text, Alert, Stack } from "@mantine/core";
|
|
||||||
import { modals } from "@mantine/modals";
|
|
||||||
import { Helmet } from "react-helmet-async";
|
|
||||||
import { useTranslation } from "react-i18next";
|
|
||||||
import { useCallback } from "react";
|
|
||||||
import { getAppName } from "@/lib/config";
|
|
||||||
import SettingsTitle from "@/components/settings/settings-title";
|
|
||||||
import IntegrationRow from "../components/integration-row";
|
|
||||||
import IntegrationListSkeleton from "../components/integration-list-skeleton";
|
|
||||||
import {
|
|
||||||
useAvailableIntegrations,
|
|
||||||
useInstalledIntegrations,
|
|
||||||
useInstallIntegration,
|
|
||||||
useUninstallIntegration,
|
|
||||||
} from "../queries/integration-query";
|
|
||||||
import { getOAuthInstallUrl } from "../services/integration-service";
|
|
||||||
import { notifications } from "@mantine/notifications";
|
|
||||||
|
|
||||||
export default function Integrations() {
|
|
||||||
const { t } = useTranslation();
|
|
||||||
const { data: available, isLoading: loadingAvailable } =
|
|
||||||
useAvailableIntegrations();
|
|
||||||
const { data: installed, isLoading: loadingInstalled } =
|
|
||||||
useInstalledIntegrations();
|
|
||||||
const installMutation = useInstallIntegration();
|
|
||||||
const uninstallMutation = useUninstallIntegration();
|
|
||||||
|
|
||||||
const handleInstall = useCallback(
|
|
||||||
async (type: string) => {
|
|
||||||
const definition = available?.find((d) => d.type === type);
|
|
||||||
|
|
||||||
// OAuth providers only become installed once the admin's OAuth
|
|
||||||
// callback succeeds; a cancelled or failed flow persists nothing.
|
|
||||||
if (definition?.capabilities?.includes("oauth")) {
|
|
||||||
try {
|
|
||||||
const { authorizationUrl } = await getOAuthInstallUrl({ type });
|
|
||||||
window.location.href = authorizationUrl;
|
|
||||||
} catch (err: any) {
|
|
||||||
notifications.show({
|
|
||||||
message:
|
|
||||||
err?.response?.data?.message ?? t("Failed to start installation"),
|
|
||||||
color: "red",
|
|
||||||
});
|
|
||||||
}
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
installMutation.mutate({ type });
|
|
||||||
},
|
|
||||||
[installMutation, available, t],
|
|
||||||
);
|
|
||||||
|
|
||||||
const handleUninstall = useCallback(
|
|
||||||
(integrationId: string) => {
|
|
||||||
const installation = installed?.find((i) => i.id === integrationId);
|
|
||||||
const name =
|
|
||||||
available?.find((d) => d.type === installation?.type)?.name ??
|
|
||||||
installation?.type ??
|
|
||||||
"";
|
|
||||||
modals.openConfirmModal({
|
|
||||||
title: t("Uninstall {{name}}", { name }),
|
|
||||||
centered: true,
|
|
||||||
children: (
|
|
||||||
<Text size="sm">
|
|
||||||
{t(
|
|
||||||
"This disables the {{name}} integration for the entire workspace. Members' connections are removed and links are not enriched.",
|
|
||||||
{ name },
|
|
||||||
)}
|
|
||||||
</Text>
|
|
||||||
),
|
|
||||||
labels: { confirm: t("Uninstall"), cancel: t("Cancel") },
|
|
||||||
confirmProps: { color: "red" },
|
|
||||||
onConfirm: () => uninstallMutation.mutate({ integrationId }),
|
|
||||||
});
|
|
||||||
},
|
|
||||||
[uninstallMutation, installed, available, t],
|
|
||||||
);
|
|
||||||
|
|
||||||
const isLoading = loadingAvailable || loadingInstalled;
|
|
||||||
const error = new URLSearchParams(window.location.search).get("error");
|
|
||||||
|
|
||||||
return (
|
|
||||||
<>
|
|
||||||
<Helmet>
|
|
||||||
<title>
|
|
||||||
{t("Integrations")} - {getAppName()}
|
|
||||||
</title>
|
|
||||||
</Helmet>
|
|
||||||
|
|
||||||
<SettingsTitle title={t("Integrations")} />
|
|
||||||
|
|
||||||
<Text size="sm" c="dimmed" mb="md">
|
|
||||||
{t("Manage workspace integrations.")}
|
|
||||||
</Text>
|
|
||||||
|
|
||||||
{error === "oauth_failed" && (
|
|
||||||
<Alert color="red" mb="md">
|
|
||||||
{t("OAuth connection failed. Please try again.")}
|
|
||||||
</Alert>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{isLoading ? (
|
|
||||||
<IntegrationListSkeleton />
|
|
||||||
) : !available?.length ? (
|
|
||||||
<Text c="dimmed" size="sm">
|
|
||||||
{t("No integrations available.")}
|
|
||||||
</Text>
|
|
||||||
) : (
|
|
||||||
<Stack gap={0}>
|
|
||||||
{available.map((def) => {
|
|
||||||
const installation = installed?.find((i) => i.type === def.type);
|
|
||||||
return (
|
|
||||||
<IntegrationRow
|
|
||||||
key={def.type}
|
|
||||||
definition={def}
|
|
||||||
installation={installation}
|
|
||||||
onInstall={handleInstall}
|
|
||||||
onUninstall={handleUninstall}
|
|
||||||
/>
|
|
||||||
);
|
|
||||||
})}
|
|
||||||
</Stack>
|
|
||||||
)}
|
|
||||||
</>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -1,112 +0,0 @@
|
|||||||
import { useEffect, useState } from "react";
|
|
||||||
import { useSearchParams, useNavigate } from "react-router-dom";
|
|
||||||
import { Alert, Button, Card, Group, Loader, Stack, Text } from "@mantine/core";
|
|
||||||
import { useTranslation } from "react-i18next";
|
|
||||||
import { useAtomValue } from "jotai";
|
|
||||||
import {
|
|
||||||
decodeSlackLinkState,
|
|
||||||
confirmSlackLink,
|
|
||||||
SlackLinkStateInfo,
|
|
||||||
} from "../services/slack-link-service";
|
|
||||||
import { currentUserAtom } from "@/features/user/atoms/current-user-atom";
|
|
||||||
import APP_ROUTE from "@/lib/app-route";
|
|
||||||
|
|
||||||
export default function SlackLinkPage() {
|
|
||||||
const { t } = useTranslation();
|
|
||||||
const [searchParams] = useSearchParams();
|
|
||||||
const navigate = useNavigate();
|
|
||||||
const state = searchParams.get("state");
|
|
||||||
const currentUser = useAtomValue(currentUserAtom);
|
|
||||||
|
|
||||||
const [info, setInfo] = useState<SlackLinkStateInfo | null>(null);
|
|
||||||
const [error, setError] = useState<string | null>(null);
|
|
||||||
const [submitting, setSubmitting] = useState(false);
|
|
||||||
const [done, setDone] = useState(false);
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
if (!currentUser) {
|
|
||||||
const redirectPath = window.location.pathname + window.location.search;
|
|
||||||
navigate(`${APP_ROUTE.AUTH.LOGIN}?redirect=${encodeURIComponent(redirectPath)}`);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!state) {
|
|
||||||
setError(t("Missing state parameter"));
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
decodeSlackLinkState(state)
|
|
||||||
.then(setInfo)
|
|
||||||
.catch((e) => setError(e?.response?.data?.message ?? e.message));
|
|
||||||
}, [state, t, currentUser, navigate]);
|
|
||||||
|
|
||||||
async function onConfirm() {
|
|
||||||
if (!state) return;
|
|
||||||
setSubmitting(true);
|
|
||||||
try {
|
|
||||||
await confirmSlackLink(state);
|
|
||||||
setDone(true);
|
|
||||||
} catch (e: any) {
|
|
||||||
setError(e?.response?.data?.message ?? e.message);
|
|
||||||
} finally {
|
|
||||||
setSubmitting(false);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (done) {
|
|
||||||
return (
|
|
||||||
<Card maw={500} mx="auto" mt={80} p="lg">
|
|
||||||
<Stack>
|
|
||||||
<Text fw={600}>{t("Connected")}</Text>
|
|
||||||
<Text c="dimmed">{t("You can close this tab and return to Slack.")}</Text>
|
|
||||||
</Stack>
|
|
||||||
</Card>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (error) {
|
|
||||||
return (
|
|
||||||
<Card maw={500} mx="auto" mt={80} p="lg">
|
|
||||||
<Alert color="red" title={t("Could not link account")}>
|
|
||||||
{error}
|
|
||||||
</Alert>
|
|
||||||
</Card>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!info || !currentUser) {
|
|
||||||
return (
|
|
||||||
<div style={{ display: "flex", justifyContent: "center", marginTop: 80 }}>
|
|
||||||
<Loader />
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
return (
|
|
||||||
<Card maw={500} mx="auto" mt={80} p="lg">
|
|
||||||
<Stack>
|
|
||||||
<Text fw={600}>{t("Link your Docmost account to Slack")}</Text>
|
|
||||||
<Text>
|
|
||||||
{t("Connect Docmost account")}{" "}
|
|
||||||
<b>{currentUser.user.email}</b>{" "}
|
|
||||||
{t("to Slack user")} <b>@{info.slackUserName}</b>
|
|
||||||
{info.slackTeamName && (
|
|
||||||
<>
|
|
||||||
{" "}
|
|
||||||
{t("in")} <b>{info.slackTeamName}</b>
|
|
||||||
</>
|
|
||||||
)}
|
|
||||||
?
|
|
||||||
</Text>
|
|
||||||
<Group justify="flex-end">
|
|
||||||
<Button variant="default" onClick={() => window.close()}>
|
|
||||||
{t("Cancel")}
|
|
||||||
</Button>
|
|
||||||
<Button onClick={onConfirm} loading={submitting}>
|
|
||||||
{t("Confirm")}
|
|
||||||
</Button>
|
|
||||||
</Group>
|
|
||||||
</Stack>
|
|
||||||
</Card>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -1,100 +0,0 @@
|
|||||||
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
|
|
||||||
import { useTranslation } from "react-i18next";
|
|
||||||
import { notifications } from "@mantine/notifications";
|
|
||||||
import * as integrationService from "../services/integration-service";
|
|
||||||
|
|
||||||
export function useAvailableIntegrations() {
|
|
||||||
return useQuery({
|
|
||||||
queryKey: ["available-integrations"],
|
|
||||||
queryFn: integrationService.getAvailableIntegrations,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
export function useInstalledIntegrations() {
|
|
||||||
return useQuery({
|
|
||||||
queryKey: ["installed-integrations"],
|
|
||||||
queryFn: integrationService.getInstalledIntegrations,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
export function useInstallIntegration() {
|
|
||||||
const qc = useQueryClient();
|
|
||||||
const { t } = useTranslation();
|
|
||||||
return useMutation({
|
|
||||||
mutationFn: integrationService.installIntegration,
|
|
||||||
onSuccess: () => {
|
|
||||||
notifications.show({ message: t("Integration installed successfully") });
|
|
||||||
qc.invalidateQueries({ queryKey: ["installed-integrations"] });
|
|
||||||
},
|
|
||||||
onError: (error) => {
|
|
||||||
const errorMessage = error["response"]?.data?.message;
|
|
||||||
notifications.show({
|
|
||||||
message: errorMessage || t("Failed to install integration"),
|
|
||||||
color: "red",
|
|
||||||
});
|
|
||||||
},
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
export function useUninstallIntegration() {
|
|
||||||
const qc = useQueryClient();
|
|
||||||
const { t } = useTranslation();
|
|
||||||
return useMutation({
|
|
||||||
mutationFn: integrationService.uninstallIntegration,
|
|
||||||
onSuccess: () => {
|
|
||||||
notifications.show({
|
|
||||||
message: t("Integration uninstalled successfully"),
|
|
||||||
});
|
|
||||||
qc.invalidateQueries({ queryKey: ["installed-integrations"] });
|
|
||||||
},
|
|
||||||
onError: (error) => {
|
|
||||||
const errorMessage = error["response"]?.data?.message;
|
|
||||||
notifications.show({
|
|
||||||
message: errorMessage || t("Failed to uninstall integration"),
|
|
||||||
color: "red",
|
|
||||||
});
|
|
||||||
},
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
export function useMyConnections() {
|
|
||||||
return useQuery({
|
|
||||||
queryKey: ["my-connections"],
|
|
||||||
queryFn: integrationService.getMyConnections,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
export function useConnectionStatus(integrationId: string | undefined) {
|
|
||||||
return useQuery({
|
|
||||||
queryKey: ["integration-connection", integrationId],
|
|
||||||
queryFn: () =>
|
|
||||||
integrationService.getConnectionStatus({
|
|
||||||
integrationId: integrationId!,
|
|
||||||
}),
|
|
||||||
enabled: !!integrationId,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
export function useDisconnectIntegration() {
|
|
||||||
const qc = useQueryClient();
|
|
||||||
const { t } = useTranslation();
|
|
||||||
return useMutation({
|
|
||||||
mutationFn: integrationService.disconnectIntegration,
|
|
||||||
onSuccess: (_data, variables) => {
|
|
||||||
notifications.show({ message: t("Integration disconnected") });
|
|
||||||
qc.invalidateQueries({
|
|
||||||
queryKey: ["integration-connection", variables.integrationId],
|
|
||||||
});
|
|
||||||
qc.invalidateQueries({ queryKey: ["my-connections"] });
|
|
||||||
// removeQueries, not invalidate: refetchOnMount false leaves invalidated inactive queries unrefreshed
|
|
||||||
qc.removeQueries({ queryKey: ["unfurl"] });
|
|
||||||
},
|
|
||||||
onError: (error) => {
|
|
||||||
const errorMessage = error["response"]?.data?.message;
|
|
||||||
notifications.show({
|
|
||||||
message: errorMessage || t("Failed to disconnect integration"),
|
|
||||||
color: "red",
|
|
||||||
});
|
|
||||||
},
|
|
||||||
});
|
|
||||||
}
|
|
||||||
@@ -1,92 +0,0 @@
|
|||||||
import api from "@/lib/api-client";
|
|
||||||
import {
|
|
||||||
IntegrationDefinition,
|
|
||||||
Integration,
|
|
||||||
ConnectionStatus,
|
|
||||||
UserConnection,
|
|
||||||
UnfurlResult,
|
|
||||||
UnfurlNeedsConnection,
|
|
||||||
} from "../types/integration.types";
|
|
||||||
|
|
||||||
export async function getAvailableIntegrations(): Promise<
|
|
||||||
IntegrationDefinition[]
|
|
||||||
> {
|
|
||||||
const req = await api.post<IntegrationDefinition[]>(
|
|
||||||
"/integrations/available",
|
|
||||||
);
|
|
||||||
return req.data;
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function getInstalledIntegrations(): Promise<Integration[]> {
|
|
||||||
const req = await api.post<Integration[]>("/integrations/list");
|
|
||||||
return req.data;
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function installIntegration(data: {
|
|
||||||
type: string;
|
|
||||||
}): Promise<Integration> {
|
|
||||||
const req = await api.post<Integration>("/integrations/install", data);
|
|
||||||
return req.data;
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function uninstallIntegration(data: {
|
|
||||||
integrationId: string;
|
|
||||||
}): Promise<void> {
|
|
||||||
await api.post("/integrations/uninstall", data);
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function getMyConnections(): Promise<UserConnection[]> {
|
|
||||||
const req = await api.post<UserConnection[]>("/integrations/connections/mine");
|
|
||||||
return req.data;
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function getConnectionStatus(data: {
|
|
||||||
integrationId: string;
|
|
||||||
}): Promise<ConnectionStatus> {
|
|
||||||
const req = await api.post<ConnectionStatus>(
|
|
||||||
"/integrations/connection/status",
|
|
||||||
data,
|
|
||||||
);
|
|
||||||
return req.data;
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function getOAuthAuthorizeUrl(data: {
|
|
||||||
integrationId: string;
|
|
||||||
returnPath?: string;
|
|
||||||
}): Promise<{ authorizationUrl: string }> {
|
|
||||||
const req = await api.post<{ authorizationUrl: string }>(
|
|
||||||
"/integrations/oauth/authorize",
|
|
||||||
data,
|
|
||||||
);
|
|
||||||
return req.data;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* For workspace-scoped providers: returns the authorize URL WITHOUT creating
|
|
||||||
* the integration row. The row is created atomically when the OAuth callback
|
|
||||||
* succeeds; a cancelled OAuth leaves no half-installed state.
|
|
||||||
*/
|
|
||||||
export async function getOAuthInstallUrl(data: {
|
|
||||||
type: string;
|
|
||||||
}): Promise<{ authorizationUrl: string }> {
|
|
||||||
const req = await api.post<{ authorizationUrl: string }>(
|
|
||||||
"/integrations/oauth/install",
|
|
||||||
data,
|
|
||||||
);
|
|
||||||
return req.data;
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function disconnectIntegration(data: {
|
|
||||||
integrationId: string;
|
|
||||||
}): Promise<void> {
|
|
||||||
await api.post("/integrations/oauth/disconnect", data);
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function unfurlUrl(data: {
|
|
||||||
url: string;
|
|
||||||
}): Promise<UnfurlResult | UnfurlNeedsConnection | null> {
|
|
||||||
const req = await api.post<{
|
|
||||||
data: UnfurlResult | UnfurlNeedsConnection | null;
|
|
||||||
}>("/integrations/unfurl", data);
|
|
||||||
return req.data.data;
|
|
||||||
}
|
|
||||||
@@ -1,23 +0,0 @@
|
|||||||
import api from "@/lib/api-client";
|
|
||||||
|
|
||||||
export type SlackLinkStateInfo = {
|
|
||||||
slackUserName: string;
|
|
||||||
slackUserId: string;
|
|
||||||
slackTeamId: string;
|
|
||||||
slackTeamName: string | null;
|
|
||||||
integrationWorkspaceId: string | undefined;
|
|
||||||
};
|
|
||||||
|
|
||||||
export async function decodeSlackLinkState(
|
|
||||||
state: string,
|
|
||||||
): Promise<SlackLinkStateInfo> {
|
|
||||||
const req = await api.post<SlackLinkStateInfo>(
|
|
||||||
"/integrations/slack/link/state",
|
|
||||||
{ state },
|
|
||||||
);
|
|
||||||
return req.data;
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function confirmSlackLink(state: string): Promise<void> {
|
|
||||||
await api.post("/integrations/slack/link", { state });
|
|
||||||
}
|
|
||||||
@@ -1,69 +0,0 @@
|
|||||||
export type IntegrationCapability = "oauth" | "unfurl" | "actions";
|
|
||||||
|
|
||||||
export type OAuthConfig = {
|
|
||||||
authUrl: string;
|
|
||||||
tokenUrl: string;
|
|
||||||
scopes: string[];
|
|
||||||
connectionScope?: 'workspace' | 'user';
|
|
||||||
};
|
|
||||||
|
|
||||||
export type IntegrationDefinition = {
|
|
||||||
type: string;
|
|
||||||
name: string;
|
|
||||||
description: string;
|
|
||||||
icon: string;
|
|
||||||
capabilities: IntegrationCapability[];
|
|
||||||
oauth?: OAuthConfig;
|
|
||||||
requiresLicense?: boolean;
|
|
||||||
};
|
|
||||||
|
|
||||||
export type Integration = {
|
|
||||||
id: string;
|
|
||||||
workspaceId: string;
|
|
||||||
type: string;
|
|
||||||
settings: Record<string, any> | null;
|
|
||||||
installedById: string | null;
|
|
||||||
createdAt: string;
|
|
||||||
updatedAt: string;
|
|
||||||
};
|
|
||||||
|
|
||||||
export type ConnectionStatus = {
|
|
||||||
connected: boolean;
|
|
||||||
providerUserId?: string;
|
|
||||||
};
|
|
||||||
|
|
||||||
export type UserConnection = {
|
|
||||||
integrationId: string;
|
|
||||||
type: string;
|
|
||||||
providerUserId: string | null;
|
|
||||||
providerDisplayName: string | null;
|
|
||||||
connectedAt: string;
|
|
||||||
invalidatedAt: string | null;
|
|
||||||
};
|
|
||||||
|
|
||||||
export type UnfurlResult = {
|
|
||||||
title: string;
|
|
||||||
description?: string;
|
|
||||||
url: string;
|
|
||||||
provider: string;
|
|
||||||
providerIcon?: string;
|
|
||||||
status?: string;
|
|
||||||
statusColor?: string;
|
|
||||||
author?: string;
|
|
||||||
authorAvatarUrl?: string;
|
|
||||||
metadata?: Record<string, any>;
|
|
||||||
};
|
|
||||||
|
|
||||||
// Returned when the link's provider needs a per-user connection the
|
|
||||||
// requesting user has not authorized yet.
|
|
||||||
export type UnfurlNeedsConnection = {
|
|
||||||
needsConnection: true;
|
|
||||||
integrationId: string;
|
|
||||||
integrationType: string;
|
|
||||||
integrationName: string;
|
|
||||||
// false for workspace-scoped providers (Slack): linking happens on the
|
|
||||||
// provider's side, so no Docmost-initiated OAuth button.
|
|
||||||
oauthConnect: boolean;
|
|
||||||
title: string;
|
|
||||||
description?: string;
|
|
||||||
};
|
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
import React, { useEffect, useState } from "react";
|
import React, { useEffect, useRef, useState } from "react";
|
||||||
import { useDebouncedValue } from "@mantine/hooks";
|
import { useDebouncedValue } from "@mantine/hooks";
|
||||||
import { Group, Select, SelectProps, Text } from "@mantine/core";
|
import { Group, Select, SelectProps, Text } from "@mantine/core";
|
||||||
import { useGetSpacesQuery } from "@/features/space/queries/space-query.ts";
|
import { useGetSpacesQuery } from "@/features/space/queries/space-query.ts";
|
||||||
@@ -14,6 +14,7 @@ interface SpaceSelectProps {
|
|||||||
width?: number;
|
width?: number;
|
||||||
opened?: boolean;
|
opened?: boolean;
|
||||||
clearable?: boolean;
|
clearable?: boolean;
|
||||||
|
withinPortal?: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
const renderSelectOption: SelectProps["renderOption"] = ({ option }) => (
|
const renderSelectOption: SelectProps["renderOption"] = ({ option }) => (
|
||||||
@@ -41,6 +42,7 @@ export function SpaceSelect({
|
|||||||
width,
|
width,
|
||||||
opened,
|
opened,
|
||||||
clearable,
|
clearable,
|
||||||
|
withinPortal = true,
|
||||||
}: SpaceSelectProps) {
|
}: SpaceSelectProps) {
|
||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
const [searchValue, setSearchValue] = useState("");
|
const [searchValue, setSearchValue] = useState("");
|
||||||
@@ -50,9 +52,13 @@ export function SpaceSelect({
|
|||||||
limit: 50,
|
limit: 50,
|
||||||
});
|
});
|
||||||
const [data, setData] = useState([]);
|
const [data, setData] = useState([]);
|
||||||
|
const fetchedSpaces = useRef(new Map<string, ISpace>());
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (spaces) {
|
if (spaces) {
|
||||||
|
spaces.items.forEach((space: ISpace) =>
|
||||||
|
fetchedSpaces.current.set(space.slug, space),
|
||||||
|
);
|
||||||
const spaceData = spaces?.items
|
const spaceData = spaces?.items
|
||||||
.filter((space: ISpace) => space.slug !== value)
|
.filter((space: ISpace) => space.slug !== value)
|
||||||
.map((space: ISpace) => {
|
.map((space: ISpace) => {
|
||||||
@@ -83,14 +89,19 @@ export function SpaceSelect({
|
|||||||
onSearchChange={setSearchValue}
|
onSearchChange={setSearchValue}
|
||||||
clearable={clearable}
|
clearable={clearable}
|
||||||
variant="filled"
|
variant="filled"
|
||||||
onChange={(slug) =>
|
onChange={(slug) => {
|
||||||
onChange(spaces.items?.find((item) => item.slug === slug))
|
// options accumulate across fetches; resolve against everything
|
||||||
}
|
// fetched, not just the latest query result
|
||||||
|
const space = slug && fetchedSpaces.current.get(slug);
|
||||||
|
if (space) {
|
||||||
|
onChange(space);
|
||||||
|
}
|
||||||
|
}}
|
||||||
onClick={(e) => e.stopPropagation()}
|
onClick={(e) => e.stopPropagation()}
|
||||||
nothingFoundMessage={t("No space found")}
|
nothingFoundMessage={t("No space found")}
|
||||||
limit={50}
|
limit={50}
|
||||||
checkIconPosition="right"
|
checkIconPosition="right"
|
||||||
comboboxProps={{ width, withinPortal: true, position: "bottom", keepMounted: false, dropdownPadding: 0 }}
|
comboboxProps={{ width, withinPortal, position: "bottom", keepMounted: false, dropdownPadding: 0 }}
|
||||||
dropdownOpened={opened}
|
dropdownOpened={opened}
|
||||||
/>
|
/>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -70,6 +70,7 @@ export function SwitchSpace({
|
|||||||
onChange={(space) => handleSelect(space.slug)}
|
onChange={(space) => handleSelect(space.slug)}
|
||||||
width={300}
|
width={300}
|
||||||
opened={true}
|
opened={true}
|
||||||
|
withinPortal={false}
|
||||||
/>
|
/>
|
||||||
</Popover.Dropdown>
|
</Popover.Dropdown>
|
||||||
</Popover>
|
</Popover>
|
||||||
|
|||||||
@@ -27,7 +27,6 @@ const APP_ROUTE = {
|
|||||||
SPACES: "/settings/spaces",
|
SPACES: "/settings/spaces",
|
||||||
BILLING: "/settings/billing",
|
BILLING: "/settings/billing",
|
||||||
SECURITY: "/settings/security",
|
SECURITY: "/settings/security",
|
||||||
INTEGRATIONS: "/settings/integrations",
|
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -43,6 +43,10 @@ export function isCloud(): boolean {
|
|||||||
return castToBoolean(getConfigValue("CLOUD"));
|
return castToBoolean(getConfigValue("CLOUD"));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export function isBetaConfluenceImporter(): boolean {
|
||||||
|
return castToBoolean(getConfigValue("BETA_CONFLUENCE_IMPORTER"));
|
||||||
|
}
|
||||||
|
|
||||||
export function getAvatarUrl(
|
export function getAvatarUrl(
|
||||||
avatarUrl: string,
|
avatarUrl: string,
|
||||||
type: AvatarIconType = AvatarIconType.AVATAR,
|
type: AvatarIconType = AvatarIconType.AVATAR,
|
||||||
|
|||||||
@@ -16,6 +16,7 @@ export default defineConfig(({ mode }) => {
|
|||||||
BILLING_TRIAL_DAYS,
|
BILLING_TRIAL_DAYS,
|
||||||
POSTHOG_HOST,
|
POSTHOG_HOST,
|
||||||
POSTHOG_KEY,
|
POSTHOG_KEY,
|
||||||
|
BETA_CONFLUENCE_IMPORTER,
|
||||||
} = loadEnv(mode, envPath, "");
|
} = loadEnv(mode, envPath, "");
|
||||||
|
|
||||||
return {
|
return {
|
||||||
@@ -31,6 +32,7 @@ export default defineConfig(({ mode }) => {
|
|||||||
BILLING_TRIAL_DAYS,
|
BILLING_TRIAL_DAYS,
|
||||||
POSTHOG_HOST,
|
POSTHOG_HOST,
|
||||||
POSTHOG_KEY,
|
POSTHOG_KEY,
|
||||||
|
BETA_CONFLUENCE_IMPORTER
|
||||||
},
|
},
|
||||||
APP_VERSION: JSON.stringify(process.env.npm_package_version),
|
APP_VERSION: JSON.stringify(process.env.npm_package_version),
|
||||||
},
|
},
|
||||||
@@ -55,6 +57,7 @@ export default defineConfig(({ mode }) => {
|
|||||||
},
|
},
|
||||||
},
|
},
|
||||||
server: {
|
server: {
|
||||||
|
allowedHosts: ['docmost.nz'],
|
||||||
proxy: {
|
proxy: {
|
||||||
"/api": {
|
"/api": {
|
||||||
target: APP_URL,
|
target: APP_URL,
|
||||||
|
|||||||
@@ -77,6 +77,7 @@
|
|||||||
"class-validator": "0.15.1",
|
"class-validator": "0.15.1",
|
||||||
"cookie": "1.1.1",
|
"cookie": "1.1.1",
|
||||||
"csv-stringify": "6.8.0",
|
"csv-stringify": "6.8.0",
|
||||||
|
"entities": "7.0.1",
|
||||||
"fast-bm25": "0.0.5",
|
"fast-bm25": "0.0.5",
|
||||||
"fastify-ip": "2.0.0",
|
"fastify-ip": "2.0.0",
|
||||||
"fs-extra": "11.3.4",
|
"fs-extra": "11.3.4",
|
||||||
|
|||||||
@@ -17,6 +17,7 @@ import { EventEmitterModule } from '@nestjs/event-emitter';
|
|||||||
import { HealthModule } from './integrations/health/health.module';
|
import { HealthModule } from './integrations/health/health.module';
|
||||||
import { ExportModule } from './integrations/export/export.module';
|
import { ExportModule } from './integrations/export/export.module';
|
||||||
import { ImportModule } from './integrations/import/import.module';
|
import { ImportModule } from './integrations/import/import.module';
|
||||||
|
import { ImportProcessorModule } from './integrations/import/import-processor.module';
|
||||||
import { SecurityModule } from './integrations/security/security.module';
|
import { SecurityModule } from './integrations/security/security.module';
|
||||||
import { TelemetryModule } from './integrations/telemetry/telemetry.module';
|
import { TelemetryModule } from './integrations/telemetry/telemetry.module';
|
||||||
import { RedisModule } from '@nestjs-labs/nestjs-ioredis';
|
import { RedisModule } from '@nestjs-labs/nestjs-ioredis';
|
||||||
@@ -76,6 +77,7 @@ try {
|
|||||||
StaticModule,
|
StaticModule,
|
||||||
HealthModule,
|
HealthModule,
|
||||||
ImportModule,
|
ImportModule,
|
||||||
|
ImportProcessorModule,
|
||||||
ExportModule,
|
ExportModule,
|
||||||
StorageModule.forRootAsync({
|
StorageModule.forRootAsync({
|
||||||
imports: [EnvironmentModule],
|
imports: [EnvironmentModule],
|
||||||
|
|||||||
@@ -5,7 +5,6 @@ import { Superscript } from '@tiptap/extension-superscript';
|
|||||||
import SubScript from '@tiptap/extension-subscript';
|
import SubScript from '@tiptap/extension-subscript';
|
||||||
import { Typography } from '@tiptap/extension-typography';
|
import { Typography } from '@tiptap/extension-typography';
|
||||||
import { TextStyle } from '@tiptap/extension-text-style';
|
import { TextStyle } from '@tiptap/extension-text-style';
|
||||||
import { Color } from '@tiptap/extension-color';
|
|
||||||
import { Youtube } from '@tiptap/extension-youtube';
|
import { Youtube } from '@tiptap/extension-youtube';
|
||||||
import { TaskList, TaskItem } from '@tiptap/extension-list';
|
import { TaskList, TaskItem } from '@tiptap/extension-list';
|
||||||
import {
|
import {
|
||||||
@@ -36,6 +35,7 @@ import {
|
|||||||
Mention,
|
Mention,
|
||||||
Subpages,
|
Subpages,
|
||||||
Highlight,
|
Highlight,
|
||||||
|
Color,
|
||||||
Indent,
|
Indent,
|
||||||
UniqueID,
|
UniqueID,
|
||||||
Columns,
|
Columns,
|
||||||
@@ -49,8 +49,6 @@ import {
|
|||||||
Footnotes,
|
Footnotes,
|
||||||
Footnote,
|
Footnote,
|
||||||
FootnoteReference,
|
FootnoteReference,
|
||||||
IntegrationLink,
|
|
||||||
IntegrationMention,
|
|
||||||
} from '@docmost/editor-ext';
|
} from '@docmost/editor-ext';
|
||||||
import {
|
import {
|
||||||
extensions as coreExtensions,
|
extensions as coreExtensions,
|
||||||
@@ -130,8 +128,6 @@ export const tiptapExtensions = [
|
|||||||
Footnotes,
|
Footnotes,
|
||||||
Footnote,
|
Footnote,
|
||||||
FootnoteReference,
|
FootnoteReference,
|
||||||
IntegrationLink,
|
|
||||||
IntegrationMention
|
|
||||||
] as any;
|
] as any;
|
||||||
|
|
||||||
export function jsonToHtml(tiptapJson: any) {
|
export function jsonToHtml(tiptapJson: any) {
|
||||||
|
|||||||
@@ -107,6 +107,7 @@ export const EXCLUDED_AUDIT_EVENTS: Set<string> = new Set([
|
|||||||
AuditEvent.PAGE_CREATED,
|
AuditEvent.PAGE_CREATED,
|
||||||
AuditEvent.PAGE_MOVED_TO_SPACE,
|
AuditEvent.PAGE_MOVED_TO_SPACE,
|
||||||
AuditEvent.PAGE_DUPLICATED,
|
AuditEvent.PAGE_DUPLICATED,
|
||||||
|
AuditEvent.COMMENT_CREATED,
|
||||||
AuditEvent.COMMENT_UPDATED,
|
AuditEvent.COMMENT_UPDATED,
|
||||||
AuditEvent.COMMENT_RESOLVED,
|
AuditEvent.COMMENT_RESOLVED,
|
||||||
AuditEvent.COMMENT_REOPENED,
|
AuditEvent.COMMENT_REOPENED,
|
||||||
|
|||||||
@@ -15,7 +15,6 @@ export enum EventName {
|
|||||||
WORKSPACE_CREATED = 'workspace.created',
|
WORKSPACE_CREATED = 'workspace.created',
|
||||||
WORKSPACE_UPDATED = 'workspace.updated',
|
WORKSPACE_UPDATED = 'workspace.updated',
|
||||||
WORKSPACE_DELETED = 'workspace.deleted',
|
WORKSPACE_DELETED = 'workspace.deleted',
|
||||||
NOTIFICATION_CREATED = 'notification.created',
|
|
||||||
|
|
||||||
BASE_CREATED = 'base.created',
|
BASE_CREATED = 'base.created',
|
||||||
BASE_UPDATED = 'base.updated',
|
BASE_UPDATED = 'base.updated',
|
||||||
|
|||||||
@@ -7,6 +7,7 @@ export const Feature = {
|
|||||||
PAGE_PERMISSIONS: 'page:permissions',
|
PAGE_PERMISSIONS: 'page:permissions',
|
||||||
AI: 'ai',
|
AI: 'ai',
|
||||||
CONFLUENCE_IMPORT: 'import:confluence',
|
CONFLUENCE_IMPORT: 'import:confluence',
|
||||||
|
CONFLUENCE_API_IMPORT: 'import:confluence-api',
|
||||||
DOCX_IMPORT: 'import:docx',
|
DOCX_IMPORT: 'import:docx',
|
||||||
PDF_IMPORT: 'import:pdf',
|
PDF_IMPORT: 'import:pdf',
|
||||||
ATTACHMENT_INDEXING: 'attachment:indexing',
|
ATTACHMENT_INDEXING: 'attachment:indexing',
|
||||||
@@ -23,7 +24,6 @@ export const Feature = {
|
|||||||
PERSONAL_SPACES: 'spaces:personal',
|
PERSONAL_SPACES: 'spaces:personal',
|
||||||
DOCX_EXPORT: 'export:docx',
|
DOCX_EXPORT: 'export:docx',
|
||||||
BASES: 'bases',
|
BASES: 'bases',
|
||||||
INTEGRATIONS: 'integrations',
|
|
||||||
} as const;
|
} as const;
|
||||||
|
|
||||||
export type FeatureKey = (typeof Feature)[keyof typeof Feature];
|
export type FeatureKey = (typeof Feature)[keyof typeof Feature];
|
||||||
|
|||||||
@@ -1,64 +0,0 @@
|
|||||||
import { getProxyAwareFetch, proxyFetch } from './proxy-fetch';
|
|
||||||
|
|
||||||
describe('getProxyAwareFetch', () => {
|
|
||||||
const originalEnv = { ...process.env };
|
|
||||||
|
|
||||||
afterEach(() => {
|
|
||||||
process.env = { ...originalEnv };
|
|
||||||
});
|
|
||||||
|
|
||||||
it('returns undefined when no proxy env vars are set', () => {
|
|
||||||
delete process.env.HTTP_PROXY;
|
|
||||||
delete process.env.HTTPS_PROXY;
|
|
||||||
delete process.env.http_proxy;
|
|
||||||
delete process.env.https_proxy;
|
|
||||||
|
|
||||||
expect(getProxyAwareFetch()).toBeUndefined();
|
|
||||||
});
|
|
||||||
|
|
||||||
it('returns a fetch function when HTTP_PROXY is set', () => {
|
|
||||||
delete process.env.HTTPS_PROXY;
|
|
||||||
delete process.env.http_proxy;
|
|
||||||
delete process.env.https_proxy;
|
|
||||||
process.env.HTTP_PROXY = 'http://proxy.example.com:8080';
|
|
||||||
|
|
||||||
expect(typeof getProxyAwareFetch()).toBe('function');
|
|
||||||
});
|
|
||||||
|
|
||||||
it('returns a fetch function when HTTPS_PROXY is set', () => {
|
|
||||||
delete process.env.HTTP_PROXY;
|
|
||||||
delete process.env.http_proxy;
|
|
||||||
delete process.env.https_proxy;
|
|
||||||
process.env.HTTPS_PROXY = 'http://proxy.example.com:8080';
|
|
||||||
|
|
||||||
expect(typeof getProxyAwareFetch()).toBe('function');
|
|
||||||
});
|
|
||||||
|
|
||||||
it('returns a fetch function when lowercase http_proxy is set', () => {
|
|
||||||
delete process.env.HTTP_PROXY;
|
|
||||||
delete process.env.HTTPS_PROXY;
|
|
||||||
delete process.env.https_proxy;
|
|
||||||
process.env.http_proxy = 'http://proxy.example.com:8080';
|
|
||||||
|
|
||||||
expect(typeof getProxyAwareFetch()).toBe('function');
|
|
||||||
});
|
|
||||||
|
|
||||||
it('proxyFetch delegates to the platform fetch when no proxy is configured', async () => {
|
|
||||||
delete process.env.HTTP_PROXY;
|
|
||||||
delete process.env.HTTPS_PROXY;
|
|
||||||
delete process.env.http_proxy;
|
|
||||||
delete process.env.https_proxy;
|
|
||||||
|
|
||||||
const original = globalThis.fetch;
|
|
||||||
const response = new Response('ok');
|
|
||||||
const spy = jest.fn().mockResolvedValue(response);
|
|
||||||
globalThis.fetch = spy as unknown as typeof fetch;
|
|
||||||
|
|
||||||
try {
|
|
||||||
await expect(proxyFetch('https://example.com')).resolves.toBe(response);
|
|
||||||
expect(spy).toHaveBeenCalledWith('https://example.com', undefined);
|
|
||||||
} finally {
|
|
||||||
globalThis.fetch = original;
|
|
||||||
}
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@@ -1,38 +0,0 @@
|
|||||||
import { EnvHttpProxyAgent, fetch as undiciFetch } from 'undici';
|
|
||||||
|
|
||||||
const LOOPBACK_BYPASS = ['localhost', '127.0.0.1', '::1'];
|
|
||||||
|
|
||||||
let cachedAgent: EnvHttpProxyAgent | undefined;
|
|
||||||
|
|
||||||
function hasProxyEnv(): boolean {
|
|
||||||
return Boolean(
|
|
||||||
process.env.HTTP_PROXY ||
|
|
||||||
process.env.HTTPS_PROXY ||
|
|
||||||
process.env.http_proxy ||
|
|
||||||
process.env.https_proxy,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
function buildAgent(): EnvHttpProxyAgent {
|
|
||||||
const existing = process.env.NO_PROXY || process.env.no_proxy || '';
|
|
||||||
const merged = [existing, ...LOOPBACK_BYPASS]
|
|
||||||
.map((s) => s.trim())
|
|
||||||
.filter(Boolean)
|
|
||||||
.join(',');
|
|
||||||
return new EnvHttpProxyAgent({ noProxy: merged });
|
|
||||||
}
|
|
||||||
|
|
||||||
export function getProxyAwareFetch(): typeof fetch | undefined {
|
|
||||||
if (!hasProxyEnv()) return undefined;
|
|
||||||
cachedAgent ??= buildAgent();
|
|
||||||
const agent = cachedAgent;
|
|
||||||
return ((input, init) =>
|
|
||||||
undiciFetch(input as any, {
|
|
||||||
...(init as any),
|
|
||||||
dispatcher: agent,
|
|
||||||
}) as unknown as Promise<Response>) as typeof fetch;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Drop-in replacement for direct fetch calls: proxies when configured, platform fetch otherwise.
|
|
||||||
export const proxyFetch: typeof fetch = (input, init) =>
|
|
||||||
(getProxyAwareFetch() ?? fetch)(input, init);
|
|
||||||
@@ -21,9 +21,6 @@ import { ShareModule } from './share/share.module';
|
|||||||
import { LabelModule } from './label/label.module';
|
import { LabelModule } from './label/label.module';
|
||||||
import { NotificationModule } from './notification/notification.module';
|
import { NotificationModule } from './notification/notification.module';
|
||||||
import { WatcherModule } from './watcher/watcher.module';
|
import { WatcherModule } from './watcher/watcher.module';
|
||||||
import { IntegrationModule } from './integration/integration.module';
|
|
||||||
import { GitHubModule } from './integration/providers/github/github.module';
|
|
||||||
import { GitLabModule } from './integration/providers/gitlab/gitlab.module';
|
|
||||||
import { FavoriteModule } from './favorite/favorite.module';
|
import { FavoriteModule } from './favorite/favorite.module';
|
||||||
import { SessionModule } from './session/session.module';
|
import { SessionModule } from './session/session.module';
|
||||||
import { ClsMiddleware } from 'nestjs-cls';
|
import { ClsMiddleware } from 'nestjs-cls';
|
||||||
@@ -46,9 +43,6 @@ import { ClsMiddleware } from 'nestjs-cls';
|
|||||||
LabelModule,
|
LabelModule,
|
||||||
NotificationModule,
|
NotificationModule,
|
||||||
WatcherModule,
|
WatcherModule,
|
||||||
IntegrationModule,
|
|
||||||
GitHubModule,
|
|
||||||
GitLabModule,
|
|
||||||
SessionModule,
|
SessionModule,
|
||||||
],
|
],
|
||||||
})
|
})
|
||||||
@@ -59,7 +53,6 @@ export class CoreModule implements NestModule {
|
|||||||
{ path: 'health', method: RequestMethod.GET },
|
{ path: 'health', method: RequestMethod.GET },
|
||||||
{ path: 'health/live', method: RequestMethod.GET },
|
{ path: 'health/live', method: RequestMethod.GET },
|
||||||
{ path: 'billing/stripe/webhook', method: RequestMethod.POST },
|
{ path: 'billing/stripe/webhook', method: RequestMethod.POST },
|
||||||
{ path: 'integrations/oauth/*/callback', method: RequestMethod.GET },
|
|
||||||
];
|
];
|
||||||
|
|
||||||
consumer
|
consumer
|
||||||
|
|||||||
@@ -1,9 +0,0 @@
|
|||||||
export enum IntegrationType {
|
|
||||||
SLACK = 'slack',
|
|
||||||
GITHUB = 'github',
|
|
||||||
GITLAB = 'gitlab',
|
|
||||||
JIRA = 'jira',
|
|
||||||
LINEAR = 'linear',
|
|
||||||
GOOGLE_DOCS = 'google_docs',
|
|
||||||
FIGMA = 'figma',
|
|
||||||
}
|
|
||||||
@@ -1,57 +0,0 @@
|
|||||||
import {
|
|
||||||
IsNotEmpty,
|
|
||||||
IsOptional,
|
|
||||||
IsString,
|
|
||||||
Matches,
|
|
||||||
MaxLength,
|
|
||||||
} from 'class-validator';
|
|
||||||
|
|
||||||
export class InstallIntegrationDto {
|
|
||||||
@IsNotEmpty()
|
|
||||||
@IsString()
|
|
||||||
type: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
export class UninstallIntegrationDto {
|
|
||||||
@IsNotEmpty()
|
|
||||||
@IsString()
|
|
||||||
integrationId: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
export class IntegrationIdDto {
|
|
||||||
@IsNotEmpty()
|
|
||||||
@IsString()
|
|
||||||
integrationId: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
export class UnfurlDto {
|
|
||||||
@IsNotEmpty()
|
|
||||||
@IsString()
|
|
||||||
url: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
export class OAuthAuthorizeDto {
|
|
||||||
@IsNotEmpty()
|
|
||||||
@IsString()
|
|
||||||
integrationId: string;
|
|
||||||
|
|
||||||
// In-app path to land on after OAuth; single leading slash keeps the
|
|
||||||
// redirect on the workspace origin.
|
|
||||||
@IsOptional()
|
|
||||||
@IsString()
|
|
||||||
@MaxLength(512)
|
|
||||||
@Matches(/^\/(?!\/)[^\s\\]*$/)
|
|
||||||
returnPath?: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
export class OAuthDisconnectDto {
|
|
||||||
@IsNotEmpty()
|
|
||||||
@IsString()
|
|
||||||
integrationId: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
export class OAuthInstallDto {
|
|
||||||
@IsNotEmpty()
|
|
||||||
@IsString()
|
|
||||||
type: string;
|
|
||||||
}
|
|
||||||
@@ -1,89 +0,0 @@
|
|||||||
import { Injectable, NotFoundException } from '@nestjs/common';
|
|
||||||
import { IntegrationConnectionRepo } from './repos/integration-connection.repo';
|
|
||||||
import { IntegrationRepo } from './repos/integration.repo';
|
|
||||||
import { IntegrationConnection } from '@docmost/db/types/entity.types';
|
|
||||||
import { UnfurlService } from './unfurl/unfurl.service';
|
|
||||||
|
|
||||||
@Injectable()
|
|
||||||
export class IntegrationConnectionService {
|
|
||||||
constructor(
|
|
||||||
private readonly connectionRepo: IntegrationConnectionRepo,
|
|
||||||
private readonly integrationRepo: IntegrationRepo,
|
|
||||||
private readonly unfurlService: UnfurlService,
|
|
||||||
) {}
|
|
||||||
|
|
||||||
async getConnectionStatus(
|
|
||||||
integrationId: string,
|
|
||||||
userId: string,
|
|
||||||
workspaceId: string,
|
|
||||||
): Promise<{ connected: boolean; providerUserId?: string }> {
|
|
||||||
const integration = await this.integrationRepo.findById(integrationId);
|
|
||||||
if (!integration || integration.workspaceId !== workspaceId) {
|
|
||||||
throw new NotFoundException('Integration not found');
|
|
||||||
}
|
|
||||||
|
|
||||||
const connection = await this.connectionRepo.findByIntegrationAndUser(
|
|
||||||
integrationId,
|
|
||||||
userId,
|
|
||||||
);
|
|
||||||
|
|
||||||
return {
|
|
||||||
connected: !!connection && !connection.invalidatedAt,
|
|
||||||
providerUserId: connection?.providerUserId ?? undefined,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
async findByIntegrationAndUser(
|
|
||||||
integrationId: string,
|
|
||||||
userId: string,
|
|
||||||
): Promise<IntegrationConnection | undefined> {
|
|
||||||
return this.connectionRepo.findByIntegrationAndUser(integrationId, userId);
|
|
||||||
}
|
|
||||||
|
|
||||||
async findByWorkspaceTypeAndUser(
|
|
||||||
workspaceId: string,
|
|
||||||
integrationType: string,
|
|
||||||
userId: string,
|
|
||||||
): Promise<IntegrationConnection | undefined> {
|
|
||||||
return this.connectionRepo.findByWorkspaceTypeAndUser(
|
|
||||||
workspaceId,
|
|
||||||
integrationType,
|
|
||||||
userId,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
async getUserConnections(userId: string, workspaceId: string) {
|
|
||||||
const rows = await this.connectionRepo.findByUserAndWorkspace(
|
|
||||||
userId,
|
|
||||||
workspaceId,
|
|
||||||
);
|
|
||||||
|
|
||||||
return rows.map((row) => ({
|
|
||||||
integrationId: row.integrationId,
|
|
||||||
type: row.type,
|
|
||||||
providerUserId: row.providerUserId ?? null,
|
|
||||||
providerDisplayName:
|
|
||||||
(row.metadata as { displayName?: string } | null)?.displayName ?? null,
|
|
||||||
connectedAt: row.createdAt,
|
|
||||||
invalidatedAt: row.invalidatedAt ?? null,
|
|
||||||
}));
|
|
||||||
}
|
|
||||||
|
|
||||||
async disconnect(
|
|
||||||
integrationId: string,
|
|
||||||
userId: string,
|
|
||||||
workspaceId: string,
|
|
||||||
): Promise<void> {
|
|
||||||
const integration = await this.integrationRepo.findById(integrationId);
|
|
||||||
if (!integration || integration.workspaceId !== workspaceId) {
|
|
||||||
throw new NotFoundException('Integration not found');
|
|
||||||
}
|
|
||||||
|
|
||||||
await this.connectionRepo.deleteByIntegrationAndUser(
|
|
||||||
integrationId,
|
|
||||||
userId,
|
|
||||||
);
|
|
||||||
|
|
||||||
await this.unfurlService.purgeUserCache(workspaceId, userId);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,138 +0,0 @@
|
|||||||
import {
|
|
||||||
Body,
|
|
||||||
Controller,
|
|
||||||
ForbiddenException,
|
|
||||||
HttpCode,
|
|
||||||
HttpStatus,
|
|
||||||
Post,
|
|
||||||
UseGuards,
|
|
||||||
} from '@nestjs/common';
|
|
||||||
import { JwtAuthGuard } from '../../common/guards/jwt-auth.guard';
|
|
||||||
import { AuthUser } from '../../common/decorators/auth-user.decorator';
|
|
||||||
import { AuthWorkspace } from '../../common/decorators/auth-workspace.decorator';
|
|
||||||
import { User, Workspace } from '@docmost/db/types/entity.types';
|
|
||||||
import { IntegrationService } from './integration.service';
|
|
||||||
import { IntegrationConnectionService } from './integration-connection.service';
|
|
||||||
import {
|
|
||||||
InstallIntegrationDto,
|
|
||||||
UninstallIntegrationDto,
|
|
||||||
IntegrationIdDto,
|
|
||||||
} from './dto/integration.dto';
|
|
||||||
import { IntegrationRegistry } from './registry/integration-registry';
|
|
||||||
import WorkspaceAbilityFactory from '../casl/abilities/workspace-ability.factory';
|
|
||||||
import {
|
|
||||||
WorkspaceCaslAction,
|
|
||||||
WorkspaceCaslSubject,
|
|
||||||
} from '../casl/interfaces/workspace-ability.type';
|
|
||||||
import { LicenseCheckService } from '../../integrations/environment/license-check.service';
|
|
||||||
import { Feature } from '../../common/features';
|
|
||||||
|
|
||||||
@Controller('integrations')
|
|
||||||
export class IntegrationController {
|
|
||||||
constructor(
|
|
||||||
private readonly integrationService: IntegrationService,
|
|
||||||
private readonly connectionService: IntegrationConnectionService,
|
|
||||||
private readonly workspaceAbility: WorkspaceAbilityFactory,
|
|
||||||
private readonly licenseCheckService: LicenseCheckService,
|
|
||||||
private readonly registry: IntegrationRegistry,
|
|
||||||
) {}
|
|
||||||
|
|
||||||
private assertIntegrationsLicensed(workspace: Workspace) {
|
|
||||||
if (
|
|
||||||
!this.licenseCheckService.hasFeature(
|
|
||||||
workspace.licenseKey,
|
|
||||||
Feature.INTEGRATIONS,
|
|
||||||
workspace.plan,
|
|
||||||
)
|
|
||||||
) {
|
|
||||||
throw new ForbiddenException('This feature requires a valid license');
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@UseGuards(JwtAuthGuard)
|
|
||||||
@HttpCode(HttpStatus.OK)
|
|
||||||
@Post('available')
|
|
||||||
async getAvailableIntegrations() {
|
|
||||||
return this.integrationService.getAvailableIntegrations();
|
|
||||||
}
|
|
||||||
|
|
||||||
@UseGuards(JwtAuthGuard)
|
|
||||||
@HttpCode(HttpStatus.OK)
|
|
||||||
@Post('list')
|
|
||||||
async getInstalledIntegrations(
|
|
||||||
@AuthWorkspace() workspace: Workspace,
|
|
||||||
) {
|
|
||||||
return this.integrationService.getInstalledIntegrations(workspace.id);
|
|
||||||
}
|
|
||||||
|
|
||||||
@UseGuards(JwtAuthGuard)
|
|
||||||
@HttpCode(HttpStatus.OK)
|
|
||||||
@Post('install')
|
|
||||||
async install(
|
|
||||||
@Body() dto: InstallIntegrationDto,
|
|
||||||
@AuthUser() user: User,
|
|
||||||
@AuthWorkspace() workspace: Workspace,
|
|
||||||
) {
|
|
||||||
const ability = this.workspaceAbility.createForUser(user, workspace);
|
|
||||||
if (
|
|
||||||
ability.cannot(
|
|
||||||
WorkspaceCaslAction.Manage,
|
|
||||||
WorkspaceCaslSubject.Settings,
|
|
||||||
)
|
|
||||||
) {
|
|
||||||
throw new ForbiddenException();
|
|
||||||
}
|
|
||||||
|
|
||||||
if (this.registry.getProvider(dto.type)?.definition.requiresLicense) {
|
|
||||||
this.assertIntegrationsLicensed(workspace);
|
|
||||||
}
|
|
||||||
return this.integrationService.install(dto.type, workspace.id, user.id);
|
|
||||||
}
|
|
||||||
|
|
||||||
@UseGuards(JwtAuthGuard)
|
|
||||||
@HttpCode(HttpStatus.OK)
|
|
||||||
@Post('uninstall')
|
|
||||||
async uninstall(
|
|
||||||
@Body() dto: UninstallIntegrationDto,
|
|
||||||
@AuthUser() user: User,
|
|
||||||
@AuthWorkspace() workspace: Workspace,
|
|
||||||
) {
|
|
||||||
const ability = this.workspaceAbility.createForUser(user, workspace);
|
|
||||||
if (
|
|
||||||
ability.cannot(
|
|
||||||
WorkspaceCaslAction.Manage,
|
|
||||||
WorkspaceCaslSubject.Settings,
|
|
||||||
)
|
|
||||||
) {
|
|
||||||
throw new ForbiddenException();
|
|
||||||
}
|
|
||||||
|
|
||||||
await this.integrationService.uninstall(dto.integrationId, workspace.id);
|
|
||||||
return { success: true };
|
|
||||||
}
|
|
||||||
|
|
||||||
@UseGuards(JwtAuthGuard)
|
|
||||||
@HttpCode(HttpStatus.OK)
|
|
||||||
@Post('connections/mine')
|
|
||||||
async getMyConnections(
|
|
||||||
@AuthUser() user: User,
|
|
||||||
@AuthWorkspace() workspace: Workspace,
|
|
||||||
) {
|
|
||||||
return this.connectionService.getUserConnections(user.id, workspace.id);
|
|
||||||
}
|
|
||||||
|
|
||||||
@UseGuards(JwtAuthGuard)
|
|
||||||
@HttpCode(HttpStatus.OK)
|
|
||||||
@Post('connection/status')
|
|
||||||
async getConnectionStatus(
|
|
||||||
@Body() dto: IntegrationIdDto,
|
|
||||||
@AuthUser() user: User,
|
|
||||||
@AuthWorkspace() workspace: Workspace,
|
|
||||||
) {
|
|
||||||
return this.connectionService.getConnectionStatus(
|
|
||||||
dto.integrationId,
|
|
||||||
user.id,
|
|
||||||
workspace.id,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,55 +0,0 @@
|
|||||||
import { Injectable, Logger, OnApplicationBootstrap } from '@nestjs/common';
|
|
||||||
import { OnEvent } from '@nestjs/event-emitter';
|
|
||||||
import { InjectQueue } from '@nestjs/bullmq';
|
|
||||||
import { Queue } from 'bullmq';
|
|
||||||
import { QueueJob, QueueName } from '../../integrations/queue/constants';
|
|
||||||
import { EventName } from '../../common/events/event.contants';
|
|
||||||
|
|
||||||
const TOKEN_REFRESH_SCHEDULER_ID = 'integration-token-refresh-scheduler';
|
|
||||||
const TOKEN_REFRESH_INTERVAL_MS = 10 * 60 * 1000; // 10 minutes
|
|
||||||
|
|
||||||
@Injectable()
|
|
||||||
export class IntegrationListener implements OnApplicationBootstrap {
|
|
||||||
private readonly logger = new Logger(IntegrationListener.name);
|
|
||||||
|
|
||||||
constructor(
|
|
||||||
@InjectQueue(QueueName.INTEGRATION_QUEUE)
|
|
||||||
private readonly integrationQueue: Queue,
|
|
||||||
) {}
|
|
||||||
|
|
||||||
async onApplicationBootstrap() {
|
|
||||||
await this.integrationQueue.upsertJobScheduler(
|
|
||||||
TOKEN_REFRESH_SCHEDULER_ID,
|
|
||||||
{ every: TOKEN_REFRESH_INTERVAL_MS },
|
|
||||||
{
|
|
||||||
name: QueueJob.INTEGRATION_TOKEN_REFRESH,
|
|
||||||
data: {},
|
|
||||||
},
|
|
||||||
);
|
|
||||||
this.logger.debug('Integration token refresh scheduler created');
|
|
||||||
}
|
|
||||||
|
|
||||||
@OnEvent(EventName.PAGE_CREATED)
|
|
||||||
async onPageCreated(payload: any) {
|
|
||||||
await this.integrationQueue.add(QueueJob.INTEGRATION_EVENT, {
|
|
||||||
eventName: EventName.PAGE_CREATED,
|
|
||||||
...payload,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
@OnEvent(EventName.PAGE_UPDATED)
|
|
||||||
async onPageUpdated(payload: any) {
|
|
||||||
await this.integrationQueue.add(QueueJob.INTEGRATION_EVENT, {
|
|
||||||
eventName: EventName.PAGE_UPDATED,
|
|
||||||
...payload,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
@OnEvent(EventName.PAGE_DELETED)
|
|
||||||
async onPageDeleted(payload: any) {
|
|
||||||
await this.integrationQueue.add(QueueJob.INTEGRATION_EVENT, {
|
|
||||||
eventName: EventName.PAGE_DELETED,
|
|
||||||
...payload,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,37 +0,0 @@
|
|||||||
import { Module } from '@nestjs/common';
|
|
||||||
import { IntegrationRegistry } from './registry/integration-registry';
|
|
||||||
import { IntegrationService } from './integration.service';
|
|
||||||
import { IntegrationConnectionService } from './integration-connection.service';
|
|
||||||
import { IntegrationController } from './integration.controller';
|
|
||||||
import { OAuthController } from './oauth/oauth.controller';
|
|
||||||
import { OAuthService } from './oauth/oauth.service';
|
|
||||||
import { UnfurlController } from './unfurl/unfurl.controller';
|
|
||||||
import { UnfurlService } from './unfurl/unfurl.service';
|
|
||||||
import { IntegrationRepo } from './repos/integration.repo';
|
|
||||||
import { IntegrationConnectionRepo } from './repos/integration-connection.repo';
|
|
||||||
import { IntegrationListener } from './integration.listener';
|
|
||||||
import { IntegrationProcessor } from './integration.processor';
|
|
||||||
|
|
||||||
@Module({
|
|
||||||
controllers: [IntegrationController, OAuthController, UnfurlController],
|
|
||||||
providers: [
|
|
||||||
IntegrationRegistry,
|
|
||||||
IntegrationService,
|
|
||||||
IntegrationConnectionService,
|
|
||||||
OAuthService,
|
|
||||||
UnfurlService,
|
|
||||||
IntegrationRepo,
|
|
||||||
IntegrationConnectionRepo,
|
|
||||||
IntegrationListener,
|
|
||||||
IntegrationProcessor,
|
|
||||||
],
|
|
||||||
exports: [
|
|
||||||
IntegrationRegistry,
|
|
||||||
IntegrationService,
|
|
||||||
IntegrationConnectionService,
|
|
||||||
OAuthService,
|
|
||||||
IntegrationRepo,
|
|
||||||
IntegrationConnectionRepo,
|
|
||||||
],
|
|
||||||
})
|
|
||||||
export class IntegrationModule {}
|
|
||||||
@@ -1,133 +0,0 @@
|
|||||||
import { OnWorkerEvent, Processor, WorkerHost } from '@nestjs/bullmq';
|
|
||||||
import { Logger, NotFoundException } from '@nestjs/common';
|
|
||||||
import { IntegrationConnection } from '@docmost/db/types/entity.types';
|
|
||||||
import { TokenInvalidError } from './registry/integration-provider.interface';
|
|
||||||
import { Job } from 'bullmq';
|
|
||||||
import { QueueJob, QueueName } from '../../integrations/queue/constants/queue.constants';
|
|
||||||
import { IntegrationRegistry } from './registry/integration-registry';
|
|
||||||
import { IntegrationRepo } from './repos/integration.repo';
|
|
||||||
import { IntegrationConnectionRepo } from './repos/integration-connection.repo';
|
|
||||||
import { OAuthService } from './oauth/oauth.service';
|
|
||||||
|
|
||||||
const TOKEN_REFRESH_WINDOW_MS = 15 * 60 * 1000; // 15 minutes
|
|
||||||
|
|
||||||
@Processor(QueueName.INTEGRATION_QUEUE)
|
|
||||||
export class IntegrationProcessor extends WorkerHost {
|
|
||||||
private readonly logger = new Logger(IntegrationProcessor.name);
|
|
||||||
|
|
||||||
constructor(
|
|
||||||
private readonly registry: IntegrationRegistry,
|
|
||||||
private readonly integrationRepo: IntegrationRepo,
|
|
||||||
private readonly connectionRepo: IntegrationConnectionRepo,
|
|
||||||
private readonly oauthService: OAuthService,
|
|
||||||
) {
|
|
||||||
super();
|
|
||||||
}
|
|
||||||
|
|
||||||
async process(job: Job): Promise<void> {
|
|
||||||
switch (job.name) {
|
|
||||||
case QueueJob.INTEGRATION_EVENT:
|
|
||||||
await this.handleIntegrationEvent(job);
|
|
||||||
break;
|
|
||||||
case QueueJob.INTEGRATION_TOKEN_REFRESH:
|
|
||||||
await this.handleTokenRefresh();
|
|
||||||
break;
|
|
||||||
default:
|
|
||||||
this.logger.warn(`Unknown job: ${job.name}`);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Route worker-level errors (e.g. lock renewal after laptop sleep) through
|
|
||||||
// the logger instead of bullmq's raw console.error fallback.
|
|
||||||
@OnWorkerEvent('error')
|
|
||||||
onError(err: Error): void {
|
|
||||||
this.logger.error(`Worker error: ${err.message}`);
|
|
||||||
}
|
|
||||||
|
|
||||||
private async handleTokenRefresh(): Promise<void> {
|
|
||||||
const connections = await this.connectionRepo.findExpiringTokens(
|
|
||||||
TOKEN_REFRESH_WINDOW_MS,
|
|
||||||
);
|
|
||||||
|
|
||||||
if (connections.length === 0) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
this.logger.log(
|
|
||||||
`Refreshing tokens for ${connections.length} connection(s)`,
|
|
||||||
);
|
|
||||||
|
|
||||||
for (const connection of connections) {
|
|
||||||
try {
|
|
||||||
await this.oauthService.getValidAccessToken(connection);
|
|
||||||
} catch (err) {
|
|
||||||
this.logger.error(
|
|
||||||
`Token refresh failed for connection ${connection.id}: ${(err as Error).message}`,
|
|
||||||
);
|
|
||||||
// Dead credential or orphaned row: retire it so findExpiringTokens stops selecting it.
|
|
||||||
if (
|
|
||||||
err instanceof NotFoundException ||
|
|
||||||
err instanceof TokenInvalidError
|
|
||||||
) {
|
|
||||||
await this.connectionRepo
|
|
||||||
.invalidate(connection.id)
|
|
||||||
.catch(() => undefined);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private async handleIntegrationEvent(job: Job): Promise<void> {
|
|
||||||
const { eventName, workspaceId, ...payload } = job.data;
|
|
||||||
|
|
||||||
if (!workspaceId) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const integrations =
|
|
||||||
await this.integrationRepo.findAllByWorkspace(workspaceId);
|
|
||||||
|
|
||||||
for (const integration of integrations) {
|
|
||||||
const provider = this.registry.getProvider(integration.type);
|
|
||||||
if (!provider?.handleEvent) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
let connection: IntegrationConnection | undefined;
|
|
||||||
try {
|
|
||||||
const connections = await this.connectionRepo.findByIntegration(
|
|
||||||
integration.id,
|
|
||||||
);
|
|
||||||
|
|
||||||
connection = connections[0];
|
|
||||||
let accessToken: string | undefined;
|
|
||||||
|
|
||||||
if (connection) {
|
|
||||||
accessToken = await this.oauthService.getValidAccessToken(connection);
|
|
||||||
}
|
|
||||||
|
|
||||||
await provider.handleEvent({
|
|
||||||
eventName,
|
|
||||||
payload,
|
|
||||||
integration: {
|
|
||||||
id: integration.id,
|
|
||||||
type: integration.type,
|
|
||||||
settings: integration.settings as Record<string, any> | null,
|
|
||||||
},
|
|
||||||
connection: connection
|
|
||||||
? { accessToken, userId: connection.userId }
|
|
||||||
: undefined,
|
|
||||||
});
|
|
||||||
} catch (err) {
|
|
||||||
this.logger.error(
|
|
||||||
`Integration event handler failed for ${integration.type}: ${(err as Error).message}`,
|
|
||||||
);
|
|
||||||
if (err instanceof TokenInvalidError && connection) {
|
|
||||||
await this.connectionRepo
|
|
||||||
.invalidate(connection.id)
|
|
||||||
.catch(() => undefined);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,80 +0,0 @@
|
|||||||
import {
|
|
||||||
BadRequestException,
|
|
||||||
Injectable,
|
|
||||||
NotFoundException,
|
|
||||||
} from '@nestjs/common';
|
|
||||||
import { InjectKysely } from 'nestjs-kysely';
|
|
||||||
import { KyselyDB } from '@docmost/db/types/kysely.types';
|
|
||||||
import { executeTx } from '@docmost/db/utils';
|
|
||||||
import { IntegrationRepo } from './repos/integration.repo';
|
|
||||||
import { IntegrationConnectionRepo } from './repos/integration-connection.repo';
|
|
||||||
import { IntegrationRegistry } from './registry/integration-registry';
|
|
||||||
import { Integration } from '@docmost/db/types/entity.types';
|
|
||||||
|
|
||||||
@Injectable()
|
|
||||||
export class IntegrationService {
|
|
||||||
constructor(
|
|
||||||
@InjectKysely() private readonly db: KyselyDB,
|
|
||||||
private readonly integrationRepo: IntegrationRepo,
|
|
||||||
private readonly connectionRepo: IntegrationConnectionRepo,
|
|
||||||
private readonly registry: IntegrationRegistry,
|
|
||||||
) {}
|
|
||||||
|
|
||||||
async getAvailableIntegrations() {
|
|
||||||
return this.registry.getAvailableIntegrations();
|
|
||||||
}
|
|
||||||
|
|
||||||
async getInstalledIntegrations(workspaceId: string): Promise<Integration[]> {
|
|
||||||
return this.integrationRepo.findAllByWorkspace(workspaceId);
|
|
||||||
}
|
|
||||||
|
|
||||||
async findById(integrationId: string): Promise<Integration | undefined> {
|
|
||||||
return this.integrationRepo.findById(integrationId);
|
|
||||||
}
|
|
||||||
|
|
||||||
async install(
|
|
||||||
type: string,
|
|
||||||
workspaceId: string,
|
|
||||||
userId: string,
|
|
||||||
): Promise<Integration> {
|
|
||||||
const provider = this.registry.getProvider(type);
|
|
||||||
if (!provider || provider.definition.hidden) {
|
|
||||||
throw new BadRequestException(`Unknown integration type: ${type}`);
|
|
||||||
}
|
|
||||||
|
|
||||||
// OAuth providers install via install-and-authorize (see OAuthService).
|
|
||||||
if (provider.definition.oauth) {
|
|
||||||
throw new BadRequestException(
|
|
||||||
'This integration is installed by completing its OAuth flow',
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
const existing = await this.integrationRepo.findByWorkspaceAndType(
|
|
||||||
workspaceId,
|
|
||||||
type,
|
|
||||||
);
|
|
||||||
if (existing) {
|
|
||||||
throw new BadRequestException(
|
|
||||||
`Integration "${type}" is already installed`,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
return this.integrationRepo.insertOrRestore({
|
|
||||||
type,
|
|
||||||
workspaceId,
|
|
||||||
installedById: userId,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
async uninstall(integrationId: string, workspaceId: string): Promise<void> {
|
|
||||||
const integration = await this.integrationRepo.findById(integrationId);
|
|
||||||
if (!integration || integration.workspaceId !== workspaceId) {
|
|
||||||
throw new NotFoundException('Integration not found');
|
|
||||||
}
|
|
||||||
// Delete child rows first so no orphan connections keep feeding the token refresh scheduler.
|
|
||||||
await executeTx(this.db, async (trx) => {
|
|
||||||
await this.connectionRepo.deleteByIntegration(integrationId, trx);
|
|
||||||
await this.integrationRepo.softDelete(integrationId, trx);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,159 +0,0 @@
|
|||||||
import {
|
|
||||||
BadRequestException,
|
|
||||||
Body,
|
|
||||||
Controller,
|
|
||||||
Get,
|
|
||||||
HttpCode,
|
|
||||||
HttpStatus,
|
|
||||||
Logger,
|
|
||||||
Param,
|
|
||||||
Post,
|
|
||||||
Query,
|
|
||||||
Res,
|
|
||||||
UseGuards,
|
|
||||||
} from '@nestjs/common';
|
|
||||||
import { FastifyReply } from 'fastify';
|
|
||||||
import { JwtAuthGuard } from '../../../common/guards/jwt-auth.guard';
|
|
||||||
import { AuthUser } from '../../../common/decorators/auth-user.decorator';
|
|
||||||
import { AuthWorkspace } from '../../../common/decorators/auth-workspace.decorator';
|
|
||||||
import { User, Workspace } from '@docmost/db/types/entity.types';
|
|
||||||
import { OAuthService } from './oauth.service';
|
|
||||||
import {
|
|
||||||
OAuthAuthorizeDto,
|
|
||||||
OAuthDisconnectDto,
|
|
||||||
OAuthInstallDto,
|
|
||||||
} from '../dto/integration.dto';
|
|
||||||
import { IntegrationConnectionService } from '../integration-connection.service';
|
|
||||||
import { IntegrationRegistry } from '../registry/integration-registry';
|
|
||||||
import { LicenseCheckService } from '../../../integrations/environment/license-check.service';
|
|
||||||
import { Feature } from '../../../common/features';
|
|
||||||
import { ForbiddenException } from '@nestjs/common';
|
|
||||||
|
|
||||||
@Controller('integrations/oauth')
|
|
||||||
export class OAuthController {
|
|
||||||
private readonly logger = new Logger(OAuthController.name);
|
|
||||||
|
|
||||||
constructor(
|
|
||||||
private readonly oauthService: OAuthService,
|
|
||||||
private readonly connectionService: IntegrationConnectionService,
|
|
||||||
private readonly licenseCheckService: LicenseCheckService,
|
|
||||||
private readonly registry: IntegrationRegistry,
|
|
||||||
) {}
|
|
||||||
|
|
||||||
@UseGuards(JwtAuthGuard)
|
|
||||||
@HttpCode(HttpStatus.OK)
|
|
||||||
@Post('authorize')
|
|
||||||
async authorize(
|
|
||||||
@Body() dto: OAuthAuthorizeDto,
|
|
||||||
@AuthUser() user: User,
|
|
||||||
@AuthWorkspace() workspace: Workspace,
|
|
||||||
) {
|
|
||||||
const { authorizationUrl } = await this.oauthService.getAuthorizationUrl(
|
|
||||||
dto.integrationId,
|
|
||||||
workspace.id,
|
|
||||||
user.id,
|
|
||||||
dto.returnPath,
|
|
||||||
);
|
|
||||||
|
|
||||||
return { authorizationUrl };
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Install-and-authorize: the install flow for every OAuth provider. The
|
|
||||||
* integration row is only created on callback after a successful token
|
|
||||||
* exchange; a cancelled or failed flow persists nothing.
|
|
||||||
*/
|
|
||||||
@UseGuards(JwtAuthGuard)
|
|
||||||
@HttpCode(HttpStatus.OK)
|
|
||||||
@Post('install')
|
|
||||||
async installAndAuthorize(
|
|
||||||
@Body() dto: OAuthInstallDto,
|
|
||||||
@AuthUser() user: User,
|
|
||||||
@AuthWorkspace() workspace: Workspace,
|
|
||||||
) {
|
|
||||||
// This flow creates the integration row on callback success; gate it
|
|
||||||
// like a plain install.
|
|
||||||
if (
|
|
||||||
this.registry.getProvider(dto.type)?.definition.requiresLicense &&
|
|
||||||
!this.licenseCheckService.hasFeature(
|
|
||||||
workspace.licenseKey,
|
|
||||||
Feature.INTEGRATIONS,
|
|
||||||
workspace.plan,
|
|
||||||
)
|
|
||||||
) {
|
|
||||||
throw new ForbiddenException('This feature requires a valid license');
|
|
||||||
}
|
|
||||||
|
|
||||||
const { authorizationUrl } = await this.oauthService.getInstallAuthorizationUrl(
|
|
||||||
dto.type,
|
|
||||||
workspace.id,
|
|
||||||
user.id,
|
|
||||||
);
|
|
||||||
|
|
||||||
return { authorizationUrl };
|
|
||||||
}
|
|
||||||
|
|
||||||
@Get(':type/callback')
|
|
||||||
async callback(
|
|
||||||
@Param('type') type: string,
|
|
||||||
@Query('code') code: string,
|
|
||||||
@Query('state') state: string,
|
|
||||||
@Res() res: FastifyReply,
|
|
||||||
) {
|
|
||||||
if (!state) {
|
|
||||||
throw new BadRequestException('Missing state parameter');
|
|
||||||
}
|
|
||||||
|
|
||||||
const statePayload = this.oauthService.verifySignedState(state);
|
|
||||||
if (!statePayload) {
|
|
||||||
throw new BadRequestException('Invalid or expired OAuth state');
|
|
||||||
}
|
|
||||||
|
|
||||||
// returnUrl is derived server-side at authorize time from the workspace's
|
|
||||||
// own hostname/customDomain (canonical DB truth, not user input), then
|
|
||||||
// signed into the state JWT. Tampering would invalidate the signature.
|
|
||||||
const returnUrl = statePayload.returnUrl;
|
|
||||||
// States signed before returnPath existed fall back to the admin page.
|
|
||||||
const returnPath = statePayload.returnPath ?? '/settings/integrations';
|
|
||||||
|
|
||||||
// Consent denied or cancelled at the provider: no code comes back.
|
|
||||||
if (!code) {
|
|
||||||
return res
|
|
||||||
.redirect(`${returnUrl}${returnPath}?error=oauth_failed`, 302)
|
|
||||||
.send();
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
await this.oauthService.exchangeCodeForTokens(
|
|
||||||
type,
|
|
||||||
code,
|
|
||||||
statePayload.integrationId,
|
|
||||||
statePayload.userId,
|
|
||||||
statePayload.workspaceId,
|
|
||||||
);
|
|
||||||
|
|
||||||
return res.redirect(`${returnUrl}${returnPath}`, 302).send();
|
|
||||||
} catch (err) {
|
|
||||||
this.logger.error(`OAuth callback error for ${type}: ${(err as Error).message}`);
|
|
||||||
return res
|
|
||||||
.redirect(`${returnUrl}${returnPath}?error=oauth_failed`, 302)
|
|
||||||
.send();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@UseGuards(JwtAuthGuard)
|
|
||||||
@HttpCode(HttpStatus.OK)
|
|
||||||
@Post('disconnect')
|
|
||||||
async disconnect(
|
|
||||||
@Body() dto: OAuthDisconnectDto,
|
|
||||||
@AuthUser() user: User,
|
|
||||||
@AuthWorkspace() workspace: Workspace,
|
|
||||||
) {
|
|
||||||
await this.connectionService.disconnect(
|
|
||||||
dto.integrationId,
|
|
||||||
user.id,
|
|
||||||
workspace.id,
|
|
||||||
);
|
|
||||||
return { success: true };
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,473 +0,0 @@
|
|||||||
import {
|
|
||||||
BadRequestException,
|
|
||||||
Injectable,
|
|
||||||
Logger,
|
|
||||||
NotFoundException,
|
|
||||||
} from '@nestjs/common';
|
|
||||||
import { EnvironmentService } from '../../../integrations/environment/environment.service';
|
|
||||||
import { DomainService } from '../../../integrations/environment/domain.service';
|
|
||||||
import { IntegrationRegistry } from '../registry/integration-registry';
|
|
||||||
import { IntegrationRepo } from '../repos/integration.repo';
|
|
||||||
import { IntegrationConnectionRepo } from '../repos/integration-connection.repo';
|
|
||||||
import { WorkspaceRepo } from '@docmost/db/repos/workspace/workspace.repo';
|
|
||||||
import { EncryptionService } from '../../../integrations/encryption/encryption.service';
|
|
||||||
import { IntegrationConnection } from '@docmost/db/types/entity.types';
|
|
||||||
import {
|
|
||||||
OAuthConfig,
|
|
||||||
TokenInvalidError,
|
|
||||||
} from '../registry/integration-provider.interface';
|
|
||||||
import { proxyFetch } from '../../../common/proxy-fetch';
|
|
||||||
import * as crypto from 'crypto';
|
|
||||||
|
|
||||||
const OAUTH_HTTP_TIMEOUT_MS = 10_000;
|
|
||||||
|
|
||||||
type OAuthTokenResponse = {
|
|
||||||
access_token: string;
|
|
||||||
refresh_token?: string;
|
|
||||||
expires_in?: number;
|
|
||||||
token_type?: string;
|
|
||||||
scope?: string;
|
|
||||||
};
|
|
||||||
|
|
||||||
export type OAuthStatePayload = {
|
|
||||||
// For "authorize-only" flows (per-user OAuth on an already-installed
|
|
||||||
// integration) integrationId is set; for "install-and-authorize" flows
|
|
||||||
// (workspace-scoped providers like Slack) it's null until the callback
|
|
||||||
// resolves-or-creates the row atomically with token exchange success.
|
|
||||||
integrationId: string | null;
|
|
||||||
type: string;
|
|
||||||
userId: string;
|
|
||||||
workspaceId: string;
|
|
||||||
// Workspace's canonical URL at authorize time. Cloud workspaces are routed
|
|
||||||
// through a single central OAuth callback (the only redirect_uri Slack/etc.
|
|
||||||
// accept), and this lets the callback redirect the user back to their own
|
|
||||||
// workspace host (subdomain or custom domain) after token exchange.
|
|
||||||
returnUrl: string;
|
|
||||||
// Settings page (relative to returnUrl) to land on after the callback.
|
|
||||||
// Derived server-side from the flow that started it, never from user input.
|
|
||||||
returnPath?: string;
|
|
||||||
exp: number;
|
|
||||||
};
|
|
||||||
|
|
||||||
@Injectable()
|
|
||||||
export class OAuthService {
|
|
||||||
private readonly logger = new Logger(OAuthService.name);
|
|
||||||
|
|
||||||
constructor(
|
|
||||||
private readonly environmentService: EnvironmentService,
|
|
||||||
private readonly domainService: DomainService,
|
|
||||||
private readonly registry: IntegrationRegistry,
|
|
||||||
private readonly integrationRepo: IntegrationRepo,
|
|
||||||
private readonly connectionRepo: IntegrationConnectionRepo,
|
|
||||||
private readonly workspaceRepo: WorkspaceRepo,
|
|
||||||
private readonly encryptionService: EncryptionService,
|
|
||||||
) {}
|
|
||||||
|
|
||||||
async getAuthorizationUrl(
|
|
||||||
integrationId: string,
|
|
||||||
workspaceId: string,
|
|
||||||
userId: string,
|
|
||||||
returnPathOverride?: string,
|
|
||||||
): Promise<{ authorizationUrl: string }> {
|
|
||||||
const integration = await this.integrationRepo.findById(integrationId);
|
|
||||||
if (!integration || integration.workspaceId !== workspaceId) {
|
|
||||||
throw new NotFoundException('Integration not found');
|
|
||||||
}
|
|
||||||
|
|
||||||
const provider = this.registry.getProvider(integration.type);
|
|
||||||
if (!provider || !provider.definition.oauth) {
|
|
||||||
throw new BadRequestException('Integration does not support OAuth');
|
|
||||||
}
|
|
||||||
|
|
||||||
const oauthConfig = provider.getOAuthConfig
|
|
||||||
? provider.getOAuthConfig((integration.settings as Record<string, any>) ?? {})
|
|
||||||
: provider.definition.oauth;
|
|
||||||
|
|
||||||
const callbackUrl = this.buildCallbackUrl(integration.type);
|
|
||||||
|
|
||||||
const workspace = await this.workspaceRepo.findById(workspaceId);
|
|
||||||
const returnUrl = this.domainService.getWorkspaceUrl(
|
|
||||||
workspace ?? { hostname: null, customDomain: null },
|
|
||||||
);
|
|
||||||
|
|
||||||
// Per-user connects are initiated from the account connections page;
|
|
||||||
// workspace-scoped authorizes from the admin integrations page. A connect
|
|
||||||
// started elsewhere (e.g. an editor connect card) passes its own path.
|
|
||||||
const returnPath =
|
|
||||||
returnPathOverride ??
|
|
||||||
((provider.definition.oauth.connectionScope ?? 'user') === 'workspace'
|
|
||||||
? '/settings/integrations'
|
|
||||||
: '/settings/account/connections');
|
|
||||||
|
|
||||||
const state = this.createSignedState({
|
|
||||||
integrationId,
|
|
||||||
type: integration.type,
|
|
||||||
userId,
|
|
||||||
workspaceId,
|
|
||||||
returnUrl,
|
|
||||||
returnPath,
|
|
||||||
exp: Date.now() + 10 * 60 * 1000,
|
|
||||||
});
|
|
||||||
|
|
||||||
const params = new URLSearchParams({
|
|
||||||
client_id: this.getClientId(integration.type),
|
|
||||||
redirect_uri: callbackUrl,
|
|
||||||
response_type: 'code',
|
|
||||||
state,
|
|
||||||
});
|
|
||||||
|
|
||||||
const scope = oauthConfig.scopes
|
|
||||||
.map((s) => encodeURIComponent(s))
|
|
||||||
.join('%20');
|
|
||||||
|
|
||||||
return {
|
|
||||||
authorizationUrl: `${oauthConfig.authUrl}?${params.toString()}&scope=${scope}`,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Install-and-authorize: the install flow for every OAuth provider.
|
|
||||||
*
|
|
||||||
* Skips creating the integration row up front. The callback persists it
|
|
||||||
* only after a successful token exchange, so a cancelled consent screen or
|
|
||||||
* misconfigured client credentials leave nothing half-installed. Refusing
|
|
||||||
* the already-installed case here keeps the install button idempotent.
|
|
||||||
*/
|
|
||||||
async getInstallAuthorizationUrl(
|
|
||||||
type: string,
|
|
||||||
workspaceId: string,
|
|
||||||
userId: string,
|
|
||||||
): Promise<{ authorizationUrl: string }> {
|
|
||||||
const provider = this.registry.getProvider(type);
|
|
||||||
if (!provider || !provider.definition.oauth) {
|
|
||||||
throw new BadRequestException('Integration does not support OAuth');
|
|
||||||
}
|
|
||||||
|
|
||||||
const existing = await this.integrationRepo.findByWorkspaceAndType(
|
|
||||||
workspaceId,
|
|
||||||
type,
|
|
||||||
);
|
|
||||||
if (existing) {
|
|
||||||
throw new BadRequestException(
|
|
||||||
`Integration "${type}" is already installed`,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
const oauthConfig = provider.getOAuthConfig
|
|
||||||
? provider.getOAuthConfig({})
|
|
||||||
: provider.definition.oauth;
|
|
||||||
|
|
||||||
const callbackUrl = this.buildCallbackUrl(type);
|
|
||||||
|
|
||||||
const workspace = await this.workspaceRepo.findById(workspaceId);
|
|
||||||
const returnUrl = this.domainService.getWorkspaceUrl(
|
|
||||||
workspace ?? { hostname: null, customDomain: null },
|
|
||||||
);
|
|
||||||
|
|
||||||
const state = this.createSignedState({
|
|
||||||
integrationId: null,
|
|
||||||
type,
|
|
||||||
userId,
|
|
||||||
workspaceId,
|
|
||||||
returnUrl,
|
|
||||||
returnPath: '/settings/integrations',
|
|
||||||
exp: Date.now() + 10 * 60 * 1000,
|
|
||||||
});
|
|
||||||
|
|
||||||
const params = new URLSearchParams({
|
|
||||||
client_id: this.getClientId(type),
|
|
||||||
redirect_uri: callbackUrl,
|
|
||||||
response_type: 'code',
|
|
||||||
state,
|
|
||||||
});
|
|
||||||
|
|
||||||
const scope = oauthConfig.scopes
|
|
||||||
.map((s) => encodeURIComponent(s))
|
|
||||||
.join('%20');
|
|
||||||
|
|
||||||
return {
|
|
||||||
authorizationUrl: `${oauthConfig.authUrl}?${params.toString()}&scope=${scope}`,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
verifySignedState(state: string): OAuthStatePayload | null {
|
|
||||||
const dotIndex = state.lastIndexOf('.');
|
|
||||||
if (dotIndex === -1) return null;
|
|
||||||
|
|
||||||
const data = state.substring(0, dotIndex);
|
|
||||||
const signature = state.substring(dotIndex + 1);
|
|
||||||
|
|
||||||
const secret = this.environmentService.getAppSecret();
|
|
||||||
const expected = crypto
|
|
||||||
.createHmac('sha256', secret)
|
|
||||||
.update(data)
|
|
||||||
.digest('base64url');
|
|
||||||
|
|
||||||
if (signature !== expected) return null;
|
|
||||||
|
|
||||||
try {
|
|
||||||
const payload: OAuthStatePayload = JSON.parse(
|
|
||||||
Buffer.from(data, 'base64url').toString(),
|
|
||||||
);
|
|
||||||
|
|
||||||
if (payload.exp < Date.now()) return null;
|
|
||||||
|
|
||||||
return payload;
|
|
||||||
} catch {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async exchangeCodeForTokens(
|
|
||||||
type: string,
|
|
||||||
code: string,
|
|
||||||
integrationId: string | null,
|
|
||||||
userId: string,
|
|
||||||
workspaceId: string,
|
|
||||||
): Promise<IntegrationConnection> {
|
|
||||||
const provider = this.registry.getProvider(type);
|
|
||||||
if (!provider || !provider.definition.oauth) {
|
|
||||||
throw new BadRequestException('Integration does not support OAuth');
|
|
||||||
}
|
|
||||||
|
|
||||||
// Install flow: no row yet; persisted only after the token exchange succeeds.
|
|
||||||
let integration = integrationId
|
|
||||||
? await this.integrationRepo.findById(integrationId)
|
|
||||||
: null;
|
|
||||||
|
|
||||||
const settings = (integration?.settings as Record<string, any>) ?? {};
|
|
||||||
|
|
||||||
const oauthConfig = provider.getOAuthConfig
|
|
||||||
? provider.getOAuthConfig(settings)
|
|
||||||
: provider.definition.oauth;
|
|
||||||
|
|
||||||
const tokenResponse = await this.requestTokens(
|
|
||||||
oauthConfig,
|
|
||||||
type,
|
|
||||||
code,
|
|
||||||
);
|
|
||||||
|
|
||||||
if (!integration) {
|
|
||||||
integration = await this.integrationRepo.insertOrRestore({
|
|
||||||
type,
|
|
||||||
workspaceId,
|
|
||||||
installedById: userId,
|
|
||||||
});
|
|
||||||
integrationId = integration.id;
|
|
||||||
}
|
|
||||||
|
|
||||||
const encryptedAccessToken = this.encryptionService.encrypt(
|
|
||||||
tokenResponse.access_token,
|
|
||||||
);
|
|
||||||
const encryptedRefreshToken = tokenResponse.refresh_token
|
|
||||||
? this.encryptionService.encrypt(tokenResponse.refresh_token)
|
|
||||||
: null;
|
|
||||||
|
|
||||||
const tokenExpiresAt = tokenResponse.expires_in
|
|
||||||
? new Date(Date.now() + tokenResponse.expires_in * 1000)
|
|
||||||
: null;
|
|
||||||
|
|
||||||
const connectionScope =
|
|
||||||
provider.definition.oauth?.connectionScope ?? 'user';
|
|
||||||
|
|
||||||
const connection =
|
|
||||||
connectionScope === 'workspace'
|
|
||||||
? await this.connectionRepo.upsertWorkspaceConnection({
|
|
||||||
integrationId,
|
|
||||||
userId,
|
|
||||||
workspaceId,
|
|
||||||
accessToken: encryptedAccessToken,
|
|
||||||
refreshToken: encryptedRefreshToken,
|
|
||||||
tokenExpiresAt,
|
|
||||||
scopes: tokenResponse.scope ?? null,
|
|
||||||
})
|
|
||||||
: await this.connectionRepo.upsert({
|
|
||||||
integrationId,
|
|
||||||
userId,
|
|
||||||
workspaceId,
|
|
||||||
accessToken: encryptedAccessToken,
|
|
||||||
refreshToken: encryptedRefreshToken,
|
|
||||||
tokenExpiresAt,
|
|
||||||
scopes: tokenResponse.scope ?? null,
|
|
||||||
});
|
|
||||||
|
|
||||||
if (provider.onConnected) {
|
|
||||||
await provider.onConnected({
|
|
||||||
integrationId,
|
|
||||||
workspaceId,
|
|
||||||
accessToken: tokenResponse.access_token,
|
|
||||||
refreshToken: tokenResponse.refresh_token,
|
|
||||||
userId,
|
|
||||||
metadata: tokenResponse,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
return connection;
|
|
||||||
}
|
|
||||||
|
|
||||||
async getValidAccessToken(
|
|
||||||
connection: IntegrationConnection,
|
|
||||||
): Promise<string> {
|
|
||||||
if (connection.invalidatedAt) {
|
|
||||||
throw new TokenInvalidError();
|
|
||||||
}
|
|
||||||
const accessToken = this.encryptionService.decrypt(connection.accessToken);
|
|
||||||
|
|
||||||
const needsRefresh =
|
|
||||||
connection.tokenExpiresAt &&
|
|
||||||
connection.refreshToken &&
|
|
||||||
new Date(connection.tokenExpiresAt).getTime() - Date.now() < 5 * 60 * 1000;
|
|
||||||
|
|
||||||
if (!needsRefresh) {
|
|
||||||
return accessToken;
|
|
||||||
}
|
|
||||||
|
|
||||||
return this.refreshAccessToken(connection);
|
|
||||||
}
|
|
||||||
|
|
||||||
private async refreshAccessToken(
|
|
||||||
connection: IntegrationConnection,
|
|
||||||
): Promise<string> {
|
|
||||||
const refreshToken = this.encryptionService.decrypt(
|
|
||||||
connection.refreshToken,
|
|
||||||
);
|
|
||||||
|
|
||||||
const integration = await this.integrationRepo.findById(
|
|
||||||
connection.integrationId,
|
|
||||||
);
|
|
||||||
if (!integration) {
|
|
||||||
throw new NotFoundException('Integration not found');
|
|
||||||
}
|
|
||||||
|
|
||||||
const provider = this.registry.getProvider(integration.type);
|
|
||||||
if (!provider || !provider.definition.oauth) {
|
|
||||||
throw new BadRequestException('Integration does not support OAuth');
|
|
||||||
}
|
|
||||||
|
|
||||||
const oauthConfig = provider.getOAuthConfig
|
|
||||||
? provider.getOAuthConfig((integration.settings as Record<string, any>) ?? {})
|
|
||||||
: provider.definition.oauth;
|
|
||||||
|
|
||||||
const params = new URLSearchParams({
|
|
||||||
grant_type: 'refresh_token',
|
|
||||||
client_id: this.getClientId(integration.type),
|
|
||||||
client_secret: this.getClientSecret(integration.type),
|
|
||||||
refresh_token: refreshToken,
|
|
||||||
});
|
|
||||||
|
|
||||||
try {
|
|
||||||
const response = await proxyFetch(oauthConfig.tokenUrl, {
|
|
||||||
method: 'POST',
|
|
||||||
headers: { 'Content-Type': 'application/x-www-form-urlencoded', Accept: 'application/json' },
|
|
||||||
body: params.toString(),
|
|
||||||
signal: AbortSignal.timeout(OAUTH_HTTP_TIMEOUT_MS),
|
|
||||||
});
|
|
||||||
|
|
||||||
if (!response.ok) {
|
|
||||||
this.logger.error(
|
|
||||||
`Token refresh failed for ${integration.type}: ${response.status}`,
|
|
||||||
);
|
|
||||||
// 400/401 from the token endpoint means invalid_grant/invalid_client:
|
|
||||||
// the refresh token is dead, not a transient failure.
|
|
||||||
if (response.status === 400 || response.status === 401) {
|
|
||||||
throw new TokenInvalidError(
|
|
||||||
`Refresh token rejected for ${integration.type}`,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
throw new BadRequestException('Token refresh failed');
|
|
||||||
}
|
|
||||||
|
|
||||||
const data: OAuthTokenResponse = await response.json();
|
|
||||||
const encryptedAccessToken = this.encryptionService.encrypt(
|
|
||||||
data.access_token,
|
|
||||||
);
|
|
||||||
const encryptedRefreshToken = data.refresh_token
|
|
||||||
? this.encryptionService.encrypt(data.refresh_token)
|
|
||||||
: connection.refreshToken;
|
|
||||||
const tokenExpiresAt = data.expires_in
|
|
||||||
? new Date(Date.now() + data.expires_in * 1000)
|
|
||||||
: null;
|
|
||||||
|
|
||||||
await this.connectionRepo.update(connection.id, {
|
|
||||||
accessToken: encryptedAccessToken,
|
|
||||||
refreshToken: encryptedRefreshToken,
|
|
||||||
tokenExpiresAt,
|
|
||||||
invalidatedAt: null,
|
|
||||||
});
|
|
||||||
|
|
||||||
return data.access_token;
|
|
||||||
} catch (err) {
|
|
||||||
if (err instanceof TokenInvalidError) {
|
|
||||||
throw err;
|
|
||||||
}
|
|
||||||
this.logger.error(`Token refresh error: ${(err as Error).message}`);
|
|
||||||
throw new BadRequestException('Failed to refresh token');
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private async requestTokens(
|
|
||||||
oauthConfig: OAuthConfig,
|
|
||||||
type: string,
|
|
||||||
code: string,
|
|
||||||
): Promise<OAuthTokenResponse> {
|
|
||||||
const params = new URLSearchParams({
|
|
||||||
grant_type: 'authorization_code',
|
|
||||||
client_id: this.getClientId(type),
|
|
||||||
client_secret: this.getClientSecret(type),
|
|
||||||
code,
|
|
||||||
redirect_uri: this.buildCallbackUrl(type),
|
|
||||||
});
|
|
||||||
|
|
||||||
const response = await proxyFetch(oauthConfig.tokenUrl, {
|
|
||||||
method: 'POST',
|
|
||||||
headers: { 'Content-Type': 'application/x-www-form-urlencoded', Accept: 'application/json' },
|
|
||||||
body: params.toString(),
|
|
||||||
signal: AbortSignal.timeout(OAUTH_HTTP_TIMEOUT_MS),
|
|
||||||
});
|
|
||||||
|
|
||||||
if (!response.ok) {
|
|
||||||
const body = await response.text();
|
|
||||||
this.logger.error(`Token exchange failed for ${type}: ${response.status} ${body}`);
|
|
||||||
throw new BadRequestException('OAuth token exchange failed');
|
|
||||||
}
|
|
||||||
|
|
||||||
return response.json();
|
|
||||||
}
|
|
||||||
|
|
||||||
buildCallbackUrl(type: string): string {
|
|
||||||
const appUrl = this.environmentService.getAppUrl();
|
|
||||||
return `${appUrl}/api/integrations/oauth/${type}/callback`;
|
|
||||||
}
|
|
||||||
|
|
||||||
private createSignedState(payload: OAuthStatePayload): string {
|
|
||||||
const data = Buffer.from(JSON.stringify(payload)).toString('base64url');
|
|
||||||
const secret = this.environmentService.getAppSecret();
|
|
||||||
const signature = crypto
|
|
||||||
.createHmac('sha256', secret)
|
|
||||||
.update(data)
|
|
||||||
.digest('base64url');
|
|
||||||
return `${data}.${signature}`;
|
|
||||||
}
|
|
||||||
|
|
||||||
private getClientId(type: string): string {
|
|
||||||
const envKey = `INTEGRATION_${type.toUpperCase()}_CLIENT_ID`;
|
|
||||||
const value = process.env[envKey];
|
|
||||||
if (!value) {
|
|
||||||
throw new BadRequestException(
|
|
||||||
`Missing environment variable: ${envKey}`,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
return value;
|
|
||||||
}
|
|
||||||
|
|
||||||
private getClientSecret(type: string): string {
|
|
||||||
const envKey = `INTEGRATION_${type.toUpperCase()}_CLIENT_SECRET`;
|
|
||||||
const value = process.env[envKey];
|
|
||||||
if (!value) {
|
|
||||||
throw new BadRequestException(
|
|
||||||
`Missing environment variable: ${envKey}`,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
return value;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,72 +0,0 @@
|
|||||||
import { UnfurlPattern } from '../../registry/integration-provider.interface';
|
|
||||||
|
|
||||||
function escapeForRegex(str: string): string {
|
|
||||||
return str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
||||||
}
|
|
||||||
|
|
||||||
export function buildGitHubPatterns(baseUrl: string): UnfurlPattern[] {
|
|
||||||
const escaped = escapeForRegex(baseUrl);
|
|
||||||
return [
|
|
||||||
// Commit within a PR: /:owner/:repo/pull/:num/commits/:sha
|
|
||||||
{
|
|
||||||
regex: new RegExp(
|
|
||||||
`^${escaped}\\/([^\\/]+)\\/([^\\/]+)\\/pull\\/(\\d+)\\/commits\\/([a-f0-9]+)`,
|
|
||||||
),
|
|
||||||
type: 'github-pr-commit',
|
|
||||||
},
|
|
||||||
// PR sub-pages: /:owner/:repo/pull/:num(/checks|/commits|/files)?
|
|
||||||
{
|
|
||||||
regex: new RegExp(`^${escaped}\\/([^\\/]+)\\/([^\\/]+)\\/pull\\/(\\d+)`),
|
|
||||||
type: 'github-pr',
|
|
||||||
},
|
|
||||||
// Single issue: /:owner/:repo/issues/:num
|
|
||||||
{
|
|
||||||
regex: new RegExp(
|
|
||||||
`^${escaped}\\/([^\\/]+)\\/([^\\/]+)\\/issues\\/(\\d+)`,
|
|
||||||
),
|
|
||||||
type: 'github-issue',
|
|
||||||
},
|
|
||||||
// Commit: /:owner/:repo/commit(s)/:sha
|
|
||||||
{
|
|
||||||
regex: new RegExp(
|
|
||||||
`^${escaped}\\/([^\\/]+)\\/([^\\/]+)\\/commits?\\/([a-f0-9]+)`,
|
|
||||||
),
|
|
||||||
type: 'github-commit',
|
|
||||||
},
|
|
||||||
// File/blob: /:owner/:repo/blob/:ref/:path(#L:start(-L:end))?
|
|
||||||
{
|
|
||||||
regex: new RegExp(
|
|
||||||
`^${escaped}\\/([^\\/]+)\\/([^\\/]+)\\/blob\\/([^\\/]+)\\/(.+?)(?:#L(\\d+)(?:-L(\\d+))?)?$`,
|
|
||||||
),
|
|
||||||
type: 'github-file',
|
|
||||||
},
|
|
||||||
// Pulls list: /:owner/:repo/pulls
|
|
||||||
{
|
|
||||||
regex: new RegExp(
|
|
||||||
`^${escaped}\\/([^\\/]+)\\/([^\\/]+)\\/pulls(?:\\/.*)?(?:\\?.*)?$`,
|
|
||||||
),
|
|
||||||
type: 'github-pulls-list',
|
|
||||||
},
|
|
||||||
// Issues list: /:owner/:repo/issues(/created_by/...|/assigned/...)?
|
|
||||||
{
|
|
||||||
regex: new RegExp(
|
|
||||||
`^${escaped}\\/([^\\/]+)\\/([^\\/]+)\\/issues(?:\\/(?:created_by|assigned)\\/[\\w.\\/-]+)?\\/?(?:\\?.*)?$`,
|
|
||||||
),
|
|
||||||
type: 'github-issues-list',
|
|
||||||
},
|
|
||||||
// Releases: /:owner/:repo/releases
|
|
||||||
{
|
|
||||||
regex: new RegExp(
|
|
||||||
`^${escaped}\\/([^\\/]+)\\/([^\\/]+)\\/releases(?:\\/.*)?(?:\\?.*)?$`,
|
|
||||||
),
|
|
||||||
type: 'github-releases-list',
|
|
||||||
},
|
|
||||||
// Repo: /:owner/:repo
|
|
||||||
{
|
|
||||||
regex: new RegExp(
|
|
||||||
`^${escaped}\\/([a-zA-Z0-9\\-_.]+)\\/([a-zA-Z0-9\\-_.]+)\\/?$`,
|
|
||||||
),
|
|
||||||
type: 'github-repo',
|
|
||||||
},
|
|
||||||
];
|
|
||||||
}
|
|
||||||
@@ -1,21 +0,0 @@
|
|||||||
import { Module, OnModuleInit } from '@nestjs/common';
|
|
||||||
import { GitHubProvider } from './github.provider';
|
|
||||||
import { GitHubService } from './github.service';
|
|
||||||
import { IntegrationRegistry } from '../../registry/integration-registry';
|
|
||||||
import { IntegrationModule } from '../../integration.module';
|
|
||||||
|
|
||||||
@Module({
|
|
||||||
imports: [IntegrationModule],
|
|
||||||
providers: [GitHubProvider, GitHubService],
|
|
||||||
exports: [GitHubProvider],
|
|
||||||
})
|
|
||||||
export class GitHubModule implements OnModuleInit {
|
|
||||||
constructor(
|
|
||||||
private readonly registry: IntegrationRegistry,
|
|
||||||
private readonly githubProvider: GitHubProvider,
|
|
||||||
) {}
|
|
||||||
|
|
||||||
onModuleInit() {
|
|
||||||
this.registry.register(this.githubProvider);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,154 +0,0 @@
|
|||||||
import { Injectable } from '@nestjs/common';
|
|
||||||
import {
|
|
||||||
IntegrationProvider,
|
|
||||||
IntegrationDefinition,
|
|
||||||
LinkDescription,
|
|
||||||
OAuthConfig,
|
|
||||||
UnfurlPattern,
|
|
||||||
UnfurlOpts,
|
|
||||||
UnfurlResult,
|
|
||||||
} from '../../registry/integration-provider.interface';
|
|
||||||
import { GitHubService } from './github.service';
|
|
||||||
import { buildGitHubPatterns } from './github-patterns';
|
|
||||||
|
|
||||||
const DEFAULT_BASE_URL = 'https://github.com';
|
|
||||||
|
|
||||||
@Injectable()
|
|
||||||
export class GitHubProvider extends IntegrationProvider {
|
|
||||||
definition: IntegrationDefinition = {
|
|
||||||
type: 'github',
|
|
||||||
name: 'GitHub',
|
|
||||||
description: 'Link previews for repos, pull requests, issues, commits, and files',
|
|
||||||
icon: 'github',
|
|
||||||
capabilities: ['oauth', 'unfurl'],
|
|
||||||
oauth: {
|
|
||||||
authUrl: 'https://github.com/login/oauth/authorize',
|
|
||||||
tokenUrl: 'https://github.com/login/oauth/access_token',
|
|
||||||
scopes: ['repo', 'read:user'],
|
|
||||||
},
|
|
||||||
unfurlPatterns: buildGitHubPatterns('https://github.com'),
|
|
||||||
};
|
|
||||||
|
|
||||||
constructor(private readonly githubService: GitHubService) {
|
|
||||||
super();
|
|
||||||
}
|
|
||||||
|
|
||||||
getOAuthConfig(settings: Record<string, any>): OAuthConfig {
|
|
||||||
const baseUrl = this.resolveBaseUrl();
|
|
||||||
return {
|
|
||||||
authUrl: `${baseUrl}/login/oauth/authorize`,
|
|
||||||
tokenUrl: `${baseUrl}/login/oauth/access_token`,
|
|
||||||
scopes: ['repo', 'read:user'],
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
getUnfurlPatterns(settings: Record<string, any>): UnfurlPattern[] {
|
|
||||||
const baseUrl = this.resolveBaseUrl();
|
|
||||||
if (baseUrl === DEFAULT_BASE_URL) return [];
|
|
||||||
return buildGitHubPatterns(baseUrl);
|
|
||||||
}
|
|
||||||
|
|
||||||
async unfurl(opts: UnfurlOpts): Promise<UnfurlResult> {
|
|
||||||
const { match, patternType, accessToken, url } = opts;
|
|
||||||
const apiBaseUrl = this.resolveApiBaseUrl(url);
|
|
||||||
const owner = match[1];
|
|
||||||
const repo = match[2];
|
|
||||||
|
|
||||||
switch (patternType) {
|
|
||||||
case 'github-pr': {
|
|
||||||
const number = parseInt(match[3], 10);
|
|
||||||
return this.githubService.unfurlPullRequest(
|
|
||||||
accessToken, apiBaseUrl, owner, repo, number, url,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
case 'github-issue': {
|
|
||||||
const number = parseInt(match[3], 10);
|
|
||||||
return this.githubService.unfurlIssue(
|
|
||||||
accessToken, apiBaseUrl, owner, repo, number, url,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
case 'github-repo':
|
|
||||||
return this.githubService.unfurlRepo(
|
|
||||||
accessToken, apiBaseUrl, owner, repo, url,
|
|
||||||
);
|
|
||||||
|
|
||||||
case 'github-commit': {
|
|
||||||
const sha = match[3];
|
|
||||||
return this.githubService.unfurlCommit(
|
|
||||||
accessToken, apiBaseUrl, owner, repo, sha, url,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
case 'github-pr-commit': {
|
|
||||||
const sha = match[4];
|
|
||||||
return this.githubService.unfurlCommit(
|
|
||||||
accessToken, apiBaseUrl, owner, repo, sha, url,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
case 'github-file': {
|
|
||||||
const ref = match[3];
|
|
||||||
const path = match[4];
|
|
||||||
const startLine = match[5] ? parseInt(match[5], 10) : undefined;
|
|
||||||
const endLine = match[6] ? parseInt(match[6], 10) : undefined;
|
|
||||||
return this.githubService.unfurlFile(
|
|
||||||
owner, repo, ref, path, startLine, endLine, url,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
case 'github-pulls-list':
|
|
||||||
case 'github-issues-list':
|
|
||||||
case 'github-releases-list':
|
|
||||||
return this.githubService.unfurlCollectionPage(
|
|
||||||
accessToken, apiBaseUrl, owner, repo, patternType.replace('github-', ''), url,
|
|
||||||
);
|
|
||||||
|
|
||||||
default:
|
|
||||||
throw new Error(`Unknown GitHub pattern type: ${patternType}`);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
describeLink(
|
|
||||||
patternType: string,
|
|
||||||
match: RegExpMatchArray,
|
|
||||||
): LinkDescription | null {
|
|
||||||
const repo = `${match[1]}/${match[2]}`;
|
|
||||||
switch (patternType) {
|
|
||||||
case 'github-pr':
|
|
||||||
return { title: `Pull Request #${match[3]}`, description: repo };
|
|
||||||
case 'github-pr-commit':
|
|
||||||
return { title: `Commit ${match[4].slice(0, 7)}`, description: repo };
|
|
||||||
case 'github-issue':
|
|
||||||
return { title: `Issue #${match[3]}`, description: repo };
|
|
||||||
case 'github-commit':
|
|
||||||
return { title: `Commit ${match[3].slice(0, 7)}`, description: repo };
|
|
||||||
case 'github-file':
|
|
||||||
return { title: match[4], description: repo };
|
|
||||||
case 'github-pulls-list':
|
|
||||||
return { title: 'Pull Requests', description: repo };
|
|
||||||
case 'github-issues-list':
|
|
||||||
return { title: 'Issues', description: repo };
|
|
||||||
case 'github-releases-list':
|
|
||||||
return { title: 'Releases', description: repo };
|
|
||||||
case 'github-repo':
|
|
||||||
return { title: repo };
|
|
||||||
default:
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private resolveBaseUrl(): string {
|
|
||||||
const baseUrl = process.env.INTEGRATION_GITHUB_BASE_URL;
|
|
||||||
return baseUrl ? baseUrl.replace(/\/+$/, '') : DEFAULT_BASE_URL;
|
|
||||||
}
|
|
||||||
|
|
||||||
private resolveApiBaseUrl(url: string): string {
|
|
||||||
const parsed = new URL(url);
|
|
||||||
if (parsed.hostname === 'github.com') {
|
|
||||||
return 'https://api.github.com';
|
|
||||||
}
|
|
||||||
return `${parsed.origin}/api/v3`;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,267 +0,0 @@
|
|||||||
import { Injectable, Logger } from '@nestjs/common';
|
|
||||||
import { UnfurlResult } from '../../registry/integration-provider.interface';
|
|
||||||
import { relativeTime } from '../../utils/relative-time';
|
|
||||||
import { providerApiFetch } from '../../utils/provider-fetch';
|
|
||||||
|
|
||||||
@Injectable()
|
|
||||||
export class GitHubService {
|
|
||||||
private readonly logger = new Logger(GitHubService.name);
|
|
||||||
|
|
||||||
async unfurlPullRequest(
|
|
||||||
accessToken: string,
|
|
||||||
apiBaseUrl: string,
|
|
||||||
owner: string,
|
|
||||||
repo: string,
|
|
||||||
number: number,
|
|
||||||
url: string,
|
|
||||||
): Promise<UnfurlResult> {
|
|
||||||
const data = await this.apiGet(
|
|
||||||
accessToken,
|
|
||||||
apiBaseUrl,
|
|
||||||
`/repos/${owner}/${repo}/pulls/${number}`,
|
|
||||||
);
|
|
||||||
|
|
||||||
const prAuthor = data.user?.login;
|
|
||||||
const prDesc = [
|
|
||||||
`#${data.number}`,
|
|
||||||
relativeTime(data.updated_at ?? data.created_at),
|
|
||||||
prAuthor,
|
|
||||||
].filter(Boolean).join(' · ');
|
|
||||||
|
|
||||||
return {
|
|
||||||
title: data.title,
|
|
||||||
description: prDesc,
|
|
||||||
url,
|
|
||||||
provider: 'github',
|
|
||||||
providerIcon: 'github',
|
|
||||||
status: this.formatPrStatus(data),
|
|
||||||
statusColor: this.getPrStatusColor(data),
|
|
||||||
author: prAuthor,
|
|
||||||
authorAvatarUrl: data.user?.avatar_url,
|
|
||||||
metadata: {
|
|
||||||
type: 'pr',
|
|
||||||
number: data.number,
|
|
||||||
repo: `${owner}/${repo}`,
|
|
||||||
labels: data.labels?.map((l: any) => l.name) ?? [],
|
|
||||||
draft: data.draft,
|
|
||||||
additions: data.additions,
|
|
||||||
deletions: data.deletions,
|
|
||||||
},
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
async unfurlIssue(
|
|
||||||
accessToken: string,
|
|
||||||
apiBaseUrl: string,
|
|
||||||
owner: string,
|
|
||||||
repo: string,
|
|
||||||
number: number,
|
|
||||||
url: string,
|
|
||||||
): Promise<UnfurlResult> {
|
|
||||||
const data = await this.apiGet(
|
|
||||||
accessToken,
|
|
||||||
apiBaseUrl,
|
|
||||||
`/repos/${owner}/${repo}/issues/${number}`,
|
|
||||||
);
|
|
||||||
|
|
||||||
const issueAuthor = data.user?.login;
|
|
||||||
const issueDesc = [
|
|
||||||
`#${data.number}`,
|
|
||||||
relativeTime(data.updated_at ?? data.created_at),
|
|
||||||
issueAuthor,
|
|
||||||
].filter(Boolean).join(' · ');
|
|
||||||
|
|
||||||
return {
|
|
||||||
title: data.title,
|
|
||||||
description: issueDesc,
|
|
||||||
url,
|
|
||||||
provider: 'github',
|
|
||||||
providerIcon: 'github',
|
|
||||||
status: data.state,
|
|
||||||
statusColor: data.state === 'open' ? 'green' : 'purple',
|
|
||||||
author: issueAuthor,
|
|
||||||
authorAvatarUrl: data.user?.avatar_url,
|
|
||||||
metadata: {
|
|
||||||
type: 'issue',
|
|
||||||
number: data.number,
|
|
||||||
repo: `${owner}/${repo}`,
|
|
||||||
labels: data.labels?.map((l: any) => l.name) ?? [],
|
|
||||||
assignees: data.assignees?.map((a: any) => a.login) ?? [],
|
|
||||||
},
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
async unfurlRepo(
|
|
||||||
accessToken: string,
|
|
||||||
apiBaseUrl: string,
|
|
||||||
owner: string,
|
|
||||||
repo: string,
|
|
||||||
url: string,
|
|
||||||
): Promise<UnfurlResult> {
|
|
||||||
const data = await this.apiGet(
|
|
||||||
accessToken,
|
|
||||||
apiBaseUrl,
|
|
||||||
`/repos/${owner}/${repo}`,
|
|
||||||
);
|
|
||||||
|
|
||||||
const visibility = data.private ? 'Private' : 'Public';
|
|
||||||
|
|
||||||
return {
|
|
||||||
title: data.full_name,
|
|
||||||
description: data.description?.slice(0, 200) ?? undefined,
|
|
||||||
url,
|
|
||||||
provider: 'github',
|
|
||||||
providerIcon: 'github',
|
|
||||||
status: visibility,
|
|
||||||
statusColor: data.private ? 'gray' : 'green',
|
|
||||||
author: data.owner?.login,
|
|
||||||
authorAvatarUrl: data.owner?.avatar_url,
|
|
||||||
metadata: {
|
|
||||||
type: 'repo',
|
|
||||||
repo: `${owner}/${repo}`,
|
|
||||||
stars: data.stargazers_count,
|
|
||||||
forks: data.forks_count,
|
|
||||||
language: data.language,
|
|
||||||
defaultBranch: data.default_branch,
|
|
||||||
},
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
async unfurlCommit(
|
|
||||||
accessToken: string,
|
|
||||||
apiBaseUrl: string,
|
|
||||||
owner: string,
|
|
||||||
repo: string,
|
|
||||||
sha: string,
|
|
||||||
url: string,
|
|
||||||
): Promise<UnfurlResult> {
|
|
||||||
const data = await this.apiGet(
|
|
||||||
accessToken,
|
|
||||||
apiBaseUrl,
|
|
||||||
`/repos/${owner}/${repo}/commits/${sha}`,
|
|
||||||
);
|
|
||||||
|
|
||||||
const shortSha = data.sha?.slice(0, 7);
|
|
||||||
|
|
||||||
const commitAuthor = data.author?.login ?? data.commit?.author?.name;
|
|
||||||
const commitDesc = [
|
|
||||||
shortSha,
|
|
||||||
relativeTime(data.commit?.author?.date ?? data.commit?.committer?.date),
|
|
||||||
commitAuthor,
|
|
||||||
].filter(Boolean).join(' · ');
|
|
||||||
|
|
||||||
return {
|
|
||||||
title: data.commit?.message?.split('\n')[0] ?? shortSha,
|
|
||||||
description: commitDesc,
|
|
||||||
url,
|
|
||||||
provider: 'github',
|
|
||||||
providerIcon: 'github',
|
|
||||||
author: commitAuthor,
|
|
||||||
authorAvatarUrl: data.author?.avatar_url,
|
|
||||||
metadata: {
|
|
||||||
type: 'commit',
|
|
||||||
sha: data.sha,
|
|
||||||
shortSha,
|
|
||||||
repo: `${owner}/${repo}`,
|
|
||||||
stats: data.stats,
|
|
||||||
},
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
unfurlFile(
|
|
||||||
owner: string,
|
|
||||||
repo: string,
|
|
||||||
ref: string,
|
|
||||||
path: string,
|
|
||||||
startLine: number | undefined,
|
|
||||||
endLine: number | undefined,
|
|
||||||
url: string,
|
|
||||||
): UnfurlResult {
|
|
||||||
const fileName = path.split('/').pop() ?? path;
|
|
||||||
const lineRange = startLine
|
|
||||||
? endLine
|
|
||||||
? `L${startLine}-L${endLine}`
|
|
||||||
: `L${startLine}`
|
|
||||||
: undefined;
|
|
||||||
|
|
||||||
return {
|
|
||||||
title: lineRange ? `${fileName}#${lineRange}` : fileName,
|
|
||||||
description: `${owner}/${repo} · ${ref.slice(0, 7)}`,
|
|
||||||
url,
|
|
||||||
provider: 'github',
|
|
||||||
providerIcon: 'github',
|
|
||||||
metadata: {
|
|
||||||
type: 'file',
|
|
||||||
repo: `${owner}/${repo}`,
|
|
||||||
ref,
|
|
||||||
path,
|
|
||||||
startLine,
|
|
||||||
endLine,
|
|
||||||
},
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
async unfurlCollectionPage(
|
|
||||||
accessToken: string,
|
|
||||||
apiBaseUrl: string,
|
|
||||||
owner: string,
|
|
||||||
repo: string,
|
|
||||||
collectionType: string,
|
|
||||||
url: string,
|
|
||||||
): Promise<UnfurlResult> {
|
|
||||||
const data = await this.apiGet(
|
|
||||||
accessToken,
|
|
||||||
apiBaseUrl,
|
|
||||||
`/repos/${owner}/${repo}`,
|
|
||||||
);
|
|
||||||
|
|
||||||
const labels: Record<string, string> = {
|
|
||||||
'pulls-list': 'Pull Requests',
|
|
||||||
'issues-list': 'Issues',
|
|
||||||
'releases-list': 'Releases',
|
|
||||||
};
|
|
||||||
|
|
||||||
return {
|
|
||||||
title: `${labels[collectionType] ?? collectionType} · ${data.full_name}`,
|
|
||||||
description: `${owner}/${repo}`,
|
|
||||||
url,
|
|
||||||
provider: 'github',
|
|
||||||
providerIcon: 'github',
|
|
||||||
author: data.owner?.login,
|
|
||||||
authorAvatarUrl: data.owner?.avatar_url,
|
|
||||||
metadata: {
|
|
||||||
type: collectionType,
|
|
||||||
repo: `${owner}/${repo}`,
|
|
||||||
},
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
private formatPrStatus(pr: any): string {
|
|
||||||
if (pr.merged) return 'merged';
|
|
||||||
if (pr.draft) return 'draft';
|
|
||||||
return pr.state;
|
|
||||||
}
|
|
||||||
|
|
||||||
private getPrStatusColor(pr: any): string {
|
|
||||||
if (pr.merged) return 'purple';
|
|
||||||
if (pr.draft) return 'gray';
|
|
||||||
if (pr.state === 'open') return 'green';
|
|
||||||
return 'red';
|
|
||||||
}
|
|
||||||
|
|
||||||
private async apiGet(
|
|
||||||
accessToken: string,
|
|
||||||
apiBaseUrl: string,
|
|
||||||
path: string,
|
|
||||||
): Promise<any> {
|
|
||||||
const response = await providerApiFetch('GitHub', `${apiBaseUrl}${path}`, {
|
|
||||||
headers: {
|
|
||||||
Authorization: `Bearer ${accessToken}`,
|
|
||||||
Accept: 'application/vnd.github.v3+json',
|
|
||||||
'User-Agent': 'Docmost',
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
return response.json();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,68 +0,0 @@
|
|||||||
import { UnfurlPattern } from '../../registry/integration-provider.interface';
|
|
||||||
|
|
||||||
function escapeForRegex(str: string): string {
|
|
||||||
return str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
||||||
}
|
|
||||||
|
|
||||||
export function buildGitLabPatterns(baseUrl: string): UnfurlPattern[] {
|
|
||||||
const escaped = escapeForRegex(baseUrl);
|
|
||||||
return [
|
|
||||||
{
|
|
||||||
regex: new RegExp(
|
|
||||||
`^${escaped}\\/(.+)\\/-\\/merge_requests\\/(\\d+)\\/diffs\\?.*commit_id=([a-f0-9]+)`,
|
|
||||||
),
|
|
||||||
type: 'gitlab-commit-in-mr',
|
|
||||||
},
|
|
||||||
{
|
|
||||||
regex: new RegExp(
|
|
||||||
`^${escaped}\\/(.+)\\/-\\/merge_requests\\/(\\d+)`,
|
|
||||||
),
|
|
||||||
type: 'gitlab-mr',
|
|
||||||
},
|
|
||||||
{
|
|
||||||
regex: new RegExp(
|
|
||||||
`^${escaped}\\/(.+)\\/-\\/issues\\/(\\d+)`,
|
|
||||||
),
|
|
||||||
type: 'gitlab-issue',
|
|
||||||
},
|
|
||||||
// Issues renamed to work items; same iid, resolved via the issues API.
|
|
||||||
{
|
|
||||||
regex: new RegExp(
|
|
||||||
`^${escaped}\\/(.+)\\/-\\/work_items\\/(\\d+)`,
|
|
||||||
),
|
|
||||||
type: 'gitlab-issue',
|
|
||||||
},
|
|
||||||
// Work item opened as a drawer over the list; the target is base64 JSON
|
|
||||||
// in the show param, decoded by the provider.
|
|
||||||
{
|
|
||||||
regex: new RegExp(
|
|
||||||
`^${escaped}\\/(.+)\\/-\\/work_items\\/?\\?(?:.*&)?show=`,
|
|
||||||
),
|
|
||||||
type: 'gitlab-work-item-drawer',
|
|
||||||
},
|
|
||||||
{
|
|
||||||
regex: new RegExp(
|
|
||||||
`^${escaped}\\/(.+)\\/-\\/commits?\\/([a-f0-9]+)`,
|
|
||||||
),
|
|
||||||
type: 'gitlab-commit',
|
|
||||||
},
|
|
||||||
{
|
|
||||||
regex: new RegExp(
|
|
||||||
`^${escaped}\\/(.+)\\/-\\/issues(?:\\/)?(?:\\?.*)?$`,
|
|
||||||
),
|
|
||||||
type: 'gitlab-issues-list',
|
|
||||||
},
|
|
||||||
{
|
|
||||||
regex: new RegExp(
|
|
||||||
`^${escaped}\\/(.+)\\/-\\/merge_requests(?:\\/)?(?:\\?.*)?$`,
|
|
||||||
),
|
|
||||||
type: 'gitlab-merges-list',
|
|
||||||
},
|
|
||||||
{
|
|
||||||
regex: new RegExp(
|
|
||||||
`^${escaped}\\/([a-zA-Z0-9\\-_.]+)\\/([a-zA-Z0-9\\-_]+)\\/?$`,
|
|
||||||
),
|
|
||||||
type: 'gitlab-project',
|
|
||||||
},
|
|
||||||
];
|
|
||||||
}
|
|
||||||
@@ -1,21 +0,0 @@
|
|||||||
import { Module, OnModuleInit } from '@nestjs/common';
|
|
||||||
import { GitLabProvider } from './gitlab.provider';
|
|
||||||
import { GitLabService } from './gitlab.service';
|
|
||||||
import { IntegrationRegistry } from '../../registry/integration-registry';
|
|
||||||
import { IntegrationModule } from '../../integration.module';
|
|
||||||
|
|
||||||
@Module({
|
|
||||||
imports: [IntegrationModule],
|
|
||||||
providers: [GitLabProvider, GitLabService],
|
|
||||||
exports: [GitLabProvider],
|
|
||||||
})
|
|
||||||
export class GitLabModule implements OnModuleInit {
|
|
||||||
constructor(
|
|
||||||
private readonly registry: IntegrationRegistry,
|
|
||||||
private readonly gitlabProvider: GitLabProvider,
|
|
||||||
) {}
|
|
||||||
|
|
||||||
onModuleInit() {
|
|
||||||
this.registry.register(this.gitlabProvider);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,188 +0,0 @@
|
|||||||
import { Injectable } from '@nestjs/common';
|
|
||||||
import {
|
|
||||||
IntegrationProvider,
|
|
||||||
IntegrationDefinition,
|
|
||||||
LinkDescription,
|
|
||||||
OAuthConfig,
|
|
||||||
UnfurlPattern,
|
|
||||||
UnfurlOpts,
|
|
||||||
UnfurlResult,
|
|
||||||
} from '../../registry/integration-provider.interface';
|
|
||||||
import { GitLabService } from './gitlab.service';
|
|
||||||
import { buildGitLabPatterns } from './gitlab-patterns';
|
|
||||||
|
|
||||||
const DEFAULT_BASE_URL = 'https://gitlab.com';
|
|
||||||
|
|
||||||
@Injectable()
|
|
||||||
export class GitLabProvider extends IntegrationProvider {
|
|
||||||
definition: IntegrationDefinition = {
|
|
||||||
type: 'gitlab',
|
|
||||||
name: 'GitLab',
|
|
||||||
description: 'Link previews for projects, merge requests, issues, and commits',
|
|
||||||
icon: 'gitlab',
|
|
||||||
capabilities: ['oauth', 'unfurl'],
|
|
||||||
oauth: {
|
|
||||||
authUrl: 'https://gitlab.com/oauth/authorize',
|
|
||||||
tokenUrl: 'https://gitlab.com/oauth/token',
|
|
||||||
scopes: ['read_api', 'read_user'],
|
|
||||||
},
|
|
||||||
unfurlPatterns: buildGitLabPatterns('https://gitlab.com'),
|
|
||||||
};
|
|
||||||
|
|
||||||
constructor(private readonly gitlabService: GitLabService) {
|
|
||||||
super();
|
|
||||||
}
|
|
||||||
|
|
||||||
getOAuthConfig(settings: Record<string, any>): OAuthConfig {
|
|
||||||
const baseUrl = this.resolveBaseUrl();
|
|
||||||
return {
|
|
||||||
authUrl: `${baseUrl}/oauth/authorize`,
|
|
||||||
tokenUrl: `${baseUrl}/oauth/token`,
|
|
||||||
scopes: ['read_api', 'read_user'],
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
getUnfurlPatterns(settings: Record<string, any>): UnfurlPattern[] {
|
|
||||||
const baseUrl = this.resolveBaseUrl();
|
|
||||||
if (baseUrl === DEFAULT_BASE_URL) return [];
|
|
||||||
return buildGitLabPatterns(baseUrl);
|
|
||||||
}
|
|
||||||
|
|
||||||
async unfurl(opts: UnfurlOpts): Promise<UnfurlResult> {
|
|
||||||
const { match, patternType, accessToken, url } = opts;
|
|
||||||
const apiBaseUrl = this.resolveApiBaseUrl(url);
|
|
||||||
|
|
||||||
switch (patternType) {
|
|
||||||
case 'gitlab-mr': {
|
|
||||||
const projectPath = match[1];
|
|
||||||
const iid = parseInt(match[2], 10);
|
|
||||||
return this.gitlabService.unfurlMergeRequest(
|
|
||||||
accessToken, apiBaseUrl, projectPath, iid, url,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
case 'gitlab-issue': {
|
|
||||||
const projectPath = match[1];
|
|
||||||
const iid = parseInt(match[2], 10);
|
|
||||||
return this.gitlabService.unfurlIssue(
|
|
||||||
accessToken, apiBaseUrl, projectPath, iid, url,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
case 'gitlab-project': {
|
|
||||||
const projectPath = `${match[1]}/${match[2]}`;
|
|
||||||
return this.gitlabService.unfurlProject(
|
|
||||||
accessToken, apiBaseUrl, projectPath, url,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
case 'gitlab-commit': {
|
|
||||||
const projectPath = match[1];
|
|
||||||
const commitSha = match[2];
|
|
||||||
return this.gitlabService.unfurlCommit(
|
|
||||||
accessToken, apiBaseUrl, projectPath, commitSha, url,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
case 'gitlab-commit-in-mr': {
|
|
||||||
const projectPath = match[1];
|
|
||||||
const commitSha = match[3];
|
|
||||||
return this.gitlabService.unfurlCommit(
|
|
||||||
accessToken, apiBaseUrl, projectPath, commitSha, url,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
case 'gitlab-work-item-drawer': {
|
|
||||||
const target = this.decodeWorkItemShowParam(url);
|
|
||||||
if (!target) {
|
|
||||||
throw new Error('Could not decode work item show param');
|
|
||||||
}
|
|
||||||
return this.gitlabService.unfurlIssue(
|
|
||||||
accessToken, apiBaseUrl, target.fullPath, target.iid, url,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
case 'gitlab-issues-list': {
|
|
||||||
const projectPath = match[1];
|
|
||||||
return this.gitlabService.unfurlIssuesList(
|
|
||||||
accessToken, apiBaseUrl, projectPath, url,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
case 'gitlab-merges-list': {
|
|
||||||
const projectPath = match[1];
|
|
||||||
return this.gitlabService.unfurlMergesList(
|
|
||||||
accessToken, apiBaseUrl, projectPath, url,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
default:
|
|
||||||
throw new Error(`Unknown GitLab pattern type: ${patternType}`);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
describeLink(
|
|
||||||
patternType: string,
|
|
||||||
match: RegExpMatchArray,
|
|
||||||
url: string,
|
|
||||||
): LinkDescription | null {
|
|
||||||
const projectPath = match[1];
|
|
||||||
switch (patternType) {
|
|
||||||
case 'gitlab-mr':
|
|
||||||
return { title: `Merge Request !${match[2]}`, description: projectPath };
|
|
||||||
case 'gitlab-issue':
|
|
||||||
return { title: `Issue #${match[2]}`, description: projectPath };
|
|
||||||
case 'gitlab-work-item-drawer': {
|
|
||||||
const target = this.decodeWorkItemShowParam(url);
|
|
||||||
return target
|
|
||||||
? { title: `Issue #${target.iid}`, description: target.fullPath }
|
|
||||||
: { title: 'Work item', description: projectPath };
|
|
||||||
}
|
|
||||||
case 'gitlab-commit':
|
|
||||||
return { title: `Commit ${match[2].slice(0, 8)}`, description: projectPath };
|
|
||||||
case 'gitlab-commit-in-mr':
|
|
||||||
return { title: `Commit ${match[3].slice(0, 8)}`, description: projectPath };
|
|
||||||
case 'gitlab-issues-list':
|
|
||||||
return { title: 'Issues', description: projectPath };
|
|
||||||
case 'gitlab-merges-list':
|
|
||||||
return { title: 'Merge Requests', description: projectPath };
|
|
||||||
case 'gitlab-project':
|
|
||||||
return { title: `${match[1]}/${match[2]}` };
|
|
||||||
default:
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// The work items list opens an item as a drawer and encodes it in the URL
|
|
||||||
// as ?show=base64({ iid, full_path, id }). full_path beats the URL path:
|
|
||||||
// a drawer opened from a group-level list still names the actual project.
|
|
||||||
private decodeWorkItemShowParam(
|
|
||||||
url: string,
|
|
||||||
): { fullPath: string; iid: number } | null {
|
|
||||||
try {
|
|
||||||
const show = new URL(url).searchParams.get('show');
|
|
||||||
if (!show) return null;
|
|
||||||
const base64 = show.replace(/-/g, '+').replace(/_/g, '/');
|
|
||||||
const payload = JSON.parse(
|
|
||||||
Buffer.from(base64, 'base64').toString('utf8'),
|
|
||||||
);
|
|
||||||
const iid = parseInt(payload.iid, 10);
|
|
||||||
if (typeof payload.full_path !== 'string' || Number.isNaN(iid)) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
return { fullPath: payload.full_path, iid };
|
|
||||||
} catch {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private resolveBaseUrl(): string {
|
|
||||||
const baseUrl = process.env.INTEGRATION_GITLAB_BASE_URL;
|
|
||||||
return baseUrl ? baseUrl.replace(/\/+$/, '') : DEFAULT_BASE_URL;
|
|
||||||
}
|
|
||||||
|
|
||||||
private resolveApiBaseUrl(url: string): string {
|
|
||||||
const parsed = new URL(url);
|
|
||||||
return `${parsed.origin}/api/v4`;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,253 +0,0 @@
|
|||||||
import { Injectable, Logger } from '@nestjs/common';
|
|
||||||
import { UnfurlResult } from '../../registry/integration-provider.interface';
|
|
||||||
import { relativeTime } from '../../utils/relative-time';
|
|
||||||
import { providerApiFetch } from '../../utils/provider-fetch';
|
|
||||||
|
|
||||||
@Injectable()
|
|
||||||
export class GitLabService {
|
|
||||||
private readonly logger = new Logger(GitLabService.name);
|
|
||||||
|
|
||||||
async unfurlMergeRequest(
|
|
||||||
accessToken: string,
|
|
||||||
apiBaseUrl: string,
|
|
||||||
projectPath: string,
|
|
||||||
iid: number,
|
|
||||||
url: string,
|
|
||||||
): Promise<UnfurlResult> {
|
|
||||||
const encodedProject = encodeURIComponent(projectPath);
|
|
||||||
const data = await this.apiGet(
|
|
||||||
accessToken,
|
|
||||||
apiBaseUrl,
|
|
||||||
`/projects/${encodedProject}/merge_requests/${iid}`,
|
|
||||||
);
|
|
||||||
|
|
||||||
const authorName = data.author?.name ?? data.author?.username;
|
|
||||||
const desc = [
|
|
||||||
`!${data.iid}`,
|
|
||||||
relativeTime(data.updated_at ?? data.created_at),
|
|
||||||
authorName,
|
|
||||||
].filter(Boolean).join(' · ');
|
|
||||||
|
|
||||||
return {
|
|
||||||
title: data.title,
|
|
||||||
description: desc,
|
|
||||||
url,
|
|
||||||
provider: 'gitlab',
|
|
||||||
providerIcon: 'gitlab',
|
|
||||||
status: this.formatMrStatus(data),
|
|
||||||
statusColor: this.getMrStatusColor(data),
|
|
||||||
author: authorName,
|
|
||||||
authorAvatarUrl: data.author?.avatar_url,
|
|
||||||
metadata: {
|
|
||||||
type: 'mr',
|
|
||||||
iid: data.iid,
|
|
||||||
project: projectPath,
|
|
||||||
labels: data.labels ?? [],
|
|
||||||
draft: data.draft ?? data.work_in_progress,
|
|
||||||
},
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
async unfurlIssue(
|
|
||||||
accessToken: string,
|
|
||||||
apiBaseUrl: string,
|
|
||||||
projectPath: string,
|
|
||||||
iid: number,
|
|
||||||
url: string,
|
|
||||||
): Promise<UnfurlResult> {
|
|
||||||
const encodedProject = encodeURIComponent(projectPath);
|
|
||||||
const data = await this.apiGet(
|
|
||||||
accessToken,
|
|
||||||
apiBaseUrl,
|
|
||||||
`/projects/${encodedProject}/issues/${iid}`,
|
|
||||||
);
|
|
||||||
|
|
||||||
const issueAuthor = data.author?.name ?? data.author?.username;
|
|
||||||
const issueDesc = [
|
|
||||||
`#${data.iid}`,
|
|
||||||
relativeTime(data.updated_at ?? data.created_at),
|
|
||||||
issueAuthor,
|
|
||||||
].filter(Boolean).join(' · ');
|
|
||||||
|
|
||||||
return {
|
|
||||||
title: data.title,
|
|
||||||
description: issueDesc,
|
|
||||||
url,
|
|
||||||
provider: 'gitlab',
|
|
||||||
providerIcon: 'gitlab',
|
|
||||||
status: data.state,
|
|
||||||
statusColor: data.state === 'opened' ? 'green' : 'blue',
|
|
||||||
author: issueAuthor,
|
|
||||||
authorAvatarUrl: data.author?.avatar_url,
|
|
||||||
metadata: {
|
|
||||||
type: 'issue',
|
|
||||||
iid: data.iid,
|
|
||||||
project: projectPath,
|
|
||||||
labels: data.labels ?? [],
|
|
||||||
assignees:
|
|
||||||
data.assignees?.map((a: any) => a.name ?? a.username) ?? [],
|
|
||||||
},
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
async unfurlProject(
|
|
||||||
accessToken: string,
|
|
||||||
apiBaseUrl: string,
|
|
||||||
projectPath: string,
|
|
||||||
url: string,
|
|
||||||
): Promise<UnfurlResult> {
|
|
||||||
const encodedProject = encodeURIComponent(projectPath);
|
|
||||||
const data = await this.apiGet(
|
|
||||||
accessToken,
|
|
||||||
apiBaseUrl,
|
|
||||||
`/projects/${encodedProject}`,
|
|
||||||
);
|
|
||||||
|
|
||||||
const visibility = data.visibility === 'public' ? 'Public' : data.visibility === 'internal' ? 'Internal' : 'Private';
|
|
||||||
|
|
||||||
return {
|
|
||||||
title: data.name,
|
|
||||||
description: data.description?.slice(0, 200) ?? undefined,
|
|
||||||
url,
|
|
||||||
provider: 'gitlab',
|
|
||||||
providerIcon: 'gitlab',
|
|
||||||
status: visibility,
|
|
||||||
statusColor: data.visibility === 'public' ? 'green' : 'gray',
|
|
||||||
author: data.namespace?.name,
|
|
||||||
authorAvatarUrl: data.avatar_url ?? data.namespace?.avatar_url,
|
|
||||||
metadata: {
|
|
||||||
type: 'project',
|
|
||||||
project: projectPath,
|
|
||||||
stars: data.star_count,
|
|
||||||
forks: data.forks_count,
|
|
||||||
defaultBranch: data.default_branch,
|
|
||||||
},
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
async unfurlCommit(
|
|
||||||
accessToken: string,
|
|
||||||
apiBaseUrl: string,
|
|
||||||
projectPath: string,
|
|
||||||
commitSha: string,
|
|
||||||
url: string,
|
|
||||||
): Promise<UnfurlResult> {
|
|
||||||
const encodedProject = encodeURIComponent(projectPath);
|
|
||||||
const data = await this.apiGet(
|
|
||||||
accessToken,
|
|
||||||
apiBaseUrl,
|
|
||||||
`/projects/${encodedProject}/repository/commits/${commitSha}`,
|
|
||||||
);
|
|
||||||
|
|
||||||
const shortSha = data.short_id ?? data.id?.slice(0, 8);
|
|
||||||
|
|
||||||
const commitDesc = [
|
|
||||||
shortSha,
|
|
||||||
relativeTime(data.committed_date ?? data.created_at),
|
|
||||||
data.author_name,
|
|
||||||
].filter(Boolean).join(' · ');
|
|
||||||
|
|
||||||
return {
|
|
||||||
title: data.title ?? data.message?.split('\n')[0],
|
|
||||||
description: commitDesc,
|
|
||||||
url,
|
|
||||||
provider: 'gitlab',
|
|
||||||
providerIcon: 'gitlab',
|
|
||||||
author: data.author_name,
|
|
||||||
authorAvatarUrl: undefined,
|
|
||||||
metadata: {
|
|
||||||
type: 'commit',
|
|
||||||
sha: data.id,
|
|
||||||
shortSha,
|
|
||||||
project: projectPath,
|
|
||||||
stats: data.stats,
|
|
||||||
},
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
async unfurlIssuesList(
|
|
||||||
accessToken: string,
|
|
||||||
apiBaseUrl: string,
|
|
||||||
projectPath: string,
|
|
||||||
url: string,
|
|
||||||
): Promise<UnfurlResult> {
|
|
||||||
const encodedProject = encodeURIComponent(projectPath);
|
|
||||||
const data = await this.apiGet(
|
|
||||||
accessToken,
|
|
||||||
apiBaseUrl,
|
|
||||||
`/projects/${encodedProject}?statistics=false`,
|
|
||||||
);
|
|
||||||
|
|
||||||
return {
|
|
||||||
title: `Issues · ${data.name}`,
|
|
||||||
description: projectPath,
|
|
||||||
url,
|
|
||||||
provider: 'gitlab',
|
|
||||||
providerIcon: 'gitlab',
|
|
||||||
author: data.namespace?.name,
|
|
||||||
authorAvatarUrl: data.avatar_url ?? data.namespace?.avatar_url,
|
|
||||||
metadata: {
|
|
||||||
type: 'issues-list',
|
|
||||||
project: projectPath,
|
|
||||||
openIssuesCount: data.open_issues_count,
|
|
||||||
},
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
async unfurlMergesList(
|
|
||||||
accessToken: string,
|
|
||||||
apiBaseUrl: string,
|
|
||||||
projectPath: string,
|
|
||||||
url: string,
|
|
||||||
): Promise<UnfurlResult> {
|
|
||||||
const encodedProject = encodeURIComponent(projectPath);
|
|
||||||
const data = await this.apiGet(
|
|
||||||
accessToken,
|
|
||||||
apiBaseUrl,
|
|
||||||
`/projects/${encodedProject}?statistics=false`,
|
|
||||||
);
|
|
||||||
|
|
||||||
return {
|
|
||||||
title: `Merge Requests · ${data.name}`,
|
|
||||||
description: projectPath,
|
|
||||||
url,
|
|
||||||
provider: 'gitlab',
|
|
||||||
providerIcon: 'gitlab',
|
|
||||||
author: data.namespace?.name,
|
|
||||||
authorAvatarUrl: data.avatar_url ?? data.namespace?.avatar_url,
|
|
||||||
metadata: {
|
|
||||||
type: 'merges-list',
|
|
||||||
project: projectPath,
|
|
||||||
},
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
private formatMrStatus(mr: any): string {
|
|
||||||
if (mr.state === 'merged') return 'merged';
|
|
||||||
if (mr.draft || mr.work_in_progress) return 'draft';
|
|
||||||
return mr.state;
|
|
||||||
}
|
|
||||||
|
|
||||||
private getMrStatusColor(mr: any): string {
|
|
||||||
if (mr.state === 'merged') return 'purple';
|
|
||||||
if (mr.draft || mr.work_in_progress) return 'gray';
|
|
||||||
if (mr.state === 'opened') return 'green';
|
|
||||||
if (mr.state === 'closed') return 'red';
|
|
||||||
return 'gray';
|
|
||||||
}
|
|
||||||
|
|
||||||
private async apiGet(
|
|
||||||
accessToken: string,
|
|
||||||
apiBaseUrl: string,
|
|
||||||
path: string,
|
|
||||||
): Promise<any> {
|
|
||||||
const response = await providerApiFetch('GitLab', `${apiBaseUrl}${path}`, {
|
|
||||||
headers: {
|
|
||||||
Authorization: `Bearer ${accessToken}`,
|
|
||||||
Accept: 'application/json',
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
return response.json();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,169 +0,0 @@
|
|||||||
export type IntegrationCapability = 'oauth' | 'unfurl' | 'actions';
|
|
||||||
|
|
||||||
export type OAuthConfig = {
|
|
||||||
authUrl: string;
|
|
||||||
tokenUrl: string;
|
|
||||||
scopes: string[];
|
|
||||||
// 'workspace' = one shared bot/app connection per integration (Slack model);
|
|
||||||
// 'user' (default) = each Docmost user OAuths separately and gets their own token (Linear, Jira, GitHub model)
|
|
||||||
connectionScope?: 'workspace' | 'user';
|
|
||||||
};
|
|
||||||
|
|
||||||
export type UnfurlPattern = {
|
|
||||||
regex: RegExp;
|
|
||||||
type: string;
|
|
||||||
};
|
|
||||||
|
|
||||||
export type UnfurlResult = {
|
|
||||||
title: string;
|
|
||||||
description?: string;
|
|
||||||
url: string;
|
|
||||||
provider: string;
|
|
||||||
providerIcon?: string;
|
|
||||||
status?: string;
|
|
||||||
statusColor?: string;
|
|
||||||
author?: string;
|
|
||||||
authorAvatarUrl?: string;
|
|
||||||
metadata?: Record<string, any>;
|
|
||||||
};
|
|
||||||
|
|
||||||
export type IntegrationDefinition = {
|
|
||||||
type: string;
|
|
||||||
name: string;
|
|
||||||
description: string;
|
|
||||||
icon: string;
|
|
||||||
capabilities: IntegrationCapability[];
|
|
||||||
oauth?: OAuthConfig;
|
|
||||||
unfurlPatterns?: UnfurlPattern[];
|
|
||||||
// Kept out of the available list and refused for install; existing
|
|
||||||
// installations keep unfurling.
|
|
||||||
hidden?: boolean;
|
|
||||||
// Install requires the INTEGRATIONS license feature; unset = free.
|
|
||||||
requiresLicense?: boolean;
|
|
||||||
};
|
|
||||||
|
|
||||||
export type ConnectedEvent = {
|
|
||||||
integrationId: string;
|
|
||||||
workspaceId: string;
|
|
||||||
accessToken: string;
|
|
||||||
refreshToken?: string;
|
|
||||||
// The Docmost user who completed the OAuth flow (installer for
|
|
||||||
// workspace-scoped providers).
|
|
||||||
userId: string;
|
|
||||||
metadata: Record<string, any>;
|
|
||||||
};
|
|
||||||
|
|
||||||
export type HandleEventOpts = {
|
|
||||||
eventName: string;
|
|
||||||
payload: Record<string, any>;
|
|
||||||
integration: {
|
|
||||||
id: string;
|
|
||||||
type: string;
|
|
||||||
settings: Record<string, any> | null;
|
|
||||||
};
|
|
||||||
connection?: {
|
|
||||||
accessToken: string;
|
|
||||||
userId: string;
|
|
||||||
};
|
|
||||||
};
|
|
||||||
|
|
||||||
export type UnfurlOpts = {
|
|
||||||
url: string;
|
|
||||||
accessToken: string;
|
|
||||||
match: RegExpMatchArray;
|
|
||||||
patternType: string;
|
|
||||||
settings?: Record<string, any>;
|
|
||||||
// The requesting Docmost user and integration. Providers backed by a shared
|
|
||||||
// (workspace) connection MUST authorize the requester against the target
|
|
||||||
// resource before returning content: the shared bot token is not itself
|
|
||||||
// proof that the requester may see it.
|
|
||||||
userId: string;
|
|
||||||
integrationId: string;
|
|
||||||
};
|
|
||||||
|
|
||||||
// Thrown by a provider's unfurl() when the requesting user is not authorized
|
|
||||||
// to view the linked resource. UnfurlService turns it into a null result
|
|
||||||
// (no card) rather than logging it as an error.
|
|
||||||
export class UnfurlForbiddenError extends Error {
|
|
||||||
constructor(message = 'Not authorized to unfurl this link') {
|
|
||||||
super(message);
|
|
||||||
this.name = 'UnfurlForbiddenError';
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Thrown by a provider's unfurl() when the requesting user has no usable
|
|
||||||
// identity with the provider yet (e.g. no Slack account link). UnfurlService
|
|
||||||
// turns it into a needs-connection response, unlike UnfurlForbiddenError
|
|
||||||
// which stays a silent null.
|
|
||||||
export class UnfurlNeedsConnectionError extends Error {
|
|
||||||
constructor(message = 'User has not connected this integration') {
|
|
||||||
super(message);
|
|
||||||
this.name = 'UnfurlNeedsConnectionError';
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Thrown when the provider definitively rejects the stored credential (API 401,
|
|
||||||
// or invalid_grant at the token endpoint). Callers retire the connection.
|
|
||||||
export class TokenInvalidError extends Error {
|
|
||||||
constructor(message = 'Integration credential is no longer valid') {
|
|
||||||
super(message);
|
|
||||||
this.name = 'TokenInvalidError';
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
export class ProviderApiError extends Error {
|
|
||||||
constructor(
|
|
||||||
readonly provider: string,
|
|
||||||
readonly status: number,
|
|
||||||
statusText = '',
|
|
||||||
) {
|
|
||||||
super(`${provider} API error: ${status} ${statusText}`.trimEnd());
|
|
||||||
this.name = 'ProviderApiError';
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
export type LinkDescription = {
|
|
||||||
title: string;
|
|
||||||
description?: string;
|
|
||||||
};
|
|
||||||
|
|
||||||
// Returned instead of an UnfurlResult when the link needs a per-user
|
|
||||||
// connection the requesting user does not have yet.
|
|
||||||
export type UnfurlNeedsConnection = {
|
|
||||||
needsConnection: true;
|
|
||||||
integrationId: string;
|
|
||||||
integrationType: string;
|
|
||||||
integrationName: string;
|
|
||||||
// true when a Docmost-initiated OAuth flow yields a personal connection
|
|
||||||
// for the requesting user (all OAuth-capable providers; workspace-scoped
|
|
||||||
// ones bind the authorizing user's identity in onConnected).
|
|
||||||
oauthConnect: boolean;
|
|
||||||
title: string;
|
|
||||||
description?: string;
|
|
||||||
};
|
|
||||||
|
|
||||||
export abstract class IntegrationProvider {
|
|
||||||
abstract definition: IntegrationDefinition;
|
|
||||||
|
|
||||||
getOAuthConfig?(
|
|
||||||
workspaceSettings: Record<string, any>,
|
|
||||||
): OAuthConfig;
|
|
||||||
|
|
||||||
getUnfurlPatterns?(
|
|
||||||
workspaceSettings: Record<string, any>,
|
|
||||||
): UnfurlPattern[];
|
|
||||||
|
|
||||||
onConnected?(opts: ConnectedEvent): Promise<void>;
|
|
||||||
|
|
||||||
unfurl?(opts: UnfurlOpts): Promise<UnfurlResult>;
|
|
||||||
|
|
||||||
// Tokenless summary of a matched link (e.g. "Pull Request #13337"),
|
|
||||||
// shown on the connect prompt before the user has authorized.
|
|
||||||
describeLink?(
|
|
||||||
patternType: string,
|
|
||||||
match: RegExpMatchArray,
|
|
||||||
url: string,
|
|
||||||
): LinkDescription | null;
|
|
||||||
|
|
||||||
handleEvent?(opts: HandleEventOpts): Promise<void>;
|
|
||||||
}
|
|
||||||
@@ -1,47 +0,0 @@
|
|||||||
import { Injectable } from '@nestjs/common';
|
|
||||||
import {
|
|
||||||
IntegrationDefinition,
|
|
||||||
IntegrationProvider,
|
|
||||||
} from './integration-provider.interface';
|
|
||||||
|
|
||||||
@Injectable()
|
|
||||||
export class IntegrationRegistry {
|
|
||||||
private providers = new Map<string, IntegrationProvider>();
|
|
||||||
|
|
||||||
register(provider: IntegrationProvider): void {
|
|
||||||
this.providers.set(provider.definition.type, provider);
|
|
||||||
}
|
|
||||||
|
|
||||||
getProvider(type: string): IntegrationProvider | undefined {
|
|
||||||
return this.providers.get(type);
|
|
||||||
}
|
|
||||||
|
|
||||||
getAllProviders(): IntegrationProvider[] {
|
|
||||||
return Array.from(this.providers.values());
|
|
||||||
}
|
|
||||||
|
|
||||||
getAvailableIntegrations(): IntegrationDefinition[] {
|
|
||||||
return this.getAllProviders()
|
|
||||||
.map((p) => p.definition)
|
|
||||||
.filter((definition) => !definition.hidden);
|
|
||||||
}
|
|
||||||
|
|
||||||
findUnfurlProvider(
|
|
||||||
url: string,
|
|
||||||
): {
|
|
||||||
provider: IntegrationProvider;
|
|
||||||
match: RegExpMatchArray;
|
|
||||||
patternType: string;
|
|
||||||
} | null {
|
|
||||||
for (const provider of this.providers.values()) {
|
|
||||||
if (!provider.definition.unfurlPatterns) continue;
|
|
||||||
for (const pattern of provider.definition.unfurlPatterns) {
|
|
||||||
const match = url.match(pattern.regex);
|
|
||||||
if (match) {
|
|
||||||
return { provider, match, patternType: pattern.type };
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,361 +0,0 @@
|
|||||||
import { Injectable } from '@nestjs/common';
|
|
||||||
import { InjectKysely } from 'nestjs-kysely';
|
|
||||||
import { sql } from 'kysely';
|
|
||||||
import { KyselyDB, KyselyTransaction } from '@docmost/db/types/kysely.types';
|
|
||||||
import {
|
|
||||||
IntegrationConnection,
|
|
||||||
InsertableIntegrationConnection,
|
|
||||||
UpdatableIntegrationConnection,
|
|
||||||
} from '@docmost/db/types/entity.types';
|
|
||||||
import { dbOrTx } from '@docmost/db/utils';
|
|
||||||
|
|
||||||
@Injectable()
|
|
||||||
export class IntegrationConnectionRepo {
|
|
||||||
constructor(@InjectKysely() private readonly db: KyselyDB) {}
|
|
||||||
|
|
||||||
async findById(
|
|
||||||
connectionId: string,
|
|
||||||
trx?: KyselyTransaction,
|
|
||||||
): Promise<IntegrationConnection | undefined> {
|
|
||||||
const db = dbOrTx(this.db, trx);
|
|
||||||
return db
|
|
||||||
.selectFrom('integrationConnections')
|
|
||||||
.selectAll()
|
|
||||||
.where('id', '=', connectionId)
|
|
||||||
.executeTakeFirst();
|
|
||||||
}
|
|
||||||
|
|
||||||
async findByIntegrationAndUser(
|
|
||||||
integrationId: string,
|
|
||||||
userId: string,
|
|
||||||
trx?: KyselyTransaction,
|
|
||||||
): Promise<IntegrationConnection | undefined> {
|
|
||||||
const db = dbOrTx(this.db, trx);
|
|
||||||
return db
|
|
||||||
.selectFrom('integrationConnections')
|
|
||||||
.selectAll()
|
|
||||||
.where('integrationId', '=', integrationId)
|
|
||||||
.where('userId', '=', userId)
|
|
||||||
.executeTakeFirst();
|
|
||||||
}
|
|
||||||
|
|
||||||
async findByWorkspaceTypeAndUser(
|
|
||||||
workspaceId: string,
|
|
||||||
integrationType: string,
|
|
||||||
userId: string,
|
|
||||||
trx?: KyselyTransaction,
|
|
||||||
): Promise<IntegrationConnection | undefined> {
|
|
||||||
const db = dbOrTx(this.db, trx);
|
|
||||||
return db
|
|
||||||
.selectFrom('integrationConnections')
|
|
||||||
.innerJoin(
|
|
||||||
'integrations',
|
|
||||||
'integrations.id',
|
|
||||||
'integrationConnections.integrationId',
|
|
||||||
)
|
|
||||||
.selectAll('integrationConnections')
|
|
||||||
.where('integrations.workspaceId', '=', workspaceId)
|
|
||||||
.where('integrations.type', '=', integrationType)
|
|
||||||
.where('integrations.deletedAt', 'is', null)
|
|
||||||
.where('integrationConnections.userId', '=', userId)
|
|
||||||
.executeTakeFirst();
|
|
||||||
}
|
|
||||||
|
|
||||||
async findByIntegration(
|
|
||||||
integrationId: string,
|
|
||||||
trx?: KyselyTransaction,
|
|
||||||
): Promise<IntegrationConnection[]> {
|
|
||||||
const db = dbOrTx(this.db, trx);
|
|
||||||
return db
|
|
||||||
.selectFrom('integrationConnections')
|
|
||||||
.selectAll()
|
|
||||||
.where('integrationId', '=', integrationId)
|
|
||||||
.execute();
|
|
||||||
}
|
|
||||||
|
|
||||||
async upsert(
|
|
||||||
connection: InsertableIntegrationConnection,
|
|
||||||
trx?: KyselyTransaction,
|
|
||||||
): Promise<IntegrationConnection> {
|
|
||||||
const db = dbOrTx(this.db, trx);
|
|
||||||
// The (integration_id, user_id) unique index is partial on kind='user';
|
|
||||||
// ON CONFLICT must repeat that predicate or Postgres cannot infer it.
|
|
||||||
return db
|
|
||||||
.insertInto('integrationConnections')
|
|
||||||
.values(connection)
|
|
||||||
.onConflict((oc) =>
|
|
||||||
oc
|
|
||||||
.columns(['integrationId', 'userId'])
|
|
||||||
.where(sql.ref('kind'), '=', 'user')
|
|
||||||
.doUpdateSet({
|
|
||||||
accessToken: connection.accessToken,
|
|
||||||
refreshToken: connection.refreshToken,
|
|
||||||
tokenExpiresAt: connection.tokenExpiresAt,
|
|
||||||
invalidatedAt: null,
|
|
||||||
scopes: connection.scopes,
|
|
||||||
providerUserId: connection.providerUserId,
|
|
||||||
metadata: connection.metadata,
|
|
||||||
updatedAt: new Date(),
|
|
||||||
}),
|
|
||||||
)
|
|
||||||
.returningAll()
|
|
||||||
.executeTakeFirstOrThrow();
|
|
||||||
}
|
|
||||||
|
|
||||||
async upsertWorkspaceConnection(
|
|
||||||
input: {
|
|
||||||
integrationId: string;
|
|
||||||
userId: string;
|
|
||||||
workspaceId: string;
|
|
||||||
accessToken: string;
|
|
||||||
refreshToken?: string | null;
|
|
||||||
tokenExpiresAt?: Date | null;
|
|
||||||
scopes?: string | null;
|
|
||||||
},
|
|
||||||
trx?: KyselyTransaction,
|
|
||||||
): Promise<IntegrationConnection> {
|
|
||||||
const db = dbOrTx(this.db, trx);
|
|
||||||
|
|
||||||
const existing = await this.findWorkspaceConnection(input.integrationId, trx);
|
|
||||||
if (existing) {
|
|
||||||
return this.update(
|
|
||||||
existing.id,
|
|
||||||
{
|
|
||||||
accessToken: input.accessToken,
|
|
||||||
refreshToken: input.refreshToken ?? null,
|
|
||||||
tokenExpiresAt: input.tokenExpiresAt ?? null,
|
|
||||||
invalidatedAt: null,
|
|
||||||
scopes: input.scopes ?? null,
|
|
||||||
userId: input.userId,
|
|
||||||
},
|
|
||||||
trx,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
// No need to clear other rows: the (integration_id, user_id) unique index
|
|
||||||
// is partial on kind='user', so a workspace insert never conflicts with
|
|
||||||
// the installer's user-link row.
|
|
||||||
|
|
||||||
return db
|
|
||||||
.insertInto('integrationConnections')
|
|
||||||
.values({
|
|
||||||
integrationId: input.integrationId,
|
|
||||||
userId: input.userId,
|
|
||||||
workspaceId: input.workspaceId,
|
|
||||||
accessToken: input.accessToken,
|
|
||||||
refreshToken: input.refreshToken ?? null,
|
|
||||||
tokenExpiresAt: input.tokenExpiresAt ?? null,
|
|
||||||
scopes: input.scopes ?? null,
|
|
||||||
kind: 'workspace',
|
|
||||||
})
|
|
||||||
.returningAll()
|
|
||||||
.executeTakeFirstOrThrow();
|
|
||||||
}
|
|
||||||
|
|
||||||
async update(
|
|
||||||
connectionId: string,
|
|
||||||
data: UpdatableIntegrationConnection,
|
|
||||||
trx?: KyselyTransaction,
|
|
||||||
): Promise<IntegrationConnection> {
|
|
||||||
const db = dbOrTx(this.db, trx);
|
|
||||||
return db
|
|
||||||
.updateTable('integrationConnections')
|
|
||||||
.set({ ...data, updatedAt: new Date() })
|
|
||||||
.where('id', '=', connectionId)
|
|
||||||
.returningAll()
|
|
||||||
.executeTakeFirstOrThrow();
|
|
||||||
}
|
|
||||||
|
|
||||||
async deleteByIntegrationAndUser(
|
|
||||||
integrationId: string,
|
|
||||||
userId: string,
|
|
||||||
trx?: KyselyTransaction,
|
|
||||||
): Promise<void> {
|
|
||||||
const db = dbOrTx(this.db, trx);
|
|
||||||
// Never delete a kind='workspace' row from a per-user disconnect.
|
|
||||||
// For Slack (and any future workspace-scoped provider) the installer's
|
|
||||||
// userId matches the workspace connection's userId; without this filter
|
|
||||||
// a single user clicking Disconnect would wipe the shared bot token and
|
|
||||||
// break the integration for the whole workspace. Full uninstall uses
|
|
||||||
// deleteByIntegration which intentionally has no kind filter.
|
|
||||||
await db
|
|
||||||
.deleteFrom('integrationConnections')
|
|
||||||
.where('integrationId', '=', integrationId)
|
|
||||||
.where('userId', '=', userId)
|
|
||||||
.where('kind', '!=', 'workspace')
|
|
||||||
.execute();
|
|
||||||
}
|
|
||||||
|
|
||||||
async findByUserAndWorkspace(
|
|
||||||
userId: string,
|
|
||||||
workspaceId: string,
|
|
||||||
trx?: KyselyTransaction,
|
|
||||||
) {
|
|
||||||
const db = dbOrTx(this.db, trx);
|
|
||||||
return db
|
|
||||||
.selectFrom('integrationConnections')
|
|
||||||
.innerJoin(
|
|
||||||
'integrations',
|
|
||||||
'integrations.id',
|
|
||||||
'integrationConnections.integrationId',
|
|
||||||
)
|
|
||||||
.select([
|
|
||||||
'integrationConnections.integrationId',
|
|
||||||
'integrations.type',
|
|
||||||
'integrationConnections.providerUserId',
|
|
||||||
'integrationConnections.metadata',
|
|
||||||
'integrationConnections.createdAt',
|
|
||||||
'integrationConnections.invalidatedAt',
|
|
||||||
])
|
|
||||||
.where('integrationConnections.userId', '=', userId)
|
|
||||||
// The workspace bot row carries the installer's userId; without this
|
|
||||||
// filter it renders on the connections page as a personal link.
|
|
||||||
.where('integrationConnections.kind', '=', 'user')
|
|
||||||
.where('integrations.workspaceId', '=', workspaceId)
|
|
||||||
.where('integrations.deletedAt', 'is', null)
|
|
||||||
.execute();
|
|
||||||
}
|
|
||||||
|
|
||||||
async findExpiringTokens(
|
|
||||||
expiresBeforeMs: number,
|
|
||||||
): Promise<IntegrationConnection[]> {
|
|
||||||
const threshold = new Date(Date.now() + expiresBeforeMs);
|
|
||||||
return this.db
|
|
||||||
.selectFrom('integrationConnections')
|
|
||||||
.innerJoin(
|
|
||||||
'integrations',
|
|
||||||
'integrations.id',
|
|
||||||
'integrationConnections.integrationId',
|
|
||||||
)
|
|
||||||
.selectAll('integrationConnections')
|
|
||||||
.where('integrations.deletedAt', 'is', null)
|
|
||||||
.where('integrationConnections.invalidatedAt', 'is', null)
|
|
||||||
.where('integrationConnections.refreshToken', 'is not', null)
|
|
||||||
.where('integrationConnections.tokenExpiresAt', 'is not', null)
|
|
||||||
.where('integrationConnections.tokenExpiresAt', '<', threshold)
|
|
||||||
.execute();
|
|
||||||
}
|
|
||||||
|
|
||||||
// Retire a rejected credential: flag for reconnect UX, drop the dead refresh token; no-op if the row is gone.
|
|
||||||
async invalidate(connectionId: string): Promise<void> {
|
|
||||||
await this.db
|
|
||||||
.updateTable('integrationConnections')
|
|
||||||
.set({
|
|
||||||
invalidatedAt: new Date(),
|
|
||||||
refreshToken: null,
|
|
||||||
tokenExpiresAt: null,
|
|
||||||
updatedAt: new Date(),
|
|
||||||
})
|
|
||||||
.where('id', '=', connectionId)
|
|
||||||
.execute();
|
|
||||||
}
|
|
||||||
|
|
||||||
async deleteByIntegration(
|
|
||||||
integrationId: string,
|
|
||||||
trx?: KyselyTransaction,
|
|
||||||
): Promise<void> {
|
|
||||||
const db = dbOrTx(this.db, trx);
|
|
||||||
await db
|
|
||||||
.deleteFrom('integrationConnections')
|
|
||||||
.where('integrationId', '=', integrationId)
|
|
||||||
.execute();
|
|
||||||
}
|
|
||||||
|
|
||||||
async findWorkspaceConnection(
|
|
||||||
integrationId: string,
|
|
||||||
trx?: KyselyTransaction,
|
|
||||||
): Promise<IntegrationConnection | undefined> {
|
|
||||||
const db = dbOrTx(this.db, trx);
|
|
||||||
return db
|
|
||||||
.selectFrom('integrationConnections')
|
|
||||||
.selectAll()
|
|
||||||
.where('integrationId', '=', integrationId)
|
|
||||||
.where('kind', '=', 'workspace')
|
|
||||||
.executeTakeFirst();
|
|
||||||
}
|
|
||||||
|
|
||||||
async findUserLink(
|
|
||||||
integrationId: string,
|
|
||||||
providerUserId: string,
|
|
||||||
trx?: KyselyTransaction,
|
|
||||||
): Promise<IntegrationConnection | undefined> {
|
|
||||||
const db = dbOrTx(this.db, trx);
|
|
||||||
return db
|
|
||||||
.selectFrom('integrationConnections')
|
|
||||||
.selectAll()
|
|
||||||
.where('integrationId', '=', integrationId)
|
|
||||||
.where('providerUserId', '=', providerUserId)
|
|
||||||
.where('kind', '=', 'user')
|
|
||||||
.executeTakeFirst();
|
|
||||||
}
|
|
||||||
|
|
||||||
async findUserLinkByUserId(
|
|
||||||
integrationId: string,
|
|
||||||
userId: string,
|
|
||||||
trx?: KyselyTransaction,
|
|
||||||
): Promise<IntegrationConnection | undefined> {
|
|
||||||
const db = dbOrTx(this.db, trx);
|
|
||||||
return db
|
|
||||||
.selectFrom('integrationConnections')
|
|
||||||
.selectAll()
|
|
||||||
.where('integrationId', '=', integrationId)
|
|
||||||
.where('userId', '=', userId)
|
|
||||||
.where('kind', '=', 'user')
|
|
||||||
.executeTakeFirst();
|
|
||||||
}
|
|
||||||
|
|
||||||
async deleteUserLink(
|
|
||||||
integrationId: string,
|
|
||||||
userId: string,
|
|
||||||
trx?: KyselyTransaction,
|
|
||||||
): Promise<void> {
|
|
||||||
const db = dbOrTx(this.db, trx);
|
|
||||||
await db
|
|
||||||
.deleteFrom('integrationConnections')
|
|
||||||
.where('integrationId', '=', integrationId)
|
|
||||||
.where('userId', '=', userId)
|
|
||||||
.where('kind', '=', 'user')
|
|
||||||
.execute();
|
|
||||||
}
|
|
||||||
|
|
||||||
async upsertUserLink(
|
|
||||||
input: {
|
|
||||||
integrationId: string;
|
|
||||||
workspaceId: string;
|
|
||||||
userId: string;
|
|
||||||
providerUserId: string;
|
|
||||||
metadata: Record<string, unknown>;
|
|
||||||
},
|
|
||||||
trx?: KyselyTransaction,
|
|
||||||
): Promise<IntegrationConnection> {
|
|
||||||
const db = dbOrTx(this.db, trx);
|
|
||||||
// Target the partial unique index uq_integration_connections_user_per_integration
|
|
||||||
// (integration_id, user_id) WHERE kind = 'user'. Without the .where() hint,
|
|
||||||
// ON CONFLICT can't match a partial index. The kind discriminator means a
|
|
||||||
// workspace bot row sharing (integration_id, user_id) with this user-link
|
|
||||||
// is no longer a conflict, so we cannot flip its kind.
|
|
||||||
return await db
|
|
||||||
.insertInto('integrationConnections')
|
|
||||||
.values({
|
|
||||||
integrationId: input.integrationId,
|
|
||||||
workspaceId: input.workspaceId,
|
|
||||||
userId: input.userId,
|
|
||||||
providerUserId: input.providerUserId,
|
|
||||||
kind: 'user',
|
|
||||||
metadata: input.metadata as any,
|
|
||||||
accessToken: null,
|
|
||||||
})
|
|
||||||
.onConflict((oc) =>
|
|
||||||
oc
|
|
||||||
.columns(['integrationId', 'userId'])
|
|
||||||
.where(sql.ref('kind'), '=', 'user')
|
|
||||||
.doUpdateSet({
|
|
||||||
providerUserId: input.providerUserId,
|
|
||||||
metadata: input.metadata as any,
|
|
||||||
updatedAt: new Date(),
|
|
||||||
}),
|
|
||||||
)
|
|
||||||
.returningAll()
|
|
||||||
.executeTakeFirstOrThrow();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,127 +0,0 @@
|
|||||||
import { Injectable } from '@nestjs/common';
|
|
||||||
import { InjectKysely } from 'nestjs-kysely';
|
|
||||||
import { sql } from 'kysely';
|
|
||||||
import { KyselyDB, KyselyTransaction } from '@docmost/db/types/kysely.types';
|
|
||||||
import {
|
|
||||||
Integration,
|
|
||||||
InsertableIntegration,
|
|
||||||
UpdatableIntegration,
|
|
||||||
} from '@docmost/db/types/entity.types';
|
|
||||||
import { dbOrTx } from '@docmost/db/utils';
|
|
||||||
|
|
||||||
@Injectable()
|
|
||||||
export class IntegrationRepo {
|
|
||||||
constructor(@InjectKysely() private readonly db: KyselyDB) {}
|
|
||||||
|
|
||||||
async findById(
|
|
||||||
integrationId: string,
|
|
||||||
trx?: KyselyTransaction,
|
|
||||||
): Promise<Integration | undefined> {
|
|
||||||
const db = dbOrTx(this.db, trx);
|
|
||||||
return db
|
|
||||||
.selectFrom('integrations')
|
|
||||||
.selectAll()
|
|
||||||
.where('id', '=', integrationId)
|
|
||||||
.where('deletedAt', 'is', null)
|
|
||||||
.executeTakeFirst();
|
|
||||||
}
|
|
||||||
|
|
||||||
async findByWorkspaceAndType(
|
|
||||||
workspaceId: string,
|
|
||||||
type: string,
|
|
||||||
trx?: KyselyTransaction,
|
|
||||||
): Promise<Integration | undefined> {
|
|
||||||
const db = dbOrTx(this.db, trx);
|
|
||||||
return db
|
|
||||||
.selectFrom('integrations')
|
|
||||||
.selectAll()
|
|
||||||
.where('workspaceId', '=', workspaceId)
|
|
||||||
.where('type', '=', type)
|
|
||||||
.where('deletedAt', 'is', null)
|
|
||||||
.executeTakeFirst();
|
|
||||||
}
|
|
||||||
|
|
||||||
async findAllByWorkspace(
|
|
||||||
workspaceId: string,
|
|
||||||
trx?: KyselyTransaction,
|
|
||||||
): Promise<Integration[]> {
|
|
||||||
const db = dbOrTx(this.db, trx);
|
|
||||||
return db
|
|
||||||
.selectFrom('integrations')
|
|
||||||
.selectAll()
|
|
||||||
.where('workspaceId', '=', workspaceId)
|
|
||||||
.where('deletedAt', 'is', null)
|
|
||||||
.execute();
|
|
||||||
}
|
|
||||||
|
|
||||||
async insert(
|
|
||||||
integration: InsertableIntegration,
|
|
||||||
trx?: KyselyTransaction,
|
|
||||||
): Promise<Integration> {
|
|
||||||
const db = dbOrTx(this.db, trx);
|
|
||||||
return db
|
|
||||||
.insertInto('integrations')
|
|
||||||
.values(integration)
|
|
||||||
.returningAll()
|
|
||||||
.executeTakeFirstOrThrow();
|
|
||||||
}
|
|
||||||
|
|
||||||
async insertOrRestore(
|
|
||||||
integration: InsertableIntegration,
|
|
||||||
trx?: KyselyTransaction,
|
|
||||||
): Promise<Integration> {
|
|
||||||
const db = dbOrTx(this.db, trx);
|
|
||||||
return db
|
|
||||||
.insertInto('integrations')
|
|
||||||
.values(integration)
|
|
||||||
.onConflict((oc) =>
|
|
||||||
oc.columns(['type', 'workspaceId']).doUpdateSet({
|
|
||||||
deletedAt: null,
|
|
||||||
installedById: integration.installedById,
|
|
||||||
updatedAt: new Date(),
|
|
||||||
}),
|
|
||||||
)
|
|
||||||
.returningAll()
|
|
||||||
.executeTakeFirstOrThrow();
|
|
||||||
}
|
|
||||||
|
|
||||||
async update(
|
|
||||||
integrationId: string,
|
|
||||||
data: UpdatableIntegration,
|
|
||||||
trx?: KyselyTransaction,
|
|
||||||
): Promise<Integration> {
|
|
||||||
const db = dbOrTx(this.db, trx);
|
|
||||||
return db
|
|
||||||
.updateTable('integrations')
|
|
||||||
.set({ ...data, updatedAt: new Date() })
|
|
||||||
.where('id', '=', integrationId)
|
|
||||||
.returningAll()
|
|
||||||
.executeTakeFirstOrThrow();
|
|
||||||
}
|
|
||||||
|
|
||||||
async softDelete(
|
|
||||||
integrationId: string,
|
|
||||||
trx?: KyselyTransaction,
|
|
||||||
): Promise<void> {
|
|
||||||
const db = dbOrTx(this.db, trx);
|
|
||||||
await db
|
|
||||||
.updateTable('integrations')
|
|
||||||
.set({ deletedAt: new Date() })
|
|
||||||
.where('id', '=', integrationId)
|
|
||||||
.execute();
|
|
||||||
}
|
|
||||||
|
|
||||||
async findByTypeAndSettingsField(
|
|
||||||
type: string,
|
|
||||||
key: string,
|
|
||||||
value: string,
|
|
||||||
): Promise<Integration | undefined> {
|
|
||||||
return this.db
|
|
||||||
.selectFrom('integrations')
|
|
||||||
.selectAll()
|
|
||||||
.where('type', '=', type)
|
|
||||||
.where('deletedAt', 'is', null)
|
|
||||||
.where(sql<string>`settings->>${sql.lit(key)}`, '=', value)
|
|
||||||
.executeTakeFirst();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,35 +0,0 @@
|
|||||||
import {
|
|
||||||
Body,
|
|
||||||
Controller,
|
|
||||||
HttpCode,
|
|
||||||
HttpStatus,
|
|
||||||
Post,
|
|
||||||
UseGuards,
|
|
||||||
} from '@nestjs/common';
|
|
||||||
import { JwtAuthGuard } from '../../../common/guards/jwt-auth.guard';
|
|
||||||
import { AuthUser } from '../../../common/decorators/auth-user.decorator';
|
|
||||||
import { AuthWorkspace } from '../../../common/decorators/auth-workspace.decorator';
|
|
||||||
import { User, Workspace } from '@docmost/db/types/entity.types';
|
|
||||||
import { UnfurlService } from './unfurl.service';
|
|
||||||
import { UnfurlDto } from '../dto/integration.dto';
|
|
||||||
|
|
||||||
@Controller('integrations')
|
|
||||||
export class UnfurlController {
|
|
||||||
constructor(private readonly unfurlService: UnfurlService) {}
|
|
||||||
|
|
||||||
@UseGuards(JwtAuthGuard)
|
|
||||||
@HttpCode(HttpStatus.OK)
|
|
||||||
@Post('unfurl')
|
|
||||||
async unfurl(
|
|
||||||
@Body() dto: UnfurlDto,
|
|
||||||
@AuthUser() user: User,
|
|
||||||
@AuthWorkspace() workspace: Workspace,
|
|
||||||
) {
|
|
||||||
const result = await this.unfurlService.unfurl(
|
|
||||||
dto.url,
|
|
||||||
user.id,
|
|
||||||
workspace.id,
|
|
||||||
);
|
|
||||||
return { data: result };
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,268 +0,0 @@
|
|||||||
import { Injectable, Logger } from '@nestjs/common';
|
|
||||||
import { IntegrationRegistry } from '../registry/integration-registry';
|
|
||||||
import { IntegrationConnectionRepo } from '../repos/integration-connection.repo';
|
|
||||||
import { IntegrationRepo } from '../repos/integration.repo';
|
|
||||||
import { OAuthService } from '../oauth/oauth.service';
|
|
||||||
import {
|
|
||||||
UnfurlResult,
|
|
||||||
UnfurlNeedsConnection,
|
|
||||||
UnfurlForbiddenError,
|
|
||||||
UnfurlNeedsConnectionError,
|
|
||||||
TokenInvalidError,
|
|
||||||
ProviderApiError,
|
|
||||||
IntegrationProvider,
|
|
||||||
} from '../registry/integration-provider.interface';
|
|
||||||
import { RedisService } from '@nestjs-labs/nestjs-ioredis';
|
|
||||||
import type { Redis } from 'ioredis';
|
|
||||||
import * as crypto from 'crypto';
|
|
||||||
|
|
||||||
const UNFURL_CACHE_TTL = 300; // 5 minutes
|
|
||||||
// Transient failures get a short negative cache so a broken provider is not
|
|
||||||
// re-fetched on every view; 404s cache at the normal TTL (the target is gone).
|
|
||||||
const UNFURL_ERROR_CACHE_TTL = 60;
|
|
||||||
const UNFURL_CACHE_PREFIX = 'unfurl:';
|
|
||||||
|
|
||||||
@Injectable()
|
|
||||||
export class UnfurlService {
|
|
||||||
private readonly logger = new Logger(UnfurlService.name);
|
|
||||||
private readonly redis: Redis;
|
|
||||||
|
|
||||||
constructor(
|
|
||||||
private readonly registry: IntegrationRegistry,
|
|
||||||
private readonly integrationRepo: IntegrationRepo,
|
|
||||||
private readonly connectionRepo: IntegrationConnectionRepo,
|
|
||||||
private readonly oauthService: OAuthService,
|
|
||||||
private readonly redisService: RedisService,
|
|
||||||
) {
|
|
||||||
this.redis = this.redisService.getOrThrow();
|
|
||||||
}
|
|
||||||
|
|
||||||
async unfurl(
|
|
||||||
url: string,
|
|
||||||
userId: string,
|
|
||||||
workspaceId: string,
|
|
||||||
): Promise<UnfurlResult | UnfurlNeedsConnection | null> {
|
|
||||||
const cacheKey = this.buildCacheKey(workspaceId, userId, url);
|
|
||||||
const cached = await this.redis.get(cacheKey);
|
|
||||||
if (cached) {
|
|
||||||
return JSON.parse(cached);
|
|
||||||
}
|
|
||||||
|
|
||||||
const resolved = await this.resolveProvider(url, workspaceId);
|
|
||||||
|
|
||||||
if (!resolved) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
const { provider, match, patternType, integration } = resolved;
|
|
||||||
|
|
||||||
if (!provider.unfurl) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Workspace-scoped providers (Slack) share one bot connection that serves
|
|
||||||
// every member; user-scoped providers need the requester's own token.
|
|
||||||
const connectionScope =
|
|
||||||
provider.definition.oauth?.connectionScope ?? 'user';
|
|
||||||
const connection =
|
|
||||||
connectionScope === 'workspace'
|
|
||||||
? await this.connectionRepo.findWorkspaceConnection(integration.id)
|
|
||||||
: await this.connectionRepo.findByIntegrationAndUser(
|
|
||||||
integration.id,
|
|
||||||
userId,
|
|
||||||
);
|
|
||||||
|
|
||||||
if (!connection || connection.invalidatedAt) {
|
|
||||||
// Dead workspace connections need an admin re-install; members get no card.
|
|
||||||
if (connectionScope === 'workspace') {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
// Not cached: the card should load as soon as the user (re)connects.
|
|
||||||
return this.buildNeedsConnection(
|
|
||||||
provider,
|
|
||||||
integration.id,
|
|
||||||
patternType,
|
|
||||||
match,
|
|
||||||
url,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
const accessToken =
|
|
||||||
await this.oauthService.getValidAccessToken(connection);
|
|
||||||
|
|
||||||
const unfurlResult = await provider.unfurl({
|
|
||||||
url,
|
|
||||||
accessToken,
|
|
||||||
match,
|
|
||||||
patternType,
|
|
||||||
settings: (integration.settings as Record<string, any>) ?? {},
|
|
||||||
userId,
|
|
||||||
integrationId: integration.id,
|
|
||||||
});
|
|
||||||
|
|
||||||
await this.redis.set(
|
|
||||||
cacheKey,
|
|
||||||
JSON.stringify(unfurlResult),
|
|
||||||
'EX',
|
|
||||||
UNFURL_CACHE_TTL,
|
|
||||||
);
|
|
||||||
|
|
||||||
return unfurlResult;
|
|
||||||
} catch (err) {
|
|
||||||
// The provider needs the requester to link an identity first (Slack's
|
|
||||||
// workspace bot serves everyone, but only linked members may unfurl).
|
|
||||||
// Not cached: the card should load as soon as the user links.
|
|
||||||
if (err instanceof UnfurlNeedsConnectionError) {
|
|
||||||
return this.buildNeedsConnection(
|
|
||||||
provider,
|
|
||||||
integration.id,
|
|
||||||
patternType,
|
|
||||||
match,
|
|
||||||
url,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
// Not-authorized is an expected outcome (no card), not an error.
|
|
||||||
if (err instanceof UnfurlForbiddenError) {
|
|
||||||
this.logger.debug(
|
|
||||||
`Unfurl not authorized for ${url}: ${(err as Error).message}`,
|
|
||||||
);
|
|
||||||
await this.cacheNull(cacheKey, UNFURL_ERROR_CACHE_TTL);
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
if (err instanceof TokenInvalidError) {
|
|
||||||
this.logger.warn(
|
|
||||||
`Retiring connection ${connection.id}: ${(err as Error).message}`,
|
|
||||||
);
|
|
||||||
await this.connectionRepo
|
|
||||||
.invalidate(connection.id)
|
|
||||||
.catch(() => undefined);
|
|
||||||
if (connectionScope === 'workspace') {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
// Not cached so the card heals the moment the user reconnects.
|
|
||||||
return this.buildNeedsConnection(
|
|
||||||
provider,
|
|
||||||
integration.id,
|
|
||||||
patternType,
|
|
||||||
match,
|
|
||||||
url,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
this.logger.error(`Unfurl failed for ${url}: ${(err as Error).message}`);
|
|
||||||
const ttl =
|
|
||||||
err instanceof ProviderApiError && err.status === 404
|
|
||||||
? UNFURL_CACHE_TTL
|
|
||||||
: UNFURL_ERROR_CACHE_TTL;
|
|
||||||
await this.cacheNull(cacheKey, ttl);
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private async cacheNull(cacheKey: string, ttl: number): Promise<void> {
|
|
||||||
await this.redis.set(cacheKey, 'null', 'EX', ttl);
|
|
||||||
}
|
|
||||||
|
|
||||||
async purgeUserCache(workspaceId: string, userId: string): Promise<void> {
|
|
||||||
const pattern = `${UNFURL_CACHE_PREFIX}${workspaceId}:${userId}:*`;
|
|
||||||
try {
|
|
||||||
const stream = this.redis.scanStream({ match: pattern, count: 100 });
|
|
||||||
for await (const keys of stream as AsyncIterable<string[]>) {
|
|
||||||
if (keys.length) {
|
|
||||||
await this.redis.unlink(...keys);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} catch (err) {
|
|
||||||
// best-effort by design: never fail a disconnect on cache purge; the TTL is the backstop
|
|
||||||
this.logger.error(
|
|
||||||
`Failed to purge unfurl cache for user ${userId}: ${(err as Error).message}`,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private buildNeedsConnection(
|
|
||||||
provider: IntegrationProvider,
|
|
||||||
integrationId: string,
|
|
||||||
patternType: string,
|
|
||||||
match: RegExpMatchArray,
|
|
||||||
url: string,
|
|
||||||
): UnfurlNeedsConnection {
|
|
||||||
const described =
|
|
||||||
provider.describeLink?.(patternType, match, url) ?? null;
|
|
||||||
|
|
||||||
let fallbackDescription: string | undefined;
|
|
||||||
try {
|
|
||||||
const parsed = new URL(url);
|
|
||||||
fallbackDescription = `${parsed.host}${parsed.pathname}`;
|
|
||||||
} catch {
|
|
||||||
fallbackDescription = undefined;
|
|
||||||
}
|
|
||||||
|
|
||||||
return {
|
|
||||||
needsConnection: true,
|
|
||||||
integrationId,
|
|
||||||
integrationType: provider.definition.type,
|
|
||||||
integrationName: provider.definition.name,
|
|
||||||
// Workspace-scoped providers also bind the authorizing user's identity
|
|
||||||
// on OAuth completion (onConnected upserts their user link), so any
|
|
||||||
// OAuth-capable provider supports connecting from Docmost.
|
|
||||||
oauthConnect: !!provider.definition.oauth,
|
|
||||||
title: described?.title ?? `${provider.definition.name} link`,
|
|
||||||
description: described?.description ?? fallbackDescription,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
private async resolveProvider(
|
|
||||||
url: string,
|
|
||||||
workspaceId: string,
|
|
||||||
): Promise<{
|
|
||||||
provider: IntegrationProvider;
|
|
||||||
match: RegExpMatchArray;
|
|
||||||
patternType: string;
|
|
||||||
integration: {
|
|
||||||
id: string;
|
|
||||||
type: string;
|
|
||||||
settings: unknown;
|
|
||||||
};
|
|
||||||
} | null> {
|
|
||||||
const staticResult = this.registry.findUnfurlProvider(url);
|
|
||||||
if (staticResult) {
|
|
||||||
const integration = await this.integrationRepo.findByWorkspaceAndType(
|
|
||||||
workspaceId,
|
|
||||||
staticResult.provider.definition.type,
|
|
||||||
);
|
|
||||||
if (integration) {
|
|
||||||
return { ...staticResult, integration };
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const integrations =
|
|
||||||
await this.integrationRepo.findAllByWorkspace(workspaceId);
|
|
||||||
|
|
||||||
for (const integration of integrations) {
|
|
||||||
const provider = this.registry.getProvider(integration.type);
|
|
||||||
if (!provider?.getUnfurlPatterns || !provider.unfurl) continue;
|
|
||||||
|
|
||||||
const settings = (integration.settings as Record<string, any>) ?? {};
|
|
||||||
const patterns = provider.getUnfurlPatterns(settings);
|
|
||||||
|
|
||||||
for (const pattern of patterns) {
|
|
||||||
const match = url.match(pattern.regex);
|
|
||||||
if (match) {
|
|
||||||
return { provider, match, patternType: pattern.type, integration };
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
private buildCacheKey(workspaceId: string, userId: string, url: string): string {
|
|
||||||
const hash = crypto
|
|
||||||
.createHash('sha256')
|
|
||||||
.update(url)
|
|
||||||
.digest('hex')
|
|
||||||
.slice(0, 16);
|
|
||||||
return `${UNFURL_CACHE_PREFIX}${workspaceId}:${userId}:${hash}`;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,67 +0,0 @@
|
|||||||
import {
|
|
||||||
ProviderApiError,
|
|
||||||
TokenInvalidError,
|
|
||||||
UnfurlForbiddenError,
|
|
||||||
} from '../registry/integration-provider.interface';
|
|
||||||
import { proxyFetch } from '../../../common/proxy-fetch';
|
|
||||||
|
|
||||||
export const INTEGRATION_HTTP_TIMEOUT_MS = 10_000;
|
|
||||||
|
|
||||||
// Providers explain refusals in the response body ("insufficient scope",
|
|
||||||
// "not allowed", ...); without it a 403 is undiagnosable from the logs.
|
|
||||||
const MAX_ERROR_BODY_CHARS = 300;
|
|
||||||
|
|
||||||
async function readErrorBody(response: Response): Promise<string> {
|
|
||||||
try {
|
|
||||||
const text = await response.text();
|
|
||||||
return text.replace(/\s+/g, ' ').trim().slice(0, MAX_ERROR_BODY_CHARS);
|
|
||||||
} catch {
|
|
||||||
return '';
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Bounds every provider call and maps 401 to TokenInvalidError so callers can retire the connection.
|
|
||||||
export async function providerApiFetch(
|
|
||||||
providerName: string,
|
|
||||||
url: string,
|
|
||||||
init: RequestInit = {},
|
|
||||||
): Promise<Response> {
|
|
||||||
const response = await proxyFetch(url, {
|
|
||||||
...init,
|
|
||||||
redirect: 'manual',
|
|
||||||
signal: AbortSignal.timeout(INTEGRATION_HTTP_TIMEOUT_MS),
|
|
||||||
});
|
|
||||||
|
|
||||||
// Don't follow redirects: a 3xx could hop to an internal address.
|
|
||||||
if (response.type === 'opaqueredirect' || response.status === 0) {
|
|
||||||
throw new ProviderApiError(providerName, 502, 'unexpected redirect');
|
|
||||||
}
|
|
||||||
|
|
||||||
if (response.status === 401) {
|
|
||||||
throw new TokenInvalidError(
|
|
||||||
`${providerName} API error: 401 Unauthorized ${await readErrorBody(response)}`.trimEnd(),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
if (!response.ok) {
|
|
||||||
const body = await readErrorBody(response);
|
|
||||||
|
|
||||||
// 403 normally means the viewer simply can't reach that resource, which is
|
|
||||||
// an expected "no card" outcome. GitHub also spends 403 on secondary rate
|
|
||||||
// limits, so quota signals stay a real error an operator can see.
|
|
||||||
const rateLimited =
|
|
||||||
response.headers.get('retry-after') !== null ||
|
|
||||||
response.headers.get('x-ratelimit-remaining') === '0';
|
|
||||||
if (response.status === 403 && !rateLimited) {
|
|
||||||
throw new UnfurlForbiddenError(
|
|
||||||
`${providerName} API error: 403 ${body}`.trimEnd(),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
throw new ProviderApiError(
|
|
||||||
providerName,
|
|
||||||
response.status,
|
|
||||||
`${response.statusText} ${body}`.trim(),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
return response;
|
|
||||||
}
|
|
||||||
@@ -1,5 +0,0 @@
|
|||||||
import { formatDistanceStrict } from 'date-fns';
|
|
||||||
|
|
||||||
export function relativeTime(iso: string): string {
|
|
||||||
return formatDistanceStrict(new Date(iso), new Date(), { addSuffix: true });
|
|
||||||
}
|
|
||||||
@@ -1,6 +1,5 @@
|
|||||||
import { Injectable, Logger } from '@nestjs/common';
|
import { Injectable, Logger } from '@nestjs/common';
|
||||||
import { InjectKysely } from 'nestjs-kysely';
|
import { InjectKysely } from 'nestjs-kysely';
|
||||||
import { EventEmitter2 } from '@nestjs/event-emitter';
|
|
||||||
import { KyselyDB } from '@docmost/db/types/kysely.types';
|
import { KyselyDB } from '@docmost/db/types/kysely.types';
|
||||||
import { NotificationRepo } from '@docmost/db/repos/notification/notification.repo';
|
import { NotificationRepo } from '@docmost/db/repos/notification/notification.repo';
|
||||||
import { InsertableNotification } from '@docmost/db/types/entity.types';
|
import { InsertableNotification } from '@docmost/db/types/entity.types';
|
||||||
@@ -9,7 +8,6 @@ import { WsGateway } from '../../ws/ws.gateway';
|
|||||||
import { MailService } from '../../integrations/mail/mail.service';
|
import { MailService } from '../../integrations/mail/mail.service';
|
||||||
import { NotificationTab, NotificationType, NotificationTypeToSettingKey } from './notification.constants';
|
import { NotificationTab, NotificationType, NotificationTypeToSettingKey } from './notification.constants';
|
||||||
import { PagePermissionRepo } from '@docmost/db/repos/page/page-permission.repo';
|
import { PagePermissionRepo } from '@docmost/db/repos/page/page-permission.repo';
|
||||||
import { EventName } from '../../common/events/event.contants';
|
|
||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
export class NotificationService {
|
export class NotificationService {
|
||||||
@@ -20,7 +18,6 @@ export class NotificationService {
|
|||||||
private readonly pagePermissionRepo: PagePermissionRepo,
|
private readonly pagePermissionRepo: PagePermissionRepo,
|
||||||
private readonly wsGateway: WsGateway,
|
private readonly wsGateway: WsGateway,
|
||||||
private readonly mailService: MailService,
|
private readonly mailService: MailService,
|
||||||
private readonly eventEmitter: EventEmitter2,
|
|
||||||
@InjectKysely() private readonly db: KyselyDB,
|
@InjectKysely() private readonly db: KyselyDB,
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
@@ -37,8 +34,6 @@ export class NotificationService {
|
|||||||
|
|
||||||
const notification = await this.notificationRepo.insert(data);
|
const notification = await this.notificationRepo.insert(data);
|
||||||
|
|
||||||
this.eventEmitter.emit(EventName.NOTIFICATION_CREATED, notification);
|
|
||||||
|
|
||||||
this.wsGateway.server
|
this.wsGateway.server
|
||||||
.to(`user-${data.userId}`)
|
.to(`user-${data.userId}`)
|
||||||
.emit('notification', { id: notification.id, type: notification.type });
|
.emit('notification', { id: notification.id, type: notification.type });
|
||||||
|
|||||||
@@ -102,19 +102,6 @@ export class PageAccessService {
|
|||||||
return { hasRestriction: hasAnyRestriction };
|
return { hasRestriction: hasAnyRestriction };
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* Validate user can create a root page in the space, throws if not.
|
|
||||||
* Mirrors the space-level check the HTTP create endpoint enforces so
|
|
||||||
* non-HTTP callers (Slack, integrations) cannot bypass it. A non-member
|
|
||||||
* (including a space in another workspace) throws from createForUser.
|
|
||||||
*/
|
|
||||||
async validateCanCreate(spaceId: string, user: User): Promise<void> {
|
|
||||||
const ability = await this.spaceAbility.createForUser(user, spaceId);
|
|
||||||
if (ability.cannot(SpaceCaslAction.Create, SpaceCaslSubject.Page)) {
|
|
||||||
throw new ForbiddenException();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async validateCanComment(
|
async validateCanComment(
|
||||||
page: Page,
|
page: Page,
|
||||||
user: User,
|
user: User,
|
||||||
|
|||||||
@@ -175,44 +175,7 @@ export class PageService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async nextPagePosition(spaceId: string, parentPageId?: string) {
|
async nextPagePosition(spaceId: string, parentPageId?: string) {
|
||||||
let pagePosition: string;
|
return this.pageRepo.nextPagePosition(spaceId, parentPageId);
|
||||||
|
|
||||||
const lastPageQuery = this.db
|
|
||||||
.selectFrom('pages')
|
|
||||||
.select(['position'])
|
|
||||||
.where('spaceId', '=', spaceId)
|
|
||||||
.where('deletedAt', 'is', null)
|
|
||||||
.orderBy('position', (ob) => ob.collate('C').desc())
|
|
||||||
.limit(1);
|
|
||||||
|
|
||||||
if (parentPageId) {
|
|
||||||
// check for children of this page
|
|
||||||
const lastPage = await lastPageQuery
|
|
||||||
.where('parentPageId', '=', parentPageId)
|
|
||||||
.executeTakeFirst();
|
|
||||||
|
|
||||||
if (!lastPage) {
|
|
||||||
pagePosition = generateJitteredKeyBetween(null, null);
|
|
||||||
} else {
|
|
||||||
// if there is an existing page, we should get a position below it
|
|
||||||
pagePosition = generateJitteredKeyBetween(lastPage.position, null);
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
// for root page
|
|
||||||
const lastPage = await lastPageQuery
|
|
||||||
.where('parentPageId', 'is', null)
|
|
||||||
.executeTakeFirst();
|
|
||||||
|
|
||||||
// if no existing page, make this the first
|
|
||||||
if (!lastPage) {
|
|
||||||
pagePosition = generateJitteredKeyBetween(null, null); // we expect "a0"
|
|
||||||
} else {
|
|
||||||
// if there is an existing page, we should get a position below it
|
|
||||||
pagePosition = generateJitteredKeyBetween(lastPage.position, null);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return pagePosition;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async update(
|
async update(
|
||||||
|
|||||||
@@ -27,7 +27,6 @@ export class SearchService {
|
|||||||
opts: {
|
opts: {
|
||||||
userId?: string;
|
userId?: string;
|
||||||
workspaceId: string;
|
workspaceId: string;
|
||||||
titlesOnly?: boolean;
|
|
||||||
},
|
},
|
||||||
): Promise<{ items: SearchResponseDto[] }> {
|
): Promise<{ items: SearchResponseDto[] }> {
|
||||||
const { query } = searchParams;
|
const { query } = searchParams;
|
||||||
@@ -35,12 +34,6 @@ export class SearchService {
|
|||||||
if (query.length < 1) {
|
if (query.length < 1) {
|
||||||
return { items: [] };
|
return { items: [] };
|
||||||
}
|
}
|
||||||
|
|
||||||
// Use ILIKE titles-only search if titlesOnly flag is set
|
|
||||||
if (opts.titlesOnly) {
|
|
||||||
return this.searchPageTitlesOnly(searchParams, opts);
|
|
||||||
}
|
|
||||||
|
|
||||||
const searchQuery = tsquery(query.trim() + '*');
|
const searchQuery = tsquery(query.trim() + '*');
|
||||||
|
|
||||||
let queryResults = this.db
|
let queryResults = this.db
|
||||||
@@ -158,71 +151,6 @@ export class SearchService {
|
|||||||
return { items: searchResults };
|
return { items: searchResults };
|
||||||
}
|
}
|
||||||
|
|
||||||
private async searchPageTitlesOnly(
|
|
||||||
searchParams: SearchDTO,
|
|
||||||
opts: {
|
|
||||||
userId?: string;
|
|
||||||
workspaceId: string;
|
|
||||||
},
|
|
||||||
): Promise<{ items: SearchResponseDto[] }> {
|
|
||||||
const { query } = searchParams;
|
|
||||||
|
|
||||||
let queryResults = this.db
|
|
||||||
.selectFrom('pages')
|
|
||||||
.select([
|
|
||||||
'id',
|
|
||||||
'slugId',
|
|
||||||
'title',
|
|
||||||
'icon',
|
|
||||||
'parentPageId',
|
|
||||||
'creatorId',
|
|
||||||
'createdAt',
|
|
||||||
'updatedAt',
|
|
||||||
])
|
|
||||||
.where('title', 'ilike', `%${query}%`)
|
|
||||||
.where('deletedAt', 'is', null)
|
|
||||||
.orderBy('updatedAt', 'desc')
|
|
||||||
.limit(searchParams.limit || 10)
|
|
||||||
.offset(searchParams.offset || 0);
|
|
||||||
|
|
||||||
if (searchParams.spaceId) {
|
|
||||||
// search by spaceId
|
|
||||||
queryResults = queryResults.where('spaceId', '=', searchParams.spaceId);
|
|
||||||
} else if (opts.userId) {
|
|
||||||
// only search spaces the user is a member of
|
|
||||||
queryResults = queryResults
|
|
||||||
.where(
|
|
||||||
'spaceId',
|
|
||||||
'in',
|
|
||||||
this.spaceMemberRepo.getUserSpaceIdsQuery(opts.userId),
|
|
||||||
)
|
|
||||||
.where('workspaceId', '=', opts.workspaceId);
|
|
||||||
} else {
|
|
||||||
return { items: [] };
|
|
||||||
}
|
|
||||||
|
|
||||||
queryResults = queryResults.select((eb) => this.pageRepo.withSpace(eb));
|
|
||||||
|
|
||||||
//@ts-ignore
|
|
||||||
let results: any[] = await queryResults.execute();
|
|
||||||
|
|
||||||
// Filter results by page-level permissions (if user is authenticated)
|
|
||||||
if (opts.userId && results.length > 0) {
|
|
||||||
const pageIds = results.map((r: any) => r.id);
|
|
||||||
const accessibleIds =
|
|
||||||
await this.pagePermissionRepo.filterAccessiblePageIds({
|
|
||||||
pageIds,
|
|
||||||
userId: opts.userId,
|
|
||||||
spaceId: searchParams.spaceId,
|
|
||||||
});
|
|
||||||
const accessibleSet = new Set(accessibleIds);
|
|
||||||
results = results.filter((r: any) => accessibleSet.has(r.id));
|
|
||||||
}
|
|
||||||
|
|
||||||
//@ts-ignore
|
|
||||||
return { items: results };
|
|
||||||
}
|
|
||||||
|
|
||||||
async searchSuggestions(
|
async searchSuggestions(
|
||||||
suggestion: SearchSuggestionDTO,
|
suggestion: SearchSuggestionDTO,
|
||||||
userId: string,
|
userId: string,
|
||||||
|
|||||||
@@ -1,92 +0,0 @@
|
|||||||
import { type Kysely, sql } from 'kysely';
|
|
||||||
|
|
||||||
export async function up(db: Kysely<any>): Promise<void> {
|
|
||||||
await db.schema
|
|
||||||
.createTable('integrations')
|
|
||||||
.ifNotExists()
|
|
||||||
.addColumn('id', 'uuid', (col) =>
|
|
||||||
col.primaryKey().defaultTo(sql`gen_uuid_v7()`),
|
|
||||||
)
|
|
||||||
.addColumn('workspace_id', 'uuid', (col) =>
|
|
||||||
col.references('workspaces.id').onDelete('cascade').notNull(),
|
|
||||||
)
|
|
||||||
.addColumn('type', 'text', (col) => col.notNull())
|
|
||||||
.addColumn('settings', 'jsonb')
|
|
||||||
.addColumn('installed_by_id', 'uuid', (col) =>
|
|
||||||
col.references('users.id').onDelete('set null'),
|
|
||||||
)
|
|
||||||
.addColumn('created_at', 'timestamptz', (col) =>
|
|
||||||
col.notNull().defaultTo(sql`now()`),
|
|
||||||
)
|
|
||||||
.addColumn('updated_at', 'timestamptz', (col) =>
|
|
||||||
col.notNull().defaultTo(sql`now()`),
|
|
||||||
)
|
|
||||||
.addColumn('deleted_at', 'timestamptz')
|
|
||||||
.addUniqueConstraint('uq_integrations_workspace_type', [
|
|
||||||
'workspace_id',
|
|
||||||
'type',
|
|
||||||
])
|
|
||||||
.execute();
|
|
||||||
|
|
||||||
await db.schema
|
|
||||||
.createTable('integration_connections')
|
|
||||||
.ifNotExists()
|
|
||||||
.addColumn('id', 'uuid', (col) =>
|
|
||||||
col.primaryKey().defaultTo(sql`gen_uuid_v7()`),
|
|
||||||
)
|
|
||||||
.addColumn('integration_id', 'uuid', (col) =>
|
|
||||||
col.references('integrations.id').onDelete('cascade').notNull(),
|
|
||||||
)
|
|
||||||
.addColumn('user_id', 'uuid', (col) =>
|
|
||||||
col.references('users.id').onDelete('cascade').notNull(),
|
|
||||||
)
|
|
||||||
.addColumn('workspace_id', 'uuid', (col) =>
|
|
||||||
col.references('workspaces.id').onDelete('cascade').notNull(),
|
|
||||||
)
|
|
||||||
.addColumn('provider_user_id', 'text')
|
|
||||||
.addColumn('access_token', 'text')
|
|
||||||
.addColumn('refresh_token', 'text')
|
|
||||||
.addColumn('token_expires_at', 'timestamptz')
|
|
||||||
.addColumn('invalidated_at', 'timestamptz')
|
|
||||||
.addColumn('scopes', 'text')
|
|
||||||
.addColumn('metadata', 'jsonb')
|
|
||||||
// 'workspace' = one shared bot/app connection per integration (Slack);
|
|
||||||
// 'user' = a per-user OAuth token or identity link (Linear, GitHub, Slack
|
|
||||||
// identity binding). Enforced via a check constraint below.
|
|
||||||
.addColumn('kind', 'text', (col) => col.notNull().defaultTo('user'))
|
|
||||||
.addColumn('created_at', 'timestamptz', (col) =>
|
|
||||||
col.notNull().defaultTo(sql`now()`),
|
|
||||||
)
|
|
||||||
.addColumn('updated_at', 'timestamptz', (col) =>
|
|
||||||
col.notNull().defaultTo(sql`now()`),
|
|
||||||
)
|
|
||||||
.execute();
|
|
||||||
|
|
||||||
await sql`
|
|
||||||
ALTER TABLE integration_connections
|
|
||||||
ADD CONSTRAINT integration_connections_kind_check
|
|
||||||
CHECK (kind IN ('workspace', 'user'))
|
|
||||||
`.execute(db);
|
|
||||||
|
|
||||||
// One workspace-bot connection per integration.
|
|
||||||
await db.schema
|
|
||||||
.createIndex('uq_integration_connections_workspace_per_integration')
|
|
||||||
.on('integration_connections')
|
|
||||||
.column('integration_id')
|
|
||||||
.where(sql.ref('kind'), '=', 'workspace')
|
|
||||||
.unique()
|
|
||||||
.execute();
|
|
||||||
|
|
||||||
await db.schema
|
|
||||||
.createIndex('uq_integration_connections_user_per_integration')
|
|
||||||
.on('integration_connections')
|
|
||||||
.columns(['integration_id', 'user_id'])
|
|
||||||
.where(sql.ref('kind'), '=', 'user')
|
|
||||||
.unique()
|
|
||||||
.execute();
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function down(db: Kysely<any>): Promise<void> {
|
|
||||||
await db.schema.dropTable('integration_connections').execute();
|
|
||||||
await db.schema.dropTable('integrations').execute();
|
|
||||||
}
|
|
||||||
@@ -16,6 +16,7 @@ import { jsonArrayFrom, jsonObjectFrom } from 'kysely/helpers/postgres';
|
|||||||
import { SpaceMemberRepo } from '@docmost/db/repos/space/space-member.repo';
|
import { SpaceMemberRepo } from '@docmost/db/repos/space/space-member.repo';
|
||||||
import { EventEmitter2 } from '@nestjs/event-emitter';
|
import { EventEmitter2 } from '@nestjs/event-emitter';
|
||||||
import { EventName } from '../../../common/events/event.contants';
|
import { EventName } from '../../../common/events/event.contants';
|
||||||
|
import { generateJitteredKeyBetween } from 'fractional-indexing-jittered';
|
||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
export class PageRepo {
|
export class PageRepo {
|
||||||
@@ -605,4 +606,27 @@ export class PageRepo {
|
|||||||
.execute()
|
.execute()
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async nextPagePosition(
|
||||||
|
spaceId: string,
|
||||||
|
parentPageId?: string,
|
||||||
|
): Promise<string> {
|
||||||
|
const lastPageQuery = this.db
|
||||||
|
.selectFrom('pages')
|
||||||
|
.select(['position'])
|
||||||
|
.where('spaceId', '=', spaceId)
|
||||||
|
.where('deletedAt', 'is', null)
|
||||||
|
.orderBy('position', (ob) => ob.collate('C').desc())
|
||||||
|
.limit(1);
|
||||||
|
|
||||||
|
const lastPage = parentPageId
|
||||||
|
? await lastPageQuery
|
||||||
|
.where('parentPageId', '=', parentPageId)
|
||||||
|
.executeTakeFirst()
|
||||||
|
: await lastPageQuery
|
||||||
|
.where('parentPageId', 'is', null)
|
||||||
|
.executeTakeFirst();
|
||||||
|
|
||||||
|
return generateJitteredKeyBetween(lastPage?.position ?? null, null);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,34 @@
|
|||||||
|
import { Json, Timestamp, Generated } from '@docmost/db/types/db';
|
||||||
|
|
||||||
|
export interface ConfluenceApiImports {
|
||||||
|
id: Generated<string>;
|
||||||
|
fileTaskId: string;
|
||||||
|
siteUrl: string;
|
||||||
|
authType: string;
|
||||||
|
authEmail: string | null;
|
||||||
|
authToken: string | null;
|
||||||
|
authUsername: string | null;
|
||||||
|
totalSpaces: Generated<number>;
|
||||||
|
importedSpaces: Generated<number>;
|
||||||
|
totalPages: Generated<number>;
|
||||||
|
importedPages: Generated<number>;
|
||||||
|
totalUsers: Generated<number>;
|
||||||
|
importedUsers: Generated<number>;
|
||||||
|
totalAttachments: Generated<number>;
|
||||||
|
importedAttachments: Generated<number>;
|
||||||
|
totalLabels: Generated<number>;
|
||||||
|
importedLabels: Generated<number>;
|
||||||
|
totalGroups: Generated<number>;
|
||||||
|
importedGroups: Generated<number>;
|
||||||
|
totalRestrictedPages: Generated<number>;
|
||||||
|
importedRestrictedPages: Generated<number>;
|
||||||
|
idMapping: Generated<Json>;
|
||||||
|
warnings: Generated<Json>;
|
||||||
|
currentPhase: string | null;
|
||||||
|
cancelled: Generated<boolean>;
|
||||||
|
spaceKeys: Generated<Json>;
|
||||||
|
workspaceId: string;
|
||||||
|
creatorId: string | null;
|
||||||
|
createdAt: Generated<Timestamp>;
|
||||||
|
updatedAt: Generated<Timestamp>;
|
||||||
|
}
|
||||||
-30
@@ -506,34 +506,6 @@ export interface Watchers {
|
|||||||
createdAt: Generated<Timestamp>;
|
createdAt: Generated<Timestamp>;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface Integrations {
|
|
||||||
id: Generated<string>;
|
|
||||||
workspaceId: string;
|
|
||||||
type: string;
|
|
||||||
settings: Json | null;
|
|
||||||
installedById: string | null;
|
|
||||||
createdAt: Generated<Timestamp>;
|
|
||||||
updatedAt: Generated<Timestamp>;
|
|
||||||
deletedAt: Timestamp | null;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface IntegrationConnections {
|
|
||||||
id: Generated<string>;
|
|
||||||
integrationId: string;
|
|
||||||
userId: string;
|
|
||||||
workspaceId: string;
|
|
||||||
providerUserId: string | null;
|
|
||||||
accessToken: string | null;
|
|
||||||
refreshToken: string | null;
|
|
||||||
tokenExpiresAt: Timestamp | null;
|
|
||||||
invalidatedAt: Timestamp | null;
|
|
||||||
scopes: string | null;
|
|
||||||
kind: string;
|
|
||||||
metadata: Json | null;
|
|
||||||
createdAt: Generated<Timestamp>;
|
|
||||||
updatedAt: Generated<Timestamp>;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface Labels {
|
export interface Labels {
|
||||||
id: Generated<string>;
|
id: Generated<string>;
|
||||||
name: string;
|
name: string;
|
||||||
@@ -682,8 +654,6 @@ export interface DB {
|
|||||||
fileTasks: FileTasks;
|
fileTasks: FileTasks;
|
||||||
groups: Groups;
|
groups: Groups;
|
||||||
groupUsers: GroupUsers;
|
groupUsers: GroupUsers;
|
||||||
integrationConnections: IntegrationConnections;
|
|
||||||
integrations: Integrations;
|
|
||||||
labels: Labels;
|
labels: Labels;
|
||||||
notifications: Notifications;
|
notifications: Notifications;
|
||||||
pageAccess: PageAccess;
|
pageAccess: PageAccess;
|
||||||
|
|||||||
@@ -1,9 +1,8 @@
|
|||||||
import { DB } from '@docmost/db/types/db';
|
import { DB } from '@docmost/db/types/db';
|
||||||
import { PageEmbeddings } from '@docmost/db/types/embeddings.types';
|
import { PageEmbeddings } from '@docmost/db/types/embeddings.types';
|
||||||
import { Integrations, IntegrationConnections } from '@docmost/db/types/db';
|
import { ConfluenceApiImports } from './custom.types';
|
||||||
|
|
||||||
export interface DbInterface extends DB {
|
export interface DbInterface extends DB {
|
||||||
pageEmbeddings: PageEmbeddings;
|
pageEmbeddings: PageEmbeddings;
|
||||||
integrations: Integrations;
|
confluenceApiImports: ConfluenceApiImports;
|
||||||
integrationConnections: IntegrationConnections;
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -8,8 +8,6 @@ import {
|
|||||||
BaseViews,
|
BaseViews,
|
||||||
Comments,
|
Comments,
|
||||||
Groups,
|
Groups,
|
||||||
Integrations as _Integrations,
|
|
||||||
IntegrationConnections as _IntegrationConnections,
|
|
||||||
Labels,
|
Labels,
|
||||||
Notifications,
|
Notifications,
|
||||||
PageLabels,
|
PageLabels,
|
||||||
@@ -201,19 +199,6 @@ export type Watcher = Selectable<Watchers>;
|
|||||||
export type InsertableWatcher = Insertable<Watchers>;
|
export type InsertableWatcher = Insertable<Watchers>;
|
||||||
export type UpdatableWatcher = Updateable<Omit<Watchers, 'id'>>;
|
export type UpdatableWatcher = Updateable<Omit<Watchers, 'id'>>;
|
||||||
|
|
||||||
// Integration
|
|
||||||
export type Integration = Selectable<_Integrations>;
|
|
||||||
export type InsertableIntegration = Insertable<_Integrations>;
|
|
||||||
export type UpdatableIntegration = Updateable<Omit<_Integrations, 'id'>>;
|
|
||||||
|
|
||||||
// Integration Connection
|
|
||||||
export type IntegrationConnection = Selectable<_IntegrationConnections>;
|
|
||||||
export type InsertableIntegrationConnection =
|
|
||||||
Insertable<_IntegrationConnections>;
|
|
||||||
export type UpdatableIntegrationConnection = Updateable<
|
|
||||||
Omit<_IntegrationConnections, 'id'>
|
|
||||||
>;
|
|
||||||
|
|
||||||
// Label
|
// Label
|
||||||
export type Label = Selectable<Labels>;
|
export type Label = Selectable<Labels>;
|
||||||
export type InsertableLabel = Insertable<Labels>;
|
export type InsertableLabel = Insertable<Labels>;
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user