@kaloma-ai/framework-api 0.0.0-stage → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,209 @@
1
+ import {
2
+ buildCatalog,
3
+ createApp,
4
+ createAuth,
5
+ createAuthz,
6
+ createBrandService,
7
+ createConnections,
8
+ createDb,
9
+ createLocalFileStorage,
10
+ createOperations,
11
+ createSettings,
12
+ frameworkMigrationsDir,
13
+ frameworkSettings,
14
+ loadBrand,
15
+ loadConfig,
16
+ resetCompanyCache,
17
+ runMigrations
18
+ } from "./chunk-DI2XKT4C.js";
19
+ import "./chunk-R6W6GTUR.js";
20
+
21
+ // src/test/harness.ts
22
+ import { mkdtempSync, writeFileSync } from "fs";
23
+ import { tmpdir } from "os";
24
+ import { join } from "path";
25
+ import { expect } from "vitest";
26
+ import { sql } from "drizzle-orm";
27
+
28
+ // src/test/scriptedEmail.ts
29
+ var scriptedMail = [];
30
+ var scriptedEmail = {
31
+ kind: "email",
32
+ key: "scripted",
33
+ label: "Scripted (tests)",
34
+ fields: [{ key: "fail", label: "Fail", type: "boolean" }],
35
+ create: ({ config }) => ({
36
+ async send(email) {
37
+ if (config.fail === true) throw new Error("The scripted mail server refused the message");
38
+ scriptedMail.push(email);
39
+ }
40
+ })
41
+ };
42
+
43
+ // src/test/scriptedLlm.ts
44
+ import { MockLanguageModelV4 } from "ai/test";
45
+ var scriptedLlm = {
46
+ kind: "llm",
47
+ key: "scripted",
48
+ label: "Scripted (tests)",
49
+ fields: [
50
+ { key: "model", label: "Model", type: "text", required: true },
51
+ { key: "reply", label: "Reply", type: "text" },
52
+ { key: "personalDataApproved", label: "Approved for personal data", type: "boolean" }
53
+ ],
54
+ create: ({ config }) => {
55
+ const reply = String(config.reply ?? "OK");
56
+ const usage = {
57
+ inputTokens: { total: 10, noCache: 10, cacheRead: void 0, cacheWrite: void 0 },
58
+ outputTokens: { total: 20, text: 20, reasoning: void 0 }
59
+ };
60
+ return new MockLanguageModelV4({
61
+ doGenerate: async () => {
62
+ if (reply === "FAIL") throw new Error("The scripted model failed");
63
+ return { content: [{ type: "text", text: reply }], finishReason: { unified: "stop", raw: void 0 }, usage, warnings: [] };
64
+ },
65
+ doStream: async () => ({
66
+ stream: new ReadableStream({
67
+ start(controller) {
68
+ controller.enqueue({ type: "text-start", id: "t" });
69
+ for (const part of reply.split(" ")) controller.enqueue({ type: "text-delta", id: "t", delta: `${part} ` });
70
+ controller.enqueue({ type: "text-end", id: "t" });
71
+ controller.enqueue({ type: "finish", finishReason: { unified: "stop", raw: void 0 }, usage });
72
+ controller.close();
73
+ }
74
+ })
75
+ })
76
+ });
77
+ }
78
+ };
79
+
80
+ // src/test/testDb.ts
81
+ import postgres from "postgres";
82
+ var testDatabaseUrl = process.env.TEST_DATABASE_URL;
83
+ async function createTestDatabase() {
84
+ const adminUrl = new URL(testDatabaseUrl);
85
+ const name = `appai_test_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`;
86
+ const admin = postgres(adminUrl.toString(), { max: 1 });
87
+ await admin.unsafe(`create database "${name}"`);
88
+ const url = new URL(adminUrl);
89
+ url.pathname = `/${name}`;
90
+ const database = createDb(url.toString());
91
+ await runMigrations(database.db, frameworkMigrationsDir());
92
+ return {
93
+ ...database,
94
+ url: url.toString(),
95
+ async drop() {
96
+ await database.close();
97
+ await admin.unsafe(`drop database "${name}" with (force)`);
98
+ await admin.end();
99
+ }
100
+ };
101
+ }
102
+
103
+ // src/test/harness.ts
104
+ var ORIGIN = "http://localhost:8080";
105
+ var PASSWORD = "a-long-enough-password";
106
+ var ADMIN = "boss@example.com";
107
+ async function createHarness(appAuthz, options = {}) {
108
+ resetCompanyCache();
109
+ const testDb = await createTestDatabase();
110
+ if (options.appMigrations) await runMigrations(testDb.db, options.appMigrations, "__app_migrations");
111
+ const outbox = [];
112
+ const email = { send: async (e) => void outbox.push(e) };
113
+ const config = loadConfig({
114
+ DATABASE_URL: testDb.url,
115
+ AUTH_SECRET: "t".repeat(40),
116
+ INITIAL_ADMIN_EMAIL: ADMIN,
117
+ NODE_ENV: "test"
118
+ });
119
+ const loadedBrand = loadBrand("/nonexistent", "test");
120
+ const settings = createSettings({ db: testDb.db, definitions: [...frameworkSettings(loadedBrand), ...options.settings ?? []] });
121
+ await settings.load();
122
+ const filesDir = mkdtempSync(join(tmpdir(), "appai-files-"));
123
+ const storage = createLocalFileStorage(filesDir);
124
+ const connections = createConnections({ db: testDb.db, config: { ...config, FILES_DIR: filesDir }, slots: options.connections, providers: [scriptedLlm, scriptedEmail], fetch: options.fetch });
125
+ const brand = createBrandService({ loaded: loadedBrand, settings, storage });
126
+ const appName = () => settings.get("app.name");
127
+ const authz = createAuthz({ db: testDb.db, catalog: buildCatalog(appAuthz), externalAccessDays: config.EXTERNAL_ACCESS_DAYS });
128
+ const auth = createAuth({ db: testDb.db, config, email, authz, appName });
129
+ const dir = mkdtempSync(join(tmpdir(), "appai-backups-"));
130
+ const ops = createOperations({
131
+ db: testDb.db,
132
+ config: { ...config, BACKUP_DIR: dir, ALERT_EMAILS: ["ops@example.com"] },
133
+ email,
134
+ appName,
135
+ settings,
136
+ connections,
137
+ // pg_dump is not installed on every developer machine: the tests use a stand-in.
138
+ dump: async (_url, file) => writeFileSync(file, "dump")
139
+ });
140
+ const app = createApp({
141
+ appName,
142
+ db: testDb.db,
143
+ auth,
144
+ authz,
145
+ email,
146
+ publicUrl: config.PUBLIC_URL,
147
+ brand,
148
+ settings,
149
+ storage,
150
+ connections,
151
+ ops,
152
+ checkDatabase: async () => {
153
+ await testDb.db.execute(sql`select 1`);
154
+ }
155
+ });
156
+ let requests = 0;
157
+ const nextAddress = () => `10.${++requests >> 16 & 255}.${requests >> 8 & 255}.${requests & 255}`;
158
+ async function call(path, opts = {}) {
159
+ return app.request(path, {
160
+ method: opts.method ?? (opts.body ? "POST" : "GET"),
161
+ headers: {
162
+ origin: ORIGIN,
163
+ "x-forwarded-for": nextAddress(),
164
+ ...opts.body ? { "content-type": "application/json" } : {},
165
+ ...opts.cookie ? { cookie: opts.cookie } : {},
166
+ ...opts.apiKey ? { "x-api-key": opts.apiKey } : {}
167
+ },
168
+ body: opts.body ? JSON.stringify(opts.body) : void 0
169
+ });
170
+ }
171
+ const cookieOf = (res) => res.headers.getSetCookie().map((c) => c.split(";")[0]).join("; ");
172
+ const lastLink = (to) => {
173
+ const mail = [...outbox].reverse().find((m) => m.to === to);
174
+ if (!mail) throw new Error(`no email for ${to}`);
175
+ const url = mail.text.match(/https?:\/\/\S+/)[0];
176
+ return { mail, path: url.replace(ORIGIN, ""), url };
177
+ };
178
+ async function signUp(address, name = "Someone", invitationId) {
179
+ const callbackURL = invitationId ? `/accept-invitation?invitation=${invitationId}` : "/";
180
+ return call("/api/auth/sign-up/email", { body: { email: address, password: PASSWORD, name, callbackURL } });
181
+ }
182
+ async function verifyAndSignIn(address) {
183
+ const res = await call(lastLink(address).path);
184
+ expect(res.status).toBeLessThan(400);
185
+ const signIn = await call("/api/auth/sign-in/email", { body: { email: address, password: PASSWORD } });
186
+ expect(signIn.status).toBe(200);
187
+ return cookieOf(signIn);
188
+ }
189
+ async function setUpAdmin() {
190
+ expect((await signUp(ADMIN, "Boss")).status).toBe(200);
191
+ return verifyAndSignIn(ADMIN);
192
+ }
193
+ async function addUser(adminCookie, address, roles) {
194
+ const invite = await call("/api/users/invitations", { cookie: adminCookie, body: { email: address, roles } });
195
+ expect(invite.status, await invite.clone().text()).toBe(201);
196
+ const { id } = await invite.json();
197
+ expect((await signUp(address, address.split("@")[0], id)).status).toBe(200);
198
+ const cookie = await verifyAndSignIn(address);
199
+ return { cookie, id };
200
+ }
201
+ return { testDb, ops, settings, storage, connections, brand, backupDir: dir, config, email, app, auth, authz, outbox, call, cookieOf, lastLink, signUp, verifyAndSignIn, setUpAdmin, addUser };
202
+ }
203
+ export {
204
+ ADMIN,
205
+ ORIGIN,
206
+ PASSWORD,
207
+ createHarness,
208
+ testDatabaseUrl
209
+ };
@@ -0,0 +1,92 @@
1
+ CREATE TABLE "account" (
2
+ "id" text PRIMARY KEY NOT NULL,
3
+ "account_id" text NOT NULL,
4
+ "provider_id" text NOT NULL,
5
+ "user_id" text NOT NULL,
6
+ "access_token" text,
7
+ "refresh_token" text,
8
+ "id_token" text,
9
+ "access_token_expires_at" timestamp,
10
+ "refresh_token_expires_at" timestamp,
11
+ "scope" text,
12
+ "password" text,
13
+ "created_at" timestamp DEFAULT now() NOT NULL,
14
+ "updated_at" timestamp NOT NULL
15
+ );
16
+ --> statement-breakpoint
17
+ CREATE TABLE "invitation" (
18
+ "id" text PRIMARY KEY NOT NULL,
19
+ "organization_id" text NOT NULL,
20
+ "email" text NOT NULL,
21
+ "role" text,
22
+ "status" text DEFAULT 'pending' NOT NULL,
23
+ "expires_at" timestamp NOT NULL,
24
+ "created_at" timestamp DEFAULT now() NOT NULL,
25
+ "inviter_id" text NOT NULL
26
+ );
27
+ --> statement-breakpoint
28
+ CREATE TABLE "member" (
29
+ "id" text PRIMARY KEY NOT NULL,
30
+ "organization_id" text NOT NULL,
31
+ "user_id" text NOT NULL,
32
+ "role" text DEFAULT 'member' NOT NULL,
33
+ "created_at" timestamp NOT NULL
34
+ );
35
+ --> statement-breakpoint
36
+ CREATE TABLE "organization" (
37
+ "id" text PRIMARY KEY NOT NULL,
38
+ "name" text NOT NULL,
39
+ "slug" text NOT NULL,
40
+ "logo" text,
41
+ "created_at" timestamp NOT NULL,
42
+ "metadata" text,
43
+ CONSTRAINT "organization_slug_unique" UNIQUE("slug")
44
+ );
45
+ --> statement-breakpoint
46
+ CREATE TABLE "session" (
47
+ "id" text PRIMARY KEY NOT NULL,
48
+ "expires_at" timestamp NOT NULL,
49
+ "token" text NOT NULL,
50
+ "created_at" timestamp DEFAULT now() NOT NULL,
51
+ "updated_at" timestamp NOT NULL,
52
+ "ip_address" text,
53
+ "user_agent" text,
54
+ "user_id" text NOT NULL,
55
+ "active_organization_id" text,
56
+ CONSTRAINT "session_token_unique" UNIQUE("token")
57
+ );
58
+ --> statement-breakpoint
59
+ CREATE TABLE "user" (
60
+ "id" text PRIMARY KEY NOT NULL,
61
+ "name" text NOT NULL,
62
+ "email" text NOT NULL,
63
+ "email_verified" boolean DEFAULT false NOT NULL,
64
+ "image" text,
65
+ "created_at" timestamp DEFAULT now() NOT NULL,
66
+ "updated_at" timestamp DEFAULT now() NOT NULL,
67
+ CONSTRAINT "user_email_unique" UNIQUE("email")
68
+ );
69
+ --> statement-breakpoint
70
+ CREATE TABLE "verification" (
71
+ "id" text PRIMARY KEY NOT NULL,
72
+ "identifier" text NOT NULL,
73
+ "value" text NOT NULL,
74
+ "expires_at" timestamp NOT NULL,
75
+ "created_at" timestamp DEFAULT now() NOT NULL,
76
+ "updated_at" timestamp DEFAULT now() NOT NULL
77
+ );
78
+ --> statement-breakpoint
79
+ ALTER TABLE "account" ADD CONSTRAINT "account_user_id_user_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."user"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
80
+ ALTER TABLE "invitation" ADD CONSTRAINT "invitation_organization_id_organization_id_fk" FOREIGN KEY ("organization_id") REFERENCES "public"."organization"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
81
+ ALTER TABLE "invitation" ADD CONSTRAINT "invitation_inviter_id_user_id_fk" FOREIGN KEY ("inviter_id") REFERENCES "public"."user"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
82
+ ALTER TABLE "member" ADD CONSTRAINT "member_organization_id_organization_id_fk" FOREIGN KEY ("organization_id") REFERENCES "public"."organization"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
83
+ ALTER TABLE "member" ADD CONSTRAINT "member_user_id_user_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."user"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
84
+ ALTER TABLE "session" ADD CONSTRAINT "session_user_id_user_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."user"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
85
+ CREATE INDEX "account_userId_idx" ON "account" USING btree ("user_id");--> statement-breakpoint
86
+ CREATE INDEX "invitation_organizationId_idx" ON "invitation" USING btree ("organization_id");--> statement-breakpoint
87
+ CREATE INDEX "invitation_email_idx" ON "invitation" USING btree ("email");--> statement-breakpoint
88
+ CREATE INDEX "member_organizationId_idx" ON "member" USING btree ("organization_id");--> statement-breakpoint
89
+ CREATE INDEX "member_userId_idx" ON "member" USING btree ("user_id");--> statement-breakpoint
90
+ CREATE UNIQUE INDEX "organization_slug_uidx" ON "organization" USING btree ("slug");--> statement-breakpoint
91
+ CREATE INDEX "session_userId_idx" ON "session" USING btree ("user_id");--> statement-breakpoint
92
+ CREATE INDEX "verification_identifier_idx" ON "verification" USING btree ("identifier");
@@ -0,0 +1,54 @@
1
+ CREATE TABLE "apikey" (
2
+ "id" text PRIMARY KEY NOT NULL,
3
+ "config_id" text DEFAULT 'default' NOT NULL,
4
+ "name" text,
5
+ "start" text,
6
+ "reference_id" text NOT NULL,
7
+ "prefix" text,
8
+ "key" text NOT NULL,
9
+ "refill_interval" integer,
10
+ "refill_amount" integer,
11
+ "last_refill_at" timestamp,
12
+ "enabled" boolean DEFAULT true,
13
+ "rate_limit_enabled" boolean DEFAULT true,
14
+ "rate_limit_time_window" integer DEFAULT 60000,
15
+ "rate_limit_max" integer DEFAULT 100,
16
+ "request_count" integer DEFAULT 0,
17
+ "remaining" integer,
18
+ "last_request" timestamp,
19
+ "expires_at" timestamp,
20
+ "created_at" timestamp NOT NULL,
21
+ "updated_at" timestamp NOT NULL,
22
+ "permissions" text,
23
+ "metadata" text
24
+ );
25
+ --> statement-breakpoint
26
+ CREATE TABLE "audit_log" (
27
+ "id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
28
+ "at" timestamp DEFAULT now() NOT NULL,
29
+ "actor_user_id" text,
30
+ "actor_email" text,
31
+ "via_key_id" text,
32
+ "action" text NOT NULL,
33
+ "target" text,
34
+ "details" jsonb
35
+ );
36
+ --> statement-breakpoint
37
+ CREATE TABLE "custom_role" (
38
+ "key" text PRIMARY KEY NOT NULL,
39
+ "label" text NOT NULL,
40
+ "permissions" text[] NOT NULL,
41
+ "created_at" timestamp DEFAULT now() NOT NULL,
42
+ "updated_at" timestamp DEFAULT now() NOT NULL
43
+ );
44
+ --> statement-breakpoint
45
+ CREATE TABLE "user_access" (
46
+ "user_id" text PRIMARY KEY NOT NULL,
47
+ "expires_at" timestamp,
48
+ "deactivated_at" timestamp
49
+ );
50
+ --> statement-breakpoint
51
+ ALTER TABLE "user_access" ADD CONSTRAINT "user_access_user_id_user_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."user"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
52
+ CREATE INDEX "apikey_configId_idx" ON "apikey" USING btree ("config_id");--> statement-breakpoint
53
+ CREATE INDEX "apikey_referenceId_idx" ON "apikey" USING btree ("reference_id");--> statement-breakpoint
54
+ CREATE INDEX "apikey_key_idx" ON "apikey" USING btree ("key");
@@ -0,0 +1,10 @@
1
+ CREATE TABLE "backup_run" (
2
+ "id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
3
+ "started_at" timestamp DEFAULT now() NOT NULL,
4
+ "finished_at" timestamp,
5
+ "status" text NOT NULL,
6
+ "trigger" text NOT NULL,
7
+ "folder" text,
8
+ "size_bytes" bigint,
9
+ "error" text
10
+ );
@@ -0,0 +1,6 @@
1
+ CREATE TABLE "app_setting" (
2
+ "key" text PRIMARY KEY NOT NULL,
3
+ "value" jsonb NOT NULL,
4
+ "updated_at" timestamp DEFAULT now() NOT NULL,
5
+ "updated_by" text
6
+ );
@@ -0,0 +1,35 @@
1
+ CREATE TABLE "connection" (
2
+ "kind" text NOT NULL,
3
+ "id" text NOT NULL,
4
+ "label" text NOT NULL,
5
+ "provider" text NOT NULL,
6
+ "config" jsonb DEFAULT '{}'::jsonb NOT NULL,
7
+ "secrets" text,
8
+ "enabled" boolean DEFAULT true NOT NULL,
9
+ "last_test_at" timestamp,
10
+ "last_test_ok" boolean,
11
+ "last_test_message" text,
12
+ "created_at" timestamp DEFAULT now() NOT NULL,
13
+ "updated_at" timestamp DEFAULT now() NOT NULL,
14
+ "updated_by" text,
15
+ CONSTRAINT "connection_kind_id_pk" PRIMARY KEY("kind","id")
16
+ );
17
+ --> statement-breakpoint
18
+ CREATE TABLE "llm_call" (
19
+ "id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
20
+ "at" timestamp DEFAULT now() NOT NULL,
21
+ "connection_id" text NOT NULL,
22
+ "model" text NOT NULL,
23
+ "input_tokens" integer,
24
+ "output_tokens" integer,
25
+ "duration_ms" integer NOT NULL,
26
+ "status" text NOT NULL,
27
+ "error" text,
28
+ "user_id" text,
29
+ "feature" text
30
+ );
31
+ --> statement-breakpoint
32
+ ALTER TABLE "backup_run" ADD COLUMN "uploaded_at" timestamp;--> statement-breakpoint
33
+ ALTER TABLE "backup_run" ADD COLUMN "upload_encrypted" boolean;--> statement-breakpoint
34
+ ALTER TABLE "backup_run" ADD COLUMN "upload_error" text;--> statement-breakpoint
35
+ CREATE INDEX "llm_call_at_idx" ON "llm_call" USING btree ("at");
@@ -0,0 +1,19 @@
1
+ CREATE TABLE "user_group" (
2
+ "id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
3
+ "name" text NOT NULL,
4
+ "description" text DEFAULT '' NOT NULL,
5
+ "created_at" timestamp DEFAULT now() NOT NULL,
6
+ "updated_at" timestamp DEFAULT now() NOT NULL
7
+ );
8
+ --> statement-breakpoint
9
+ CREATE TABLE "user_group_member" (
10
+ "group_id" uuid NOT NULL,
11
+ "user_id" text NOT NULL,
12
+ "added_at" timestamp DEFAULT now() NOT NULL,
13
+ CONSTRAINT "user_group_member_group_id_user_id_pk" PRIMARY KEY("group_id","user_id")
14
+ );
15
+ --> statement-breakpoint
16
+ ALTER TABLE "user_group_member" ADD CONSTRAINT "user_group_member_group_id_user_group_id_fk" FOREIGN KEY ("group_id") REFERENCES "public"."user_group"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
17
+ ALTER TABLE "user_group_member" ADD CONSTRAINT "user_group_member_user_id_user_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."user"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
18
+ CREATE UNIQUE INDEX "user_group_name_lower_idx" ON "user_group" USING btree (lower("name"));--> statement-breakpoint
19
+ CREATE INDEX "user_group_member_user_idx" ON "user_group_member" USING btree ("user_id");