refactor: extract core service domain layer to @shumai/core

This commit is contained in:
yiling
2026-06-01 23:16:22 +08:00
parent 2362a7f373
commit cb80822637
163 changed files with 328 additions and 67608 deletions
+2 -2
View File
@@ -1,10 +1,10 @@
import { prisma } from '@shumai/db'
import { setupTestDbHooks } from '@shumai/db'
import { s3Service } from '@/services/s3/s3'
import { s3Service } from '@shumai/core/src/s3/s3'
import { type SessionTreeEntry } from '@earendil-works/pi-agent-core'
import { describe, expect, it, vi } from 'vitest'
import { DatabaseSessionStorage } from './database-session-storage'
import { agentService } from '@/services/agent/agent'
import { agentService } from '@shumai/core/src/agent/agent'
import { createAgentSession } from './index'
import * as sandboxedBashModule from './tools/sandboxed-bash'
+2 -2
View File
@@ -1,5 +1,5 @@
import { prisma } from '@shumai/db'
import { s3Service } from '@/services/s3/s3'
import { s3Service } from '@shumai/core/src/s3/s3'
import { ulid } from 'ulid'
import {
type AgentMessage,
@@ -8,7 +8,7 @@ import {
type SessionTreeEntry,
type SessionTreeEntryBase,
} from '@earendil-works/pi-agent-core'
import { agentService } from '@/services/agent/agent'
import { agentService } from '@shumai/core/src/agent/agent'
export interface DatabaseSessionMetadata extends SessionMetadata {
agentId: string
+1 -1
View File
@@ -5,7 +5,7 @@ import { getModel } from '@earendil-works/pi-ai'
import { Type, type TSchema } from '@sinclair/typebox'
import * as fs from 'fs'
import * as path from 'path'
import { agentService } from '@/services/agent/agent'
import { agentService } from '@shumai/core/src/agent/agent'
import { DatabaseSessionStorage } from './database-session-storage'
import { analyzeAssetMediaTool } from './tools/analyze-asset-media'
import { createCreateFileTool } from './tools/create-file'
+2 -2
View File
@@ -1,8 +1,8 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { analyzeAssetMediaTool } from './analyze-asset-media'
import { s3Service } from '@/services/s3/s3'
import { s3Service } from '@shumai/core/src/s3/s3'
vi.mock('@/services/s3/s3')
vi.mock('@shumai/core/src/s3/s3')
describe('analyzeAssetMediaTool', () => {
beforeEach(() => {
+1 -1
View File
@@ -1,4 +1,4 @@
import { s3Service } from '@/services/s3/s3'
import { s3Service } from '@shumai/core/src/s3/s3'
import { Type } from '@sinclair/typebox'
import { type AgentTool } from '@earendil-works/pi-agent-core'
import { type ImageContent, type TextContent } from '@earendil-works/pi-ai'
+1 -1
View File
@@ -3,7 +3,7 @@ import { type AgentTool } from '@earendil-works/pi-agent-core'
import { executeAgentToolWorkflow } from './utils'
import * as fs from 'fs'
import * as path from 'path'
import { s3Service } from '@/services/s3/s3'
import { s3Service } from '@shumai/core/src/s3/s3'
import { detectSupportedMimeType } from '@/utils/mime'
import { ulid } from 'ulid'
+1 -1
View File
@@ -3,7 +3,7 @@ import { type AgentTool } from '@earendil-works/pi-agent-core'
import { executeAgentToolWorkflow } from './utils'
import * as fs from 'fs'
import * as path from 'path'
import { s3Service } from '@/services/s3/s3'
import { s3Service } from '@shumai/core/src/s3/s3'
import { detectSupportedMimeType } from '@/utils/mime'
import { ulid } from 'ulid'
+2 -2
View File
@@ -2,10 +2,10 @@ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
import { prisma } from '@shumai/db'
import { setupTestDbHooks } from '@shumai/db'
import { createReadSkillTool } from './read-skill'
import { s3Service } from '@/services/s3/s3'
import { s3Service } from '@shumai/core/src/s3/s3'
import * as fs from 'fs'
vi.mock('@/services/s3/s3')
vi.mock('@shumai/core/src/s3/s3')
vi.mock('fs')
vi.mock('adm-zip', () => {
return {
+1 -1
View File
@@ -1,7 +1,7 @@
import { prisma } from '@shumai/db'
import { Type } from '@sinclair/typebox'
import { type AgentTool } from '@earendil-works/pi-agent-core'
import { agentService } from '@/services/agent/agent'
import { agentService } from '@shumai/core/src/agent/agent'
const readSkillSchema = Type.Object({
skillId: Type.String({ description: 'The ID of the skill to read' }),
+1 -1
View File
@@ -1,6 +1,6 @@
import { prisma } from '@shumai/db'
import { workflowService } from '@/workflow/workflow'
import { WorkflowTaskType, WorkflowTaskStatus } from '@/generated/prisma/client'
import { WorkflowTaskType, WorkflowTaskStatus } from '@shumai/db'
export async function executeAgentToolWorkflow(params: {
toolName: string
+4 -4
View File
@@ -1,10 +1,10 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { agentService } from '@/services/agent/agent'
import { authzService } from '@/services/authz/authz'
import { agentService } from '@shumai/core/src/agent/agent'
import { authzService } from '@shumai/core/src/authz/authz'
import app from './agent'
vi.mock('@/services/agent/agent')
vi.mock('@/services/authz/authz')
vi.mock('@shumai/core/src/agent/agent')
vi.mock('@shumai/core/src/authz/authz')
describe('Agent API', () => {
beforeEach(() => {
+3 -3
View File
@@ -1,7 +1,7 @@
import { Hono } from 'hono'
import { zValidator } from '@hono/zod-validator'
import { agentService } from '@/services/agent/agent'
import { authzService, Permission, ResourceType } from '@/services/authz/authz'
import { agentService } from '@shumai/core/src/agent/agent'
import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/authz'
import {
createAgentRequestSchema,
updateAgentRequestSchema,
@@ -9,7 +9,7 @@ import {
AgentType,
} from '@shumai/dtos'
import type { Prisma } from '@/generated/prisma/client'
import type { Prisma } from '@shumai/db'
type User = Prisma.UserGetPayload<Record<string, never>>
+6 -6
View File
@@ -1,10 +1,10 @@
import { describe, expect, it, vi, beforeEach } from 'vitest'
import { Hono } from 'hono'
import attachmentRoute from './attachment'
import { assetService } from '@/services/asset/asset'
import { AssetType } from '@/generated/prisma/client'
import { assetService } from '@shumai/core/src/asset/asset'
import { AssetType } from '@shumai/db'
import { authMiddleware } from '@/api/middleware/auth'
import { authzService, Permission, ResourceType } from '@/services/authz/authz'
import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/authz'
vi.mock('@/api/middleware/auth', () => ({
// any is used here because Hono's Context and Next types are complex to mock in vitest.mock
@@ -16,10 +16,10 @@ vi.mock('@/api/middleware/auth', () => ({
},
}))
vi.mock('@/services/authz/authz')
vi.mock('@/services/asset/asset')
vi.mock('@shumai/core/src/authz/authz')
vi.mock('@shumai/core/src/asset/asset')
vi.mock('@/services/s3/s3', () => ({
vi.mock('@shumai/core/src/s3/s3', () => ({
s3Service: {
presign: vi.fn().mockResolvedValue('http://mock-s3-url'),
},
+5 -5
View File
@@ -1,12 +1,12 @@
import { Hono } from 'hono'
import { zValidator } from '@hono/zod-validator'
import { postAttachmentRequestSchema } from '@shumai/dtos'
import { assetService } from '@/services/asset/asset'
import { s3Service } from '@/services/s3/s3'
import { AssetType } from '@/generated/prisma/client'
import { assetService } from '@shumai/core/src/asset/asset'
import { s3Service } from '@shumai/core/src/s3/s3'
import { AssetType } from '@shumai/db'
import { ulid } from 'ulid'
import { authzService, Permission, ResourceType } from '@/services/authz/authz'
import type { Prisma } from '@/generated/prisma/client'
import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/authz'
import type { Prisma } from '@shumai/db'
type User = Prisma.UserGetPayload<Record<string, never>>
+1 -1
View File
@@ -1,7 +1,7 @@
import { describe, expect, it, vi, beforeEach, afterEach } from 'vitest'
import { Hono } from 'hono'
import authnRoute from './authn'
import { teamService } from '@/services/team/team'
import { teamService } from '@shumai/core/src/team/team'
describe('authn api', () => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
+2 -2
View File
@@ -1,6 +1,6 @@
import { Hono } from 'hono'
import { teamService } from '@/services/team/team'
import { auth } from '@/services/auth/auth'
import { teamService } from '@shumai/core/src/team/team'
import { auth } from '@shumai/core/src/auth/auth'
import { z } from 'zod'
import { zValidator } from '@hono/zod-validator'
import { prisma } from '@shumai/db'
+3 -3
View File
@@ -1,6 +1,6 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { collectionService } from '@/services/collection/collection'
import { authzService, Permission, ResourceType } from '@/services/authz/authz'
import { collectionService } from '@shumai/core/src/collection/collection'
import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/authz'
import { Hono, Context, Next } from 'hono'
import collectionRoute from './collection'
@@ -11,7 +11,7 @@ vi.mock('@/api/middleware/auth', () => ({
},
}))
vi.mock('@/services/authz/authz', () => ({
vi.mock('@shumai/core/src/authz/authz', () => ({
authzService: {
hasPermission: vi.fn().mockResolvedValue(undefined),
},
+3 -3
View File
@@ -1,7 +1,7 @@
import { zValidator } from '@hono/zod-validator'
import { Hono } from 'hono'
import { collectionService } from '@/services/collection/collection'
import { authzService, Permission, ResourceType } from '@/services/authz/authz'
import { collectionService } from '@shumai/core/src/collection/collection'
import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/authz'
import {
createCollectionRequestSchema,
updateCollectionRequestSchema,
@@ -9,7 +9,7 @@ import {
CollectionInfo,
CollectionFilter,
} from '@shumai/dtos'
import type { Prisma } from '@/generated/prisma/client'
import type { Prisma } from '@shumai/db'
type User = Prisma.UserGetPayload<Record<string, never>>
+6 -6
View File
@@ -2,14 +2,14 @@ import { describe, expect, it, vi, beforeEach, afterEach } from 'vitest'
import { Hono, type Context, type Next } from 'hono'
import { prisma } from '@shumai/db'
import fileRoute from './file'
import { assetService } from '@/services/asset/asset'
import { metadataService } from '@/services/metadata/metadata'
import { notificationService } from '@/services/notification/notification'
import { s3Service } from '@/services/s3/s3'
import { assetService } from '@shumai/core/src/asset/asset'
import { metadataService } from '@shumai/core/src/metadata/metadata'
import { notificationService } from '@shumai/core/src/notification/notification'
import { s3Service } from '@shumai/core/src/s3/s3'
import { authMiddleware } from '@/api/middleware/auth'
import { authzService, ResourceType, Permission } from '@/services/authz/authz'
import { authzService, ResourceType, Permission } from '@shumai/core/src/authz/authz'
vi.mock('@/services/authz/authz', () => ({
vi.mock('@shumai/core/src/authz/authz', () => ({
authzService: {
hasPermission: vi.fn().mockResolvedValue(undefined),
},
+6 -6
View File
@@ -1,11 +1,11 @@
import { Hono } from 'hono'
import { zValidator } from '@hono/zod-validator'
import { prisma } from '@shumai/db'
import { authzService, Permission, ResourceType } from '@/services/authz/authz'
import { assetService } from '@/services/asset/asset'
import { metadataService } from '@/services/metadata/metadata'
import { notificationService } from '@/services/notification/notification'
import { s3Service } from '@/services/s3/s3'
import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/authz'
import { assetService } from '@shumai/core/src/asset/asset'
import { metadataService } from '@shumai/core/src/metadata/metadata'
import { notificationService } from '@shumai/core/src/notification/notification'
import { s3Service } from '@shumai/core/src/s3/s3'
import {
updateFileRequestSchema,
updateAssetOrderRequestSchema,
@@ -18,7 +18,7 @@ import { updateAssetMetadataRequestSchema } from '@shumai/dtos'
import { paginationParamsSchema } from '@shumai/dtos'
import { ulid } from 'ulid'
import { z } from 'zod'
import type { Prisma } from '@/generated/prisma/client'
import type { Prisma } from '@shumai/db'
type User = Prisma.UserGetPayload<Record<string, never>>
+4 -4
View File
@@ -1,12 +1,12 @@
import { describe, expect, it, vi, beforeEach, afterEach } from 'vitest'
import { Hono } from 'hono'
import folderRoute from './folder'
import { assetService } from '@/services/asset/asset'
import { searchService } from '@/services/search/search'
import { authzService, ResourceType, Permission } from '@/services/authz/authz'
import { assetService } from '@shumai/core/src/asset/asset'
import { searchService } from '@shumai/core/src/search/search'
import { authzService, ResourceType, Permission } from '@shumai/core/src/authz/authz'
import { authMiddleware } from '@/api/middleware/auth'
vi.mock('@/services/authz/authz', () => ({
vi.mock('@shumai/core/src/authz/authz', () => ({
authzService: {
hasPermission: vi.fn().mockResolvedValue(undefined),
},
+4 -4
View File
@@ -1,8 +1,8 @@
import { Hono } from 'hono'
import { zValidator } from '@hono/zod-validator'
import { authzService, Permission, ResourceType } from '@/services/authz/authz'
import { assetService } from '@/services/asset/asset'
import { searchService } from '@/services/search/search'
import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/authz'
import { assetService } from '@shumai/core/src/asset/asset'
import { searchService } from '@shumai/core/src/search/search'
import {
createFolderRequestSchema,
updateFolderRequestSchema,
@@ -11,7 +11,7 @@ import {
} from '@shumai/dtos'
import { listChildrenRequestSchema, updateAssetOrderRequestSchema } from '@shumai/dtos'
import { searchRequestSchema } from '@shumai/dtos'
import type { Prisma } from '@/generated/prisma/client'
import type { Prisma } from '@shumai/db'
type User = Prisma.UserGetPayload<Record<string, never>>
+6 -6
View File
@@ -2,13 +2,13 @@ import { describe, expect, it, vi, beforeEach } from 'vitest'
import { Hono, type Context, type Next } from 'hono'
import inviteRoute from './invite'
import publicInviteRoute from './public-invite'
import { authzService, Permission, ResourceType } from '@/services/authz/authz'
import { inviteService } from '@/services/invite/invite'
import { notificationService } from '@/services/notification/notification'
import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/authz'
import { inviteService } from '@shumai/core/src/invite/invite'
import { notificationService } from '@shumai/core/src/notification/notification'
vi.mock('@/services/invite/invite')
vi.mock('@/services/notification/notification')
vi.mock('@/services/authz/authz')
vi.mock('@shumai/core/src/invite/invite')
vi.mock('@shumai/core/src/notification/notification')
vi.mock('@shumai/core/src/authz/authz')
vi.mock('@/api/middleware/auth', () => ({
authMiddleware: async (
+5 -5
View File
@@ -6,11 +6,11 @@ import {
joinRequestSchema,
InviteInfo,
} from '@shumai/dtos'
import { authzService, Permission, ResourceType } from '@/services/authz/authz'
import { inviteService } from '@/services/invite/invite'
import { notificationService } from '@/services/notification/notification'
import { NotificationType } from '@/generated/prisma/client'
import type { Prisma } from '@/generated/prisma/client'
import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/authz'
import { inviteService } from '@shumai/core/src/invite/invite'
import { notificationService } from '@shumai/core/src/notification/notification'
import { NotificationType } from '@shumai/db'
import type { Prisma } from '@shumai/db'
type User = Prisma.UserGetPayload<Record<string, never>>
+4 -4
View File
@@ -1,8 +1,8 @@
import { describe, expect, it, vi, beforeEach } from 'vitest'
import { Hono, type Context, type Next } from 'hono'
import metadataRoute from './metadata'
import { metadataService } from '@/services/metadata/metadata'
import { authzService, Permission, ResourceType } from '@/services/authz/authz'
import { metadataService } from '@shumai/core/src/metadata/metadata'
import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/authz'
vi.mock('@/api/middleware/auth', () => ({
authMiddleware: async (
@@ -14,8 +14,8 @@ vi.mock('@/api/middleware/auth', () => ({
},
}))
vi.mock('@/services/authz/authz')
vi.mock('@/services/metadata/metadata')
vi.mock('@shumai/core/src/authz/authz')
vi.mock('@shumai/core/src/metadata/metadata')
describe('metadata api', () => {
const app = new Hono<{ Variables: { user: { id: string; name: string } } }>()
+3 -3
View File
@@ -1,14 +1,14 @@
import { zValidator } from '@hono/zod-validator'
import { Hono } from 'hono'
import { metadataService } from '@/services/metadata/metadata'
import { authzService, Permission, ResourceType } from '@/services/authz/authz'
import { metadataService } from '@shumai/core/src/metadata/metadata'
import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/authz'
import {
createFieldRequestSchema,
updateFieldRequestSchema,
updateProjectFieldsOrderRequestSchema,
FieldInfo,
} from '@shumai/dtos'
import type { Prisma } from '@/generated/prisma/client'
import type { Prisma } from '@shumai/db'
type User = Prisma.UserGetPayload<Record<string, never>>
+2 -2
View File
@@ -1,5 +1,5 @@
import type { Prisma } from '@/generated/prisma/client'
import { auth } from '@/services/auth/auth'
import type { Prisma } from '@shumai/db'
import { auth } from '@shumai/core/src/auth/auth'
import { prisma } from '@shumai/db'
import { createMiddleware } from 'hono/factory'
+6 -6
View File
@@ -1,9 +1,9 @@
import { describe, expect, it, vi, beforeEach } from 'vitest'
import { Hono, type Context, type Next } from 'hono'
import notificationRoute from './notification'
import { notificationService } from '@/services/notification/notification'
import { authzService, Permission, ResourceType } from '@/services/authz/authz'
import { userMetadataService } from '@/services/user-metadata/user-metadata'
import { notificationService } from '@shumai/core/src/notification/notification'
import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/authz'
import { userMetadataService } from '@shumai/core/src/user-metadata/user-metadata'
vi.mock('@/api/middleware/auth', () => ({
authMiddleware: async (
@@ -15,9 +15,9 @@ vi.mock('@/api/middleware/auth', () => ({
},
}))
vi.mock('@/services/authz/authz')
vi.mock('@/services/notification/notification')
vi.mock('@/services/user-metadata/user-metadata')
vi.mock('@shumai/core/src/authz/authz')
vi.mock('@shumai/core/src/notification/notification')
vi.mock('@shumai/core/src/user-metadata/user-metadata')
describe('notification api', () => {
const app = new Hono<{ Variables: { user: { id: string; name: string } } }>()
+4 -4
View File
@@ -1,14 +1,14 @@
import { zValidator } from '@hono/zod-validator'
import { Hono } from 'hono'
import { notificationService } from '@/services/notification/notification'
import { authzService, Permission, ResourceType } from '@/services/authz/authz'
import { notificationService } from '@shumai/core/src/notification/notification'
import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/authz'
import {
listNotificationsRequestSchema,
markNotificationReadRequestSchema,
notificationSettingsSchema,
} from '@shumai/dtos'
import { userMetadataService } from '@/services/user-metadata/user-metadata'
import type { Prisma } from '@/generated/prisma/client'
import { userMetadataService } from '@shumai/core/src/user-metadata/user-metadata'
import type { Prisma } from '@shumai/db'
type User = Prisma.UserGetPayload<Record<string, never>>
+6 -6
View File
@@ -1,9 +1,9 @@
import { describe, expect, it, vi, beforeEach } from 'vitest'
import { Hono, type Context, type Next } from 'hono'
import projectRoute from './project'
import { authzService, Permission, ResourceType } from '@/services/authz/authz'
import { projectService } from '@/services/project/project'
import { assetService } from '@/services/asset/asset'
import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/authz'
import { projectService } from '@shumai/core/src/project/project'
import { assetService } from '@shumai/core/src/asset/asset'
vi.mock('@/api/middleware/auth', () => ({
authMiddleware: async (
@@ -15,9 +15,9 @@ vi.mock('@/api/middleware/auth', () => ({
},
}))
vi.mock('@/services/authz/authz')
vi.mock('@/services/project/project')
vi.mock('@/services/asset/asset')
vi.mock('@shumai/core/src/authz/authz')
vi.mock('@shumai/core/src/project/project')
vi.mock('@shumai/core/src/asset/asset')
describe('project api', () => {
const app = new Hono<{ Variables: { user: { id: string; name: string } } }>()
+4 -4
View File
@@ -1,8 +1,8 @@
import { Hono } from 'hono'
import { zValidator } from '@hono/zod-validator'
import { authzService, Permission, ResourceType } from '@/services/authz/authz'
import { projectService } from '@/services/project/project'
import { assetService } from '@/services/asset/asset'
import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/authz'
import { projectService } from '@shumai/core/src/project/project'
import { assetService } from '@shumai/core/src/asset/asset'
import { reparentAssetsRequestSchema, copyAssetsRequestSchema } from '@shumai/dtos'
import {
createProjectRequestSchema,
@@ -11,7 +11,7 @@ import {
recentlyDeletedRequestSchema,
} from '@shumai/dtos'
import { listMembersQuerySchema } from '@shumai/dtos'
import type { Prisma } from '@/generated/prisma/client'
import type { Prisma } from '@shumai/db'
type User = Prisma.UserGetPayload<Record<string, never>>
+4 -4
View File
@@ -1,8 +1,8 @@
import { describe, expect, it, vi, beforeEach } from 'vitest'
import { Hono, type Context, type Next } from 'hono'
import providerRoute from './provider'
import { providerService } from '@/services/provider/provider'
import { authzService, Permission, ResourceType } from '@/services/authz/authz'
import { providerService } from '@shumai/core/src/provider/provider'
import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/authz'
vi.mock('@/api/middleware/auth', () => ({
authMiddleware: async (
@@ -14,8 +14,8 @@ vi.mock('@/api/middleware/auth', () => ({
},
}))
vi.mock('@/services/authz/authz')
vi.mock('@/services/provider/provider')
vi.mock('@shumai/core/src/authz/authz')
vi.mock('@shumai/core/src/provider/provider')
describe('provider api', () => {
const app = new Hono<{ Variables: { user: { id: string; name: string } } }>()
+3 -3
View File
@@ -1,9 +1,9 @@
import { zValidator } from '@hono/zod-validator'
import { Hono } from 'hono'
import { authzService, Permission, ResourceType } from '@/services/authz/authz'
import { providerService } from '@/services/provider/provider'
import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/authz'
import { providerService } from '@shumai/core/src/provider/provider'
import { createProviderRequestSchema, updateProviderRequestSchema } from '@shumai/dtos'
import type { Prisma } from '@/generated/prisma/client'
import type { Prisma } from '@shumai/db'
type User = Prisma.UserGetPayload<Record<string, never>>
+1 -1
View File
@@ -1,5 +1,5 @@
import { Hono } from 'hono'
import { inviteService } from '@/services/invite/invite'
import { inviteService } from '@shumai/core/src/invite/invite'
import { InviteInfo } from '@shumai/dtos'
const app = new Hono()
+6 -6
View File
@@ -1,16 +1,16 @@
import { Hono } from 'hono'
import { zValidator } from '@hono/zod-validator'
import { shareService } from '@/services/share/share'
import { assetService } from '@/services/asset/asset'
import { shareService } from '@shumai/core/src/share/share'
import { assetService } from '@shumai/core/src/asset/asset'
import { paginationParamsSchema } from '@shumai/dtos'
import { z } from 'zod'
import { metadataService } from '@/services/metadata/metadata'
import { metadataService } from '@shumai/core/src/metadata/metadata'
import { FieldInfo } from '@shumai/dtos'
import type { Prisma as PrismaType } from '@/generated/prisma/client'
import { auth } from '@/services/auth/auth'
import type { Prisma as PrismaType } from '@shumai/db'
import { auth } from '@shumai/core/src/auth/auth'
import { prisma } from '@shumai/db'
import { createCommentRequestSchema } from '@shumai/dtos'
import { notificationService } from '@/services/notification/notification'
import { notificationService } from '@shumai/core/src/notification/notification'
const app = new Hono()
+1 -1
View File
@@ -1,5 +1,5 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { s3Service } from '@/services/s3/s3'
import { s3Service } from '@shumai/core/src/s3/s3'
import { Hono } from 'hono'
const { mockServeStatic } = vi.hoisted(() => ({
+1 -1
View File
@@ -1,5 +1,5 @@
import { Hono } from 'hono'
import { s3Service } from '@/services/s3/s3'
import { s3Service } from '@shumai/core/src/s3/s3'
import { serveStatic } from 'hono/bun'
const route = new Hono()
+4 -4
View File
@@ -3,9 +3,9 @@ import { Hono } from 'hono'
import shareRoute from './share'
import publicShareRoute from './public-share'
import { authMiddleware } from '@/api/middleware/auth'
import { shareService } from '@/services/share/share'
import { assetService } from '@/services/asset/asset'
import { authzService, Permission, ResourceType } from '@/services/authz/authz'
import { shareService } from '@shumai/core/src/share/share'
import { assetService } from '@shumai/core/src/asset/asset'
import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/authz'
vi.mock('@/api/middleware/auth', () => ({
// eslint-disable-next-line @typescript-eslint/no-explicit-any
@@ -16,7 +16,7 @@ vi.mock('@/api/middleware/auth', () => ({
},
}))
vi.mock('@/services/authz/authz', () => ({
vi.mock('@shumai/core/src/authz/authz', () => ({
authzService: {
hasPermission: vi.fn().mockResolvedValue(undefined),
},
+3 -3
View File
@@ -1,14 +1,14 @@
import { Hono } from 'hono'
import { zValidator } from '@hono/zod-validator'
import { authzService, Permission, ResourceType } from '@/services/authz/authz'
import { shareService } from '@/services/share/share'
import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/authz'
import { shareService } from '@shumai/core/src/share/share'
import {
createShareLinkRequestSchema,
updateShareLinkRequestSchema,
listShareLinksRequestSchema,
addAssetToShareRequestSchema,
} from '@shumai/dtos'
import type { Prisma } from '@/generated/prisma/client'
import type { Prisma } from '@shumai/db'
type User = Prisma.UserGetPayload<Record<string, never>>
+3 -3
View File
@@ -1,9 +1,9 @@
import { describe, expect, test, vi, beforeEach } from 'vitest'
import { Hono } from 'hono'
import skillRoute from './skill'
import { skillService } from '@/services/skill/skill'
import { skillService } from '@shumai/core/src/skill/skill'
import { authMiddleware } from '@/api/middleware/auth'
import { authzService, ResourceType, Permission } from '@/services/authz/authz'
import { authzService, ResourceType, Permission } from '@shumai/core/src/authz/authz'
vi.mock('@/api/middleware/auth', () => ({
// eslint-disable-next-line @typescript-eslint/no-explicit-any
@@ -14,7 +14,7 @@ vi.mock('@/api/middleware/auth', () => ({
},
}))
vi.mock('@/services/authz/authz', () => ({
vi.mock('@shumai/core/src/authz/authz', () => ({
authzService: {
hasPermission: vi.fn().mockResolvedValue(undefined),
},
+3 -3
View File
@@ -1,9 +1,9 @@
import { Hono } from 'hono'
import { zValidator } from '@hono/zod-validator'
import { authzService, Permission, ResourceType } from '@/services/authz/authz'
import { skillService } from '@/services/skill/skill'
import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/authz'
import { skillService } from '@shumai/core/src/skill/skill'
import { upsertSkillRequestSchema, updateSkillConfigRequestSchema } from '@shumai/dtos'
import type { Prisma } from '@/generated/prisma/client'
import type { Prisma } from '@shumai/db'
type User = Prisma.UserGetPayload<Record<string, never>>
+5 -5
View File
@@ -2,12 +2,12 @@ import { describe, expect, it, vi, beforeEach, afterEach } from 'vitest'
import { Hono } from 'hono'
import teamRoute from './team'
import { authMiddleware } from '@/api/middleware/auth'
import { teamService } from '@/services/team/team'
import { userMetadataService } from '@/services/user-metadata/user-metadata'
import { notificationService } from '@/services/notification/notification'
import { authzService, ResourceType, Permission } from '@/services/authz/authz'
import { teamService } from '@shumai/core/src/team/team'
import { userMetadataService } from '@shumai/core/src/user-metadata/user-metadata'
import { notificationService } from '@shumai/core/src/notification/notification'
import { authzService, ResourceType, Permission } from '@shumai/core/src/authz/authz'
vi.mock('@/services/authz/authz', () => ({
vi.mock('@shumai/core/src/authz/authz', () => ({
authzService: {
hasPermission: vi.fn().mockResolvedValue(undefined),
},
+6 -6
View File
@@ -1,10 +1,10 @@
import { Hono } from 'hono'
import { zValidator } from '@hono/zod-validator'
import { authzService, Permission, ResourceType } from '@/services/authz/authz'
import { teamService } from '@/services/team/team'
import { userMetadataService } from '@/services/user-metadata/user-metadata'
import { notificationService } from '@/services/notification/notification'
import { NotificationType } from '@/generated/prisma/client'
import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/authz'
import { teamService } from '@shumai/core/src/team/team'
import { userMetadataService } from '@shumai/core/src/user-metadata/user-metadata'
import { notificationService } from '@shumai/core/src/notification/notification'
import { NotificationType } from '@shumai/db'
import {
createTeamRequestSchema,
getUserTeamsRequestSchema,
@@ -13,7 +13,7 @@ import {
updateSandboxSettingsRequestSchema,
} from '@shumai/dtos'
import { updateUserMetadataRequestSchema } from '@shumai/dtos'
import type { Prisma } from '@/generated/prisma/client'
import type { Prisma } from '@shumai/db'
type User = Prisma.UserGetPayload<Record<string, never>>
+5 -5
View File
@@ -2,10 +2,10 @@ import { describe, expect, it, vi, beforeEach } from 'vitest'
import { Hono } from 'hono'
import uploadRoute from './upload'
import { authMiddleware } from '@/api/middleware/auth'
import { uploadService } from '@/services/upload/upload'
import { uploadService } from '@shumai/core/src/upload/upload'
import type { CreateUploadTaskResponse, TaskInfo } from '@shumai/dtos'
import type { PaginatedData } from '@/services/pagination'
import { authzService, ResourceType, Permission } from '@/services/authz/authz'
import type { PaginatedData } from '@shumai/core/src/pagination'
import { authzService, ResourceType, Permission } from '@shumai/core/src/authz/authz'
vi.mock('@/api/middleware/auth', () => ({
// We use any here because mocking Hono context and middleware
@@ -18,7 +18,7 @@ vi.mock('@/api/middleware/auth', () => ({
},
}))
vi.mock('@/services/authz/authz', () => ({
vi.mock('@shumai/core/src/authz/authz', () => ({
authzService: {
hasPermission: vi.fn().mockResolvedValue(undefined),
},
@@ -33,7 +33,7 @@ vi.mock('@/services/authz/authz', () => ({
},
}))
vi.mock('@/services/notification/notification', () => ({
vi.mock('@shumai/core/src/notification/notification', () => ({
notificationService: {
create: vi.fn().mockResolvedValue(undefined),
},
+6 -6
View File
@@ -1,17 +1,17 @@
import { Hono } from 'hono'
import { zValidator } from '@hono/zod-validator'
import { uploadService } from '@/services/upload/upload'
import { uploadService } from '@shumai/core/src/upload/upload'
import {
confirmFileUploadRequestSchema,
createUploadTaskRequestSchema,
localUploadQuerySchema,
} from '@shumai/dtos'
import { paginationParamsSchema } from '@shumai/dtos'
import { authzService, Permission, ResourceType } from '@/services/authz/authz'
import { notificationService } from '@/services/notification/notification'
import { NotificationType } from '@/generated/prisma/client'
import { s3Service, verifyLocalUrlSignature } from '@/services/s3/s3'
import type { Prisma } from '@/generated/prisma/client'
import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/authz'
import { notificationService } from '@shumai/core/src/notification/notification'
import { NotificationType } from '@shumai/db'
import { s3Service, verifyLocalUrlSignature } from '@shumai/core/src/s3/s3'
import type { Prisma } from '@shumai/db'
type User = Prisma.UserGetPayload<Record<string, never>>
+4 -4
View File
@@ -2,11 +2,11 @@ import { describe, expect, it, vi, beforeEach, afterEach } from 'vitest'
import { Hono } from 'hono'
import versionStackRoute from './versionStack'
import { authMiddleware } from '@/api/middleware/auth'
import { versionStackService } from '@/services/versionStack/versionStack'
import { assetService } from '@/services/asset/asset'
import { authzService, ResourceType, Permission } from '@/services/authz/authz'
import { versionStackService } from '@shumai/core/src/versionStack/versionStack'
import { assetService } from '@shumai/core/src/asset/asset'
import { authzService, ResourceType, Permission } from '@shumai/core/src/authz/authz'
vi.mock('@/services/authz/authz', () => ({
vi.mock('@shumai/core/src/authz/authz', () => ({
authzService: {
hasPermission: vi.fn().mockResolvedValue(undefined),
},
+4 -4
View File
@@ -1,10 +1,10 @@
import { Hono } from 'hono'
import { zValidator } from '@hono/zod-validator'
import { versionStackService } from '@/services/versionStack/versionStack'
import { assetService } from '@/services/asset/asset'
import { authzService, Permission, ResourceType } from '@/services/authz/authz'
import { versionStackService } from '@shumai/core/src/versionStack/versionStack'
import { assetService } from '@shumai/core/src/asset/asset'
import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/authz'
import { createVersionStackRequestSchema, changeStackFileVersionRequestSchema } from '@shumai/dtos'
import type { Prisma } from '@/generated/prisma/client'
import type { Prisma } from '@shumai/db'
type User = Prisma.UserGetPayload<Record<string, never>>
+3 -3
View File
@@ -1,6 +1,6 @@
import index from '@/ui/index.html'
import type { Prisma } from '@/generated/prisma/client'
import type { Prisma } from '@shumai/db'
import { Hono } from 'hono'
import agentRoute from '@/api/agent'
import attachmentRoute from '@/api/attachment'
@@ -22,8 +22,8 @@ import skillRoute from '@/api/skill'
import teamRoute from '@/api/team'
import uploadRoute from '@/api/upload'
import versionStackRoute from '@/api/versionStack'
import { metadataService } from '@/services/metadata/metadata'
import { assetService } from '@/services/asset/asset'
import { metadataService } from '@shumai/core/src/metadata/metadata'
import { assetService } from '@shumai/core/src/asset/asset'
import { workflowService } from '@/workflow/workflow'
type User = Prisma.UserGetPayload<Record<string, never>>
-179
View File
@@ -1,179 +0,0 @@
/* !!! This is code generated by Prisma. Do not edit directly. !!! */
/* eslint-disable */
// biome-ignore-all lint: generated file
// @ts-nocheck
/*
* This file should be your main import to use Prisma-related types and utilities in a browser.
* Use it to get access to models, enums, and input types.
*
* This file does not contain a `PrismaClient` class, nor several other helpers that are intended as server-side only.
* See `client.ts` for the standard, server-side entry point.
*
* 🟢 You can import this file directly.
*/
import * as Prisma from './internal/prismaNamespaceBrowser.ts'
export { Prisma }
export * as $Enums from './enums.ts'
export * from './enums.ts';
/**
* Model User
*
*/
export type User = Prisma.UserModel
/**
* Model Session
*
*/
export type Session = Prisma.SessionModel
/**
* Model Account
*
*/
export type Account = Prisma.AccountModel
/**
* Model Verification
*
*/
export type Verification = Prisma.VerificationModel
/**
* Model AuthToken
*
*/
export type AuthToken = Prisma.AuthTokenModel
/**
* Model Team
*
*/
export type Team = Prisma.TeamModel
/**
* Model Sandbox
*
*/
export type Sandbox = Prisma.SandboxModel
/**
* Model Skill
*
*/
export type Skill = Prisma.SkillModel
/**
* Model TeamMember
*
*/
export type TeamMember = Prisma.TeamMemberModel
/**
* Model Project
*
*/
export type Project = Prisma.ProjectModel
/**
* Model ProjectMember
*
*/
export type ProjectMember = Prisma.ProjectMemberModel
/**
* Model ShareLink
*
*/
export type ShareLink = Prisma.ShareLinkModel
/**
* Model Asset
*
*/
export type Asset = Prisma.AssetModel
/**
* Model StorageKey
*
*/
export type StorageKey = Prisma.StorageKeyModel
/**
* Model AssetMetadataValue
*
*/
export type AssetMetadataValue = Prisma.AssetMetadataValueModel
/**
* Model AssetComment
*
*/
export type AssetComment = Prisma.AssetCommentModel
/**
* Model AssetCommentAttachment
*
*/
export type AssetCommentAttachment = Prisma.AssetCommentAttachmentModel
/**
* Model AssetEmbedding
*
*/
export type AssetEmbedding = Prisma.AssetEmbeddingModel
/**
* Model Invite
*
*/
export type Invite = Prisma.InviteModel
/**
* Model MetadataField
*
*/
export type MetadataField = Prisma.MetadataFieldModel
/**
* Model Notification
*
*/
export type Notification = Prisma.NotificationModel
/**
* Model SystemSettings
*
*/
export type SystemSettings = Prisma.SystemSettingsModel
/**
* Model Task
*
*/
export type Task = Prisma.TaskModel
/**
* Model WorkflowTask
*
*/
export type WorkflowTask = Prisma.WorkflowTaskModel
/**
* Model Agent
*
*/
export type Agent = Prisma.AgentModel
/**
* Model AgentSkill
*
*/
export type AgentSkill = Prisma.AgentSkillModel
/**
* Model AgentSession
*
*/
export type AgentSession = Prisma.AgentSessionModel
/**
* Model AgentSessionEntry
*
*/
export type AgentSessionEntry = Prisma.AgentSessionEntryModel
/**
* Model UserMetadata
*
*/
export type UserMetadata = Prisma.UserMetadataModel
/**
* Model Model
*
*/
export type Model = Prisma.ModelModel
/**
* Model Provider
*
*/
export type Provider = Prisma.ProviderModel
/**
* Model Collection
*
*/
export type Collection = Prisma.CollectionModel
-203
View File
@@ -1,203 +0,0 @@
/* !!! This is code generated by Prisma. Do not edit directly. !!! */
/* eslint-disable */
// biome-ignore-all lint: generated file
// @ts-nocheck
/*
* This file should be your main import to use Prisma. Through it you get access to all the models, enums, and input types.
* If you're looking for something you can import in the client-side of your application, please refer to the `browser.ts` file instead.
*
* 🟢 You can import this file directly.
*/
import * as process from 'node:process'
import * as path from 'node:path'
import { fileURLToPath } from 'node:url'
globalThis['__dirname'] = path.dirname(fileURLToPath(import.meta.url))
import * as runtime from "@prisma/client/runtime/client"
import * as $Enums from "./enums.ts"
import * as $Class from "./internal/class.ts"
import * as Prisma from "./internal/prismaNamespace.ts"
export * as $Enums from './enums.ts'
export * from "./enums.ts"
/**
* ## Prisma Client
*
* Type-safe database client for TypeScript
* @example
* ```
* const prisma = new PrismaClient({
* adapter: new PrismaPg({ connectionString: process.env.DATABASE_URL })
* })
* // Fetch zero or more Users
* const users = await prisma.user.findMany()
* ```
*
* Read more in our [docs](https://pris.ly/d/client).
*/
export const PrismaClient = $Class.getPrismaClientClass()
export type PrismaClient<LogOpts extends Prisma.LogLevel = never, OmitOpts extends Prisma.PrismaClientOptions["omit"] = Prisma.PrismaClientOptions["omit"], ExtArgs extends runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs> = $Class.PrismaClient<LogOpts, OmitOpts, ExtArgs>
export { Prisma }
/**
* Model User
*
*/
export type User = Prisma.UserModel
/**
* Model Session
*
*/
export type Session = Prisma.SessionModel
/**
* Model Account
*
*/
export type Account = Prisma.AccountModel
/**
* Model Verification
*
*/
export type Verification = Prisma.VerificationModel
/**
* Model AuthToken
*
*/
export type AuthToken = Prisma.AuthTokenModel
/**
* Model Team
*
*/
export type Team = Prisma.TeamModel
/**
* Model Sandbox
*
*/
export type Sandbox = Prisma.SandboxModel
/**
* Model Skill
*
*/
export type Skill = Prisma.SkillModel
/**
* Model TeamMember
*
*/
export type TeamMember = Prisma.TeamMemberModel
/**
* Model Project
*
*/
export type Project = Prisma.ProjectModel
/**
* Model ProjectMember
*
*/
export type ProjectMember = Prisma.ProjectMemberModel
/**
* Model ShareLink
*
*/
export type ShareLink = Prisma.ShareLinkModel
/**
* Model Asset
*
*/
export type Asset = Prisma.AssetModel
/**
* Model StorageKey
*
*/
export type StorageKey = Prisma.StorageKeyModel
/**
* Model AssetMetadataValue
*
*/
export type AssetMetadataValue = Prisma.AssetMetadataValueModel
/**
* Model AssetComment
*
*/
export type AssetComment = Prisma.AssetCommentModel
/**
* Model AssetCommentAttachment
*
*/
export type AssetCommentAttachment = Prisma.AssetCommentAttachmentModel
/**
* Model AssetEmbedding
*
*/
export type AssetEmbedding = Prisma.AssetEmbeddingModel
/**
* Model Invite
*
*/
export type Invite = Prisma.InviteModel
/**
* Model MetadataField
*
*/
export type MetadataField = Prisma.MetadataFieldModel
/**
* Model Notification
*
*/
export type Notification = Prisma.NotificationModel
/**
* Model SystemSettings
*
*/
export type SystemSettings = Prisma.SystemSettingsModel
/**
* Model Task
*
*/
export type Task = Prisma.TaskModel
/**
* Model WorkflowTask
*
*/
export type WorkflowTask = Prisma.WorkflowTaskModel
/**
* Model Agent
*
*/
export type Agent = Prisma.AgentModel
/**
* Model AgentSkill
*
*/
export type AgentSkill = Prisma.AgentSkillModel
/**
* Model AgentSession
*
*/
export type AgentSession = Prisma.AgentSessionModel
/**
* Model AgentSessionEntry
*
*/
export type AgentSessionEntry = Prisma.AgentSessionEntryModel
/**
* Model UserMetadata
*
*/
export type UserMetadata = Prisma.UserMetadataModel
/**
* Model Model
*
*/
export type Model = Prisma.ModelModel
/**
* Model Provider
*
*/
export type Provider = Prisma.ProviderModel
/**
* Model Collection
*
*/
export type Collection = Prisma.CollectionModel
File diff suppressed because it is too large Load Diff
-155
View File
@@ -1,155 +0,0 @@
/* !!! This is code generated by Prisma. Do not edit directly. !!! */
/* eslint-disable */
// biome-ignore-all lint: generated file
// @ts-nocheck
/*
* This file exports all enum related types from the schema.
*
* 🟢 You can import this file directly.
*/
export const UserType = {
human: 'human',
agent: 'agent'
} as const
export type UserType = (typeof UserType)[keyof typeof UserType]
export const AssetType = {
folder: 'folder',
file: 'file',
share: 'share',
root: 'root',
attachment: 'attachment',
version_stack: 'version_stack',
share_root: 'share_root',
symlink: 'symlink'
} as const
export type AssetType = (typeof AssetType)[keyof typeof AssetType]
export const AssetStatus = {
uploading: 'uploading',
uploaded: 'uploaded',
processing: 'processing',
processed: 'processed',
trashed: 'trashed',
pending_purge: 'pending_purge'
} as const
export type AssetStatus = (typeof AssetStatus)[keyof typeof AssetStatus]
export const StorageKeyStatus = {
active: 'active',
purging: 'purging'
} as const
export type StorageKeyStatus = (typeof StorageKeyStatus)[keyof typeof StorageKeyStatus]
export const InviteRole = {
editor: 'editor',
reviewer: 'reviewer'
} as const
export type InviteRole = (typeof InviteRole)[keyof typeof InviteRole]
export const MetadataFieldScope = {
SYSTEM: 'SYSTEM',
TEAM: 'TEAM',
PROJECT: 'PROJECT'
} as const
export type MetadataFieldScope = (typeof MetadataFieldScope)[keyof typeof MetadataFieldScope]
export const NotificationType = {
comment_created: 'comment_created',
reply_created: 'reply_created',
mention: 'mention',
successful_file_uploaded: 'successful_file_uploaded',
metadata_field_updated_status: 'metadata_field_updated_status',
new_user_join_team: 'new_user_join_team',
new_user_join_project: 'new_user_join_project'
} as const
export type NotificationType = (typeof NotificationType)[keyof typeof NotificationType]
export const ProjectMemberRole = {
owner: 'owner',
editor: 'editor',
reviewer: 'reviewer'
} as const
export type ProjectMemberRole = (typeof ProjectMemberRole)[keyof typeof ProjectMemberRole]
export const TaskType = {
upload: 'upload'
} as const
export type TaskType = (typeof TaskType)[keyof typeof TaskType]
export const TaskStatus = {
pending: 'pending',
uploading: 'uploading',
completed: 'completed',
failed: 'failed'
} as const
export type TaskStatus = (typeof TaskStatus)[keyof typeof TaskStatus]
export const TeamMemberRole = {
owner: 'owner',
editor: 'editor',
reviewer: 'reviewer'
} as const
export type TeamMemberRole = (typeof TeamMemberRole)[keyof typeof TeamMemberRole]
export const TeamMemberScope = {
team: 'team',
project: 'project'
} as const
export type TeamMemberScope = (typeof TeamMemberScope)[keyof typeof TeamMemberScope]
export const WorkflowTaskType = {
transcode: 'transcode',
ai_metadata_autofill: 'ai_metadata_autofill',
chat: 'chat',
ai_embedding: 'ai_embedding',
query_embedding_for_search: 'query_embedding_for_search',
agent_tool_call: 'agent_tool_call'
} as const
export type WorkflowTaskType = (typeof WorkflowTaskType)[keyof typeof WorkflowTaskType]
export const WorkflowTaskStatus = {
pending: 'pending',
processing: 'processing',
completed: 'completed',
failed: 'failed'
} as const
export type WorkflowTaskStatus = (typeof WorkflowTaskStatus)[keyof typeof WorkflowTaskStatus]
export const AgentType = {
chat: 'chat',
autofill: 'autofill',
embedding: 'embedding'
} as const
export type AgentType = (typeof AgentType)[keyof typeof AgentType]
File diff suppressed because one or more lines are too long
File diff suppressed because it is too large Load Diff
-601
View File
@@ -1,601 +0,0 @@
/* !!! This is code generated by Prisma. Do not edit directly. !!! */
/* eslint-disable */
// biome-ignore-all lint: generated file
// @ts-nocheck
/*
* WARNING: This is an internal file that is subject to change!
*
* 🛑 Under no circumstances should you import this file directly! 🛑
*
* All exports from this file are wrapped under a `Prisma` namespace object in the browser.ts file.
* While this enables partial backward compatibility, it is not part of the stable public API.
*
* If you are looking for your Models, Enums, and Input Types, please import them from the respective
* model files in the `model` directory!
*/
import * as runtime from "@prisma/client/runtime/index-browser"
export type * from '../models.ts'
export type * from './prismaNamespace.ts'
export const Decimal = runtime.Decimal
export const NullTypes = {
DbNull: runtime.NullTypes.DbNull as (new (secret: never) => typeof runtime.DbNull),
JsonNull: runtime.NullTypes.JsonNull as (new (secret: never) => typeof runtime.JsonNull),
AnyNull: runtime.NullTypes.AnyNull as (new (secret: never) => typeof runtime.AnyNull),
}
/**
* Helper for filtering JSON entries that have `null` on the database (empty on the db)
*
* @see https://www.prisma.io/docs/concepts/components/prisma-client/working-with-fields/working-with-json-fields#filtering-on-a-json-field
*/
export const DbNull = runtime.DbNull
/**
* Helper for filtering JSON entries that have JSON `null` values (not empty on the db)
*
* @see https://www.prisma.io/docs/concepts/components/prisma-client/working-with-fields/working-with-json-fields#filtering-on-a-json-field
*/
export const JsonNull = runtime.JsonNull
/**
* Helper for filtering JSON entries that are `Prisma.DbNull` or `Prisma.JsonNull`
*
* @see https://www.prisma.io/docs/concepts/components/prisma-client/working-with-fields/working-with-json-fields#filtering-on-a-json-field
*/
export const AnyNull = runtime.AnyNull
export const ModelName = {
User: 'User',
Session: 'Session',
Account: 'Account',
Verification: 'Verification',
AuthToken: 'AuthToken',
Team: 'Team',
Sandbox: 'Sandbox',
Skill: 'Skill',
TeamMember: 'TeamMember',
Project: 'Project',
ProjectMember: 'ProjectMember',
ShareLink: 'ShareLink',
Asset: 'Asset',
StorageKey: 'StorageKey',
AssetMetadataValue: 'AssetMetadataValue',
AssetComment: 'AssetComment',
AssetCommentAttachment: 'AssetCommentAttachment',
AssetEmbedding: 'AssetEmbedding',
Invite: 'Invite',
MetadataField: 'MetadataField',
Notification: 'Notification',
SystemSettings: 'SystemSettings',
Task: 'Task',
WorkflowTask: 'WorkflowTask',
Agent: 'Agent',
AgentSkill: 'AgentSkill',
AgentSession: 'AgentSession',
AgentSessionEntry: 'AgentSessionEntry',
UserMetadata: 'UserMetadata',
Model: 'Model',
Provider: 'Provider',
Collection: 'Collection'
} as const
export type ModelName = (typeof ModelName)[keyof typeof ModelName]
/*
* Enums
*/
export const TransactionIsolationLevel = runtime.makeStrictEnum({
ReadUncommitted: 'ReadUncommitted',
ReadCommitted: 'ReadCommitted',
RepeatableRead: 'RepeatableRead',
Serializable: 'Serializable'
} as const)
export type TransactionIsolationLevel = (typeof TransactionIsolationLevel)[keyof typeof TransactionIsolationLevel]
export const UserScalarFieldEnum = {
id: 'id',
type: 'type',
name: 'name',
email: 'email',
emailVerified: 'emailVerified',
image: 'image',
password: 'password',
agentSettings: 'agentSettings',
guestEmail: 'guestEmail',
createdAt: 'createdAt',
updatedAt: 'updatedAt'
} as const
export type UserScalarFieldEnum = (typeof UserScalarFieldEnum)[keyof typeof UserScalarFieldEnum]
export const SessionScalarFieldEnum = {
id: 'id',
expiresAt: 'expiresAt',
token: 'token',
createdAt: 'createdAt',
updatedAt: 'updatedAt',
ipAddress: 'ipAddress',
userAgent: 'userAgent',
userId: 'userId'
} as const
export type SessionScalarFieldEnum = (typeof SessionScalarFieldEnum)[keyof typeof SessionScalarFieldEnum]
export const AccountScalarFieldEnum = {
id: 'id',
accountId: 'accountId',
providerId: 'providerId',
userId: 'userId',
accessToken: 'accessToken',
refreshToken: 'refreshToken',
idToken: 'idToken',
accessTokenExpiresAt: 'accessTokenExpiresAt',
refreshTokenExpiresAt: 'refreshTokenExpiresAt',
scope: 'scope',
password: 'password',
createdAt: 'createdAt',
updatedAt: 'updatedAt'
} as const
export type AccountScalarFieldEnum = (typeof AccountScalarFieldEnum)[keyof typeof AccountScalarFieldEnum]
export const VerificationScalarFieldEnum = {
id: 'id',
identifier: 'identifier',
value: 'value',
expiresAt: 'expiresAt',
createdAt: 'createdAt',
updatedAt: 'updatedAt'
} as const
export type VerificationScalarFieldEnum = (typeof VerificationScalarFieldEnum)[keyof typeof VerificationScalarFieldEnum]
export const AuthTokenScalarFieldEnum = {
id: 'id',
accessToken: 'accessToken',
refreshToken: 'refreshToken',
accessTokenExpiresAt: 'accessTokenExpiresAt',
refreshTokenExpiresAt: 'refreshTokenExpiresAt',
userId: 'userId'
} as const
export type AuthTokenScalarFieldEnum = (typeof AuthTokenScalarFieldEnum)[keyof typeof AuthTokenScalarFieldEnum]
export const TeamScalarFieldEnum = {
id: 'id',
name: 'name',
settings: 'settings',
createdAt: 'createdAt',
updatedAt: 'updatedAt',
rootFolderId: 'rootFolderId'
} as const
export type TeamScalarFieldEnum = (typeof TeamScalarFieldEnum)[keyof typeof TeamScalarFieldEnum]
export const SandboxScalarFieldEnum = {
id: 'id',
allowedDomains: 'allowedDomains',
createdAt: 'createdAt',
updatedAt: 'updatedAt',
teamId: 'teamId'
} as const
export type SandboxScalarFieldEnum = (typeof SandboxScalarFieldEnum)[keyof typeof SandboxScalarFieldEnum]
export const SkillScalarFieldEnum = {
id: 'id',
name: 'name',
description: 'description',
config: 'config',
assetId: 'assetId',
hash: 'hash',
createdAt: 'createdAt',
updatedAt: 'updatedAt',
teamId: 'teamId'
} as const
export type SkillScalarFieldEnum = (typeof SkillScalarFieldEnum)[keyof typeof SkillScalarFieldEnum]
export const TeamMemberScalarFieldEnum = {
id: 'id',
role: 'role',
scope: 'scope',
teamId: 'teamId',
userId: 'userId',
lastReadNotificationId: 'lastReadNotificationId'
} as const
export type TeamMemberScalarFieldEnum = (typeof TeamMemberScalarFieldEnum)[keyof typeof TeamMemberScalarFieldEnum]
export const ProjectScalarFieldEnum = {
id: 'id',
name: 'name',
coverImageKey: 'coverImageKey',
metadataOverrides: 'metadataOverrides',
enableNotification: 'enableNotification',
createdAt: 'createdAt',
updatedAt: 'updatedAt',
teamId: 'teamId',
rootFolderId: 'rootFolderId',
shareRootId: 'shareRootId'
} as const
export type ProjectScalarFieldEnum = (typeof ProjectScalarFieldEnum)[keyof typeof ProjectScalarFieldEnum]
export const ProjectMemberScalarFieldEnum = {
id: 'id',
role: 'role',
projectId: 'projectId',
teamMemberId: 'teamMemberId'
} as const
export type ProjectMemberScalarFieldEnum = (typeof ProjectMemberScalarFieldEnum)[keyof typeof ProjectMemberScalarFieldEnum]
export const ShareLinkScalarFieldEnum = {
id: 'id',
name: 'name',
expireAt: 'expireAt',
password: 'password',
isDisabled: 'isDisabled',
defaultSortOrder: 'defaultSortOrder',
fieldVisibility: 'fieldVisibility',
createdAt: 'createdAt',
updatedAt: 'updatedAt',
projectId: 'projectId',
rootFolderId: 'rootFolderId'
} as const
export type ShareLinkScalarFieldEnum = (typeof ShareLinkScalarFieldEnum)[keyof typeof ShareLinkScalarFieldEnum]
export const AssetScalarFieldEnum = {
id: 'id',
name: 'name',
nameNgram: 'nameNgram',
type: 'type',
mediaType: 'mediaType',
fileCount: 'fileCount',
sizeByte: 'sizeByte',
status: 'status',
transcodeTaskId: 'transcodeTaskId',
media: 'media',
isDeleted: 'isDeleted',
deletedAt: 'deletedAt',
sortIndex: 'sortIndex',
createdAt: 'createdAt',
updatedAt: 'updatedAt',
parentId: 'parentId',
targetId: 'targetId',
storageKeyId: 'storageKeyId',
creatorId: 'creatorId',
taskId: 'taskId',
projectId: 'projectId'
} as const
export type AssetScalarFieldEnum = (typeof AssetScalarFieldEnum)[keyof typeof AssetScalarFieldEnum]
export const StorageKeyScalarFieldEnum = {
id: 'id',
key: 'key',
status: 'status',
createdAt: 'createdAt',
updatedAt: 'updatedAt'
} as const
export type StorageKeyScalarFieldEnum = (typeof StorageKeyScalarFieldEnum)[keyof typeof StorageKeyScalarFieldEnum]
export const AssetMetadataValueScalarFieldEnum = {
id: 'id',
assetId: 'assetId',
fieldKey: 'fieldKey',
stringValue: 'stringValue',
numberValue: 'numberValue',
booleanValue: 'booleanValue',
jsonValue: 'jsonValue',
dateValue: 'dateValue'
} as const
export type AssetMetadataValueScalarFieldEnum = (typeof AssetMetadataValueScalarFieldEnum)[keyof typeof AssetMetadataValueScalarFieldEnum]
export const AssetCommentScalarFieldEnum = {
id: 'id',
message: 'message',
annotation: 'annotation',
second: 'second',
sessionId: 'sessionId',
createdAt: 'createdAt',
updatedAt: 'updatedAt',
assetId: 'assetId',
creatorId: 'creatorId',
replyToId: 'replyToId'
} as const
export type AssetCommentScalarFieldEnum = (typeof AssetCommentScalarFieldEnum)[keyof typeof AssetCommentScalarFieldEnum]
export const AssetCommentAttachmentScalarFieldEnum = {
id: 'id',
createdAt: 'createdAt',
updatedAt: 'updatedAt',
commentId: 'commentId',
assetId: 'assetId'
} as const
export type AssetCommentAttachmentScalarFieldEnum = (typeof AssetCommentAttachmentScalarFieldEnum)[keyof typeof AssetCommentAttachmentScalarFieldEnum]
export const AssetEmbeddingScalarFieldEnum = {
id: 'id',
startTime: 'startTime',
endTime: 'endTime',
createdAt: 'createdAt',
updatedAt: 'updatedAt',
assetId: 'assetId'
} as const
export type AssetEmbeddingScalarFieldEnum = (typeof AssetEmbeddingScalarFieldEnum)[keyof typeof AssetEmbeddingScalarFieldEnum]
export const InviteScalarFieldEnum = {
id: 'id',
code: 'code',
role: 'role',
used: 'used',
createdAt: 'createdAt',
updatedAt: 'updatedAt',
teamId: 'teamId',
projectId: 'projectId',
inviterId: 'inviterId'
} as const
export type InviteScalarFieldEnum = (typeof InviteScalarFieldEnum)[keyof typeof InviteScalarFieldEnum]
export const MetadataFieldScalarFieldEnum = {
id: 'id',
key: 'key',
scope: 'scope',
config: 'config',
readOnly: 'readOnly',
aiAutofill: 'aiAutofill',
description: 'description',
teamId: 'teamId',
projectId: 'projectId'
} as const
export type MetadataFieldScalarFieldEnum = (typeof MetadataFieldScalarFieldEnum)[keyof typeof MetadataFieldScalarFieldEnum]
export const NotificationScalarFieldEnum = {
id: 'id',
type: 'type',
createdAt: 'createdAt',
updatedAt: 'updatedAt',
teamId: 'teamId',
projectId: 'projectId',
creatorId: 'creatorId',
assetId: 'assetId',
taskId: 'taskId',
userId: 'userId'
} as const
export type NotificationScalarFieldEnum = (typeof NotificationScalarFieldEnum)[keyof typeof NotificationScalarFieldEnum]
export const SystemSettingsScalarFieldEnum = {
id: 'id',
key: 'key',
value: 'value',
createdAt: 'createdAt',
updatedAt: 'updatedAt'
} as const
export type SystemSettingsScalarFieldEnum = (typeof SystemSettingsScalarFieldEnum)[keyof typeof SystemSettingsScalarFieldEnum]
export const TaskScalarFieldEnum = {
id: 'id',
type: 'type',
status: 'status',
name: 'name',
total: 'total',
uploaded: 'uploaded',
createdAt: 'createdAt',
updatedAt: 'updatedAt',
creatorId: 'creatorId'
} as const
export type TaskScalarFieldEnum = (typeof TaskScalarFieldEnum)[keyof typeof TaskScalarFieldEnum]
export const WorkflowTaskScalarFieldEnum = {
id: 'id',
uid: 'uid',
teamId: 'teamId',
projectId: 'projectId',
assetId: 'assetId',
type: 'type',
status: 'status',
payload: 'payload',
output: 'output',
heartbeat: 'heartbeat',
inputTokens: 'inputTokens',
outputTokens: 'outputTokens',
model: 'model',
createdAt: 'createdAt',
updatedAt: 'updatedAt'
} as const
export type WorkflowTaskScalarFieldEnum = (typeof WorkflowTaskScalarFieldEnum)[keyof typeof WorkflowTaskScalarFieldEnum]
export const AgentScalarFieldEnum = {
id: 'id',
type: 'type',
enabled: 'enabled',
soul: 'soul',
providerId: 'providerId',
modelId: 'modelId',
teamId: 'teamId',
config: 'config',
createdAt: 'createdAt',
updatedAt: 'updatedAt'
} as const
export type AgentScalarFieldEnum = (typeof AgentScalarFieldEnum)[keyof typeof AgentScalarFieldEnum]
export const AgentSkillScalarFieldEnum = {
id: 'id',
agentId: 'agentId',
skillId: 'skillId',
createdAt: 'createdAt',
updatedAt: 'updatedAt'
} as const
export type AgentSkillScalarFieldEnum = (typeof AgentSkillScalarFieldEnum)[keyof typeof AgentSkillScalarFieldEnum]
export const AgentSessionScalarFieldEnum = {
id: 'id',
agentId: 'agentId',
userId: 'userId',
cwd: 'cwd',
leafId: 'leafId',
createdAt: 'createdAt',
updatedAt: 'updatedAt'
} as const
export type AgentSessionScalarFieldEnum = (typeof AgentSessionScalarFieldEnum)[keyof typeof AgentSessionScalarFieldEnum]
export const AgentSessionEntryScalarFieldEnum = {
id: 'id',
sessionId: 'sessionId',
entry: 'entry'
} as const
export type AgentSessionEntryScalarFieldEnum = (typeof AgentSessionEntryScalarFieldEnum)[keyof typeof AgentSessionEntryScalarFieldEnum]
export const UserMetadataScalarFieldEnum = {
id: 'id',
key: 'key',
value: 'value',
createdAt: 'createdAt',
updatedAt: 'updatedAt',
userId: 'userId',
teamId: 'teamId'
} as const
export type UserMetadataScalarFieldEnum = (typeof UserMetadataScalarFieldEnum)[keyof typeof UserMetadataScalarFieldEnum]
export const ModelScalarFieldEnum = {
id: 'id',
modelId: 'modelId',
name: 'name',
config: 'config',
createdAt: 'createdAt',
updatedAt: 'updatedAt',
providerId: 'providerId'
} as const
export type ModelScalarFieldEnum = (typeof ModelScalarFieldEnum)[keyof typeof ModelScalarFieldEnum]
export const ProviderScalarFieldEnum = {
id: 'id',
name: 'name',
isBuiltin: 'isBuiltin',
config: 'config',
createdAt: 'createdAt',
updatedAt: 'updatedAt',
teamId: 'teamId'
} as const
export type ProviderScalarFieldEnum = (typeof ProviderScalarFieldEnum)[keyof typeof ProviderScalarFieldEnum]
export const CollectionScalarFieldEnum = {
id: 'id',
name: 'name',
filter: 'filter',
createdAt: 'createdAt',
updatedAt: 'updatedAt',
projectId: 'projectId'
} as const
export type CollectionScalarFieldEnum = (typeof CollectionScalarFieldEnum)[keyof typeof CollectionScalarFieldEnum]
export const SortOrder = {
asc: 'asc',
desc: 'desc'
} as const
export type SortOrder = (typeof SortOrder)[keyof typeof SortOrder]
export const NullableJsonNullValueInput = {
DbNull: DbNull,
JsonNull: JsonNull
} as const
export type NullableJsonNullValueInput = (typeof NullableJsonNullValueInput)[keyof typeof NullableJsonNullValueInput]
export const JsonNullValueInput = {
JsonNull: JsonNull
} as const
export type JsonNullValueInput = (typeof JsonNullValueInput)[keyof typeof JsonNullValueInput]
export const QueryMode = {
default: 'default',
insensitive: 'insensitive'
} as const
export type QueryMode = (typeof QueryMode)[keyof typeof QueryMode]
export const JsonNullValueFilter = {
DbNull: DbNull,
JsonNull: JsonNull,
AnyNull: AnyNull
} as const
export type JsonNullValueFilter = (typeof JsonNullValueFilter)[keyof typeof JsonNullValueFilter]
export const NullsOrder = {
first: 'first',
last: 'last'
} as const
export type NullsOrder = (typeof NullsOrder)[keyof typeof NullsOrder]
-43
View File
@@ -1,43 +0,0 @@
/* !!! This is code generated by Prisma. Do not edit directly. !!! */
/* eslint-disable */
// biome-ignore-all lint: generated file
// @ts-nocheck
/*
* This is a barrel export file for all models and their related types.
*
* 🟢 You can import this file directly.
*/
export type * from './models/User.ts'
export type * from './models/Session.ts'
export type * from './models/Account.ts'
export type * from './models/Verification.ts'
export type * from './models/AuthToken.ts'
export type * from './models/Team.ts'
export type * from './models/Sandbox.ts'
export type * from './models/Skill.ts'
export type * from './models/TeamMember.ts'
export type * from './models/Project.ts'
export type * from './models/ProjectMember.ts'
export type * from './models/ShareLink.ts'
export type * from './models/Asset.ts'
export type * from './models/StorageKey.ts'
export type * from './models/AssetMetadataValue.ts'
export type * from './models/AssetComment.ts'
export type * from './models/AssetCommentAttachment.ts'
export type * from './models/AssetEmbedding.ts'
export type * from './models/Invite.ts'
export type * from './models/MetadataField.ts'
export type * from './models/Notification.ts'
export type * from './models/SystemSettings.ts'
export type * from './models/Task.ts'
export type * from './models/WorkflowTask.ts'
export type * from './models/Agent.ts'
export type * from './models/AgentSkill.ts'
export type * from './models/AgentSession.ts'
export type * from './models/AgentSessionEntry.ts'
export type * from './models/UserMetadata.ts'
export type * from './models/Model.ts'
export type * from './models/Provider.ts'
export type * from './models/Collection.ts'
export type * from './commonInputTypes.ts'
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
-1863
View File
File diff suppressed because it is too large Load Diff
-2860
View File
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
-3725
View File
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
-183
View File
@@ -1,183 +0,0 @@
import * as Prisma from './internal/prismaNamespace';
declare global {
namespace PrismaJson {
// This namespace will always be empty. Definitions should be done by
// you manually, and merged automatically by typescript. Make sure that
// your declaration merging file is included in your tsconfig.json
//
// Learn more: https://github.com/arthurfiorette/prisma-json-types-generator/issues/143
// Declaration Merging: https://www.typescriptlang.org/docs/handbook/declaration-merging.html
}
}
/** A filter to be used against nullable List types. */
export type NullableListFilter<T> = {
equals?: T | T[] | null;
has?: T | null;
hasEvery?: T[];
hasSome?: T[];
isEmpty?: boolean;
};
/** A type to determine how to update a json field */
export type UpdateInput<T> = T extends object ? { [P in keyof T]?: UpdateInput<T[P]> } : T;
/** A type to determine how to update a json[] field */
export type UpdateManyInput<T> = T | T[] | { set?: T[]; push?: T | T[] };
/** A type to determine how to create a json[] input */
export type CreateManyInput<T> = T | T[] | { set?: T[] };
/**
* A typed version of NestedStringFilter, allowing narrowing of string types to
* discriminated unions.
*/
export type TypedNestedStringFilter<S extends string> =
//@ts-ignore - When Prisma.StringFilter is not present, this type is not used
Prisma.StringFilter & {
equals?: S;
in?: S[];
notIn?: S[];
not?: TypedNestedStringFilter<S> | S;
};
/**
* A typed version of StringFilter, allowing narrowing of string types to discriminated
* unions.
*/
export type TypedStringFilter<S extends string> =
//@ts-ignore - When Prisma.StringFilter is not present, this type is not used
Prisma.StringFilter & {
equals?: S;
in?: S[];
notIn?: S[];
not?: TypedNestedStringFilter<S> | S;
};
/**
* A typed version of NestedStringNullableFilter, allowing narrowing of string types to
* discriminated unions.
*/
export type TypedNestedStringNullableFilter<S extends string> =
//@ts-ignore - When Prisma.StringNullableFilter is not present, this type is not used
Prisma.StringNullableFilter & {
equals?: S | null;
in?: S[] | null;
notIn?: S[] | null;
not?: TypedNestedStringNullableFilter<S> | S | null;
};
/**
* A typed version of StringNullableFilter, allowing narrowing of string types to
* discriminated unions.
*/
export type TypedStringNullableFilter<S extends string> =
//@ts-ignore - When Prisma.StringNullableFilter is not present, this type is not used
Prisma.StringNullableFilter & {
equals?: S | null;
in?: S[] | null;
notIn?: S[] | null;
not?: TypedNestedStringNullableFilter<S> | S | null;
};
/**
* A typed version of NestedStringWithAggregatesFilter, allowing narrowing of string types
* to discriminated unions.
*/
export type TypedNestedStringWithAggregatesFilter<S extends string> =
//@ts-ignore - When Prisma.NestedStringWithAggregatesFilter is not present, this type is not used
Prisma.NestedStringWithAggregatesFilter & {
equals?: S;
in?: S[];
notIn?: S[];
not?: TypedNestedStringWithAggregatesFilter<S> | S;
};
/**
* A typed version of StringWithAggregatesFilter, allowing narrowing of string types to
* discriminated unions.
*/
export type TypedStringWithAggregatesFilter<S extends string> =
//@ts-ignore - When Prisma.StringWithAggregatesFilter is not present, this type is not used
Prisma.StringWithAggregatesFilter & {
equals?: S;
in?: S[];
notIn?: S[];
not?: TypedNestedStringWithAggregatesFilter<S> | S;
};
/**
* A typed version of NestedStringNullableWithAggregatesFilter, allowing narrowing of
* string types to discriminated unions.
*/
export type TypedNestedStringNullableWithAggregatesFilter<S extends string> =
//@ts-ignore - When Prisma.NestedStringNullableWithAggregatesFilter is not present, this type is not used
Prisma.NestedStringNullableWithAggregatesFilter & {
equals?: S | null;
in?: S[] | null;
notIn?: S[] | null;
not?: TypedNestedStringNullableWithAggregatesFilter<S> | S | null;
};
/**
* A typed version of StringNullableWithAggregatesFilter, allowing narrowing of string
* types to discriminated unions.
*/
export type TypedStringNullableWithAggregatesFilter<S extends string> =
//@ts-ignore - When Prisma.StringNullableWithAggregatesFilter is not present, this type is not used
Prisma.StringNullableWithAggregatesFilter & {
equals?: S | null;
in?: S[] | null;
notIn?: S[] | null;
not?: TypedNestedStringNullableWithAggregatesFilter<S> | S | null;
};
/**
* A typed version of StringFieldUpdateOperationsInput, allowing narrowing of string types
* to discriminated unions.
*/
export type TypedStringFieldUpdateOperationsInput<S extends string> =
//@ts-ignore - When Prisma.StringFieldUpdateOperationsInput is not present, this type is not used
Prisma.StringFieldUpdateOperationsInput & {
set?: S;
};
/**
* A typed version of NullableStringFieldUpdateOperationsInput, allowing narrowing of
* string types to discriminated unions.
*/
export type TypedNullableStringFieldUpdateOperationsInput<S extends string> =
//@ts-ignore - When Prisma.NullableStringFieldUpdateOperationsInput is not present, this type is not used
Prisma.NullableStringFieldUpdateOperationsInput & {
set?: S | null;
};
/**
* A typed version of StringNullableListFilter, allowing narrowing of string types to
* discriminated unions.
*/
export type TypedStringNullableListFilter<S extends string> =
//@ts-ignore - When Prisma.StringNullableListFilter is not present, this type is not used
Prisma.StringNullableListFilter & {
equals?: S[] | null;
has?: S | null;
hasEvery?: S[];
hasSome?: S[];
};
/**
* A typed version of the input type to update a string[] field, allowing narrowing of
* string types to discriminated unions.
*/
export type UpdateStringArrayInput<S extends string> = {
set?: S[];
push?: S | S[];
};
/**
* A typed version of the input type to create a string[] field, allowing narrowing of
* string types to discriminated unions.
*/
export type CreateStringArrayInput<S extends string> = {
set?: S[];
};
-223
View File
@@ -1,223 +0,0 @@
import { describe, expect, test } from 'vitest'
import { AgentService } from './agent'
import { prisma } from '@shumai/db'
import { setupTestDbHooks } from '@shumai/db'
describe('AgentService', () => {
setupTestDbHooks()
// eslint-disable-next-line @typescript-eslint/no-explicit-any
async function setupTestData(db: any) {
const team = await db.team.create({
data: {
name: 'Test Team',
},
})
const provider = await db.provider.create({
data: {
name: 'Google',
teamId: team.id,
config: {
api: 'openai-completions',
},
},
})
const model = await db.model.create({
data: {
modelId: 'gemini-pro',
name: 'Gemini Pro',
providerId: provider.id,
config: {},
},
})
const skill = await db.skill.create({
data: {
name: 'Test Skill',
teamId: team.id,
assetId: 'asset1',
hash: 'hash1',
},
})
const user = await db.user.create({
data: {
name: 'Bot 1',
email: 'bot1@shumai.ai',
type: 'agent',
},
})
const agent = await db.agent.create({
data: {
id: user.id,
teamId: team.id,
type: 'chat',
providerId: provider.id,
modelId: model.id,
soul: 'Test soul',
config: {
provider: provider.id,
model: model.id,
},
},
})
await db.teamMember.create({
data: {
teamId: team.id,
userId: user.id,
role: 'owner',
},
})
return { team, provider, model, skill, agent }
}
describe('create, update, delete agents', () => {
test('Create Agent with Provider and Model', async () => {
const db = prisma
const svc = new AgentService()
const { team, provider, model } = await setupTestData(db)
const agent = await svc.createAgent({
teamId: team.id,
name: 'New Agent',
type: 'chat',
enabled: true,
providerId: provider.id,
modelId: model.id,
thinkingLevel: 'medium',
systemPrompt: 'You are helpful',
soul: 'I am a soul',
})
expect(agent?.id).toBeDefined()
expect(agent?.user.name).toBe('New Agent')
expect(agent?.providerId).toBe(provider.id)
expect(agent?.modelId).toBe(model.id)
expect(agent?.soul).toBe('I am a soul')
const teamMember = await db.teamMember.findFirst({
where: { userId: agent?.id, teamId: team.id },
})
expect(teamMember).toBeDefined()
})
test('Create Agent with Skills', async () => {
const db = prisma
const svc = new AgentService()
const { team, provider, model, skill } = await setupTestData(db)
const agent = await svc.createAgent({
teamId: team.id,
name: 'Skill Agent',
type: 'chat',
enabled: true,
providerId: provider.id,
modelId: model.id,
thinkingLevel: 'medium',
skills: [skill.id],
})
expect(agent?.skills?.length).toBe(1)
expect(agent?.skills?.[0].skillId).toBe(skill.id)
})
test('Create Agent validation fails if model mismatch', async () => {
const db = prisma
const svc = new AgentService()
const { team, model } = await setupTestData(db)
const otherProvider = await db.provider.create({
data: {
name: 'Other',
teamId: team.id,
config: {
api: 'openai-completions',
},
},
})
await expect(
svc.createAgent({
teamId: team.id,
name: 'Fail Agent',
type: 'chat',
enabled: true,
providerId: otherProvider.id,
modelId: model.id,
thinkingLevel: 'medium',
}),
).rejects.toThrow('model does not belong to provider')
})
test('Update Agent and Skills', async () => {
const db = prisma
const svc = new AgentService()
const { agent, skill } = await setupTestData(db)
const updated = await svc.updateAgent({
agentId: agent.id,
name: 'Updated Agent',
type: 'autofill',
enabled: true,
providerId: agent.providerId!,
modelId: agent.modelId!,
thinkingLevel: 'high',
soul: 'New soul',
skills: [], // Disable all skills
})
expect(updated.user.name).toBe('Updated Agent')
expect(updated.type).toBe('autofill')
expect(updated.soul).toBe('New soul')
expect(updated.skills?.length).toBe(0)
const reUpdated = await svc.updateAgent({
agentId: agent.id,
name: 'Updated Agent',
type: 'autofill',
enabled: true,
providerId: agent.providerId!,
modelId: agent.modelId!,
thinkingLevel: 'high',
soul: 'New soul',
skills: [skill.id], // Re-enable one
})
expect(reUpdated.skills?.length).toBe(1)
})
test('Delete Agent', async () => {
const db = prisma
const svc = new AgentService()
const { agent } = await setupTestData(db)
await svc.deleteAgent({ agentId: agent.id })
const deletedAgent = await db.agent.findUnique({
where: { id: agent.id },
})
expect(deletedAgent).toBeNull()
const deletedUser = await db.user.findUnique({
where: { id: agent.id },
})
expect(deletedUser).toBeNull()
})
test('List Agents', async () => {
const db = prisma
const svc = new AgentService()
const { team } = await setupTestData(db)
const agents = await svc.listAgents({ teamId: team.id })
expect(agents.length).toBe(1)
expect(agents[0].user.name).toBe('Bot 1')
expect(agents[0].provider).toBeDefined()
expect(agents[0].modelRef).toBeDefined()
})
})
})
-330
View File
@@ -1,330 +0,0 @@
import { prisma } from '@shumai/db'
import {
CreateAgentParams,
DeleteAgentParams,
ListAgentsParams,
UpdateAgentParams,
} from '@shumai/dtos'
import '@shumai/db/src/prisma-json-types'
import { s3Service } from '@/services/s3/s3'
import AdmZip from 'adm-zip'
import * as fs from 'fs'
import * as path from 'path'
export class AgentService {
constructor(private readonly prismaClient: typeof prisma = prisma) {}
async getSkillContent(skillId: string): Promise<string> {
const skill = await this.prismaClient.skill.findUnique({
where: { id: skillId },
})
if (!skill) {
throw new Error(`Skill with ID ${skillId} not found.`)
}
const skillDir = path.join(process.cwd(), '.pi', 'skills', skill.id)
const hashFile = path.join(skillDir, '.hash')
let needsDownload = true
if (fs.existsSync(hashFile)) {
const localHash = fs.readFileSync(hashFile, 'utf8')
if (localHash === skill.hash) {
needsDownload = false
}
}
if (needsDownload) {
if (fs.existsSync(skillDir)) {
fs.rmSync(skillDir, { recursive: true, force: true })
}
fs.mkdirSync(skillDir, { recursive: true })
const asset = await this.prismaClient.asset.findUnique({
where: { id: skill.assetId },
include: { storageKey: true },
})
if (!asset || !asset.storageKey?.key) {
throw new Error('Skill asset not found or has no key')
}
const { buffer: zipBuffer } = await s3Service.getObject(
process.env.S3_BUCKET || 'shumai',
asset.storageKey.key,
)
const zip = new AdmZip(zipBuffer)
zip.extractAllTo(skillDir, true)
fs.writeFileSync(hashFile, skill.hash)
}
// Read SKILL.md
let skillMdPath = path.join(skillDir, 'SKILL.md')
if (!fs.existsSync(skillMdPath)) {
skillMdPath = path.join(skillDir, 'skill.md')
}
if (!fs.existsSync(skillMdPath)) {
throw new Error(`Skill downloaded but SKILL.md not found in ${skillDir}`)
}
return fs.readFileSync(skillMdPath, 'utf8')
}
async getSkillEnvs(skillId: string): Promise<Record<string, string>> {
const skill = await this.prismaClient.skill.findUnique({
where: { id: skillId },
})
if (!skill) return {}
const config = skill.config as unknown as PrismaJson.SkillConfig
const envs: Record<string, string> = {}
if (config?.environmentVariables && Array.isArray(config.environmentVariables)) {
for (const envVar of config.environmentVariables) {
const value =
envVar.default !== undefined && envVar.default !== null && envVar.default !== ''
? envVar.default
: process.env[envVar.name]
if (value !== undefined) {
envs[envVar.name] = value
}
}
}
return envs
}
async createAgent(params: CreateAgentParams) {
const {
teamId,
name,
type,
enabled,
avatar,
providerId,
modelId,
thinkingLevel,
systemPrompt,
soul,
skills,
} = params
if (type === 'embedding' || type === 'autofill') {
const existing = await this.prismaClient.agent.findFirst({
where: {
type,
teamId,
},
})
if (existing) {
throw new Error(`Agent of type ${type} already exists for this team`)
}
}
if (type === 'chat' || type === 'autofill') {
if (!providerId || !modelId) {
throw new Error('providerId and modelId are required for chat/autofill agents')
}
const model = await this.prismaClient.model.findUnique({
where: { id: modelId },
})
if (!model) throw new Error('model not found')
if (model.providerId !== providerId) {
throw new Error('model does not belong to provider')
}
}
return this.prismaClient.$transaction(async (tx) => {
const team = await tx.team.findUnique({
where: { id: teamId },
})
if (!team) throw new Error('team not found')
const agentConfig: PrismaJson.AgentConfig = {
provider: providerId || '',
model: modelId || '',
thinkingLevel,
systemPrompt,
}
const user = await tx.user.create({
data: {
name,
email: `agent-${Date.now()}-${Math.random().toString(36).substring(7)}@shumai.ai`,
type: 'agent',
image: avatar,
},
})
const agent = await tx.agent.create({
data: {
id: user.id,
teamId,
type,
enabled: enabled ?? true,
providerId: providerId || null,
modelId: modelId || null,
soul,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
config: agentConfig as any,
skills: {
create:
skills?.map((skillId) => ({
skillId,
})) || [],
},
},
})
await tx.teamMember.create({
data: {
teamId,
userId: user.id,
role: 'reviewer', // Default role for agents
},
})
return tx.agent.findUnique({
where: { id: agent.id },
include: { user: true, skills: { include: { skill: true } } },
})
})
}
async updateAgent(params: UpdateAgentParams) {
const {
agentId,
name,
type,
enabled,
avatar,
providerId,
modelId,
thinkingLevel,
systemPrompt,
soul,
skills,
} = params
const agent = await this.prismaClient.agent.findUnique({
where: { id: agentId },
include: { user: { include: { teamMembers: true } } },
})
if (!agent) throw new Error('agent not found')
if (type === 'embedding' || type === 'autofill') {
const existing = await this.prismaClient.agent.findFirst({
where: {
type,
id: { not: agentId },
teamId: agent.teamId,
},
})
if (existing) {
throw new Error(`Agent of type ${type} already exists for this team`)
}
}
if (type === 'chat' || type === 'autofill') {
if (!providerId || !modelId) {
throw new Error('providerId and modelId are required for chat/autofill agents')
}
const model = await this.prismaClient.model.findUnique({
where: { id: modelId },
})
if (!model) throw new Error('model not found')
if (model.providerId !== providerId) {
throw new Error('model does not belong to provider')
}
}
const agentConfig: PrismaJson.AgentConfig = {
provider: providerId || '',
model: modelId || '',
thinkingLevel,
systemPrompt,
}
return this.prismaClient.$transaction(async (tx) => {
await tx.user.update({
where: { id: agentId },
data: {
name,
image: avatar,
},
})
// Update skills: easier to delete all and recreate
await tx.agentSkill.deleteMany({
where: { agentId },
})
return tx.agent.update({
where: { id: agentId },
data: {
type,
enabled: enabled ?? true,
providerId: providerId || null,
modelId: modelId || null,
soul,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
config: agentConfig as any,
skills: {
create:
skills?.map((skillId) => ({
skillId,
})) || [],
},
},
include: { user: true, skills: { include: { skill: true } } },
})
})
}
async deleteAgent(params: DeleteAgentParams) {
const { agentId } = params
const agent = await this.prismaClient.agent.findUnique({
where: { id: agentId },
})
if (!agent) throw new Error('agent not found')
// Deleting user will cascade to agent and teamMember due to schema definition
await this.prismaClient.user.delete({
where: { id: agentId },
})
}
async listAgents(params: ListAgentsParams) {
return this.prismaClient.agent.findMany({
where: {
teamId: params.teamId,
},
orderBy: {
id: 'desc',
},
include: {
user: true,
provider: true,
modelRef: true,
skills: {
include: {
skill: true,
},
},
},
})
}
async getSessionEntries(params: { sessionId: string }) {
return this.prismaClient.agentSessionEntry.findMany({
where: { sessionId: params.sessionId },
orderBy: { id: 'asc' },
})
}
}
export const agentService = new AgentService()
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
-96
View File
@@ -1,96 +0,0 @@
import { betterAuth } from 'better-auth'
import { prismaAdapter } from 'better-auth/adapters/prisma'
import { prisma } from '@shumai/db'
import { teamService } from '@/services/team/team'
import { inviteService } from '@/services/invite/invite'
import { createAuthMiddleware } from 'better-auth/api'
export const auth = betterAuth({
database: prismaAdapter(prisma, {
provider: 'postgresql',
}),
emailAndPassword: {
enabled: true,
minPasswordLength: 3,
},
secret: process.env.BETTER_AUTH_SECRET,
// eslint-disable-next-line @typescript-eslint/naming-convention
baseURL: process.env.BETTER_AUTH_URL,
basePath: '/api/auth',
trustedOrigins: ['http://localhost:3000', 'http://127.0.0.1:3000'],
advanced: {
disableCSRFCheck: true,
},
hooks: {
before: createAuthMiddleware(async (ctx) => {
if (ctx.path === '/sign-up/email') {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const body = ctx.body as any
const inviteCode = body?.inviteCode
const info = await teamService.getSignupInfo()
if (info.userCount > 0) {
if (!inviteCode && !info.enablePublicSignup) {
console.log('[Better Auth Hook] Public signup is disabled')
return ctx.json(
{
error: 'Public signup is disabled',
},
{
status: 403,
},
)
}
}
}
}),
after: createAuthMiddleware(async (ctx) => {
if (ctx.path === '/sign-up/email') {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const result = ctx.context.returned as any
// Only proceed if the signup was successful and we have a user
if (result && result.user && result.user.id) {
const user = result.user
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const body = ctx.body as any
const inviteCode = body?.inviteCode
try {
const info = await teamService.getSignupInfo()
const defaultTeam = await teamService.ensureDefaultTeam()
// If this is the very first user, make them owner
if (info.userCount === 1) {
await prisma.teamMember.create({
data: {
teamId: defaultTeam.id,
userId: user.id,
role: 'owner',
scope: 'team',
},
})
} else if (!inviteCode) {
// If public signup is enabled and no invite code, add as editor
await prisma.teamMember.create({
data: {
teamId: defaultTeam.id,
userId: user.id,
role: 'editor',
scope: 'team',
},
})
}
if (inviteCode) {
await inviteService.consumeInvite(inviteCode, user.id)
}
} catch (err) {
console.error(`[Better Auth Hook] Error in after hook: ${err}`)
}
}
}
}),
},
})
-400
View File
@@ -1,400 +0,0 @@
import { setupTestDbHooks } from '@shumai/db'
import { describe, expect, it } from 'vitest'
import { prisma } from '@shumai/db'
import { authzService, Permission, ResourceType } from '@/services/authz/authz'
describe('AuthzService', () => {
setupTestDbHooks()
it('should test authorization permissions correctly', async () => {
// Setup Data
// Users
const userOwner = await prisma.user.create({
data: { name: 'owner', email: 'owner@example.com', password: 'pass' },
})
const userEditor = await prisma.user.create({
data: { name: 'editor', email: 'editor@example.com', password: 'pass' },
})
const userReviewer = await prisma.user.create({
data: { name: 'reviewer', email: 'reviewer@example.com', password: 'pass' },
})
const userOther = await prisma.user.create({
data: { name: 'other', email: 'other@example.com', password: 'pass' },
})
// Team
const team = await prisma.team.create({
data: { name: 'Team A' },
})
// Memberships
await prisma.teamMember.create({
data: { teamId: team.id, userId: userOwner.id, role: 'owner' },
})
await prisma.teamMember.create({
data: { teamId: team.id, userId: userEditor.id, role: 'editor' },
})
await prisma.teamMember.create({
data: { teamId: team.id, userId: userReviewer.id, role: 'reviewer' },
})
// Project & Asset
const project = await prisma.project.create({
data: { name: 'Project A', teamId: team.id },
})
const asset = await prisma.asset.create({
data: {
name: 'File A',
projectId: project.id,
type: 'file',
status: 'processed',
},
})
// Collection
const collection = await prisma.collection.create({
data: {
name: 'Collection A',
projectId: project.id,
filter: {
sourceFolderId: 'root',
searchFilter: { conditions: [], operator: 'AND', recursively: true, isSemantic: false },
},
},
})
// Project Scope User
const userProjectEditor = await prisma.user.create({
data: { name: 'p_editor', email: 'p_editor@example.com', password: 'pass' },
})
const tmPe = await prisma.teamMember.create({
data: {
teamId: team.id,
userId: userProjectEditor.id,
role: 'reviewer',
scope: 'project',
},
})
await prisma.projectMember.create({
data: { projectId: project.id, teamMemberId: tmPe.id, role: 'editor' },
})
const tests = [
{
name: 'Owner can Admin Project',
req: {
type: ResourceType.Project,
id: project.id,
user: userOwner,
permission: Permission.Admin,
},
wantErr: false,
},
{
name: 'Editor cannot Admin Project',
req: {
type: ResourceType.Project,
id: project.id,
user: userEditor,
permission: Permission.Admin,
},
wantErr: true,
},
{
name: 'Editor can Edit Project',
req: {
type: ResourceType.Project,
id: project.id,
user: userEditor,
permission: Permission.Edit,
},
wantErr: false,
},
{
name: 'Reviewer cannot Edit Project',
req: {
type: ResourceType.Project,
id: project.id,
user: userReviewer,
permission: Permission.Edit,
},
wantErr: true,
},
{
name: 'Reviewer can Read Project',
req: {
type: ResourceType.Project,
id: project.id,
user: userReviewer,
permission: Permission.Read,
},
wantErr: false,
},
{
name: 'Non-member cannot Read Project',
req: {
type: ResourceType.Project,
id: project.id,
user: userOther,
permission: Permission.Read,
},
wantErr: true,
errMessage: 'is not a member of the team',
},
{
name: 'Project Editor can Edit Project',
req: {
type: ResourceType.Project,
id: project.id,
user: userProjectEditor,
permission: Permission.Edit,
},
wantErr: false,
},
{
name: 'Project Editor cannot Admin Project',
req: {
type: ResourceType.Project,
id: project.id,
user: userProjectEditor,
permission: Permission.Admin,
},
wantErr: true,
},
{
name: 'Project Scope User can Read Team',
req: {
type: ResourceType.Team,
id: team.id,
user: userProjectEditor,
permission: Permission.Read,
},
wantErr: false,
},
{
name: 'Project Scope User cannot Edit Team',
req: {
type: ResourceType.Team,
id: team.id,
user: userProjectEditor,
permission: Permission.Edit,
},
wantErr: true,
errMessage: 'User has only project scope',
},
{
name: 'Resolve Context from Asset',
req: {
type: ResourceType.Asset,
id: asset.id,
user: userOwner,
permission: Permission.Edit,
},
wantErr: false,
},
{
name: 'Resolve Context from Collection',
req: {
type: ResourceType.Collection,
id: collection.id,
user: userOwner,
permission: Permission.Edit,
},
wantErr: false,
},
{
name: 'Asset Not Found',
req: {
type: ResourceType.Asset,
id: '01HJXXW6A61234567890ABCDEF',
user: userOwner,
permission: Permission.Read,
},
wantErr: true,
errMessage: 'Asset not found',
},
]
for (const tt of tests) {
if (tt.wantErr) {
let err
try {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
await authzService.hasPermission(tt.req as any)
// eslint-disable-next-line @typescript-eslint/no-explicit-any
} catch (e: any) {
err = e
}
expect(err, tt.name).toBeDefined()
if (tt.errMessage) {
expect(err.message).include(tt.errMessage)
}
} else {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
await expect(authzService.hasPermission(tt.req as any), tt.name).resolves.toBeUndefined()
}
}
})
it('should resolve context correctly for each ResourceType', async () => {
// Setup complete data graph for all types
const team = await prisma.team.create({ data: { name: 'Team X' } })
const project = await prisma.project.create({ data: { name: 'Project X', teamId: team.id } })
// Asset (Project-scoped)
const assetProject = await prisma.asset.create({
data: { name: 'Asset P', projectId: project.id, type: 'file', status: 'processed' },
})
// Asset (Team-scoped root folder fallback)
const assetTeam = await prisma.asset.create({
data: { name: 'Team Root', type: 'root', status: 'processed' },
})
await prisma.team.update({
where: { id: team.id },
data: { rootFolderId: assetTeam.id },
})
// Collection
const collection = await prisma.collection.create({
data: {
name: 'Coll',
projectId: project.id,
filter: {
sourceFolderId: 'root',
searchFilter: { conditions: [], operator: 'AND', recursively: true, isSemantic: false },
},
},
})
// Agent & Session
const user = await prisma.user.create({
data: { name: 'BotUser2', email: 'bot2@example.com', password: 'p' },
})
const agent = await prisma.agent.create({
data: {
id: user.id,
teamId: team.id,
type: 'chat',
enabled: true,
config: { provider: 'openai', model: 'gpt-4o' },
},
})
const agentSession = await prisma.agentSession.create({
data: { agentId: agent.id, cwd: '/tmp' },
})
// Share
const share = await prisma.shareLink.create({
data: { name: 'Share1', rootFolderId: assetProject.id, projectId: project.id },
})
// Metadata Field
const teamField = await prisma.metadataField.create({
data: {
key: 'field_t',
scope: 'TEAM',
teamId: team.id,
config: { name: 'Field T', type: 'text' },
},
})
const projectField = await prisma.metadataField.create({
data: {
key: 'field_p',
scope: 'PROJECT',
projectId: project.id,
config: { name: 'Field P', type: 'text' },
},
})
// Skill
const skill = await prisma.skill.create({
data: { name: 'Skill 1', teamId: team.id, hash: '123', assetId: assetProject.id },
})
// Provider
const provider = await prisma.provider.create({
data: { name: 'Prov 1', teamId: team.id, config: { api: 'openai' } },
})
// Invite
const inviteTeam = await prisma.invite.create({
data: { code: 'inv_t', teamId: team.id, role: 'editor', inviterId: user.id },
})
const inviteProject = await prisma.invite.create({
data: {
code: 'inv_p',
teamId: team.id,
projectId: project.id,
role: 'editor',
inviterId: user.id,
},
})
// Comment
const comment = await prisma.assetComment.create({
data: { assetId: assetProject.id, creatorId: user.id, message: 'hello' },
})
// Test execution via cast
const resolveContext = (type: ResourceType, id: string) =>
(
authzService as unknown as {
resolveContext: (
type: ResourceType,
id: string,
) => Promise<{ teamId: string; projectId?: string }>
}
).resolveContext(type, id)
// Tests
await expect(resolveContext(ResourceType.Team, team.id)).resolves.toEqual({ teamId: team.id })
await expect(resolveContext(ResourceType.Project, project.id)).resolves.toEqual({
teamId: team.id,
projectId: project.id,
})
await expect(resolveContext(ResourceType.Asset, assetProject.id)).resolves.toEqual({
teamId: team.id,
projectId: project.id,
})
await expect(resolveContext(ResourceType.Asset, assetTeam.id)).resolves.toEqual({
teamId: team.id,
})
await expect(resolveContext(ResourceType.Collection, collection.id)).resolves.toEqual({
teamId: team.id,
projectId: project.id,
})
await expect(resolveContext(ResourceType.Agent, agent.id)).resolves.toEqual({ teamId: team.id })
await expect(resolveContext(ResourceType.AgentSession, agentSession.id)).resolves.toEqual({
teamId: team.id,
})
await expect(resolveContext(ResourceType.Share, share.id)).resolves.toEqual({
teamId: team.id,
projectId: project.id,
})
await expect(resolveContext(ResourceType.MetadataField, teamField.key)).resolves.toEqual({
teamId: team.id,
})
await expect(resolveContext(ResourceType.MetadataField, projectField.key)).resolves.toEqual({
teamId: team.id,
projectId: project.id,
})
await expect(resolveContext(ResourceType.Skill, skill.id)).resolves.toEqual({ teamId: team.id })
await expect(resolveContext(ResourceType.Provider, provider.id)).resolves.toEqual({
teamId: team.id,
})
await expect(resolveContext(ResourceType.Invite, inviteTeam.id)).resolves.toEqual({
teamId: team.id,
projectId: undefined,
})
await expect(resolveContext(ResourceType.Invite, inviteProject.id)).resolves.toEqual({
teamId: team.id,
projectId: project.id,
})
await expect(resolveContext(ResourceType.Comment, comment.id)).resolves.toEqual({
teamId: team.id,
projectId: project.id,
})
})
})
-236
View File
@@ -1,236 +0,0 @@
import { prisma } from '@shumai/db'
import type { Prisma } from '@/generated/prisma/client.ts'
type User = Prisma.UserGetPayload<Record<string, never>>
export enum Permission {
Read = 'Read',
Edit = 'Edit',
Admin = 'Admin',
}
export enum ResourceType {
Team = 'team',
Project = 'project',
Asset = 'asset',
Collection = 'collection',
Agent = 'agent',
Share = 'share',
MetadataField = 'metadataField',
Skill = 'skill',
Provider = 'provider',
Invite = 'invite',
Comment = 'comment',
AgentSession = 'agentSession',
}
export interface AuthzRequest {
user: User
permission: Permission
type: ResourceType
id: string
}
export class AuthzService {
async hasPermission(req: AuthzRequest): Promise<void> {
if (!req.user) throw new Error('User is required')
const { teamId, projectId } = await this.resolveContext(req.type, req.id)
// 1. Check Team Membership
const member = await prisma.teamMember.findUnique({
where: {
teamIdUserId: {
teamId: teamId,
userId: req.user.id,
},
},
})
if (!member) throw new Error('User is not a member of the team')
// 2. Check Scope
if (member.scope === 'team') {
return this.checkRole(member.role, req.permission)
}
// 3. Scope is Project
if (!projectId) {
// User has project scope but no project context provided (e.g. Team-level resource)
// If it's a team-level resource, project-scoped users shouldn't have access except for Read maybe?
// But usually team resources like Skills/Providers are managed by Team Owners/Editors.
// For now, let's keep the logic: project-scoped users can't access team-level resources unless it's Read (like ListProjects).
if (req.permission === Permission.Read) {
return
}
throw new Error('User has only project scope')
}
// Check Project Membership
const pm = await prisma.projectMember.findUnique({
where: {
projectIdTeamMemberId: {
projectId: projectId,
teamMemberId: member.id,
},
},
})
if (!pm) throw new Error(`User is not a member of project ${projectId}`)
return this.checkRole(pm.role, req.permission)
}
private async resolveContext(
type: ResourceType,
id: string,
): Promise<{ teamId: string; projectId?: string }> {
switch (type) {
case ResourceType.Team:
return { teamId: id }
case ResourceType.Project: {
const proj = await prisma.project.findUnique({
where: { id },
select: { teamId: true },
})
if (!proj) throw new Error('Project not found')
return { teamId: proj.teamId, projectId: id }
}
case ResourceType.Asset: {
const asset = await prisma.asset.findUnique({
where: { id },
select: {
parentId: true,
teamRootFolder: { select: { id: true } },
project: { select: { id: true, teamId: true } },
},
})
if (!asset) throw new Error('Asset not found')
if (asset.project) {
return { teamId: asset.project.teamId, projectId: asset.project.id }
}
if (asset.teamRootFolder) {
return { teamId: asset.teamRootFolder.id }
}
if (asset.parentId) {
// If it's a nested asset, we might need recursive lookup.
// However, in this project, assets typically have projectId if they are in a project.
// If parentId is set but no project, it might be in a team root folder.
// For now, let's try to get context from parent.
return this.resolveContext(ResourceType.Asset, asset.parentId)
}
throw new Error('Could not resolve context for asset')
}
case ResourceType.Collection: {
const coll = await prisma.collection.findUnique({
where: { id },
include: { project: true },
})
if (!coll) throw new Error('Collection not found')
return { teamId: coll.project.teamId, projectId: coll.projectId }
}
case ResourceType.Agent: {
const agent = await prisma.agent.findUnique({
where: { id },
select: { teamId: true },
})
if (!agent) throw new Error('Agent not found')
return { teamId: agent.teamId }
}
case ResourceType.AgentSession: {
const session = await prisma.agentSession.findUnique({
where: { id },
include: { agent: true },
})
if (!session) throw new Error('Agent session not found')
return { teamId: session.agent.teamId }
}
case ResourceType.Share: {
const share = await prisma.shareLink.findUnique({
where: { id },
include: { project: true },
})
if (!share) throw new Error('Share not found')
return { teamId: share.project.teamId, projectId: share.projectId }
}
case ResourceType.MetadataField: {
const field = await prisma.metadataField.findUnique({
where: { key: id },
select: { teamId: true, projectId: true },
})
if (!field) throw new Error('Metadata field not found')
if (field.projectId) {
const proj = await prisma.project.findUnique({
where: { id: field.projectId },
select: { teamId: true },
})
return { teamId: proj!.teamId, projectId: field.projectId }
}
if (!field.teamId) throw new Error('Metadata field has no context')
return { teamId: field.teamId }
}
case ResourceType.Skill: {
const skill = await prisma.skill.findUnique({
where: { id },
select: { teamId: true },
})
if (!skill) throw new Error('Skill not found')
return { teamId: skill.teamId }
}
case ResourceType.Provider: {
const provider = await prisma.provider.findUnique({
where: { id },
select: { teamId: true },
})
if (!provider) throw new Error('Provider not found')
return { teamId: provider.teamId }
}
case ResourceType.Invite: {
const invite = await prisma.invite.findUnique({
where: { id },
select: { teamId: true, projectId: true },
})
if (!invite) throw new Error('Invite not found')
return { teamId: invite.teamId, projectId: invite.projectId ?? undefined }
}
case ResourceType.Comment: {
const comment = await prisma.assetComment.findUnique({
where: { id },
include: { asset: { include: { project: true } } },
})
if (!comment) throw new Error('Comment not found')
if (!comment.asset.project) throw new Error('Comment asset has no project')
return { teamId: comment.asset.project.teamId, projectId: comment.asset.projectId! }
}
default:
throw new Error(`Unsupported resource type: ${type}`)
}
}
private checkRole(role: string, permission: Permission): void {
switch (permission) {
case Permission.Read:
return
case Permission.Edit:
if (role === 'owner' || role === 'editor') return
break
case Permission.Admin:
if (role === 'owner') return
break
}
throw new Error('Permission denied')
}
}
export const authzService = new AuthzService()
-149
View File
@@ -1,149 +0,0 @@
import { describe, it, expect } from 'vitest'
import { prisma } from '@shumai/db'
import { setupTestDbHooks } from '@shumai/db'
import { collectionService } from './collection'
import { projectService } from '../project/project'
describe('CollectionService', () => {
setupTestDbHooks()
async function setupProject() {
const user = await prisma.user.create({
data: { name: 'Test User', email: 'test@example.com' },
})
const team = await prisma.team.create({
data: {
name: 'Test Team',
settings: {
enablePublicSignup: true,
transcode: { videoStrategy: 'best_match' },
},
sandbox: { create: {} },
},
})
await prisma.teamMember.create({
data: {
teamId: team.id,
userId: user.id,
role: 'owner',
scope: 'team',
},
})
const project = await projectService.createProject(user, {
teamId: team.id,
name: 'Test Project',
})
return { team, project }
}
it('can create, get, update, and delete a collection', async () => {
const { project } = await setupProject()
// Create
const collection = await collectionService.createCollection(project.id, {
name: 'Test Collection',
filter: {
sourceFolderId: project.rootFolder!,
searchFilter: {
operator: 'AND',
conditions: [{ field: 'name', operator: 'contains', value: 'test' }],
recursively: true,
isSemantic: false,
},
},
})
expect(collection.name).toBe('Test Collection')
// eslint-disable-next-line @typescript-eslint/no-explicit-any
expect((collection.filter as any).searchFilter.conditions[0].value).toBe('test')
// Get
const fetched = await collectionService.getCollection(collection.id)
expect(fetched?.id).toBe(collection.id)
// Update
const updated = await collectionService.updateCollection(collection.id, {
name: 'Updated Name',
filter: {
sourceFolderId: project.rootFolder!,
searchFilter: {
operator: 'AND',
conditions: [{ field: 'rating', operator: 'eq', value: 5 }],
recursively: true,
isSemantic: false,
},
},
})
expect(updated.name).toBe('Updated Name')
// eslint-disable-next-line @typescript-eslint/no-explicit-any
expect((updated.filter as any).searchFilter.conditions[0].field).toBe('rating')
// Delete
await collectionService.deleteCollection(collection.id)
const deleted = await collectionService.getCollection(collection.id)
expect(deleted).toBeNull()
})
it('can list collections for a project with pagination', async () => {
const { project } = await setupProject()
// Create multiple collections
for (let i = 0; i < 5; i++) {
await collectionService.createCollection(project.id, {
name: `Collection ${i}`,
filter: {
sourceFolderId: project.rootFolder!,
searchFilter: { operator: 'AND', conditions: [], recursively: true, isSemantic: false },
},
})
}
// List first page
const list1 = await collectionService.listCollections(project.id, {
first: 2,
includeCount: true,
})
expect(list1.data.length).toBe(2)
expect(list1.pageInfo.total).toBe(5)
expect(list1.pageInfo.cursor).toBeDefined()
// List second page
const list2 = await collectionService.listCollections(project.id, {
first: 2,
after: list1.pageInfo.cursor,
})
expect(list2.data.length).toBe(2)
expect(list2.data[0].name).not.toBe(list1.data[0].name)
// List last page
const list3 = await collectionService.listCollections(project.id, {
first: 2,
after: list2.pageInfo.cursor,
})
expect(list3.data.length).toBe(1)
expect(list3.pageInfo.cursor).toBeUndefined()
})
it('cascades delete when project is deleted', async () => {
const { project } = await setupProject()
await collectionService.createCollection(project.id, {
name: 'To be deleted',
filter: {
sourceFolderId: project.rootFolder!,
searchFilter: { operator: 'AND', conditions: [], recursively: true, isSemantic: false },
},
})
const countBefore = await prisma.collection.count({
where: { projectId: project.id },
})
expect(countBefore).toBe(1)
await projectService.deleteProject(project.id)
const countAfter = await prisma.collection.count({
where: { projectId: project.id },
})
expect(countAfter).toBe(0)
})
})
-59
View File
@@ -1,59 +0,0 @@
import { prisma } from '@shumai/db'
import { paginateQuery } from '../pagination'
import {
CreateCollectionRequest,
UpdateCollectionRequest,
ListCollectionsRequest,
} from '@shumai/dtos'
export class CollectionService {
async createCollection(projectId: string, req: CreateCollectionRequest) {
return await prisma.collection.create({
data: {
name: req.name,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
filter: req.filter as any,
projectId,
},
})
}
async updateCollection(collectionId: string, req: UpdateCollectionRequest) {
return await prisma.collection.update({
where: { id: collectionId },
data: {
...(req.name && { name: req.name }),
// eslint-disable-next-line @typescript-eslint/no-explicit-any
...(req.filter && { filter: req.filter as any }),
},
})
}
async deleteCollection(collectionId: string) {
return await prisma.collection.delete({
where: { id: collectionId },
})
}
async getCollection(collectionId: string) {
return await prisma.collection.findUnique({
where: { id: collectionId },
})
}
async listCollections(projectId: string, req: ListCollectionsRequest) {
return await paginateQuery(
(skip, take) =>
prisma.collection.findMany({
where: { projectId },
orderBy: { id: 'desc' },
skip,
take,
}),
() => prisma.collection.count({ where: { projectId } }),
req,
)
}
}
export const collectionService = new CollectionService()
-27
View File
@@ -1,27 +0,0 @@
import { describe, expect, it } from 'vitest'
import { marshal, unmarshal } from './hyrumtoken'
const testkey = new Uint8Array([
24, 12, 15, 90, 143, 133, 171, 28, 34, 75, 185, 194, 102, 93, 165, 183, 235, 96, 135, 135, 165, 1,
129, 91, 32, 7, 139, 135, 130, 2, 241, 168,
])
describe('hyrumtoken', () => {
it('encodes and decodes', () => {
const data = { Foo: 'foo', Bar: 'bar' }
const encoded = marshal(testkey, data)
const out = unmarshal(testkey, encoded)
expect(out).toEqual(data)
})
it('unmarshals empty string to null', () => {
const out = unmarshal(testkey, '')
expect(out).toBeNull()
})
it('unmarshals known string', () => {
const token = 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAULRUMRVA4GIqe5Y8N_z8B4J7hw'
const out = unmarshal(testkey, token)
expect(out).toBe(123)
})
})
-35
View File
@@ -1,35 +0,0 @@
import { Buffer } from 'buffer'
import nacl from 'tweetnacl'
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export function marshal(key: Uint8Array, v: any): string {
const b = Buffer.from(JSON.stringify(v), 'utf8')
const nonce = nacl.randomBytes(nacl.secretbox.nonceLength)
const d = nacl.secretbox(b, nonce, key)
const combined = Buffer.concat([nonce, d])
return combined.toString('base64url')
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export function unmarshal(key: Uint8Array, s: string): any {
if (!s) {
return null
}
const combined = Buffer.from(s, 'base64url')
if (combined.length < nacl.secretbox.nonceLength) {
throw new Error('token too short')
}
const nonce = combined.subarray(0, nacl.secretbox.nonceLength)
const d = combined.subarray(nacl.secretbox.nonceLength)
const b = nacl.secretbox.open(d, nonce, key)
if (!b) {
throw new Error('decrypt token failed')
}
const jsonStr = Buffer.from(b).toString('utf8')
return JSON.parse(jsonStr)
}

Some files were not shown because too many files have changed in this diff Show More