Compare commits

..

14 Commits

Author SHA1 Message Date
dswbx 7a046fa18e updated references 2025-07-07 08:39:21 +02:00
dswbx 786d1d1bd4 init media adapter refactoring 2025-07-05 18:12:55 +02:00
dswbx c384bf4dd4 remove unneeded vite dep 2025-07-05 14:17:26 +02:00
dswbx db2a994a01 Merge pull request #192 from bknd-io/feat/jsonv-refactor
feat/jsonv-refactor
2025-07-05 14:02:22 +02:00
dswbx 166ea4a71b removed @sinclair/typebox 2025-07-05 13:57:36 +02:00
dswbx 0d3bb3b7d6 added validator for rjsf, hook form via standard schema 2025-07-05 13:29:30 +02:00
dswbx cfbec5b6ea Merge remote-tracking branch 'origin/main' into feat/jsonv-refactor
# Conflicts:
#	bun.lock
2025-07-05 11:11:06 +02:00
dswbx 5143ee5726 updated schemas, fixed tests, skipping flow tests for now 2025-07-03 14:00:29 +02:00
dswbx fe1716ed01 fix secret schema 2025-07-02 17:59:38 +02:00
dswbx 0c31dcdb95 updated lock 2025-07-02 17:58:47 +02:00
dswbx 4cc0f8e172 Merge branch 'release/0.15' into feat/jsonv-refactor
# Conflicts:
#	app/build.ts
#	app/package.json
#	app/src/App.ts
#	app/src/adapter/cloudflare/storage/StorageR2Adapter.ts
#	app/src/auth/authenticate/Authenticator.ts
#	app/src/auth/authenticate/strategies/PasswordStrategy.ts
#	app/src/data/entities/Entity.ts
#	app/src/data/fields/DateField.ts
#	app/src/data/server/query.ts
#	app/src/flows/flows/triggers/EventTrigger.ts
#	app/src/flows/tasks/presets/LogTask.ts
#	app/src/media/AppMedia.ts
#	app/src/modules/server/AppServer.ts
#	app/src/modules/server/SystemController.ts
#	app/vite.dev.ts
#	bun.lock
2025-07-02 17:18:12 +02:00
dswbx c161a26ec0 test secrets extraction 2025-06-25 07:49:39 +02:00
dswbx 6e78a4c238 fixes 2025-06-21 17:05:27 +02:00
dswbx 42edce904f initial refactor 2025-06-21 13:35:58 +02:00
520 changed files with 10645 additions and 23337 deletions
-10
View File
@@ -1,10 +0,0 @@
{
"mcpServers": {
"bknd": {
"url": "http://localhost:3000/mcp",
"headers": {
"API_KEY": "value"
}
}
}
}
+1 -1
View File
@@ -20,7 +20,7 @@ jobs:
- name: Setup Bun - name: Setup Bun
uses: oven-sh/setup-bun@v1 uses: oven-sh/setup-bun@v1
with: with:
bun-version: "1.2.19" bun-version: "1.2.14"
- name: Install dependencies - name: Install dependencies
working-directory: ./app working-directory: ./app
+1 -3
View File
@@ -31,6 +31,4 @@ packages/media/.env
.git_old .git_old
docker/tmp docker/tmp
.debug .debug
.history .history
.aider*
.vercel
+1 -1
View File
@@ -1,6 +1,6 @@
[![npm version](https://img.shields.io/npm/v/bknd.svg)](https://npmjs.org/package/bknd) [![npm version](https://img.shields.io/npm/v/bknd.svg)](https://npmjs.org/package/bknd)
![bknd](https://raw.githubusercontent.com/bknd-io/bknd/refs/heads/main/docs/public/assets/poster.png) ![bknd](https://raw.githubusercontent.com/bknd-io/bknd/refs/heads/main/docs/_assets/poster.png)
<p align="center" width="100%"> <p align="center" width="100%">
<a href="https://stackblitz.com/github/bknd-io/bknd-examples?hideExplorer=1&embed=1&view=preview&startScript=example-admin-rich&initialPath=%2Fdata%2Fschema" target="_blank"> <a href="https://stackblitz.com/github/bknd-io/bknd-examples?hideExplorer=1&embed=1&view=preview&startScript=example-admin-rich&initialPath=%2Fdata%2Fschema" target="_blank">
+1 -2
View File
@@ -1,2 +1 @@
tmp/* tmp/*
!tmp/.gitkeep
+6 -6
View File
@@ -9,16 +9,16 @@ beforeAll(disableConsoleLog);
afterAll(enableConsoleLog); afterAll(enableConsoleLog);
describe("adapter", () => { describe("adapter", () => {
it("makes config", async () => { it("makes config", () => {
expect(omitKeys(await adapter.makeConfig({}), ["connection"])).toEqual({}); expect(omitKeys(adapter.makeConfig({}), ["connection"])).toEqual({});
expect( expect(omitKeys(adapter.makeConfig({}, { env: { TEST: "test" } }), ["connection"])).toEqual(
omitKeys(await adapter.makeConfig({}, { env: { TEST: "test" } }), ["connection"]), {},
).toEqual({}); );
// merges everything returned from `app` with the config // merges everything returned from `app` with the config
expect( expect(
omitKeys( omitKeys(
await adapter.makeConfig( adapter.makeConfig(
{ app: (a) => ({ initialConfig: { server: { cors: { origin: a.env.TEST } } } }) }, { app: (a) => ({ initialConfig: { server: { cors: { origin: a.env.TEST } } } }) },
{ env: { TEST: "test" } }, { env: { TEST: "test" } },
), ),
+3 -3
View File
@@ -1,12 +1,12 @@
import { afterAll, beforeAll, describe, expect, it } from "bun:test"; import { afterAll, beforeAll, describe, expect, it } from "bun:test";
import { Guard } from "../../src/auth/authorize/Guard"; import { Guard } from "../../src/auth";
import { DataApi } from "../../src/data/api/DataApi"; import { DataApi } from "../../src/data/api/DataApi";
import { DataController } from "../../src/data/api/DataController"; import { DataController } from "../../src/data/api/DataController";
import { dataConfigSchema } from "../../src/data/data-schema"; import { dataConfigSchema } from "../../src/data/data-schema";
import * as proto from "../../src/data/prototype"; import * as proto from "../../src/data/prototype";
import { schemaToEm } from "../helper"; import { schemaToEm } from "../helper";
import { disableConsoleLog, enableConsoleLog } from "core/utils/test"; import { disableConsoleLog, enableConsoleLog } from "core/utils/test";
import { parse } from "core/utils/schema"; import { parse } from "core/object/schema";
beforeAll(disableConsoleLog); beforeAll(disableConsoleLog);
afterAll(enableConsoleLog); afterAll(enableConsoleLog);
@@ -202,7 +202,7 @@ describe("DataApi", () => {
{ {
// create many // create many
const res = await api.createMany("posts", payload); const res = await api.createMany("posts", payload);
expect(res.data?.length).toEqual(4); expect(res.data.length).toEqual(4);
expect(res.ok).toBeTrue(); expect(res.ok).toBeTrue();
} }
-18
View File
@@ -20,7 +20,6 @@ describe("App", () => {
"guard", "guard",
"flags", "flags",
"logger", "logger",
"mcp",
"helper", "helper",
]); ]);
}, },
@@ -136,21 +135,4 @@ describe("App", () => {
// expect async listeners to be executed sync after request // expect async listeners to be executed sync after request
expect(called).toHaveBeenCalled(); expect(called).toHaveBeenCalled();
}); });
test("getMcpClient", async () => {
const app = createApp({
initialConfig: {
server: {
mcp: {
enabled: true,
},
},
},
});
await app.build();
const client = app.getMcpClient();
const res = await client.listTools();
expect(res).toBeDefined();
expect(res?.tools.length).toBeGreaterThan(0);
});
}); });
-10
View File
@@ -8,15 +8,10 @@ describe("AppServer", () => {
expect(server).toBeDefined(); expect(server).toBeDefined();
expect(server.config).toEqual({ expect(server.config).toEqual({
cors: { cors: {
allow_credentials: true,
origin: "*", origin: "*",
allow_methods: ["GET", "POST", "PATCH", "PUT", "DELETE"], allow_methods: ["GET", "POST", "PATCH", "PUT", "DELETE"],
allow_headers: ["Content-Type", "Content-Length", "Authorization", "Accept"], allow_headers: ["Content-Type", "Content-Length", "Authorization", "Accept"],
}, },
mcp: {
enabled: false,
path: "/api/system/mcp",
},
}); });
} }
@@ -30,15 +25,10 @@ describe("AppServer", () => {
expect(server).toBeDefined(); expect(server).toBeDefined();
expect(server.config).toEqual({ expect(server.config).toEqual({
cors: { cors: {
allow_credentials: true,
origin: "https", origin: "https",
allow_methods: ["GET", "POST"], allow_methods: ["GET", "POST"],
allow_headers: ["Content-Type", "Content-Length", "Authorization", "Accept"], allow_headers: ["Content-Type", "Content-Length", "Authorization", "Accept"],
}, },
mcp: {
enabled: false,
path: "/api/system/mcp",
},
}); });
} }
}); });
-226
View File
@@ -1,226 +0,0 @@
import { describe, test, expect, beforeEach, beforeAll, afterAll } from "bun:test";
import { type App, createApp, createMcpToolCaller } from "core/test/utils";
import { disableConsoleLog, enableConsoleLog } from "core/utils";
import type { McpServer } from "bknd/utils";
beforeAll(disableConsoleLog);
afterAll(enableConsoleLog);
/**
* - [x] auth_me
* - [x] auth_strategies
* - [x] auth_user_create
* - [x] auth_user_token
* - [x] auth_user_password_change
* - [x] auth_user_password_test
* - [x] config_auth_get
* - [x] config_auth_update
* - [x] config_auth_strategies_get
* - [x] config_auth_strategies_add
* - [x] config_auth_strategies_update
* - [x] config_auth_strategies_remove
* - [x] config_auth_roles_get
* - [x] config_auth_roles_add
* - [x] config_auth_roles_update
* - [x] config_auth_roles_remove
*/
describe("mcp auth", async () => {
let app: App;
let server: McpServer;
beforeEach(async () => {
app = createApp({
initialConfig: {
auth: {
enabled: true,
jwt: {
secret: "secret",
},
},
server: {
mcp: {
enabled: true,
},
},
},
});
await app.build();
server = app.mcp!;
server.setLogLevel("error");
server.onNotification((message) => {
console.dir(message, { depth: null });
});
});
const tool = createMcpToolCaller();
test("auth_*", async () => {
const me = await tool(server, "auth_me", {});
expect(me.user).toBeNull();
// strategies
const strategies = await tool(server, "auth_strategies", {});
expect(Object.keys(strategies.strategies).length).toEqual(1);
expect(strategies.strategies.password.enabled).toBe(true);
// create user
const user = await tool(
server,
"auth_user_create",
{
email: "test@test.com",
password: "12345678",
},
new Headers(),
);
expect(user.email).toBe("test@test.com");
// create token
const token = await tool(
server,
"auth_user_token",
{
email: "test@test.com",
},
new Headers(),
);
expect(token.token).toBeDefined();
expect(token.user.email).toBe("test@test.com");
// me
const me2 = await tool(
server,
"auth_me",
{},
new Request("http://localhost", {
headers: new Headers({
Authorization: `Bearer ${token.token}`,
}),
}),
);
expect(me2.user.email).toBe("test@test.com");
// change password
const changePassword = await tool(
server,
"auth_user_password_change",
{
email: "test@test.com",
password: "87654321",
},
new Headers(),
);
expect(changePassword.changed).toBe(true);
// test password
const testPassword = await tool(
server,
"auth_user_password_test",
{
email: "test@test.com",
password: "87654321",
},
new Headers(),
);
expect(testPassword.valid).toBe(true);
});
test("config_auth_{get,update}", async () => {
expect(await tool(server, "config_auth_get", {})).toEqual({
path: "",
secrets: false,
partial: false,
value: app.toJSON().auth,
});
// update
await tool(server, "config_auth_update", {
value: {
allow_register: false,
},
});
expect(app.toJSON().auth.allow_register).toBe(false);
});
test("config_auth_strategies_{get,add,update,remove}", async () => {
const strategies = await tool(server, "config_auth_strategies_get", {
key: "password",
});
expect(strategies).toEqual({
secrets: false,
module: "auth",
key: "password",
value: {
enabled: true,
type: "password",
},
});
// add google oauth
const addGoogleOauth = await tool(server, "config_auth_strategies_add", {
key: "google",
value: {
type: "oauth",
enabled: true,
config: {
name: "google",
type: "oidc",
client: {
client_id: "client_id",
client_secret: "client_secret",
},
},
},
return_config: true,
});
expect(addGoogleOauth.config.google.enabled).toBe(true);
expect(app.toJSON().auth.strategies.google?.enabled).toBe(true);
// update (disable) google oauth
await tool(server, "config_auth_strategies_update", {
key: "google",
value: {
enabled: false,
},
});
expect(app.toJSON().auth.strategies.google?.enabled).toBe(false);
// remove google oauth
await tool(server, "config_auth_strategies_remove", {
key: "google",
});
expect(app.toJSON().auth.strategies.google).toBeUndefined();
});
test("config_auth_roles_{get,add,update,remove}", async () => {
// add role
const addGuestRole = await tool(server, "config_auth_roles_add", {
key: "guest",
value: {
permissions: ["read", "write"],
},
return_config: true,
});
expect(addGuestRole.config.guest.permissions).toEqual(["read", "write"]);
// update role
await tool(server, "config_auth_roles_update", {
key: "guest",
value: {
permissions: ["read"],
},
});
expect(app.toJSON().auth.roles?.guest?.permissions).toEqual(["read"]);
// get role
const getGuestRole = await tool(server, "config_auth_roles_get", {
key: "guest",
});
expect(getGuestRole.value.permissions).toEqual(["read"]);
// remove role
await tool(server, "config_auth_roles_remove", {
key: "guest",
});
expect(app.toJSON().auth.roles?.guest).toBeUndefined();
});
});
-35
View File
@@ -1,35 +0,0 @@
import { describe, it, expect } from "bun:test";
import { createApp } from "core/test/utils";
import { registries } from "index";
import { StorageLocalAdapter } from "adapter/node/storage/StorageLocalAdapter";
describe("mcp", () => {
it("should have tools", async () => {
registries.media.register("local", StorageLocalAdapter);
const app = createApp({
initialConfig: {
auth: {
enabled: true,
},
media: {
enabled: true,
adapter: {
type: "local",
config: {
path: "./",
},
},
},
server: {
mcp: {
enabled: true,
},
},
},
});
await app.build();
expect(app.mcp?.tools.length).toBeGreaterThan(0);
});
});
-346
View File
@@ -1,346 +0,0 @@
import { describe, test, expect, beforeEach, beforeAll, afterAll } from "bun:test";
import { type App, createApp, createMcpToolCaller } from "core/test/utils";
import { getSystemMcp } from "modules/mcp/system-mcp";
import { pickKeys, type McpServer } from "bknd/utils";
import { entity, text } from "bknd";
import { disableConsoleLog, enableConsoleLog } from "core/utils";
beforeAll(disableConsoleLog);
afterAll(enableConsoleLog);
/**
* - [ ] data_sync
* - [x] data_entity_fn_count
* - [x] data_entity_fn_exists
* - [x] data_entity_read_one
* - [x] data_entity_read_many
* - [x] data_entity_insert
* - [x] data_entity_update_many
* - [x] data_entity_update_one
* - [x] data_entity_delete_one
* - [x] data_entity_delete_many
* - [x] data_entity_info
* - [ ] config_data_get
* - [ ] config_data_update
* - [x] config_data_entities_get
* - [x] config_data_entities_add
* - [x] config_data_entities_update
* - [x] config_data_entities_remove
* - [x] config_data_relations_add
* - [x] config_data_relations_get
* - [x] config_data_relations_update
* - [x] config_data_relations_remove
* - [x] config_data_indices_get
* - [x] config_data_indices_add
* - [x] config_data_indices_update
* - [x] config_data_indices_remove
*/
describe("mcp data", async () => {
let app: App;
let server: McpServer;
beforeEach(async () => {
const time = performance.now();
app = createApp({
initialConfig: {
server: {
mcp: {
enabled: true,
},
},
},
});
await app.build();
server = app.mcp!;
server.setLogLevel("error");
server.onNotification((message) => {
console.dir(message, { depth: null });
});
});
const tool = createMcpToolCaller();
test("config_data_entities_{add,get,update,remove}", async () => {
const result = await tool(server, "config_data_entities_add", {
key: "test",
return_config: true,
value: {},
});
expect(result.success).toBe(true);
expect(result.module).toBe("data");
expect(result.config.test?.type).toEqual("regular");
const entities = Object.keys(app.toJSON().data.entities ?? {});
expect(entities).toContain("test");
{
// get
const result = await tool(server, "config_data_entities_get", {
key: "test",
});
expect(result.module).toBe("data");
expect(result.key).toBe("test");
expect(result.value.type).toEqual("regular");
}
{
// update
const result = await tool(server, "config_data_entities_update", {
key: "test",
return_config: true,
value: {
config: {
name: "Test",
},
},
});
expect(result.success).toBe(true);
expect(result.module).toBe("data");
expect(result.config.test.config?.name).toEqual("Test");
expect(app.toJSON().data.entities?.test?.config?.name).toEqual("Test");
}
{
// remove
const result = await tool(server, "config_data_entities_remove", {
key: "test",
});
expect(result.success).toBe(true);
expect(result.module).toBe("data");
expect(app.toJSON().data.entities?.test).toBeUndefined();
}
});
test("config_data_relations_{add,get,update,remove}", async () => {
// create posts and comments
await tool(server, "config_data_entities_add", {
key: "posts",
value: {},
});
await tool(server, "config_data_entities_add", {
key: "comments",
value: {},
});
expect(Object.keys(app.toJSON().data.entities ?? {})).toEqual(["posts", "comments"]);
// create relation
await tool(server, "config_data_relations_add", {
key: "", // doesn't matter
value: {
type: "n:1",
source: "comments",
target: "posts",
},
});
const config = app.toJSON().data;
expect(
pickKeys((config.relations?.n1_comments_posts as any) ?? {}, ["type", "source", "target"]),
).toEqual({
type: "n:1",
source: "comments",
target: "posts",
});
expect(config.entities?.comments?.fields?.posts_id?.type).toBe("relation");
{
// info
const postsInfo = await tool(server, "data_entity_info", {
entity: "posts",
});
expect(postsInfo.fields).toEqual(["id"]);
expect(postsInfo.relations.all.length).toBe(1);
const commentsInfo = await tool(server, "data_entity_info", {
entity: "comments",
});
expect(commentsInfo.fields).toEqual(["id", "posts_id"]);
expect(commentsInfo.relations.all.length).toBe(1);
}
// update
await tool(server, "config_data_relations_update", {
key: "n1_comments_posts",
value: {
config: {
with_limit: 10,
},
},
});
expect((app.toJSON().data.relations?.n1_comments_posts?.config as any)?.with_limit).toBe(10);
// delete
await tool(server, "config_data_relations_remove", {
key: "n1_comments_posts",
});
expect(app.toJSON().data.relations?.n1_comments_posts).toBeUndefined();
});
test("config_data_indices_update", async () => {
expect(server.tools.map((t) => t.name).includes("config_data_indices_update")).toBe(false);
});
test("config_data_indices_{add,get,remove}", async () => {
// create posts and comments
await tool(server, "config_data_entities_add", {
key: "posts",
value: entity("posts", {
title: text(),
content: text(),
}).toJSON(),
});
// add index on title
await tool(server, "config_data_indices_add", {
key: "", // auto generated
value: {
entity: "posts",
fields: ["title"],
},
});
expect(app.toJSON().data.indices?.idx_posts_title).toEqual({
entity: "posts",
fields: ["title"],
unique: false,
});
// delete
await tool(server, "config_data_indices_remove", {
key: "idx_posts_title",
});
expect(app.toJSON().data.indices?.idx_posts_title).toBeUndefined();
});
test("data_entity_*", async () => {
// create posts and comments
await tool(server, "config_data_entities_add", {
key: "posts",
value: entity("posts", {
title: text(),
content: text(),
}).toJSON(),
});
await tool(server, "config_data_entities_add", {
key: "comments",
value: entity("comments", {
content: text(),
}).toJSON(),
});
// insert a few posts
for (let i = 0; i < 10; i++) {
await tool(server, "data_entity_insert", {
entity: "posts",
json: {
title: `Post ${i}`,
},
});
}
// insert a few comments
for (let i = 0; i < 5; i++) {
await tool(server, "data_entity_insert", {
entity: "comments",
json: {
content: `Comment ${i}`,
},
});
}
const result = await tool(server, "data_entity_read_many", {
entity: "posts",
limit: 5,
});
expect(result.data.length).toBe(5);
expect(result.meta.items).toBe(5);
expect(result.meta.total).toBe(10);
expect(result.data[0].title).toBe("Post 0");
{
// count
const result = await tool(server, "data_entity_fn_count", {
entity: "posts",
});
expect(result.count).toBe(10);
}
{
// exists
const res = await tool(server, "data_entity_fn_exists", {
entity: "posts",
json: {
id: result.data[0].id,
},
});
expect(res.exists).toBe(true);
const res2 = await tool(server, "data_entity_fn_exists", {
entity: "posts",
json: {
id: "123",
},
});
expect(res2.exists).toBe(false);
}
// update
await tool(server, "data_entity_update_one", {
entity: "posts",
id: result.data[0].id,
json: {
title: "Post 0 updated",
},
});
const result2 = await tool(server, "data_entity_read_one", {
entity: "posts",
id: result.data[0].id,
});
expect(result2.data.title).toBe("Post 0 updated");
// delete the second post
await tool(server, "data_entity_delete_one", {
entity: "posts",
id: result.data[1].id,
});
const result3 = await tool(server, "data_entity_read_many", {
entity: "posts",
limit: 2,
});
expect(result3.data.map((p) => p.id)).toEqual([1, 3]);
// update many
await tool(server, "data_entity_update_many", {
entity: "posts",
update: {
title: "Post updated",
},
where: {
title: { $isnull: 0 },
},
});
const result4 = await tool(server, "data_entity_read_many", {
entity: "posts",
limit: 10,
});
expect(result4.data.length).toBe(9);
expect(result4.data.map((p) => p.title)).toEqual(
Array.from({ length: 9 }, () => "Post updated"),
);
// delete many
await tool(server, "data_entity_delete_many", {
entity: "posts",
json: {
title: { $isnull: 0 },
},
});
const result5 = await tool(server, "data_entity_read_many", {
entity: "posts",
limit: 10,
});
expect(result5.data.length).toBe(0);
expect(result5.meta.items).toBe(0);
expect(result5.meta.total).toBe(0);
});
});
-118
View File
@@ -1,118 +0,0 @@
import { describe, test, expect, beforeAll, beforeEach, afterAll } from "bun:test";
import { type App, createApp, createMcpToolCaller } from "core/test/utils";
import { getSystemMcp } from "modules/mcp/system-mcp";
import { registries } from "index";
import { StorageLocalAdapter } from "adapter/node/storage/StorageLocalAdapter";
import { disableConsoleLog, enableConsoleLog } from "core/utils";
import type { McpServer } from "bknd/utils";
beforeAll(disableConsoleLog);
afterAll(enableConsoleLog);
/**
* - [x] config_media_get
* - [x] config_media_update
* - [x] config_media_adapter_get
* - [x] config_media_adapter_update
*/
describe("mcp media", async () => {
let app: App;
let server: McpServer;
beforeEach(async () => {
registries.media.register("local", StorageLocalAdapter);
app = createApp({
initialConfig: {
media: {
enabled: true,
adapter: {
type: "local",
config: {
path: "./",
},
},
},
server: {
mcp: {
enabled: true,
},
},
},
});
await app.build();
server = app.mcp!;
server.setLogLevel("error");
server.onNotification((message) => {
console.dir(message, { depth: null });
});
});
const tool = createMcpToolCaller();
test("config_media_{get,update}", async () => {
const result = await tool(server, "config_media_get", {});
expect(result).toEqual({
path: "",
secrets: false,
partial: false,
value: app.toJSON().media,
});
// partial
expect((await tool(server, "config_media_get", { path: "adapter" })).value).toEqual({
type: "local",
config: {
path: "./",
},
});
// update
await tool(server, "config_media_update", {
value: {
storage: {
body_max_size: 1024 * 1024 * 10,
},
},
return_config: true,
});
expect(app.toJSON().media.storage.body_max_size).toBe(1024 * 1024 * 10);
});
test("config_media_adapter_{get,update}", async () => {
const result = await tool(server, "config_media_adapter_get", {});
expect(result).toEqual({
secrets: false,
value: app.toJSON().media.adapter,
});
// update
await tool(server, "config_media_adapter_update", {
value: {
type: "local",
config: {
path: "./subdir",
},
},
});
const adapter = app.toJSON().media.adapter as any;
expect(adapter.config.path).toBe("./subdir");
expect(adapter.type).toBe("local");
// set to s3
{
await tool(server, "config_media_adapter_update", {
value: {
type: "s3",
config: {
access_key: "123",
secret_access_key: "456",
url: "https://example.com/what",
},
},
});
const adapter = app.toJSON(true).media.adapter as any;
expect(adapter.type).toBe("s3");
expect(adapter.config.url).toBe("https://example.com/what");
}
});
});
-72
View File
@@ -1,72 +0,0 @@
import { describe, test, expect, beforeAll, mock, beforeEach, afterAll } from "bun:test";
import { type App, createApp, createMcpToolCaller } from "core/test/utils";
import type { McpServer } from "bknd/utils";
/**
* - [x] config_server_get
* - [x] config_server_update
*/
describe("mcp system", async () => {
let app: App;
let server: McpServer;
beforeAll(async () => {
app = createApp({
initialConfig: {
server: {
mcp: {
enabled: true,
},
},
},
});
await app.build();
server = app.mcp!;
});
const tool = createMcpToolCaller();
test("config_server_get", async () => {
const result = await tool(server, "config_server_get", {});
expect(JSON.parse(JSON.stringify(result))).toEqual({
path: "",
secrets: false,
partial: false,
value: JSON.parse(JSON.stringify(app.toJSON().server)),
});
});
test("config_server_get2", async () => {
const result = await tool(server, "config_server_get", {});
expect(JSON.parse(JSON.stringify(result))).toEqual({
path: "",
secrets: false,
partial: false,
value: JSON.parse(JSON.stringify(app.toJSON().server)),
});
});
test("config_server_update", async () => {
const original = JSON.parse(JSON.stringify(app.toJSON().server));
const result = await tool(server, "config_server_update", {
value: {
cors: {
origin: "http://localhost",
},
},
return_config: true,
});
expect(JSON.parse(JSON.stringify(result))).toEqual({
success: true,
module: "server",
config: {
...original,
cors: {
...original.cors,
origin: "http://localhost",
},
},
});
expect(app.toJSON().server.cors.origin).toBe("http://localhost");
});
});
-56
View File
@@ -1,56 +0,0 @@
import { AppEvents } from "App";
import { describe, test, expect, beforeAll, mock } from "bun:test";
import { type App, createApp, createMcpToolCaller } from "core/test/utils";
import type { McpServer } from "bknd/utils";
/**
* - [x] system_config
* - [x] system_build
* - [x] system_ping
* - [x] system_info
*/
describe("mcp system", async () => {
let app: App;
let server: McpServer;
beforeAll(async () => {
app = createApp({
initialConfig: {
server: {
mcp: {
enabled: true,
},
},
},
});
await app.build();
server = app.mcp!;
});
const tool = createMcpToolCaller();
test("system_ping", async () => {
const result = await tool(server, "system_ping", {});
expect(result).toEqual({ pong: true });
});
test("system_info", async () => {
const result = await tool(server, "system_info", {});
expect(Object.keys(result).length).toBeGreaterThan(0);
expect(Object.keys(result)).toContainValues(["version", "runtime", "connection"]);
});
test("system_build", async () => {
const called = mock(() => null);
app.emgr.onEvent(AppEvents.AppBuiltEvent, () => void called(), { once: true });
const result = await tool(server, "system_build", {});
expect(called).toHaveBeenCalledTimes(1);
expect(result.success).toBe(true);
});
test("system_config", async () => {
const result = await tool(server, "system_config", {});
expect(result).toEqual(app.toJSON());
});
});
+1 -2
View File
@@ -1,5 +1,4 @@
import { describe, expect, test } from "bun:test"; import { describe, expect, test } from "bun:test";
import { registries } from "../../src";
import { createApp } from "core/test/utils"; import { createApp } from "core/test/utils";
import * as proto from "../../src/data/prototype"; import * as proto from "../../src/data/prototype";
import { StorageLocalAdapter } from "adapter/node/storage/StorageLocalAdapter"; import { StorageLocalAdapter } from "adapter/node/storage/StorageLocalAdapter";
@@ -14,8 +13,8 @@ describe("repros", async () => {
* There was an issue that AppData had old configs because of system entity "media" * There was an issue that AppData had old configs because of system entity "media"
*/ */
test("registers media entity correctly to relate to it", async () => { test("registers media entity correctly to relate to it", async () => {
registries.media.register("local", StorageLocalAdapter);
const app = createApp(); const app = createApp();
app.module.media.adapters.set("local", StorageLocalAdapter);
await app.build(); await app.build();
{ {
+43 -1
View File
@@ -1,3 +1,45 @@
import { describe, expect, test } from "bun:test"; import { describe, expect, test } from "bun:test";
import { Authenticator, type User, type UserPool } from "../../src/auth";
import { cookieConfig } from "../../src/auth/authenticate/Authenticator";
import { PasswordStrategy } from "../../src/auth/authenticate/strategies/PasswordStrategy";
import { parse } from "core/object/schema";
describe("Authenticator", async () => {}); /*class MemoryUserPool implements UserPool {
constructor(private users: User[] = []) {}
async findBy(prop: "id" | "email" | "username", value: string | number) {
return this.users.find((user) => user[prop] === value);
}
async create(user: Pick<User, "email" | "password">) {
const id = this.users.length + 1;
const newUser = { ...user, id, username: user.email };
this.users.push(newUser);
return newUser;
}
}*/
describe("Authenticator", async () => {
test("cookie options", async () => {
console.log("parsed", parse(cookieConfig, undefined));
console.log(cookieConfig.template({}));
});
/*const userpool = new MemoryUserPool([
{ id: 1, email: "d", username: "test", password: await hash.sha256("test") },
]);
test("sha256 login", async () => {
const auth = new Authenticator(userpool, {
password: new PasswordStrategy({
hashing: "sha256",
}),
});
const { token } = await auth.login("password", { email: "d", password: "test" });
expect(token).toBeDefined();
const { iat, ...decoded } = decodeJwt<any>(token);
expect(decoded).toEqual({ id: 1, email: "d", username: "test" });
expect(await auth.verify(token)).toBe(true);
});*/
});
@@ -1,5 +1,5 @@
import { describe, expect, test } from "bun:test"; import { describe, expect, test } from "bun:test";
import { Guard } from "../../../src/auth/authorize/Guard"; import { Guard } from "../../../src/auth";
describe("authorize", () => { describe("authorize", () => {
test("basic", async () => { test("basic", async () => {
+2 -2
View File
@@ -1,6 +1,6 @@
import { describe, expect, test } from "bun:test"; import { describe, expect, test } from "bun:test";
import { Registry } from "core/registry/Registry"; import { Registry } from "core";
import { s } from "core/utils/schema"; import { s } from "core/object/schema";
type Constructor<T> = new (...args: any[]) => T; type Constructor<T> = new (...args: any[]) => T;
@@ -1,6 +1,6 @@
import { describe, expect, test } from "bun:test"; import { describe, expect, test } from "bun:test";
import { s } from "core/utils/schema"; import { SchemaObject } from "../../../src/core";
import { SchemaObject } from "core/object/SchemaObject"; import { s } from "core/object/schema";
describe("SchemaObject", async () => { describe("SchemaObject", async () => {
test("basic", async () => { test("basic", async () => {
+9 -6
View File
@@ -1,16 +1,19 @@
import { afterAll, beforeAll, describe, expect, test } from "bun:test"; import { afterAll, beforeAll, describe, expect, test } from "bun:test";
import { Guard } from "../../src/auth/authorize/Guard"; import { Guard } from "../../src/auth";
import { parse } from "core/utils/schema"; import { parse } from "core/object/schema";
import {
Entity,
type EntityData,
EntityManager,
ManyToOneRelation,
TextField,
} from "../../src/data";
import { DataController } from "../../src/data/api/DataController"; import { DataController } from "../../src/data/api/DataController";
import { dataConfigSchema } from "../../src/data/data-schema"; import { dataConfigSchema } from "../../src/data/data-schema";
import { disableConsoleLog, enableConsoleLog, getDummyConnection } from "../helper"; import { disableConsoleLog, enableConsoleLog, getDummyConnection } from "../helper";
import type { RepositoryResultJSON } from "data/entities/query/RepositoryResult"; import type { RepositoryResultJSON } from "data/entities/query/RepositoryResult";
import type { MutatorResultJSON } from "data/entities/mutation/MutatorResult"; import type { MutatorResultJSON } from "data/entities/mutation/MutatorResult";
import { Entity, EntityManager, type EntityData } from "data/entities";
import { TextField } from "data/fields";
import { ManyToOneRelation } from "data/relations";
const { dummyConnection, afterAllCleanup } = getDummyConnection(); const { dummyConnection, afterAllCleanup } = getDummyConnection();
beforeAll(() => disableConsoleLog(["log", "warn"])); beforeAll(() => disableConsoleLog(["log", "warn"]));
+8 -2
View File
@@ -1,6 +1,12 @@
import { afterAll, describe, expect, test } from "bun:test"; import { afterAll, describe, expect, test } from "bun:test";
import { Entity, EntityManager } from "data/entities"; import {
import { TextField, PrimaryField, NumberField } from "data/fields"; Entity,
EntityManager,
NumberField,
PrimaryField,
Repository,
TextField,
} from "../../src/data";
import { getDummyConnection } from "./helper"; import { getDummyConnection } from "./helper";
const { dummyConnection, afterAllCleanup } = getDummyConnection(); const { dummyConnection, afterAllCleanup } = getDummyConnection();
+1 -1
View File
@@ -2,7 +2,7 @@ import { unlink } from "node:fs/promises";
import type { SqliteDatabase } from "kysely"; import type { SqliteDatabase } from "kysely";
// @ts-ignore // @ts-ignore
import Database from "libsql"; import Database from "libsql";
import { SqliteLocalConnection } from "data/connection/sqlite/SqliteLocalConnection"; import { SqliteLocalConnection } from "../../src/data";
export function getDummyDatabase(memory: boolean = true): { export function getDummyDatabase(memory: boolean = true): {
dummyDb: SqliteDatabase; dummyDb: SqliteDatabase;
+8 -5
View File
@@ -1,10 +1,13 @@
// eslint-disable-next-line import/no-unresolved // eslint-disable-next-line import/no-unresolved
import { afterAll, describe, expect, test } from "bun:test"; import { afterAll, describe, expect, test } from "bun:test";
import { Entity } from "data/entities"; import {
import { EntityManager } from "data/entities/EntityManager"; Entity,
import { ManyToOneRelation } from "data/relations"; EntityManager,
import { NumberField, TextField } from "data/fields"; ManyToOneRelation,
import { SchemaManager } from "data/schema/SchemaManager"; NumberField,
SchemaManager,
TextField,
} from "../../src/data";
import { getDummyConnection } from "./helper"; import { getDummyConnection } from "./helper";
const { dummyConnection, afterAllCleanup } = getDummyConnection(); const { dummyConnection, afterAllCleanup } = getDummyConnection();
+2 -3
View File
@@ -1,8 +1,7 @@
// eslint-disable-next-line import/no-unresolved // eslint-disable-next-line import/no-unresolved
import { afterAll, describe, expect, test } from "bun:test"; import { afterAll, describe, expect, test } from "bun:test";
import { Entity, EntityManager } from "data/entities"; import { Entity, EntityManager, Mutator, NumberField, TextField } from "../../src/data";
import { NumberField, TextField } from "data/fields"; import { TransformPersistFailedException } from "../../src/data/errors";
import { TransformPersistFailedException } from "data/errors";
import { getDummyConnection } from "./helper"; import { getDummyConnection } from "./helper";
const { dummyConnection, afterAllCleanup } = getDummyConnection(); const { dummyConnection, afterAllCleanup } = getDummyConnection();
+2 -4
View File
@@ -1,8 +1,6 @@
import { afterAll, expect as bunExpect, describe, test } from "bun:test"; import { afterAll, expect as bunExpect, describe, test } from "bun:test";
import { stripMark } from "core/utils/schema"; import { stripMark } from "core/object/schema";
import { Entity, EntityManager } from "data/entities"; import { Entity, EntityManager, PolymorphicRelation, TextField } from "../../src/data";
import { TextField } from "data/fields";
import { PolymorphicRelation } from "data/relations";
import { getDummyConnection } from "./helper"; import { getDummyConnection } from "./helper";
const { dummyConnection, afterAllCleanup } = getDummyConnection(); const { dummyConnection, afterAllCleanup } = getDummyConnection();
+11 -12
View File
@@ -2,20 +2,19 @@ import { describe, expect, test } from "bun:test";
import { import {
BooleanField, BooleanField,
DateField, DateField,
Entity,
EntityIndex,
EntityManager,
EnumField, EnumField,
JsonField, JsonField,
NumberField,
TextField,
EntityIndex,
} from "data/fields";
import { Entity, EntityManager } from "data/entities";
import {
ManyToManyRelation, ManyToManyRelation,
ManyToOneRelation, ManyToOneRelation,
NumberField,
OneToOneRelation, OneToOneRelation,
PolymorphicRelation, PolymorphicRelation,
} from "data/relations"; TextField,
import { DummyConnection } from "data/connection/DummyConnection"; } from "../../src/data";
import { DummyConnection } from "../../src/data/connection/DummyConnection";
import { import {
FieldPrototype, FieldPrototype,
type FieldSchema, type FieldSchema,
@@ -33,8 +32,8 @@ import {
number, number,
relation, relation,
text, text,
} from "data/prototype"; } from "../../src/data/prototype";
import { MediaField } from "media/MediaField"; import { MediaField } from "../../src/media/MediaField";
describe("prototype", () => { describe("prototype", () => {
test("...", () => { test("...", () => {
@@ -297,9 +296,9 @@ describe("prototype", () => {
new Entity("posts", [new TextField("name"), new TextField("slug", { required: true })]), new Entity("posts", [new TextField("name"), new TextField("slug", { required: true })]),
new Entity("comments", [new TextField("some")]), new Entity("comments", [new TextField("some")]),
new Entity("users", [new TextField("email")]), new Entity("users", [new TextField("email")]),
] as const; ];
const _em2 = new EntityManager( const _em2 = new EntityManager(
[...es], es,
new DummyConnection(), new DummyConnection(),
[new ManyToOneRelation(es[0], es[1]), new ManyToOneRelation(es[0], es[2])], [new ManyToOneRelation(es[0], es[1]), new ManyToOneRelation(es[0], es[2])],
[ [
+10 -11
View File
@@ -1,14 +1,13 @@
// eslint-disable-next-line import/no-unresolved // eslint-disable-next-line import/no-unresolved
import { afterAll, describe, expect, test } from "bun:test"; import { afterAll, describe, expect, test } from "bun:test";
import { Entity, EntityManager } from "data/entities"; import { Entity, EntityManager, TextField } from "../../src/data";
import { TextField } from "data/fields";
import { import {
ManyToManyRelation, ManyToManyRelation,
ManyToOneRelation, ManyToOneRelation,
OneToOneRelation, OneToOneRelation,
PolymorphicRelation, PolymorphicRelation,
RelationField, RelationField,
} from "data/relations"; } from "../../src/data/relations";
import { getDummyConnection } from "./helper"; import { getDummyConnection } from "./helper";
const { dummyConnection, afterAllCleanup } = getDummyConnection(); const { dummyConnection, afterAllCleanup } = getDummyConnection();
@@ -78,7 +77,7 @@ describe("Relations", async () => {
const em = new EntityManager(entities, dummyConnection, relations); const em = new EntityManager(entities, dummyConnection, relations);
// verify naming // verify naming
const rel = em.relations.all[0]!; const rel = em.relations.all[0];
expect(rel.source.entity.name).toBe(posts.name); expect(rel.source.entity.name).toBe(posts.name);
expect(rel.source.reference).toBe(posts.name); expect(rel.source.reference).toBe(posts.name);
expect(rel.target.entity.name).toBe(users.name); expect(rel.target.entity.name).toBe(users.name);
@@ -90,11 +89,11 @@ describe("Relations", async () => {
// verify low level relation // verify low level relation
expect(em.relationsOf(users.name).length).toBe(1); expect(em.relationsOf(users.name).length).toBe(1);
expect(em.relationsOf(users.name).length).toBe(1); expect(em.relationsOf(users.name).length).toBe(1);
expect(em.relationsOf(users.name)[0]!.source.entity).toBe(posts); expect(em.relationsOf(users.name)[0].source.entity).toBe(posts);
expect(posts.field("author_id")).toBeInstanceOf(RelationField); expect(posts.field("author_id")).toBeInstanceOf(RelationField);
expect(em.relationsOf(users.name).length).toBe(1); expect(em.relationsOf(users.name).length).toBe(1);
expect(em.relationsOf(users.name).length).toBe(1); expect(em.relationsOf(users.name).length).toBe(1);
expect(em.relationsOf(users.name)[0]!.source.entity).toBe(posts); expect(em.relationsOf(users.name)[0].source.entity).toBe(posts);
// verify high level relation (from users) // verify high level relation (from users)
const userPostsRel = em.relationOf(users.name, "posts"); const userPostsRel = em.relationOf(users.name, "posts");
@@ -192,7 +191,7 @@ describe("Relations", async () => {
const em = new EntityManager(entities, dummyConnection, relations); const em = new EntityManager(entities, dummyConnection, relations);
// verify naming // verify naming
const rel = em.relations.all[0]!; const rel = em.relations.all[0];
expect(rel.source.entity.name).toBe(users.name); expect(rel.source.entity.name).toBe(users.name);
expect(rel.source.reference).toBe(users.name); expect(rel.source.reference).toBe(users.name);
expect(rel.target.entity.name).toBe(settings.name); expect(rel.target.entity.name).toBe(settings.name);
@@ -203,8 +202,8 @@ describe("Relations", async () => {
expect(em.relationsOf(users.name).length).toBe(1); expect(em.relationsOf(users.name).length).toBe(1);
expect(em.relationsOf(users.name).length).toBe(1); expect(em.relationsOf(users.name).length).toBe(1);
expect(em.relationsOf(users.name)[0]!.source.entity).toBe(users); expect(em.relationsOf(users.name)[0].source.entity).toBe(users);
expect(em.relationsOf(users.name)[0]!.target.entity).toBe(settings); expect(em.relationsOf(users.name)[0].target.entity).toBe(settings);
// verify high level relation (from users) // verify high level relation (from users)
const userSettingRel = em.relationOf(users.name, settings.name); const userSettingRel = em.relationOf(users.name, settings.name);
@@ -324,7 +323,7 @@ describe("Relations", async () => {
); );
// mutation info // mutation info
expect(relations[0]!.helper(posts.name)!.getMutationInfo()).toEqual({ expect(relations[0].helper(posts.name)!.getMutationInfo()).toEqual({
reference: "categories", reference: "categories",
local_field: undefined, local_field: undefined,
$set: false, $set: false,
@@ -335,7 +334,7 @@ describe("Relations", async () => {
cardinality: undefined, cardinality: undefined,
relation_type: "m:n", relation_type: "m:n",
}); });
expect(relations[0]!.helper(categories.name)!.getMutationInfo()).toEqual({ expect(relations[0].helper(categories.name)!.getMutationInfo()).toEqual({
reference: "posts", reference: "posts",
local_field: undefined, local_field: undefined,
$set: false, $set: false,
+6 -2
View File
@@ -1,6 +1,6 @@
import { describe, expect, test } from "bun:test"; import { describe, expect, test } from "bun:test";
import { Entity } from "data/entities"; import { Entity, NumberField, TextField } from "data";
import { NumberField, TextField } from "data/fields"; import * as p from "data/prototype";
describe("[data] Entity", async () => { describe("[data] Entity", async () => {
const entity = new Entity("test", [ const entity = new Entity("test", [
@@ -47,4 +47,8 @@ describe("[data] Entity", async () => {
entity.addField(field); entity.addField(field);
expect(entity.getField("new_field")).toBe(field); expect(entity.getField("new_field")).toBe(field);
}); });
test.only("types", async () => {
console.log(entity.toTypes());
});
}); });
@@ -1,8 +1,12 @@
import { afterAll, describe, expect, test } from "bun:test"; import { afterAll, describe, expect, test } from "bun:test";
import { Entity, EntityManager } from "data/entities"; import {
import { ManyToManyRelation, ManyToOneRelation } from "data/relations"; Entity,
import { SchemaManager } from "data/schema/SchemaManager"; EntityManager,
import { UnableToConnectException } from "data/errors"; ManyToManyRelation,
ManyToOneRelation,
SchemaManager,
} from "../../../src/data";
import { UnableToConnectException } from "../../../src/data/errors";
import { getDummyConnection } from "../helper"; import { getDummyConnection } from "../helper";
const { dummyConnection, afterAllCleanup } = getDummyConnection(); const { dummyConnection, afterAllCleanup } = getDummyConnection();
+2 -4
View File
@@ -1,8 +1,6 @@
import { afterAll, describe, expect, test } from "bun:test"; import { afterAll, describe, expect, test } from "bun:test";
import { Entity, EntityManager } from "data/entities"; import { Entity, EntityManager, ManyToOneRelation, TextField } from "../../../src/data";
import { ManyToOneRelation } from "data/relations"; import { JoinBuilder } from "../../../src/data/entities/query/JoinBuilder";
import { TextField } from "data/fields";
import { JoinBuilder } from "data/entities/query/JoinBuilder";
import { getDummyConnection } from "../helper"; import { getDummyConnection } from "../helper";
const { dummyConnection, afterAllCleanup } = getDummyConnection(); const { dummyConnection, afterAllCleanup } = getDummyConnection();
+8 -6
View File
@@ -1,16 +1,18 @@
import { afterAll, beforeAll, describe, expect, test } from "bun:test"; import { afterAll, beforeAll, describe, expect, test } from "bun:test";
import type { EventManager } from "../../../src/core/events"; import type { EventManager } from "../../../src/core/events";
import { Entity, EntityManager } from "data/entities";
import { import {
Entity,
EntityManager,
ManyToOneRelation, ManyToOneRelation,
MutatorEvents,
NumberField,
OneToOneRelation, OneToOneRelation,
RelationField, type RelationField,
RelationMutator, RelationMutator,
} from "data/relations"; TextField,
import { NumberField, TextField } from "data/fields"; } from "../../../src/data";
import * as proto from "data/prototype"; import * as proto from "../../../src/data/prototype";
import { getDummyConnection, disableConsoleLog, enableConsoleLog } from "../../helper"; import { getDummyConnection, disableConsoleLog, enableConsoleLog } from "../../helper";
import { MutatorEvents } from "data/events";
const { dummyConnection, afterAllCleanup } = getDummyConnection(); const { dummyConnection, afterAllCleanup } = getDummyConnection();
afterAll(afterAllCleanup); afterAll(afterAllCleanup);
+12 -5
View File
@@ -1,10 +1,17 @@
import { afterAll, describe, expect, test } from "bun:test"; import { afterAll, describe, expect, test } from "bun:test";
import type { Kysely, Transaction } from "kysely"; import type { Kysely, Transaction } from "kysely";
import { TextField } from "data/fields"; import { Perf } from "core/utils";
import { em as $em, entity as $entity, text as $text } from "data/prototype"; import {
import { Entity, EntityManager } from "data/entities"; Entity,
import { ManyToOneRelation } from "data/relations"; EntityManager,
import { RepositoryEvents } from "data/events"; LibsqlConnection,
ManyToOneRelation,
RepositoryEvents,
TextField,
entity as $entity,
text as $text,
em as $em,
} from "data";
import { getDummyConnection } from "../helper"; import { getDummyConnection } from "../helper";
type E = Kysely<any> | Transaction<any>; type E = Kysely<any> | Transaction<any>;
@@ -1,9 +1,7 @@
// eslint-disable-next-line import/no-unresolved // eslint-disable-next-line import/no-unresolved
import { afterAll, describe, expect, test } from "bun:test"; import { afterAll, describe, expect, test } from "bun:test";
import { randomString } from "core/utils"; import { randomString } from "../../../src/core/utils";
import { Entity, EntityManager } from "data/entities"; import { Entity, EntityIndex, EntityManager, SchemaManager, TextField } from "../../../src/data";
import { TextField, EntityIndex } from "data/fields";
import { SchemaManager } from "data/schema/SchemaManager";
import { getDummyConnection } from "../helper"; import { getDummyConnection } from "../helper";
const { dummyConnection, afterAllCleanup } = getDummyConnection(); const { dummyConnection, afterAllCleanup } = getDummyConnection();
+1 -1
View File
@@ -1,6 +1,6 @@
import { describe, test, expect } from "bun:test"; import { describe, test, expect } from "bun:test";
import { getDummyConnection } from "../helper"; import { getDummyConnection } from "../helper";
import { WhereBuilder, type WhereQuery } from "data/entities/query/WhereBuilder"; import { type WhereQuery, WhereBuilder } from "data";
function qb() { function qb() {
const c = getDummyConnection(); const c = getDummyConnection();
+10 -5
View File
@@ -1,9 +1,14 @@
import { describe, expect, test } from "bun:test"; import { describe, expect, test } from "bun:test";
import { Entity, EntityManager } from "data/entities"; import {
import { ManyToManyRelation, ManyToOneRelation, PolymorphicRelation } from "data/relations"; Entity,
import { TextField } from "data/fields"; EntityManager,
import * as proto from "data/prototype"; ManyToManyRelation,
import { WithBuilder } from "data/entities/query/WithBuilder"; ManyToOneRelation,
PolymorphicRelation,
TextField,
WithBuilder,
} from "../../../src/data";
import * as proto from "../../../src/data/prototype";
import { schemaToEm } from "../../helper"; import { schemaToEm } from "../../helper";
import { getDummyConnection } from "../helper"; import { getDummyConnection } from "../helper";
@@ -1,5 +1,5 @@
import { afterAll, describe, expect, test } from "bun:test"; import { afterAll, describe, expect, test } from "bun:test";
import { EntityManager } from "data/entities/EntityManager"; import { EntityManager } from "../../../../src/data";
import { getDummyConnection } from "../../helper"; import { getDummyConnection } from "../../helper";
const { dummyConnection, afterAllCleanup } = getDummyConnection(); const { dummyConnection, afterAllCleanup } = getDummyConnection();
@@ -1,10 +1,9 @@
import { bunTestRunner } from "adapter/bun/test";
import { describe, expect, test } from "bun:test"; import { describe, expect, test } from "bun:test";
import { BooleanField } from "data/fields"; import { BooleanField } from "../../../../src/data";
import { fieldTestSuite, transformPersist } from "data/fields/field-test-suite"; import { fieldTestSuite, transformPersist } from "data/fields/field-test-suite";
describe("[data] BooleanField", async () => { describe("[data] BooleanField", async () => {
fieldTestSuite(bunTestRunner, BooleanField, { defaultValue: true, schemaType: "boolean" }); fieldTestSuite({ expect, test }, BooleanField, { defaultValue: true, schemaType: "boolean" });
test("transformRetrieve", async () => { test("transformRetrieve", async () => {
const field = new BooleanField("test"); const field = new BooleanField("test");
@@ -1,5 +1,5 @@
import { describe, test } from "bun:test"; import { describe, expect, test } from "bun:test";
import { DateField } from "data/fields"; import { DateField, dateFieldConfigSchema } from "../../../../src/data";
import { fieldTestSuite } from "data/fields/field-test-suite"; import { fieldTestSuite } from "data/fields/field-test-suite";
import { bunTestRunner } from "adapter/bun/test"; import { bunTestRunner } from "adapter/bun/test";
@@ -1,6 +1,5 @@
import { bunTestRunner } from "adapter/bun/test";
import { describe, expect, test } from "bun:test"; import { describe, expect, test } from "bun:test";
import { EnumField } from "data/fields"; import { EnumField } from "../../../../src/data";
import { fieldTestSuite, transformPersist } from "data/fields/field-test-suite"; import { fieldTestSuite, transformPersist } from "data/fields/field-test-suite";
function options(strings: string[]) { function options(strings: string[]) {
@@ -9,7 +8,7 @@ function options(strings: string[]) {
describe("[data] EnumField", async () => { describe("[data] EnumField", async () => {
fieldTestSuite( fieldTestSuite(
bunTestRunner, { expect, test },
// @ts-ignore // @ts-ignore
EnumField, EnumField,
{ defaultValue: "a", schemaType: "text" }, { defaultValue: "a", schemaType: "text" },
+1 -1
View File
@@ -2,7 +2,7 @@ import { describe, expect, test } from "bun:test";
import { baseFieldConfigSchema, Field } from "../../../../src/data/fields/Field"; import { baseFieldConfigSchema, Field } from "../../../../src/data/fields/Field";
import { fieldTestSuite } from "data/fields/field-test-suite"; import { fieldTestSuite } from "data/fields/field-test-suite";
import { bunTestRunner } from "adapter/bun/test"; import { bunTestRunner } from "adapter/bun/test";
import { stripMark } from "core/utils/schema"; import { stripMark } from "core/object/schema";
describe("[data] Field", async () => { describe("[data] Field", async () => {
class FieldSpec extends Field { class FieldSpec extends Field {
@@ -1,7 +1,6 @@
import { describe, expect, test } from "bun:test"; import { describe, expect, test } from "bun:test";
import { Entity } from "data/entities"; import { Entity, EntityIndex, Field } from "../../../../src/data";
import { Field, EntityIndex } from "data/fields"; import { s } from "core/object/schema";
import { s } from "core/utils/schema";
class TestField extends Field { class TestField extends Field {
protected getSchema(): any { protected getSchema(): any {
@@ -1,11 +1,10 @@
import { bunTestRunner } from "adapter/bun/test";
import { describe, expect, test } from "bun:test"; import { describe, expect, test } from "bun:test";
import { JsonField } from "data/fields"; import { JsonField } from "../../../../src/data";
import { fieldTestSuite, transformPersist } from "data/fields/field-test-suite"; import { fieldTestSuite, transformPersist } from "data/fields/field-test-suite";
describe("[data] JsonField", async () => { describe("[data] JsonField", async () => {
const field = new JsonField("test"); const field = new JsonField("test");
fieldTestSuite(bunTestRunner, JsonField, { fieldTestSuite({ expect, test }, JsonField, {
defaultValue: { a: 1 }, defaultValue: { a: 1 },
sampleValues: ["string", { test: 1 }, 1], sampleValues: ["string", { test: 1 }, 1],
schemaType: "text", schemaType: "text",
@@ -1,5 +1,5 @@
import { describe, expect, test } from "bun:test"; import { describe, expect, test } from "bun:test";
import { JsonSchemaField } from "data/fields"; import { JsonSchemaField } from "../../../../src/data";
import { fieldTestSuite } from "data/fields/field-test-suite"; import { fieldTestSuite } from "data/fields/field-test-suite";
describe("[data] JsonSchemaField", async () => { describe("[data] JsonSchemaField", async () => {
@@ -1,6 +1,5 @@
import { bunTestRunner } from "adapter/bun/test";
import { describe, expect, test } from "bun:test"; import { describe, expect, test } from "bun:test";
import { NumberField } from "data/fields"; import { NumberField } from "../../../../src/data";
import { fieldTestSuite, transformPersist } from "data/fields/field-test-suite"; import { fieldTestSuite, transformPersist } from "data/fields/field-test-suite";
describe("[data] NumberField", async () => { describe("[data] NumberField", async () => {
@@ -16,5 +15,5 @@ describe("[data] NumberField", async () => {
expect(transformPersist(field2, 10000)).resolves.toBe(10000); expect(transformPersist(field2, 10000)).resolves.toBe(10000);
}); });
fieldTestSuite(bunTestRunner, NumberField, { defaultValue: 12, schemaType: "integer" }); fieldTestSuite({ expect, test }, NumberField, { defaultValue: 12, schemaType: "integer" });
}); });
@@ -1,5 +1,5 @@
import { describe, expect, test } from "bun:test"; import { describe, expect, test } from "bun:test";
import { PrimaryField } from "data/fields"; import { PrimaryField } from "../../../../src/data";
describe("[data] PrimaryField", async () => { describe("[data] PrimaryField", async () => {
const field = new PrimaryField("primary"); const field = new PrimaryField("primary");
@@ -1,5 +1,5 @@
import { describe, expect, test } from "bun:test"; import { describe, expect, test } from "bun:test";
import { TextField } from "data/fields"; import { TextField, textFieldConfigSchema } from "../../../../src/data";
import { fieldTestSuite, transformPersist } from "data/fields/field-test-suite"; import { fieldTestSuite, transformPersist } from "data/fields/field-test-suite";
import { bunTestRunner } from "adapter/bun/test"; import { bunTestRunner } from "adapter/bun/test";
@@ -1,11 +1,11 @@
import { describe, expect, it, test } from "bun:test"; import { describe, expect, it, test } from "bun:test";
import { Entity, type EntityManager } from "data/entities"; import { Entity, type EntityManager } from "../../../../src/data";
import { import {
type BaseRelationConfig, type BaseRelationConfig,
EntityRelation, EntityRelation,
EntityRelationAnchor, EntityRelationAnchor,
RelationTypes, RelationTypes,
} from "data/relations"; } from "../../../../src/data/relations";
class TestEntityRelation extends EntityRelation { class TestEntityRelation extends EntityRelation {
constructor(config?: BaseRelationConfig) { constructor(config?: BaseRelationConfig) {
@@ -24,11 +24,11 @@ class TestEntityRelation extends EntityRelation {
return this; return this;
} }
buildWith(): any { buildWith(a: any, b: any, c: any): any {
return; return;
} }
buildJoin(): any { buildJoin(a: any, b: any): any {
return; return;
} }
} }
@@ -1,24 +0,0 @@
import { describe, it, expect } from "bun:test";
import * as sDirect from "jsonv-ts";
import { s as sFromBknd } from "bknd/utils";
describe("jsonv-ts resolution", () => {
it("should resolve to a single instance", () => {
const sameNamespace = sDirect === (sFromBknd as unknown as typeof sDirect);
// If this fails, two instances are being loaded via different specifiers/paths
expect(sameNamespace).toBe(true);
});
it("should resolve specifiers to a single package path", async () => {
const base = await import.meta.resolve("jsonv-ts");
const hono = await import.meta.resolve("jsonv-ts/hono");
const mcp = await import.meta.resolve("jsonv-ts/mcp");
expect(typeof base).toBe("string");
expect(typeof hono).toBe("string");
expect(typeof mcp).toBe("string");
// They can be different files (subpath exports), but they should share the same package root
const pkgRoot = (p: string) => p.slice(0, p.lastIndexOf("jsonv-ts") + "jsonv-ts".length);
expect(pkgRoot(base)).toBe(pkgRoot(hono));
expect(pkgRoot(base)).toBe(pkgRoot(mcp));
});
});
+1 -1
View File
@@ -1,6 +1,6 @@
import { describe, expect, test } from "bun:test"; import { describe, expect, test } from "bun:test";
import { Flow, LogTask, SubFlowTask, RenderTask, Task } from "../../src/flows"; import { Flow, LogTask, SubFlowTask, RenderTask, Task } from "../../src/flows";
import { s } from "core/utils/schema"; import { s } from "core/object/schema";
export class StringifyTask<Output extends string> extends Task< export class StringifyTask<Output extends string> extends Task<
typeof StringifyTask.schema, typeof StringifyTask.schema,
+1 -1
View File
@@ -1,7 +1,7 @@
import { describe, expect, test } from "bun:test"; import { describe, expect, test } from "bun:test";
import { Task } from "../../src/flows"; import { Task } from "../../src/flows";
import { dynamic } from "../../src/flows/tasks/Task"; import { dynamic } from "../../src/flows/tasks/Task";
import { s } from "core/utils/schema"; import { s } from "core/object/schema";
describe.skip("Task", async () => { describe.skip("Task", async () => {
test("resolveParams: template with parse", async () => { test("resolveParams: template with parse", async () => {
+1 -1
View File
@@ -1,7 +1,7 @@
import { describe, expect, test } from "bun:test"; import { describe, expect, test } from "bun:test";
import { Hono } from "hono"; import { Hono } from "hono";
import { Event, EventManager } from "../../src/core/events"; import { Event, EventManager } from "../../src/core/events";
import { s, parse } from "core/utils/schema"; import { s, parse } from "core/object/schema";
import { EventTrigger, Flow, HttpTrigger, type InputsMap, Task } from "../../src/flows"; import { EventTrigger, Flow, HttpTrigger, type InputsMap, Task } from "../../src/flows";
import { dynamic } from "../../src/flows/tasks/Task"; import { dynamic } from "../../src/flows/tasks/Task";
+1 -1
View File
@@ -2,7 +2,7 @@
import { describe, expect, test } from "bun:test"; import { describe, expect, test } from "bun:test";
import { isEqual } from "lodash-es"; import { isEqual } from "lodash-es";
import { _jsonp, withDisabledConsole } from "../../src/core/utils"; import { _jsonp, withDisabledConsole } from "../../src/core/utils";
import { s } from "core/utils/schema"; import { s } from "core/object/schema";
import { Condition, ExecutionEvent, FetchTask, Flow, LogTask, Task } from "../../src/flows"; import { Condition, ExecutionEvent, FetchTask, Flow, LogTask, Task } from "../../src/flows";
/*beforeAll(disableConsoleLog); /*beforeAll(disableConsoleLog);
+2 -3
View File
@@ -2,12 +2,11 @@ import { unlink } from "node:fs/promises";
import type { SelectQueryBuilder, SqliteDatabase } from "kysely"; import type { SelectQueryBuilder, SqliteDatabase } from "kysely";
import Database from "libsql"; import Database from "libsql";
import { format as sqlFormat } from "sql-formatter"; import { format as sqlFormat } from "sql-formatter";
import { type Connection, EntityManager, SqliteLocalConnection } from "../src/data";
import type { em as protoEm } from "../src/data/prototype"; import type { em as protoEm } from "../src/data/prototype";
import { writeFile } from "node:fs/promises"; import { writeFile } from "node:fs/promises";
import { join } from "node:path"; import { join } from "node:path";
import { slugify } from "bknd/utils"; import { slugify } from "core/utils/strings";
import { type Connection, SqliteLocalConnection } from "data/connection";
import { EntityManager } from "data/entities/EntityManager";
export function getDummyDatabase(memory: boolean = true): { export function getDummyDatabase(memory: boolean = true): {
dummyDb: SqliteDatabase; dummyDb: SqliteDatabase;
+3 -5
View File
@@ -1,17 +1,12 @@
/// <reference types="@types/bun" /> /// <reference types="@types/bun" />
import { afterAll, beforeAll, describe, expect, test } from "bun:test"; import { afterAll, beforeAll, describe, expect, test } from "bun:test";
import { registries } from "../../src";
import { createApp } from "core/test/utils"; import { createApp } from "core/test/utils";
import { mergeObject, randomString } from "../../src/core/utils"; import { mergeObject, randomString } from "../../src/core/utils";
import type { TAppMediaConfig } from "../../src/media/media-schema"; import type { TAppMediaConfig } from "../../src/media/media-schema";
import { StorageLocalAdapter } from "adapter/node/storage/StorageLocalAdapter"; import { StorageLocalAdapter } from "adapter/node/storage/StorageLocalAdapter";
import { assetsPath, assetsTmpPath, disableConsoleLog, enableConsoleLog } from "../helper"; import { assetsPath, assetsTmpPath, disableConsoleLog, enableConsoleLog } from "../helper";
beforeAll(() => {
registries.media.register("local", StorageLocalAdapter);
});
const path = `${assetsPath}/image.png`; const path = `${assetsPath}/image.png`;
async function makeApp(mediaOverride: Partial<TAppMediaConfig> = {}) { async function makeApp(mediaOverride: Partial<TAppMediaConfig> = {}) {
@@ -32,6 +27,8 @@ async function makeApp(mediaOverride: Partial<TAppMediaConfig> = {}) {
}, },
}); });
app.module.media.adapters.set("local", StorageLocalAdapter);
await app.build(); await app.build();
return app; return app;
} }
@@ -54,6 +51,7 @@ describe("MediaController", () => {
body: file, body: file,
}); });
const result = (await res.json()) as any; const result = (await res.json()) as any;
console.log(result);
expect(result.name).toBe(name); expect(result.name).toBe(name);
const destFile = Bun.file(assetsTmpPath + "/" + name); const destFile = Bun.file(assetsTmpPath + "/" + name);
+1 -1
View File
@@ -1,7 +1,7 @@
import { describe, expect, test } from "bun:test"; import { describe, expect, test } from "bun:test";
import { type FileBody, Storage } from "../../src/media/storage/Storage"; import { type FileBody, Storage } from "../../src/media/storage/Storage";
import * as StorageEvents from "../../src/media/storage/events"; import * as StorageEvents from "../../src/media/storage/events";
import { StorageAdapter } from "media/storage/StorageAdapter"; import { StorageAdapter } from "media";
class TestAdapter extends StorageAdapter { class TestAdapter extends StorageAdapter {
files: Record<string, FileBody> = {}; files: Record<string, FileBody> = {};
+3 -2
View File
@@ -1,9 +1,10 @@
import { afterAll, beforeAll, beforeEach, describe, expect, spyOn, test } from "bun:test"; import { afterAll, beforeAll, beforeEach, describe, expect, spyOn, test } from "bun:test";
import { createApp } from "core/test/utils"; import { createApp } from "core/test/utils";
import { AuthController } from "../../src/auth/api/AuthController"; import { AuthController } from "../../src/auth/api/AuthController";
import { em, entity, make, text } from "data/prototype"; import { em, entity, make, text } from "../../src/data";
import { AppAuth, type ModuleBuildContext } from "modules"; import { AppAuth, type ModuleBuildContext } from "../../src/modules";
import { disableConsoleLog, enableConsoleLog } from "../helper"; import { disableConsoleLog, enableConsoleLog } from "../helper";
// @ts-ignore
import { makeCtx, moduleTestSuite } from "./module-test-suite"; import { makeCtx, moduleTestSuite } from "./module-test-suite";
describe("AppAuth", () => { describe("AppAuth", () => {
+1 -1
View File
@@ -1,5 +1,5 @@
import { beforeEach, describe, expect, test } from "bun:test"; import { beforeEach, describe, expect, test } from "bun:test";
import { parse } from "core/utils/schema"; import { parse } from "core/object/schema";
import { fieldsSchema } from "../../src/data/data-schema"; import { fieldsSchema } from "../../src/data/data-schema";
import { AppData, type ModuleBuildContext } from "../../src/modules"; import { AppData, type ModuleBuildContext } from "../../src/modules";
import { makeCtx, moduleTestSuite } from "./module-test-suite"; import { makeCtx, moduleTestSuite } from "./module-test-suite";
+3 -8
View File
@@ -1,21 +1,15 @@
import { describe, expect, test } from "bun:test"; import { describe, expect, test } from "bun:test";
import { createApp } from "core/test/utils"; import { createApp } from "core/test/utils";
import { em, entity, text } from "data/prototype"; import { em, entity, text } from "../../src/data";
import { registries } from "modules/registries";
import { StorageLocalAdapter } from "adapter/node/storage/StorageLocalAdapter"; import { StorageLocalAdapter } from "adapter/node/storage/StorageLocalAdapter";
import { AppMedia } from "../../src/media/AppMedia"; import { AppMedia } from "../../src/media/AppMedia";
import { moduleTestSuite } from "./module-test-suite"; import { moduleTestSuite } from "./module-test-suite";
describe("AppMedia", () => { describe("AppMedia", () => {
test.only("...", () => {
const media = new AppMedia();
console.log(media.toJSON());
});
moduleTestSuite(AppMedia); moduleTestSuite(AppMedia);
test("should allow additional fields", async () => { test("should allow additional fields", async () => {
registries.media.register("local", StorageLocalAdapter); //registries.media.register("local", StorageLocalAdapter);
const app = createApp({ const app = createApp({
initialConfig: { initialConfig: {
@@ -36,6 +30,7 @@ describe("AppMedia", () => {
}).toJSON(), }).toJSON(),
}, },
}); });
app.module.media.adapters.set("local", StorageLocalAdapter);
await app.build(); await app.build();
+2 -3
View File
@@ -1,7 +1,6 @@
import { describe, expect, test } from "bun:test"; import { describe, expect, test } from "bun:test";
import { s, stripMark } from "core/utils/schema"; import { s, stripMark } from "core/object/schema";
import { em, entity, index, text } from "data/prototype"; import { EntityManager, em, entity, index, text } from "../../src/data";
import { EntityManager } from "data/entities/EntityManager";
import { DummyConnection } from "../../src/data/connection/DummyConnection"; import { DummyConnection } from "../../src/data/connection/DummyConnection";
import { Module } from "../../src/modules/Module"; import { Module } from "../../src/modules/Module";
import { ModuleHelper } from "modules/ModuleHelper"; import { ModuleHelper } from "modules/ModuleHelper";
+2 -4
View File
@@ -1,13 +1,11 @@
import { afterEach, beforeEach, describe, expect, mock, test } from "bun:test"; import { afterEach, beforeEach, describe, expect, mock, test } from "bun:test";
import { disableConsoleLog, enableConsoleLog } from "core/utils"; import { disableConsoleLog, enableConsoleLog } from "core/utils";
import { Connection, entity, text } from "data";
import { Module } from "modules/Module"; import { Module } from "modules/Module";
import { type ConfigTable, getDefaultConfig, ModuleManager } from "modules/ModuleManager"; import { type ConfigTable, getDefaultConfig, ModuleManager } from "modules/ModuleManager";
import { CURRENT_VERSION, TABLE_NAME } from "modules/migrations"; import { CURRENT_VERSION, TABLE_NAME } from "modules/migrations";
import { getDummyConnection } from "../helper"; import { getDummyConnection } from "../helper";
import { s, stripMark } from "core/utils/schema"; import { s, stripMark } from "core/object/schema";
import { Connection } from "data/connection/Connection";
import { entity, text } from "data/prototype";
describe("ModuleManager", async () => { describe("ModuleManager", async () => {
test("s1: no config, no build", async () => { test("s1: no config, no build", async () => {
+5 -6
View File
@@ -1,13 +1,13 @@
import { beforeEach, describe, expect, it } from "bun:test"; import { beforeEach, describe, expect, it } from "bun:test";
import { Hono } from "hono"; import { Hono } from "hono";
import { Guard } from "auth/authorize/Guard"; import { Guard } from "../../src/auth";
import { EventManager } from "core/events"; import { DebugLogger } from "../../src/core";
import { EntityManager } from "data/entities/EntityManager"; import { EventManager } from "../../src/core/events";
import { Module, type ModuleBuildContext } from "modules/Module"; import { EntityManager } from "../../src/data";
import { Module, type ModuleBuildContext } from "../../src/modules/Module";
import { getDummyConnection } from "../helper"; import { getDummyConnection } from "../helper";
import { ModuleHelper } from "modules/ModuleHelper"; import { ModuleHelper } from "modules/ModuleHelper";
import { DebugLogger, McpServer } from "bknd/utils";
export function makeCtx(overrides?: Partial<ModuleBuildContext>): ModuleBuildContext { export function makeCtx(overrides?: Partial<ModuleBuildContext>): ModuleBuildContext {
const { dummyConnection } = getDummyConnection(); const { dummyConnection } = getDummyConnection();
@@ -19,7 +19,6 @@ export function makeCtx(overrides?: Partial<ModuleBuildContext>): ModuleBuildCon
guard: new Guard(), guard: new Guard(),
flags: Module.ctx_flags, flags: Module.ctx_flags,
logger: new DebugLogger(false), logger: new DebugLogger(false),
mcp: new McpServer(),
...overrides, ...overrides,
}; };
return { return {
+1 -3
View File
@@ -102,9 +102,7 @@ describe("json form", () => {
] satisfies [string, Exclude<JSONSchema, boolean>, boolean][]; ] satisfies [string, Exclude<JSONSchema, boolean>, boolean][];
for (const [pointer, schema, output] of examples) { for (const [pointer, schema, output] of examples) {
expect(utils.isRequired(new Draft2019(schema), pointer, schema), `${pointer} `).toBe( expect(utils.isRequired(new Draft2019(schema), pointer, schema)).toBe(output);
output,
);
} }
}); });
+1 -20
View File
@@ -1,24 +1,6 @@
import pkg from "./package.json" with { type: "json" }; import pkg from "./package.json" with { type: "json" };
import c from "picocolors"; import c from "picocolors";
import { formatNumber } from "bknd/utils"; import { formatNumber } from "core/utils";
import * as esbuild from "esbuild";
if (process.env.DEBUG) {
await esbuild.build({
entryPoints: ["./src/cli/index.ts"],
outdir: "./dist/cli",
platform: "node",
minify: false,
format: "esm",
bundle: true,
external: ["jsonv-ts", "jsonv-ts/*"],
define: {
__isDev: "0",
__version: JSON.stringify(pkg.version),
},
});
process.exit(0);
}
const result = await Bun.build({ const result = await Bun.build({
entrypoints: ["./src/cli/index.ts"], entrypoints: ["./src/cli/index.ts"],
@@ -26,7 +8,6 @@ const result = await Bun.build({
outdir: "./dist/cli", outdir: "./dist/cli",
env: "PUBLIC_*", env: "PUBLIC_*",
minify: true, minify: true,
external: ["jsonv-ts", "jsonv-ts/*"],
define: { define: {
__isDev: "0", __isDev: "0",
__version: JSON.stringify(pkg.version), __version: JSON.stringify(pkg.version),
+82 -90
View File
@@ -1,7 +1,6 @@
import { $ } from "bun"; import { $ } from "bun";
import * as tsup from "tsup"; import * as tsup from "tsup";
import pkg from "./package.json" with { type: "json" }; import pkg from "./package.json" with { type: "json" };
import c from "picocolors";
const args = process.argv.slice(2); const args = process.argv.slice(2);
const watch = args.includes("--watch"); const watch = args.includes("--watch");
@@ -10,14 +9,6 @@ const types = args.includes("--types");
const sourcemap = args.includes("--sourcemap"); const sourcemap = args.includes("--sourcemap");
const clean = args.includes("--clean"); const clean = args.includes("--clean");
// silence tsup
const oldConsole = {
log: console.log,
warn: console.warn,
};
console.log = () => {};
console.warn = () => {};
const define = { const define = {
__isDev: "0", __isDev: "0",
__version: JSON.stringify(pkg.version), __version: JSON.stringify(pkg.version),
@@ -36,11 +27,11 @@ function buildTypes() {
Bun.spawn(["bun", "build:types"], { Bun.spawn(["bun", "build:types"], {
stdout: "inherit", stdout: "inherit",
onExit: () => { onExit: () => {
oldConsole.log(c.cyan("[Types]"), c.green("built")); console.info("Types built");
Bun.spawn(["bun", "tsc-alias"], { Bun.spawn(["bun", "tsc-alias"], {
stdout: "inherit", stdout: "inherit",
onExit: () => { onExit: () => {
oldConsole.log(c.cyan("[Types]"), c.green("aliased")); console.info("Types aliased");
types_running = false; types_running = false;
}, },
}); });
@@ -48,10 +39,6 @@ function buildTypes() {
}); });
} }
if (types && !watch) {
buildTypes();
}
let watcher_timeout: any; let watcher_timeout: any;
function delayTypes() { function delayTypes() {
if (!watch || !types) return; if (!watch || !types) return;
@@ -61,6 +48,17 @@ function delayTypes() {
watcher_timeout = setTimeout(buildTypes, 1000); watcher_timeout = setTimeout(buildTypes, 1000);
} }
if (types && !watch) {
buildTypes();
}
function banner(title: string) {
console.info("");
console.info("=".repeat(40));
console.info(title.toUpperCase());
console.info("-".repeat(40));
}
// collection of always-external packages // collection of always-external packages
const external = [ const external = [
"bun:test", "bun:test",
@@ -69,20 +67,26 @@ const external = [
"@libsql/client", "@libsql/client",
"bknd", "bknd",
/^bknd\/.*/, /^bknd\/.*/,
"jsonv-ts",
/^jsonv-ts\/.*/,
] as const; ] as const;
/** /**
* Building backend and general API * Building backend and general API
*/ */
async function buildApi() { async function buildApi() {
banner("Building API");
await tsup.build({ await tsup.build({
minify, minify,
sourcemap, sourcemap,
watch, watch,
define, define,
entry: ["src/index.ts", "src/core/utils/index.ts", "src/plugins/index.ts"], entry: [
"src/index.ts",
"src/core/index.ts",
"src/core/utils/index.ts",
"src/data/index.ts",
"src/media/index.ts",
"src/plugins/index.ts",
],
outDir: "dist", outDir: "dist",
external: [...external], external: [...external],
metafile: true, metafile: true,
@@ -95,7 +99,6 @@ async function buildApi() {
}, },
onSuccess: async () => { onSuccess: async () => {
delayTypes(); delayTypes();
oldConsole.log(c.cyan("[API]"), c.green("built"));
}, },
}); });
} }
@@ -139,6 +142,7 @@ async function buildUi() {
}, },
} satisfies tsup.Options; } satisfies tsup.Options;
banner("Building UI");
await tsup.build({ await tsup.build({
...base, ...base,
entry: ["src/ui/index.ts", "src/ui/main.css", "src/ui/styles.css"], entry: ["src/ui/index.ts", "src/ui/main.css", "src/ui/styles.css"],
@@ -146,10 +150,10 @@ async function buildUi() {
onSuccess: async () => { onSuccess: async () => {
await rewriteClient("./dist/ui/index.js"); await rewriteClient("./dist/ui/index.js");
delayTypes(); delayTypes();
oldConsole.log(c.cyan("[UI]"), c.green("built"));
}, },
}); });
banner("Building Client");
await tsup.build({ await tsup.build({
...base, ...base,
entry: ["src/ui/client/index.ts"], entry: ["src/ui/client/index.ts"],
@@ -157,7 +161,6 @@ async function buildUi() {
onSuccess: async () => { onSuccess: async () => {
await rewriteClient("./dist/ui/client/index.js"); await rewriteClient("./dist/ui/client/index.js");
delayTypes(); delayTypes();
oldConsole.log(c.cyan("[UI]"), "Client", c.green("built"));
}, },
}); });
} }
@@ -168,6 +171,7 @@ async function buildUi() {
* - ui/client is external, and after built replaced with "bknd/client" * - ui/client is external, and after built replaced with "bknd/client"
*/ */
async function buildUiElements() { async function buildUiElements() {
banner("Building UI Elements");
await tsup.build({ await tsup.build({
minify, minify,
sourcemap, sourcemap,
@@ -201,7 +205,6 @@ async function buildUiElements() {
onSuccess: async () => { onSuccess: async () => {
await rewriteClient("./dist/ui/elements/index.js"); await rewriteClient("./dist/ui/elements/index.js");
delayTypes(); delayTypes();
oldConsole.log(c.cyan("[UI]"), "Elements", c.green("built"));
}, },
}); });
} }
@@ -222,7 +225,6 @@ function baseConfig(adapter: string, overrides: Partial<tsup.Options> = {}): tsu
splitting: false, splitting: false,
onSuccess: async () => { onSuccess: async () => {
delayTypes(); delayTypes();
oldConsole.log(c.cyan("[Adapter]"), adapter || "base", c.green("built"));
}, },
...overrides, ...overrides,
define: { define: {
@@ -241,75 +243,65 @@ function baseConfig(adapter: string, overrides: Partial<tsup.Options> = {}): tsu
} }
async function buildAdapters() { async function buildAdapters() {
await Promise.all([ banner("Building Adapters");
// base adapter handles // base adapter handles
tsup.build({ await tsup.build({
...baseConfig(""), ...baseConfig(""),
entry: ["src/adapter/index.ts"], entry: ["src/adapter/index.ts"],
outDir: "dist/adapter", outDir: "dist/adapter",
}), });
// specific adatpers // specific adatpers
tsup.build(baseConfig("react-router")), await tsup.build(baseConfig("react-router"));
tsup.build( await tsup.build(
baseConfig("bun", { baseConfig("bun", {
external: [/^bun\:.*/],
}),
),
tsup.build(baseConfig("astro")),
tsup.build(baseConfig("aws")),
tsup.build(
baseConfig("cloudflare", {
external: ["wrangler", "node:process"],
}),
),
tsup.build(
baseConfig("cloudflare/proxy", {
entry: ["src/adapter/cloudflare/proxy.ts"],
outDir: "dist/adapter/cloudflare",
metafile: false,
external: [/bknd/, "wrangler", "node:process"],
}),
),
tsup.build({
...baseConfig("vite"),
platform: "node",
}),
tsup.build({
...baseConfig("nextjs"),
platform: "node",
}),
tsup.build({
...baseConfig("node"),
platform: "node",
}),
tsup.build({
...baseConfig("sqlite/edge"),
entry: ["src/adapter/sqlite/edge.ts"],
outDir: "dist/adapter/sqlite",
metafile: false,
}),
tsup.build({
...baseConfig("sqlite/node"),
entry: ["src/adapter/sqlite/node.ts"],
outDir: "dist/adapter/sqlite",
platform: "node",
metafile: false,
}),
tsup.build({
...baseConfig("sqlite/bun"),
entry: ["src/adapter/sqlite/bun.ts"],
outDir: "dist/adapter/sqlite",
metafile: false,
external: [/^bun\:.*/], external: [/^bun\:.*/],
}), }),
]); );
await tsup.build(baseConfig("astro"));
await tsup.build(baseConfig("aws"));
await tsup.build(baseConfig("cloudflare"));
await tsup.build({
...baseConfig("vite"),
platform: "node",
});
await tsup.build({
...baseConfig("nextjs"),
platform: "node",
});
await tsup.build({
...baseConfig("node"),
platform: "node",
});
await tsup.build({
...baseConfig("sqlite/edge"),
entry: ["src/adapter/sqlite/edge.ts"],
outDir: "dist/adapter/sqlite",
metafile: false,
});
await tsup.build({
...baseConfig("sqlite/node"),
entry: ["src/adapter/sqlite/node.ts"],
outDir: "dist/adapter/sqlite",
platform: "node",
metafile: false,
});
await tsup.build({
...baseConfig("sqlite/bun"),
entry: ["src/adapter/sqlite/bun.ts"],
outDir: "dist/adapter/sqlite",
metafile: false,
external: [/^bun\:.*/],
});
} }
await Promise.all([buildApi(), buildUi(), buildUiElements(), buildAdapters()]); await buildApi();
await buildUi();
await buildUiElements();
await buildAdapters();
+1 -2
View File
@@ -2,5 +2,4 @@
#registry = "http://localhost:4873" #registry = "http://localhost:4873"
[test] [test]
coverageSkipTestFiles = true coverageSkipTestFiles = true
console.depth = 10
-35
View File
@@ -1,35 +0,0 @@
import { createApp } from "bknd/adapter/bun";
async function generate() {
console.info("Generating MCP documentation...");
const app = await createApp({
initialConfig: {
server: {
mcp: {
enabled: true,
},
},
auth: {
enabled: true,
},
media: {
enabled: true,
adapter: {
type: "local",
config: {
path: "./",
},
},
},
},
});
await app.build();
const res = await app.server.request("/mcp?explain=1");
const { tools, resources } = await res.json();
await Bun.write("../docs/mcp.json", JSON.stringify({ tools, resources }, null, 2));
console.info("MCP documentation generated.");
}
void generate();
+29 -19
View File
@@ -3,7 +3,7 @@
"type": "module", "type": "module",
"sideEffects": false, "sideEffects": false,
"bin": "./dist/cli/index.js", "bin": "./dist/cli/index.js",
"version": "0.17.0", "version": "0.16.0-rc.0",
"description": "Lightweight Firebase/Supabase alternative built to run anywhere — incl. Next.js, React Router, Astro, Cloudflare, Bun, Node, AWS Lambda & more.", "description": "Lightweight Firebase/Supabase alternative built to run anywhere — incl. Next.js, React Router, Astro, Cloudflare, Bun, Node, AWS Lambda & more.",
"homepage": "https://bknd.io", "homepage": "https://bknd.io",
"repository": { "repository": {
@@ -13,7 +13,6 @@
"bugs": { "bugs": {
"url": "https://github.com/bknd-io/bknd/issues" "url": "https://github.com/bknd-io/bknd/issues"
}, },
"packageManager": "bun@1.2.19",
"engines": { "engines": {
"node": ">=22" "node": ">=22"
}, },
@@ -39,12 +38,11 @@
"test:adapters": "bun test src/adapter/**/*.adapter.spec.ts --bail", "test:adapters": "bun test src/adapter/**/*.adapter.spec.ts --bail",
"test:coverage": "ALL_TESTS=1 bun test --bail --coverage", "test:coverage": "ALL_TESTS=1 bun test --bail --coverage",
"test:vitest:coverage": "vitest run --coverage", "test:vitest:coverage": "vitest run --coverage",
"test:e2e": "VITE_DB_URL=:memory: playwright test", "test:e2e": "playwright test",
"test:e2e:adapters": "VITE_DB_URL=:memory: bun run e2e/adapters.ts", "test:e2e:adapters": "bun run e2e/adapters.ts",
"test:e2e:ui": "VITE_DB_URL=:memory: playwright test --ui", "test:e2e:ui": "playwright test --ui",
"test:e2e:debug": "VITE_DB_URL=:memory: playwright test --debug", "test:e2e:debug": "playwright test --debug",
"test:e2e:report": "VITE_DB_URL=:memory: playwright show-report", "test:e2e:report": "playwright show-report"
"docs:build-assets": "bun internal/docs.build-assets.ts"
}, },
"license": "FSL-1.1-MIT", "license": "FSL-1.1-MIT",
"dependencies": { "dependencies": {
@@ -62,11 +60,11 @@
"bcryptjs": "^3.0.2", "bcryptjs": "^3.0.2",
"dayjs": "^1.11.13", "dayjs": "^1.11.13",
"fast-xml-parser": "^5.0.8", "fast-xml-parser": "^5.0.8",
"hono": "4.8.3", "hono": "^4.7.11",
"json-schema-form-react": "^0.0.2",
"json-schema-library": "10.0.0-rc7", "json-schema-library": "10.0.0-rc7",
"json-schema-to-ts": "^3.1.1", "json-schema-to-ts": "^3.1.1",
"jsonv-ts": "0.8.2", "kysely": "^0.27.6",
"kysely": "0.27.6",
"lodash-es": "^4.17.21", "lodash-es": "^4.17.21",
"oauth4webapi": "^2.11.1", "oauth4webapi": "^2.11.1",
"object-path-immutable": "^4.1.2", "object-path-immutable": "^4.1.2",
@@ -76,7 +74,6 @@
"devDependencies": { "devDependencies": {
"@aws-sdk/client-s3": "^3.758.0", "@aws-sdk/client-s3": "^3.758.0",
"@bluwy/giget-core": "^0.1.2", "@bluwy/giget-core": "^0.1.2",
"@clack/prompts": "^0.11.0",
"@cloudflare/vitest-pool-workers": "^0.8.38", "@cloudflare/vitest-pool-workers": "^0.8.38",
"@cloudflare/workers-types": "^4.20250606.0", "@cloudflare/workers-types": "^4.20250606.0",
"@dagrejs/dagre": "^1.1.4", "@dagrejs/dagre": "^1.1.4",
@@ -103,6 +100,7 @@
"dotenv": "^16.4.7", "dotenv": "^16.4.7",
"jotai": "^2.12.2", "jotai": "^2.12.2",
"jsdom": "^26.0.0", "jsdom": "^26.0.0",
"jsonv-ts": "^0.2.2",
"kysely-d1": "^0.3.0", "kysely-d1": "^0.3.0",
"kysely-generic-sqlite": "^1.2.1", "kysely-generic-sqlite": "^1.2.1",
"libsql-stateless-easy": "^1.8.0", "libsql-stateless-easy": "^1.8.0",
@@ -163,6 +161,16 @@
"import": "./dist/ui/client/index.js", "import": "./dist/ui/client/index.js",
"require": "./dist/ui/client/index.js" "require": "./dist/ui/client/index.js"
}, },
"./data": {
"types": "./dist/types/data/index.d.ts",
"import": "./dist/data/index.js",
"require": "./dist/data/index.js"
},
"./core": {
"types": "./dist/types/core/index.d.ts",
"import": "./dist/core/index.js",
"require": "./dist/core/index.js"
},
"./utils": { "./utils": {
"types": "./dist/types/core/utils/index.d.ts", "types": "./dist/types/core/utils/index.d.ts",
"import": "./dist/core/utils/index.js", "import": "./dist/core/utils/index.js",
@@ -173,6 +181,11 @@
"import": "./dist/cli/index.js", "import": "./dist/cli/index.js",
"require": "./dist/cli/index.js" "require": "./dist/cli/index.js"
}, },
"./media": {
"types": "./dist/types/media/index.d.ts",
"import": "./dist/media/index.js",
"require": "./dist/media/index.js"
},
"./plugins": { "./plugins": {
"types": "./dist/types/plugins/index.d.ts", "types": "./dist/types/plugins/index.d.ts",
"import": "./dist/plugins/index.js", "import": "./dist/plugins/index.js",
@@ -197,11 +210,6 @@
"import": "./dist/adapter/cloudflare/index.js", "import": "./dist/adapter/cloudflare/index.js",
"require": "./dist/adapter/cloudflare/index.js" "require": "./dist/adapter/cloudflare/index.js"
}, },
"./adapter/cloudflare/proxy": {
"types": "./dist/types/adapter/cloudflare/proxy.d.ts",
"import": "./dist/adapter/cloudflare/proxy.js",
"require": "./dist/adapter/cloudflare/proxy.js"
},
"./adapter": { "./adapter": {
"types": "./dist/types/adapter/index.d.ts", "types": "./dist/types/adapter/index.d.ts",
"import": "./dist/adapter/index.js" "import": "./dist/adapter/index.js"
@@ -243,13 +251,15 @@
}, },
"./dist/main.css": "./dist/ui/main.css", "./dist/main.css": "./dist/ui/main.css",
"./dist/styles.css": "./dist/ui/styles.css", "./dist/styles.css": "./dist/ui/styles.css",
"./dist/manifest.json": "./dist/static/.vite/manifest.json", "./dist/manifest.json": "./dist/static/.vite/manifest.json"
"./static/*": "./dist/static/*"
}, },
"typesVersions": { "typesVersions": {
"*": { "*": {
"data": ["./dist/types/data/index.d.ts"],
"core": ["./dist/types/core/index.d.ts"],
"utils": ["./dist/types/core/utils/index.d.ts"], "utils": ["./dist/types/core/utils/index.d.ts"],
"cli": ["./dist/types/cli/index.d.ts"], "cli": ["./dist/types/cli/index.d.ts"],
"media": ["./dist/types/media/index.d.ts"],
"plugins": ["./dist/types/plugins/index.d.ts"], "plugins": ["./dist/types/plugins/index.d.ts"],
"adapter": ["./dist/types/adapter/index.d.ts"], "adapter": ["./dist/types/adapter/index.d.ts"],
"adapter/cloudflare": ["./dist/types/adapter/cloudflare/index.d.ts"], "adapter/cloudflare": ["./dist/types/adapter/cloudflare/index.d.ts"],
+2 -2
View File
@@ -1,10 +1,10 @@
import type { SafeUser } from "bknd"; import type { SafeUser } from "auth";
import { AuthApi, type AuthApiOptions } from "auth/api/AuthApi"; import { AuthApi, type AuthApiOptions } from "auth/api/AuthApi";
import { DataApi, type DataApiOptions } from "data/api/DataApi"; import { DataApi, type DataApiOptions } from "data/api/DataApi";
import { decode } from "hono/jwt"; import { decode } from "hono/jwt";
import { MediaApi, type MediaApiOptions } from "media/api/MediaApi"; import { MediaApi, type MediaApiOptions } from "media/api/MediaApi";
import { SystemApi } from "modules/SystemApi"; import { SystemApi } from "modules/SystemApi";
import { omitKeys } from "bknd/utils"; import { omitKeys } from "core/utils";
import type { BaseModuleApiOptions } from "modules"; import type { BaseModuleApiOptions } from "modules";
export type TApiUser = SafeUser; export type TApiUser = SafeUser;
+11 -49
View File
@@ -1,5 +1,5 @@
import type { CreateUserPayload } from "auth/AppAuth"; import type { CreateUserPayload } from "auth/AppAuth";
import { $console, McpClient } from "bknd/utils"; import { $console } from "core/utils";
import { Event } from "core/events"; import { Event } from "core/events";
import type { em as prototypeEm } from "data/prototype"; import type { em as prototypeEm } from "data/prototype";
import { Connection } from "data/connection/Connection"; import { Connection } from "data/connection/Connection";
@@ -23,34 +23,14 @@ import type { IEmailDriver, ICacheDriver } from "core/drivers";
import { Api, type ApiOptions } from "Api"; import { Api, type ApiOptions } from "Api";
export type AppPluginConfig = { export type AppPluginConfig = {
/**
* The name of the plugin.
*/
name: string; name: string;
/**
* The schema of the plugin.
*/
schema?: () => MaybePromise<ReturnType<typeof prototypeEm> | void>; schema?: () => MaybePromise<ReturnType<typeof prototypeEm> | void>;
/**
* Called before the app is built.
*/
beforeBuild?: () => MaybePromise<void>; beforeBuild?: () => MaybePromise<void>;
/**
* Called after the app is built.
*/
onBuilt?: () => MaybePromise<void>; onBuilt?: () => MaybePromise<void>;
/**
* Called when the server is initialized.
*/
onServerInit?: (server: Hono<ServerEnv>) => MaybePromise<void>; onServerInit?: (server: Hono<ServerEnv>) => MaybePromise<void>;
/**
* Called when the app is booted.
*/
onBoot?: () => MaybePromise<void>;
/**
* Called when the app is first booted.
*/
onFirstBoot?: () => MaybePromise<void>; onFirstBoot?: () => MaybePromise<void>;
onBoot?: () => MaybePromise<void>;
onModulesCreated?: (modules: Modules) => void;
}; };
export type AppPlugin = (app: App) => AppPluginConfig; export type AppPlugin = (app: App) => AppPluginConfig;
@@ -61,9 +41,6 @@ export class AppConfigUpdatedEvent extends AppEvent<{
}> { }> {
static override slug = "app-config-updated"; static override slug = "app-config-updated";
} }
/**
* @type {Event<{ app: App }>}
*/
export class AppBuiltEvent extends AppEvent { export class AppBuiltEvent extends AppEvent {
static override slug = "app-built"; static override slug = "app-built";
} }
@@ -95,9 +72,6 @@ export type AppOptions = {
}; };
}; };
export type CreateAppConfig = { export type CreateAppConfig = {
/**
* bla
*/
connection?: Connection | { url: string }; connection?: Connection | { url: string };
initialConfig?: InitialModuleConfigs; initialConfig?: InitialModuleConfigs;
options?: AppOptions; options?: AppOptions;
@@ -117,7 +91,6 @@ export class App<C extends Connection = Connection, Options extends AppOptions =
private trigger_first_boot = false; private trigger_first_boot = false;
private _building: boolean = false; private _building: boolean = false;
private _systemController: SystemController | null = null;
constructor( constructor(
public connection: C, public connection: C,
@@ -141,6 +114,7 @@ export class App<C extends Connection = Connection, Options extends AppOptions =
onFirstBoot: this.onFirstBoot.bind(this), onFirstBoot: this.onFirstBoot.bind(this),
onServerInit: this.onServerInit.bind(this), onServerInit: this.onServerInit.bind(this),
onModulesBuilt: this.onModulesBuilt.bind(this), onModulesBuilt: this.onModulesBuilt.bind(this),
onModulesCreated: this.onModulesCreated.bind(this),
}); });
this.modules.ctx().emgr.registerEvents(AppEvents); this.modules.ctx().emgr.registerEvents(AppEvents);
} }
@@ -190,12 +164,11 @@ export class App<C extends Connection = Connection, Options extends AppOptions =
if (options?.sync) this.modules.ctx().flags.sync_required = true; if (options?.sync) this.modules.ctx().flags.sync_required = true;
await this.modules.build({ fetch: options?.fetch }); await this.modules.build({ fetch: options?.fetch });
const { guard } = this.modules.ctx(); const { guard, server } = this.modules.ctx();
// load system controller // load system controller
guard.registerPermissions(Object.values(SystemPermissions)); guard.registerPermissions(Object.values(SystemPermissions));
this._systemController = new SystemController(this); server.route("/api/system", new SystemController(this).getController());
this._systemController.register(this);
// emit built event // emit built event
$console.log("App built"); $console.log("App built");
@@ -227,10 +200,6 @@ export class App<C extends Connection = Connection, Options extends AppOptions =
return this.modules.ctx().em; return this.modules.ctx().em;
} }
get mcp() {
return this._systemController?._mcpServer;
}
get fetch(): Hono["fetch"] { get fetch(): Hono["fetch"] {
return this.server.fetch as any; return this.server.fetch as any;
} }
@@ -289,18 +258,6 @@ export class App<C extends Connection = Connection, Options extends AppOptions =
return new Api({ host: "http://localhost", ...(options ?? {}), fetcher }); return new Api({ host: "http://localhost", ...(options ?? {}), fetcher });
} }
getMcpClient() {
if (!this.mcp) {
throw new Error("MCP is not enabled");
}
const mcpPath = this.modules.get("server").config.mcp.path;
return new McpClient({
url: "http://localhost" + mcpPath,
fetch: this.server.request,
});
}
async onUpdated<Module extends keyof Modules>(module: Module, config: ModuleConfigs[Module]) { async onUpdated<Module extends keyof Modules>(module: Module, config: ModuleConfigs[Module]) {
// if the EventManager was disabled, we assume we shouldn't // if the EventManager was disabled, we assume we shouldn't
// respond to events, such as "onUpdated". // respond to events, such as "onUpdated".
@@ -370,6 +327,11 @@ export class App<C extends Connection = Connection, Options extends AppOptions =
} }
} }
} }
protected async onModulesCreated(modules: Modules, ctx: ModuleBuildContext) {
await this.runPlugins("onModulesCreated", modules, ctx);
this.options?.manager?.onModulesCreated?.(modules, ctx);
}
} }
export function createApp(config: CreateAppConfig = {}) { export function createApp(config: CreateAppConfig = {}) {
+7 -11
View File
@@ -3,33 +3,31 @@
import path from "node:path"; import path from "node:path";
import { type RuntimeBkndConfig, createRuntimeApp, type RuntimeOptions } from "bknd/adapter"; import { type RuntimeBkndConfig, createRuntimeApp, type RuntimeOptions } from "bknd/adapter";
import { registerLocalMediaAdapter } from "."; import { registerLocalMediaAdapter } from ".";
import { config, type App } from "bknd"; import { config } from "bknd/core";
import type { ServeOptions } from "bun"; import type { ServeOptions } from "bun";
import { serveStatic } from "hono/bun"; import { serveStatic } from "hono/bun";
import type { App } from "App";
type BunEnv = Bun.Env; type BunEnv = Bun.Env;
export type BunBkndConfig<Env = BunEnv> = RuntimeBkndConfig<Env> & Omit<ServeOptions, "fetch">; export type BunBkndConfig<Env = BunEnv> = RuntimeBkndConfig<Env> & Omit<ServeOptions, "fetch">;
export async function createApp<Env = BunEnv>( export async function createApp<Env = BunEnv>(
{ distPath, serveStatic: _serveStatic, ...config }: BunBkndConfig<Env> = {}, { distPath, ...config }: BunBkndConfig<Env> = {},
args: Env = {} as Env, args: Env = {} as Env,
opts?: RuntimeOptions, opts?: RuntimeOptions,
) { ) {
const root = path.resolve(distPath ?? "./node_modules/bknd/dist", "static"); const root = path.resolve(distPath ?? "./node_modules/bknd/dist", "static");
registerLocalMediaAdapter();
return await createRuntimeApp( const app = await createRuntimeApp(
{ {
serveStatic:
_serveStatic ??
serveStatic({
root,
}),
...config, ...config,
serveStatic: serveStatic({ root }),
}, },
args ?? (process.env as Env), args ?? (process.env as Env),
opts, opts,
); );
registerLocalMediaAdapter(app);
return app;
} }
export function createHandler<Env = BunEnv>( export function createHandler<Env = BunEnv>(
@@ -56,7 +54,6 @@ export function serve<Env = BunEnv>(
onBuilt, onBuilt,
buildConfig, buildConfig,
adminOptions, adminOptions,
serveStatic,
...serveOptions ...serveOptions
}: BunBkndConfig<Env> = {}, }: BunBkndConfig<Env> = {},
args: Env = {} as Env, args: Env = {} as Env,
@@ -74,7 +71,6 @@ export function serve<Env = BunEnv>(
buildConfig, buildConfig,
adminOptions, adminOptions,
distPath, distPath,
serveStatic,
}, },
args, args,
opts, opts,
@@ -1,5 +1,5 @@
import { Database } from "bun:sqlite"; import { Database } from "bun:sqlite";
import { genericSqlite, type GenericSqliteConnection } from "bknd"; import { genericSqlite, type GenericSqliteConnection } from "bknd/data";
export type BunSqliteConnection = GenericSqliteConnection<Database>; export type BunSqliteConnection = GenericSqliteConnection<Database>;
export type BunSqliteConnectionConfig = { export type BunSqliteConnectionConfig = {
+1 -7
View File
@@ -1,5 +1,3 @@
import { inspect } from "node:util";
export type BindingTypeMap = { export type BindingTypeMap = {
D1Database: D1Database; D1Database: D1Database;
KVNamespace: KVNamespace; KVNamespace: KVNamespace;
@@ -14,11 +12,7 @@ export function getBindings<T extends GetBindingType>(env: any, type: T): Bindin
const bindings: BindingMap<T>[] = []; const bindings: BindingMap<T>[] = [];
for (const key in env) { for (const key in env) {
try { try {
if ( if (env[key] && (env[key] as any).constructor.name === type) {
(env[key] as any).constructor.name === type ||
String(env[key]) === `[object ${type}]` ||
inspect(env[key]).includes(type)
) {
bindings.push({ bindings.push({
key, key,
value: env[key] as BindingTypeMap[T], value: env[key] as BindingTypeMap[T],
@@ -18,7 +18,7 @@ describe("cf adapter", () => {
}); });
it("makes config", async () => { it("makes config", async () => {
const staticConfig = await makeConfig( const staticConfig = makeConfig(
{ {
connection: { url: DB_URL }, connection: { url: DB_URL },
initialConfig: { data: { basepath: DB_URL } }, initialConfig: { data: { basepath: DB_URL } },
@@ -28,7 +28,7 @@ describe("cf adapter", () => {
expect(staticConfig.initialConfig).toEqual({ data: { basepath: DB_URL } }); expect(staticConfig.initialConfig).toEqual({ data: { basepath: DB_URL } });
expect(staticConfig.connection).toBeDefined(); expect(staticConfig.connection).toBeDefined();
const dynamicConfig = await makeConfig( const dynamicConfig = makeConfig(
{ {
app: (env) => ({ app: (env) => ({
initialConfig: { data: { basepath: env.DB_URL } }, initialConfig: { data: { basepath: env.DB_URL } },
@@ -5,8 +5,10 @@ import { Hono } from "hono";
import { serveStatic } from "hono/cloudflare-workers"; import { serveStatic } from "hono/cloudflare-workers";
import { getFresh } from "./modes/fresh"; import { getFresh } from "./modes/fresh";
import { getCached } from "./modes/cached"; import { getCached } from "./modes/cached";
import type { App, MaybePromise } from "bknd"; import { getDurable } from "./modes/durable";
import { $console } from "bknd/utils"; import type { App } from "bknd";
import { $console } from "core/utils";
import { registerMedia } from "./storage/StorageR2Adapter";
declare global { declare global {
namespace Cloudflare { namespace Cloudflare {
@@ -16,11 +18,12 @@ declare global {
export type CloudflareEnv = Cloudflare.Env; export type CloudflareEnv = Cloudflare.Env;
export type CloudflareBkndConfig<Env = CloudflareEnv> = RuntimeBkndConfig<Env> & { export type CloudflareBkndConfig<Env = CloudflareEnv> = RuntimeBkndConfig<Env> & {
mode?: "warm" | "fresh" | "cache"; mode?: "warm" | "fresh" | "cache" | "durable";
bindings?: (args: Env) => MaybePromise<{ bindings?: (args: Env) => {
kv?: KVNamespace; kv?: KVNamespace;
dobj?: DurableObjectNamespace;
db?: D1Database; db?: D1Database;
}>; };
d1?: { d1?: {
session?: boolean; session?: boolean;
transport?: "header" | "cookie"; transport?: "header" | "cookie";
@@ -31,7 +34,7 @@ export type CloudflareBkndConfig<Env = CloudflareEnv> = RuntimeBkndConfig<Env> &
keepAliveSeconds?: number; keepAliveSeconds?: number;
forceHttps?: boolean; forceHttps?: boolean;
manifest?: string; manifest?: string;
registerMedia?: boolean | ((env: Env) => void); registerMedia?: boolean;
}; };
export type Context<Env = CloudflareEnv> = { export type Context<Env = CloudflareEnv> = {
@@ -91,11 +94,22 @@ export function serve<Env extends CloudflareEnv = CloudflareEnv>(
case "cache": case "cache":
app = await getCached(config, context); app = await getCached(config, context);
break; break;
case "durable":
return await getDurable(config, context);
default: default:
throw new Error(`Unknown mode ${mode}`); throw new Error(`Unknown mode ${mode}`);
} }
registerMediaInternal(app, config, context);
return app.fetch(request, env, ctx); return app.fetch(request, env, ctx);
}, },
}; };
} }
let media_registered: boolean = false;
function registerMediaInternal(app: App, config: CloudflareBkndConfig<any>, ctx?: Context) {
if (!media_registered && config.registerMedia !== false) {
registerMedia(app, ctx?.env as any);
media_registered = true;
}
}
+8 -19
View File
@@ -1,16 +1,15 @@
/// <reference types="@cloudflare/workers-types" /> /// <reference types="@cloudflare/workers-types" />
import { Connection } from "bknd";
import { sqlite } from "bknd/adapter/sqlite";
import { makeConfig as makeAdapterConfig } from "bknd/adapter";
import { registerMedia } from "./storage/StorageR2Adapter";
import { getBinding } from "./bindings"; import { getBinding } from "./bindings";
import { d1Sqlite } from "./connection/D1Connection"; import { d1Sqlite } from "./connection/D1Connection";
import { Connection } from "bknd/data";
import type { CloudflareBkndConfig, CloudflareEnv } from "."; import type { CloudflareBkndConfig, CloudflareEnv } from ".";
import { App } from "bknd"; import { App } from "bknd";
import { makeConfig as makeAdapterConfig } from "bknd/adapter";
import type { Context, ExecutionContext } from "hono"; import type { Context, ExecutionContext } from "hono";
import { $console } from "bknd/utils"; import { $console } from "core/utils";
import { setCookie } from "hono/cookie"; import { setCookie } from "hono/cookie";
import { sqlite } from "bknd/adapter/sqlite";
export const constants = { export const constants = {
exec_async_event_id: "cf_register_waituntil", exec_async_event_id: "cf_register_waituntil",
@@ -88,21 +87,11 @@ export function d1SessionHelper(config: CloudflareBkndConfig<any>) {
}; };
} }
let media_registered: boolean = false; export function makeConfig<Env extends CloudflareEnv = CloudflareEnv>(
export async function makeConfig<Env extends CloudflareEnv = CloudflareEnv>(
config: CloudflareBkndConfig<Env>, config: CloudflareBkndConfig<Env>,
args?: CfMakeConfigArgs<Env>, args?: CfMakeConfigArgs<Env>,
) { ) {
if (!media_registered && config.registerMedia !== false) { const appConfig = makeAdapterConfig(config, args?.env);
if (typeof config.registerMedia === "function") {
config.registerMedia(args?.env as any);
} else {
registerMedia(args?.env as any);
}
media_registered = true;
}
const appConfig = await makeAdapterConfig(config, args?.env);
// if connection instance is given, don't do anything // if connection instance is given, don't do anything
// other than checking if D1 session is defined // other than checking if D1 session is defined
@@ -115,12 +104,12 @@ export async function makeConfig<Env extends CloudflareEnv = CloudflareEnv>(
} }
// if connection is given, try to open with unified sqlite adapter // if connection is given, try to open with unified sqlite adapter
} else if (appConfig.connection) { } else if (appConfig.connection) {
appConfig.connection = sqlite(appConfig.connection) as any; appConfig.connection = sqlite(appConfig.connection);
// if connection is not given, but env is set // if connection is not given, but env is set
// try to make D1 from bindings // try to make D1 from bindings
} else if (args?.env) { } else if (args?.env) {
const bindings = await config.bindings?.(args?.env); const bindings = config.bindings?.(args?.env);
const sessionHelper = d1SessionHelper(config); const sessionHelper = d1SessionHelper(config);
const sessionId = sessionHelper.get(args.request); const sessionId = sessionHelper.get(args.request);
let session: D1DatabaseSession | undefined; let session: D1DatabaseSession | undefined;
@@ -1,6 +1,6 @@
/// <reference types="@cloudflare/workers-types" /> /// <reference types="@cloudflare/workers-types" />
import { genericSqlite, type GenericSqliteConnection } from "bknd"; import { genericSqlite, type GenericSqliteConnection } from "bknd/data";
import type { QueryResult } from "kysely"; import type { QueryResult } from "kysely";
export type D1SqliteConnection = GenericSqliteConnection<D1Database>; export type D1SqliteConnection = GenericSqliteConnection<D1Database>;
@@ -1,18 +1,18 @@
/// <reference types="@cloudflare/workers-types" /> /// <reference types="@cloudflare/workers-types" />
import { genericSqlite, type GenericSqliteConnection } from "bknd"; import { genericSqlite, type GenericSqliteConnection } from "bknd/data";
import type { QueryResult } from "kysely"; import type { QueryResult } from "kysely";
export type DoSqliteConnection = GenericSqliteConnection<DurableObjectState["storage"]["sql"]>; export type D1SqliteConnection = GenericSqliteConnection<D1Database>;
export type DurableObjecSql = DurableObjectState["storage"]["sql"]; export type DurableObjecSql = DurableObjectState["storage"]["sql"];
export type DoConnectionConfig<DB extends DurableObjecSql> = export type D1ConnectionConfig<DB extends DurableObjecSql> =
| DurableObjectState | DurableObjectState
| { | {
sql: DB; sql: DB;
}; };
export function doSqlite<DB extends DurableObjecSql>(config: DoConnectionConfig<DB>) { export function doSqlite<DB extends DurableObjecSql>(config: D1ConnectionConfig<DB>) {
const db = "sql" in config ? config.sql : config.storage.sql; const db = "sql" in config ? config.sql : config.storage.sql;
return genericSqlite( return genericSqlite(
@@ -21,7 +21,7 @@ export function doSqlite<DB extends DurableObjecSql>(config: DoConnectionConfig<
(utils) => { (utils) => {
// must be async to work with the miniflare mock // must be async to work with the miniflare mock
const getStmt = async (sql: string, parameters?: any[] | readonly any[]) => const getStmt = async (sql: string, parameters?: any[] | readonly any[]) =>
db.exec(sql, ...(parameters || [])); await db.exec(sql, ...(parameters || []));
const mapResult = ( const mapResult = (
cursor: SqlStorageCursor<Record<string, SqlStorageValue>>, cursor: SqlStorageCursor<Record<string, SqlStorageValue>>,
+2 -4
View File
@@ -3,8 +3,8 @@ import { d1Sqlite, type D1ConnectionConfig } from "./connection/D1Connection";
export * from "./cloudflare-workers.adapter"; export * from "./cloudflare-workers.adapter";
export { makeApp, getFresh } from "./modes/fresh"; export { makeApp, getFresh } from "./modes/fresh";
export { getCached } from "./modes/cached"; export { getCached } from "./modes/cached";
export { DurableBkndApp, getDurable } from "./modes/durable";
export { d1Sqlite, type D1ConnectionConfig }; export { d1Sqlite, type D1ConnectionConfig };
export { doSqlite, type DoConnectionConfig } from "./connection/DoConnection";
export { export {
getBinding, getBinding,
getBindings, getBindings,
@@ -13,9 +13,7 @@ export {
type BindingMap, type BindingMap,
} from "./bindings"; } from "./bindings";
export { constants } from "./config"; export { constants } from "./config";
export { StorageR2Adapter, registerMedia } from "./storage/StorageR2Adapter"; export { StorageR2Adapter } from "./storage/StorageR2Adapter";
export { registries } from "bknd";
export { devFsVitePlugin, devFsWrite } from "./vite";
// for compatibility with old code // for compatibility with old code
export function d1<DB extends D1Database | D1DatabaseSession = D1Database>( export function d1<DB extends D1Database | D1DatabaseSession = D1Database>(
+1 -1
View File
@@ -8,7 +8,7 @@ export async function getCached<Env extends CloudflareEnv = CloudflareEnv>(
args: Context<Env>, args: Context<Env>,
) { ) {
const { env, ctx } = args; const { env, ctx } = args;
const { kv } = await config.bindings?.(env)!; const { kv } = config.bindings?.(env)!;
if (!kv) throw new Error("kv namespace is not defined in cloudflare.bindings"); if (!kv) throw new Error("kv namespace is not defined in cloudflare.bindings");
const key = config.key ?? "app"; const key = config.key ?? "app";
+134
View File
@@ -0,0 +1,134 @@
import { DurableObject } from "cloudflare:workers";
import type { App, CreateAppConfig } from "bknd";
import { createRuntimeApp, makeConfig } from "bknd/adapter";
import type { CloudflareBkndConfig, Context, CloudflareEnv } from "../index";
import { constants, registerAsyncsExecutionContext } from "../config";
import { $console } from "core/utils";
export async function getDurable<Env extends CloudflareEnv = CloudflareEnv>(
config: CloudflareBkndConfig<Env>,
ctx: Context<Env>,
) {
const { dobj } = config.bindings?.(ctx.env)!;
if (!dobj) throw new Error("durable object is not defined in cloudflare.bindings");
const key = config.key ?? "app";
if ([config.onBuilt, config.beforeBuild].some((x) => x)) {
$console.warn("onBuilt and beforeBuild are not supported with DurableObject mode");
}
const start = performance.now();
const id = dobj.idFromName(key);
const stub = dobj.get(id) as unknown as DurableBkndApp;
const create_config = makeConfig(config, ctx.env);
const res = await stub.fire(ctx.request, {
config: create_config,
keepAliveSeconds: config.keepAliveSeconds,
});
const headers = new Headers(res.headers);
headers.set("X-TTDO", String(performance.now() - start));
return new Response(res.body, {
status: res.status,
statusText: res.statusText,
headers,
});
}
export class DurableBkndApp extends DurableObject {
protected id = Math.random().toString(36).slice(2);
protected app?: App;
protected interval?: any;
async fire(
request: Request,
options: {
config: CreateAppConfig;
html?: string;
keepAliveSeconds?: number;
setAdminHtml?: boolean;
},
) {
let buildtime = 0;
if (!this.app) {
const start = performance.now();
const config = options.config;
// change protocol to websocket if libsql
if (
config?.connection &&
"type" in config.connection &&
config.connection.type === "libsql"
) {
//config.connection.config.protocol = "wss";
}
this.app = await createRuntimeApp({
...config,
onBuilt: async (app) => {
registerAsyncsExecutionContext(app, this.ctx);
app.modules.server.get(constants.do_endpoint, async (c) => {
// @ts-ignore
const context: any = c.req.raw.cf ? c.req.raw.cf : c.env.cf;
return c.json({
id: this.id,
keepAliveSeconds: options?.keepAliveSeconds ?? 0,
colo: context.colo,
});
});
await this.onBuilt(app);
},
adminOptions: { html: options.html },
beforeBuild: async (app) => {
await this.beforeBuild(app);
},
});
buildtime = performance.now() - start;
}
if (options?.keepAliveSeconds) {
this.keepAlive(options.keepAliveSeconds);
}
const res = await this.app!.fetch(request);
const headers = new Headers(res.headers);
headers.set("X-BuildTime", buildtime.toString());
headers.set("X-DO-ID", this.id);
return new Response(res.body, {
status: res.status,
statusText: res.statusText,
headers,
});
}
async onBuilt(app: App) {}
async beforeBuild(app: App) {}
protected keepAlive(seconds: number) {
if (this.interval) {
clearInterval(this.interval);
}
let i = 0;
this.interval = setInterval(() => {
i += 1;
if (i === seconds) {
console.log("cleared");
clearInterval(this.interval);
// ping every 30 seconds
} else if (i % 30 === 0) {
console.log("ping");
this.app?.modules.ctx().connection.ping();
}
}, 1000);
}
}
+1 -1
View File
@@ -7,7 +7,7 @@ export async function makeApp<Env extends CloudflareEnv = CloudflareEnv>(
args?: CfMakeConfigArgs<Env>, args?: CfMakeConfigArgs<Env>,
opts?: RuntimeOptions, opts?: RuntimeOptions,
) { ) {
return await createRuntimeApp<Env>(await makeConfig(config, args), args?.env, opts); return await createRuntimeApp<Env>(makeConfig(config, args), args?.env, opts);
} }
export async function getFresh<Env extends CloudflareEnv = CloudflareEnv>( export async function getFresh<Env extends CloudflareEnv = CloudflareEnv>(
-67
View File
@@ -1,67 +0,0 @@
import {
d1Sqlite,
getBinding,
registerMedia,
type CloudflareBkndConfig,
type CloudflareEnv,
} from "bknd/adapter/cloudflare";
import type { PlatformProxy } from "wrangler";
import process from "node:process";
export type WithPlatformProxyOptions = {
/**
* By default, proxy is used if the PROXY environment variable is set to 1.
* You can override/force this by setting this option.
*/
useProxy?: boolean;
};
export function withPlatformProxy<Env extends CloudflareEnv>(
config?: CloudflareBkndConfig<Env>,
opts?: WithPlatformProxyOptions,
) {
const use_proxy =
typeof opts?.useProxy === "boolean" ? opts.useProxy : process.env.PROXY === "1";
let proxy: PlatformProxy | undefined;
async function getEnv(env?: Env): Promise<Env> {
if (use_proxy) {
if (!proxy) {
const getPlatformProxy = await import("wrangler").then((mod) => mod.getPlatformProxy);
proxy = await getPlatformProxy();
setTimeout(proxy?.dispose, 1000);
}
return proxy.env as unknown as Env;
}
return env || ({} as Env);
}
return {
...config,
beforeBuild: async (app, registries) => {
if (!use_proxy) return;
const env = await getEnv();
registerMedia(env, registries as any);
await config?.beforeBuild?.(app, registries);
},
bindings: async (env) => {
return (await config?.bindings?.(await getEnv(env))) || {};
},
// @ts-ignore
app: async (_env) => {
const env = await getEnv(_env);
if (config?.app === undefined && use_proxy) {
const binding = getBinding(env, "D1Database");
return {
connection: d1Sqlite({
binding: binding.value,
}),
};
} else if (typeof config?.app === "function") {
return config?.app(env);
}
return config?.app || {};
},
} satisfies CloudflareBkndConfig<Env>;
}
@@ -1,7 +1,8 @@
import { registries as $registries, isDebug, guessMimeType } from "bknd"; import type { App } from "bknd";
import { isDebug } from "bknd/core";
import { guessMimeType as guess, StorageAdapter, type FileBody } from "bknd/media";
import { getBindings } from "../bindings"; import { getBindings } from "../bindings";
import { s } from "bknd/utils"; import { s } from "core/object/schema";
import { StorageAdapter, type FileBody } from "bknd";
export function makeSchema(bindings: string[] = []) { export function makeSchema(bindings: string[] = []) {
return s.object( return s.object(
@@ -12,13 +13,10 @@ export function makeSchema(bindings: string[] = []) {
); );
} }
export function registerMedia( export function registerMedia(app: App, env: Record<string, any>) {
env: Record<string, any>,
registries: typeof $registries = $registries,
) {
const r2_bindings = getBindings(env, "R2Bucket"); const r2_bindings = getBindings(env, "R2Bucket");
registries.media.register( app.module.media.adapters.set(
"r2", "r2",
class extends StorageR2Adapter { class extends StorageR2Adapter {
constructor(private config: any) { constructor(private config: any) {
@@ -92,7 +90,7 @@ export class StorageR2Adapter extends StorageAdapter {
const responseHeaders = new Headers({ const responseHeaders = new Headers({
"Accept-Ranges": "bytes", "Accept-Ranges": "bytes",
"Content-Type": guessMimeType(key), "Content-Type": guess(key),
}); });
const range = headers.has("range"); const range = headers.has("range");
@@ -144,7 +142,7 @@ export class StorageR2Adapter extends StorageAdapter {
if (!metadata || Object.keys(metadata).length === 0) { if (!metadata || Object.keys(metadata).length === 0) {
// guessing is especially required for dev environment (miniflare) // guessing is especially required for dev environment (miniflare)
metadata = { metadata = {
contentType: guessMimeType(object.key), contentType: guess(object.key),
}; };
} }
@@ -161,7 +159,7 @@ export class StorageR2Adapter extends StorageAdapter {
} }
return { return {
type: String(head.httpMetadata?.contentType ?? guessMimeType(key)), type: String(head.httpMetadata?.contentType ?? guess(key)),
size: head.size, size: head.size,
}; };
} }
-135
View File
@@ -1,135 +0,0 @@
import type { Plugin } from "vite";
import { writeFile as nodeWriteFile } from "node:fs/promises";
import { resolve } from "node:path";
/**
* Vite plugin that provides Node.js filesystem access during development
* by injecting a polyfill into the SSR environment
*/
export function devFsVitePlugin({
verbose = false,
configFile = "bknd.config.ts",
}: {
verbose?: boolean;
configFile?: string;
}): Plugin {
let isDev = false;
let projectRoot = "";
return {
name: "dev-fs-plugin",
enforce: "pre",
configResolved(config) {
isDev = config.command === "serve";
projectRoot = config.root;
},
configureServer(server) {
if (!isDev) return;
// Intercept stdout to watch for our write requests
const originalStdoutWrite = process.stdout.write;
process.stdout.write = function (chunk: any, encoding?: any, callback?: any) {
const output = chunk.toString();
// Check if this output contains our special write request
if (output.includes("{{DEV_FS_WRITE_REQUEST}}")) {
try {
// Extract the JSON from the log line
const match = output.match(/{{DEV_FS_WRITE_REQUEST}} ({.*})/);
if (match) {
const writeRequest = JSON.parse(match[1]);
if (writeRequest.type === "DEV_FS_WRITE_REQUEST") {
if (verbose) {
console.debug("[dev-fs-plugin] Intercepted write request via stdout");
}
// Process the write request immediately
(async () => {
try {
const fullPath = resolve(projectRoot, writeRequest.filename);
await nodeWriteFile(fullPath, writeRequest.data);
if (verbose) {
console.debug("[dev-fs-plugin] File written successfully!");
}
} catch (error) {
console.error("[dev-fs-plugin] Error writing file:", error);
}
})();
// Don't output the raw write request to console
return true;
}
}
} catch (error) {
// Not a valid write request, continue with normal output
}
}
// @ts-ignore
// biome-ignore lint:
return originalStdoutWrite.apply(process.stdout, arguments);
};
// Restore stdout when server closes
server.httpServer?.on("close", () => {
process.stdout.write = originalStdoutWrite;
});
},
// @ts-ignore
transform(code, id, options) {
// Only transform in SSR mode during development
if (!isDev || !options?.ssr) return;
// Check if this is the bknd config file
if (id.includes(configFile)) {
if (verbose) {
console.debug("[dev-fs-plugin] Transforming", configFile);
}
// Inject our filesystem polyfill at the top of the file
const polyfill = `
// Dev-fs polyfill injected by vite-plugin-dev-fs
if (typeof globalThis !== 'undefined') {
globalThis.__devFsPolyfill = {
writeFile: async (filename, data) => {
${verbose ? "console.debug('dev-fs polyfill: Intercepting write request for', filename);" : ""}
// Use console logging as a communication channel
// The main process will watch for this specific log pattern
const writeRequest = {
type: 'DEV_FS_WRITE_REQUEST',
filename: filename,
data: data,
timestamp: Date.now()
};
// Output as a specially formatted console message
console.log('{{DEV_FS_WRITE_REQUEST}}', JSON.stringify(writeRequest));
${verbose ? "console.debug('dev-fs polyfill: Write request sent via console');" : ""}
return Promise.resolve();
}
};
}
`;
return polyfill + code;
}
},
};
}
// Write function that uses the dev-fs polyfill injected by our Vite plugin
export async function devFsWrite(filename: string, data: string): Promise<void> {
try {
// Check if the dev-fs polyfill is available (injected by our Vite plugin)
if (typeof globalThis !== "undefined" && (globalThis as any).__devFsPolyfill) {
return (globalThis as any).__devFsPolyfill.writeFile(filename, data);
}
// Fallback to Node.js fs for other environments (Node.js, Bun)
const { writeFile } = await import("node:fs/promises");
return writeFile(filename, data);
} catch (error) {
console.error("[dev-fs-write] Error writing file:", error);
}
}
+19 -74
View File
@@ -1,21 +1,17 @@
import { import { App, type CreateAppConfig } from "bknd";
config as $config, import { config as $config } from "bknd/core";
App,
type CreateAppConfig,
Connection,
guessMimeType,
type MaybePromise,
registries as $registries,
} from "bknd";
import { $console } from "bknd/utils"; import { $console } from "bknd/utils";
import type { Context, MiddlewareHandler, Next } from "hono"; import type { MiddlewareHandler } from "hono";
import type { AdminControllerOptions } from "modules/server/AdminController"; import type { AdminControllerOptions } from "modules/server/AdminController";
import type { Manifest } from "vite"; import { Connection } from "bknd/data";
import type { MaybePromise } from "core/types";
export { Connection } from "bknd/data";
export type BkndConfig<Args = any> = CreateAppConfig & { export type BkndConfig<Args = any> = CreateAppConfig & {
app?: CreateAppConfig | ((args: Args) => MaybePromise<CreateAppConfig>); app?: CreateAppConfig | ((args: Args) => CreateAppConfig);
onBuilt?: (app: App) => Promise<void>; onBuilt?: (app: App) => MaybePromise<void>;
beforeBuild?: (app: App, registries?: typeof $registries) => Promise<void>; beforeBuild?: (app: App) => MaybePromise<void>;
buildConfig?: Parameters<App["build"]>[0]; buildConfig?: Parameters<App["build"]>[0];
}; };
@@ -38,10 +34,10 @@ export type DefaultArgs = {
[key: string]: any; [key: string]: any;
}; };
export async function makeConfig<Args = DefaultArgs>( export function makeConfig<Args = DefaultArgs>(
config: BkndConfig<Args>, config: BkndConfig<Args>,
args?: Args, args?: Args,
): Promise<CreateAppConfig> { ): CreateAppConfig {
let additionalConfig: CreateAppConfig = {}; let additionalConfig: CreateAppConfig = {};
const { app, ...rest } = config; const { app, ...rest } = config;
if (app) { if (app) {
@@ -49,7 +45,7 @@ export async function makeConfig<Args = DefaultArgs>(
if (!args) { if (!args) {
throw new Error("args is required when config.app is a function"); throw new Error("args is required when config.app is a function");
} }
additionalConfig = await app(args); additionalConfig = app(args);
} else { } else {
additionalConfig = app; additionalConfig = app;
} }
@@ -68,16 +64,16 @@ export async function createAdapterApp<Config extends BkndConfig = BkndConfig, A
const id = opts?.id ?? "app"; const id = opts?.id ?? "app";
let app = apps.get(id); let app = apps.get(id);
if (!app || opts?.force) { if (!app || opts?.force) {
const appConfig = await makeConfig(config, args); const appConfig = makeConfig(config, args);
if (!appConfig.connection || !Connection.isConnection(appConfig.connection)) { if (!appConfig.connection || !Connection.isConnection(appConfig.connection)) {
let connection: Connection | undefined; let connection: Connection | undefined;
if (Connection.isConnection(config.connection)) { if (Connection.isConnection(config.connection)) {
connection = config.connection; connection = config.connection;
} else { } else {
const sqlite = (await import("bknd/adapter/sqlite")).sqlite; const sqlite = (await import("bknd/adapter/sqlite")).sqlite;
const conf = appConfig.connection ?? { url: ":memory:" }; const conf = config.connection ?? { url: ":memory:" };
connection = sqlite(conf) as any; connection = sqlite(conf);
$console.info(`Using ${connection!.name} connection`, conf.url); $console.info(`Using ${connection.name} connection`, conf.url);
} }
appConfig.connection = connection; appConfig.connection = connection;
} }
@@ -106,7 +102,7 @@ export async function createFrameworkApp<Args = DefaultArgs>(
); );
} }
await config.beforeBuild?.(app, $registries); await config.beforeBuild?.(app);
await app.build(config.buildConfig); await app.build(config.buildConfig);
} }
@@ -139,60 +135,9 @@ export async function createRuntimeApp<Args = DefaultArgs>(
"sync", "sync",
); );
await config.beforeBuild?.(app, $registries); await config.beforeBuild?.(app);
await app.build(config.buildConfig); await app.build(config.buildConfig);
} }
return app; return app;
} }
/**
* Creates a middleware handler to serve static assets via dynamic imports.
* This is useful for environments where filesystem access is limited but bundled assets can be imported.
*
* @param manifest - Vite manifest object containing asset information
* @returns Hono middleware handler for serving static assets
*
* @example
* ```typescript
* import { serveStaticViaImport } from "bknd/adapter";
*
* serve({
* serveStatic: serveStaticViaImport(),
* });
* ```
*/
export function serveStaticViaImport(opts?: { manifest?: Manifest }) {
let files: string[] | undefined;
// @ts-ignore
return async (c: Context, next: Next) => {
if (!files) {
const manifest =
opts?.manifest || ((await import("bknd/dist/manifest.json")).default as Manifest);
files = Object.values(manifest).flatMap((asset) => [asset.file, ...(asset.css || [])]);
}
const path = c.req.path.substring(1);
if (files.includes(path)) {
try {
const content = await import(/* @vite-ignore */ `bknd/static/${path}?raw`, {
assert: { type: "text" },
}).then((m) => m.default);
if (content) {
return c.body(content, {
headers: {
"Content-Type": guessMimeType(path),
"Cache-Control": "public, max-age=31536000, immutable",
},
});
}
} catch (e) {
console.error("Error serving static file:", e);
return c.text("File not found", 404);
}
}
await next();
};
}
@@ -1,4 +1,4 @@
import { genericSqlite } from "bknd"; import { genericSqlite } from "bknd/data";
import { DatabaseSync } from "node:sqlite"; import { DatabaseSync } from "node:sqlite";
export type NodeSqliteConnectionConfig = { export type NodeSqliteConnectionConfig = {
+7 -5
View File
@@ -3,8 +3,9 @@ import { serve as honoServe } from "@hono/node-server";
import { serveStatic } from "@hono/node-server/serve-static"; import { serveStatic } from "@hono/node-server/serve-static";
import { registerLocalMediaAdapter } from "adapter/node/storage"; import { registerLocalMediaAdapter } from "adapter/node/storage";
import { type RuntimeBkndConfig, createRuntimeApp, type RuntimeOptions } from "bknd/adapter"; import { type RuntimeBkndConfig, createRuntimeApp, type RuntimeOptions } from "bknd/adapter";
import { config as $config, type App } from "bknd"; import { config as $config } from "bknd/core";
import { $console } from "bknd/utils"; import { $console } from "core/utils";
import type { App } from "App";
type NodeEnv = NodeJS.ProcessEnv; type NodeEnv = NodeJS.ProcessEnv;
export type NodeBkndConfig<Env = NodeEnv> = RuntimeBkndConfig<Env> & { export type NodeBkndConfig<Env = NodeEnv> = RuntimeBkndConfig<Env> & {
@@ -28,16 +29,17 @@ export async function createApp<Env = NodeEnv>(
console.warn("relativeDistPath is deprecated, please use distPath instead"); console.warn("relativeDistPath is deprecated, please use distPath instead");
} }
registerLocalMediaAdapter(); const app = await createRuntimeApp(
return await createRuntimeApp(
{ {
serveStatic: serveStatic({ root }),
...config, ...config,
serveStatic: serveStatic({ root }),
}, },
// @ts-ignore // @ts-ignore
args ?? { env: process.env }, args ?? { env: process.env },
opts, opts,
); );
registerLocalMediaAdapter(app);
return app;
} }
export function createHandler<Env = NodeEnv>( export function createHandler<Env = NodeEnv>(
@@ -1,7 +1,8 @@
import { readFile, readdir, stat, unlink, writeFile } from "node:fs/promises"; import { readFile, readdir, stat, unlink, writeFile } from "node:fs/promises";
import type { FileBody, FileListObject, FileMeta, FileUploadPayload } from "bknd"; import { isFile } from "bknd/utils";
import { StorageAdapter, guessMimeType } from "bknd"; import type { FileBody, FileListObject, FileMeta, FileUploadPayload } from "bknd/media";
import { parse, s, isFile } from "bknd/utils"; import { StorageAdapter, guessMimeType as guess } from "bknd/media";
import { parse, s } from "core/object/schema";
export const localAdapterConfig = s.object( export const localAdapterConfig = s.object(
{ {
@@ -83,7 +84,7 @@ export class StorageLocalAdapter extends StorageAdapter {
async getObject(key: string, headers: Headers): Promise<Response> { async getObject(key: string, headers: Headers): Promise<Response> {
try { try {
const content = await readFile(`${this.config.path}/${key}`); const content = await readFile(`${this.config.path}/${key}`);
const mimeType = guessMimeType(key); const mimeType = guess(key);
return new Response(content, { return new Response(content, {
status: 200, status: 200,
@@ -105,7 +106,7 @@ export class StorageLocalAdapter extends StorageAdapter {
async getObjectMeta(key: string): Promise<FileMeta> { async getObjectMeta(key: string): Promise<FileMeta> {
const stats = await stat(`${this.config.path}/${key}`); const stats = await stat(`${this.config.path}/${key}`);
return { return {
type: guessMimeType(key) || "application/octet-stream", type: guess(key) || "application/octet-stream",
size: stats.size, size: stats.size,
}; };
} }
+3 -7
View File
@@ -1,14 +1,10 @@
import { registries } from "bknd"; import type { App } from "bknd";
import { type LocalAdapterConfig, StorageLocalAdapter } from "./StorageLocalAdapter"; import { type LocalAdapterConfig, StorageLocalAdapter } from "./StorageLocalAdapter";
export * from "./StorageLocalAdapter"; export * from "./StorageLocalAdapter";
let registered = false; export function registerLocalMediaAdapter(app: App) {
export function registerLocalMediaAdapter() { app.module.media.adapters.set("local", StorageLocalAdapter);
if (!registered) {
registries.media.register("local", StorageLocalAdapter);
registered = true;
}
return (config: Partial<LocalAdapterConfig> = {}) => { return (config: Partial<LocalAdapterConfig> = {}) => {
const adapter = new StorageLocalAdapter(config); const adapter = new StorageLocalAdapter(config);
+1 -1
View File
@@ -1,4 +1,4 @@
import type { Connection } from "bknd"; import type { Connection } from "bknd/data";
import { bunSqlite } from "../bun/connection/BunSqliteConnection"; import { bunSqlite } from "../bun/connection/BunSqliteConnection";
export function sqlite(config?: { url: string }): Connection { export function sqlite(config?: { url: string }): Connection {
+1 -1
View File
@@ -1,4 +1,4 @@
import { type Connection, libsql } from "bknd"; import { type Connection, libsql } from "bknd/data";
export function sqlite(config: { url: string }): Connection { export function sqlite(config: { url: string }): Connection {
return libsql(config); return libsql(config);
+1 -1
View File
@@ -1,4 +1,4 @@
import type { Connection } from "bknd"; import type { Connection } from "bknd/data";
import { nodeSqlite } from "../node/connection/NodeSqliteConnection"; import { nodeSqlite } from "../node/connection/NodeSqliteConnection";
export function sqlite(config?: { url: string }): Connection { export function sqlite(config?: { url: string }): Connection {
+3 -2
View File
@@ -32,8 +32,7 @@ async function createApp<ViteEnv>(
env: ViteEnv = {} as ViteEnv, env: ViteEnv = {} as ViteEnv,
opts: FrameworkOptions = {}, opts: FrameworkOptions = {},
): Promise<App> { ): Promise<App> {
registerLocalMediaAdapter(); const app = await createRuntimeApp(
return await createRuntimeApp(
{ {
...config, ...config,
adminOptions: config.adminOptions ?? { adminOptions: config.adminOptions ?? {
@@ -49,6 +48,8 @@ async function createApp<ViteEnv>(
env, env,
opts, opts,
); );
registerLocalMediaAdapter(app);
return app;
} }
export function serve<ViteEnv>( export function serve<ViteEnv>(
+7 -38
View File
@@ -1,9 +1,8 @@
import type { DB, PrimaryFieldType } from "bknd"; import { Authenticator, AuthPermissions, Role, type Strategy } from "auth";
import * as AuthPermissions from "auth/auth-permissions"; import type { PasswordStrategy } from "auth/authenticate/strategies";
import type { AuthStrategy } from "auth/authenticate/strategies/Strategy"; import type { DB } from "core";
import type { PasswordStrategy } from "auth/authenticate/strategies/PasswordStrategy"; import { $console, secureRandomString, transformObject } from "core/utils";
import { $console, secureRandomString, transformObject } from "bknd/utils"; import type { Entity, EntityManager } from "data";
import type { Entity, EntityManager } from "data/entities";
import { em, entity, enumm, type FieldSchema } from "data/prototype"; import { em, entity, enumm, type FieldSchema } from "data/prototype";
import { Module } from "modules/Module"; import { Module } from "modules/Module";
import { AuthController } from "./api/AuthController"; import { AuthController } from "./api/AuthController";
@@ -11,12 +10,9 @@ import { type AppAuthSchema, authConfigSchema, STRATEGIES } from "./auth-schema"
import { AppUserPool } from "auth/AppUserPool"; import { AppUserPool } from "auth/AppUserPool";
import type { AppEntity } from "core/config"; import type { AppEntity } from "core/config";
import { usersFields } from "./auth-entities"; import { usersFields } from "./auth-entities";
import { Authenticator } from "./authenticate/Authenticator";
import { Role } from "./authorize/Role";
export type UsersFields = typeof AppAuth.usersFields;
export type UserFieldSchema = FieldSchema<typeof AppAuth.usersFields>; export type UserFieldSchema = FieldSchema<typeof AppAuth.usersFields>;
declare module "bknd" { declare module "core" {
interface Users extends AppEntity, UserFieldSchema {} interface Users extends AppEntity, UserFieldSchema {}
interface DB { interface DB {
users: Users; users: Users;
@@ -88,12 +84,11 @@ export class AppAuth extends Module<AppAuthSchema> {
super.setBuilt(); super.setBuilt();
this._controller = new AuthController(this); this._controller = new AuthController(this);
this._controller.registerMcp();
this.ctx.server.route(this.config.basepath, this._controller.getController()); this.ctx.server.route(this.config.basepath, this._controller.getController());
this.ctx.guard.registerPermissions(AuthPermissions); this.ctx.guard.registerPermissions(AuthPermissions);
} }
isStrategyEnabled(strategy: AuthStrategy | string) { isStrategyEnabled(strategy: Strategy | string) {
const name = typeof strategy === "string" ? strategy : strategy.getName(); const name = typeof strategy === "string" ? strategy : strategy.getName();
// for now, password is always active // for now, password is always active
if (name === "password") return true; if (name === "password") return true;
@@ -178,32 +173,6 @@ export class AppAuth extends Module<AppAuthSchema> {
return created; return created;
} }
async changePassword(userId: PrimaryFieldType, newPassword: string) {
const users_entity = this.config.entity_name as "users";
const { data: user } = await this.em.repository(users_entity).findId(userId);
if (!user) {
throw new Error("User not found");
} else if (user.strategy !== "password") {
throw new Error("User is not using password strategy");
}
const togglePw = (visible: boolean) => {
const field = this.em.entity(users_entity).field("strategy_value")!;
field.config.hidden = !visible;
field.config.fillable = visible;
};
const pw = this.authenticator.strategy("password" as const) as PasswordStrategy;
togglePw(true);
await this.em.mutator(users_entity).updateOne(user.id, {
strategy_value: await pw.hash(newPassword),
});
togglePw(false);
return true;
}
override toJSON(secrets?: boolean): AppAuthSchema { override toJSON(secrets?: boolean): AppAuthSchema {
if (!this.config.enabled) { if (!this.config.enabled) {
return this.configDefault; return this.configDefault;
+1 -1
View File
@@ -1,6 +1,6 @@
import { AppAuth } from "auth/AppAuth"; import { AppAuth } from "auth/AppAuth";
import type { CreateUser, SafeUser, User, UserPool } from "auth/authenticate/Authenticator"; import type { CreateUser, SafeUser, User, UserPool } from "auth/authenticate/Authenticator";
import { $console } from "bknd/utils"; import { $console } from "core/utils";
import { pick } from "lodash-es"; import { pick } from "lodash-es";
import { import {
InvalidConditionsException, InvalidConditionsException,
+2 -2
View File
@@ -1,6 +1,6 @@
import type { AuthActionResponse } from "auth/api/AuthController"; import type { AuthActionResponse } from "auth/api/AuthController";
import type { AppAuthSchema } from "auth/auth-schema"; import type { AppAuthSchema } from "auth/auth-schema";
import type { AuthResponse, SafeUser, AuthStrategy } from "bknd"; import type { AuthResponse, SafeUser, Strategy } from "auth/authenticate/Authenticator";
import { type BaseModuleApiOptions, ModuleApi } from "modules/ModuleApi"; import { type BaseModuleApiOptions, ModuleApi } from "modules/ModuleApi";
export type AuthApiOptions = BaseModuleApiOptions & { export type AuthApiOptions = BaseModuleApiOptions & {
@@ -39,7 +39,7 @@ export class AuthApi extends ModuleApi<AuthApiOptions> {
} }
async actionSchema(strategy: string, action: string) { async actionSchema(strategy: string, action: string) {
return this.get<AuthStrategy>([strategy, "actions", action, "schema.json"]); return this.get<Strategy>([strategy, "actions", action, "schema.json"]);
} }
async action(strategy: string, action: string, input: any) { async action(strategy: string, action: string, input: any) {
+5 -135
View File
@@ -1,20 +1,9 @@
import type { DB, SafeUser } from "bknd"; import { type AppAuth, AuthPermissions, type SafeUser, type Strategy } from "auth";
import type { AuthStrategy } from "auth/authenticate/strategies/Strategy"; import { transformObject } from "core/utils";
import type { AppAuth } from "auth/AppAuth"; import { DataPermissions } from "data";
import * as AuthPermissions from "auth/auth-permissions";
import * as DataPermissions from "data/permissions";
import type { Hono } from "hono"; import type { Hono } from "hono";
import { Controller, type ServerEnv } from "modules/Controller"; import { Controller, type ServerEnv } from "modules/Controller";
import { import { describeRoute, jsc, s, parse, InvalidSchemaError } from "core/object/schema";
describeRoute,
jsc,
s,
parse,
InvalidSchemaError,
transformObject,
mcpTool,
} from "bknd/utils";
import type { PasswordStrategy } from "auth/authenticate/strategies";
export type AuthActionResponse = { export type AuthActionResponse = {
success: boolean; success: boolean;
@@ -41,7 +30,7 @@ export class AuthController extends Controller {
return this.em.repo(entity_name as "users"); return this.em.repo(entity_name as "users");
} }
private registerStrategyActions(strategy: AuthStrategy, mainHono: Hono<ServerEnv>) { private registerStrategyActions(strategy: Strategy, mainHono: Hono<ServerEnv>) {
if (!this.auth.isStrategyEnabled(strategy)) { if (!this.auth.isStrategyEnabled(strategy)) {
return; return;
} }
@@ -127,9 +116,6 @@ export class AuthController extends Controller {
summary: "Get the current user", summary: "Get the current user",
tags: ["auth"], tags: ["auth"],
}), }),
mcpTool("auth_me", {
noErrorCodes: [403],
}),
auth(), auth(),
async (c) => { async (c) => {
const claims = c.get("auth")?.user; const claims = c.get("auth")?.user;
@@ -171,7 +157,6 @@ export class AuthController extends Controller {
summary: "Get the available authentication strategies", summary: "Get the available authentication strategies",
tags: ["auth"], tags: ["auth"],
}), }),
mcpTool("auth_strategies"),
jsc("query", s.object({ include_disabled: s.boolean().optional() })), jsc("query", s.object({ include_disabled: s.boolean().optional() })),
async (c) => { async (c) => {
const { include_disabled } = c.req.valid("query"); const { include_disabled } = c.req.valid("query");
@@ -201,119 +186,4 @@ export class AuthController extends Controller {
return hono; return hono;
} }
override registerMcp(): void {
const { mcp } = this.auth.ctx;
const idType = s.anyOf([s.number({ title: "Integer" }), s.string({ title: "UUID" })]);
const getUser = async (params: { id?: string | number; email?: string }) => {
let user: DB["users"] | undefined = undefined;
if (params.id) {
const { data } = await this.userRepo.findId(params.id);
user = data;
} else if (params.email) {
const { data } = await this.userRepo.findOne({ email: params.email });
user = data;
}
if (!user) {
throw new Error("User not found");
}
return user;
};
mcp.tool(
// @todo: needs permission
"auth_user_create",
{
description: "Create a new user",
inputSchema: s.object({
email: s.string({ format: "email" }),
password: s.string({ minLength: 8 }),
role: s
.string({
enum: Object.keys(this.auth.config.roles ?? {}),
})
.optional(),
}),
},
async (params, c) => {
await c.context.ctx().helper.throwUnlessGranted(AuthPermissions.createUser, c);
return c.json(await this.auth.createUser(params));
},
);
mcp.tool(
// @todo: needs permission
"auth_user_token",
{
description: "Get a user token",
inputSchema: s.object({
id: idType.optional(),
email: s.string({ format: "email" }).optional(),
}),
},
async (params, c) => {
await c.context.ctx().helper.throwUnlessGranted(AuthPermissions.createToken, c);
const user = await getUser(params);
return c.json({ user, token: await this.auth.authenticator.jwt(user) });
},
);
mcp.tool(
// @todo: needs permission
"auth_user_password_change",
{
description: "Change a user's password",
inputSchema: s.object({
id: idType.optional(),
email: s.string({ format: "email" }).optional(),
password: s.string({ minLength: 8 }),
}),
},
async (params, c) => {
await c.context.ctx().helper.throwUnlessGranted(AuthPermissions.changePassword, c);
const user = await getUser(params);
if (!(await this.auth.changePassword(user.id, params.password))) {
throw new Error("Failed to change password");
}
return c.json({ changed: true });
},
);
mcp.tool(
// @todo: needs permission
"auth_user_password_test",
{
description: "Test a user's password",
inputSchema: s.object({
email: s.string({ format: "email" }),
password: s.string({ minLength: 8 }),
}),
},
async (params, c) => {
await c.context.ctx().helper.throwUnlessGranted(AuthPermissions.testPassword, c);
const pw = this.auth.authenticator.strategy("password") as PasswordStrategy;
const controller = pw.getController(this.auth.authenticator);
const res = await controller.request(
new Request("https://localhost/login", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
email: params.email,
password: params.password,
}),
}),
);
return c.json({ valid: res.ok });
},
);
}
} }
+1 -4
View File
@@ -1,7 +1,4 @@
import { Permission } from "core/security/Permission"; import { Permission } from "core";
export const createUser = new Permission("auth.user.create"); export const createUser = new Permission("auth.user.create");
//export const updateUser = new Permission("auth.user.update"); //export const updateUser = new Permission("auth.user.update");
export const testPassword = new Permission("auth.user.password.test");
export const changePassword = new Permission("auth.user.password.change");
export const createToken = new Permission("auth.user.token.create");
+13 -23
View File
@@ -1,7 +1,7 @@
import { cookieConfig, jwtConfig } from "auth/authenticate/Authenticator"; import { cookieConfig, jwtConfig } from "auth/authenticate/Authenticator";
import { CustomOAuthStrategy, OAuthStrategy, PasswordStrategy } from "auth/authenticate/strategies"; import { CustomOAuthStrategy, OAuthStrategy, PasswordStrategy } from "auth/authenticate/strategies";
import { objectTransform, s } from "bknd/utils"; import { objectTransform } from "core/utils";
import { $object, $record } from "modules/mcp"; import { s } from "core/object/schema";
export const Strategies = { export const Strategies = {
password: { password: {
@@ -46,8 +46,7 @@ export const guardRoleSchema = s.strictObject({
implicit_allow: s.boolean().optional(), implicit_allow: s.boolean().optional(),
}); });
export const authConfigSchema = $object( export const authConfigSchema = s.strictObject(
"config_auth",
{ {
enabled: s.boolean({ default: false }), enabled: s.boolean({ default: false }),
basepath: s.string({ default: "/api/auth" }), basepath: s.string({ default: "/api/auth" }),
@@ -55,29 +54,20 @@ export const authConfigSchema = $object(
allow_register: s.boolean({ default: true }).optional(), allow_register: s.boolean({ default: true }).optional(),
jwt: jwtConfig, jwt: jwtConfig,
cookie: cookieConfig, cookie: cookieConfig,
strategies: $record( strategies: s.record(strategiesSchema, {
"config_auth_strategies", title: "Strategies",
strategiesSchema, default: {
{ password: {
title: "Strategies", type: "password",
default: { enabled: true,
password: { config: {
type: "password", hashing: "sha256",
enabled: true,
config: {
hashing: "sha256",
},
}, },
}, },
}, },
s.strictObject({ }),
type: s.string(),
enabled: s.boolean({ default: true }).optional(),
config: s.object({}),
}),
),
guard: guardConfigSchema.optional(), guard: guardConfigSchema.optional(),
roles: $record("config_auth_roles", guardRoleSchema, { default: {} }).optional(), roles: s.record(guardRoleSchema, { default: {} }).optional(),
}, },
{ title: "Authentication" }, { title: "Authentication" },
); );

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