-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathschema.ts
More file actions
407 lines (368 loc) · 16 KB
/
schema.ts
File metadata and controls
407 lines (368 loc) · 16 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
import { sql } from "drizzle-orm";
import {
boolean,
integer,
json,
pgEnum,
pgTable,
text,
timestamp,
varchar,
} from "drizzle-orm/pg-core";
const uuid = sql`uuid_generate_v4()`;
// ============================================================================
// Enums
// ============================================================================
export const orgRoleEnum = pgEnum("org_role", ["owner", "reviewer", "contributor"]);
export const prStatusEnum = pgEnum("pr_status", ["open", "approved", "rejected", "merged"]);
export const auditActionEnum = pgEnum("audit_action", [
"org_created",
"org_member_invited",
"org_member_removed",
"workspace_created",
"workspace_cloned",
"workspace_version_created",
"pr_created",
"pr_approved",
"pr_rejected",
"pr_merged",
"secret_created",
"secret_updated",
"secret_deleted",
]);
// ============================================================================
// Organizations
// ============================================================================
export const organizations = pgTable("organization", {
id: text("id").primaryKey().default(uuid).notNull(),
name: varchar("name").notNull(),
slug: varchar("slug").notNull().unique(),
description: varchar("description"),
ownerId: varchar("owner_id").notNull(),
createdAt: timestamp("created_at").defaultNow().notNull(),
updatedAt: timestamp("updated_at"),
});
// Member invitation status
export const memberStatusEnum = pgEnum("member_status", ["pending", "accepted", "rejected"]);
export const organizationMembers = pgTable("organization_member", {
id: text("id").primaryKey().default(uuid).notNull(),
organizationId: text("organization_id").notNull().references(() => organizations.id, { onDelete: "cascade" }),
userId: varchar("user_id").notNull(),
email: varchar("email").notNull(),
role: orgRoleEnum("role").notNull().default("contributor"),
status: memberStatusEnum("status").notNull().default("pending"),
invitedAt: timestamp("invited_at").defaultNow().notNull(),
joinedAt: timestamp("joined_at"),
});
// ============================================================================
// Workspaces (Git-like repositories for workflows)
// ============================================================================
export const workspaces = pgTable("workspace", {
id: text("id").primaryKey().default(uuid).notNull(),
name: varchar("name").notNull(),
description: varchar("description"),
organizationId: text("organization_id").notNull().references(() => organizations.id, { onDelete: "cascade" }),
// For forked workspaces, track the parent
parentWorkspaceId: text("parent_workspace_id"),
forkedFromVersion: integer("forked_from_version"),
forkedByUserId: varchar("forked_by_user_id"),
// Current version number (incremented on each merge/update)
currentVersion: integer("current_version").notNull().default(1),
createdAt: timestamp("created_at").defaultNow().notNull(),
updatedAt: timestamp("updated_at"),
});
export const workspaceVersions = pgTable("workspace_version", {
id: text("id").primaryKey().default(uuid).notNull(),
workspaceId: text("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
version: integer("version").notNull(),
// The workflow content at this version
content: json("content").$type<{
nodes: Array<{
id: string;
type: string;
position: { x: number; y: number };
data: Record<string, unknown>;
}>;
edges: Array<{
id: string;
source: string;
target: string;
sourceHandle?: string;
targetHandle?: string;
}>;
}>(),
message: varchar("message"), // Commit message
createdByUserId: varchar("created_by_user_id").notNull(),
createdAt: timestamp("created_at").defaultNow().notNull(),
});
// ============================================================================
// Pull Requests
// ============================================================================
export const pullRequests = pgTable("pull_request", {
id: text("id").primaryKey().default(uuid).notNull(),
title: varchar("title").notNull(),
description: varchar("description"),
// Source workspace (the fork)
sourceWorkspaceId: text("source_workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
sourceVersion: integer("source_version").notNull(),
// Target workspace (the main workspace)
targetWorkspaceId: text("target_workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
targetVersion: integer("target_version").notNull(),
status: prStatusEnum("status").notNull().default("open"),
createdByUserId: varchar("created_by_user_id").notNull(),
reviewedByUserId: varchar("reviewed_by_user_id"),
reviewedAt: timestamp("reviewed_at"),
mergedAt: timestamp("merged_at"),
createdAt: timestamp("created_at").defaultNow().notNull(),
updatedAt: timestamp("updated_at"),
});
export const pullRequestComments = pgTable("pull_request_comment", {
id: text("id").primaryKey().default(uuid).notNull(),
pullRequestId: text("pull_request_id").notNull().references(() => pullRequests.id, { onDelete: "cascade" }),
userId: varchar("user_id").notNull(),
content: text("content").notNull(),
// Optional: reference a specific node in the diff
nodeId: varchar("node_id"),
createdAt: timestamp("created_at").defaultNow().notNull(),
updatedAt: timestamp("updated_at"),
});
// ============================================================================
// Workspace Secrets (Isolated credentials per workspace/user)
// ============================================================================
export const workspaceSecrets = pgTable("workspace_secret", {
id: text("id").primaryKey().default(uuid).notNull(),
workspaceId: text("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
userId: varchar("user_id").notNull(),
// Opaque reference ID used in workflow nodes (e.g., "cred_abc123")
credentialRef: varchar("credential_ref").notNull(),
// Reference to the actual credential in the credentials table
credentialId: text("credential_id").references(() => credentials.id, { onDelete: "set null" }),
// Human-readable name for the secret binding
name: varchar("name").notNull(),
// Provider type (google, openai, etc.)
provider: varchar("provider").notNull(),
// Whether this is bound to an actual credential
isBound: boolean("is_bound").notNull().default(false),
createdAt: timestamp("created_at").defaultNow().notNull(),
updatedAt: timestamp("updated_at"),
});
// ============================================================================
// Audit Logs
// ============================================================================
export const auditLogs = pgTable("audit_log", {
id: text("id").primaryKey().default(uuid).notNull(),
organizationId: text("organization_id").references(() => organizations.id, { onDelete: "set null" }),
workspaceId: text("workspace_id").references(() => workspaces.id, { onDelete: "set null" }),
pullRequestId: text("pull_request_id").references(() => pullRequests.id, { onDelete: "set null" }),
userId: varchar("user_id").notNull(),
action: auditActionEnum("action").notNull(),
details: json("details").$type<Record<string, unknown>>(),
ipAddress: varchar("ip_address"),
userAgent: varchar("user_agent"),
createdAt: timestamp("created_at").defaultNow().notNull(),
});
// ============================================================================
// Workflows (Updated to support workspace integration)
// ============================================================================
// Workflows table - stores the workflow definition as JSON
export const workflows = pgTable("workflow", {
id: text("id").primaryKey().default(uuid).notNull(),
name: varchar("name").notNull(),
description: varchar("description"),
createdAt: timestamp("created_at").defaultNow().notNull(),
updatedAt: timestamp("updated_at"),
// Stores the React Flow nodes and edges
content: json("content").$type<{
nodes: Array<{
id: string;
type: string;
position: { x: number; y: number };
data: Record<string, unknown>;
}>;
edges: Array<{
id: string;
source: string;
target: string;
}>;
}>(),
userId: varchar("user_id").notNull(),
// Whether the workflow is active/enabled
enabled: boolean("enabled").notNull().default(true),
// Optional: link to a workspace (for collaborative workflows)
workspaceId: text("workspace_id").references(() => workspaces.id, { onDelete: "set null" }),
});
// Workflow executions log - stores execution history
export const workflowExecutions = pgTable("workflow_execution", {
id: text("id").primaryKey().default(uuid).notNull(),
workflowId: text("workflow_id").notNull(),
userId: varchar("user_id").notNull(),
status: varchar("status").notNull().default("pending"), // pending, running, completed, failed
startedAt: timestamp("started_at").defaultNow().notNull(),
completedAt: timestamp("completed_at"),
// Input data from the trigger
triggerInput: json("trigger_input"),
// Final output or error
result: json("result"),
// Detailed step-by-step execution log
executionLog: json("execution_log").$type<Array<{
nodeId: string;
nodeType: string;
status: "success" | "error";
input: unknown;
output: unknown;
error?: string;
timestamp: string;
}>>(),
});
// ============================================================================
// Credentials (for OAuth and API keys)
// ============================================================================
/**
* Provider credential types
*/
type ProviderCredentials =
| { type: "oauth2"; accessToken: string; refreshToken: string; expiresAt: number; tokenType: string; scope: string[] }
| { type: "api_key"; apiKey: string }
| { type: "service_account"; clientEmail: string; privateKey: string; projectId: string };
/**
* Stores credentials for providers (OAuth, API keys, etc.)
* Note: In production, credentials should be encrypted at rest
*/
export const credentials = pgTable("credential", {
id: text("id").primaryKey().default(uuid).notNull(),
userId: varchar("user_id").notNull(),
provider: varchar("provider").notNull(), // google, openai, email, etc.
name: varchar("name").notNull(),
credentials: json("credentials").$type<ProviderCredentials>().notNull(),
createdAt: timestamp("created_at").defaultNow().notNull(),
updatedAt: timestamp("updated_at"),
});
// ============================================================================
// AI Assistant (Chat Interface)
// ============================================================================
export const assistantConversations = pgTable("assistant_conversation", {
id: text("id").primaryKey().default(uuid).notNull(),
userId: varchar("user_id").notNull(),
title: varchar("title").notNull().default("New Conversation"),
createdAt: timestamp("created_at").defaultNow().notNull(),
updatedAt: timestamp("updated_at"),
});
export const assistantMessages = pgTable("assistant_message", {
id: text("id").primaryKey().default(uuid).notNull(),
conversationId: text("conversation_id").notNull()
.references(() => assistantConversations.id, { onDelete: "cascade" }),
role: varchar("role").notNull(), // "user" | "assistant"
content: text("content").notNull(),
metadata: json("metadata").$type<Record<string, unknown>>(),
createdAt: timestamp("created_at").defaultNow().notNull(),
});
// ============================================================================
// x402 Smart Contracts Library
// ============================================================================
// Contract template categories
export const contractCategoryEnum = pgEnum("contract_category", [
"x402-settlement",
"x402-hook",
"token",
"nft",
]);
// Networks for contract deployment
export const cronosNetworkEnum = pgEnum("cronos_network", [
"cronos_mainnet",
"cronos_testnet",
]);
// Contract templates (Settlement Router, hooks, etc.)
export const contractTemplates = pgTable("contract_template", {
id: text("id").primaryKey().default(uuid).notNull(),
name: varchar("name").notNull(),
description: text("description"),
category: contractCategoryEnum("category").notNull(),
soliditySourceCode: text("solidity_source_code").notNull(),
abi: json("abi").$type<object[]>(),
constructorParams: json("constructor_params").$type<Array<{
name: string;
type: string;
description: string;
required: boolean;
}>>(),
createdAt: timestamp("created_at").defaultNow().notNull(),
});
// User deployed contracts
export const userContracts = pgTable("user_contract", {
id: text("id").primaryKey().default(uuid).notNull(),
userId: varchar("user_id").notNull(),
templateId: text("template_id").references(() => contractTemplates.id),
name: varchar("name").notNull(),
contractAddress: varchar("contract_address", { length: 42 }).notNull(),
network: cronosNetworkEnum("network").notNull(),
constructorArgs: json("constructor_args").$type<Record<string, unknown>>(),
deployedSourceCode: text("deployed_source_code").notNull(),
abi: json("abi").$type<object[]>().notNull(),
transactionHash: varchar("transaction_hash", { length: 66 }).notNull(),
deployedAt: timestamp("deployed_at").defaultNow().notNull(),
});
// User DApps (built on top of contracts)
export const userDapps = pgTable("user_dapp", {
id: text("id").primaryKey().default(uuid).notNull(),
userId: varchar("user_id").notNull(),
contractId: text("contract_id").references(() => userContracts.id),
name: varchar("name").notNull(),
slug: varchar("slug").notNull().unique(),
description: text("description"),
uiConfig: json("ui_config").$type<{
templateType: string;
theme: Record<string, string>;
branding: Record<string, string>;
}>(),
isPublished: boolean("is_published").notNull().default(false),
createdAt: timestamp("created_at").defaultNow().notNull(),
updatedAt: timestamp("updated_at"),
});
// ============================================================================
// User Profile
// ============================================================================
export const profile = pgTable("profile", {
id: text("id").primaryKey().notNull(),
customerId: text("customer_id"),
subscriptionId: text("subscription_id"),
productId: text("product_id"),
onboardedAt: timestamp("onboarded_at"),
});
// ============================================================================
// Legacy Tables (keeping for migration)
// ============================================================================
// Legacy projects table - keeping for migration, will be removed
export const projects = pgTable("project", {
id: text("id").primaryKey().default(uuid).notNull(),
name: varchar("name").notNull(),
transcriptionModel: varchar("transcription_model").notNull(),
visionModel: varchar("vision_model").notNull(),
createdAt: timestamp("created_at").defaultNow().notNull(),
updatedAt: timestamp("updated_at"),
content: json("content"),
userId: varchar("user_id").notNull(),
image: varchar("image"),
members: text("members").array(),
welcomeProject: boolean("demo_project").notNull().default(false),
});
// ============================================================================
// User Configuration (Per-user wallet keys, API keys)
// ============================================================================
/**
* Stores per-user configuration including wallet private keys
* for autonomous Cronos payments and optional API key overrides.
*/
export const userConfigs = pgTable("user_config", {
id: text("id").primaryKey().default(uuid).notNull(),
userId: varchar("user_id").notNull().unique(),
// Encrypted wallet private key for Cronos payments
walletPrivateKey: text("wallet_private_key"),
// Wallet address (derived from private key, for display)
walletAddress: varchar("wallet_address"),
// Optional: user's own OpenAI API key
openaiApiKey: text("openai_api_key"),
// Optional: user's own Anthropic API key
anthropicApiKey: text("anthropic_api_key"),
createdAt: timestamp("created_at").defaultNow().notNull(),
updatedAt: timestamp("updated_at"),
});