Compare commits

..

9 Commits

Author SHA1 Message Date
dswbx 0ff310d6c4 e2e: added script to auto test adapters 2025-04-03 16:38:53 +02:00
dswbx 5178dbee0d e2e: replaced image 2025-04-03 11:07:10 +02:00
dswbx f0f2b571b5 e2e: added adapter configs 2025-04-03 11:04:31 +02:00
dswbx 2cff116fcf Merge remote-tracking branch 'origin/release/0.11' into feat/init-e2e 2025-04-03 09:18:09 +02:00
dswbx 53a48b4b6b e2e: overwrite webserver config with env 2025-04-03 07:56:19 +02:00
dswbx 6f92ef7b74 fix bun picking up e2e tests 2025-04-02 20:50:46 +02:00
dswbx e3628a3dc8 updated/moved vitest, finished merge 2025-04-02 20:39:08 +02:00
dswbx fd4bbccfb7 Merge remote-tracking branch 'origin/release/0.11' into feat/init-e2e
# Conflicts:
#	app/.gitignore
#	app/package.json
#	app/vite.dev.ts
#	bun.lock
2025-04-02 20:24:18 +02:00
dswbx 7ed5db5eaa init e2e 2025-03-28 15:17:04 +01:00
203 changed files with 2307 additions and 2848 deletions
-1
View File
@@ -1,4 +1,3 @@
playwright-report playwright-report
test-results test-results
bknd.config.* bknd.config.*
__test__/helper.d.ts
+4 -26
View File
@@ -1,8 +1,8 @@
/// <reference types="@types/bun" /> /// <reference types="@types/bun" />
import { describe, expect, it } from "bun:test"; import { describe, expect, it } from "bun:test";
import { Hono } from "hono"; import { Hono } from "hono";
import { getFileFromContext, isFile, isReadableStream } from "core/utils"; import { getFileFromContext, isFile, isReadableStream } from "../../src/core/utils";
import { MediaApi } from "media/api/MediaApi"; import { MediaApi } from "../../src/media/api/MediaApi";
import { assetsPath, assetsTmpPath } from "../helper"; import { assetsPath, assetsTmpPath } from "../helper";
const mockedBackend = new Hono() const mockedBackend = new Hono()
@@ -39,28 +39,10 @@ describe("MediaApi", () => {
// @ts-ignore tests // @ts-ignore tests
const api = new MediaApi({ const api = new MediaApi({
token: "token", token: "token",
token_transport: "header",
}); });
expect(api.getUploadHeaders().get("Authorization")).toBe("Bearer token"); expect(api.getUploadHeaders().get("Authorization")).toBe("Bearer token");
}); });
it("should return empty headers if not using `header` transport", () => {
expect(
new MediaApi({
token_transport: "cookie",
})
.getUploadHeaders()
.has("Authorization"),
).toBe(false);
expect(
new MediaApi({
token_transport: "none",
})
.getUploadHeaders()
.has("Authorization"),
).toBe(false);
});
it("should get file: native", async () => { it("should get file: native", async () => {
const name = "image.png"; const name = "image.png";
const path = `${assetsTmpPath}/${name}`; const path = `${assetsTmpPath}/${name}`;
@@ -121,12 +103,8 @@ describe("MediaApi", () => {
}); });
it("should upload file in various ways", async () => { it("should upload file in various ways", async () => {
const api = new MediaApi( // @ts-ignore tests
{ const api = new MediaApi({}, mockedBackend.request);
upload_fetcher: mockedBackend.request,
},
mockedBackend.request,
);
const file = Bun.file(`${assetsPath}/image.png`); const file = Bun.file(`${assetsPath}/image.png`);
async function matches(req: Promise<any>, filename: string) { async function matches(req: Promise<any>, filename: string) {
+3 -2
View File
@@ -1,6 +1,7 @@
import { describe, expect, test } from "bun:test"; import { describe, expect, test } from "bun:test";
import { type TObject, type TString, Type } from "@sinclair/typebox"; import type { TObject, TString } from "@sinclair/typebox";
import { Registry } from "core"; import { Registry } from "../../src/core/registry/Registry";
import { type TSchema, Type } from "../../src/core/utils";
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 { SchemaObject } from "../../../src/core"; import { SchemaObject } from "../../../src/core";
import { Type } from "@sinclair/typebox"; import { Type } from "../../../src/core/utils";
describe("SchemaObject", async () => { describe("SchemaObject", async () => {
test("basic", async () => { test("basic", async () => {
@@ -266,12 +266,5 @@ describe("[data] Repository (Events)", async () => {
expect(events.has(RepositoryEvents.RepositoryFindManyBefore.slug)).toBeTrue(); expect(events.has(RepositoryEvents.RepositoryFindManyBefore.slug)).toBeTrue();
expect(events.has(RepositoryEvents.RepositoryFindManyAfter.slug)).toBeTrue(); expect(events.has(RepositoryEvents.RepositoryFindManyAfter.slug)).toBeTrue();
events.clear(); events.clear();
// check find one on findMany with limit 1
await repo.findMany({ where: { id: 1 }, limit: 1 });
await repo.emgr.executeAsyncs();
expect(events.has(RepositoryEvents.RepositoryFindOneBefore.slug)).toBeTrue();
expect(events.has(RepositoryEvents.RepositoryFindOneAfter.slug)).toBeTrue();
events.clear();
}); });
}); });
@@ -1,5 +1,5 @@
import { describe, expect, test } from "bun:test"; import { describe, expect, test } from "bun:test";
import { Type } from "@sinclair/typebox"; import { Type } from "../../../../src/core/utils";
import { Entity, EntityIndex, Field } from "../../../../src/data"; import { Entity, EntityIndex, Field } from "../../../../src/data";
class TestField extends Field { class TestField extends Field {
+41 -22
View File
@@ -1,23 +1,5 @@
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, RenderTask, SubFlowTask } from "../../src/flows";
import { Type } from "@sinclair/typebox";
export class StringifyTask<Output extends string> extends Task<
typeof StringifyTask.schema,
Output
> {
type = "stringify";
static override schema = Type.Optional(
Type.Object({
input: Type.Optional(Type.String()),
}),
);
async execute() {
return JSON.stringify(this.params.input) as Output;
}
}
describe("SubFlowTask", async () => { describe("SubFlowTask", async () => {
test("Simple Subflow", async () => { test("Simple Subflow", async () => {
@@ -40,6 +22,8 @@ describe("SubFlowTask", async () => {
const execution = flow.createExecution(); const execution = flow.createExecution();
await execution.start(); await execution.start();
/*console.log(execution.logs);
console.log(execution.getResponse());*/
expect(execution.getResponse()).toEqual("Subflow output: subflow"); expect(execution.getResponse()).toEqual("Subflow output: subflow");
}); });
@@ -56,8 +40,8 @@ describe("SubFlowTask", async () => {
loop: true, loop: true,
input: [1, 2, 3], input: [1, 2, 3],
}); });
const task3 = new StringifyTask("stringify", { const task3 = new RenderTask("render2", {
input: "{{ sub.output }}", render: `Subflow output: {{ sub.output | join: ", " }}`,
}); });
const flow = new Flow("test", [task, task2, task3], []); const flow = new Flow("test", [task, task2, task3], []);
@@ -67,6 +51,41 @@ describe("SubFlowTask", async () => {
const execution = flow.createExecution(); const execution = flow.createExecution();
await execution.start(); await execution.start();
expect(execution.getResponse()).toEqual('"run 1,run 2,run 3"'); console.log("errors", execution.getErrors());
/*console.log(execution.logs);
console.log(execution.getResponse());*/
expect(execution.getResponse()).toEqual("Subflow output: run 1, run 2, run 3");
});
test("Simple loop from flow input", async () => {
const subTask = new RenderTask("render", {
render: "run {{ flow.output }}",
});
const subflow = new Flow("subflow", [subTask]);
const task = new LogTask("log");
const task2 = new SubFlowTask("sub", {
flow: subflow,
loop: true,
input: "{{ flow.output | json }}",
});
const task3 = new RenderTask("render2", {
render: `Subflow output: {{ sub.output | join: ", " }}`,
});
const flow = new Flow("test", [task, task2, task3], []);
flow.task(task).asInputFor(task2);
flow.task(task2).asInputFor(task3);
const execution = flow.createExecution();
await execution.start([4, 5, 6]);
/*console.log(execution.logs);
console.log(execution.getResponse());*/
expect(execution.getResponse()).toEqual("Subflow output: run 4, run 5, run 6");
}); });
}); });
+59 -1
View File
@@ -1,5 +1,5 @@
import { describe, expect, test } from "bun:test"; import { describe, expect, test } from "bun:test";
import { Type } from "@sinclair/typebox"; import { Type } from "../../src/core/utils";
import { Task } from "../../src/flows"; import { Task } from "../../src/flows";
import { dynamic } from "../../src/flows/tasks/Task"; import { dynamic } from "../../src/flows/tasks/Task";
@@ -51,4 +51,62 @@ describe("Task", async () => {
expect(result.test).toEqual({ key: "path", value: "1/1" }); expect(result.test).toEqual({ key: "path", value: "1/1" });
}); });
test("resolveParams: with json", async () => {
const result = await Task.resolveParams(
Type.Object({
test: dynamic(Type.Object({ key: Type.String(), value: Type.String() })),
}),
{
test: "{{ some | json }}",
},
{
some: {
key: "path",
value: "1/1",
},
},
);
expect(result.test).toEqual({ key: "path", value: "1/1" });
});
test("resolveParams: with array", async () => {
const result = await Task.resolveParams(
Type.Object({
test: dynamic(Type.Array(Type.String())),
}),
{
test: '{{ "1,2,3" | split: "," | json }}',
},
);
expect(result.test).toEqual(["1", "2", "3"]);
});
test("resolveParams: boolean", async () => {
const result = await Task.resolveParams(
Type.Object({
test: dynamic(Type.Boolean()),
}),
{
test: "{{ true }}",
},
);
expect(result.test).toEqual(true);
});
test("resolveParams: float", async () => {
const result = await Task.resolveParams(
Type.Object({
test: dynamic(Type.Number(), Number.parseFloat),
}),
{
test: "{{ 3.14 }}",
},
);
expect(result.test).toEqual(3.14);
});
}); });
+1 -2
View File
@@ -1,8 +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 { parse } from "../../src/core/utils"; import { type Static, type StaticDecode, Type, parse } from "../../src/core/utils";
import { type Static, type StaticDecode, Type } from "@sinclair/typebox";
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 -2
View File
@@ -1,8 +1,7 @@
// eslint-disable-next-line import/no-unresolved // eslint-disable-next-line import/no-unresolved
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 { type Static, Type, _jsonp, withDisabledConsole } from "../../src/core/utils";
import { type Static, Type } from "@sinclair/typebox";
import { Condition, ExecutionEvent, FetchTask, Flow, LogTask, Task } from "../../src/flows"; import { Condition, ExecutionEvent, FetchTask, Flow, LogTask, Task } from "../../src/flows";
/*beforeAll(disableConsoleLog); /*beforeAll(disableConsoleLog);
+1 -60
View File
@@ -69,7 +69,7 @@ describe("AppAuth", () => {
}, },
body: JSON.stringify({ body: JSON.stringify({
email: "some@body.com", email: "some@body.com",
password: "12345678", password: "123456",
}), }),
}); });
enableConsoleLog(); enableConsoleLog();
@@ -81,65 +81,6 @@ describe("AppAuth", () => {
} }
}); });
test("creates user on register (bcrypt)", async () => {
const auth = new AppAuth(
{
enabled: true,
strategies: {
password: {
type: "password",
config: {
hashing: "bcrypt",
},
},
},
// @ts-ignore
jwt: {
secret: "123456",
},
},
ctx,
);
await auth.build();
await ctx.em.schema().sync({ force: true });
// expect no users, but the query to pass
const res = await ctx.em.repository("users").findMany();
expect(res.data.length).toBe(0);
const app = new AuthController(auth).getController();
{
disableConsoleLog();
const res = await app.request("/password/register", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
email: "some@body.com",
password: "12345678",
}),
});
enableConsoleLog();
expect(res.status).toBe(200);
const { data: users } = await ctx.em.repository("users").findMany();
expect(users.length).toBe(1);
expect(users[0]?.email).toBe("some@body.com");
}
{
// check user in database
const rawUser = await ctx.connection.kysely
.selectFrom("users")
.selectAll()
.executeTakeFirstOrThrow();
expect(rawUser.strategy_value).toStartWith("$");
}
});
test("registers auth middleware for bknd routes only", async () => { test("registers auth middleware for bknd routes only", async () => {
const app = createApp({ const app = createApp({
initialConfig: { initialConfig: {
+3 -41
View File
@@ -1,51 +1,13 @@
import { beforeEach, describe, expect, test } from "bun:test"; import { describe, expect, test } from "bun:test";
import { parse } from "../../src/core/utils"; import { parse } from "../../src/core/utils";
import { fieldsSchema } from "../../src/data/data-schema"; import { fieldsSchema } from "../../src/data/data-schema";
import { AppData, type ModuleBuildContext } from "../../src/modules"; import { AppData } from "../../src/modules";
import { makeCtx, moduleTestSuite } from "./module-test-suite"; import { moduleTestSuite } from "./module-test-suite";
import * as proto from "data/prototype";
describe("AppData", () => { describe("AppData", () => {
moduleTestSuite(AppData); moduleTestSuite(AppData);
let ctx: ModuleBuildContext;
beforeEach(() => {
ctx = makeCtx();
});
test("field config construction", () => { test("field config construction", () => {
expect(parse(fieldsSchema, { type: "text" })).toBeDefined(); expect(parse(fieldsSchema, { type: "text" })).toBeDefined();
}); });
test("should prevent multi-deletion of entities in single request", async () => {
const schema = proto.em({
one: proto.entity("one", {
text: proto.text(),
}),
two: proto.entity("two", {
text: proto.text(),
}),
three: proto.entity("three", {
text: proto.text(),
}),
});
const check = () => {
const expected = ["one", "two", "three"];
const fromConfig = Object.keys(data.config.entities ?? {});
const fromEm = data.em.entities.map((e) => e.name);
expect(fromConfig).toEqual(expected);
expect(fromEm).toEqual(expected);
};
// auth must be enabled, otherwise default config is returned
const data = new AppData(schema.toJSON(), ctx);
await data.build();
check();
expect(data.schema().remove("entities")).rejects.toThrow(/more than one entity/);
check();
await data.setContext(makeCtx()).build();
check();
});
}); });
+3 -4
View File
@@ -1,6 +1,5 @@
import { describe, expect, test } from "bun:test"; import { describe, expect, test } from "bun:test";
import { stripMark } from "../../src/core/utils"; import { type TSchema, Type, stripMark } from "../../src/core/utils";
import { type TSchema, Type } from "@sinclair/typebox";
import { EntityManager, em, entity, index, text } from "../../src/data"; import { EntityManager, em, entity, index, text } from "../../src/data";
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";
@@ -10,10 +9,10 @@ function createModule<Schema extends TSchema>(schema: Schema) {
getSchema() { getSchema() {
return schema; return schema;
} }
override toJSON() { toJSON() {
return this.config; return this.config;
} }
override useForceParse() { useForceParse() {
return true; return true;
} }
} }
+5 -132
View File
@@ -1,13 +1,10 @@
import { afterEach, beforeEach, describe, expect, mock, test } from "bun:test"; import { afterEach, beforeEach, describe, expect, mock, test } from "bun:test";
import { disableConsoleLog, enableConsoleLog, stripMark } from "core/utils"; import { Type, disableConsoleLog, enableConsoleLog, stripMark } from "../../src/core/utils";
import { Type } from "@sinclair/typebox"; import { entity, text } from "../../src/data";
import { Connection, entity, text } from "data"; import { Module } from "../../src/modules/Module";
import { Module } from "modules/Module"; import { ModuleManager, getDefaultConfig } from "../../src/modules/ModuleManager";
import { type ConfigTable, getDefaultConfig, ModuleManager } from "modules/ModuleManager"; import { CURRENT_VERSION, TABLE_NAME } from "../../src/modules/migrations";
import { CURRENT_VERSION, TABLE_NAME } from "modules/migrations";
import { getDummyConnection } from "../helper"; import { getDummyConnection } from "../helper";
import { diff } from "core/object/diff";
import type { Static } from "@sinclair/typebox";
describe("ModuleManager", async () => { describe("ModuleManager", async () => {
test("s1: no config, no build", async () => { test("s1: no config, no build", async () => {
@@ -383,128 +380,4 @@ describe("ModuleManager", async () => {
expect(() => f.default()).toThrow(); expect(() => f.default()).toThrow();
}); });
}); });
async function getRawConfig(c: Connection) {
return (await c.kysely
.selectFrom(TABLE_NAME)
.selectAll()
.where("type", "=", "config")
.orderBy("version", "desc")
.executeTakeFirstOrThrow()) as unknown as ConfigTable;
}
async function getDiffs(c: Connection, opts?: { dir?: "asc" | "desc"; limit?: number }) {
return await c.kysely
.selectFrom(TABLE_NAME)
.selectAll()
.where("type", "=", "diff")
.orderBy("version", opts?.dir ?? "desc")
.$if(!!opts?.limit, (b) => b.limit(opts!.limit!))
.execute();
}
describe("diffs", () => {
test("never empty", async () => {
const { dummyConnection: c } = getDummyConnection();
const mm = new ModuleManager(c);
await mm.build();
await mm.save();
expect(await getDiffs(c)).toHaveLength(0);
});
test("has timestamps", async () => {
const { dummyConnection: c } = getDummyConnection();
const mm = new ModuleManager(c);
await mm.build();
await mm.get("data").schema().patch("basepath", "/api/data2");
await mm.save();
const config = await getRawConfig(c);
const diffs = await getDiffs(c);
expect(config.json.data.basepath).toBe("/api/data2");
expect(diffs).toHaveLength(1);
expect(diffs[0]!.created_at).toBeDefined();
expect(diffs[0]!.updated_at).toBeDefined();
});
});
describe("validate & revert", () => {
const schema = Type.Object({
value: Type.Array(Type.Number(), { default: [] }),
});
type SampleSchema = Static<typeof schema>;
class Sample extends Module<typeof schema> {
getSchema() {
return schema;
}
override async build() {
this.setBuilt();
}
override async onBeforeUpdate(from: SampleSchema, to: SampleSchema) {
if (to.value.length > 3) {
throw new Error("too many values");
}
if (to.value.includes(7)) {
throw new Error("contains 7");
}
return to;
}
}
class TestModuleManager extends ModuleManager {
constructor(...args: ConstructorParameters<typeof ModuleManager>) {
super(...args);
this.modules["module1"] = new Sample({}, this.ctx());
}
}
test("respects module onBeforeUpdate", async () => {
const { dummyConnection: c } = getDummyConnection();
const mm = new TestModuleManager(c);
await mm.build();
const m = mm.get("module1" as any) as Sample;
{
expect(async () => {
await m.schema().set({ value: [1, 2, 3, 4, 5] });
return mm.save();
}).toThrow(/too many values/);
expect(m.config.value).toHaveLength(0);
expect((mm.configs() as any).module1.value).toHaveLength(0);
}
{
expect(async () => {
await mm.mutateConfigSafe("module1" as any).set({ value: [1, 2, 3, 4, 5] });
return mm.save();
}).toThrow(/too many values/);
expect(m.config.value).toHaveLength(0);
expect((mm.configs() as any).module1.value).toHaveLength(0);
}
{
expect(async () => {
await m.schema().set({ value: [1, 7, 5] });
return mm.save();
}).toThrow(/contains 7/);
expect(m.config.value).toHaveLength(0);
expect((mm.configs() as any).module1.value).toHaveLength(0);
}
{
expect(async () => {
await mm.mutateConfigSafe("module1" as any).set({ value: [1, 7, 5] });
return mm.save();
}).toThrow(/contains 7/);
expect(m.config.value).toHaveLength(0);
expect((mm.configs() as any).module1.value).toHaveLength(0);
}
});
});
}); });
+2 -10
View File
@@ -186,8 +186,7 @@ const adapters = {
}, },
} as const; } as const;
async function testAdapter(name: keyof typeof adapters) { for (const [name, config] of Object.entries(adapters)) {
const config = adapters[name];
console.log("adapter", c.cyan(name)); console.log("adapter", c.cyan(name));
await config.clean(); await config.clean();
@@ -203,12 +202,5 @@ async function testAdapter(name: keyof typeof adapters) {
await Bun.sleep(250); await Bun.sleep(250);
console.log("Waiting for process to exit..."); console.log("Waiting for process to exit...");
} }
} //process.exit(0);
if (process.env.TEST_ADAPTER) {
await testAdapter(process.env.TEST_ADAPTER as any);
} else {
for (const [name] of Object.entries(adapters)) {
await testAdapter(name as any);
}
} }
+1 -1
View File
@@ -13,7 +13,7 @@ test("can enable media", async ({ page }) => {
await page.goto(`${config.base_path}/media/settings`); await page.goto(`${config.base_path}/media/settings`);
// enable // enable
const enableToggle = page.getByTestId(testIds.media.switchEnabled); const enableToggle = page.locator("css=button#enabled");
if ((await enableToggle.getAttribute("aria-checked")) !== "true") { if ((await enableToggle.getAttribute("aria-checked")) !== "true") {
await expect(enableToggle).toBeVisible(); await expect(enableToggle).toBeVisible();
await enableToggle.click(); await enableToggle.click();
+10 -9
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.11.2", "version": "0.11.0-rc.2",
"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": {
@@ -14,7 +14,7 @@
"url": "https://github.com/bknd-io/bknd/issues" "url": "https://github.com/bknd-io/bknd/issues"
}, },
"scripts": { "scripts": {
"dev": "BKND_CLI_LOG_LEVEL=debug vite", "dev": "vite",
"build": "NODE_ENV=production bun run build.ts --minify --types", "build": "NODE_ENV=production bun run build.ts --minify --types",
"build:all": "rm -rf dist && bun run build:static && NODE_ENV=production bun run build.ts --minify --types --clean && bun run build:cli", "build:all": "rm -rf dist && bun run build:static && NODE_ENV=production bun run build.ts --minify --types --clean && bun run build:cli",
"build:ci": "mkdir -p dist/static/.vite && echo '{}' > dist/static/.vite/manifest.json && NODE_ENV=production bun run build.ts", "build:ci": "mkdir -p dist/static/.vite && echo '{}' > dist/static/.vite/manifest.json && NODE_ENV=production bun run build.ts",
@@ -26,7 +26,7 @@
"build:types": "tsc -p tsconfig.build.json --emitDeclarationOnly && tsc-alias", "build:types": "tsc -p tsconfig.build.json --emitDeclarationOnly && tsc-alias",
"updater": "bun x npm-check-updates -ui", "updater": "bun x npm-check-updates -ui",
"cli": "LOCAL=1 bun src/cli/index.ts", "cli": "LOCAL=1 bun src/cli/index.ts",
"prepublishOnly": "bun run types && bun run test && bun run test:node && bun run test:e2e && bun run build:all && cp ../README.md ./", "prepublishOnly": "bun run types && bun run test && bun run test:node && bun run build:all && cp ../README.md ./",
"postpublish": "rm -f README.md", "postpublish": "rm -f README.md",
"test": "ALL_TESTS=1 bun test --bail", "test": "ALL_TESTS=1 bun test --bail",
"test:all": "bun run test && bun run test:node", "test:all": "bun run test && bun run test:node",
@@ -38,7 +38,6 @@
"test:vitest:watch": "vitest", "test:vitest:watch": "vitest",
"test:vitest:coverage": "vitest run --coverage", "test:vitest:coverage": "vitest run --coverage",
"test:e2e": "playwright test", "test:e2e": "playwright test",
"test:e2e:adapters": "bun run e2e/adapters.ts",
"test:e2e:ui": "playwright test --ui", "test:e2e:ui": "playwright test --ui",
"test:e2e:debug": "playwright test --debug", "test:e2e:debug": "playwright test --debug",
"test:e2e:report": "playwright show-report" "test:e2e:report": "playwright show-report"
@@ -48,28 +47,31 @@
"@cfworker/json-schema": "^4.1.1", "@cfworker/json-schema": "^4.1.1",
"@codemirror/lang-html": "^6.4.9", "@codemirror/lang-html": "^6.4.9",
"@codemirror/lang-json": "^6.0.1", "@codemirror/lang-json": "^6.0.1",
"@codemirror/lang-liquid": "^6.2.2",
"@hello-pangea/dnd": "^18.0.1", "@hello-pangea/dnd": "^18.0.1",
"@libsql/client": "^0.15.2", "@libsql/client": "^0.15.2",
"@mantine/core": "^7.17.1", "@mantine/core": "^7.17.1",
"@mantine/hooks": "^7.17.1", "@mantine/hooks": "^7.17.1",
"@sinclair/typebox": "^0.34.30",
"@tanstack/react-form": "^1.0.5", "@tanstack/react-form": "^1.0.5",
"@uiw/react-codemirror": "^4.23.10", "@uiw/react-codemirror": "^4.23.10",
"@xyflow/react": "^12.4.4", "@xyflow/react": "^12.4.4",
"aws4fetch": "^1.0.20", "aws4fetch": "^1.0.20",
"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.7.4", "hono": "^4.7.4",
"json-schema-form-react": "^0.0.2", "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",
"kysely": "^0.27.6", "kysely": "^0.27.6",
"liquidjs": "^10.21.0",
"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",
"picocolors": "^1.1.1",
"radix-ui": "^1.1.3", "radix-ui": "^1.1.3",
"swr": "^2.3.3", "swr": "^2.3.3",
"lodash-es": "^4.17.21", "wrangler": "^4.4.1"
"@sinclair/typebox": "0.34.30"
}, },
"devDependencies": { "devDependencies": {
"@aws-sdk/client-s3": "^3.758.0", "@aws-sdk/client-s3": "^3.758.0",
@@ -105,7 +107,6 @@
"postcss-preset-mantine": "^1.17.0", "postcss-preset-mantine": "^1.17.0",
"postcss-simple-vars": "^7.0.1", "postcss-simple-vars": "^7.0.1",
"posthog-js-lite": "^3.4.2", "posthog-js-lite": "^3.4.2",
"picocolors": "^1.1.1",
"react": "^19.0.0", "react": "^19.0.0",
"react-dom": "^19.0.0", "react-dom": "^19.0.0",
"react-hook-form": "^7.54.2", "react-hook-form": "^7.54.2",
-1
View File
@@ -12,7 +12,6 @@ export default defineConfig({
retries: process.env.CI ? 2 : 0, retries: process.env.CI ? 2 : 0,
workers: process.env.CI ? 1 : undefined, workers: process.env.CI ? 1 : undefined,
reporter: "html", reporter: "html",
timeout: 20000,
use: { use: {
baseURL: baseUrl, baseURL: baseUrl,
trace: "on-first-retry", trace: "on-first-retry",
+3 -6
View File
@@ -8,11 +8,6 @@ import { omitKeys } from "core/utils";
export type TApiUser = SafeUser; export type TApiUser = SafeUser;
export type ApiFetcher = (
input: RequestInfo | URL,
init?: RequestInit,
) => Response | Promise<Response>;
declare global { declare global {
interface Window { interface Window {
__BKND__: { __BKND__: {
@@ -26,7 +21,7 @@ export type ApiOptions = {
headers?: Headers; headers?: Headers;
key?: string; key?: string;
localStorage?: boolean; localStorage?: boolean;
fetcher?: ApiFetcher; fetcher?: typeof fetch;
verbose?: boolean; verbose?: boolean;
verified?: boolean; verified?: boolean;
} & ( } & (
@@ -122,6 +117,8 @@ export class Api {
this.updateToken(token); this.updateToken(token);
} }
} }
//console.warn("Couldn't extract token");
} }
updateToken(token?: string, rebuild?: boolean) { updateToken(token?: string, rebuild?: boolean) {
+2 -5
View File
@@ -15,7 +15,7 @@ import * as SystemPermissions from "modules/permissions";
import { AdminController, type AdminControllerOptions } from "modules/server/AdminController"; import { AdminController, type AdminControllerOptions } from "modules/server/AdminController";
import { SystemController } from "modules/server/SystemController"; import { SystemController } from "modules/server/SystemController";
// biome-ignore format: must be here // biome-ignore format: must be there
import { Api, type ApiOptions } from "Api"; import { Api, type ApiOptions } from "Api";
import type { ServerEnv } from "modules/Controller"; import type { ServerEnv } from "modules/Controller";
@@ -180,10 +180,7 @@ export class App {
registerAdminController(config?: AdminControllerOptions) { registerAdminController(config?: AdminControllerOptions) {
// register admin // register admin
this.adminController = new AdminController(this, config); this.adminController = new AdminController(this, config);
this.modules.server.route( this.modules.server.route(config?.basepath ?? "/", this.adminController.getController());
this.adminController.basepath,
this.adminController.getController(),
);
return this; return this;
} }
+1 -1
View File
@@ -43,7 +43,7 @@ export async function createApp<Env extends AwsLambdaEnv = AwsLambdaEnv>(
case "url": case "url":
additional.adminOptions = { additional.adminOptions = {
...(typeof adminOptions === "object" ? adminOptions : {}), ...(typeof adminOptions === "object" ? adminOptions : {}),
assetsPath: assets.url, assets_path: assets.url,
}; };
break; break;
default: default:
@@ -1,16 +1,14 @@
/// <reference types="@cloudflare/workers-types" /> /// <reference types="@cloudflare/workers-types" />
import type { RuntimeBkndConfig } from "bknd/adapter"; import type { FrameworkBkndConfig } from "bknd/adapter";
import { Hono } from "hono"; import { Hono } from "hono";
import { serveStatic } from "hono/cloudflare-workers"; import { serveStatic } from "hono/cloudflare-workers";
import { getFresh } from "./modes/fresh";
import { getCached } from "./modes/cached"; import { getCached } from "./modes/cached";
import { getDurable } from "./modes/durable"; import { getDurable } from "./modes/durable";
import type { App } from "bknd"; import { getFresh, getWarm } from "./modes/fresh";
import { $console } from "core";
export type CloudflareEnv = object; export type CloudflareEnv = object;
export type CloudflareBkndConfig<Env = CloudflareEnv> = RuntimeBkndConfig<Env> & { export type CloudflareBkndConfig<Env = CloudflareEnv> = FrameworkBkndConfig<Env> & {
mode?: "warm" | "fresh" | "cache" | "durable"; mode?: "warm" | "fresh" | "cache" | "durable";
bindings?: (args: Env) => { bindings?: (args: Env) => {
kv?: KVNamespace; kv?: KVNamespace;
@@ -22,6 +20,8 @@ export type CloudflareBkndConfig<Env = CloudflareEnv> = RuntimeBkndConfig<Env> &
keepAliveSeconds?: number; keepAliveSeconds?: number;
forceHttps?: boolean; forceHttps?: boolean;
manifest?: string; manifest?: string;
setAdminHtml?: boolean;
html?: string;
}; };
export type Context<Env = CloudflareEnv> = { export type Context<Env = CloudflareEnv> = {
@@ -38,12 +38,12 @@ export function serve<Env extends CloudflareEnv = CloudflareEnv>(
const url = new URL(request.url); const url = new URL(request.url);
if (config.manifest && config.static === "assets") { if (config.manifest && config.static === "assets") {
$console.warn("manifest is not useful with static 'assets'"); console.warn("manifest is not useful with static 'assets'");
} else if (!config.manifest && config.static === "kv") { } else if (!config.manifest && config.static === "kv") {
throw new Error("manifest is required with static 'kv'"); throw new Error("manifest is required with static 'kv'");
} }
if (config.manifest && config.static === "kv") { if (config.manifest && config.static !== "assets") {
const pathname = url.pathname.slice(1); const pathname = url.pathname.slice(1);
const assetManifest = JSON.parse(config.manifest); const assetManifest = JSON.parse(config.manifest);
if (pathname && pathname in assetManifest) { if (pathname && pathname in assetManifest) {
@@ -70,24 +70,18 @@ export function serve<Env extends CloudflareEnv = CloudflareEnv>(
const context = { request, env, ctx } as Context<Env>; const context = { request, env, ctx } as Context<Env>;
const mode = config.mode ?? "warm"; const mode = config.mode ?? "warm";
let app: App;
switch (mode) { switch (mode) {
case "fresh": case "fresh":
app = await getFresh(config, context, { force: true }); return await getFresh(config, context);
break;
case "warm": case "warm":
app = await getFresh(config, context); return await getWarm(config, context);
break;
case "cache": case "cache":
app = await getCached(config, context); return await getCached(config, context);
break;
case "durable": case "durable":
return await getDurable(config, context); return await getDurable(config, context);
default: default:
throw new Error(`Unknown mode ${mode}`); throw new Error(`Unknown mode ${mode}`);
} }
return app.fetch(request, env, ctx);
}, },
}; };
} }
+2 -3
View File
@@ -5,7 +5,6 @@ import type { CloudflareBkndConfig, CloudflareEnv } from ".";
import { App } from "bknd"; import { App } from "bknd";
import { makeConfig as makeAdapterConfig } from "bknd/adapter"; import { makeConfig as makeAdapterConfig } from "bknd/adapter";
import type { ExecutionContext } from "hono"; import type { ExecutionContext } from "hono";
import { $console } from "core";
export const constants = { export const constants = {
exec_async_event_id: "cf_register_waituntil", exec_async_event_id: "cf_register_waituntil",
@@ -28,12 +27,12 @@ export function makeConfig<Env extends CloudflareEnv = CloudflareEnv>(
if (!appConfig.connection) { if (!appConfig.connection) {
let db: D1Database | undefined; let db: D1Database | undefined;
if (bindings?.db) { if (bindings?.db) {
$console.log("Using database from bindings"); console.log("Using database from bindings");
db = bindings.db; db = bindings.db;
} else if (Object.keys(args).length > 0) { } else if (Object.keys(args).length > 0) {
const binding = getBinding(args, "D1Database"); const binding = getBinding(args, "D1Database");
if (binding) { if (binding) {
$console.log(`Using database from env "${binding.key}"`); console.log(`Using database from env "${binding.key}"`);
db = binding.value; db = binding.value;
} }
} }
+1 -1
View File
@@ -1,7 +1,7 @@
import { D1Connection, type D1ConnectionConfig } from "./D1Connection"; import { D1Connection, type D1ConnectionConfig } from "./D1Connection";
export * from "./cloudflare-workers.adapter"; export * from "./cloudflare-workers.adapter";
export { makeApp, getFresh } from "./modes/fresh"; export { makeApp, getFresh, getWarm } from "./modes/fresh";
export { getCached } from "./modes/cached"; export { getCached } from "./modes/cached";
export { DurableBkndApp, getDurable } from "./modes/durable"; export { DurableBkndApp, getDurable } from "./modes/durable";
export { D1Connection, type D1ConnectionConfig }; export { D1Connection, type D1ConnectionConfig };
@@ -40,6 +40,7 @@ export async function getCached<Env extends CloudflareEnv = CloudflareEnv>(
); );
await config.beforeBuild?.(app); await config.beforeBuild?.(app);
}, },
adminOptions: { html: config.html },
}, },
{ env, ctx, ...args }, { env, ctx, ...args },
); );
+3 -3
View File
@@ -3,7 +3,6 @@ import type { App, CreateAppConfig } from "bknd";
import { createRuntimeApp, makeConfig } from "bknd/adapter"; import { createRuntimeApp, makeConfig } from "bknd/adapter";
import type { CloudflareBkndConfig, Context, CloudflareEnv } from "../index"; import type { CloudflareBkndConfig, Context, CloudflareEnv } from "../index";
import { constants, registerAsyncsExecutionContext } from "../config"; import { constants, registerAsyncsExecutionContext } from "../config";
import { $console } from "core";
export async function getDurable<Env extends CloudflareEnv = CloudflareEnv>( export async function getDurable<Env extends CloudflareEnv = CloudflareEnv>(
config: CloudflareBkndConfig<Env>, config: CloudflareBkndConfig<Env>,
@@ -14,7 +13,7 @@ export async function getDurable<Env extends CloudflareEnv = CloudflareEnv>(
const key = config.key ?? "app"; const key = config.key ?? "app";
if ([config.onBuilt, config.beforeBuild].some((x) => x)) { if ([config.onBuilt, config.beforeBuild].some((x) => x)) {
$console.warn("onBuilt and beforeBuild are not supported with DurableObject mode"); console.log("onBuilt and beforeBuild are not supported with DurableObject mode");
} }
const start = performance.now(); const start = performance.now();
@@ -26,7 +25,9 @@ export async function getDurable<Env extends CloudflareEnv = CloudflareEnv>(
const res = await stub.fire(ctx.request, { const res = await stub.fire(ctx.request, {
config: create_config, config: create_config,
html: config.html,
keepAliveSeconds: config.keepAliveSeconds, keepAliveSeconds: config.keepAliveSeconds,
setAdminHtml: config.setAdminHtml,
}); });
const headers = new Headers(res.headers); const headers = new Headers(res.headers);
@@ -109,7 +110,6 @@ export class DurableBkndApp extends DurableObject {
} }
async onBuilt(app: App) {} async onBuilt(app: App) {}
async beforeBuild(app: App) {} async beforeBuild(app: App) {}
protected keepAlive(seconds: number) { protected keepAlive(seconds: number) {
+31 -12
View File
@@ -7,7 +7,33 @@ export async function makeApp<Env extends CloudflareEnv = CloudflareEnv>(
args: Env = {} as Env, args: Env = {} as Env,
opts?: RuntimeOptions, opts?: RuntimeOptions,
) { ) {
return await createRuntimeApp<Env>(makeConfig(config, args), args, opts); return await createRuntimeApp<Env>(
{
...makeConfig(config, args),
adminOptions: config.html ? { html: config.html } : undefined,
},
args,
opts,
);
}
export async function getWarm<Env extends CloudflareEnv = CloudflareEnv>(
config: CloudflareBkndConfig<Env>,
ctx: Context<Env>,
opts: RuntimeOptions = {},
) {
const app = await makeApp(
{
...config,
onBuilt: async (app) => {
registerAsyncsExecutionContext(app, ctx.ctx);
config.onBuilt?.(app);
},
},
ctx.env,
opts,
);
return app.fetch(ctx.request);
} }
export async function getFresh<Env extends CloudflareEnv = CloudflareEnv>( export async function getFresh<Env extends CloudflareEnv = CloudflareEnv>(
@@ -15,15 +41,8 @@ export async function getFresh<Env extends CloudflareEnv = CloudflareEnv>(
ctx: Context<Env>, ctx: Context<Env>,
opts: RuntimeOptions = {}, opts: RuntimeOptions = {},
) { ) {
return await makeApp( return await getWarm(config, ctx, {
{ ...opts,
...config, force: true,
onBuilt: async (app) => { });
registerAsyncsExecutionContext(app, ctx.ctx);
await config.onBuilt?.(app);
},
},
ctx.env,
opts,
);
} }
@@ -3,7 +3,7 @@ import { test } from "node:test";
import { Miniflare } from "miniflare"; import { Miniflare } from "miniflare";
import { StorageR2Adapter } from "./StorageR2Adapter"; import { StorageR2Adapter } from "./StorageR2Adapter";
import { adapterTestSuite } from "media"; import { adapterTestSuite } from "media";
import { nodeTestRunner } from "adapter/node/test"; import { nodeTestRunner } from "adapter/node";
import path from "node:path"; import path from "node:path";
// https://github.com/nodejs/node/issues/44372#issuecomment-1736530480 // https://github.com/nodejs/node/issues/44372#issuecomment-1736530480
@@ -1,10 +1,8 @@
import { registries } from "bknd"; import { registries } from "bknd";
import { isDebug } from "bknd/core"; import { isDebug } from "bknd/core";
import { StringEnum } from "bknd/utils"; import { StringEnum, Type } from "bknd/utils";
import { guessMimeType as guess, StorageAdapter, type FileBody } from "bknd/media"; import { guessMimeType as guess, StorageAdapter, type FileBody } from "bknd/media";
import { getBindings } from "../bindings"; import { getBindings } from "../bindings";
import * as tb from "@sinclair/typebox";
const { Type } = tb;
export function makeSchema(bindings: string[] = []) { export function makeSchema(bindings: string[] = []) {
return Type.Object( return Type.Object(
@@ -124,10 +122,12 @@ export class StorageR2Adapter extends StorageAdapter {
} }
} }
//console.log("response headers:before", headersToObject(responseHeaders));
this.writeHttpMetadata(responseHeaders, object); this.writeHttpMetadata(responseHeaders, object);
responseHeaders.set("etag", object.httpEtag); responseHeaders.set("etag", object.httpEtag);
responseHeaders.set("Content-Length", String(object.size)); responseHeaders.set("Content-Length", String(object.size));
responseHeaders.set("Last-Modified", object.uploaded.toUTCString()); responseHeaders.set("Last-Modified", object.uploaded.toUTCString());
//console.log("response headers:after", headersToObject(responseHeaders));
return new Response(object.body, { return new Response(object.body, {
status: object.range ? 206 : 200, status: object.range ? 206 : 200,
+1
View File
@@ -3,6 +3,7 @@ import { type LocalAdapterConfig, StorageLocalAdapter } from "./storage/StorageL
export * from "./node.adapter"; export * from "./node.adapter";
export { StorageLocalAdapter, type LocalAdapterConfig }; export { StorageLocalAdapter, type LocalAdapterConfig };
export { nodeTestRunner } from "./test";
let registered = false; let registered = false;
export function registerLocalMediaAdapter() { export function registerLocalMediaAdapter() {
@@ -1,7 +1,7 @@
import { describe, before, after } from "node:test"; import { describe, before, after } from "node:test";
import * as node from "./node.adapter"; import * as node from "./node.adapter";
import { adapterTestSuite } from "adapter/adapter-test-suite"; import { adapterTestSuite } from "adapter/adapter-test-suite";
import { nodeTestRunner } from "adapter/node/test"; import { nodeTestRunner } from "adapter/node";
import { disableConsoleLog, enableConsoleLog } from "core/utils"; import { disableConsoleLog, enableConsoleLog } from "core/utils";
before(() => disableConsoleLog()); before(() => disableConsoleLog());
+1 -2
View File
@@ -4,7 +4,6 @@ import { serveStatic } from "@hono/node-server/serve-static";
import { registerLocalMediaAdapter } from "adapter/node/index"; import { registerLocalMediaAdapter } from "adapter/node/index";
import { type RuntimeBkndConfig, createRuntimeApp, type RuntimeOptions } from "bknd/adapter"; import { type RuntimeBkndConfig, createRuntimeApp, type RuntimeOptions } from "bknd/adapter";
import { config as $config } from "bknd/core"; import { config as $config } from "bknd/core";
import { $console } from "core";
type NodeEnv = NodeJS.ProcessEnv; type NodeEnv = NodeJS.ProcessEnv;
export type NodeBkndConfig<Env = NodeEnv> = RuntimeBkndConfig<Env> & { export type NodeBkndConfig<Env = NodeEnv> = RuntimeBkndConfig<Env> & {
@@ -63,7 +62,7 @@ export function serve<Env = NodeEnv>(
fetch: createHandler(config, args, opts), fetch: createHandler(config, args, opts),
}, },
(connInfo) => { (connInfo) => {
$console.log(`Server is running on http://localhost:${connInfo.port}`); console.log(`Server is running on http://localhost:${connInfo.port}`);
listener?.(connInfo); listener?.(connInfo);
}, },
); );
@@ -1,6 +1,5 @@
import { describe } from "node:test"; import { describe } from "node:test";
import { nodeTestRunner } from "adapter/node/test"; import { StorageLocalAdapter, nodeTestRunner } from "adapter/node";
import { StorageLocalAdapter } from "adapter/node";
import { adapterTestSuite } from "media/storage/adapters/adapter-test-suite"; import { adapterTestSuite } from "media/storage/adapters/adapter-test-suite";
import { readFileSync } from "node:fs"; import { readFileSync } from "node:fs";
import path from "node:path"; import path from "node:path";
@@ -1,9 +1,7 @@
import { readFile, readdir, stat, unlink, writeFile } from "node:fs/promises"; import { readFile, readdir, stat, unlink, writeFile } from "node:fs/promises";
import { type Static, isFile, parse } from "bknd/utils"; import { type Static, Type, isFile, parse } from "bknd/utils";
import type { FileBody, FileListObject, FileMeta, FileUploadPayload } from "bknd/media"; import type { FileBody, FileListObject, FileMeta, FileUploadPayload } from "bknd/media";
import { StorageAdapter, guessMimeType as guess } from "bknd/media"; import { StorageAdapter, guessMimeType as guess } from "bknd/media";
import * as tb from "@sinclair/typebox";
const { Type } = tb;
export const localAdapterConfig = Type.Object( export const localAdapterConfig = Type.Object(
{ {
+38 -32
View File
@@ -1,24 +1,18 @@
import { serveStatic } from "@hono/node-server/serve-static"; import { serveStatic } from "@hono/node-server/serve-static";
import { import { type DevServerOptions, default as honoViteDevServer } from "@hono/vite-dev-server";
type DevServerOptions,
default as honoViteDevServer,
} from "@hono/vite-dev-server";
import type { App } from "bknd"; import type { App } from "bknd";
import { import { type RuntimeBkndConfig, createRuntimeApp } from "bknd/adapter";
type RuntimeBkndConfig,
createRuntimeApp,
type FrameworkOptions,
} from "bknd/adapter";
import { registerLocalMediaAdapter } from "bknd/adapter/node"; import { registerLocalMediaAdapter } from "bknd/adapter/node";
import { devServerConfig } from "./dev-server-config"; import { devServerConfig } from "./dev-server-config";
export type ViteEnv = NodeJS.ProcessEnv; export type ViteBkndConfig<Env = any> = RuntimeBkndConfig<Env> & {
export type ViteBkndConfig<Env = ViteEnv> = RuntimeBkndConfig<Env> & {}; mode?: "cached" | "fresh";
setAdminHtml?: boolean;
forceDev?: boolean | { mainPath: string };
html?: string;
};
export function addViteScript( export function addViteScript(html: string, addBkndContext: boolean = true) {
html: string,
addBkndContext: boolean = true,
) {
return html.replace( return html.replace(
"</head>", "</head>",
`<script type="module"> `<script type="module">
@@ -34,40 +28,52 @@ ${addBkndContext ? "<!-- BKND_CONTEXT -->" : ""}
); );
} }
async function createApp<ViteEnv>( async function createApp(config: ViteBkndConfig = {}, env?: any) {
config: ViteBkndConfig<ViteEnv> = {},
env: ViteEnv = {} as ViteEnv,
opts: FrameworkOptions = {},
): Promise<App> {
registerLocalMediaAdapter(); registerLocalMediaAdapter();
return await createRuntimeApp( return await createRuntimeApp(
{ {
...config, ...config,
adminOptions: config.adminOptions ?? { adminOptions:
forceDev: { config.setAdminHtml === false
mainPath: "/src/main.tsx", ? undefined
}, : {
}, html: config.html,
forceDev: config.forceDev ?? {
mainPath: "/src/main.tsx",
},
},
serveStatic: ["/assets/*", serveStatic({ root: config.distPath ?? "./" })], serveStatic: ["/assets/*", serveStatic({ root: config.distPath ?? "./" })],
}, },
env, env,
opts,
); );
} }
export function serve<ViteEnv>( export function serveFresh(config: Omit<ViteBkndConfig, "mode"> = {}) {
config: ViteBkndConfig<ViteEnv> = {},
args?: ViteEnv,
opts?: FrameworkOptions,
) {
return { return {
async fetch(request: Request, env: any, ctx: ExecutionContext) { async fetch(request: Request, env: any, ctx: ExecutionContext) {
const app = await createApp(config, env, opts); const app = await createApp(config, env);
return app.fetch(request, env, ctx); return app.fetch(request, env, ctx);
}, },
}; };
} }
let app: App;
export function serveCached(config: Omit<ViteBkndConfig, "mode"> = {}) {
return {
async fetch(request: Request, env: any, ctx: ExecutionContext) {
if (!app) {
app = await createApp(config, env);
}
return app.fetch(request, env, ctx);
},
};
}
export function serve({ mode, ...config }: ViteBkndConfig = {}) {
return mode === "fresh" ? serveFresh(config) : serveCached(config);
}
export function devServer(options: DevServerOptions) { export function devServer(options: DevServerOptions) {
return honoViteDevServer({ return honoViteDevServer({
...devServerConfig, ...devServerConfig,
+135 -12
View File
@@ -1,13 +1,20 @@
import { Authenticator, AuthPermissions, Role, type Strategy } from "auth"; import {
type AuthAction,
AuthPermissions,
Authenticator,
type ProfileExchange,
Role,
type Strategy,
} from "auth";
import type { PasswordStrategy } from "auth/authenticate/strategies"; import type { PasswordStrategy } from "auth/authenticate/strategies";
import { $console, type DB, type PrimaryFieldType } from "core"; import { $console, type DB, Exception, type PrimaryFieldType } from "core";
import { secureRandomString, transformObject } from "core/utils"; import { type Static, secureRandomString, transformObject } from "core/utils";
import type { Entity, EntityManager } from "data"; import type { Entity, EntityManager } from "data";
import { em, entity, enumm, type FieldSchema, text } from "data/prototype"; import { type FieldSchema, em, entity, enumm, text } from "data/prototype";
import { pick } from "lodash-es";
import { Module } from "modules/Module"; import { Module } from "modules/Module";
import { AuthController } from "./api/AuthController"; import { AuthController } from "./api/AuthController";
import { type AppAuthSchema, authConfigSchema, STRATEGIES } from "./auth-schema"; import { type AppAuthSchema, STRATEGIES, authConfigSchema } from "./auth-schema";
import { AppUserPool } from "auth/AppUserPool";
export type UserFieldSchema = FieldSchema<typeof AppAuth.usersFields>; export type UserFieldSchema = FieldSchema<typeof AppAuth.usersFields>;
declare module "core" { declare module "core" {
@@ -16,6 +23,7 @@ declare module "core" {
} }
} }
type AuthSchema = Static<typeof authConfigSchema>;
export type CreateUserPayload = { email: string; password: string; [key: string]: any }; export type CreateUserPayload = { email: string; password: string; [key: string]: any };
export class AppAuth extends Module<typeof authConfigSchema> { export class AppAuth extends Module<typeof authConfigSchema> {
@@ -23,12 +31,12 @@ export class AppAuth extends Module<typeof authConfigSchema> {
cache: Record<string, any> = {}; cache: Record<string, any> = {};
_controller!: AuthController; _controller!: AuthController;
override async onBeforeUpdate(from: AppAuthSchema, to: AppAuthSchema) { override async onBeforeUpdate(from: AuthSchema, to: AuthSchema) {
const defaultSecret = authConfigSchema.properties.jwt.properties.secret.default; const defaultSecret = authConfigSchema.properties.jwt.properties.secret.default;
if (!from.enabled && to.enabled) { if (!from.enabled && to.enabled) {
if (to.jwt.secret === defaultSecret) { if (to.jwt.secret === defaultSecret) {
$console.warn("No JWT secret provided, generating a random one"); console.warn("No JWT secret provided, generating a random one");
to.jwt.secret = secureRandomString(64); to.jwt.secret = secureRandomString(64);
} }
} }
@@ -72,7 +80,7 @@ export class AppAuth extends Module<typeof authConfigSchema> {
} }
}); });
this._authenticator = new Authenticator(strategies, new AppUserPool(this), { this._authenticator = new Authenticator(strategies, this.resolveUser.bind(this), {
jwt: this.config.jwt, jwt: this.config.jwt,
cookie: this.config.cookie, cookie: this.config.cookie,
}); });
@@ -82,7 +90,7 @@ export class AppAuth extends Module<typeof authConfigSchema> {
this._controller = new AuthController(this); this._controller = new AuthController(this);
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(Object.values(AuthPermissions));
} }
isStrategyEnabled(strategy: Strategy | string) { isStrategyEnabled(strategy: Strategy | string) {
@@ -114,6 +122,120 @@ export class AppAuth extends Module<typeof authConfigSchema> {
return this.ctx.em as any; return this.ctx.em as any;
} }
private async resolveUser(
action: AuthAction,
strategy: Strategy,
identifier: string,
profile: ProfileExchange,
): Promise<any> {
if (!this.config.allow_register && action === "register") {
throw new Exception("Registration is not allowed", 403);
}
const fields = this.getUsersEntity()
.getFillableFields("create")
.map((f) => f.name);
const filteredProfile = Object.fromEntries(
Object.entries(profile).filter(([key]) => fields.includes(key)),
);
switch (action) {
case "login":
return this.login(strategy, identifier, filteredProfile);
case "register":
return this.register(strategy, identifier, filteredProfile);
}
}
private filterUserData(user: any) {
return pick(user, this.config.jwt.fields);
}
private async login(strategy: Strategy, identifier: string, profile: ProfileExchange) {
if (!("email" in profile)) {
throw new Exception("Profile must have email");
}
if (typeof identifier !== "string" || identifier.length === 0) {
throw new Exception("Identifier must be a string");
}
const users = this.getUsersEntity();
this.toggleStrategyValueVisibility(true);
const result = await this.em
.repo(users as unknown as "users")
.findOne({ email: profile.email! });
this.toggleStrategyValueVisibility(false);
if (!result.data) {
throw new Exception("User not found", 404);
}
// compare strategy and identifier
if (result.data.strategy !== strategy.getName()) {
//console.log("!!! User registered with different strategy");
throw new Exception("User registered with different strategy");
}
if (result.data.strategy_value !== identifier) {
throw new Exception("Invalid credentials");
}
return this.filterUserData(result.data);
}
private async register(strategy: Strategy, identifier: string, profile: ProfileExchange) {
if (!("email" in profile)) {
throw new Exception("Profile must have an email");
}
if (typeof identifier !== "string" || identifier.length === 0) {
throw new Exception("Identifier must be a string");
}
const users = this.getUsersEntity();
const { data } = await this.em.repo(users).findOne({ email: profile.email! });
if (data) {
throw new Exception("User already exists");
}
const payload: any = {
...profile,
strategy: strategy.getName(),
strategy_value: identifier,
};
const mutator = this.em.mutator(users);
mutator.__unstable_toggleSystemEntityCreation(false);
this.toggleStrategyValueVisibility(true);
const createResult = await mutator.insertOne(payload);
mutator.__unstable_toggleSystemEntityCreation(true);
this.toggleStrategyValueVisibility(false);
if (!createResult.data) {
throw new Error("Could not create user");
}
return this.filterUserData(createResult.data);
}
private toggleStrategyValueVisibility(visible: boolean) {
const toggle = (name: string, visible: boolean) => {
const field = this.getUsersEntity().field(name)!;
if (visible) {
field.config.hidden = false;
field.config.fillable = true;
} else {
// reset to normal
const template = AppAuth.usersFields.strategy_value.config;
field.config.hidden = template.hidden;
field.config.fillable = template.fillable;
}
};
toggle("strategy_value", visible);
toggle("strategy", visible);
// @todo: think about a PasswordField that automatically hashes on save?
}
getUsersEntity(forceCreate?: boolean): Entity<"users", typeof AppAuth.usersFields> { getUsersEntity(forceCreate?: boolean): Entity<"users", typeof AppAuth.usersFields> {
const entity_name = this.config.entity_name; const entity_name = this.config.entity_name;
if (forceCreate || !this.em.hasEntity(entity_name)) { if (forceCreate || !this.em.hasEntity(entity_name)) {
@@ -166,7 +288,7 @@ export class AppAuth extends Module<typeof authConfigSchema> {
throw new Error("Cannot create user, auth not enabled"); throw new Error("Cannot create user, auth not enabled");
} }
const strategy = "password" as const; const strategy = "password";
const pw = this.authenticator.strategy(strategy) as PasswordStrategy; const pw = this.authenticator.strategy(strategy) as PasswordStrategy;
const strategy_value = await pw.hash(password); const strategy_value = await pw.hash(password);
const mutator = this.em.mutator(this.config.entity_name as "users"); const mutator = this.em.mutator(this.config.entity_name as "users");
@@ -193,7 +315,8 @@ export class AppAuth extends Module<typeof authConfigSchema> {
...this.authenticator.toJSON(secrets), ...this.authenticator.toJSON(secrets),
strategies: transformObject(strategies, (strategy) => ({ strategies: transformObject(strategies, (strategy) => ({
enabled: this.isStrategyEnabled(strategy), enabled: this.isStrategyEnabled(strategy),
...strategy.toJSON(secrets), type: strategy.getType(),
config: strategy.toJSON(secrets),
})), })),
}; };
} }
-83
View File
@@ -1,83 +0,0 @@
import { AppAuth } from "auth/AppAuth";
import type { CreateUser, SafeUser, User, UserPool } from "auth/authenticate/Authenticator";
import { $console } from "core";
import { pick } from "lodash-es";
import {
InvalidConditionsException,
UnableToCreateUserException,
UserNotFoundException,
} from "auth/errors";
export class AppUserPool implements UserPool {
constructor(private appAuth: AppAuth) {}
get em() {
return this.appAuth.em;
}
get users() {
return this.appAuth.getUsersEntity();
}
async findBy(strategy: string, prop: keyof SafeUser, value: any) {
$console.debug("[AppUserPool:findBy]", { strategy, prop, value });
this.toggleStrategyValueVisibility(true);
const result = await this.em.repo(this.users).findOne({ [prop]: value, strategy });
this.toggleStrategyValueVisibility(false);
if (!result.data) {
$console.debug("[AppUserPool]: User not found");
throw new UserNotFoundException();
}
return result.data;
}
async create(strategy: string, payload: CreateUser & Partial<Omit<User, "id">>) {
$console.debug("[AppUserPool:create]", { strategy, payload });
if (!("strategy_value" in payload)) {
throw new InvalidConditionsException("Profile must have a strategy_value value");
}
const fields = this.users.getSelect(undefined, "create");
const safeProfile = pick(payload, fields) as any;
const createPayload: Omit<User, "id"> = {
...safeProfile,
strategy,
};
const mutator = this.em.mutator(this.users);
mutator.__unstable_toggleSystemEntityCreation(false);
this.toggleStrategyValueVisibility(true);
const createResult = await mutator.insertOne(createPayload);
mutator.__unstable_toggleSystemEntityCreation(true);
this.toggleStrategyValueVisibility(false);
if (!createResult.data) {
throw new UnableToCreateUserException();
}
$console.debug("[AppUserPool]: User created", createResult.data);
return createResult.data;
}
private toggleStrategyValueVisibility(visible: boolean) {
const toggle = (name: string, visible: boolean) => {
const field = this.users.field(name)!;
if (visible) {
field.config.hidden = false;
field.config.fillable = true;
} else {
// reset to normal
const template = AppAuth.usersFields.strategy_value.config;
field.config.hidden = template.hidden;
field.config.fillable = template.fillable;
}
};
toggle("strategy_value", visible);
toggle("strategy", visible);
// @todo: think about a PasswordField that automatically hashes on save?
}
}
+1 -3
View File
@@ -1,11 +1,9 @@
import { type AppAuth, AuthPermissions, type SafeUser, type Strategy } from "auth"; import { type AppAuth, AuthPermissions, type SafeUser, type Strategy } from "auth";
import { tbValidator as tb } from "core"; import { tbValidator as tb } from "core";
import { TypeInvalidError, parse, transformObject } from "core/utils"; import { Type, TypeInvalidError, parse, transformObject } from "core/utils";
import { DataPermissions } from "data"; import { DataPermissions } from "data";
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 * as tbbox from "@sinclair/typebox";
const { Type } = tbbox;
export type AuthActionResponse = { export type AuthActionResponse = {
success: boolean; success: boolean;
+1 -3
View File
@@ -1,8 +1,6 @@
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 { type Static, StringRecord, objectTransform } from "core/utils"; import { type Static, StringRecord, Type, objectTransform } from "core/utils";
import * as tbbox from "@sinclair/typebox";
const { Type } = tbbox;
export const Strategies = { export const Strategies = {
password: { password: {
+88 -137
View File
@@ -1,22 +1,19 @@
import { $console, type DB, Exception } from "core"; import { type DB, Exception } from "core";
import { addFlashMessage } from "core/server/flash"; import { addFlashMessage } from "core/server/flash";
import { import {
type Static, type Static,
StringEnum, StringEnum,
type TObject, type TObject,
Type,
parse, parse,
runtimeSupports, runtimeSupports,
truncate, transformObject,
} from "core/utils"; } from "core/utils";
import type { Context, Hono } from "hono"; import type { Context, Hono } from "hono";
import { deleteCookie, getSignedCookie, setSignedCookie } from "hono/cookie"; import { deleteCookie, getSignedCookie, setSignedCookie } from "hono/cookie";
import { sign, verify } from "hono/jwt"; import { sign, verify } from "hono/jwt";
import type { CookieOptions } from "hono/utils/cookie"; import type { CookieOptions } from "hono/utils/cookie";
import type { ServerEnv } from "modules/Controller"; import type { ServerEnv } from "modules/Controller";
import { pick } from "lodash-es";
import * as tbbox from "@sinclair/typebox";
import { InvalidConditionsException } from "auth/errors";
const { Type } = tbbox;
type Input = any; // workaround type Input = any; // workaround
export type JWTPayload = Parameters<typeof sign>[0]; export type JWTPayload = Parameters<typeof sign>[0];
@@ -25,12 +22,11 @@ export const strategyActions = ["create", "change"] as const;
export type StrategyActionName = (typeof strategyActions)[number]; export type StrategyActionName = (typeof strategyActions)[number];
export type StrategyAction<S extends TObject = TObject> = { export type StrategyAction<S extends TObject = TObject> = {
schema: S; schema: S;
preprocess: (input: Static<S>) => Promise<Omit<DB["users"], "id" | "strategy">>; preprocess: (input: unknown) => Promise<Omit<DB["users"], "id" | "strategy">>;
}; };
export type StrategyActions = Partial<Record<StrategyActionName, StrategyAction>>; export type StrategyActions = Partial<Record<StrategyActionName, StrategyAction>>;
// @todo: add schema to interface to ensure proper inference // @todo: add schema to interface to ensure proper inference
// @todo: add tests (e.g. invalid strategy_value)
export interface Strategy { export interface Strategy {
getController: (auth: Authenticator) => Hono<any>; getController: (auth: Authenticator) => Hono<any>;
getType: () => string; getType: () => string;
@@ -40,22 +36,29 @@ export interface Strategy {
getActions?: () => StrategyActions; getActions?: () => StrategyActions;
} }
export type User = DB["users"]; export type User = {
id: number;
email: string;
username: string;
password: string;
role: string;
};
export type ProfileExchange = { export type ProfileExchange = {
email?: string; email?: string;
strategy?: string; username?: string;
strategy_value?: string; sub?: string;
password?: string;
[key: string]: any; [key: string]: any;
}; };
export type SafeUser = Omit<User, "strategy_value">; export type SafeUser = Omit<User, "password">;
export type CreateUser = Pick<User, "email"> & { [key: string]: any }; export type CreateUser = Pick<User, "email"> & { [key: string]: any };
export type AuthResponse = { user: SafeUser; token: string }; export type AuthResponse = { user: SafeUser; token: string };
export interface UserPool { export interface UserPool<Fields = "id" | "email" | "username"> {
findBy: (strategy: string, prop: keyof SafeUser, value: string | number) => Promise<User>; findBy: (prop: Fields, value: string | number) => Promise<User | undefined>;
create: (strategy: string, user: CreateUser) => Promise<User>; create: (user: CreateUser) => Promise<User | undefined>;
} }
const defaultCookieExpires = 60 * 60 * 24 * 7; // 1 week in seconds const defaultCookieExpires = 60 * 60 * 24 * 7; // 1 week in seconds
@@ -97,17 +100,12 @@ export const authenticatorConfig = Type.Object({
type AuthConfig = Static<typeof authenticatorConfig>; type AuthConfig = Static<typeof authenticatorConfig>;
export type AuthAction = "login" | "register"; export type AuthAction = "login" | "register";
export type AuthResolveOptions = {
identifier?: "email" | string;
redirect?: string;
forceJsonResponse?: boolean;
};
export type AuthUserResolver = ( export type AuthUserResolver = (
action: AuthAction, action: AuthAction,
strategy: Strategy, strategy: Strategy,
identifier: string,
profile: ProfileExchange, profile: ProfileExchange,
opts?: AuthResolveOptions, ) => Promise<SafeUser | undefined>;
) => Promise<ProfileExchange | undefined>;
type AuthClaims = SafeUser & { type AuthClaims = SafeUser & {
iat: number; iat: number;
iss?: string; iss?: string;
@@ -115,117 +113,33 @@ type AuthClaims = SafeUser & {
}; };
export class Authenticator<Strategies extends Record<string, Strategy> = Record<string, Strategy>> { export class Authenticator<Strategies extends Record<string, Strategy> = Record<string, Strategy>> {
private readonly strategies: Strategies;
private readonly config: AuthConfig; private readonly config: AuthConfig;
private readonly userResolver: AuthUserResolver;
constructor( constructor(strategies: Strategies, userResolver?: AuthUserResolver, config?: AuthConfig) {
private readonly strategies: Strategies, this.userResolver = userResolver ?? (async (a, s, i, p) => p as any);
private readonly userPool: UserPool, this.strategies = strategies as Strategies;
config?: AuthConfig,
) {
this.config = parse(authenticatorConfig, config ?? {}); this.config = parse(authenticatorConfig, config ?? {});
} }
async resolveLogin( async resolve(
c: Context, action: AuthAction,
strategy: Strategy, strategy: Strategy,
profile: Partial<SafeUser>, identifier: string,
verify: (user: User) => Promise<void>, profile: ProfileExchange,
opts?: AuthResolveOptions, ): Promise<AuthResponse> {
) { //console.log("resolve", { action, strategy: strategy.getName(), profile });
try { const user = await this.userResolver(action, strategy, identifier, profile);
// @todo: centralize identifier and checks
// @todo: check identifier value (if allowed)
const identifier = opts?.identifier || "email";
if (typeof identifier !== "string" || identifier.length === 0) {
throw new InvalidConditionsException("Identifier must be a string");
}
if (!(identifier in profile)) {
throw new InvalidConditionsException(`Profile must have identifier "${identifier}"`);
}
const user = await this.userPool.findBy( if (user) {
strategy.getName(), return {
identifier as any, user,
profile[identifier], token: await this.jwt(user),
); };
if (!user.strategy_value) {
throw new InvalidConditionsException("User must have a strategy value");
} else if (user.strategy !== strategy.getName()) {
throw new InvalidConditionsException("User signed up with a different strategy");
}
await verify(user);
const data = await this.safeAuthResponse(user);
return this.respondWithUser(c, data, opts);
} catch (e) {
return this.respondWithError(c, e as Error, opts);
}
}
async resolveRegister(
c: Context,
strategy: Strategy,
profile: CreateUser,
verify: (user: User) => Promise<void>,
opts?: AuthResolveOptions,
) {
try {
const identifier = opts?.identifier || "email";
if (typeof identifier !== "string" || identifier.length === 0) {
throw new InvalidConditionsException("Identifier must be a string");
}
if (!(identifier in profile)) {
throw new InvalidConditionsException(`Profile must have identifier "${identifier}"`);
}
if (!("strategy_value" in profile)) {
throw new InvalidConditionsException("Profile must have a strategy value");
}
const user = await this.userPool.create(strategy.getName(), {
...profile,
strategy_value: profile.strategy_value,
});
await verify(user);
const data = await this.safeAuthResponse(user);
return this.respondWithUser(c, data, opts);
} catch (e) {
return this.respondWithError(c, e as Error, opts);
}
}
private async respondWithUser(c: Context, data: AuthResponse, opts?: AuthResolveOptions) {
const successUrl = this.getSafeUrl(
c,
opts?.redirect ?? this.config.cookie.pathSuccess ?? "/",
);
if ("token" in data) {
await this.setAuthCookie(c, data.token);
if (this.isJsonRequest(c) || opts?.forceJsonResponse) {
return c.json(data);
}
// can't navigate to "/" doesn't work on nextjs
return c.redirect(successUrl);
} }
throw new Exception("Invalid response"); throw new Error("User could not be resolved");
}
async respondWithError(c: Context, error: Error, opts?: AuthResolveOptions) {
$console.error("respondWithError", error);
if (this.isJsonRequest(c) || opts?.forceJsonResponse) {
// let the server handle it
throw error;
}
await addFlashMessage(c, String(error), "error");
const referer = this.getSafeUrl(c, opts?.redirect ?? c.req.header("Referer") ?? "/");
return c.redirect(referer);
} }
getStrategies(): Strategies { getStrategies(): Strategies {
@@ -244,8 +158,13 @@ export class Authenticator<Strategies extends Record<string, Strategy> = Record<
} }
// @todo: add jwt tests // @todo: add jwt tests
async jwt(_user: SafeUser | ProfileExchange): Promise<string> { async jwt(user: Omit<User, "password">): Promise<string> {
const user = pick(_user, this.config.jwt.fields); const prohibited = ["password"];
for (const prop of prohibited) {
if (prop in user) {
throw new Error(`Property "${prop}" is prohibited`);
}
}
const payload: JWTPayload = { const payload: JWTPayload = {
...user, ...user,
@@ -270,14 +189,6 @@ export class Authenticator<Strategies extends Record<string, Strategy> = Record<
return sign(payload, secret, this.config.jwt?.alg ?? "HS256"); return sign(payload, secret, this.config.jwt?.alg ?? "HS256");
} }
async safeAuthResponse(_user: User): Promise<AuthResponse> {
const user = pick(_user, this.config.jwt.fields) as SafeUser;
return {
user,
token: await this.jwt(user),
};
}
async verify(jwt: string): Promise<AuthClaims | undefined> { async verify(jwt: string): Promise<AuthClaims | undefined> {
try { try {
const payload = await verify( const payload = await verify(
@@ -319,7 +230,7 @@ export class Authenticator<Strategies extends Record<string, Strategy> = Record<
return token; return token;
} catch (e: any) { } catch (e: any) {
if (e instanceof Error) { if (e instanceof Error) {
$console.error("[getAuthCookie]", e.message); console.error("[Error:getAuthCookie]", e.message);
} }
return undefined; return undefined;
@@ -336,13 +247,11 @@ export class Authenticator<Strategies extends Record<string, Strategy> = Record<
} }
private async setAuthCookie(c: Context<ServerEnv>, token: string) { private async setAuthCookie(c: Context<ServerEnv>, token: string) {
$console.debug("setting auth cookie", truncate(token));
const secret = this.config.jwt.secret; const secret = this.config.jwt.secret;
await setSignedCookie(c, "auth", token, secret, this.cookieOptions); await setSignedCookie(c, "auth", token, secret, this.cookieOptions);
} }
private async deleteAuthCookie(c: Context) { private async deleteAuthCookie(c: Context) {
$console.debug("deleting auth cookie");
await deleteCookie(c, "auth", this.cookieOptions); await deleteCookie(c, "auth", this.cookieOptions);
} }
@@ -358,6 +267,7 @@ export class Authenticator<Strategies extends Record<string, Strategy> = Record<
// @todo: move this to a server helper // @todo: move this to a server helper
isJsonRequest(c: Context): boolean { isJsonRequest(c: Context): boolean {
//return c.req.header("Content-Type") === "application/x-www-form-urlencoded";
return c.req.header("Content-Type") === "application/json"; return c.req.header("Content-Type") === "application/json";
} }
@@ -381,6 +291,37 @@ export class Authenticator<Strategies extends Record<string, Strategy> = Record<
return p; return p;
} }
async respond(c: Context, data: AuthResponse | Error | any, redirect?: string) {
const successUrl = this.getSafeUrl(c, redirect ?? this.config.cookie.pathSuccess ?? "/");
const referer = redirect ?? c.req.header("Referer") ?? successUrl;
//console.log("auth respond", { redirect, successUrl, successPath });
if ("token" in data) {
await this.setAuthCookie(c, data.token);
if (this.isJsonRequest(c)) {
return c.json(data);
}
// can't navigate to "/" doesn't work on nextjs
//console.log("auth success, redirecting to", successUrl);
return c.redirect(successUrl);
}
if (this.isJsonRequest(c)) {
return c.json(data, 400);
}
let message = "An error occured";
if (data instanceof Exception) {
message = data.message;
}
await addFlashMessage(c, message, "error");
//console.log("auth failed, redirecting to", referer);
return c.redirect(referer);
}
// @todo: don't extract user from token, but from the database or cache // @todo: don't extract user from token, but from the database or cache
async resolveAuthFromRequest(c: Context): Promise<SafeUser | undefined> { async resolveAuthFromRequest(c: Context): Promise<SafeUser | undefined> {
let token: string | undefined; let token: string | undefined;
@@ -405,3 +346,13 @@ export class Authenticator<Strategies extends Record<string, Strategy> = Record<
}; };
} }
} }
export function createStrategyAction<S extends TObject>(
schema: S,
preprocess: (input: Static<S>) => Promise<Partial<DB["users"]>>,
) {
return {
schema,
preprocess,
} as StrategyAction<S>;
}
@@ -1,135 +1,152 @@
import { type Authenticator, InvalidCredentialsException, type User } from "auth"; import type { Authenticator, Strategy } from "auth";
import { $console, tbValidator as tb } from "core"; import { isDebug, tbValidator as tb } from "core";
import { hash, parse, type Static, StrictObject, StringEnum } from "core/utils"; import { type Static, StringEnum, Type, parse } from "core/utils";
import { Hono } from "hono"; import { hash } from "core/utils";
import { compare as bcryptCompare, genSalt as bcryptGenSalt, hash as bcryptHash } from "bcryptjs"; import { type Context, Hono } from "hono";
import * as tbbox from "@sinclair/typebox"; import { type StrategyAction, type StrategyActions, createStrategyAction } from "../Authenticator";
import { Strategy } from "./Strategy";
const { Type } = tbbox; type LoginSchema = { username: string; password: string } | { email: string; password: string };
type RegisterSchema = { email: string; password: string; [key: string]: any };
const schema = StrictObject({ const schema = Type.Object({
hashing: StringEnum(["plain", "sha256", "bcrypt"], { default: "sha256" }), hashing: StringEnum(["plain", "sha256" /*, "bcrypt"*/] as const, { default: "sha256" }),
rounds: Type.Optional(Type.Number({ minimum: 1, maximum: 10 })),
}); });
export type PasswordStrategyOptions = Static<typeof schema>; export type PasswordStrategyOptions = Static<typeof schema>;
/*export type PasswordStrategyOptions2 = {
hashing?: "plain" | "bcrypt" | "sha256";
};*/
export class PasswordStrategy extends Strategy<typeof schema> { export class PasswordStrategy implements Strategy {
constructor(config: Partial<PasswordStrategyOptions> = {}) { private options: PasswordStrategyOptions;
super(config as any, "password", "password", "form");
this.registerAction("create", this.getPayloadSchema(), async ({ password, ...input }) => { constructor(options: Partial<PasswordStrategyOptions> = {}) {
return { this.options = parse(schema, options);
...input, }
strategy_value: await this.hash(password),
}; async hash(password: string) {
}); switch (this.options.hashing) {
case "sha256":
return hash.sha256(password);
default:
return password;
}
}
async login(input: LoginSchema) {
if (!("email" in input) || !("password" in input)) {
throw new Error("Invalid input: Email and password must be provided");
}
const hashedPassword = await this.hash(input.password);
return { ...input, password: hashedPassword };
}
async register(input: RegisterSchema) {
if (!input.email || !input.password) {
throw new Error("Invalid input: Email and password must be provided");
}
return {
...input,
password: await this.hash(input.password),
};
}
getController(authenticator: Authenticator): Hono<any> {
const hono = new Hono();
return hono
.post(
"/login",
tb(
"query",
Type.Object({
redirect: Type.Optional(Type.String()),
}),
),
async (c) => {
const body = await authenticator.getBody(c);
const { redirect } = c.req.valid("query");
try {
const payload = await this.login(body);
const data = await authenticator.resolve(
"login",
this,
payload.password,
payload,
);
return await authenticator.respond(c, data, redirect);
} catch (e) {
return await authenticator.respond(c, e);
}
},
)
.post(
"/register",
tb(
"query",
Type.Object({
redirect: Type.Optional(Type.String()),
}),
),
async (c) => {
const body = await authenticator.getBody(c);
const { redirect } = c.req.valid("query");
const payload = await this.register(body);
const data = await authenticator.resolve(
"register",
this,
payload.password,
payload,
);
return await authenticator.respond(c, data, redirect);
},
);
}
getActions(): StrategyActions {
return {
create: createStrategyAction(
Type.Object({
email: Type.String({
pattern: "^[\\w-\\.]+@([\\w-]+\\.)+[\\w-]{2,4}$",
}),
password: Type.String({
minLength: 8, // @todo: this should be configurable
}),
}),
async ({ password, ...input }) => {
return {
...input,
strategy_value: await this.hash(password),
};
},
),
};
} }
getSchema() { getSchema() {
return schema; return schema;
} }
private getPayloadSchema() { getType() {
return Type.Object({ return "password";
email: Type.String({
pattern: "^[\\w-\\.\\+_]+@([\\w-]+\\.)+[\\w-]{2,4}$",
}),
password: Type.String({
minLength: 8, // @todo: this should be configurable
}),
});
} }
async hash(password: string) { getMode() {
switch (this.config.hashing) { return "form" as const;
case "sha256":
return hash.sha256(password);
case "bcrypt": {
const salt = await bcryptGenSalt(this.config.rounds ?? 4);
return bcryptHash(password, salt);
}
default:
return password;
}
} }
async compare(actual: string, compare: string): Promise<boolean> { getName() {
switch (this.config.hashing) { return "password" as const;
case "sha256": {
const compareHashed = await this.hash(compare);
return actual === compareHashed;
}
case "bcrypt":
return await bcryptCompare(compare, actual);
}
return false;
} }
verify(password: string) { toJSON(secrets?: boolean) {
return async (user: User) => { return secrets ? this.options : undefined;
const compare = await this.compare(user?.strategy_value!, password);
if (compare !== true) {
throw new InvalidCredentialsException();
}
};
}
getController(authenticator: Authenticator): Hono<any> {
const hono = new Hono();
const redirectQuerySchema = Type.Object({
redirect: Type.Optional(Type.String()),
});
const payloadSchema = this.getPayloadSchema();
hono.post("/login", tb("query", redirectQuerySchema), async (c) => {
try {
const body = parse(payloadSchema, await authenticator.getBody(c), {
onError: (errors) => {
$console.error("Invalid login payload", [...errors]);
throw new InvalidCredentialsException();
},
});
const { redirect } = c.req.valid("query");
return await authenticator.resolveLogin(c, this, body, this.verify(body.password), {
redirect,
});
} catch (e) {
return authenticator.respondWithError(c, e as any);
}
});
hono.post("/register", tb("query", redirectQuerySchema), async (c) => {
try {
const { redirect } = c.req.valid("query");
const { password, email, ...body } = parse(
payloadSchema,
await authenticator.getBody(c),
{
onError: (errors) => {
$console.error("Invalid register payload", [...errors]);
new InvalidCredentialsException();
},
},
);
const profile = {
...body,
email,
strategy_value: await this.hash(password),
};
return await authenticator.resolveRegister(c, this, profile, async () => void 0, {
redirect,
});
} catch (e) {
return authenticator.respondWithError(c, e as any);
}
});
return hono;
} }
} }
@@ -1,63 +0,0 @@
import type {
Authenticator,
StrategyAction,
StrategyActionName,
StrategyActions,
} from "../Authenticator";
import type { Hono } from "hono";
import type { Static, TSchema } from "@sinclair/typebox";
import { parse, type TObject } from "core/utils";
export type StrategyMode = "form" | "external";
export abstract class Strategy<Schema extends TSchema = TSchema> {
protected actions: StrategyActions = {};
constructor(
protected config: Static<Schema>,
public type: string,
public name: string,
public mode: StrategyMode,
) {
// don't worry about typing, it'll throw if invalid
this.config = parse(this.getSchema(), (config ?? {}) as any) as Static<Schema>;
}
protected registerAction<S extends TObject = TObject>(
name: StrategyActionName,
schema: S,
preprocess: StrategyAction<S>["preprocess"],
): void {
this.actions[name] = {
schema,
preprocess,
} as const;
}
protected abstract getSchema(): Schema;
abstract getController(auth: Authenticator): Hono;
getType(): string {
return this.type;
}
getMode() {
return this.mode;
}
getName(): string {
return this.name;
}
toJSON(secrets?: boolean): { type: string; config: Static<Schema> | {} | undefined } {
return {
type: this.getType(),
config: secrets ? this.config : undefined,
};
}
getActions(): StrategyActions {
return this.actions;
}
}
@@ -5,8 +5,8 @@ import { OAuthCallbackException, OAuthStrategy } from "./oauth/OAuthStrategy";
export * as issuers from "./oauth/issuers"; export * as issuers from "./oauth/issuers";
export { export {
type PasswordStrategyOptions,
PasswordStrategy, PasswordStrategy,
type PasswordStrategyOptions,
OAuthStrategy, OAuthStrategy,
OAuthCallbackException, OAuthCallbackException,
CustomOAuthStrategy, CustomOAuthStrategy,
@@ -1,35 +1,43 @@
import { type Static, StrictObject, StringEnum } from "core/utils"; import { type Static, StringEnum, Type } from "core/utils";
import * as tbbox from "@sinclair/typebox";
import type * as oauth from "oauth4webapi"; import type * as oauth from "oauth4webapi";
import { OAuthStrategy } from "./OAuthStrategy"; import { OAuthStrategy } from "./OAuthStrategy";
const { Type } = tbbox;
type SupportedTypes = "oauth2" | "oidc"; type SupportedTypes = "oauth2" | "oidc";
type RequireKeys<T extends object, K extends keyof T> = Required<Pick<T, K>> & Omit<T, K>; type RequireKeys<T extends object, K extends keyof T> = Required<Pick<T, K>> & Omit<T, K>;
const UrlString = Type.String({ pattern: "^(https?|wss?)://[^\\s/$.?#].[^\\s]*$" }); const UrlString = Type.String({ pattern: "^(https?|wss?)://[^\\s/$.?#].[^\\s]*$" });
const oauthSchemaCustom = StrictObject( const oauthSchemaCustom = Type.Object(
{ {
type: StringEnum(["oidc", "oauth2"] as const, { default: "oidc" }), type: StringEnum(["oidc", "oauth2"] as const, { default: "oidc" }),
name: Type.String(), name: Type.String(),
client: StrictObject({ client: Type.Object(
client_id: Type.String(), {
client_secret: Type.String(), client_id: Type.String(),
token_endpoint_auth_method: StringEnum(["client_secret_basic"]), client_secret: Type.String(),
}), token_endpoint_auth_method: StringEnum(["client_secret_basic"]),
as: StrictObject({ },
issuer: Type.String(), {
code_challenge_methods_supported: Type.Optional(StringEnum(["S256"])), additionalProperties: false,
scopes_supported: Type.Optional(Type.Array(Type.String())), },
scope_separator: Type.Optional(Type.String({ default: " " })), ),
authorization_endpoint: Type.Optional(UrlString), as: Type.Object(
token_endpoint: Type.Optional(UrlString), {
userinfo_endpoint: Type.Optional(UrlString), issuer: Type.String(),
}), code_challenge_methods_supported: Type.Optional(StringEnum(["S256"])),
scopes_supported: Type.Optional(Type.Array(Type.String())),
scope_separator: Type.Optional(Type.String({ default: " " })),
authorization_endpoint: Type.Optional(UrlString),
token_endpoint: Type.Optional(UrlString),
userinfo_endpoint: Type.Optional(UrlString),
},
{
additionalProperties: false,
},
),
// @todo: profile mapping // @todo: profile mapping
}, },
{ title: "Custom OAuth" }, { title: "Custom OAuth", additionalProperties: false },
); );
type OAuthConfigCustom = Static<typeof oauthSchemaCustom>; type OAuthConfigCustom = Static<typeof oauthSchemaCustom>;
@@ -54,11 +62,6 @@ export type IssuerConfig<UserInfo = any> = {
}; };
export class CustomOAuthStrategy extends OAuthStrategy { export class CustomOAuthStrategy extends OAuthStrategy {
constructor(config: OAuthConfigCustom) {
super(config as any);
this.type = "custom_oauth";
}
override getIssuerConfig(): IssuerConfig { override getIssuerConfig(): IssuerConfig {
return { ...this.config, profile: async (info) => info } as any; return { ...this.config, profile: async (info) => info } as any;
} }
@@ -67,4 +70,8 @@ export class CustomOAuthStrategy extends OAuthStrategy {
override getSchema() { override getSchema() {
return oauthSchemaCustom; return oauthSchemaCustom;
} }
override getType() {
return "custom_oauth";
}
} }
@@ -1,13 +1,10 @@
import type { AuthAction, Authenticator } from "auth"; import type { AuthAction, Authenticator, Strategy } from "auth";
import { Exception, isDebug } from "core"; import { Exception, isDebug } from "core";
import { type Static, StringEnum, filterKeys, StrictObject } from "core/utils"; import { type Static, StringEnum, type TSchema, Type, filterKeys, parse } from "core/utils";
import { type Context, Hono } from "hono"; import { type Context, Hono } from "hono";
import { getSignedCookie, setSignedCookie } from "hono/cookie"; import { getSignedCookie, setSignedCookie } from "hono/cookie";
import * as oauth from "oauth4webapi"; import * as oauth from "oauth4webapi";
import * as issuers from "./issuers"; import * as issuers from "./issuers";
import * as tbbox from "@sinclair/typebox";
import { Strategy } from "auth/authenticate/strategies/Strategy";
const { Type } = tbbox;
type ConfiguredIssuers = keyof typeof issuers; type ConfiguredIssuers = keyof typeof issuers;
type SupportedTypes = "oauth2" | "oidc"; type SupportedTypes = "oauth2" | "oidc";
@@ -16,12 +13,17 @@ type RequireKeys<T extends object, K extends keyof T> = Required<Pick<T, K>> & O
const schemaProvided = Type.Object( const schemaProvided = Type.Object(
{ {
//type: StringEnum(["oidc", "oauth2"] as const, { default: "oidc" }),
name: StringEnum(Object.keys(issuers) as ConfiguredIssuers[]), name: StringEnum(Object.keys(issuers) as ConfiguredIssuers[]),
type: StringEnum(["oidc", "oauth2"] as const, { default: "oauth2" }), client: Type.Object(
client: StrictObject({ {
client_id: Type.String(), client_id: Type.String(),
client_secret: Type.String(), client_secret: Type.String(),
}), },
{
additionalProperties: false,
},
),
}, },
{ title: "OAuth" }, { title: "OAuth" },
); );
@@ -69,13 +71,11 @@ export class OAuthCallbackException extends Exception {
} }
} }
export class OAuthStrategy extends Strategy<typeof schemaProvided> { export class OAuthStrategy implements Strategy {
constructor(config: ProvidedOAuthConfig) { constructor(private _config: OAuthConfig) {}
super(config, "oauth", config.name, "external");
}
getSchema() { get config() {
return schemaProvided; return this._config;
} }
getIssuerConfig(): IssuerConfig { getIssuerConfig(): IssuerConfig {
@@ -103,7 +103,7 @@ export class OAuthStrategy extends Strategy<typeof schemaProvided> {
type: info.type, type: info.type,
client: { client: {
...info.client, ...info.client,
...this.config.client, ...this._config.client,
}, },
}; };
} }
@@ -172,7 +172,8 @@ export class OAuthStrategy extends Strategy<typeof schemaProvided> {
) { ) {
const config = await this.getConfig(); const config = await this.getConfig();
const { client, as, type } = config; const { client, as, type } = config;
//console.log("config", config);
console.log("callbackParams", callbackParams, options);
const parameters = oauth.validateAuthResponse( const parameters = oauth.validateAuthResponse(
as, as,
client, // no client_secret required client, // no client_secret required
@@ -180,9 +181,13 @@ export class OAuthStrategy extends Strategy<typeof schemaProvided> {
oauth.expectNoState, oauth.expectNoState,
); );
if (oauth.isOAuth2Error(parameters)) { if (oauth.isOAuth2Error(parameters)) {
//console.log("callback.error", parameters);
throw new OAuthCallbackException(parameters, "validateAuthResponse"); throw new OAuthCallbackException(parameters, "validateAuthResponse");
} }
/*console.log(
"callback.parameters",
JSON.stringify(Object.fromEntries(parameters.entries()), null, 2),
);*/
const response = await oauth.authorizationCodeGrantRequest( const response = await oauth.authorizationCodeGrantRequest(
as, as,
client, client,
@@ -190,9 +195,13 @@ export class OAuthStrategy extends Strategy<typeof schemaProvided> {
options.redirect_uri, options.redirect_uri,
options.state, options.state,
); );
//console.log("callback.response", response);
const challenges = oauth.parseWwwAuthenticateChallenges(response); const challenges = oauth.parseWwwAuthenticateChallenges(response);
if (challenges) { if (challenges) {
for (const challenge of challenges) {
//console.log("callback.challenge", challenge);
}
// @todo: Handle www-authenticate challenges as needed // @todo: Handle www-authenticate challenges as needed
throw new OAuthCallbackException(challenges, "www-authenticate"); throw new OAuthCallbackException(challenges, "www-authenticate");
} }
@@ -207,13 +216,20 @@ export class OAuthStrategy extends Strategy<typeof schemaProvided> {
expectedNonce, expectedNonce,
); );
if (oauth.isOAuth2Error(result)) { if (oauth.isOAuth2Error(result)) {
console.log("callback.error", result);
// @todo: Handle OAuth 2.0 response body error // @todo: Handle OAuth 2.0 response body error
throw new OAuthCallbackException(result, "processAuthorizationCodeOpenIDResponse"); throw new OAuthCallbackException(result, "processAuthorizationCodeOpenIDResponse");
} }
//console.log("callback.result", result);
const claims = oauth.getValidatedIdTokenClaims(result); const claims = oauth.getValidatedIdTokenClaims(result);
//console.log("callback.IDTokenClaims", claims);
const infoRequest = await oauth.userInfoRequest(as, client, result.access_token!); const infoRequest = await oauth.userInfoRequest(as, client, result.access_token!);
const resultUser = await oauth.processUserInfoResponse(as, client, claims.sub, infoRequest); const resultUser = await oauth.processUserInfoResponse(as, client, claims.sub, infoRequest);
//console.log("callback.resultUser", resultUser);
return await config.profile(resultUser, config, claims); // @todo: check claims return await config.profile(resultUser, config, claims); // @todo: check claims
} }
@@ -224,7 +240,8 @@ export class OAuthStrategy extends Strategy<typeof schemaProvided> {
) { ) {
const config = await this.getConfig(); const config = await this.getConfig();
const { client, type, as, profile } = config; const { client, type, as, profile } = config;
console.log("config", { client, as, type });
console.log("callbackParams", callbackParams, options);
const parameters = oauth.validateAuthResponse( const parameters = oauth.validateAuthResponse(
as, as,
client, // no client_secret required client, // no client_secret required
@@ -232,9 +249,13 @@ export class OAuthStrategy extends Strategy<typeof schemaProvided> {
oauth.expectNoState, oauth.expectNoState,
); );
if (oauth.isOAuth2Error(parameters)) { if (oauth.isOAuth2Error(parameters)) {
console.log("callback.error", parameters);
throw new OAuthCallbackException(parameters, "validateAuthResponse"); throw new OAuthCallbackException(parameters, "validateAuthResponse");
} }
console.log(
"callback.parameters",
JSON.stringify(Object.fromEntries(parameters.entries()), null, 2),
);
const response = await oauth.authorizationCodeGrantRequest( const response = await oauth.authorizationCodeGrantRequest(
as, as,
client, client,
@@ -245,6 +266,9 @@ export class OAuthStrategy extends Strategy<typeof schemaProvided> {
const challenges = oauth.parseWwwAuthenticateChallenges(response); const challenges = oauth.parseWwwAuthenticateChallenges(response);
if (challenges) { if (challenges) {
for (const challenge of challenges) {
//console.log("callback.challenge", challenge);
}
// @todo: Handle www-authenticate challenges as needed // @todo: Handle www-authenticate challenges as needed
throw new OAuthCallbackException(challenges, "www-authenticate"); throw new OAuthCallbackException(challenges, "www-authenticate");
} }
@@ -255,15 +279,19 @@ export class OAuthStrategy extends Strategy<typeof schemaProvided> {
try { try {
result = await oauth.processAuthorizationCodeOAuth2Response(as, client, response); result = await oauth.processAuthorizationCodeOAuth2Response(as, client, response);
if (oauth.isOAuth2Error(result)) { if (oauth.isOAuth2Error(result)) {
console.log("error", result);
throw new Error(); // Handle OAuth 2.0 response body error throw new Error(); // Handle OAuth 2.0 response body error
} }
} catch (e) { } catch (e) {
result = (await copy.json()) as any; result = (await copy.json()) as any;
console.log("failed", result);
} }
const res2 = await oauth.userInfoRequest(as, client, result.access_token!); const res2 = await oauth.userInfoRequest(as, client, result.access_token!);
const user = await res2.json(); const user = await res2.json();
console.log("res2", res2, user);
console.log("result", result);
return await config.profile(user, config, result); return await config.profile(user, config, result);
} }
@@ -273,6 +301,7 @@ export class OAuthStrategy extends Strategy<typeof schemaProvided> {
): Promise<UserProfile> { ): Promise<UserProfile> {
const type = this.getIssuerConfig().type; const type = this.getIssuerConfig().type;
console.log("type", type);
switch (type) { switch (type) {
case "oidc": case "oidc":
return await this.oidc(callbackParams, options); return await this.oidc(callbackParams, options);
@@ -296,6 +325,7 @@ export class OAuthStrategy extends Strategy<typeof schemaProvided> {
}; };
const setState = async (c: Context, config: TState): Promise<void> => { const setState = async (c: Context, config: TState): Promise<void> => {
console.log("--- setting state", config);
await setSignedCookie(c, cookie_name, JSON.stringify(config), secret, { await setSignedCookie(c, cookie_name, JSON.stringify(config), secret, {
secure: true, secure: true,
httpOnly: true, httpOnly: true,
@@ -326,6 +356,7 @@ export class OAuthStrategy extends Strategy<typeof schemaProvided> {
const params = new URLSearchParams(url.search); const params = new URLSearchParams(url.search);
const state = await getState(c); const state = await getState(c);
console.log("state", state);
// @todo: add config option to determine if state.action is allowed // @todo: add config option to determine if state.action is allowed
const redirect_uri = const redirect_uri =
@@ -338,28 +369,21 @@ export class OAuthStrategy extends Strategy<typeof schemaProvided> {
state: state.state, state: state.state,
}); });
const safeProfile = { try {
email: profile.email, const data = await auth.resolve(state.action, this, profile.sub, profile);
strategy_value: profile.sub, console.log("******** RESOLVED ********", data);
} as const;
const verify = async (user) => { if (state.mode === "cookie") {
if (user.strategy_value !== profile.sub) { return await auth.respond(c, data, state.redirect);
throw new Exception("Invalid credentials");
} }
};
const opts = {
redirect: state.redirect,
forceJsonResponse: state.mode !== "cookie",
} as const;
switch (state.action) { return c.json(data);
case "login": } catch (e) {
return auth.resolveLogin(c, this, safeProfile, verify, opts); if (state.mode === "cookie") {
case "register": return await auth.respond(c, e, state.redirect);
return auth.resolveRegister(c, this, safeProfile, verify, opts); }
default:
throw new Error("Invalid action"); throw e;
} }
}); });
@@ -388,8 +412,10 @@ export class OAuthStrategy extends Strategy<typeof schemaProvided> {
redirect_uri, redirect_uri,
state, state,
}); });
//console.log("_state", state);
await setState(c, { state, action, redirect: referer.toString(), mode: "cookie" }); await setState(c, { state, action, redirect: referer.toString(), mode: "cookie" });
console.log("--redirecting to", response.url);
return c.redirect(response.url); return c.redirect(response.url);
}); });
@@ -430,15 +456,28 @@ export class OAuthStrategy extends Strategy<typeof schemaProvided> {
return hono; return hono;
} }
override toJSON(secrets?: boolean) { getType() {
return "oauth";
}
getMode() {
return "external" as const;
}
getName() {
return this.config.name;
}
getSchema() {
return schemaProvided;
}
toJSON(secrets?: boolean) {
const config = secrets ? this.config : filterKeys(this.config, ["secret", "client_id"]); const config = secrets ? this.config : filterKeys(this.config, ["secret", "client_id"]);
return { return {
...super.toJSON(secrets), type: this.getIssuerConfig().type,
config: { ...config,
...config,
type: this.getIssuerConfig().type,
},
}; };
} }
} }
@@ -34,6 +34,8 @@ export const github: IssuerConfig<GithubUserInfo> = {
config: Omit<IssuerConfig, "profile">, config: Omit<IssuerConfig, "profile">,
tokenResponse: any, tokenResponse: any,
) => { ) => {
console.log("github info", info, config, tokenResponse);
try { try {
const res = await fetch("https://api.github.com/user/emails", { const res = await fetch("https://api.github.com/user/emails", {
headers: { headers: {
@@ -43,6 +45,7 @@ export const github: IssuerConfig<GithubUserInfo> = {
}, },
}); });
const data = (await res.json()) as GithubUserEmailResponse; const data = (await res.json()) as GithubUserEmailResponse;
console.log("data", data);
const email = data.find((e: any) => e.primary)?.email; const email = data.find((e: any) => e.primary)?.email;
if (!email) { if (!email) {
throw new Error("No primary email found"); throw new Error("No primary email found");
+20 -22
View File
@@ -1,4 +1,4 @@
import { $console, Exception, Permission } from "core"; import { Exception, Permission } from "core";
import { objectTransform } from "core/utils"; import { objectTransform } from "core/utils";
import type { Context } from "hono"; import type { Context } from "hono";
import type { ServerEnv } from "modules/Controller"; import type { ServerEnv } from "modules/Controller";
@@ -14,6 +14,8 @@ export type GuardConfig = {
}; };
export type GuardContext = Context<ServerEnv> | GuardUserContext; export type GuardContext = Context<ServerEnv> | GuardUserContext;
const debug = false;
export class Guard { export class Guard {
permissions: Permission[]; permissions: Permission[];
roles?: Role[]; roles?: Role[];
@@ -81,12 +83,8 @@ export class Guard {
return this; return this;
} }
registerPermissions(permissions: Record<string, Permission>); registerPermissions(permissions: Permission[]) {
registerPermissions(permissions: Permission[]); for (const permission of permissions) {
registerPermissions(permissions: Permission[] | Record<string, Permission>) {
const p = Array.isArray(permissions) ? permissions : Object.values(permissions);
for (const permission of p) {
this.registerPermission(permission); this.registerPermission(permission);
} }
@@ -97,14 +95,16 @@ export class Guard {
if (user && typeof user.role === "string") { if (user && typeof user.role === "string") {
const role = this.roles?.find((role) => role.name === user?.role); const role = this.roles?.find((role) => role.name === user?.role);
if (role) { if (role) {
$console.debug(`guard: role "${user.role}" found`); debug && console.log("guard: role found", [user.role]);
return role; return role;
} }
} }
$console.debug("guard: role not found", { debug &&
user, console.log("guard: role not found", {
}); user: user,
role: user?.role,
});
return this.getDefaultRole(); return this.getDefaultRole();
} }
@@ -120,14 +120,11 @@ export class Guard {
hasPermission(name: string, user?: GuardUserContext): boolean; hasPermission(name: string, user?: GuardUserContext): boolean;
hasPermission(permissionOrName: Permission | string, user?: GuardUserContext): boolean { hasPermission(permissionOrName: Permission | string, user?: GuardUserContext): boolean {
if (!this.isEnabled()) { if (!this.isEnabled()) {
//console.log("guard not enabled, allowing");
return true; return true;
} }
const name = typeof permissionOrName === "string" ? permissionOrName : permissionOrName.name; const name = typeof permissionOrName === "string" ? permissionOrName : permissionOrName.name;
$console.debug("guard: checking permission", {
name,
user: { id: user?.id, role: user?.role },
});
const exists = this.permissionExists(name); const exists = this.permissionExists(name);
if (!exists) { if (!exists) {
throw new Error(`Permission ${name} does not exist`); throw new Error(`Permission ${name} does not exist`);
@@ -136,10 +133,10 @@ export class Guard {
const role = this.getUserRole(user); const role = this.getUserRole(user);
if (!role) { if (!role) {
$console.debug("guard: user has no role, denying"); debug && console.log("guard: role not found, denying");
return false; return false;
} else if (role.implicit_allow === true) { } else if (role.implicit_allow === true) {
$console.debug(`guard: role "${role.name}" has implicit allow, allowing`); debug && console.log("guard: role implicit allow, allowing");
return true; return true;
} }
@@ -147,11 +144,12 @@ export class Guard {
(rolePermission) => rolePermission.permission.name === name, (rolePermission) => rolePermission.permission.name === name,
); );
$console.debug("guard: rolePermission, allowing?", { debug &&
permission: name, console.log("guard: rolePermission, allowing?", {
role: role.name, permission: name,
allowing: !!rolePermission, role: role.name,
}); allowing: !!rolePermission,
});
return !!rolePermission; return !!rolePermission;
} }
+7 -45
View File
@@ -1,66 +1,28 @@
import { Exception, isDebug } from "core"; import { Exception } from "core";
import { HttpStatus } from "core/utils";
export class AuthException extends Exception { export class UserExistsException extends Exception {
getSafeErrorAndCode() {
return {
error: "Invalid credentials",
code: HttpStatus.UNAUTHORIZED,
};
}
override toJSON(): any {
if (isDebug()) {
return super.toJSON();
}
return {
error: this.getSafeErrorAndCode().error,
type: "AuthException",
};
}
}
export class UserExistsException extends AuthException {
override name = "UserExistsException"; override name = "UserExistsException";
override code = HttpStatus.UNPROCESSABLE_ENTITY; override code = 422;
constructor() { constructor() {
super("User already exists"); super("User already exists");
} }
} }
export class UserNotFoundException extends AuthException { export class UserNotFoundException extends Exception {
override name = "UserNotFoundException"; override name = "UserNotFoundException";
override code = HttpStatus.NOT_FOUND; override code = 404;
constructor() { constructor() {
super("User not found"); super("User not found");
} }
} }
export class InvalidCredentialsException extends AuthException { export class InvalidCredentialsException extends Exception {
override name = "InvalidCredentialsException"; override name = "InvalidCredentialsException";
override code = HttpStatus.UNAUTHORIZED; override code = 401;
constructor() { constructor() {
super("Invalid credentials"); super("Invalid credentials");
} }
} }
export class UnableToCreateUserException extends AuthException {
override name = "UnableToCreateUserException";
override code = HttpStatus.INTERNAL_SERVER_ERROR;
constructor() {
super("Unable to create user");
}
}
export class InvalidConditionsException extends AuthException {
override code = HttpStatus.UNPROCESSABLE_ENTITY;
constructor(message: string) {
super(message ?? "Invalid conditions");
}
}
+1
View File
@@ -1,4 +1,5 @@
export { UserExistsException, UserNotFoundException, InvalidCredentialsException } from "./errors"; export { UserExistsException, UserNotFoundException, InvalidCredentialsException } from "./errors";
export { sha256 } from "./utils/hash";
export { export {
type ProfileExchange, type ProfileExchange,
type Strategy, type Strategy,
+13
View File
@@ -0,0 +1,13 @@
// @deprecated: moved to @bknd/core
export async function sha256(password: string, salt?: string) {
// 1. Convert password to Uint8Array
const encoder = new TextEncoder();
const data = encoder.encode((salt ?? "") + password);
// 2. Hash the data using SHA-256
const hashBuffer = await crypto.subtle.digest("SHA-256", data);
// 3. Convert hash to hex string for easier display
const hashArray = Array.from(new Uint8Array(hashBuffer));
return hashArray.map((byte) => byte.toString(16).padStart(2, "0")).join("");
}
-2
View File
@@ -8,8 +8,6 @@ export const config: CliCommand = (program) => {
.option("--pretty", "pretty print") .option("--pretty", "pretty print")
.action((options) => { .action((options) => {
const config = getDefaultConfig(); const config = getDefaultConfig();
// biome-ignore lint/suspicious/noConsoleLog:
console.log(options.pretty ? JSON.stringify(config, null, 2) : JSON.stringify(config)); console.log(options.pretty ? JSON.stringify(config, null, 2) : JSON.stringify(config));
}); });
}; };
-1
View File
@@ -32,6 +32,5 @@ async function action(options: { out?: string; clean?: boolean }) {
// delete ".vite" directory in out // delete ".vite" directory in out
await fs.rm(path.resolve(out, ".vite"), { recursive: true }); await fs.rm(path.resolve(out, ".vite"), { recursive: true });
// biome-ignore lint/suspicious/noConsoleLog:
console.log(c.green(`Assets copied to: ${c.bold(out)}`)); console.log(c.green(`Assets copied to: ${c.bold(out)}`));
} }
+10 -21
View File
@@ -43,12 +43,10 @@ export const create: CliCommand = (program) => {
function errorOutro() { function errorOutro() {
$p.outro(color.red("Failed to create project.")); $p.outro(color.red("Failed to create project."));
// biome-ignore lint/suspicious/noConsoleLog:
console.log( console.log(
color.yellow("Sorry that this happened. If you think this is a bug, please report it at: ") + color.yellow("Sorry that this happened. If you think this is a bug, please report it at: ") +
color.cyan("https://github.com/bknd-io/bknd/issues"), color.cyan("https://github.com/bknd-io/bknd/issues"),
); );
// biome-ignore lint/suspicious/noConsoleLog:
console.log(""); console.log("");
process.exit(1); process.exit(1);
} }
@@ -57,14 +55,7 @@ async function onExit() {
await flush(); await flush();
} }
async function action(options: { async function action(options: { template?: string; dir?: string; integration?: string, yes?: boolean, clean?: boolean }) {
template?: string;
dir?: string;
integration?: string;
yes?: boolean;
clean?: boolean;
}) {
// biome-ignore lint/suspicious/noConsoleLog:
console.log(""); console.log("");
const $t = createScoped("create"); const $t = createScoped("create");
$t.capture("start", { $t.capture("start", {
@@ -105,12 +96,10 @@ async function action(options: {
$t.properties.at = "dir"; $t.properties.at = "dir";
if (fs.existsSync(downloadOpts.dir)) { if (fs.existsSync(downloadOpts.dir)) {
const clean = const clean = options.clean ?? await $p.confirm({
options.clean ?? message: `Directory ${color.cyan(downloadOpts.dir)} exists. Clean it?`,
(await $p.confirm({ initialValue: false,
message: `Directory ${color.cyan(downloadOpts.dir)} exists. Clean it?`, });
initialValue: false,
}));
if ($p.isCancel(clean)) { if ($p.isCancel(clean)) {
await onExit(); await onExit();
process.exit(1); process.exit(1);
@@ -185,6 +174,8 @@ async function action(options: {
process.exit(1); process.exit(1);
} }
//console.log("integration", { type, integration });
const choices = templates.filter((t) => t.integration === integration); const choices = templates.filter((t) => t.integration === integration);
if (choices.length === 0) { if (choices.length === 0) {
await onExit(); await onExit();
@@ -270,11 +261,9 @@ async function action(options: {
$p.log.success(`Updated package name to ${color.cyan(ctx.name)}`); $p.log.success(`Updated package name to ${color.cyan(ctx.name)}`);
{ {
const install = const install = options.yes ?? await $p.confirm({
options.yes ?? message: "Install dependencies?",
(await $p.confirm({ });
message: "Install dependencies?",
}));
if ($p.isCancel(install)) { if ($p.isCancel(install)) {
await onExit(); await onExit();
@@ -29,15 +29,13 @@ export const cloudflare = {
{ dir: ctx.dir }, { dir: ctx.dir },
); );
const db = ctx.skip const db = ctx.skip ? "d1" : await $p.select({
? "d1" message: "What database do you want to use?",
: await $p.select({ options: [
message: "What database do you want to use?", { label: "Cloudflare D1", value: "d1" },
options: [ { label: "LibSQL", value: "libsql" },
{ label: "Cloudflare D1", value: "d1" }, ],
{ label: "LibSQL", value: "libsql" }, });
],
});
if ($p.isCancel(db)) { if ($p.isCancel(db)) {
process.exit(1); process.exit(1);
} }
@@ -66,19 +64,17 @@ export const cloudflare = {
async function createD1(ctx: TemplateSetupCtx) { async function createD1(ctx: TemplateSetupCtx) {
const default_db = "data"; const default_db = "data";
const name = ctx.skip const name = ctx.skip ? default_db : await $p.text({
? default_db message: "Enter database name",
: await $p.text({ initialValue: default_db,
message: "Enter database name", placeholder: default_db,
initialValue: default_db, validate: (v) => {
placeholder: default_db, if (!v) {
validate: (v) => { return "Invalid name";
if (!v) { }
return "Invalid name"; return;
} },
return; });
},
});
if ($p.isCancel(name)) { if ($p.isCancel(name)) {
process.exit(1); process.exit(1);
} }
@@ -157,16 +153,13 @@ async function createLibsql(ctx: TemplateSetupCtx) {
} }
async function createR2(ctx: TemplateSetupCtx) { async function createR2(ctx: TemplateSetupCtx) {
const create = ctx.skip const create = ctx.skip ?? await $p.confirm({
? false message: "Do you want to use a R2 bucket?",
: await $p.confirm({ initialValue: true,
message: "Do you want to use a R2 bucket?", });
initialValue: true,
});
if ($p.isCancel(create)) { if ($p.isCancel(create)) {
process.exit(1); process.exit(1);
} }
if (!create) { if (!create) {
await overrideJson( await overrideJson(
WRANGLER_FILE, WRANGLER_FILE,
@@ -180,19 +173,17 @@ async function createR2(ctx: TemplateSetupCtx) {
} }
const default_bucket = "bucket"; const default_bucket = "bucket";
const name = ctx.skip const name = ctx.skip ? default_bucket : await $p.text({
? default_bucket message: "Enter bucket name",
: await $p.text({ initialValue: default_bucket,
message: "Enter bucket name", placeholder: default_bucket,
initialValue: default_bucket, validate: (v) => {
placeholder: default_bucket, if (!v) {
validate: (v) => { return "Invalid name";
if (!v) { }
return "Invalid name"; return;
} },
return; });
},
});
if ($p.isCancel(name)) { if ($p.isCancel(name)) {
process.exit(1); process.exit(1);
} }
-2
View File
@@ -17,7 +17,6 @@ export const debug: CliCommand = (program) => {
const subjects = { const subjects = {
paths: async () => { paths: async () => {
// biome-ignore lint/suspicious/noConsoleLog:
console.log("[PATHS]", { console.log("[PATHS]", {
rootpath: getRootPath(), rootpath: getRootPath(),
distPath: getDistPath(), distPath: getDistPath(),
@@ -28,7 +27,6 @@ const subjects = {
}); });
}, },
routes: async () => { routes: async () => {
// biome-ignore lint/suspicious/noConsoleLog:
console.log("[APP ROUTES]"); console.log("[APP ROUTES]");
const credentials = getConnectionCredentialsFromEnv(); const credentials = getConnectionCredentialsFromEnv();
const app = createApp({ connection: credentials }); const app = createApp({ connection: credentials });
+4 -6
View File
@@ -1,10 +1,9 @@
import path from "node:path"; import path from "node:path";
import type { Config } from "@libsql/client/node"; import type { Config } from "@libsql/client/node";
import { $console, config } from "core"; import { config } from "core";
import type { MiddlewareHandler } from "hono"; import type { MiddlewareHandler } from "hono";
import open from "open"; import open from "open";
import { fileExists, getRelativeDistPath } from "../../utils/sys"; import { fileExists, getRelativeDistPath } from "../../utils/sys";
import type { App } from "App";
export const PLATFORMS = ["node", "bun"] as const; export const PLATFORMS = ["node", "bun"] as const;
export type Platform = (typeof PLATFORMS)[number]; export type Platform = (typeof PLATFORMS)[number];
@@ -33,11 +32,11 @@ export async function attachServeStatic(app: any, platform: Platform) {
export async function startServer( export async function startServer(
server: Platform, server: Platform,
app: App, app: any,
options: { port: number; open?: boolean }, options: { port: number; open?: boolean },
) { ) {
const port = options.port; const port = options.port;
$console.log(`Using ${server} serve`); console.log(`Using ${server} serve`);
switch (server) { switch (server) {
case "node": { case "node": {
@@ -59,8 +58,7 @@ export async function startServer(
} }
const url = `http://localhost:${port}`; const url = `http://localhost:${port}`;
$console.info("Server listening on", url); console.info("Server listening on", url);
if (options.open) { if (options.open) {
await open(url); await open(url);
} }
+9 -18
View File
@@ -17,13 +17,12 @@ import {
startServer, startServer,
} from "./platform"; } from "./platform";
import { makeConfig } from "adapter"; import { makeConfig } from "adapter";
import { isBun as $isBun } from "cli/utils/sys";
const env_files = [".env", ".dev.vars"]; const env_files = [".env", ".dev.vars"];
dotenv.config({ dotenv.config({
path: env_files.map((file) => path.resolve(process.cwd(), file)), path: env_files.map((file) => path.resolve(process.cwd(), file)),
}); });
const isBun = $isBun(); const isBun = typeof Bun !== "undefined";
export const run: CliCommand = (program) => { export const run: CliCommand = (program) => {
program program
@@ -77,12 +76,12 @@ async function makeApp(config: MakeAppConfig) {
app.emgr.onEvent( app.emgr.onEvent(
App.Events.AppBuiltEvent, App.Events.AppBuiltEvent,
async () => { async () => {
await attachServeStatic(app, config.server?.platform ?? "node");
app.registerAdminController();
if (config.onBuilt) { if (config.onBuilt) {
await config.onBuilt(app); await config.onBuilt(app);
} }
await attachServeStatic(app, config.server?.platform ?? "node");
app.registerAdminController();
}, },
"sync", "sync",
); );
@@ -92,14 +91,14 @@ async function makeApp(config: MakeAppConfig) {
} }
export async function makeConfigApp(_config: CliBkndConfig, platform?: Platform) { export async function makeConfigApp(_config: CliBkndConfig, platform?: Platform) {
const config = makeConfig(_config, process.env); const config = makeConfig(_config, { env: process.env });
return makeApp({ return makeApp({
...config, ...config,
server: { platform }, server: { platform },
}); });
} }
type RunOptions = { async function action(options: {
port: number; port: number;
memory?: boolean; memory?: boolean;
config?: string; config?: string;
@@ -107,9 +106,8 @@ type RunOptions = {
dbToken?: string; dbToken?: string;
server: Platform; server: Platform;
open?: boolean; open?: boolean;
}; }) {
colorizeConsole(console);
export async function makeAppFromEnv(options: Partial<RunOptions> = {}) {
const configFilePath = await getConfigPath(options.config); const configFilePath = await getConfigPath(options.config);
let app: App | undefined = undefined; let app: App | undefined = undefined;
@@ -149,19 +147,12 @@ export async function makeAppFromEnv(options: Partial<RunOptions> = {}) {
// if nothing helps, create a file based app // if nothing helps, create a file based app
if (!app) { if (!app) {
const connection = { url: "file:data.db" } as Config; const connection = { url: "file:data.db" } as Config;
console.info("Using fallback connection", c.cyan(connection.url)); console.info("Using connection", c.cyan(connection.url));
app = await makeApp({ app = await makeApp({
connection, connection,
server: { platform: options.server }, server: { platform: options.server },
}); });
} }
return app;
}
async function action(options: RunOptions) {
colorizeConsole(console);
const app = await makeAppFromEnv(options);
await startServer(options.server, app, { port: options.port, open: options.open }); await startServer(options.server, app, { port: options.port, open: options.open });
} }
-1
View File
@@ -8,7 +8,6 @@ export const schema: CliCommand = (program) => {
.option("--pretty", "pretty print") .option("--pretty", "pretty print")
.action((options) => { .action((options) => {
const schema = getDefaultSchema(); const schema = getDefaultSchema();
// biome-ignore lint/suspicious/noConsoleLog:
console.log(options.pretty ? JSON.stringify(schema, null, 2) : JSON.stringify(schema)); console.log(options.pretty ? JSON.stringify(schema, null, 2) : JSON.stringify(schema));
}); });
}; };
+36 -71
View File
@@ -1,32 +1,28 @@
import { import { password as $password, text as $text } from "@clack/prompts";
isCancel as $isCancel,
log as $log,
password as $password,
text as $text,
} from "@clack/prompts";
import type { App } from "App"; import type { App } from "App";
import type { PasswordStrategy } from "auth/authenticate/strategies"; import type { PasswordStrategy } from "auth/authenticate/strategies";
import { makeAppFromEnv } from "cli/commands/run"; import { makeConfigApp } from "cli/commands/run";
import type { CliCommand } from "cli/types"; import { getConfigPath } from "cli/commands/run/platform";
import type { CliBkndConfig, CliCommand } from "cli/types";
import { Argument } from "commander"; import { Argument } from "commander";
import { $console } from "core";
import c from "picocolors";
import { isBun } from "cli/utils/sys";
export const user: CliCommand = (program) => { export const user: CliCommand = (program) => {
program program
.command("user") .command("user")
.description("create/update users, or generate a token (auth)") .description("create and update user (auth)")
.addArgument( .addArgument(new Argument("<action>", "action to perform").choices(["create", "update"]))
new Argument("<action>", "action to perform").choices(["create", "update", "token"]),
)
.action(action); .action(action);
}; };
async function action(action: "create" | "update" | "token", options: any) { async function action(action: "create" | "update", options: any) {
const app = await makeAppFromEnv({ const configFilePath = await getConfigPath();
server: "node", if (!configFilePath) {
}); console.error("config file not found");
return;
}
const config = (await import(configFilePath).then((m) => m.default)) as CliBkndConfig;
const app = await makeConfigApp(config, options.server);
switch (action) { switch (action) {
case "create": case "create":
@@ -35,9 +31,6 @@ async function action(action: "create" | "update" | "token", options: any) {
case "update": case "update":
await update(app, options); await update(app, options);
break; break;
case "token":
await token(app, options);
break;
} }
} }
@@ -45,8 +38,7 @@ async function create(app: App, options: any) {
const strategy = app.module.auth.authenticator.strategy("password") as PasswordStrategy; const strategy = app.module.auth.authenticator.strategy("password") as PasswordStrategy;
if (!strategy) { if (!strategy) {
$log.error("Password strategy not configured"); throw new Error("Password strategy not configured");
process.exit(1);
} }
const email = await $text({ const email = await $text({
@@ -58,7 +50,6 @@ async function create(app: App, options: any) {
return; return;
}, },
}); });
if ($isCancel(email)) process.exit(1);
const password = await $password({ const password = await $password({
message: "Enter password", message: "Enter password",
@@ -69,17 +60,20 @@ async function create(app: App, options: any) {
return; return;
}, },
}); });
if ($isCancel(password)) process.exit(1);
if (typeof email !== "string" || typeof password !== "string") {
console.log("Cancelled");
process.exit(0);
}
try { try {
const created = await app.createUser({ const created = await app.createUser({
email, email,
password: await strategy.hash(password as string), password: await strategy.hash(password as string),
}); });
$log.success(`Created user: ${c.cyan(created.email)}`); console.log("Created:", created);
} catch (e) { } catch (e) {
$log.error("Error creating user"); console.error("Error", e);
$console.error(e);
} }
} }
@@ -98,14 +92,17 @@ async function update(app: App, options: any) {
return; return;
}, },
})) as string; })) as string;
if ($isCancel(email)) process.exit(1); if (typeof email !== "string") {
console.log("Cancelled");
process.exit(0);
}
const { data: user } = await em.repository(users_entity).findOne({ email }); const { data: user } = await em.repository(users_entity).findOne({ email });
if (!user) { if (!user) {
$log.error("User not found"); console.log("User not found");
process.exit(1); process.exit(0);
} }
$log.info(`User found: ${c.cyan(user.email)}`); console.log("User found:", user);
const password = await $password({ const password = await $password({
message: "New Password?", message: "New Password?",
@@ -116,7 +113,10 @@ async function update(app: App, options: any) {
return; return;
}, },
}); });
if ($isCancel(password)) process.exit(1); if (typeof password !== "string") {
console.log("Cancelled");
process.exit(0);
}
try { try {
function togglePw(visible: boolean) { function togglePw(visible: boolean) {
@@ -134,43 +134,8 @@ async function update(app: App, options: any) {
}); });
togglePw(false); togglePw(false);
$log.success(`Updated user: ${c.cyan(user.email)}`); console.log("Updated:", user);
} catch (e) { } catch (e) {
$log.error("Error updating user"); console.error("Error", e);
$console.error(e);
} }
} }
async function token(app: App, options: any) {
if (isBun()) {
$log.error("Please use node to generate tokens");
process.exit(1);
}
const config = app.module.auth.toJSON(true);
const users_entity = config.entity_name as "users";
const em = app.modules.ctx().em;
const email = (await $text({
message: "Which user? Enter email",
validate: (v) => {
if (!v.includes("@")) {
return "Invalid email";
}
return;
},
})) as string;
if ($isCancel(email)) process.exit(1);
const { data: user } = await em.repository(users_entity).findOne({ email });
if (!user) {
$log.error("User not found");
process.exit(1);
}
$log.info(`User found: ${c.cyan(user.email)}`);
// biome-ignore lint/suspicious/noConsoleLog:
console.log(
`\n${c.dim("Token:")}\n${c.yellow(await app.module.auth.authenticator.jwt(user))}\n`,
);
}
-8
View File
@@ -3,14 +3,6 @@ import { readFile } from "node:fs/promises";
import path from "node:path"; import path from "node:path";
import url from "node:url"; import url from "node:url";
export function isBun(): boolean {
try {
return typeof Bun !== "undefined";
} catch (e) {
return false;
}
}
export function getRootPath() { export function getRootPath() {
const _path = path.dirname(url.fileURLToPath(import.meta.url)); const _path = path.dirname(url.fileURLToPath(import.meta.url));
// because of "src", local needs one more level up // because of "src", local needs one more level up
+3
View File
@@ -29,6 +29,7 @@ export class AwsClient extends Aws4fetchClient {
} }
getUrl(path: string = "/", searchParamsObj: Record<string, any> = {}): string { getUrl(path: string = "/", searchParamsObj: Record<string, any> = {}): string {
//console.log("super:getUrl", path, searchParamsObj);
const url = new URL(path); const url = new URL(path);
const converted = this.convertParams(searchParamsObj); const converted = this.convertParams(searchParamsObj);
Object.entries(converted).forEach(([key, value]) => { Object.entries(converted).forEach(([key, value]) => {
@@ -75,6 +76,8 @@ export class AwsClient extends Aws4fetchClient {
} }
const raw = await response.text(); const raw = await response.text();
//console.log("raw", raw);
//console.log(JSON.stringify(xmlToObject(raw), null, 2));
return xmlToObject(raw) as T; return xmlToObject(raw) as T;
} }
+2 -5
View File
@@ -1,12 +1,9 @@
import type { ContentfulStatusCode } from "hono/utils/http-status";
import { HttpStatus } from "./utils/reqres";
export class Exception extends Error { export class Exception extends Error {
code: ContentfulStatusCode = HttpStatus.BAD_REQUEST; code = 400;
override name = "Exception"; override name = "Exception";
protected _context = undefined; protected _context = undefined;
constructor(message: string, code?: ContentfulStatusCode) { constructor(message: string, code?: number) {
super(message); super(message);
if (code) { if (code) {
this.code = code; this.code = code;
-4
View File
@@ -14,10 +14,6 @@ export abstract class Event<Params = any, Returning = void> {
params: Params; params: Params;
returned: boolean = false; returned: boolean = false;
/**
* Shallow validation of the event return
* It'll be deeply validated on the place where it is called
*/
validate(value: Returning): Event<Params, Returning> | void { validate(value: Returning): Event<Params, Returning> | void {
throw new EventReturnedWithoutValidation(this as any, value); throw new EventReturnedWithoutValidation(this as any, value);
} }
+8 -4
View File
@@ -1,6 +1,5 @@
import { type Event, type EventClass, InvalidEventReturn } from "./Event"; import { type Event, type EventClass, InvalidEventReturn } from "./Event";
import { EventListener, type ListenerHandler, type ListenerMode } from "./EventListener"; import { EventListener, type ListenerHandler, type ListenerMode } from "./EventListener";
import { $console } from "core";
export type RegisterListenerConfig = export type RegisterListenerConfig =
| ListenerMode | ListenerMode
@@ -84,6 +83,10 @@ export class EventManager<
} else { } else {
// @ts-expect-error // @ts-expect-error
slug = eventOrSlug.constructor?.slug ?? eventOrSlug.slug; slug = eventOrSlug.constructor?.slug ?? eventOrSlug.slug;
/*eventOrSlug instanceof Event
? // @ts-expect-error slug is static
eventOrSlug.constructor.slug
: eventOrSlug.slug;*/
} }
return !!this.events.find((e) => slug === e.slug); return !!this.events.find((e) => slug === e.slug);
@@ -125,7 +128,8 @@ export class EventManager<
if (listener.id) { if (listener.id) {
const existing = this.listeners.find((l) => l.id === listener.id); const existing = this.listeners.find((l) => l.id === listener.id);
if (existing) { if (existing) {
$console.debug(`Listener with id "${listener.id}" already exists.`); // @todo: add a verbose option?
//console.warn(`Listener with id "${listener.id}" already exists.`);
return this; return this;
} }
} }
@@ -187,7 +191,7 @@ export class EventManager<
// @ts-expect-error slug is static // @ts-expect-error slug is static
const slug = event.constructor.slug; const slug = event.constructor.slug;
if (!this.enabled) { if (!this.enabled) {
$console.debug("EventManager disabled, not emitting", slug); console.log("EventManager disabled, not emitting", slug);
return event; return event;
} }
@@ -236,7 +240,7 @@ export class EventManager<
} catch (e) { } catch (e) {
if (e instanceof InvalidEventReturn) { if (e instanceof InvalidEventReturn) {
this.options?.onInvalidReturn?.(_event, e); this.options?.onInvalidReturn?.(_event, e);
$console.warn(`Invalid return of event listener for "${slug}": ${e.message}`); console.warn(`Invalid return of event listener for "${slug}": ${e.message}`);
} else if (this.options?.onError) { } else if (this.options?.onError) {
this.options.onError(_event, e); this.options.onError(_event, e);
} else { } else {
-2
View File
@@ -25,10 +25,8 @@ export {
isBooleanLike, isBooleanLike,
} from "./object/query/query"; } from "./object/query/query";
export { Registry, type Constructor } from "./registry/Registry"; export { Registry, type Constructor } from "./registry/Registry";
export { getFlashMessage } from "./server/flash";
export * from "./console"; export * from "./console";
export * from "./events";
// compatibility // compatibility
export type Middleware = MiddlewareHandler<any, any, any>; export type Middleware = MiddlewareHandler<any, any, any>;
+13 -1
View File
@@ -73,7 +73,6 @@ export class SchemaObject<Schema extends TObject> {
forceParse: true, forceParse: true,
skipMark: this.isForceParse(), skipMark: this.isForceParse(),
}); });
// regardless of "noEmit" this should always be triggered // regardless of "noEmit" this should always be triggered
const updatedConfig = await this.onBeforeUpdate(this._config, valid); const updatedConfig = await this.onBeforeUpdate(this._config, valid);
@@ -123,15 +122,19 @@ export class SchemaObject<Schema extends TObject> {
const partial = path.length > 0 ? (set({}, path, value) as Partial<Static<Schema>>) : value; const partial = path.length > 0 ? (set({}, path, value) as Partial<Static<Schema>>) : value;
this.throwIfRestricted(partial); this.throwIfRestricted(partial);
//console.log(getFullPathKeys(value).map((k) => path + "." + k));
// overwrite arrays and primitives, only deep merge objects // overwrite arrays and primitives, only deep merge objects
// @ts-ignore // @ts-ignore
//console.log("---alt:new", _jsonp(mergeObject(current, partial)));
const config = mergeObjectWith(current, partial, (objValue, srcValue) => { const config = mergeObjectWith(current, partial, (objValue, srcValue) => {
if (Array.isArray(objValue) && Array.isArray(srcValue)) { if (Array.isArray(objValue) && Array.isArray(srcValue)) {
return srcValue; return srcValue;
} }
}); });
//console.log("---new", _jsonp(config));
//console.log("overwritePaths", this.options?.overwritePaths);
if (this.options?.overwritePaths) { if (this.options?.overwritePaths) {
const keys = getFullPathKeys(value).map((k) => { const keys = getFullPathKeys(value).map((k) => {
// only prepend path if given // only prepend path if given
@@ -146,6 +149,7 @@ export class SchemaObject<Schema extends TObject> {
} }
}); });
}); });
//console.log("overwritePaths", keys, overwritePaths);
if (overwritePaths.length > 0) { if (overwritePaths.length > 0) {
// filter out less specific paths (but only if more than 1) // filter out less specific paths (but only if more than 1)
@@ -153,10 +157,12 @@ export class SchemaObject<Schema extends TObject> {
overwritePaths.length > 1 overwritePaths.length > 1
? overwritePaths.filter((k) => ? overwritePaths.filter((k) =>
overwritePaths.some((k2) => { overwritePaths.some((k2) => {
//console.log("keep?", { k, k2 }, k2 !== k && k2.startsWith(k));
return k2 !== k && k2.startsWith(k); return k2 !== k && k2.startsWith(k);
}), }),
) )
: overwritePaths; : overwritePaths;
//console.log("specific", specific);
for (const p of specific) { for (const p of specific) {
set(config, p, get(partial, p)); set(config, p, get(partial, p));
@@ -164,6 +170,8 @@ export class SchemaObject<Schema extends TObject> {
} }
} }
//console.log("patch", _jsonp({ path, value, partial, config, current }));
const newConfig = await this.set(config); const newConfig = await this.set(config);
return [partial, newConfig]; return [partial, newConfig];
} }
@@ -173,11 +181,14 @@ export class SchemaObject<Schema extends TObject> {
const partial = path.length > 0 ? (set({}, path, value) as Partial<Static<Schema>>) : value; const partial = path.length > 0 ? (set({}, path, value) as Partial<Static<Schema>>) : value;
this.throwIfRestricted(partial); this.throwIfRestricted(partial);
//console.log(getFullPathKeys(value).map((k) => path + "." + k));
// overwrite arrays and primitives, only deep merge objects // overwrite arrays and primitives, only deep merge objects
// @ts-ignore // @ts-ignore
const config = set(current, path, value); const config = set(current, path, value);
//console.log("overwrite", { path, value, partial, config, current });
const newConfig = await this.set(config); const newConfig = await this.set(config);
return [partial, newConfig]; return [partial, newConfig];
} }
@@ -187,6 +198,7 @@ export class SchemaObject<Schema extends TObject> {
if (p.length > 1) { if (p.length > 1) {
const parent = p.slice(0, -1).join("."); const parent = p.slice(0, -1).join(".");
if (!has(this._config, parent)) { if (!has(this._config, parent)) {
//console.log("parent", parent, JSON.stringify(this._config, null, 2));
throw new Error(`Parent path "${parent}" does not exist`); throw new Error(`Parent path "${parent}" does not exist`);
} }
} }
+13 -14
View File
@@ -1,5 +1,4 @@
// biome-ignore lint/suspicious/noConstEnum: <explanation> enum Change {
export const enum DiffChange {
Add = "a", Add = "a",
Remove = "r", Remove = "r",
Edit = "e", Edit = "e",
@@ -8,8 +7,8 @@ export const enum DiffChange {
type Object = object; type Object = object;
type Primitive = string | number | boolean | null | object | any[] | undefined; type Primitive = string | number | boolean | null | object | any[] | undefined;
export interface DiffEntry { interface DiffEntry {
t: DiffChange | string; t: Change | string;
p: (string | number)[]; p: (string | number)[];
o: Primitive; o: Primitive;
n: Primitive; n: Primitive;
@@ -48,7 +47,7 @@ function diff(oldObj: Object, newObj: Object): DiffEntry[] {
if (typeof oldValue !== typeof newValue) { if (typeof oldValue !== typeof newValue) {
diffs.push({ diffs.push({
t: DiffChange.Edit, t: Change.Edit,
p: path, p: path,
o: oldValue, o: oldValue,
n: newValue, n: newValue,
@@ -58,14 +57,14 @@ function diff(oldObj: Object, newObj: Object): DiffEntry[] {
for (let i = 0; i < maxLength; i++) { for (let i = 0; i < maxLength; i++) {
if (i >= oldValue.length) { if (i >= oldValue.length) {
diffs.push({ diffs.push({
t: DiffChange.Add, t: Change.Add,
p: [...path, i], p: [...path, i],
o: undefined, o: undefined,
n: newValue[i], n: newValue[i],
}); });
} else if (i >= newValue.length) { } else if (i >= newValue.length) {
diffs.push({ diffs.push({
t: DiffChange.Remove, t: Change.Remove,
p: [...path, i], p: [...path, i],
o: oldValue[i], o: oldValue[i],
n: undefined, n: undefined,
@@ -81,14 +80,14 @@ function diff(oldObj: Object, newObj: Object): DiffEntry[] {
for (const key of allKeys) { for (const key of allKeys) {
if (!(key in oldValue)) { if (!(key in oldValue)) {
diffs.push({ diffs.push({
t: DiffChange.Add, t: Change.Add,
p: [...path, key], p: [...path, key],
o: undefined, o: undefined,
n: newValue[key], n: newValue[key],
}); });
} else if (!(key in newValue)) { } else if (!(key in newValue)) {
diffs.push({ diffs.push({
t: DiffChange.Remove, t: Change.Remove,
p: [...path, key], p: [...path, key],
o: oldValue[key], o: oldValue[key],
n: undefined, n: undefined,
@@ -99,7 +98,7 @@ function diff(oldObj: Object, newObj: Object): DiffEntry[] {
} }
} else { } else {
diffs.push({ diffs.push({
t: DiffChange.Edit, t: Change.Edit,
p: path, p: path,
o: oldValue, o: oldValue,
n: newValue, n: newValue,
@@ -137,9 +136,9 @@ function applyChange(obj: Object, diff: DiffEntry) {
const parent = getParent(obj, path.slice(0, -1)); const parent = getParent(obj, path.slice(0, -1));
const key = path[path.length - 1]!; const key = path[path.length - 1]!;
if (type === DiffChange.Add || type === DiffChange.Edit) { if (type === Change.Add || type === Change.Edit) {
parent[key] = newValue; parent[key] = newValue;
} else if (type === DiffChange.Remove) { } else if (type === Change.Remove) {
if (Array.isArray(parent)) { if (Array.isArray(parent)) {
parent.splice(key as number, 1); parent.splice(key as number, 1);
} else { } else {
@@ -153,13 +152,13 @@ function revertChange(obj: Object, diff: DiffEntry) {
const parent = getParent(obj, path.slice(0, -1)); const parent = getParent(obj, path.slice(0, -1));
const key = path[path.length - 1]!; const key = path[path.length - 1]!;
if (type === DiffChange.Add) { if (type === Change.Add) {
if (Array.isArray(parent)) { if (Array.isArray(parent)) {
parent.splice(key as number, 1); parent.splice(key as number, 1);
} else { } else {
delete parent[key]; delete parent[key];
} }
} else if (type === DiffChange.Remove || type === DiffChange.Edit) { } else if (type === Change.Remove || type === Change.Edit) {
parent[key] = oldValue; parent[key] = oldValue;
} }
} }
@@ -1,70 +0,0 @@
import { describe, expect, test } from "bun:test";
import { SimpleRenderer } from "core";
describe(SimpleRenderer, () => {
const renderer = new SimpleRenderer(
{
name: "World",
views: 123,
nested: {
foo: "bar",
baz: ["quz", "foo"],
},
someArray: [1, 2, 3],
enabled: true,
},
{
renderKeys: true,
},
);
test("strings", async () => {
const tests = [
["Hello {{ name }}, count: {{views}}", "Hello World, count: 123"],
["Nested: {{nested.foo}}", "Nested: bar"],
["Nested: {{nested.baz[0]}}", "Nested: quz"],
] as const;
for (const [template, expected] of tests) {
expect(await renderer.renderString(template)).toEqual(expected);
}
});
test("arrays", async () => {
const tests = [
[
["{{someArray[0]}}", "{{someArray[1]}}", "{{someArray[2]}}"],
["1", "2", "3"],
],
] as const;
for (const [template, expected] of tests) {
const result = await renderer.render(template);
expect(result).toEqual(expected as any);
}
});
test("objects", async () => {
const tests = [
[
{
foo: "{{name}}",
bar: "{{views}}",
baz: "{{nested.foo}}",
quz: "{{nested.baz[0]}}",
},
{
foo: "World",
bar: "123",
baz: "bar",
quz: "quz",
},
],
] as const;
for (const [template, expected] of tests) {
const result = await renderer.render(template);
expect(result).toEqual(expected as any);
}
});
});
+42 -17
View File
@@ -1,13 +1,17 @@
import { get } from "lodash-es"; import { Liquid, LiquidError } from "liquidjs";
import type { RenderOptions } from "liquidjs/dist/liquid-options";
import { BkndError } from "../errors";
export type TemplateObject = Record<string, string | Record<string, string>>; export type TemplateObject = Record<string, string | Record<string, string>>;
export type TemplateTypes = string | TemplateObject | any; export type TemplateTypes = string | TemplateObject;
export type SimpleRendererOptions = { export type SimpleRendererOptions = RenderOptions & {
renderKeys?: boolean; renderKeys?: boolean;
}; };
export class SimpleRenderer { export class SimpleRenderer {
private engine = new Liquid();
constructor( constructor(
private variables: Record<string, any> = {}, private variables: Record<string, any> = {},
private options: SimpleRendererOptions = {}, private options: SimpleRendererOptions = {},
@@ -18,6 +22,7 @@ export class SimpleRenderer {
} }
static hasMarkup(template: string | object): boolean { static hasMarkup(template: string | object): boolean {
//console.log("has markup?", template);
let flat: string = ""; let flat: string = "";
if (Array.isArray(template) || typeof template === "object") { if (Array.isArray(template) || typeof template === "object") {
@@ -29,29 +34,49 @@ export class SimpleRenderer {
flat = String(template); flat = String(template);
} }
const checks = ["{{"]; //console.log("** flat", flat);
return checks.some((check) => flat.includes(check));
const checks = ["{{", "{%", "{#", "{:"];
const hasMarkup = checks.some((check) => flat.includes(check));
//console.log("--has markup?", hasMarkup);
return hasMarkup;
} }
async render<Given extends TemplateTypes = TemplateTypes>(template: Given): Promise<Given> { async render<Given extends TemplateTypes>(template: Given): Promise<Given> {
if (typeof template === "undefined" || template === null) return template; try {
if (typeof template === "string") {
return (await this.renderString(template)) as unknown as Given;
} else if (Array.isArray(template)) {
return (await Promise.all(
template.map((item) => this.render(item)),
)) as unknown as Given;
} else if (typeof template === "object") {
return (await this.renderObject(template)) as unknown as Given;
}
} catch (e) {
if (e instanceof LiquidError) {
const details = {
name: e.name,
token: {
kind: e.token.kind,
input: e.token.input,
begin: e.token.begin,
end: e.token.end,
},
};
if (typeof template === "string") { throw new BkndError(e.message, details, "liquid");
return (await this.renderString(template)) as unknown as Given; }
} else if (Array.isArray(template)) {
return (await Promise.all(template.map((item) => this.render(item)))) as unknown as Given; throw e;
} else if (typeof template === "object") {
return (await this.renderObject(template as any)) as unknown as Given;
} }
throw new Error("Invalid template type"); throw new Error("Invalid template type");
} }
async renderString(template: string): Promise<string> { async renderString(template: string): Promise<string> {
return template.replace(/{{\s*([^{}]+?)\s*}}/g, (_, expr: string) => { //console.log("*** renderString", template, this.variables);
const value = get(this.variables, expr.trim()); return this.engine.parseAndRender(template, this.variables, this.options);
return value == null ? "" : String(value);
});
} }
async renderObject(template: TemplateObject): Promise<TemplateObject> { async renderObject(template: TemplateObject): Promise<TemplateObject> {
+2 -2
View File
@@ -9,11 +9,13 @@ export class DebugLogger {
} }
context(context: string) { context(context: string) {
//console.log("[ settings context ]", context, this._context);
this._context.push(context); this._context.push(context);
return this; return this;
} }
clear() { clear() {
//console.log("[ clear context ]", this._context.pop(), this._context);
this._context.pop(); this._context.pop();
return this; return this;
} }
@@ -31,8 +33,6 @@ export class DebugLogger {
const indents = " ".repeat(Math.max(this._context.length - 1, 0)); const indents = " ".repeat(Math.max(this._context.length - 1, 0));
const context = const context =
this._context.length > 0 ? `[${this._context[this._context.length - 1]}]` : ""; this._context.length > 0 ? `[${this._context[this._context.length - 1]}]` : "";
// biome-ignore lint/suspicious/noConsoleLog: <explanation>
console.log(indents, context, time, ...args); console.log(indents, context, time, ...args);
this.last = now; this.last = now;
+1
View File
@@ -4,6 +4,7 @@ import weekOfYear from "dayjs/plugin/weekOfYear.js";
declare module "dayjs" { declare module "dayjs" {
interface Dayjs { interface Dayjs {
week(): number; week(): number;
week(value: number): dayjs.Dayjs; week(value: number): dayjs.Dayjs;
} }
} }
+2 -3
View File
@@ -2,7 +2,6 @@ import { extension, guess, isMimeType } from "media/storage/mime-types-tiny";
import { randomString } from "core/utils/strings"; import { randomString } from "core/utils/strings";
import type { Context } from "hono"; import type { Context } from "hono";
import { invariant } from "core/utils/runtime"; import { invariant } from "core/utils/runtime";
import { $console } from "../console";
export function getContentName(request: Request): string | undefined; export function getContentName(request: Request): string | undefined;
export function getContentName(contentDisposition: string): string | undefined; export function getContentName(contentDisposition: string): string | undefined;
@@ -131,7 +130,7 @@ export async function getFileFromContext(c: Context<any>): Promise<File> {
return await blobToFile(v); return await blobToFile(v);
} }
} catch (e) { } catch (e) {
$console.warn("Error parsing form data", e); console.warn("Error parsing form data", e);
} }
} else { } else {
try { try {
@@ -142,7 +141,7 @@ export async function getFileFromContext(c: Context<any>): Promise<File> {
return await blobToFile(blob, { name: getContentName(c.req.raw), type: contentType }); return await blobToFile(blob, { name: getContentName(c.req.raw), type: contentType });
} }
} catch (e) { } catch (e) {
$console.warn("Error parsing blob", e); console.warn("Error parsing blob", e);
} }
} }
+8 -14
View File
@@ -1,3 +1,7 @@
import { randomString } from "core/utils/strings";
import type { Context } from "hono";
import { extension, guess, isMimeType } from "media/storage/mime-types-tiny";
export function headersToObject(headers: Headers): Record<string, string> { export function headersToObject(headers: Headers): Record<string, string> {
if (!headers) return {}; if (!headers) return {};
return { ...Object.fromEntries(headers.entries()) }; return { ...Object.fromEntries(headers.entries()) };
@@ -98,7 +102,7 @@ export function decodeSearch(str) {
export const enum HttpStatus { export const enum HttpStatus {
// Informational responses (100199) // Informational responses (100199)
CONTINUE = 100, CONTINUE = 100,
//SWITCHING_PROTOCOLS = 101, SWITCHING_PROTOCOLS = 101,
PROCESSING = 102, PROCESSING = 102,
EARLY_HINTS = 103, EARLY_HINTS = 103,
@@ -107,8 +111,8 @@ export const enum HttpStatus {
CREATED = 201, CREATED = 201,
ACCEPTED = 202, ACCEPTED = 202,
NON_AUTHORITATIVE_INFORMATION = 203, NON_AUTHORITATIVE_INFORMATION = 203,
//NO_CONTENT = 204, NO_CONTENT = 204,
//RESET_CONTENT = 205, RESET_CONTENT = 205,
PARTIAL_CONTENT = 206, PARTIAL_CONTENT = 206,
MULTI_STATUS = 207, MULTI_STATUS = 207,
ALREADY_REPORTED = 208, ALREADY_REPORTED = 208,
@@ -119,7 +123,7 @@ export const enum HttpStatus {
MOVED_PERMANENTLY = 301, MOVED_PERMANENTLY = 301,
FOUND = 302, FOUND = 302,
SEE_OTHER = 303, SEE_OTHER = 303,
//NOT_MODIFIED = 304, NOT_MODIFIED = 304,
USE_PROXY = 305, USE_PROXY = 305,
TEMPORARY_REDIRECT = 307, TEMPORARY_REDIRECT = 307,
PERMANENT_REDIRECT = 308, PERMANENT_REDIRECT = 308,
@@ -168,13 +172,3 @@ export const enum HttpStatus {
NOT_EXTENDED = 510, NOT_EXTENDED = 510,
NETWORK_AUTHENTICATION_REQUIRED = 511, NETWORK_AUTHENTICATION_REQUIRED = 511,
} }
// biome-ignore lint/suspicious/noConstEnum: <explanation>
export const enum HttpStatusEmpty {
// Informational responses (100199)
SWITCHING_PROTOCOLS = 101,
// Successful responses (200299)
NO_CONTENT = 204,
RESET_CONTENT = 205,
// Redirection messages (300399)
NOT_MODIFIED = 304,
}
-5
View File
@@ -132,8 +132,3 @@ export function slugify(str: string): string {
.replace(/-+/g, "-") // remove consecutive hyphens .replace(/-+/g, "-") // remove consecutive hyphens
); );
} }
export function truncate(str: string, length = 50, end = "..."): string {
if (str.length <= length) return str;
return str.substring(0, length) + end;
}
+56 -51
View File
@@ -1,11 +1,18 @@
import * as tb from "@sinclair/typebox"; import {
import type { Kind,
type ObjectOptions,
type SchemaOptions,
type Static,
type StaticDecode,
type StringOptions,
type TLiteral,
type TLiteralValue,
type TObject,
type TRecord,
type TSchema,
type TString,
Type,
TypeRegistry, TypeRegistry,
Static,
StaticDecode,
TSchema,
SchemaOptions,
TObject,
} from "@sinclair/typebox"; } from "@sinclair/typebox";
import { import {
DefaultErrorFunction, DefaultErrorFunction,
@@ -36,7 +43,7 @@ const validationSymbol = Symbol("tb-parse-validation");
export class TypeInvalidError extends Error { export class TypeInvalidError extends Error {
errors: ValueError[]; errors: ValueError[];
constructor( constructor(
public schema: tb.TSchema, public schema: TSchema,
public data: unknown, public data: unknown,
message?: string, message?: string,
) { ) {
@@ -85,28 +92,29 @@ export function mark(obj: any, validated = true) {
} }
} }
export function parse<Schema extends tb.TSchema = tb.TSchema>( export function parse<Schema extends TSchema = TSchema>(
schema: Schema, schema: Schema,
data: RecursivePartial<tb.Static<Schema>>, data: RecursivePartial<Static<Schema>>,
options?: ParseOptions, options?: ParseOptions,
): tb.Static<Schema> { ): Static<Schema> {
if (!options?.forceParse && typeof data === "object" && validationSymbol in data) { if (!options?.forceParse && typeof data === "object" && validationSymbol in data) {
if (options?.useDefaults === false) { if (options?.useDefaults === false) {
return data as tb.Static<typeof schema>; return data as Static<typeof schema>;
} }
// this is important as defaults are expected // this is important as defaults are expected
return Default(schema, data as any) as tb.Static<Schema>; return Default(schema, data as any) as Static<Schema>;
} }
const parsed = options?.useDefaults === false ? data : Default(schema, data); const parsed = options?.useDefaults === false ? data : Default(schema, data);
if (Check(schema, parsed)) { if (Check(schema, parsed)) {
options?.skipMark !== true && mark(parsed, true); options?.skipMark !== true && mark(parsed, true);
return parsed as tb.Static<typeof schema>; return parsed as Static<typeof schema>;
} else if (options?.onError) { } else if (options?.onError) {
options.onError(Errors(schema, data)); options.onError(Errors(schema, data));
} else { } else {
//console.warn("errors", JSON.stringify([...Errors(schema, data)], null, 2));
throw new TypeInvalidError(schema, data); throw new TypeInvalidError(schema, data);
} }
@@ -114,24 +122,26 @@ export function parse<Schema extends tb.TSchema = tb.TSchema>(
return undefined as any; return undefined as any;
} }
export function parseDecode<Schema extends tb.TSchema = tb.TSchema>( export function parseDecode<Schema extends TSchema = TSchema>(
schema: Schema, schema: Schema,
data: RecursivePartial<tb.StaticDecode<Schema>>, data: RecursivePartial<StaticDecode<Schema>>,
): tb.StaticDecode<Schema> { ): StaticDecode<Schema> {
//console.log("parseDecode", schema, data);
const parsed = Default(schema, data); const parsed = Default(schema, data);
if (Check(schema, parsed)) { if (Check(schema, parsed)) {
return parsed as tb.StaticDecode<typeof schema>; return parsed as StaticDecode<typeof schema>;
} }
//console.log("errors", ...Errors(schema, data));
throw new TypeInvalidError(schema, data); throw new TypeInvalidError(schema, data);
} }
export function strictParse<Schema extends tb.TSchema = tb.TSchema>( export function strictParse<Schema extends TSchema = TSchema>(
schema: Schema, schema: Schema,
data: tb.Static<Schema>, data: Static<Schema>,
options?: ParseOptions, options?: ParseOptions,
): tb.Static<Schema> { ): Static<Schema> {
return parse(schema, data as any, options); return parse(schema, data as any, options);
} }
@@ -140,14 +150,11 @@ export function registerCustomTypeboxKinds(registry: typeof TypeRegistry) {
return typeof value === "string" && schema.enum.includes(value); return typeof value === "string" && schema.enum.includes(value);
}); });
} }
registerCustomTypeboxKinds(tb.TypeRegistry); registerCustomTypeboxKinds(TypeRegistry);
export const StringEnum = <const T extends readonly string[]>( export const StringEnum = <const T extends readonly string[]>(values: T, options?: StringOptions) =>
values: T, Type.Unsafe<T[number]>({
options?: tb.StringOptions, [Kind]: "StringEnum",
) =>
tb.Type.Unsafe<T[number]>({
[tb.Kind]: "StringEnum",
type: "string", type: "string",
enum: values, enum: values,
...options, ...options,
@@ -155,47 +162,45 @@ export const StringEnum = <const T extends readonly string[]>(
// key value record compatible with RJSF and typebox inference // key value record compatible with RJSF and typebox inference
// acting like a Record, but using an Object with additionalProperties // acting like a Record, but using an Object with additionalProperties
export const StringRecord = <T extends tb.TSchema>(properties: T, options?: tb.ObjectOptions) => export const StringRecord = <T extends TSchema>(properties: T, options?: ObjectOptions) =>
tb.Type.Object({}, { ...options, additionalProperties: properties }) as unknown as tb.TRecord< Type.Object({}, { ...options, additionalProperties: properties }) as unknown as TRecord<
tb.TString, TString,
typeof properties typeof properties
>; >;
// fixed value that only be what is given + prefilled // fixed value that only be what is given + prefilled
export const Const = <T extends tb.TLiteralValue = tb.TLiteralValue>( export const Const = <T extends TLiteralValue = TLiteralValue>(value: T, options?: SchemaOptions) =>
value: T, Type.Literal(value, { ...options, default: value, const: value, readOnly: true }) as TLiteral<T>;
options?: tb.SchemaOptions,
) =>
tb.Type.Literal(value, {
...options,
default: value,
const: value,
readOnly: true,
}) as tb.TLiteral<T>;
export const StringIdentifier = tb.Type.String({ export const StringIdentifier = Type.String({
pattern: "^[a-zA-Z_][a-zA-Z0-9_]*$", pattern: "^[a-zA-Z_][a-zA-Z0-9_]*$",
minLength: 2, minLength: 2,
maxLength: 150, maxLength: 150,
}); });
export const StrictObject = <T extends tb.TProperties>(
properties: T,
options?: tb.ObjectOptions,
): tb.TObject<T> => tb.Type.Object(properties, { ...options, additionalProperties: false });
SetErrorFunction((error) => { SetErrorFunction((error) => {
if (error?.schema?.errorMessage) { if (error?.schema?.errorMessage) {
return error.schema.errorMessage; return error.schema.errorMessage;
} }
if (error?.schema?.[tb.Kind] === "StringEnum") { if (error?.schema?.[Kind] === "StringEnum") {
return `Expected: ${error.schema.enum.map((e) => `"${e}"`).join(", ")}`; return `Expected: ${error.schema.enum.map((e) => `"${e}"`).join(", ")}`;
} }
return DefaultErrorFunction(error); return DefaultErrorFunction(error);
}); });
export type { Static, StaticDecode, TSchema, TObject, ValueError, SchemaOptions }; export {
Type,
export { Value, Default, Errors, Check }; type Static,
type StaticDecode,
type TSchema,
Kind,
type TObject,
type ValueError,
type SchemaOptions,
Value,
Default,
Errors,
Check,
};
-13
View File
@@ -61,19 +61,6 @@ export class AppData extends Module<typeof dataConfigSchema> {
this.setBuilt(); this.setBuilt();
} }
override async onBeforeUpdate(from: AppDataConfig, to: AppDataConfig): Promise<AppDataConfig> {
// this is not 100% yet, since it could be legit
const entities = {
from: Object.keys(from.entities ?? {}),
to: Object.keys(to.entities ?? {}),
};
if (entities.from.length - entities.to.length > 1) {
throw new Error("Cannot remove more than one entity at a time");
}
return to;
}
getSchema() { getSchema() {
return dataConfigSchema; return dataConfigSchema;
} }
+13 -4
View File
@@ -1,6 +1,5 @@
import { $console, isDebug, tbValidator as tb } from "core"; import { isDebug, tbValidator as tb } from "core";
import { StringEnum } from "core/utils"; import { StringEnum, Type } from "core/utils";
import * as tbbox from "@sinclair/typebox";
import { import {
DataPermissions, DataPermissions,
type EntityData, type EntityData,
@@ -15,7 +14,6 @@ import type { ModuleBuildContext } from "modules";
import { Controller } from "modules/Controller"; import { Controller } from "modules/Controller";
import * as SystemPermissions from "modules/permissions"; import * as SystemPermissions from "modules/permissions";
import type { AppDataConfig } from "../data-schema"; import type { AppDataConfig } from "../data-schema";
const { Type } = tbbox;
export class DataController extends Controller { export class DataController extends Controller {
constructor( constructor(
@@ -47,6 +45,7 @@ export class DataController extends Controller {
const template = { data: res.data, meta }; const template = { data: res.data, meta };
// @todo: this works but it breaks in FE (need to improve DataTable) // @todo: this works but it breaks in FE (need to improve DataTable)
//return objectCleanEmpty(template) as any;
// filter empty // filter empty
return Object.fromEntries( return Object.fromEntries(
Object.entries(template).filter(([_, v]) => typeof v !== "undefined" && v !== null), Object.entries(template).filter(([_, v]) => typeof v !== "undefined" && v !== null),
@@ -57,6 +56,7 @@ export class DataController extends Controller {
const template = { data: res.data }; const template = { data: res.data };
// filter empty // filter empty
//return objectCleanEmpty(template);
return Object.fromEntries(Object.entries(template).filter(([_, v]) => v !== undefined)); return Object.fromEntries(Object.entries(template).filter(([_, v]) => v !== undefined));
} }
@@ -72,6 +72,11 @@ export class DataController extends Controller {
const { permission, auth } = this.middlewares; const { permission, auth } = this.middlewares;
const hono = this.create().use(auth(), permission(SystemPermissions.accessApi)); const hono = this.create().use(auth(), permission(SystemPermissions.accessApi));
const definedEntities = this.em.entities.map((e) => e.name);
const tbNumber = Type.Transform(Type.String({ pattern: "^[1-9][0-9]{0,}$" }))
.Decode(Number.parseInt)
.Encode(String);
// @todo: sample implementation how to augment handler with additional info // @todo: sample implementation how to augment handler with additional info
function handler<HH extends Handler>(name: string, h: HH): any { function handler<HH extends Handler>(name: string, h: HH): any {
const func = h; const func = h;
@@ -136,8 +141,10 @@ export class DataController extends Controller {
}), }),
), ),
async (c) => { async (c) => {
//console.log("request", c.req.raw);
const { entity, context } = c.req.param(); const { entity, context } = c.req.param();
if (!this.entityExists(entity)) { if (!this.entityExists(entity)) {
console.warn("not found:", entity, definedEntities);
return this.notFound(c); return this.notFound(c);
} }
const _entity = this.em.entity(entity); const _entity = this.em.entity(entity);
@@ -247,6 +254,7 @@ export class DataController extends Controller {
async (c) => { async (c) => {
const { entity } = c.req.param(); const { entity } = c.req.param();
if (!this.entityExists(entity)) { if (!this.entityExists(entity)) {
console.warn("not found:", entity, definedEntities);
return this.notFound(c); return this.notFound(c);
} }
const options = c.req.valid("query") as RepoQuery; const options = c.req.valid("query") as RepoQuery;
@@ -320,6 +328,7 @@ export class DataController extends Controller {
return this.notFound(c); return this.notFound(c);
} }
const options = (await c.req.valid("json")) as RepoQuery; const options = (await c.req.valid("json")) as RepoQuery;
//console.log("options", options);
const result = await this.em.repository(entity).findMany(options); const result = await this.em.repository(entity).findMany(options);
return c.json(this.repoResult(result), { status: result.data ? 200 : 404 }); return c.json(this.repoResult(result), { status: result.data ? 200 : 404 });
@@ -38,7 +38,7 @@ export class LibsqlConnection extends SqliteConnection {
if (clientOrCredentials && "url" in clientOrCredentials) { if (clientOrCredentials && "url" in clientOrCredentials) {
let { url, authToken, protocol } = clientOrCredentials; let { url, authToken, protocol } = clientOrCredentials;
if (protocol && LIBSQL_PROTOCOLS.includes(protocol)) { if (protocol && LIBSQL_PROTOCOLS.includes(protocol)) {
$console.log("changing protocol to", protocol); console.log("changing protocol to", protocol);
const [, rest] = url.split("://"); const [, rest] = url.split("://");
url = `${protocol}://${rest}`; url = `${protocol}://${rest}`;
} }
+25 -26
View File
@@ -1,5 +1,4 @@
import { type Static, StringRecord, objectTransform } from "core/utils"; import { type Static, StringRecord, Type, objectTransform } from "core/utils";
import * as tb from "@sinclair/typebox";
import { import {
FieldClassMap, FieldClassMap,
RelationClassMap, RelationClassMap,
@@ -19,37 +18,36 @@ export type FieldType = keyof typeof FIELDS;
export const RELATIONS = RelationClassMap; export const RELATIONS = RelationClassMap;
export const fieldsSchemaObject = objectTransform(FIELDS, (field, name) => { export const fieldsSchemaObject = objectTransform(FIELDS, (field, name) => {
return tb.Type.Object( return Type.Object(
{ {
type: tb.Type.Const(name, { default: name, readOnly: true }), type: Type.Const(name, { default: name, readOnly: true }),
config: tb.Type.Optional(field.schema), config: Type.Optional(field.schema),
}, },
{ {
title: name, title: name,
}, },
); );
}); });
export const fieldsSchema = tb.Type.Union(Object.values(fieldsSchemaObject)); export const fieldsSchema = Type.Union(Object.values(fieldsSchemaObject));
export const entityFields = StringRecord(fieldsSchema); export const entityFields = StringRecord(fieldsSchema);
export type TAppDataField = Static<typeof fieldsSchema>; export type TAppDataField = Static<typeof fieldsSchema>;
export type TAppDataEntityFields = Static<typeof entityFields>; export type TAppDataEntityFields = Static<typeof entityFields>;
export const entitiesSchema = tb.Type.Object({ export const entitiesSchema = Type.Object({
type: tb.Type.Optional( //name: Type.String(),
tb.Type.String({ enum: entityTypes, default: "regular", readOnly: true }), type: Type.Optional(Type.String({ enum: entityTypes, default: "regular", readOnly: true })),
), config: Type.Optional(entityConfigSchema),
config: tb.Type.Optional(entityConfigSchema), fields: Type.Optional(entityFields),
fields: tb.Type.Optional(entityFields),
}); });
export type TAppDataEntity = Static<typeof entitiesSchema>; export type TAppDataEntity = Static<typeof entitiesSchema>;
export const relationsSchema = Object.entries(RelationClassMap).map(([name, relationClass]) => { export const relationsSchema = Object.entries(RelationClassMap).map(([name, relationClass]) => {
return tb.Type.Object( return Type.Object(
{ {
type: tb.Type.Const(name, { default: name, readOnly: true }), type: Type.Const(name, { default: name, readOnly: true }),
source: tb.Type.String(), source: Type.String(),
target: tb.Type.String(), target: Type.String(),
config: tb.Type.Optional(relationClass.schema), config: Type.Optional(relationClass.schema),
}, },
{ {
title: name, title: name,
@@ -58,23 +56,24 @@ export const relationsSchema = Object.entries(RelationClassMap).map(([name, rela
}); });
export type TAppDataRelation = Static<(typeof relationsSchema)[number]>; export type TAppDataRelation = Static<(typeof relationsSchema)[number]>;
export const indicesSchema = tb.Type.Object( export const indicesSchema = Type.Object(
{ {
entity: tb.Type.String(), entity: Type.String(),
fields: tb.Type.Array(tb.Type.String(), { minItems: 1 }), fields: Type.Array(Type.String(), { minItems: 1 }),
unique: tb.Type.Optional(tb.Type.Boolean({ default: false })), //name: Type.Optional(Type.String()),
unique: Type.Optional(Type.Boolean({ default: false })),
}, },
{ {
additionalProperties: false, additionalProperties: false,
}, },
); );
export const dataConfigSchema = tb.Type.Object( export const dataConfigSchema = Type.Object(
{ {
basepath: tb.Type.Optional(tb.Type.String({ default: "/api/data" })), basepath: Type.Optional(Type.String({ default: "/api/data" })),
entities: tb.Type.Optional(StringRecord(entitiesSchema, { default: {} })), entities: Type.Optional(StringRecord(entitiesSchema, { default: {} })),
relations: tb.Type.Optional(StringRecord(tb.Type.Union(relationsSchema), { default: {} })), relations: Type.Optional(StringRecord(Type.Union(relationsSchema), { default: {} })),
indices: tb.Type.Optional(StringRecord(indicesSchema, { default: {} })), indices: Type.Optional(StringRecord(indicesSchema, { default: {} })),
}, },
{ {
additionalProperties: false, additionalProperties: false,
+9 -13
View File
@@ -1,14 +1,13 @@
import { $console, config } from "core"; import { config } from "core";
import { import {
type Static, type Static,
StringEnum, StringEnum,
Type,
parse, parse,
snakeToPascalWithSpaces, snakeToPascalWithSpaces,
transformObject, transformObject,
} from "core/utils"; } from "core/utils";
import { type Field, PrimaryField, type TActionContext, type TRenderContext } from "../fields"; import { type Field, PrimaryField, type TActionContext, type TRenderContext } from "../fields";
import * as tbbox from "@sinclair/typebox";
const { Type } = tbbox;
// @todo: entity must be migrated to typebox // @todo: entity must be migrated to typebox
export const entityConfigSchema = Type.Object( export const entityConfigSchema = Type.Object(
@@ -184,9 +183,9 @@ export class Entity<
if (existing) { if (existing) {
// @todo: for now adding a graceful method // @todo: for now adding a graceful method
if (JSON.stringify(existing) === JSON.stringify(field)) { if (JSON.stringify(existing) === JSON.stringify(field)) {
$console.warn( /*console.warn(
`Field "${field.name}" already exists on entity "${this.name}", but it's the same, so skipping.`, `Field "${field.name}" already exists on entity "${this.name}", but it's the same, so skipping.`,
); );*/
return; return;
} }
@@ -232,14 +231,8 @@ export class Entity<
} }
for (const field of fields) { for (const field of fields) {
if (!field.isValid(data?.[field.name], context)) { if (!field.isValid(data[field.name], context)) {
$console.warn( console.log("Entity.isValidData:invalid", context, field.name, data[field.name]);
"invalid data given for",
this.name,
context,
field.name,
data[field.name],
);
if (options?.explain) { if (options?.explain) {
throw new Error(`Field "${field.name}" has invalid data: "${data[field.name]}"`); throw new Error(`Field "${field.name}" has invalid data: "${data[field.name]}"`);
} }
@@ -265,6 +258,7 @@ export class Entity<
const _fields = Object.fromEntries(fields.map((field) => [field.name, field])); const _fields = Object.fromEntries(fields.map((field) => [field.name, field]));
const schema = Type.Object( const schema = Type.Object(
transformObject(_fields, (field) => { transformObject(_fields, (field) => {
//const hidden = field.isHidden(options?.context);
const fillable = field.isFillable(options?.context); const fillable = field.isFillable(options?.context);
return { return {
title: field.config.label, title: field.config.label,
@@ -282,7 +276,9 @@ export class Entity<
toJSON() { toJSON() {
return { return {
//name: this.name,
type: this.type, type: this.type,
//fields: transformObject(this.fields, (field) => field.toJSON()),
fields: Object.fromEntries(this.fields.map((field) => [field.name, field.toJSON()])), fields: Object.fromEntries(this.fields.map((field) => [field.name, field.toJSON()])),
config: this.config, config: this.config,
}; };
+5 -4
View File
@@ -1,4 +1,4 @@
import { $console, type DB as DefaultDB } from "core"; import type { DB as DefaultDB } from "core";
import { EventManager } from "core/events"; import { EventManager } from "core/events";
import { sql } from "kysely"; import { sql } from "kysely";
import { Connection } from "../connection/Connection"; import { Connection } from "../connection/Connection";
@@ -55,6 +55,7 @@ export class EntityManager<TBD extends object = DefaultDB> {
this.connection = connection; this.connection = connection;
this.emgr = emgr ?? new EventManager(); this.emgr = emgr ?? new EventManager();
//console.log("registering events", EntityManager.Events);
this.emgr.registerEvents(EntityManager.Events); this.emgr.registerEvents(EntityManager.Events);
} }
@@ -89,9 +90,7 @@ export class EntityManager<TBD extends object = DefaultDB> {
if (existing) { if (existing) {
// @todo: for now adding a graceful method // @todo: for now adding a graceful method
if (JSON.stringify(existing) === JSON.stringify(entity)) { if (JSON.stringify(existing) === JSON.stringify(entity)) {
$console.warn( //console.warn(`Entity "${entity.name}" already exists, but it's the same, so skipping.`);
`Entity "${entity.name}" already exists, but it's the same, skipping adding it.`,
);
return; return;
} }
@@ -109,6 +108,7 @@ export class EntityManager<TBD extends object = DefaultDB> {
} }
this._entities[entityIndex] = entity; this._entities[entityIndex] = entity;
// caused issues because this.entity() was using a reference (for when initial config was given) // caused issues because this.entity() was using a reference (for when initial config was given)
} }
@@ -295,6 +295,7 @@ export class EntityManager<TBD extends object = DefaultDB> {
return { return {
entities: Object.fromEntries(this.entities.map((e) => [e.name, e.toJSON()])), entities: Object.fromEntries(this.entities.map((e) => [e.name, e.toJSON()])),
relations: Object.fromEntries(this.relations.all.map((r) => [r.getName(), r.toJSON()])), relations: Object.fromEntries(this.relations.all.map((r) => [r.getName(), r.toJSON()])),
//relations: this.relations.all.map((r) => r.toJSON()),
indices: Object.fromEntries(this.indices.map((i) => [i.name, i.toJSON()])), indices: Object.fromEntries(this.indices.map((i) => [i.name, i.toJSON()])),
}; };
} }
+3 -2
View File
@@ -1,4 +1,4 @@
import { $console, type DB as DefaultDB, type PrimaryFieldType } from "core"; import type { DB as DefaultDB, PrimaryFieldType } from "core";
import { type EmitsEvents, EventManager } from "core/events"; import { type EmitsEvents, EventManager } from "core/events";
import type { DeleteQueryBuilder, InsertQueryBuilder, UpdateQueryBuilder } from "kysely"; import type { DeleteQueryBuilder, InsertQueryBuilder, UpdateQueryBuilder } from "kysely";
import { type TActionContext, WhereBuilder } from ".."; import { type TActionContext, WhereBuilder } from "..";
@@ -72,6 +72,7 @@ export class Mutator<
// if relation field (include key and value in validatedData) // if relation field (include key and value in validatedData)
if (Array.isArray(result)) { if (Array.isArray(result)) {
//console.log("--- (instructions)", result);
const [relation_key, relation_value] = result; const [relation_key, relation_value] = result;
validatedData[relation_key] = relation_value; validatedData[relation_key] = relation_value;
} }
@@ -121,7 +122,7 @@ export class Mutator<
}; };
} catch (e) { } catch (e) {
// @todo: redact // @todo: redact
$console.error("[Error in query]", sql); console.log("[Error in query]", sql);
throw e; throw e;
} }
} }
+25 -29
View File
@@ -302,38 +302,24 @@ export class Repository<TBD extends object = DefaultDB, TB extends keyof TBD = a
} }
} }
private async triggerFindBefore(entity: Entity, options: RepoQuery): Promise<void> {
const event =
options.limit === 1
? Repository.Events.RepositoryFindOneBefore
: Repository.Events.RepositoryFindManyBefore;
await this.emgr.emit(new event({ entity, options }));
}
private async triggerFindAfter(
entity: Entity,
options: RepoQuery,
data: EntityData[],
): Promise<void> {
if (options.limit === 1) {
await this.emgr.emit(
new Repository.Events.RepositoryFindOneAfter({ entity, options, data: data[0]! }),
);
} else {
await this.emgr.emit(
new Repository.Events.RepositoryFindManyAfter({ entity, options, data }),
);
}
}
protected async single( protected async single(
qb: RepositoryQB, qb: RepositoryQB,
options: RepoQuery, options: RepoQuery,
): Promise<RepositoryResponse<EntityData>> { ): Promise<RepositoryResponse<EntityData>> {
await this.triggerFindBefore(this.entity, options); await this.emgr.emit(
new Repository.Events.RepositoryFindOneBefore({ entity: this.entity, options }),
);
const { data, ...response } = await this.performQuery(qb); const { data, ...response } = await this.performQuery(qb);
await this.triggerFindAfter(this.entity, options, data); await this.emgr.emit(
new Repository.Events.RepositoryFindOneAfter({
entity: this.entity,
options,
data: data[0]!,
}),
);
return { ...response, data: data[0]! }; return { ...response, data: data[0]! };
} }
@@ -434,16 +420,26 @@ export class Repository<TBD extends object = DefaultDB, TB extends keyof TBD = a
limit: 1, limit: 1,
}); });
return (await this.single(qb, options)) as any; return this.single(qb, options) as any;
} }
async findMany(_options?: Partial<RepoQuery>): Promise<RepositoryResponse<TBD[TB][]>> { async findMany(_options?: Partial<RepoQuery>): Promise<RepositoryResponse<TBD[TB][]>> {
const { qb, options } = this.buildQuery(_options); const { qb, options } = this.buildQuery(_options);
await this.triggerFindBefore(this.entity, options);
await this.emgr.emit(
new Repository.Events.RepositoryFindManyBefore({ entity: this.entity, options }),
);
const res = await this.performQuery(qb); const res = await this.performQuery(qb);
await this.triggerFindAfter(this.entity, options, res.data); await this.emgr.emit(
new Repository.Events.RepositoryFindManyAfter({
entity: this.entity,
options,
data: res.data,
}),
);
return res as any; return res as any;
} }
+8 -8
View File
@@ -1,26 +1,26 @@
import { Exception } from "core"; import { Exception } from "core";
import { HttpStatus, type TypeInvalidError } from "core/utils"; import type { TypeInvalidError } from "core/utils";
import type { Entity } from "./entities"; import type { Entity } from "./entities";
import type { Field } from "./fields"; import type { Field } from "./fields";
export class UnableToConnectException extends Exception { export class UnableToConnectException extends Exception {
override name = "UnableToConnectException"; override name = "UnableToConnectException";
override code = HttpStatus.INTERNAL_SERVER_ERROR; override code = 500;
} }
export class InvalidSearchParamsException extends Exception { export class InvalidSearchParamsException extends Exception {
override name = "InvalidSearchParamsException"; override name = "InvalidSearchParamsException";
override code = HttpStatus.UNPROCESSABLE_ENTITY; override code = 422;
} }
export class TransformRetrieveFailedException extends Exception { export class TransformRetrieveFailedException extends Exception {
override name = "TransformRetrieveFailedException"; override name = "TransformRetrieveFailedException";
override code = HttpStatus.UNPROCESSABLE_ENTITY; override code = 422;
} }
export class TransformPersistFailedException extends Exception { export class TransformPersistFailedException extends Exception {
override name = "TransformPersistFailedException"; override name = "TransformPersistFailedException";
override code = HttpStatus.UNPROCESSABLE_ENTITY; override code = 422;
static invalidType(property: string, expected: string, given: any) { static invalidType(property: string, expected: string, given: any) {
const givenValue = typeof given === "object" ? JSON.stringify(given) : given; const givenValue = typeof given === "object" ? JSON.stringify(given) : given;
@@ -37,7 +37,7 @@ export class TransformPersistFailedException extends Exception {
export class InvalidFieldConfigException extends Exception { export class InvalidFieldConfigException extends Exception {
override name = "InvalidFieldConfigException"; override name = "InvalidFieldConfigException";
override code = HttpStatus.BAD_REQUEST; override code = 400;
constructor( constructor(
field: Field<any, any, any>, field: Field<any, any, any>,
@@ -54,7 +54,7 @@ export class InvalidFieldConfigException extends Exception {
export class EntityNotDefinedException extends Exception { export class EntityNotDefinedException extends Exception {
override name = "EntityNotDefinedException"; override name = "EntityNotDefinedException";
override code = HttpStatus.BAD_REQUEST; override code = 400;
constructor(entity?: Entity | string) { constructor(entity?: Entity | string) {
if (!entity) { if (!entity) {
@@ -67,7 +67,7 @@ export class EntityNotDefinedException extends Exception {
export class EntityNotFoundException extends Exception { export class EntityNotFoundException extends Exception {
override name = "EntityNotFoundException"; override name = "EntityNotFoundException";
override code = HttpStatus.NOT_FOUND; override code = 404;
constructor(entity: Entity | string, id: any) { constructor(entity: Entity | string, id: any) {
super( super(
+3 -12
View File
@@ -1,4 +1,4 @@
import { $console, type PrimaryFieldType } from "core"; import type { PrimaryFieldType } from "core";
import { Event, InvalidEventReturn } from "core/events"; import { Event, InvalidEventReturn } from "core/events";
import type { Entity, EntityData } from "../entities"; import type { Entity, EntityData } from "../entities";
import type { RepoQuery } from "../server/data-query-impl"; import type { RepoQuery } from "../server/data-query-impl";
@@ -9,10 +9,6 @@ export class MutatorInsertBefore extends Event<{ entity: Entity; data: EntityDat
override validate(data: EntityData) { override validate(data: EntityData) {
const { entity } = this.params; const { entity } = this.params;
if (!entity.isValidData(data, "create")) { if (!entity.isValidData(data, "create")) {
$console.warn("MutatorInsertBefore.validate: invalid", {
entity: entity.name,
data,
});
throw new InvalidEventReturn("EntityData", "invalid"); throw new InvalidEventReturn("EntityData", "invalid");
} }
@@ -40,18 +36,13 @@ export class MutatorUpdateBefore extends Event<
static override slug = "mutator-update-before"; static override slug = "mutator-update-before";
override validate(data: EntityData) { override validate(data: EntityData) {
const { entity, entityId } = this.params; const { entity, ...rest } = this.params;
if (!entity.isValidData(data, "update")) { if (!entity.isValidData(data, "update")) {
$console.warn("MutatorUpdateBefore.validate: invalid", {
entity: entity.name,
entityId,
data,
});
throw new InvalidEventReturn("EntityData", "invalid"); throw new InvalidEventReturn("EntityData", "invalid");
} }
return this.clone({ return this.clone({
entityId, ...rest,
entity, entity,
data, data,
}); });
+2 -3
View File
@@ -1,9 +1,7 @@
import type { Static } from "core/utils"; import { type Static, Type } from "core/utils";
import type { EntityManager } from "data"; import type { EntityManager } from "data";
import { TransformPersistFailedException } from "../errors"; import { TransformPersistFailedException } from "../errors";
import { Field, type TActionContext, type TRenderContext, baseFieldConfigSchema } from "./Field"; import { Field, type TActionContext, type TRenderContext, baseFieldConfigSchema } from "./Field";
import * as tb from "@sinclair/typebox";
const { Type } = tb;
export const booleanFieldConfigSchema = Type.Composite([ export const booleanFieldConfigSchema = Type.Composite([
Type.Object({ Type.Object({
@@ -49,6 +47,7 @@ export class BooleanField<Required extends true | false = false> extends Field<
} }
override transformRetrieve(value: unknown): boolean | null { override transformRetrieve(value: unknown): boolean | null {
//console.log("Boolean:transformRetrieve:value", value);
if (typeof value === "undefined" || value === null) { if (typeof value === "undefined" || value === null) {
if (this.isRequired()) return false; if (this.isRequired()) return false;
if (this.hasDefault()) return this.getDefault(); if (this.hasDefault()) return this.getDefault();
+12 -6
View File
@@ -1,13 +1,11 @@
import { type Static, StringEnum, dayjs } from "core/utils"; import { type Static, StringEnum, Type, dayjs } from "core/utils";
import type { EntityManager } from "../entities"; import type { EntityManager } from "../entities";
import { Field, type TActionContext, type TRenderContext, baseFieldConfigSchema } from "./Field"; import { Field, type TActionContext, type TRenderContext, baseFieldConfigSchema } from "./Field";
import { $console } from "core";
import * as tbbox from "@sinclair/typebox";
const { Type } = tbbox;
export const dateFieldConfigSchema = Type.Composite( export const dateFieldConfigSchema = Type.Composite(
[ [
Type.Object({ Type.Object({
//default_value: Type.Optional(Type.Date()),
type: StringEnum(["date", "datetime", "week"] as const, { default: "date" }), type: StringEnum(["date", "datetime", "week"] as const, { default: "date" }),
timezone: Type.Optional(Type.String()), timezone: Type.Optional(Type.String()),
min_date: Type.Optional(Type.String()), min_date: Type.Optional(Type.String()),
@@ -53,11 +51,13 @@ export class DateField<Required extends true | false = false> extends Field<
} }
private parseDateFromString(value: string): Date { private parseDateFromString(value: string): Date {
//console.log("parseDateFromString", value);
if (this.config.type === "week" && value.includes("-W")) { if (this.config.type === "week" && value.includes("-W")) {
const [year, week] = value.split("-W").map((n) => Number.parseInt(n, 10)) as [ const [year, week] = value.split("-W").map((n) => Number.parseInt(n, 10)) as [
number, number,
number, number,
]; ];
//console.log({ year, week });
// @ts-ignore causes errors on build? // @ts-ignore causes errors on build?
return dayjs().year(year).week(week).toDate(); return dayjs().year(year).week(week).toDate();
} }
@@ -67,12 +67,15 @@ export class DateField<Required extends true | false = false> extends Field<
override getValue(value: string, context?: TRenderContext): string | undefined { override getValue(value: string, context?: TRenderContext): string | undefined {
if (value === null || !value) return; if (value === null || !value) return;
//console.log("getValue", { value, context });
const date = this.parseDateFromString(value); const date = this.parseDateFromString(value);
//console.log("getValue.date", date);
if (context === "submit") { if (context === "submit") {
try { try {
return date.toISOString(); return date.toISOString();
} catch (e) { } catch (e) {
//console.warn("DateField.getValue:value/submit", value, e);
return undefined; return undefined;
} }
} }
@@ -81,7 +84,7 @@ export class DateField<Required extends true | false = false> extends Field<
try { try {
return `${date.getFullYear()}-W${dayjs(date).week()}`; return `${date.getFullYear()}-W${dayjs(date).week()}`;
} catch (e) { } catch (e) {
$console.warn("DateField.getValue:week error", value, String(e)); console.warn("error - DateField.getValue:week", value, e);
return; return;
} }
} }
@@ -94,7 +97,8 @@ export class DateField<Required extends true | false = false> extends Field<
return this.formatDate(local); return this.formatDate(local);
} catch (e) { } catch (e) {
$console.warn("DateField.getValue error", this.config.type, value, String(e)); console.warn("DateField.getValue:value", value);
console.warn("DateField.getValue:e", e);
return; return;
} }
} }
@@ -113,6 +117,7 @@ export class DateField<Required extends true | false = false> extends Field<
} }
override transformRetrieve(_value: string): Date | null { override transformRetrieve(_value: string): Date | null {
//console.log("transformRetrieve DateField", _value);
const value = super.transformRetrieve(_value); const value = super.transformRetrieve(_value);
if (value === null) return null; if (value === null) return null;
@@ -131,6 +136,7 @@ export class DateField<Required extends true | false = false> extends Field<
const value = await super.transformPersist(_value, em, context); const value = await super.transformPersist(_value, em, context);
if (this.nullish(value)) return value; if (this.nullish(value)) return value;
//console.log("transformPersist DateField", value);
switch (this.config.type) { switch (this.config.type) {
case "date": case "date":
case "week": case "week":
+10 -4
View File
@@ -1,9 +1,7 @@
import { Const, type Static, StringEnum } from "core/utils"; import { Const, type Static, StringEnum, StringRecord, Type } from "core/utils";
import type { EntityManager } from "data"; import type { EntityManager } from "data";
import { TransformPersistFailedException } from "../errors"; import { TransformPersistFailedException } from "../errors";
import { baseFieldConfigSchema, Field, type TActionContext, type TRenderContext } from "./Field"; import { Field, type TActionContext, type TRenderContext, baseFieldConfigSchema } from "./Field";
import * as tbbox from "@sinclair/typebox";
const { Type } = tbbox;
export const enumFieldConfigSchema = Type.Composite( export const enumFieldConfigSchema = Type.Composite(
[ [
@@ -55,6 +53,10 @@ export class EnumField<Required extends true | false = false, TypeOverride = str
constructor(name: string, config: Partial<EnumFieldConfig>) { constructor(name: string, config: Partial<EnumFieldConfig>) {
super(name, config); super(name, config);
/*if (this.config.options.values.length === 0) {
throw new Error(`Enum field "${this.name}" requires at least one option`);
}*/
if (this.config.default_value && !this.isValidValue(this.config.default_value)) { if (this.config.default_value && !this.isValidValue(this.config.default_value)) {
throw new Error(`Default value "${this.config.default_value}" is not a valid option`); throw new Error(`Default value "${this.config.default_value}" is not a valid option`);
} }
@@ -67,6 +69,10 @@ export class EnumField<Required extends true | false = false, TypeOverride = str
getOptions(): { label: string; value: string }[] { getOptions(): { label: string; value: string }[] {
const options = this.config?.options ?? { type: "strings", values: [] }; const options = this.config?.options ?? { type: "strings", values: [] };
/*if (options.values?.length === 0) {
throw new Error(`Enum field "${this.name}" requires at least one option`);
}*/
if (options.type === "strings") { if (options.type === "strings") {
return options.values?.map((option) => ({ label: option, value: option })); return options.values?.map((option) => ({ label: option, value: option }));
} }
+3 -6
View File
@@ -4,14 +4,13 @@ import {
type Static, type Static,
StringEnum, StringEnum,
type TSchema, type TSchema,
Type,
TypeInvalidError, TypeInvalidError,
} from "core/utils"; } from "core/utils";
import type { HTMLInputTypeAttribute, InputHTMLAttributes } from "react"; import type { HTMLInputTypeAttribute, InputHTMLAttributes } from "react";
import type { EntityManager } from "../entities"; import type { EntityManager } from "../entities";
import { InvalidFieldConfigException, TransformPersistFailedException } from "../errors"; import { InvalidFieldConfigException, TransformPersistFailedException } from "../errors";
import type { FieldSpec } from "data/connection/Connection"; import type { FieldSpec } from "data/connection/Connection";
import * as tbbox from "@sinclair/typebox";
const { Type } = tbbox;
// @todo: contexts need to be reworked // @todo: contexts need to be reworked
// e.g. "table" is irrelevant, because if read is not given, it fails // e.g. "table" is irrelevant, because if read is not given, it fails
@@ -185,14 +184,12 @@ export abstract class Field<
}; };
} }
// @todo: add field level validation
isValid(value: any, context: TActionContext): boolean { isValid(value: any, context: TActionContext): boolean {
if (typeof value !== "undefined") { if (value) {
return this.isFillable(context); return this.isFillable(context);
} else if (context === "create") { } else {
return !this.isRequired(); return !this.isRequired();
} }
return true;
} }
/** /**
+2 -3
View File
@@ -1,9 +1,7 @@
import type { Static } from "core/utils"; import { type Static, Type } from "core/utils";
import type { EntityManager } from "data"; import type { EntityManager } from "data";
import { TransformPersistFailedException } from "../errors"; import { TransformPersistFailedException } from "../errors";
import { Field, type TActionContext, type TRenderContext, baseFieldConfigSchema } from "./Field"; import { Field, type TActionContext, type TRenderContext, baseFieldConfigSchema } from "./Field";
import * as tbbox from "@sinclair/typebox";
const { Type } = tbbox;
export const jsonFieldConfigSchema = Type.Composite([baseFieldConfigSchema, Type.Object({})]); export const jsonFieldConfigSchema = Type.Composite([baseFieldConfigSchema, Type.Object({})]);
@@ -84,6 +82,7 @@ export class JsonField<Required extends true | false = false, TypeOverride = obj
context: TActionContext, context: TActionContext,
): Promise<string | undefined> { ): Promise<string | undefined> {
const value = await super.transformPersist(_value, em, context); const value = await super.transformPersist(_value, em, context);
//console.log("value", value);
if (this.nullish(value)) return value; if (this.nullish(value)) return value;
if (!this.isSerializable(value)) { if (!this.isSerializable(value)) {
+12 -3
View File
@@ -1,10 +1,8 @@
import { type Schema as JsonSchema, Validator } from "@cfworker/json-schema"; import { type Schema as JsonSchema, Validator } from "@cfworker/json-schema";
import { Default, FromSchema, type Static } from "core/utils"; import { Default, FromSchema, type Static, Type } from "core/utils";
import type { EntityManager } from "data"; import type { EntityManager } from "data";
import { TransformPersistFailedException } from "../errors"; import { TransformPersistFailedException } from "../errors";
import { Field, type TActionContext, type TRenderContext, baseFieldConfigSchema } from "./Field"; import { Field, type TActionContext, type TRenderContext, baseFieldConfigSchema } from "./Field";
import * as tbbox from "@sinclair/typebox";
const { Type } = tbbox;
export const jsonSchemaFieldConfigSchema = Type.Composite( export const jsonSchemaFieldConfigSchema = Type.Composite(
[ [
@@ -48,16 +46,22 @@ export class JsonSchemaField<
override isValid(value: any, context: TActionContext = "update"): boolean { override isValid(value: any, context: TActionContext = "update"): boolean {
const parentValid = super.isValid(value, context); const parentValid = super.isValid(value, context);
//console.log("jsonSchemaField:isValid", this.getJsonSchema(), this.name, value, parentValid);
if (parentValid) { if (parentValid) {
// already checked in parent // already checked in parent
if (!this.isRequired() && (!value || typeof value !== "object")) { if (!this.isRequired() && (!value || typeof value !== "object")) {
//console.log("jsonschema:valid: not checking", this.name, value, context);
return true; return true;
} }
const result = this.validator.validate(value); const result = this.validator.validate(value);
//console.log("jsonschema:errors", this.name, result.errors);
return result.valid; return result.valid;
} else {
//console.log("jsonschema:invalid", this.name, value, context);
} }
//console.log("jsonschema:invalid:fromParent", this.name, value, context);
return false; return false;
} }
@@ -85,6 +89,7 @@ export class JsonSchemaField<
try { try {
return Default(FromSchema(this.getJsonSchema()), {}); return Default(FromSchema(this.getJsonSchema()), {});
} catch (e) { } catch (e) {
//console.error("jsonschema:transformRetrieve", e);
return null; return null;
} }
} else if (this.hasDefault()) { } else if (this.hasDefault()) {
@@ -102,9 +107,13 @@ export class JsonSchemaField<
): Promise<string | undefined> { ): Promise<string | undefined> {
const value = await super.transformPersist(_value, em, context); const value = await super.transformPersist(_value, em, context);
if (this.nullish(value)) return value; if (this.nullish(value)) return value;
//console.log("jsonschema:transformPersist", this.name, _value, context);
if (!this.isValid(value)) { if (!this.isValid(value)) {
//console.error("jsonschema:transformPersist:invalid", this.name, value);
throw new TransformPersistFailedException(this.name, value); throw new TransformPersistFailedException(this.name, value);
} else {
//console.log("jsonschema:transformPersist:valid", this.name, value);
} }
if (!value || typeof value !== "object") return this.getDefault(); if (!value || typeof value !== "object") return this.getDefault();
+1 -3
View File
@@ -1,9 +1,7 @@
import type { Static } from "core/utils"; import { type Static, Type } from "core/utils";
import type { EntityManager } from "data"; import type { EntityManager } from "data";
import { TransformPersistFailedException } from "../errors"; import { TransformPersistFailedException } from "../errors";
import { Field, type TActionContext, type TRenderContext, baseFieldConfigSchema } from "./Field"; import { Field, type TActionContext, type TRenderContext, baseFieldConfigSchema } from "./Field";
import * as tbbox from "@sinclair/typebox";
const { Type } = tbbox;
export const numberFieldConfigSchema = Type.Composite( export const numberFieldConfigSchema = Type.Composite(
[ [
+1 -3
View File
@@ -1,8 +1,6 @@
import { config } from "core"; import { config } from "core";
import type { Static } from "core/utils"; import { type Static, Type } from "core/utils";
import { Field, baseFieldConfigSchema } from "./Field"; import { Field, baseFieldConfigSchema } from "./Field";
import * as tbbox from "@sinclair/typebox";
const { Type } = tbbox;
export const primaryFieldConfigSchema = Type.Composite([ export const primaryFieldConfigSchema = Type.Composite([
Type.Omit(baseFieldConfigSchema, ["required"]), Type.Omit(baseFieldConfigSchema, ["required"]),
+1 -3
View File
@@ -1,9 +1,7 @@
import { type Static, Type } from "core/utils";
import type { EntityManager } from "data"; import type { EntityManager } from "data";
import type { Static } from "core/utils";
import { TransformPersistFailedException } from "../errors"; import { TransformPersistFailedException } from "../errors";
import { Field, type TActionContext, baseFieldConfigSchema } from "./Field"; import { Field, type TActionContext, baseFieldConfigSchema } from "./Field";
import * as tb from "@sinclair/typebox";
const { Type } = tb;
export const textFieldConfigSchema = Type.Composite( export const textFieldConfigSchema = Type.Composite(
[ [
+1 -3
View File
@@ -1,7 +1,5 @@
import type { Static } from "core/utils"; import { type Static, Type } from "core/utils";
import { Field, baseFieldConfigSchema } from "./Field"; import { Field, baseFieldConfigSchema } from "./Field";
import * as tbbox from "@sinclair/typebox";
const { Type } = tbbox;
export const virtualFieldConfigSchema = Type.Composite([baseFieldConfigSchema, Type.Object({})]); export const virtualFieldConfigSchema = Type.Composite([baseFieldConfigSchema, Type.Object({})]);
+9
View File
@@ -98,9 +98,12 @@ export function fieldTestSuite(
test("toJSON", async () => { test("toJSON", async () => {
const _config = { const _config = {
..._requiredConfig, ..._requiredConfig,
//order: 1,
fillable: true, fillable: true,
required: false, required: false,
hidden: false, hidden: false,
//virtual: false,
//default_value: undefined
}; };
function fieldJson(field: Field) { function fieldJson(field: Field) {
@@ -112,16 +115,19 @@ export function fieldTestSuite(
} }
expect(fieldJson(noConfigField)).toEqual({ expect(fieldJson(noConfigField)).toEqual({
//name: "no_config",
type: noConfigField.type, type: noConfigField.type,
config: _config, config: _config,
}); });
expect(fieldJson(fillable)).toEqual({ expect(fieldJson(fillable)).toEqual({
//name: "fillable",
type: noConfigField.type, type: noConfigField.type,
config: _config, config: _config,
}); });
expect(fieldJson(required)).toEqual({ expect(fieldJson(required)).toEqual({
//name: "required",
type: required.type, type: required.type,
config: { config: {
..._config, ..._config,
@@ -130,6 +136,7 @@ export function fieldTestSuite(
}); });
expect(fieldJson(hidden)).toEqual({ expect(fieldJson(hidden)).toEqual({
//name: "hidden",
type: required.type, type: required.type,
config: { config: {
..._config, ..._config,
@@ -138,6 +145,7 @@ export function fieldTestSuite(
}); });
expect(fieldJson(dflt)).toEqual({ expect(fieldJson(dflt)).toEqual({
//name: "dflt",
type: dflt.type, type: dflt.type,
config: { config: {
..._config, ..._config,
@@ -146,6 +154,7 @@ export function fieldTestSuite(
}); });
expect(fieldJson(requiredAndDefault)).toEqual({ expect(fieldJson(requiredAndDefault)).toEqual({
//name: "full",
type: requiredAndDefault.type, type: requiredAndDefault.type,
config: { config: {
..._config, ..._config,
@@ -39,6 +39,7 @@ export class EntityIndex {
return { return {
entity: this.entity.name, entity: this.entity.name,
fields: this.fields.map((f) => f.name), fields: this.fields.map((f) => f.name),
//name: this.name,
unique: this.unique, unique: this.unique,
}; };
} }
+12
View File
@@ -18,6 +18,7 @@ export function getChangeSet(
data: EntityData, data: EntityData,
fields: Field[], fields: Field[],
): EntityData { ): EntityData {
//console.log("getChangeSet", formData, data);
return transform( return transform(
formData, formData,
(acc, _value, key) => { (acc, _value, key) => {
@@ -31,6 +32,17 @@ export function getChangeSet(
// @todo: add typing for "action" // @todo: add typing for "action"
if (action === "create" || newValue !== data[key]) { if (action === "create" || newValue !== data[key]) {
acc[key] = newValue; acc[key] = newValue;
/*console.log("changed", {
key,
value,
valueType: typeof value,
prev: data[key],
newValue,
new: value,
sent: acc[key]
});*/
} else {
//console.log("no change", key, value, data[key]);
} }
}, },
{} as typeof formData, {} as typeof formData,
+11 -3
View File
@@ -1,4 +1,4 @@
import { type Static, parse } from "core/utils"; import { type Static, Type, parse } from "core/utils";
import type { ExpressionBuilder, SelectQueryBuilder } from "kysely"; import type { ExpressionBuilder, SelectQueryBuilder } from "kysely";
import type { Entity, EntityData, EntityManager } from "../entities"; import type { Entity, EntityData, EntityManager } from "../entities";
import { import {
@@ -8,12 +8,19 @@ import {
} from "../relations"; } from "../relations";
import type { RepoQuery } from "../server/data-query-impl"; import type { RepoQuery } from "../server/data-query-impl";
import type { RelationType } from "./relation-types"; import type { RelationType } from "./relation-types";
import * as tbbox from "@sinclair/typebox";
const { Type } = tbbox;
export type KyselyJsonFrom = any; export type KyselyJsonFrom = any;
export type KyselyQueryBuilder = SelectQueryBuilder<any, any, any>; export type KyselyQueryBuilder = SelectQueryBuilder<any, any, any>;
/*export type RelationConfig = {
mappedBy?: string;
inversedBy?: string;
sourceCardinality?: number;
connectionTable?: string;
connectionTableMappedName?: string;
required?: boolean;
};*/
export type BaseRelationConfig = Static<typeof EntityRelation.schema>; export type BaseRelationConfig = Static<typeof EntityRelation.schema>;
// @todo: add generic type for relation config // @todo: add generic type for relation config
@@ -158,6 +165,7 @@ export abstract class EntityRelation<
* @param entity * @param entity
*/ */
isListableFor(entity: Entity): boolean { isListableFor(entity: Entity): boolean {
//console.log("isListableFor", entity.name, this.source.entity.name, this.target.entity.name);
return this.target.entity.name === entity.name; return this.target.entity.name === entity.name;
} }
+4 -5
View File
@@ -1,14 +1,12 @@
import type { Static } from "core/utils"; import { type Static, Type } from "core/utils";
import type { ExpressionBuilder } from "kysely"; import type { ExpressionBuilder } from "kysely";
import { Entity, type EntityManager } from "../entities"; import { Entity, type EntityManager } from "../entities";
import { type Field, PrimaryField } from "../fields"; import { type Field, PrimaryField, VirtualField } from "../fields";
import type { RepoQuery } from "../server/data-query-impl"; import type { RepoQuery } from "../server/data-query-impl";
import { EntityRelation, type KyselyQueryBuilder } from "./EntityRelation"; import { EntityRelation, type KyselyJsonFrom, type KyselyQueryBuilder } from "./EntityRelation";
import { EntityRelationAnchor } from "./EntityRelationAnchor"; import { EntityRelationAnchor } from "./EntityRelationAnchor";
import { RelationField } from "./RelationField"; import { RelationField } from "./RelationField";
import { type RelationType, RelationTypes } from "./relation-types"; import { type RelationType, RelationTypes } from "./relation-types";
import * as tbbox from "@sinclair/typebox";
const { Type } = tbbox;
export type ManyToManyRelationConfig = Static<typeof ManyToManyRelation.schema>; export type ManyToManyRelationConfig = Static<typeof ManyToManyRelation.schema>;
@@ -48,6 +46,7 @@ export class ManyToManyRelation extends EntityRelation<typeof ManyToManyRelation
this.connectionTableMappedName = config?.connectionTableMappedName || connectionTable; this.connectionTableMappedName = config?.connectionTableMappedName || connectionTable;
this.additionalFields = additionalFields || []; this.additionalFields = additionalFields || [];
//this.connectionTable = connectionTable;
} }
static defaultConnectionTable(source: Entity, target: Entity) { static defaultConnectionTable(source: Entity, target: Entity) {

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