mirror of
https://github.com/shumaiOne/shumai.git
synced 2026-11-28 20:04:26 +00:00
initial commit
This commit is contained in:
@@ -0,0 +1,45 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { setupTestDbHooks } from '@/db-test-hooks'
|
||||
import { aiChatActivity } from './agent'
|
||||
import { agentExecutor } from '../executor'
|
||||
|
||||
vi.mock('../executor', () => ({
|
||||
agentExecutor: {
|
||||
chatWithAgent: vi.fn(),
|
||||
},
|
||||
}))
|
||||
|
||||
describe('Agent Activities', () => {
|
||||
setupTestDbHooks()
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
it('should call aiChatActivity', async () => {
|
||||
vi.mocked(agentExecutor.chatWithAgent).mockResolvedValue({
|
||||
text: 'AI response',
|
||||
usage: { inputTokens: 1, outputTokens: 1, model: 'gpt-4' },
|
||||
sessionId: 'mock-session-id',
|
||||
})
|
||||
|
||||
await aiChatActivity({
|
||||
teamId: 't1',
|
||||
agentId: 'b1',
|
||||
message: 'Hi',
|
||||
imageUrls: [],
|
||||
projectId: 'p1',
|
||||
folderId: 'f1',
|
||||
})
|
||||
|
||||
expect(agentExecutor.chatWithAgent).toHaveBeenCalledWith(
|
||||
't1',
|
||||
'b1',
|
||||
'Hi',
|
||||
[],
|
||||
'',
|
||||
undefined,
|
||||
undefined,
|
||||
)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,70 @@
|
||||
import { agentExecutor, AutofillField } from '../executor'
|
||||
import { prisma } from '@/db'
|
||||
|
||||
export interface AutofillAiParams {
|
||||
teamId: string
|
||||
images: string[]
|
||||
fields: AutofillField[]
|
||||
}
|
||||
|
||||
export async function autofillAiActivity(params: AutofillAiParams) {
|
||||
const prompt = 'Analyze the provided images and extract metadata.'
|
||||
return agentExecutor.autofill(params.teamId, prompt, params.images, params.fields)
|
||||
}
|
||||
|
||||
export interface AiChatParams {
|
||||
teamId: string
|
||||
agentId: string
|
||||
message: string
|
||||
imageUrls: string[]
|
||||
projectId: string
|
||||
folderId: string
|
||||
agentsInstruction?: string
|
||||
sessionId?: string
|
||||
userId?: string
|
||||
}
|
||||
|
||||
export async function aiChatActivity(params: AiChatParams) {
|
||||
const cleanMessage = params.message.replace(/<@[A-Z0-9]+>/g, '').trim()
|
||||
return agentExecutor.chatWithAgent(
|
||||
params.teamId,
|
||||
params.agentId,
|
||||
cleanMessage,
|
||||
params.imageUrls,
|
||||
params.agentsInstruction || '',
|
||||
params.sessionId,
|
||||
params.userId,
|
||||
)
|
||||
}
|
||||
|
||||
export interface CreateCommentParams {
|
||||
assetId: string
|
||||
message: string
|
||||
isAi?: boolean
|
||||
agentId?: string | null
|
||||
replyToId?: string | null
|
||||
}
|
||||
|
||||
export async function createCommentActivity(params: CreateCommentParams) {
|
||||
return prisma.assetComment.create({
|
||||
data: {
|
||||
assetId: params.assetId,
|
||||
message: params.message,
|
||||
isAi: params.isAi ?? false,
|
||||
creatorId: params.agentId && params.agentId !== 'default' ? params.agentId : null,
|
||||
replyToId: params.replyToId,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
export interface UpdateCommentParams {
|
||||
commentId: string
|
||||
message: string
|
||||
}
|
||||
|
||||
export async function updateCommentActivity(params: UpdateCommentParams) {
|
||||
return prisma.assetComment.update({
|
||||
where: { id: params.commentId },
|
||||
data: { message: params.message },
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,146 @@
|
||||
import { describe, it, expect, beforeEach, vi } from 'vitest'
|
||||
import { prisma } from '@/db'
|
||||
import { setupTestDbHooks } from '@/db-test-hooks'
|
||||
import { DatabaseSessionManager } from './database-session-manager'
|
||||
import { s3Service } from '@/services/s3/s3'
|
||||
|
||||
vi.mock('@/services/s3/s3', () => ({
|
||||
s3Service: {
|
||||
getObject: vi.fn(),
|
||||
},
|
||||
}))
|
||||
|
||||
describe('DatabaseSessionManager', () => {
|
||||
setupTestDbHooks()
|
||||
|
||||
let agentId: string
|
||||
|
||||
beforeEach(async () => {
|
||||
const user = await prisma.user.create({
|
||||
data: { name: 'Test Agent', email: 'agent@test.com', type: 'agent' },
|
||||
})
|
||||
await prisma.agent.create({
|
||||
data: {
|
||||
id: user.id,
|
||||
type: 'chat',
|
||||
config: { provider: 'openai', model: 'gpt-4o' },
|
||||
},
|
||||
})
|
||||
agentId = user.id
|
||||
})
|
||||
|
||||
it('creates a new session in DB', async () => {
|
||||
const manager = await DatabaseSessionManager.create({ agentId })
|
||||
const sessionId = manager.getDbSessionId()
|
||||
expect(sessionId).toBeDefined()
|
||||
|
||||
const session = await prisma.agentSession.findUnique({ where: { id: sessionId } })
|
||||
expect(session).toBeDefined()
|
||||
expect(session?.agentId).toBe(agentId)
|
||||
})
|
||||
|
||||
it('persists message entries to DB', async () => {
|
||||
const manager = await DatabaseSessionManager.create({ agentId })
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
manager.appendMessage({ role: 'user', content: 'Hello' } as any)
|
||||
await manager.waitForSync()
|
||||
|
||||
const sessionId = manager.getDbSessionId()
|
||||
const entries = await prisma.agentSessionEntry.findMany({ where: { sessionId } })
|
||||
expect(entries).toHaveLength(1)
|
||||
// In simplified schema, type/parentId are part of the entry object
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const entry = entries[0].entry as any
|
||||
expect(entry.type).toBe('message')
|
||||
expect(entry.message.content).toBe('Hello')
|
||||
|
||||
const session = await prisma.agentSession.findUnique({ where: { id: sessionId } })
|
||||
expect(session?.leafId).toBe(entries[0].id)
|
||||
})
|
||||
|
||||
it('loads existing session from DB', async () => {
|
||||
const manager1 = await DatabaseSessionManager.create({ agentId })
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const msgId = manager1.appendMessage({ role: 'user', content: 'Message 1' } as any)
|
||||
await manager1.waitForSync()
|
||||
const sessionId = manager1.getDbSessionId()
|
||||
|
||||
const manager2 = await DatabaseSessionManager.create({ agentId, sessionId })
|
||||
expect(manager2.getDbSessionId()).toBe(sessionId)
|
||||
expect(manager2.getLeafId()).toBe(msgId)
|
||||
|
||||
const context = manager2.buildSessionContext()
|
||||
expect(context.messages).toHaveLength(1)
|
||||
expect(context.messages[0].content).toBe('Message 1')
|
||||
})
|
||||
|
||||
it('re-injects image data from S3', async () => {
|
||||
const session = await prisma.agentSession.create({
|
||||
data: { agentId, cwd: '/tmp' },
|
||||
})
|
||||
|
||||
const entry = {
|
||||
id: 'e1',
|
||||
type: 'message',
|
||||
message: {
|
||||
role: 'toolResult',
|
||||
content: [
|
||||
{ type: 'image', data: '__S3_DATA__' },
|
||||
],
|
||||
details: { sourceKeys: ['key1'] },
|
||||
},
|
||||
}
|
||||
|
||||
await prisma.agentSessionEntry.create({
|
||||
data: {
|
||||
id: entry.id,
|
||||
sessionId: session.id,
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
entry: entry as any,
|
||||
},
|
||||
})
|
||||
|
||||
vi.mocked(s3Service.getObject).mockResolvedValue({
|
||||
buffer: Buffer.from('fake-image-data'),
|
||||
contentType: 'image/png',
|
||||
})
|
||||
|
||||
const manager = await DatabaseSessionManager.create({ agentId, sessionId: session.id })
|
||||
const context = manager.buildSessionContext()
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const reInjectedMessage = context.messages[0] as any
|
||||
|
||||
expect(reInjectedMessage.content[0].data).toBe(Buffer.from('fake-image-data').toString('base64'))
|
||||
expect(s3Service.getObject).toHaveBeenCalledWith(expect.any(String), 'key1')
|
||||
})
|
||||
|
||||
it('handles branching', async () => {
|
||||
const manager = await DatabaseSessionManager.create({ agentId })
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const m1Id = manager.appendMessage({ role: 'user', content: 'M1' } as any)
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
manager.appendMessage({ role: 'assistant', content: 'A1' } as any)
|
||||
await manager.waitForSync()
|
||||
|
||||
// Branch from M1
|
||||
manager.branch(m1Id)
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const m2Id = manager.appendMessage({ role: 'user', content: 'M2' } as any)
|
||||
await manager.waitForSync()
|
||||
|
||||
const sessionId = manager.getDbSessionId()
|
||||
const entries = await prisma.agentSessionEntry.findMany({ where: { sessionId } })
|
||||
expect(entries).toHaveLength(3)
|
||||
|
||||
const m2Entry = entries.find((e) => e.id === m2Id)
|
||||
// parentId is now inside the entry object
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
expect((m2Entry?.entry as any).parentId).toBe(m1Id)
|
||||
|
||||
const context = manager.buildSessionContext()
|
||||
expect(context.messages).toHaveLength(2)
|
||||
expect(context.messages[0].content).toBe('M1')
|
||||
expect(context.messages[1].content).toBe('M2')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,136 @@
|
||||
import { prisma } from '@/db'
|
||||
import { s3Service } from '@/services/s3/s3'
|
||||
import { SessionEntry, SessionManager } from '@mariozechner/pi-coding-agent'
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
export class DatabaseSessionManager extends (SessionManager as any) {
|
||||
private dbSessionId: string
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
private writeQueue: Promise<any> = Promise.resolve()
|
||||
|
||||
private constructor(sessionId: string, cwd: string) {
|
||||
super(cwd, '', undefined, false) // persist = false, we handle it manually
|
||||
this.dbSessionId = sessionId
|
||||
}
|
||||
|
||||
static async create(params: {
|
||||
agentId: string
|
||||
userId?: string
|
||||
sessionId?: string
|
||||
cwd?: string
|
||||
}): Promise<DatabaseSessionManager> {
|
||||
const sessionId = params.sessionId
|
||||
const cwd = params.cwd || process.cwd()
|
||||
|
||||
if (sessionId) {
|
||||
const session = await prisma.agentSession.findUnique({
|
||||
where: { id: sessionId },
|
||||
include: { entries: { orderBy: { id: 'asc' } } },
|
||||
})
|
||||
if (!session) {
|
||||
throw new Error(`Session ${sessionId} not found`)
|
||||
}
|
||||
const manager = new DatabaseSessionManager(sessionId, session.cwd)
|
||||
// Load entries into in-memory SessionManager
|
||||
for (const e of session.entries) {
|
||||
const entry = e.entry
|
||||
|
||||
// Dynamically re-inject image data if it was stripped
|
||||
if (entry.type === 'message' && entry.message.role === 'toolResult') {
|
||||
const msg = entry.message
|
||||
const details = msg.details as { sourceKeys?: string[] } | undefined
|
||||
if (Array.isArray(msg.content) && details?.sourceKeys) {
|
||||
const sourceKeys = details.sourceKeys
|
||||
let keyIdx = 0
|
||||
for (const item of msg.content) {
|
||||
if (item.type === 'image' && item.data === '__S3_DATA__' && sourceKeys[keyIdx]) {
|
||||
const key = sourceKeys[keyIdx]
|
||||
try {
|
||||
const { buffer } = await s3Service.getObject(process.env.S3_BUCKET || 'shumai', key)
|
||||
item.data = buffer.toString('base64')
|
||||
} catch (err) {
|
||||
console.error(`Failed to re-inject image data for key ${key}:`, err)
|
||||
}
|
||||
keyIdx++
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
manager._appendEntry(entry, false) // false to avoid re-saving
|
||||
}
|
||||
return manager
|
||||
} else {
|
||||
const session = await prisma.agentSession.create({
|
||||
data: {
|
||||
agentId: params.agentId,
|
||||
userId: params.userId,
|
||||
cwd: cwd,
|
||||
},
|
||||
})
|
||||
return new DatabaseSessionManager(session.id, cwd)
|
||||
}
|
||||
}
|
||||
|
||||
// Override _appendEntry to save to database
|
||||
// Note: we use (manager as any)._appendEntry = ... in static factory if needed,
|
||||
// but since we extend it, we can just define it here.
|
||||
// We need to match the signature of the base class.
|
||||
protected _appendEntry(entry: SessionEntry, shouldSave = true) {
|
||||
// Call super._appendEntry (which is private, so we use the prototype)
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const superAppendEntry = (SessionManager.prototype as any)['_appendEntry']
|
||||
superAppendEntry.call(this, entry)
|
||||
|
||||
if (shouldSave) {
|
||||
this.saveEntryToDb(entry)
|
||||
}
|
||||
}
|
||||
|
||||
private saveEntryToDb(entry: SessionEntry) {
|
||||
this.writeQueue = this.writeQueue.then(async () => {
|
||||
try {
|
||||
// Deep clone to avoid stripping data from the in-memory session manager
|
||||
const strippedEntry = JSON.parse(JSON.stringify(entry)) as SessionEntry
|
||||
|
||||
// Strip image data before saving to DB
|
||||
if (strippedEntry.type === 'message' && strippedEntry.message.role === 'toolResult') {
|
||||
const msg = strippedEntry.message
|
||||
const details = msg.details as { sourceKeys?: string[] } | undefined
|
||||
if (Array.isArray(msg.content) && details?.sourceKeys) {
|
||||
const sourceKeys = details.sourceKeys
|
||||
let keyIdx = 0
|
||||
msg.content.forEach((item) => {
|
||||
if (item.type === 'image' && sourceKeys[keyIdx]) {
|
||||
item.data = '__S3_DATA__'
|
||||
keyIdx++
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
await prisma.agentSessionEntry.create({
|
||||
data: {
|
||||
id: strippedEntry.id,
|
||||
sessionId: this.dbSessionId,
|
||||
entry: strippedEntry,
|
||||
},
|
||||
})
|
||||
await prisma.agentSession.update({
|
||||
where: { id: this.dbSessionId },
|
||||
data: { leafId: strippedEntry.id },
|
||||
})
|
||||
} catch (err) {
|
||||
console.error('Failed to save session entry to DB:', err)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
async waitForSync() {
|
||||
await this.writeQueue
|
||||
}
|
||||
|
||||
getDbSessionId() {
|
||||
return this.dbSessionId
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,250 @@
|
||||
import { describe, expect, it, vi, beforeEach } from 'vitest'
|
||||
import { prisma } from '@/db'
|
||||
import { setupTestDbHooks } from '@/db-test-hooks'
|
||||
import { agentExecutor, type AutofillField } from './executor'
|
||||
import * as piAgent from '@mariozechner/pi-coding-agent'
|
||||
|
||||
vi.mock('@mariozechner/pi-coding-agent', async () => {
|
||||
const actual = await vi.importActual('@mariozechner/pi-coding-agent')
|
||||
return {
|
||||
...actual,
|
||||
createAgentSession: vi.fn(),
|
||||
}
|
||||
})
|
||||
|
||||
const mockProviderConfig: PrismaJson.ProviderConfig = {
|
||||
api: 'openai-completions',
|
||||
baseUrl: 'http://localhost:11434/v1',
|
||||
apiKey: 'test-key',
|
||||
}
|
||||
|
||||
const mockModelConfig: PrismaJson.ModelConfig = {
|
||||
reasoning: false,
|
||||
input: ['text'],
|
||||
contextWindow: 1000,
|
||||
maxTokens: 1000,
|
||||
cost: {
|
||||
input: 0,
|
||||
output: 0,
|
||||
cacheRead: 0,
|
||||
cacheWrite: 0,
|
||||
},
|
||||
}
|
||||
|
||||
describe('AgentExecutor', () => {
|
||||
setupTestDbHooks()
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
it('autofills with agent', async () => {
|
||||
const team = await prisma.team.create({
|
||||
data: {
|
||||
name: 'Autofill Team',
|
||||
},
|
||||
})
|
||||
|
||||
const provider = await prisma.provider.create({
|
||||
data: {
|
||||
name: 'openai',
|
||||
teamId: team.id,
|
||||
config: mockProviderConfig,
|
||||
},
|
||||
})
|
||||
|
||||
const model = await prisma.model.create({
|
||||
data: {
|
||||
modelId: 'gpt-4',
|
||||
name: 'GPT-4',
|
||||
providerId: provider.id,
|
||||
config: mockModelConfig,
|
||||
},
|
||||
})
|
||||
|
||||
await prisma.user.create({
|
||||
data: {
|
||||
name: 'Autofiller',
|
||||
email: `autofiller-${Date.now()}@shumai.ai`,
|
||||
type: 'agent',
|
||||
agent: {
|
||||
create: {
|
||||
type: 'autofill',
|
||||
enabled: true,
|
||||
providerId: provider.id,
|
||||
modelId: model.id,
|
||||
config: {
|
||||
provider: 'openai',
|
||||
model: 'gpt-4',
|
||||
},
|
||||
},
|
||||
},
|
||||
teamMembers: {
|
||||
create: {
|
||||
teamId: team.id,
|
||||
role: 'reviewer',
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
const mockSession = {
|
||||
sendUserMessage: vi.fn().mockImplementation(async () => {
|
||||
// Find the tool in the session's customTools and call its execute
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const tool = (mockSession as any).customTools.find(
|
||||
(t: unknown) => (t as { name: string }).name === 'autofill_metadata',
|
||||
)
|
||||
if (tool) {
|
||||
await tool.execute('call_1', { data: 1 })
|
||||
}
|
||||
}),
|
||||
getSessionStats: vi.fn().mockReturnValue({ tokens: { input: 5, output: 5 } }),
|
||||
getLastAssistantText: vi.fn().mockReturnValue('{"data": 1}'),
|
||||
state: { tools: [], systemPrompt: '', messages: [] },
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
customTools: [] as any[],
|
||||
}
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
;(piAgent.createAgentSession as any).mockImplementation(async (config: any) => {
|
||||
mockSession.customTools = config.customTools
|
||||
return { session: mockSession }
|
||||
})
|
||||
|
||||
const fields: AutofillField[] = [{ id: 'f1', config: { name: 'Field 1', type: 'text' } }]
|
||||
const resp = await agentExecutor.autofill(team.id, 'extract data', [], fields)
|
||||
expect(resp.text).toBe('{"data":1}')
|
||||
expect(resp.usage.inputTokens).toBe(5)
|
||||
})
|
||||
|
||||
it('chats with bot', async () => {
|
||||
const team = await prisma.team.create({
|
||||
data: {
|
||||
name: 'Chat Bot Team',
|
||||
},
|
||||
})
|
||||
|
||||
const provider = await prisma.provider.create({
|
||||
data: {
|
||||
name: 'google',
|
||||
teamId: team.id,
|
||||
config: mockProviderConfig,
|
||||
},
|
||||
})
|
||||
|
||||
const model = await prisma.model.create({
|
||||
data: {
|
||||
modelId: 'gemini',
|
||||
name: 'Gemini',
|
||||
providerId: provider.id,
|
||||
config: mockModelConfig,
|
||||
},
|
||||
})
|
||||
|
||||
await prisma.user.create({
|
||||
data: {
|
||||
name: 'Chatter',
|
||||
email: `chatter-${Date.now()}@shumai.ai`,
|
||||
type: 'agent',
|
||||
agent: {
|
||||
create: {
|
||||
type: 'chat',
|
||||
enabled: true,
|
||||
providerId: provider.id,
|
||||
modelId: model.id,
|
||||
config: {
|
||||
provider: 'google',
|
||||
model: 'gemini',
|
||||
},
|
||||
},
|
||||
},
|
||||
teamMembers: {
|
||||
create: {
|
||||
teamId: team.id,
|
||||
role: 'reviewer',
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
const mockSession = {
|
||||
sendUserMessage: vi.fn().mockResolvedValue(undefined),
|
||||
getSessionStats: vi.fn().mockReturnValue({ tokens: { input: 5, output: 5 } }),
|
||||
getLastAssistantText: vi.fn().mockReturnValue('mock text'),
|
||||
state: { tools: [], systemPrompt: '', messages: [] },
|
||||
}
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
;(piAgent.createAgentSession as any).mockResolvedValue({ session: mockSession })
|
||||
|
||||
const resp = await agentExecutor.chat(team.id, 'hello')
|
||||
expect(resp.text).toBe('mock text')
|
||||
})
|
||||
|
||||
it('chat with instruction', async () => {
|
||||
const team = await prisma.team.create({
|
||||
data: {
|
||||
name: 'Pirate Team',
|
||||
},
|
||||
})
|
||||
|
||||
const provider = await prisma.provider.create({
|
||||
data: {
|
||||
name: 'google',
|
||||
teamId: team.id,
|
||||
config: mockProviderConfig,
|
||||
},
|
||||
})
|
||||
|
||||
const model = await prisma.model.create({
|
||||
data: {
|
||||
modelId: 'gemini-pro',
|
||||
name: 'Gemini Pro',
|
||||
providerId: provider.id,
|
||||
config: mockModelConfig,
|
||||
},
|
||||
})
|
||||
|
||||
const botUser = await prisma.user.create({
|
||||
data: { name: 'Pirate', email: 'pirate@shumai.ai', type: 'agent' },
|
||||
})
|
||||
|
||||
const agent = await prisma.agent.create({
|
||||
data: {
|
||||
id: botUser.id,
|
||||
type: 'chat',
|
||||
enabled: true,
|
||||
providerId: provider.id,
|
||||
modelId: model.id,
|
||||
soul: 'You are a pirate',
|
||||
config: {
|
||||
provider: 'google',
|
||||
model: 'gemini-pro',
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
await prisma.teamMember.create({
|
||||
data: { teamId: team.id, userId: botUser.id, role: 'reviewer' },
|
||||
})
|
||||
|
||||
const mockSession = {
|
||||
sendUserMessage: vi.fn().mockResolvedValue(undefined),
|
||||
getSessionStats: vi.fn().mockReturnValue({ tokens: { input: 10, output: 20 } }),
|
||||
getLastAssistantText: vi.fn().mockReturnValue('Arr matey!'),
|
||||
state: { tools: [], systemPrompt: '', messages: [] },
|
||||
}
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
;(piAgent.createAgentSession as any).mockResolvedValue({ session: mockSession })
|
||||
|
||||
const resp = await agentExecutor.chatWithAgent(
|
||||
team.id,
|
||||
agent.id,
|
||||
'hello',
|
||||
[],
|
||||
'Talk like a pirate',
|
||||
)
|
||||
expect(resp.text).toBe('Arr matey!')
|
||||
expect(resp.usage.inputTokens).toBe(10)
|
||||
expect(resp.usage.outputTokens).toBe(20)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,328 @@
|
||||
import { prisma } from '@/db'
|
||||
import { logger } from '@/logger'
|
||||
import { s3Service } from '@/services/s3/s3'
|
||||
import { getModel, type ImageContent, type TextContent } from '@mariozechner/pi-ai'
|
||||
import {
|
||||
AuthStorage,
|
||||
createAgentSession,
|
||||
DefaultResourceLoader,
|
||||
ModelRegistry,
|
||||
SessionManager,
|
||||
SettingsManager,
|
||||
defineTool,
|
||||
} from '@mariozechner/pi-coding-agent'
|
||||
import { Type, type TSchema } from '@sinclair/typebox'
|
||||
import * as fs from 'fs'
|
||||
import * as path from 'path'
|
||||
import { DatabaseSessionManager } from './database-session-manager'
|
||||
import { analyzeAssetMediaTool } from './tools/analyze-asset-media'
|
||||
import { readSkillTool } from './tools/read-skill'
|
||||
import { Usage } from '@/services/ai/provider/provider'
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
export type Tool = any
|
||||
|
||||
export interface AutofillField {
|
||||
id: string
|
||||
config: PrismaJson.FieldConfig
|
||||
description?: string | null
|
||||
}
|
||||
|
||||
export class AgentExecutor {
|
||||
constructor(private readonly prismaClient: typeof prisma = prisma) {}
|
||||
|
||||
private async getTeam(teamId: string) {
|
||||
return this.prismaClient.team.findUnique({
|
||||
where: { id: teamId },
|
||||
})
|
||||
}
|
||||
|
||||
async chat(teamId: string, prompt: string): Promise<{ text: string; usage: Usage }> {
|
||||
const agent = await this.prismaClient.agent.findFirst({
|
||||
where: {
|
||||
type: 'chat',
|
||||
enabled: true,
|
||||
user: {
|
||||
teamMembers: {
|
||||
some: { teamId },
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
if (!agent) {
|
||||
throw new Error('no chat agent found for team')
|
||||
}
|
||||
const { text, usage } = await this.chatWithAgent(teamId, agent.id, prompt, [], '')
|
||||
return { text, usage }
|
||||
}
|
||||
|
||||
async chatWithAgent(
|
||||
teamId: string,
|
||||
agentId: string,
|
||||
prompt: string,
|
||||
images: string[],
|
||||
agentsInstruction: string,
|
||||
sessionId?: string,
|
||||
userId?: string,
|
||||
tools: Tool[] = [],
|
||||
): Promise<{ text: string; usage: Usage; sessionId: string }> {
|
||||
const t = await this.getTeam(teamId)
|
||||
if (!t) throw new Error('failed to get team')
|
||||
|
||||
const agent = await this.prismaClient.agent.findUnique({
|
||||
where: { id: agentId },
|
||||
include: {
|
||||
provider: true,
|
||||
modelRef: true,
|
||||
},
|
||||
})
|
||||
|
||||
if (!agent) {
|
||||
throw new Error(`agent ${agentId} not found`)
|
||||
}
|
||||
|
||||
if (!agent.provider) throw new Error('agent has no provider configured')
|
||||
if (!agent.modelRef) throw new Error('agent has no model configured')
|
||||
|
||||
const providerName = agent.provider.name
|
||||
const modelId = agent.modelRef.modelId
|
||||
|
||||
const agentDir = path.join(process.cwd(), '.pi', 'agents', agent.id)
|
||||
if (!fs.existsSync(agentDir)) fs.mkdirSync(agentDir, { recursive: true })
|
||||
|
||||
const authStorage = AuthStorage.create(path.join(agentDir, 'auth.json'))
|
||||
const modelRegistry = ModelRegistry.create(authStorage)
|
||||
modelRegistry.getAll()
|
||||
|
||||
// Fetch and register the required provider from database
|
||||
const dbProviders = await this.prismaClient.provider.findMany({
|
||||
where: { teamId, name: providerName },
|
||||
include: { models: true },
|
||||
})
|
||||
for (const p of dbProviders) {
|
||||
// Ensure each model has a name (fallback to ID) to satisfy registerProvider's strict requirement
|
||||
const config = {
|
||||
...p.config,
|
||||
models: p.models.map((m) => ({
|
||||
...m.config,
|
||||
id: m.modelId,
|
||||
name: m.name || m.modelId,
|
||||
})),
|
||||
}
|
||||
modelRegistry.registerProvider(p.name, config)
|
||||
}
|
||||
|
||||
// Setup credentials
|
||||
const dbProvider = dbProviders[0]
|
||||
if (dbProvider?.config.apiKey) {
|
||||
authStorage.set(providerName, { type: 'api_key', key: dbProvider.config.apiKey })
|
||||
}
|
||||
|
||||
// Fetch team skills
|
||||
const teamSkills = await this.prismaClient.skill.findMany({
|
||||
where: { teamId },
|
||||
})
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const model = (getModel as any)(providerName, modelId)
|
||||
|
||||
const settingsManager = SettingsManager.create(process.cwd(), agentDir)
|
||||
const resourceLoader = new DefaultResourceLoader({
|
||||
cwd: process.cwd(),
|
||||
agentDir,
|
||||
settingsManager,
|
||||
systemPromptOverride: () => {
|
||||
let systemPrompt = '你是shumai小助手。'
|
||||
if (agentsInstruction) {
|
||||
systemPrompt = `${systemPrompt}\n\nContext and Instructions:\n${agentsInstruction}`
|
||||
}
|
||||
|
||||
const modelConfig = agent.modelRef?.config as unknown as PrismaJson.ModelConfig
|
||||
if (modelConfig?.input) {
|
||||
systemPrompt += `\n\nYour current model supports the following input types: ${modelConfig.input.join(', ')}.`
|
||||
}
|
||||
|
||||
if (teamSkills.length > 0) {
|
||||
systemPrompt += '\n\nAvailable Skills:\n'
|
||||
for (const s of teamSkills) {
|
||||
systemPrompt += `- ${s.name} (ID: ${s.id}): ${s.description || 'No description'}\n`
|
||||
}
|
||||
systemPrompt +=
|
||||
'\nTo use a skill, first use the "read_skill" tool with the skill ID to read its instructions.'
|
||||
}
|
||||
|
||||
return systemPrompt
|
||||
},
|
||||
noContextFiles: true,
|
||||
})
|
||||
await resourceLoader.reload()
|
||||
const sessionManager = await DatabaseSessionManager.create({
|
||||
agentId,
|
||||
userId,
|
||||
sessionId,
|
||||
cwd: process.cwd(),
|
||||
})
|
||||
|
||||
const { session } = await createAgentSession({
|
||||
cwd: process.cwd(),
|
||||
agentDir,
|
||||
authStorage,
|
||||
modelRegistry,
|
||||
model,
|
||||
resourceLoader,
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
sessionManager: sessionManager as any as SessionManager,
|
||||
customTools: [analyzeAssetMediaTool, readSkillTool, ...tools],
|
||||
})
|
||||
const content: (TextContent | ImageContent)[] = []
|
||||
|
||||
if (agentsInstruction) {
|
||||
session.state.systemPrompt = `${session.state.systemPrompt}\n\nContext and Instructions:\n${agentsInstruction}`
|
||||
}
|
||||
content.push({ type: 'text', text: prompt })
|
||||
|
||||
if (images && images.length > 0) {
|
||||
for (const key of images) {
|
||||
const { buffer, contentType } = await s3Service.getObject(
|
||||
process.env.S3_BUCKET || 'shumai',
|
||||
key,
|
||||
)
|
||||
content.push({
|
||||
type: 'image',
|
||||
data: buffer.toString('base64'),
|
||||
mimeType: contentType,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
await session.sendUserMessage(content)
|
||||
|
||||
session.state.messages.forEach((msg) => {
|
||||
if (msg.role === 'toolResult') {
|
||||
// For tool results, log details (metadata) instead of content (which may have large images)
|
||||
const logMsg = { ...msg, content: undefined }
|
||||
logger.debug(logMsg, 'agent message')
|
||||
} else {
|
||||
logger.debug(msg, 'agent message')
|
||||
}
|
||||
})
|
||||
|
||||
const stats = session.getSessionStats()
|
||||
const text = session.getLastAssistantText() || ''
|
||||
|
||||
if (!text) {
|
||||
const lastMessage = session.messages[session.messages.length - 1]
|
||||
if (lastMessage && lastMessage.role === 'assistant' && lastMessage.errorMessage) {
|
||||
throw new Error(`AI error: ${lastMessage.errorMessage}`)
|
||||
}
|
||||
}
|
||||
|
||||
const usage: Usage = {
|
||||
model: modelId,
|
||||
inputTokens: stats.tokens.input || 0,
|
||||
outputTokens: stats.tokens.output || 0,
|
||||
}
|
||||
|
||||
await sessionManager.waitForSync()
|
||||
|
||||
return { text, usage, sessionId: sessionManager.getDbSessionId() }
|
||||
} finally {
|
||||
// Cleanup handled by agent session if needed
|
||||
}
|
||||
}
|
||||
|
||||
async autofill(
|
||||
teamId: string,
|
||||
prompt: string,
|
||||
images: string[],
|
||||
fields: AutofillField[],
|
||||
): Promise<{ text: string; usage: Usage }> {
|
||||
const agent = await this.prismaClient.agent.findFirst({
|
||||
where: {
|
||||
type: 'autofill',
|
||||
enabled: true,
|
||||
user: {
|
||||
teamMembers: {
|
||||
some: { teamId },
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
if (!agent) {
|
||||
throw new Error('no autofill agent found for team')
|
||||
}
|
||||
|
||||
const toolSchema = fieldsToTypeBoxSchema(fields)
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
let capturedData: any = null
|
||||
|
||||
const autofillTool = defineTool({
|
||||
name: 'autofill_metadata',
|
||||
label: 'Autofill Metadata',
|
||||
description: 'Extract metadata from the images.',
|
||||
parameters: toolSchema,
|
||||
execute: async (_toolCallId, params) => {
|
||||
capturedData = params
|
||||
return {
|
||||
content: [{ type: 'text', text: 'Metadata captured successfully.' }],
|
||||
details: {},
|
||||
}
|
||||
},
|
||||
})
|
||||
|
||||
const fullPrompt = `${prompt}\n\nPlease use the "autofill_metadata" tool to provide the extracted metadata.`
|
||||
|
||||
const { usage } = await this.chatWithAgent(
|
||||
teamId,
|
||||
agent.id,
|
||||
fullPrompt,
|
||||
images,
|
||||
'',
|
||||
undefined,
|
||||
undefined,
|
||||
[autofillTool],
|
||||
)
|
||||
|
||||
return {
|
||||
text: capturedData ? JSON.stringify(capturedData) : '{}',
|
||||
usage,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export const agentExecutor = new AgentExecutor()
|
||||
|
||||
export function fieldsToTypeBoxSchema(fields: AutofillField[]) {
|
||||
const properties: Record<string, TSchema> = {}
|
||||
for (const f of fields) {
|
||||
let schema: TSchema
|
||||
switch (f.config.type) {
|
||||
case 'text':
|
||||
case 'longText':
|
||||
schema = Type.String()
|
||||
break
|
||||
case 'number':
|
||||
case 'rating':
|
||||
schema = Type.Number()
|
||||
break
|
||||
case 'toggle':
|
||||
schema = Type.Boolean()
|
||||
break
|
||||
case 'select':
|
||||
schema = Type.String({
|
||||
enum: f.config.select?.options?.map((o) => o.id) || [],
|
||||
})
|
||||
break
|
||||
default:
|
||||
schema = Type.String()
|
||||
}
|
||||
|
||||
if (f.description) {
|
||||
schema.description = f.description
|
||||
}
|
||||
properties[f.id] = schema
|
||||
}
|
||||
|
||||
return Type.Object(properties)
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { fieldsToTypeBoxSchema, type AutofillField } from './executor'
|
||||
|
||||
describe('fieldsToTypeBoxSchema', () => {
|
||||
it('converts text fields', () => {
|
||||
const fields: AutofillField[] = [
|
||||
{ id: 'f1', config: { name: 'Title', type: 'text' }, description: 'The title' },
|
||||
{ id: 'f2', config: { name: 'Desc', type: 'longText' } },
|
||||
]
|
||||
const schema = fieldsToTypeBoxSchema(fields)
|
||||
expect(schema.properties.f1.type).toBe('string')
|
||||
expect(schema.properties.f1.description).toBe('The title')
|
||||
expect(schema.properties.f2.type).toBe('string')
|
||||
})
|
||||
|
||||
it('converts numeric fields', () => {
|
||||
const fields: AutofillField[] = [
|
||||
{ id: 'f1', config: { name: 'Price', type: 'number' } },
|
||||
{ id: 'f2', config: { name: 'Rating', type: 'rating' } },
|
||||
]
|
||||
const schema = fieldsToTypeBoxSchema(fields)
|
||||
expect(schema.properties.f1.type).toBe('number')
|
||||
expect(schema.properties.f2.type).toBe('number')
|
||||
})
|
||||
|
||||
it('converts toggle fields', () => {
|
||||
const fields: AutofillField[] = [{ id: 'f1', config: { name: 'Active', type: 'toggle' } }]
|
||||
const schema = fieldsToTypeBoxSchema(fields)
|
||||
expect(schema.properties.f1.type).toBe('boolean')
|
||||
})
|
||||
|
||||
it('converts select fields with enums', () => {
|
||||
const fields: AutofillField[] = [
|
||||
{
|
||||
id: 'f1',
|
||||
config: {
|
||||
name: 'Status',
|
||||
type: 'select',
|
||||
select: {
|
||||
options: [
|
||||
{ id: 'opt1', displayName: 'Option 1', color: 'red' },
|
||||
{ id: 'opt2', displayName: 'Option 2', color: 'blue' },
|
||||
],
|
||||
},
|
||||
},
|
||||
},
|
||||
]
|
||||
const schema = fieldsToTypeBoxSchema(fields)
|
||||
expect(schema.properties.f1.type).toBe('string')
|
||||
expect(schema.properties.f1.enum).toEqual(['opt1', 'opt2'])
|
||||
})
|
||||
|
||||
it('defaults to string for unknown types', () => {
|
||||
const fields: AutofillField[] = [
|
||||
// @ts-ignore
|
||||
{ id: 'f1', config: { name: 'Unknown', type: 'invalid' } },
|
||||
]
|
||||
const schema = fieldsToTypeBoxSchema(fields)
|
||||
expect(schema.properties.f1.type).toBe('string')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,70 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { analyzeAssetMediaTool } from './analyze-asset-media'
|
||||
import { s3Service } from '@/services/s3/s3'
|
||||
|
||||
vi.mock('@/services/s3/s3')
|
||||
|
||||
describe('analyzeAssetMediaTool', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
it('should analyze media by S3 key and return image content', async () => {
|
||||
// Mock S3 with WEBP magic bytes
|
||||
const buffer = Buffer.from([
|
||||
0x52, 0x49, 0x46, 0x46, 0x00, 0x00, 0x00, 0x00, 0x57, 0x45, 0x42, 0x50,
|
||||
])
|
||||
vi.mocked(s3Service.getObject).mockResolvedValue({ buffer, contentType: 'image/webp' })
|
||||
|
||||
const result = await analyzeAssetMediaTool.execute(
|
||||
'1',
|
||||
{ key: 'assets/test.webp' },
|
||||
undefined,
|
||||
undefined,
|
||||
{} as any, // eslint-disable-line @typescript-eslint/no-explicit-any
|
||||
)
|
||||
|
||||
expect(result.content[0].type).toBe('image')
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
expect((result.content[0] as any).mimeType).toBe('image/webp')
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
expect((result.details as any).sourceKey).toBe('assets/test.webp')
|
||||
})
|
||||
|
||||
it('should infer mimeType from content if S3 response has generic mimeType', async () => {
|
||||
// Mock S3 with MP4 magic bytes
|
||||
const buffer = Buffer.from([
|
||||
0x00, 0x00, 0x00, 0x18, 0x66, 0x74, 0x79, 0x70, 0x69, 0x73, 0x6f, 0x6d,
|
||||
])
|
||||
vi.mocked(s3Service.getObject).mockResolvedValue({ buffer, contentType: 'application/octet-stream' })
|
||||
|
||||
const result = await analyzeAssetMediaTool.execute(
|
||||
'1',
|
||||
{ key: 'assets/no-extension-but-mp4' },
|
||||
undefined,
|
||||
undefined,
|
||||
{} as any, // eslint-disable-line @typescript-eslint/no-explicit-any
|
||||
)
|
||||
|
||||
expect(result.content[0].type).toBe('image') // Wrapped as image type for base64
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
expect((result.content[0] as any).mimeType).toBe('video/mp4')
|
||||
})
|
||||
|
||||
it('should return error if S3 getObject fails', async () => {
|
||||
// Mock S3 failure
|
||||
vi.mocked(s3Service.getObject).mockRejectedValue(new Error('S3 error'))
|
||||
|
||||
const result = await analyzeAssetMediaTool.execute(
|
||||
'1',
|
||||
{ key: 'assets/non-existent' },
|
||||
undefined,
|
||||
undefined,
|
||||
{} as any, // eslint-disable-line @typescript-eslint/no-explicit-any
|
||||
)
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const textContent = (result.content[0] as any).text
|
||||
expect(textContent).toContain('Error analyzing media: S3 error')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,74 @@
|
||||
import { s3Service } from '@/services/s3/s3'
|
||||
import { Type } from '@sinclair/typebox'
|
||||
import { defineTool } from '@mariozechner/pi-coding-agent'
|
||||
import { ImageContent, TextContent } from '@mariozechner/pi-ai'
|
||||
import { detectSupportedMimeType } from '@/utils/mime'
|
||||
|
||||
const analyzeAssetMediaSchema = Type.Object({
|
||||
key: Type.String({
|
||||
description:
|
||||
'The S3 key of the media file to analyze. This MUST be a key obtained from the asset media info.',
|
||||
}),
|
||||
})
|
||||
|
||||
export interface MediaAnalysisDetails {
|
||||
sourceKey: string
|
||||
}
|
||||
|
||||
export const analyzeAssetMediaTool = defineTool<
|
||||
typeof analyzeAssetMediaSchema,
|
||||
MediaAnalysisDetails
|
||||
>({
|
||||
name: 'analyze_asset_media',
|
||||
label: 'Analyze Asset Media',
|
||||
description:
|
||||
'Retrieves and views the media content (images/video) by its S3 key. The key must be obtained from the asset media info provided in the context.',
|
||||
parameters: analyzeAssetMediaSchema,
|
||||
execute: async (_toolCallId, params) => {
|
||||
try {
|
||||
const { key } = params
|
||||
if (!key) {
|
||||
return {
|
||||
content: [{ type: 'text', text: 'S3 key is required.' }],
|
||||
details: { sourceKey: '' },
|
||||
}
|
||||
}
|
||||
|
||||
const bucket = process.env.S3_BUCKET || 'shumai'
|
||||
const { buffer, contentType } = await s3Service.getObject(bucket, key)
|
||||
const uint8Array = new Uint8Array(buffer)
|
||||
let mimeType = contentType
|
||||
|
||||
if (mimeType === 'application/octet-stream') {
|
||||
mimeType = detectSupportedMimeType(uint8Array) || 'application/octet-stream'
|
||||
}
|
||||
|
||||
const content: (TextContent | ImageContent)[] = [
|
||||
{
|
||||
type: 'image',
|
||||
data: buffer.toString('base64'),
|
||||
mimeType,
|
||||
},
|
||||
]
|
||||
|
||||
return {
|
||||
content,
|
||||
details: {
|
||||
sourceKey: key,
|
||||
},
|
||||
}
|
||||
} catch (error) {
|
||||
return {
|
||||
content: [
|
||||
{
|
||||
type: 'text',
|
||||
text: `Error analyzing media: ${
|
||||
error instanceof Error ? error.message : String(error)
|
||||
}`,
|
||||
},
|
||||
],
|
||||
details: { sourceKey: params.key || '' },
|
||||
}
|
||||
}
|
||||
},
|
||||
})
|
||||
@@ -0,0 +1,121 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { prisma } from '@/db'
|
||||
import { setupTestDbHooks } from '@/db-test-hooks'
|
||||
import { readSkillTool } from './read-skill'
|
||||
import { s3Service } from '@/services/s3/s3'
|
||||
import * as fs from 'fs'
|
||||
|
||||
vi.mock('@/services/s3/s3')
|
||||
vi.mock('fs')
|
||||
vi.mock('adm-zip', () => {
|
||||
return {
|
||||
default: class {
|
||||
extractAllTo = vi.fn()
|
||||
},
|
||||
}
|
||||
})
|
||||
|
||||
describe('readSkillTool', () => {
|
||||
setupTestDbHooks()
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
it('should return error if skill not found', async () => {
|
||||
const result = await readSkillTool.execute(
|
||||
'1',
|
||||
{ skillId: 'non-existent' },
|
||||
undefined,
|
||||
undefined,
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- mocking AgentSession is too complex for this test
|
||||
{} as unknown as any,
|
||||
)
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
expect((result.content[0] as any).text).toContain('not found')
|
||||
})
|
||||
|
||||
it('should read skill from cache if hash matches', async () => {
|
||||
const team = await prisma.team.create({ data: { name: 'Test Team' } })
|
||||
const skill = await prisma.skill.create({
|
||||
data: {
|
||||
name: 'Test Skill',
|
||||
assetId: 'asset1',
|
||||
hash: 'match-hash',
|
||||
teamId: team.id,
|
||||
},
|
||||
})
|
||||
|
||||
vi.spyOn(fs, 'existsSync').mockReturnValue(true)
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- mocking node fs calls
|
||||
vi.spyOn(fs, 'readFileSync').mockImplementation((path: any) => {
|
||||
if (path.toString().endsWith('.hash')) return 'match-hash'
|
||||
if (path.toString().endsWith('SKILL.md')) return '# Test Skill Content'
|
||||
return ''
|
||||
})
|
||||
|
||||
const result = await readSkillTool.execute(
|
||||
'1',
|
||||
{ skillId: skill.id },
|
||||
undefined,
|
||||
undefined,
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- mocking AgentSession is too complex for this test
|
||||
{} as unknown as any,
|
||||
)
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
expect((result.content[0] as any).text).toBe('# Test Skill Content')
|
||||
expect(s3Service.getObject).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('should download and extract skill if cache missing or hash mismatch', async () => {
|
||||
const team = await prisma.team.create({ data: { name: 'Test Team' } })
|
||||
const skill = await prisma.skill.create({
|
||||
data: {
|
||||
name: 'New Skill',
|
||||
assetId: 'asset1',
|
||||
hash: 'new-hash',
|
||||
teamId: team.id,
|
||||
},
|
||||
})
|
||||
|
||||
await prisma.asset.create({
|
||||
data: {
|
||||
id: 'asset1',
|
||||
name: 'skill.zip',
|
||||
key: 'skills/skill.zip',
|
||||
type: 'file',
|
||||
status: 'uploaded',
|
||||
},
|
||||
})
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- mocking node fs calls
|
||||
vi.spyOn(fs, 'existsSync').mockImplementation((path: any) => {
|
||||
if (path.toString().endsWith('.hash')) return false
|
||||
if (path.toString().endsWith('SKILL.md')) return true
|
||||
return true
|
||||
})
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- mocking node fs calls
|
||||
vi.spyOn(fs, 'readFileSync').mockImplementation((path: any) => {
|
||||
if (path.toString().endsWith('SKILL.md')) return '# Extracted Content'
|
||||
return ''
|
||||
})
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- mocking s3Service return
|
||||
;(s3Service.getObject as any).mockResolvedValue({ buffer: Buffer.from('zipdata'), contentType: 'application/zip' })
|
||||
|
||||
const result = await readSkillTool.execute(
|
||||
'1',
|
||||
{ skillId: skill.id },
|
||||
undefined,
|
||||
undefined,
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- mocking AgentSession is too complex for this test
|
||||
{} as unknown as any,
|
||||
)
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
expect((result.content[0] as any).text).toBe('# Extracted Content')
|
||||
expect(s3Service.getObject).toHaveBeenCalled()
|
||||
expect(fs.writeFileSync).toHaveBeenCalledWith(expect.stringContaining('.hash'), 'new-hash')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,101 @@
|
||||
import { prisma } from '@/db'
|
||||
import { s3Service } from '@/services/s3/s3'
|
||||
import { Type } from '@sinclair/typebox'
|
||||
import { defineTool } from '@mariozechner/pi-coding-agent'
|
||||
import * as path from 'path'
|
||||
import * as fs from 'fs'
|
||||
import AdmZip from 'adm-zip'
|
||||
|
||||
const readSkillSchema = Type.Object({
|
||||
skillId: Type.String({ description: 'The ID of the skill to read' }),
|
||||
})
|
||||
|
||||
export const readSkillTool = defineTool<typeof readSkillSchema, { skillId: string }>({
|
||||
name: 'read_skill',
|
||||
label: 'Read Agent Skill',
|
||||
description: 'Downloads and reads an agent skill to understand how to use it.',
|
||||
parameters: readSkillSchema,
|
||||
execute: async (_toolCallId, params) => {
|
||||
try {
|
||||
const skill = await prisma.skill.findUnique({
|
||||
where: { id: params.skillId },
|
||||
})
|
||||
|
||||
if (!skill) {
|
||||
return {
|
||||
content: [{ type: 'text', text: `Skill with ID ${params.skillId} not found.` }],
|
||||
details: { skillId: params.skillId },
|
||||
}
|
||||
}
|
||||
|
||||
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 prisma.asset.findUnique({
|
||||
where: { id: skill.assetId },
|
||||
})
|
||||
|
||||
if (!asset || !asset.key) {
|
||||
throw new Error('Skill asset not found or has no key')
|
||||
}
|
||||
|
||||
const { buffer: zipBuffer } = await s3Service.getObject(process.env.S3_BUCKET || 'shumai', asset.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)) {
|
||||
return {
|
||||
content: [
|
||||
{
|
||||
type: 'text',
|
||||
text: `Skill downloaded but SKILL.md not found in ${skillDir}`,
|
||||
},
|
||||
],
|
||||
details: { skillId: params.skillId },
|
||||
}
|
||||
}
|
||||
|
||||
const skillMdContent = fs.readFileSync(skillMdPath, 'utf8')
|
||||
return {
|
||||
content: [{ type: 'text', text: skillMdContent }],
|
||||
details: { skillId: params.skillId },
|
||||
}
|
||||
} catch (error) {
|
||||
return {
|
||||
content: [
|
||||
{
|
||||
type: 'text',
|
||||
text: `Error reading skill ${params.skillId}: ${
|
||||
error instanceof Error ? error.message : String(error)
|
||||
}`,
|
||||
},
|
||||
],
|
||||
details: { skillId: params.skillId },
|
||||
}
|
||||
}
|
||||
},
|
||||
})
|
||||
@@ -0,0 +1,203 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { aiAutofillMedia } from './ai-autofill'
|
||||
import { WorkflowTask, WorkflowTaskStatus, WorkflowTaskType } from '@/generated/prisma/client'
|
||||
import * as workflowUtils from '@/workflow/workflow-utils'
|
||||
|
||||
vi.mock('@/workflow/workflow-utils', async (importOriginal) => {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const actual = (await importOriginal()) as any
|
||||
return {
|
||||
...actual,
|
||||
getActivities: vi.fn(),
|
||||
executeActivity: vi.fn(),
|
||||
sleep: vi.fn(),
|
||||
}
|
||||
})
|
||||
|
||||
describe('AIAutofill Workflow', () => {
|
||||
const mockActivities = {
|
||||
updateTaskStatusActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'updateTaskStatusActivity',
|
||||
}),
|
||||
getAssetActivity: Object.assign(vi.fn(), { _activityName: 'getAssetActivity' }),
|
||||
extractAiMetadataActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'extractAiMetadataActivity',
|
||||
}),
|
||||
getProjectAutofillFieldsActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'getProjectAutofillFieldsActivity',
|
||||
}),
|
||||
autofillAiActivity: Object.assign(vi.fn(), { _activityName: 'autofillAiActivity' }),
|
||||
updateTaskUsageActivity: Object.assign(vi.fn(), { _activityName: 'updateTaskUsageActivity' }),
|
||||
updateAssetMetadataActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'updateAssetMetadataActivity',
|
||||
}),
|
||||
createCommentActivity: Object.assign(vi.fn(), { _activityName: 'createCommentActivity' }),
|
||||
updateCommentActivity: Object.assign(vi.fn(), { _activityName: 'updateCommentActivity' }),
|
||||
getTranscodeWorkerQueueActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'getTranscodeWorkerQueueActivity',
|
||||
}),
|
||||
getAgentWorkerQueueActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'getAgentWorkerQueueActivity',
|
||||
}),
|
||||
downloadMediaToTmpActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'downloadMediaToTmpActivity',
|
||||
}),
|
||||
cleanupTmpDirActivity: Object.assign(vi.fn(), { _activityName: 'cleanupTmpDirActivity' }),
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
;(workflowUtils.getActivities as any).mockReturnValue(mockActivities)
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
;(workflowUtils.executeActivity as any).mockImplementation(
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
(_queue: string, fn: any, ...args: any[]) => {
|
||||
if (typeof fn !== 'function') {
|
||||
throw new Error(`fn is not a function in executeActivity. Queue: ${_queue}`)
|
||||
}
|
||||
return fn(...args)
|
||||
},
|
||||
)
|
||||
|
||||
mockActivities.getTranscodeWorkerQueueActivity.mockResolvedValue('transcode_worker_queue')
|
||||
mockActivities.getAgentWorkerQueueActivity.mockResolvedValue('agent_worker_queue')
|
||||
mockActivities.downloadMediaToTmpActivity.mockResolvedValue({
|
||||
filePath: '/tmp/test.mp4',
|
||||
tmpDir: '/tmp',
|
||||
})
|
||||
})
|
||||
|
||||
it('should process AI autofill successfully', async () => {
|
||||
const task: WorkflowTask = {
|
||||
id: 'task-1',
|
||||
assetId: 'asset-1',
|
||||
type: WorkflowTaskType.ai_metadata_autofill,
|
||||
status: WorkflowTaskStatus.pending,
|
||||
output: null,
|
||||
payload: {},
|
||||
createdAt: new Date(),
|
||||
updatedAt: new Date(),
|
||||
heartbeat: null,
|
||||
teamId: 'team-1',
|
||||
projectId: 'proj-1',
|
||||
uid: 'task-1-uid',
|
||||
model: null,
|
||||
inputTokens: 0,
|
||||
outputTokens: 0,
|
||||
}
|
||||
|
||||
mockActivities.getAssetActivity.mockResolvedValue({
|
||||
id: 'asset-1',
|
||||
key: 'test.mp4',
|
||||
mediaType: 'video/mp4',
|
||||
project: { id: 'proj-1', teamId: 'team-1' },
|
||||
})
|
||||
|
||||
mockActivities.createCommentActivity.mockResolvedValue({ id: 'placeholder-1' })
|
||||
mockActivities.extractAiMetadataActivity.mockResolvedValue(['frame1.webp'])
|
||||
mockActivities.getProjectAutofillFieldsActivity.mockResolvedValue([
|
||||
{ id: 'field-1', config: { type: 'text', name: 'Field 1' } },
|
||||
])
|
||||
mockActivities.autofillAiActivity.mockResolvedValue({
|
||||
text: JSON.stringify({ 'field-1': 'Extracted Value' }),
|
||||
usage: { inputTokens: 10, outputTokens: 5, model: 'gpt-4v' },
|
||||
})
|
||||
|
||||
await aiAutofillMedia(task)
|
||||
|
||||
expect(mockActivities.createCommentActivity).toHaveBeenCalledWith({
|
||||
assetId: 'asset-1',
|
||||
message: '__AUTOFILL__',
|
||||
isAi: true,
|
||||
agentId: 'default',
|
||||
})
|
||||
|
||||
expect(mockActivities.updateAssetMetadataActivity).toHaveBeenCalledWith({
|
||||
assetId: 'asset-1',
|
||||
metadata: [{ key: 'field-1', value: 'Extracted Value' }],
|
||||
})
|
||||
})
|
||||
|
||||
it('should use agentId from payload if provided', async () => {
|
||||
const task: WorkflowTask = {
|
||||
id: 'task-1',
|
||||
assetId: 'asset-1',
|
||||
type: WorkflowTaskType.ai_metadata_autofill,
|
||||
status: WorkflowTaskStatus.pending,
|
||||
output: null,
|
||||
payload: { agentId: 'real-agent-id' },
|
||||
createdAt: new Date(),
|
||||
updatedAt: new Date(),
|
||||
heartbeat: null,
|
||||
teamId: 'team-1',
|
||||
projectId: 'proj-1',
|
||||
uid: 'task-1-uid',
|
||||
model: null,
|
||||
inputTokens: 0,
|
||||
outputTokens: 0,
|
||||
}
|
||||
|
||||
mockActivities.getAssetActivity.mockResolvedValue({
|
||||
id: 'asset-1',
|
||||
key: 'test.mp4',
|
||||
mediaType: 'video/mp4',
|
||||
project: { id: 'proj-1', teamId: 'team-1' },
|
||||
})
|
||||
|
||||
mockActivities.createCommentActivity.mockResolvedValue({ id: 'placeholder-1' })
|
||||
mockActivities.extractAiMetadataActivity.mockResolvedValue(['frame1.webp'])
|
||||
mockActivities.getProjectAutofillFieldsActivity.mockResolvedValue([
|
||||
{ id: 'field-1', config: { type: 'text', name: 'Field 1' } },
|
||||
])
|
||||
mockActivities.autofillAiActivity.mockResolvedValue({
|
||||
text: JSON.stringify({ 'field-1': 'Extracted Value' }),
|
||||
usage: { inputTokens: 10, outputTokens: 5, model: 'gpt-4v' },
|
||||
})
|
||||
|
||||
await aiAutofillMedia(task)
|
||||
|
||||
expect(mockActivities.createCommentActivity).toHaveBeenCalledWith({
|
||||
assetId: 'asset-1',
|
||||
message: '__AUTOFILL__',
|
||||
isAi: true,
|
||||
agentId: 'real-agent-id',
|
||||
})
|
||||
})
|
||||
|
||||
it('should handle failures and update task status with error', async () => {
|
||||
const task: WorkflowTask = {
|
||||
id: 'task-fail',
|
||||
assetId: 'asset-1',
|
||||
type: WorkflowTaskType.ai_metadata_autofill,
|
||||
status: WorkflowTaskStatus.pending,
|
||||
output: null,
|
||||
payload: {},
|
||||
createdAt: new Date(),
|
||||
updatedAt: new Date(),
|
||||
heartbeat: null,
|
||||
teamId: 'team-1',
|
||||
projectId: 'proj-1',
|
||||
uid: 'task-fail-uid',
|
||||
model: null,
|
||||
inputTokens: 0,
|
||||
outputTokens: 0,
|
||||
}
|
||||
|
||||
mockActivities.createCommentActivity.mockResolvedValue({ id: 'placeholder-err' })
|
||||
mockActivities.getAssetActivity.mockRejectedValue(new Error('Asset missing'))
|
||||
|
||||
await expect(aiAutofillMedia(task)).rejects.toThrow('Asset missing')
|
||||
|
||||
expect(mockActivities.updateCommentActivity).toHaveBeenCalledWith({
|
||||
commentId: 'placeholder-err',
|
||||
message: expect.stringContaining('failed'),
|
||||
})
|
||||
|
||||
expect(mockActivities.updateTaskStatusActivity).toHaveBeenCalledWith({
|
||||
taskId: 'task-fail',
|
||||
status: WorkflowTaskStatus.failed,
|
||||
output: { error: 'Asset missing' },
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,192 @@
|
||||
import type { WorkflowTask } from '@/generated/prisma/client'
|
||||
import {
|
||||
getActivities,
|
||||
executeActivity,
|
||||
TaskQueueDb,
|
||||
TaskQueueAgent,
|
||||
TaskQueueTranscode,
|
||||
} from '@/workflow/workflow-utils'
|
||||
|
||||
export async function aiAutofillMedia(task: WorkflowTask): Promise<void> {
|
||||
const {
|
||||
updateTaskStatusActivity,
|
||||
getAssetActivity,
|
||||
extractAiMetadataActivity,
|
||||
getProjectAutofillFieldsActivity,
|
||||
autofillAiActivity,
|
||||
updateTaskUsageActivity,
|
||||
updateAssetMetadataActivity,
|
||||
createCommentActivity,
|
||||
updateCommentActivity,
|
||||
getTranscodeWorkerQueueActivity,
|
||||
getAgentWorkerQueueActivity,
|
||||
downloadMediaToTmpActivity,
|
||||
cleanupTmpDirActivity,
|
||||
} = getActivities()
|
||||
|
||||
let placeholderCommentId: string | undefined
|
||||
let tmpDir: string | undefined
|
||||
let transcodeWorkerQueue: string | undefined
|
||||
|
||||
try {
|
||||
// Update status to processing
|
||||
await executeActivity(TaskQueueDb, updateTaskStatusActivity, {
|
||||
taskId: task.id,
|
||||
status: 'processing',
|
||||
})
|
||||
|
||||
// 0. Create Placeholder Comment
|
||||
const payload = task.payload as Record<string, unknown>
|
||||
const placeholder = await executeActivity(TaskQueueDb, createCommentActivity, {
|
||||
assetId: task.assetId,
|
||||
message: '__AUTOFILL__',
|
||||
isAi: true,
|
||||
agentId: (payload?.agentId as string) || 'default',
|
||||
})
|
||||
placeholderCommentId = placeholder.id
|
||||
|
||||
// 1. Get Asset
|
||||
const asset = await executeActivity(TaskQueueDb, getAssetActivity, task.assetId)
|
||||
if (!asset || !asset.project) {
|
||||
throw new Error('Asset or project not found')
|
||||
}
|
||||
const teamId = asset.project.teamId
|
||||
const projectId = asset.project.id
|
||||
|
||||
// 2. Prepare Data (Images)
|
||||
const isImage = asset.mediaType?.startsWith('image/') || false
|
||||
|
||||
// Extraction requires FFmpeg, run on Transcode worker
|
||||
transcodeWorkerQueue = await executeActivity(
|
||||
TaskQueueTranscode,
|
||||
getTranscodeWorkerQueueActivity,
|
||||
)
|
||||
|
||||
const download = await executeActivity(transcodeWorkerQueue, downloadMediaToTmpActivity, {
|
||||
assetKey: asset.key || '',
|
||||
})
|
||||
const { filePath } = download
|
||||
tmpDir = download.tmpDir
|
||||
|
||||
const generatedFiles = await executeActivity(transcodeWorkerQueue, extractAiMetadataActivity, {
|
||||
assetKey: asset.key || '',
|
||||
filePath,
|
||||
type: 'autofill',
|
||||
isImage,
|
||||
})
|
||||
|
||||
if (generatedFiles.length === 0) {
|
||||
// If no images could be extracted, we can't do much
|
||||
if (placeholderCommentId) {
|
||||
await executeActivity(TaskQueueDb, updateCommentActivity, {
|
||||
commentId: placeholderCommentId,
|
||||
message: 'Autofill completed: No images could be extracted for analysis.',
|
||||
})
|
||||
}
|
||||
await executeActivity(TaskQueueDb, updateTaskStatusActivity, {
|
||||
taskId: task.id,
|
||||
status: 'completed',
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
// 3. Get Project Autofill Fields
|
||||
const fields = await executeActivity(TaskQueueDb, getProjectAutofillFieldsActivity, projectId)
|
||||
if (fields.length === 0) {
|
||||
if (placeholderCommentId) {
|
||||
await executeActivity(TaskQueueDb, updateCommentActivity, {
|
||||
commentId: placeholderCommentId,
|
||||
message: 'Autofill completed: No autofill fields defined in project.',
|
||||
})
|
||||
}
|
||||
await executeActivity(TaskQueueDb, updateTaskStatusActivity, {
|
||||
taskId: task.id,
|
||||
status: 'completed',
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
// 4. Call AI Service
|
||||
const agentWorkerQueue = await executeActivity(TaskQueueAgent, getAgentWorkerQueueActivity)
|
||||
|
||||
const aiResult = await executeActivity(agentWorkerQueue, autofillAiActivity, {
|
||||
teamId,
|
||||
images: generatedFiles,
|
||||
fields: fields.map((f) => ({
|
||||
id: f.id,
|
||||
config: f.config as unknown as PrismaJson.FieldConfig,
|
||||
description: f.description,
|
||||
})),
|
||||
})
|
||||
|
||||
if (aiResult.usage) {
|
||||
// Update Usage
|
||||
await executeActivity(TaskQueueDb, updateTaskUsageActivity, {
|
||||
taskId: task.id,
|
||||
inputTokens: aiResult.usage.inputTokens,
|
||||
outputTokens: aiResult.usage.outputTokens,
|
||||
model: aiResult.usage.model,
|
||||
})
|
||||
}
|
||||
|
||||
// 6. Update Asset Metadata
|
||||
const result = JSON.parse(aiResult.text)
|
||||
const metadataUpdates = Object.entries(result).map(([key, value]) => ({
|
||||
key,
|
||||
value,
|
||||
}))
|
||||
|
||||
if (metadataUpdates.length > 0) {
|
||||
await executeActivity(TaskQueueDb, updateAssetMetadataActivity, {
|
||||
assetId: asset.id,
|
||||
metadata: metadataUpdates,
|
||||
})
|
||||
}
|
||||
|
||||
// 7. Update Placeholder Comment
|
||||
if (placeholderCommentId) {
|
||||
await executeActivity(TaskQueueDb, updateCommentActivity, {
|
||||
commentId: placeholderCommentId,
|
||||
message: 'Autofill completed successfully.',
|
||||
})
|
||||
}
|
||||
|
||||
// Update status to completed
|
||||
await executeActivity(TaskQueueDb, updateTaskStatusActivity, {
|
||||
taskId: task.id,
|
||||
status: 'completed',
|
||||
})
|
||||
} catch (err) {
|
||||
console.error(`AiAutofillMedia failed for task ${task.id}:`, err)
|
||||
|
||||
// Update placeholder comment with error message
|
||||
if (placeholderCommentId) {
|
||||
try {
|
||||
await executeActivity(TaskQueueDb, updateCommentActivity, {
|
||||
commentId: placeholderCommentId,
|
||||
message: `Autofill failed: ${err instanceof Error ? err.message : String(err)}`,
|
||||
})
|
||||
} catch (commentErr) {
|
||||
console.error('Failed to update error comment:', commentErr)
|
||||
}
|
||||
}
|
||||
|
||||
// Update status to failed
|
||||
await executeActivity(TaskQueueDb, updateTaskStatusActivity, {
|
||||
taskId: task.id,
|
||||
status: 'failed',
|
||||
output: { error: err instanceof Error ? err.message : String(err) },
|
||||
})
|
||||
throw err
|
||||
} finally {
|
||||
if (tmpDir && transcodeWorkerQueue) {
|
||||
try {
|
||||
await executeActivity(transcodeWorkerQueue, cleanupTmpDirActivity, { tmpDir })
|
||||
} catch (cleanupErr) {
|
||||
console.error('Failed to cleanup tmp dir:', cleanupErr)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export const aiAutofillWorkflow = aiAutofillMedia
|
||||
@@ -0,0 +1,222 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { aiChat } from './ai-chat'
|
||||
import { WorkflowTask, WorkflowTaskStatus, WorkflowTaskType } from '@/generated/prisma/client'
|
||||
import * as workflowUtils from '@/workflow/workflow-utils'
|
||||
|
||||
vi.mock('@/workflow/workflow-utils', async (importOriginal) => {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const actual = (await importOriginal()) as any
|
||||
return {
|
||||
...actual,
|
||||
getActivities: vi.fn(),
|
||||
executeActivity: vi.fn(),
|
||||
sleep: vi.fn().mockResolvedValue(undefined),
|
||||
}
|
||||
})
|
||||
|
||||
describe('AIChat Workflow', () => {
|
||||
const mockActivities = {
|
||||
updateTaskStatusActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'updateTaskStatusActivity',
|
||||
}),
|
||||
getAssetActivity: Object.assign(vi.fn(), { _activityName: 'getAssetActivity' }),
|
||||
getCommentActivity: Object.assign(vi.fn(), { _activityName: 'getCommentActivity' }),
|
||||
extractAiMetadataActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'extractAiMetadataActivity',
|
||||
}),
|
||||
aiChatActivity: Object.assign(vi.fn(), { _activityName: 'aiChatActivity' }),
|
||||
createCommentActivity: Object.assign(vi.fn(), { _activityName: 'createCommentActivity' }),
|
||||
updateCommentActivity: Object.assign(vi.fn(), { _activityName: 'updateCommentActivity' }),
|
||||
updateTaskUsageActivity: Object.assign(vi.fn(), { _activityName: 'updateTaskUsageActivity' }),
|
||||
getAgentWorkerQueueActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'getAgentWorkerQueueActivity',
|
||||
}),
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
;(workflowUtils.getActivities as any).mockReturnValue(mockActivities)
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
;(workflowUtils.executeActivity as any).mockImplementation(
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
(_queue: string, fn: any, ...args: any[]) => {
|
||||
if (typeof fn !== 'function') {
|
||||
throw new Error(`fn is not a function in executeActivity. Queue: ${_queue}`)
|
||||
}
|
||||
return fn(...args)
|
||||
},
|
||||
)
|
||||
mockActivities.getAgentWorkerQueueActivity.mockResolvedValue('agent_worker_queue')
|
||||
})
|
||||
|
||||
it('should process AI chat successfully', async () => {
|
||||
const task: WorkflowTask = {
|
||||
id: 'task-1',
|
||||
assetId: 'asset-1',
|
||||
type: WorkflowTaskType.chat,
|
||||
status: WorkflowTaskStatus.pending,
|
||||
output: null,
|
||||
payload: {
|
||||
userCommentId: 'comment-1',
|
||||
agentId: 'bot-1',
|
||||
projectId: 'proj-1',
|
||||
},
|
||||
createdAt: new Date(),
|
||||
updatedAt: new Date(),
|
||||
heartbeat: null,
|
||||
teamId: 'team-1',
|
||||
projectId: 'proj-1',
|
||||
uid: 'task-uid',
|
||||
model: null,
|
||||
inputTokens: 0,
|
||||
outputTokens: 0,
|
||||
}
|
||||
|
||||
mockActivities.getAssetActivity.mockResolvedValue({
|
||||
id: 'asset-1',
|
||||
key: 'test.png',
|
||||
mediaType: 'image/png',
|
||||
project: { teamId: 'team-1', id: 'proj-1' },
|
||||
})
|
||||
|
||||
mockActivities.getCommentActivity.mockResolvedValue({
|
||||
id: 'comment-1',
|
||||
message: 'Hello AI',
|
||||
})
|
||||
|
||||
mockActivities.createCommentActivity.mockResolvedValue({
|
||||
id: 'placeholder-1',
|
||||
})
|
||||
|
||||
mockActivities.aiChatActivity.mockResolvedValue({
|
||||
text: 'Hello Human',
|
||||
usage: { inputTokens: 10, outputTokens: 20, model: 'gpt-4' },
|
||||
})
|
||||
|
||||
await aiChat(task)
|
||||
|
||||
expect(mockActivities.updateTaskStatusActivity).toHaveBeenCalledWith({
|
||||
taskId: 'task-1',
|
||||
status: WorkflowTaskStatus.processing,
|
||||
})
|
||||
|
||||
expect(mockActivities.createCommentActivity).toHaveBeenCalledWith({
|
||||
assetId: 'asset-1',
|
||||
message: '__CHAT__',
|
||||
isAi: true,
|
||||
agentId: 'bot-1',
|
||||
replyToId: 'comment-1',
|
||||
})
|
||||
|
||||
expect(mockActivities.updateCommentActivity).toHaveBeenCalledWith({
|
||||
commentId: 'placeholder-1',
|
||||
message: 'Hello Human',
|
||||
})
|
||||
|
||||
expect(mockActivities.updateTaskUsageActivity).toHaveBeenCalledWith({
|
||||
taskId: 'task-1',
|
||||
inputTokens: 10,
|
||||
outputTokens: 20,
|
||||
model: 'gpt-4',
|
||||
})
|
||||
|
||||
expect(mockActivities.updateTaskStatusActivity).toHaveBeenCalledWith({
|
||||
taskId: 'task-1',
|
||||
status: WorkflowTaskStatus.completed,
|
||||
output: { sessionId: undefined },
|
||||
})
|
||||
})
|
||||
|
||||
it('should attach AI response to thread root if triggering comment is a reply', async () => {
|
||||
const task: WorkflowTask = {
|
||||
id: 'task-nested',
|
||||
assetId: 'asset-1',
|
||||
type: WorkflowTaskType.chat,
|
||||
status: WorkflowTaskStatus.pending,
|
||||
output: null,
|
||||
payload: {
|
||||
userCommentId: 'reply-1',
|
||||
agentId: 'bot-1',
|
||||
},
|
||||
createdAt: new Date(),
|
||||
updatedAt: new Date(),
|
||||
heartbeat: null,
|
||||
teamId: 'team-1',
|
||||
projectId: 'proj-1',
|
||||
uid: 'task-uid-nested',
|
||||
model: null,
|
||||
inputTokens: 0,
|
||||
outputTokens: 0,
|
||||
}
|
||||
|
||||
mockActivities.getAssetActivity.mockResolvedValue({
|
||||
id: 'asset-1',
|
||||
project: { teamId: 'team-1', id: 'proj-1' },
|
||||
})
|
||||
|
||||
mockActivities.getCommentActivity.mockResolvedValue({
|
||||
id: 'reply-1',
|
||||
replyToId: 'root-comment-id',
|
||||
message: 'Nested reply message',
|
||||
})
|
||||
|
||||
mockActivities.createCommentActivity.mockResolvedValue({ id: 'placeholder-nested' })
|
||||
|
||||
mockActivities.aiChatActivity.mockResolvedValue({
|
||||
text: 'AI response to root',
|
||||
})
|
||||
|
||||
await aiChat(task)
|
||||
|
||||
expect(mockActivities.createCommentActivity).toHaveBeenCalledWith({
|
||||
assetId: 'asset-1',
|
||||
message: '__CHAT__',
|
||||
isAi: true,
|
||||
agentId: 'bot-1',
|
||||
replyToId: 'root-comment-id', // MUST be root, not reply-1
|
||||
})
|
||||
})
|
||||
|
||||
it('should handle failures and update placeholder with error', async () => {
|
||||
const task: WorkflowTask = {
|
||||
id: 'task-fail',
|
||||
assetId: 'asset-1',
|
||||
type: WorkflowTaskType.chat,
|
||||
status: WorkflowTaskStatus.pending,
|
||||
output: null,
|
||||
payload: {
|
||||
userCommentId: 'comment-1',
|
||||
agentId: 'bot-1',
|
||||
},
|
||||
createdAt: new Date(),
|
||||
updatedAt: new Date(),
|
||||
heartbeat: null,
|
||||
teamId: 'team-1',
|
||||
projectId: 'proj-1',
|
||||
uid: 'task-uid',
|
||||
model: null,
|
||||
inputTokens: 0,
|
||||
outputTokens: 0,
|
||||
}
|
||||
|
||||
mockActivities.createCommentActivity.mockResolvedValue({
|
||||
id: 'placeholder-err',
|
||||
})
|
||||
|
||||
mockActivities.getAssetActivity.mockRejectedValue(new Error('DB Down'))
|
||||
|
||||
await expect(aiChat(task)).rejects.toThrow('DB Down')
|
||||
|
||||
expect(mockActivities.updateCommentActivity).toHaveBeenCalledWith({
|
||||
commentId: 'placeholder-err',
|
||||
message: expect.stringContaining('error'),
|
||||
})
|
||||
|
||||
expect(mockActivities.updateTaskStatusActivity).toHaveBeenCalledWith({
|
||||
taskId: 'task-fail',
|
||||
status: WorkflowTaskStatus.failed,
|
||||
output: { error: 'DB Down' },
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,150 @@
|
||||
import type { WorkflowTask } from '@/generated/prisma/client'
|
||||
import { getActivities, executeActivity, TaskQueueDb, TaskQueueAgent } from '@/workflow/workflow-utils'
|
||||
|
||||
export async function aiChat(task: WorkflowTask): Promise<void> {
|
||||
const {
|
||||
updateTaskStatusActivity,
|
||||
getAssetActivity,
|
||||
getCommentActivity,
|
||||
aiChatActivity,
|
||||
createCommentActivity,
|
||||
updateCommentActivity,
|
||||
updateTaskUsageActivity,
|
||||
getAgentWorkerQueueActivity,
|
||||
} = getActivities()
|
||||
|
||||
let placeholderCommentId: string | undefined
|
||||
|
||||
try {
|
||||
// Update status to processing
|
||||
await executeActivity(TaskQueueDb, updateTaskStatusActivity, {
|
||||
taskId: task.id,
|
||||
status: 'processing',
|
||||
})
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const payload = task.payload as any
|
||||
|
||||
// 1. Get User Comment
|
||||
const userCommentId = payload?.userCommentId
|
||||
if (!userCommentId) throw new Error('userCommentId missing in payload')
|
||||
const userComment = await executeActivity(TaskQueueDb, getCommentActivity, userCommentId)
|
||||
if (!userComment) throw new Error('User comment not found')
|
||||
|
||||
// 2. Create Placeholder Comment
|
||||
const placeholder = await executeActivity(TaskQueueDb, createCommentActivity, {
|
||||
assetId: task.assetId,
|
||||
message: '__CHAT__',
|
||||
isAi: true,
|
||||
agentId: payload?.agentId,
|
||||
replyToId: userComment.replyToId ?? userComment.id,
|
||||
})
|
||||
placeholderCommentId = placeholder.id
|
||||
|
||||
// 3. Get Asset
|
||||
const asset = await executeActivity(TaskQueueDb, getAssetActivity, task.assetId)
|
||||
if (!asset || !asset.project) {
|
||||
throw new Error('Asset or project not found')
|
||||
}
|
||||
const teamId = asset.project.teamId
|
||||
|
||||
// 4. Prepare Images (Attachments only)
|
||||
const attachmentImageUrls: string[] = []
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const userCommentWithAttachments = userComment as any
|
||||
if (userCommentWithAttachments?.attachments) {
|
||||
for (const att of userCommentWithAttachments.attachments) {
|
||||
if (att.asset?.mediaType?.startsWith('image/') && att.asset?.key) {
|
||||
attachmentImageUrls.push(att.asset.key)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let instruction = `The user is discussing an asset with ID: ${asset.id}.`
|
||||
|
||||
if (asset.media) {
|
||||
instruction += `\n\nAsset Media Info:\n${JSON.stringify(asset.media, null, 2)}`
|
||||
}
|
||||
|
||||
instruction += `\n\nIf you need to view the asset's media content (frames/images/video), call the 'analyze_asset_media' tool by passing the appropriate 'key' from the Asset Media Info above. Choose the most suitable format based on your capabilities and the user's request (e.g., use a poster or sprite for quick visual checks, or a transcode/raw file for detailed analysis).`
|
||||
|
||||
// 5. Call AI Chat
|
||||
let folderId = ''
|
||||
if (asset.type === 'folder') {
|
||||
folderId = asset.id
|
||||
} else if (asset.parentId) {
|
||||
folderId = asset.parentId
|
||||
}
|
||||
|
||||
const agentWorkerQueue = await executeActivity(TaskQueueAgent, getAgentWorkerQueueActivity)
|
||||
|
||||
const aiResult = await executeActivity(agentWorkerQueue, aiChatActivity, {
|
||||
teamId,
|
||||
agentId: payload.agentId,
|
||||
message: userComment.message || '',
|
||||
imageUrls: attachmentImageUrls,
|
||||
projectId: payload.projectId,
|
||||
folderId,
|
||||
agentsInstruction: instruction,
|
||||
sessionId: payload.session_id,
|
||||
userId: payload.userId,
|
||||
})
|
||||
|
||||
// 6. Update Placeholder Comment
|
||||
if (placeholderCommentId) {
|
||||
await executeActivity(TaskQueueDb, updateCommentActivity, {
|
||||
commentId: placeholderCommentId,
|
||||
message: aiResult.text,
|
||||
})
|
||||
|
||||
// Also store sessionId in comment's metadata if we had such a field,
|
||||
// but for now we just return it in task status.
|
||||
}
|
||||
|
||||
// 7. Update Usage
|
||||
if (aiResult.usage) {
|
||||
await executeActivity(TaskQueueDb, updateTaskUsageActivity, {
|
||||
taskId: task.id,
|
||||
inputTokens: aiResult.usage.inputTokens,
|
||||
outputTokens: aiResult.usage.outputTokens,
|
||||
model: aiResult.usage.model,
|
||||
})
|
||||
}
|
||||
|
||||
// Update status to completed
|
||||
await executeActivity(TaskQueueDb, updateTaskStatusActivity, {
|
||||
taskId: task.id,
|
||||
status: 'completed',
|
||||
output: { sessionId: aiResult.sessionId },
|
||||
})
|
||||
} catch (err) {
|
||||
console.error(`AiChat failed for task ${task.id}:`, err)
|
||||
|
||||
// Update placeholder comment with error message
|
||||
if (placeholderCommentId) {
|
||||
try {
|
||||
const errorMessage =
|
||||
err instanceof Error && err.message.startsWith('AI error:')
|
||||
? `AI error: ${err.message.substring(9)}`
|
||||
: 'Sorry, I encountered an error while processing your request.'
|
||||
|
||||
await executeActivity(TaskQueueDb, updateCommentActivity, {
|
||||
commentId: placeholderCommentId,
|
||||
message: errorMessage,
|
||||
})
|
||||
} catch (commentErr) {
|
||||
console.error('Failed to update error comment:', commentErr)
|
||||
}
|
||||
}
|
||||
|
||||
// Update status to failed
|
||||
await executeActivity(TaskQueueDb, updateTaskStatusActivity, {
|
||||
taskId: task.id,
|
||||
status: 'failed',
|
||||
output: { error: err instanceof Error ? err.message : String(err) },
|
||||
})
|
||||
throw err
|
||||
}
|
||||
}
|
||||
|
||||
export const aiChatWorkflow = aiChat
|
||||
@@ -0,0 +1,144 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { agentService } from '@/services/agent/agent'
|
||||
import { authzService } from '@/services/authz/authz'
|
||||
import app from './agent'
|
||||
|
||||
vi.mock('@/services/agent/agent')
|
||||
vi.mock('@/services/authz/authz')
|
||||
|
||||
describe('Agent API', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
vi.mocked(authzService.hasPermission).mockResolvedValue(undefined)
|
||||
})
|
||||
|
||||
describe('GET /teams/:teamId/agents', () => {
|
||||
it('returns list of agents', async () => {
|
||||
const mockAgents = [
|
||||
{
|
||||
id: 'agent1',
|
||||
user: { name: 'Bot 1', image: 'avatar1' },
|
||||
type: 'chat',
|
||||
providerId: 'prov1',
|
||||
modelId: 'model1',
|
||||
soul: 'Soul',
|
||||
config: {
|
||||
provider: 'prov1',
|
||||
model: 'model1',
|
||||
thinkingLevel: 'high',
|
||||
systemPrompt: 'prompt',
|
||||
},
|
||||
skills: [],
|
||||
},
|
||||
]
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
vi.mocked(agentService.listAgents).mockResolvedValue(mockAgents as any)
|
||||
|
||||
const res = await app.request('/teams/team1/agents', {
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const data = await res.json()
|
||||
expect(data).toHaveLength(1)
|
||||
expect(data[0].name).toBe('Bot 1')
|
||||
expect(data[0].providerId).toBe('prov1')
|
||||
})
|
||||
})
|
||||
|
||||
describe('POST /teams/:teamId/agents', () => {
|
||||
it('creates an agent', async () => {
|
||||
const mockAgent = {
|
||||
id: 'agent2',
|
||||
user: { name: 'New Agent', image: 'avatar2' },
|
||||
type: 'chat',
|
||||
providerId: 'prov1',
|
||||
modelId: 'model1',
|
||||
soul: 'New Soul',
|
||||
config: { provider: 'prov1', model: 'model1', thinkingLevel: 'low', systemPrompt: 'p' },
|
||||
skills: [],
|
||||
}
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
vi.mocked(agentService.createAgent).mockResolvedValue(mockAgent as any)
|
||||
|
||||
const res = await app.request('/teams/team1/agents', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
name: 'New Agent',
|
||||
type: 'chat',
|
||||
providerId: 'prov1',
|
||||
modelId: 'model1',
|
||||
thinkingLevel: 'low',
|
||||
systemPrompt: 'p',
|
||||
soul: 'New Soul',
|
||||
skills: ['skill1'],
|
||||
}),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const data = await res.json()
|
||||
expect(data.name).toBe('New Agent')
|
||||
expect(data.soul).toBe('New Soul')
|
||||
})
|
||||
|
||||
it('validates request', async () => {
|
||||
const res = await app.request('/teams/team1/agents', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
name: '',
|
||||
type: 'chat',
|
||||
}),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(400)
|
||||
})
|
||||
})
|
||||
|
||||
describe('PUT /teams/:teamId/agents/:agentId', () => {
|
||||
it('updates an agent', async () => {
|
||||
const mockAgent = {
|
||||
id: 'agent1',
|
||||
user: { name: 'Updated Agent', image: 'avatar1' },
|
||||
type: 'autofill',
|
||||
providerId: 'prov1',
|
||||
modelId: 'model1',
|
||||
soul: 'Updated Soul',
|
||||
config: { provider: 'prov1', model: 'model1' },
|
||||
skills: [],
|
||||
}
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
vi.mocked(agentService.updateAgent).mockResolvedValue(mockAgent as any)
|
||||
|
||||
const res = await app.request('/teams/team1/agents/agent1', {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
name: 'Updated Agent',
|
||||
type: 'autofill',
|
||||
providerId: 'prov1',
|
||||
modelId: 'model1',
|
||||
soul: 'Updated Soul',
|
||||
skills: [],
|
||||
}),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const data = await res.json()
|
||||
expect(data.name).toBe('Updated Agent')
|
||||
expect(data.soul).toBe('Updated Soul')
|
||||
})
|
||||
})
|
||||
|
||||
describe('DELETE /teams/:teamId/agents/:agentId', () => {
|
||||
it('deletes an agent', async () => {
|
||||
const res = await app.request('/teams/team1/agents/agent1', {
|
||||
method: 'DELETE',
|
||||
})
|
||||
|
||||
expect(res.status).toBe(204)
|
||||
expect(agentService.deleteAgent).toHaveBeenCalledWith({ agentId: 'agent1' })
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,151 @@
|
||||
import { Hono } from 'hono'
|
||||
import { zValidator } from '@hono/zod-validator'
|
||||
import { agentService } from '@/services/agent/agent'
|
||||
import { authzService, Permission } from '@/services/authz/authz'
|
||||
import {
|
||||
createAgentRequestSchema,
|
||||
updateAgentRequestSchema,
|
||||
AgentInfo,
|
||||
AgentType,
|
||||
} from '@/dtos/agent'
|
||||
|
||||
import type { Prisma } from '@/generated/prisma/client'
|
||||
|
||||
type User = Prisma.UserGetPayload<Record<string, never>>
|
||||
|
||||
const route = new Hono<{ Variables: { user: User } }>()
|
||||
.get('/teams/:teamId/agents', async (c) => {
|
||||
const teamId = c.req.param('teamId')
|
||||
const userReq = c.get('user')
|
||||
|
||||
await authzService.hasPermission({
|
||||
teamId,
|
||||
user: userReq,
|
||||
permission: Permission.Read,
|
||||
})
|
||||
|
||||
const agents = await agentService.listAgents({ teamId })
|
||||
|
||||
const res: AgentInfo[] = agents.map((agent) => {
|
||||
const config = agent.config as unknown as PrismaJson.AgentConfig
|
||||
return {
|
||||
id: agent.id,
|
||||
name: agent.user.name,
|
||||
type: agent.type as AgentType,
|
||||
enabled: agent.enabled,
|
||||
avatar: agent.user.image || undefined,
|
||||
providerId: agent.providerId || undefined,
|
||||
modelId: agent.modelId || undefined,
|
||||
thinkingLevel: config.thinkingLevel || '',
|
||||
systemPrompt: config.systemPrompt,
|
||||
soul: agent.soul || undefined,
|
||||
skills: agent.skills.map((s) => ({
|
||||
id: s.id,
|
||||
skillId: s.skillId,
|
||||
skill: s.skill,
|
||||
})),
|
||||
}
|
||||
})
|
||||
|
||||
return c.json(res, 200)
|
||||
})
|
||||
.post('/teams/:teamId/agents', zValidator('json', createAgentRequestSchema), async (c) => {
|
||||
const teamId = c.req.param('teamId')
|
||||
const userReq = c.get('user')
|
||||
const req = c.req.valid('json')
|
||||
|
||||
await authzService.hasPermission({
|
||||
teamId,
|
||||
user: userReq,
|
||||
permission: Permission.Admin,
|
||||
})
|
||||
|
||||
const agent = await agentService.createAgent({
|
||||
teamId,
|
||||
...req,
|
||||
})
|
||||
|
||||
if (!agent) throw new Error('failed to create agent')
|
||||
|
||||
const config = agent.config as unknown as PrismaJson.AgentConfig
|
||||
const info: AgentInfo = {
|
||||
id: agent.id,
|
||||
name: agent.user.name,
|
||||
type: agent.type as AgentType,
|
||||
enabled: agent.enabled,
|
||||
avatar: agent.user.image || undefined,
|
||||
providerId: agent.providerId || undefined,
|
||||
modelId: agent.modelId || undefined,
|
||||
thinkingLevel: config.thinkingLevel || '',
|
||||
systemPrompt: config.systemPrompt,
|
||||
soul: agent.soul || undefined,
|
||||
skills: agent.skills.map((s) => ({
|
||||
id: s.id,
|
||||
skillId: s.skillId,
|
||||
skill: s.skill,
|
||||
})),
|
||||
}
|
||||
|
||||
return c.json(info, 200)
|
||||
})
|
||||
.put(
|
||||
'/teams/:teamId/agents/:agentId',
|
||||
zValidator('json', updateAgentRequestSchema),
|
||||
async (c) => {
|
||||
const teamId = c.req.param('teamId')
|
||||
const agentId = c.req.param('agentId')
|
||||
const userReq = c.get('user')
|
||||
const req = c.req.valid('json')
|
||||
|
||||
await authzService.hasPermission({
|
||||
teamId,
|
||||
user: userReq,
|
||||
permission: Permission.Admin,
|
||||
})
|
||||
|
||||
const agent = await agentService.updateAgent({
|
||||
agentId,
|
||||
...req,
|
||||
})
|
||||
|
||||
const config = agent.config as unknown as PrismaJson.AgentConfig
|
||||
const info: AgentInfo = {
|
||||
id: agent.id,
|
||||
name: agent.user.name,
|
||||
type: agent.type as AgentType,
|
||||
enabled: agent.enabled,
|
||||
avatar: agent.user.image || undefined,
|
||||
providerId: agent.providerId || undefined,
|
||||
modelId: agent.modelId || undefined,
|
||||
thinkingLevel: config.thinkingLevel || '',
|
||||
systemPrompt: config.systemPrompt,
|
||||
soul: agent.soul || undefined,
|
||||
skills: agent.skills.map((s) => ({
|
||||
id: s.id,
|
||||
skillId: s.skillId,
|
||||
skill: s.skill,
|
||||
})),
|
||||
}
|
||||
|
||||
return c.json(info, 200)
|
||||
},
|
||||
)
|
||||
.delete('/teams/:teamId/agents/:agentId', async (c) => {
|
||||
const teamId = c.req.param('teamId')
|
||||
const agentId = c.req.param('agentId')
|
||||
const userReq = c.get('user')
|
||||
|
||||
await authzService.hasPermission({
|
||||
teamId,
|
||||
user: userReq,
|
||||
permission: Permission.Admin,
|
||||
})
|
||||
|
||||
await agentService.deleteAgent({
|
||||
agentId,
|
||||
})
|
||||
|
||||
return new Response(null, { status: 204 })
|
||||
})
|
||||
|
||||
export default route
|
||||
@@ -0,0 +1,69 @@
|
||||
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 { authMiddleware } from '@/api/middleware/auth'
|
||||
|
||||
vi.mock('@/api/middleware/auth', () => ({
|
||||
// any is used here because Hono's Context and Next types are complex to mock in vitest.mock
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
authMiddleware: async (c: any, next: any) => {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
c.set('user', { id: 'user1', name: 'Test User' } as any)
|
||||
await next()
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('@/services/authz/authz', () => ({
|
||||
authzService: {
|
||||
hasPermission: vi.fn(),
|
||||
},
|
||||
Permission: {
|
||||
Read: 'Read',
|
||||
Edit: 'Edit',
|
||||
Admin: 'Admin',
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('@/services/s3/s3', () => ({
|
||||
s3Service: {
|
||||
presign: vi.fn().mockResolvedValue('http://mock-s3-url'),
|
||||
},
|
||||
}))
|
||||
|
||||
describe('Attachment API', () => {
|
||||
const app = new Hono().use('*', authMiddleware).route('/', attachmentRoute)
|
||||
|
||||
beforeEach(() => {
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
it('POST /projects/:projectId/attachments', async () => {
|
||||
// We only need the id for this test
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
vi.spyOn(assetService, 'createAsset').mockResolvedValue({ id: 'asset1' } as any)
|
||||
|
||||
const res = await app.request('/projects/project1/attachments', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json', Authorization: 'Bearer test' },
|
||||
body: JSON.stringify({
|
||||
fileName: 'test.txt',
|
||||
contentType: 'text/plain',
|
||||
size: 100,
|
||||
}),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const json = await res.json()
|
||||
expect(json.id).toBe('asset1')
|
||||
expect(json.uploadUrl).toBe('http://mock-s3-url')
|
||||
expect(assetService.createAsset).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
name: 'test.txt',
|
||||
type: AssetType.attachment,
|
||||
projectId: 'project1',
|
||||
}),
|
||||
)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,48 @@
|
||||
import { Hono } from 'hono'
|
||||
import { zValidator } from '@hono/zod-validator'
|
||||
import { postAttachmentRequestSchema } from '@/dtos/asset'
|
||||
import { assetService } from '@/services/asset/asset'
|
||||
import { s3Service } from '@/services/s3/s3'
|
||||
import { AssetType } from '@/generated/prisma/client'
|
||||
import { ulid } from 'ulid'
|
||||
import { authzService, Permission } from '@/services/authz/authz'
|
||||
import type { Prisma } from '@/generated/prisma/client'
|
||||
|
||||
type User = Prisma.UserGetPayload<Record<string, never>>
|
||||
|
||||
const route = new Hono<{ Variables: { user: User } }>().post(
|
||||
'/projects/:projectId/attachments',
|
||||
zValidator('json', postAttachmentRequestSchema),
|
||||
async (c) => {
|
||||
const projectId = c.req.param('projectId')
|
||||
const user = c.get('user')
|
||||
const req = c.req.valid('json')
|
||||
|
||||
await authzService.hasPermission({
|
||||
projectId,
|
||||
user,
|
||||
permission: Permission.Edit,
|
||||
})
|
||||
|
||||
const key = `attachments/${ulid()}/${req.fileName}`
|
||||
|
||||
const assetInfo = await assetService.createAsset({
|
||||
name: req.fileName,
|
||||
type: AssetType.attachment,
|
||||
projectId: projectId,
|
||||
key: key,
|
||||
sizeByte: req.size,
|
||||
contentType: req.contentType,
|
||||
creatorId: user.id,
|
||||
})
|
||||
|
||||
const uploadUrl = await s3Service.presign(process.env.S3_BUCKET || 'shumai', key, 'PUT')
|
||||
|
||||
return c.json({
|
||||
id: assetInfo.id,
|
||||
uploadUrl: uploadUrl,
|
||||
})
|
||||
},
|
||||
)
|
||||
|
||||
export default route
|
||||
@@ -0,0 +1,33 @@
|
||||
import { describe, expect, it, vi, beforeEach, afterEach } from 'vitest'
|
||||
import { Hono } from 'hono'
|
||||
import authnRoute from './authn'
|
||||
import { teamService } from '@/services/team/team'
|
||||
|
||||
describe('authn api', () => {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
let mockGetSignupInfo: any
|
||||
|
||||
beforeEach(() => {
|
||||
mockGetSignupInfo = vi.spyOn(teamService, 'getSignupInfo')
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
it('GET /signup-info', async () => {
|
||||
mockGetSignupInfo.mockResolvedValue({
|
||||
userCount: 5,
|
||||
enablePublicSignup: true,
|
||||
})
|
||||
|
||||
const app = new Hono().route('/', authnRoute)
|
||||
const res = await app.request('/signup-info')
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(await res.json()).toEqual({
|
||||
userCount: 5,
|
||||
enablePublicSignup: true,
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,49 @@
|
||||
import { Hono } from 'hono'
|
||||
import { teamService } from '@/services/team/team'
|
||||
import { auth } from '@/services/auth/auth'
|
||||
import { z } from 'zod'
|
||||
import { zValidator } from '@hono/zod-validator'
|
||||
import { prisma } from '@/db'
|
||||
import { ulid } from 'ulid'
|
||||
|
||||
const app = new Hono()
|
||||
|
||||
const identifySchema = z.object({
|
||||
username: z.string().min(1),
|
||||
email: z.string().email(),
|
||||
})
|
||||
|
||||
const route = app
|
||||
.get('/signup-info', async (c) => {
|
||||
const info = await teamService.getSignupInfo()
|
||||
return c.json({
|
||||
userCount: info.userCount,
|
||||
enablePublicSignup: info.enablePublicSignup,
|
||||
})
|
||||
})
|
||||
.get('/me', async (c) => {
|
||||
const session = await auth.api.getSession({
|
||||
headers: c.req.raw.headers,
|
||||
})
|
||||
return c.json({ id: session?.user?.id ?? null })
|
||||
})
|
||||
.post('/identify', zValidator('json', identifySchema), async (c) => {
|
||||
const { username, email } = c.req.valid('json')
|
||||
|
||||
const dummyEmail = `guest_${ulid()}@guest.local`
|
||||
const user = await prisma.user.create({
|
||||
data: {
|
||||
name: username,
|
||||
email: dummyEmail,
|
||||
guestEmail: email,
|
||||
type: 'human',
|
||||
},
|
||||
})
|
||||
|
||||
return c.json({ id: user.id })
|
||||
})
|
||||
.all('/auth/*', (c) => {
|
||||
return auth.handler(c.req.raw)
|
||||
})
|
||||
|
||||
export default route
|
||||
@@ -0,0 +1,307 @@
|
||||
import { describe, expect, it, vi, beforeEach, afterEach } from 'vitest'
|
||||
import { Hono } from 'hono'
|
||||
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 { authzService } from '@/services/authz/authz'
|
||||
import { authMiddleware } from '@/api/middleware/auth'
|
||||
|
||||
vi.mock('@/services/authz/authz', () => ({
|
||||
authzService: {
|
||||
hasPermission: vi.fn(),
|
||||
},
|
||||
Permission: {
|
||||
Read: 'Read',
|
||||
Edit: 'Edit',
|
||||
Admin: 'Admin',
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('@/api/middleware/auth', () => ({
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
authMiddleware: async (c: any, next: any) => {
|
||||
c.set('user', { id: 'user1', name: 'Test User' })
|
||||
await next()
|
||||
},
|
||||
}))
|
||||
|
||||
describe('file api', () => {
|
||||
beforeEach(() => {
|
||||
vi.mocked(authzService.hasPermission).mockClear()
|
||||
|
||||
vi.spyOn(assetService, 'getAsset').mockImplementation(vi.fn())
|
||||
vi.spyOn(assetService, 'updateAssetName').mockImplementation(vi.fn())
|
||||
vi.spyOn(assetService, 'deleteAssets').mockImplementation(vi.fn())
|
||||
vi.spyOn(assetService, 'createComment').mockImplementation(vi.fn())
|
||||
vi.spyOn(assetService, 'listComments').mockImplementation(vi.fn())
|
||||
vi.spyOn(assetService, 'getComment').mockImplementation(vi.fn())
|
||||
vi.spyOn(assetService, 'restoreAssets').mockImplementation(vi.fn())
|
||||
vi.spyOn(metadataService, 'updateAssetMetadata').mockImplementation(vi.fn())
|
||||
vi.spyOn(notificationService, 'create').mockImplementation(vi.fn())
|
||||
vi.spyOn(s3Service, 'putObject').mockImplementation(vi.fn())
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
it('GET /teams/:teamId/files/:fileId', async () => {
|
||||
vi.mocked(assetService.getAsset).mockResolvedValue({
|
||||
id: 'test-id',
|
||||
name: 'test-file',
|
||||
sizeByte: 10,
|
||||
fileCount: 1,
|
||||
type: 'file',
|
||||
status: 'active',
|
||||
mediaType: 'image/jpeg',
|
||||
createdAt: new Date().toISOString(),
|
||||
updatedAt: new Date().toISOString(),
|
||||
})
|
||||
|
||||
const app = new Hono().use('*', authMiddleware).route('/', fileRoute)
|
||||
const res = await app.request('/teams/test-team/files/test-id')
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const json = await res.json()
|
||||
expect(json.name).toBe('test-file')
|
||||
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith({
|
||||
assetId: 'test-id',
|
||||
user: { id: 'user1', name: 'Test User' },
|
||||
permission: 'Read',
|
||||
})
|
||||
})
|
||||
|
||||
it('PUT /teams/:teamId/files/:fileId', async () => {
|
||||
vi.mocked(assetService.updateAssetName).mockResolvedValue({
|
||||
id: 'test-id',
|
||||
name: 'new-name',
|
||||
sizeByte: 10,
|
||||
fileCount: 1,
|
||||
type: 'file',
|
||||
status: 'active',
|
||||
mediaType: 'image/jpeg',
|
||||
createdAt: new Date().toISOString(),
|
||||
updatedAt: new Date().toISOString(),
|
||||
})
|
||||
|
||||
const app = new Hono().use('*', authMiddleware).route('/', fileRoute)
|
||||
const res = await app.request('/teams/test-team/files/test-id', {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ name: 'new-name' }),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const json = await res.json()
|
||||
expect(json.name).toBe('new-name')
|
||||
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith({
|
||||
assetId: 'test-id',
|
||||
user: { id: 'user1', name: 'Test User' },
|
||||
permission: 'Edit',
|
||||
})
|
||||
})
|
||||
|
||||
it('DELETE /teams/:teamId/files', async () => {
|
||||
vi.mocked(assetService.deleteAssets).mockResolvedValue(undefined)
|
||||
|
||||
const app = new Hono().use('*', authMiddleware).route('/', fileRoute)
|
||||
const res = await app.request('/teams/test-team/files', {
|
||||
method: 'DELETE',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ ids: ['test-id'] }),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(204)
|
||||
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith({
|
||||
assetId: 'test-id',
|
||||
user: { id: 'user1', name: 'Test User' },
|
||||
permission: 'Edit',
|
||||
})
|
||||
expect(assetService.deleteAssets).toHaveBeenCalledWith(['test-id'])
|
||||
})
|
||||
|
||||
it('POST /teams/:teamId/files/restore', async () => {
|
||||
vi.mocked(assetService.restoreAssets).mockResolvedValue(undefined)
|
||||
|
||||
const app = new Hono().use('*', authMiddleware).route('/', fileRoute)
|
||||
const res = await app.request('/teams/test-team/files/restore', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ ids: ['test-id'] }),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(204)
|
||||
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith({
|
||||
assetId: 'test-id',
|
||||
user: { id: 'user1', name: 'Test User' },
|
||||
permission: 'Edit',
|
||||
})
|
||||
expect(assetService.restoreAssets).toHaveBeenCalledWith(['test-id'])
|
||||
})
|
||||
|
||||
it('POST /teams/:teamId/files/:fileId/comments', async () => {
|
||||
vi.mocked(assetService.createComment).mockResolvedValue({
|
||||
id: 'comment-id',
|
||||
assetId: 'test-id',
|
||||
message: 'hello',
|
||||
annotations: null,
|
||||
creator: { id: 'user1', name: 'user-name' },
|
||||
replies: [],
|
||||
attachments: [],
|
||||
mentions: [],
|
||||
createdAt: new Date().toISOString(),
|
||||
updatedAt: new Date().toISOString(),
|
||||
isAi: false,
|
||||
})
|
||||
|
||||
const app = new Hono().use('*', authMiddleware).route('/', fileRoute)
|
||||
const res = await app.request('/teams/test-team/files/test-id/comments', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ message: 'hello', attachmentIds: [] }),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(201)
|
||||
const json = await res.json()
|
||||
expect(json.message).toBe('hello')
|
||||
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith({
|
||||
assetId: 'test-id',
|
||||
user: { id: 'user1', name: 'Test User' },
|
||||
permission: 'Read',
|
||||
})
|
||||
|
||||
expect(notificationService.create).toHaveBeenCalledWith({
|
||||
type: 'comment_created',
|
||||
teamId: 'test-team',
|
||||
creatorId: 'user1',
|
||||
assetId: 'test-id',
|
||||
commentMessage: 'hello',
|
||||
})
|
||||
})
|
||||
|
||||
it('GET /teams/:teamId/files/:fileId/comments', async () => {
|
||||
vi.mocked(assetService.listComments).mockResolvedValue({
|
||||
data: [
|
||||
{
|
||||
id: 'comment-id',
|
||||
assetId: 'test-id',
|
||||
message: 'hello',
|
||||
annotations: null,
|
||||
creator: { id: 'user1', name: 'user-name' },
|
||||
replies: [],
|
||||
attachments: [],
|
||||
mentions: [],
|
||||
createdAt: new Date().toISOString(),
|
||||
updatedAt: new Date().toISOString(),
|
||||
isAi: false,
|
||||
},
|
||||
],
|
||||
pageInfo: { cursor: 'cursor', total: 1 },
|
||||
})
|
||||
|
||||
const app = new Hono().use('*', authMiddleware).route('/', fileRoute)
|
||||
const res = await app.request('/teams/test-team/files/test-id/comments')
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const json = await res.json()
|
||||
expect(json.data).toHaveLength(1)
|
||||
expect(json.data[0].message).toBe('hello')
|
||||
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith({
|
||||
assetId: 'test-id',
|
||||
user: { id: 'user1', name: 'Test User' },
|
||||
permission: 'Read',
|
||||
})
|
||||
})
|
||||
|
||||
it('POST /teams/:teamId/files', async () => {
|
||||
vi.mocked(s3Service.putObject).mockResolvedValue(undefined)
|
||||
|
||||
const formData = new FormData()
|
||||
const file = new File(['test content'], 'test.jpg', { type: 'image/jpeg' })
|
||||
formData.append('file', file)
|
||||
|
||||
const app = new Hono().use('*', authMiddleware).route('/', fileRoute)
|
||||
const res = await app.request('/teams/test-team/files', {
|
||||
method: 'POST',
|
||||
body: formData,
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const json = await res.json()
|
||||
expect(json.key).toMatch(/^files\//)
|
||||
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith({
|
||||
teamId: 'test-team',
|
||||
user: { id: 'user1', name: 'Test User' },
|
||||
permission: 'Read',
|
||||
})
|
||||
expect(s3Service.putObject).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('PATCH /teams/:teamId/files/:fileId/metadata', async () => {
|
||||
vi.mocked(metadataService.updateAssetMetadata).mockResolvedValue(undefined)
|
||||
|
||||
const app = new Hono().use('*', authMiddleware).route('/', fileRoute)
|
||||
const res = await app.request('/teams/test-team/files/test-id/metadata', {
|
||||
method: 'PATCH',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify([{ key: 'status', value: 'approved' }]),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith({
|
||||
assetId: 'test-id',
|
||||
user: { id: 'user1', name: 'Test User' },
|
||||
permission: 'Edit',
|
||||
})
|
||||
|
||||
expect(notificationService.create).toHaveBeenCalledWith({
|
||||
type: 'metadata_field_updated_status',
|
||||
teamId: 'test-team',
|
||||
creatorId: 'user1',
|
||||
assetId: 'test-id',
|
||||
})
|
||||
})
|
||||
|
||||
it('PATCH /teams/:teamId/files/:fileId/order', async () => {
|
||||
vi.spyOn(assetService, 'updateAssetOrder').mockResolvedValue({
|
||||
id: 'test-id',
|
||||
name: 'test-file',
|
||||
sizeByte: 10,
|
||||
fileCount: 1,
|
||||
type: 'file',
|
||||
status: 'active',
|
||||
mediaType: 'image/jpeg',
|
||||
createdAt: new Date().toISOString(),
|
||||
updatedAt: new Date().toISOString(),
|
||||
})
|
||||
|
||||
const app = new Hono().use('*', authMiddleware).route('/', fileRoute)
|
||||
const res = await app.request('/teams/test-team/files/test-id/order', {
|
||||
method: 'PATCH',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ beforeIndex: 'index-1' }),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith({
|
||||
assetId: 'test-id',
|
||||
user: { id: 'user1', name: 'Test User' },
|
||||
permission: 'Edit',
|
||||
})
|
||||
|
||||
expect(assetService.updateAssetOrder).toHaveBeenCalledWith('test-id', {
|
||||
beforeIndex: 'index-1',
|
||||
})
|
||||
})
|
||||
})
|
||||
+231
@@ -0,0 +1,231 @@
|
||||
import { Hono } from 'hono'
|
||||
import { zValidator } from '@hono/zod-validator'
|
||||
import { authzService, Permission } 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 {
|
||||
updateFileRequestSchema,
|
||||
updateAssetOrderRequestSchema,
|
||||
deleteFilesRequestSchema,
|
||||
restoreFilesRequestSchema,
|
||||
createCommentRequestSchema,
|
||||
uploadFileRequestSchema,
|
||||
} from '@/dtos/asset'
|
||||
import { updateAssetMetadataRequestSchema } from '@/dtos/metadata'
|
||||
import { paginationParamsSchema } from '@/dtos/pagination'
|
||||
import { ulid } from 'ulid'
|
||||
import { z } from 'zod'
|
||||
import type { Prisma } from '@/generated/prisma/client'
|
||||
|
||||
type User = Prisma.UserGetPayload<Record<string, never>>
|
||||
|
||||
const route = new Hono<{ Variables: { user: User } }>()
|
||||
.get('/teams/:teamId/files/:fileId', async (c) => {
|
||||
const fileId = c.req.param('fileId')
|
||||
const user = c.get('user')
|
||||
|
||||
await authzService.hasPermission({
|
||||
assetId: fileId,
|
||||
user,
|
||||
permission: Permission.Read,
|
||||
})
|
||||
|
||||
const asset = await assetService.getAsset({ assetId: fileId })
|
||||
return c.json(asset)
|
||||
})
|
||||
.patch(
|
||||
'/teams/:teamId/files/:fileId/order',
|
||||
zValidator('json', updateAssetOrderRequestSchema),
|
||||
async (c) => {
|
||||
const fileId = c.req.param('fileId')
|
||||
const user = c.get('user')
|
||||
const req = c.req.valid('json')
|
||||
|
||||
await authzService.hasPermission({
|
||||
assetId: fileId,
|
||||
user,
|
||||
permission: Permission.Edit,
|
||||
})
|
||||
|
||||
const updated = await assetService.updateAssetOrder(fileId, req)
|
||||
return c.json(updated)
|
||||
},
|
||||
)
|
||||
.put('/teams/:teamId/files/:fileId', zValidator('json', updateFileRequestSchema), async (c) => {
|
||||
const fileId = c.req.param('fileId')
|
||||
const user = c.get('user')
|
||||
const req = c.req.valid('json')
|
||||
|
||||
await authzService.hasPermission({
|
||||
assetId: fileId,
|
||||
user,
|
||||
permission: Permission.Edit,
|
||||
})
|
||||
|
||||
const updatedAsset = await assetService.updateAssetName({
|
||||
id: fileId,
|
||||
name: req.name,
|
||||
})
|
||||
|
||||
return c.json(updatedAsset)
|
||||
})
|
||||
.delete('/teams/:teamId/files', zValidator('json', deleteFilesRequestSchema), async (c) => {
|
||||
const user = c.get('user')
|
||||
const req = c.req.valid('json')
|
||||
|
||||
for (const id of req.ids) {
|
||||
await authzService.hasPermission({
|
||||
assetId: id,
|
||||
user,
|
||||
permission: Permission.Edit,
|
||||
})
|
||||
}
|
||||
|
||||
await assetService.deleteAssets(req.ids)
|
||||
return c.body(null, 204)
|
||||
})
|
||||
.patch(
|
||||
'/teams/:teamId/files/:fileId/metadata',
|
||||
zValidator('json', z.array(updateAssetMetadataRequestSchema)),
|
||||
async (c) => {
|
||||
const teamId = c.req.param('teamId')
|
||||
const fileId = c.req.param('fileId')
|
||||
const user = c.get('user')
|
||||
const req = c.req.valid('json')
|
||||
|
||||
await authzService.hasPermission({
|
||||
assetId: fileId,
|
||||
user,
|
||||
permission: Permission.Edit,
|
||||
})
|
||||
|
||||
await metadataService.updateAssetMetadata(fileId, req)
|
||||
|
||||
const hasStatus = req.some((m) => m.key === 'status')
|
||||
if (hasStatus) {
|
||||
notificationService.create({
|
||||
type: 'metadata_field_updated_status',
|
||||
teamId,
|
||||
creatorId: user.id,
|
||||
assetId: fileId,
|
||||
})
|
||||
}
|
||||
|
||||
return c.json('')
|
||||
},
|
||||
)
|
||||
.post(
|
||||
'/teams/:teamId/files/:fileId/comments',
|
||||
zValidator('json', createCommentRequestSchema.omit({ assetId: true, userId: true })),
|
||||
async (c) => {
|
||||
const teamId = c.req.param('teamId')
|
||||
const fileId = c.req.param('fileId')
|
||||
const user = c.get('user')
|
||||
const req = c.req.valid('json')
|
||||
|
||||
await authzService.hasPermission({
|
||||
assetId: fileId,
|
||||
user,
|
||||
permission: Permission.Read,
|
||||
})
|
||||
|
||||
const comment = await assetService.createComment({
|
||||
assetId: fileId,
|
||||
userId: user.id,
|
||||
replyToId: req.replyToId,
|
||||
message: req.message,
|
||||
annotations: req.annotations,
|
||||
second: req.second,
|
||||
attachmentIds: req.attachmentIds,
|
||||
})
|
||||
|
||||
const notifType = req.replyToId ? 'reply_created' : 'comment_created'
|
||||
|
||||
notificationService.create({
|
||||
type: notifType,
|
||||
teamId,
|
||||
creatorId: user.id,
|
||||
assetId: fileId,
|
||||
commentMessage: req.message,
|
||||
})
|
||||
|
||||
return c.json(comment, 201)
|
||||
},
|
||||
)
|
||||
.get(
|
||||
'/teams/:teamId/files/:fileId/comments',
|
||||
zValidator('query', paginationParamsSchema),
|
||||
async (c) => {
|
||||
const fileId = c.req.param('fileId')
|
||||
const user = c.get('user')
|
||||
const req = c.req.valid('query')
|
||||
|
||||
await authzService.hasPermission({
|
||||
assetId: fileId,
|
||||
user,
|
||||
permission: Permission.Read,
|
||||
})
|
||||
|
||||
const comments = await assetService.listComments(fileId, req)
|
||||
return c.json(comments)
|
||||
},
|
||||
)
|
||||
.get('/teams/:teamId/comments/:commentId', async (c) => {
|
||||
const commentId = c.req.param('commentId')
|
||||
const user = c.get('user')
|
||||
|
||||
const comment = await assetService.getComment(commentId)
|
||||
|
||||
await authzService.hasPermission({
|
||||
assetId: comment.assetId,
|
||||
user,
|
||||
permission: Permission.Read,
|
||||
})
|
||||
|
||||
return c.json(comment)
|
||||
})
|
||||
.post(
|
||||
'/teams/:teamId/files/restore',
|
||||
zValidator('json', restoreFilesRequestSchema),
|
||||
async (c) => {
|
||||
const user = c.get('user')
|
||||
const req = c.req.valid('json')
|
||||
|
||||
for (const id of req.ids) {
|
||||
await authzService.hasPermission({
|
||||
assetId: id,
|
||||
user,
|
||||
permission: Permission.Edit,
|
||||
})
|
||||
}
|
||||
|
||||
await assetService.restoreAssets(req.ids)
|
||||
return c.body(null, 204)
|
||||
},
|
||||
)
|
||||
.post('/teams/:teamId/files', zValidator('form', uploadFileRequestSchema), async (c) => {
|
||||
const teamId = c.req.param('teamId')
|
||||
const user = c.get('user')
|
||||
const { file } = c.req.valid('form')
|
||||
|
||||
await authzService.hasPermission({
|
||||
teamId,
|
||||
user,
|
||||
permission: Permission.Read,
|
||||
})
|
||||
|
||||
if (file.size > 10 * 1024 * 1024) {
|
||||
return c.json('file too large, max 10MB', 400)
|
||||
}
|
||||
|
||||
const key = `files/${ulid()}`
|
||||
const buffer = Buffer.from(await file.arrayBuffer())
|
||||
|
||||
await s3Service.putObject(process.env.S3_BUCKET || 'shumai', key, buffer, file.size, file.type)
|
||||
|
||||
return c.json({ key })
|
||||
})
|
||||
|
||||
export default route
|
||||
@@ -0,0 +1,278 @@
|
||||
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 } from '@/services/authz/authz'
|
||||
import { authMiddleware } from '@/api/middleware/auth'
|
||||
|
||||
vi.mock('@/services/authz/authz', () => ({
|
||||
authzService: {
|
||||
hasPermission: vi.fn(),
|
||||
},
|
||||
Permission: {
|
||||
Read: 'Read',
|
||||
Edit: 'Edit',
|
||||
Admin: 'Admin',
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('@/api/middleware/auth', () => ({
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
authMiddleware: async (c: any, next: any) => {
|
||||
c.set('user', { id: 'user1', name: 'Test User' })
|
||||
await next()
|
||||
},
|
||||
}))
|
||||
|
||||
describe('folder api', () => {
|
||||
beforeEach(() => {
|
||||
vi.mocked(authzService.hasPermission).mockClear()
|
||||
|
||||
vi.spyOn(assetService, 'getAsset').mockImplementation(vi.fn())
|
||||
vi.spyOn(assetService, 'createAsset').mockImplementation(vi.fn())
|
||||
vi.spyOn(assetService, 'updateAssetName').mockImplementation(vi.fn())
|
||||
vi.spyOn(assetService, 'deleteAssets').mockImplementation(vi.fn())
|
||||
vi.spyOn(assetService, 'restoreAssets').mockImplementation(vi.fn())
|
||||
vi.spyOn(assetService, 'listChildren').mockImplementation(vi.fn())
|
||||
vi.spyOn(searchService, 'search').mockImplementation(vi.fn())
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
it('GET /teams/:teamId/folders/:folderId', async () => {
|
||||
vi.mocked(assetService.getAsset).mockResolvedValue({
|
||||
id: 'test-id',
|
||||
name: 'test-folder',
|
||||
sizeByte: 10,
|
||||
fileCount: 1,
|
||||
type: 'folder',
|
||||
status: 'active',
|
||||
mediaType: null,
|
||||
createdAt: new Date().toISOString(),
|
||||
updatedAt: new Date().toISOString(),
|
||||
})
|
||||
|
||||
const app = new Hono().use('*', authMiddleware).route('/', folderRoute)
|
||||
const res = await app.request('/teams/test-team/folders/test-id')
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const json = await res.json()
|
||||
expect(json.name).toBe('test-folder')
|
||||
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith({
|
||||
assetId: 'test-id',
|
||||
user: { id: 'user1', name: 'Test User' },
|
||||
permission: 'Read',
|
||||
})
|
||||
})
|
||||
|
||||
it('PUT /teams/:teamId/folders/:folderId', async () => {
|
||||
vi.mocked(assetService.updateAssetName).mockResolvedValue({
|
||||
id: 'test-id',
|
||||
name: 'new-name',
|
||||
sizeByte: 10,
|
||||
fileCount: 1,
|
||||
type: 'folder',
|
||||
status: 'active',
|
||||
mediaType: null,
|
||||
createdAt: new Date().toISOString(),
|
||||
updatedAt: new Date().toISOString(),
|
||||
})
|
||||
|
||||
const app = new Hono().use('*', authMiddleware).route('/', folderRoute)
|
||||
const res = await app.request('/teams/test-team/folders/test-id', {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ name: 'new-name' }),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const json = await res.json()
|
||||
expect(json.name).toBe('new-name')
|
||||
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith({
|
||||
assetId: 'test-id',
|
||||
user: { id: 'user1', name: 'Test User' },
|
||||
permission: 'Edit',
|
||||
})
|
||||
})
|
||||
|
||||
it('POST /teams/:teamId/folders', async () => {
|
||||
vi.mocked(assetService.createAsset).mockResolvedValue({
|
||||
id: 'new-id',
|
||||
name: 'new-folder',
|
||||
sizeByte: 0,
|
||||
fileCount: 0,
|
||||
type: 'folder',
|
||||
status: 'active',
|
||||
mediaType: null,
|
||||
createdAt: new Date().toISOString(),
|
||||
updatedAt: new Date().toISOString(),
|
||||
})
|
||||
|
||||
const app = new Hono().use('*', authMiddleware).route('/', folderRoute)
|
||||
const res = await app.request('/teams/test-team/folders', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ name: 'new-folder', parentId: 'parent-id' }),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const json = await res.json()
|
||||
expect(json.name).toBe('new-folder')
|
||||
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith({
|
||||
assetId: 'parent-id',
|
||||
user: { id: 'user1', name: 'Test User' },
|
||||
permission: 'Edit',
|
||||
})
|
||||
})
|
||||
|
||||
it('GET /teams/:teamId/folders/:folderId/children', async () => {
|
||||
vi.mocked(assetService.listChildren).mockResolvedValue({
|
||||
data: [
|
||||
{
|
||||
id: 'child-id',
|
||||
name: 'child-folder',
|
||||
sizeByte: 0,
|
||||
fileCount: 0,
|
||||
type: 'folder',
|
||||
status: 'active',
|
||||
mediaType: null,
|
||||
createdAt: new Date().toISOString(),
|
||||
updatedAt: new Date().toISOString(),
|
||||
},
|
||||
],
|
||||
pageInfo: { total: 1, cursor: '' },
|
||||
})
|
||||
|
||||
const app = new Hono().use('*', authMiddleware).route('/', folderRoute)
|
||||
const res = await app.request('/teams/test-team/folders/test-id/children?assetType=folder')
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const json = await res.json()
|
||||
expect(json.data).toHaveLength(1)
|
||||
expect(json.data[0].name).toBe('child-folder')
|
||||
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith({
|
||||
assetId: 'test-id',
|
||||
user: { id: 'user1', name: 'Test User' },
|
||||
permission: 'Read',
|
||||
})
|
||||
})
|
||||
|
||||
it('DELETE /teams/:teamId/folders', async () => {
|
||||
vi.mocked(assetService.deleteAssets).mockResolvedValue(undefined)
|
||||
|
||||
const app = new Hono().use('*', authMiddleware).route('/', folderRoute)
|
||||
const res = await app.request('/teams/test-team/folders', {
|
||||
method: 'DELETE',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ ids: ['test-id'] }),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(204)
|
||||
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith({
|
||||
assetId: 'test-id',
|
||||
user: { id: 'user1', name: 'Test User' },
|
||||
permission: 'Edit',
|
||||
})
|
||||
expect(assetService.deleteAssets).toHaveBeenCalledWith(['test-id'])
|
||||
})
|
||||
|
||||
it('POST /teams/:teamId/folders/restore', async () => {
|
||||
vi.mocked(assetService.restoreAssets).mockResolvedValue(undefined)
|
||||
|
||||
const app = new Hono().use('*', authMiddleware).route('/', folderRoute)
|
||||
const res = await app.request('/teams/test-team/folders/restore', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ ids: ['test-id'] }),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(204)
|
||||
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith({
|
||||
assetId: 'test-id',
|
||||
user: { id: 'user1', name: 'Test User' },
|
||||
permission: 'Edit',
|
||||
})
|
||||
expect(assetService.restoreAssets).toHaveBeenCalledWith(['test-id'])
|
||||
})
|
||||
|
||||
it('POST /teams/:teamId/folders/:folderId/search', async () => {
|
||||
vi.mocked(searchService.search).mockResolvedValue({
|
||||
data: [
|
||||
{
|
||||
id: 'result-id',
|
||||
name: 'result-folder',
|
||||
sizeByte: 0,
|
||||
fileCount: 0,
|
||||
type: 'folder',
|
||||
status: 'active',
|
||||
mediaType: null,
|
||||
createdAt: new Date().toISOString(),
|
||||
updatedAt: new Date().toISOString(),
|
||||
},
|
||||
],
|
||||
pageInfo: { total: 1, cursor: '' },
|
||||
})
|
||||
|
||||
const app = new Hono().use('*', authMiddleware).route('/', folderRoute)
|
||||
const res = await app.request('/teams/test-team/folders/test-id/search', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
conditions: [{ field: 'name', operator: 'eq', value: 'result-folder' }],
|
||||
}),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const json = await res.json()
|
||||
expect(json.data).toHaveLength(1)
|
||||
expect(json.data[0].name).toBe('result-folder')
|
||||
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith({
|
||||
assetId: 'test-id',
|
||||
user: { id: 'user1', name: 'Test User' },
|
||||
permission: 'Read',
|
||||
})
|
||||
})
|
||||
|
||||
it('PATCH /teams/:teamId/folders/:folderId/order', async () => {
|
||||
vi.spyOn(assetService, 'updateAssetOrder').mockResolvedValue({
|
||||
id: 'test-id',
|
||||
name: 'test-folder',
|
||||
sizeByte: 10,
|
||||
fileCount: 1,
|
||||
type: 'folder',
|
||||
status: 'active',
|
||||
mediaType: null,
|
||||
createdAt: new Date().toISOString(),
|
||||
updatedAt: new Date().toISOString(),
|
||||
})
|
||||
|
||||
const app = new Hono().use('*', authMiddleware).route('/', folderRoute)
|
||||
const res = await app.request('/teams/test-team/folders/test-id/order', {
|
||||
method: 'PATCH',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ beforeIndex: 'index-1' }),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith({
|
||||
assetId: 'test-id',
|
||||
user: { id: 'user1', name: 'Test User' },
|
||||
permission: 'Edit',
|
||||
})
|
||||
|
||||
expect(assetService.updateAssetOrder).toHaveBeenCalledWith('test-id', {
|
||||
beforeIndex: 'index-1',
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,167 @@
|
||||
import { Hono } from 'hono'
|
||||
import { zValidator } from '@hono/zod-validator'
|
||||
import { authzService, Permission } from '@/services/authz/authz'
|
||||
import { assetService } from '@/services/asset/asset'
|
||||
import { searchService } from '@/services/search/search'
|
||||
import {
|
||||
createFolderRequestSchema,
|
||||
updateFolderRequestSchema,
|
||||
deleteFoldersRequestSchema,
|
||||
restoreFoldersRequestSchema,
|
||||
} from '@/dtos/folder'
|
||||
import { listChildrenRequestSchema, updateAssetOrderRequestSchema } from '@/dtos/asset'
|
||||
import { searchRequestSchema } from '@/dtos/search'
|
||||
import type { Prisma } from '@/generated/prisma/client'
|
||||
|
||||
type User = Prisma.UserGetPayload<Record<string, never>>
|
||||
|
||||
const route = new Hono<{ Variables: { user: User } }>()
|
||||
.post('/teams/:teamId/folders', zValidator('json', createFolderRequestSchema), async (c) => {
|
||||
const user = c.get('user')
|
||||
const req = c.req.valid('json')
|
||||
|
||||
await authzService.hasPermission({
|
||||
assetId: req.parentId,
|
||||
user,
|
||||
permission: Permission.Edit,
|
||||
})
|
||||
|
||||
const newAsset = await assetService.createAsset({
|
||||
name: req.name,
|
||||
parentId: req.parentId,
|
||||
type: 'folder',
|
||||
})
|
||||
|
||||
return c.json(newAsset)
|
||||
})
|
||||
.patch(
|
||||
'/teams/:teamId/folders/:folderId/order',
|
||||
zValidator('json', updateAssetOrderRequestSchema),
|
||||
async (c) => {
|
||||
const folderId = c.req.param('folderId')
|
||||
const user = c.get('user')
|
||||
const req = c.req.valid('json')
|
||||
|
||||
await authzService.hasPermission({
|
||||
assetId: folderId,
|
||||
user,
|
||||
permission: Permission.Edit,
|
||||
})
|
||||
|
||||
const updated = await assetService.updateAssetOrder(folderId, req)
|
||||
return c.json(updated)
|
||||
},
|
||||
)
|
||||
.put(
|
||||
'/teams/:teamId/folders/:folderId',
|
||||
zValidator('json', updateFolderRequestSchema),
|
||||
async (c) => {
|
||||
const folderId = c.req.param('folderId')
|
||||
const user = c.get('user')
|
||||
const req = c.req.valid('json')
|
||||
|
||||
await authzService.hasPermission({
|
||||
assetId: folderId,
|
||||
user,
|
||||
permission: Permission.Edit,
|
||||
})
|
||||
|
||||
const updatedAsset = await assetService.updateAssetName({
|
||||
id: folderId,
|
||||
name: req.name,
|
||||
})
|
||||
|
||||
return c.json(updatedAsset)
|
||||
},
|
||||
)
|
||||
.get('/teams/:teamId/folders/:folderId', async (c) => {
|
||||
const folderId = c.req.param('folderId')
|
||||
const user = c.get('user')
|
||||
|
||||
await authzService.hasPermission({
|
||||
assetId: folderId,
|
||||
user,
|
||||
permission: Permission.Read,
|
||||
})
|
||||
|
||||
const assetInfo = await assetService.getAsset({ assetId: folderId })
|
||||
return c.json(assetInfo)
|
||||
})
|
||||
.get(
|
||||
'/teams/:teamId/folders/:folderId/children',
|
||||
zValidator('query', listChildrenRequestSchema),
|
||||
async (c) => {
|
||||
const folderId = c.req.param('folderId')
|
||||
const user = c.get('user')
|
||||
const req = c.req.valid('query')
|
||||
|
||||
await authzService.hasPermission({
|
||||
assetId: folderId,
|
||||
user,
|
||||
permission: Permission.Read,
|
||||
})
|
||||
|
||||
const resp = await assetService.listChildren({
|
||||
assetId: folderId,
|
||||
assetType: req.assetType,
|
||||
|
||||
sort: req.sort,
|
||||
order: req.order,
|
||||
})
|
||||
return c.json(resp)
|
||||
},
|
||||
)
|
||||
.delete('/teams/:teamId/folders', zValidator('json', deleteFoldersRequestSchema), async (c) => {
|
||||
const user = c.get('user')
|
||||
const req = c.req.valid('json')
|
||||
|
||||
for (const id of req.ids) {
|
||||
await authzService.hasPermission({
|
||||
assetId: id,
|
||||
user,
|
||||
permission: Permission.Edit,
|
||||
})
|
||||
}
|
||||
|
||||
await assetService.deleteAssets(req.ids)
|
||||
return c.body(null, 204)
|
||||
})
|
||||
.post(
|
||||
'/teams/:teamId/folders/restore',
|
||||
zValidator('json', restoreFoldersRequestSchema),
|
||||
async (c) => {
|
||||
const user = c.get('user')
|
||||
const req = c.req.valid('json')
|
||||
|
||||
for (const id of req.ids) {
|
||||
await authzService.hasPermission({
|
||||
assetId: id,
|
||||
user,
|
||||
permission: Permission.Edit,
|
||||
})
|
||||
}
|
||||
|
||||
await assetService.restoreAssets(req.ids)
|
||||
return c.body(null, 204)
|
||||
},
|
||||
)
|
||||
.post(
|
||||
'/teams/:teamId/folders/:folderId/search',
|
||||
zValidator('json', searchRequestSchema),
|
||||
async (c) => {
|
||||
const folderId = c.req.param('folderId')
|
||||
const user = c.get('user')
|
||||
const req = c.req.valid('json')
|
||||
|
||||
await authzService.hasPermission({
|
||||
assetId: folderId,
|
||||
user,
|
||||
permission: Permission.Read,
|
||||
})
|
||||
|
||||
const result = await searchService.search(folderId, req)
|
||||
return c.json(result)
|
||||
},
|
||||
)
|
||||
|
||||
export default route
|
||||
@@ -0,0 +1,185 @@
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
import { Hono } from 'hono'
|
||||
import inviteRoute from './invite'
|
||||
import publicInviteRoute from './public-invite'
|
||||
import { authMiddleware } from '@/api/middleware/auth'
|
||||
|
||||
vi.mock('@/services/invite/invite', () => ({
|
||||
inviteService: {
|
||||
createTeamInvite: vi.fn(),
|
||||
createProjectInvite: vi.fn(),
|
||||
getInvite: vi.fn(),
|
||||
consumeInvite: vi.fn(),
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('@/services/notification/notification', () => ({
|
||||
notificationService: {
|
||||
create: vi.fn(),
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('@/services/authz/authz', () => ({
|
||||
authzService: {
|
||||
hasPermission: vi.fn(),
|
||||
},
|
||||
Permission: {
|
||||
Read: 'Read',
|
||||
Edit: 'Edit',
|
||||
Admin: 'Admin',
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('@/api/middleware/auth', () => ({
|
||||
// any is used here because Hono's Context and Next types are complex to mock in vitest.mock
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
authMiddleware: async (c: any, next: any) => {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
c.set('user', { id: 'u1', name: 'Test User' } as any)
|
||||
await next()
|
||||
},
|
||||
}))
|
||||
|
||||
const getApp = () => {
|
||||
const app = new Hono()
|
||||
.route('/', publicInviteRoute)
|
||||
.use('*', authMiddleware)
|
||||
.route('/', inviteRoute)
|
||||
return app
|
||||
}
|
||||
|
||||
describe('Invite API', () => {
|
||||
it('GET /invite/:code', async () => {
|
||||
const app = getApp()
|
||||
const { inviteService } = await import('@/services/invite/invite')
|
||||
vi.mocked(inviteService.getInvite).mockResolvedValue({
|
||||
code: 'code123',
|
||||
teamId: 't1',
|
||||
team: { name: 'My Team' },
|
||||
inviter: { name: 'Inviter' },
|
||||
role: 'editor',
|
||||
used: false,
|
||||
} as never)
|
||||
|
||||
const res = await app.request('/invite/code123')
|
||||
expect(res.status).toBe(200)
|
||||
expect(await res.json()).toEqual({
|
||||
code: 'code123',
|
||||
role: 'editor',
|
||||
teamId: 't1',
|
||||
teamName: 'My Team',
|
||||
inviterName: 'Inviter',
|
||||
isUsed: false,
|
||||
})
|
||||
})
|
||||
|
||||
it('POST /teams/:teamId/invite', async () => {
|
||||
const app = getApp()
|
||||
const { authzService } = await import('@/services/authz/authz')
|
||||
const { inviteService } = await import('@/services/invite/invite')
|
||||
vi.mocked(authzService.hasPermission).mockResolvedValue(undefined as never)
|
||||
vi.mocked(inviteService.createTeamInvite).mockResolvedValue({
|
||||
code: 'test-code',
|
||||
role: 'editor',
|
||||
teamId: 't1',
|
||||
team: { name: 'Team A' },
|
||||
inviter: { name: 'Inviter' },
|
||||
used: false,
|
||||
} as never)
|
||||
|
||||
const res = await app.request('/teams/t1/invite', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
Authorization: 'Bearer fake',
|
||||
},
|
||||
body: JSON.stringify({ role: 'editor' }),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(await res.json()).toEqual({
|
||||
code: 'test-code',
|
||||
role: 'editor',
|
||||
teamId: 't1',
|
||||
teamName: 'Team A',
|
||||
inviterName: 'Inviter',
|
||||
isUsed: false,
|
||||
})
|
||||
expect(inviteService.createTeamInvite).toHaveBeenCalledWith({
|
||||
teamId: 't1',
|
||||
role: 'editor',
|
||||
inviterId: 'u1',
|
||||
})
|
||||
})
|
||||
|
||||
it('POST /projects/:projectId/invite', async () => {
|
||||
const app = getApp()
|
||||
const { authzService } = await import('@/services/authz/authz')
|
||||
const { inviteService } = await import('@/services/invite/invite')
|
||||
vi.mocked(authzService.hasPermission).mockResolvedValue(undefined as never)
|
||||
vi.mocked(inviteService.createProjectInvite).mockResolvedValue({
|
||||
code: 'proj-code',
|
||||
role: 'reviewer',
|
||||
teamId: 't1',
|
||||
team: { name: 'Team A' },
|
||||
project: { id: 'p1', name: 'Project A' },
|
||||
inviter: { name: 'Inviter' },
|
||||
used: false,
|
||||
} as never)
|
||||
|
||||
const res = await app.request('/projects/p1/invite', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
Authorization: 'Bearer fake',
|
||||
},
|
||||
body: JSON.stringify({ role: 'reviewer' }),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(await res.json()).toEqual({
|
||||
code: 'proj-code',
|
||||
role: 'reviewer',
|
||||
teamId: 't1',
|
||||
teamName: 'Team A',
|
||||
projectId: 'p1',
|
||||
projectName: 'Project A',
|
||||
inviterName: 'Inviter',
|
||||
isUsed: false,
|
||||
})
|
||||
expect(inviteService.createProjectInvite).toHaveBeenCalledWith({
|
||||
projectId: 'p1',
|
||||
role: 'reviewer',
|
||||
inviterId: 'u1',
|
||||
})
|
||||
})
|
||||
|
||||
it('POST /join (Team)', async () => {
|
||||
const app = getApp()
|
||||
const { inviteService } = await import('@/services/invite/invite')
|
||||
const { notificationService } = await import('@/services/notification/notification')
|
||||
|
||||
vi.mocked(notificationService.create).mockResolvedValue(undefined as never)
|
||||
|
||||
vi.mocked(inviteService.getInvite).mockResolvedValue({
|
||||
code: 'code123',
|
||||
teamId: 't1',
|
||||
team: { name: 'Team A' },
|
||||
inviter: { name: 'Inviter' },
|
||||
used: false,
|
||||
} as never)
|
||||
vi.mocked(inviteService.consumeInvite).mockResolvedValue(undefined as never)
|
||||
|
||||
const res = await app.request('/join', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
Authorization: 'Bearer fake',
|
||||
},
|
||||
body: JSON.stringify({ code: 'code123' }),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(inviteService.consumeInvite).toHaveBeenCalledWith('code123', 'u1')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,111 @@
|
||||
import { zValidator } from '@hono/zod-validator'
|
||||
import { Hono } from 'hono'
|
||||
import {
|
||||
createProjectInviteRequestSchema,
|
||||
createTeamInviteRequestSchema,
|
||||
joinRequestSchema,
|
||||
InviteInfo,
|
||||
} from '@/dtos/invite'
|
||||
import { authzService, Permission } 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'
|
||||
|
||||
type User = Prisma.UserGetPayload<Record<string, never>>
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const mapToInviteInfo = (inv: any): InviteInfo => {
|
||||
const info: InviteInfo = {
|
||||
code: inv.code,
|
||||
role: inv.role!,
|
||||
teamId: inv.teamId,
|
||||
teamName: inv.team.name,
|
||||
inviterName: inv.inviter.name,
|
||||
isUsed: inv.used,
|
||||
}
|
||||
|
||||
if (inv.project) {
|
||||
info.projectId = inv.project.id
|
||||
info.projectName = inv.project.name
|
||||
}
|
||||
|
||||
return info
|
||||
}
|
||||
|
||||
const route = new Hono<{ Variables: { user: User } }>()
|
||||
.post('/teams/:teamId/invite', zValidator('json', createTeamInviteRequestSchema), async (c) => {
|
||||
const teamId = c.req.param('teamId')
|
||||
const req = c.req.valid('json')
|
||||
const user = c.get('user')
|
||||
|
||||
await authzService.hasPermission({
|
||||
teamId,
|
||||
user,
|
||||
permission: Permission.Admin,
|
||||
})
|
||||
|
||||
const inv = await inviteService.createTeamInvite({
|
||||
teamId,
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
role: req.role as any,
|
||||
inviterId: user.id,
|
||||
})
|
||||
|
||||
return c.json(mapToInviteInfo(inv))
|
||||
})
|
||||
.post(
|
||||
'/projects/:projectId/invite',
|
||||
zValidator('json', createProjectInviteRequestSchema),
|
||||
async (c) => {
|
||||
const projectId = c.req.param('projectId')
|
||||
const req = c.req.valid('json')
|
||||
const user = c.get('user')
|
||||
|
||||
await authzService.hasPermission({
|
||||
projectId,
|
||||
user,
|
||||
permission: Permission.Admin,
|
||||
})
|
||||
|
||||
const inv = await inviteService.createProjectInvite({
|
||||
projectId,
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
role: req.role as any,
|
||||
inviterId: user.id,
|
||||
})
|
||||
|
||||
return c.json(mapToInviteInfo(inv))
|
||||
},
|
||||
)
|
||||
.post('/join', zValidator('json', joinRequestSchema), async (c) => {
|
||||
const req = c.req.valid('json')
|
||||
const user = c.get('user')
|
||||
|
||||
try {
|
||||
const info = await inviteService.getInvite(req.code)
|
||||
|
||||
await inviteService.consumeInvite(req.code, user.id)
|
||||
|
||||
if (info.projectId) {
|
||||
await notificationService.create({
|
||||
type: NotificationType.new_user_join_project,
|
||||
teamId: info.teamId,
|
||||
projectId: info.projectId,
|
||||
userId: user.id,
|
||||
})
|
||||
} else {
|
||||
await notificationService.create({
|
||||
type: NotificationType.new_user_join_team,
|
||||
teamId: info.teamId,
|
||||
userId: user.id,
|
||||
})
|
||||
}
|
||||
|
||||
return new Response(null, { status: 200 })
|
||||
} catch {
|
||||
return c.json({ error: 'Bad Request' }, 400)
|
||||
}
|
||||
})
|
||||
|
||||
export default route
|
||||
@@ -0,0 +1,154 @@
|
||||
import { describe, expect, it, vi, beforeEach, afterEach } from 'vitest'
|
||||
import { Hono } from 'hono'
|
||||
import metadataRoute from './metadata'
|
||||
import { metadataService } from '@/services/metadata/metadata'
|
||||
import { Prisma } from '@/generated/prisma/client.ts'
|
||||
import { authMiddleware } from '@/api/middleware/auth'
|
||||
|
||||
vi.mock('@/services/authz/authz', () => ({
|
||||
authzService: {
|
||||
hasPermission: vi.fn(),
|
||||
},
|
||||
Permission: {
|
||||
Read: 'Read',
|
||||
Edit: 'Edit',
|
||||
Admin: 'Admin',
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('@/api/middleware/auth', () => ({
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
authMiddleware: async (c: any, next: any) => {
|
||||
c.set('user', { id: 'user1', name: 'Test User' })
|
||||
await next()
|
||||
},
|
||||
}))
|
||||
|
||||
describe('metadata api', () => {
|
||||
beforeEach(() => {
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
it('GET /teams/:teamId/fields', async () => {
|
||||
const mockField = {
|
||||
key: 'field1',
|
||||
scope: 'TEAM',
|
||||
config: { name: 'Test Field', type: 'text' },
|
||||
readOnly: false,
|
||||
description: 'desc',
|
||||
aiAutofill: true,
|
||||
} as Prisma.MetadataFieldGetPayload<Record<string, never>>
|
||||
|
||||
vi.spyOn(metadataService, 'listTeamFields').mockResolvedValue([mockField])
|
||||
|
||||
const app = new Hono().use('*', authMiddleware).route('/', metadataRoute)
|
||||
const res = await app.request('/teams/t1/fields')
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const json = await res.json()
|
||||
expect(json).toHaveLength(1)
|
||||
expect(json[0].id).toBe('field1')
|
||||
expect(json[0].config.name).toBe('Test Field')
|
||||
expect(json[0].aiAutofill).toBe(true)
|
||||
})
|
||||
|
||||
it('POST /teams/:teamId/fields', async () => {
|
||||
const mockField = {
|
||||
key: 'newfield',
|
||||
scope: 'TEAM',
|
||||
config: { name: 'New Field', type: 'text' },
|
||||
readOnly: false,
|
||||
description: 'desc',
|
||||
aiAutofill: true,
|
||||
} as Prisma.MetadataFieldGetPayload<Record<string, never>>
|
||||
|
||||
vi.spyOn(metadataService, 'createTeamField').mockResolvedValue(mockField)
|
||||
|
||||
const app = new Hono().use('*', authMiddleware).route('/', metadataRoute)
|
||||
const res = await app.request('/teams/t1/fields', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
config: { name: 'New Field', type: 'text' },
|
||||
aiAutofill: true,
|
||||
description: 'desc',
|
||||
}),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const json = await res.json()
|
||||
expect(json.id).toBe('newfield')
|
||||
})
|
||||
|
||||
it('GET /projects/:projectId/fields', async () => {
|
||||
const mockField = {
|
||||
key: 'field1',
|
||||
scope: 'PROJECT',
|
||||
config: { name: 'Project Field', type: 'text' },
|
||||
readOnly: false,
|
||||
description: 'desc',
|
||||
aiAutofill: false,
|
||||
} as Prisma.MetadataFieldGetPayload<Record<string, never>>
|
||||
|
||||
vi.spyOn(metadataService, 'listProjectFields').mockResolvedValue([
|
||||
{ field: mockField, visible: true },
|
||||
])
|
||||
|
||||
const app = new Hono().use('*', authMiddleware).route('/', metadataRoute)
|
||||
const res = await app.request('/projects/p1/fields')
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const json = await res.json()
|
||||
expect(json).toHaveLength(1)
|
||||
expect(json[0].id).toBe('field1')
|
||||
expect(json[0].visible).toBe(true)
|
||||
})
|
||||
|
||||
it('PATCH /projects/:projectId/fields/order', async () => {
|
||||
vi.spyOn(metadataService, 'updateProjectFieldsOrder').mockResolvedValue(undefined)
|
||||
|
||||
const app = new Hono().use('*', authMiddleware).route('/', metadataRoute)
|
||||
const res = await app.request('/projects/p1/fields/order', {
|
||||
method: 'PATCH',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify([{ fieldId: 'field1', visible: true }]),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(204)
|
||||
expect(metadataService.updateProjectFieldsOrder).toHaveBeenCalledWith('user1', 'p1', [
|
||||
{ fieldId: 'field1', visible: true },
|
||||
])
|
||||
})
|
||||
|
||||
it('DELETE /teams/:teamId/fields/:fieldId', async () => {
|
||||
vi.spyOn(metadataService, 'deleteTeamField').mockResolvedValue(undefined)
|
||||
|
||||
const app = new Hono().use('*', authMiddleware).route('/', metadataRoute)
|
||||
const res = await app.request('/teams/t1/fields/f1', {
|
||||
method: 'DELETE',
|
||||
})
|
||||
|
||||
expect(res.status).toBe(204)
|
||||
expect(metadataService.deleteTeamField).toHaveBeenCalledWith('t1', 'f1')
|
||||
})
|
||||
|
||||
it('PATCH /teams/:teamId/files/:fileId/metadata', async () => {
|
||||
vi.spyOn(metadataService, 'updateAssetMetadata').mockResolvedValue(undefined)
|
||||
|
||||
const app = new Hono().use('*', authMiddleware).route('/', metadataRoute)
|
||||
const res = await app.request('/teams/t1/files/f1/metadata', {
|
||||
method: 'PATCH',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify([{ key: 'resolution_width', value: 1920 }]),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(204)
|
||||
expect(metadataService.updateAssetMetadata).toHaveBeenCalledWith('f1', [
|
||||
{ key: 'resolution_width', value: 1920 },
|
||||
])
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,194 @@
|
||||
import { zValidator } from '@hono/zod-validator'
|
||||
import { z } from 'zod'
|
||||
import { Hono } from 'hono'
|
||||
import { metadataService } from '@/services/metadata/metadata'
|
||||
import { authzService, Permission } from '@/services/authz/authz'
|
||||
import {
|
||||
createFieldRequestSchema,
|
||||
updateFieldRequestSchema,
|
||||
updateProjectFieldsOrderRequestSchema,
|
||||
updateAssetMetadataRequestSchema,
|
||||
FieldInfo,
|
||||
} from '@/dtos/metadata'
|
||||
import type { Prisma } from '@/generated/prisma/client'
|
||||
|
||||
type User = Prisma.UserGetPayload<Record<string, never>>
|
||||
|
||||
function toFieldInfo(
|
||||
f: Prisma.MetadataFieldGetPayload<Record<string, never>>,
|
||||
visible = false,
|
||||
): FieldInfo {
|
||||
return {
|
||||
id: f.key,
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
config: f.config as any,
|
||||
scope: f.scope ?? '',
|
||||
readOnly: f.readOnly,
|
||||
visible: visible,
|
||||
description: f.description,
|
||||
aiAutofill: f.aiAutofill,
|
||||
}
|
||||
}
|
||||
|
||||
const route = new Hono<{ Variables: { user: User } }>()
|
||||
.post('/teams/:teamId/fields', zValidator('json', createFieldRequestSchema), async (c) => {
|
||||
const teamId = c.req.param('teamId')
|
||||
const req = c.req.valid('json')
|
||||
const user = c.get('user')
|
||||
|
||||
await authzService.hasPermission({
|
||||
teamId,
|
||||
user,
|
||||
permission: Permission.Admin,
|
||||
})
|
||||
|
||||
const field = await metadataService.createTeamField(teamId, req)
|
||||
return c.json(toFieldInfo(field))
|
||||
})
|
||||
.get('/teams/:teamId/fields', async (c) => {
|
||||
const teamId = c.req.param('teamId')
|
||||
const user = c.get('user')
|
||||
|
||||
await authzService.hasPermission({
|
||||
teamId,
|
||||
user,
|
||||
permission: Permission.Read,
|
||||
})
|
||||
|
||||
const fields = await metadataService.listTeamFields(teamId)
|
||||
return c.json(fields.map((f) => toFieldInfo(f)))
|
||||
})
|
||||
.put(
|
||||
'/teams/:teamId/fields/:fieldId',
|
||||
zValidator('json', updateFieldRequestSchema),
|
||||
async (c) => {
|
||||
const teamId = c.req.param('teamId')
|
||||
const fieldId = c.req.param('fieldId')
|
||||
const req = c.req.valid('json')
|
||||
const user = c.get('user')
|
||||
|
||||
await authzService.hasPermission({
|
||||
teamId,
|
||||
user,
|
||||
permission: Permission.Admin,
|
||||
})
|
||||
|
||||
const field = await metadataService.updateTeamField(teamId, fieldId, req)
|
||||
return c.json(toFieldInfo(field))
|
||||
},
|
||||
)
|
||||
.delete('/teams/:teamId/fields/:fieldId', async (c) => {
|
||||
const teamId = c.req.param('teamId')
|
||||
const fieldId = c.req.param('fieldId')
|
||||
const user = c.get('user')
|
||||
|
||||
await authzService.hasPermission({
|
||||
teamId,
|
||||
user,
|
||||
permission: Permission.Admin,
|
||||
})
|
||||
|
||||
await metadataService.deleteTeamField(teamId, fieldId)
|
||||
return new Response(null, { status: 204 })
|
||||
})
|
||||
.post('/projects/:projectId/fields', zValidator('json', createFieldRequestSchema), async (c) => {
|
||||
const projectId = c.req.param('projectId')
|
||||
const req = c.req.valid('json')
|
||||
const user = c.get('user')
|
||||
|
||||
await authzService.hasPermission({
|
||||
projectId,
|
||||
user,
|
||||
permission: Permission.Admin,
|
||||
})
|
||||
|
||||
const field = await metadataService.createProjectField(projectId, req)
|
||||
return c.json(toFieldInfo(field))
|
||||
})
|
||||
.get('/projects/:projectId/fields', async (c) => {
|
||||
const projectId = c.req.param('projectId')
|
||||
const user = c.get('user')
|
||||
|
||||
await authzService.hasPermission({
|
||||
projectId,
|
||||
user,
|
||||
permission: Permission.Read,
|
||||
})
|
||||
|
||||
const fields = await metadataService.listProjectFields(user.id, projectId)
|
||||
return c.json(fields.map((f) => toFieldInfo(f.field, f.visible)))
|
||||
})
|
||||
.patch(
|
||||
'/projects/:projectId/fields/order',
|
||||
zValidator('json', updateProjectFieldsOrderRequestSchema),
|
||||
async (c) => {
|
||||
const projectId = c.req.param('projectId')
|
||||
const req = c.req.valid('json')
|
||||
const user = c.get('user')
|
||||
|
||||
await authzService.hasPermission({
|
||||
projectId,
|
||||
user,
|
||||
permission: Permission.Admin,
|
||||
})
|
||||
|
||||
await metadataService.updateProjectFieldsOrder(user.id, projectId, req)
|
||||
return new Response(null, { status: 204 })
|
||||
},
|
||||
)
|
||||
.put(
|
||||
'/projects/:projectId/fields/:fieldId',
|
||||
zValidator('json', updateFieldRequestSchema),
|
||||
async (c) => {
|
||||
const projectId = c.req.param('projectId')
|
||||
const fieldId = c.req.param('fieldId')
|
||||
const req = c.req.valid('json')
|
||||
const user = c.get('user')
|
||||
|
||||
await authzService.hasPermission({
|
||||
projectId,
|
||||
user,
|
||||
permission: Permission.Admin,
|
||||
})
|
||||
|
||||
const field = await metadataService.updateProjectField(projectId, fieldId, req)
|
||||
return c.json(toFieldInfo(field))
|
||||
},
|
||||
)
|
||||
.delete('/projects/:projectId/fields/:fieldId', async (c) => {
|
||||
const projectId = c.req.param('projectId')
|
||||
const fieldId = c.req.param('fieldId')
|
||||
const user = c.get('user')
|
||||
|
||||
await authzService.hasPermission({
|
||||
projectId,
|
||||
user,
|
||||
permission: Permission.Admin,
|
||||
})
|
||||
|
||||
await metadataService.deleteProjectField(projectId, fieldId)
|
||||
return new Response(null, { status: 204 })
|
||||
})
|
||||
|
||||
.patch(
|
||||
'/teams/:teamId/files/:fileId/metadata',
|
||||
zValidator('json', z.array(updateAssetMetadataRequestSchema)),
|
||||
async (c) => {
|
||||
const teamId = c.req.param('teamId')
|
||||
const fileId = c.req.param('fileId') // Actually maps to assetId
|
||||
const req = c.req.valid('json')
|
||||
const user = c.get('user')
|
||||
|
||||
await authzService.hasPermission({
|
||||
teamId,
|
||||
assetId: fileId,
|
||||
user,
|
||||
permission: Permission.Edit,
|
||||
})
|
||||
|
||||
await metadataService.updateAssetMetadata(fileId, req)
|
||||
return new Response(null, { status: 204 })
|
||||
},
|
||||
)
|
||||
|
||||
export default route
|
||||
@@ -0,0 +1,35 @@
|
||||
import type { Prisma } from '@/generated/prisma/client'
|
||||
import { auth } from '@/services/auth/auth'
|
||||
import { prisma } from '@/db'
|
||||
import { createMiddleware } from 'hono/factory'
|
||||
|
||||
type User = Prisma.UserGetPayload<Record<string, never>>
|
||||
|
||||
export const authMiddleware = createMiddleware<{
|
||||
Variables: {
|
||||
user: User
|
||||
}
|
||||
}>(async (c, next) => {
|
||||
const session = await auth.api.getSession({
|
||||
headers: c.req.raw.headers,
|
||||
})
|
||||
|
||||
if (!session) {
|
||||
return c.json({ error: 'Unauthorized' }, 401)
|
||||
}
|
||||
|
||||
try {
|
||||
const user = await prisma.user.findUnique({
|
||||
where: { id: session.user.id },
|
||||
})
|
||||
|
||||
if (!user) {
|
||||
return c.json({ error: 'User not found' }, 401)
|
||||
}
|
||||
|
||||
c.set('user', user)
|
||||
await next()
|
||||
} catch {
|
||||
return c.json({ error: 'Authentication failed' }, 401)
|
||||
}
|
||||
})
|
||||
@@ -0,0 +1,78 @@
|
||||
import { describe, expect, it, vi, beforeEach, afterEach } from 'vitest'
|
||||
import { Hono } from 'hono'
|
||||
import notificationRoute from './notification'
|
||||
import { notificationService } from '@/services/notification/notification'
|
||||
import { authMiddleware } from '@/api/middleware/auth'
|
||||
|
||||
vi.mock('@/services/authz/authz', () => ({
|
||||
authzService: {
|
||||
hasPermission: vi.fn(),
|
||||
},
|
||||
Permission: {
|
||||
Read: 'Read',
|
||||
Edit: 'Edit',
|
||||
Admin: 'Admin',
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('@/api/middleware/auth', () => ({
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
authMiddleware: async (c: any, next: any) => {
|
||||
c.set('user', { id: 'user1', name: 'Test User' })
|
||||
await next()
|
||||
},
|
||||
}))
|
||||
|
||||
describe('notification api', () => {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
let mockList: any
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
let mockMarkRead: any
|
||||
|
||||
beforeEach(() => {
|
||||
mockList = vi.fn()
|
||||
mockMarkRead = vi.fn()
|
||||
vi.spyOn(notificationService, 'list').mockImplementation(mockList)
|
||||
vi.spyOn(notificationService, 'markRead').mockImplementation(mockMarkRead)
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
it('GET /teams/:teamId/notifications', async () => {
|
||||
mockList.mockResolvedValue({
|
||||
data: [{ id: 'n1', type: 'comment_created' }],
|
||||
pageInfo: { total: 1, cursor: 'abc' },
|
||||
})
|
||||
|
||||
const app = new Hono().use('*', authMiddleware).route('/', notificationRoute)
|
||||
const res = await app.request('/teams/t1/notifications?unreadOnly=true&pageSize=10')
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const json = await res.json()
|
||||
expect(json.data).toHaveLength(1)
|
||||
expect(json.pageInfo.total).toBe(1)
|
||||
expect(json.pageInfo.cursor).toBe('abc')
|
||||
|
||||
expect(mockList).toHaveBeenCalledWith('t1', 'user1', {
|
||||
unreadOnly: true,
|
||||
after: undefined,
|
||||
pageSize: 10,
|
||||
})
|
||||
})
|
||||
|
||||
it('POST /teams/:teamId/notifications/read', async () => {
|
||||
mockMarkRead.mockResolvedValue(undefined)
|
||||
|
||||
const app = new Hono().use('*', authMiddleware).route('/', notificationRoute)
|
||||
const res = await app.request('/teams/t1/notifications/read', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ notificationId: 'n1' }),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(204)
|
||||
expect(mockMarkRead).toHaveBeenCalledWith('t1', 'user1', 'n1')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,64 @@
|
||||
import { zValidator } from '@hono/zod-validator'
|
||||
import { Hono } from 'hono'
|
||||
import { notificationService } from '@/services/notification/notification'
|
||||
import { authzService, Permission } from '@/services/authz/authz'
|
||||
import {
|
||||
listNotificationsRequestSchema,
|
||||
markNotificationReadRequestSchema,
|
||||
} from '@/dtos/notification'
|
||||
import type { Prisma } from '@/generated/prisma/client'
|
||||
|
||||
type User = Prisma.UserGetPayload<Record<string, never>>
|
||||
|
||||
const route = new Hono<{ Variables: { user: User } }>()
|
||||
.get(
|
||||
'/teams/:teamId/notifications',
|
||||
zValidator('query', listNotificationsRequestSchema),
|
||||
async (c) => {
|
||||
const teamId = c.req.param('teamId')
|
||||
const req = c.req.valid('query')
|
||||
const user = c.get('user')
|
||||
|
||||
await authzService.hasPermission({
|
||||
teamId,
|
||||
user,
|
||||
permission: Permission.Read,
|
||||
})
|
||||
|
||||
const res = await notificationService.list(teamId, user.id, {
|
||||
unreadOnly: req.unreadOnly,
|
||||
after: req.after,
|
||||
pageSize: req.pageSize,
|
||||
})
|
||||
|
||||
// To align with Go struct casing, map pageInfo to page_info
|
||||
return c.json({
|
||||
data: res.data,
|
||||
pageInfo: {
|
||||
total: res.pageInfo.total,
|
||||
cursor: res.pageInfo.cursor,
|
||||
},
|
||||
})
|
||||
},
|
||||
)
|
||||
.post(
|
||||
'/teams/:teamId/notifications/read',
|
||||
zValidator('json', markNotificationReadRequestSchema),
|
||||
async (c) => {
|
||||
const teamId = c.req.param('teamId')
|
||||
const req = c.req.valid('json')
|
||||
const user = c.get('user')
|
||||
|
||||
await authzService.hasPermission({
|
||||
teamId,
|
||||
user,
|
||||
permission: Permission.Read,
|
||||
})
|
||||
|
||||
await notificationService.markRead(teamId, user.id, req.notificationId)
|
||||
|
||||
return new Response(null, { status: 204 })
|
||||
},
|
||||
)
|
||||
|
||||
export default route
|
||||
@@ -0,0 +1,178 @@
|
||||
import { describe, expect, it, vi, beforeEach, afterEach } from 'vitest'
|
||||
import { Hono } from 'hono'
|
||||
import projectRoute from './project'
|
||||
import { authMiddleware } from '@/api/middleware/auth'
|
||||
import { projectService } from '@/services/project/project'
|
||||
import { assetService } from '@/services/asset/asset'
|
||||
import { authzService } from '@/services/authz/authz'
|
||||
|
||||
vi.mock('@/services/authz/authz', () => ({
|
||||
authzService: {
|
||||
hasPermission: vi.fn(),
|
||||
},
|
||||
Permission: {
|
||||
Read: 'Read',
|
||||
Edit: 'Edit',
|
||||
Admin: 'Admin',
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('@/api/middleware/auth', () => ({
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
authMiddleware: async (c: any, next: any) => {
|
||||
c.set('user', { id: 'user1', name: 'Test User' })
|
||||
await next()
|
||||
},
|
||||
}))
|
||||
|
||||
describe('project api', () => {
|
||||
let mockListProjects: any // eslint-disable-line @typescript-eslint/no-explicit-any
|
||||
let mockCreateProject: any // eslint-disable-line @typescript-eslint/no-explicit-any
|
||||
let mockUpdateProject: any // eslint-disable-line @typescript-eslint/no-explicit-any
|
||||
let mockGetProject: any // eslint-disable-line @typescript-eslint/no-explicit-any
|
||||
let mockGetProjectTeam: any // eslint-disable-line @typescript-eslint/no-explicit-any
|
||||
let mockListProjectMembers: any // eslint-disable-line @typescript-eslint/no-explicit-any
|
||||
let mockReparentAssets: any // eslint-disable-line @typescript-eslint/no-explicit-any
|
||||
|
||||
beforeEach(() => {
|
||||
mockListProjects = vi.fn()
|
||||
mockCreateProject = vi.fn()
|
||||
mockUpdateProject = vi.fn()
|
||||
mockGetProject = vi.fn()
|
||||
mockGetProjectTeam = vi.fn()
|
||||
mockListProjectMembers = vi.fn()
|
||||
mockReparentAssets = vi.fn()
|
||||
vi.mocked(authzService.hasPermission).mockClear()
|
||||
|
||||
vi.spyOn(projectService, 'listProjects').mockImplementation(mockListProjects)
|
||||
vi.spyOn(projectService, 'createProject').mockImplementation(mockCreateProject)
|
||||
vi.spyOn(projectService, 'updateProject').mockImplementation(mockUpdateProject)
|
||||
vi.spyOn(projectService, 'getProject').mockImplementation(mockGetProject)
|
||||
vi.spyOn(projectService, 'getProjectTeam').mockImplementation(mockGetProjectTeam)
|
||||
vi.spyOn(projectService, 'listProjectMembers').mockImplementation(mockListProjectMembers)
|
||||
vi.spyOn(assetService, 'reparentAssets').mockImplementation(mockReparentAssets)
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
it('GET /teams/:teamId/projects', async () => {
|
||||
mockListProjects.mockResolvedValue({
|
||||
data: [{ id: 'foo', name: 'foo.png', rootFolder: 'uid' }],
|
||||
pageInfo: { total: 100, cursor: 'abc' },
|
||||
})
|
||||
|
||||
const app = new Hono().use('*', authMiddleware).route('/', projectRoute)
|
||||
const res = await app.request('/teams/t/projects?page_size=10')
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const json = await res.json()
|
||||
expect(json.data).toHaveLength(1)
|
||||
expect(json.pageInfo.total).toBe(100)
|
||||
expect(json.data[0].id).toBe('foo')
|
||||
})
|
||||
|
||||
it('POST /teams/:teamId/projects', async () => {
|
||||
mockCreateProject.mockResolvedValue({
|
||||
id: 'foo',
|
||||
name: 'foo.png',
|
||||
coverImage: 'http://s3/bucket/key',
|
||||
})
|
||||
|
||||
const app = new Hono().use('*', authMiddleware).route('/', projectRoute)
|
||||
const res = await app.request('/teams/t/projects', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ name: 'foo.png', coverImageKey: 'key' }),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const json = await res.json()
|
||||
expect(json.id).toBe('foo')
|
||||
expect(json.name).toBe('foo.png')
|
||||
expect(json.coverImage).toBe('http://s3/bucket/key')
|
||||
})
|
||||
|
||||
it('PUT /teams/:teamId/projects/:projectId', async () => {
|
||||
mockUpdateProject.mockResolvedValue({
|
||||
id: 'foo',
|
||||
name: 'updated',
|
||||
coverImage: 'http://s3/bucket/key',
|
||||
})
|
||||
|
||||
const app = new Hono().use('*', authMiddleware).route('/', projectRoute)
|
||||
const res = await app.request('/teams/t/projects/foo', {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ name: 'updated' }),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const json = await res.json()
|
||||
expect(json.name).toBe('updated')
|
||||
})
|
||||
|
||||
it('GET /projects/:projectId', async () => {
|
||||
mockGetProject.mockResolvedValue({
|
||||
id: 'p',
|
||||
name: 'foo.png',
|
||||
rootFolder: 'root_folder_id',
|
||||
})
|
||||
|
||||
const app = new Hono().use('*', authMiddleware).route('/', projectRoute)
|
||||
const res = await app.request('/projects/p')
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const json = await res.json()
|
||||
expect(json.rootFolder).toBe('root_folder_id')
|
||||
expect(json.id).toBe('p')
|
||||
})
|
||||
|
||||
it('GET /projects/:projectId/team', async () => {
|
||||
mockGetProjectTeam.mockResolvedValue('teamId')
|
||||
|
||||
const app = new Hono().use('*', authMiddleware).route('/', projectRoute)
|
||||
const res = await app.request('/projects/p/team')
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const json = await res.json()
|
||||
expect(json.teamId).toBe('teamId')
|
||||
})
|
||||
|
||||
it('POST /projects/:projectId/reparent', async () => {
|
||||
mockReparentAssets.mockResolvedValue(undefined)
|
||||
|
||||
const app = new Hono().use('*', authMiddleware).route('/', projectRoute)
|
||||
const res = await app.request('/projects/p/reparent', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
newParentId: 'new_parent_id',
|
||||
assetIds: ['asset_1', 'asset_2'],
|
||||
}),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(204)
|
||||
expect(authzService.hasPermission).toHaveBeenNthCalledWith(1, {
|
||||
assetId: 'new_parent_id',
|
||||
user: { id: 'user1', name: 'Test User' },
|
||||
permission: 'Edit',
|
||||
})
|
||||
expect(authzService.hasPermission).toHaveBeenNthCalledWith(2, {
|
||||
assetId: 'asset_1',
|
||||
user: { id: 'user1', name: 'Test User' },
|
||||
permission: 'Edit',
|
||||
})
|
||||
expect(authzService.hasPermission).toHaveBeenNthCalledWith(3, {
|
||||
assetId: 'asset_2',
|
||||
user: { id: 'user1', name: 'Test User' },
|
||||
permission: 'Edit',
|
||||
})
|
||||
expect(mockReparentAssets).toHaveBeenCalledWith({
|
||||
newParentId: 'new_parent_id',
|
||||
assetIds: ['asset_1', 'asset_2'],
|
||||
creatorId: 'user1',
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,192 @@
|
||||
import { Hono } from 'hono'
|
||||
import { zValidator } from '@hono/zod-validator'
|
||||
import { authzService, Permission } from '@/services/authz/authz'
|
||||
import { projectService } from '@/services/project/project'
|
||||
import { assetService } from '@/services/asset/asset'
|
||||
import { reparentAssetsRequestSchema } from '@/dtos/asset'
|
||||
import {
|
||||
createProjectRequestSchema,
|
||||
updateProjectRequestSchema,
|
||||
listProjectsRequestSchema,
|
||||
recentlyDeletedRequestSchema,
|
||||
} from '@/dtos/project'
|
||||
import { listMembersQuerySchema } from '@/dtos/team'
|
||||
import type { Prisma } from '@/generated/prisma/client'
|
||||
|
||||
type User = Prisma.UserGetPayload<Record<string, never>>
|
||||
|
||||
const route = new Hono<{ Variables: { user: User } }>()
|
||||
.post('/teams/:teamId/projects', zValidator('json', createProjectRequestSchema), async (c) => {
|
||||
const teamId = c.req.param('teamId')
|
||||
const user = c.get('user')
|
||||
const req = c.req.valid('json')
|
||||
|
||||
await authzService.hasPermission({
|
||||
teamId,
|
||||
user,
|
||||
permission: Permission.Edit,
|
||||
})
|
||||
|
||||
const newProject = await projectService.createProject(user, {
|
||||
teamId,
|
||||
...req,
|
||||
})
|
||||
|
||||
return c.json(newProject)
|
||||
})
|
||||
.put(
|
||||
'/teams/:teamId/projects/:projectId',
|
||||
zValidator('json', updateProjectRequestSchema),
|
||||
async (c) => {
|
||||
const projectId = c.req.param('projectId')
|
||||
const user = c.get('user')
|
||||
const req = c.req.valid('json')
|
||||
|
||||
await authzService.hasPermission({
|
||||
projectId,
|
||||
user,
|
||||
permission: Permission.Edit,
|
||||
})
|
||||
|
||||
const updatedProject = await projectService.updateProject({
|
||||
projectId,
|
||||
...req,
|
||||
})
|
||||
|
||||
return c.json(updatedProject)
|
||||
},
|
||||
)
|
||||
.get(
|
||||
'/projects/:projectId/recently-deleted',
|
||||
zValidator('query', recentlyDeletedRequestSchema),
|
||||
async (c) => {
|
||||
const projectId = c.req.param('projectId')
|
||||
const user = c.get('user')
|
||||
|
||||
await authzService.hasPermission({
|
||||
projectId,
|
||||
user,
|
||||
permission: Permission.Read,
|
||||
})
|
||||
|
||||
// STUB: AssetService is not migrated yet.
|
||||
return c.json({ data: [], pageInfo: {} })
|
||||
},
|
||||
)
|
||||
.get('/teams/:teamId/projects', zValidator('query', listProjectsRequestSchema), async (c) => {
|
||||
const teamId = c.req.param('teamId')
|
||||
const user = c.get('user')
|
||||
const req = c.req.valid('query')
|
||||
|
||||
await authzService.hasPermission({
|
||||
teamId,
|
||||
user,
|
||||
permission: Permission.Read,
|
||||
})
|
||||
|
||||
const res = await projectService.listProjects({
|
||||
teamId,
|
||||
userId: user.id,
|
||||
sortBy: req.sortBy,
|
||||
sortDirection: req.sortDirection,
|
||||
pagination: req,
|
||||
})
|
||||
|
||||
return c.json({
|
||||
data: res.data,
|
||||
pageInfo: {
|
||||
total: res.pageInfo.total,
|
||||
cursor: res.pageInfo.cursor,
|
||||
},
|
||||
})
|
||||
})
|
||||
.get('/projects/:projectId', async (c) => {
|
||||
const projectId = c.req.param('projectId')
|
||||
const user = c.get('user')
|
||||
|
||||
await authzService.hasPermission({
|
||||
projectId,
|
||||
user,
|
||||
permission: Permission.Read,
|
||||
})
|
||||
|
||||
const p = await projectService.getProject(projectId)
|
||||
return c.json(p)
|
||||
})
|
||||
.get('/projects/:projectId/team', async (c) => {
|
||||
const projectId = c.req.param('projectId')
|
||||
const user = c.get('user')
|
||||
|
||||
await authzService.hasPermission({
|
||||
projectId,
|
||||
user,
|
||||
permission: Permission.Read,
|
||||
})
|
||||
|
||||
const teamId = await projectService.getProjectTeam(projectId)
|
||||
return c.json({ teamId })
|
||||
})
|
||||
.get('/projects/:projectId/members', zValidator('query', listMembersQuerySchema), async (c) => {
|
||||
const projectId = c.req.param('projectId')
|
||||
const user = c.get('user')
|
||||
const { includeAgents } = c.req.valid('query')
|
||||
|
||||
await authzService.hasPermission({
|
||||
projectId,
|
||||
user,
|
||||
permission: Permission.Read,
|
||||
})
|
||||
|
||||
const members = await projectService.listProjectMembers({
|
||||
projectId,
|
||||
includeAgents: includeAgents,
|
||||
})
|
||||
return c.json(members)
|
||||
})
|
||||
.get('/projects/:projectId/bots', async (c) => {
|
||||
const projectId = c.req.param('projectId')
|
||||
const user = c.get('user')
|
||||
|
||||
await authzService.hasPermission({
|
||||
projectId,
|
||||
user,
|
||||
permission: Permission.Read,
|
||||
})
|
||||
|
||||
// STUB: AgentService is not migrated yet.
|
||||
return c.json([])
|
||||
})
|
||||
|
||||
.post(
|
||||
'/projects/:projectId/reparent',
|
||||
zValidator('json', reparentAssetsRequestSchema),
|
||||
async (c) => {
|
||||
const user = c.get('user')
|
||||
const req = c.req.valid('json')
|
||||
|
||||
// Check Edit permission on target folder/project
|
||||
await authzService.hasPermission({
|
||||
assetId: req.newParentId,
|
||||
user,
|
||||
permission: Permission.Edit,
|
||||
})
|
||||
|
||||
// Check Edit permission on all source assets
|
||||
for (const assetId of req.assetIds) {
|
||||
await authzService.hasPermission({
|
||||
assetId,
|
||||
user,
|
||||
permission: Permission.Edit,
|
||||
})
|
||||
}
|
||||
|
||||
await assetService.reparentAssets({
|
||||
...req,
|
||||
creatorId: user.id,
|
||||
})
|
||||
|
||||
return c.body(null, 204)
|
||||
},
|
||||
)
|
||||
|
||||
export default route
|
||||
@@ -0,0 +1,158 @@
|
||||
import { describe, expect, it, vi, beforeEach, afterEach } from 'vitest'
|
||||
import { Hono } from 'hono'
|
||||
import providerRoute from './provider'
|
||||
import { authMiddleware } from '@/api/middleware/auth'
|
||||
import { providerService } from '@/services/provider/provider'
|
||||
import { authzService } from '@/services/authz/authz'
|
||||
|
||||
vi.mock('@/services/authz/authz', () => ({
|
||||
authzService: {
|
||||
hasPermission: vi.fn(),
|
||||
},
|
||||
Permission: {
|
||||
Read: 'Read',
|
||||
Edit: 'Edit',
|
||||
Admin: 'Admin',
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('@/api/middleware/auth', () => ({
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
authMiddleware: async (c: any, next: any) => {
|
||||
c.set('user', { id: 'user1', name: 'Test User' })
|
||||
await next()
|
||||
},
|
||||
}))
|
||||
|
||||
describe('provider api', () => {
|
||||
const app = new Hono().use('*', authMiddleware).route('/', providerRoute)
|
||||
|
||||
let mockListByTeam: any // eslint-disable-line @typescript-eslint/no-explicit-any
|
||||
let mockCreate: any // eslint-disable-line @typescript-eslint/no-explicit-any
|
||||
let mockUpdate: any // eslint-disable-line @typescript-eslint/no-explicit-any
|
||||
let mockDelete: any // eslint-disable-line @typescript-eslint/no-explicit-any
|
||||
|
||||
beforeEach(() => {
|
||||
mockListByTeam = vi.spyOn(providerService, 'listByTeam')
|
||||
mockCreate = vi.spyOn(providerService, 'create')
|
||||
mockUpdate = vi.spyOn(providerService, 'update')
|
||||
mockDelete = vi.spyOn(providerService, 'delete')
|
||||
|
||||
// Default to admin permission granted
|
||||
vi.mocked(authzService.hasPermission).mockResolvedValue(undefined)
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
it('GET /teams/:teamId/providers returns providers', async () => {
|
||||
mockListByTeam.mockResolvedValue([{ id: 'p1', name: 'openai', config: {} }])
|
||||
|
||||
const res = await app.request('/teams/t1/providers')
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const data = await res.json()
|
||||
expect(data).toHaveLength(1)
|
||||
expect(data[0].id).toBe('p1')
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
teamId: 't1',
|
||||
permission: 'Admin',
|
||||
}),
|
||||
)
|
||||
})
|
||||
|
||||
it('GET /teams/:teamId/providers/:id/models returns models', async () => {
|
||||
const mockListModelsByProvider = vi.spyOn(providerService, 'listModelsByProvider')
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
mockListModelsByProvider.mockResolvedValue([{ modelId: 'm1', name: 'model1' } as any])
|
||||
|
||||
const res = await app.request('/teams/t1/providers/p1/models')
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const data = await res.json()
|
||||
expect(data).toHaveLength(1)
|
||||
expect(data[0].modelId).toBe('m1')
|
||||
expect(mockListModelsByProvider).toHaveBeenCalledWith('t1', 'p1')
|
||||
})
|
||||
|
||||
it('POST /teams/:teamId/providers creates provider', async () => {
|
||||
const config = {
|
||||
baseUrl: 'https://api.openai.com/v1',
|
||||
api: 'openai-completions',
|
||||
}
|
||||
const models = [
|
||||
{
|
||||
modelId: 'gpt-4',
|
||||
name: 'GPT-4',
|
||||
config: {
|
||||
api: 'openai-completions',
|
||||
reasoning: false,
|
||||
input: ['text'],
|
||||
contextWindow: 128000,
|
||||
maxTokens: 4096,
|
||||
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
|
||||
},
|
||||
},
|
||||
]
|
||||
mockCreate.mockResolvedValue({ id: 'p1', name: 'openai', config, models })
|
||||
|
||||
const res = await app.request('/teams/t1/providers', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ name: 'openai', config, models }),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const data = await res.json()
|
||||
expect(data.name).toBe('openai')
|
||||
expect(mockCreate).toHaveBeenCalledWith('t1', 'openai', config, models)
|
||||
})
|
||||
|
||||
it('PUT /teams/:teamId/providers/:id updates provider', async () => {
|
||||
const config = {
|
||||
baseUrl: 'https://new-url.com',
|
||||
api: 'openai-completions',
|
||||
}
|
||||
const models = [
|
||||
{
|
||||
modelId: 'gpt-4',
|
||||
name: 'GPT-4',
|
||||
config: {
|
||||
api: 'openai-completions',
|
||||
reasoning: false,
|
||||
input: ['text'],
|
||||
contextWindow: 128000,
|
||||
maxTokens: 4096,
|
||||
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
|
||||
},
|
||||
},
|
||||
]
|
||||
mockUpdate.mockResolvedValue({ id: 'p1', name: 'openai', config, models })
|
||||
|
||||
const res = await app.request('/teams/t1/providers/p1', {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ config, models }),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const data = await res.json()
|
||||
expect(data.config.baseUrl).toBe('https://new-url.com')
|
||||
expect(mockUpdate).toHaveBeenCalledWith('t1', 'p1', config, models)
|
||||
})
|
||||
|
||||
it('DELETE /teams/:teamId/providers/:id deletes provider', async () => {
|
||||
mockDelete.mockResolvedValue({ id: 'p1' })
|
||||
|
||||
const res = await app.request('/teams/t1/providers/p1', {
|
||||
method: 'DELETE',
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const data = await res.json()
|
||||
expect(data.success).toBe(true)
|
||||
expect(mockDelete).toHaveBeenCalledWith('t1', 'p1')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,90 @@
|
||||
import { zValidator } from '@hono/zod-validator'
|
||||
import { Hono } from 'hono'
|
||||
import { authzService, Permission } from '@/services/authz/authz'
|
||||
import { providerService } from '@/services/provider/provider'
|
||||
import { createProviderRequestSchema, updateProviderRequestSchema } from '@/dtos/provider'
|
||||
import type { Prisma } from '@/generated/prisma/client'
|
||||
|
||||
type User = Prisma.UserGetPayload<Record<string, never>>
|
||||
|
||||
const route = new Hono<{ Variables: { user: User } }>()
|
||||
.get('/teams/:teamId/providers', async (c) => {
|
||||
const teamId = c.req.param('teamId')
|
||||
const user = c.get('user')
|
||||
|
||||
await authzService.hasPermission({
|
||||
teamId,
|
||||
user,
|
||||
permission: Permission.Admin,
|
||||
})
|
||||
|
||||
const providers = await providerService.listByTeam(teamId)
|
||||
return c.json(providers)
|
||||
})
|
||||
|
||||
.get('/teams/:teamId/providers/:id/models', async (c) => {
|
||||
const teamId = c.req.param('teamId')
|
||||
const id = c.req.param('id')
|
||||
const user = c.get('user')
|
||||
|
||||
await authzService.hasPermission({
|
||||
teamId,
|
||||
user,
|
||||
permission: Permission.Admin,
|
||||
})
|
||||
|
||||
const models = await providerService.listModelsByProvider(teamId, id)
|
||||
return c.json(models)
|
||||
})
|
||||
|
||||
.post('/teams/:teamId/providers', zValidator('json', createProviderRequestSchema), async (c) => {
|
||||
const teamId = c.req.param('teamId')
|
||||
const user = c.get('user')
|
||||
const { name, config, models } = c.req.valid('json')
|
||||
|
||||
await authzService.hasPermission({
|
||||
teamId,
|
||||
user,
|
||||
permission: Permission.Admin,
|
||||
})
|
||||
|
||||
const provider = await providerService.create(teamId, name, config, models)
|
||||
return c.json(provider)
|
||||
})
|
||||
|
||||
.put(
|
||||
'/teams/:teamId/providers/:id',
|
||||
zValidator('json', updateProviderRequestSchema),
|
||||
async (c) => {
|
||||
const teamId = c.req.param('teamId')
|
||||
const id = c.req.param('id')
|
||||
const user = c.get('user')
|
||||
const { config, models } = c.req.valid('json')
|
||||
|
||||
await authzService.hasPermission({
|
||||
teamId,
|
||||
user,
|
||||
permission: Permission.Admin,
|
||||
})
|
||||
|
||||
const provider = await providerService.update(teamId, id, config, models)
|
||||
return c.json(provider)
|
||||
},
|
||||
)
|
||||
|
||||
.delete('/teams/:teamId/providers/:id', async (c) => {
|
||||
const teamId = c.req.param('teamId')
|
||||
const id = c.req.param('id')
|
||||
const user = c.get('user')
|
||||
|
||||
await authzService.hasPermission({
|
||||
teamId,
|
||||
user,
|
||||
permission: Permission.Admin,
|
||||
})
|
||||
|
||||
await providerService.delete(teamId, id)
|
||||
return c.json({ success: true })
|
||||
})
|
||||
|
||||
export default route
|
||||
@@ -0,0 +1,36 @@
|
||||
import { Hono } from 'hono'
|
||||
import { inviteService } from '@/services/invite/invite'
|
||||
import { InviteInfo } from '@/dtos/invite'
|
||||
|
||||
const app = new Hono()
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const mapToInviteInfo = (inv: any): InviteInfo => {
|
||||
const info: InviteInfo = {
|
||||
code: inv.code,
|
||||
role: inv.role!,
|
||||
teamId: inv.teamId,
|
||||
teamName: inv.team.name,
|
||||
inviterName: inv.inviter.name,
|
||||
isUsed: inv.used,
|
||||
}
|
||||
|
||||
if (inv.project) {
|
||||
info.projectId = inv.project.id
|
||||
info.projectName = inv.project.name
|
||||
}
|
||||
|
||||
return info
|
||||
}
|
||||
|
||||
const route = app.get('/invite/:code', async (c) => {
|
||||
const code = c.req.param('code')
|
||||
try {
|
||||
const inv = await inviteService.getInvite(code)
|
||||
return c.json(mapToInviteInfo(inv))
|
||||
} catch {
|
||||
return c.json({ error: 'Not found' }, 404)
|
||||
}
|
||||
})
|
||||
|
||||
export default route
|
||||
@@ -0,0 +1,250 @@
|
||||
import { Hono } from 'hono'
|
||||
import { zValidator } from '@hono/zod-validator'
|
||||
import { shareService } from '@/services/share/share'
|
||||
import { assetService } from '@/services/asset/asset'
|
||||
import { paginationParamsSchema } from '@/dtos/pagination'
|
||||
import { z } from 'zod'
|
||||
import { metadataService } from '@/services/metadata/metadata'
|
||||
import { FieldInfo } from '@/dtos/metadata'
|
||||
import type { Prisma as PrismaType } from '@/generated/prisma/client'
|
||||
import { auth } from '@/services/auth/auth'
|
||||
import { prisma } from '@/db'
|
||||
import { createCommentRequestSchema } from '@/dtos/asset'
|
||||
import { notificationService } from '@/services/notification/notification'
|
||||
|
||||
const app = new Hono()
|
||||
|
||||
function toFieldInfo(
|
||||
f: PrismaType.MetadataFieldGetPayload<Record<string, never>>,
|
||||
visible = false,
|
||||
): FieldInfo {
|
||||
return {
|
||||
id: f.key,
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
config: f.config as any,
|
||||
scope: f.scope ?? '',
|
||||
readOnly: f.readOnly,
|
||||
visible: visible,
|
||||
description: f.description,
|
||||
aiAutofill: f.aiAutofill,
|
||||
}
|
||||
}
|
||||
|
||||
const sharedChildrenRequestSchema = paginationParamsSchema.extend({
|
||||
assetType: z.string().optional(),
|
||||
})
|
||||
|
||||
const route = app
|
||||
.get('/shares/:shareId/info', async (c) => {
|
||||
const shareId = c.req.param('shareId')
|
||||
try {
|
||||
const shareLink = await shareService.getShareLink(shareId)
|
||||
return c.json({
|
||||
id: shareLink.id,
|
||||
name: shareLink.name,
|
||||
expireAt: shareLink.expireAt,
|
||||
isDisabled: shareLink.isDisabled,
|
||||
isExpired: shareLink.isExpired,
|
||||
hasPassword: shareLink.hasPassword,
|
||||
rootFolderId: shareLink.rootFolderId,
|
||||
projectId: shareLink.projectId,
|
||||
})
|
||||
} catch (err) {
|
||||
return c.json({ error: (err as Error).message }, 404)
|
||||
}
|
||||
})
|
||||
.get('/shares/:shareId/fields', async (c) => {
|
||||
const shareId = c.req.param('shareId')
|
||||
const password = c.req.header('x-share-password')
|
||||
|
||||
try {
|
||||
const shareLink = await shareService.getShareLink(shareId)
|
||||
await shareService.verifyPublicAccess(shareLink.rootFolderId, password)
|
||||
|
||||
const fields = await metadataService.listProjectFields(null, shareLink.projectId)
|
||||
const fieldVisibility = (shareLink.fieldVisibility || {}) as Record<string, boolean>
|
||||
|
||||
return c.json(
|
||||
fields
|
||||
.filter((f) => fieldVisibility[f.field.key])
|
||||
.map((f) => toFieldInfo(f.field, f.visible)),
|
||||
)
|
||||
} catch (err) {
|
||||
const msg = (err as Error).message
|
||||
if (msg === 'Invalid password for share link') {
|
||||
return c.json({ error: 'Unauthorized' }, 401)
|
||||
}
|
||||
if (msg === 'Share link has expired' || msg === 'Share link is disabled') {
|
||||
return c.json({ error: msg }, 403)
|
||||
}
|
||||
return c.json({ error: msg }, 500)
|
||||
}
|
||||
})
|
||||
.get(
|
||||
'/shares/:shareId/folders/:folderId/children',
|
||||
zValidator('query', sharedChildrenRequestSchema),
|
||||
async (c) => {
|
||||
const folderId = c.req.param('folderId')
|
||||
const password = c.req.header('x-share-password')
|
||||
const req = c.req.valid('query')
|
||||
|
||||
try {
|
||||
const shareLink = await shareService.verifyPublicAccess(folderId, password)
|
||||
|
||||
let sort: string | undefined
|
||||
let order: string | undefined
|
||||
|
||||
if (shareLink.defaultSortOrder) {
|
||||
const parts = shareLink.defaultSortOrder.split(':')
|
||||
sort = parts[0]
|
||||
order = parts[1]
|
||||
}
|
||||
|
||||
const res = await assetService.listChildren({
|
||||
...req,
|
||||
assetId: folderId,
|
||||
assetType: req.assetType || 'file',
|
||||
sort,
|
||||
order,
|
||||
})
|
||||
|
||||
return c.json(res)
|
||||
} catch (err) {
|
||||
const msg = (err as Error).message
|
||||
if (msg === 'Invalid password for share link') {
|
||||
return c.json({ error: 'Unauthorized' }, 401)
|
||||
}
|
||||
if (msg === 'Share link has expired' || msg === 'Share link is disabled') {
|
||||
return c.json({ error: msg }, 403)
|
||||
}
|
||||
return c.json({ error: msg }, 500)
|
||||
}
|
||||
},
|
||||
)
|
||||
.get('/shares/:shareId/files/:fileId', async (c) => {
|
||||
const fileId = c.req.param('fileId')
|
||||
const password = c.req.header('x-share-password')
|
||||
|
||||
try {
|
||||
await shareService.verifyPublicAccess(fileId, password)
|
||||
|
||||
const asset = await assetService.getAsset({ assetId: fileId })
|
||||
return c.json(asset)
|
||||
} catch (err) {
|
||||
const msg = (err as Error).message
|
||||
if (msg === 'Invalid password for share link') {
|
||||
return c.json({ error: 'Unauthorized' }, 401)
|
||||
}
|
||||
if (msg === 'Share link has expired' || msg === 'Share link is disabled') {
|
||||
return c.json({ error: msg }, 403)
|
||||
}
|
||||
return c.json({ error: msg }, 500)
|
||||
}
|
||||
})
|
||||
.get(
|
||||
'/shares/:shareId/files/:fileId/comments',
|
||||
zValidator('query', paginationParamsSchema),
|
||||
async (c) => {
|
||||
const fileId = c.req.param('fileId')
|
||||
const password = c.req.header('x-share-password')
|
||||
const req = c.req.valid('query')
|
||||
|
||||
try {
|
||||
await shareService.verifyPublicAccess(fileId, password)
|
||||
|
||||
const targetFileId = await assetService.resolveTargetAssetId(fileId)
|
||||
const res = await assetService.listComments(targetFileId, req)
|
||||
return c.json(res)
|
||||
} catch (err) {
|
||||
const msg = (err as Error).message
|
||||
if (msg === 'Invalid password for share link') {
|
||||
return c.json({ error: 'Unauthorized' }, 401)
|
||||
}
|
||||
if (msg === 'Share link has expired' || msg === 'Share link is disabled') {
|
||||
return c.json({ error: msg }, 403)
|
||||
}
|
||||
return c.json({ error: msg }, 500)
|
||||
}
|
||||
},
|
||||
)
|
||||
.post(
|
||||
'/shares/:shareId/files/:fileId/comments',
|
||||
zValidator('json', createCommentRequestSchema.omit({ assetId: true, userId: true })),
|
||||
async (c) => {
|
||||
const shareId = c.req.param('shareId')
|
||||
const fileId = c.req.param('fileId')
|
||||
const password = c.req.header('x-share-password')
|
||||
const guestUserId = c.req.header('x-guest-user-id')
|
||||
const req = c.req.valid('json')
|
||||
|
||||
try {
|
||||
const shareLink = await shareService.getShareLink(shareId)
|
||||
await shareService.verifyPublicAccess(fileId, password)
|
||||
|
||||
const targetFileId = await assetService.resolveTargetAssetId(fileId)
|
||||
|
||||
const project = await prisma.project.findUnique({
|
||||
where: { id: shareLink.projectId },
|
||||
select: { teamId: true },
|
||||
})
|
||||
|
||||
if (!project) {
|
||||
throw new Error('Project not found')
|
||||
}
|
||||
|
||||
// Identify user
|
||||
let userId: string | null = null
|
||||
const session = await auth.api.getSession({
|
||||
headers: c.req.raw.headers,
|
||||
})
|
||||
|
||||
if (session?.user) {
|
||||
userId = session.user.id
|
||||
} else if (guestUserId) {
|
||||
const guestUser = await prisma.user.findUnique({
|
||||
where: { id: guestUserId },
|
||||
})
|
||||
if (guestUser) {
|
||||
userId = guestUser.id
|
||||
}
|
||||
}
|
||||
|
||||
if (!userId) {
|
||||
return c.json({ error: 'Unauthorized' }, 401)
|
||||
}
|
||||
|
||||
const comment = await assetService.createComment({
|
||||
assetId: targetFileId,
|
||||
userId: userId,
|
||||
replyToId: req.replyToId,
|
||||
message: req.message,
|
||||
annotations: req.annotations,
|
||||
second: req.second,
|
||||
attachmentIds: req.attachmentIds,
|
||||
})
|
||||
|
||||
const notifType = req.replyToId ? 'reply_created' : 'comment_created'
|
||||
|
||||
notificationService.create({
|
||||
type: notifType,
|
||||
teamId: project.teamId,
|
||||
creatorId: userId,
|
||||
assetId: targetFileId,
|
||||
commentMessage: req.message,
|
||||
})
|
||||
|
||||
return c.json(comment, 201)
|
||||
} catch (err) {
|
||||
const msg = (err as Error).message
|
||||
if (msg === 'Invalid password for share link') {
|
||||
return c.json({ error: 'Unauthorized' }, 401)
|
||||
}
|
||||
if (msg === 'Share link has expired' || msg === 'Share link is disabled') {
|
||||
return c.json({ error: msg }, 403)
|
||||
}
|
||||
return c.json({ error: msg }, 500)
|
||||
}
|
||||
},
|
||||
)
|
||||
|
||||
export default route
|
||||
@@ -0,0 +1,54 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { s3Service } from '@/services/s3/s3'
|
||||
import route from './s3'
|
||||
import { Hono } from 'hono'
|
||||
|
||||
describe('S3 API', () => {
|
||||
const app = new Hono().route('/files', route)
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
it('GET /files/:bucket/:key sets Content-Type', async () => {
|
||||
const mockHead = vi.spyOn(s3Service, 'headObject').mockResolvedValue({
|
||||
key: 'test.webp',
|
||||
size: 100,
|
||||
lastModified: new Date(),
|
||||
contentType: 'image/webp',
|
||||
eTag: '"test"',
|
||||
})
|
||||
const mockGet = vi.spyOn(s3Service, 'getObject').mockResolvedValue({ buffer: Buffer.from('test'), contentType: 'image/webp' })
|
||||
|
||||
const res = await app.request('/files/b1/test.webp')
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(res.headers.get('Content-Type')).toBe('image/webp')
|
||||
expect(mockHead).toHaveBeenCalledWith('b1', 'test.webp')
|
||||
expect(mockGet).toHaveBeenCalledWith('b1', 'test.webp')
|
||||
})
|
||||
|
||||
it('GET /files/:bucket/:key handles missing contentType', async () => {
|
||||
vi.spyOn(s3Service, 'headObject').mockResolvedValue({
|
||||
key: 'test',
|
||||
size: 100,
|
||||
lastModified: new Date(),
|
||||
contentType: 'application/octet-stream',
|
||||
eTag: '"test"',
|
||||
})
|
||||
vi.spyOn(s3Service, 'getObject').mockResolvedValue({ buffer: Buffer.from('test'), contentType: 'application/octet-stream' })
|
||||
|
||||
const res = await app.request('/files/b1/test')
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(res.headers.get('Content-Type')).toBe('application/octet-stream')
|
||||
})
|
||||
|
||||
it('GET /files/:bucket/:key returns 404 if not found', async () => {
|
||||
vi.spyOn(s3Service, 'headObject').mockRejectedValue(new Error('NoSuchKey'))
|
||||
|
||||
const res = await app.request('/files/b1/not-found')
|
||||
|
||||
expect(res.status).toBe(404)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,43 @@
|
||||
import { Hono } from 'hono'
|
||||
import { s3Service } from '@/services/s3/s3'
|
||||
|
||||
const route = new Hono()
|
||||
.get('/:bucket/:key{.+}', async (c) => {
|
||||
const bucket = c.req.param('bucket')
|
||||
const key = c.req.param('key')
|
||||
|
||||
try {
|
||||
const info = await s3Service.headObject(bucket, key)
|
||||
const { buffer: data, contentType } = await s3Service.getObject(bucket, key)
|
||||
|
||||
if (contentType) {
|
||||
c.header('Content-Type', contentType)
|
||||
} else if (info.contentType) {
|
||||
c.header('Content-Type', info.contentType)
|
||||
}
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
return c.body(data as any)
|
||||
} catch (e: unknown) {
|
||||
const error = e as Error
|
||||
if (error.message?.includes('NoSuchKey')) {
|
||||
return c.text('Not Found', 404)
|
||||
}
|
||||
return c.text(error.message || 'Internal Server Error', 500)
|
||||
}
|
||||
})
|
||||
.put('/:bucket/:key{.+}', async (c) => {
|
||||
const bucket = c.req.param('bucket')
|
||||
const key = c.req.param('key')
|
||||
const body = await c.req.arrayBuffer()
|
||||
|
||||
try {
|
||||
await s3Service.putObject(bucket, key, Buffer.from(body), body.byteLength)
|
||||
return c.text('OK')
|
||||
} catch (e: unknown) {
|
||||
const error = e as Error
|
||||
return c.text(error.message || 'Internal Server Error', 500)
|
||||
}
|
||||
})
|
||||
|
||||
export default route
|
||||
@@ -0,0 +1,202 @@
|
||||
import { describe, expect, test, vi, beforeEach } from 'vitest'
|
||||
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'
|
||||
|
||||
vi.mock('@/api/middleware/auth', () => ({
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
authMiddleware: async (c: any, next: any) => {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
c.set('user', { id: 'user1', name: 'Test User' } as any)
|
||||
await next()
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('@/services/authz/authz', () => ({
|
||||
authzService: {
|
||||
hasPermission: vi.fn().mockResolvedValue(undefined),
|
||||
},
|
||||
Permission: {
|
||||
Read: 'read',
|
||||
Edit: 'edit',
|
||||
Admin: 'admin',
|
||||
},
|
||||
}))
|
||||
|
||||
describe('Share API', () => {
|
||||
const app = new Hono()
|
||||
.route('/', publicShareRoute)
|
||||
.use('*', authMiddleware)
|
||||
.route('/', shareRoute)
|
||||
|
||||
beforeEach(() => {
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
// Public Routes
|
||||
describe('GET /shares/:shareId/info', () => {
|
||||
test('Success', async () => {
|
||||
vi.spyOn(shareService, 'getShareLink').mockResolvedValue({
|
||||
id: 'share1',
|
||||
name: 'Public Share',
|
||||
isDisabled: false,
|
||||
isExpired: false,
|
||||
hasPassword: true,
|
||||
rootFolderId: 'folder1',
|
||||
projectId: 'project1',
|
||||
createdAt: new Date().toISOString(),
|
||||
updatedAt: new Date().toISOString(),
|
||||
})
|
||||
|
||||
const res = await app.request('/shares/share1/info', {
|
||||
method: 'GET',
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const body = await res.json()
|
||||
expect(body.name).toBe('Public Share')
|
||||
expect(body.hasPassword).toBe(true)
|
||||
})
|
||||
})
|
||||
|
||||
describe('GET /shares/:shareId/folders/:folderId/children', () => {
|
||||
test('Success', async () => {
|
||||
vi.spyOn(shareService, 'verifyPublicAccess').mockResolvedValue({
|
||||
id: 'share1',
|
||||
name: 'My Share',
|
||||
isDisabled: false,
|
||||
rootFolderId: 'folder1',
|
||||
projectId: 'project1',
|
||||
password: null,
|
||||
expireAt: null,
|
||||
defaultSortOrder: 'name:asc',
|
||||
fieldVisibility: null,
|
||||
createdAt: new Date(),
|
||||
updatedAt: new Date(),
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
} as any)
|
||||
vi.spyOn(assetService, 'listChildren').mockResolvedValue({
|
||||
data: [],
|
||||
pageInfo: { total: 0, cursor: undefined },
|
||||
})
|
||||
|
||||
const res = await app.request('/shares/share1/folders/folder1/children?assetType=file', {
|
||||
method: 'GET',
|
||||
headers: { 'x-share-password': 'pass' },
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(shareService.verifyPublicAccess).toHaveBeenCalledWith('folder1', 'pass')
|
||||
expect(assetService.listChildren).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
assetId: 'folder1',
|
||||
assetType: 'file',
|
||||
sort: 'name',
|
||||
order: 'asc',
|
||||
}),
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
// Protected Routes
|
||||
describe('POST /teams/:teamId/projects/:projectId/shares', () => {
|
||||
test('Success', async () => {
|
||||
vi.spyOn(shareService, 'createShareLink').mockResolvedValue({
|
||||
id: 'share1',
|
||||
name: 'test-share',
|
||||
isDisabled: false,
|
||||
rootFolderId: 'root1',
|
||||
projectId: 'project1',
|
||||
isExpired: false,
|
||||
hasPassword: false,
|
||||
createdAt: new Date().toISOString(),
|
||||
updatedAt: new Date().toISOString(),
|
||||
})
|
||||
|
||||
const res = await app.request('/teams/team1/projects/project1/shares', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ name: 'My Share' }),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const body = await res.json()
|
||||
expect(body.id).toBe('share1')
|
||||
expect(shareService.createShareLink).toHaveBeenCalledWith('project1', { name: 'My Share' })
|
||||
})
|
||||
})
|
||||
|
||||
describe('GET /teams/:teamId/projects/:projectId/shares', () => {
|
||||
test('Success', async () => {
|
||||
vi.spyOn(shareService, 'listProjectShareLinks').mockResolvedValue({
|
||||
data: [],
|
||||
pageInfo: { total: 0, cursor: undefined },
|
||||
})
|
||||
|
||||
const res = await app.request('/teams/team1/projects/project1/shares', {
|
||||
method: 'GET',
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(shareService.listProjectShareLinks).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
projectId: 'project1',
|
||||
}),
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
describe('GET /teams/:teamId/shares/:shareId', () => {
|
||||
test('Success', async () => {
|
||||
vi.spyOn(shareService, 'getShareLink').mockResolvedValue({
|
||||
id: 'share1',
|
||||
name: 'test-share',
|
||||
isDisabled: false,
|
||||
rootFolderId: 'root1',
|
||||
projectId: 'project1',
|
||||
isExpired: false,
|
||||
hasPassword: false,
|
||||
createdAt: new Date().toISOString(),
|
||||
updatedAt: new Date().toISOString(),
|
||||
})
|
||||
|
||||
const res = await app.request('/teams/team1/shares/share1', {
|
||||
method: 'GET',
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(shareService.getShareLink).toHaveBeenCalledWith('share1')
|
||||
})
|
||||
})
|
||||
|
||||
describe('POST /teams/:teamId/shares/:shareId/assets', () => {
|
||||
test('Success', async () => {
|
||||
vi.spyOn(shareService, 'getShareLink').mockResolvedValue({
|
||||
id: 'share1',
|
||||
name: 'test-share',
|
||||
isDisabled: false,
|
||||
rootFolderId: 'root1',
|
||||
projectId: 'project1',
|
||||
isExpired: false,
|
||||
hasPassword: false,
|
||||
createdAt: new Date().toISOString(),
|
||||
updatedAt: new Date().toISOString(),
|
||||
})
|
||||
vi.spyOn(shareService, 'addAssetToShare').mockResolvedValue(1)
|
||||
|
||||
const res = await app.request('/teams/team1/shares/share1/assets', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ assetIds: ['asset1'] }),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const body = await res.json()
|
||||
expect(body.addedCount).toBe(1)
|
||||
expect(shareService.addAssetToShare).toHaveBeenCalledWith('share1', { assetIds: ['asset1'] })
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,147 @@
|
||||
import { Hono } from 'hono'
|
||||
import { zValidator } from '@hono/zod-validator'
|
||||
import { authzService, Permission } from '@/services/authz/authz'
|
||||
import { shareService } from '@/services/share/share'
|
||||
import {
|
||||
createShareLinkRequestSchema,
|
||||
updateShareLinkRequestSchema,
|
||||
listShareLinksRequestSchema,
|
||||
addAssetToShareRequestSchema,
|
||||
} from '@/dtos/share'
|
||||
import type { Prisma } from '@/generated/prisma/client'
|
||||
|
||||
type User = Prisma.UserGetPayload<Record<string, never>>
|
||||
|
||||
const route = new Hono<{ Variables: { user: User } }>()
|
||||
.post(
|
||||
'/teams/:teamId/projects/:projectId/shares',
|
||||
zValidator('json', createShareLinkRequestSchema),
|
||||
async (c) => {
|
||||
const projectId = c.req.param('projectId')
|
||||
const user = c.get('user')
|
||||
const req = c.req.valid('json')
|
||||
|
||||
await authzService.hasPermission({
|
||||
projectId,
|
||||
user,
|
||||
permission: Permission.Edit,
|
||||
})
|
||||
|
||||
const shareLink = await shareService.createShareLink(projectId, req)
|
||||
return c.json(shareLink)
|
||||
},
|
||||
)
|
||||
.get(
|
||||
'/teams/:teamId/projects/:projectId/shares',
|
||||
zValidator('query', listShareLinksRequestSchema),
|
||||
async (c) => {
|
||||
const projectId = c.req.param('projectId')
|
||||
const user = c.get('user')
|
||||
const req = c.req.valid('query')
|
||||
|
||||
await authzService.hasPermission({
|
||||
projectId,
|
||||
user,
|
||||
permission: Permission.Read,
|
||||
})
|
||||
|
||||
const res = await shareService.listProjectShareLinks({
|
||||
...req,
|
||||
projectId,
|
||||
})
|
||||
|
||||
return c.json(res)
|
||||
},
|
||||
)
|
||||
.get('/teams/:teamId/shares/:shareId', async (c) => {
|
||||
const shareId = c.req.param('shareId')
|
||||
const user = c.get('user')
|
||||
|
||||
const shareLink = await shareService.getShareLink(shareId)
|
||||
|
||||
await authzService.hasPermission({
|
||||
projectId: shareLink.projectId,
|
||||
user,
|
||||
permission: Permission.Read,
|
||||
})
|
||||
|
||||
return c.json(shareLink)
|
||||
})
|
||||
.put(
|
||||
'/teams/:teamId/shares/:shareId',
|
||||
zValidator('json', updateShareLinkRequestSchema),
|
||||
async (c) => {
|
||||
const shareId = c.req.param('shareId')
|
||||
const user = c.get('user')
|
||||
const req = c.req.valid('json')
|
||||
|
||||
const shareLink = await shareService.getShareLink(shareId)
|
||||
await authzService.hasPermission({
|
||||
projectId: shareLink.projectId,
|
||||
user,
|
||||
permission: Permission.Edit,
|
||||
})
|
||||
|
||||
const updated = await shareService.updateShareLink(shareId, req)
|
||||
return c.json(updated)
|
||||
},
|
||||
)
|
||||
.delete('/teams/:teamId/shares/:shareId', async (c) => {
|
||||
const shareId = c.req.param('shareId')
|
||||
const user = c.get('user')
|
||||
|
||||
const shareLink = await shareService.getShareLink(shareId)
|
||||
await authzService.hasPermission({
|
||||
projectId: shareLink.projectId,
|
||||
user,
|
||||
permission: Permission.Edit,
|
||||
})
|
||||
|
||||
await shareService.deleteShareLink(shareId)
|
||||
return c.body(null, 204)
|
||||
})
|
||||
.post(
|
||||
'/teams/:teamId/shares/:shareId/assets',
|
||||
zValidator('json', addAssetToShareRequestSchema),
|
||||
async (c) => {
|
||||
const shareId = c.req.param('shareId')
|
||||
const user = c.get('user')
|
||||
const req = c.req.valid('json')
|
||||
|
||||
const shareLink = await shareService.getShareLink(shareId)
|
||||
await authzService.hasPermission({
|
||||
projectId: shareLink.projectId,
|
||||
user,
|
||||
permission: Permission.Edit,
|
||||
})
|
||||
|
||||
// Also check if user has read permission on the source assets
|
||||
for (const assetId of req.assetIds) {
|
||||
await authzService.hasPermission({
|
||||
assetId,
|
||||
user,
|
||||
permission: Permission.Read,
|
||||
})
|
||||
}
|
||||
|
||||
const addedCount = await shareService.addAssetToShare(shareId, req)
|
||||
return c.json({ addedCount })
|
||||
},
|
||||
)
|
||||
.delete('/teams/:teamId/shares/:shareId/assets/:assetId', async (c) => {
|
||||
const shareId = c.req.param('shareId')
|
||||
const assetId = c.req.param('assetId') // symlink asset id
|
||||
const user = c.get('user')
|
||||
|
||||
const shareLink = await shareService.getShareLink(shareId)
|
||||
await authzService.hasPermission({
|
||||
projectId: shareLink.projectId,
|
||||
user,
|
||||
permission: Permission.Edit,
|
||||
})
|
||||
|
||||
await shareService.removeAssetFromShare(shareId, assetId)
|
||||
return c.body(null, 204)
|
||||
})
|
||||
|
||||
export default route
|
||||
@@ -0,0 +1,170 @@
|
||||
import { describe, expect, test, vi, beforeEach } from 'vitest'
|
||||
import { Hono } from 'hono'
|
||||
import skillRoute from './skill'
|
||||
import { skillService } from '@/services/skill/skill'
|
||||
import { authMiddleware } from '@/api/middleware/auth'
|
||||
import { authzService } from '@/services/authz/authz'
|
||||
|
||||
vi.mock('@/api/middleware/auth', () => ({
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
authMiddleware: async (c: any, next: any) => {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
c.set('user', { id: 'user1', name: 'Test User' } as any)
|
||||
await next()
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('@/services/authz/authz', () => ({
|
||||
authzService: {
|
||||
hasPermission: vi.fn(),
|
||||
},
|
||||
Permission: {
|
||||
Read: 'read',
|
||||
Edit: 'edit',
|
||||
Admin: 'admin',
|
||||
},
|
||||
}))
|
||||
|
||||
describe('Skill API', () => {
|
||||
const app = new Hono().use('*', authMiddleware).route('/', skillRoute)
|
||||
|
||||
beforeEach(() => {
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
describe('GET /teams/:teamId/skills', () => {
|
||||
test('Success', async () => {
|
||||
const mockSkills = [
|
||||
{
|
||||
id: 'skill1',
|
||||
name: 'Skill 1',
|
||||
description: 'Desc 1',
|
||||
config: null,
|
||||
assetId: 'asset1',
|
||||
hash: 'hash1',
|
||||
createdAt: new Date().toISOString(),
|
||||
updatedAt: new Date().toISOString(),
|
||||
},
|
||||
]
|
||||
vi.spyOn(skillService, 'listSkills').mockResolvedValue(mockSkills)
|
||||
|
||||
const res = await app.request('/teams/team1/skills', {
|
||||
method: 'GET',
|
||||
headers: { Authorization: 'Bearer test' },
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(await res.json()).toEqual({ skills: mockSkills })
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ permission: 'admin' }),
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
describe('POST /teams/:teamId/skills', () => {
|
||||
test('Success with assetId', async () => {
|
||||
const mockSkill = {
|
||||
id: 'skill1',
|
||||
name: 'Skill 1',
|
||||
description: 'Desc 1',
|
||||
config: null,
|
||||
assetId: 'asset1',
|
||||
hash: 'hash1',
|
||||
createdAt: new Date().toISOString(),
|
||||
updatedAt: new Date().toISOString(),
|
||||
}
|
||||
vi.spyOn(skillService, 'upsertSkill').mockResolvedValue(mockSkill)
|
||||
|
||||
const res = await app.request('/teams/team1/skills', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json', Authorization: 'Bearer test' },
|
||||
body: JSON.stringify({ assetId: 'asset1' }),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(await res.json()).toEqual(mockSkill)
|
||||
expect(skillService.upsertSkill).toHaveBeenCalledWith('team1', { assetId: 'asset1' })
|
||||
})
|
||||
|
||||
test('Success with githubUrl', async () => {
|
||||
const mockSkill = {
|
||||
id: 'skill1',
|
||||
name: 'Skill 1',
|
||||
description: 'Desc 1',
|
||||
config: null,
|
||||
assetId: 'asset1',
|
||||
hash: 'hash1',
|
||||
createdAt: new Date().toISOString(),
|
||||
updatedAt: new Date().toISOString(),
|
||||
}
|
||||
vi.spyOn(skillService, 'upsertSkill').mockResolvedValue(mockSkill)
|
||||
|
||||
const res = await app.request('/teams/team1/skills', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json', Authorization: 'Bearer test' },
|
||||
body: JSON.stringify({ githubUrl: 'https://github.com/test/repo' }),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(await res.json()).toEqual(mockSkill)
|
||||
expect(skillService.upsertSkill).toHaveBeenCalledWith('team1', {
|
||||
githubUrl: 'https://github.com/test/repo',
|
||||
})
|
||||
})
|
||||
|
||||
test('Forbidden without Admin permission', async () => {
|
||||
vi.spyOn(authzService, 'hasPermission').mockRejectedValueOnce(new Error('Forbidden'))
|
||||
|
||||
const res = await app.request('/teams/team1/skills', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json', Authorization: 'Bearer test' },
|
||||
body: JSON.stringify({ assetId: 'asset1' }),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(500) // The app uses a global error handler that returns 500 for thrown errors in these tests
|
||||
})
|
||||
})
|
||||
|
||||
describe('DELETE /teams/:teamId/skills/:id', () => {
|
||||
test('Success', async () => {
|
||||
vi.spyOn(skillService, 'deleteSkill').mockResolvedValue(undefined)
|
||||
|
||||
const res = await app.request('/teams/team1/skills/skill1', {
|
||||
method: 'DELETE',
|
||||
headers: { Authorization: 'Bearer test' },
|
||||
})
|
||||
|
||||
expect(res.status).toBe(204)
|
||||
expect(skillService.deleteSkill).toHaveBeenCalledWith('skill1')
|
||||
})
|
||||
})
|
||||
|
||||
describe('PATCH /teams/:teamId/skills/:id/config', () => {
|
||||
test('Success', async () => {
|
||||
const mockConfig = {
|
||||
environmentVariables: [{ name: 'TEST_VAR', default: 'test_val' }],
|
||||
}
|
||||
const mockSkill = {
|
||||
id: 'skill1',
|
||||
name: 'Skill 1',
|
||||
description: 'Desc 1',
|
||||
config: mockConfig,
|
||||
assetId: 'asset1',
|
||||
hash: 'hash1',
|
||||
createdAt: new Date().toISOString(),
|
||||
updatedAt: new Date().toISOString(),
|
||||
}
|
||||
vi.spyOn(skillService, 'updateSkillConfig').mockResolvedValue(mockSkill)
|
||||
|
||||
const res = await app.request('/teams/team1/skills/skill1/config', {
|
||||
method: 'PATCH',
|
||||
headers: { 'Content-Type': 'application/json', Authorization: 'Bearer test' },
|
||||
body: JSON.stringify({ config: mockConfig }),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(await res.json()).toEqual(mockSkill)
|
||||
expect(skillService.updateSkillConfig).toHaveBeenCalledWith('skill1', mockConfig)
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,79 @@
|
||||
import { Hono } from 'hono'
|
||||
import { zValidator } from '@hono/zod-validator'
|
||||
import { authzService, Permission } from '@/services/authz/authz'
|
||||
import { skillService } from '@/services/skill/skill'
|
||||
import { upsertSkillRequestSchema, updateSkillConfigRequestSchema } from '@/dtos/skill'
|
||||
import type { Prisma } from '@/generated/prisma/client'
|
||||
|
||||
type User = Prisma.UserGetPayload<Record<string, never>>
|
||||
|
||||
const route = new Hono<{ Variables: { user: User } }>()
|
||||
.get('/teams/:teamId/skills', async (c) => {
|
||||
const user = c.get('user')
|
||||
const teamId = c.req.param('teamId')
|
||||
|
||||
await authzService.hasPermission({
|
||||
teamId,
|
||||
user,
|
||||
permission: Permission.Admin,
|
||||
})
|
||||
|
||||
const skills = await skillService.listSkills(teamId)
|
||||
return c.json({ skills })
|
||||
})
|
||||
.post('/teams/:teamId/skills', zValidator('json', upsertSkillRequestSchema), async (c) => {
|
||||
const user = c.get('user')
|
||||
const teamId = c.req.param('teamId')
|
||||
const req = c.req.valid('json')
|
||||
|
||||
await authzService.hasPermission({
|
||||
teamId,
|
||||
user,
|
||||
permission: Permission.Admin,
|
||||
})
|
||||
|
||||
try {
|
||||
const skill = await skillService.upsertSkill(teamId, req)
|
||||
return c.json(skill)
|
||||
} catch (err: unknown) {
|
||||
if (err instanceof Error && err.name === 'ConflictError') {
|
||||
return c.json({ error: err.message }, 409)
|
||||
}
|
||||
throw err
|
||||
}
|
||||
})
|
||||
.delete('/teams/:teamId/skills/:id', async (c) => {
|
||||
const user = c.get('user')
|
||||
const teamId = c.req.param('teamId')
|
||||
const id = c.req.param('id')
|
||||
|
||||
await authzService.hasPermission({
|
||||
teamId,
|
||||
user,
|
||||
permission: Permission.Admin,
|
||||
})
|
||||
|
||||
await skillService.deleteSkill(id)
|
||||
return new Response(null, { status: 204 })
|
||||
})
|
||||
.patch(
|
||||
'/teams/:teamId/skills/:id/config',
|
||||
zValidator('json', updateSkillConfigRequestSchema),
|
||||
async (c) => {
|
||||
const user = c.get('user')
|
||||
const teamId = c.req.param('teamId')
|
||||
const id = c.req.param('id')
|
||||
const req = c.req.valid('json')
|
||||
|
||||
await authzService.hasPermission({
|
||||
teamId,
|
||||
user,
|
||||
permission: Permission.Admin,
|
||||
})
|
||||
|
||||
const skill = await skillService.updateSkillConfig(id, req.config)
|
||||
return c.json(skill)
|
||||
},
|
||||
)
|
||||
|
||||
export default route
|
||||
@@ -0,0 +1,187 @@
|
||||
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'
|
||||
|
||||
vi.mock('@/services/authz/authz', () => ({
|
||||
authzService: {
|
||||
hasPermission: vi.fn(),
|
||||
},
|
||||
Permission: {
|
||||
Read: 'Read',
|
||||
Edit: 'Edit',
|
||||
Admin: 'Admin',
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('@/api/middleware/auth', () => ({
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
authMiddleware: async (c: any, next: any) => {
|
||||
c.set('user', { id: 'user1', name: 'Test User' })
|
||||
await next()
|
||||
},
|
||||
}))
|
||||
|
||||
describe('team api', () => {
|
||||
const app = new Hono().use('*', authMiddleware).route('/', teamRoute)
|
||||
let mockCreateTeam: any // eslint-disable-line @typescript-eslint/no-explicit-any
|
||||
let mockGetUserTeams: any // eslint-disable-line @typescript-eslint/no-explicit-any
|
||||
let mockJoinTeam: any // eslint-disable-line @typescript-eslint/no-explicit-any
|
||||
let mockGetMe: any // eslint-disable-line @typescript-eslint/no-explicit-any
|
||||
let mockGetTeamMembers: any // eslint-disable-line @typescript-eslint/no-explicit-any
|
||||
let mockGetSettings: any // eslint-disable-line @typescript-eslint/no-explicit-any
|
||||
let mockUpdateSettings: any // eslint-disable-line @typescript-eslint/no-explicit-any
|
||||
let mockListUserMetadata: any // eslint-disable-line @typescript-eslint/no-explicit-any
|
||||
let mockUpsertUserMetadata: any // eslint-disable-line @typescript-eslint/no-explicit-any
|
||||
let mockCreateNotification: any // eslint-disable-line @typescript-eslint/no-explicit-any
|
||||
|
||||
beforeEach(() => {
|
||||
mockCreateTeam = vi.spyOn(teamService, 'createTeam')
|
||||
mockGetUserTeams = vi.spyOn(teamService, 'getUserTeams')
|
||||
mockJoinTeam = vi.spyOn(teamService, 'joinTeam')
|
||||
mockGetMe = vi.spyOn(teamService, 'getMe')
|
||||
mockGetTeamMembers = vi.spyOn(teamService, 'getTeamMembers')
|
||||
mockGetSettings = vi.spyOn(teamService, 'getSettings')
|
||||
mockUpdateSettings = vi.spyOn(teamService, 'updateSettings')
|
||||
mockListUserMetadata = vi.spyOn(userMetadataService, 'listMetadata')
|
||||
mockUpsertUserMetadata = vi.spyOn(userMetadataService, 'upsertMetadata')
|
||||
mockCreateNotification = vi.spyOn(notificationService, 'create').mockResolvedValue()
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
it('POST /teams creates a new team', async () => {
|
||||
const mockTeam = { id: 't1', name: 'New Team', updatedAt: new Date() }
|
||||
mockCreateTeam.mockResolvedValue(mockTeam)
|
||||
|
||||
const res = await app.request('/teams', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
name: 'New Team',
|
||||
}),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const data = await res.json()
|
||||
expect(data.id).toBe('t1')
|
||||
expect(mockCreateTeam).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ id: 'user1' }),
|
||||
expect.objectContaining({ name: 'New Team' }),
|
||||
)
|
||||
})
|
||||
|
||||
it('GET /teams returns user teams', async () => {
|
||||
mockGetUserTeams.mockResolvedValue({
|
||||
data: [{ id: 't1', name: 'User Team', updatedAt: new Date() }],
|
||||
pageInfo: { total: 1, cursor: undefined },
|
||||
})
|
||||
|
||||
const res = await app.request('/teams?first=10')
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const data = await res.json()
|
||||
expect(data.data[0].id).toBe('t1')
|
||||
expect(mockGetUserTeams).toHaveBeenCalledWith(expect.objectContaining({ userId: 'user1' }))
|
||||
})
|
||||
|
||||
it('POST /teams/:teamId/members joins team and sends notification', async () => {
|
||||
mockJoinTeam.mockResolvedValue(undefined)
|
||||
|
||||
const res = await app.request('/teams/t1/members', { method: 'POST' })
|
||||
|
||||
expect(res.status).toBe(204)
|
||||
expect(mockJoinTeam).toHaveBeenCalledWith({ teamId: 't1', userId: 'user1' })
|
||||
expect(mockCreateNotification).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
type: 'new_user_join_team',
|
||||
teamId: 't1',
|
||||
userId: 'user1',
|
||||
}),
|
||||
)
|
||||
})
|
||||
|
||||
it('GET /teams/:teamId/me returns user role in team', async () => {
|
||||
mockGetMe.mockResolvedValue({ id: 'user1', name: 'Test User', role: 'owner' })
|
||||
|
||||
const res = await app.request('/teams/t1/me')
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const data = await res.json()
|
||||
expect(data.role).toBe('owner')
|
||||
expect(mockGetMe).toHaveBeenCalledWith({ teamId: 't1', user: expect.any(Object) })
|
||||
})
|
||||
|
||||
it('GET /teams/:teamId/members returns members', async () => {
|
||||
mockGetTeamMembers.mockResolvedValue([{ id: 'user1', name: 'Test User', role: 'owner' }])
|
||||
|
||||
const res = await app.request('/teams/t1/members')
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const data = await res.json()
|
||||
expect(data).toHaveLength(1)
|
||||
expect(mockGetTeamMembers).toHaveBeenCalledWith({ teamId: 't1', includeAgents: false })
|
||||
})
|
||||
|
||||
it('GET /teams/:teamId/settings returns settings', async () => {
|
||||
mockGetSettings.mockResolvedValue({ someKey: 'some_value' })
|
||||
|
||||
const res = await app.request('/teams/t1/settings')
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const data = await res.json()
|
||||
expect(data.someKey).toBe('some_value')
|
||||
expect(mockGetSettings).toHaveBeenCalledWith('t1')
|
||||
})
|
||||
|
||||
it('PATCH /teams/:teamId/settings updates settings', async () => {
|
||||
mockUpdateSettings.mockResolvedValue({ someKey: 'new_value' })
|
||||
|
||||
const res = await app.request('/teams/t1/settings', {
|
||||
method: 'PATCH',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ key: 'someKey', value: 'new_value' }),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const data = await res.json()
|
||||
expect(data.someKey).toBe('new_value')
|
||||
expect(mockUpdateSettings).toHaveBeenCalledWith('t1', 'someKey', 'new_value')
|
||||
})
|
||||
|
||||
it('GET /teams/:teamId/user-metadata returns all metadata for the user in the team', async () => {
|
||||
mockListUserMetadata.mockResolvedValue([
|
||||
{ key: 'key1', value: 'value1' },
|
||||
{ key: 'key2', value: 'value2' },
|
||||
])
|
||||
|
||||
const res = await app.request('/teams/t1/user-metadata')
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const data = await res.json()
|
||||
expect(data).toHaveLength(2)
|
||||
expect(data[0].key).toBe('key1')
|
||||
expect(mockListUserMetadata).toHaveBeenCalledWith('user1', 't1')
|
||||
})
|
||||
|
||||
it('PUT /teams/:teamId/user-metadata/:key upserts the metadata', async () => {
|
||||
mockUpsertUserMetadata.mockResolvedValue({ key: 'key1', value: 'value1' })
|
||||
|
||||
const res = await app.request('/teams/t1/user-metadata/key1', {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ value: 'value1' }),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const data = await res.json()
|
||||
expect(data.key).toBe('key1')
|
||||
expect(data.value).toBe('value1')
|
||||
expect(mockUpsertUserMetadata).toHaveBeenCalledWith('user1', 't1', 'key1', 'value1')
|
||||
})
|
||||
})
|
||||
+160
@@ -0,0 +1,160 @@
|
||||
import { Hono } from 'hono'
|
||||
import { zValidator } from '@hono/zod-validator'
|
||||
import { authzService, Permission } 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 {
|
||||
createTeamRequestSchema,
|
||||
getUserTeamsRequestSchema,
|
||||
updateTeamSettingsRequestSchema,
|
||||
listMembersQuerySchema,
|
||||
} from '@/dtos/team'
|
||||
import { updateUserMetadataRequestSchema } from '@/dtos/user-metadata'
|
||||
import type { Prisma } from '@/generated/prisma/client'
|
||||
|
||||
type User = Prisma.UserGetPayload<Record<string, never>>
|
||||
|
||||
const route = new Hono<{ Variables: { user: User } }>()
|
||||
.post('/teams', zValidator('json', createTeamRequestSchema), async (c) => {
|
||||
const user = c.get('user')
|
||||
const req = c.req.valid('json')
|
||||
|
||||
const newTeam = await teamService.createTeam(user, req)
|
||||
return c.json(newTeam)
|
||||
})
|
||||
.get('/teams', zValidator('query', getUserTeamsRequestSchema), async (c) => {
|
||||
const user = c.get('user')
|
||||
const pg = c.req.valid('query')
|
||||
|
||||
const teams = await teamService.getUserTeams({
|
||||
userId: user.id,
|
||||
pagination: pg,
|
||||
})
|
||||
|
||||
return c.json({
|
||||
data: teams.data,
|
||||
pageInfo: {
|
||||
total: teams.pageInfo.total,
|
||||
cursor: teams.pageInfo.cursor,
|
||||
},
|
||||
})
|
||||
})
|
||||
.post('/teams/:teamId/members', async (c) => {
|
||||
const user = c.get('user')
|
||||
const teamId = c.req.param('teamId')
|
||||
|
||||
await teamService.joinTeam({
|
||||
teamId,
|
||||
userId: user.id,
|
||||
})
|
||||
|
||||
await notificationService.create({
|
||||
type: NotificationType.new_user_join_team,
|
||||
teamId,
|
||||
userId: user.id,
|
||||
})
|
||||
|
||||
return new Response(null, { status: 204 })
|
||||
})
|
||||
.get('/teams/:teamId/me', async (c) => {
|
||||
const user = c.get('user')
|
||||
const teamId = c.req.param('teamId')
|
||||
|
||||
await authzService.hasPermission({
|
||||
teamId,
|
||||
user,
|
||||
permission: Permission.Read,
|
||||
})
|
||||
|
||||
const me = await teamService.getMe({
|
||||
teamId,
|
||||
user,
|
||||
})
|
||||
|
||||
return c.json(me)
|
||||
})
|
||||
.get('/teams/:teamId/members', zValidator('query', listMembersQuerySchema), async (c) => {
|
||||
const user = c.get('user')
|
||||
const teamId = c.req.param('teamId')
|
||||
const { includeAgents } = c.req.valid('query')
|
||||
|
||||
await authzService.hasPermission({
|
||||
teamId,
|
||||
user,
|
||||
permission: Permission.Read,
|
||||
})
|
||||
|
||||
const members = await teamService.getTeamMembers({
|
||||
teamId,
|
||||
includeAgents: includeAgents,
|
||||
})
|
||||
|
||||
return c.json(members)
|
||||
})
|
||||
.get('/teams/:teamId/settings', async (c) => {
|
||||
const user = c.get('user')
|
||||
const teamId = c.req.param('teamId')
|
||||
|
||||
await authzService.hasPermission({
|
||||
teamId,
|
||||
user,
|
||||
permission: Permission.Read,
|
||||
})
|
||||
|
||||
const settings = await teamService.getSettings(teamId)
|
||||
return c.json(settings)
|
||||
})
|
||||
.patch(
|
||||
'/teams/:teamId/settings',
|
||||
zValidator('json', updateTeamSettingsRequestSchema),
|
||||
async (c) => {
|
||||
const user = c.get('user')
|
||||
const teamId = c.req.param('teamId')
|
||||
const req = c.req.valid('json')
|
||||
|
||||
await authzService.hasPermission({
|
||||
teamId,
|
||||
user,
|
||||
permission: Permission.Admin,
|
||||
})
|
||||
|
||||
const settings = await teamService.updateSettings(teamId, req.key, req.value)
|
||||
return c.json(settings)
|
||||
},
|
||||
)
|
||||
.get('/teams/:teamId/user-metadata', async (c) => {
|
||||
const user = c.get('user')
|
||||
const teamId = c.req.param('teamId')
|
||||
|
||||
await authzService.hasPermission({
|
||||
teamId,
|
||||
user,
|
||||
permission: Permission.Read,
|
||||
})
|
||||
|
||||
const metadata = await userMetadataService.listMetadata(user.id, teamId)
|
||||
return c.json(metadata)
|
||||
})
|
||||
.put(
|
||||
'/teams/:teamId/user-metadata/:key',
|
||||
zValidator('json', updateUserMetadataRequestSchema),
|
||||
async (c) => {
|
||||
const user = c.get('user')
|
||||
const teamId = c.req.param('teamId')
|
||||
const key = c.req.param('key')
|
||||
const req = c.req.valid('json')
|
||||
|
||||
await authzService.hasPermission({
|
||||
teamId,
|
||||
user,
|
||||
permission: Permission.Read,
|
||||
})
|
||||
|
||||
const metadata = await userMetadataService.upsertMetadata(user.id, teamId, key, req.value)
|
||||
return c.json({ key: metadata.key, value: metadata.value })
|
||||
},
|
||||
)
|
||||
|
||||
export default route
|
||||
@@ -0,0 +1,95 @@
|
||||
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 type { CreateUploadTaskResponse, TaskInfo } from '@/dtos/upload'
|
||||
import type { PaginatedData } from '@/services/pagination'
|
||||
|
||||
vi.mock('@/api/middleware/auth', () => ({
|
||||
// We use any here because mocking Hono context and middleware
|
||||
// with full type safety is overly complex for these unit tests.
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
authMiddleware: async (c: any, next: any) => {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
c.set('user', { id: 'user1', name: 'Test User' } as any)
|
||||
await next()
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('@/services/authz/authz', () => ({
|
||||
authzService: {
|
||||
hasPermission: vi.fn(),
|
||||
},
|
||||
Permission: {
|
||||
Read: 'Read',
|
||||
Edit: 'Edit',
|
||||
Admin: 'Admin',
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('@/services/notification/notification', () => ({
|
||||
notificationService: {
|
||||
create: vi.fn().mockResolvedValue(undefined),
|
||||
},
|
||||
}))
|
||||
|
||||
describe('Upload API', () => {
|
||||
const app = new Hono().use('*', authMiddleware).route('/', uploadRoute)
|
||||
|
||||
beforeEach(() => {
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
it('GET /teams/:teamId/upload/tasks', async () => {
|
||||
// We mock the return value as it is only used for checking the call
|
||||
vi.spyOn(uploadService, 'listUploadTasks').mockResolvedValue({
|
||||
data: [],
|
||||
pageInfo: {},
|
||||
} as unknown as PaginatedData<TaskInfo[]>)
|
||||
|
||||
const res = await app.request('/teams/team1/upload/tasks', {
|
||||
headers: { Authorization: 'Bearer test' },
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(uploadService.listUploadTasks).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('POST /teams/:teamId/upload/tasks', async () => {
|
||||
// We mock the return value as it is only used for checking the call
|
||||
vi.spyOn(uploadService, 'createUploadTask').mockResolvedValue({
|
||||
taskId: 'task1',
|
||||
presignedUrls: [],
|
||||
} as unknown as CreateUploadTaskResponse)
|
||||
|
||||
const res = await app.request('/teams/team1/upload/tasks', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json', Authorization: 'Bearer test' },
|
||||
body: JSON.stringify({
|
||||
parentId: 'parent1',
|
||||
files: [],
|
||||
}),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(uploadService.createUploadTask).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('PATCH /teams/:teamId/upload/tasks/:taskId', async () => {
|
||||
vi.spyOn(uploadService, 'confirmFileUpload').mockResolvedValue(undefined)
|
||||
|
||||
const res = await app.request('/teams/team1/upload/tasks/task1', {
|
||||
method: 'PATCH',
|
||||
headers: { 'Content-Type': 'application/json', Authorization: 'Bearer test' },
|
||||
body: JSON.stringify({
|
||||
fileId: 'file1',
|
||||
}),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(uploadService.confirmFileUpload).toHaveBeenCalledWith('user1', 'task1', {
|
||||
fileId: 'file1',
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,101 @@
|
||||
import { Hono } from 'hono'
|
||||
import { zValidator } from '@hono/zod-validator'
|
||||
import { uploadService } from '@/services/upload/upload'
|
||||
import {
|
||||
confirmFileUploadRequestSchema,
|
||||
createUploadTaskRequestSchema,
|
||||
localUploadQuerySchema,
|
||||
} from '@/dtos/upload'
|
||||
import { paginationParamsSchema } from '@/dtos/pagination'
|
||||
import { authzService, Permission } 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'
|
||||
|
||||
type User = Prisma.UserGetPayload<Record<string, never>>
|
||||
|
||||
const route = new Hono<{ Variables: { user: User } }>()
|
||||
.put('/upload/local', zValidator('query', localUploadQuerySchema), async (c) => {
|
||||
const { bucket, key, Signature } = c.req.valid('query')
|
||||
|
||||
if (!verifyLocalUrlSignature(bucket, key, Signature)) {
|
||||
return c.text('Invalid signature', 403)
|
||||
}
|
||||
|
||||
const contentType = c.req.header('Content-Type')
|
||||
let buffer: Buffer
|
||||
let size: number
|
||||
let finalContentType = contentType
|
||||
|
||||
if (contentType?.includes('multipart/form-data')) {
|
||||
const body = await c.req.parseBody()
|
||||
const file = body['file'] as File
|
||||
if (!file) {
|
||||
return c.text('No file uploaded', 400)
|
||||
}
|
||||
buffer = Buffer.from(await file.arrayBuffer())
|
||||
size = file.size
|
||||
finalContentType = file.type || 'application/octet-stream'
|
||||
} else {
|
||||
const arrayBuffer = await c.req.arrayBuffer()
|
||||
buffer = Buffer.from(arrayBuffer)
|
||||
size = arrayBuffer.byteLength
|
||||
}
|
||||
|
||||
await s3Service.putObject(bucket, key, buffer, size, finalContentType)
|
||||
|
||||
return c.json({ success: true })
|
||||
})
|
||||
.get('/teams/:teamId/upload/tasks', zValidator('query', paginationParamsSchema), async (c) => {
|
||||
const user = c.get('user')
|
||||
const params = c.req.valid('query')
|
||||
|
||||
const tasks = await uploadService.listUploadTasks(user.id, params)
|
||||
return c.json(tasks)
|
||||
})
|
||||
.post(
|
||||
'/teams/:teamId/upload/tasks',
|
||||
zValidator('json', createUploadTaskRequestSchema),
|
||||
async (c) => {
|
||||
const teamId = c.req.param('teamId')
|
||||
const user = c.get('user')
|
||||
const req = c.req.valid('json')
|
||||
|
||||
await authzService.hasPermission({
|
||||
teamId,
|
||||
assetId: req.parentId,
|
||||
user,
|
||||
permission: Permission.Edit,
|
||||
})
|
||||
|
||||
const resp = await uploadService.createUploadTask(user.id, req)
|
||||
return c.json(resp)
|
||||
},
|
||||
)
|
||||
.patch(
|
||||
'/teams/:teamId/upload/tasks/:taskId',
|
||||
zValidator('json', confirmFileUploadRequestSchema),
|
||||
async (c) => {
|
||||
const teamId = c.req.param('teamId')
|
||||
const taskId = c.req.param('taskId')
|
||||
const user = c.get('user')
|
||||
const req = c.req.valid('json')
|
||||
|
||||
await uploadService.confirmFileUpload(user.id, taskId, req)
|
||||
|
||||
if (!req.errorMessage) {
|
||||
await notificationService.create({
|
||||
type: NotificationType.successful_file_uploaded,
|
||||
teamId: teamId,
|
||||
creatorId: user.id,
|
||||
assetId: req.fileId,
|
||||
taskId: taskId,
|
||||
})
|
||||
}
|
||||
|
||||
return c.json({ success: true })
|
||||
},
|
||||
)
|
||||
|
||||
export default route
|
||||
@@ -0,0 +1,118 @@
|
||||
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'
|
||||
|
||||
vi.mock('@/services/authz/authz', () => ({
|
||||
authzService: {
|
||||
hasPermission: vi.fn(),
|
||||
},
|
||||
Permission: {
|
||||
Read: 'Read',
|
||||
Edit: 'Edit',
|
||||
Admin: 'Admin',
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('@/api/middleware/auth', () => ({
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
authMiddleware: async (c: any, next: any) => {
|
||||
c.set('user', { id: 'user1', name: 'Test User' })
|
||||
await next()
|
||||
},
|
||||
}))
|
||||
|
||||
describe('versionStack api', () => {
|
||||
let mockCreateVersionStack: any // eslint-disable-line @typescript-eslint/no-explicit-any
|
||||
let mockChangeStackFileVersion: any // eslint-disable-line @typescript-eslint/no-explicit-any
|
||||
let mockGetAsset: any // eslint-disable-line @typescript-eslint/no-explicit-any
|
||||
|
||||
beforeEach(() => {
|
||||
mockCreateVersionStack = vi.spyOn(versionStackService, 'createVersionStack')
|
||||
mockChangeStackFileVersion = vi.spyOn(versionStackService, 'changeStackFileVersion')
|
||||
mockGetAsset = vi.spyOn(assetService, 'getAsset')
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
describe('POST /projects/:projectID/version_stacks', () => {
|
||||
it('should create a version stack and return asset info', async () => {
|
||||
const mockStack = { id: 'stack1' }
|
||||
const mockAssetInfo = { id: 'stack1', type: 'version_stack', name: 'v1' }
|
||||
|
||||
mockCreateVersionStack.mockResolvedValue(mockStack)
|
||||
mockGetAsset.mockResolvedValue(mockAssetInfo)
|
||||
|
||||
const app = new Hono().use('*', authMiddleware).route('/', versionStackRoute)
|
||||
|
||||
const res = await app.request('/projects/p1/version_stacks', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ fileIds: ['f1', 'f2'] }),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const data = await res.json()
|
||||
expect(data).toEqual(mockAssetInfo)
|
||||
|
||||
expect(mockCreateVersionStack).toHaveBeenCalledWith({
|
||||
projectId: 'p1',
|
||||
creatorId: 'user1',
|
||||
fileIds: ['f1', 'f2'],
|
||||
})
|
||||
expect(mockGetAsset).toHaveBeenCalledWith({ assetId: 'stack1' })
|
||||
})
|
||||
|
||||
it('should fail with validation error for invalid body', async () => {
|
||||
const app = new Hono().use('*', authMiddleware).route('/', versionStackRoute)
|
||||
|
||||
const res = await app.request('/projects/p1/version_stacks', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ wrongField: [] }),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(400)
|
||||
expect(mockCreateVersionStack).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
|
||||
describe('POST /projects/:projectID/version_stacks/:stackID/order', () => {
|
||||
it('should change order and return 200', async () => {
|
||||
mockChangeStackFileVersion.mockResolvedValue()
|
||||
|
||||
const app = new Hono().use('*', authMiddleware).route('/', versionStackRoute)
|
||||
|
||||
const res = await app.request('/projects/p1/version_stacks/stack1/order', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ fileId: 'f1', beforeId: 'f2' }),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
|
||||
expect(mockChangeStackFileVersion).toHaveBeenCalledWith({
|
||||
stackId: 'stack1',
|
||||
fileId: 'f1',
|
||||
beforeId: 'f2',
|
||||
})
|
||||
})
|
||||
|
||||
it('should fail with validation error for invalid body', async () => {
|
||||
const app = new Hono().use('*', authMiddleware).route('/', versionStackRoute)
|
||||
|
||||
const res = await app.request('/projects/p1/version_stacks/stack1/order', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ fileId: 'f1' }), // missing beforeId
|
||||
})
|
||||
|
||||
expect(res.status).toBe(400)
|
||||
expect(mockChangeStackFileVersion).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,67 @@
|
||||
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 } from '@/services/authz/authz'
|
||||
import {
|
||||
createVersionStackRequestSchema,
|
||||
changeStackFileVersionRequestSchema,
|
||||
} from '@/dtos/versionStack'
|
||||
import type { Prisma } from '@/generated/prisma/client'
|
||||
|
||||
type User = Prisma.UserGetPayload<Record<string, never>>
|
||||
|
||||
const app = new Hono<{ Variables: { user: User } }>()
|
||||
|
||||
const route = app
|
||||
.post(
|
||||
'/projects/:projectID/version_stacks',
|
||||
zValidator('json', createVersionStackRequestSchema),
|
||||
async (c) => {
|
||||
const projectId = c.req.param('projectID')
|
||||
const user = c.get('user')
|
||||
const req = c.req.valid('json')
|
||||
|
||||
await authzService.hasPermission({
|
||||
projectId,
|
||||
user,
|
||||
permission: Permission.Edit,
|
||||
})
|
||||
|
||||
const stack = await versionStackService.createVersionStack({
|
||||
fileIds: req.fileIds,
|
||||
projectId,
|
||||
creatorId: user.id,
|
||||
})
|
||||
|
||||
const stackInfo = await assetService.getAsset({ assetId: stack.id })
|
||||
|
||||
return c.json(stackInfo)
|
||||
},
|
||||
)
|
||||
.post(
|
||||
'/projects/:projectID/version_stacks/:stackID/order',
|
||||
zValidator('json', changeStackFileVersionRequestSchema),
|
||||
async (c) => {
|
||||
const projectId = c.req.param('projectID')
|
||||
const stackId = c.req.param('stackID')
|
||||
const user = c.get('user')
|
||||
const req = c.req.valid('json')
|
||||
|
||||
await authzService.hasPermission({
|
||||
projectId,
|
||||
user,
|
||||
permission: Permission.Edit,
|
||||
})
|
||||
|
||||
await versionStackService.changeStackFileVersion({
|
||||
stackId,
|
||||
fileId: req.fileId,
|
||||
beforeId: req.beforeId,
|
||||
})
|
||||
|
||||
return new Response(null, { status: 200 })
|
||||
},
|
||||
)
|
||||
|
||||
export default route
|
||||
@@ -0,0 +1,106 @@
|
||||
import index from '@/ui/index.html'
|
||||
|
||||
import type { Prisma } from '@/generated/prisma/client'
|
||||
import { Hono } from 'hono'
|
||||
import agentRoute from '@/api/agent'
|
||||
import attachmentRoute from '@/api/attachment'
|
||||
import authnRoute from '@/api/authn'
|
||||
import fileRoute from '@/api/file'
|
||||
import folderRoute from '@/api/folder'
|
||||
import inviteRoute from '@/api/invite'
|
||||
import metadataRoute from '@/api/metadata'
|
||||
import { authMiddleware } from '@/api/middleware/auth'
|
||||
import notificationRoute from '@/api/notification'
|
||||
import projectRoute from '@/api/project'
|
||||
import providerRoute from '@/api/provider'
|
||||
import publicInviteRoute from '@/api/public-invite'
|
||||
import publicShareRoute from '@/api/public-share'
|
||||
import s3Route from '@/api/s3'
|
||||
import shareRoute from '@/api/share'
|
||||
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 { workflowService } from '@/workflow/workflow'
|
||||
|
||||
type User = Prisma.UserGetPayload<Record<string, never>>
|
||||
|
||||
const app = new Hono()
|
||||
|
||||
const apiRoute = new Hono<{ Variables: { user: User } }>()
|
||||
// Public Routes
|
||||
.route('/', authnRoute)
|
||||
.route('/', publicInviteRoute)
|
||||
.route('/', publicShareRoute)
|
||||
|
||||
// Protected Routes
|
||||
.use('*', authMiddleware)
|
||||
.route('/', inviteRoute)
|
||||
.route('/', providerRoute)
|
||||
.route('/', notificationRoute)
|
||||
.route('/', metadataRoute)
|
||||
.route('/', projectRoute)
|
||||
.route('/', teamRoute)
|
||||
.route('/', versionStackRoute)
|
||||
.route('/', fileRoute)
|
||||
.route('/', folderRoute)
|
||||
.route('/', agentRoute)
|
||||
.route('/', attachmentRoute)
|
||||
.route('/', uploadRoute)
|
||||
.route('/', shareRoute)
|
||||
.route('/', skillRoute)
|
||||
|
||||
app.route('/files', s3Route)
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||
const apiAppRoute = app.route('/api', apiRoute)
|
||||
|
||||
export type AppType = typeof apiAppRoute
|
||||
|
||||
export async function run() {
|
||||
// Start services
|
||||
await metadataService.syncSystemFields().catch(console.error)
|
||||
workflowService.start()
|
||||
if (process.env.WORKFLOW_EXECUTOR === 'temporal') {
|
||||
const args = process.argv.slice(2)
|
||||
let workersOption = ''
|
||||
for (let i = 0; i < args.length; i++) {
|
||||
if (args[i] === '--workers') {
|
||||
workersOption = args[i + 1] || ''
|
||||
} else if (args[i].startsWith('--workers=')) {
|
||||
workersOption = args[i].split('=')[1]
|
||||
}
|
||||
}
|
||||
|
||||
const queuesToStart = ['db_queue']
|
||||
if (workersOption === 'agent' || workersOption === 'ai') {
|
||||
queuesToStart.push('agent_queue')
|
||||
} else if (workersOption === 'transcode') {
|
||||
queuesToStart.push('transcode_queue')
|
||||
} else if (workersOption === 'all') {
|
||||
queuesToStart.push('agent_queue', 'transcode_queue')
|
||||
}
|
||||
|
||||
Promise.all(queuesToStart.map((q) => workflowService.startWorkers(q))).catch(console.error)
|
||||
}
|
||||
|
||||
const server = Bun.serve({
|
||||
port: 3000,
|
||||
fetch: app.fetch,
|
||||
routes: {
|
||||
// Serve index.html for root
|
||||
'/': index,
|
||||
|
||||
// Proxy API requests to Hono
|
||||
'/api/*': app.fetch,
|
||||
'/files/*': app.fetch,
|
||||
|
||||
// Catch-all for SPA routing (fallback to index.html)
|
||||
'/*': index,
|
||||
},
|
||||
development: process.env.NODE_ENV !== 'production',
|
||||
})
|
||||
|
||||
console.log(`🚀 Server running at ${server.url}`)
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
import { workflowService } from '@/workflow/workflow'
|
||||
import { TaskQueueAgent, TaskQueueTranscode } from '@/workflow/workflow-utils'
|
||||
|
||||
export async function run() {
|
||||
const domain = process.argv[3]
|
||||
|
||||
if (!domain) {
|
||||
console.error('Please specify a worker domain.')
|
||||
console.log('Available domains: agent, transcode, all')
|
||||
process.exit(1)
|
||||
}
|
||||
|
||||
switch (domain) {
|
||||
case 'agent':
|
||||
case 'ai':
|
||||
await workflowService.startWorkers(TaskQueueAgent)
|
||||
break
|
||||
case 'transcode':
|
||||
await workflowService.startWorkers(TaskQueueTranscode)
|
||||
break
|
||||
case 'all':
|
||||
await Promise.all([
|
||||
workflowService.startWorkers(TaskQueueAgent),
|
||||
workflowService.startWorkers(TaskQueueTranscode),
|
||||
])
|
||||
break
|
||||
default:
|
||||
console.error('Unknown domain: ' + domain)
|
||||
console.log('Available domains: agent, transcode, all')
|
||||
process.exit(1)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
import { afterEach, beforeEach } from 'vitest'
|
||||
import { getPrismaTestingHelper } from '@/db'
|
||||
|
||||
export function setupTestDbHooks() {
|
||||
beforeEach(async () => {
|
||||
await getPrismaTestingHelper().startNewTransaction()
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
getPrismaTestingHelper().rollbackCurrentTransaction()
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
import { PrismaClient } from '@/generated/prisma/client'
|
||||
import { PrismaTestingHelper } from '@/test-utils'
|
||||
import { PrismaPg } from '@prisma/adapter-pg'
|
||||
import { Pool } from 'pg'
|
||||
import { generateNgrams } from '@/utils/ngram'
|
||||
|
||||
const isTest = process.env.NODE_ENV === 'test'
|
||||
|
||||
const globalForPrisma = globalThis as unknown as {
|
||||
prisma: PrismaClient | undefined
|
||||
}
|
||||
|
||||
// We use any here because PrismaTestingHelper is generic and the extended client type is complex
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
let prismaTestingHelper: PrismaTestingHelper<any> | null = null
|
||||
|
||||
function createPrismaClient() {
|
||||
const connectionString = process.env.DATABASE_URL
|
||||
const pool = new Pool({ connectionString })
|
||||
const adapter = new PrismaPg(pool)
|
||||
const client = new PrismaClient({ adapter, log: ['error'] })
|
||||
return client.$extends({
|
||||
query: {
|
||||
workflowTask: {
|
||||
async create({ args, query }) {
|
||||
const result = await query(args)
|
||||
// Lazy load workflowService to avoid circular dependency
|
||||
import('@/workflow/workflow').then((mod) => {
|
||||
const service = mod?.workflowService
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const task = result as any
|
||||
if (service && task.status === 'pending') {
|
||||
// result is the created task, but the extension types are complex
|
||||
service.submit(task).catch(console.error)
|
||||
}
|
||||
})
|
||||
return result
|
||||
},
|
||||
},
|
||||
asset: {
|
||||
async create({ args, query }) {
|
||||
if (typeof args.data.name === 'string') {
|
||||
args.data.nameNgram = generateNgrams(args.data.name)
|
||||
}
|
||||
return query(args)
|
||||
},
|
||||
async update({ args, query }) {
|
||||
if (typeof args.data.name === 'string') {
|
||||
args.data.nameNgram = generateNgrams(args.data.name)
|
||||
}
|
||||
return query(args)
|
||||
},
|
||||
async upsert({ args, query }) {
|
||||
if (typeof args.create.name === 'string') {
|
||||
args.create.nameNgram = generateNgrams(args.create.name)
|
||||
}
|
||||
if (typeof args.update.name === 'string') {
|
||||
args.update.nameNgram = generateNgrams(args.update.name)
|
||||
}
|
||||
return query(args)
|
||||
},
|
||||
async updateMany({ args, query }) {
|
||||
if (typeof args.data.name === 'string') {
|
||||
args.data.nameNgram = generateNgrams(args.data.name)
|
||||
}
|
||||
return query(args)
|
||||
},
|
||||
async createMany({ args, query }) {
|
||||
if (Array.isArray(args.data)) {
|
||||
for (const item of args.data) {
|
||||
if (typeof item.name === 'string') {
|
||||
item.nameNgram = generateNgrams(item.name)
|
||||
}
|
||||
}
|
||||
}
|
||||
return query(args)
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
export const prisma = (isTest
|
||||
? getPrismaTestingHelper().getProxyClient()
|
||||
: (globalForPrisma.prisma ?? createPrismaClient())) as unknown as PrismaClient
|
||||
|
||||
if (!isTest && process.env.NODE_ENV !== 'production') {
|
||||
globalForPrisma.prisma = prisma
|
||||
}
|
||||
|
||||
export function getPrismaTestingHelper() {
|
||||
if (!prismaTestingHelper) {
|
||||
prismaTestingHelper = new PrismaTestingHelper(createPrismaClient())
|
||||
}
|
||||
return prismaTestingHelper
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
import { z } from 'zod'
|
||||
|
||||
export const agentTypeSchema = z.enum(['chat', 'autofill', 'embedding', 'transcription'])
|
||||
export type AgentType = z.infer<typeof agentTypeSchema>
|
||||
|
||||
export const agentSkillSchema = z.object({
|
||||
id: z.string().optional(),
|
||||
skillId: z.string(),
|
||||
skill: z
|
||||
.object({
|
||||
id: z.string(),
|
||||
name: z.string(),
|
||||
})
|
||||
.optional(),
|
||||
})
|
||||
export type AgentSkill = z.infer<typeof agentSkillSchema>
|
||||
|
||||
export const agentInfoSchema = z.object({
|
||||
id: z.string(),
|
||||
name: z.string(),
|
||||
type: agentTypeSchema,
|
||||
enabled: z.boolean(),
|
||||
avatar: z.string().optional(),
|
||||
providerId: z.string().optional(),
|
||||
modelId: z.string().optional(),
|
||||
thinkingLevel: z.string().optional().default(''),
|
||||
systemPrompt: z.string().optional(),
|
||||
soul: z.string().optional(),
|
||||
skills: z.array(agentSkillSchema).optional(),
|
||||
})
|
||||
export type AgentInfo = z.infer<typeof agentInfoSchema>
|
||||
|
||||
const baseAgentRequest = z.object({
|
||||
name: z.string().min(1),
|
||||
type: agentTypeSchema,
|
||||
enabled: z.boolean().optional().default(true),
|
||||
avatar: z.string().optional(),
|
||||
providerId: z.string().optional(),
|
||||
modelId: z.string().optional(),
|
||||
thinkingLevel: z.string().optional().default(''),
|
||||
systemPrompt: z.string().optional(),
|
||||
soul: z.string().optional(),
|
||||
skills: z.array(z.string()).optional(),
|
||||
})
|
||||
|
||||
export const createAgentRequestSchema = baseAgentRequest.superRefine((data, ctx) => {
|
||||
if (data.type === 'chat' || data.type === 'autofill') {
|
||||
if (!data.providerId) {
|
||||
ctx.addIssue({
|
||||
code: z.ZodIssueCode.custom,
|
||||
message: 'providerId is required for chat/autofill agents',
|
||||
path: ['providerId'],
|
||||
})
|
||||
}
|
||||
if (!data.modelId) {
|
||||
ctx.addIssue({
|
||||
code: z.ZodIssueCode.custom,
|
||||
message: 'modelId is required for chat/autofill agents',
|
||||
path: ['modelId'],
|
||||
})
|
||||
}
|
||||
}
|
||||
})
|
||||
export type CreateAgentRequest = z.infer<typeof createAgentRequestSchema>
|
||||
|
||||
export const updateAgentRequestSchema = baseAgentRequest.superRefine((data, ctx) => {
|
||||
if (data.type === 'chat' || data.type === 'autofill') {
|
||||
if (!data.providerId) {
|
||||
ctx.addIssue({
|
||||
code: z.ZodIssueCode.custom,
|
||||
message: 'providerId is required for chat/autofill agents',
|
||||
path: ['providerId'],
|
||||
})
|
||||
}
|
||||
if (!data.modelId) {
|
||||
ctx.addIssue({
|
||||
code: z.ZodIssueCode.custom,
|
||||
message: 'modelId is required for chat/autofill agents',
|
||||
path: ['modelId'],
|
||||
})
|
||||
}
|
||||
}
|
||||
})
|
||||
export type UpdateAgentRequest = z.infer<typeof updateAgentRequestSchema>
|
||||
|
||||
export interface CreateAgentParams extends CreateAgentRequest {
|
||||
teamId: string
|
||||
}
|
||||
|
||||
export interface UpdateAgentParams extends UpdateAgentRequest {
|
||||
agentId: string
|
||||
}
|
||||
|
||||
export interface DeleteAgentParams {
|
||||
agentId: string
|
||||
}
|
||||
|
||||
export interface ListAgentsParams {
|
||||
teamId: string
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
import { z } from 'zod'
|
||||
|
||||
export enum AiProvider {
|
||||
OpenAi = 'openai',
|
||||
Google = 'google',
|
||||
Anthropic = 'anthropic',
|
||||
ElevenLabs = 'elevenlabs',
|
||||
}
|
||||
|
||||
export const aiProviderSettingsSchema = z.object({
|
||||
apiKey: z.string().optional(),
|
||||
baseUrl: z.string().optional(),
|
||||
chatModels: z.array(z.string()).optional(),
|
||||
transcribeModels: z.array(z.string()).optional(),
|
||||
})
|
||||
|
||||
export type AiProviderSettings = z.infer<typeof aiProviderSettingsSchema>
|
||||
@@ -0,0 +1,261 @@
|
||||
import { z } from 'zod'
|
||||
import { paginationPageInfoSchema, paginationParamsSchema } from './pagination'
|
||||
|
||||
export const assetInfoPaginatedListSchema = z.object({
|
||||
data: z.array(z.lazy(() => assetInfoSchema)),
|
||||
pageInfo: paginationPageInfoSchema,
|
||||
})
|
||||
export type AssetInfoPaginatedList = z.infer<typeof assetInfoPaginatedListSchema>
|
||||
|
||||
export const previewInfoSchema = z.object({
|
||||
mediaType: z.string().nullable(),
|
||||
thumbnailUrl: z.string().optional(),
|
||||
originalHeight: z.number().optional(),
|
||||
originalWidth: z.number().optional(),
|
||||
spriteUrl: z.string().optional(),
|
||||
})
|
||||
export type PreviewInfo = z.infer<typeof previewInfoSchema>
|
||||
|
||||
export const childPreviewSchema = z.object({
|
||||
type: z.string().nullable(),
|
||||
preview: previewInfoSchema.nullable(),
|
||||
})
|
||||
export type ChildPreview = z.infer<typeof childPreviewSchema>
|
||||
|
||||
export const userInfoSchema = z.object({
|
||||
id: z.string(),
|
||||
name: z.string(),
|
||||
})
|
||||
export type UserInfo = z.infer<typeof userInfoSchema>
|
||||
|
||||
export const fieldValueInfoSchema = z.object({
|
||||
fieldId: z.string(),
|
||||
|
||||
value: z.any(),
|
||||
})
|
||||
export type FieldValueInfo = z.infer<typeof fieldValueInfoSchema>
|
||||
|
||||
export const ancestorFolderSchema = z.object({
|
||||
id: z.string(),
|
||||
name: z.string(),
|
||||
})
|
||||
export type AncestorFolder = z.infer<typeof ancestorFolderSchema>
|
||||
|
||||
export const mediaMetadataSchema = z.object({
|
||||
duration: z.number().optional(),
|
||||
originalWidth: z.number().optional(),
|
||||
originalHeight: z.number().optional(),
|
||||
frameRate: z.number().optional(),
|
||||
})
|
||||
export type MediaMetadata = z.infer<typeof mediaMetadataSchema>
|
||||
|
||||
export const assetInfoSchema = z.object({
|
||||
id: z.string(),
|
||||
name: z.string(),
|
||||
sizeByte: z.number(),
|
||||
fileCount: z.number(),
|
||||
type: z.string(),
|
||||
targetType: z.string().optional().nullable(),
|
||||
status: z.string(),
|
||||
mediaType: z.string().nullable(),
|
||||
latestChildren: z.array(childPreviewSchema).optional(),
|
||||
preview: previewInfoSchema.nullable().optional(),
|
||||
createdAt: z.string(),
|
||||
updatedAt: z.string(),
|
||||
deletedAt: z.string().nullable().optional(),
|
||||
creator: userInfoSchema.nullable().optional(),
|
||||
fieldValues: z.array(fieldValueInfoSchema).optional(),
|
||||
sortIndex: z.string().optional().nullable(),
|
||||
|
||||
media: z
|
||||
.object({
|
||||
original: z.object({ downloadUrl: z.string(), key: z.string().optional() }).optional(),
|
||||
videoTranscodes: z
|
||||
.array(
|
||||
z.object({
|
||||
id: z.string(),
|
||||
url: z.string(),
|
||||
key: z.string(),
|
||||
width: z.number(),
|
||||
height: z.number(),
|
||||
size: z.number(),
|
||||
isRaw: z.boolean(),
|
||||
}),
|
||||
)
|
||||
.optional(),
|
||||
imageTranscodes: z
|
||||
.array(
|
||||
z.object({
|
||||
id: z.string(),
|
||||
url: z.string(),
|
||||
key: z.string(),
|
||||
width: z.number(),
|
||||
height: z.number(),
|
||||
size: z.number(),
|
||||
isRaw: z.boolean(),
|
||||
}),
|
||||
)
|
||||
.optional(),
|
||||
videoPreview: z.object({ url: z.string(), key: z.string().optional() }).optional(),
|
||||
mimeType: z.string().optional(),
|
||||
metadata: mediaMetadataSchema.optional(),
|
||||
})
|
||||
.optional(),
|
||||
ancestorFolders: z.array(ancestorFolderSchema).optional(),
|
||||
})
|
||||
export type AssetInfo = z.infer<typeof assetInfoSchema>
|
||||
|
||||
export const createAssetRequestSchema = z.object({
|
||||
name: z.string(),
|
||||
type: z.string(),
|
||||
projectId: z.string().optional(),
|
||||
parentId: z.string().optional(),
|
||||
key: z.string().optional(),
|
||||
sizeByte: z.number().optional(),
|
||||
contentType: z.string().optional(),
|
||||
creatorId: z.string().optional(),
|
||||
})
|
||||
export type CreateAssetRequest = z.infer<typeof createAssetRequestSchema>
|
||||
|
||||
export const getAssetRequestSchema = z.object({
|
||||
assetId: z.string(),
|
||||
})
|
||||
export type GetAssetRequest = z.infer<typeof getAssetRequestSchema>
|
||||
|
||||
export const updateAssetNameRequestSchema = z.object({
|
||||
id: z.string(),
|
||||
name: z.string(),
|
||||
})
|
||||
export type UpdateAssetNameRequest = z.infer<typeof updateAssetNameRequestSchema>
|
||||
|
||||
export const listChildrenRequestSchema = z.object({
|
||||
assetId: z.string().optional(),
|
||||
assetType: z.string(),
|
||||
projectId: z.string().optional(),
|
||||
showRemoved: z.boolean().optional(),
|
||||
prefix: z.string().optional(),
|
||||
sort: z.string().optional(),
|
||||
order: z.string().optional(),
|
||||
// pagination props mixed in via merge
|
||||
...paginationParamsSchema.shape,
|
||||
})
|
||||
export type ListChildrenRequest = z.infer<typeof listChildrenRequestSchema>
|
||||
|
||||
export const createCommentRequestSchema = z.object({
|
||||
assetId: z.string(),
|
||||
userId: z.string(),
|
||||
replyToId: z.string().optional(),
|
||||
message: z.string(),
|
||||
|
||||
annotations: z.any().optional(),
|
||||
second: z.number().optional(),
|
||||
attachmentIds: z.array(z.string()),
|
||||
})
|
||||
export type CreateCommentRequest = z.infer<typeof createCommentRequestSchema>
|
||||
|
||||
export const attachmentInfoSchema = z.object({
|
||||
id: z.string(),
|
||||
assetId: z.string(),
|
||||
url: z.string(),
|
||||
mediaType: z.string().nullable(),
|
||||
})
|
||||
export type AttachmentInfo = z.infer<typeof attachmentInfoSchema>
|
||||
|
||||
export type CommentInfo = {
|
||||
id: string
|
||||
assetId: string
|
||||
message: string | null
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
annotations: any
|
||||
creator: UserInfo
|
||||
replies: CommentInfo[]
|
||||
attachments: AttachmentInfo[]
|
||||
mentions: UserInfo[]
|
||||
createdAt: string
|
||||
updatedAt: string
|
||||
isAi: boolean
|
||||
}
|
||||
|
||||
export const commentInfoSchema: z.ZodType<CommentInfo> = z.object({
|
||||
id: z.string(),
|
||||
assetId: z.string(),
|
||||
message: z.string().nullable(),
|
||||
|
||||
annotations: z.any(),
|
||||
creator: userInfoSchema,
|
||||
replies: z.array(z.lazy(() => commentInfoSchema)),
|
||||
attachments: z.array(attachmentInfoSchema),
|
||||
mentions: z.array(userInfoSchema),
|
||||
createdAt: z.string(),
|
||||
updatedAt: z.string(),
|
||||
isAi: z.boolean(),
|
||||
})
|
||||
|
||||
export const reparentAssetsRequestSchema = z.object({
|
||||
newParentId: z.string(),
|
||||
assetIds: z.array(z.string()),
|
||||
creatorId: z.string().optional(),
|
||||
})
|
||||
export type ReparentAssetsRequest = z.infer<typeof reparentAssetsRequestSchema>
|
||||
|
||||
export const updateFileRequestSchema = z.object({
|
||||
name: z.string(),
|
||||
})
|
||||
export type UpdateFileRequest = z.infer<typeof updateFileRequestSchema>
|
||||
|
||||
export const updateAssetOrderRequestSchema = z.object({
|
||||
beforeIndex: z.string().optional(),
|
||||
afterIndex: z.string().optional(),
|
||||
})
|
||||
export type UpdateAssetOrderRequest = z.infer<typeof updateAssetOrderRequestSchema>
|
||||
|
||||
export const deleteFilesRequestSchema = z.object({
|
||||
ids: z.array(z.string()),
|
||||
})
|
||||
export type DeleteFilesRequest = z.infer<typeof deleteFilesRequestSchema>
|
||||
|
||||
export const restoreFilesRequestSchema = z.object({
|
||||
ids: z.array(z.string()),
|
||||
})
|
||||
export type RestoreFilesRequest = z.infer<typeof restoreFilesRequestSchema>
|
||||
|
||||
export const uploadFileRequestSchema = z.object({
|
||||
file: z.instanceof(File),
|
||||
})
|
||||
export type UploadFileRequest = z.infer<typeof uploadFileRequestSchema>
|
||||
|
||||
export const uploadTeamFileResponseSchema = z.object({
|
||||
key: z.string(),
|
||||
})
|
||||
export type UploadTeamFileResponse = z.infer<typeof uploadTeamFileResponseSchema>
|
||||
|
||||
export interface ImageTranscode {
|
||||
id: string
|
||||
url: string
|
||||
width: number
|
||||
height: number
|
||||
size: number
|
||||
isRaw: boolean
|
||||
}
|
||||
|
||||
export interface VideoTranscode {
|
||||
id: string
|
||||
url: string
|
||||
width: number
|
||||
height: number
|
||||
size: number
|
||||
isRaw: boolean
|
||||
}
|
||||
|
||||
export const postAttachmentRequestSchema = z.object({
|
||||
fileName: z.string(),
|
||||
contentType: z.string(),
|
||||
size: z.number(),
|
||||
})
|
||||
export type PostAttachmentRequest = z.infer<typeof postAttachmentRequestSchema>
|
||||
|
||||
export const postAttachmentResponseSchema = z.object({
|
||||
id: z.string(),
|
||||
uploadUrl: z.string(),
|
||||
})
|
||||
export type PostAttachmentResponse = z.infer<typeof postAttachmentResponseSchema>
|
||||
@@ -0,0 +1,8 @@
|
||||
import { z } from 'zod'
|
||||
|
||||
export const signupInfoResponseSchema = z.object({
|
||||
userCount: z.number(),
|
||||
enablePublicSignup: z.boolean(),
|
||||
})
|
||||
|
||||
export type SignupInfoResponse = z.infer<typeof signupInfoResponseSchema>
|
||||
@@ -0,0 +1,22 @@
|
||||
import { z } from 'zod'
|
||||
|
||||
export const createFolderRequestSchema = z.object({
|
||||
name: z.string(),
|
||||
parentId: z.string(),
|
||||
})
|
||||
export type CreateFolderRequest = z.infer<typeof createFolderRequestSchema>
|
||||
|
||||
export const updateFolderRequestSchema = z.object({
|
||||
name: z.string(),
|
||||
})
|
||||
export type UpdateFolderRequest = z.infer<typeof updateFolderRequestSchema>
|
||||
|
||||
export const deleteFoldersRequestSchema = z.object({
|
||||
ids: z.array(z.string()),
|
||||
})
|
||||
export type DeleteFoldersRequest = z.infer<typeof deleteFoldersRequestSchema>
|
||||
|
||||
export const restoreFoldersRequestSchema = z.object({
|
||||
ids: z.array(z.string()),
|
||||
})
|
||||
export type RestoreFoldersRequest = z.infer<typeof restoreFoldersRequestSchema>
|
||||
@@ -0,0 +1,32 @@
|
||||
import { z } from 'zod'
|
||||
|
||||
export const inviteInfoSchema = z.object({
|
||||
code: z.string(),
|
||||
role: z.enum(['editor', 'reviewer', 'owner']),
|
||||
teamId: z.string(),
|
||||
teamName: z.string(),
|
||||
projectId: z.string().optional(),
|
||||
projectName: z.string().optional(),
|
||||
inviterName: z.string(),
|
||||
isUsed: z.boolean(),
|
||||
})
|
||||
|
||||
export type InviteInfo = z.infer<typeof inviteInfoSchema>
|
||||
|
||||
export const createTeamInviteRequestSchema = z.object({
|
||||
role: z.enum(['editor', 'reviewer']),
|
||||
})
|
||||
|
||||
export type CreateTeamInviteRequest = z.infer<typeof createTeamInviteRequestSchema>
|
||||
|
||||
export const createProjectInviteRequestSchema = z.object({
|
||||
role: z.enum(['editor', 'reviewer']),
|
||||
})
|
||||
|
||||
export type CreateProjectInviteRequest = z.infer<typeof createProjectInviteRequestSchema>
|
||||
|
||||
export const joinRequestSchema = z.object({
|
||||
code: z.string(),
|
||||
})
|
||||
|
||||
export type JoinRequest = z.infer<typeof joinRequestSchema>
|
||||
@@ -0,0 +1,80 @@
|
||||
import { z } from 'zod'
|
||||
|
||||
export const FieldType = {
|
||||
text: 'text',
|
||||
longText: 'longText',
|
||||
select: 'select',
|
||||
selectMulti: 'selectMulti',
|
||||
rating: 'rating',
|
||||
number: 'number',
|
||||
toggle: 'toggle',
|
||||
date: 'date',
|
||||
} as const
|
||||
|
||||
export type FieldType = (typeof FieldType)[keyof typeof FieldType]
|
||||
|
||||
export const selectOptionSchema = z.object({
|
||||
id: z.string(),
|
||||
displayName: z.string(),
|
||||
color: z.string().optional(),
|
||||
})
|
||||
export type SelectOption = z.infer<typeof selectOptionSchema>
|
||||
|
||||
export const fieldConfigSchema = z.object({
|
||||
name: z.string(),
|
||||
type: z.enum(['text', 'longText', 'select', 'selectMulti', 'rating', 'number', 'toggle', 'date']),
|
||||
text: z.any().optional(),
|
||||
longText: z.any().optional(),
|
||||
select: z.any().optional(),
|
||||
selectMulti: z.any().optional(),
|
||||
rating: z.any().optional(),
|
||||
number: z.any().optional(),
|
||||
toggle: z.any().optional(),
|
||||
date: z.any().optional(),
|
||||
})
|
||||
|
||||
export const createFieldRequestSchema = z.object({
|
||||
key: z.string().optional(),
|
||||
label: z.string().optional(),
|
||||
scope: z.string().optional(),
|
||||
config: fieldConfigSchema,
|
||||
aiAutofill: z.boolean().default(false),
|
||||
description: z.string().default(''),
|
||||
})
|
||||
export type CreateFieldRequest = z.infer<typeof createFieldRequestSchema>
|
||||
|
||||
export const updateFieldRequestSchema = z.object({
|
||||
label: z.string().optional(),
|
||||
config: fieldConfigSchema,
|
||||
aiAutofill: z.boolean().optional(),
|
||||
description: z.string().optional(),
|
||||
})
|
||||
export type UpdateFieldRequest = z.infer<typeof updateFieldRequestSchema>
|
||||
|
||||
export const projectFieldOrderSchema = z.object({
|
||||
fieldId: z.string(),
|
||||
visible: z.boolean(),
|
||||
})
|
||||
export type ProjectFieldOrder = z.infer<typeof projectFieldOrderSchema>
|
||||
|
||||
export const updateProjectFieldsOrderRequestSchema = z.array(projectFieldOrderSchema)
|
||||
export type UpdateProjectFieldsOrderRequest = z.infer<typeof updateProjectFieldsOrderRequestSchema>
|
||||
|
||||
export const updateAssetMetadataRequestSchema = z.object({
|
||||
key: z.string(),
|
||||
value: z.any(),
|
||||
})
|
||||
export type UpdateAssetMetadataRequest = z.infer<typeof updateAssetMetadataRequestSchema>
|
||||
|
||||
export const updateAssetMetadataRequestListSchema = z.array(updateAssetMetadataRequestSchema)
|
||||
|
||||
export const fieldInfoSchema = z.object({
|
||||
id: z.string(),
|
||||
config: fieldConfigSchema,
|
||||
scope: z.string(),
|
||||
readOnly: z.boolean(),
|
||||
visible: z.boolean(),
|
||||
description: z.string(),
|
||||
aiAutofill: z.boolean(),
|
||||
})
|
||||
export type FieldInfo = z.infer<typeof fieldInfoSchema>
|
||||
@@ -0,0 +1,75 @@
|
||||
import { z } from 'zod'
|
||||
import { NotificationType } from '@/generated/prisma/client'
|
||||
|
||||
export const teamUserInfoSchema = z.object({
|
||||
id: z.string().optional(),
|
||||
name: z.string().optional(),
|
||||
role: z.string().optional(),
|
||||
})
|
||||
|
||||
export type TeamUserInfo = z.infer<typeof teamUserInfoSchema>
|
||||
|
||||
export const entityInfoSchema = z.object({
|
||||
id: z.string().optional(),
|
||||
name: z.string().optional(),
|
||||
})
|
||||
|
||||
export type EntityInfo = z.infer<typeof entityInfoSchema>
|
||||
|
||||
export const assetPreviewSchema = z.object({
|
||||
id: z.string().optional(),
|
||||
mediaType: z.string().optional(),
|
||||
name: z.string().optional(),
|
||||
preview: z.string().optional(),
|
||||
})
|
||||
|
||||
export type AssetPreview = z.infer<typeof assetPreviewSchema>
|
||||
|
||||
export const notificationInfoSchema = z.object({
|
||||
id: z.string().optional(),
|
||||
creator: teamUserInfoSchema.optional(),
|
||||
type: z.string().optional(),
|
||||
team: entityInfoSchema.optional(),
|
||||
project: entityInfoSchema.optional(),
|
||||
asset: assetPreviewSchema.optional(),
|
||||
user: teamUserInfoSchema.optional(),
|
||||
createdAt: z.string().optional(),
|
||||
isRead: z.boolean().optional(),
|
||||
})
|
||||
|
||||
export type NotificationInfo = z.infer<typeof notificationInfoSchema>
|
||||
|
||||
export const listNotificationsRequestSchema = z.object({
|
||||
unreadOnly: z
|
||||
.union([z.boolean(), z.string()])
|
||||
.transform((v) => v === true || v === 'true')
|
||||
.optional(),
|
||||
after: z.string().optional(),
|
||||
pageSize: z.coerce.number().optional(),
|
||||
})
|
||||
|
||||
export type ListNotificationsRequest = z.infer<typeof listNotificationsRequestSchema>
|
||||
|
||||
export const markNotificationReadRequestSchema = z.object({
|
||||
notificationId: z.string().min(1),
|
||||
})
|
||||
|
||||
export type MarkNotificationReadRequest = z.infer<typeof markNotificationReadRequestSchema>
|
||||
|
||||
// Service types
|
||||
export interface CreateNotificationRequest {
|
||||
type: NotificationType
|
||||
teamId: string
|
||||
projectId?: string
|
||||
creatorId?: string
|
||||
assetId?: string
|
||||
taskId?: string
|
||||
userId?: string
|
||||
commentMessage?: string // For parsing mentions
|
||||
}
|
||||
|
||||
export interface ListNotificationParams {
|
||||
unreadOnly?: boolean
|
||||
after?: string
|
||||
pageSize?: number
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
import { z } from 'zod'
|
||||
|
||||
export const paginationPageInfoSchema = z.object({
|
||||
cursor: z.string().optional(),
|
||||
total: z.number().optional(),
|
||||
})
|
||||
|
||||
export type PaginationPageInfo = z.infer<typeof paginationPageInfoSchema>
|
||||
|
||||
export const paginationParamsSchema = z.object({
|
||||
first: z.coerce.number().optional(),
|
||||
after: z.string().optional(),
|
||||
includeCount: z
|
||||
.union([z.boolean(), z.string()])
|
||||
.transform((v) => v === true || v === 'true')
|
||||
.optional(),
|
||||
})
|
||||
|
||||
export type PaginationParams = z.infer<typeof paginationParamsSchema>
|
||||
@@ -0,0 +1,99 @@
|
||||
import { z } from 'zod'
|
||||
import { paginationPageInfoSchema, paginationParamsSchema } from './pagination'
|
||||
|
||||
export const createProjectRequestSchema = z.object({
|
||||
name: z.string(),
|
||||
coverImageKey: z.string().optional(),
|
||||
enableNotification: z.boolean().default(false),
|
||||
})
|
||||
export type CreateProjectRequest = z.infer<typeof createProjectRequestSchema>
|
||||
|
||||
export const updateProjectRequestSchema = z.object({
|
||||
name: z.string().optional(),
|
||||
coverImageKey: z.string().optional(),
|
||||
enableNotification: z.boolean().optional(),
|
||||
})
|
||||
export type UpdateProjectRequest = z.infer<typeof updateProjectRequestSchema>
|
||||
|
||||
export const projectInfoSchema = z.object({
|
||||
id: z.string(),
|
||||
name: z.string(),
|
||||
rootFolder: z.string().optional(),
|
||||
coverImage: z.string().optional(),
|
||||
coverImageKey: z.string().optional(),
|
||||
enableNotification: z.boolean(),
|
||||
updatedAt: z.union([z.string(), z.date()]),
|
||||
})
|
||||
export type ProjectInfo = z.infer<typeof projectInfoSchema>
|
||||
|
||||
export const listProjectsRequestSchema = z
|
||||
.object({
|
||||
sortBy: z.string().optional(),
|
||||
sortDirection: z.enum(['asc', 'desc']).optional(),
|
||||
})
|
||||
.merge(paginationParamsSchema)
|
||||
|
||||
export const listProjectsResponseSchema = z.object({
|
||||
data: z.array(projectInfoSchema),
|
||||
pageInfo: paginationPageInfoSchema,
|
||||
})
|
||||
|
||||
export const getProjectTeamResponseSchema = z.object({
|
||||
teamId: z.string(),
|
||||
})
|
||||
export type GetProjectTeamResponse = z.infer<typeof getProjectTeamResponseSchema>
|
||||
|
||||
export const projectUserInfoSchema = z.object({
|
||||
id: z.string(),
|
||||
name: z.string(),
|
||||
role: z.string(),
|
||||
})
|
||||
export type ProjectUserInfo = z.infer<typeof projectUserInfoSchema>
|
||||
|
||||
export const botInfoSchema = z.object({
|
||||
id: z.string(),
|
||||
name: z.string(),
|
||||
})
|
||||
export type BotInfo = z.infer<typeof botInfoSchema>
|
||||
|
||||
export const recentlyDeletedRequestSchema = z
|
||||
.object({
|
||||
assetType: z.string(),
|
||||
sort: z.enum(['createdAt', 'name', 'size']).optional(),
|
||||
order: z.enum(['asc', 'desc']).optional(),
|
||||
})
|
||||
.merge(paginationParamsSchema)
|
||||
|
||||
// Service Layer Interfaces
|
||||
export interface ServiceCreateProjectRequest {
|
||||
teamId: string
|
||||
name: string
|
||||
coverImageKey?: string
|
||||
enableNotification?: boolean
|
||||
}
|
||||
|
||||
export interface ServiceUpdateProjectRequest {
|
||||
projectId: string
|
||||
name?: string
|
||||
coverImageKey?: string
|
||||
enableNotification?: boolean
|
||||
}
|
||||
|
||||
export interface ServiceListProjectsRequest {
|
||||
teamId: string
|
||||
userId: string
|
||||
sortBy?: string
|
||||
sortDirection?: 'asc' | 'desc'
|
||||
pagination: z.infer<typeof paginationParamsSchema>
|
||||
}
|
||||
|
||||
export interface ServiceAddProjectMemberRequest {
|
||||
projectId: string
|
||||
userId: string
|
||||
role: string
|
||||
}
|
||||
|
||||
export interface ServiceListProjectMembersRequest {
|
||||
projectId: string
|
||||
includeAgents?: boolean
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
import { z } from 'zod'
|
||||
export { z }
|
||||
|
||||
// We define a serializable version of ProviderConfig for our API and DB
|
||||
// as the original ProviderConfig interface includes non-serializable fields (functions)
|
||||
export const providerModelConfigSchema = z.object({
|
||||
api: z.string().optional(),
|
||||
reasoning: z.boolean().default(false),
|
||||
input: z.array(z.enum(['text', 'image'])).default(['text']),
|
||||
contextWindow: z.number().int().positive().default(128000),
|
||||
maxTokens: z.number().int().positive().default(4096),
|
||||
cost: z.object({
|
||||
input: z.number().nonnegative().default(0),
|
||||
output: z.number().nonnegative().default(0),
|
||||
cacheRead: z.number().nonnegative().default(0),
|
||||
cacheWrite: z.number().nonnegative().default(0),
|
||||
}),
|
||||
})
|
||||
|
||||
export const providerModelSchema = z.object({
|
||||
id: z.string().optional(),
|
||||
modelId: z.string().min(1, 'Model ID is required'),
|
||||
name: z.string().min(0).default(''),
|
||||
config: providerModelConfigSchema,
|
||||
})
|
||||
|
||||
export const providerConfigSchema = z.object({
|
||||
baseUrl: z.string().url('Must be a valid URL').optional().or(z.literal('')),
|
||||
apiKey: z.string().optional().or(z.literal('')),
|
||||
api: z.string().min(1, 'API Protocol is required'),
|
||||
headers: z.record(z.string(), z.string()).optional(),
|
||||
authHeader: z.boolean().optional(),
|
||||
})
|
||||
|
||||
export type ProviderConfigSerializable = z.infer<typeof providerConfigSchema>
|
||||
|
||||
export const createProviderRequestSchema = z.object({
|
||||
name: z.string().min(1, 'Provider name is required'),
|
||||
config: providerConfigSchema,
|
||||
models: z.array(providerModelSchema).min(1, 'At least one model is required'),
|
||||
})
|
||||
|
||||
export const updateProviderRequestSchema = z.object({
|
||||
config: providerConfigSchema,
|
||||
models: z.array(providerModelSchema).min(1, 'At least one model is required'),
|
||||
})
|
||||
|
||||
export const providerResponseSchema = z.object({
|
||||
id: z.string(),
|
||||
name: z.string(),
|
||||
isBuiltin: z.boolean(),
|
||||
config: providerConfigSchema,
|
||||
models: z.array(providerModelSchema).optional(),
|
||||
modelsCount: z.number().optional(),
|
||||
createdAt: z.date(),
|
||||
updatedAt: z.date(),
|
||||
})
|
||||
|
||||
export type ProviderResponse = z.infer<typeof providerResponseSchema>
|
||||
@@ -0,0 +1,7 @@
|
||||
export interface ObjectInfo {
|
||||
key: string
|
||||
size: number
|
||||
lastModified: Date
|
||||
contentType: string
|
||||
eTag: string
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
import { z } from 'zod'
|
||||
import { paginationParamsSchema } from './pagination'
|
||||
|
||||
export const searchConditionOperatorSchema = z.enum([
|
||||
'is',
|
||||
'eq',
|
||||
'neq',
|
||||
'gt',
|
||||
'gte',
|
||||
'lt',
|
||||
'lte',
|
||||
'contains',
|
||||
'notContains',
|
||||
'isEmpty',
|
||||
'isNotEmpty',
|
||||
'in',
|
||||
'notIn',
|
||||
'hasAny',
|
||||
'hasAll',
|
||||
'hasNone',
|
||||
'isWithin',
|
||||
])
|
||||
export type SearchConditionOperator = z.infer<typeof searchConditionOperatorSchema>
|
||||
|
||||
export const searchConditionSchema = z.object({
|
||||
field: z.string(),
|
||||
operator: searchConditionOperatorSchema,
|
||||
value: z.any(),
|
||||
})
|
||||
export type SearchCondition = z.infer<typeof searchConditionSchema>
|
||||
|
||||
export const searchSortOrderSchema = z.enum(['asc', 'desc'])
|
||||
export type SearchSortOrder = z.infer<typeof searchSortOrderSchema>
|
||||
|
||||
export const searchSortSchema = z.object({
|
||||
field: z.string(),
|
||||
order: searchSortOrderSchema,
|
||||
})
|
||||
export type SearchSort = z.infer<typeof searchSortSchema>
|
||||
|
||||
export const searchOperatorSchema = z.enum(['AND', 'OR'])
|
||||
export type SearchOperator = z.infer<typeof searchOperatorSchema>
|
||||
|
||||
export const searchAssetTypeSchema = z.enum(['file', 'folder'])
|
||||
export type SearchAssetType = z.infer<typeof searchAssetTypeSchema>
|
||||
|
||||
export const searchRequestSchema = z
|
||||
.object({
|
||||
operator: searchOperatorSchema.optional().default('AND'),
|
||||
conditions: z.array(searchConditionSchema).optional().default([]),
|
||||
sort: searchSortSchema.optional(),
|
||||
|
||||
assetType: searchAssetTypeSchema.optional(),
|
||||
showSymlink: z.boolean().optional(),
|
||||
recursively: z.boolean().optional().default(true),
|
||||
query: z.string().optional(),
|
||||
})
|
||||
.merge(paginationParamsSchema)
|
||||
export type SearchRequest = z.infer<typeof searchRequestSchema>
|
||||
@@ -0,0 +1,52 @@
|
||||
import { z } from 'zod'
|
||||
import { paginationParamsSchema } from './pagination'
|
||||
|
||||
export interface ShareLinkInfo {
|
||||
id: string
|
||||
name: string
|
||||
expireAt?: string
|
||||
isDisabled: boolean
|
||||
hasPassword: boolean
|
||||
defaultSortOrder?: string
|
||||
fieldVisibility?: Record<string, boolean>
|
||||
rootFolderId: string
|
||||
projectId: string
|
||||
isExpired: boolean
|
||||
createdAt: string
|
||||
updatedAt: string
|
||||
}
|
||||
|
||||
export const createShareLinkRequestSchema = z.object({
|
||||
name: z.string().min(1),
|
||||
expireAt: z.string().datetime().optional(),
|
||||
password: z.string().optional(),
|
||||
isDisabled: z.boolean().optional(),
|
||||
defaultSortOrder: z.string().optional(),
|
||||
})
|
||||
|
||||
export type CreateShareLinkRequest = z.infer<typeof createShareLinkRequestSchema>
|
||||
|
||||
export const updateShareLinkRequestSchema = z.object({
|
||||
name: z.string().min(1).optional(),
|
||||
expireAt: z.string().datetime().optional().nullable(),
|
||||
password: z.string().optional().nullable(),
|
||||
isDisabled: z.boolean().optional(),
|
||||
defaultSortOrder: z.string().optional().nullable(),
|
||||
fieldVisibility: z.record(z.string(), z.boolean()).optional().nullable(),
|
||||
})
|
||||
|
||||
export type UpdateShareLinkRequest = z.infer<typeof updateShareLinkRequestSchema>
|
||||
|
||||
export const listShareLinksRequestSchema = paginationParamsSchema.extend({
|
||||
projectId: z.string().optional(), // projectId can come from param
|
||||
})
|
||||
|
||||
export type ListShareLinksRequest = z.infer<typeof listShareLinksRequestSchema> & {
|
||||
projectId: string
|
||||
}
|
||||
|
||||
export const addAssetToShareRequestSchema = z.object({
|
||||
assetIds: z.array(z.string().min(1)).min(1),
|
||||
})
|
||||
|
||||
export type AddAssetToShareRequest = z.infer<typeof addAssetToShareRequestSchema>
|
||||
@@ -0,0 +1,37 @@
|
||||
import { z } from 'zod'
|
||||
|
||||
export interface SkillInfo {
|
||||
id: string
|
||||
name: string
|
||||
description: string | null
|
||||
config: PrismaJson.SkillConfig | null
|
||||
assetId: string
|
||||
hash: string
|
||||
createdAt: string
|
||||
updatedAt: string
|
||||
}
|
||||
|
||||
export const upsertSkillRequestSchema = z.object({
|
||||
assetId: z.string().optional(),
|
||||
githubUrl: z.string().optional(),
|
||||
override: z.boolean().optional(),
|
||||
})
|
||||
|
||||
export type UpsertSkillRequest = z.infer<typeof upsertSkillRequestSchema>
|
||||
|
||||
export const updateSkillConfigRequestSchema = z.object({
|
||||
config: z.object({
|
||||
environmentVariables: z.array(
|
||||
z.object({
|
||||
name: z.string(),
|
||||
default: z.string().optional(),
|
||||
}),
|
||||
),
|
||||
}),
|
||||
})
|
||||
|
||||
export type UpdateSkillConfigRequest = z.infer<typeof updateSkillConfigRequestSchema>
|
||||
|
||||
export interface ListSkillsResponse {
|
||||
skills: SkillInfo[]
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
import { z } from 'zod'
|
||||
import { paginationPageInfoSchema, paginationParamsSchema } from './pagination'
|
||||
import { UserType } from '@/generated/prisma/enums'
|
||||
|
||||
export const createTeamRequestSchema = z.object({
|
||||
name: z.string(),
|
||||
})
|
||||
export type CreateTeamRequest = z.infer<typeof createTeamRequestSchema>
|
||||
|
||||
export const teamInfoSchema = z.object({
|
||||
id: z.string(),
|
||||
name: z.string(),
|
||||
rootFolder: z.string().optional(),
|
||||
updatedAt: z.union([z.string(), z.date()]),
|
||||
})
|
||||
export type TeamInfo = z.infer<typeof teamInfoSchema>
|
||||
|
||||
export const getUserTeamsRequestSchema = paginationParamsSchema
|
||||
export type GetUserTeamsRequest = z.infer<typeof getUserTeamsRequestSchema>
|
||||
|
||||
export const getUserTeamsResponseSchema = z.object({
|
||||
data: z.array(teamInfoSchema),
|
||||
pageInfo: paginationPageInfoSchema,
|
||||
})
|
||||
export type GetUserTeamsResponse = z.infer<typeof getUserTeamsResponseSchema>
|
||||
|
||||
export const joinTeamRequestSchema = z.object({
|
||||
teamId: z.string(),
|
||||
userId: z.string(),
|
||||
})
|
||||
export type JoinTeamRequest = z.infer<typeof joinTeamRequestSchema>
|
||||
|
||||
export const getMeResponseSchema = z.object({
|
||||
id: z.string(),
|
||||
name: z.string(),
|
||||
email: z.string().optional(),
|
||||
role: z.string(),
|
||||
})
|
||||
export type GetMeResponse = z.infer<typeof getMeResponseSchema>
|
||||
|
||||
export const userInfoSchema = z.object({
|
||||
id: z.string(),
|
||||
name: z.string(),
|
||||
role: z.string(),
|
||||
email: z.string().optional(),
|
||||
type: z.nativeEnum(UserType).optional(),
|
||||
})
|
||||
export type UserInfo = z.infer<typeof userInfoSchema>
|
||||
|
||||
export const listMembersQuerySchema = z.object({
|
||||
includeAgents: z
|
||||
.string()
|
||||
.optional()
|
||||
.transform((v) => v === 'true'),
|
||||
})
|
||||
|
||||
export const updateTeamSettingsRequestSchema = z.object({
|
||||
key: z.string(),
|
||||
value: z.any(),
|
||||
})
|
||||
export type UpdateTeamSettingsRequest = z.infer<typeof updateTeamSettingsRequestSchema>
|
||||
|
||||
export const VideoTranscodeStrategy = {
|
||||
disable: 'disable',
|
||||
single: 'single',
|
||||
full: 'full',
|
||||
} as const
|
||||
export type VideoTranscodeStrategy =
|
||||
(typeof VideoTranscodeStrategy)[keyof typeof VideoTranscodeStrategy]
|
||||
|
||||
export const ImageTranscodeStrategy = {
|
||||
disable: 'disable',
|
||||
single: 'single',
|
||||
} as const
|
||||
export type ImageTranscodeStrategy =
|
||||
(typeof ImageTranscodeStrategy)[keyof typeof ImageTranscodeStrategy]
|
||||
|
||||
// Service Layer Interfaces
|
||||
export interface ServiceCreateTeamRequest {
|
||||
name: string
|
||||
}
|
||||
|
||||
export interface ServiceGetUserTeamsRequest {
|
||||
userId: string
|
||||
pagination: z.infer<typeof paginationParamsSchema>
|
||||
}
|
||||
|
||||
export interface ServiceJoinTeamRequest {
|
||||
teamId: string
|
||||
userId: string
|
||||
}
|
||||
|
||||
export interface ServiceGetMeRequest {
|
||||
teamId: string
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
user: any
|
||||
}
|
||||
|
||||
export interface ServiceGetTeamMembersRequest {
|
||||
teamId: string
|
||||
includeAgents?: boolean
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
import { z } from 'zod'
|
||||
|
||||
export type FileNode = {
|
||||
name: string
|
||||
id: string
|
||||
size: number
|
||||
children: FileNode[]
|
||||
type: string
|
||||
mediaType?: string
|
||||
}
|
||||
|
||||
export const fileNodeSchema: z.ZodType<FileNode> = z.lazy(() =>
|
||||
z.object({
|
||||
name: z.string(),
|
||||
id: z.string(),
|
||||
size: z.number(),
|
||||
children: z.array(fileNodeSchema),
|
||||
type: z.string(),
|
||||
mediaType: z.string().optional(),
|
||||
}),
|
||||
)
|
||||
|
||||
export const createUploadTaskRequestSchema = z.object({
|
||||
parentId: z.string(),
|
||||
files: z.array(fileNodeSchema),
|
||||
})
|
||||
export type CreateUploadTaskRequest = z.infer<typeof createUploadTaskRequestSchema>
|
||||
|
||||
export const presignedUrlSchema = z.object({
|
||||
id: z.string(),
|
||||
fileId: z.string(),
|
||||
url: z.string(),
|
||||
})
|
||||
export type PresignedUrl = z.infer<typeof presignedUrlSchema>
|
||||
|
||||
export const createUploadTaskResponseSchema = z.object({
|
||||
taskId: z.string(),
|
||||
presignedUrls: z.array(presignedUrlSchema),
|
||||
})
|
||||
export type CreateUploadTaskResponse = z.infer<typeof createUploadTaskResponseSchema>
|
||||
|
||||
export const confirmFileUploadRequestSchema = z.object({
|
||||
fileId: z.string(),
|
||||
errorMessage: z.string().optional(),
|
||||
})
|
||||
export type ConfirmFileUploadRequest = z.infer<typeof confirmFileUploadRequestSchema>
|
||||
|
||||
export const taskInfoSchema = z.object({
|
||||
id: z.string(),
|
||||
name: z.string(),
|
||||
total: z.number(),
|
||||
uploaded: z.number(),
|
||||
createdAt: z.string(),
|
||||
})
|
||||
export type TaskInfo = z.infer<typeof taskInfoSchema>
|
||||
|
||||
export const localUploadQuerySchema = z.object({
|
||||
bucket: z.string(),
|
||||
key: z.string(),
|
||||
Signature: z.string(),
|
||||
})
|
||||
export type LocalUploadQuery = z.infer<typeof localUploadQuerySchema>
|
||||
|
||||
export const localUploadBodySchema = z.object({
|
||||
file: z.instanceof(File),
|
||||
})
|
||||
export type LocalUploadBody = z.infer<typeof localUploadBodySchema>
|
||||
@@ -0,0 +1,15 @@
|
||||
import { z } from 'zod'
|
||||
|
||||
export const userMetadataItemSchema = z.object({
|
||||
key: z.string(),
|
||||
value: z.unknown(),
|
||||
})
|
||||
export type UserMetadataItem = z.infer<typeof userMetadataItemSchema>
|
||||
|
||||
export const updateUserMetadataRequestSchema = z.object({
|
||||
value: z.unknown(),
|
||||
})
|
||||
export type UpdateUserMetadataRequest = z.infer<typeof updateUserMetadataRequestSchema>
|
||||
|
||||
export const listUserMetadataResponseSchema = z.array(userMetadataItemSchema)
|
||||
export type ListUserMetadataResponse = z.infer<typeof listUserMetadataResponseSchema>
|
||||
@@ -0,0 +1,24 @@
|
||||
import { z } from 'zod'
|
||||
|
||||
export const createVersionStackRequestSchema = z.object({
|
||||
fileIds: z.array(z.string()),
|
||||
})
|
||||
export type CreateVersionStackRequest = z.infer<typeof createVersionStackRequestSchema>
|
||||
|
||||
export interface CreateVersionStackParams {
|
||||
fileIds: string[]
|
||||
projectId: string
|
||||
creatorId: string
|
||||
}
|
||||
|
||||
export const changeStackFileVersionRequestSchema = z.object({
|
||||
fileId: z.string(),
|
||||
beforeId: z.string(),
|
||||
})
|
||||
export type ChangeStackFileVersionRequest = z.infer<typeof changeStackFileVersionRequestSchema>
|
||||
|
||||
export interface ChangeStackFileVersionParams {
|
||||
stackId: string
|
||||
fileId: string
|
||||
beforeId: string
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
import * as fs from 'fs'
|
||||
import * as path from 'path'
|
||||
import * as dotenv from 'dotenv'
|
||||
import { expand as dotenvExpand } from 'dotenv-expand'
|
||||
|
||||
export type Env = { [key: string]: string | undefined }
|
||||
export type LoadedEnvFiles = Array<{
|
||||
path: string
|
||||
contents: string
|
||||
env: Env
|
||||
}>
|
||||
|
||||
let initialEnv: Env | undefined = undefined
|
||||
let combinedEnv: Env | undefined = undefined
|
||||
let cachedLoadedEnvFiles: LoadedEnvFiles = []
|
||||
|
||||
type Log = {
|
||||
info: (...args: unknown[]) => void
|
||||
error: (...args: unknown[]) => void
|
||||
}
|
||||
|
||||
function replaceProcessEnv(sourceEnv: Env) {
|
||||
Object.keys(process.env).forEach((key) => {
|
||||
if (sourceEnv[key] === undefined || sourceEnv[key] === '') {
|
||||
delete process.env[key]
|
||||
}
|
||||
})
|
||||
|
||||
Object.entries(sourceEnv).forEach(([key, value]) => {
|
||||
process.env[key] = value
|
||||
})
|
||||
}
|
||||
|
||||
export function processEnv(loadedEnvFiles: LoadedEnvFiles, dir?: string, log: Log = console) {
|
||||
if (!initialEnv) {
|
||||
initialEnv = Object.assign({}, process.env)
|
||||
}
|
||||
|
||||
const origEnv = Object.assign({}, initialEnv)
|
||||
const parsed: dotenv.DotenvParseOutput = {}
|
||||
|
||||
for (const envFile of loadedEnvFiles) {
|
||||
try {
|
||||
const result: dotenv.DotenvConfigOutput = {}
|
||||
result.parsed = dotenv.parse(envFile.contents)
|
||||
|
||||
const expandResult = dotenvExpand(result)
|
||||
const parsedResult = expandResult.parsed
|
||||
if (parsedResult) {
|
||||
for (const key of Object.keys(parsedResult)) {
|
||||
if (typeof parsed[key] === 'undefined' && typeof origEnv[key] === 'undefined') {
|
||||
parsed[key] = parsedResult[key]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
envFile.env = result.parsed || {}
|
||||
} catch (err) {
|
||||
log.error(`Failed to load env from ${path.join(dir || '', envFile.path)}`, err)
|
||||
}
|
||||
}
|
||||
|
||||
return Object.assign(process.env, parsed)
|
||||
}
|
||||
|
||||
export function loadEnvConfig(
|
||||
dir: string,
|
||||
dev?: boolean,
|
||||
log: Log = console,
|
||||
): {
|
||||
combinedEnv: Env
|
||||
loadedEnvFiles: LoadedEnvFiles
|
||||
} {
|
||||
if (!initialEnv) {
|
||||
initialEnv = Object.assign({}, process.env)
|
||||
}
|
||||
|
||||
if (combinedEnv) {
|
||||
return { combinedEnv, loadedEnvFiles: cachedLoadedEnvFiles }
|
||||
}
|
||||
|
||||
replaceProcessEnv(initialEnv)
|
||||
cachedLoadedEnvFiles = []
|
||||
|
||||
const isTest = process.env.NODE_ENV === 'test'
|
||||
const mode = isTest ? 'test' : dev ? 'development' : 'production'
|
||||
const dotenvFiles = [
|
||||
`.env.${mode}.local`,
|
||||
mode !== 'test' && `.env.local`,
|
||||
`.env.${mode}`,
|
||||
'.env',
|
||||
].filter(Boolean) as string[]
|
||||
|
||||
for (const envFile of dotenvFiles) {
|
||||
const dotEnvPath = path.join(dir, envFile)
|
||||
|
||||
try {
|
||||
const stats = fs.statSync(dotEnvPath)
|
||||
|
||||
if (!stats.isFile() && !stats.isFIFO()) {
|
||||
continue
|
||||
}
|
||||
|
||||
const contents = fs.readFileSync(dotEnvPath, 'utf8')
|
||||
cachedLoadedEnvFiles.push({
|
||||
path: envFile,
|
||||
contents,
|
||||
env: {},
|
||||
})
|
||||
} catch (err: unknown) {
|
||||
if (err && typeof err === 'object' && 'code' in err && err.code !== 'ENOENT') {
|
||||
log.error(`Failed to load env from ${envFile}`, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
combinedEnv = processEnv(cachedLoadedEnvFiles, dir, log)
|
||||
|
||||
return { combinedEnv, loadedEnvFiles: cachedLoadedEnvFiles }
|
||||
}
|
||||
@@ -0,0 +1,164 @@
|
||||
|
||||
/* !!! 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 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 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
|
||||
@@ -0,0 +1,188 @@
|
||||
|
||||
/* !!! 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 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 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
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,147 @@
|
||||
|
||||
/* !!! 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',
|
||||
removed: 'removed'
|
||||
} as const
|
||||
|
||||
export type AssetStatus = (typeof AssetStatus)[keyof typeof AssetStatus]
|
||||
|
||||
|
||||
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',
|
||||
ai_transcription: 'ai_transcription',
|
||||
chat: 'chat',
|
||||
ai_embedding: 'ai_embedding'
|
||||
} 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',
|
||||
transcription: 'transcription'
|
||||
} 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
@@ -0,0 +1,563 @@
|
||||
|
||||
/* !!! 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',
|
||||
Skill: 'Skill',
|
||||
TeamMember: 'TeamMember',
|
||||
Project: 'Project',
|
||||
ProjectMember: 'ProjectMember',
|
||||
ShareLink: 'ShareLink',
|
||||
Asset: 'Asset',
|
||||
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'
|
||||
} 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 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',
|
||||
key: 'key',
|
||||
type: 'type',
|
||||
mediaType: 'mediaType',
|
||||
fileCount: 'fileCount',
|
||||
sizeByte: 'sizeByte',
|
||||
status: 'status',
|
||||
transcodeTaskId: 'transcodeTaskId',
|
||||
media: 'media',
|
||||
removed: 'removed',
|
||||
deletedAt: 'deletedAt',
|
||||
sortIndex: 'sortIndex',
|
||||
createdAt: 'createdAt',
|
||||
updatedAt: 'updatedAt',
|
||||
parentId: 'parentId',
|
||||
targetId: 'targetId',
|
||||
creatorId: 'creatorId',
|
||||
taskId: 'taskId',
|
||||
projectId: 'projectId'
|
||||
} as const
|
||||
|
||||
export type AssetScalarFieldEnum = (typeof AssetScalarFieldEnum)[keyof typeof AssetScalarFieldEnum]
|
||||
|
||||
|
||||
export const AssetMetadataValueScalarFieldEnum = {
|
||||
id: 'id',
|
||||
assetId: 'assetId',
|
||||
fieldId: 'fieldId',
|
||||
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',
|
||||
isAi: 'isAi',
|
||||
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',
|
||||
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 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]
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
|
||||
/* !!! 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/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/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 './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
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user