4 Commits
Author SHA1 Message Date
Cameron Pak 62f6985e8f Fix typos in web integration docs
Correct a grammatical error and a minor typo in the web integration
documentation to improve clarity.
2026-04-06 06:59:26 -05:00
Cameron Pak 609eeade23 Fix: Correct standalone mode logic and API call
Adjusted the condition for standalone mode to correctly check for
`adminOptions` when `serveStatic` is not enabled, ensuring the warning
message is displayed appropriately.

Updated the `getApi` call to pass optional headers when available,
allowing for authenticated API requests with custom headers.
2026-04-06 06:58:43 -05:00
Cameron Pak 2eba931e39 Test web adapter standalone mode with serve 2026-04-06 06:58:35 -05:00
shishantbiswas 54aae56734 add: agnostic web compliant adapter 2026-04-04 00:27:29 +05:30
602 changed files with 5004 additions and 5894 deletions
+1 -1
View File
@@ -1,6 +1,6 @@
{
"mcpServers": {
"userbase": {
"bknd": {
"url": "http://localhost:28623/api/system/mcp"
}
}
+3 -3
View File
@@ -15,9 +15,9 @@ jobs:
env:
POSTGRES_PASSWORD: postgres
POSTGRES_USER: postgres
POSTGRES_DB: userbase
# ports:
# - 5430:5432
POSTGRES_DB: bknd
ports:
- 5430:5432
options: >-
--health-cmd pg_isready
--health-interval 10s
+5 -8
View File
@@ -1,22 +1,19 @@
{
"js/ts.tsdk.path": "node_modules/typescript/lib",
"typescript.tsdk": "node_modules/typescript/lib",
"biome.enabled": true,
"editor.defaultFormatter": "biomejs.biome",
"editor.codeActionsOnSave": {
//"source.organizeImports.biome": "explicit",
"source.fixAll.biome": "explicit"
},
"js/ts.preferences.importModuleSpecifier": "non-relative",
"js/ts.preferences.autoImportFileExcludePatterns": [
"typescript.preferences.importModuleSpecifier": "non-relative",
"typescript.preferences.autoImportFileExcludePatterns": [
"**/dist/**",
"**/node_modules/**/dist/**",
"**/node_modules/**/!(src|lib|esm)/**" // optional, stricter
],
"js/ts.preferences.includePackageJsonAutoImports": "on",
"js/ts.tsserver.watchOptions": {
"typescript.preferences.includePackageJsonAutoImports": "on",
"typescript.tsserver.watchOptions": {
"excludeDirectories": ["**/dist", "**/node_modules/**/dist"]
},
"[typescriptreact]": {
"editor.defaultFormatter": "biomejs.biome"
}
}
+22 -22
View File
@@ -1,6 +1,6 @@
# Contributing to userbase
# Contributing to bknd
Thank you for your interest in contributing to userbase. This guide will help you get started, understand the codebase, and submit contributions that align with the project's direction.
Thank you for your interest in contributing to bknd. This guide will help you get started, understand the codebase, and submit contributions that align with the project's direction.
## Table of Contents
@@ -23,7 +23,7 @@ Thank you for your interest in contributing to userbase. This guide will help yo
**Open a GitHub Issue before writing code.** This is the preferred way to propose any change. It lets maintainers and the community align on the approach before time is spent on implementation. If you have discussed a contribution in the [Discord server](https://discord.com/invite/952SFk8Tb8) instead, include a link to the relevant Discord thread in your pull request. Pull requests submitted without a corresponding issue or Discord discussion may be closed.
**Unsolicited architectural changes will be closed.** The internal architecture of userbase is intentional. Refactors, restructuring, or changes to core patterns must be discussed and approved before any code is written.
**Unsolicited architectural changes will be closed.** The internal architecture of bknd is intentional. Refactors, restructuring, or changes to core patterns must be discussed and approved before any code is written.
Contributions that are generally welcome (after opening an issue):
@@ -33,12 +33,12 @@ Contributions that are generally welcome (after opening an issue):
- New examples
- Test coverage improvements
**A note on versioning**: userbase is pre-1.0 and under active development. Full backward compatibility is not guaranteed before v1.0.0. Contributors should be aware that APIs and internal interfaces may change between releases.
**A note on versioning**: bknd is pre-1.0 and under active development. Full backward compatibility is not guaranteed before v1.0.0. Contributors should be aware that APIs and internal interfaces may change between releases.
## Important Resources
- **Documentation**: https://docs.userbase.io
- **Issue Tracker**: https://github.com/userbase-io/userbase/issues
- **Documentation**: https://docs.bknd.io
- **Issue Tracker**: https://github.com/bknd-io/bknd/issues
- **Discord**: https://discord.com/invite/952SFk8Tb8
- **FAQ / Search**: https://www.answeroverflow.com/c/1308395750564302952
@@ -86,8 +86,8 @@ Contributions that are generally welcome (after opening an issue):
This is a Bun monorepo using workspaces. The vast majority of the code lives in `app/`.
```
userbase/
app/ # Main "userbase" npm package (this is where most work happens)
bknd/
app/ # Main "bknd" npm package (this is where most work happens)
src/
adapter/ # Runtime/framework adapters (node, bun, cloudflare, nextjs, astro, etc.)
auth/ # Authentication module (strategies, sessions, user pool)
@@ -100,9 +100,9 @@ userbase/
modules/ # Module system, MCP server, permissions framework
plugins/ # Built-in plugins (auth, data, cloudflare, dev)
ui/ # All frontend code
client/ # TypeScript SDK and React hooks (exported as userbase/client)
elements/ # React components for auth/media (exported as userbase/elements)
(everything else) # Admin UI (exported as userbase/ui)
client/ # TypeScript SDK and React hooks (exported as bknd/client)
elements/ # React components for auth/media (exported as bknd/elements)
(everything else) # Admin UI (exported as bknd/ui)
App.ts # Central application orchestrator
index.ts # Main package exports
__test__/ # Unit tests (mirrors src/ structure)
@@ -110,11 +110,11 @@ userbase/
build.ts # Build script (tsup/esbuild)
build.cli.ts # CLI build script
packages/ # Small satellite packages
cli/ # Standalone CLI package (userbase-cli)
cli/ # Standalone CLI package (bknd-cli)
plasmic/ # Plasmic integration
postgres/ # Postgres helper
sqlocal/ # SQLocal helper
docs/ # Documentation site (Next.js + Fumadocs, deployed to docs.userbase.io)
docs/ # Documentation site (Next.js + Fumadocs, deployed to docs.bknd.io)
examples/ # Example projects across runtimes and frameworks
docker/ # Docker configuration
```
@@ -127,7 +127,7 @@ The project uses TypeScript path aliases defined in `app/tsconfig.json`. Imports
### Module System
userbase is built around four core modules, each with its own schema, API routes, and permissions:
bknd is built around four core modules, each with its own schema, API routes, and permissions:
- **Data** -- entity definitions, field types, relations, queries (backed by Kysely)
- **Auth** -- authentication strategies, sessions, user management
@@ -138,7 +138,7 @@ These modules are managed by the `ModuleManager` (in `app/src/modules/`), which
### Adapter Pattern
Adapters in `app/src/adapter/` allow userbase to run on different runtimes and frameworks. Each adapter provides the glue between userbase's Hono-based server and a specific environment (Node, Bun, Cloudflare Workers, Next.js, Astro, etc.).
Adapters in `app/src/adapter/` allow bknd to run on different runtimes and frameworks. Each adapter provides the glue between bknd's Hono-based server and a specific environment (Node, Bun, Cloudflare Workers, Next.js, Astro, etc.).
### Plugin System
@@ -242,26 +242,26 @@ Open a GitHub Issue with:
- A clear title describing the problem.
- Steps to reproduce the bug.
- Expected behavior vs. actual behavior.
- Your environment (runtime, database, adapter, userbase version).
- Your environment (runtime, database, adapter, bknd version).
- Any relevant error messages or logs.
## Getting Help
- **Discord**: https://discord.com/invite/952SFk8Tb8
- **FAQ / Search**: https://www.answeroverflow.com/c/1308395750564302952
- **GitHub Issues**: https://github.com/userbase-io/userbase/issues
- **GitHub Issues**: https://github.com/bknd-io/bknd/issues
## Contributors
Thank you to everyone who has contributed to userbase.
Thank you to everyone who has contributed to bknd.
<a href="https://github.com/userbase-io/userbase/graphs/contributors">
<img src="https://contrib.rocks/image?repo=userbase-io/userbase" />
<a href="https://github.com/bknd-io/bknd/graphs/contributors">
<img src="https://contrib.rocks/image?repo=bknd-io/bknd" />
</a>
Made with [contrib.rocks](https://contrib.rocks).
## Maintainers
- **Dennis** ([@dswbx](https://github.com/dswbx)) -- Creator and maintainer of userbase
- **Cameron Pak** ([@cameronapak](https://github.com/cameronapak)) -- Maintainer of userbase docs
- **Dennis** ([@dswbx](https://github.com/dswbx)) -- Creator and maintainer of bknd
- **Cameron Pak** ([@cameronapak](https://github.com/cameronapak)) -- Maintainer of bknd docs
-2
View File
@@ -1,5 +1,3 @@
This is an independently maintained fork of [bknd](https://github.com/bknd-io/bknd) which is a drop in replacement for the original package. It is intended to be used in projects that require a more up-to-date version of bknd, or that need to use features that are not available in the original package.
[![npm version](https://img.shields.io/npm/v/bknd.svg)](https://npmjs.org/package/bknd)
![bknd](https://raw.githubusercontent.com/bknd-io/bknd/refs/heads/main/docs/public/assets/poster.png)
+1 -1
View File
@@ -1,5 +1,5 @@
playwright-report
test-results
userbase.config.*
bknd.config.*
__test__/helper.d.ts
.env.local
+2 -1
View File
@@ -4,7 +4,8 @@ import { disableConsoleLog, enableConsoleLog, omitKeys } from "core/utils";
import { adapterTestSuite } from "adapter/adapter-test-suite";
import { bunTestRunner } from "adapter/bun/test";
const stripConnection = <T extends Record<string, any>>(cfg: T) => omitKeys(cfg, ["connection"]);
const stripConnection = <T extends Record<string, any>>(cfg: T) =>
omitKeys(cfg, ["connection"]);
beforeAll(disableConsoleLog);
afterAll(enableConsoleLog);
+3 -9
View File
@@ -73,13 +73,7 @@ describe("Api", async () => {
it("should extract tokens case insensitive", async () => {
const token = await sign({ sub: "test" }, "1234");
expect(
new Api({ headers: new Headers({ Authorization: `Bearer ${token}` }) }).getAuthState()
.token,
).toBe(token);
expect(
new Api({ headers: new Headers({ Authorization: `bearer ${token}` }) }).getAuthState()
.token,
).toBe(token);
});
expect(new Api({ headers: new Headers({ Authorization: `Bearer ${token}` }) }).getAuthState().token).toBe(token);
expect(new Api({ headers: new Headers({ Authorization: `bearer ${token}` }) }).getAuthState().token).toBe(token);
})
});
+1 -1
View File
@@ -1,5 +1,5 @@
import { describe, expect, mock, test, beforeAll, afterAll } from "bun:test";
import { createApp as internalCreateApp, type CreateAppConfig } from "userbase";
import { createApp as internalCreateApp, type CreateAppConfig } from "bknd";
import { getDummyConnection } from "../../__test__/helper";
import { ModuleManager } from "modules/ModuleManager";
import { em, entity, text } from "data/prototype";
+1 -1
View File
@@ -1,7 +1,7 @@
import { describe, test, expect, beforeEach, beforeAll, afterAll } from "bun:test";
import { type App, createApp, createMcpToolCaller } from "core/test/utils";
import { disableConsoleLog, enableConsoleLog } from "core/utils";
import type { McpServer } from "userbase/utils";
import type { McpServer } from "bknd/utils";
beforeAll(disableConsoleLog);
afterAll(enableConsoleLog);
+2 -2
View File
@@ -1,8 +1,8 @@
import { describe, test, expect, beforeEach, beforeAll, afterAll } from "bun:test";
import { type App, createApp, createMcpToolCaller } from "core/test/utils";
import { getSystemMcp } from "modules/mcp/system-mcp";
import { pickKeys, type McpServer } from "userbase/utils";
import { entity, text } from "userbase";
import { pickKeys, type McpServer } from "bknd/utils";
import { entity, text } from "bknd";
import { disableConsoleLog, enableConsoleLog } from "core/utils";
beforeAll(disableConsoleLog);
+1 -1
View File
@@ -4,7 +4,7 @@ import { getSystemMcp } from "modules/mcp/system-mcp";
import { registries } from "index";
import { StorageLocalAdapter } from "adapter/node/storage/StorageLocalAdapter";
import { disableConsoleLog, enableConsoleLog } from "core/utils";
import type { McpServer } from "userbase/utils";
import type { McpServer } from "bknd/utils";
beforeAll(disableConsoleLog);
afterAll(enableConsoleLog);
+1 -1
View File
@@ -1,6 +1,6 @@
import { describe, test, expect, beforeAll, afterAll } from "bun:test";
import { type App, createApp, createMcpToolCaller } from "core/test/utils";
import type { McpServer } from "userbase/utils";
import type { McpServer } from "bknd/utils";
import { disableConsoleLog, enableConsoleLog } from "core/utils/test";
beforeAll(() => disableConsoleLog());
+1 -1
View File
@@ -1,7 +1,7 @@
import { AppEvents } from "App";
import { describe, test, expect, beforeAll, mock, afterAll } from "bun:test";
import { type App, createApp, createMcpToolCaller } from "core/test/utils";
import type { McpServer } from "userbase/utils";
import type { McpServer } from "bknd/utils";
import { disableConsoleLog, enableConsoleLog } from "core/utils/test";
beforeAll(disableConsoleLog);
+7 -11
View File
@@ -51,18 +51,14 @@ describe("Authenticator", async () => {
});
const token = await auth.jwt({ sub: "test" });
const res = await auth.resolveAuthFromRequest(
new Headers({
const res = await auth.resolveAuthFromRequest(new Headers({
Authorization: `Bearer ${token}`,
}),
);
expect((res as any).sub).toBe("test");
}));
expect((res as any).sub).toBe("test")
const res2 = await auth.resolveAuthFromRequest(
new Headers({
const res2 = await auth.resolveAuthFromRequest(new Headers({
Authorization: `bearer ${token}`,
}),
);
expect((res2 as any).sub).toBe("test");
});
}));
expect((res2 as any).sub).toBe("test")
})
});
@@ -2,7 +2,7 @@ import { describe, expect, test, beforeAll, afterAll } from "bun:test";
import { Guard, type GuardConfig } from "auth/authorize/Guard";
import { Permission } from "auth/authorize/Permission";
import { Role, type RoleSchema } from "auth/authorize/Role";
import { objectTransform, s } from "userbase/utils";
import { objectTransform, s } from "bknd/utils";
import { disableConsoleLog, enableConsoleLog } from "core/utils/test";
beforeAll(disableConsoleLog);
@@ -3,7 +3,7 @@ import { createApp } from "core/test/utils";
import type { CreateAppConfig } from "App";
import * as proto from "data/prototype";
import { mergeObject } from "core/utils/objects";
import type { App, DB } from "userbase";
import type { App, DB } from "bknd";
import type { CreateUserPayload } from "auth/AppAuth";
import { disableConsoleLog, enableConsoleLog } from "core/utils/test";
@@ -1,5 +1,5 @@
import { describe, it, expect } from "bun:test";
import { s } from "userbase/utils";
import { s } from "bknd/utils";
import { Permission } from "auth/authorize/Permission";
import { Policy } from "auth/authorize/Policy";
import { Hono } from "hono";
@@ -7,7 +7,7 @@ import { getPermissionRoutes, permission } from "auth/middlewares/permission.mid
import { auth } from "auth/middlewares/auth.middleware";
import { Guard, mergeFilters, type GuardConfig } from "auth/authorize/Guard";
import { Role, RolePermission } from "auth/authorize/Role";
import { Exception } from "userbase";
import { Exception } from "bknd";
import { convert } from "core/object/query/object-query";
describe("Permission", () => {
@@ -421,7 +421,7 @@ describe("permission middleware", () => {
);
const res = await hono.request("/test");
// expecting 500 because userbase should have handled it correctly
// expecting 500 because bknd should have handled it correctly
expect(res.status).toBe(500);
});
-1
View File
@@ -26,7 +26,6 @@ describe("Polymorphic", async () => {
target: "media",
config: {
mappedBy: "image",
on_delete: "set null",
},
});
// media should not see categories
+7 -14
View File
@@ -1,21 +1,19 @@
import { describe, beforeAll, afterAll, test } from "bun:test";
import type { PostgresConnection } from "data/connection/postgres/PostgresConnection";
import { pg, postgresJs } from "userbase";
import { pg, postgresJs } from "bknd";
import { Pool } from "pg";
import postgres from "postgres";
import { disableConsoleLog, enableConsoleLog, $waitUntil } from "userbase/utils";
import { disableConsoleLog, enableConsoleLog, $waitUntil } from "bknd/utils";
import { $ } from "bun";
import { connectionTestSuite } from "data/connection/connection-test-suite";
import { bunTestRunner } from "adapter/bun/test";
const isCI = !!(process.env.GITEA_ACTIONS || process.env.GITHUB_ACTIONS);
const credentials = {
host: isCI ? "postgres" : "localhost",
port: 5432,
host: "localhost",
port: 5430,
user: "postgres",
password: "postgres",
database: "userbase",
database: "bknd",
};
async function cleanDatabase(connection: InstanceType<typeof PostgresConnection>) {
@@ -41,13 +39,8 @@ async function isPostgresRunning() {
describe("postgres", () => {
beforeAll(async () => {
if (process.env.GITEA_ACTIONS || process.env.GITHUB_ACTIONS) {
console.log("Running in CI: Skipping manual docker run");
return;
}
if (!(await isPostgresRunning())) {
await $`docker run --rm --name userbase-test-postgres -d -e POSTGRES_PASSWORD=${credentials.password} -e POSTGRES_USER=${credentials.user} -e POSTGRES_DB=${credentials.database} -p ${credentials.port}:5432 postgres:17`;
await $`docker run --rm --name bknd-test-postgres -d -e POSTGRES_PASSWORD=${credentials.password} -e POSTGRES_USER=${credentials.user} -e POSTGRES_DB=${credentials.database} -p ${credentials.port}:5432 postgres:17`;
await $waitUntil("Postgres is running", isPostgresRunning, 500, 20);
await new Promise((resolve) => setTimeout(resolve, 500));
}
@@ -57,7 +50,7 @@ describe("postgres", () => {
afterAll(async () => {
if (await isPostgresRunning()) {
try {
await $`docker stop userbase-test-postgres`;
await $`docker stop bknd-test-postgres`;
} catch (e) {}
}
+2 -2
View File
@@ -1,10 +1,10 @@
import { describe, it, expect } from "bun:test";
import * as sDirect from "jsonv-ts";
import { s as sFromUserbase } from "userbase/utils";
import { s as sFromBknd } from "bknd/utils";
describe("jsonv-ts resolution", () => {
it("should resolve to a single instance", () => {
const sameNamespace = sDirect === (sFromUserbase as unknown as typeof sDirect);
const sameNamespace = sDirect === (sFromBknd as unknown as typeof sDirect);
// If this fails, two instances are being loaded via different specifiers/paths
expect(sameNamespace).toBe(true);
});
+1 -1
View File
@@ -5,7 +5,7 @@ import { format as sqlFormat } from "sql-formatter";
import type { em as protoEm } from "../src/data/prototype";
import { writeFile } from "node:fs/promises";
import { join } from "node:path";
import { slugify } from "userbase/utils";
import { slugify } from "bknd/utils";
import { type Connection, SqliteLocalConnection } from "data/connection";
import { EntityManager } from "data/entities/EntityManager";
@@ -57,11 +57,11 @@ const configs = {
},
users: {
normal: {
email: "normal@userbase.io",
email: "normal@bknd.io",
password: "12345678",
},
admin: {
email: "admin@userbase.io",
email: "admin@bknd.io",
password: "12345678",
role: "admin",
},
@@ -271,7 +271,7 @@ describe("integration auth", () => {
expect(
await app
.createUser({
email: "test@userbase.io",
email: "test@bknd.io",
password: "12345678",
})
.then((r) => r.role),
@@ -280,7 +280,7 @@ describe("integration auth", () => {
// throws error if role doesn't exist
expect(
app.createUser({
email: "test@userbase.io",
email: "test@bknd.io",
password: "12345678",
role: "doesnt exist",
}),
@@ -290,7 +290,7 @@ describe("integration auth", () => {
expect(
await app
.createUser({
email: "test2@userbase.io",
email: "test2@bknd.io",
password: "12345678",
role: "admin",
})
@@ -301,7 +301,7 @@ describe("integration auth", () => {
expect(
await $fns
.register({
email: "test3@userbase.io",
email: "test3@bknd.io",
password: "12345678",
role: "admin",
})
@@ -312,7 +312,7 @@ describe("integration auth", () => {
expect(
await $fns
.register({
email: "test3@userbase.io",
email: "test3@bknd.io",
password: "12345678",
})
.then((r) => r.data.user.role),
+1 -1
View File
@@ -136,7 +136,7 @@ describe("AppAuth", () => {
}
});
test("registers auth middleware for userbase routes only", async () => {
test("registers auth middleware for bknd routes only", async () => {
const app = createApp({
config: {
auth: {
@@ -7,9 +7,7 @@ import v7 from "./samples/v7.json";
import v8 from "./samples/v8.json";
import v8_2 from "./samples/v8-2.json";
import v9 from "./samples/v9.json";
import v10 from "./samples/v10.json";
import { disableConsoleLog, enableConsoleLog } from "core/utils/test";
import { CURRENT_VERSION } from "modules/db/migrations";
beforeAll(() => disableConsoleLog());
afterAll(enableConsoleLog);
@@ -25,7 +23,7 @@ async function createVersionedApp(
const { version, ...rest } = config;
const db = dummyConnection.kysely as Kysely<any>;
await sql`CREATE TABLE "__userbase" (
await sql`CREATE TABLE "__bknd" (
"id" integer not null primary key autoincrement,
"version" integer,
"type" text,
@@ -35,7 +33,7 @@ async function createVersionedApp(
)`.execute(db);
await db
.insertInto("__userbase")
.insertInto("__bknd")
.values({
version,
type: "config",
@@ -61,9 +59,9 @@ async function getRawConfig(
) {
const db = app.em.connection.kysely;
return await db
.selectFrom("__userbase")
.selectFrom("__bknd")
.selectAll()
.where("version", "=", opts?.version ?? CURRENT_VERSION)
.$if(!!opts?.version, (qb) => qb.where("version", "=", opts?.version))
.$if((opts?.types?.length ?? 0) > 0, (qb) => qb.where("type", "in", opts?.types))
.execute();
}
@@ -117,6 +115,7 @@ describe("Migrations", () => {
"^^s3.secret_access_key^^",
);
const [config, secrets] = (await getRawConfig(app, {
version: 10,
types: ["config", "secrets"],
})) as any;
@@ -130,15 +129,4 @@ describe("Migrations", () => {
"^^s3.secret_access_key^^",
);
});
test("migration from 10 to 11", async () => {
expect(v10.version).toBe(10);
expect(v10.data.entities.test.fields.title.config.fillable).toEqual(["read", "update"]);
const app = await createVersionedApp(v10);
expect(app.version()).toBeGreaterThan(10);
const [config] = (await getRawConfig(app, { types: ["config"] })) as any;
expect(config.json.data.entities.test.fields.title.config.fillable).toEqual(true);
});
});
@@ -1,270 +0,0 @@
{
"version": 10,
"server": {
"cors": {
"origin": "*",
"allow_methods": ["GET", "POST", "PATCH", "PUT", "DELETE"],
"allow_headers": [
"Content-Type",
"Content-Length",
"Authorization",
"Accept"
],
"allow_credentials": true
},
"mcp": {
"enabled": true,
"path": "/api/system/mcp",
"logLevel": "warning"
}
},
"data": {
"basepath": "/api/data",
"default_primary_format": "integer",
"entities": {
"test": {
"type": "regular",
"fields": {
"id": {
"type": "primary",
"config": {
"format": "integer",
"fillable": false,
"required": false
}
},
"title": {
"type": "text",
"config": {
"required": false,
"fillable": ["read", "update"]
}
},
"status": {
"type": "enum",
"config": {
"default_value": "INACTIVE",
"options": {
"type": "strings",
"values": ["INACTIVE", "SUBSCRIBED", "UNSUBSCRIBED"]
},
"required": true,
"fillable": true
}
},
"created_at": {
"type": "date",
"config": {
"type": "datetime",
"required": true,
"fillable": true
}
},
"schema": {
"type": "jsonschema",
"config": {
"default_from_schema": true,
"schema": {
"type": "object",
"properties": {
"one": {
"type": "number",
"default": 1
}
}
},
"required": true,
"fillable": true
}
},
"text": {
"type": "text",
"config": {
"required": false,
"fillable": true
}
}
},
"config": {
"sort_field": "id",
"sort_dir": "asc"
}
},
"items": {
"type": "regular",
"fields": {
"id": {
"type": "primary",
"config": {
"format": "integer",
"fillable": false,
"required": false
}
},
"title": {
"type": "text",
"config": {
"required": false,
"fillable": true
}
}
},
"config": {
"sort_field": "id",
"sort_dir": "asc"
}
},
"media": {
"type": "system",
"fields": {
"id": {
"type": "primary",
"config": {
"format": "integer",
"fillable": false,
"required": false
}
},
"path": {
"type": "text",
"config": {
"required": true,
"fillable": true
}
},
"folder": {
"type": "boolean",
"config": {
"default_value": false,
"hidden": true,
"fillable": ["create"],
"required": false
}
},
"mime_type": {
"type": "text",
"config": {
"required": false,
"fillable": true
}
},
"size": {
"type": "number",
"config": {
"required": false,
"fillable": true
}
},
"scope": {
"type": "text",
"config": {
"hidden": true,
"fillable": ["create"],
"required": false
}
},
"etag": {
"type": "text",
"config": {
"required": false,
"fillable": true
}
},
"modified_at": {
"type": "date",
"config": {
"type": "datetime",
"required": false,
"fillable": true
}
},
"reference": {
"type": "text",
"config": {
"required": false,
"fillable": true
}
},
"entity_id": {
"type": "text",
"config": {
"required": false,
"fillable": true
}
},
"metadata": {
"type": "json",
"config": {
"required": false,
"fillable": true
}
}
},
"config": {
"sort_field": "id",
"sort_dir": "asc"
}
}
},
"relations": {},
"indices": {
"idx_unique_media_path": {
"entity": "media",
"fields": ["path"],
"unique": true
},
"idx_media_reference": {
"entity": "media",
"fields": ["reference"],
"unique": false
},
"idx_media_entity_id": {
"entity": "media",
"fields": ["entity_id"],
"unique": false
}
}
},
"auth": {
"enabled": false,
"basepath": "/api/auth",
"entity_name": "users",
"allow_register": true,
"jwt": {
"secret": "",
"alg": "HS256",
"fields": ["id", "email", "role"]
},
"cookie": {
"path": "/",
"sameSite": "lax",
"secure": true,
"httpOnly": true,
"expires": 604800,
"partitioned": false,
"renew": true,
"pathSuccess": "/",
"pathLoggedOut": "/"
},
"strategies": {
"password": {
"type": "password",
"enabled": true,
"config": {
"hashing": "sha256"
}
}
},
"guard": {
"enabled": false
},
"roles": {}
},
"media": {
"enabled": false
},
"flows": {
"basepath": "/api/flows",
"flows": {}
}
}
@@ -546,7 +546,7 @@
"config": {
"access_key": "123",
"secret_access_key": "123",
"url": "https://123.r2.cloudflarestorage.com/userbase-123"
"url": "https://123.r2.cloudflarestorage.com/bknd-123"
}
}
},
+1 -1
View File
@@ -7,7 +7,7 @@ import { EntityManager } from "data/entities/EntityManager";
import { Module, type ModuleBuildContext } from "modules/Module";
import { getDummyConnection } from "../helper";
import { ModuleHelper } from "modules/ModuleHelper";
import { DebugLogger, McpServer } from "userbase/utils";
import { DebugLogger, McpServer } from "bknd/utils";
export function makeCtx(overrides?: Partial<ModuleBuildContext>): ModuleBuildContext {
const { dummyConnection } = getDummyConnection();
+21 -21
View File
@@ -1,6 +1,6 @@
import { describe, it, expect, beforeEach } from "vitest";
import { AppReduced, type AppType } from "ui/client/utils/AppReduced";
import type { UserbaseAdminProps } from "ui/Admin";
import type { BkndAdminProps } from "ui/Admin";
// Import the normalizeAdminPath function for testing
// Note: This assumes the function is exported or we need to test it indirectly through public methods
@@ -24,7 +24,7 @@ describe("AppReduced", () => {
describe("getSettingsPath", () => {
it("should return settings path with basepath", () => {
const options: UserbaseAdminProps["config"] = {
const options: BkndAdminProps["config"] = {
basepath: "/admin",
logo_return_path: "/",
};
@@ -36,7 +36,7 @@ describe("AppReduced", () => {
});
it("should return settings path with empty basepath", () => {
const options: UserbaseAdminProps["config"] = {
const options: BkndAdminProps["config"] = {
basepath: "",
logo_return_path: "/",
};
@@ -48,7 +48,7 @@ describe("AppReduced", () => {
});
it("should append additional path segments", () => {
const options: UserbaseAdminProps["config"] = {
const options: BkndAdminProps["config"] = {
basepath: "/admin",
logo_return_path: "/",
};
@@ -60,7 +60,7 @@ describe("AppReduced", () => {
});
it("should normalize multiple slashes", () => {
const options: UserbaseAdminProps["config"] = {
const options: BkndAdminProps["config"] = {
basepath: "//admin//",
logo_return_path: "/",
};
@@ -72,7 +72,7 @@ describe("AppReduced", () => {
});
it("should handle basepath without leading slash", () => {
const options: UserbaseAdminProps["config"] = {
const options: BkndAdminProps["config"] = {
basepath: "admin",
logo_return_path: "/",
};
@@ -86,7 +86,7 @@ describe("AppReduced", () => {
describe("getAbsolutePath", () => {
it("should return absolute path with basepath", () => {
const options: UserbaseAdminProps["config"] = {
const options: BkndAdminProps["config"] = {
basepath: "/admin",
logo_return_path: "/",
};
@@ -98,7 +98,7 @@ describe("AppReduced", () => {
});
it("should return base path when no path provided", () => {
const options: UserbaseAdminProps["config"] = {
const options: BkndAdminProps["config"] = {
basepath: "/admin",
logo_return_path: "/",
};
@@ -110,7 +110,7 @@ describe("AppReduced", () => {
});
it("should normalize paths correctly", () => {
const options: UserbaseAdminProps["config"] = {
const options: BkndAdminProps["config"] = {
basepath: "//admin//",
logo_return_path: "/",
};
@@ -124,7 +124,7 @@ describe("AppReduced", () => {
describe("options getter", () => {
it("should return merged options with defaults", () => {
const customOptions: UserbaseAdminProps["config"] = {
const customOptions: BkndAdminProps["config"] = {
basepath: "/custom-admin",
logo_return_path: "/custom-home",
};
@@ -139,7 +139,7 @@ describe("AppReduced", () => {
});
it("should use default logo_return_path when not provided", () => {
const customOptions: UserbaseAdminProps["config"] = {
const customOptions: BkndAdminProps["config"] = {
basepath: "/admin",
};
@@ -153,7 +153,7 @@ describe("AppReduced", () => {
describe("path normalization behavior", () => {
it("should normalize duplicate slashes in settings path", () => {
const options: UserbaseAdminProps["config"] = {
const options: BkndAdminProps["config"] = {
basepath: "/admin",
logo_return_path: "/",
};
@@ -165,7 +165,7 @@ describe("AppReduced", () => {
});
it("should handle root path normalization", () => {
const options: UserbaseAdminProps["config"] = {
const options: BkndAdminProps["config"] = {
basepath: "/",
logo_return_path: "/",
};
@@ -179,7 +179,7 @@ describe("AppReduced", () => {
});
it("should preserve entity paths ending with slash", () => {
const options: UserbaseAdminProps["config"] = {
const options: BkndAdminProps["config"] = {
basepath: "/admin",
logo_return_path: "/",
};
@@ -191,7 +191,7 @@ describe("AppReduced", () => {
});
it("should remove trailing slashes from non-entity paths", () => {
const options: UserbaseAdminProps["config"] = {
const options: BkndAdminProps["config"] = {
basepath: "/admin",
logo_return_path: "/",
};
@@ -205,7 +205,7 @@ describe("AppReduced", () => {
describe("withBasePath - double slash fix (admin_basepath with trailing slash)", () => {
it("should not produce double slashes when admin_basepath has trailing slash", () => {
const options: UserbaseAdminProps["config"] = {
const options: BkndAdminProps["config"] = {
basepath: "/admin",
logo_return_path: "/",
};
@@ -218,7 +218,7 @@ describe("AppReduced", () => {
});
it("should work correctly when admin_basepath has no trailing slash", () => {
const options: UserbaseAdminProps["config"] = {
const options: BkndAdminProps["config"] = {
basepath: "/admin",
logo_return_path: "/",
};
@@ -230,7 +230,7 @@ describe("AppReduced", () => {
});
it("should handle absolute paths with admin_basepath trailing slash", () => {
const options: UserbaseAdminProps["config"] = {
const options: BkndAdminProps["config"] = {
basepath: "/admin",
logo_return_path: "/",
};
@@ -243,7 +243,7 @@ describe("AppReduced", () => {
});
it("should handle settings path with admin_basepath trailing slash", () => {
const options: UserbaseAdminProps["config"] = {
const options: BkndAdminProps["config"] = {
basepath: "/admin",
logo_return_path: "/",
};
@@ -258,7 +258,7 @@ describe("AppReduced", () => {
describe("edge cases", () => {
it("should handle undefined basepath", () => {
const options: UserbaseAdminProps["config"] = {
const options: BkndAdminProps["config"] = {
logo_return_path: "/",
};
@@ -270,7 +270,7 @@ describe("AppReduced", () => {
});
it("should handle null path segments", () => {
const options: UserbaseAdminProps["config"] = {
const options: BkndAdminProps["config"] = {
basepath: "/admin",
logo_return_path: "/",
};
+2 -2
View File
@@ -1,9 +1,9 @@
import pkg from "./package.json" with { type: "json" };
import c from "picocolors";
import { formatNumber } from "userbase/utils";
import { formatNumber } from "bknd/utils";
const deps = Object.keys(pkg.dependencies);
const external = ["jsonv-ts/*", "wrangler", "userbase", "userbase/*", ...deps];
const external = ["jsonv-ts/*", "wrangler", "bknd", "bknd/*", ...deps];
const result = await Bun.build({
entrypoints: ["./src/cli/index.ts"],
+38 -18
View File
@@ -83,8 +83,8 @@ const external = [
"node:test",
"node:assert/strict",
"@libsql/client",
"userbase",
/^userbase\/.*/,
"bknd",
/^bknd\/.*/,
"jsonv-ts",
/^jsonv-ts\/.*/,
] as const;
@@ -125,7 +125,10 @@ async function buildApi() {
async function rewriteClient(path: string) {
const bundle = await Bun.file(path).text();
await Bun.write(path, '"use client";\n' + bundle.replaceAll("ui/client", "userbase/client"));
await Bun.write(
path,
'"use client";\n' + bundle.replaceAll("ui/client", "bknd/client"),
);
}
/**
@@ -188,7 +191,7 @@ async function buildUi() {
/**
* Building UI Elements
* - tailwind-merge is mocked, no exclude
* - ui/client is external, and after built replaced with "userbase/client"
* - ui/client is external, and after built replaced with "bknd/client"
*/
async function buildUiElements() {
await tsup.build({
@@ -200,8 +203,8 @@ async function buildUiElements() {
outDir: "dist/ui/elements",
external: [
"ui/client",
"userbase",
/^userbase\/.*/,
"bknd",
/^bknd\/.*/,
"wouter",
"react",
"react-dom",
@@ -235,7 +238,10 @@ async function buildUiElements() {
/**
* Building adapters
*/
function baseConfig(adapter: string, overrides: Partial<tsup.Options> = {}): tsup.Options {
function baseConfig(
adapter: string,
overrides: Partial<tsup.Options> = {},
): tsup.Options {
return {
minify,
sourcemap,
@@ -259,7 +265,7 @@ function baseConfig(adapter: string, overrides: Partial<tsup.Options> = {}): tsu
external: [
/^cloudflare*/,
/^@?hono.*?/,
/^(userbase|react|next|node).*?/,
/^(bknd|react|next|node).*?/,
/.*\.(html)$/,
...external,
...(Array.isArray(overrides.external) ? overrides.external : []),
@@ -305,7 +311,7 @@ async function buildAdapters() {
entry: ["src/adapter/cloudflare/proxy.ts"],
outDir: "dist/adapter/cloudflare",
metafile: false,
external: [/userbase/, "wrangler", "node:process"],
external: [/bknd/, "wrangler", "node:process"],
}),
),
@@ -324,6 +330,11 @@ async function buildAdapters() {
platform: "node",
}),
tsup.build({
...baseConfig("web"),
platform: "neutral",
}),
tsup.build({
...baseConfig("sveltekit"),
platform: "node",
@@ -339,11 +350,6 @@ async function buildAdapters() {
platform: "node",
}),
tsup.build({
...baseConfig("solid-start"),
platform: "node",
}),
tsup.build({
...baseConfig("sqlite/edge"),
entry: ["src/adapter/sqlite/edge.ts"],
@@ -366,11 +372,17 @@ async function buildAdapters() {
metafile: false,
external: [/^bun\:.*/],
}),
]);
}
async function buildAll() {
await Promise.all([buildApi(), buildUi(), buildUiElements(), buildAdapters()]);
await Promise.all([
buildApi(),
buildUi(),
buildUiElements(),
buildAdapters(),
]);
}
// initial build
@@ -402,14 +414,22 @@ if (watch) {
};
// watch src directory recursively
fsWatch(join(import.meta.dir, "src"), { recursive: true }, (event, filename) => {
fsWatch(
join(import.meta.dir, "src"),
{ recursive: true },
(event, filename) => {
if (!filename) return;
// ignore non-source files
if (!filename.endsWith(".ts") && !filename.endsWith(".tsx") && !filename.endsWith(".css"))
if (
!filename.endsWith(".ts") &&
!filename.endsWith(".tsx") &&
!filename.endsWith(".css")
)
return;
oldConsole.log(c.cyan("[Watch]"), c.dim(`${event}: ${filename}`));
debouncedRebuild();
});
},
);
// keep process alive
await new Promise(() => {});
+1 -4
View File
@@ -3,10 +3,7 @@ import path from "node:path";
import c from "picocolors";
const basePath = new URL(import.meta.resolve("../../")).pathname.slice(0, -1);
type RunOptions = Omit<
Bun.SpawnOptions.SpawnOptions<"ignore", "pipe", "pipe">,
"stdout" | "stderr"
>;
type RunOptions = Omit<Bun.SpawnOptions.SpawnOptions<"ignore", "pipe", "pipe">, "stdout" | "stderr">;
async function run(
cmd: string[] | string,
+2 -2
View File
@@ -15,10 +15,10 @@ const configs = {
nextjs: {
base_path: "/admin",
},
nuxt: {
meta: {
base_path: "/admin",
},
"solid-start": {
nuxt: {
base_path: "/admin",
},
astro: {
+1 -1
View File
@@ -1,4 +1,4 @@
import { createApp } from "userbase/adapter/bun";
import { createApp } from "bknd/adapter/bun";
async function generate() {
console.info("Generating MCP documentation...");
+14 -15
View File
@@ -1,24 +1,24 @@
{
"name": "userbase",
"name": "bknd",
"type": "module",
"sideEffects": false,
"bin": "./dist/cli/index.js",
"version": "0.0.4",
"version": "0.21.0-rc.1",
"description": "Lightweight Firebase/Supabase alternative built to run anywhere — incl. Next.js, React Router, Astro, Cloudflare, Bun, Node, AWS Lambda & more.",
"homepage": "https://gitea.bsws.in/shishantbiswas/userbase",
"homepage": "https://bknd.io",
"repository": {
"type": "git",
"url": "https://gitea.bsws.in/shishantbiswas/userbase.git"
"url": "https://github.com/bknd-io/bknd.git"
},
"bugs": {
"url": "https://gitea.bsws.in/shishantbiswas/userbase/issues"
"url": "https://github.com/bknd-io/bknd/issues"
},
"packageManager": "bun@1.3.3",
"engines": {
"node": ">=22.13"
},
"scripts": {
"dev": "USERBASE_CLI_LOG_LEVEL=debug vite",
"dev": "BKND_CLI_LOG_LEVEL=debug vite",
"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:ci": "mkdir -p dist/static/.vite && echo '{}' > dist/static/.vite/manifest.json && NODE_ENV=production bun run build.ts",
@@ -88,7 +88,7 @@
"@libsql/client": "^0.15.15",
"@mantine/modals": "^7.17.1",
"@mantine/notifications": "^7.17.1",
"@playwright/test": "^1.63.0",
"@playwright/test": "^1.56.1",
"@rjsf/core": "5.22.2",
"@rjsf/utils": "5.22.0",
"@standard-schema/spec": "^1.0.0",
@@ -233,6 +233,11 @@
"import": "./dist/adapter/nextjs/index.js",
"require": "./dist/adapter/nextjs/index.js"
},
"./adapter/web": {
"types": "./dist/types/adapter/web/index.d.ts",
"import": "./dist/adapter/web/index.js",
"require": "./dist/adapter/web/index.js"
},
"./adapter/nuxt": {
"types": "./dist/types/adapter/nuxt/index.d.ts",
"import": "./dist/adapter/nuxt/index.js",
@@ -263,11 +268,6 @@
"import": "./dist/adapter/sveltekit/index.js",
"require": "./dist/adapter/sveltekit/index.js"
},
"./adapter/solid-start": {
"types": "./dist/types/adapter/solid-start/index.d.ts",
"import": "./dist/adapter/solid-start/index.js",
"require": "./dist/adapter/solid-start/index.js"
},
"./adapter/aws": {
"types": "./dist/types/adapter/aws/index.d.ts",
"import": "./dist/adapter/aws/index.js",
@@ -297,13 +297,13 @@
"adapter/cloudflare": ["./dist/types/adapter/cloudflare/index.d.ts"],
"adapter/vite": ["./dist/types/adapter/vite/index.d.ts"],
"adapter/nextjs": ["./dist/types/adapter/nextjs/index.d.ts"],
"adapter/web": ["./dist/types/adapter/web/index.d.ts"],
"adapter/nuxt": ["./dist/types/adapter/nuxt/index.d.ts"],
"adapter/react-router": ["./dist/types/adapter/react-router/index.d.ts"],
"adapter/bun": ["./dist/types/adapter/bun/index.d.ts"],
"adapter/node": ["./dist/types/adapter/node/index.d.ts"],
"adapter/sveltekit": ["./dist/types/adapter/sveltekit/index.d.ts"],
"adapter/tanstack-start": ["./dist/types/adapter/tanstack-start/index.d.ts"],
"adapter/solid-start": ["./dist/types/adapter/solid-start/index.d.ts"],
"adapter/sqlite": ["./dist/types/adapter/sqlite/edge.d.ts"]
}
},
@@ -337,7 +337,6 @@
"sveltekit",
"svelte",
"bun",
"node",
"solid-start"
"node"
]
}
+2 -2
View File
@@ -1,10 +1,10 @@
import type { SafeUser } from "userbase";
import type { SafeUser } from "bknd";
import { AuthApi, type AuthApiOptions } from "auth/api/AuthApi";
import { DataApi, type DataApiOptions } from "data/api/DataApi";
import { decode } from "hono/jwt";
import { MediaApi, type MediaApiOptions } from "media/api/MediaApi";
import { SystemApi } from "modules/SystemApi";
import { omitKeys } from "userbase/utils";
import { omitKeys } from "bknd/utils";
import type { BaseModuleApiOptions } from "modules";
export type TApiUser = SafeUser;
+2 -2
View File
@@ -1,5 +1,5 @@
import type { CreateUserPayload } from "auth/AppAuth";
import { $console, McpClient } from "userbase/utils";
import { $console, McpClient } from "bknd/utils";
import { Event } from "core/events";
import type { em as prototypeEm } from "data/prototype";
import { Connection } from "data/connection/Connection";
@@ -346,7 +346,7 @@ export class App<
try {
// gracefully add the app id
c.res.headers.set("X-userbase-id", this._id);
c.res.headers.set("X-bknd-id", this._id);
} catch (e) {}
await this.emgr.emit(
+3 -3
View File
@@ -1,10 +1,10 @@
import type { TestRunner } from "core/test";
import type { UserbaseConfig, DefaultArgs } from "./index";
import type { BkndConfig, DefaultArgs } from "./index";
import type { App } from "App";
import { disableConsoleLog, enableConsoleLog } from "core/utils/test";
export function adapterTestSuite<
Config extends UserbaseConfig = UserbaseConfig,
Config extends BkndConfig = BkndConfig,
Args extends DefaultArgs = DefaultArgs,
>(
testRunner: TestRunner,
@@ -39,7 +39,7 @@ export function adapterTestSuite<
}),
beforeBuild,
onBuilt,
} as const satisfies UserbaseConfig;
} as const satisfies BkndConfig;
const app = await makeApp(
config as any,
+4 -4
View File
@@ -1,20 +1,20 @@
import { type FrameworkUserbaseConfig, createFrameworkApp } from "userbase/adapter";
import { type FrameworkBkndConfig, createFrameworkApp } from "bknd/adapter";
type AstroEnv = NodeJS.ProcessEnv;
type TAstro = {
request: Request;
};
export type AstroUserbaseConfig<Env = AstroEnv> = FrameworkUserbaseConfig<Env>;
export type AstroBkndConfig<Env = AstroEnv> = FrameworkBkndConfig<Env>;
export async function getApp<Env = AstroEnv>(
config: AstroUserbaseConfig<Env> = {},
config: AstroBkndConfig<Env> = {},
args: Env = import.meta.env as Env,
) {
return await createFrameworkApp(config, args);
}
export function serve<Env = AstroEnv>(
config: AstroUserbaseConfig<Env> = {},
config: AstroBkndConfig<Env> = {},
args: Env = import.meta.env as Env,
) {
return async (fnArgs: TAstro) => {
+7 -7
View File
@@ -1,11 +1,11 @@
import type { App } from "userbase";
import type { App } from "bknd";
import { handle } from "hono/aws-lambda";
import { serveStatic } from "@hono/node-server/serve-static";
import { type RuntimeUserbaseConfig, createRuntimeApp } from "userbase/adapter";
import { type RuntimeBkndConfig, createRuntimeApp } from "bknd/adapter";
type AwsLambdaEnv = object;
export type AwsLambdaUserbaseConfig<Env extends AwsLambdaEnv = AwsLambdaEnv> =
RuntimeUserbaseConfig<Env> & {
export type AwsLambdaBkndConfig<Env extends AwsLambdaEnv = AwsLambdaEnv> =
RuntimeBkndConfig<Env> & {
assets?:
| {
mode: "local";
@@ -18,10 +18,10 @@ export type AwsLambdaUserbaseConfig<Env extends AwsLambdaEnv = AwsLambdaEnv> =
};
export async function createApp<Env extends AwsLambdaEnv = AwsLambdaEnv>(
{ adminOptions = false, assets, ...config }: AwsLambdaUserbaseConfig<Env> = {},
{ adminOptions = false, assets, ...config }: AwsLambdaBkndConfig<Env> = {},
args: Env = {} as Env,
): Promise<App> {
let additional: Partial<RuntimeUserbaseConfig> = {
let additional: Partial<RuntimeBkndConfig> = {
adminOptions,
};
@@ -60,7 +60,7 @@ export async function createApp<Env extends AwsLambdaEnv = AwsLambdaEnv>(
}
export function serve<Env extends AwsLambdaEnv = AwsLambdaEnv>(
config: AwsLambdaUserbaseConfig<Env> = {},
config: AwsLambdaBkndConfig<Env> = {},
args: Env = {} as Env,
) {
return async (event) => {
@@ -7,20 +7,20 @@ import {
useState,
type ReactNode,
} from "react";
import { checksum } from "userbase/utils";
import { App, registries, sqlocal, type UserbaseConfig } from "userbase";
import { checksum } from "bknd/utils";
import { App, registries, sqlocal, type BkndConfig } from "bknd";
import { Route, Router, Switch } from "wouter";
import { ClientProvider } from "userbase/client";
import { ClientProvider } from "bknd/client";
import { SQLocalKysely } from "sqlocal/kysely";
import type { ClientConfig, DatabasePath } from "sqlocal";
import { OpfsStorageAdapter } from "userbase/adapter/browser";
import type { UserbaseAdminConfig } from "userbase/ui";
import { OpfsStorageAdapter } from "bknd/adapter/browser";
import type { BkndAdminConfig } from "bknd/ui";
const Admin = lazy(() =>
Promise.all([
import("userbase/ui"),
import("bknd/ui"),
// @ts-ignore
import("userbase/dist/styles.css"),
import("bknd/dist/styles.css"),
]).then(([mod]) => ({
default: mod.Admin,
})),
@@ -34,34 +34,34 @@ function safeViewTransition(fn: () => void) {
}
}
export type BrowserUserbaseConfig<Args = ImportMetaEnv> = Omit<
UserbaseConfig<Args>,
export type BrowserBkndConfig<Args = ImportMetaEnv> = Omit<
BkndConfig<Args>,
"connection" | "app"
> & {
adminConfig?: UserbaseAdminConfig;
adminConfig?: BkndAdminConfig;
connection?: ClientConfig | DatabasePath;
};
export type UserbaseBrowserAppProps = {
export type BkndBrowserAppProps = {
children: ReactNode;
header?: ReactNode;
loading?: ReactNode;
notFound?: ReactNode;
} & BrowserUserbaseConfig;
} & BrowserBkndConfig;
const UserbaseBrowserAppContext = createContext<{
const BkndBrowserAppContext = createContext<{
app: App;
hash: string;
}>(undefined!);
export function UserbaseBrowserApp({
export function BkndBrowserApp({
children,
adminConfig,
header,
loading,
notFound,
...config
}: UserbaseBrowserAppProps) {
}: BkndBrowserAppProps) {
const [app, setApp] = useState<App | undefined>(undefined);
const [hash, setHash] = useState<string>("");
const adminRoutePath = (adminConfig?.basepath ?? "") + "/*?";
@@ -90,7 +90,7 @@ export function UserbaseBrowserApp({
}
return (
<UserbaseBrowserAppContext.Provider value={{ app, hash }}>
<BkndBrowserAppContext.Provider value={{ app, hash }}>
<ClientProvider storage={window.localStorage} fetcher={app.server.request}>
{header}
<Router key={hash}>
@@ -110,12 +110,12 @@ export function UserbaseBrowserApp({
</Switch>
</Router>
</ClientProvider>
</UserbaseBrowserAppContext.Provider>
</BkndBrowserAppContext.Provider>
);
}
export function useApp() {
return useContext(UserbaseBrowserAppContext);
return useContext(BkndBrowserAppContext);
}
const Center = (props: React.HTMLAttributes<HTMLDivElement>) => (
@@ -133,7 +133,7 @@ const Center = (props: React.HTMLAttributes<HTMLDivElement>) => (
);
let initialized = false;
async function setup(config: BrowserUserbaseConfig = {}) {
async function setup(config: BrowserBkndConfig = {}) {
if (initialized) return;
initialized = true;
@@ -1,6 +1,6 @@
import type { FileBody, FileListObject, FileMeta, FileUploadPayload } from "userbase";
import { StorageAdapter, guessMimeType } from "userbase";
import { parse, s, isFile, isBlob } from "userbase/utils";
import type { FileBody, FileListObject, FileMeta, FileUploadPayload } from "bknd";
import { StorageAdapter, guessMimeType } from "bknd";
import { parse, s, isFile, isBlob } from "bknd/utils";
export const opfsAdapterConfig = s.object(
{
+1 -1
View File
@@ -1,2 +1,2 @@
export * from "./OpfsStorageAdapter";
export * from "./UserbaseBrowserApp";
export * from "./BkndBrowserApp";
+7 -7
View File
@@ -1,18 +1,18 @@
import path from "node:path";
import { type RuntimeUserbaseConfig, createRuntimeApp } from "userbase/adapter";
import { type RuntimeBkndConfig, createRuntimeApp } from "bknd/adapter";
import { registerLocalMediaAdapter } from ".";
import { config, type App } from "userbase";
import { config, type App } from "bknd";
import { serveStatic } from "hono/bun";
type BunEnv = Bun.Env;
export type BunUserbaseConfig<Env = BunEnv> = RuntimeUserbaseConfig<Env> &
export type BunBkndConfig<Env = BunEnv> = RuntimeBkndConfig<Env> &
Omit<Bun.Serve.Options<undefined, string>, "fetch">;
export async function createApp<Env = BunEnv>(
{ distPath, serveStatic: _serveStatic, ...config }: BunUserbaseConfig<Env> = {},
{ distPath, serveStatic: _serveStatic, ...config }: BunBkndConfig<Env> = {},
args: Env = Bun.env as Env,
) {
const root = path.resolve(distPath ?? "./node_modules/userbase/dist", "static");
const root = path.resolve(distPath ?? "./node_modules/bknd/dist", "static");
registerLocalMediaAdapter();
return await createRuntimeApp(
@@ -29,7 +29,7 @@ export async function createApp<Env = BunEnv>(
}
export function createHandler<Env = BunEnv>(
config: BunUserbaseConfig<Env> = {},
config: BunBkndConfig<Env> = {},
args: Env = Bun.env as Env,
) {
let app: App | undefined;
@@ -55,7 +55,7 @@ export function serve<Env = BunEnv>(
serveStatic,
beforeBuild,
...serveOptions
}: BunUserbaseConfig<Env> = {},
}: BunBkndConfig<Env> = {},
args: Env = Bun.env as Env,
) {
Bun.serve({
@@ -3,8 +3,8 @@ import {
genericSqlite,
type GenericSqliteConnection,
type GenericSqliteConnectionConfig,
} from "userbase";
import { omitKeys } from "userbase/utils";
} from "bknd";
import { omitKeys } from "bknd/utils";
export type BunSqliteConnection = GenericSqliteConnection<Database>;
export type BunSqliteConnectionConfig = Omit<
@@ -3,7 +3,7 @@ import { makeConfig, type CloudflareContext } from "./config";
import { disableConsoleLog, enableConsoleLog } from "core/utils";
import { adapterTestSuite } from "adapter/adapter-test-suite";
import { bunTestRunner } from "adapter/bun/test";
import { type CloudflareUserbaseConfig, createApp } from "./cloudflare-workers.adapter";
import { type CloudflareBkndConfig, createApp } from "./cloudflare-workers.adapter";
beforeAll(disableConsoleLog);
afterAll(enableConsoleLog);
@@ -40,7 +40,7 @@ describe("cf adapter", () => {
expect(dynamicConfig.connection).toBeDefined();
});
adapterTestSuite<CloudflareUserbaseConfig, CloudflareContext<any>>(bunTestRunner, {
adapterTestSuite<CloudflareBkndConfig, CloudflareContext<any>>(bunTestRunner, {
makeApp: async (c, a) => {
return await createApp(c, { env: a } as any);
},
@@ -1,11 +1,11 @@
/// <reference types="@cloudflare/workers-types" />
import type { RuntimeUserbaseConfig } from "userbase/adapter";
import type { RuntimeBkndConfig } from "bknd/adapter";
import { Hono } from "hono";
import { serveStatic } from "hono/cloudflare-workers";
import type { App, MaybePromise } from "userbase";
import { $console } from "userbase/utils";
import { createRuntimeApp } from "userbase/adapter";
import type { App, MaybePromise } from "bknd";
import { $console } from "bknd/utils";
import { createRuntimeApp } from "bknd/adapter";
import { registerAsyncsExecutionContext, makeConfig, type CloudflareContext } from "./config";
declare global {
@@ -15,7 +15,7 @@ declare global {
}
export type CloudflareEnv = Cloudflare.Env;
export type CloudflareUserbaseConfig<Env = CloudflareEnv> = RuntimeUserbaseConfig<Env> & {
export type CloudflareBkndConfig<Env = CloudflareEnv> = RuntimeBkndConfig<Env> & {
bindings?: (args: Env) => MaybePromise<{
kv?: KVNamespace;
db?: D1Database;
@@ -34,7 +34,7 @@ export type CloudflareUserbaseConfig<Env = CloudflareEnv> = RuntimeUserbaseConfi
};
export async function createApp<Env extends CloudflareEnv = CloudflareEnv>(
config: CloudflareUserbaseConfig<Env> = {},
config: CloudflareBkndConfig<Env> = {},
ctx: Partial<CloudflareContext<Env>> = {},
) {
const appConfig = await makeConfig(config, ctx);
@@ -57,7 +57,7 @@ export const getFresh = createApp;
let app: App | undefined;
export function serve<Env extends CloudflareEnv = CloudflareEnv>(
config: CloudflareUserbaseConfig<Env> = {},
config: CloudflareBkndConfig<Env> = {},
serveOptions?: (args: Env) => {
warm?: boolean;
},
+10 -11
View File
@@ -1,22 +1,21 @@
/// <reference types="@cloudflare/workers-types" />
import { Connection } from "userbase";
import { sqlite } from "userbase/adapter/sqlite";
import { makeConfig as makeAdapterConfig } from "userbase/adapter";
import { Connection } from "bknd";
import { sqlite } from "bknd/adapter/sqlite";
import { makeConfig as makeAdapterConfig } from "bknd/adapter";
import { registerMedia } from "./storage/StorageR2Adapter";
import { getBinding } from "./bindings";
import { d1Sqlite } from "./connection/D1Connection";
import type { CloudflareUserbaseConfig, CloudflareEnv } from ".";
import { App } from "userbase";
import type { CloudflareBkndConfig, CloudflareEnv } from ".";
import { App } from "bknd";
import type { Context as HonoContext, ExecutionContext } from "hono";
import { $console } from "userbase/utils";
import { $console } from "bknd/utils";
import { setCookie } from "hono/cookie";
export const constants = {
exec_async_event_id: "cf_register_waituntil",
cache_endpoint: "/__userbase/cache",
do_endpoint: "/__userbase/do",
cache_endpoint: "/__bknd/cache",
do_endpoint: "/__bknd/do",
d1_session: {
cookie: "cf_d1_session",
header: "x-cf-d1-session",
@@ -41,7 +40,7 @@ function getCookieValue(cookies: string | null, name: string) {
return null;
}
export function d1SessionHelper(config: CloudflareUserbaseConfig<any>) {
export function d1SessionHelper(config: CloudflareBkndConfig<any>) {
const headerKey = constants.d1_session.header;
const cookieKey = constants.d1_session.cookie;
const transport = config.d1?.transport;
@@ -91,7 +90,7 @@ export function d1SessionHelper(config: CloudflareUserbaseConfig<any>) {
let media_registered: boolean = false;
export async function makeConfig<Env extends CloudflareEnv = CloudflareEnv>(
config: CloudflareUserbaseConfig<Env>,
config: CloudflareBkndConfig<Env>,
args?: Partial<CloudflareContext<Env>>,
) {
if (!media_registered && config.registerMedia !== false) {
@@ -1,6 +1,6 @@
/// <reference types="@cloudflare/workers-types" />
import { genericSqlite, type GenericSqliteConnection } from "userbase";
import { genericSqlite, type GenericSqliteConnection } from "bknd";
import type { QueryResult } from "kysely";
export type D1SqliteConnection = GenericSqliteConnection<D1Database>;
@@ -1,6 +1,6 @@
/// <reference types="@cloudflare/workers-types" />
import { genericSqlite, type GenericSqliteConnection } from "userbase";
import { genericSqlite, type GenericSqliteConnection } from "bknd";
import type { QueryResult } from "kysely";
export type DoSqliteConnection = GenericSqliteConnection<DurableObjectState["storage"]["sql"]>;
+2 -2
View File
@@ -5,7 +5,7 @@ export {
createApp,
serve,
type CloudflareEnv,
type CloudflareUserbaseConfig,
type CloudflareBkndConfig,
} from "./cloudflare-workers.adapter";
export { d1Sqlite, type D1ConnectionConfig };
export { doSqlite, type DoConnectionConfig } from "./connection/DoConnection";
@@ -18,7 +18,7 @@ export {
} from "./bindings";
export { constants, makeConfig, type CloudflareContext } from "./config";
export { StorageR2Adapter, registerMedia } from "./storage/StorageR2Adapter";
export { registries } from "userbase";
export { registries } from "bknd";
export { devFsVitePlugin, devFsWrite } from "./vite";
// for compatibility with old code
+5 -5
View File
@@ -2,12 +2,12 @@ import {
d1Sqlite,
getBinding,
registerMedia,
type CloudflareUserbaseConfig,
type CloudflareBkndConfig,
type CloudflareEnv,
} from "userbase/adapter/cloudflare";
} from "bknd/adapter/cloudflare";
import type { GetPlatformProxyOptions, PlatformProxy } from "wrangler";
import process from "node:process";
import { $console } from "userbase/utils";
import { $console } from "bknd/utils";
export type WithPlatformProxyOptions = {
/**
@@ -42,7 +42,7 @@ async function getPlatformProxy(opts?: GetPlatformProxyOptions) {
}
export function withPlatformProxy<Env extends CloudflareEnv>(
config: CloudflareUserbaseConfig<Env> = {},
config: CloudflareBkndConfig<Env> = {},
opts?: WithPlatformProxyOptions,
) {
const use_proxy =
@@ -91,5 +91,5 @@ export function withPlatformProxy<Env extends CloudflareEnv>(
connection,
};
},
} satisfies CloudflareUserbaseConfig<Env>;
} satisfies CloudflareBkndConfig<Env>;
}
@@ -1,7 +1,7 @@
import { registries as $registries, isDebug, guessMimeType } from "userbase";
import { registries as $registries, isDebug, guessMimeType } from "bknd";
import { getBindings } from "../bindings";
import { s } from "userbase/utils";
import { StorageAdapter, type FileBody } from "userbase";
import { s } from "bknd/utils";
import { StorageAdapter, type FileBody } from "bknd";
export function makeSchema(bindings: string[] = []) {
return s.object(
+2 -2
View File
@@ -8,7 +8,7 @@ import { resolve } from "node:path";
*/
export function devFsVitePlugin({
verbose = false,
configFile = "userbase.config.ts",
configFile = "bknd.config.ts",
}: {
verbose?: boolean;
configFile?: string;
@@ -195,7 +195,7 @@ export function devFsVitePlugin({
return;
}
// Check if this is the userbase config file
// Check if this is the bknd config file
if (id.includes(configFile)) {
if (verbose) {
console.debug("[dev-fs-plugin] Transforming", configFile);
+16 -16
View File
@@ -7,27 +7,27 @@ import {
type MaybePromise,
registries as $registries,
type Merge,
} from "userbase";
import { $console } from "userbase/utils";
} from "bknd";
import { $console } from "bknd/utils";
import type { Context, MiddlewareHandler, Next } from "hono";
import type { AdminControllerOptions } from "modules/server/AdminController";
import type { Manifest } from "vite";
export type UserbaseConfig<Args = any, Additional = {}> = Merge<
export type BkndConfig<Args = any, Additional = {}> = Merge<
CreateAppConfig &
Omit<Additional, "app"> & {
app?:
| Omit<UserbaseConfig<Args, Additional>, "app">
| ((args: Args) => MaybePromise<Omit<UserbaseConfig<Args, Additional>, "app">>);
| Omit<BkndConfig<Args, Additional>, "app">
| ((args: Args) => MaybePromise<Omit<BkndConfig<Args, Additional>, "app">>);
onBuilt?: (app: App) => MaybePromise<void>;
beforeBuild?: (app?: App, registries?: typeof $registries) => MaybePromise<void>;
buildConfig?: Parameters<App["build"]>[0];
}
>;
export type FrameworkUserbaseConfig<Args = any> = UserbaseConfig<Args>;
export type FrameworkBkndConfig<Args = any> = BkndConfig<Args>;
export type RuntimeUserbaseConfig<Args = any> = UserbaseConfig<Args> & {
export type RuntimeBkndConfig<Args = any> = BkndConfig<Args> & {
distPath?: string;
serveStatic?: MiddlewareHandler | [string, MiddlewareHandler];
adminOptions?: AdminControllerOptions | false;
@@ -38,9 +38,9 @@ export type DefaultArgs = {
};
export async function makeConfig<Args = DefaultArgs>(
config: UserbaseConfig<Args>,
config: BkndConfig<Args>,
args?: Args,
): Promise<Omit<UserbaseConfig<Args>, "app">> {
): Promise<Omit<BkndConfig<Args>, "app">> {
let additionalConfig: CreateAppConfig = {};
const { app, ...rest } = config;
if (app) {
@@ -57,10 +57,10 @@ export async function makeConfig<Args = DefaultArgs>(
return { ...rest, ...additionalConfig };
}
export async function createAdapterApp<Config extends UserbaseConfig = UserbaseConfig, Args = DefaultArgs>(
export async function createAdapterApp<Config extends BkndConfig = BkndConfig, Args = DefaultArgs>(
config: Config = {} as Config,
args?: Args,
): Promise<{ app: App; config: UserbaseConfig<Args> }> {
): Promise<{ app: App; config: BkndConfig<Args> }> {
await config.beforeBuild?.(undefined, $registries);
const appConfig = await makeConfig(config, args);
@@ -69,7 +69,7 @@ export async function createAdapterApp<Config extends UserbaseConfig = UserbaseC
if (Connection.isConnection(config.connection)) {
connection = config.connection;
} else {
const sqlite = (await import("userbase/adapter/sqlite")).sqlite;
const sqlite = (await import("bknd/adapter/sqlite")).sqlite;
const conf = appConfig.connection ?? { url: "file:data.db" };
connection = sqlite(conf) as any;
$console.info(`Using ${connection!.name} connection`, conf.url);
@@ -84,7 +84,7 @@ export async function createAdapterApp<Config extends UserbaseConfig = UserbaseC
}
export async function createFrameworkApp<Args = DefaultArgs>(
config: FrameworkUserbaseConfig = {},
config: FrameworkBkndConfig = {},
args?: Args,
): Promise<App> {
const { app, config: appConfig } = await createAdapterApp(config, args);
@@ -108,7 +108,7 @@ export async function createFrameworkApp<Args = DefaultArgs>(
}
export async function createRuntimeApp<Args = DefaultArgs>(
{ serveStatic, adminOptions, ...config }: RuntimeUserbaseConfig<Args> = {},
{ serveStatic, adminOptions, ...config }: RuntimeBkndConfig<Args> = {},
args?: Args,
): Promise<App> {
const { app, config: appConfig } = await createAdapterApp(config, args);
@@ -148,7 +148,7 @@ export async function createRuntimeApp<Args = DefaultArgs>(
*
* @example
* ```typescript
* import { serveStaticViaImport } from "userbase/adapter";
* import { serveStaticViaImport } from "bknd/adapter";
*
* serve({
* serveStatic: serveStaticViaImport(),
@@ -161,7 +161,7 @@ export function serveStaticViaImport(opts?: {
package?: string;
}) {
let files: string[] | undefined;
const pkg = opts?.package ?? "userbase";
const pkg = opts?.package ?? "bknd";
// @ts-ignore
return async (c: Context, next: Next) => {
@@ -3,13 +3,13 @@ import * as nextjs from "./nextjs.adapter";
import { disableConsoleLog, enableConsoleLog } from "core/utils";
import { adapterTestSuite } from "adapter/adapter-test-suite";
import { bunTestRunner } from "adapter/bun/test";
import type { NextjsUserbaseConfig } from "./nextjs.adapter";
import type { NextjsBkndConfig } from "./nextjs.adapter";
beforeAll(disableConsoleLog);
afterAll(enableConsoleLog);
describe("nextjs adapter", () => {
adapterTestSuite<NextjsUserbaseConfig>(bunTestRunner, {
adapterTestSuite<NextjsBkndConfig>(bunTestRunner, {
makeApp: nextjs.getApp,
makeHandler: nextjs.serve,
});
+6 -6
View File
@@ -1,21 +1,21 @@
import { createFrameworkApp, type FrameworkUserbaseConfig } from "userbase/adapter";
import { isNode } from "userbase/utils";
import { createFrameworkApp, type FrameworkBkndConfig } from "bknd/adapter";
import { isNode } from "bknd/utils";
// @ts-expect-error next is not installed
import type { NextApiRequest } from "next";
type NextjsEnv = NextApiRequest["env"];
export type NextjsUserbaseConfig<Env = NextjsEnv> = FrameworkUserbaseConfig<Env> & {
export type NextjsBkndConfig<Env = NextjsEnv> = FrameworkBkndConfig<Env> & {
cleanRequest?: { searchParams?: string[] };
};
export async function getApp<Env = NextjsEnv>(
config: NextjsUserbaseConfig<Env>,
config: NextjsBkndConfig<Env>,
args: Env = process.env as Env,
) {
return await createFrameworkApp(config, args);
}
function getCleanRequest(req: Request, cleanRequest: NextjsUserbaseConfig["cleanRequest"]) {
function getCleanRequest(req: Request, cleanRequest: NextjsBkndConfig["cleanRequest"]) {
if (!cleanRequest) return req;
const url = new URL(req.url);
@@ -41,7 +41,7 @@ function getCleanRequest(req: Request, cleanRequest: NextjsUserbaseConfig["clean
}
export function serve<Env = NextjsEnv>(
{ cleanRequest, ...config }: NextjsUserbaseConfig<Env> = {},
{ cleanRequest, ...config }: NextjsBkndConfig<Env> = {},
args: Env = process.env as Env,
) {
return async (req: Request) => {
@@ -2,9 +2,9 @@ import {
genericSqlite,
type GenericSqliteConnection,
type GenericSqliteConnectionConfig,
} from "userbase";
} from "bknd";
import { DatabaseSync } from "node:sqlite";
import { omitKeys } from "userbase/utils";
import { omitKeys } from "bknd/utils";
export type NodeSqliteConnection = GenericSqliteConnection<DatabaseSync>;
export type NodeSqliteConnectionConfig = Omit<
+8 -8
View File
@@ -2,12 +2,12 @@ import path from "node:path";
import { serve as honoServe } from "@hono/node-server";
import { serveStatic } from "@hono/node-server/serve-static";
import { registerLocalMediaAdapter } from "adapter/node/storage";
import { type RuntimeUserbaseConfig, createRuntimeApp } from "userbase/adapter";
import { config as $config, type App } from "userbase";
import { $console } from "userbase/utils";
import { type RuntimeBkndConfig, createRuntimeApp } from "bknd/adapter";
import { config as $config, type App } from "bknd";
import { $console } from "bknd/utils";
type NodeEnv = NodeJS.ProcessEnv;
export type NodeUserbaseConfig<Env = NodeEnv> = RuntimeUserbaseConfig<Env> & {
export type NodeBkndConfig<Env = NodeEnv> = RuntimeBkndConfig<Env> & {
port?: number;
hostname?: string;
listener?: Parameters<typeof honoServe>[1];
@@ -16,12 +16,12 @@ export type NodeUserbaseConfig<Env = NodeEnv> = RuntimeUserbaseConfig<Env> & {
};
export async function createApp<Env = NodeEnv>(
{ distPath, relativeDistPath, ...config }: NodeUserbaseConfig<Env> = {},
{ distPath, relativeDistPath, ...config }: NodeBkndConfig<Env> = {},
args: Env = process.env as Env,
) {
const root = path.relative(
process.cwd(),
path.resolve(distPath ?? relativeDistPath ?? "./node_modules/userbase/dist", "static"),
path.resolve(distPath ?? relativeDistPath ?? "./node_modules/bknd/dist", "static"),
);
if (relativeDistPath) {
$console.warn("relativeDistPath is deprecated, please use distPath instead");
@@ -38,7 +38,7 @@ export async function createApp<Env = NodeEnv>(
}
export function createHandler<Env = NodeEnv>(
config: NodeUserbaseConfig<Env> = {},
config: NodeBkndConfig<Env> = {},
args: Env = process.env as Env,
) {
let app: App | undefined;
@@ -51,7 +51,7 @@ export function createHandler<Env = NodeEnv>(
}
export function serve<Env = NodeEnv>(
{ port = $config.server.default_port, hostname, listener, ...config }: NodeUserbaseConfig<Env> = {},
{ port = $config.server.default_port, hostname, listener, ...config }: NodeBkndConfig<Env> = {},
args: Env = process.env as Env,
) {
honoServe(
@@ -1,7 +1,7 @@
import { readFile, readdir, stat, unlink, writeFile } from "node:fs/promises";
import type { FileBody, FileListObject, FileMeta, FileUploadPayload } from "userbase";
import { StorageAdapter, guessMimeType } from "userbase";
import { parse, s, isFile } from "userbase/utils";
import type { FileBody, FileListObject, FileMeta, FileUploadPayload } from "bknd";
import { StorageAdapter, guessMimeType } from "bknd";
import { parse, s, isFile } from "bknd/utils";
export const localAdapterConfig = s.object(
{
+1 -1
View File
@@ -1,4 +1,4 @@
import { registries } from "userbase";
import { registries } from "bknd";
import { type LocalAdapterConfig, StorageLocalAdapter } from "./StorageLocalAdapter";
export * from "./StorageLocalAdapter";
+10 -7
View File
@@ -1,15 +1,15 @@
import { createRuntimeApp, type RuntimeUserbaseConfig } from "userbase/adapter";
import { createRuntimeApp, type RuntimeBkndConfig } from "bknd/adapter";
export type NuxtEnv = NodeJS.ProcessEnv;
export type NuxtUserbaseConfig<Env = NuxtEnv> = RuntimeUserbaseConfig<Env>;
export type NuxtBkndConfig<Env = NuxtEnv> = RuntimeBkndConfig<Env>;
/**
* Get userbase app instance
* @param config - userbase configuration
* Get bknd app instance
* @param config - bknd configuration
* @param args - environment variables
*/
export async function getApp<Env>(
config: NuxtUserbaseConfig<Env> = {} as NuxtUserbaseConfig<Env>,
config: NuxtBkndConfig<Env> = {} as NuxtBkndConfig<Env>,
args: Env,
) {
return await createRuntimeApp(config, args);
@@ -17,10 +17,13 @@ export async function getApp<Env>(
/**
* Create middleware handler for Nuxt
* @param config - userbase configuration
* @param config - bknd configuration
* @param args - environment variables
*/
export function serve<Env>(config: NuxtUserbaseConfig<Env> = {} as NuxtUserbaseConfig<Env>, args: Env) {
export function serve<Env>(
config: NuxtBkndConfig<Env> = {} as NuxtBkndConfig<Env>,
args: Env,
) {
return async (request: Request) => {
return (await getApp(config, args)).fetch(request);
};
@@ -1,20 +1,20 @@
import { type FrameworkUserbaseConfig, createFrameworkApp } from "userbase/adapter";
import { type FrameworkBkndConfig, createFrameworkApp } from "bknd/adapter";
type ReactRouterEnv = NodeJS.ProcessEnv;
type ReactRouterFunctionArgs = {
request: Request;
};
export type ReactRouterUserbaseConfig<Env = ReactRouterEnv> = FrameworkUserbaseConfig<Env>;
export type ReactRouterBkndConfig<Env = ReactRouterEnv> = FrameworkBkndConfig<Env>;
export async function getApp<Env = ReactRouterEnv>(
config: ReactRouterUserbaseConfig<Env>,
config: ReactRouterBkndConfig<Env>,
args: Env = process.env as Env,
) {
return await createFrameworkApp(config, args);
}
export function serve<Env = ReactRouterEnv>(
config: ReactRouterUserbaseConfig<Env> = {},
config: ReactRouterBkndConfig<Env> = {},
args: Env = process.env as Env,
) {
return async (fnArgs: ReactRouterFunctionArgs) => {
-1
View File
@@ -1 +0,0 @@
export * from "./solid-start.adapter";
@@ -1,16 +0,0 @@
import { afterAll, beforeAll, describe } from "bun:test";
import * as solidStart from "./solid-start.adapter";
import { disableConsoleLog, enableConsoleLog } from "core/utils";
import { adapterTestSuite } from "adapter/adapter-test-suite";
import { bunTestRunner } from "adapter/bun/test";
import type { SolidStartUserbaseConfig } from "./solid-start.adapter";
beforeAll(disableConsoleLog);
afterAll(enableConsoleLog);
describe("solid-start adapter", () => {
adapterTestSuite<SolidStartUserbaseConfig>(bunTestRunner, {
makeApp: solidStart.getApp,
makeHandler: solidStart.serve,
});
});
@@ -1,31 +0,0 @@
import { createRuntimeApp, type RuntimeUserbaseConfig } from "userbase/adapter";
export type SolidStartEnv = NodeJS.ProcessEnv;
export type SolidStartUserbaseConfig<Env = SolidStartEnv> = RuntimeUserbaseConfig<Env>;
/**
* Get userbase app instance
* @param config - userbase configuration
* @param args - environment variables
*/
export async function getApp<Env = SolidStartEnv>(
config: SolidStartUserbaseConfig<Env>,
args: Env = process.env as Env,
) {
return await createRuntimeApp(config, args);
}
/**
* Create middleware handler for Solid Start
* @param config - userbase configuration
* @param args - environment variables
*/
export function serve<Env = SolidStartEnv>(
config: SolidStartUserbaseConfig<Env> = {},
args: Env = process.env as Env,
) {
return async (req: Request) => {
const app = await getApp(config, args);
return app.fetch(req);
};
}
+1 -1
View File
@@ -1,4 +1,4 @@
import type { Connection } from "userbase";
import type { Connection } from "bknd";
import { bunSqlite } from "../bun/connection/BunSqliteConnection";
export function sqlite(config?: { url: string }): Connection {
+1 -1
View File
@@ -1,4 +1,4 @@
import { type Connection, libsql } from "userbase";
import { type Connection, libsql } from "bknd";
export function sqlite(config: { url: string }): Connection {
return libsql(config);
+1 -1
View File
@@ -1,4 +1,4 @@
import type { Connection } from "userbase";
import type { Connection } from "bknd";
import { nodeSqlite } from "../node/connection/NodeSqliteConnection";
export function sqlite(config?: { url: string }): Connection {
@@ -1,18 +1,18 @@
import { createRuntimeApp, type RuntimeUserbaseConfig } from "userbase/adapter";
import { createRuntimeApp, type RuntimeBkndConfig } from "bknd/adapter";
type TSvelteKit = {
request: Request;
};
export type SvelteKitUserbaseConfig<Env> = Pick<RuntimeUserbaseConfig<Env>, "adminOptions">;
export type SvelteKitBkndConfig<Env> = Pick<RuntimeBkndConfig<Env>, "adminOptions">;
/**
* Get userbase app instance
* @param config - userbase configuration
* Get bknd app instance
* @param config - bknd configuration
* @param args - environment variables (use $env/dynamic/private for universal runtime support)
*/
export async function getApp<Env>(
config: SvelteKitUserbaseConfig<Env> = {} as SvelteKitUserbaseConfig<Env>,
config: SvelteKitBkndConfig<Env> = {} as SvelteKitBkndConfig<Env>,
args: Env,
) {
return await createRuntimeApp(config, args);
@@ -20,11 +20,11 @@ export async function getApp<Env>(
/**
* Create request handler for hooks.server.ts
* @param config - userbase configuration
* @param config - bknd configuration
* @param args - environment variables (use $env/dynamic/private for universal runtime support)
*/
export function serve<Env>(
config: SvelteKitUserbaseConfig<Env> = {} as SvelteKitUserbaseConfig<Env>,
config: SvelteKitBkndConfig<Env> = {} as SvelteKitBkndConfig<Env>,
args: Env,
) {
return async (fnArgs: TSvelteKit) => {
@@ -1,12 +1,13 @@
import { createFrameworkApp, type FrameworkUserbaseConfig } from "userbase/adapter";
import { createFrameworkApp, type FrameworkBkndConfig } from "bknd/adapter";
export type TanstackStartEnv = NodeJS.ProcessEnv;
export type TanstackStartConfig<Env = TanstackStartEnv> = FrameworkUserbaseConfig<Env>;
export type TanstackStartConfig<Env = TanstackStartEnv> =
FrameworkBkndConfig<Env>;
/**
* Get userbase app instance
* @param config - userbase configuration
* Get bknd app instance
* @param config - bknd configuration
* @param args - environment variables
*/
export async function getApp<Env = TanstackStartEnv>(
@@ -18,7 +19,7 @@ export async function getApp<Env = TanstackStartEnv>(
/**
* Create request handler for src/routes/api.$.ts
* @param config - userbase configuration
* @param config - bknd configuration
* @param args - environment variables
*/
export function serve<Env = TanstackStartEnv>(
+8 -8
View File
@@ -1,17 +1,17 @@
import { serveStatic } from "@hono/node-server/serve-static";
import { type DevServerOptions, default as honoViteDevServer } from "@hono/vite-dev-server";
import type { App } from "userbase";
import { type RuntimeUserbaseConfig, createRuntimeApp } from "userbase/adapter";
import { registerLocalMediaAdapter } from "userbase/adapter/node";
import type { App } from "bknd";
import { type RuntimeBkndConfig, createRuntimeApp } from "bknd/adapter";
import { registerLocalMediaAdapter } from "bknd/adapter/node";
import { devServerConfig } from "./dev-server-config";
import type { MiddlewareHandler } from "hono";
export type ViteEnv = NodeJS.ProcessEnv;
export type ViteUserbaseConfig<Env = ViteEnv> = RuntimeUserbaseConfig<Env> & {
export type ViteBkndConfig<Env = ViteEnv> = RuntimeBkndConfig<Env> & {
serveStatic?: false | MiddlewareHandler;
};
export function addViteScript(html: string, addUserbaseContext: boolean = true) {
export function addViteScript(html: string, addBkndContext: boolean = true) {
return html.replace(
"</head>",
`<script type="module">
@@ -22,13 +22,13 @@ window.$RefreshSig$ = () => (type) => type
window.__vite_plugin_react_preamble_installed__ = true
</script>
<script type="module" src="/@vite/client"></script>
${addUserbaseContext ? "<!-- BKND_CONTEXT -->" : ""}
${addBkndContext ? "<!-- BKND_CONTEXT -->" : ""}
</head>`,
);
}
async function createApp<ViteEnv>(
config: ViteUserbaseConfig<ViteEnv> = {},
config: ViteBkndConfig<ViteEnv> = {},
env: ViteEnv = {} as ViteEnv,
): Promise<App> {
registerLocalMediaAdapter();
@@ -49,7 +49,7 @@ async function createApp<ViteEnv>(
);
}
export function serve<ViteEnv>(config: ViteUserbaseConfig<ViteEnv> = {}, args?: ViteEnv) {
export function serve<ViteEnv>(config: ViteBkndConfig<ViteEnv> = {}, args?: ViteEnv) {
return {
async fetch(request: Request, env: any, ctx: ExecutionContext) {
const app = await createApp(config, env);
+1
View File
@@ -0,0 +1 @@
export * from "./web.adapter";
+104
View File
@@ -0,0 +1,104 @@
import { afterAll, beforeAll, describe, test, expect } from "bun:test";
import { createBknd } from "./web.adapter";
import { disableConsoleLog, enableConsoleLog } from "core/utils";
import { adapterTestSuite } from "adapter/adapter-test-suite";
import { bunTestRunner } from "adapter/bun/test";
beforeAll(disableConsoleLog);
afterAll(enableConsoleLog);
describe("web adapter via createBknd", () => {
adapterTestSuite(bunTestRunner, {
makeApp: (options, args) => createBknd({ mode: "api", options }, args).getApp(),
makeHandler: (options, args) => createBknd({ mode: "api", options: options ?? {} }, args).serve(),
});
// ------------------------ MODE API ------------------------
test("caches app instance", async () => {
const bknd = createBknd({ mode: "api", options: { connection: { url: ":memory:" } } });
const app1 = await bknd.getApp();
const app2 = await bknd.getApp();
expect(app1).toBe(app2);
});
test("getApi returns api", async () => {
const bknd = createBknd({ mode: "api", options: { connection: { url: ":memory:" } } });
const api = await bknd.getApi();
expect(api).toBeDefined();
});
test("uses createFrameworkApp ", async () => {
const bknd = createBknd({ mode: "api", options: { connection: { url: ":memory:" } } });
const app = await bknd.getApp();
expect(app).toBeDefined();
expect(app.isBuilt()).toBe(true);
});
test("serve returns a fetch handler", async () => {
const bknd = createBknd({ mode: "api", options: { connection: { url: ":memory:" } } });
const handler = bknd.serve();
const res = await handler(new Request("http://localhost:3000/api/system/config"));
expect(res.status).toBe(200);
});
});
// ------------------------ MODE STANDALONE ------------------------
describe("web adapter via createBknd in standalone mode", () => {
adapterTestSuite(bunTestRunner, {
makeApp: (options, args) => createBknd({ mode: "standalone", options }, args).getApp(),
makeHandler: (options, args) => createBknd({ mode: "standalone", options: options ?? {} }, args).serve(),
});
test("caches app instance", async () => {
const bknd = createBknd({ mode: "standalone", options: { connection: { url: ":memory:" } } });
const app1 = await bknd.getApp();
const app2 = await bknd.getApp();
expect(app1).toBe(app2);
});
test("getApi returns api", async () => {
const bknd = createBknd({ mode: "standalone", options: { connection: { url: ":memory:" } } });
const api = await bknd.getApi();
expect(api).toBeDefined();
});
test("uses createRuntimeApp", async () => {
const bknd = createBknd({
mode: "standalone",
options: {
connection: { url: ":memory:" },
adminOptions: { adminBasepath: "/admin" },
}
});
const app = await bknd.getApp();
expect(app).toBeDefined();
expect(app.isBuilt()).toBe(true);
});
test("serve returns a fetch handler", async () => {
const bknd = createBknd({
mode: "standalone",
options: {
connection: { url: ":memory:" },
adminOptions: { adminBasepath: "/admin" },
}
});
const handler = bknd.serve();
const res = await handler(new Request("http://localhost:3000/api/system/config"));
expect(res.status).toBe(200);
});
test("check admin route", async () => {
const bknd = createBknd({
mode: "standalone",
options: {
connection: { url: ":memory:" },
adminOptions: { adminBasepath: "/admin" },
}
});
const handler = bknd.serve();
const res = await handler(new Request("http://localhost:3000/admin"));
expect(res.status).toBe(200);
});
});
+68
View File
@@ -0,0 +1,68 @@
import {
createFrameworkApp,
createRuntimeApp,
type FrameworkBkndConfig,
type RuntimeBkndConfig,
} from "bknd/adapter";
import { $console } from "core/utils";
import type { App } from "App";
export type AdapterModeWithOptions<Env = Record<string, string | undefined>> =
| {
mode: "standalone";
options: RuntimeBkndConfig<Env>;
}
| {
mode: "api";
options: FrameworkBkndConfig<Env>;
};
export function createBknd<Env>(config: AdapterModeWithOptions<Env>, env?: Env) {
let appPromise: Promise<App> | undefined;
const { mode, options } = config;
async function getApp(): Promise<App> {
if (!appPromise) {
if (mode === "standalone") {
if (options.adminOptions && !options.serveStatic) {
$console.warn(
"adminOptions provided without serveStatic — admin UI assets may not be served. " +
"See `serveStatic`, `serveStaticViaImport`, or add a `package.json` script that runs `bknd copy-assets --out {relative_static_assets_directory_path}`.",
);
}
appPromise = createRuntimeApp(options, env);
} else {
appPromise = createFrameworkApp(options, env);
}
}
return appPromise;
}
async function getApi(opts?: { headers?: Headers; verify?: boolean }) {
const app = await getApp();
if (opts?.verify) {
const api = app.getApi({ headers: opts.headers });
await api.verifyAuth();
return api;
}
return app.getApi(opts?.headers ? { headers: opts.headers } : undefined);
}
function serve() {
return async (req: Request) => {
const app = await getApp();
return app.fetch(req);
};
}
return { getApp, getApi, serve };
}
/** Utility type to determine the config type based on mode,
* Usage `Config<"standalone">` or `Config<"api">`
*/
export type Config<T extends AdapterModeWithOptions["mode"]> = Extract<
Parameters<typeof createBknd>[0],
{ mode: T }
>['options'];
+3 -3
View File
@@ -1,8 +1,8 @@
import type { DB, PrimaryFieldType } from "userbase";
import type { DB, PrimaryFieldType } from "bknd";
import * as AuthPermissions from "auth/auth-permissions";
import type { AuthStrategy } from "auth/authenticate/strategies/Strategy";
import type { PasswordStrategy } from "auth/authenticate/strategies/PasswordStrategy";
import { $console, secureRandomString, transformObject, pickKeys } from "userbase/utils";
import { $console, secureRandomString, transformObject, pickKeys } from "bknd/utils";
import type { Entity, EntityManager } from "data/entities";
import { em, entity, enumm, type FieldSchema } from "data/prototype";
import { Module } from "modules/Module";
@@ -16,7 +16,7 @@ import { Role } from "./authorize/Role";
export type UsersFields = typeof AppAuth.usersFields;
export type UserFieldSchema = FieldSchema<typeof AppAuth.usersFields>;
declare module "userbase" {
declare module "bknd" {
interface Users extends AppEntity, UserFieldSchema {}
interface DB {
users: Users;
+1 -1
View File
@@ -1,6 +1,6 @@
import { AppAuth } from "auth/AppAuth";
import type { CreateUser, SafeUser, User, UserPool } from "auth/authenticate/Authenticator";
import { $console } from "userbase/utils";
import { $console } from "bknd/utils";
import { pick } from "lodash-es";
import {
InvalidConditionsException,
+2 -2
View File
@@ -1,6 +1,6 @@
import type { AuthActionResponse } from "auth/api/AuthController";
import type { AppAuthSchema } from "auth/auth-schema";
import type { AuthResponse, SafeUser, AuthStrategy } from "userbase";
import type { AuthResponse, SafeUser, AuthStrategy } from "bknd";
import { type BaseModuleApiOptions, ModuleApi } from "modules/ModuleApi";
export type AuthApiOptions = BaseModuleApiOptions & {
@@ -69,7 +69,7 @@ export class AuthApi extends ModuleApi<AuthApiOptions> {
async logout() {
return this.get(["logout"], undefined, {
headers: {
// this way userbase detects a json request and doesn't redirect back
// this way bknd detects a json request and doesn't redirect back
Accept: "application/json",
},
}).then(() => this.options.onTokenUpdate?.(undefined, true));
+2 -2
View File
@@ -1,4 +1,4 @@
import type { DB, SafeUser } from "userbase";
import type { DB, SafeUser } from "bknd";
import type { AuthStrategy } from "auth/authenticate/strategies/Strategy";
import type { AppAuth } from "auth/AppAuth";
import * as AuthPermissions from "auth/auth-permissions";
@@ -14,7 +14,7 @@ import {
transformObject,
mcpTool,
$console,
} from "userbase/utils";
} from "bknd/utils";
import type { PasswordStrategy } from "auth/authenticate/strategies";
export type AuthActionResponse = {
+1 -1
View File
@@ -1,7 +1,7 @@
import { cookieConfig, jwtConfig } from "auth/authenticate/Authenticator";
import { CustomOAuthStrategy, OAuthStrategy, PasswordStrategy } from "auth/authenticate/strategies";
import { roleSchema } from "auth/authorize/Role";
import { objectTransform, omitKeys, pick, s } from "userbase/utils";
import { objectTransform, omitKeys, pick, s } from "bknd/utils";
import { $object, $record } from "modules/mcp";
export const Strategies = {
+2 -2
View File
@@ -1,4 +1,4 @@
import type { DB } from "userbase";
import type { DB } from "bknd";
import { Exception } from "core/errors";
import { addFlashMessage } from "core/server/flash";
import type { Context } from "hono";
@@ -7,7 +7,7 @@ import { sign, verify } from "hono/jwt";
import { type CookieOptions, serializeSigned } from "hono/utils/cookie";
import type { ServerEnv } from "modules/Controller";
import { InvalidConditionsException } from "auth/errors";
import { s, parse, secret, runtimeSupports, truncate, $console, pickKeys } from "userbase/utils";
import { s, parse, secret, runtimeSupports, truncate, $console, pickKeys } from "bknd/utils";
import type { AuthStrategy } from "./strategies/Strategy";
type Input = any; // workaround
@@ -1,7 +1,7 @@
import type { User } from "userbase";
import type { User } from "bknd";
import type { Authenticator } from "auth/authenticate/Authenticator";
import { InvalidCredentialsException } from "auth/errors";
import { hash, $console, s, parse, jsc, describeRoute } from "userbase/utils";
import { hash, $console, s, parse, jsc, describeRoute } from "bknd/utils";
import { Hono } from "hono";
import { compare as bcryptCompare, genSalt as bcryptGenSalt, hash as bcryptHash } from "bcryptjs";
import { AuthStrategy } from "./Strategy";
@@ -5,7 +5,7 @@ import type {
StrategyActions,
} from "../Authenticator";
import type { Hono } from "hono";
import { type s, parse } from "userbase/utils";
import { type s, parse } from "bknd/utils";
export type StrategyMode = "form" | "external";
@@ -1,6 +1,6 @@
import type * as oauth from "oauth4webapi";
import { OAuthStrategy } from "./OAuthStrategy";
import { s } from "userbase/utils";
import { s } from "bknd/utils";
type SupportedTypes = "oauth2" | "oidc";
@@ -3,7 +3,7 @@ import { type Context, Hono } from "hono";
import { getSignedCookie, setSignedCookie } from "hono/cookie";
import * as oauth from "oauth4webapi";
import * as issuers from "./issuers";
import { s, filterKeys } from "userbase/utils";
import { s, filterKeys } from "bknd/utils";
import { Exception } from "core/errors";
import { isDebug } from "core/env";
import { AuthStrategy } from "../Strategy";
@@ -37,7 +37,7 @@ export const github: IssuerConfig<GithubUserInfo> = {
try {
const res = await fetch("https://api.github.com/user/emails", {
headers: {
"User-Agent": "userbase", // this is mandatory... *smh*
"User-Agent": "bknd", // this is mandatory... *smh*
Accept: "application/json",
Authorization: `Bearer ${tokenResponse.access_token}`,
},
+2 -2
View File
@@ -1,10 +1,10 @@
import { Exception } from "core/errors";
import { $console, mergeObject, type s } from "userbase/utils";
import { $console, mergeObject, type s } from "bknd/utils";
import type { Permission, PermissionContext } from "auth/authorize/Permission";
import type { Context } from "hono";
import type { ServerEnv } from "modules/Controller";
import type { Role } from "./Role";
import { HttpStatus } from "userbase/utils";
import { HttpStatus } from "bknd/utils";
import type { Policy, PolicySchema } from "./Policy";
import { convert, type ObjectQuery } from "core/object/query/object-query";
+1 -1
View File
@@ -1,4 +1,4 @@
import { s, type ParseOptions, parse, InvalidSchemaError, HttpStatus } from "userbase/utils";
import { s, type ParseOptions, parse, InvalidSchemaError, HttpStatus } from "bknd/utils";
export const permissionOptionsSchema = s
.strictObject({
+1 -1
View File
@@ -1,4 +1,4 @@
import { s, parse, recursivelyReplacePlaceholders } from "userbase/utils";
import { s, parse, recursivelyReplacePlaceholders } from "bknd/utils";
import * as query from "core/object/query/object-query";
export const policySchema = s
+1 -1
View File
@@ -1,4 +1,4 @@
import { s } from "userbase/utils";
import { s } from "bknd/utils";
import { Permission } from "./Permission";
import { Policy, policySchema } from "./Policy";
+1 -1
View File
@@ -1,6 +1,6 @@
import { Exception } from "core/errors";
import { isDebug } from "core/env";
import { HttpStatus } from "userbase/utils";
import { HttpStatus } from "bknd/utils";
export class AuthException extends Exception {
getSafeErrorAndCode() {
+4 -2
View File
@@ -1,4 +1,4 @@
import { $console, patternMatch } from "userbase/utils";
import { $console, patternMatch } from "bknd/utils";
import type { Context } from "hono";
import { createMiddleware } from "hono/factory";
import type { ServerEnv } from "modules/Controller";
@@ -26,7 +26,9 @@ export function shouldSkip(c: Context<ServerEnv>, skip?: (string | RegExp)[]) {
return result;
}
export const auth = (options?: { skip?: (string | RegExp)[] }) =>
export const auth = (options?: {
skip?: (string | RegExp)[];
}) =>
createMiddleware<ServerEnv>(async (c, next) => {
if (!c.get("auth")) {
c.set("auth", {
@@ -1,5 +1,5 @@
import type { Permission, PermissionContext } from "auth/authorize/Permission";
import { $console, threw } from "userbase/utils";
import { $console, threw } from "bknd/utils";
import type { Context, Hono } from "hono";
import type { RouterRoute } from "hono/types";
import { createMiddleware } from "hono/factory";
+1 -1
View File
@@ -4,7 +4,7 @@ import { makeAppFromEnv } from "cli/commands/run";
import { writeFile } from "node:fs/promises";
import c from "picocolors";
import { withConfigOptions } from "cli/utils/options";
import { $console } from "userbase/utils";
import { $console } from "bknd/utils";
export const config: CliCommand = (program) => {
withConfigOptions(program.command("config"))
+8 -8
View File
@@ -5,9 +5,9 @@ import type { CliCommand } from "cli/types";
import { typewriter, wait } from "cli/utils/cli";
import { execAsync, getVersion } from "cli/utils/sys";
import { Option } from "commander";
import { env } from "userbase";
import { env } from "bknd";
import color from "picocolors";
import { overridePackageJson, updateUserbasePackages } from "./npm";
import { overridePackageJson, updateBkndPackages } from "./npm";
import { type Template, templates, type TemplateSetupCtx } from "./templates";
import { createScoped, flush } from "cli/utils/telemetry";
import path from "node:path";
@@ -48,7 +48,7 @@ function errorOutro() {
// biome-ignore lint/suspicious/noConsoleLog:
console.log(
color.yellow("Sorry that this happened. If you think this is a bug, please report it at: ") +
color.cyan("https://github.com/userbase-io/userbase/issues"),
color.cyan("https://github.com/bknd-io/bknd/issues"),
);
// biome-ignore lint/suspicious/noConsoleLog:
console.log("");
@@ -80,12 +80,12 @@ async function action(options: {
const version = await getVersion();
$p.intro(
`👋 Welcome to the ${color.bold(color.cyan("userbase"))} create cli ${color.bold(`v${version}`)}`,
`👋 Welcome to the ${color.bold(color.cyan("bknd"))} create cli ${color.bold(`v${version}`)}`,
);
await $p.stream.message(
(async function* () {
yield* typewriter("Thanks for choosing to create a new project with userbase!", color.dim);
yield* typewriter("Thanks for choosing to create a new project with bknd!", color.dim);
await wait();
})(),
);
@@ -127,7 +127,7 @@ async function action(options: {
? downloadOpts.dir.split("/").pop()
: downloadOpts.dir.replace(/[./]/g, "");
if (!name || name.length === 0) name = "userbase";
if (!name || name.length === 0) name = "bknd";
let template: Template | undefined;
@@ -254,7 +254,7 @@ async function action(options: {
}
s.stop("Template downloaded.");
await updateUserbasePackages(ctx.dir);
await updateBkndPackages(ctx.dir);
if (template.preinstall) {
await template.preinstall(ctx);
@@ -335,7 +335,7 @@ async function action(options: {
yield "\n\n";
yield* typewriter(
`Enter your project's directory using ${color.cyan("cd " + ctx.dir)}
If you need help, check ${color.cyan("https://docs.userbase.io")} or join our Discord!`,
If you need help, check ${color.cyan("https://docs.bknd.io")} or join our Discord!`,
);
await wait(2);
})(),
+2 -2
View File
@@ -92,10 +92,10 @@ export async function replacePackageJsonVersions(
);
}
export async function updateUserbasePackages(dir?: string, map?: Record<string, string>) {
export async function updateBkndPackages(dir?: string, map?: Record<string, string>) {
try {
const versions = {
userbase: await sysGetVersion(),
bknd: await sysGetVersion(),
...(map ?? {}),
};
await replacePackageJsonVersions(
+2 -2
View File
@@ -9,8 +9,8 @@ export const aws = {
key: "aws",
title: "AWS Lambda Basic",
integration: "aws",
description: "A basic userbase AWS Lambda starter",
path: "gh:userbase-io/userbase/examples/aws-lambda",
description: "A basic bknd AWS Lambda starter",
path: "gh:bknd-io/bknd/examples/aws-lambda",
ref: true,
setup: async (ctx) => {
await $p.stream.info(
@@ -11,8 +11,8 @@ export const cloudflare = {
key: "cloudflare",
title: "Cloudflare Basic",
integration: "cloudflare",
description: "A basic userbase Cloudflare worker",
path: "gh:userbase-io/userbase/examples/cloudflare-worker",
description: "A basic bknd Cloudflare worker",
path: "gh:bknd-io/bknd/examples/cloudflare-worker",
ref: true,
setup: async (ctx) => {
// overwrite assets directory & name
@@ -22,7 +22,7 @@ export const cloudflare = {
...json,
name: ctx.name,
assets: {
directory: "node_modules/userbase/dist/static",
directory: "node_modules/bknd/dist/static",
},
}),
{ dir: ctx.dir },
@@ -6,15 +6,15 @@ export const deno = {
key: "deno",
title: "Deno Basic",
integration: "deno",
description: "A basic userbase Deno server with static assets",
path: "gh:userbase-io/userbase/examples/deno",
description: "A basic bknd Deno server with static assets",
path: "gh:bknd-io/bknd/examples/deno",
installDeps: false,
ref: true,
setup: async (ctx) => {
const version = await getVersion();
await overrideJson(
"deno.json",
(json) => ({ ...json, links: undefined, imports: { userbase: `npm:userbase@${version}` } }),
(json) => ({ ...json, links: undefined, imports: { bknd: `npm:bknd@${version}` } }),
{ dir: ctx.dir },
);
},
+13 -13
View File
@@ -33,7 +33,7 @@ export type Template = {
description?: string;
path: string;
/**
* adds a ref "#{ref}" to the path. If "true", adds the current version of userbase
* adds a ref "#{ref}" to the path. If "true", adds the current version of bknd
*/
ref?: true | string;
/**
@@ -53,48 +53,48 @@ export const templates: Template[] = [
key: "node",
title: "Node.js Basic",
integration: "node",
description: "A basic userbase Node.js server",
path: "gh:userbase-io/userbase/examples/node",
description: "A basic bknd Node.js server",
path: "gh:bknd-io/bknd/examples/node",
ref: true,
},
{
key: "bun",
title: "Bun Basic",
integration: "bun",
description: "A basic userbase Bun server",
path: "gh:userbase-io/userbase/examples/bun",
description: "A basic bknd Bun server",
path: "gh:bknd-io/bknd/examples/bun",
ref: true,
},
{
key: "nextjs",
title: "Next.js Basic",
integration: "nextjs",
description: "A basic userbase Next.js starter",
path: "gh:userbase-io/userbase/examples/nextjs",
description: "A basic bknd Next.js starter",
path: "gh:bknd-io/bknd/examples/nextjs",
ref: true,
},
{
key: "astro",
title: "Astro Basic",
integration: "astro",
description: "A basic userbase Astro starter",
path: "gh:userbase-io/userbase/examples/astro",
description: "A basic bknd Astro starter",
path: "gh:bknd-io/bknd/examples/astro",
ref: true,
},
{
key: "react-router",
title: "React Router Basic",
integration: "react-router",
description: "A basic userbase React Router starter",
path: "gh:userbase-io/userbase/examples/react-router",
description: "A basic bknd React Router starter",
path: "gh:bknd-io/bknd/examples/react-router",
ref: true,
},
{
key: "aws",
title: "AWS Lambda Basic",
integration: "aws",
description: "A basic userbase AWS Lambda starter",
path: "gh:userbase-io/userbase/examples/aws-lambda",
description: "A basic bknd AWS Lambda starter",
path: "gh:bknd-io/bknd/examples/aws-lambda",
ref: true,
},
deno,

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