@flexkit/studio 0.2.22 → 0.2.24
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{activity-nav-button-7RLCHOFV.js → activity-nav-button-4VTYGP4T.js} +2 -2
- package/dist/{activity-nav-button-7RLCHOFV.js.map → activity-nav-button-4VTYGP4T.js.map} +1 -1
- package/dist/astro.js +1 -1
- package/dist/chat-page-A7FG7WTN.js +4 -0
- package/dist/chat-page-A7FG7WTN.js.map +1 -0
- package/dist/{chunk-MHVZXDVL.js → chunk-3COXA5QH.js} +2 -2
- package/dist/{chunk-MHVZXDVL.js.map → chunk-3COXA5QH.js.map} +1 -1
- package/dist/{chunk-SE4HJCGA.js → chunk-3IUKXOKF.js} +2 -2
- package/dist/{chunk-SE4HJCGA.js.map → chunk-3IUKXOKF.js.map} +1 -1
- package/dist/{chunk-7ERLYAPR.js → chunk-5OGT6WGZ.js} +2 -2
- package/dist/{chunk-7ERLYAPR.js.map → chunk-5OGT6WGZ.js.map} +1 -1
- package/dist/{chunk-BM7INZL3.js → chunk-AKW7EKYI.js} +3 -3
- package/dist/{chunk-BM7INZL3.js.map → chunk-AKW7EKYI.js.map} +1 -1
- package/dist/{chunk-GGC75EMC.js → chunk-C4XLDODU.js} +2 -0
- package/dist/{chunk-K2KW6UYG.js → chunk-HTSMODQB.js} +2 -2
- package/dist/{chunk-K2KW6UYG.js.map → chunk-HTSMODQB.js.map} +1 -1
- package/dist/chunk-I6Z3WLAX.js +2 -0
- package/dist/chunk-I6Z3WLAX.js.map +1 -0
- package/dist/{chunk-HBTMGDOM.js → chunk-IQ2F2FFF.js} +2 -2
- package/dist/{chunk-HBTMGDOM.js.map → chunk-IQ2F2FFF.js.map} +1 -1
- package/dist/{chunk-RPLKJVDQ.js → chunk-JSJZKPXU.js} +3 -3
- package/dist/{chunk-RPLKJVDQ.js.map → chunk-JSJZKPXU.js.map} +1 -1
- package/dist/{chunk-4LVMCUHR.js → chunk-KN7OJFEX.js} +2 -2
- package/dist/{chunk-4LVMCUHR.js.map → chunk-KN7OJFEX.js.map} +1 -1
- package/dist/chunk-L3GBAK54.js +4 -0
- package/dist/chunk-L3GBAK54.js.map +1 -0
- package/dist/chunk-MNLYE7DK.js +3 -0
- package/dist/chunk-MNLYE7DK.js.map +1 -0
- package/dist/{chunk-YXUEPR7K.js → chunk-NO3AH2M3.js} +3 -3
- package/dist/{chunk-YXUEPR7K.js.map → chunk-NO3AH2M3.js.map} +1 -1
- package/dist/{chunk-6AI7322C.js → chunk-NSVX6HEN.js} +3 -3
- package/dist/{chunk-6AI7322C.js.map → chunk-NSVX6HEN.js.map} +1 -1
- package/dist/chunk-SZOEW2TL.js +8 -0
- package/dist/chunk-SZOEW2TL.js.map +1 -0
- package/dist/chunk-U6E7GNQW.js +2 -0
- package/dist/chunk-U6E7GNQW.js.map +1 -0
- package/dist/{chunk-UJEDL3IZ.js → chunk-UBFBXBPG.js} +2 -2
- package/dist/{chunk-UJEDL3IZ.js.map → chunk-UBFBXBPG.js.map} +1 -1
- package/dist/{chunk-LIMXKPEK.js → chunk-V7C4EHK3.js} +2 -2
- package/dist/{chunk-LIMXKPEK.js.map → chunk-V7C4EHK3.js.map} +1 -1
- package/dist/chunk-WPCPL2TQ.js +3 -0
- package/dist/chunk-WPCPL2TQ.js.map +1 -0
- package/dist/{chunk-UCHWUGRT.js → chunk-XV2B3W6Z.js} +3 -3
- package/dist/{chunk-UCHWUGRT.js.map → chunk-XV2B3W6Z.js.map} +1 -1
- package/dist/electron.js +1 -1
- package/dist/{entry-GWZ7DELK.js → entry-RMRLV3NM.js} +2 -2
- package/dist/{entry-GWZ7DELK.js.map → entry-RMRLV3NM.js.map} +1 -1
- package/dist/index.js +8 -10
- package/dist/index.js.map +1 -1
- package/dist/{list-LMIKCT2W.js → list-GVATECOW.js} +2 -2
- package/dist/{list-LMIKCT2W.js.map → list-GVATECOW.js.map} +1 -1
- package/dist/{list-FQZII7QD.js → list-HR55TZQX.js} +3 -3
- package/dist/{list-FQZII7QD.js.map → list-HR55TZQX.js.map} +1 -1
- package/dist/nextjs.js +1 -1
- package/dist/pages-OJYYLSI3.js +5 -0
- package/dist/pages-OJYYLSI3.js.map +1 -0
- package/dist/plugin-pages-BS2IMNRU.js +2 -0
- package/dist/{plugin-pages-4HTADSK3.js.map → plugin-pages-BS2IMNRU.js.map} +1 -1
- package/dist/record-links-2QWJFFZF.js +2 -0
- package/dist/{record-links-FDWV4X5W.js.map → record-links-2QWJFFZF.js.map} +1 -1
- package/dist/{root-ZYUSZZWR.js → root-54BI6S4V.js} +3 -3
- package/dist/{root-ZYUSZZWR.js.map → root-54BI6S4V.js.map} +1 -1
- package/dist/root-E35GZ7SV.js +14 -0
- package/dist/root-E35GZ7SV.js.map +1 -0
- package/dist/{root-X3V4NC2D.js → root-GAB2SFFF.js} +2 -2
- package/dist/{root-X3V4NC2D.js.map → root-GAB2SFFF.js.map} +1 -1
- package/dist/{root-VL4EM2IS.js → root-JWXXF653.js} +3 -3
- package/dist/{root-VL4EM2IS.js.map → root-JWXXF653.js.map} +1 -1
- package/dist/{root-OSXC52GL.js → root-U52KZQSD.js} +2 -2
- package/dist/{root-OSXC52GL.js.map → root-U52KZQSD.js.map} +1 -1
- package/dist/{root-GYJGAS22.js → root-ZCXGZCUT.js} +2 -2
- package/dist/{root-GYJGAS22.js.map → root-ZCXGZCUT.js.map} +1 -1
- package/dist/{search-UW7WE2CS.js → search-IOYOKT6M.js} +2 -2
- package/dist/{search-UW7WE2CS.js.map → search-IOYOKT6M.js.map} +1 -1
- package/dist/{skills-pages-Q4YSUQVZ.js → skills-pages-MA6JLBB4.js} +2 -2
- package/dist/{skills-pages-Q4YSUQVZ.js.map → skills-pages-MA6JLBB4.js.map} +1 -1
- package/dist/{source-PGSWL4DQ.js → source-3YZNNITL.js} +2 -2
- package/dist/{source-PGSWL4DQ.js.map → source-3YZNNITL.js.map} +1 -1
- package/dist/tanstack-start.js +1 -1
- package/dist/{user-nav-B37OEVQN.js → user-nav-OWTTAXZS.js} +2 -2
- package/dist/{user-nav-B37OEVQN.js.map → user-nav-OWTTAXZS.js.map} +1 -1
- package/package.json +4 -4
- package/dist/chat-page-WLKJ3QNZ.js +0 -4
- package/dist/chat-page-WLKJ3QNZ.js.map +0 -1
- package/dist/chunk-HGXYSP47.js +0 -8
- package/dist/chunk-HGXYSP47.js.map +0 -1
- package/dist/chunk-JIB4PRLH.js +0 -3
- package/dist/chunk-JIB4PRLH.js.map +0 -1
- package/dist/chunk-QCVQJN5O.js +0 -2
- package/dist/chunk-QCVQJN5O.js.map +0 -1
- package/dist/chunk-QTFFVG7C.js +0 -2
- package/dist/chunk-QTFFVG7C.js.map +0 -1
- package/dist/chunk-SY67F62K.js +0 -3
- package/dist/chunk-SY67F62K.js.map +0 -1
- package/dist/pages-NKE7FV34.js +0 -5
- package/dist/pages-NKE7FV34.js.map +0 -1
- package/dist/plugin-pages-4HTADSK3.js +0 -2
- package/dist/record-links-FDWV4X5W.js +0 -2
- package/dist/root-YDHREGTF.js +0 -14
- package/dist/root-YDHREGTF.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/apps/ai/activity.ts","../src/apps/ai/notification-settings.ts"],"names":["EPOCH","getActivitySourcePath","item","getActivitySourceLabel","RESOLUTION_LABELS","getActivityStatusLabel","getActivityStatusTone","isActivityItemOpen","planActivityNotifications","mutedKinds","newItems","since","newest","latest","fresh","nextSince","DEFAULT_NOTIFICATION_PREFERENCES","userRequest","url","init","response","useNotificationPreferences","data","error","mutate","useSWR","userApiPaths","saveNotificationPreferences","preferences","isWebPushSupported","getDesktop","decodeApplicationServerKey","base64Url","base64","binary","bytes","index","ensurePushSubscription","publicKey","pushManager","applicationServerKey","subscription","sameKey","current","expected","byte"],"mappings":"6HAMA,IAAMA,CAAAA,CAAQ,0BAAA,CAYP,SAASC,CAAAA,CAAsBC,CAAAA,CAAmC,CACvE,OAAIA,CAAAA,CAAK,MAAA,CACA,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AY,CAAA,CAAI,MAAM,SAAA,CAAU,aAAA,CAAc,KAAA,CAChDC,CAAAA,CAAuBT,CAAAA,CAA2BO,CAAS,CAAA,CAC7DG,CAAAA,CAAe,MAAMF,CAAAA,CAAY,eAAA,EAAgB,CAGrD,OAAIE,CAAAA,EAAgB,CAACC,CAAAA,CAAQD,CAAAA,CAAa,QAAQ,oBAAA,CAAsBD,CAAoB,CAAA,GAC1F,MAAMC,CAAAA,CAAa,WAAA,EAAY,CAC/BA,CAAAA,CAAe,MAGjBA,CAAAA,GAAiB,MAAMF,CAAAA,CAAY,SAAA,CAAU,CAAE,oBAAA,CAAAC,CAAAA,CAAsB,eAAA,CAAiB,IAAK,CAAC,CAAA,CAE5F,MAAMvB,CAAAA,CAAYS,GAAAA,CAAa,IAAA,CAAM,CAAE,IAAA,CAAM,KAAK,SAAA,CAAUe,CAAAA,CAAa,MAAA,EAAQ,CAAA,CAAG,MAAA,CAAQ,MAAO,CAAC,EAE7F,IACT,CAEA,SAASC,CAAAA,CAAQC,CAAAA,CAA6BC,CAAAA,CAA+B,CAC3E,OAAI,CAACD,CAAAA,EAAWA,CAAAA,CAAQ,UAAA,GAAeC,CAAAA,CAAS,UAAA,CACvC,KAAA,CAGK,IAAI,UAAA,CAAWD,CAAO,CAAA,CAEvB,KAAA,CAAM,CAACE,CAAAA,CAAMT,CAAAA,GAAUS,CAAAA,GAASD,CAAAA,CAASR,CAAK,CAAC,CAC9D","file":"chunk-4LVMCUHR.js","sourcesContent":["import type { ActivityItem, ActivityItemKind, ActivityItemResolution } from './types';\n\n/** More new items than this in one poll are announced by a single summary notification. */\nconst MAX_SEPARATE_NOTIFICATIONS = 3;\n\n/** Watermark before the first item exists: every later unread item is new. */\nconst EPOCH = '1970-01-01T00:00:00.000Z';\n\nexport interface ActivityNotification {\n body: string;\n /** AI-app relative path opened on click, e.g. `activity/<id>`. */\n path: string;\n /** Same tag = same notification across tabs and repeated polls. */\n tag: string;\n title: string;\n}\n\n/** Path, relative to the AI app, of the chat or run an item came from. */\nexport function getActivitySourcePath(item: ActivityItem): string | null {\n if (item.chatId) {\n return `agent/chats/${item.chatId}`;\n }\n\n if (item.automationId && item.automationRunId) {\n return `automations/${item.automationId}/runs/${item.automationRunId}`;\n }\n\n return null;\n}\n\nexport function getActivitySourceLabel(item: ActivityItem): string | null {\n if (item.chatId) {\n return 'View chat';\n }\n\n return item.automationId && item.automationRunId ? 'View run' : null;\n}\n\nconst RESOLUTION_LABELS: { [key in ActivityItemResolution]: string } = {\n answered: 'Answered',\n approved: 'Approved',\n cancelled: 'Cancelled',\n dismissed: 'Dismissed',\n expired: 'Expired',\n rejected: 'Rejected',\n};\n\n/** Short status for a row: what happened to it, or that it still waits on the viewer. */\nexport function getActivityStatusLabel(item: ActivityItem): string | null {\n if (item.kind === 'automation_failure') {\n return 'Failed';\n }\n\n if (item.kind === 'automation_result') {\n return 'Result';\n }\n\n if (item.kind === 'monitor_event') {\n return 'Monitor';\n }\n\n if (item.resolution) {\n return RESOLUTION_LABELS[item.resolution];\n }\n\n if (!item.requiresAction || item.state === 'done' || item.state === 'dismissed') {\n return null;\n }\n\n return item.kind === 'question' ? 'Needs answer' : 'Needs approval';\n}\n\n/** How a row's status badge reads: waiting on the viewer, a failure, or neutral. */\nexport function getActivityStatusTone(item: ActivityItem): 'attention' | 'failure' | 'neutral' {\n if (item.kind === 'automation_failure') {\n return 'failure';\n }\n\n return isActivityItemOpen(item) ? 'attention' : 'neutral';\n}\n\n/** True while the item still waits on the viewer. */\nexport function isActivityItemOpen(item: ActivityItem): boolean {\n return item.requiresAction && item.resolvedAt === null && item.state !== 'dismissed' && item.state !== 'done';\n}\n\n/**\n * Turns one summary poll into desktop notifications and the next watermark.\n * The first poll (no watermark yet) only seeds it, so opening Studio never\n * replays notifications for items the user already had.\n */\nexport function planActivityNotifications({\n mutedKinds = [],\n newItems,\n since,\n}: {\n /** Kinds the viewer turned off for desktop notifications; they still move the watermark. */\n mutedKinds?: ActivityItemKind[];\n newItems: ActivityItem[];\n since: string | null;\n}): { notifications: ActivityNotification[]; since: string } {\n const newest = newItems.reduce<string | null>(\n (latest, item) => (latest === null || item.createdAt > latest ? item.createdAt : latest),\n null\n );\n\n if (since === null) {\n return { notifications: [], since: newest ?? EPOCH };\n }\n\n const fresh = newItems.filter((item) => item.createdAt > since && !mutedKinds.includes(item.kind));\n const nextSince = newest !== null && newest > since ? newest : since;\n\n if (fresh.length === 0) {\n return { notifications: [], since: nextSince };\n }\n\n if (fresh.length > MAX_SEPARATE_NOTIFICATIONS) {\n return {\n notifications: [\n {\n body: 'Open Activity in Flexkit Studio to review them.',\n path: 'activity',\n tag: `flexkit-activity-batch:${nextSince}`,\n title: `${fresh.length.toString()} new items in Activity`,\n },\n ],\n since: nextSince,\n };\n }\n\n return {\n notifications: fresh.map((item) => ({\n body: item.body ?? '',\n path: `activity/${encodeURIComponent(item.id)}`,\n tag: `flexkit-activity:${item.id}`,\n title: item.title,\n })),\n since: nextSince,\n };\n}\n","import useSWR, { type KeyedMutator } from 'swr';\nimport { userApiPaths } from '../../core/api-paths';\nimport { getDesktop } from '../../core/desktop';\nimport type { ActivityItemKind } from './types';\n\n/** A person's notification choices, shared by every project they open. */\nexport interface NotificationPreferences {\n /** Email an approval request left unread past the project's delay. */\n approvalEmail: boolean;\n /** Kinds that never raise a desktop notification. */\n desktopMutedKinds: ActivityItemKind[];\n}\n\nexport const DEFAULT_NOTIFICATION_PREFERENCES: NotificationPreferences = { approvalEmail: true, desktopMutedKinds: [] };\n\nasync function userRequest<T>(url: string, init?: RequestInit): Promise<T> {\n const response = await fetch(url, {\n credentials: 'same-origin',\n ...init,\n headers: { 'Content-Type': 'application/json', ...init?.headers },\n });\n\n if (!response.ok) {\n throw new Error(`Request failed with ${response.status.toString()}.`);\n }\n\n return (await response.json()) as T;\n}\n\nexport function useNotificationPreferences(): {\n /** False until the stored preferences arrived (or could not be loaded, which means the defaults). */\n isLoaded: boolean;\n mutate: KeyedMutator<{ preferences: NotificationPreferences }>;\n preferences: NotificationPreferences;\n} {\n const { data, error, mutate } = useSWR<{ preferences: NotificationPreferences }>(\n userApiPaths.notificationPreferences,\n (url: string) => userRequest<{ preferences: NotificationPreferences }>(url)\n );\n\n return {\n isLoaded: data !== undefined || error !== undefined,\n mutate,\n preferences: data?.preferences ?? DEFAULT_NOTIFICATION_PREFERENCES,\n };\n}\n\nexport function saveNotificationPreferences(preferences: NotificationPreferences): Promise<{ preferences: NotificationPreferences }> {\n return userRequest(userApiPaths.notificationPreferences, { body: JSON.stringify(preferences), method: 'PUT' });\n}\n\nexport function isWebPushSupported(): boolean {\n // The desktop app keeps polling while it runs in the background and notifies natively.\n return (\n typeof window !== 'undefined' &&\n getDesktop() === undefined &&\n typeof Notification !== 'undefined' &&\n 'serviceWorker' in navigator &&\n 'PushManager' in window\n );\n}\n\n/** The VAPID public key as the bytes `PushManager.subscribe` expects. */\nexport function decodeApplicationServerKey(base64Url: string): Uint8Array<ArrayBuffer> {\n const base64 = `${base64Url}${'='.repeat((4 - (base64Url.length % 4)) % 4)}`.replace(/-/g, '+').replace(/_/g, '/');\n const binary = atob(base64);\n const bytes = new Uint8Array(new ArrayBuffer(binary.length));\n\n for (let index = 0; index < binary.length; index += 1) {\n bytes[index] = binary.charCodeAt(index);\n }\n\n return bytes;\n}\n\n/**\n * Hosted Studio only: registers the service worker and saves this browser's\n * push subscription for the signed-in user, so Activity items arrive while no\n * Studio tab is open. Needs notification permission; never asks for it.\n * Safe to call on every load: an existing subscription is saved again.\n * Returns false when Web Push is unavailable here.\n */\nexport async function ensurePushSubscription(): Promise<boolean> {\n if (!isWebPushSupported() || Notification.permission !== 'granted') {\n return false;\n }\n\n const { publicKey } = await userRequest<{ publicKey: string | null }>(userApiPaths.push);\n\n if (!publicKey) {\n return false;\n }\n\n await navigator.serviceWorker.register('/sw.js', { scope: '/' });\n\n const { pushManager } = await navigator.serviceWorker.ready;\n const applicationServerKey = decodeApplicationServerKey(publicKey);\n let subscription = await pushManager.getSubscription();\n\n // A subscription made with an older key would never receive again.\n if (subscription && !sameKey(subscription.options.applicationServerKey, applicationServerKey)) {\n await subscription.unsubscribe();\n subscription = null;\n }\n\n subscription ??= await pushManager.subscribe({ applicationServerKey, userVisibleOnly: true });\n\n await userRequest(userApiPaths.push, { body: JSON.stringify(subscription.toJSON()), method: 'POST' });\n\n return true;\n}\n\nfunction sameKey(current: ArrayBuffer | null, expected: Uint8Array): boolean {\n if (!current || current.byteLength !== expected.byteLength) {\n return false;\n }\n\n const bytes = new Uint8Array(current);\n\n return bytes.every((byte, index) => byte === expected[index]);\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/apps/ai/activity.ts","../src/apps/ai/notification-settings.ts"],"names":["EPOCH","getActivitySourcePath","item","getActivitySourceLabel","RESOLUTION_LABELS","getActivityStatusLabel","getActivityStatusTone","isActivityItemOpen","planActivityNotifications","mutedKinds","newItems","since","newest","latest","fresh","nextSince","DEFAULT_NOTIFICATION_PREFERENCES","userRequest","url","init","response","useNotificationPreferences","data","error","mutate","useSWR","userApiPaths","saveNotificationPreferences","preferences","isWebPushSupported","getDesktop","decodeApplicationServerKey","base64Url","base64","binary","bytes","index","ensurePushSubscription","publicKey","pushManager","applicationServerKey","subscription","sameKey","current","expected","byte"],"mappings":"6HAMA,IAAMA,CAAAA,CAAQ,0BAAA,CAYP,SAASC,CAAAA,CAAsBC,CAAAA,CAAmC,CACvE,OAAIA,CAAAA,CAAK,MAAA,CACA,CAAA,YAAA,EAAeA,CAAAA,CAAK,MAAM,GAG/BA,CAAAA,CAAK,YAAA,EAAgBA,CAAAA,CAAK,eAAA,CACrB,CAAA,YAAA,EAAeA,CAAAA,CAAK,YAAY,CAAA,MAAA,EAASA,EAAK,eAAe,CAAA,CAAA,CAG/D,IACT,CAEO,SAASC,CAAAA,CAAuBD,CAAAA,CAAmC,CACxE,OAAIA,CAAAA,CAAK,MAAA,CACA,WAAA,CAGFA,CAAAA,CAAK,YAAA,EAAgBA,CAAAA,CAAK,eAAA,CA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AAiB,MAAMF,CAAAA,CAAY,SAAA,CAAU,CAAE,oBAAA,CAAAC,CAAAA,CAAsB,eAAA,CAAiB,IAAK,CAAC,CAAA,CAE5F,MAAMvB,CAAAA,CAAYS,GAAAA,CAAa,IAAA,CAAM,CAAE,IAAA,CAAM,KAAK,SAAA,CAAUe,CAAAA,CAAa,MAAA,EAAQ,CAAA,CAAG,MAAA,CAAQ,MAAO,CAAC,EAE7F,IACT,CAEA,SAASC,CAAAA,CAAQC,CAAAA,CAA6BC,CAAAA,CAA+B,CAC3E,OAAI,CAACD,CAAAA,EAAWA,CAAAA,CAAQ,UAAA,GAAeC,CAAAA,CAAS,UAAA,CACvC,KAAA,CAGK,IAAI,UAAA,CAAWD,CAAO,CAAA,CAEvB,KAAA,CAAM,CAACE,CAAAA,CAAMT,CAAAA,GAAUS,CAAAA,GAASD,CAAAA,CAASR,CAAK,CAAC,CAC9D","file":"chunk-KN7OJFEX.js","sourcesContent":["import type { ActivityItem, ActivityItemKind, ActivityItemResolution } from './types';\n\n/** More new items than this in one poll are announced by a single summary notification. */\nconst MAX_SEPARATE_NOTIFICATIONS = 3;\n\n/** Watermark before the first item exists: every later unread item is new. */\nconst EPOCH = '1970-01-01T00:00:00.000Z';\n\nexport interface ActivityNotification {\n body: string;\n /** AI-app relative path opened on click, e.g. `activity/<id>`. */\n path: string;\n /** Same tag = same notification across tabs and repeated polls. */\n tag: string;\n title: string;\n}\n\n/** Path, relative to the AI app, of the chat or run an item came from. */\nexport function getActivitySourcePath(item: ActivityItem): string | null {\n if (item.chatId) {\n return `agent/chats/${item.chatId}`;\n }\n\n if (item.automationId && item.automationRunId) {\n return `automations/${item.automationId}/runs/${item.automationRunId}`;\n }\n\n return null;\n}\n\nexport function getActivitySourceLabel(item: ActivityItem): string | null {\n if (item.chatId) {\n return 'View chat';\n }\n\n return item.automationId && item.automationRunId ? 'View run' : null;\n}\n\nconst RESOLUTION_LABELS: { [key in ActivityItemResolution]: string } = {\n answered: 'Answered',\n approved: 'Approved',\n cancelled: 'Cancelled',\n dismissed: 'Dismissed',\n expired: 'Expired',\n rejected: 'Rejected',\n};\n\n/** Short status for a row: what happened to it, or that it still waits on the viewer. */\nexport function getActivityStatusLabel(item: ActivityItem): string | null {\n if (item.kind === 'automation_failure') {\n return 'Failed';\n }\n\n if (item.kind === 'automation_result') {\n return 'Result';\n }\n\n if (item.kind === 'monitor_event') {\n return 'Monitor';\n }\n\n if (item.resolution) {\n return RESOLUTION_LABELS[item.resolution];\n }\n\n if (!item.requiresAction || item.state === 'done' || item.state === 'dismissed') {\n return null;\n }\n\n return item.kind === 'question' ? 'Needs answer' : 'Needs approval';\n}\n\n/** How a row's status badge reads: waiting on the viewer, a failure, or neutral. */\nexport function getActivityStatusTone(item: ActivityItem): 'attention' | 'failure' | 'neutral' {\n if (item.kind === 'automation_failure') {\n return 'failure';\n }\n\n return isActivityItemOpen(item) ? 'attention' : 'neutral';\n}\n\n/** True while the item still waits on the viewer. */\nexport function isActivityItemOpen(item: ActivityItem): boolean {\n return item.requiresAction && item.resolvedAt === null && item.state !== 'dismissed' && item.state !== 'done';\n}\n\n/**\n * Turns one summary poll into desktop notifications and the next watermark.\n * The first poll (no watermark yet) only seeds it, so opening Studio never\n * replays notifications for items the user already had.\n */\nexport function planActivityNotifications({\n mutedKinds = [],\n newItems,\n since,\n}: {\n /** Kinds the viewer turned off for desktop notifications; they still move the watermark. */\n mutedKinds?: ActivityItemKind[];\n newItems: ActivityItem[];\n since: string | null;\n}): { notifications: ActivityNotification[]; since: string } {\n const newest = newItems.reduce<string | null>(\n (latest, item) => (latest === null || item.createdAt > latest ? item.createdAt : latest),\n null\n );\n\n if (since === null) {\n return { notifications: [], since: newest ?? EPOCH };\n }\n\n const fresh = newItems.filter((item) => item.createdAt > since && !mutedKinds.includes(item.kind));\n const nextSince = newest !== null && newest > since ? newest : since;\n\n if (fresh.length === 0) {\n return { notifications: [], since: nextSince };\n }\n\n if (fresh.length > MAX_SEPARATE_NOTIFICATIONS) {\n return {\n notifications: [\n {\n body: 'Open Activity in Flexkit Studio to review them.',\n path: 'activity',\n tag: `flexkit-activity-batch:${nextSince}`,\n title: `${fresh.length.toString()} new items in Activity`,\n },\n ],\n since: nextSince,\n };\n }\n\n return {\n notifications: fresh.map((item) => ({\n body: item.body ?? '',\n path: `activity/${encodeURIComponent(item.id)}`,\n tag: `flexkit-activity:${item.id}`,\n title: item.title,\n })),\n since: nextSince,\n };\n}\n","import useSWR, { type KeyedMutator } from 'swr';\nimport { userApiPaths } from '../../core/api-paths';\nimport { getDesktop } from '../../core/desktop';\nimport type { ActivityItemKind } from './types';\n\n/** A person's notification choices, shared by every project they open. */\nexport interface NotificationPreferences {\n /** Email an approval request left unread past the project's delay. */\n approvalEmail: boolean;\n /** Kinds that never raise a desktop notification. */\n desktopMutedKinds: ActivityItemKind[];\n}\n\nexport const DEFAULT_NOTIFICATION_PREFERENCES: NotificationPreferences = { approvalEmail: true, desktopMutedKinds: [] };\n\nasync function userRequest<T>(url: string, init?: RequestInit): Promise<T> {\n const response = await fetch(url, {\n credentials: 'same-origin',\n ...init,\n headers: { 'Content-Type': 'application/json', ...init?.headers },\n });\n\n if (!response.ok) {\n throw new Error(`Request failed with ${response.status.toString()}.`);\n }\n\n return (await response.json()) as T;\n}\n\nexport function useNotificationPreferences(): {\n /** False until the stored preferences arrived (or could not be loaded, which means the defaults). */\n isLoaded: boolean;\n mutate: KeyedMutator<{ preferences: NotificationPreferences }>;\n preferences: NotificationPreferences;\n} {\n const { data, error, mutate } = useSWR<{ preferences: NotificationPreferences }>(\n userApiPaths.notificationPreferences,\n (url: string) => userRequest<{ preferences: NotificationPreferences }>(url)\n );\n\n return {\n isLoaded: data !== undefined || error !== undefined,\n mutate,\n preferences: data?.preferences ?? DEFAULT_NOTIFICATION_PREFERENCES,\n };\n}\n\nexport function saveNotificationPreferences(preferences: NotificationPreferences): Promise<{ preferences: NotificationPreferences }> {\n return userRequest(userApiPaths.notificationPreferences, { body: JSON.stringify(preferences), method: 'PUT' });\n}\n\nexport function isWebPushSupported(): boolean {\n // The desktop app keeps polling while it runs in the background and notifies natively.\n return (\n typeof window !== 'undefined' &&\n getDesktop() === undefined &&\n typeof Notification !== 'undefined' &&\n 'serviceWorker' in navigator &&\n 'PushManager' in window\n );\n}\n\n/** The VAPID public key as the bytes `PushManager.subscribe` expects. */\nexport function decodeApplicationServerKey(base64Url: string): Uint8Array<ArrayBuffer> {\n const base64 = `${base64Url}${'='.repeat((4 - (base64Url.length % 4)) % 4)}`.replace(/-/g, '+').replace(/_/g, '/');\n const binary = atob(base64);\n const bytes = new Uint8Array(new ArrayBuffer(binary.length));\n\n for (let index = 0; index < binary.length; index += 1) {\n bytes[index] = binary.charCodeAt(index);\n }\n\n return bytes;\n}\n\n/**\n * Hosted Studio only: registers the service worker and saves this browser's\n * push subscription for the signed-in user, so Activity items arrive while no\n * Studio tab is open. Needs notification permission; never asks for it.\n * Safe to call on every load: an existing subscription is saved again.\n * Returns false when Web Push is unavailable here.\n */\nexport async function ensurePushSubscription(): Promise<boolean> {\n if (!isWebPushSupported() || Notification.permission !== 'granted') {\n return false;\n }\n\n const { publicKey } = await userRequest<{ publicKey: string | null }>(userApiPaths.push);\n\n if (!publicKey) {\n return false;\n }\n\n await navigator.serviceWorker.register('/sw.js', { scope: '/' });\n\n const { pushManager } = await navigator.serviceWorker.ready;\n const applicationServerKey = decodeApplicationServerKey(publicKey);\n let subscription = await pushManager.getSubscription();\n\n // A subscription made with an older key would never receive again.\n if (subscription && !sameKey(subscription.options.applicationServerKey, applicationServerKey)) {\n await subscription.unsubscribe();\n subscription = null;\n }\n\n subscription ??= await pushManager.subscribe({ applicationServerKey, userVisibleOnly: true });\n\n await userRequest(userApiPaths.push, { body: JSON.stringify(subscription.toJSON()), method: 'POST' });\n\n return true;\n}\n\nfunction sameKey(current: ArrayBuffer | null, expected: Uint8Array): boolean {\n if (!current || current.byteLength !== expected.byteLength) {\n return false;\n }\n\n const bytes = new Uint8Array(current);\n\n return bytes.every((byte, index) => byte === expected[index]);\n}\n"]}
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import'./index.css';import {a}from'./chunk-HKN6BX5U.js';import {c}from'./chunk-WPCPL2TQ.js';import {b,c as c$1}from'./chunk-5CVDMZUI.js';import {useState,useEffect}from'react';var d="0.2.24",L={current:d,latest:d,isCurrent:true};function le(){let e=b(),[t,r]=useState(null);return useEffect(()=>{if(e)return e.onUpdateDownloaded(o=>{r(o.version);})},[e]),e?t===null?{current:e.version,latest:e.version,isCurrent:true}:{current:e.version,latest:t,isCurrent:false,upgrade:()=>e.installUpdate()}:L}var U="flexkit:telemetry",V="flexkit:error-reporting",B=/^(localhost|127\.0\.0\.1|\[::1\]|0\.0\.0\.0)$|\.(localhost|test|local)$/i;function M(e){return e.override==="on"?true:e.override==="off"||!e.hosted||e.domain!=="flexkit.io"||e.version==="0.0.0"?false:e.isDesktop||!B.test(e.hostname)}function Y(){try{let e=a();return e?.getItem(U)??e?.getItem(V)??null}catch{return null}}function k({hosted:e}){return typeof window>"u"?false:M({hosted:e,isDesktop:!!b(),domain:c$1,hostname:window.location.hostname,version:d,override:Y()})}async function v(e,t,{keepalive:r=false}={}){return (await fetch(e,{body:t,credentials:"same-origin",headers:{"Content-Type":"application/json"},keepalive:r,method:"POST"})).status}var f={componentStack:4e3,message:2e3,name:200,path:500,stack:8e3,userAgent:500},$=10,G=6e4,K=50,z=5e3,R=/^[a-z0-9]{1,64}$/;function g(e,t){return e.length>t?e.slice(0,t):e}function J(e){let t=e;try{/^[a-z][a-z0-9+.-]*:/i.test(e)&&(t=new URL(e).pathname);}catch{}return g(t.split(/[?#]/)[0]??"",f.path)}function H(e){if(e instanceof Error)return {name:e.name||"Error",message:typeof e.message=="string"?e.message:"",stack:typeof e.stack=="string"?e.stack:void 0};if(typeof e=="string")return {name:"Error",message:e};if(e==null)return {name:"Error",message:`Non-Error thrown: ${String(e)}`};if(typeof e=="object"){let t=e.constructor?.name;return {name:"Error",message:`Non-Error thrown: ${typeof t=="string"&&t?t:"object"}`}}return {name:"Error",message:`Non-Error thrown: ${typeof e}`}}var X=[/ResizeObserver loop (limit exceeded|completed with undelivered notifications)/i,/^Script error\.?$/i,/The (operation|user) (was )?aborted/i,/signal is aborted without reason/i],A=/\b(chrome|moz|safari(-web)?|ms-browser)-extension:\/\//i,F=/[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}/gi;function Z(e){return e.replace(F,"<email>")}function q(e,t){return e.name==="AbortError"||X.some(r=>r.test(e.message))||t&&A.test(t)?true:!!(e.stack&&A.test(e.stack))}function W(e,t){let r=H(e);if(q(r,t.sourceUrl))return null;let o={source:t.source,name:g(r.name,f.name),message:g(Z(r.message),f.message),occurredAt:(t.now??new Date).toISOString()};return r.stack&&(o.stack=g(r.stack,f.stack)),t.componentStack&&(o.componentStack=g(t.componentStack,f.componentStack)),t.path&&(o.path=J(t.path)),t.projectId&&R.test(t.projectId)&&(o.projectId=t.projectId),o}function Q(e){return `${e.name}
|
|
2
|
+
${e.message}
|
|
3
|
+
${e.stack??""}`}var ee=new TextEncoder;function P(e){return ee.encode(e).length}function te(e,t,r=G){let o=P(JSON.stringify({app:e,errors:[]})),s=[];for(let i of t.slice(0,$)){let n=P(JSON.stringify(i))+(s.length?1:0);if(o+n>r)break;o+=n,s.push(i);}return s.length===0?null:{body:JSON.stringify({app:e,errors:s}),count:s.length}}function re({app:e,send:t,getPath:r,now:o=()=>new Date,setTimer:s=(n,u)=>setTimeout(n,u),clearTimer:i=n=>clearTimeout(n)}){let n=[],u=new Set,_=0,y=null,a=null,E=false;function T(){a===null&&n.length>0&&!E&&(a=s(()=>{a=null,x();},z));}function D(l){let S=te(e,n);return S?(n.splice(0,S.count),t(S.body,{unloading:l}).then(p=>{(p===401||p===403||p===429)&&(E=true,n.length=0);}).catch(()=>{}),n.length>0):(n.shift(),n.length>0)}function x({unloading:l=false}={}){try{if(E)return;a!==null&&l&&(i(a),a=null),n.length>0&&D(l),T();}catch{}}return {report(l,S){try{if(E||_>=K)return;let p=W(l,{...S,now:o(),path:r?.(),projectId:y});if(!p)return;let b=Q(p);if(u.has(b))return;u.add(b),_+=1,n.push(p),T();}catch{}},setProjectId(l){y=l;},flush:x,pending:()=>n,dispose(){a!==null&&(i(a),a=null),E=true,n.length=0;}}}var ne=async(e,{unloading:t})=>{let r=c.clientErrors;if(t&&!b()&&typeof navigator<"u"&&typeof navigator.sendBeacon=="function")try{if(navigator.sendBeacon(r,new Blob([e],{type:"text/plain"})))return null}catch{}return v(r,e,{keepalive:t})},m=null;function we(e,{source:t="manual",componentStack:r}={}){m?.report(e,{source:t,componentStack:r});}function Re(e){m?.setProjectId(e);}function _e({hosted:e}){if(typeof window>"u"||m)return ()=>{};if(!k({hosted:e}))return ()=>{};let t=b(),r=re({app:{platform:t?"desktop":"web",version:d,userAgent:g(navigator.userAgent,f.userAgent)},send:ne,getPath:()=>window.location.pathname});function o(n){r.report(n.error??n.message,{source:"window",sourceUrl:n.filename});}function s(n){r.report(n.reason,{source:"unhandledrejection"});}function i(){r.flush({unloading:true});}return window.addEventListener("error",o),window.addEventListener("unhandledrejection",s),window.addEventListener("pagehide",i),m=r,()=>{window.removeEventListener("error",o),window.removeEventListener("unhandledrejection",s),window.removeEventListener("pagehide",i),r.flush({unloading:true}),r.dispose(),m===r&&(m=null);}}function oe(e){return e.event==="graph_opened"?`graph_opened:${e.projectId}`:e.event}function ie(e){let t=new Set,r=new Set;return {track(o,{onDelivered:s}={}){let i=oe(o);if(t.has(i)||r.has(i))return;t.add(i);let n=u=>{t.delete(i),u!==null&&u>=200&&u<300&&(r.add(i),s?.());};try{e(JSON.stringify(o)).then(n,()=>n(null));}catch{n(null);}}}}var w=null;function Oe(e){e.event==="graph_opened"&&!R.test(e.projectId)||w?.track(e);}var C="flexkit:desktop-launch-recorded";function se(e){try{return sessionStorage.getItem(e)==="1"}catch{return false}}function ae(e){try{sessionStorage.setItem(e,"1");}catch{}}function Ae({hosted:e}){if(!k({hosted:e}))return ()=>{};let t=ie(o=>v(c.productEvents,o,{keepalive:true})),r=b();return w=t,r&&!se(C)&&t.track({appVersion:r.version,event:"desktop_app_opened",os:r.platform},{onDelivered:()=>ae(C)}),()=>{w===t&&(w=null);}}export{le as a,we as b,Re as c,_e as d,Oe as e,Ae as f};//# sourceMappingURL=chunk-L3GBAK54.js.map
|
|
4
|
+
//# sourceMappingURL=chunk-L3GBAK54.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/core/use-studio-version.ts","../src/core/telemetry.ts","../src/core/error/error-reporter.ts","../src/core/analytics/product-events.ts"],"names":["STUDIO_VERSION","WEB_VERSION","useStudioVersion","desktop","getDesktop","downloaded","setDownloaded","useState","useEffect","update","TELEMETRY_STORAGE_KEY","LEGACY_TELEMETRY_STORAGE_KEY","LOCAL_HOSTNAME","isTelemetryEnabled","env","readOverride","storage","getLocalStorage","isStudioTelemetryEnabled","hosted","flexkitDomain","postToUserApi","path","body","keepalive","LIMITS","MAX_ERRORS_PER_REPORT","MAX_REPORT_BYTES","MAX_ERRORS_PER_SESSION","FLUSH_INTERVAL_MS","PROJECT_ID_PATTERN","truncate","value","max","toReportPath","pathOrUrl","describeError","error","constructorName","NOISE_MESSAGES","EXTENSION_URL","EMAIL_ADDRESS","maskMessage","message","isNoiseError","details","sourceUrl","pattern","buildClientError","options","entry","errorKey","encoder","byteLength","buildReportBody","app","queue","maxBytes","size","errors","errorSize","createErrorReporter","send","getPath","now","setTimer","callback","ms","clearTimer","timer","seen","accepted","projectId","stopped","schedule","flush","sendNext","unloading","next","status","key","id","sendReportToBff","url","userApiPaths","installed","reportStudioError","source","componentStack","setErrorReportingProjectId","installErrorReporter","reporter","onError","event","onUnhandledRejection","onPageHide","productEventKey","studioEvent","createProductEventTracker","pending","delivered","onDelivered","settle","tracker","trackStudioEvent","DESKTOP_LAUNCH_STORAGE_KEY","readSessionFlag","writeSessionFlag","installProductEvents","current"],"mappings":"gLAeO,IAAMA,CAAAA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esktop } from './desktop';\n\nexport interface StudioVersion {\n current: string;\n latest: string;\n isCurrent: boolean;\n /** Applies the newer version (the desktop app restarts into it); undefined when there is nothing to apply. */\n upgrade?: () => void;\n}\n\n// `@flexkit/studio`'s own version, inlined at build time; a build without the\n// define (tests, tooling) shows a placeholder.\nexport const STUDIO_VERSION = typeof __STUDIO_VERSION__ === 'string' ? __STUDIO_VERSION__ : '0.0.0';\nconst WEB_VERSION: StudioVersion = { current: STUDIO_VERSION, latest: STUDIO_VERSION, isCurrent: true };\n\n/**\n * The Studio version shown in the app bar. The web Studio is always current\n * (the hosted Studio deploys with the packages); the desktop app reports its\n * own version and the update it has downloaded, if any.\n */\nexport function useStudioVersion(): StudioVersion {\n const desktop = getDesktop();\n const [downloaded, setDownloaded] = useState<string | null>(null);\n\n useEffect(() => {\n if (!desktop) {\n return;\n }\n\n return desktop.onUpdateDownloaded((update) => {\n setDownloaded(update.version);\n });\n }, [desktop]);\n\n if (!desktop) {\n return WEB_VERSION;\n }\n\n if (downloaded === null) {\n return { current: desktop.version, latest: desktop.version, isCurrent: true };\n }\n\n return { current: desktop.version, latest: downloaded, isCurrent: false, upgrade: () => desktop.installUpdate() };\n}\n","import { getDesktop } from './desktop';\nimport { flexkitDomain } from './domains';\nimport { getLocalStorage } from './local-storage';\nimport { STUDIO_VERSION } from './use-studio-version';\n\n/**\n * The on/off decision and the transport shared by the Studio's error reports\n * (core/error/error-reporter.ts) and product events\n * (core/analytics/product-events.ts).\n */\n\n/** Turns error reports and product events on (`on`) or off (`off`) in this browser, whatever the environment. */\nexport const TELEMETRY_STORAGE_KEY = 'flexkit:telemetry';\n/** The key error reporting shipped with; still honoured. */\nexport const LEGACY_TELEMETRY_STORAGE_KEY = 'flexkit:error-reporting';\n\nexport interface TelemetryEnvironment {\n /** The Studio lists the signed-in user's projects (hosted Studio, desktop app). */\n hosted: boolean;\n isDesktop: boolean;\n domain: string;\n hostname: string;\n version: string;\n /** The local storage setting in this browser, if any. */\n override: string | null;\n}\n\nconst LOCAL_HOSTNAME = /^(localhost|127\\.0\\.0\\.1|\\[::1\\]|0\\.0\\.0\\.0)$|\\.(localhost|test|local)$/i;\n\n/**\n * On for the hosted Studio and the desktop app against the production\n * backend, and off in development: a local backend (`flexkit.test`), a local\n * host, or a build without a version. The local storage setting forces it\n * `on` or `off`.\n */\nexport function isTelemetryEnabled(env: TelemetryEnvironment): boolean {\n if (env.override === 'on') {\n return true;\n }\n\n if (env.override === 'off') {\n return false;\n }\n\n if (!env.hosted || env.domain !== 'flexkit.io' || env.version === '0.0.0') {\n return false;\n }\n\n return env.isDesktop || !LOCAL_HOSTNAME.test(env.hostname);\n}\n\nfunction readOverride(): string | null {\n try {\n const storage = getLocalStorage();\n\n return storage?.getItem(TELEMETRY_STORAGE_KEY) ?? storage?.getItem(LEGACY_TELEMETRY_STORAGE_KEY) ?? null;\n } catch {\n return null;\n }\n}\n\n/** Whether this Studio sends error reports and product events to Flexkit. */\nexport function isStudioTelemetryEnabled({ hosted }: { hosted: boolean }): boolean {\n if (typeof window === 'undefined') {\n return false;\n }\n\n return isTelemetryEnabled({\n hosted,\n isDesktop: Boolean(getDesktop()),\n domain: flexkitDomain,\n hostname: window.location.hostname,\n version: STUDIO_VERSION,\n override: readOverride(),\n });\n}\n\n/**\n * POSTs JSON to a user-level backend route through the Studio's server proxy,\n * which adds the session. `keepalive` lets the request outlive the page.\n * Returns the response status.\n */\nexport async function postToUserApi(path: string, body: string, { keepalive = false } = {}): Promise<number> {\n const response = await fetch(path, {\n body,\n credentials: 'same-origin',\n headers: { 'Content-Type': 'application/json' },\n keepalive,\n method: 'POST',\n });\n\n return response.status;\n}\n","import { userApiPaths } from '../api-paths';\nimport { getDesktop } from '../desktop';\nimport { STUDIO_VERSION } from '../use-studio-version';\nimport { isStudioTelemetryEnabled, postToUserApi } from '../telemetry';\n\n/**\n * Reports unexpected Studio errors (uncaught errors, unhandled rejections and\n * errors caught by the error boundaries) to Flexkit through the Studio's own\n * BFF (`/api/flexkit/-/client-errors`), which forwards the session so the\n * report is attributed to the signed-in user.\n *\n * Reports carry the error, the Studio path (no query string or hash) and the\n * current project id; never request bodies, form values or record data.\n */\n\nexport type ClientErrorSource = 'window' | 'unhandledrejection' | 'react' | 'manual';\n\nexport interface ClientError {\n source: ClientErrorSource;\n name: string;\n message: string;\n stack?: string;\n componentStack?: string;\n path?: string;\n projectId?: string;\n occurredAt: string;\n}\n\nexport interface ClientErrorApp {\n platform: 'web' | 'desktop';\n version: string;\n userAgent?: string;\n}\n\nexport interface ClientErrorReport {\n app: ClientErrorApp;\n errors: ClientError[];\n}\n\n/** Field limits of the backend schema. */\nconst LIMITS = {\n componentStack: 4_000,\n message: 2_000,\n name: 200,\n path: 500,\n stack: 8_000,\n userAgent: 500,\n} as const;\n\n/** The backend accepts 1 to 10 errors per report. */\nexport const MAX_ERRORS_PER_REPORT = 10;\n/** The backend refuses bodies over 64 KB; `keepalive` requests share a 64 KB budget too. */\nexport const MAX_REPORT_BYTES = 60_000;\n/** Reports kept per page session; anything after that is dropped. */\nexport const MAX_ERRORS_PER_SESSION = 50;\n/** At most one report is sent per interval; errors in between are batched. */\nexport const FLUSH_INTERVAL_MS = 5_000;\n\n/** Kept for callers and tests that name the gate after error reporting. */\nexport {\n isTelemetryEnabled as isErrorReportingEnabled,\n LEGACY_TELEMETRY_STORAGE_KEY as ERROR_REPORTING_STORAGE_KEY,\n type TelemetryEnvironment as ErrorReportingEnvironment,\n} from '../telemetry';\n\nexport const PROJECT_ID_PATTERN = /^[a-z0-9]{1,64}$/;\n\nfunction truncate(value: string, max: number): string {\n return value.length > max ? value.slice(0, max) : value;\n}\n\n/** The pathname of a path or URL, without query string or hash. */\nexport function toReportPath(pathOrUrl: string): string {\n let path = pathOrUrl;\n\n try {\n if (/^[a-z][a-z0-9+.-]*:/i.test(pathOrUrl)) {\n path = new URL(pathOrUrl).pathname;\n }\n } catch {\n // Not a URL; strip by hand below.\n }\n\n return truncate(path.split(/[?#]/)[0] ?? '', LIMITS.path);\n}\n\nexport interface ErrorDetails {\n name: string;\n message: string;\n stack?: string;\n}\n\n/**\n * Name, message and stack of anything thrown. A non-Error value (a rejected\n * promise with a plain object) is described by its type only, so record data\n * someone rejected with never leaves the browser.\n */\nexport function describeError(error: unknown): ErrorDetails {\n if (error instanceof Error) {\n return {\n name: error.name || 'Error',\n message: typeof error.message === 'string' ? error.message : '',\n stack: typeof error.stack === 'string' ? error.stack : undefined,\n };\n }\n\n if (typeof error === 'string') {\n return { name: 'Error', message: error };\n }\n\n if (error === null || error === undefined) {\n return { name: 'Error', message: `Non-Error thrown: ${String(error)}` };\n }\n\n if (typeof error === 'object') {\n const constructorName = (error as { constructor?: { name?: unknown } }).constructor?.name;\n\n return {\n name: 'Error',\n message: `Non-Error thrown: ${typeof constructorName === 'string' && constructorName ? constructorName : 'object'}`,\n };\n }\n\n return { name: 'Error', message: `Non-Error thrown: ${typeof error}` };\n}\n\nconst NOISE_MESSAGES = [\n /ResizeObserver loop (limit exceeded|completed with undelivered notifications)/i,\n // Cross-origin script errors carry nothing to act on.\n /^Script error\\.?$/i,\n /The (operation|user) (was )?aborted/i,\n /signal is aborted without reason/i,\n];\n\nconst EXTENSION_URL = /\\b(chrome|moz|safari(-web)?|ms-browser)-extension:\\/\\//i;\n\nconst EMAIL_ADDRESS = /[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,}/gi;\n\n/** Masks email addresses an error message may quote from a record or form. */\nexport function maskMessage(message: string): string {\n return message.replace(EMAIL_ADDRESS, '<email>');\n}\n\n/** Errors that are not Studio bugs: browser quirks, aborted requests, browser extensions. */\nexport function isNoiseError(details: ErrorDetails, sourceUrl?: string): boolean {\n if (details.name === 'AbortError') {\n return true;\n }\n\n if (NOISE_MESSAGES.some((pattern) => pattern.test(details.message))) {\n return true;\n }\n\n if (sourceUrl && EXTENSION_URL.test(sourceUrl)) {\n return true;\n }\n\n return Boolean(details.stack && EXTENSION_URL.test(details.stack));\n}\n\nexport interface BuildClientErrorOptions {\n source: ClientErrorSource;\n componentStack?: string;\n path?: string;\n projectId?: string | null;\n /** The script the error came from (`ErrorEvent.filename`), checked for browser extensions. */\n sourceUrl?: string;\n now?: Date;\n}\n\n/** The report entry for an error, or null when it is noise. */\nexport function buildClientError(error: unknown, options: BuildClientErrorOptions): ClientError | null {\n const details = describeError(error);\n\n if (isNoiseError(details, options.sourceUrl)) {\n return null;\n }\n\n const entry: ClientError = {\n source: options.source,\n name: truncate(details.name, LIMITS.name),\n message: truncate(maskMessage(details.message), LIMITS.message),\n occurredAt: (options.now ?? new Date()).toISOString(),\n };\n\n if (details.stack) {\n entry.stack = truncate(details.stack, LIMITS.stack);\n }\n\n if (options.componentStack) {\n entry.componentStack = truncate(options.componentStack, LIMITS.componentStack);\n }\n\n if (options.path) {\n entry.path = toReportPath(options.path);\n }\n\n if (options.projectId && PROJECT_ID_PATTERN.test(options.projectId)) {\n entry.projectId = options.projectId;\n }\n\n return entry;\n}\n\n/** Identity of an error within a page session: the same message and stack are reported once. */\nexport function errorKey(error: Pick<ClientError, 'message' | 'name' | 'stack'>): string {\n return `${error.name}\\n${error.message}\\n${error.stack ?? ''}`;\n}\n\nconst encoder = new TextEncoder();\n\nfunction byteLength(value: string): number {\n return encoder.encode(value).length;\n}\n\n/**\n * Takes the errors that fit one report (at most 10 and `maxBytes` of JSON)\n * off the front of the queue. Returns the request body and how many errors it holds.\n */\nexport function buildReportBody(\n app: ClientErrorApp,\n queue: readonly ClientError[],\n maxBytes = MAX_REPORT_BYTES\n): { body: string; count: number } | null {\n // The envelope plus each error once, joined by commas.\n let size = byteLength(JSON.stringify({ app, errors: [] } satisfies ClientErrorReport));\n const errors: ClientError[] = [];\n\n for (const error of queue.slice(0, MAX_ERRORS_PER_REPORT)) {\n const errorSize = byteLength(JSON.stringify(error)) + (errors.length ? 1 : 0);\n\n if (size + errorSize > maxBytes) {\n break;\n }\n\n size += errorSize;\n errors.push(error);\n }\n\n if (errors.length === 0) {\n return null;\n }\n\n return { body: JSON.stringify({ app, errors } satisfies ClientErrorReport), count: errors.length };\n}\n\nexport type SendReport = (body: string, options: { unloading: boolean }) => Promise<number | null>;\n\nexport interface ErrorReporterOptions {\n app: ClientErrorApp;\n send: SendReport;\n /** The current Studio path; only its pathname is sent. */\n getPath?: () => string | undefined;\n now?: () => Date;\n setTimer?: (callback: () => void, ms: number) => unknown;\n clearTimer?: (timer: unknown) => void;\n}\n\nexport interface ErrorReporter {\n report: (error: unknown, options: Omit<BuildClientErrorOptions, 'path' | 'projectId' | 'now'>) => void;\n setProjectId: (projectId: string | null) => void;\n /** Sends the next report now; `unloading` uses a beacon or keepalive request that outlives the page. */\n flush: (options?: { unloading?: boolean }) => void;\n /** Errors waiting to be sent (tests). */\n pending: () => readonly ClientError[];\n dispose: () => void;\n}\n\n/** The queue, dedupe, cap and batching; the transport and the clock are injected. */\nexport function createErrorReporter({\n app,\n send,\n getPath,\n now = () => new Date(),\n setTimer = (callback, ms) => setTimeout(callback, ms),\n clearTimer = (timer) => clearTimeout(timer as ReturnType<typeof setTimeout>),\n}: ErrorReporterOptions): ErrorReporter {\n const queue: ClientError[] = [];\n const seen = new Set<string>();\n let accepted = 0;\n let projectId: string | null = null;\n let timer: unknown = null;\n let stopped = false;\n\n function schedule(): void {\n if (timer === null && queue.length > 0 && !stopped) {\n timer = setTimer(() => {\n timer = null;\n flush();\n }, FLUSH_INTERVAL_MS);\n }\n }\n\n function sendNext(unloading: boolean): boolean {\n const next = buildReportBody(app, queue);\n\n if (!next) {\n // An error that cannot fit a report on its own; drop it.\n queue.shift();\n\n return queue.length > 0;\n }\n\n queue.splice(0, next.count);\n send(next.body, { unloading })\n .then((status) => {\n // Rate limited or not allowed: stop for this page session rather than retry.\n if (status === 401 || status === 403 || status === 429) {\n stopped = true;\n queue.length = 0;\n }\n })\n .catch(() => {\n // Never report the reporter's own failures.\n });\n\n return queue.length > 0;\n }\n\n function flush({ unloading = false }: { unloading?: boolean } = {}): void {\n try {\n if (stopped) {\n return;\n }\n\n if (timer !== null && unloading) {\n clearTimer(timer);\n timer = null;\n }\n\n // One report per flush, also when the page goes away: beacons and\n // keepalive requests share a 64 KB budget, so a second would be refused.\n if (queue.length > 0) {\n sendNext(unloading);\n }\n\n schedule();\n } catch {\n // Error reporting must never break the Studio.\n }\n }\n\n return {\n report(error, options) {\n try {\n if (stopped || accepted >= MAX_ERRORS_PER_SESSION) {\n return;\n }\n\n const entry = buildClientError(error, {\n ...options,\n now: now(),\n path: getPath?.(),\n projectId,\n });\n\n if (!entry) {\n return;\n }\n\n const key = errorKey(entry);\n\n if (seen.has(key)) {\n return;\n }\n\n seen.add(key);\n accepted += 1;\n queue.push(entry);\n schedule();\n } catch {\n // Error reporting must never break the Studio.\n }\n },\n setProjectId(id) {\n projectId = id;\n },\n flush,\n pending: () => queue,\n dispose() {\n if (timer !== null) {\n clearTimer(timer);\n timer = null;\n }\n\n stopped = true;\n queue.length = 0;\n },\n };\n}\n\n/** Sends a report through the BFF; a beacon when the page is going away on the web. */\nexport const sendReportToBff: SendReport = async (body, { unloading }) => {\n const url = userApiPaths.clientErrors;\n\n // A beacon outlives the page. The BFF reads its JSON body like a fetch's\n // and the browser sends the session cookie with it (same origin). The\n // desktop app's BFF only answers script requests, so it uses `keepalive`.\n if (unloading && !getDesktop() && typeof navigator !== 'undefined' && typeof navigator.sendBeacon === 'function') {\n try {\n // text/plain is CORS-safelisted, so no browser refuses the beacon; the body is still JSON.\n if (navigator.sendBeacon(url, new Blob([body], { type: 'text/plain' }))) {\n return null;\n }\n } catch {\n // Fall back to a keepalive fetch.\n }\n }\n\n return postToUserApi(url, body, { keepalive: unloading });\n};\n\nlet installed: ErrorReporter | null = null;\n\n/** Reports an error caught by the Studio (an error boundary, for example). Does nothing when reporting is off. */\nexport function reportStudioError(\n error: unknown,\n { source = 'manual', componentStack }: { source?: ClientErrorSource; componentStack?: string } = {}\n): void {\n installed?.report(error, { source, componentStack });\n}\n\n/** The project the Studio shows, added to reports; null outside a project. */\nexport function setErrorReportingProjectId(projectId: string | null): void {\n installed?.setProjectId(projectId);\n}\n\n/**\n * Starts reporting uncaught errors and unhandled rejections when reporting is\n * enabled for this environment. Returns the function that stops it.\n */\nexport function installErrorReporter({ hosted }: { hosted: boolean }): () => void {\n if (typeof window === 'undefined' || installed) {\n return () => undefined;\n }\n\n if (!isStudioTelemetryEnabled({ hosted })) {\n return () => undefined;\n }\n\n const desktop = getDesktop();\n\n const reporter = createErrorReporter({\n app: {\n platform: desktop ? 'desktop' : 'web',\n version: STUDIO_VERSION,\n userAgent: truncate(navigator.userAgent, LIMITS.userAgent),\n },\n send: sendReportToBff,\n getPath: () => window.location.pathname,\n });\n\n function onError(event: ErrorEvent): void {\n reporter.report(event.error ?? event.message, { source: 'window', sourceUrl: event.filename });\n }\n\n function onUnhandledRejection(event: PromiseRejectionEvent): void {\n reporter.report(event.reason, { source: 'unhandledrejection' });\n }\n\n function onPageHide(): void {\n reporter.flush({ unloading: true });\n }\n\n window.addEventListener('error', onError);\n window.addEventListener('unhandledrejection', onUnhandledRejection);\n window.addEventListener('pagehide', onPageHide);\n installed = reporter;\n\n return () => {\n window.removeEventListener('error', onError);\n window.removeEventListener('unhandledrejection', onUnhandledRejection);\n window.removeEventListener('pagehide', onPageHide);\n reporter.flush({ unloading: true });\n reporter.dispose();\n\n if (installed === reporter) {\n installed = null;\n }\n };\n}\n","import { userApiPaths } from '../api-paths';\nimport { getDesktop } from '../desktop';\nimport { PROJECT_ID_PATTERN } from '../error/error-reporter';\nimport { isStudioTelemetryEnabled, postToUserApi } from '../telemetry';\n\n/**\n * Product events only the Studio can see, sent to Flexkit through the\n * Studio's own server proxy (`/api/flexkit/-/product-events`) with the\n * session: the Graph app opened, the desktop app launched. They follow the\n * Studio's telemetry setting (see core/telemetry.ts) and carry ids, the\n * desktop app version and the OS only.\n */\nexport type StudioProductEvent =\n | { event: 'graph_opened'; projectId: string }\n | { event: 'desktop_app_opened'; appVersion: string; os: 'darwin' | 'linux' | 'win32' };\n\n/** Identity of an event within a page session; the backend also counts each once per day. */\nexport function productEventKey(studioEvent: StudioProductEvent): string {\n return studioEvent.event === 'graph_opened' ? `graph_opened:${studioEvent.projectId}` : studioEvent.event;\n}\n\n/** Sends the event body; resolves with the response status. */\nexport type SendProductEvent = (body: string) => Promise<number>;\n\nexport interface ProductEventTracker {\n track: (studioEvent: StudioProductEvent, options?: { onDelivered?: () => void }) => void;\n}\n\n/**\n * Sends each event once per page session through `send`. An event counts as\n * sent only once the backend accepted it, so one sent while offline or signed\n * out is sent again next time. Never throws.\n */\nexport function createProductEventTracker(send: SendProductEvent): ProductEventTracker {\n const pending = new Set<string>();\n const delivered = new Set<string>();\n\n return {\n track(studioEvent, { onDelivered } = {}) {\n const key = productEventKey(studioEvent);\n\n if (pending.has(key) || delivered.has(key)) {\n return;\n }\n\n pending.add(key);\n\n const settle = (status: number | null): void => {\n pending.delete(key);\n\n if (status !== null && status >= 200 && status < 300) {\n delivered.add(key);\n onDelivered?.();\n }\n };\n\n try {\n send(JSON.stringify(studioEvent)).then(settle, () => settle(null));\n } catch {\n settle(null);\n }\n },\n };\n}\n\nlet tracker: ProductEventTracker | null = null;\n\n/** Records an event when product events are on (see `installProductEvents`); otherwise does nothing. */\nexport function trackStudioEvent(studioEvent: StudioProductEvent): void {\n if (studioEvent.event === 'graph_opened' && !PROJECT_ID_PATTERN.test(studioEvent.projectId)) {\n return;\n }\n\n tracker?.track(studioEvent);\n}\n\n/** Session storage flag: this desktop app launch was recorded (page reloads keep it, a relaunch does not). */\nexport const DESKTOP_LAUNCH_STORAGE_KEY = 'flexkit:desktop-launch-recorded';\n\nfunction readSessionFlag(key: string): boolean {\n try {\n return sessionStorage.getItem(key) === '1';\n } catch {\n return false;\n }\n}\n\nfunction writeSessionFlag(key: string): void {\n try {\n sessionStorage.setItem(key, '1');\n } catch {\n // Without session storage the backend's once-per-day count still applies.\n }\n}\n\n/**\n * Turns product events on for this environment and records the desktop app\n * launch (once per launch, once the user is signed in). Returns the function\n * that turns them off again.\n */\nexport function installProductEvents({ hosted }: { hosted: boolean }): () => void {\n if (!isStudioTelemetryEnabled({ hosted })) {\n return () => undefined;\n }\n\n const current = createProductEventTracker((body) =>\n postToUserApi(userApiPaths.productEvents, body, { keepalive: true })\n );\n const desktop = getDesktop();\n\n tracker = current;\n\n if (desktop && !readSessionFlag(DESKTOP_LAUNCH_STORAGE_KEY)) {\n current.track(\n { appVersion: desktop.version, event: 'desktop_app_opened', os: desktop.platform },\n { onDelivered: () => writeSessionFlag(DESKTOP_LAUNCH_STORAGE_KEY) }\n );\n }\n\n return () => {\n if (tracker === current) {\n tracker = null;\n }\n };\n}\n"]}
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import'./index.css';import {e}from'./chunk-7KLXWCDS.js';import {b as b$1,c}from'./chunk-5CVDMZUI.js';import {put}from'@vercel/blob/client';function w(s,o){let l=o.trim();return l?s.trim()?/\s$/.test(s)||/^[.,!?;:]/.test(l)?`${s}${l}`:`${s} ${l}`:s.length===0?l:`${s}${l}`:s}async function C(s){if(typeof window>"u")throw new Error("Dictation is only available in the browser.");let o=window.AudioContext??window.webkitAudioContext;if(!o)throw new Error("This browser cannot decode recorded audio.");let l=await s.arrayBuffer(),u=new o;try{let n=await u.decodeAudioData(l.slice(0)),i=$(n),t=I(i,n.sampleRate,24e3),e=P(t),a=t.length/24e3;if(a<.25)throw new Error("No speech was captured. Try again.");if(a>60)throw new Error(`Dictation is limited to ${String(60)} seconds.`);return {durationSeconds:a,pcm:new Blob([e],{type:"audio/pcm"})}}finally{await u.close();}}function $(s){let{length:o,numberOfChannels:l}=s;if(l===1)return s.getChannelData(0).slice();let u=new Float32Array(o);for(let n=0;n<o;n+=1){let i=0;for(let t=0;t<l;t+=1)i+=s.getChannelData(t)[n]??0;u[n]=i/l;}return u}function I(s,o,l){if(o===l)return s;let u=o/l,n=Math.max(1,Math.round(s.length/u)),i=new Float32Array(n);for(let t=0;t<n;t+=1){let e=t*u,a=Math.floor(e),c=Math.min(a+1,s.length-1),r=e-a,g=s[a]??0,m=s[c]??0;i[t]=g+(m-g)*r;}return i}function P(s){let o=new ArrayBuffer(s.length*2),l=new DataView(o);for(let u=0;u<s.length;u+=1){let n=Math.max(-1,Math.min(1,s[u]??0));l.setInt16(u*2,n<0?n*32768:n*32767,true);}return o}async function b(s){if(!(typeof crypto>"u"||!crypto.subtle))try{let o=await crypto.subtle.digest("SHA-256",await s.arrayBuffer());return Array.from(new Uint8Array(o),l=>l.toString(16).padStart(2,"0")).join("")}catch{return}}var d=class extends Error{code;status;constructor(o,l,u=null){super(l),this.name="AgentUploadError",this.code=u,this.status=o;}};function y(){if(typeof window>"u")return "flexkit.io";if(b$1())return c;let{hostname:s}=window.location;return s==="localhost"||s==="127.0.0.1"||s==="flexkit.test"||s.endsWith(".flexkit.test")?"flexkit.test":"flexkit.io"}function v(){return `https://${y()}`}function x(s,o){return `https://${s}.api.${y()}/automations/webhook/${encodeURIComponent(o)}`}function N(s){let o=`/api/flexkit/${s}`,l=`${o}/automations`,u=`${o}/skills`,n=`${o}/agent/chats`;async function i(t,e){let a=await fetch(t,{credentials:"include",headers:{"Content-Type":"application/json",...e?.headers??{}},...e}),c=await a.json();if(!a.ok){let r=c&&typeof c=="object"&&"error"in c?String(c.error):"Request failed";throw new Error(r)}return c}return {connectPlugins:t=>i(`${o}/plugins/connect`,{method:"POST",body:JSON.stringify(t)}),connectPluginToken:t=>i(`${o}/plugins/connect-token`,{method:"POST",body:JSON.stringify(t)}),pluginOAuthStatus:t=>i(`${o}/plugins/oauth-transactions/${encodeURIComponent(t)}`),updatePluginConnection:(t,e)=>i(`${o}/plugin-connections/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(e)}),disconnectPlugin:t=>i(`${o}/plugin-connections/${encodeURIComponent(t)}`,{method:"DELETE"}),installPlugin:t=>i(`${o}/plugins/${encodeURIComponent(t)}/installation`,{method:"PUT",body:JSON.stringify({})}),setPluginPolicy:(t,e)=>i(`${o}/plugins/${encodeURIComponent(t)}/policy`,{method:"PATCH",body:JSON.stringify(e)}),refreshPluginTools:t=>i(`${o}/plugin-connections/${encodeURIComponent(t)}/tools/refresh`,{method:"POST"}),cancelRun:async t=>i(`${l}/runs/${encodeURIComponent(t)}/cancel`,{method:"POST"}),createAgentChat:async t=>i(n,{body:JSON.stringify({modelId:t?.modelId??null}),method:"POST"}),deleteAgentChat:async t=>i(`${n}/${encodeURIComponent(t)}`,{method:"DELETE"}),getAgentChatStreamUrl:(t,e)=>`${n}/${encodeURIComponent(t)}/stream?workflowRunId=${encodeURIComponent(e)}`,renameAgentChat:async(t,e)=>i(`${n}/${encodeURIComponent(t)}`,{body:JSON.stringify({title:e}),method:"PATCH"}),sendAgentChatMessage:async(t,e)=>i(`${n}/${encodeURIComponent(t)}/messages`,{body:JSON.stringify(e),method:"POST"}),announcePluginConnected:async(t,e)=>i(`${n}/${encodeURIComponent(t)}/plugin-connected`,{body:JSON.stringify({pluginId:e}),method:"POST"}),sendAgentChatFollowUp:async(t,e)=>i(`${n}/${encodeURIComponent(t)}/follow-ups`,{body:JSON.stringify(e),method:"POST"}),answerAgentChatQuestion:async(t,e,a)=>{let c=await fetch(`${n}/${encodeURIComponent(t)}/questions/${encodeURIComponent(e)}/answer`,{body:JSON.stringify(a),credentials:"include",headers:{"Content-Type":"application/json"},method:"POST"}),r=await c.json();if(!c.ok&&!r.question)throw new Error(r.errorMessage??r.error??"Request failed");return {errorMessage:c.ok?void 0:r.errorMessage,question:r.question}},startAgentChat:async({attachments:t,content:e,modelId:a})=>i(n,{body:JSON.stringify({message:{attachments:t,content:e},modelId:a??null}),method:"POST"}),startQueuedAgentChatMessage:async(t,e)=>i(`${n}/${encodeURIComponent(t)}/follow-ups/${encodeURIComponent(e)}/start`,{method:"POST"}),stopAgentChat:async t=>i(`${n}/${encodeURIComponent(t)}/stop`,{method:"POST"}),stopAgentChatMonitor:async(t,e)=>i(`${n}/${encodeURIComponent(t)}/monitors/${encodeURIComponent(e)}/stop`,{method:"POST"}),transcribeAgentAudio:async(t,e)=>{let{durationSeconds:a,pcm:c}=await C(t),r=new FormData;r.append("file",c,"audio.pcm"),r.append("durationSeconds",String(a));let g=await fetch(`${o}/agent/transcribe`,{body:r,credentials:"include",method:"POST",signal:e}),m=await g.json();if(!g.ok){let S=m&&typeof m=="object"&&m.error?String(m.error):"Request failed";throw new Error(S)}if(!m.text?.trim())throw new Error("No speech was recognized. Try again.");return {text:m.text}},uploadAgentChatAttachment:async(t,e$1)=>{let[a,c]=await Promise.all([fetch(`${o}/agent/uploads`,{body:JSON.stringify({filename:t.name,mediaType:t.type||null,sizeBytes:t.size}),credentials:"include",headers:{"Content-Type":"application/json"},method:"POST",signal:e$1}),e({name:t.name,size:t.size})===null?b(t):void 0]),r=await a.json();if(!a.ok||!r.pathname||!r.token||!r.mediaType)throw new d(a.status,r.error?String(r.error):"The file could not be uploaded.",r.code??null);let g=await put(r.pathname,t,{abortSignal:e$1,access:"public",contentType:r.mediaType,token:r.token});return {filename:t.name,mediaType:r.mediaType,sizeBytes:t.size,url:g.url,...c?{sha256:c}:{}}},decideApproval:async(t,e)=>{let a=await fetch(`${l}/approvals/${encodeURIComponent(t)}/decide`,{body:JSON.stringify(e),credentials:"include",headers:{"Content-Type":"application/json"},method:"POST"}),c=await a.json();if(!a.ok&&typeof c.success!="boolean")throw new Error(c.error?String(c.error):"Request failed");return c},markActivityRead:async t=>i(`${o}/activity/read`,{body:JSON.stringify(t==="all"?{all:true}:{ids:t}),method:"POST"}),setActivityItemState:async(t,e)=>i(`${o}/activity/${encodeURIComponent(t)}`,{body:JSON.stringify({state:e}),method:"PATCH"}),createAutomation:async t=>i(l,{body:JSON.stringify(t),method:"POST"}),createSkill:async t=>i(u,{body:JSON.stringify(t),method:"POST"}),deleteAutomation:async t=>i(`${l}/${encodeURIComponent(t)}`,{method:"DELETE"}),deleteSkill:async t=>i(`${u}/${encodeURIComponent(t)}`,{method:"DELETE"}),getArtifactUrl:(t,e)=>{let a=e?.download?"?download=1":"";return `${l}/artifacts/${encodeURIComponent(t)}/content${a}`},getRunArtifacts:async t=>i(`${l}/runs/${encodeURIComponent(t)}/artifacts`).then(e=>e.artifacts),getStreamUrl:t=>`${l}/runs/${encodeURIComponent(t)}/stream`,getTranscriptUrl:t=>`${l}/runs/${encodeURIComponent(t)}/transcript`,listChannels:async(t,e)=>{let a=e?`${o}/plugin-connections/${encodeURIComponent(e)}/channels`:`${o}/plugins/${t}/channels`,c=await fetch(a,{credentials:"include",headers:{"Content-Type":"application/json"}}),r=await c.json();if(c.ok)return {channels:r.channels??[],errorMessage:r.errorMessage,success:r.success??true};if(r.success===false)return {channels:r.channels??[],errorMessage:r.errorMessage??`Failed to load ${t==="slack"?"Slack":"Teams"} channels.`,success:false};let g=r.error?String(r.error):"Request failed";throw new Error(g)},runAutomation:async t=>i(`${l}/${encodeURIComponent(t)}/runs`,{method:"POST"}),updateAutomation:async(t,e)=>i(`${l}/${encodeURIComponent(t)}`,{body:JSON.stringify(e),method:"PATCH"}),updateSkill:async(t,e)=>i(`${u}/${encodeURIComponent(t)}`,{body:JSON.stringify(e),method:"PATCH"})}}var p=class extends Error{status;constructor(o,l="Request failed"){super(l),this.name="FetcherError",this.status=o;}},D=async s=>{let o=await fetch(s,{credentials:"include"});if(!o.ok)throw new p(o.status);return await o.json()};function E(s){let o=`/api/flexkit/${s}/automations`,l=`/api/flexkit/${s}/skills`,u=`/api/flexkit/${s}/agent/chats`;return {activity:(n={})=>{let{filter:i="all",limit:t=25,offset:e=0}=n,a=new URLSearchParams({filter:i,limit:t.toString(),offset:e.toString()});return `/api/flexkit/${s}/activity?${a.toString()}`},activityItem:n=>`/api/flexkit/${s}/activity/${encodeURIComponent(n)}`,activitySummary:n=>n?`/api/flexkit/${s}/activity/summary?since=${encodeURIComponent(n)}`:`/api/flexkit/${s}/activity/summary`,agentChat:n=>`${u}/${encodeURIComponent(n)}`,agentChatSearch:n=>`${u}/search?q=${encodeURIComponent(n)}`,agentChats:(n=0)=>`${u}?offset=${n.toString()}`,agentProfile:()=>`/api/flexkit/${s}/agent/profile`,approval:n=>`${o}/approvals/${encodeURIComponent(n)}`,approvals:(n={})=>{let{limit:i=25,offset:t=0,runId:e,status:a}=n,c=new URLSearchParams({limit:i.toString(),offset:t.toString()});return a&&c.set("status",a),e&&c.set("runId",e),`${o}/approvals?${c.toString()}`},approvalsCount:`${o}/approvals?limit=1`,automation:n=>`${o}/${encodeURIComponent(n)}`,automationRuns:(n,i=0,t=25)=>`${o}/${encodeURIComponent(n)}/runs?offset=${i.toString()}&limit=${t.toString()}`,automations:(n={})=>{let{enabled:i,limit:t=25,offset:e=0,search:a,visibility:c}=n,r=new URLSearchParams({limit:t.toString(),offset:e.toString()});i&&i.length>0&&r.set("enabled",i.map(m=>m?"true":"false").join(",")),c&&c.length>0&&r.set("visibility",c.join(","));let g=a?.trim();return g&&r.set("q",g),`${o}?${r.toString()}`},creditBalance:`${o}/credits`,entities:`${o}/entities`,run:n=>`${o}/runs/${encodeURIComponent(n)}`,runHistory:(n,i=0,t=25)=>`${o}/runs?scope=${n}&offset=${i.toString()}&limit=${t.toString()}`,skill:n=>`${l}/${encodeURIComponent(n)}`,skills:(n={})=>{let{limit:i=25,offset:t=0,search:e,visibility:a}=n,c=new URLSearchParams({limit:i.toString(),offset:t.toString()});a&&a.length>0&&c.set("visibility",a.join(","));let r=e?.trim();return r&&c.set("q",r),`${l}?${c.toString()}`},spaces:`/api/flexkit/${s}/spaces`,members:n=>n?`/api/flexkit/${s}/members?spaceId=${encodeURIComponent(n)}`:`/api/flexkit/${s}/members`,tools:n=>n?`${o}/${encodeURIComponent(n)}/tools`:`${o}/tools`}}
|
|
2
|
+
export{w as a,v as b,x as c,N as d,p as e,D as f,E as g};//# sourceMappingURL=chunk-MNLYE7DK.js.map
|
|
3
|
+
//# sourceMappingURL=chunk-MNLYE7DK.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/apps/ai/agent/dictation.ts","../src/apps/ai/api.ts"],"names":["appendDictatedText","existing","transcript","dictated","convertRecordedAudioToPcm","blob","AudioContextCtor","arrayBuffer","audioContext","audioBuffer","mono","mixToMono","resampled","resample","pcm","floatToPcm16","durationSeconds","buffer","length","channelCount","index","sum","channel","samples","sourceRate","targetRate","ratio","outputLength","output","sourceIndex","left","right","fraction","leftSample","rightSample","view","sample","sha256Hex","file","digest","byte","AgentUploadError","status","message","code","getApiRootDomain","getDesktop","flexkitDomain","hostname","getPlatformOrigin","getWebhookTriggerUrl","projectId","token","createApiClient","projectBasePath","automationsBasePath","skillsBasePath","agentChatsBasePath","request","url","init","response","data","error","input","id","runId","chatId","workflowRunId","title","pluginId","questionId","result","attachments","content","modelId","messageId","monitorId","audio","signal","formData","tokenResponse","sha256","getKnowledgeFileProblem","tokenData","put","approvalId","ids","itemId","state","automationId","skillId","artifactId","options","suffix","provider","connectionId","FetcherError","fetcher","paths","basePath","filter","limit","offset","params","since","query","enabled","search","visibility","value","trimmedSearch","scope","spaceId"],"mappings":"2IAIO,SAASA,CAAAA,CAAmBC,CAAAA,CAAkBC,CAAAA,CAA4B,CAC/E,IAAMC,CAAAA,CAAWD,CAAAA,CAAW,IAAA,EAAK,CAEjC,OAAKC,CAAAA,CAIAF,CAAAA,CAAS,IAAA,EAAK,CAIf,KAAA,CAAM,IAAA,CAAKA,CAAQ,CAAA,EAAK,WAAA,CAAY,IAAA,CAAKE,CAAQ,CAAA,CAC5C,CAAA,EAAGF,CAAQ,CAAA,EAAGE,CAAQ,CAAA,CAAA,CAGxB,CAAA,EAAGF,CAAQ,CAAA,CAAA,EAAIE,CAAQ,CAAA,CAAA,CAPrBF,CAAAA,CAAS,MAAA,GAAW,CAAA,CAAIE,CAAAA,CAAW,CAAA,EAAGF,CAAQ,CAAA,EAAGE,CAAQ,CAAA,CAAA,CAJzDF,CAYX,CAEA,eAAsBG,CAAAA,CAA0BC,EAA6D,CAC3G,GAAI,OAAO,MAAA,CAAW,GAAA,CACpB,MAAM,IAAI,K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AAAA,CAAM,QAAA,GACb,MAAA,CAAQC,CAAAA,CAAO,QAAA,EACjB,CAAC,CAAA,CAEGM,CAAAA,EAAcA,CAAAA,CAAW,MAAA,CAAS,CAAA,EACpCL,CAAAA,CAAO,GAAA,CAAI,YAAA,CAAcK,CAAAA,CAAW,IAAA,CAAK,GAAG,CAAC,CAAA,CAG/C,IAAME,CAAAA,CAAgBH,CAAAA,EAAQ,IAAA,EAAK,CAEnC,OAAIG,CAAAA,EACFP,CAAAA,CAAO,GAAA,CAAI,GAAA,CAAKO,CAAa,CAAA,CAGxB,CAAA,EAAGvD,CAAc,CAAA,CAAA,EAAIgD,EAAO,QAAA,EAAU,CAAA,CAC/C,CAAA,CACA,MAAA,CAAQ,CAAA,aAAA,EAAgBrD,CAAS,CAAA,OAAA,CAAA,CACjC,OAAA,CAAU8D,CAAAA,EACRA,CAAAA,CACI,CAAA,aAAA,EAAgB9D,CAAS,CAAA,iBAAA,EAAoB,kBAAA,CAAmB8D,CAAO,CAAC,CAAA,CAAA,CACxE,CAAA,aAAA,EAAgB9D,CAAS,CAAA,QAAA,CAAA,CAC/B,KAAA,CAAQuC,CAAAA,EACNA,CAAAA,CAAe,CAAA,EAAGU,CAAQ,CAAA,CAAA,EAAI,kBAAA,CAAmBV,CAAY,CAAC,CAAA,MAAA,CAAA,CAAW,CAAA,EAAGU,CAAQ,QACxF,CACF","file":"chunk-MNLYE7DK.js","sourcesContent":["export const DICTATION_SAMPLE_RATE = 24_000;\nexport const DICTATION_MAX_DURATION_SECONDS = 60;\nexport const DICTATION_MIN_DURATION_SECONDS = 0.25;\n\nexport function appendDictatedText(existing: string, transcript: string): string {\n const dictated = transcript.trim();\n\n if (!dictated) {\n return existing;\n }\n\n if (!existing.trim()) {\n return existing.length === 0 ? dictated : `${existing}${dictated}`;\n }\n\n if (/\\s$/.test(existing) || /^[.,!?;:]/.test(dictated)) {\n return `${existing}${dictated}`;\n }\n\n return `${existing} ${dictated}`;\n}\n\nexport async function convertRecordedAudioToPcm(blob: Blob): Promise<{ durationSeconds: number; pcm: Blob }> {\n if (typeof window === 'undefined') {\n throw new Error('Dictation is only available in the browser.');\n }\n\n const AudioContextCtor = window.AudioContext ?? window.webkitAudioContext;\n\n if (!AudioContextCtor) {\n throw new Error('This browser cannot decode recorded audio.');\n }\n\n const arrayBuffer = await blob.arrayBuffer();\n const audioContext = new AudioContextCtor();\n\n try {\n const audioBuffer = await audioContext.decodeAudioData(arrayBuffer.slice(0));\n const mono = mixToMono(audioBuffer);\n const resampled = resample(mono, audioBuffer.sampleRate, DICTATION_SAMPLE_RATE);\n const pcm = floatToPcm16(resampled);\n const durationSeconds = resampled.length / DICTATION_SAMPLE_RATE;\n\n if (durationSeconds < DICTATION_MIN_DURATION_SECONDS) {\n throw new Error('No speech was captured. Try again.');\n }\n\n if (durationSeconds > DICTATION_MAX_DURATION_SECONDS) {\n throw new Error(`Dictation is limited to ${String(DICTATION_MAX_DURATION_SECONDS)} seconds.`);\n }\n\n return {\n durationSeconds,\n pcm: new Blob([pcm], { type: 'audio/pcm' }),\n };\n } finally {\n await audioContext.close();\n }\n}\n\nfunction mixToMono(buffer: AudioBuffer): Float32Array {\n const { length, numberOfChannels: channelCount } = buffer;\n\n if (channelCount === 1) {\n return buffer.getChannelData(0).slice();\n }\n\n const mono = new Float32Array(length);\n\n for (let index = 0; index < length; index += 1) {\n let sum = 0;\n\n for (let channel = 0; channel < channelCount; channel += 1) {\n sum += buffer.getChannelData(channel)[index] ?? 0;\n }\n\n mono[index] = sum / channelCount;\n }\n\n return mono;\n}\n\nfunction resample(samples: Float32Array, sourceRate: number, targetRate: number): Float32Array {\n if (sourceRate === targetRate) {\n return samples;\n }\n\n const ratio = sourceRate / targetRate;\n const outputLength = Math.max(1, Math.round(samples.length / ratio));\n const output = new Float32Array(outputLength);\n\n for (let index = 0; index < outputLength; index += 1) {\n const sourceIndex = index * ratio;\n const left = Math.floor(sourceIndex);\n const right = Math.min(left + 1, samples.length - 1);\n const fraction = sourceIndex - left;\n const leftSample = samples[left] ?? 0;\n const rightSample = samples[right] ?? 0;\n output[index] = leftSample + (rightSample - leftSample) * fraction;\n }\n\n return output;\n}\n\nfunction floatToPcm16(samples: Float32Array): ArrayBuffer {\n const buffer = new ArrayBuffer(samples.length * 2);\n const view = new DataView(buffer);\n\n for (let index = 0; index < samples.length; index += 1) {\n const sample = Math.max(-1, Math.min(1, samples[index] ?? 0));\n view.setInt16(index * 2, sample < 0 ? sample * 0x8000 : sample * 0x7fff, true);\n }\n\n return buffer;\n}\n\ndeclare global {\n interface Window {\n webkitAudioContext?: typeof AudioContext;\n }\n}\n","import { getKnowledgeFileProblem } from '../knowledge/knowledge';\nimport type { PluginConnection, PluginScope, PluginTools } from './plugin-types';\nimport { put } from '@vercel/blob/client';\nimport { convertRecordedAudioToPcm } from './agent/dictation';\nimport { getDesktop } from '../../core/desktop';\nimport { flexkitDomain } from '../../core/domains';\nimport type {\n ActivityItem,\n ActivityItemState,\n AgentChat,\n AgentChatAttachment,\n AgentChatFollowUpResult,\n AgentChatMessage,\n AgentChatMonitor,\n AgentChatQuestion,\n AgentChatQuestionResponse,\n AgentChatTurn,\n Automation,\n AutomationApproval,\n AutomationApprovalStatus,\n AutomationArtifact,\n AutomationInput,\n AutomationToolChannel,\n AutomationToolProvider,\n AutomationVisibility,\n MutationResult,\n Skill,\n SkillInput,\n} from './types';\n\nexport interface DecideApprovalInput {\n /** Approve and always allow this plugin tool for the automation. */\n remember?: boolean;\n approved: boolean;\n /** For a proposed automation: the approver's edited instructions and whether to run it once now. */\n automationEdits?: { instructions?: string; runOnce?: boolean };\n force?: boolean;\n reason?: string;\n}\n\nexport interface SendAgentChatMessageInput {\n attachments?: AgentChatAttachment[];\n content: string;\n modelId?: string | null;\n}\n\n/** A new chat and its first turn, started by one request. */\nexport interface StartAgentChatResult {\n chat: AgentChat;\n turn: AgentChatTurn;\n}\n\n/** Lowercase hex SHA-256 of a file, or undefined where the browser cannot hash (insecure contexts). */\nasync function sha256Hex(file: File): Promise<string | undefined> {\n if (typeof crypto === 'undefined' || !crypto.subtle) {\n return undefined;\n }\n\n try {\n const digest = await crypto.subtle.digest('SHA-256', await file.arrayBuffer());\n\n return Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, '0')).join('');\n } catch {\n return undefined;\n }\n}\n\n/** Thrown when the API refuses an upload; `code` lets the UI tailor the message. */\nexport class AgentUploadError extends Error {\n code: string | null;\n status: number;\n\n constructor(status: number, message: string, code: string | null = null) {\n super(message);\n this.name = 'AgentUploadError';\n this.code = code;\n this.status = status;\n }\n}\n\nexport interface ApiClient {\n /** Starts OAuth for a new account, or for `connectionId` to reconnect that specific account. */\n connectPlugins: (_input: {\n pluginId: string;\n scope: PluginScope;\n studioOrigin: string;\n connectionId?: string;\n }) => Promise<{ transactionId: string; authorizeUrl: string; completionOrigin: string; launchTicket: string }>;\n /** Connects a token plugin with a pasted token, or replaces the token of `connectionId`. */\n connectPluginToken: (_input: {\n pluginId: string;\n scope: PluginScope;\n token: string;\n connectionId?: string;\n }) => Promise<{ connection: PluginConnection }>;\n /** Renames (label null resets to the provider name) or makes a connection primary. */\n updatePluginConnection: (\n _id: string,\n _input: { label?: string | null; primary?: true }\n ) => Promise<{ connection: PluginConnection }>;\n pluginOAuthStatus: (\n _id: string\n ) => Promise<{ id: string; status: 'pending' | 'exchanging' | 'complete' | 'failed'; expires_at: string }>;\n disconnectPlugin: (_id: string) => Promise<{ success: boolean }>;\n installPlugin: (_id: string) => Promise<unknown>;\n setPluginPolicy: (_id: string, _input: { enabled: boolean; allowPersonal: boolean }) => Promise<{ success: boolean }>;\n refreshPluginTools: (_id: string) => Promise<PluginTools>;\n\n cancelRun: (_runId: string) => Promise<MutationResult>;\n createAgentChat: (_input?: { modelId?: string | null }) => Promise<{ chat: AgentChat }>;\n deleteAgentChat: (_chatId: string) => Promise<{ success: boolean }>;\n getAgentChatStreamUrl: (_chatId: string, _workflowRunId: string) => string;\n renameAgentChat: (_chatId: string, _title: string) => Promise<{ chat: AgentChat }>;\n sendAgentChatMessage: (_chatId: string, _input: SendAgentChatMessageInput) => Promise<AgentChatTurn>;\n /**\n * Sends a message while the chat's turn is running. The platform decides\n * whether it steers that turn or waits as the next one; if the turn has\n * meanwhile ended, the message starts the next turn.\n */\n sendAgentChatFollowUp: (_chatId: string, _input: SendAgentChatMessageInput) => Promise<AgentChatFollowUpResult>;\n /** The user connected a plugin from the chat's connect card: starts the turn that uses it, or queues it. */\n announcePluginConnected: (\n _chatId: string,\n _pluginId: string\n ) => Promise<Extract<AgentChatFollowUpResult, { followUp: unknown } | { turn: unknown }>>;\n /** Answers (or dismisses) the questions a chat turn waits on; a settled question comes back with an error. */\n answerAgentChatQuestion: (\n _chatId: string,\n _questionId: string,\n _response: AgentChatQuestionResponse\n ) => Promise<{ errorMessage?: string; question?: AgentChatQuestion }>;\n /** Creates a chat and sends its first message in one request. */\n startAgentChat: (_input: SendAgentChatMessageInput) => Promise<StartAgentChatResult>;\n /** Starts the next turn from a queued follow-up once the previous turn has ended. */\n startQueuedAgentChatMessage: (_chatId: string, _messageId: string) => Promise<AgentChatTurn>;\n stopAgentChat: (_chatId: string) => Promise<{ message: AgentChatMessage }>;\n stopAgentChatMonitor: (_chatId: string, _monitorId: string) => Promise<{ monitor: AgentChatMonitor }>;\n transcribeAgentAudio: (_audio: Blob, _signal?: AbortSignal) => Promise<{ text: string }>;\n /** Uploads a chat attachment straight to the platform file store. */\n uploadAgentChatAttachment: (_file: File, _signal?: AbortSignal) => Promise<AgentChatAttachment>;\n decideApproval: (\n _approvalId: string,\n _input: DecideApprovalInput\n ) => Promise<MutationResult & { approval?: AutomationApproval }>;\n createAutomation: (_input: AutomationInput) => Promise<MutationResult & { automation?: Automation }>;\n createSkill: (_input: SkillInput) => Promise<MutationResult & { skill?: Skill }>;\n deleteAutomation: (_automationId: string) => Promise<MutationResult>;\n deleteSkill: (_skillId: string) => Promise<MutationResult>;\n getArtifactUrl: (_artifactId: string, _options?: { download?: boolean }) => string;\n getRunArtifacts: (_workflowRunId: string) => Promise<AutomationArtifact[]>;\n getStreamUrl: (_workflowRunId: string) => string;\n /** JSON transcript of a finished run (owners and developers). */\n getTranscriptUrl: (_runId: string) => string;\n /** Lists delivery channels of `connectionId`, or of the provider's primary project account when omitted. */\n listChannels: (\n _provider: AutomationToolProvider,\n _connectionId?: string | null\n ) => Promise<{\n channels: AutomationToolChannel[];\n errorMessage?: string;\n success: boolean;\n }>;\n runAutomation: (_automationId: string) => Promise<MutationResult & { runId?: string }>;\n updateAutomation: (\n _automationId: string,\n _input: AutomationInput\n ) => Promise<MutationResult & { automation?: Automation }>;\n updateSkill: (_skillId: string, _input: SkillInput) => Promise<MutationResult & { skill?: Skill }>;\n /** Marks the caller's Activity items read; `'all'` marks every unread item. */\n markActivityRead: (_ids: string[] | 'all') => Promise<{ success: boolean }>;\n setActivityItemState: (\n _itemId: string,\n _state: Extract<ActivityItemState, 'unread' | 'read' | 'dismissed'>\n ) => Promise<{ item: ActivityItem }>;\n}\n\nfunction getApiRootDomain(): string {\n if (typeof window === 'undefined') {\n return 'flexkit.io';\n }\n\n // The desktop app serves the Studio on its own scheme (`flexkit://app`), so\n // its page hostname says nothing; the backend it was built for does.\n if (getDesktop()) {\n return flexkitDomain;\n }\n\n const { hostname } = window.location;\n const isDevHost =\n hostname === 'localhost' ||\n hostname === '127.0.0.1' ||\n hostname === 'flexkit.test' ||\n hostname.endsWith('.flexkit.test');\n\n return isDevHost ? 'flexkit.test' : 'flexkit.io';\n}\n\n/** Origin that hosts plugin OAuth start and completion. */\nexport function getPlatformOrigin(): string {\n return `https://${getApiRootDomain()}`;\n}\n\n/** Public URL an external system calls to fire a webhook trigger. */\nexport function getWebhookTriggerUrl(projectId: string, token: string): string {\n return `https://${projectId}.api.${getApiRootDomain()}/automations/webhook/${encodeURIComponent(token)}`;\n}\n\nexport function createApiClient(projectId: string): ApiClient {\n const projectBasePath = `/api/flexkit/${projectId}`;\n const automationsBasePath = `${projectBasePath}/automations`;\n const skillsBasePath = `${projectBasePath}/skills`;\n const agentChatsBasePath = `${projectBasePath}/agent/chats`;\n\n async function request<T>(url: string, init?: RequestInit): Promise<T> {\n const response = await fetch(url, {\n credentials: 'include',\n headers: {\n 'Content-Type': 'application/json',\n ...(init?.headers ?? {}),\n },\n ...init,\n });\n const data = (await response.json()) as T;\n\n if (!response.ok) {\n const error = data && typeof data === 'object' && 'error' in data ? String(data.error) : 'Request failed';\n\n throw new Error(error);\n }\n\n return data;\n }\n\n return {\n connectPlugins: (input) =>\n request(`${projectBasePath}/plugins/connect`, { method: 'POST', body: JSON.stringify(input) }),\n connectPluginToken: (input) =>\n request(`${projectBasePath}/plugins/connect-token`, { method: 'POST', body: JSON.stringify(input) }),\n pluginOAuthStatus: (id) => request(`${projectBasePath}/plugins/oauth-transactions/${encodeURIComponent(id)}`),\n updatePluginConnection: (id, input) =>\n request(`${projectBasePath}/plugin-connections/${encodeURIComponent(id)}`, {\n method: 'PATCH',\n body: JSON.stringify(input),\n }),\n disconnectPlugin: (id) =>\n request(`${projectBasePath}/plugin-connections/${encodeURIComponent(id)}`, { method: 'DELETE' }),\n installPlugin: (id) =>\n request(`${projectBasePath}/plugins/${encodeURIComponent(id)}/installation`, {\n method: 'PUT',\n body: JSON.stringify({}),\n }),\n setPluginPolicy: (id, input) =>\n request(`${projectBasePath}/plugins/${encodeURIComponent(id)}/policy`, {\n method: 'PATCH',\n body: JSON.stringify(input),\n }),\n refreshPluginTools: (id) =>\n request(`${projectBasePath}/plugin-connections/${encodeURIComponent(id)}/tools/refresh`, { method: 'POST' }),\n cancelRun: async (runId) =>\n request<MutationResult>(`${automationsBasePath}/runs/${encodeURIComponent(runId)}/cancel`, { method: 'POST' }),\n createAgentChat: async (input) =>\n request<{ chat: AgentChat }>(agentChatsBasePath, {\n body: JSON.stringify({ modelId: input?.modelId ?? null }),\n method: 'POST',\n }),\n deleteAgentChat: async (chatId) =>\n request<{ success: boolean }>(`${agentChatsBasePath}/${encodeURIComponent(chatId)}`, { method: 'DELETE' }),\n getAgentChatStreamUrl: (chatId, workflowRunId) =>\n `${agentChatsBasePath}/${encodeURIComponent(chatId)}/stream?workflowRunId=${encodeURIComponent(workflowRunId)}`,\n renameAgentChat: async (chatId, title) =>\n request<{ chat: AgentChat }>(`${agentChatsBasePath}/${encodeURIComponent(chatId)}`, {\n body: JSON.stringify({ title }),\n method: 'PATCH',\n }),\n sendAgentChatMessage: async (chatId, input) =>\n request<AgentChatTurn>(`${agentChatsBasePath}/${encodeURIComponent(chatId)}/messages`, {\n body: JSON.stringify(input),\n method: 'POST',\n }),\n announcePluginConnected: async (chatId, pluginId) =>\n request(`${agentChatsBasePath}/${encodeURIComponent(chatId)}/plugin-connected`, {\n body: JSON.stringify({ pluginId }),\n method: 'POST',\n }),\n sendAgentChatFollowUp: async (chatId, input) =>\n request<AgentChatFollowUpResult>(`${agentChatsBasePath}/${encodeURIComponent(chatId)}/follow-ups`, {\n body: JSON.stringify(input),\n method: 'POST',\n }),\n answerAgentChatQuestion: async (chatId, questionId, response) => {\n const result = await fetch(\n `${agentChatsBasePath}/${encodeURIComponent(chatId)}/questions/${encodeURIComponent(questionId)}/answer`,\n {\n body: JSON.stringify(response),\n credentials: 'include',\n headers: { 'Content-Type': 'application/json' },\n method: 'POST',\n }\n );\n const data = (await result.json()) as { errorMessage?: string; error?: string; question?: AgentChatQuestion };\n\n // A question settled elsewhere (409) comes back with its final state for the card to show.\n if (!result.ok && !data.question) {\n throw new Error(data.errorMessage ?? data.error ?? 'Request failed');\n }\n\n return { errorMessage: result.ok ? undefined : data.errorMessage, question: data.question };\n },\n startAgentChat: async ({ attachments, content, modelId }) =>\n request<StartAgentChatResult>(agentChatsBasePath, {\n body: JSON.stringify({ message: { attachments, content }, modelId: modelId ?? null }),\n method: 'POST',\n }),\n startQueuedAgentChatMessage: async (chatId, messageId) =>\n request<AgentChatTurn>(\n `${agentChatsBasePath}/${encodeURIComponent(chatId)}/follow-ups/${encodeURIComponent(messageId)}/start`,\n { method: 'POST' }\n ),\n stopAgentChat: async (chatId) =>\n request<{ message: AgentChatMessage }>(`${agentChatsBasePath}/${encodeURIComponent(chatId)}/stop`, {\n method: 'POST',\n }),\n stopAgentChatMonitor: async (chatId, monitorId) =>\n request<{ monitor: AgentChatMonitor }>(\n `${agentChatsBasePath}/${encodeURIComponent(chatId)}/monitors/${encodeURIComponent(monitorId)}/stop`,\n { method: 'POST' }\n ),\n transcribeAgentAudio: async (audio, signal) => {\n const { durationSeconds, pcm } = await convertRecordedAudioToPcm(audio);\n const formData = new FormData();\n formData.append('file', pcm, 'audio.pcm');\n formData.append('durationSeconds', String(durationSeconds));\n\n const response = await fetch(`${projectBasePath}/agent/transcribe`, {\n body: formData,\n credentials: 'include',\n method: 'POST',\n signal,\n });\n const data = (await response.json()) as { error?: string; text?: string };\n\n if (!response.ok) {\n const error = data && typeof data === 'object' && data.error ? String(data.error) : 'Request failed';\n\n throw new Error(error);\n }\n\n if (!data.text?.trim()) {\n throw new Error('No speech was recognized. Try again.');\n }\n\n return { text: data.text };\n },\n uploadAgentChatAttachment: async (file, signal) => {\n // The platform issues a token scoped to one pathname, type and size; the\n // browser then writes the bytes to the store directly, so large files\n // never pass through the API function body limit. The hash is computed\n // alongside: Knowledge documents are keyed by it, so the platform can tell\n // later whether this file is already one.\n const [tokenResponse, sha256] = await Promise.all([\n fetch(`${projectBasePath}/agent/uploads`, {\n body: JSON.stringify({ filename: file.name, mediaType: file.type || null, sizeBytes: file.size }),\n credentials: 'include',\n headers: { 'Content-Type': 'application/json' },\n method: 'POST',\n signal,\n }),\n // Only files Knowledge can index are worth hashing; a screenshot never matches a document.\n getKnowledgeFileProblem({ name: file.name, size: file.size }) === null ? sha256Hex(file) : undefined,\n ]);\n const tokenData = (await tokenResponse.json()) as {\n code?: string;\n error?: string;\n mediaType?: string;\n pathname?: string;\n token?: string;\n };\n\n if (!tokenResponse.ok || !tokenData.pathname || !tokenData.token || !tokenData.mediaType) {\n throw new AgentUploadError(\n tokenResponse.status,\n tokenData.error ? String(tokenData.error) : 'The file could not be uploaded.',\n tokenData.code ?? null\n );\n }\n\n const blob = await put(tokenData.pathname, file, {\n abortSignal: signal,\n access: 'public',\n contentType: tokenData.mediaType,\n token: tokenData.token,\n });\n\n return {\n filename: file.name,\n mediaType: tokenData.mediaType,\n sizeBytes: file.size,\n url: blob.url,\n ...(sha256 ? { sha256 } : {}),\n };\n },\n decideApproval: async (approvalId, input) => {\n const response = await fetch(`${automationsBasePath}/approvals/${encodeURIComponent(approvalId)}/decide`, {\n body: JSON.stringify(input),\n credentials: 'include',\n headers: {\n 'Content-Type': 'application/json',\n },\n method: 'POST',\n });\n const data = (await response.json()) as MutationResult & { approval?: AutomationApproval; error?: string };\n\n // Business errors (stale_preview, already_decided) come back as 400\n // with a structured body the caller must be able to inspect.\n if (!response.ok && typeof data.success !== 'boolean') {\n throw new Error(data.error ? String(data.error) : 'Request failed');\n }\n\n return data;\n },\n markActivityRead: async (ids) =>\n request<{ success: boolean }>(`${projectBasePath}/activity/read`, {\n body: JSON.stringify(ids === 'all' ? { all: true } : { ids }),\n method: 'POST',\n }),\n setActivityItemState: async (itemId, state) =>\n request<{ item: ActivityItem }>(`${projectBasePath}/activity/${encodeURIComponent(itemId)}`, {\n body: JSON.stringify({ state }),\n method: 'PATCH',\n }),\n createAutomation: async (input) =>\n request<MutationResult & { automation?: Automation }>(automationsBasePath, {\n body: JSON.stringify(input),\n method: 'POST',\n }),\n createSkill: async (input) =>\n request<MutationResult & { skill?: Skill }>(skillsBasePath, {\n body: JSON.stringify(input),\n method: 'POST',\n }),\n deleteAutomation: async (automationId) =>\n request<MutationResult>(`${automationsBasePath}/${encodeURIComponent(automationId)}`, { method: 'DELETE' }),\n deleteSkill: async (skillId) =>\n request<MutationResult>(`${skillsBasePath}/${encodeURIComponent(skillId)}`, { method: 'DELETE' }),\n getArtifactUrl: (artifactId, options) => {\n const suffix = options?.download ? '?download=1' : '';\n\n return `${automationsBasePath}/artifacts/${encodeURIComponent(artifactId)}/content${suffix}`;\n },\n getRunArtifacts: async (workflowRunId) =>\n request<{ artifacts: AutomationArtifact[] }>(\n `${automationsBasePath}/runs/${encodeURIComponent(workflowRunId)}/artifacts`\n ).then((response) => response.artifacts),\n getStreamUrl: (workflowRunId) => `${automationsBasePath}/runs/${encodeURIComponent(workflowRunId)}/stream`,\n getTranscriptUrl: (runId) => `${automationsBasePath}/runs/${encodeURIComponent(runId)}/transcript`,\n listChannels: async (provider, connectionId) => {\n const url = connectionId\n ? `${projectBasePath}/plugin-connections/${encodeURIComponent(connectionId)}/channels`\n : `${projectBasePath}/plugins/${provider}/channels`;\n const response = await fetch(url, {\n credentials: 'include',\n headers: {\n 'Content-Type': 'application/json',\n },\n });\n const data = (await response.json()) as {\n channels?: AutomationToolChannel[];\n error?: string;\n errorMessage?: string;\n success?: boolean;\n };\n\n if (response.ok) {\n return {\n channels: data.channels ?? [],\n errorMessage: data.errorMessage,\n success: data.success ?? true,\n };\n }\n\n if (data.success === false) {\n return {\n channels: data.channels ?? [],\n errorMessage: data.errorMessage ?? `Failed to load ${provider === 'slack' ? 'Slack' : 'Teams'} channels.`,\n success: false,\n };\n }\n\n const error = data.error ? String(data.error) : 'Request failed';\n\n throw new Error(error);\n },\n runAutomation: async (automationId) =>\n request<MutationResult & { runId?: string }>(`${automationsBasePath}/${encodeURIComponent(automationId)}/runs`, {\n method: 'POST',\n }),\n updateAutomation: async (automationId, input) =>\n request<MutationResult & { automation?: Automation }>(\n `${automationsBasePath}/${encodeURIComponent(automationId)}`,\n {\n body: JSON.stringify(input),\n method: 'PATCH',\n }\n ),\n updateSkill: async (skillId, input) =>\n request<MutationResult & { skill?: Skill }>(`${skillsBasePath}/${encodeURIComponent(skillId)}`, {\n body: JSON.stringify(input),\n method: 'PATCH',\n }),\n };\n}\n\nexport class FetcherError extends Error {\n status: number;\n\n constructor(status: number, message = 'Request failed') {\n super(message);\n this.name = 'FetcherError';\n this.status = status;\n }\n}\n\nexport const fetcher = async <T>(url: string): Promise<T> => {\n const response = await fetch(url, { credentials: 'include' });\n\n if (!response.ok) {\n throw new FetcherError(response.status);\n }\n\n return (await response.json()) as T;\n};\n\nexport function paths(projectId: string): {\n activity: (_options?: { filter?: 'all' | 'needs_action'; limit?: number; offset?: number }) => string;\n activityItem: (_itemId: string) => string;\n /** Badge counts; with `since`, also the unread items created after it. */\n activitySummary: (_since?: string | null) => string;\n agentChat: (_chatId: string) => string;\n agentChatSearch: (_query: string) => string;\n agentChats: (_offset?: number) => string;\n agentProfile: () => string;\n approval: (_approvalId: string) => string;\n approvals: (_options?: {\n limit?: number;\n offset?: number;\n runId?: string;\n status?: AutomationApprovalStatus;\n }) => string;\n approvalsCount: string;\n automation: (_automationId: string) => string;\n automationRuns: (_automationId: string, _offset?: number, _limit?: number) => string;\n automations: (_options?: {\n enabled?: boolean[];\n limit?: number;\n offset?: number;\n search?: string;\n visibility?: AutomationVisibility[];\n }) => string;\n creditBalance: string;\n entities: string;\n run: (_runId: string) => string;\n runHistory: (_scope: 'mine' | 'team', _offset?: number, _limit?: number) => string;\n skill: (_skillId: string) => string;\n skills: (_options?: {\n limit?: number;\n offset?: number;\n search?: string;\n visibility?: AutomationVisibility[];\n }) => string;\n spaces: string;\n /** Members for pickers; with a space id, only members who can see that space. */\n members: (_spaceId?: string | null) => string;\n tools: (_automationId?: string) => string;\n} {\n const basePath = `/api/flexkit/${projectId}/automations`;\n const skillsBasePath = `/api/flexkit/${projectId}/skills`;\n const agentChatsBasePath = `/api/flexkit/${projectId}/agent/chats`;\n\n return {\n activity: (options = {}) => {\n const { filter = 'all', limit = 25, offset = 0 } = options;\n const params = new URLSearchParams({ filter, limit: limit.toString(), offset: offset.toString() });\n\n return `/api/flexkit/${projectId}/activity?${params.toString()}`;\n },\n activityItem: (itemId) => `/api/flexkit/${projectId}/activity/${encodeURIComponent(itemId)}`,\n activitySummary: (since) =>\n since\n ? `/api/flexkit/${projectId}/activity/summary?since=${encodeURIComponent(since)}`\n : `/api/flexkit/${projectId}/activity/summary`,\n agentChat: (chatId) => `${agentChatsBasePath}/${encodeURIComponent(chatId)}`,\n agentChatSearch: (query) => `${agentChatsBasePath}/search?q=${encodeURIComponent(query)}`,\n agentChats: (offset = 0) => `${agentChatsBasePath}?offset=${offset.toString()}`,\n agentProfile: () => `/api/flexkit/${projectId}/agent/profile`,\n approval: (approvalId) => `${basePath}/approvals/${encodeURIComponent(approvalId)}`,\n approvals: (options = {}) => {\n const { limit = 25, offset = 0, runId, status } = options;\n const params = new URLSearchParams({\n limit: limit.toString(),\n offset: offset.toString(),\n });\n\n if (status) {\n params.set('status', status);\n }\n\n if (runId) {\n params.set('runId', runId);\n }\n\n return `${basePath}/approvals?${params.toString()}`;\n },\n approvalsCount: `${basePath}/approvals?limit=1`,\n automation: (automationId) => `${basePath}/${encodeURIComponent(automationId)}`,\n automationRuns: (automationId, offset = 0, limit = 25) =>\n `${basePath}/${encodeURIComponent(automationId)}/runs?offset=${offset.toString()}&limit=${limit.toString()}`,\n automations: (options = {}) => {\n const { enabled, limit = 25, offset = 0, search, visibility } = options;\n const params = new URLSearchParams({\n limit: limit.toString(),\n offset: offset.toString(),\n });\n\n if (enabled && enabled.length > 0) {\n params.set('enabled', enabled.map((value) => (value ? 'true' : 'false')).join(','));\n }\n\n if (visibility && visibility.length > 0) {\n params.set('visibility', visibility.join(','));\n }\n\n const trimmedSearch = search?.trim();\n\n if (trimmedSearch) {\n params.set('q', trimmedSearch);\n }\n\n return `${basePath}?${params.toString()}`;\n },\n creditBalance: `${basePath}/credits`,\n entities: `${basePath}/entities`,\n run: (runId) => `${basePath}/runs/${encodeURIComponent(runId)}`,\n runHistory: (scope, offset = 0, limit = 25) =>\n `${basePath}/runs?scope=${scope}&offset=${offset.toString()}&limit=${limit.toString()}`,\n skill: (skillId) => `${skillsBasePath}/${encodeURIComponent(skillId)}`,\n skills: (options = {}) => {\n const { limit = 25, offset = 0, search, visibility } = options;\n const params = new URLSearchParams({\n limit: limit.toString(),\n offset: offset.toString(),\n });\n\n if (visibility && visibility.length > 0) {\n params.set('visibility', visibility.join(','));\n }\n\n const trimmedSearch = search?.trim();\n\n if (trimmedSearch) {\n params.set('q', trimmedSearch);\n }\n\n return `${skillsBasePath}?${params.toString()}`;\n },\n spaces: `/api/flexkit/${projectId}/spaces`,\n members: (spaceId) =>\n spaceId\n ? `/api/flexkit/${projectId}/members?spaceId=${encodeURIComponent(spaceId)}`\n : `/api/flexkit/${projectId}/members`,\n tools: (automationId) =>\n automationId ? `${basePath}/${encodeURIComponent(automationId)}/tools` : `${basePath}/tools`,\n };\n}\n"]}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import'./index.css';import {f as f$1,e as e$2}from'./chunk-
|
|
1
|
+
import'./index.css';import {f as f$1,e as e$2}from'./chunk-JSJZKPXU.js';import {p,o as o$1,h as h$1,i}from'./chunk-XV2B3W6Z.js';import {b}from'./chunk-V7C4EHK3.js';import {j}from'./chunk-AKW7EKYI.js';import {d,c}from'./chunk-XMOSCJOI.js';import {s}from'./chunk-7KLXWCDS.js';import {f}from'./chunk-NSVX6HEN.js';import {na}from'./chunk-DGIY4SKN.js';import {e,g,h,j as j$1,o,n,k}from'./chunk-SZEGGBOC.js';import {a,d as d$1,c as c$1,e as e$1,g as g$1}from'./chunk-HDOIOXMP.js';import {b as b$1}from'./chunk-6NRQMG26.js';import {PencilIcon,Trash2Icon,Ellipsis,Settings2,RefreshCw,Loader2,Trash2}from'lucide-react';import {jsxs,jsx}from'react/jsx-runtime';import {lazy,useState,Suspense}from'react';import {find,propEq}from'ramda';import {gql}from'@apollo/client';import {useApolloClient}from'@apollo/client/react';import {toast}from'sonner';function Be({entityName:e$1,entityNamePlural:a,row:c,options:i={canDelete:true,canEdit:true}}){let m=j(),N=b(),p=c.original._id,D=(i.canDelete??true)&&N,f=i.canEdit??true;function h$1(){m({type:"EditEntity",payload:{entityId:p,entityNamePlural:a}});}function d(){m({type:"DeleteEntity",payload:{entityId:p,entityName:e$1}});}return jsxs("div",{className:"fk:flex",children:[f&&jsxs(b$1,{className:"fk:flex fk:h-7 fk:w-7 fk:p-0 fk:mr-1",onClick:h$1,variant:"ghost",children:[jsx(PencilIcon,{className:"fk:h-4 fk:w-4"}),jsx("span",{className:"fk:sr-only",children:"Edit"})]}),D&&!f&&jsxs(b$1,{className:"fk:flex fk:h-7 fk:w-7 fk:p-0 fk:mr-1",onClick:d,variant:"ghost",children:[jsx(Trash2Icon,{className:"fk:h-4 fk:w-4"}),jsx("span",{className:"fk:sr-only",children:"Delete"})]}),f&&D&&jsxs(e,{children:[jsx(g,{asChild:true,children:jsxs(b$1,{className:"fk:flex fk:h-7 fk:w-7 fk:p-0",variant:"ghost",children:[jsx(Ellipsis,{className:"fk:h-4 fk:w-4"}),jsx("span",{className:"fk:sr-only",children:"Additional actions"})]})}),jsxs(h,{align:"end",className:"w-[160px]",children:[jsxs(j$1,{onClick:h$1,children:[jsx(PencilIcon,{className:"fk:mr-2 fk:h-4 fk:w-4"}),"Edit"]}),jsx(o,{}),jsxs(j$1,{className:"fk:text-destructive",onClick:d,children:[jsx(Trash2Icon,{className:"fk:mr-2 fk:h-4 fk:w-4"}),"Delete"]})]})]})]})}function Z({table:e$1}){return jsxs(e,{children:[jsx(g,{asChild:true,children:jsxs(b$1,{className:"fk:hidden fk:h-8 fk:lg:flex",size:"sm",variant:"outline",children:[jsx(Settings2,{className:"fk:mr-2 fk:h-4 fk:w-4"}),"View"]})}),jsxs(h,{align:"end",className:"fk:w-[150px]",children:[jsx(n,{children:"Toggle columns"}),jsx(o,{}),e$1.getAllColumns().filter(a=>typeof a.accessorFn<"u"&&a.getCanHide()).map(a=>jsx(k,{checked:a.getIsVisible(),className:"capitalize",onCheckedChange:c=>{a.toggleVisibility(!!c);},children:a.id},a.id))]})]})}var Ce=lazy(()=>import('./record-links-2QWJFFZF.js').then(e=>({default:e.EntityKnowledgeButton}))),ve=lazy(()=>import('./entry-RMRLV3NM.js').then(e=>({default:e.EntityGraphButton})));function at({entityName:e,isReloading:a$1=false,onReload:c$2,table:i$1}){let m=j(),N=d(),p$1=c(),D=useApolloClient(),{currentProject:f$2,currentProjectId:h}=f(),d$2=f$2?.schema??[],w=f$2?.scopes,[ae,ne,le]=f$1(),[b$2,P]=useState(false),y=b(),r=i$1.getSelectedRowModel().rows.map(t=>t.original._id);function se(){m({type:"AddEntity",payload:{entityName:e}});}function ie(t){N({type:"setScope",payload:{projectId:h,scope:t}});}async function re(t){if(t.length===0)return;let u=h$1(e,d$2,t);await new Promise((pe,fe)=>{ne(gql`
|
|
2
2
|
${u}
|
|
3
|
-
`),le({variables:{where:i(t)},update(x){for(let me of t)x.evict({id:me});},onCompleted:()=>{pe();},onError:x=>{fe(x);}}),ae(true);});}function ce(){let t=e==="_asset"?"asset":e.toLowerCase();m({type:"AlertDialog",payload:{options:{dialogTitle:`Delete ${r.length} ${t}${r.length>1?"s":""}`,dialogMessage:r.length>1?`Are you sure you want to delete the selected ${t}s? They will be deleted permanently.`:`Are you sure you want to delete the selected ${t}? The item will be deleted permanently.`,dialogCancelTitle:"Cancel",dialogActionLabel:"Delete",isDestructive:true,dialogActionSubmit:async()=>{P(true);try{let u=[...r];await re(u),i$1.resetRowSelection(),await p(D,o$1(e,d$2),u),toast.success(u.length>1?"Items successfully deleted.":"Item successfully deleted.");}catch{toast.error("Failed to delete selected items.");}finally{P(false);}},dialogActionCancel:()=>{}}}});}return jsxs("div",{className:"fk:flex fk:items-center fk:justify-between",children:[jsxs("div",{className:"fk:flex fk:flex-1 fk:items-center fk:space-x-2",children:[w&&w.length>0?jsxs(a,{defaultValue:p$1.scope,onValueChange:t=>{ie(t);},value:p$1.scope,children:[jsxs(d$1,{className:"fk:w-48!",id:"project",size:"sm",children:[jsx("span",{className:"fk:text-muted-foreground",children:"Scope:"}),jsx(c$1,{children:(find(propEq(p$1.scope??"","name"))(w)||null)?.label})]}),jsx(e$1,{children:w.map(t=>jsx(g$1,{value:t.name,children:t.label},t.name))})]}):null,jsx(Z,{table:i$1}),c$2?jsx(b$1,{"aria-label":"Reload",className:"fk:h-8",disabled:b$2||a$1,onClick:c$2,size:"icon-sm",variant:"outline",children:jsx(RefreshCw,{className:a$1?"fk:animate-spin":void 0})}):null,jsx(e$2,{table:i$1})]}),r.length>0?jsx(na,{disabled:!y,children:jsxs(b$1,{className:"fk:h-8 fk:mr-2 fk:lg:flex",disabled:b$2||!y,onClick:ce,size:"sm",variant:"destructive",children:[b$2?jsx(Loader2,{className:"fk:mr-2 fk:h-4 fk:w-4 fk:animate-spin"}):jsx(Trash2,{className:"fk:mr-2 fk:h-4 fk:w-4"}),"Delete (",r.length,")"]})}):null,e&&s(e)?jsx(Suspense,{fallback:null,children:jsx(Ce,{entityName:e})}):null,e?jsx(Suspense,{fallback:null,children:jsx(ve,{entityName:e,selectedIds:r})}):null,jsx(na,{disabled:!y,children:jsx(b$1,{className:"fk:h-8 fk:lg:flex",disabled:b$2||!y,onClick:se,size:"sm",variant:"default",children:"Create"})})]})}export{Be as a,Z as b,at as c};//# sourceMappingURL=chunk-
|
|
4
|
-
//# sourceMappingURL=chunk-
|
|
3
|
+
`),le({variables:{where:i(t)},update(x){for(let me of t)x.evict({id:me});},onCompleted:()=>{pe();},onError:x=>{fe(x);}}),ae(true);});}function ce(){let t=e==="_asset"?"asset":e.toLowerCase();m({type:"AlertDialog",payload:{options:{dialogTitle:`Delete ${r.length} ${t}${r.length>1?"s":""}`,dialogMessage:r.length>1?`Are you sure you want to delete the selected ${t}s? They will be deleted permanently.`:`Are you sure you want to delete the selected ${t}? The item will be deleted permanently.`,dialogCancelTitle:"Cancel",dialogActionLabel:"Delete",isDestructive:true,dialogActionSubmit:async()=>{P(true);try{let u=[...r];await re(u),i$1.resetRowSelection(),await p(D,o$1(e,d$2),u),toast.success(u.length>1?"Items successfully deleted.":"Item successfully deleted.");}catch{toast.error("Failed to delete selected items.");}finally{P(false);}},dialogActionCancel:()=>{}}}});}return jsxs("div",{className:"fk:flex fk:items-center fk:justify-between",children:[jsxs("div",{className:"fk:flex fk:flex-1 fk:items-center fk:space-x-2",children:[w&&w.length>0?jsxs(a,{defaultValue:p$1.scope,onValueChange:t=>{ie(t);},value:p$1.scope,children:[jsxs(d$1,{className:"fk:w-48!",id:"project",size:"sm",children:[jsx("span",{className:"fk:text-muted-foreground",children:"Scope:"}),jsx(c$1,{children:(find(propEq(p$1.scope??"","name"))(w)||null)?.label})]}),jsx(e$1,{children:w.map(t=>jsx(g$1,{value:t.name,children:t.label},t.name))})]}):null,jsx(Z,{table:i$1}),c$2?jsx(b$1,{"aria-label":"Reload",className:"fk:h-8",disabled:b$2||a$1,onClick:c$2,size:"icon-sm",variant:"outline",children:jsx(RefreshCw,{className:a$1?"fk:animate-spin":void 0})}):null,jsx(e$2,{table:i$1})]}),r.length>0?jsx(na,{disabled:!y,children:jsxs(b$1,{className:"fk:h-8 fk:mr-2 fk:lg:flex",disabled:b$2||!y,onClick:ce,size:"sm",variant:"destructive",children:[b$2?jsx(Loader2,{className:"fk:mr-2 fk:h-4 fk:w-4 fk:animate-spin"}):jsx(Trash2,{className:"fk:mr-2 fk:h-4 fk:w-4"}),"Delete (",r.length,")"]})}):null,e&&s(e)?jsx(Suspense,{fallback:null,children:jsx(Ce,{entityName:e})}):null,e?jsx(Suspense,{fallback:null,children:jsx(ve,{entityName:e,selectedIds:r})}):null,jsx(na,{disabled:!y,children:jsx(b$1,{className:"fk:h-8 fk:lg:flex",disabled:b$2||!y,onClick:se,size:"sm",variant:"default",children:"Create"})})]})}export{Be as a,Z as b,at as c};//# sourceMappingURL=chunk-NO3AH2M3.js.map
|
|
4
|
+
//# sourceMappingURL=chunk-NO3AH2M3.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/data-grid/data-table-row-actions.tsx","../src/data-grid/data-table-view-options.tsx","../src/data-grid/data-table-toolbar.tsx"],"names":["DataTableRowActions","entityName","entityNamePlural","row","options","actionDispatch","useDispatch","canMutate","useCanMutate","entityId","canDelete","canEdit","handleEdit","handleDelete","jsxs","Button","jsx","PencilIcon","Trash2Icon","DropdownMenu","DropdownMenuTrigger","Ellipsis","DropdownMenuContent","DropdownMenuItem","DropdownMenuSeparator","DataTableViewOptions","table","Settings2","DropdownMenuLabel","column","DropdownMenuCheckboxItem","value","EntityKnowledgeButton","lazy","m","EntityGraphButton","DataTableToolbar","isReloading","onReload","appDispatch","useAppDispatch","appContext","useAppContext","apolloClient","useApolloClient","currentProject","currentProjectId","useConfig","schema","scopes","runMutation","setMutation","setOptions","useEntityMutation","isDeleting","setIsDeleting","useState","selectedIds","handleCreate","handleScopeChange","deleteSelected","ids","mutation","getEntityDeleteMutation","resolve","reject","gql","getEntityDeleteWhere","cache","id","error","handleBatchDelete","itemLabel","idsToDelete","scheduleEntityListRemoval","getEntityListQueryName","toast","Select","SelectTrigger","SelectValue","find","propEq","SelectContent","scopeItem","SelectItem","RefreshCw","DataTableSortedBy","PermissionTooltip","Loader2","Trash2","isKnowledgeLinkableEntity","Suspense"],"mappings":"q0BA0BO,SAASA,EAAAA,CAA2B,CACzC,UAAA,CAAAC,GAAAA,CACA,gBAAA,CAAAC,CAAAA,CACA,GAAA,CAAAC,CAAAA,CACA,OAAA,CAAAC,CAAAA,CAAU,CAAE,SAAA,CAAW,IAAA,CAAM,OAAA,CAAS,IAAK,CAC7C,CAAA,CAAiD,CAC/C,IAAMC,CAAAA,CAAiBC,CAAAA,EAAY,CAC7BC,CAAAA,CAAYC,CAAAA,EAAa,CAEzBC,CAAAA,CAAWN,CAAAA,CAAI,QAAA,CAAS,GAAA,CAGxBO,CAAAA,CAAAA,CAAaN,CAAAA,CAAQ,SAAA,EAAa,IAAA,GAASG,CAAAA,CAC3CI,CAAAA,CAAUP,CAAAA,CAAQ,OAAA,EAAW,IAAA,CAEnC,SAASQ,GAAAA,EAAmB,CAC1BP,CAAAA,CAAe,CAAE,IAAA,CAAM,YAAA,CAAc,OAAA,CAAS,CAAE,SAAAI,CAAAA,CAAU,gBAAA,CAAAP,CAAiB,CAA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C,CAAAA,CACzB,OAAA,CAASmD,GACT,IAAA,CAAK,IAAA,CACL,QAAQ,SAAA,CACT,QAAA,CAAA,QAAA,CAED,CAAA,CACF,CAAA,CAAA,CACF,CAEJ","file":"chunk-YXUEPR7K.js","sourcesContent":["'use client';\n\nimport type { JSX } from 'react';\nimport { Ellipsis, PencilIcon, Trash2Icon } from 'lucide-react';\nimport type { Row } from '@tanstack/react-table';\nimport { Button } from '../ui/primitives/button';\nimport {\n DropdownMenu,\n DropdownMenuContent,\n DropdownMenuItem,\n DropdownMenuSeparator,\n DropdownMenuTrigger,\n} from '../ui/primitives/dropdown-menu';\nimport { useDispatch } from '../entities/actions-context';\nimport { useCanMutate } from '../core/permissions';\n\ninterface DataTableRowActionsProps<TData> {\n entityName: string;\n entityNamePlural: string;\n row: Row<TData>;\n options?: {\n canDelete?: boolean;\n canEdit?: boolean;\n };\n}\n\nexport function DataTableRowActions<TData>({\n entityName,\n entityNamePlural,\n row,\n options = { canDelete: true, canEdit: true },\n}: DataTableRowActionsProps<TData>): JSX.Element {\n const actionDispatch = useDispatch();\n const canMutate = useCanMutate();\n // @ts-expect-error -- the DataGrid's original type doesn't know about the _id property\n const entityId = row.original._id;\n // Read-only roles keep the pencil (the drawer doubles as their read view)\n // but lose the delete affordance entirely.\n const canDelete = (options.canDelete ?? true) && canMutate;\n const canEdit = options.canEdit ?? true;\n\n function handleEdit(): void {\n actionDispatch({ type: 'EditEntity', payload: { entityId, entityNamePlural } });\n }\n\n function handleDelete(): void {\n actionDispatch({ type: 'DeleteEntity', payload: { entityId, entityName } });\n }\n\n return (\n <div className=\"fk:flex\">\n {canEdit && (\n <Button className=\"fk:flex fk:h-7 fk:w-7 fk:p-0 fk:mr-1\" onClick={handleEdit} variant=\"ghost\">\n <PencilIcon className=\"fk:h-4 fk:w-4\" />\n <span className=\"fk:sr-only\">Edit</span>\n </Button>\n )}\n {canDelete && !canEdit && (\n <Button className=\"fk:flex fk:h-7 fk:w-7 fk:p-0 fk:mr-1\" onClick={handleDelete} variant=\"ghost\">\n <Trash2Icon className=\"fk:h-4 fk:w-4\" />\n <span className=\"fk:sr-only\">Delete</span>\n </Button>\n )}\n {canEdit && canDelete && (\n <DropdownMenu>\n <DropdownMenuTrigger asChild>\n <Button className=\"fk:flex fk:h-7 fk:w-7 fk:p-0\" variant=\"ghost\">\n <Ellipsis className=\"fk:h-4 fk:w-4\" />\n <span className=\"fk:sr-only\">Additional actions</span>\n </Button>\n </DropdownMenuTrigger>\n <DropdownMenuContent align=\"end\" className=\"w-[160px]\">\n <DropdownMenuItem onClick={handleEdit}>\n <PencilIcon className=\"fk:mr-2 fk:h-4 fk:w-4\" />\n Edit\n </DropdownMenuItem>\n <DropdownMenuSeparator />\n <DropdownMenuItem className=\"fk:text-destructive\" onClick={handleDelete}>\n <Trash2Icon className=\"fk:mr-2 fk:h-4 fk:w-4\" />\n Delete\n </DropdownMenuItem>\n </DropdownMenuContent>\n </DropdownMenu>\n )}\n </div>\n );\n}\n","'use client';\n\nimport type { JSX } from 'react';\nimport { Settings2 } from 'lucide-react';\nimport type { Table } from '@tanstack/react-table';\nimport { Button } from '../ui/primitives/button';\nimport {\n DropdownMenu,\n DropdownMenuCheckboxItem,\n DropdownMenuContent,\n DropdownMenuLabel,\n DropdownMenuSeparator,\n DropdownMenuTrigger,\n} from '../ui/primitives/dropdown-menu';\n\ninterface DataTableViewOptionsProps<TData> {\n table: Table<TData>;\n}\n\nexport function DataTableViewOptions<TData>({ table }: DataTableViewOptionsProps<TData>): JSX.Element {\n return (\n <DropdownMenu>\n <DropdownMenuTrigger asChild>\n <Button className=\"fk:hidden fk:h-8 fk:lg:flex\" size=\"sm\" variant=\"outline\">\n <Settings2 className=\"fk:mr-2 fk:h-4 fk:w-4\" />\n View\n </Button>\n </DropdownMenuTrigger>\n <DropdownMenuContent align=\"end\" className=\"fk:w-[150px]\">\n <DropdownMenuLabel>Toggle columns</DropdownMenuLabel>\n <DropdownMenuSeparator />\n {table\n .getAllColumns()\n .filter((column) => typeof column.accessorFn !== 'undefined' && column.getCanHide())\n .map((column) => {\n return (\n <DropdownMenuCheckboxItem\n checked={column.getIsVisible()}\n className=\"capitalize\"\n key={column.id}\n onCheckedChange={(value) => {\n column.toggleVisibility(Boolean(value));\n }}\n >\n {column.id}\n </DropdownMenuCheckboxItem>\n );\n })}\n </DropdownMenuContent>\n </DropdownMenu>\n );\n}\n","'use client';\n\nimport { lazy, Suspense, useState } from 'react';\nimport type { JSX } from 'react';\nimport { find, propEq } from 'ramda';\nimport type { Table } from '@tanstack/react-table';\nimport { Loader2, RefreshCw, Trash2 } from 'lucide-react';\nimport { gql } from '@apollo/client';\nimport { useApolloClient } from '@apollo/client/react';\nimport { toast } from 'sonner';\nimport { Button } from '../ui/primitives/button';\nimport { PermissionTooltip } from '../ui/components/permission-tooltip';\nimport { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '../ui/primitives/select';\nimport { useDispatch } from '../entities/actions-context';\nimport { useAppContext, useAppDispatch } from '../core/app-context';\nimport { useCanMutate } from '../core/permissions';\nimport { useConfig } from '../core/config/config-context';\nimport { DataTableViewOptions } from './data-table-view-options';\nimport { DataTableSortedBy } from './data-table-sorted-by';\nimport { useEntityMutation } from '../graphql-client/use-entity-mutation';\nimport { getEntityDeleteMutation, getEntityDeleteWhere } from '../graphql-client/queries';\nimport { getEntityListQueryName, scheduleEntityListRemoval } from '../graphql-client/refetch-entity-lists';\nimport { isKnowledgeLinkableEntity } from '../apps/knowledge/knowledge';\n\n// Loaded on demand: the Knowledge module should only download when a list of\n// a linkable entity is in view, the way the record drawer loads its panel.\nconst EntityKnowledgeButton = lazy(() =>\n import('../apps/knowledge/record-links').then((m) => ({ default: m.EntityKnowledgeButton }))\n);\nconst EntityGraphButton = lazy(() => import('../apps/graph/entry').then((m) => ({ default: m.EntityGraphButton })));\n\ninterface DataTableToolbarProps<TData> {\n entityName: string;\n isReloading?: boolean;\n onReload?: () => void;\n table: Table<TData>;\n}\n\nexport function DataTableToolbar<TData>({\n entityName,\n isReloading = false,\n onReload,\n table,\n}: DataTableToolbarProps<TData>): JSX.Element {\n const actionDispatch = useDispatch();\n const appDispatch = useAppDispatch();\n const appContext = useAppContext();\n const apolloClient = useApolloClient();\n const { currentProject, currentProjectId } = useConfig();\n const schema = currentProject?.schema ?? [];\n const scopes = currentProject?.scopes;\n const [runMutation, setMutation, setOptions] = useEntityMutation();\n const [isDeleting, setIsDeleting] = useState(false);\n const canMutate = useCanMutate();\n\n // Collect selected entity ids from the table\n // @ts-expect-error -- the DataGrid's original type doesn't know about the _id property\n const selectedIds: string[] = table.getSelectedRowModel().rows.map((row) => row.original._id as string);\n\n function handleCreate(): void {\n actionDispatch({ type: 'AddEntity', payload: { entityName } });\n }\n\n function handleScopeChange(value: string): void {\n appDispatch({ type: 'setScope', payload: { projectId: currentProjectId, scope: value } });\n }\n\n async function deleteSelected(ids: string[]): Promise<void> {\n if (ids.length === 0) {\n return;\n }\n\n const mutation = getEntityDeleteMutation(entityName, schema, ids);\n\n await new Promise<void>((resolve, reject) => {\n setMutation(gql`\n ${mutation}\n `);\n\n setOptions({\n variables: { where: getEntityDeleteWhere(ids) },\n update(cache: { evict: (arg0: { id: string }) => void }) {\n for (const id of ids) {\n cache.evict({ id });\n }\n },\n onCompleted: () => {\n resolve();\n },\n onError: (error: Error) => {\n reject(error);\n },\n });\n\n runMutation(true);\n });\n }\n\n function handleBatchDelete(): void {\n const itemLabel = entityName === '_asset' ? 'asset' : entityName.toLowerCase();\n\n actionDispatch({\n type: 'AlertDialog',\n payload: {\n options: {\n dialogTitle: `Delete ${selectedIds.length} ${itemLabel}${selectedIds.length > 1 ? 's' : ''}`,\n dialogMessage:\n selectedIds.length > 1\n ? `Are you sure you want to delete the selected ${itemLabel}s? They will be deleted permanently.`\n : `Are you sure you want to delete the selected ${itemLabel}? The item will be deleted permanently.`,\n dialogCancelTitle: 'Cancel',\n dialogActionLabel: 'Delete',\n isDestructive: true,\n dialogActionSubmit: async () => {\n setIsDeleting(true);\n\n try {\n const idsToDelete = [...selectedIds];\n\n await deleteSelected(idsToDelete);\n\n table.resetRowSelection();\n // Drop rows immediately, then soft-refetch counts/pages.\n await scheduleEntityListRemoval(apolloClient, getEntityListQueryName(entityName, schema), idsToDelete);\n toast.success(idsToDelete.length > 1 ? 'Items successfully deleted.' : 'Item successfully deleted.');\n } catch {\n toast.error('Failed to delete selected items.');\n } finally {\n setIsDeleting(false);\n }\n },\n dialogActionCancel: () => {\n // no-op\n },\n },\n },\n });\n }\n\n return (\n <div className=\"fk:flex fk:items-center fk:justify-between\">\n <div className=\"fk:flex fk:flex-1 fk:items-center fk:space-x-2\">\n {scopes && scopes.length > 0 ? (\n <Select\n defaultValue={appContext.scope}\n onValueChange={(value) => {\n handleScopeChange(value);\n }}\n value={appContext.scope}\n >\n <SelectTrigger className=\"fk:w-48!\" id=\"project\" size=\"sm\">\n <span className=\"fk:text-muted-foreground\">Scope:</span>\n <SelectValue>\n {\n ((find(propEq(appContext.scope ?? '', 'name'))(scopes) as { name: string; label: string }) || null)\n ?.label\n }\n </SelectValue>\n </SelectTrigger>\n <SelectContent>\n {scopes.map((scopeItem) => (\n <SelectItem key={scopeItem.name} value={scopeItem.name}>\n {scopeItem.label}\n </SelectItem>\n ))}\n </SelectContent>\n </Select>\n ) : null}\n <DataTableViewOptions table={table} />\n {onReload ? (\n <Button\n aria-label=\"Reload\"\n className=\"fk:h-8\"\n disabled={isDeleting || isReloading}\n onClick={onReload}\n size=\"icon-sm\"\n variant=\"outline\"\n >\n <RefreshCw className={isReloading ? 'fk:animate-spin' : undefined} />\n </Button>\n ) : null}\n <DataTableSortedBy table={table} />\n </div>\n {selectedIds.length > 0 ? (\n <PermissionTooltip disabled={!canMutate}>\n <Button\n className=\"fk:h-8 fk:mr-2 fk:lg:flex\"\n disabled={isDeleting || !canMutate}\n onClick={handleBatchDelete}\n size=\"sm\"\n variant=\"destructive\"\n >\n {isDeleting ? (\n <Loader2 className=\"fk:mr-2 fk:h-4 fk:w-4 fk:animate-spin\" />\n ) : (\n <Trash2 className=\"fk:mr-2 fk:h-4 fk:w-4\" />\n )}\n Delete ({selectedIds.length})\n </Button>\n </PermissionTooltip>\n ) : null}\n {entityName && isKnowledgeLinkableEntity(entityName) ? (\n <Suspense fallback={null}>\n <EntityKnowledgeButton entityName={entityName} />\n </Suspense>\n ) : null}\n {entityName ? (\n <Suspense fallback={null}>\n <EntityGraphButton entityName={entityName} selectedIds={selectedIds} />\n </Suspense>\n ) : null}\n <PermissionTooltip disabled={!canMutate}>\n <Button\n className=\"fk:h-8 fk:lg:flex\"\n disabled={isDeleting || !canMutate}\n onClick={handleCreate}\n size=\"sm\"\n variant=\"default\"\n >\n Create\n </Button>\n </PermissionTooltip>\n </div>\n );\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/data-grid/data-table-row-actions.tsx","../src/data-grid/data-table-view-options.tsx","../src/data-grid/data-table-toolbar.tsx"],"names":["DataTableRowActions","entityName","entityNamePlural","row","options","actionDispatch","useDispatch","canMutate","useCanMutate","entityId","canDelete","canEdit","handleEdit","handleDelete","jsxs","Button","jsx","PencilIcon","Trash2Icon","DropdownMenu","DropdownMenuTrigger","Ellipsis","DropdownMenuContent","DropdownMenuItem","DropdownMenuSeparator","DataTableViewOptions","table","Settings2","DropdownMenuLabel","column","DropdownMenuCheckboxItem","value","EntityKnowledgeButton","lazy","m","EntityGraphButton","DataTableToolbar","isReloading","onReload","appDispatch","useAppDispatch","appContext","useAppContext","apolloClient","useApolloClient","currentProject","currentProjectId","useConfig","schema","scopes","runMutation","setMutation","setOptions","useEntityMutation","isDeleting","setIsDeleting","useState","selectedIds","handleCreate","handleScopeChange","deleteSelected","ids","mutation","getEntityDeleteMutation","resolve","reject","gql","getEntityDeleteWhere","cache","id","error","handleBatchDelete","itemLabel","idsToDelete","scheduleEntityListRemoval","getEntityListQueryName","toast","Select","SelectTrigger","SelectValue","find","propEq","SelectContent","scopeItem","SelectItem","RefreshCw","DataTableSortedBy","PermissionToo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AAA,CAAO,UAAU,uBAAA,CAAwB,CAAA,CAC1C,WACOhC,CAAAA,CAAY,MAAA,CAAO,KAC9B,CAAA,CACF,CAAA,CACE,KACHxD,CAAAA,EAAcyF,CAAAA,CAA0BzF,CAAU,CAAA,CACjDe,GAAAA,CAAC2E,SAAA,CAAS,QAAA,CAAU,IAAA,CAClB,QAAA,CAAA3E,GAAAA,CAACgB,EAAAA,CAAA,CAAsB,UAAA,CAAY/B,CAAAA,CAAY,EACjD,CAAA,CACE,IAAA,CACHA,EACCe,GAAAA,CAAC2E,QAAAA,CAAA,CAAS,QAAA,CAAU,IAAA,CAClB,SAAA3E,GAAAA,CAACmB,EAAAA,CAAA,CAAkB,UAAA,CAAYlC,CAAAA,CAAY,YAAawD,CAAAA,CAAa,CAAA,CACvE,CAAA,CACE,IAAA,CACJzC,GAAAA,CAACuE,EAAAA,CAAA,CAAkB,QAAA,CAAU,CAAChF,EAC5B,QAAA,CAAAS,GAAAA,CAACD,IAAA,CACC,SAAA,CAAU,oBACV,QAAA,CAAUuC,GAAAA,EAAc,CAAC/C,CAAAA,CACzB,OAAA,CAASmD,GACT,IAAA,CAAK,IAAA,CACL,QAAQ,SAAA,CACT,QAAA,CAAA,QAAA,CAED,CAAA,CACF,CAAA,CAAA,CACF,CAEJ","file":"chunk-NO3AH2M3.js","sourcesContent":["'use client';\n\nimport type { JSX } from 'react';\nimport { Ellipsis, PencilIcon, Trash2Icon } from 'lucide-react';\nimport type { Row } from '@tanstack/react-table';\nimport { Button } from '../ui/primitives/button';\nimport {\n DropdownMenu,\n DropdownMenuContent,\n DropdownMenuItem,\n DropdownMenuSeparator,\n DropdownMenuTrigger,\n} from '../ui/primitives/dropdown-menu';\nimport { useDispatch } from '../entities/actions-context';\nimport { useCanMutate } from '../core/permissions';\n\ninterface DataTableRowActionsProps<TData> {\n entityName: string;\n entityNamePlural: string;\n row: Row<TData>;\n options?: {\n canDelete?: boolean;\n canEdit?: boolean;\n };\n}\n\nexport function DataTableRowActions<TData>({\n entityName,\n entityNamePlural,\n row,\n options = { canDelete: true, canEdit: true },\n}: DataTableRowActionsProps<TData>): JSX.Element {\n const actionDispatch = useDispatch();\n const canMutate = useCanMutate();\n // @ts-expect-error -- the DataGrid's original type doesn't know about the _id property\n const entityId = row.original._id;\n // Read-only roles keep the pencil (the drawer doubles as their read view)\n // but lose the delete affordance entirely.\n const canDelete = (options.canDelete ?? true) && canMutate;\n const canEdit = options.canEdit ?? true;\n\n function handleEdit(): void {\n actionDispatch({ type: 'EditEntity', payload: { entityId, entityNamePlural } });\n }\n\n function handleDelete(): void {\n actionDispatch({ type: 'DeleteEntity', payload: { entityId, entityName } });\n }\n\n return (\n <div className=\"fk:flex\">\n {canEdit && (\n <Button className=\"fk:flex fk:h-7 fk:w-7 fk:p-0 fk:mr-1\" onClick={handleEdit} variant=\"ghost\">\n <PencilIcon className=\"fk:h-4 fk:w-4\" />\n <span className=\"fk:sr-only\">Edit</span>\n </Button>\n )}\n {canDelete && !canEdit && (\n <Button className=\"fk:flex fk:h-7 fk:w-7 fk:p-0 fk:mr-1\" onClick={handleDelete} variant=\"ghost\">\n <Trash2Icon className=\"fk:h-4 fk:w-4\" />\n <span className=\"fk:sr-only\">Delete</span>\n </Button>\n )}\n {canEdit && canDelete && (\n <DropdownMenu>\n <DropdownMenuTrigger asChild>\n <Button className=\"fk:flex fk:h-7 fk:w-7 fk:p-0\" variant=\"ghost\">\n <Ellipsis className=\"fk:h-4 fk:w-4\" />\n <span className=\"fk:sr-only\">Additional actions</span>\n </Button>\n </DropdownMenuTrigger>\n <DropdownMenuContent align=\"end\" className=\"w-[160px]\">\n <DropdownMenuItem onClick={handleEdit}>\n <PencilIcon className=\"fk:mr-2 fk:h-4 fk:w-4\" />\n Edit\n </DropdownMenuItem>\n <DropdownMenuSeparator />\n <DropdownMenuItem className=\"fk:text-destructive\" onClick={handleDelete}>\n <Trash2Icon className=\"fk:mr-2 fk:h-4 fk:w-4\" />\n Delete\n </DropdownMenuItem>\n </DropdownMenuContent>\n </DropdownMenu>\n )}\n </div>\n );\n}\n","'use client';\n\nimport type { JSX } from 'react';\nimport { Settings2 } from 'lucide-react';\nimport type { Table } from '@tanstack/react-table';\nimport { Button } from '../ui/primitives/button';\nimport {\n DropdownMenu,\n DropdownMenuCheckboxItem,\n DropdownMenuContent,\n DropdownMenuLabel,\n DropdownMenuSeparator,\n DropdownMenuTrigger,\n} from '../ui/primitives/dropdown-menu';\n\ninterface DataTableViewOptionsProps<TData> {\n table: Table<TData>;\n}\n\nexport function DataTableViewOptions<TData>({ table }: DataTableViewOptionsProps<TData>): JSX.Element {\n return (\n <DropdownMenu>\n <DropdownMenuTrigger asChild>\n <Button className=\"fk:hidden fk:h-8 fk:lg:flex\" size=\"sm\" variant=\"outline\">\n <Settings2 className=\"fk:mr-2 fk:h-4 fk:w-4\" />\n View\n </Button>\n </DropdownMenuTrigger>\n <DropdownMenuContent align=\"end\" className=\"fk:w-[150px]\">\n <DropdownMenuLabel>Toggle columns</DropdownMenuLabel>\n <DropdownMenuSeparator />\n {table\n .getAllColumns()\n .filter((column) => typeof column.accessorFn !== 'undefined' && column.getCanHide())\n .map((column) => {\n return (\n <DropdownMenuCheckboxItem\n checked={column.getIsVisible()}\n className=\"capitalize\"\n key={column.id}\n onCheckedChange={(value) => {\n column.toggleVisibility(Boolean(value));\n }}\n >\n {column.id}\n </DropdownMenuCheckboxItem>\n );\n })}\n </DropdownMenuContent>\n </DropdownMenu>\n );\n}\n","'use client';\n\nimport { lazy, Suspense, useState } from 'react';\nimport type { JSX } from 'react';\nimport { find, propEq } from 'ramda';\nimport type { Table } from '@tanstack/react-table';\nimport { Loader2, RefreshCw, Trash2 } from 'lucide-react';\nimport { gql } from '@apollo/client';\nimport { useApolloClient } from '@apollo/client/react';\nimport { toast } from 'sonner';\nimport { Button } from '../ui/primitives/button';\nimport { PermissionTooltip } from '../ui/components/permission-tooltip';\nimport { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '../ui/primitives/select';\nimport { useDispatch } from '../entities/actions-context';\nimport { useAppContext, useAppDispatch } from '../core/app-context';\nimport { useCanMutate } from '../core/permissions';\nimport { useConfig } from '../core/config/config-context';\nimport { DataTableViewOptions } from './data-table-view-options';\nimport { DataTableSortedBy } from './data-table-sorted-by';\nimport { useEntityMutation } from '../graphql-client/use-entity-mutation';\nimport { getEntityDeleteMutation, getEntityDeleteWhere } from '../graphql-client/queries';\nimport { getEntityListQueryName, scheduleEntityListRemoval } from '../graphql-client/refetch-entity-lists';\nimport { isKnowledgeLinkableEntity } from '../apps/knowledge/knowledge';\n\n// Loaded on demand: the Knowledge module should only download when a list of\n// a linkable entity is in view, the way the record drawer loads its panel.\nconst EntityKnowledgeButton = lazy(() =>\n import('../apps/knowledge/record-links').then((m) => ({ default: m.EntityKnowledgeButton }))\n);\nconst EntityGraphButton = lazy(() => import('../apps/graph/entry').then((m) => ({ default: m.EntityGraphButton })));\n\ninterface DataTableToolbarProps<TData> {\n entityName: string;\n isReloading?: boolean;\n onReload?: () => void;\n table: Table<TData>;\n}\n\nexport function DataTableToolbar<TData>({\n entityName,\n isReloading = false,\n onReload,\n table,\n}: DataTableToolbarProps<TData>): JSX.Element {\n const actionDispatch = useDispatch();\n const appDispatch = useAppDispatch();\n const appContext = useAppContext();\n const apolloClient = useApolloClient();\n const { currentProject, currentProjectId } = useConfig();\n const schema = currentProject?.schema ?? [];\n const scopes = currentProject?.scopes;\n const [runMutation, setMutation, setOptions] = useEntityMutation();\n const [isDeleting, setIsDeleting] = useState(false);\n const canMutate = useCanMutate();\n\n // Collect selected entity ids from the table\n // @ts-expect-error -- the DataGrid's original type doesn't know about the _id property\n const selectedIds: string[] = table.getSelectedRowModel().rows.map((row) => row.original._id as string);\n\n function handleCreate(): void {\n actionDispatch({ type: 'AddEntity', payload: { entityName } });\n }\n\n function handleScopeChange(value: string): void {\n appDispatch({ type: 'setScope', payload: { projectId: currentProjectId, scope: value } });\n }\n\n async function deleteSelected(ids: string[]): Promise<void> {\n if (ids.length === 0) {\n return;\n }\n\n const mutation = getEntityDeleteMutation(entityName, schema, ids);\n\n await new Promise<void>((resolve, reject) => {\n setMutation(gql`\n ${mutation}\n `);\n\n setOptions({\n variables: { where: getEntityDeleteWhere(ids) },\n update(cache: { evict: (arg0: { id: string }) => void }) {\n for (const id of ids) {\n cache.evict({ id });\n }\n },\n onCompleted: () => {\n resolve();\n },\n onError: (error: Error) => {\n reject(error);\n },\n });\n\n runMutation(true);\n });\n }\n\n function handleBatchDelete(): void {\n const itemLabel = entityName === '_asset' ? 'asset' : entityName.toLowerCase();\n\n actionDispatch({\n type: 'AlertDialog',\n payload: {\n options: {\n dialogTitle: `Delete ${selectedIds.length} ${itemLabel}${selectedIds.length > 1 ? 's' : ''}`,\n dialogMessage:\n selectedIds.length > 1\n ? `Are you sure you want to delete the selected ${itemLabel}s? They will be deleted permanently.`\n : `Are you sure you want to delete the selected ${itemLabel}? The item will be deleted permanently.`,\n dialogCancelTitle: 'Cancel',\n dialogActionLabel: 'Delete',\n isDestructive: true,\n dialogActionSubmit: async () => {\n setIsDeleting(true);\n\n try {\n const idsToDelete = [...selectedIds];\n\n await deleteSelected(idsToDelete);\n\n table.resetRowSelection();\n // Drop rows immediately, then soft-refetch counts/pages.\n await scheduleEntityListRemoval(apolloClient, getEntityListQueryName(entityName, schema), idsToDelete);\n toast.success(idsToDelete.length > 1 ? 'Items successfully deleted.' : 'Item successfully deleted.');\n } catch {\n toast.error('Failed to delete selected items.');\n } finally {\n setIsDeleting(false);\n }\n },\n dialogActionCancel: () => {\n // no-op\n },\n },\n },\n });\n }\n\n return (\n <div className=\"fk:flex fk:items-center fk:justify-between\">\n <div className=\"fk:flex fk:flex-1 fk:items-center fk:space-x-2\">\n {scopes && scopes.length > 0 ? (\n <Select\n defaultValue={appContext.scope}\n onValueChange={(value) => {\n handleScopeChange(value);\n }}\n value={appContext.scope}\n >\n <SelectTrigger className=\"fk:w-48!\" id=\"project\" size=\"sm\">\n <span className=\"fk:text-muted-foreground\">Scope:</span>\n <SelectValue>\n {\n ((find(propEq(appContext.scope ?? '', 'name'))(scopes) as { name: string; label: string }) || null)\n ?.label\n }\n </SelectValue>\n </SelectTrigger>\n <SelectContent>\n {scopes.map((scopeItem) => (\n <SelectItem key={scopeItem.name} value={scopeItem.name}>\n {scopeItem.label}\n </SelectItem>\n ))}\n </SelectContent>\n </Select>\n ) : null}\n <DataTableViewOptions table={table} />\n {onReload ? (\n <Button\n aria-label=\"Reload\"\n className=\"fk:h-8\"\n disabled={isDeleting || isReloading}\n onClick={onReload}\n size=\"icon-sm\"\n variant=\"outline\"\n >\n <RefreshCw className={isReloading ? 'fk:animate-spin' : undefined} />\n </Button>\n ) : null}\n <DataTableSortedBy table={table} />\n </div>\n {selectedIds.length > 0 ? (\n <PermissionTooltip disabled={!canMutate}>\n <Button\n className=\"fk:h-8 fk:mr-2 fk:lg:flex\"\n disabled={isDeleting || !canMutate}\n onClick={handleBatchDelete}\n size=\"sm\"\n variant=\"destructive\"\n >\n {isDeleting ? (\n <Loader2 className=\"fk:mr-2 fk:h-4 fk:w-4 fk:animate-spin\" />\n ) : (\n <Trash2 className=\"fk:mr-2 fk:h-4 fk:w-4\" />\n )}\n Delete ({selectedIds.length})\n </Button>\n </PermissionTooltip>\n ) : null}\n {entityName && isKnowledgeLinkableEntity(entityName) ? (\n <Suspense fallback={null}>\n <EntityKnowledgeButton entityName={entityName} />\n </Suspense>\n ) : null}\n {entityName ? (\n <Suspense fallback={null}>\n <EntityGraphButton entityName={entityName} selectedIds={selectedIds} />\n </Suspense>\n ) : null}\n <PermissionTooltip disabled={!canMutate}>\n <Button\n className=\"fk:h-8 fk:lg:flex\"\n disabled={isDeleting || !canMutate}\n onClick={handleCreate}\n size=\"sm\"\n variant=\"default\"\n >\n Create\n </Button>\n </PermissionTooltip>\n </div>\n );\n}\n"]}
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import'./index.css';import {g,d as d$1}from'./chunk-
|
|
2
|
-
export{x as a,d as b,f as c,Fe as d,Xe as e,qe as f};//# sourceMappingURL=chunk-
|
|
3
|
-
//# sourceMappingURL=chunk-
|
|
1
|
+
import'./index.css';import {g,d as d$1}from'./chunk-WPCPL2TQ.js';import {b as b$1}from'./chunk-U45E5X3H.js';import {createContext,lazy,Suspense,useMemo,useContext}from'react';import {Navigate,useParams}from'react-router-dom';import {Bot,Layout,FileStack,BookOpenText,Waypoints,SquarePlay}from'lucide-react';import {jsx,jsxs}from'react/jsx-runtime';import w,{mutate}from'swr';var d={name:"_asset",plural:"_assets",display:"originalFilename",menu:{hidden:true},attributes:[{name:"path",label:"Asset",scope:"global",options:{size:140},dataType:"string",inputType:"text",previewType:"assetPreviewField",defaultValue:""},{name:"originalFilename",label:"Filename",scope:"global",options:{size:320},dataType:"string",inputType:"text",previewType:"text",defaultValue:""},{name:"size",label:"Size",scope:"global",options:{size:120},dataType:"int",inputType:"text",previewType:"text",defaultValue:""},{name:"width",label:"Width",scope:"global",options:{size:90},dataType:"int",inputType:"text",previewType:"text",defaultValue:""},{name:"height",label:"Height",scope:"global",options:{size:100},dataType:"int",inputType:"text",previewType:"text",defaultValue:""},{name:"mimeType",label:"Mime Type",scope:"global",options:{size:160},dataType:"string",inputType:"text",previewType:"text",defaultValue:""},{name:"lqip",label:"lqip",scope:"global",hidden:true,dataType:"string",inputType:"text",previewType:"text",defaultValue:""},{name:"url",label:"URL",scope:"global",hidden:true,readOnly:true,dataType:"string",inputType:"text",previewType:"text",defaultValue:""},{name:"_updatedAt",label:"Updated At",scope:"global",options:{size:220},readOnly:true,hidden:true,dataType:"datetime",inputType:"datetime",previewType:"datetime",defaultValue:""},{name:"tags",label:"Tags",scope:"relationship",dataType:"string",inputType:"relationship",defaultValue:"",previewType:"tags",options:{size:300},relationship:{mode:"multiple",field:"name",entity:"_tag"}}]};var f={name:"_tag",plural:"_tags",display:"name",menu:{hidden:true},attributes:[{name:"name",label:"Tag Name",scope:"global",options:{size:220},dataType:"string",inputType:"text",previewType:"text",defaultValue:""},{name:"_updatedAt",label:"Updated At",scope:"global",options:{size:220},readOnly:true,hidden:true,dataType:"datetime",inputType:"datetime",previewType:"datetime",defaultValue:""},{name:"assets",label:"Assets",scope:"relationship",dataType:"string",inputType:"relationship",defaultValue:"",relationship:{mode:"multiple",field:"originalFilename",entity:"_asset"}}]};function x(){let{resolvedTheme:e}=b$1();return jsx("div",{className:"fk:flex fk:w-full fk:h-full fk:justify-center fk:items-center fk:bg-background",children:jsxs("div",{className:"fk:flex fk:flex-col fk:items-center",children:[e==="dark"?jsxs("svg",{className:"fk:h-8 fk:w-8 fk:animate-bounce",fill:"none",viewBox:"0 0 48 48",xmlns:"http://www.w3.org/2000/svg",children:[jsx("path",{d:"M7 8H41V40H7V8Z",fill:"#020817"}),jsx("path",{d:"M24 0C42 0 48 6 48 24C48 42 42 48 24 48C6 48 0 42 0 24C0 6 6 0 24 0ZM17.7494 9.52381H8.7619L19.2833 23.8313L8.7619 38.7078H17.7494L21.0499 33.6639V14.2549L17.7494 9.52381ZM38.9577 9.52381H29.9542L26.2857 14.8229V33.0406L29.9542 38.7078H38.9577L28.3908 23.8313L38.9577 9.52381Z",fill:"white"})]}):jsxs("svg",{className:"fk:h-8 fk:w-8 fk:animate-bounce",fill:"none",viewBox:"0 0 48 48",xmlns:"http://www.w3.org/2000/svg",children:[jsx("path",{d:"M7 8H41V40H7V8Z",fill:"white"}),jsx("path",{d:"M24 0C42 0 48 6 48 24C48 42 42 48 24 48C6 48 0 42 0 24C0 6 6 0 24 0ZM17.7494 9.52381H8.7619L19.2833 23.8313L8.7619 38.7078H17.7494L21.0499 33.6639V14.2549L17.7494 9.52381ZM38.9577 9.52381H29.9542L26.2857 14.8229V33.0406L29.9542 38.7078H38.9577L28.3908 23.8313L38.9577 9.52381Z",fill:"#020817"})]}),jsx("div",{className:"fk:text-foreground fk:text-center fk:mt-4 fk:animate-pulse",children:"Loading..."})]})})}var _=Navigate;function o(e){let t=lazy(e);return jsx(Suspense,{fallback:jsx(x,{}),children:jsx(t,{})})}var J=o(()=>import('./root-GAB2SFFF.js').then(e=>({default:e.Root}))),X=o(()=>import('./list-GVATECOW.js').then(e=>({default:e.List}))),q=o(()=>import('./edit-entity-PVT34FD7.js').then(e=>({default:e.EditEntity}))),K=o(()=>import('./root-JWXXF653.js').then(e=>({default:e.Root}))),G=o(()=>import('./root-ZCXGZCUT.js').then(e=>({default:e.Root}))),$=o(()=>import('./list-HR55TZQX.js').then(e=>({default:e.List}))),Q=o(()=>import('./source-3YZNNITL.js').then(e=>({default:e.Source}))),Y=o(()=>import('./root-E35GZ7SV.js').then(e=>({default:e.Root}))),ee=o(()=>import('./root-54BI6S4V.js').then(e=>({default:e.Root}))),te=o(()=>import('./root-U52KZQSD.js').then(e=>({default:e.Root}))),oe=o(()=>import('./plugin-pages-BS2IMNRU.js').then(e=>({default:e.PluginsPage}))),ne=o(()=>import('./plugin-pages-BS2IMNRU.js').then(e=>({default:e.InstalledPluginsPage}))),ae=o(()=>import('./plugin-pages-BS2IMNRU.js').then(e=>({default:e.PluginDetailPage}))),T=o(()=>import('./chat-page-A7FG7WTN.js').then(e=>({default:e.AgentChatPage}))),ie=o(()=>import('./pages-OJYYLSI3.js').then(e=>({default:e.AutomationsPage}))),re=o(()=>import('./pages-OJYYLSI3.js').then(e=>({default:e.RunHistoryPage}))),se=o(()=>import('./pages-OJYYLSI3.js').then(e=>({default:e.ApprovalsPage}))),pe=o(()=>import('./pages-OJYYLSI3.js').then(e=>({default:e.ActivityPage}))),ce=o(()=>import('./pages-OJYYLSI3.js').then(e=>({default:e.ActivityItemPage}))),le=o(()=>import('./pages-OJYYLSI3.js').then(e=>({default:e.CreateAutomationPage}))),me=o(()=>import('./pages-OJYYLSI3.js').then(e=>({default:e.AutomationDetailPage}))),ue=o(()=>import('./pages-OJYYLSI3.js').then(e=>({default:e.RunsPage}))),de=o(()=>import('./pages-OJYYLSI3.js').then(e=>({default:e.RunDetailPage}))),fe=o(()=>import('./skills-pages-MA6JLBB4.js').then(e=>({default:e.SkillsPage}))),ge=o(()=>import('./skills-pages-MA6JLBB4.js').then(e=>({default:e.CreateSkillPage}))),he=o(()=>import('./skills-pages-MA6JLBB4.js').then(e=>({default:e.SkillDetailPage}))),l=[{name:"ai",icon:jsx(Bot,{strokeWidth:1.5}),title:"AI",component:te,routes:[{path:"plugins",component:oe},{path:"plugins/installed",component:ne},{path:"plugins/:pluginId",component:ae},{component:jsx(_,{replace:true,to:"agent"}),path:""},{component:T,path:"agent"},{component:T,path:"agent/chats/:chatId"},{component:ie,path:"automations"},{component:re,path:"runs"},{component:se,path:"approvals"},{component:pe,path:"activity"},{component:ce,path:"activity/:itemId"},{component:le,path:"automations/new"},{component:me,path:"automations/:automationId"},{component:ue,path:"automations/:automationId/runs"},{component:de,path:"automations/:automationId/runs/:runId"},{component:fe,path:"skills"},{component:ge,path:"skills/new"},{component:he,path:"skills/:skillId"}]},{name:"desk",icon:jsx(Layout,{strokeWidth:1.5}),title:"Desk",component:J,routes:[{path:"list/:entity",component:X,children:[{path:"edit/:id",component:q}]}]},{name:"asset-manager",icon:jsx(FileStack,{strokeWidth:1.5}),title:"Asset Manager",component:K,routes:[]},{name:"knowledge",icon:jsx(BookOpenText,{strokeWidth:1.5}),title:"Knowledge",component:G,routes:[{component:$,path:""},{component:Q,path:":sourceId"}]},{name:"graph",icon:jsx(Waypoints,{strokeWidth:1.5}),title:"Graph",component:Y,routes:[]},{name:"explorer",icon:jsx(SquarePlay,{strokeWidth:1.5}),title:"Explorer",component:ee,routes:[]}];async function C(e){try{let t=await fetch(d$1(e).schema,{credentials:"include",mode:"cors"});if(!t.ok){let a=t.statusText||`Request failed with status ${String(t.status)}`;try{let i=await t.json();a=i.error??i.message??a;}catch{}return {ok:!1,projectId:e,error:{status:t.status,message:a}}}let n=await t.json();return {ok:!0,project:{...n,projectId:n.projectId||e}}}catch(t){return {ok:false,projectId:e,error:{status:0,message:t instanceof Error?t.message:"Network error"}}}}function b(e,t){let n=[],a={};for(let i of e??[])i.ok?n.push(i.project):a[i.projectId]=i.error;return {projects:n,errors:a,isLoading:t}}function L(e,t){let n=t&&e.length>0?["project-schemas",t,...e]:null,{data:a,isLoading:i}=w(n,()=>Promise.all(e.map(p=>C(p))),{revalidateOnFocus:false,revalidateOnReconnect:false});return b(a,!!n&&(i||a===void 0))}function Pe(e,t){return b(e?[e]:void 0,t)}function A(e,t){let n=t&&e?["project-schema",t,e]:null,{data:a,isLoading:i}=w(n,()=>C(e??""),{revalidateOnFocus:false,revalidateOnReconnect:false});return Pe(a,!!n&&(i||a===void 0))}function Se(e,t){return Array.isArray(e)&&(e[0]==="project-schema"||e[0]==="project-schemas")&&e.slice(2).includes(t)}function Fe(e){return mutate(t=>Se(t,e))}var R=createContext({mode:"projects",apps:l,contributions:{apps:l},currentProjectId:void 0,currentProject:void 0,currentProjectSchema:[],projects:[],projectIds:[],projectSummaries:[],schemaErrors:{},isLoadingSchemas:false});function xe(e){return [...e.filter(n=>n.name!==d.name&&n.name!==f.name),d,f]}function Xe({projectIds:e,projectSummaries:t=[],mode:n="projects",userId:a,children:i}){let{projectId:p}=useParams(),[,I]=g(),h=I.user?.id??a,V=L(n==="projects"?e:[],h),O=A(n==="hosted"&&p&&e.includes(p)?p:void 0,h),{projects:y,errors:P,isLoading:S}=n==="hosted"?O:V,m=useMemo(()=>e.map(s=>y.find(u=>u.projectId===s)).filter(s=>s!==void 0).map(s=>({...s,schema:xe(s.schema)})),[y,e]),H=useMemo(()=>{let s=m.find(u=>u.projectId===p);return {mode:n,apps:l,contributions:{apps:l},currentProjectId:p,currentProject:s,currentProjectSchema:s?.schema??[],projects:m,projectIds:e,projectSummaries:t,schemaErrors:P,isLoadingSchemas:S}},[p,P,S,n,e,t,m]);return jsx(R.Provider,{value:H,children:i})}function qe(){return useContext(R)}
|
|
2
|
+
export{x as a,d as b,f as c,Fe as d,Xe as e,qe as f};//# sourceMappingURL=chunk-NSVX6HEN.js.map
|
|
3
|
+
//# sourceMappingURL=chunk-NSVX6HEN.js.map
|