Author SHA1 Message Date
Jonas Perusquia Morales c59dde38b7 chore: Update GitHub Actions versions in test workflow to latest 2026-08-06 12:34:58 -06:00
Jonas Perusquia Morales 7ff8d6aa86 chore: Remove unused tsx dependency 2026-08-06 11:57:22 -06:00
Jonas Perusquia Morales 2cb985f16d chore: Update package dependencies
Removed stale @aws-crypto packages and bumped multiple dependencies
including: @tsdown/css, @types/node, @vitest/coverage-v8, postcss,
tailwindcss, tsdown, vitest, and various AWS SDK packages to their
latest versions.
2026-08-06 11:56:26 -06:00
Jonas Perusquia Morales 1072b1e69a fix: Disable automatic clean to preserve dist/static 2026-08-06 11:47:31 -06:00
Jonas Perusquia Morales 0c37afd595 fix: Fix admin UI manifest loading in Cloudflare Workers
Use static import so the bundler includes the manifest. Dynamic imports
are not resolved by workerd via package.json exports.
2026-07-14 11:44:55 -06:00
Jonas Perusquia Morales 817441f01d chore: add middleware to normalize trailing slashes in routes 2026-07-13 12:39:05 -06:00
Jonas Perusquia Morales f5824efc24 chore: upgrade astro example from v5 to v7 2026-07-10 13:51:50 -06:00
Jonas Perusquia Morales 7231a7a57b chore: Remove unused Card import from Layout 2026-07-10 13:51:27 -06:00
Jonas Perusquia Morales ec29dc5317 chore: Bump dependencies to latest patch versions 2026-06-19 11:22:50 -06:00
Jonas Perusquia Morales 031123988a chore: ugpraded dependencies 2026-06-05 14:39:52 -06:00
Jonas Perusquia Morales 68723c375f fix: deepwiki feedback addressed 2026-05-15 13:31:50 -06:00
Jonas Perusquia Morales a5dd4d4977 chore: upgrade vite related dependencies 2026-05-13 10:44:06 -06:00
Jonas Perusquia Morales 94aad8af56 chore: incremental build 2026-05-08 10:31:36 -06:00
Jonas Perusquia Morales c904e74a4d chore: upgrade tsdown to v0.22.0
- Bumped minimum Node version from 22.13 to 22.18 (tsdown)
2026-05-08 10:31:12 -06:00
Jonas Perusquia Morales 1b92fd21e0 chore: upgrade postcss to latest 2026-05-05 09:27:00 -06:00
Jonas Perusquia Morales 27b294a1b9 chore: remove unused import 2026-04-30 22:52:10 -06:00
Jonas Perusquia Morales a5a350a23a fix: node tests 2026-04-30 10:41:54 -06:00
Jonas Perusquia Morales cd3f51dd10 chore: upgrade vitest from v3 to v4 2026-04-30 10:41:43 -06:00
Jonas Perusquia Morales 140afa7d83 chore: update PostCSS with Tailwind CSS intergation and adjust dependencies 2026-04-29 18:23:36 -06:00
Jonas Perusquia Morales 845afe10e2 fix: update TypeScript type definitions to use .d.mts extension 2026-04-28 10:32:06 -06:00
Jonas Perusquia Morales 93d4caef25 chore: add alias resolution for sqlite adapter in vitest configuration 2026-04-28 10:31:51 -06:00
Jonas Perusquia MoralesandCopilot 821321539f chore: ensure output format is set to esm in buildTypes function
Co-authored-by: Copilot <copilot@github.com>
2026-04-28 10:31:40 -06:00
Jonas Perusquia MoralesandCopilot 8d62186ddc chore: update build configuration to use string format for esm
Co-authored-by: Copilot <copilot@github.com>
2026-04-28 10:31:20 -06:00
Jonas Perusquia Morales f69a56fb18 fix: update BunFile import to use dynamic import syntax 2026-04-28 09:50:59 -06:00
Jonas Perusquia Morales a3f20b1034 chore: update TypeScript output directory for app workspace 2026-04-28 09:50:46 -06:00
Jonas Perusquia Morales 69ecc27d8e chore: update @tsdown/css and tsdown to v0.21.10
chore: update bun types to latest v1.3.13
2026-04-28 09:50:11 -06:00
Jonas Perusquia Morales 5e983ca1bd chore: update bun.lock 2026-04-21 10:19:06 -06:00
Jonás Perusquía Morales c955c962b3 Merge branch 'release/0.21' into chore/migrate-tsup-to-tsdown 2026-04-16 16:29:25 -06:00
Jonas Perusquia Morales fecf53dc25 chore: upgrade tsdown to v0.21.9 2026-04-16 13:36:52 -06:00
Jonas Perusquia Morales 3f0e924f69 chore: format code and improve readability in build.ts 2026-04-16 13:14:36 -06:00
Jonas Perusquia Morales 01e54fcbc9 chore: Bump tsdown and @tsdown/css to 0.21.8 2026-04-15 16:19:05 -06:00
Jonas Perusquia Morales b2bad5a7fb chore: update build process to improve type generation and configuration 2026-04-02 13:01:51 -06:00
Jonas Perusquia Morales 4c2bd9fc01 chore: simplify exclude paths in tsconfig.build.json 2026-04-02 12:54:38 -06:00
Jonas Perusquia Morales 672784503a chore: disable declaration generation in tsdown configuration for cli and plasmic packages 2026-04-02 12:42:22 -06:00
Jonas Perusquia Morales 10c65a8d0e chore: add entry point to buildTypes function and enable declaration in tsconfig 2026-04-01 18:14:43 -06:00
Jonas Perusquia Morales 7f950a041c chore: update buildTypes function configuration for improved type generation 2026-04-01 16:50:35 -06:00
Jonas Perusquia Morales dbcbeff876 chore: disable declaration and declarationMap in tsconfig.json 2026-04-01 16:49:01 -06:00
Jonas Perusquia Morales a19ed5255c chore: update tailwindcss and related dependencies to version 4.2.2 2026-04-01 16:48:48 -06:00
Jonas Perusquia Morales c783125c0f fix: matched alias not found for tailwind-merge 2026-04-01 14:35:47 -06:00
Jonas Perusquia Morales 90195f9209 chore: simplify buildTypes function by removing unused typeEntryGroups and streamlining build options 2026-03-30 13:10:44 -06:00
Jonas Perusquia Morales bea716c1df chore: update postcss dependency to version 8.5.8 2026-03-30 13:07:58 -06:00
Jonas Perusquia Morales 9a4fee48cb chore: add type annotations for MediaEvents and DatabaseEvents exports 2026-03-30 13:07:34 -06:00
Jonas Perusquia Morales 63f2a2fc3f chore: refactor EventRegistryMap type for clarity and update Events getter to use it 2026-03-30 13:07:26 -06:00
Jonas Perusquia Morales 0489058e3c chore: change isSelectQueryBuilder property to readonly in SelectQueryBuilderExpression interface 2026-03-30 13:07:17 -06:00
Jonas Perusquia Morales 13f78ffa83 chore: update Node.js engine requirement and upgrade TypeScript version 2026-03-30 13:06:36 -06:00
Jonas Perusquia Morales 7140351c4b chore: comment out typeEntryGroups and related code in buildTypes function 2026-03-30 11:59:13 -06:00
Jonas Perusquia Morales 2591be2491 chore: re-add clean:types script to remove type declaration files 2026-03-30 11:13:00 -06:00
Jonas Perusquia Morales 6d30e9ec96 chore: update dependencies and migrate from tsup to tsdown in cli and plasmic packages 2026-03-30 11:08:45 -06:00
75 changed files with 1788 additions and 5290 deletions
+3 -3
View File
@@ -25,15 +25,15 @@ jobs:
--health-retries 5 --health-retries 5
steps: steps:
- uses: actions/checkout@v4 - uses: actions/checkout@v7
- name: Setup Node.js - name: Setup Node.js
uses: actions/setup-node@v4 uses: actions/setup-node@v7
with: with:
node-version: "22.x" node-version: "22.x"
- name: Setup Bun - name: Setup Bun
uses: oven-sh/setup-bun@v1 uses: oven-sh/setup-bun@v2
with: with:
bun-version: "1.3.3" bun-version: "1.3.3"
+2 -2
View File
@@ -107,7 +107,7 @@ bknd/
index.ts # Main package exports index.ts # Main package exports
__test__/ # Unit tests (mirrors src/ structure) __test__/ # Unit tests (mirrors src/ structure)
e2e/ # End-to-end tests (Playwright) e2e/ # End-to-end tests (Playwright)
build.ts # Build script (tsup/esbuild) build.ts # Build script (tsdown/rolldown)
build.cli.ts # CLI build script build.cli.ts # CLI build script
packages/ # Small satellite packages packages/ # Small satellite packages
cli/ # Standalone CLI package (bknd-cli) cli/ # Standalone CLI package (bknd-cli)
@@ -146,7 +146,7 @@ Plugins (in `app/src/plugins/`) hook into the app lifecycle via callbacks like `
### Build System ### Build System
The build is handled by a custom `app/build.ts` script using tsup (esbuild under the hood). It builds four targets in parallel: The build is handled by a custom `app/build.ts` script using tsdown (rolldown under the hood). It builds four targets in parallel:
- **API** -- the core backend - **API** -- the core backend
- **UI** -- the admin interface - **UI** -- the admin interface
@@ -7,9 +7,7 @@ import v7 from "./samples/v7.json";
import v8 from "./samples/v8.json"; import v8 from "./samples/v8.json";
import v8_2 from "./samples/v8-2.json"; import v8_2 from "./samples/v8-2.json";
import v9 from "./samples/v9.json"; import v9 from "./samples/v9.json";
import v10 from "./samples/v10.json";
import { disableConsoleLog, enableConsoleLog } from "core/utils/test"; import { disableConsoleLog, enableConsoleLog } from "core/utils/test";
import { CURRENT_VERSION } from "modules/db/migrations";
beforeAll(() => disableConsoleLog()); beforeAll(() => disableConsoleLog());
afterAll(enableConsoleLog); afterAll(enableConsoleLog);
@@ -63,7 +61,7 @@ async function getRawConfig(
return await db return await db
.selectFrom("__bknd") .selectFrom("__bknd")
.selectAll() .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)) .$if((opts?.types?.length ?? 0) > 0, (qb) => qb.where("type", "in", opts?.types))
.execute(); .execute();
} }
@@ -117,6 +115,7 @@ describe("Migrations", () => {
"^^s3.secret_access_key^^", "^^s3.secret_access_key^^",
); );
const [config, secrets] = (await getRawConfig(app, { const [config, secrets] = (await getRawConfig(app, {
version: 10,
types: ["config", "secrets"], types: ["config", "secrets"],
})) as any; })) as any;
@@ -130,15 +129,4 @@ describe("Migrations", () => {
"^^s3.secret_access_key^^", "^^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": {}
}
}
+349 -333
View File
@@ -1,9 +1,9 @@
import { $ } from "bun"; import { build, type UserConfig } from "tsdown";
import * as tsup from "tsup";
import pkg from "./package.json" with { type: "json" }; import pkg from "./package.json" with { type: "json" };
import c from "picocolors"; import c from "picocolors";
import { watch as fsWatch, readdirSync, rmSync } from "node:fs"; import { watch as fsWatch, readdirSync, rmSync } from "node:fs";
import { join } from "node:path"; import { join, resolve } from "node:path";
import { buildTypes as runTypesBuild } from "./build.types";
const args = process.argv.slice(2); const args = process.argv.slice(2);
const watch = args.includes("--watch"); const watch = args.includes("--watch");
@@ -11,18 +11,19 @@ const minify = args.includes("--minify");
const types = args.includes("--types"); const types = args.includes("--types");
const sourcemap = args.includes("--sourcemap"); const sourcemap = args.includes("--sourcemap");
const clean = args.includes("--clean"); const clean = args.includes("--clean");
const dev = args.includes("--dev");
// silence tsup // silence tsdown
const oldConsole = { const oldConsole = {
log: console.log, log: console.log,
warn: console.warn, warn: console.warn,
}; };
console.log = () => {}; console.log = () => { };
console.warn = () => {}; console.warn = () => { };
const define = { const define = {
__isDev: "0", __isDev: "0",
__version: JSON.stringify(pkg.version), __version: JSON.stringify(pkg.version),
}; };
if (clean) { if (clean) {
@@ -36,156 +37,167 @@ if (clean) {
const entryPath = join(distPath, entry); const entryPath = join(distPath, entry);
rmSync(entryPath, { recursive: true, force: true }); rmSync(entryPath, { recursive: true, force: true });
} }
} catch (e) { } catch {
// dist may not exist yet, ignore // dist may not exist yet, ignore
} }
} }
let types_running = false; let types_running = false;
function buildTypes() { async function buildTypes() {
if (types_running || !types) return; if (types_running || !types) return;
types_running = true; types_running = true;
Bun.spawn(["bun", "build:types"], { try {
stdout: "inherit", await runTypesBuild();
onExit: () => {
oldConsole.log(c.cyan("[Types]"), c.green("built")); oldConsole.log(c.cyan("[Types]"), c.green("built"));
Bun.spawn(["bun", "tsc-alias"], { } finally {
stdout: "inherit", types_running = false;
onExit: () => { }
oldConsole.log(c.cyan("[Types]"), c.green("aliased"));
types_running = false;
},
});
},
});
}
if (types && !watch) {
buildTypes();
} }
let watcher_timeout: any; let watcher_timeout: any;
function delayTypes() { function delayTypes(delayTime = 1000) {
if (!watch || !types) return; if (!watch || !types) return;
if (watcher_timeout) { if (watcher_timeout) {
clearTimeout(watcher_timeout); clearTimeout(watcher_timeout);
} }
watcher_timeout = setTimeout(buildTypes, 1000); watcher_timeout = setTimeout(() => {
void buildTypes().catch((error) => {
oldConsole.warn(c.cyan("[Types]"), c.red("build failed"), error);
});
}, delayTime);
} }
const dependencies = Object.keys(pkg.dependencies); const dependencies = Object.keys(pkg.dependencies);
// collection of always-external packages // collection of always-neverBundle packages
const external = [ const neverBundle = [
...dependencies, ...dependencies,
"bun:test", "bun:test",
"node:test", "node:test",
"node:assert/strict", "node:assert/strict",
"@libsql/client", "@libsql/client",
"bknd", "bknd",
/^bknd\/.*/, /^bknd\/.*/,
"jsonv-ts", "jsonv-ts",
/^jsonv-ts\/.*/, /^jsonv-ts\/.*/,
] as const; ] as const;
/** /**
* Building backend and general API * Building backend and general API
*/ */
async function buildApi() { async function buildApi() {
await tsup.build({ await build({
minify, minify,
sourcemap, sourcemap,
// don't use tsup's broken watch, we'll handle it ourselves // don't use tsdown's broken watch, we'll handle it ourselves
watch: false, watch: false,
define, // cleaning is handled manually (--clean) to preserve dist/static
entry: [ clean: false,
"src/index.ts", dts: false,
"src/core/utils/index.ts", define,
"src/plugins/index.ts", entry: [
"src/modes/index.ts", "src/index.ts",
], "src/core/utils/index.ts",
outDir: "dist", "src/plugins/index.ts",
external: [...external], "src/modes/index.ts",
metafile: true, ],
target: "esnext", unbundle: false,
platform: "browser", outDir: "dist",
removeNodeProtocol: false, deps: {
format: ["esm"], neverBundle: [
splitting: false, ...neverBundle
loader: { ],
".svg": "dataurl", },
},
onSuccess: async () => { target: "esnext",
delayTypes(); platform: "browser",
oldConsole.log(c.cyan("[API]"), c.green("built")); nodeProtocol: true,
}, format: "esm",
});
loader: {
".svg": "dataurl",
},
onSuccess: async () => {
delayTypes();
oldConsole.log(c.cyan("[API]"), c.green("built"));
},
});
} }
async function rewriteClient(path: string) { async function rewriteClient(path: string) {
const bundle = await Bun.file(path).text(); const bundle = await Bun.file(path).text();
await Bun.write( await Bun.write(path, '"use client";\n' + bundle.replaceAll("ui/client", "bknd/client"));
path,
'"use client";\n' + bundle.replaceAll("ui/client", "bknd/client"),
);
} }
/** /**
* Building UI for direct imports * Building UI for direct imports
*/ */
async function buildUi() { async function buildUi() {
const base = { const base = {
minify, minify,
sourcemap, sourcemap,
watch: false, watch: false,
define, // cleaning is handled manually (--clean) to preserve dist/static
external: [ clean: false,
...external, dts: false,
"react", define,
"react-dom", css: {
"react/jsx-runtime", transformer: "postcss",
"react/jsx-dev-runtime", postcss: "postcss.config.js",
"use-sync-external-store", minify: true,
/codemirror/, splitting: false
"@xyflow/react", },
"@mantine/core", deps: {
], neverBundle: [
metafile: true, ...neverBundle,
platform: "browser", "react",
format: ["esm"], "react-dom",
splitting: false, "react/jsx-runtime",
bundle: true, "react/jsx-dev-runtime",
treeshake: true, "use-sync-external-store",
loader: { /codemirror/,
".svg": "dataurl", "@xyflow/react",
}, "@mantine/core",
esbuildOptions: (options) => { ],
options.logLevel = "silent"; },
}, devtools: dev,
} satisfies tsup.Options; platform: "browser",
format: "esm",
unbundle: false,
treeshake: true,
loader: {
".svg": "dataurl",
},
await tsup.build({ logLevel: "silent",
...base, } satisfies UserConfig;
entry: ["src/ui/index.ts", "src/ui/main.css", "src/ui/styles.css"],
outDir: "dist/ui",
onSuccess: async () => {
await rewriteClient("./dist/ui/index.js");
delayTypes();
oldConsole.log(c.cyan("[UI]"), c.green("built"));
},
});
await tsup.build({
...base,
entry: ["src/ui/client/index.ts"], await Promise.all([
outDir: "dist/ui/client", build({
onSuccess: async () => { ...base,
await rewriteClient("./dist/ui/client/index.js"); entry: ["src/ui/index.ts", "src/ui/main.css", "src/ui/styles.css"],
delayTypes(); outDir: "dist/ui",
oldConsole.log(c.cyan("[UI]"), "Client", c.green("built")); onSuccess: async () => {
}, await rewriteClient("./dist/ui/index.js");
}); delayTypes();
oldConsole.log(c.cyan("[UI]"), c.green("built"));
},
}),
build({
...base,
entry: ["src/ui/client/index.ts"],
outDir: "dist/ui/client",
onSuccess: async () => {
await rewriteClient("./dist/ui/client/index.js");
delayTypes();
oldConsole.log(c.cyan("[UI]"), "Client", c.green("built"));
},
}),
]);
} }
/** /**
@@ -194,243 +206,247 @@ async function buildUi() {
* - ui/client is external, and after built replaced with "bknd/client" * - ui/client is external, and after built replaced with "bknd/client"
*/ */
async function buildUiElements() { async function buildUiElements() {
await tsup.build({ await build({
minify, minify,
sourcemap, sourcemap,
watch: false, watch: false,
define, // cleaning is handled manually (--clean) to preserve dist/static
entry: ["src/ui/elements/index.ts"], clean: false,
outDir: "dist/ui/elements", dts: false,
external: [ define,
"ui/client", entry: ["src/ui/elements/index.ts"],
"bknd", outDir: "dist/ui/elements",
/^bknd\/.*/, deps: {
"wouter", neverBundle: [
"react", "ui/client",
"react-dom", "bknd",
"react/jsx-runtime", /^bknd\/.*/,
"react/jsx-dev-runtime", "wouter",
"use-sync-external-store", "react",
], "react-dom",
metafile: true, "react/jsx-runtime",
platform: "browser", "react/jsx-dev-runtime",
format: ["esm"], "use-sync-external-store",
splitting: false, ],
bundle: true, },
treeshake: true, platform: "browser",
loader: { format: "esm",
".svg": "dataurl", bundle: true,
}, treeshake: true,
esbuildOptions: (options) => { loader: {
options.alias = { ".svg": "dataurl",
// not important for elements, mock to reduce bundle },
"tailwind-merge": "./src/ui/elements/mocks/tailwind-merge.ts", alias: {
}; // not important for elements, mock to reduce bundle
}, "tailwind-merge": resolve(import.meta.dir, "src/ui/elements/mocks/tailwind-merge.ts"),
onSuccess: async () => { },
await rewriteClient("./dist/ui/elements/index.js");
delayTypes(); onSuccess: async () => {
oldConsole.log(c.cyan("[UI]"), "Elements", c.green("built")); await rewriteClient("./dist/ui/elements/index.js");
}, delayTypes();
}); oldConsole.log(c.cyan("[UI]"), "Elements", c.green("built"));
},
});
} }
/** /**
* Building adapters * Building adapters
*/ */
function baseConfig( function baseConfig(adapter: string, overrides: Partial<UserConfig> = {}): UserConfig {
adapter: string, return {
overrides: Partial<tsup.Options> = {}, minify,
): tsup.Options { sourcemap,
return { watch: false,
minify, // cleaning is handled manually (--clean) to preserve dist/static
sourcemap, clean: false,
watch: false, dts: false,
entry: [`src/adapter/${adapter}/index.ts`], entry: [`src/adapter/${adapter}/index.ts`],
format: ["esm"], format: "esm",
platform: "neutral", platform: "neutral",
outDir: `dist/adapter/${adapter}`, outDir: `dist/adapter/${adapter}`,
metafile: true, devtools: dev,
splitting: false, nodeProtocol: true,
removeNodeProtocol: false, onSuccess: async () => {
onSuccess: async () => { delayTypes();
delayTypes(); oldConsole.log(c.cyan("[Adapter]"), adapter || "base", c.green("built"));
oldConsole.log(c.cyan("[Adapter]"), adapter || "base", c.green("built")); },
}, ...overrides,
...overrides, define: {
define: { ...define,
...define, ...overrides.define,
...overrides.define, },
}, deps: {
external: [ neverBundle: [
/^cloudflare*/, /^cloudflare*/,
/^@?hono.*?/, /^@?hono.*?/,
/^(bknd|react|next|node).*?/, /^(bknd|react|next|node).*?/,
/.*\.(html)$/, /.*\.(html)$/,
...external, ...neverBundle,
...(Array.isArray(overrides.external) ? overrides.external : []), ...(Array.isArray(overrides.deps?.neverBundle) ? overrides.deps.neverBundle : []),
], ],
}; },
};
} }
async function buildAdapters() { async function buildAdapters() {
await Promise.all([ await Promise.all([
// base adapter handles // base adapter handles
tsup.build({ build({
...baseConfig(""), ...baseConfig(""),
target: "esnext", target: "esnext",
platform: "neutral", platform: "neutral",
entry: ["src/adapter/index.ts"], entry: ["src/adapter/index.ts"],
outDir: "dist/adapter", outDir: "dist/adapter",
// only way to keep @vite-ignore comments // only way to keep @vite-ignore comments
minify: false, minify: false,
}), dts: false,
// specific adatpers
tsup.build(baseConfig("react-router")),
tsup.build(
baseConfig("browser", {
external: [/^sqlocal\/?.*?/, "wouter"],
}), }),
),
tsup.build( // specific adapters
baseConfig("bun", { build(baseConfig("react-router")),
external: [/^bun\:.*/], build(
baseConfig("browser", {
deps: {
neverBundle: [/^sqlocal\/?.*?/, "wouter"],
},
}),
),
build(
baseConfig("bun", {
deps: {
neverBundle: [/^bun:.*/],
},
}),
),
build(baseConfig("astro")),
build(baseConfig("aws")),
build(
baseConfig("cloudflare", {
deps: {
neverBundle: ["wrangler", "node:process", "miniflare"],
},
}),
),
build(
baseConfig("cloudflare/proxy", {
target: "esnext",
entry: ["src/adapter/cloudflare/proxy.ts"],
outDir: "dist/adapter/cloudflare",
devtools: false,
deps: {
neverBundle: [/bknd/, "wrangler", "node:process", "miniflare"],
},
}),
),
build({
...baseConfig("vite"),
platform: "node",
}), }),
),
tsup.build(baseConfig("astro")), build({
tsup.build(baseConfig("aws")), ...baseConfig("nextjs"),
tsup.build( platform: "node",
baseConfig("cloudflare", {
external: ["wrangler", "node:process"],
}), }),
),
tsup.build( build({
baseConfig("cloudflare/proxy", { ...baseConfig("tanstack-start"),
target: "esnext", platform: "node",
entry: ["src/adapter/cloudflare/proxy.ts"],
outDir: "dist/adapter/cloudflare",
metafile: false,
external: [/bknd/, "wrangler", "node:process"],
}), }),
),
tsup.build({ build({
...baseConfig("vite"), ...baseConfig("sveltekit"),
platform: "node", platform: "node",
}), }),
tsup.build({ build({
...baseConfig("nextjs"), ...baseConfig("nuxt"),
platform: "node", platform: "node",
}), }),
tsup.build({ build({
...baseConfig("tanstack-start"), ...baseConfig("node"),
platform: "node", platform: "node",
}), }),
tsup.build({ build({
...baseConfig("sveltekit"), ...baseConfig("sqlite/edge"),
platform: "node", entry: ["src/adapter/sqlite/edge.ts"],
}), outDir: "dist/adapter/sqlite",
devtools: false,
}),
tsup.build({ build({
...baseConfig("nuxt"), ...baseConfig("sqlite/node"),
platform: "node", entry: ["src/adapter/sqlite/node.ts"],
}), outDir: "dist/adapter/sqlite",
platform: "node",
devtools: false,
}),
tsup.build({ build(
...baseConfig("node"), baseConfig("sqlite/bun", {
platform: "node", entry: ["src/adapter/sqlite/bun.ts"],
}), outDir: "dist/adapter/sqlite",
devtools: false,
tsup.build({ deps: {
...baseConfig("solid-start"), neverBundle: [/^bun:.*/],
platform: "node", },
}), }),
),
tsup.build({ ]);
...baseConfig("sqlite/edge"),
entry: ["src/adapter/sqlite/edge.ts"],
outDir: "dist/adapter/sqlite",
metafile: false,
}),
tsup.build({
...baseConfig("sqlite/node"),
entry: ["src/adapter/sqlite/node.ts"],
outDir: "dist/adapter/sqlite",
platform: "node",
metafile: false,
}),
tsup.build({
...baseConfig("sqlite/bun"),
entry: ["src/adapter/sqlite/bun.ts"],
outDir: "dist/adapter/sqlite",
metafile: false,
external: [/^bun\:.*/],
}),
]);
} }
async function buildAll() { const buildPipeline = [buildApi, buildUi, buildUiElements, buildAdapters];
await Promise.all([
buildApi(), // Run type generation in parallel, since it can be slow and doesn't block the main build
buildUi(), if (types) {
buildUiElements(), buildPipeline.push(async () => await buildTypes());
buildAdapters(),
]);
} }
// initial build // initial build
await buildAll(); await buildAll();
// custom watcher since tsup's watch is broken in 8.3.5+ async function buildAll() {
await Promise.all(buildPipeline.map(fn => fn()));
}
// custom watcher since tsdown's watch is broken in v0.21.7
if (watch) { if (watch) {
oldConsole.log(c.cyan("[Watch]"), "watching for changes in src/..."); oldConsole.log(c.cyan("[Watch]"), "watching for changes in src/...");
let debounceTimer: ReturnType<typeof setTimeout> | null = null; let debounceTimer: ReturnType<typeof setTimeout> | null = null;
let isBuilding = false; let isBuilding = false;
const rebuild = async () => { const rebuild = async () => {
if (isBuilding) return; if (isBuilding) return;
isBuilding = true; isBuilding = true;
oldConsole.log(c.cyan("[Watch]"), "rebuilding..."); oldConsole.log(c.cyan("[Watch]"), "rebuilding...");
try { try {
await buildAll(); await buildAll();
oldConsole.log(c.cyan("[Watch]"), c.green("done")); oldConsole.log(c.cyan("[Watch]"), c.green("done"));
} catch (e) { } catch (e) {
oldConsole.warn(c.cyan("[Watch]"), c.red("build failed"), e); oldConsole.warn(c.cyan("[Watch]"), c.red("build failed"), e);
} }
isBuilding = false; isBuilding = false;
}; };
const debouncedRebuild = () => { const debouncedRebuild = () => {
if (debounceTimer) clearTimeout(debounceTimer); if (debounceTimer) clearTimeout(debounceTimer);
debounceTimer = setTimeout(rebuild, 100); debounceTimer = setTimeout(rebuild, 100);
}; };
// watch src directory recursively // watch src directory recursively
fsWatch( fsWatch(join(import.meta.dir, "src"), { recursive: true }, (event, filename) => {
join(import.meta.dir, "src"),
{ recursive: true },
(event, filename) => {
if (!filename) return; if (!filename) return;
// ignore non-source files // ignore non-source files
if ( if (!filename.endsWith(".ts") && !filename.endsWith(".tsx") && !filename.endsWith(".css"))
!filename.endsWith(".ts") && return;
!filename.endsWith(".tsx") &&
!filename.endsWith(".css")
)
return;
oldConsole.log(c.cyan("[Watch]"), c.dim(`${event}: ${filename}`)); oldConsole.log(c.cyan("[Watch]"), c.dim(`${event}: ${filename}`));
debouncedRebuild(); debouncedRebuild();
}, });
);
// keep process alive // keep process alive
await new Promise(() => {}); await new Promise(() => { });
} }
+35
View File
@@ -0,0 +1,35 @@
import { build } from "tsdown";
import c from "picocolors";
export async function buildTypes() {
await build({
tsconfig: "tsconfig.build.json",
watch: false,
clean: true,
logLevel: "silent",
unbundle: true,
root: "src",
outDir: "dist/types",
entry: ["./src/**/*.ts", "./src/**/*.tsx"],
format: "esm",
dts: {
emitDtsOnly: true,
resolver: "oxc",
eager: true,
incremental: true,
},
deps: {
skipNodeModulesBundle: true
},
});
}
if (import.meta.main) {
try {
await buildTypes();
console.log(c.cyan("[Types]"), c.green("built"));
} catch (error) {
console.error(c.cyan("[Types]"), c.red("build failed"), error);
process.exitCode = 1;
}
}
-3
View File
@@ -18,9 +18,6 @@ const configs = {
nuxt: { nuxt: {
base_path: "/admin", base_path: "/admin",
}, },
"solid-start": {
base_path: "/admin",
},
astro: { astro: {
base_path: "/admin", base_path: "/admin",
}, },
+108 -86
View File
@@ -15,7 +15,8 @@
}, },
"packageManager": "bun@1.3.3", "packageManager": "bun@1.3.3",
"engines": { "engines": {
"node": ">=22.13" "node": ">=22.18.0",
"bun": ">=1.3.3"
}, },
"scripts": { "scripts": {
"dev": "BKND_CLI_LOG_LEVEL=debug vite", "dev": "BKND_CLI_LOG_LEVEL=debug vite",
@@ -23,11 +24,11 @@
"build:all": "rm -rf dist && bun run build:static && NODE_ENV=production bun run build.ts --minify --types --clean && bun run build:cli", "build:all": "rm -rf dist && bun run build:static && NODE_ENV=production bun run build.ts --minify --types --clean && bun run build:cli",
"build:ci": "mkdir -p dist/static/.vite && echo '{}' > dist/static/.vite/manifest.json && NODE_ENV=production bun run build.ts", "build:ci": "mkdir -p dist/static/.vite && echo '{}' > dist/static/.vite/manifest.json && NODE_ENV=production bun run build.ts",
"build:cli": "bun run build.cli.ts", "build:cli": "bun run build.cli.ts",
"build:types": "bun run build.types.ts",
"build:static": "vite build", "build:static": "vite build",
"watch": "bun run build.ts --types --watch", "watch": "bun run build.ts --types --watch",
"types": "bun tsc -p tsconfig.build.json --noEmit", "types": "bun tsc -p tsconfig.build.json --noEmit",
"clean:types": "find ./dist -name '*.d.ts' -delete && rm -f ./dist/tsconfig.tsbuildinfo", "clean:types": "find ./dist -name '*.d.ts' -delete && rm -f ./dist/tsconfig.tsbuildinfo",
"build:types": "tsc -p tsconfig.build.json --emitDeclarationOnly && tsc-alias",
"updater": "bun x npm-check-updates -ui", "updater": "bun x npm-check-updates -ui",
"cli": "LOCAL=1 bun src/cli/index.ts", "cli": "LOCAL=1 bun src/cli/index.ts",
"prepublishOnly": "bun run types && bun run test && bun run test:node && NODE_NO_WARNINGS=1 VITE_DB_URL=:memory: bun run test:e2e && bun run build:all && cp ../README.md ./", "prepublishOnly": "bun run types && bun run test && bun run test:node && NODE_NO_WARNINGS=1 VITE_DB_URL=:memory: bun run test:e2e && bun run build:all && cp ../README.md ./",
@@ -93,17 +94,18 @@
"@rjsf/utils": "5.22.0", "@rjsf/utils": "5.22.0",
"@standard-schema/spec": "^1.0.0", "@standard-schema/spec": "^1.0.0",
"@tabler/icons-react": "3.35.0", "@tabler/icons-react": "3.35.0",
"@tailwindcss/postcss": "^4.1.16", "@tailwindcss/postcss": "^4.2.2",
"@tailwindcss/vite": "^4.1.16", "@tailwindcss/vite": "^4.2.4",
"@tanstack/react-store": "^0.8.0", "@tanstack/react-store": "^0.8.0",
"@testing-library/jest-dom": "^6.6.3", "@testing-library/jest-dom": "^6.6.3",
"@testing-library/react": "^16.2.0", "@testing-library/react": "^16.2.0",
"@types/node": "^24.10.0", "@tsdown/css": "^0.22.14",
"@types/node": "^24.13.3",
"@types/pg": "^8.15.6", "@types/pg": "^8.15.6",
"@types/react": "^19.0.10", "@types/react": "^19.2.16",
"@types/react-dom": "^19.0.4", "@types/react-dom": "^19.0.4",
"@vitejs/plugin-react": "^5.1.0", "@vitejs/plugin-react": "^6.0.2",
"@vitest/coverage-v8": "3.0.9", "@vitest/coverage-v8": "4.1.10",
"autoprefixer": "^10.4.21", "autoprefixer": "^10.4.21",
"clsx": "^2.1.1", "clsx": "^2.1.1",
"commander": "^14.0.2", "commander": "^14.0.2",
@@ -114,89 +116,87 @@
"kysely-postgres-js": "^2.0.0", "kysely-postgres-js": "^2.0.0",
"libsql": "^0.5.22", "libsql": "^0.5.22",
"libsql-stateless-easy": "^1.8.0", "libsql-stateless-easy": "^1.8.0",
"miniflare": "^4.20251011.2", "miniflare": "^4.20260317.3",
"open": "^10.2.0", "open": "^10.2.0",
"openapi-types": "^12.1.3", "openapi-types": "^12.1.3",
"pg": "^8.16.3", "pg": "^8.16.3",
"postcss": "^8.5.3", "postcss": "^8.5.26",
"postcss-import": "^16.1.1",
"postcss-preset-mantine": "^1.18.0", "postcss-preset-mantine": "^1.18.0",
"postcss-simple-vars": "^7.0.1", "postcss-simple-vars": "^7.0.1",
"postgres": "^3.4.7", "postgres": "^3.4.7",
"posthog-js-lite": "^3.6.0", "posthog-js-lite": "^3.6.0",
"react": "^19.0.0", "react": "^19.2.7",
"react-dom": "^19.0.0", "react-dom": "^19.2.7",
"react-hook-form": "^7.66.0", "react-hook-form": "^7.66.0",
"react-icons": "5.5.0", "react-icons": "5.5.0",
"react-json-view-lite": "^2.5.0", "react-json-view-lite": "^2.5.0",
"sql-formatter": "^15.6.10", "sql-formatter": "^15.6.10",
"sqlocal": "^0.16.0", "sqlocal": "^0.16.0",
"tailwind-merge": "^3.0.2", "tailwind-merge": "^3.0.2",
"tailwindcss": "^4.1.16", "tailwindcss": "^4.3.3",
"tailwindcss-animate": "^1.0.7", "tailwindcss-animate": "^1.0.7",
"tsc-alias": "^1.8.16", "tsdown": "^0.22.14",
"tsup": "^8.5.0",
"tsx": "^4.20.6",
"uuid": "^13.0.0", "uuid": "^13.0.0",
"vite": "^7.1.12", "vite": "^8.0.16",
"vite-plugin-circular-dependency": "^0.5.0", "vite-plugin-circular-dependency": "^0.6.0",
"vite-tsconfig-paths": "^5.1.4", "vitest": "4.1.10",
"vitest": "3.0.9",
"wouter": "^3.7.1", "wouter": "^3.7.1",
"wrangler": "^4.45.4" "wrangler": "^4.78.0"
}, },
"optionalDependencies": { "optionalDependencies": {
"@hono/node-server": "^1.19.6" "@hono/node-server": "^1.19.6"
}, },
"peerDependencies": { "peerDependencies": {
"react": ">=19", "react": ">=19.2.6",
"react-dom": ">=19" "react-dom": ">=19.2.6"
}, },
"main": "./dist/index.js", "main": "./dist/index.js",
"module": "./dist/index.js", "module": "./dist/index.js",
"types": "./dist/types/index.d.ts", "types": "./dist/types/index.d.mts",
"exports": { "exports": {
".": { ".": {
"types": "./dist/types/index.d.ts", "types": "./dist/types/index.d.mts",
"import": "./dist/index.js", "import": "./dist/index.js",
"require": "./dist/index.js" "require": "./dist/index.js"
}, },
"./ui": { "./ui": {
"types": "./dist/types/ui/index.d.ts", "types": "./dist/types/ui/index.d.mts",
"import": "./dist/ui/index.js", "import": "./dist/ui/index.js",
"require": "./dist/ui/index.js" "require": "./dist/ui/index.js"
}, },
"./elements": { "./elements": {
"types": "./dist/types/ui/elements/index.d.ts", "types": "./dist/types/ui/elements/index.d.mts",
"import": "./dist/ui/elements/index.js", "import": "./dist/ui/elements/index.js",
"require": "./dist/ui/elements/index.js" "require": "./dist/ui/elements/index.js"
}, },
"./client": { "./client": {
"types": "./dist/types/ui/client/index.d.ts", "types": "./dist/types/ui/client/index.d.mts",
"import": "./dist/ui/client/index.js", "import": "./dist/ui/client/index.js",
"require": "./dist/ui/client/index.js" "require": "./dist/ui/client/index.js"
}, },
"./utils": { "./utils": {
"types": "./dist/types/core/utils/index.d.ts", "types": "./dist/types/core/utils/index.d.mts",
"import": "./dist/core/utils/index.js", "import": "./dist/core/utils/index.js",
"require": "./dist/core/utils/index.js" "require": "./dist/core/utils/index.js"
}, },
"./cli": { "./cli": {
"types": "./dist/types/cli/index.d.ts", "types": "./dist/types/cli/index.d.mts",
"import": "./dist/cli/index.js", "import": "./dist/cli/index.js",
"require": "./dist/cli/index.js" "require": "./dist/cli/index.js"
}, },
"./plugins": { "./plugins": {
"types": "./dist/types/plugins/index.d.ts", "types": "./dist/types/plugins/index.d.mts",
"import": "./dist/plugins/index.js", "import": "./dist/plugins/index.js",
"require": "./dist/plugins/index.js" "require": "./dist/plugins/index.js"
}, },
"./modes": { "./modes": {
"types": "./dist/types/modes/index.d.ts", "types": "./dist/types/modes/index.d.mts",
"import": "./dist/modes/index.js", "import": "./dist/modes/index.js",
"require": "./dist/modes/index.js" "require": "./dist/modes/index.js"
}, },
"./adapter/sqlite": { "./adapter/sqlite": {
"types": "./dist/types/adapter/sqlite/edge.d.ts", "types": "./dist/types/adapter/sqlite/edge.d.mts",
"import": { "import": {
"workerd": "./dist/adapter/sqlite/edge.js", "workerd": "./dist/adapter/sqlite/edge.js",
"edge-light": "./dist/adapter/sqlite/edge.js", "edge-light": "./dist/adapter/sqlite/edge.js",
@@ -204,107 +204,130 @@
"vercel": "./dist/adapter/sqlite/edge.js", "vercel": "./dist/adapter/sqlite/edge.js",
"browser": "./dist/adapter/sqlite/edge.js", "browser": "./dist/adapter/sqlite/edge.js",
"bun": "./dist/adapter/sqlite/bun.js", "bun": "./dist/adapter/sqlite/bun.js",
"node": "./dist/adapter/sqlite/node.js", "node": "./dist/adapter/sqlite/node.mjs",
"default": "./dist/adapter/sqlite/node.js" "default": "./dist/adapter/sqlite/node.mjs"
}, },
"require": "./dist/adapter/sqlite/node.js" "require": "./dist/adapter/sqlite/node.mjs"
}, },
"./adapter/cloudflare": { "./adapter/cloudflare": {
"types": "./dist/types/adapter/cloudflare/index.d.ts", "types": "./dist/types/adapter/cloudflare/index.d.mts",
"import": "./dist/adapter/cloudflare/index.js", "import": "./dist/adapter/cloudflare/index.js",
"require": "./dist/adapter/cloudflare/index.js" "require": "./dist/adapter/cloudflare/index.js"
}, },
"./adapter/cloudflare/proxy": { "./adapter/cloudflare/proxy": {
"types": "./dist/types/adapter/cloudflare/proxy.d.ts", "types": "./dist/types/adapter/cloudflare/proxy.d.mts",
"import": "./dist/adapter/cloudflare/proxy.js", "import": "./dist/adapter/cloudflare/proxy.js",
"require": "./dist/adapter/cloudflare/proxy.js" "require": "./dist/adapter/cloudflare/proxy.js"
}, },
"./adapter": { "./adapter": {
"types": "./dist/types/adapter/index.d.ts", "types": "./dist/types/adapter/index.d.mts",
"import": "./dist/adapter/index.js" "import": "./dist/adapter/index.js"
}, },
"./adapter/vite": { "./adapter/vite": {
"types": "./dist/types/adapter/vite/index.d.ts", "types": "./dist/types/adapter/vite/index.d.mts",
"import": "./dist/adapter/vite/index.js", "import": "./dist/adapter/vite/index.mjs",
"require": "./dist/adapter/vite/index.js" "require": "./dist/adapter/vite/index.mjs"
}, },
"./adapter/nextjs": { "./adapter/nextjs": {
"types": "./dist/types/adapter/nextjs/index.d.ts", "types": "./dist/types/adapter/nextjs/index.d.mts",
"import": "./dist/adapter/nextjs/index.js", "import": "./dist/adapter/nextjs/index.mjs",
"require": "./dist/adapter/nextjs/index.js" "require": "./dist/adapter/nextjs/index.mjs"
}, },
"./adapter/nuxt": { "./adapter/nuxt": {
"types": "./dist/types/adapter/nuxt/index.d.ts", "types": "./dist/types/adapter/nuxt/index.d.mts",
"import": "./dist/adapter/nuxt/index.js", "import": "./dist/adapter/nuxt/index.mjs",
"require": "./dist/adapter/nuxt/index.js" "require": "./dist/adapter/nuxt/index.mjs"
}, },
"./adapter/react-router": { "./adapter/react-router": {
"types": "./dist/types/adapter/react-router/index.d.ts", "types": "./dist/types/adapter/react-router/index.d.mts",
"import": "./dist/adapter/react-router/index.js", "import": "./dist/adapter/react-router/index.js",
"require": "./dist/adapter/react-router/index.js" "require": "./dist/adapter/react-router/index.js"
}, },
"./adapter/bun": { "./adapter/bun": {
"types": "./dist/types/adapter/bun/index.d.ts", "types": "./dist/types/adapter/bun/index.d.mts",
"import": "./dist/adapter/bun/index.js", "import": "./dist/adapter/bun/index.js",
"require": "./dist/adapter/bun/index.js" "require": "./dist/adapter/bun/index.js"
}, },
"./adapter/node": { "./adapter/node": {
"types": "./dist/types/adapter/node/index.d.ts", "types": "./dist/types/adapter/node/index.d.mts",
"import": "./dist/adapter/node/index.js", "import": "./dist/adapter/node/index.mjs",
"require": "./dist/adapter/node/index.js" "require": "./dist/adapter/node/index.mjs"
}, },
"./adapter/astro": { "./adapter/astro": {
"types": "./dist/types/adapter/astro/index.d.ts", "types": "./dist/types/adapter/astro/index.d.mts",
"import": "./dist/adapter/astro/index.js", "import": "./dist/adapter/astro/index.js",
"require": "./dist/adapter/astro/index.js" "require": "./dist/adapter/astro/index.js"
}, },
"./adapter/sveltekit": { "./adapter/sveltekit": {
"types": "./dist/types/adapter/sveltekit/index.d.ts", "types": "./dist/types/adapter/sveltekit/index.d.mts",
"import": "./dist/adapter/sveltekit/index.js", "import": "./dist/adapter/sveltekit/index.mjs",
"require": "./dist/adapter/sveltekit/index.js" "require": "./dist/adapter/sveltekit/index.mjs"
},
"./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": { "./adapter/aws": {
"types": "./dist/types/adapter/aws/index.d.ts", "types": "./dist/types/adapter/aws/index.d.mts",
"import": "./dist/adapter/aws/index.js", "import": "./dist/adapter/aws/index.js",
"require": "./dist/adapter/aws/index.js" "require": "./dist/adapter/aws/index.js"
}, },
"./adapter/browser": { "./adapter/browser": {
"types": "./dist/types/adapter/browser/index.d.ts", "types": "./dist/types/adapter/browser/index.d.mts",
"import": "./dist/adapter/browser/index.js", "import": "./dist/adapter/browser/index.js",
"require": "./dist/adapter/browser/index.js" "require": "./dist/adapter/browser/index.js"
}, },
"./adapter/tanstack-start": { "./adapter/tanstack-start": {
"types": "./dist/types/adapter/tanstack-start/index.d.ts", "types": "./dist/types/adapter/tanstack-start/index.d.mts",
"import": "./dist/adapter/tanstack-start/index.js", "import": "./dist/adapter/tanstack-start/index.mjs",
"require": "./dist/adapter/tanstack-start/index.js" "require": "./dist/adapter/tanstack-start/index.mjs"
}, },
"./dist/main.css": "./dist/ui/main.css", "./dist/main.css": "./dist/ui/style.css",
"./dist/styles.css": "./dist/ui/styles.css", "./dist/styles.css": "./dist/ui/style.css",
"./dist/style.css": "./dist/ui/style.css",
"./dist/manifest.json": "./dist/static/.vite/manifest.json", "./dist/manifest.json": "./dist/static/.vite/manifest.json",
"./static/*": "./dist/static/*" "./static/*": "./dist/static/*"
}, },
"typesVersions": { "typesVersions": {
"*": { "*": {
"utils": ["./dist/types/core/utils/index.d.ts"], "utils": [
"cli": ["./dist/types/cli/index.d.ts"], "./dist/types/core/utils/index.d.mts"
"plugins": ["./dist/types/plugins/index.d.ts"], ],
"adapter": ["./dist/types/adapter/index.d.ts"], "cli": [
"adapter/cloudflare": ["./dist/types/adapter/cloudflare/index.d.ts"], "./dist/types/cli/index.d.mts"
"adapter/vite": ["./dist/types/adapter/vite/index.d.ts"], ],
"adapter/nextjs": ["./dist/types/adapter/nextjs/index.d.ts"], "plugins": [
"adapter/nuxt": ["./dist/types/adapter/nuxt/index.d.ts"], "./dist/types/plugins/index.d.mts"
"adapter/react-router": ["./dist/types/adapter/react-router/index.d.ts"], ],
"adapter/bun": ["./dist/types/adapter/bun/index.d.ts"], "adapter": [
"adapter/node": ["./dist/types/adapter/node/index.d.ts"], "./dist/types/adapter/index.d.mts"
"adapter/sveltekit": ["./dist/types/adapter/sveltekit/index.d.ts"], ],
"adapter/tanstack-start": ["./dist/types/adapter/tanstack-start/index.d.ts"], "adapter/cloudflare": [
"adapter/solid-start": ["./dist/types/adapter/solid-start/index.d.ts"], "./dist/types/adapter/cloudflare/index.d.mts"
"adapter/sqlite": ["./dist/types/adapter/sqlite/edge.d.ts"] ],
"adapter/vite": [
"./dist/types/adapter/vite/index.d.mts"
],
"adapter/nextjs": [
"./dist/types/adapter/nextjs/index.d.mts"
],
"adapter/nuxt": [
"./dist/types/adapter/nuxt/index.d.mts"
],
"adapter/react-router": [
"./dist/types/adapter/react-router/index.d.mts"
],
"adapter/bun": [
"./dist/types/adapter/bun/index.d.mts"
],
"adapter/node": [
"./dist/types/adapter/node/index.d.mts"
],
"adapter/sveltekit": [
"./dist/types/adapter/sveltekit/index.d.mts"
],
"adapter/tanstack-start": [
"./dist/types/adapter/tanstack-start/index.d.mts"
],
"adapter/sqlite": [
"./dist/types/adapter/sqlite/edge.d.mts"
]
} }
}, },
"publishConfig": { "publishConfig": {
@@ -337,7 +360,6 @@
"sveltekit", "sveltekit",
"svelte", "svelte",
"bun", "bun",
"node", "node"
"solid-start"
] ]
} }
@@ -8,6 +8,12 @@ import { $console } from "bknd/utils";
import { createRuntimeApp } from "bknd/adapter"; import { createRuntimeApp } from "bknd/adapter";
import { registerAsyncsExecutionContext, makeConfig, type CloudflareContext } from "./config"; import { registerAsyncsExecutionContext, makeConfig, type CloudflareContext } from "./config";
// Statically import the admin UI build manifest so the bundler (wrangler/esbuild)
// resolves and bundles it at build time, rather than leaving a runtime dynamic
// import that workerd cannot resolve via package.json exports maps.
// @ts-ignore
import adminUiManifest from "bknd/dist/manifest.json";
declare global { declare global {
namespace Cloudflare { namespace Cloudflare {
interface Env {} interface Env {}
@@ -38,6 +44,19 @@ export async function createApp<Env extends CloudflareEnv = CloudflareEnv>(
ctx: Partial<CloudflareContext<Env>> = {}, ctx: Partial<CloudflareContext<Env>> = {},
) { ) {
const appConfig = await makeConfig(config, ctx); const appConfig = await makeConfig(config, ctx);
// The AdminController can't dynamically import "bknd/dist/manifest.json"
// at runtime in the Workers runtime (workerd ignores package.json exports
// for runtime imports). Statically import it here so esbuild bundles the
// manifest into the Worker and pass it as the admin controller's manifest
// unless the caller explicitly provides one (or disables the admin).
if (appConfig.adminOptions !== false && !(appConfig.adminOptions as any)?.manifest) {
appConfig.adminOptions = {
...(appConfig.adminOptions as any),
manifest: adminUiManifest,
};
}
return await createRuntimeApp<Env>( return await createRuntimeApp<Env>(
{ {
...appConfig, ...appConfig,
-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 { SolidStartBkndConfig } from "./solid-start.adapter";
beforeAll(disableConsoleLog);
afterAll(enableConsoleLog);
describe("solid-start adapter", () => {
adapterTestSuite<SolidStartBkndConfig>(bunTestRunner, {
makeApp: solidStart.getApp,
makeHandler: solidStart.serve,
});
});
@@ -1,31 +0,0 @@
import { createRuntimeApp, type RuntimeBkndConfig } from "bknd/adapter";
export type SolidStartEnv = NodeJS.ProcessEnv;
export type SolidStartBkndConfig<Env = SolidStartEnv> = RuntimeBkndConfig<Env>;
/**
* Get bknd app instance
* @param config - bknd configuration
* @param args - environment variables
*/
export async function getApp<Env = SolidStartEnv>(
config: SolidStartBkndConfig<Env>,
args: Env = process.env as Env,
) {
return await createRuntimeApp(config, args);
}
/**
* Create middleware handler for Solid Start
* @param config - bknd configuration
* @param args - environment variables
*/
export function serve<Env = SolidStartEnv>(
config: SolidStartBkndConfig<Env> = {},
args: Env = process.env as Env,
) {
return async (req: Request) => {
const app = await getApp(config, args);
return app.fetch(req);
};
}
+7 -1
View File
@@ -14,6 +14,12 @@ export interface EmitsEvents {
emgr: EventManager; emgr: EventManager;
} }
export type EventRegistryMap<
RegisteredEvents extends Record<string, EventClass> = Record<string, EventClass>,
> = {
[K in keyof RegisteredEvents]: RegisteredEvents[K];
};
// for compatibility, moved it to Event.ts // for compatibility, moved it to Event.ts
export type { EventClass }; export type { EventClass };
@@ -65,7 +71,7 @@ export class EventManager<
return [...this.listeners]; return [...this.listeners];
} }
get Events(): { [K in keyof RegisteredEvents]: RegisteredEvents[K] } { get Events(): EventRegistryMap<RegisteredEvents> {
// proxy class to access events // proxy class to access events
return new Proxy(this, { return new Proxy(this, {
get: (_, prop: string) => { get: (_, prop: string) => {
+1 -1
View File
@@ -31,7 +31,7 @@ export type IndexMetadata = {
}; };
export interface SelectQueryBuilderExpression<O> extends AliasableExpression<O> { export interface SelectQueryBuilderExpression<O> extends AliasableExpression<O> {
get isSelectQueryBuilder(): true; readonly isSelectQueryBuilder: true;
toOperationNode(): SelectQueryNode; toOperationNode(): SelectQueryNode;
} }
+7 -15
View File
@@ -136,10 +136,8 @@ export class Entity<
.map((field) => (alias ? `${alias}.${field.name} as ${field.name}` : field.name)); .map((field) => (alias ? `${alias}.${field.name} as ${field.name}` : field.name));
} }
getFillableFields(context?: "create" | "update", include_virtual?: boolean): Field[] { getFillableFields(context?: TActionContext, include_virtual?: boolean): Field[] {
return this.getFields({ virtual: include_virtual }).filter((field) => return this.getFields(include_virtual).filter((field) => field.isFillable(context));
field.isFillable(context),
);
} }
getRequiredFields(): Field[] { getRequiredFields(): Field[] {
@@ -191,15 +189,9 @@ export class Entity<
return this.fields.findIndex((field) => field.name === name) !== -1; return this.fields.findIndex((field) => field.name === name) !== -1;
} }
getFields({ getFields(include_virtual: boolean = false): Field[] {
virtual = false, if (include_virtual) return this.fields;
primary = true, return this.fields.filter((f) => !f.isVirtual());
}: { virtual?: boolean; primary?: boolean } = {}): Field[] {
return this.fields.filter((f) => {
if (!virtual && f.isVirtual()) return false;
if (!primary && f instanceof PrimaryField) return false;
return true;
});
} }
addField(field: Field) { addField(field: Field) {
@@ -239,7 +231,7 @@ export class Entity<
} }
} }
const fields = this.getFillableFields(context as any, false); const fields = this.getFillableFields(context, false);
if (options?.ignoreUnknown !== true) { if (options?.ignoreUnknown !== true) {
const field_names = fields.map((f) => f.name); const field_names = fields.map((f) => f.name);
@@ -283,7 +275,7 @@ export class Entity<
fields = this.getFillableFields(options.context); fields = this.getFillableFields(options.context);
break; break;
default: default:
fields = this.getFields({ virtual: true }); fields = this.getFields(true);
} }
const _fields = Object.fromEntries(fields.map((field) => [field.name, field])); const _fields = Object.fromEntries(fields.map((field) => [field.name, field]));
+2 -4
View File
@@ -83,10 +83,8 @@ export class Mutator<
} }
// we should never get here, but just to be sure (why?) // we should never get here, but just to be sure (why?)
if (!field.isFillable(context as any)) { if (!field.isFillable(context)) {
throw new Error( throw new Error(`Field "${key}" is not fillable on entity "${entity.name}"`);
`Field "${key}" of entity "${entity.name}" is not fillable on context "${context}"`,
);
} }
// transform from field // transform from field
+7 -15
View File
@@ -26,19 +26,11 @@ export const baseFieldConfigSchema = s
.strictObject({ .strictObject({
label: s.string(), label: s.string(),
description: s.string(), description: s.string(),
required: s.boolean({ default: DEFAULT_REQUIRED }), required: s.boolean({ default: false }),
fillable: s.anyOf( fillable: s.anyOf([
[ s.boolean({ title: "Boolean" }),
s.boolean({ title: "Boolean" }), s.array(s.string({ enum: ActionContext }), { title: "Context", uniqueItems: true }),
s.array(s.string({ enum: ["create", "update"] }), { ]),
title: "Context",
uniqueItems: true,
}),
],
{
default: DEFAULT_FILLABLE,
},
),
hidden: s.anyOf([ hidden: s.anyOf([
s.boolean({ title: "Boolean" }), s.boolean({ title: "Boolean" }),
// @todo: tmp workaround // @todo: tmp workaround
@@ -111,7 +103,7 @@ export abstract class Field<
return this.config?.default_value; return this.config?.default_value;
} }
isFillable(context?: "create" | "update"): boolean { isFillable(context?: TActionContext): boolean {
if (Array.isArray(this.config.fillable)) { if (Array.isArray(this.config.fillable)) {
return context ? this.config.fillable.includes(context) : DEFAULT_FILLABLE; return context ? this.config.fillable.includes(context) : DEFAULT_FILLABLE;
} }
@@ -173,7 +165,7 @@ export abstract class Field<
// @todo: add field level validation // @todo: add field level validation
isValid(value: any, context: TActionContext): boolean { isValid(value: any, context: TActionContext): boolean {
if (typeof value !== "undefined") { if (typeof value !== "undefined") {
return this.isFillable(context as any); return this.isFillable(context);
} else if (context === "create") { } else if (context === "create") {
return !this.isRequired(); return !this.isRequired();
} }
+5 -2
View File
@@ -99,7 +99,6 @@ export function fieldTestSuite(
const _config = { const _config = {
..._requiredConfig, ..._requiredConfig,
required: false, required: false,
fillable: true,
}; };
function fieldJson(field: Field) { function fieldJson(field: Field) {
@@ -117,7 +116,10 @@ export function fieldTestSuite(
expect(fieldJson(fillable)).toEqual({ expect(fieldJson(fillable)).toEqual({
type: noConfigField.type, type: noConfigField.type,
config: _config, config: {
..._config,
fillable: true,
},
}); });
expect(fieldJson(required)).toEqual({ expect(fieldJson(required)).toEqual({
@@ -148,6 +150,7 @@ export function fieldTestSuite(
type: requiredAndDefault.type, type: requiredAndDefault.type,
config: { config: {
..._config, ..._config,
fillable: true,
required: true, required: true,
default_value: config.defaultValue, default_value: config.defaultValue,
}, },
+1 -2
View File
@@ -24,8 +24,7 @@ export function getChangeSet(
(acc, _value, key) => { (acc, _value, key) => {
const field = fields.find((f) => f.name === key); const field = fields.find((f) => f.name === key);
// @todo: filtering virtual here, need to check (because of media) // @todo: filtering virtual here, need to check (because of media)
// @note: adding non-fillable here as it'll fail validaiton on backend if (!field || field.isVirtual()) return;
if (!field || field.isVirtual() || !field.isFillable()) return;
const value = _value === "" ? null : _value; const value = _value === "" ? null : _value;
// normalize to null if undefined // normalize to null if undefined
+1 -1
View File
@@ -77,7 +77,7 @@ export class SchemaManager {
} }
getIntrospectionFromEntity(entity: Entity): IntrospectedTable { getIntrospectionFromEntity(entity: Entity): IntrospectedTable {
const fields = entity.getFields({ virtual: false }); const fields = entity.getFields(false);
const indices = this.em.getIndicesOf(entity); const indices = this.em.getIndicesOf(entity);
// this is intentionally setting values to defaults, like "nullable" and "default" // this is intentionally setting values to defaults, like "nullable" and "default"
+5 -2
View File
@@ -82,7 +82,7 @@ export * as AuthPermissions from "auth/auth-permissions";
*/ */
export { getExtensionFromName, getRandomizedFilename } from "media/utils"; export { getExtensionFromName, getRandomizedFilename } from "media/utils";
import * as StorageEvents from "media/storage/events"; import * as StorageEvents from "media/storage/events";
export const MediaEvents = { export const MediaEvents: typeof StorageEvents = {
...StorageEvents, ...StorageEvents,
}; };
export * as MediaPermissions from "media/media-permissions"; export * as MediaPermissions from "media/media-permissions";
@@ -104,7 +104,10 @@ export { StorageCloudinaryAdapter } from "media/storage/adapters/cloudinary/Stor
* Data * Data
*/ */
import { MutatorEvents, RepositoryEvents } from "data/events"; import { MutatorEvents, RepositoryEvents } from "data/events";
export const DatabaseEvents = { ...MutatorEvents, ...RepositoryEvents }; export const DatabaseEvents: typeof MutatorEvents & typeof RepositoryEvents = {
...MutatorEvents,
...RepositoryEvents,
};
export type { export type {
RepoQuery, RepoQuery,
RepoQueryIn, RepoQueryIn,
@@ -1,12 +1,11 @@
import { retry, type TestRunner } from "core/test"; import { retry, type TestRunner } from "core/test";
import type { StorageAdapter } from "media/storage/StorageAdapter"; import type { StorageAdapter } from "media/storage/StorageAdapter";
import { randomString } from "bknd/utils"; import { randomString } from "bknd/utils";
import type { BunFile } from "bun";
export async function adapterTestSuite( export async function adapterTestSuite(
testRunner: TestRunner, testRunner: TestRunner,
_adapter: StorageAdapter | (() => StorageAdapter), _adapter: StorageAdapter | (() => StorageAdapter),
file: File | BunFile, file: File | import("bun").BunFile,
opts?: { opts?: {
retries?: number; retries?: number;
retryTimeout?: number; retryTimeout?: number;
-24
View File
@@ -1,7 +1,6 @@
import { transformObject } from "bknd/utils"; import { transformObject } from "bknd/utils";
import type { Kysely } from "kysely"; import type { Kysely } from "kysely";
import { set } from "lodash-es"; import { set } from "lodash-es";
import type { InitialModuleConfigs } from "modules/ModuleManager";
export type MigrationContext = { export type MigrationContext = {
db: Kysely<any>; db: Kysely<any>;
@@ -108,29 +107,6 @@ export const migrations: Migration[] = [
return config; return config;
}, },
}, },
{
// change field.config.fillable to only "create" and "update"
version: 11,
up: async (config: InitialModuleConfigs) => {
const { data, ...rest } = config;
return {
...rest,
data: {
...data,
entities: transformObject(data?.entities ?? {}, (entity) => {
return {
...entity,
fields: transformObject(entity?.fields ?? {}, (field) => {
const fillable = field!.config?.fillable;
if (!fillable || typeof fillable === "boolean") return field;
return { ...field, config: { ...field!.config, fillable: true } };
}),
};
}),
},
};
},
},
]; ];
export const CURRENT_VERSION = migrations[migrations.length - 1]?.version ?? 0; export const CURRENT_VERSION = migrations[migrations.length - 1]?.version ?? 0;
+15
View File
@@ -55,6 +55,21 @@ export class AppServer extends Module<AppServerConfig> {
const origin = this.config.cors.origin ?? "*"; const origin = this.config.cors.origin ?? "*";
const origins = origin.includes(",") ? origin.split(",").map((o) => o.trim()) : [origin]; const origins = origin.includes(",") ? origin.split(",").map((o) => o.trim()) : [origin];
const all_origins = origins.includes("*"); const all_origins = origins.includes("*");
// Normalize trailing slashes so that /admin/ matches /admin.
// Hono's app.route doesn't match trailing slashes; host frameworks
// like Nuxt/Nitro redirect /admin -> /admin/. When running standalone
// we emit a 308 ourselves so the route layer sees a clean path without
// re-running the middleware chain (which would re-consume c.req.raw).
this.client.use("*", async (c, next) => {
const url = new URL(c.req.url);
if (url.pathname.length > 1 && url.pathname.endsWith("/")) {
url.pathname = url.pathname.replace(/\/+$/, "");
return c.redirect(url.toString(), 308);
}
return next();
});
this.client.use( this.client.use(
"*", "*",
cors({ cors({
-858
View File
@@ -1,858 +0,0 @@
import { describe, test, expect, beforeAll, afterAll } from "bun:test";
import { sort } from "./sort.plugin";
import { em, entity, text, number } from "bknd";
import { createApp } from "core/test/utils";
import { disableConsoleLog, enableConsoleLog } from "core/utils/test";
beforeAll(() => disableConsoleLog());
afterAll(enableConsoleLog);
describe("sort plugin", () => {
test("should add sort field to configured entities", async () => {
const app = createApp({
config: {
data: em({
tasks: entity("tasks", {
title: text(),
}),
}).toJSON(),
},
options: {
plugins: [
sort({
entities: {
tasks: {
field: "position",
},
},
}),
],
},
});
await app.build();
const taskEntity = app.em.entity("tasks");
expect(taskEntity).toBeDefined();
expect(taskEntity?.fields.map((f) => f.name)).toContain("position");
expect(taskEntity?.field("position")?.type).toBe("number");
});
test("should auto-assign sort values on insert (starting from 0)", async () => {
const app = createApp({
config: {
data: em({
tasks: entity("tasks", {
title: text(),
}),
}).toJSON(),
},
options: {
plugins: [
sort({
entities: {
tasks: {
field: "position",
},
},
}),
],
},
});
await app.build();
const mutator = app.em.mutator("tasks");
// insert first item
const { data: task1 } = await mutator.insertOne({ title: "Task 1" });
expect(task1.position).toBe(0);
// insert second item
const { data: task2 } = await mutator.insertOne({ title: "Task 2" });
expect(task2.position).toBe(1);
// insert third item
const { data: task3 } = await mutator.insertOne({ title: "Task 3" });
expect(task3.position).toBe(2);
});
test("should preserve manually set sort values on insert", async () => {
const app = createApp({
config: {
data: em({
tasks: entity("tasks", {
title: text(),
}),
}).toJSON(),
},
options: {
plugins: [
sort({
entities: {
tasks: {
field: "position",
},
},
}),
],
},
});
await app.build();
const mutator = app.em.mutator("tasks");
// insert with explicit position
const { data: task } = await mutator.insertOne({ title: "Task 1", position: 10 });
expect(task.position).toBe(10);
});
test("should reorder items via API endpoint", async () => {
const app = createApp({
config: {
data: em({
tasks: entity("tasks", {
title: text(),
}),
}).toJSON(),
},
options: {
plugins: [
sort({
entities: {
tasks: {
field: "position",
},
},
}),
],
},
});
await app.build();
const mutator = app.em.mutator("tasks");
// create tasks at positions 0, 1, 2
const { data: task1 } = await mutator.insertOne({ title: "Task 1" });
const { data: task2 } = await mutator.insertOne({ title: "Task 2" });
const { data: task3 } = await mutator.insertOne({ title: "Task 3" });
// move task3 (position 2) to position 0
const res = await app.server.request("/api/sort/tasks/reorder", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ id: task3.id, position: 0 }),
});
expect(res.status).toBe(200);
// verify positions
const repo = app.em.repo("tasks");
const { data: updatedTask1 } = await repo.findOne({ id: task1.id });
const { data: updatedTask2 } = await repo.findOne({ id: task2.id });
const { data: updatedTask3 } = await repo.findOne({ id: task3.id });
expect(updatedTask3.position).toBe(0); // moved to position 0
expect(updatedTask1.position).toBe(1); // shifted down
expect(updatedTask2.position).toBe(2); // shifted down
});
test("should automatically reorder when updating sort field directly", async () => {
const app = createApp({
config: {
data: em({
tasks: entity("tasks", {
title: text(),
}),
}).toJSON(),
},
options: {
plugins: [
sort({
entities: {
tasks: {
field: "position",
},
},
}),
],
},
});
await app.build();
const mutator = app.em.mutator("tasks");
// create tasks at positions 0, 1, 2, 3
const { data: task1 } = await mutator.insertOne({ title: "Task 1" });
const { data: task2 } = await mutator.insertOne({ title: "Task 2" });
const { data: task3 } = await mutator.insertOne({ title: "Task 3" });
const { data: task4 } = await mutator.insertOne({ title: "Task 4" });
// move task4 (position 3) to position 1 by updating directly
await mutator.updateOne(task4.id, { position: 1 });
// verify positions
const repo = app.em.repo("tasks");
const { data: updatedTask1 } = await repo.findOne({ id: task1.id });
const { data: updatedTask2 } = await repo.findOne({ id: task2.id });
const { data: updatedTask3 } = await repo.findOne({ id: task3.id });
const { data: updatedTask4 } = await repo.findOne({ id: task4.id });
expect(updatedTask1.position).toBe(0); // unchanged
expect(updatedTask2.position).toBe(2); // shifted down
expect(updatedTask3.position).toBe(3); // shifted down
expect(updatedTask4.position).toBe(1); // moved to position 1
});
test("should automatically reorder when moving items up", async () => {
const app = createApp({
config: {
data: em({
tasks: entity("tasks", {
title: text(),
}),
}).toJSON(),
},
options: {
plugins: [
sort({
entities: {
tasks: {
field: "position",
},
},
}),
],
},
});
await app.build();
const mutator = app.em.mutator("tasks");
// create tasks at positions 0, 1, 2, 3
const { data: task1 } = await mutator.insertOne({ title: "Task 1" });
const { data: task2 } = await mutator.insertOne({ title: "Task 2" });
const { data: task3 } = await mutator.insertOne({ title: "Task 3" });
const { data: task4 } = await mutator.insertOne({ title: "Task 4" });
// move task1 (position 0) to position 2 by updating directly
await mutator.updateOne(task1.id, { position: 2 });
// verify positions
const repo = app.em.repo("tasks");
const { data: updatedTask1 } = await repo.findOne({ id: task1.id });
const { data: updatedTask2 } = await repo.findOne({ id: task2.id });
const { data: updatedTask3 } = await repo.findOne({ id: task3.id });
const { data: updatedTask4 } = await repo.findOne({ id: task4.id });
expect(updatedTask1.position).toBe(2); // moved to position 2
expect(updatedTask2.position).toBe(0); // shifted up
expect(updatedTask3.position).toBe(1); // shifted up
expect(updatedTask4.position).toBe(3); // unchanged
});
test("should support scoped sorting", async () => {
const app = createApp({
config: {
data: em({
tasks: entity("tasks", {
title: text(),
project_id: number(),
}),
}).toJSON(),
},
options: {
plugins: [
sort({
entities: {
tasks: {
field: "position",
scope: "project_id",
},
},
}),
],
},
});
await app.build();
const mutator = app.em.mutator("tasks");
// create tasks in project 1
const { data: p1t1 } = await mutator.insertOne({
title: "P1 Task 1",
project_id: 1,
});
const { data: p1t2 } = await mutator.insertOne({
title: "P1 Task 2",
project_id: 1,
});
// create tasks in project 2
const { data: p2t1 } = await mutator.insertOne({
title: "P2 Task 1",
project_id: 2,
});
const { data: p2t2 } = await mutator.insertOne({
title: "P2 Task 2",
project_id: 2,
});
// positions should be scoped per project
expect(p1t1.position).toBe(0);
expect(p1t2.position).toBe(1);
expect(p2t1.position).toBe(0); // resets for new scope
expect(p2t2.position).toBe(1);
});
test("should reorder only within scope", async () => {
const app = createApp({
config: {
data: em({
tasks: entity("tasks", {
title: text(),
project_id: number(),
}),
}).toJSON(),
},
options: {
plugins: [
sort({
entities: {
tasks: {
field: "position",
scope: "project_id",
},
},
}),
],
},
});
await app.build();
const mutator = app.em.mutator("tasks");
// create tasks in project 1
const { data: p1t1 } = await mutator.insertOne({
title: "P1 Task 1",
project_id: 1,
});
const { data: p1t2 } = await mutator.insertOne({
title: "P1 Task 2",
project_id: 1,
});
const { data: p1t3 } = await mutator.insertOne({
title: "P1 Task 3",
project_id: 1,
});
// create tasks in project 2
const { data: p2t1 } = await mutator.insertOne({
title: "P2 Task 1",
project_id: 2,
});
const { data: p2t2 } = await mutator.insertOne({
title: "P2 Task 2",
project_id: 2,
});
// move p1t3 to position 0 (should only affect project 1)
await app.server.request("/api/sort/tasks/reorder", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ id: p1t3.id, position: 0 }),
});
// verify project 1 tasks
const repo = app.em.repo("tasks");
const { data: updatedP1t1 } = await repo.findOne({ id: p1t1.id });
const { data: updatedP1t2 } = await repo.findOne({ id: p1t2.id });
const { data: updatedP1t3 } = await repo.findOne({ id: p1t3.id });
expect(updatedP1t3.position).toBe(0); // moved to position 0
expect(updatedP1t1.position).toBe(1); // shifted
expect(updatedP1t2.position).toBe(2); // shifted
// verify project 2 tasks are unchanged
const { data: updatedP2t1 } = await repo.findOne({ id: p2t1.id });
const { data: updatedP2t2 } = await repo.findOne({ id: p2t2.id });
expect(updatedP2t1.position).toBe(0); // unchanged
expect(updatedP2t2.position).toBe(1); // unchanged
});
test("should recalculate all positions", async () => {
const app = createApp({
config: {
data: em({
tasks: entity("tasks", {
title: text(),
}),
}).toJSON(),
},
options: {
plugins: [
sort({
entities: {
tasks: {
field: "position",
},
},
}),
],
},
});
await app.build();
const mutator = app.em.mutator("tasks");
// create tasks with irregular positions
await mutator.insertOne({ title: "Task 1", position: 5 });
await mutator.insertOne({ title: "Task 2", position: 10 });
await mutator.insertOne({ title: "Task 3", position: 15 });
await mutator.insertOne({ title: "Task 4", position: 100 });
// recalculate
const res = await app.server.request("/api/sort/tasks/recalculate", {
method: "POST",
body: JSON.stringify({}),
headers: {
"Content-Type": "application/json",
},
});
expect(res.status).toBe(200);
// verify positions are now 0, 1, 2, 3
const { data: tasks } = await app.em.repo("tasks").findMany({
orderBy: [{ position: "asc" }],
});
expect(tasks.length).toBe(4);
expect(tasks[0].position).toBe(0);
expect(tasks[1].position).toBe(1);
expect(tasks[2].position).toBe(2);
expect(tasks[3].position).toBe(3);
});
test("should recalculate positions within scope only", async () => {
const app = createApp({
config: {
data: em({
tasks: entity("tasks", {
title: text(),
project_id: number(),
}),
}).toJSON(),
},
options: {
plugins: [
sort({
entities: {
tasks: {
field: "position",
scope: "project_id",
},
},
}),
],
},
});
await app.build();
const mutator = app.em.mutator("tasks");
// create tasks in project 1 with irregular positions
await mutator.insertOne({ title: "P1 Task 1", project_id: 1, position: 5 });
await mutator.insertOne({ title: "P1 Task 2", project_id: 1, position: 15 });
// create tasks in project 2 with irregular positions
await mutator.insertOne({ title: "P2 Task 1", project_id: 2, position: 10 });
await mutator.insertOne({ title: "P2 Task 2", project_id: 2, position: 20 });
// recalculate only project 1
const res = await app.server.request("/api/sort/tasks/recalculate", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ scope: 1 }),
});
expect(res.status).toBe(200);
// verify project 1 tasks are recalculated
const { data: p1Tasks } = await app.em.repo("tasks").findMany({
where: { project_id: 1 },
orderBy: [{ position: "asc" }],
});
expect(p1Tasks.length).toBe(2);
expect(p1Tasks[0].position).toBe(0);
expect(p1Tasks[1].position).toBe(1);
// verify project 2 tasks are unchanged
const { data: p2Tasks } = await app.em.repo("tasks").findMany({
where: { project_id: 2 },
orderBy: [{ position: "asc" }],
});
expect(p2Tasks.length).toBe(2);
expect(p2Tasks[0].position).toBe(10); // unchanged
expect(p2Tasks[1].position).toBe(20); // unchanged
});
test("should handle moving items to the end", async () => {
const app = createApp({
config: {
data: em({
tasks: entity("tasks", {
title: text(),
}),
}).toJSON(),
},
options: {
plugins: [
sort({
entities: {
tasks: {
field: "position",
},
},
}),
],
},
});
await app.build();
const mutator = app.em.mutator("tasks");
// create tasks at positions 0, 1, 2, 3
const { data: task1 } = await mutator.insertOne({ title: "Task 1" });
const { data: task2 } = await mutator.insertOne({ title: "Task 2" });
const { data: task3 } = await mutator.insertOne({ title: "Task 3" });
const { data: task4 } = await mutator.insertOne({ title: "Task 4" });
// move task1 to the end (position 3)
await app.server.request("/api/sort/tasks/reorder", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ id: task1.id, position: 3 }),
});
// verify positions
const repo = app.em.repo("tasks");
const { data: updatedTask1 } = await repo.findOne({ id: task1.id });
const { data: updatedTask2 } = await repo.findOne({ id: task2.id });
const { data: updatedTask3 } = await repo.findOne({ id: task3.id });
const { data: updatedTask4 } = await repo.findOne({ id: task4.id });
expect(updatedTask1.position).toBe(3); // moved to end
expect(updatedTask2.position).toBe(0); // shifted up
expect(updatedTask3.position).toBe(1); // shifted up
expect(updatedTask4.position).toBe(2); // shifted up
});
test("should return 400 for invalid item id", async () => {
const app = createApp({
config: {
data: em({
tasks: entity("tasks", {
title: text(),
}),
}).toJSON(),
},
options: {
plugins: [
sort({
entities: {
tasks: {
field: "position",
},
},
}),
],
},
});
await app.build();
const res = await app.server.request("/api/sort/tasks/reorder", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ id: 999999, position: 0 }),
});
expect(res.status).toBe(400);
});
test("should handle multiple entities with different configurations", async () => {
const app = createApp({
config: {
data: em({
tasks: entity("tasks", {
title: text(),
}),
categories: entity("categories", {
name: text(),
}),
}).toJSON(),
},
options: {
plugins: [
sort({
entities: {
tasks: {
field: "position",
},
categories: {
field: "order",
},
},
}),
],
},
});
await app.build();
// verify both entities have their sort fields
const taskEntity = app.em.entity("tasks");
const categoryEntity = app.em.entity("categories");
expect(taskEntity?.fields.map((f) => f.name)).toContain("position");
expect(categoryEntity?.fields.map((f) => f.name)).toContain("order");
// create items in both entities
const { data: task } = await app.em.mutator("tasks").insertOne({ title: "Task 1" });
const { data: category } = await app.em.mutator("categories").insertOne({ name: "Cat 1" });
expect(task.position).toBe(0);
expect(category.order).toBe(0);
// verify both endpoints exist
const taskRes = await app.server.request("/api/sort/tasks/recalculate", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({}),
});
const catRes = await app.server.request("/api/sort/categories/recalculate", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({}),
});
expect(taskRes.status).toBe(200);
expect(catRes.status).toBe(200);
});
test("should not trigger reorder when updating other fields", async () => {
const app = createApp({
config: {
data: em({
tasks: entity("tasks", {
title: text(),
}),
}).toJSON(),
},
options: {
plugins: [
sort({
entities: {
tasks: {
field: "position",
},
},
}),
],
},
});
await app.build();
const mutator = app.em.mutator("tasks");
// create tasks
const { data: task1 } = await mutator.insertOne({ title: "Task 1" });
const { data: task2 } = await mutator.insertOne({ title: "Task 2" });
const { data: task3 } = await mutator.insertOne({ title: "Task 3" });
// update title only (should not trigger reordering)
await mutator.updateOne(task2.id, { title: "Task 2 Updated" });
// verify positions are unchanged
const repo = app.em.repo("tasks");
const { data: updatedTask1 } = await repo.findOne({ id: task1.id });
const { data: updatedTask2 } = await repo.findOne({ id: task2.id });
const { data: updatedTask3 } = await repo.findOne({ id: task3.id });
expect(updatedTask1.position).toBe(0);
expect(updatedTask2.position).toBe(1);
expect(updatedTask2.title).toBe("Task 2 Updated");
expect(updatedTask3.position).toBe(2);
});
test("should handle null sort values", async () => {
const app = createApp({
config: {
data: em({
tasks: entity("tasks", {
title: text(),
}),
}).toJSON(),
},
options: {
plugins: [
sort({
entities: {
tasks: {
field: "position",
},
},
}),
],
},
});
await app.build();
const mutator = app.em.mutator("tasks");
// create task with null position (bypass listener by using kysely directly)
await app.connection.kysely
.insertInto("tasks")
.values({ title: "Task with null", position: null })
.execute();
// create normal task
await mutator.insertOne({ title: "Task 2" });
// update the null task to have a position
const nullTask = await app.connection.kysely
.selectFrom("tasks")
.selectAll()
.where("title", "=", "Task with null")
.executeTakeFirst();
await mutator.updateOne(nullTask!.id, { position: 0 });
// verify both tasks have proper positions
const { data: tasks } = await app.em.repo("tasks").findMany({
sort: { by: "position", dir: "asc" },
});
expect(tasks.length).toBe(2);
expect(tasks[0].position).toBe(0);
expect(tasks[1].position).toBe(1);
});
test("should not create duplicates when moving to an occupied position", async () => {
const app = createApp({
config: {
data: em({
tasks: entity("tasks", {
title: text(),
}),
}).toJSON(),
},
options: {
plugins: [
sort({
entities: {
tasks: {
field: "position",
},
},
}),
],
},
});
await app.build();
const mutator = app.em.mutator("tasks");
// create two tasks at positions 0 and 1
const { data: task1 } = await mutator.insertOne({ title: "Task 1" });
const { data: task2 } = await mutator.insertOne({ title: "Task 2" });
expect(task1.position).toBe(0);
expect(task2.position).toBe(1);
// move task2 (at position 1) to position 0
await mutator.updateOne(task2.id, { position: 0 });
// verify no duplicates
const { data: tasks } = await app.em.repo("tasks").findMany({
sort: { by: "position", dir: "asc" },
});
expect(tasks.length).toBe(2);
expect(tasks[0].id).toBe(task2.id);
expect(tasks[0].position).toBe(0);
expect(tasks[1].id).toBe(task1.id);
expect(tasks[1].position).toBe(1);
// verify no tasks have the same position
const positions = tasks.map((t) => t.position);
const uniquePositions = new Set(positions);
expect(uniquePositions.size).toBe(positions.length);
});
test("should preserve order when recalculating", async () => {
const app = createApp({
config: {
data: em({
tasks: entity("tasks", {
title: text(),
}),
}).toJSON(),
},
options: {
plugins: [
sort({
entities: {
tasks: {
field: "position",
},
},
}),
],
},
});
await app.build();
const mutator = app.em.mutator("tasks");
// create tasks with specific positions
const { data: taskA } = await mutator.insertOne({ title: "Task A", position: 5 });
const { data: taskB } = await mutator.insertOne({ title: "Task B", position: 3 });
const { data: taskC } = await mutator.insertOne({ title: "Task C", position: 10 });
// recalculate
await app.server.request("/api/sort/tasks/recalculate", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({}),
});
// verify order is preserved (B, A, C based on original positions)
const { data: tasks } = await app.em.repo("tasks").findMany({
sort: { by: "position", dir: "asc" },
});
expect(tasks[0].id).toBe(taskB.id); // was at 3, now at 0
expect(tasks[0].position).toBe(0);
expect(tasks[1].id).toBe(taskA.id); // was at 5, now at 1
expect(tasks[1].position).toBe(1);
expect(tasks[2].id).toBe(taskC.id); // was at 10, now at 2
expect(tasks[2].position).toBe(2);
});
});
-423
View File
@@ -1,423 +0,0 @@
import { Exception, type App, type AppPlugin, DatabaseEvents, em, entity, number } from "bknd";
import { invariant, HttpStatus, jsc, s, $console } from "bknd/utils";
import { Hono } from "hono";
import { sql } from "kysely";
const DEFAULT_BATCH_SIZE = 1000;
export type SortPluginOptions = {
/**
* The base path for the API endpoints.
* @default "/api/sort"
*/
apiBasePath?: string;
/**
* Configuration for entities that should have sorting enabled.
* Key is the entity name, value is the configuration.
*/
entities: Record<
string,
{
/**
* The name of the sort property (must be a number field).
*/
field: string;
/**
* Optional scope field name. If provided, sorting will only happen within the same scope.
* For example, if scope is "category_id", items will only be sorted within items
* that have the same category_id value.
*/
scope?: string;
}
>;
/**
* The batch size for recalculating sort order.
* @default 1000
*/
recalculateBatchSize?: number;
};
class SortError extends Exception {
override name = "SortError";
override code = HttpStatus.BAD_REQUEST;
}
export function sort({
apiBasePath = "/api/sort",
entities,
recalculateBatchSize = DEFAULT_BATCH_SIZE,
}: SortPluginOptions): AppPlugin {
return (app: App) => {
return {
name: "sort",
schema: () => {
return em(
Object.fromEntries(
Object.entries(entities).map(([entityName, config]) => [
entityName,
entity(entityName, {
[config.field]: number({ default_value: 0 }),
}),
]),
),
({ index }, schema) => {
for (const [entityName, config] of Object.entries(entities)) {
const indexed = app.em.getIndexedFields(entityName);
if (!indexed.some((f) => f.name === config.field)) {
index(schema[entityName]!).on([config.field]);
}
}
},
);
},
onBuilt: async () => {
invariant(
entities && Object.keys(entities).length > 0,
"At least one entity must be configured",
);
// validate entities exist and have the configured fields
for (const [entityName, config] of Object.entries(entities)) {
const entity = app.em.entity(entityName);
invariant(entity, `Entity "${entityName}" not found in schema`);
const sortFieldSchema = entity.field(config.field)!;
invariant(
sortFieldSchema,
`Sort field "${config.field}" not found in entity "${entityName}"`,
);
invariant(
sortFieldSchema.type === "number",
`Sort field "${config.field}" in entity "${entityName}" must be a number field`,
);
if (config.scope) {
const scopeFieldSchema = entity.field(config.scope);
invariant(
scopeFieldSchema,
`Scope field "${config.scope}" not found in entity "${entityName}"`,
);
}
}
const hono = new Hono();
// register recalculate endpoints for each entity
for (const [entityName, config] of Object.entries(entities)) {
hono.post(
`/${entityName}/recalculate`,
jsc(
"json",
s
.object({
scope: s.any().optional(),
})
.optional(),
),
async (c) => {
const body = c.req.valid("json");
const scope = body?.scope;
await recalculateSortOrder(
app,
entityName,
config,
recalculateBatchSize,
scope,
);
return c.json({ success: true, message: "Sort order recalculated" });
},
);
hono.post(
`/${entityName}/reorder`,
jsc(
"json",
s.object({
id: s.any(),
position: s.number(),
}),
),
async (c) => {
const { id, position } = c.req.valid("json");
await reorderItem(app, entityName, config, id, position);
return c.json({ success: true, message: "Item reordered" });
},
);
}
app.server.route(apiBasePath, hono);
// register listeners for automatic reordering
registerListeners(app, entities);
},
};
};
}
async function reorderItem(
app: App,
entityName: string,
config: SortPluginOptions["entities"][string],
id: any,
newPosition: number,
) {
const { field: sortField, scope: scopeField } = config;
const em = app.em.fork();
const kysely = em.connection.kysely;
// get the item
const { data: item } = await em.repo(entityName).findOne({ id });
if (!item) {
throw new SortError(`Item with id "${id}" not found in entity "${entityName}"`);
}
const oldPosition = item[sortField] as number | null | undefined;
const scopeValue = scopeField ? item[scopeField] : undefined;
// update the item with new position (using forked em, so no listeners are triggered)
await em.mutator(entityName).updateOne(id, { [sortField]: newPosition });
// shift other items using kysely
if (oldPosition !== undefined && oldPosition !== null && oldPosition !== newPosition) {
if (newPosition < oldPosition) {
// moving up: increment items between newPosition and oldPosition
let query = kysely
.updateTable(entityName)
.set({ [sortField]: sql`${sql.ref(sortField)} + 1` } as any)
.where(sortField as any, ">=", newPosition)
.where(sortField as any, "<", oldPosition)
.where("id", "!=", id);
if (scopeField && scopeValue !== undefined) {
query = query.where(scopeField as any, "=", scopeValue);
}
await query.execute();
} else {
// moving down: decrement items between oldPosition and newPosition
let query = kysely
.updateTable(entityName)
.set({ [sortField]: sql`${sql.ref(sortField)} - 1` } as any)
.where(sortField as any, ">", oldPosition)
.where(sortField as any, "<=", newPosition)
.where("id", "!=", id);
if (scopeField && scopeValue !== undefined) {
query = query.where(scopeField as any, "=", scopeValue);
}
await query.execute();
}
} else if (oldPosition === undefined || oldPosition === null) {
// new item, shift everything at or after this position
let query = kysely
.updateTable(entityName)
.set({ [sortField]: sql`${sql.ref(sortField)} + 1` } as any)
.where(sortField as any, ">=", newPosition)
.where("id", "!=", id);
if (scopeField && scopeValue !== undefined) {
query = query.where(scopeField as any, "=", scopeValue);
}
await query.execute();
}
}
async function recalculateSortOrder(
app: App,
entityName: string,
config: SortPluginOptions["entities"][string],
batchSize: number,
scope?: any,
) {
const { field: sortField, scope: scopeField } = config;
const db = app.connection.kysely;
const { count } = (await db
.selectFrom(entityName)
.select((eb) => eb.fn.count<number>("id").as("count"))
.$if(Boolean(scopeField && scope !== undefined), (eb) =>
eb.where(scopeField as any, "=", scope),
)
.$castTo<{ count: number }>()
.executeTakeFirst()) ?? { count: 0 };
const batches = Math.ceil(count / batchSize);
for (let i = 0; i < batches; i++) {
// get all items in scope, ordered by current sort value
const items = await db
.selectFrom(entityName)
.select(["id", sortField])
.$if(Boolean(scopeField && scope !== undefined), (eb) =>
eb.where(scopeField as any, "=", scope),
)
.orderBy(sortField, "asc")
.limit(batchSize)
.offset(i * batchSize)
.execute();
const newQbs = items.map((item, index) =>
db
.updateTable(entityName)
.set({ [sortField]: index })
.where("id", "=", item.id),
);
await app.connection.executeQueries(...newQbs);
$console.log(
`[Sort Plugin] Recalculated sort order for ${items.length} items in entity "${entityName}"${scopeField && scope !== undefined ? ` (scope: ${scope})` : ""} [batch ${i + 1}/${batches}]`,
);
}
}
function registerListeners(app: App, entities: SortPluginOptions["entities"]) {
const kysely = app.connection.kysely;
// handle insert events
app.emgr.onEvent(
DatabaseEvents.MutatorInsertBefore,
async (e) => {
const entityName = e.params.entity.name;
const config = entities[entityName];
if (!config) return e.params.data;
const { field: sortField, scope: scopeField } = config;
const data = e.params.data;
const scopeValue = scopeField ? data[scopeField] : undefined;
// if no position provided, set to max + 1
if (data[sortField] === undefined || data[sortField] === null) {
const query = kysely
.selectFrom(entityName)
.select((eb) => [eb.fn.max<number>(eb.ref(sortField)).as("max")])
// add scope filter if needed
.$if(Boolean(scopeField && scopeValue), (eb) =>
eb.where(scopeField as any, "=", scopeValue as any),
);
const result = await query.executeTakeFirst();
const max = result?.max ?? -1;
return {
...data,
[sortField]: max + 1,
};
}
// if position is provided, shift other items at or after that position
const newPosition = data[sortField] as number;
let shiftQuery = kysely
.updateTable(entityName)
.set({ [sortField]: sql`${sql.ref(sortField)} + 1` } as any)
.where(sortField as any, ">=", newPosition);
if (scopeField && scopeValue !== undefined) {
shiftQuery = shiftQuery.where(scopeField as any, "=", scopeValue);
}
await shiftQuery.execute();
return data;
},
{
mode: "sync",
id: "bknd-sort-insert",
},
);
// handle update events
app.emgr.onEvent(
DatabaseEvents.MutatorUpdateBefore,
async (e) => {
const entityName = e.params.entity.name;
const config = entities[entityName];
if (!config) return e.params.data;
const { field: sortField, scope: scopeField } = config;
const data = e.params.data;
// only handle if sort field is being updated
if (!(sortField in data)) return e.params.data;
const newPosition = data[sortField] as number;
const id = e.params.entityId;
// get the current item to know its old position and scope
const item = await kysely
.selectFrom(entityName)
.selectAll()
.where("id" as any, "=", id)
.executeTakeFirst();
if (!item) return data;
const oldPosition = item[sortField] as number | null | undefined;
const scopeValue = scopeField ? item[scopeField] : undefined;
// if oldPosition is null or undefined, treat as inserting at newPosition
if (oldPosition === null || oldPosition === undefined) {
// shift items at or after the new position
let query = kysely
.updateTable(entityName)
.set({ [sortField]: sql`${sql.ref(sortField)} + 1` } as any)
.where(sortField as any, ">=", newPosition)
.where("id" as any, "!=", id);
if (scopeField && scopeValue !== undefined) {
query = query.where(scopeField as any, "=", scopeValue);
}
await query.execute();
return data;
}
// shift other items using kysely
if (oldPosition !== newPosition) {
if (newPosition < oldPosition) {
// moving up: increment items between newPosition and oldPosition
let query = kysely
.updateTable(entityName)
.set({ [sortField]: sql`${sql.ref(sortField)} + 1` } as any)
.where(sortField as any, ">=", newPosition)
.where(sortField as any, "<", oldPosition)
.where("id" as any, "!=", id);
if (scopeField && scopeValue !== undefined) {
query = query.where(scopeField as any, "=", scopeValue);
}
await query.execute();
} else {
// moving down: decrement items between oldPosition and newPosition
let query = kysely
.updateTable(entityName)
.set({ [sortField]: sql`${sql.ref(sortField)} - 1` } as any)
.where(sortField as any, ">", oldPosition)
.where(sortField as any, "<=", newPosition)
.where("id" as any, "!=", id);
if (scopeField && scopeValue !== undefined) {
query = query.where(scopeField as any, "=", scopeValue);
}
await query.execute();
}
}
return data;
},
{
mode: "sync",
id: "bknd-sort-update",
},
);
}
-1
View File
@@ -9,4 +9,3 @@ export { syncTypes, type SyncTypesOptions } from "./dev/sync-types.plugin";
export { syncSecrets, type SyncSecretsOptions } from "./dev/sync-secrets.plugin"; export { syncSecrets, type SyncSecretsOptions } from "./dev/sync-secrets.plugin";
export { timestamps, type TimestampsPluginOptions } from "./data/timestamps.plugin"; export { timestamps, type TimestampsPluginOptions } from "./data/timestamps.plugin";
export { emailOTP, type EmailOTPPluginOptions } from "./auth/email-otp.plugin"; export { emailOTP, type EmailOTPPluginOptions } from "./auth/email-otp.plugin";
export { sort, type SortPluginOptions } from "./data/sort.plugin";
+8 -15
View File
@@ -1,6 +1,6 @@
import { MantineProvider } from "@mantine/core"; import { MantineProvider } from "@mantine/core";
import { Notifications } from "@mantine/notifications"; import { Notifications } from "@mantine/notifications";
import React, { type ReactNode } from "react"; import { type ReactNode } from "react";
import { BkndProvider } from "ui/client/bknd"; import { BkndProvider } from "ui/client/bknd";
import { useTheme, type AppTheme } from "ui/client/use-theme"; import { useTheme, type AppTheme } from "ui/client/use-theme";
import { Logo } from "ui/components/display/Logo"; import { Logo } from "ui/components/display/Logo";
@@ -16,11 +16,6 @@ export type BkndAdminConfig = {
* @default `/` * @default `/`
*/ */
basepath?: string; basepath?: string;
/**
* Sub-path for the Admin UI within the base path
* @default ``
*/
admin_basepath?: string;
/** /**
* Path to return to when clicking the logo * Path to return to when clicking the logo
* @default `/` * @default `/`
@@ -77,14 +72,6 @@ export default function Admin(props: BkndAdminProps) {
); );
} }
function BkndWrapper({ options, children }: { options?: BkndAdminConfig; children: ReactNode }) {
return (
<BkndProvider options={options} fallback={<Skeleton theme={options?.theme} />}>
{children}
</BkndProvider>
);
}
function AdminInner(props: BkndAdminProps) { function AdminInner(props: BkndAdminProps) {
const { theme } = useTheme(); const { theme } = useTheme();
const config = { const config = {
@@ -92,10 +79,16 @@ function AdminInner(props: BkndAdminProps) {
...useBkndWindowContext(), ...useBkndWindowContext(),
}; };
const BkndWrapper = ({ children }: { children: ReactNode }) => (
<BkndProvider options={config} fallback={<Skeleton theme={config?.theme} />}>
{children}
</BkndProvider>
);
return ( return (
<MantineProvider {...createMantineTheme(theme as any)}> <MantineProvider {...createMantineTheme(theme as any)}>
<Notifications position="top-right" /> <Notifications position="top-right" />
<Routes BkndWrapper={BkndWrapper} options={config} basePath={config?.basepath}> <Routes BkndWrapper={BkndWrapper} basePath={config?.basepath}>
{props.children} {props.children}
</Routes> </Routes>
</MantineProvider> </MantineProvider>
@@ -30,7 +30,7 @@ export const Group = <E extends ElementType = "div">({
{...props} {...props}
data-role="group" data-role="group"
className={twMerge( className={twMerge(
"flex flex-col gap-1.5 has-disabled:cursor-not-allowed w-full", "flex flex-col gap-1.5 w-full",
as === "fieldset" && "border border-primary/10 p-3 rounded-md", as === "fieldset" && "border border-primary/10 p-3 rounded-md",
as === "fieldset" && error && "border-red-500", as === "fieldset" && error && "border-red-500",
error && "text-red-500", error && "text-red-500",
@@ -97,7 +97,7 @@ export const Input = forwardRef<HTMLInputElement, React.ComponentProps<"input">>
ref={ref} ref={ref}
className={twMerge( className={twMerge(
"bg-muted/40 h-11 rounded-md py-2.5 px-4 outline-none w-full disabled:cursor-not-allowed", "bg-muted/40 h-11 rounded-md py-2.5 px-4 outline-none w-full disabled:cursor-not-allowed",
disabledOrReadonly && "bg-muted/50 text-primary/50 cursor-not-allowed", disabledOrReadonly && "bg-muted/50 text-primary/50",
!disabledOrReadonly && !disabledOrReadonly &&
"focus:bg-muted focus:outline-none focus:ring-2 focus:ring-zinc-500 focus:border-transparent transition-all", "focus:bg-muted focus:outline-none focus:ring-2 focus:ring-zinc-500 focus:border-transparent transition-all",
props.className, props.className,
@@ -154,7 +154,7 @@ export const Textarea = forwardRef<HTMLTextAreaElement, React.ComponentProps<"te
{...props} {...props}
ref={ref} ref={ref}
className={twMerge( className={twMerge(
"bg-muted/40 min-h-11 rounded-md py-2.5 px-4 focus:bg-muted outline-none focus:outline-none focus:ring-2 focus:ring-zinc-500 focus:border-transparent transition-all disabled:bg-muted/50 disabled:text-primary/50 disabled:cursor-not-allowed", "bg-muted/40 min-h-11 rounded-md py-2.5 px-4 focus:bg-muted outline-none focus:outline-none focus:ring-2 focus:ring-zinc-500 focus:border-transparent transition-all disabled:bg-muted/50 disabled:text-primary/50",
props.className, props.className,
)} )}
/> />
@@ -214,7 +214,7 @@ export const BooleanInput = forwardRef<HTMLInputElement, React.ComponentProps<"i
{...props} {...props}
type="checkbox" type="checkbox"
ref={ref} ref={ref}
className="outline-none focus:outline-none focus:ring-2 focus:ring-zinc-500 transition-all disabled:opacity-70 disabled:cursor-not-allowed scale-150 ml-1" className="outline-none focus:outline-none focus:ring-2 focus:ring-zinc-500 transition-all disabled:opacity-70 scale-150 ml-1"
checked={checked} checked={checked}
onChange={handleCheck} onChange={handleCheck}
disabled={props.disabled} disabled={props.disabled}
@@ -260,6 +260,7 @@ export const Switch = forwardRef<
props.disabled && "opacity-50 !cursor-not-allowed", props.disabled && "opacity-50 !cursor-not-allowed",
)} )}
onCheckedChange={(bool) => { onCheckedChange={(bool) => {
console.log("setting", bool);
props.onChange?.({ target: { value: bool } }); props.onChange?.({ target: { value: bool } });
}} }}
{...(props as any)} {...(props as any)}
@@ -293,7 +294,7 @@ export const Select = forwardRef<
{...props} {...props}
ref={ref} ref={ref}
className={twMerge( className={twMerge(
"bg-muted/40 focus:bg-muted rounded-md py-2.5 px-4 outline-none focus:outline-none focus:ring-2 focus:ring-zinc-500 focus:border-transparent transition-all disabled:bg-muted/50 disabled:text-primary/50 disabled:cursor-not-allowed", "bg-muted/40 focus:bg-muted rounded-md py-2.5 px-4 outline-none focus:outline-none focus:ring-2 focus:ring-zinc-500 focus:border-transparent transition-all disabled:bg-muted/50 disabled:text-primary/50",
"appearance-none h-11 w-full", "appearance-none h-11 w-full",
!props.multiple && "border-r-8 border-r-transparent", !props.multiple && "border-r-8 border-r-transparent",
props.className, props.className,
+5 -10
View File
@@ -1,6 +1,5 @@
import { type LinkProps, Link as WouterLink, useRouter } from "wouter"; import { type LinkProps, Link as WouterLink, useRouter } from "wouter";
import { useEvent } from "../../hooks/use-event"; import { useEvent } from "../../hooks/use-event";
import { useBkndOptions } from "ui/client/BkndProvider";
/* /*
* Transforms `path` into its relative `base` version * Transforms `path` into its relative `base` version
@@ -71,13 +70,11 @@ export function Link({
return false; return false;
} }
const bkndOptions = useBkndOptions();
const adminBasePath = bkndOptions?.admin_basepath ?? "";
const _href = props.href ?? props.to;
const _href = props.href ?? props.to;
const href = router const href = router
.hrefs( .hrefs(
_href[0] === "~" ? adminBasePath + _href.slice(1) : router.base + _href, _href[0] === "~" ? _href.slice(1) : router.base + _href,
router, // pass router as a second argument for convinience router, // pass router as a second argument for convinience
) )
.replace("//", "/"); .replace("//", "/");
@@ -85,9 +82,8 @@ export function Link({
const active = const active =
href.replace(router.base, "").length <= 1 ? href === absPath : isActive(absPath, href); href.replace(router.base, "").length <= 1 ? href === absPath : isActive(absPath, href);
// console.log({ adminBasePath, _href, href, bkndOptions })
if (native) { if (native) {
return <a className={`${active ? "active " : ""}${className}`} {...props} href={href} />; return <a className={`${active ? "active " : ""}${className}`} {...props} />;
} }
const wouterOnClick = (e: any) => { const wouterOnClick = (e: any) => {
@@ -103,11 +99,10 @@ export function Link({
}; };
return ( return (
// @ts-expect-error className is not typed on WouterLink
<WouterLink <WouterLink
{...props} // @ts-expect-error className is not typed on WouterLink
className={`${active ? "active " : ""}${className}`} className={`${active ? "active " : ""}${className}`}
href={`~${href}`} {...props}
onClick={wouterOnClick} onClick={wouterOnClick}
/> />
); );
+1 -1
View File
@@ -101,7 +101,7 @@ export function useNavigate() {
} }
} }
const _url = options?.absolute ? `~/${app.options.basepath}/${app.options.admin_basepath}${url}`.replace(/\/+/g, "/") : url; const _url = options?.absolute ? `~/${basepath}${url}`.replace(/\/+/g, "/") : url;
const state = { const state = {
...options?.state, ...options?.state,
referrer: location, referrer: location,
+4 -3
View File
@@ -102,9 +102,10 @@ body,
/* Chrome, Edge, and Safari */ /* Chrome, Edge, and Safari */
& *::-webkit-scrollbar { & *::-webkit-scrollbar {
@apply w-1; @apply w-1;
&:horizontal { }
@apply h-px;
} & *::-webkit-scrollbar:horizontal {
@apply h-px;
} }
& *::-webkit-scrollbar-track { & *::-webkit-scrollbar-track {
@@ -45,7 +45,7 @@ export function EntityForm({
className, className,
action, action,
}: EntityFormProps) { }: EntityFormProps) {
const fields = entity.getFields({ virtual: true, primary: false }); const fields = entity.getFillableFields(action, true);
const options = useEntityAdminOptions(entity, action); const options = useEntityAdminOptions(entity, action);
return ( return (
@@ -93,6 +93,10 @@ export function EntityForm({
); );
} }
if (!field.isFillable(action)) {
return;
}
const _key = `${entity.name}-${field.name}-${key}`; const _key = `${entity.name}-${field.name}-${key}`;
return ( return (
@@ -124,7 +128,7 @@ export function EntityForm({
<EntityFormField <EntityFormField
field={field} field={field}
fieldApi={props} fieldApi={props}
disabled={fieldsDisabled || !field.isFillable(action)} disabled={fieldsDisabled}
tabIndex={key + 1} tabIndex={key + 1}
action={action} action={action}
data={data} data={data}
@@ -17,7 +17,7 @@ export function useEntityForm({
}: EntityFormProps) { }: EntityFormProps) {
const data = initialData ?? {}; const data = initialData ?? {};
// @todo: check if virtual must be filtered // @todo: check if virtual must be filtered
const fields = entity.getFields({ virtual: true, primary: false }); const fields = entity.getFillableFields(action, true);
// filter defaultValues to only contain fillable fields // filter defaultValues to only contain fillable fields
const defaultValues = getDefaultValues(fields, data); const defaultValues = getDefaultValues(fields, data);
+2 -5
View File
@@ -12,7 +12,6 @@ import { FlashMessage } from "ui/modules/server/FlashMessage";
import { AuthRegister } from "ui/routes/auth/auth.register"; import { AuthRegister } from "ui/routes/auth/auth.register";
import { BkndModalsProvider } from "ui/modals"; import { BkndModalsProvider } from "ui/modals";
import { useBkndWindowContext } from "bknd/client"; import { useBkndWindowContext } from "bknd/client";
import type { BkndAdminProps } from "ui/Admin";
import ToolsRoutes from "./tools"; import ToolsRoutes from "./tools";
// @ts-ignore // @ts-ignore
@@ -25,12 +24,10 @@ try {
export function Routes({ export function Routes({
BkndWrapper, BkndWrapper,
options,
basePath = "", basePath = "",
children, children,
}: { }: {
BkndWrapper: ComponentType<{ children: ReactNode; options?: BkndAdminProps["config"] }>; BkndWrapper: ComponentType<{ children: ReactNode }>;
options?: BkndAdminProps["config"];
basePath?: string; basePath?: string;
children?: ReactNode; children?: ReactNode;
}) { }) {
@@ -46,7 +43,7 @@ export function Routes({
<Route path="/auth/login" component={AuthLogin} /> <Route path="/auth/login" component={AuthLogin} />
<Route path="/auth/register" component={AuthRegister} /> <Route path="/auth/register" component={AuthRegister} />
<BkndWrapper options={options}> <BkndWrapper>
<BkndModalsProvider> <BkndModalsProvider>
<Route path="/" nest> <Route path="/" nest>
<Root> <Root>
+3 -1
View File
@@ -3,8 +3,10 @@
"compilerOptions": { "compilerOptions": {
"outDir": "./dist/types", "outDir": "./dist/types",
"rootDir": "./src", "rootDir": "./src",
"declaration": true,
"incremental": true,
"tsBuildInfoFile": "./dist/tsconfig.tsbuildinfo" "tsBuildInfoFile": "./dist/tsconfig.tsbuildinfo"
}, },
"include": ["./src/**/*.ts", "./src/**/*.tsx"], "include": ["./src/**/*.ts", "./src/**/*.tsx"],
"exclude": ["./node_modules", "./__test__", "./e2e"] "exclude": ["node_modules", "__test__", "e2e"]
} }
+4 -3
View File
@@ -10,7 +10,8 @@
"noImplicitAny": false, "noImplicitAny": false,
"allowJs": true, "allowJs": true,
"verbatimModuleSyntax": true, "verbatimModuleSyntax": true,
"declaration": true, "declaration": false,
"declarationMap": false,
"strict": true, "strict": true,
"allowUnusedLabels": false, "allowUnusedLabels": false,
"allowUnreachableCode": false, "allowUnreachableCode": false,
@@ -26,7 +27,7 @@
"esModuleInterop": true, "esModuleInterop": true,
"skipLibCheck": true, "skipLibCheck": true,
"rootDir": ".", "rootDir": ".",
"outDir": "./dist/types", "outDir": "./dist",
"paths": { "paths": {
"*": ["./src/*"], "*": ["./src/*"],
"bknd": ["./src/index.ts"], "bknd": ["./src/index.ts"],
@@ -47,5 +48,5 @@
"__test__", "__test__",
"e2e/**/*.ts" "e2e/**/*.ts"
], ],
"exclude": ["node_modules", "dist", "dist/types", "**/*.d.ts"] "exclude": ["node_modules", "dist", "**/*.d.ts"]
} }
+10 -8
View File
@@ -1,13 +1,17 @@
import devServer from "@hono/vite-dev-server"; import devServer from "@hono/vite-dev-server";
import react from "@vitejs/plugin-react"; import react from "@vitejs/plugin-react";
import { defineConfig } from "vite"; import { defineConfig } from "vite";
import tsconfigPaths from "vite-tsconfig-paths";
import { devServerConfig } from "./src/adapter/vite/dev-server-config"; import { devServerConfig } from "./src/adapter/vite/dev-server-config";
import tailwindcss from "@tailwindcss/vite"; import tailwindcss from '@tailwindcss/postcss'
import pkg from "./package.json" with { type: "json" }; import pkg from "./package.json" with { type: "json" };
// https://vitejs.dev/config/ // https://vitejs.dev/config/
export default defineConfig({ export default defineConfig({
css: {
postcss: {
plugins: [tailwindcss()],
},
},
define: { define: {
__isDev: process.env.NODE_ENV === "production" ? "0" : "1", __isDev: process.env.NODE_ENV === "production" ? "0" : "1",
__version: JSON.stringify(pkg.version), __version: JSON.stringify(pkg.version),
@@ -21,23 +25,21 @@ export default defineConfig({
overlay: true, overlay: true,
}, },
}, },
resolve: {
tsconfigPaths: true
},
plugins: [ plugins: [
react(), react(),
tsconfigPaths({
// otherwise it'll throw an error because of examples/astro
ignoreConfigErrors: true,
}),
devServer({ devServer({
...devServerConfig, ...devServerConfig,
entry: "./vite.dev.ts", entry: "./vite.dev.ts",
//entry: "./vite.dev.code.ts", //entry: "./vite.dev.code.ts",
}), }),
tailwindcss(),
], ],
build: { build: {
manifest: true, manifest: true,
outDir: "./dist/static", outDir: "./dist/static",
rollupOptions: { rolldownOptions: {
input: "./src/ui/main.tsx", input: "./src/ui/main.tsx",
}, },
}, },
+3 -7
View File
@@ -1,13 +1,9 @@
import { defineConfig } from "vitest/config"; import { defineConfig } from "vitest/config";
import tsconfigPaths from "vite-tsconfig-paths";
export default defineConfig({ export default defineConfig({
plugins: [ resolve: {
tsconfigPaths({ tsconfigPaths: true,
root: ".", },
ignoreConfigErrors: true,
}) as any,
],
test: { test: {
include: ["**/*.vi-test.ts", "**/*.vitest.ts"], include: ["**/*.vi-test.ts", "**/*.vitest.ts"],
}, },
+1 -1
View File
@@ -35,7 +35,7 @@
"files": { "files": {
"includes": [ "includes": [
"**", "**",
"!!**/.tsup", "!!**/.tsdown",
"!!**/node_modules", "!!**/node_modules",
"!!**/.cache", "!!**/.cache",
"!!**/.wrangler", "!!**/.wrangler",
+1148 -1983
View File
File diff suppressed because it is too large Load Diff
@@ -335,55 +335,3 @@ export default {
``` ```
<AutoTypeTable path="../app/src/plugins/auth/email-otp.plugin.ts" name="EmailOTPPluginOptions" /> <AutoTypeTable path="../app/src/plugins/auth/email-otp.plugin.ts" name="EmailOTPPluginOptions" />
### `sort`
A plugin that maintains sequential numeric positions for one or more entities. Positions are updated automatically when items are inserted or moved. You can optionally configure a scope so that positions are maintained independently within groups, such as tasks within a project.
```typescript title="bknd.config.ts"
import { sort } from "bknd/plugins";
export default {
options: {
plugins: [
sort({
entities: {
tasks: {
field: "position",
scope: "project_id",
},
},
}),
],
},
} satisfies BkndConfig;
```
The configured `field` is used for the numeric position. If the field does not exist, the plugin adds it as a number field with a default value of `0`; if it already exists, it must be a number field. The plugin also adds an index for the field when one is not already present. The optional `scope` field limits reordering to records with the same scope value.
The plugin registers the following endpoints. The default base path is `/api/sort` and can be changed with `apiBasePath`:
- `POST /api/sort/:entity/reorder` moves an item to a position. The request body must include the item `id` and its new numeric `position`.
- `POST /api/sort/:entity/recalculate` recalculates positions in ascending order of the configured field. To recalculate only one scope, pass its value in the optional `scope` property.
```http title="Move a task"
POST /api/sort/tasks/reorder
Content-Type: application/json
{
"id": "task_123",
"position": 2
}
```
```http title="Recalculate a project's task positions"
POST /api/sort/tasks/recalculate
Content-Type: application/json
{
"scope": "project_456"
}
```
<AutoTypeTable path="../app/src/plugins/data/sort.plugin.ts" name="SortPluginOptions" />
@@ -6,7 +6,6 @@
"sveltekit", "sveltekit",
"tanstack-start", "tanstack-start",
"vite", "vite",
"nuxt", "nuxt"
"solid-start"
] ]
} }
@@ -1,334 +0,0 @@
---
title: "Solid Start"
description: "Run bknd inside Solid Start"
tags: ["documentation"]
---
## Installation
To get started with Solid Start and bknd you can either install the package manually, and follow the descriptions below, or use the CLI starter.
Create a new Solid Start project by following the [official guide](https://docs.solidjs.com/solid-start/getting-started), and then install bknd as a dependency:
<Tabs groupId='package-manager' persist items={[ 'npm', 'pnpm', 'yarn', 'bun']}>
```bash tab="npm"
npm install bknd
```
```bash tab="pnpm"
pnpm install bknd
```
```bash tab="yarn"
yarn add bknd
```
```bash tab="bun"
bun add bknd
```
</Tabs>
## Configuration
<Callout type="warning">
When run with Node.js, a version of 22 (LTS) or higher is required. Please
verify your version by running `node -v`, and
[upgrade](https://nodejs.org/en/download/) if necessary.
</Callout>
Now create a `bknd.config.ts` file in the root of your project. If you created the project using the CLI starter, this file is already created for you.
```typescript title="bknd.config.ts"
import type { SolidStartBkndConfig } from "bknd/adapter/solid-start";
import { em, entity, text, boolean } from "bknd";
import { secureRandomString } from "bknd/utils";
const schema = em({
todos: entity("todos", {
title: text(),
done: boolean(),
}),
});
// register your schema to get automatic type completion
type Database = (typeof schema)["DB"];
declare module "bknd" {
interface DB extends Database {}
}
export default {
connection: {
url: "file:data.db",
},
options: {
// the seed option is only executed if the database was empty
seed: async (ctx) => {
// create some entries
await ctx.em.mutator("todos").insertMany([
{ title: "Learn bknd", done: true },
{ title: "Build something cool", done: false },
]);
// and create a user
await ctx.app.module.auth.createUser({
email: "test@bknd.io",
password: "12345678",
});
},
},
config: {
data: schema.toJSON(),
auth: {
enabled: true,
jwt: {
secret: secureRandomString(32),
},
},
},
// please run `bun bknd copy-assets --out public/admin` to copy the admin assets into the public directory
// alternatively add this as a postinstall script in your package.json like this:
// "postinstall": "bknd copy-assets --out public/admin"
adminOptions: {
adminBasepath: "/admin",
assetsPath: "/admin/", // trailing slash is important
},
} satisfies SolidStartBkndConfig;
```
See [bknd.config.ts](/extending/config) for more information on how to configure bknd. The `SolidStartBkndConfig` type extends the `BkndConfig` type with the following additional properties:
```typescript
export type SolidStartBkndConfig<Env = SolidStartEnv> = RuntimeBkndConfig<Env>;
```
## Serve the API and Admin UI
The Solid Start adapter uses middleware to handle API requests and serve the Admin UI. Create a `src/middleware/index.ts` file:
```ts title="src/middleware/index.ts"
import { createMiddleware } from "@solidjs/start/middleware";
import config from "../../bknd.config";
import { serve } from "bknd/adapter/solid-start";
const handler = serve(config);
export default createMiddleware({
onRequest: async (event) => {
const url = new URL(event.request.url);
const pathname = url.pathname;
if (pathname.startsWith("/api") || pathname !== "/") {
const res = await handler(event.request);
if (res && res.status !== 404) {
return res;
}
}
},
});
```
### Update the app config (Solid Start v1 based on vinxi)
Add the following to your `app.config.ts` file:
```ts title="app.config.ts"
import { defineConfig } from "@solidjs/start/config";
const app = defineConfig({
// ... your existing config
middleware: "src/middleware/index.ts",
// ... your existing config
});
export default app;
```
### Update the vite config (Solid Start v2)
Add the following to your `vite.config.ts` file:
```ts title="vite.config.ts"
import { defineConfig } from "vite";
import solid from "vite-plugin-solid";
import { solidStart } from "@solidjs/start/vite";
export default defineConfig({
plugins: [
solid(),
solidStart({
middleware: "./src/middleware/index.ts",
}),
],
});
```
<Callout type="success">
You can visit https://localhost:3000/admin to see the admin UI. Additionally you can create more todos as you explore the admin UI.
</Callout>
Create a helper file to instantiate the bknd instance and retrieve the API, importing the configuration from the `bknd.config.ts` file:
```ts title="src/lib/bknd.ts"
import { getApp as getBkndApp } from "bknd/adapter/solid-start";
import bkndConfig from "../../bknd.config";
import type { App } from "bknd";
export const getApp = async () => {
return await getBkndApp(bkndConfig);
};
export async function getApi({
headers,
verify,
}: {
verify?: boolean;
headers?: Headers;
}) {
const app = await getApp();
if (verify) {
const api = app.getApi({ headers });
await api.verifyAuth();
return api;
}
return app.getApi();
};
```
## Example usage of the API
You can use the `getApi` helper function we've already set up to fetch and mutate in static pages and server components:
```tsx title="src/routes/index.tsx"
import { getApi } from "~/lib/bknd";
import { query, createAsync } from "@solidjs/router";
export const getTodo = async () => {
"use server"
const api = await getApi({});
const limit = 5;
const todos = await api.data.readMany("todos");
const total = todos.body.meta.total as number;
return { total, todos: todos as unknown as Todo[], limit };
};
const getTodosFromServer = query(async () => await getTodo(), "getTodosFromServer");
export default function Home() {
const data = createAsync(() => getTodosFromServer());
return (
<ul>
<For each={data()}>
{(todo) => <li>{todo.title}</li>}
</For>
</ul>
);
}
```
## Using authentication
When using authentication, you'll need to pass the headers to the `getApi` function to verify the user is authenticated.
```tsx title="src/routes/auth.tsx"
import { createResource, Suspense } from "solid-js";
import { A } from "@solidjs/router";
import { getRequestEvent } from "solid-js/web";
import { getApi } from "~/lib/bknd";
export const getUser = async () => {
"use server"
const request = getRequestEvent()?.request;
const api = await getApi({ verify: true, headers: request?.headers });
return api.getUser();
}
export default function Auth() {
const [data] = createResource(async () => {
const user = await getUser()
return { user };
}, {
initialValue: {
user: null
}
});
return (
<div class="grid grid-rows-[20px_1fr_20px] items-center justify-items-center min-h-screen p-8 pb-20 gap-16 sm:p-20">
<main class="flex flex-col gap-8 row-start-2 items-center sm:items-start">
<div class="flex flex-row items-center ">
<img
class="dark:invert size-18"
src="/solid.svg"
alt="Solid logo"
/>
<div class="ml-3.5 mr-2 opacity-70">&amp;</div>
<img
class="dark:invert"
src="/bknd.svg"
alt="bknd logo"
width={183}
height={59}
/>
</div>
<Suspense fallback={<p>Loading...</p>}>
<div>
{data()?.user ? (
<>
Logged in as {data()?.user?.email}.
<A
class="underline"
target="_self"
href={"/api/auth/logout"}
>
Logout
</A>
</>
) : (
<div class="flex flex-col gap-1">
<p>
Not logged in.
<A
class="underline"
target="_self"
href={"/admin/auth/login"}
>
Login
</A>
</p>
<p class="text-xs opacity-50">
Sign in with:
<b>
<code>test@bknd.io</code>
</b>
/
<b>
<code>12345678</code>
</b>
</p>
</div>
)}
</div>
</Suspense>
</main>
</div>
);
}
```
## Tips
Use `target="_self"` on links, anytime your traversing to an external route (like `/api/auth/logout` which are handled by bknd's middleware) to prevent solid router from intercepting the link.
```jsx
<A href="/api/auth/logout" target="_self">
Logout
</A>
```
@@ -45,12 +45,6 @@ bknd seamlessly integrates with popular frameworks, allowing you to use what you
href="/integration/nuxt" href="/integration/nuxt"
/> />
<Card
icon={<Icon icon="simple-icons:solid" className="text-fd-primary !size-6" />}
title="Solid Start"
href="/integration/solid-start"
/>
<Card title="Yours missing?" href="https://github.com/bknd-io/bknd/issues/new"> <Card title="Yours missing?" href="https://github.com/bknd-io/bknd/issues/new">
Create a new issue to request a guide for your framework. Create a new issue to request a guide for your framework.
</Card> </Card>
@@ -162,12 +162,6 @@ Pick your framework or runtime to get started.
href="/integration/nuxt" href="/integration/nuxt"
/> />
<Card
icon={<Icon icon="simple-icons:solid" className="text-fd-primary !size-6" />}
title="Solid Start"
href="/integration/solid-start"
/>
<Card <Card
icon={<Icon icon="tabler:lambda" className="text-fd-primary !size-6" />} icon={<Icon icon="tabler:lambda" className="text-fd-primary !size-6" />}
title="AWS Lambda" title="AWS Lambda"
+3 -3
View File
@@ -10,11 +10,11 @@
"astro": "astro" "astro": "astro"
}, },
"dependencies": { "dependencies": {
"@astrojs/check": "^0.9.4", "@astrojs/check": "^0.9.9",
"@astrojs/react": "^4.2.2", "@astrojs/react": "^6.0.1",
"@types/react": "^19.0.12", "@types/react": "^19.0.12",
"@types/react-dom": "^19.0.4", "@types/react-dom": "^19.0.4",
"astro": "^5.16.9", "astro": "^7.0.7",
"bknd": "file:../../app", "bknd": "file:../../app",
"react": "^19.1.0", "react": "^19.1.0",
"react-dom": "^19.1.0", "react-dom": "^19.1.0",
-1
View File
@@ -1,5 +1,4 @@
--- ---
import Card from "../components/Card.astro";
interface Props { interface Props {
title: string; title: string;
} }
-31
View File
@@ -1,31 +0,0 @@
dist
.wrangler
.output
.vercel
.netlify
.vinxi
app.config.timestamp_*.js
# Environment
.env
.env*.local
# dependencies
/node_modules
# IDEs and editors
/.idea
.project
.classpath
*.launch
.settings/
# Temp
gitignore
# System Files
.DS_Store
Thumbs.db
public/admin
data.db
-59
View File
@@ -1,59 +0,0 @@
# bknd starter: Solid Start
A minimal example of a Solid Start project with bknd integration.
## Project Structure
Inside of your Solid Start project, you'll see the following folders and files:
```text
.
├── bknd.config.ts
├── bun.lock
├── package.json
├── public
│ ├── admin # generated by bknd and contains the admin UI
│ ├── bknd.ico
│ ├── bknd.svg
│ ├── file.svg
│ ├── globe.svg
│ ├── solid.svg
│ └── window.svg
├── README.md # you're here
├── src
│ ├── app.css
│ ├── app.tsx
│ ├── components
│ │ ├── Footer.tsx
│ │ └── List.tsx
│ ├── entry-client.tsx
│ ├── entry-server.tsx
│ ├── global.d.ts
│ ├── lib
│ │ └── bknd.ts # initializes bknd instance
│ ├── middleware
│ │ └── index.ts # mounts bknd middleware
│ └── routes
│ ├── [...404].tsx
│ ├── index.tsx
│ └── user.tsx
├── tsconfig.json
└── vite.config.ts
```
Here is a quick overview about how to adjust the behavior of `bknd`:
* Initialization of the `bknd` config with helper functions are located at `src/lib/bknd.ts`
* Admin UI is rendered using `src/middleware/index.ts`
## Commands
All commands are run from the root of the project, from a terminal:
| Command | Action |
|:--------------------------|:-------------------------------------------------|
| `npm install` | Installs dependencies |
| `npm run dev` | Starts local dev server at `localhost:3000` |
| `npm run build` | Build your production site |
## Want to learn more?
Feel free to check [our documentation](https://docs.bknd.io/integration/solid-start) or jump into our [Discord server](https://discord.gg/952SFk8Tb8).
-51
View File
@@ -1,51 +0,0 @@
import { em, entity, text, boolean } from "bknd";
import { secureRandomString } from "bknd/utils";
import type { SolidStartBkndConfig } from "bknd/adapter/solid-start";
const schema = em({
todos: entity("todos", {
title: text(),
done: boolean(),
}),
});
// register your schema to get automatic type completion
type Database = (typeof schema)["DB"];
declare module "bknd" {
interface DB extends Database { }
}
export default {
connection: { url: "file:data.db" },
options: {
// the seed option is only executed if the database was empty
seed: async (ctx) => {
// create some entries
await ctx.em.mutator("todos").insertMany([
{ title: "Learn bknd", done: true },
{ title: "Build something cool", done: false },
]);
// and create a user
await ctx.app.module.auth.createUser({
email: "test@bknd.io",
password: "12345678",
});
},
},
config: {
data: schema.toJSON(),
auth: {
enabled: true,
jwt: {
secret: secureRandomString(32),
},
},
},
adminOptions: {
adminBasepath: "/admin",
assetsPath: "/admin/",
logoReturnPath: "../..",
},
} satisfies SolidStartBkndConfig;
-28
View File
@@ -1,28 +0,0 @@
{
"name": "example-basic",
"type": "module",
"scripts": {
"dev": "vite dev",
"build": "vite build",
"start": "vite start",
"preview": "vite preview",
"typegen": "bunx tsx node_modules/.bin/bknd types --outfile bknd-types.d.ts",
"postinstall": "bun run bknd copy-assets --out public/admin"
},
"dependencies": {
"@solidjs/meta": "^0.29.4",
"@solidjs/router": "^1.0.0",
"@solidjs/start": "2.0.5",
"bknd": "file:../../app",
"nitro": "3.0.260903-beta",
"solid-js": "^1.9.5",
"vite": "^8.3.0"
},
"engines": {
"node": ">=22"
},
"devDependencies": {
"@tailwindcss/vite": "^4.1.18",
"tailwindcss": "^4.1.18"
}
}
Binary file not shown.

Before

Width:  |  Height:  |  Size: 15 KiB

-14
View File
@@ -1,14 +0,0 @@
<svg
width="578"
height="188"
viewBox="0 0 578 188"
fill="black"
xmlns="http://www.w3.org/2000/svg"
>
<path
fill-rule="evenodd"
clip-rule="evenodd"
d="M41.5 34C37.0817 34 33.5 37.5817 33.5 42V146C33.5 150.418 37.0817 154 41.5 154H158.5C162.918 154 166.5 150.418 166.5 146V42C166.5 37.5817 162.918 34 158.5 34H41.5ZM123.434 113.942C124.126 111.752 124.5 109.42 124.5 107C124.5 94.2975 114.203 84 101.5 84C99.1907 84 96.9608 84.3403 94.8579 84.9736L87.2208 65.1172C90.9181 63.4922 93.5 59.7976 93.5 55.5C93.5 49.701 88.799 45 83 45C77.201 45 72.5 49.701 72.5 55.5C72.5 61.299 77.201 66 83 66C83.4453 66 83.8841 65.9723 84.3148 65.9185L92.0483 86.0256C87.1368 88.2423 83.1434 92.1335 80.7957 96.9714L65.4253 91.1648C65.4746 90.7835 65.5 90.3947 65.5 90C65.5 85.0294 61.4706 81 56.5 81C51.5294 81 47.5 85.0294 47.5 90C47.5 94.9706 51.5294 99 56.5 99C60.0181 99 63.0648 96.9814 64.5449 94.0392L79.6655 99.7514C78.9094 102.03 78.5 104.467 78.5 107C78.5 110.387 79.2321 113.603 80.5466 116.498L69.0273 123.731C67.1012 121.449 64.2199 120 61 120C55.201 120 50.5 124.701 50.5 130.5C50.5 136.299 55.201 141 61 141C66.799 141 71.5 136.299 71.5 130.5C71.5 128.997 71.1844 127.569 70.6158 126.276L81.9667 119.149C86.0275 125.664 93.2574 130 101.5 130C110.722 130 118.677 124.572 122.343 116.737L132.747 120.899C132.585 121.573 132.5 122.276 132.5 123C132.5 127.971 136.529 132 141.5 132C146.471 132 150.5 127.971 150.5 123C150.5 118.029 146.471 114 141.5 114C138.32 114 135.525 115.649 133.925 118.139L123.434 113.942Z"
/>
<path d="M243.9 151.5C240.4 151.5 237 151 233.7 150C230.4 149 227.4 147.65 224.7 145.95C222 144.15 219.75 142.15 217.95 139.95C216.15 137.65 215 135.3 214.5 132.9L219.3 131.1L218.25 149.7H198.15V39H219.45V89.25L215.4 87.6C216 85.2 217.15 82.9 218.85 80.7C220.55 78.4 222.7 76.4 225.3 74.7C227.9 72.9 230.75 71.5 233.85 70.5C236.95 69.5 240.15 69 243.45 69C250.35 69 256.5 70.8 261.9 74.4C267.3 77.9 271.55 82.75 274.65 88.95C277.85 95.15 279.45 102.25 279.45 110.25C279.45 118.25 277.9 125.35 274.8 131.55C271.7 137.75 267.45 142.65 262.05 146.25C256.75 149.75 250.7 151.5 243.9 151.5ZM238.8 133.35C242.8 133.35 246.25 132.4 249.15 130.5C252.15 128.5 254.5 125.8 256.2 122.4C257.9 118.9 258.75 114.85 258.75 110.25C258.75 105.75 257.9 101.75 256.2 98.25C254.6 94.75 252.3 92.05 249.3 90.15C246.3 88.25 242.8 87.3 238.8 87.3C234.8 87.3 231.3 88.25 228.3 90.15C225.3 92.05 222.95 94.75 221.25 98.25C219.55 101.75 218.7 105.75 218.7 110.25C218.7 114.85 219.55 118.9 221.25 122.4C222.95 125.8 225.3 128.5 228.3 130.5C231.3 132.4 234.8 133.35 238.8 133.35ZM308.312 126.15L302.012 108.6L339.512 70.65H367.562L308.312 126.15ZM288.062 150V39H309.362V150H288.062ZM341.762 150L313.262 114.15L328.262 102.15L367.412 150H341.762ZM371.675 150V70.65H392.075L392.675 86.85L388.475 88.65C389.575 85.05 391.525 81.8 394.325 78.9C397.225 75.9 400.675 73.5 404.675 71.7C408.675 69.9 412.875 69 417.275 69C423.275 69 428.275 70.2 432.275 72.6C436.375 75 439.425 78.65 441.425 83.55C443.525 88.35 444.575 94.3 444.575 101.4V150H423.275V103.05C423.275 99.45 422.775 96.45 421.775 94.05C420.775 91.65 419.225 89.9 417.125 88.8C415.125 87.6 412.625 87.1 409.625 87.3C407.225 87.3 404.975 87.7 402.875 88.5C400.875 89.2 399.125 90.25 397.625 91.65C396.225 93.05 395.075 94.65 394.175 96.45C393.375 98.25 392.975 100.2 392.975 102.3V150H382.475C380.175 150 378.125 150 376.325 150C374.525 150 372.975 150 371.675 150ZM488.536 151.5C481.636 151.5 475.436 149.75 469.936 146.25C464.436 142.65 460.086 137.8 456.886 131.7C453.786 125.5 452.236 118.35 452.236 110.25C452.236 102.35 453.786 95.3 456.886 89.1C460.086 82.9 464.386 78 469.786 74.4C475.286 70.8 481.536 69 488.536 69C492.236 69 495.786 69.6 499.186 70.8C502.686 71.9 505.786 73.45 508.486 75.45C511.286 77.45 513.536 79.7 515.236 82.2C516.936 84.6 517.886 87.15 518.086 89.85L512.686 90.75V39H533.986V150H513.886L512.986 131.7L517.186 132.15C516.986 134.65 516.086 137.05 514.486 139.35C512.886 141.65 510.736 143.75 508.036 145.65C505.436 147.45 502.436 148.9 499.036 150C495.736 151 492.236 151.5 488.536 151.5ZM493.336 133.8C497.336 133.8 500.836 132.8 503.836 130.8C506.836 128.8 509.186 126.05 510.886 122.55C512.586 119.05 513.436 114.95 513.436 110.25C513.436 105.65 512.586 101.6 510.886 98.1C509.186 94.5 506.836 91.75 503.836 89.85C500.836 87.85 497.336 86.85 493.336 86.85C489.336 86.85 485.836 87.85 482.836 89.85C479.936 91.75 477.636 94.5 475.936 98.1C474.336 101.6 473.536 105.65 473.536 110.25C473.536 114.95 474.336 119.05 475.936 122.55C477.636 126.05 479.936 128.8 482.836 130.8C485.836 132.8 489.336 133.8 493.336 133.8Z" />
</svg>

Before

Width:  |  Height:  |  Size: 4.5 KiB

-1
View File
@@ -1 +0,0 @@
<svg fill="none" viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg"><path d="M14.5 13.5V5.41a1 1 0 0 0-.3-.7L9.8.29A1 1 0 0 0 9.08 0H1.5v13.5A2.5 2.5 0 0 0 4 16h8a2.5 2.5 0 0 0 2.5-2.5m-1.5 0v-7H8v-5H3v12a1 1 0 0 0 1 1h8a1 1 0 0 0 1-1M9.5 5V2.12L12.38 5zM5.13 5h-.62v1.25h2.12V5zm-.62 3h7.12v1.25H4.5zm.62 3h-.62v1.25h7.12V11z" clip-rule="evenodd" fill="#666" fill-rule="evenodd"/></svg>

Before

Width:  |  Height:  |  Size: 391 B

-1
View File
@@ -1 +0,0 @@
<svg fill="none" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><g clip-path="url(#a)"><path fill-rule="evenodd" clip-rule="evenodd" d="M10.27 14.1a6.5 6.5 0 0 0 3.67-3.45q-1.24.21-2.7.34-.31 1.83-.97 3.1M8 16A8 8 0 1 0 8 0a8 8 0 0 0 0 16m.48-1.52a7 7 0 0 1-.96 0H7.5a4 4 0 0 1-.84-1.32q-.38-.89-.63-2.08a40 40 0 0 0 3.92 0q-.25 1.2-.63 2.08a4 4 0 0 1-.84 1.31zm2.94-4.76q1.66-.15 2.95-.43a7 7 0 0 0 0-2.58q-1.3-.27-2.95-.43a18 18 0 0 1 0 3.44m-1.27-3.54a17 17 0 0 1 0 3.64 39 39 0 0 1-4.3 0 17 17 0 0 1 0-3.64 39 39 0 0 1 4.3 0m1.1-1.17q1.45.13 2.69.34a6.5 6.5 0 0 0-3.67-3.44q.65 1.26.98 3.1M8.48 1.5l.01.02q.41.37.84 1.31.38.89.63 2.08a40 40 0 0 0-3.92 0q.25-1.2.63-2.08a4 4 0 0 1 .85-1.32 7 7 0 0 1 .96 0m-2.75.4a6.5 6.5 0 0 0-3.67 3.44 29 29 0 0 1 2.7-.34q.31-1.83.97-3.1M4.58 6.28q-1.66.16-2.95.43a7 7 0 0 0 0 2.58q1.3.27 2.95.43a18 18 0 0 1 0-3.44m.17 4.71q-1.45-.12-2.69-.34a6.5 6.5 0 0 0 3.67 3.44q-.65-1.27-.98-3.1" fill="#666"/></g><defs><clipPath id="a"><path fill="#fff" d="M0 0h16v16H0z"/></clipPath></defs></svg>

Before

Width:  |  Height:  |  Size: 1.0 KiB

-1
View File
@@ -1 +0,0 @@
<svg data-hk="000000220" width="500" height="500" viewBox="0 0 500 500" fill="none" xmlns="http://www.w3.org/2000/svg" role="presentation" class="drop-shadow-[10px_20px_35px_rgb(125,211,252,0.3)] size-52 md:size-[400px] mx-auto"><path d="M233.205 430.856L304.742 425.279C304.742 425.279 329.208 421.295 343.569 397.659L293.041 385.443L233.205 430.856Z" fill="url(#paint0_linear_1_2)"></path><path d="M134.278 263.278C113.003 264.341 73.6443 268.059 73.6443 268.059L245.173 392.614L284.265 402.44L343.569 397.925L170.977 273.105C170.977 273.105 157.148 263.278 137.203 263.278C136.139 263.278 135.342 263.278 134.278 263.278Z" fill="url(#paint1_linear_1_2)"></path><path d="M355.536 238.58L429.2 234.065C429.2 234.065 454.464 230.348 468.825 206.977L416.435 193.964L355.536 238.58Z" fill="url(#paint2_linear_1_2)"></path><path d="M251.289 68.6128C229.217 69.4095 188.795 72.5964 188.795 72.5964L367.503 200.072L407.926 210.429L469.09 206.712L289.318 78.9702C289.318 78.9702 274.426 68.6128 253.417 68.6128C252.885 68.6128 252.087 68.6128 251.289 68.6128Z" fill="url(#paint3_linear_1_2)"></path><path d="M31.0946 295.679C30.8287 295.945 30.8287 296.21 30.8287 296.475L77.8993 330.469L202.623 420.764C228.95 439.62 264.586 431.653 282.67 402.44L187.465 333.921L110.077 277.62C100.504 270.715 89.8663 267.528 79.2289 267.528C60.6134 267.528 42.2639 277.354 31.0946 295.679Z" fill="url(#paint4_linear_1_2)"></path><path d="M147.043 99.9505C147.043 100.216 146.776 100.482 146.511 100.747L195.442 135.538L244.374 170.062L325.751 227.957C353.142 247.345 389.841 239.642 407.925 210.695L358.461 175.374L308.997 140.318L228.153 82.6881C218.047 75.5177 206.611 72.0652 195.442 72.0652C176.561 72.3308 158.212 81.8915 147.043 99.9505Z" fill="url(#paint5_linear_1_2)"></path><path d="M112.471 139.255L175.497 208.305C178.423 212.289 181.614 216.006 185.337 219.193L308.199 354.105L369.364 350.387C387.448 321.439 380.002 282.135 352.611 262.748L271.234 204.852L222.568 170.328L173.636 135.538L112.471 139.255Z" fill="url(#paint6_linear_1_2)"></path><path d="M111.939 140.052C94.1213 168.734 101.567 207.509 128.427 226.629L209.005 283.994L258.735 319.049L308.199 354.105C326.283 325.158 318.836 285.852 291.445 266.465L112.471 139.255C112.471 139.521 112.204 139.787 111.939 140.052Z" fill="url(#paint7_linear_1_2)"></path><defs><linearGradient id="paint0_linear_1_2" x1="359.728" y1="56.8062" x2="265.623" y2="521.28" gradientUnits="userSpaceOnUse"><stop stop-color="#1593F5"></stop><stop offset="1" stop-color="#0084CE"></stop></linearGradient><linearGradient id="paint1_linear_1_2" x1="350.496" y1="559.872" x2="-44.0802" y2="-73.2062" gradientUnits="userSpaceOnUse"><stop stop-color="#1593F5"></stop><stop offset="1" stop-color="#0084CE"></stop></linearGradient><linearGradient id="paint2_linear_1_2" x1="610.25" y1="570.526" x2="372.635" y2="144.034" gradientUnits="userSpaceOnUse"><stop stop-color="white"></stop><stop offset="1" stop-color="#15ABFF"></stop></linearGradient><linearGradient id="paint3_linear_1_2" x1="188.808" y1="-180.608" x2="390.515" y2="281.703" gradientUnits="userSpaceOnUse"><stop stop-color="white"></stop><stop offset="1" stop-color="#79CFFF"></stop></linearGradient><linearGradient id="paint4_linear_1_2" x1="415.84" y1="-4.74684" x2="95.1922" y2="439.83" gradientUnits="userSpaceOnUse"><stop stop-color="#0057E5"></stop><stop offset="1" stop-color="#0084CE"></stop></linearGradient><linearGradient id="paint5_linear_1_2" x1="343.141" y1="-21.5427" x2="242.301" y2="256.708" gradientUnits="userSpaceOnUse"><stop stop-color="white"></stop><stop offset="1" stop-color="#15ABFF"></stop></linearGradient><linearGradient id="paint6_linear_1_2" x1="469.095" y1="533.421" x2="-37.6939" y2="-135.731" gradientUnits="userSpaceOnUse"><stop stop-color="white"></stop><stop offset="1" stop-color="#79CFFF"></stop></linearGradient><linearGradient id="paint7_linear_1_2" x1="380.676" y1="-89.0869" x2="120.669" y2="424.902" gradientUnits="userSpaceOnUse"><stop stop-color="white"></stop><stop offset="1" stop-color="#79CFFF"></stop></linearGradient></defs></svg>

Before

Width:  |  Height:  |  Size: 4.0 KiB

-1
View File
@@ -1 +0,0 @@
<svg fill="none" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><path fill-rule="evenodd" clip-rule="evenodd" d="M1.5 2.5h13v10a1 1 0 0 1-1 1h-11a1 1 0 0 1-1-1zM0 1h16v11.5a2.5 2.5 0 0 1-2.5 2.5h-11A2.5 2.5 0 0 1 0 12.5zm3.75 4.5a.75.75 0 1 0 0-1.5.75.75 0 0 0 0 1.5M7 4.75a.75.75 0 1 1-1.5 0 .75.75 0 0 1 1.5 0m1.75.75a.75.75 0 1 0 0-1.5.75.75 0 0 0 0 1.5" fill="#666"/></svg>

Before

Width:  |  Height:  |  Size: 385 B

-33
View File
@@ -1,33 +0,0 @@
@import url('https://fonts.googleapis.com/css2?family=Geist+Mono:wght@100..900&display=swap');
@import "tailwindcss";
.geist-mono-100 {
font-optical-sizing: auto;
font-weight: 100;
font-style: normal;
}
:root {
--background: #ffffff;
--foreground: #171717;
font-family: "Geist Mono", monospace;
}
@media (prefers-color-scheme: dark) {
:root {
--background: #0a0a0a;
--foreground: #ededed;
}
}
@theme {
--font-sans: var(--font-geist-sans);
--font-mono: var(--font-geist-mono);
--color-background: var(--background);
--color-foreground: var(--foreground);
}
body {
@apply bg-background text-foreground;
font-family: var(--font-geist-mono-100)
}
-20
View File
@@ -1,20 +0,0 @@
import { MetaProvider, Title } from "@solidjs/meta";
import { Router } from "@solidjs/router";
import { FileRoutes } from "@solidjs/start/router";
import { Suspense } from "solid-js";
import "./app.css";
export default function App() {
return (
<Router
root={props => (
<MetaProvider>
<Title>Solid Start 🤝 Bknd.io</Title>
<Suspense>{props.children}</Suspense>
</MetaProvider>
)}
>
<FileRoutes />
</Router>
);
}
-53
View File
@@ -1,53 +0,0 @@
import { A, useLocation } from "@solidjs/router";
export function Footer() {
const pathname = useLocation().pathname;
return (
<footer class="row-start-3 flex gap-6 flex-wrap items-center justify-center">
<A
class="flex items-center gap-2 hover:underline hover:underline-offset-4"
href={pathname === "/" ? "/user" : "/"}
>
<img
aria-hidden
src="/file.svg"
alt="File icon"
width={16}
height={16}
/>
{pathname === "/" ? "User" : "Home"}
</A>
<A
target="_self"
class="flex items-center gap-2 hover:underline hover:underline-offset-4"
href="/admin"
rel="noopener noreferrer"
>
<img
aria-hidden
src="/window.svg"
alt="Window icon"
width={16}
height={16}
/>
Admin
</A>
<a
class="flex items-center gap-2 hover:underline hover:underline-offset-4"
href={"https://bknd.io"}
target="_blank"
rel="noopener noreferrer"
>
<img
aria-hidden
src="/globe.svg"
alt="Globe icon"
width={16}
height={16}
/>
Go to bknd.io →
</a>
</footer>
);
}
-11
View File
@@ -1,11 +0,0 @@
import { JSX } from "solid-js";
export const List = ({ items = [] }: { items: JSX.Element[] }) => (
<ol class="list-inside list-decimal text-sm text-center sm:text-left font-[family-name:var(--font-geist-mono)]">
{items.map((item, i) => (
<li class={i < items.length - 1 ? "mb-2" : ""}>
{item}
</li>
))}
</ol>
);
-4
View File
@@ -1,4 +0,0 @@
// @refresh reload
import { mount, StartClient } from "@solidjs/start/client";
mount(() => <StartClient />, document.getElementById("app")!);
-21
View File
@@ -1,21 +0,0 @@
// @refresh reload
import { createHandler, StartServer } from "@solidjs/start/server";
export default createHandler(() => (
<StartServer
document={({ assets, children, scripts }) => (
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="icon" href="/solid.svg" />
{assets}
</head>
<body>
<div id="app">{children}</div>
{scripts}
</body>
</html>
)}
/>
));
-1
View File
@@ -1 +0,0 @@
/// <reference types="@solidjs/start/env" />
-30
View File
@@ -1,30 +0,0 @@
import { getApp as getBkndApp } from "bknd/adapter/solid-start";
import bkndConfig from "../../bknd.config";
import type { App } from "bknd";
let client: App | null = null;
export const getApp = async () => {
if (!client) {
client = await getBkndApp(bkndConfig);
}
return client;
};
export async function getApi({
headers,
verify,
}: {
verify?: boolean;
headers?: Headers;
}) {
const app = await getApp();
if (verify) {
const api = app.getApi({ headers });
await api.verifyAuth();
return api;
}
return app.getApi();
}
-20
View File
@@ -1,20 +0,0 @@
import { createMiddleware } from "@solidjs/start/middleware";
import config from "../../bknd.config";
import { serve } from "bknd/adapter/solid-start";
const handler = serve(config);
export default createMiddleware({
onRequest: async (event) => {
const url = new URL(event.request.url);
const pathname = url.pathname;
if (pathname.startsWith("/api") || pathname !== "/") {
const res = await handler(event.request);
if (res && res.status !== 404) {
return res;
}
}
},
});
-19
View File
@@ -1,19 +0,0 @@
import { Title } from "@solidjs/meta";
import { HttpStatusCode } from "@solidjs/start";
export default function NotFound() {
return (
<main>
<Title>Not Found</Title>
<HttpStatusCode code={404} />
<h1>Page Not Found</h1>
<p>
Visit{" "}
<a href="https://start.solidjs.com" target="_blank">
start.solidjs.com
</a>{" "}
to learn how to build SolidStart apps.
</p>
</main>
);
}
-150
View File
@@ -1,150 +0,0 @@
import type { DB } from "bknd";
import { For, Suspense } from "solid-js";
import { Footer } from "~/components/Footer";
import { List } from "~/components/List";
import { getApi } from "~/lib/bknd";
import { action, redirect, useAction, useSubmission } from "@solidjs/router";
import { query, createAsync } from "@solidjs/router";
type Todo = DB['todos'];
export const getTodo = async () => {
"use server"
const api = await getApi({});
const limit = 5;
const todos = await api.data.readMany("todos");
const total = todos.body.meta.total as number;
return { total, todos: todos as unknown as Todo[], limit };
};
const getTodosFromServer = query(async () => await getTodo(), "getTodosFromServer");
const createTodo = action(async (formData: FormData) => {
"use server"
const title = formData.get("title") as string;
const api = await getApi({});
await api.data.createOne("todos", { title });
throw redirect("/", { revalidate: getTodosFromServer.keyFor() });
}, "createTodo");
const completeTodo = action(async (todo: Todo) => {
"use server"
const api = await getApi({});
await api.data.updateOne("todos", todo.id, {
done: !todo.done,
});
throw redirect("/", { revalidate: getTodosFromServer.keyFor() });
}, "completeTodo");
const deleteTodo = action(async (todo: Todo) => {
"use server"
const api = await getApi({});
await api.data.deleteOne("todos", todo.id);
throw redirect("/", { revalidate: getTodosFromServer.keyFor() });
}, "deleteTodo");
export default function Home() {
const data = createAsync(() => getTodosFromServer());
const submission = useSubmission(createTodo);
const updateTodo = useAction(completeTodo);
const removeTodo = useAction(deleteTodo);
return (
<div class="grid grid-rows-[20px_1fr_20px] items-center justify-items-center min-h-screen p-8 pb-20 gap-16 sm:p-20 ">
<main class="flex flex-col gap-8 row-start-2 items-center sm:items-start">
<div class="flex flex-row items-center justify-evenly min-w-full">
<img
class="size-18"
src="/solid.svg"
alt="Solid Start logo"
/>
<div class="ml-3.5 mr-2 opacity-70">&amp;</div>
<img
class="dark:invert"
src="/bknd.svg"
alt="bknd logo"
width={183}
height={59}
/>
</div>
<Description />
<Suspense>
<div class="flex flex-col border border-foreground/15 w-full py-4 px-5 gap-2">
<h2 class=" mb-1 opacity-70">
<code>What's next?</code>
</h2>
<div class="flex flex-col w-full gap-2">
{(data()?.total ?? 0) > (data()?.limit ?? 0) && (
<div class="bg-foreground/10 flex justify-center p-1 text-xs rounded text-foreground/40">
{(data()?.total ?? 0) - (data()?.limit ?? 0)} more todo(s) hidden
</div>
)}
<div class="flex flex-col gap-3">
<For each={data()?.todos?.splice(0, data()?.limit ?? 0)}>
{(todo) => (
<div class="flex flex-row">
<div class="flex flex-row flex-grow items-center gap-3 ml-1">
<input
type="checkbox"
class="flex-shrink-0 cursor-pointer"
checked={Boolean(todo.done)}
onChange={async () => {
await updateTodo(todo);
}}
/>
<div class="text-foreground/90 leading-none">
{todo.title}
</div>
</div>
<button
type="button"
class="cursor-pointer grayscale transition-all hover:grayscale-0 text-xs "
onClick={async () => {
await removeTodo(todo);
}}
>
❌
</button>
</div>
)}
</For>
</div>
<form
class="flex flex-row w-full gap-3 mt-2"
action={createTodo}
method="post"
>
<input
type="text"
name="title"
placeholder="New todo"
class="py-2 px-4 flex flex-grow rounded-sm bg-black/5 focus:bg-black/10 dark:bg-white/5 dark:focus:bg-white/10 transition-colors outline-none"
/>
<button type="submit" class="cursor-pointer" disabled={submission.pending}>
{submission.pending ? "Adding..." : "Add"}
</button>
</form>
</div>
</div>
</Suspense>
</main>
<Footer />
</div>);
}
const Description = () => (
<List
items={[
"Get started with a full backend.",
"Focus on what matters instead of repetition.",
]}
/>
);
-139
View File
@@ -1,139 +0,0 @@
import { A } from "@solidjs/router";
import type { DB } from "bknd";
import { createResource, Suspense } from "solid-js";
import { getRequestEvent } from "solid-js/web";
import { Footer } from "~/components/Footer";
import { List } from "~/components/List";
import { getApi } from "~/lib/bknd";
const getUser = async () => {
"use server"
const request = getRequestEvent()?.request;
const api = await getApi({ verify: true, headers: request?.headers });
return api.getUser();
}
type Todo = DB['todos'];
export const getTodo = async () => {
"use server"
const api = await getApi({});
const limit = 5;
const todos = await api.data.readMany("todos");
const total = todos.body.meta.total as number;
return { total, todos: todos as unknown as Todo[], limit };
};
export default function Home() {
const [data] = createResource(async () => {
const todo = await getTodo();
const user = await getUser()
return { todo, user };
}, {
initialValue: {
todo: {
todos: [],
limit: 0,
total: 0
},
user: null
}
});
return (
<div class="grid grid-rows-[20px_1fr_20px] items-center justify-items-center min-h-screen p-8 pb-20 gap-16 sm:p-20">
<main class="flex flex-col gap-8 row-start-2 items-center sm:items-start">
<div class="flex flex-row items-center justify-evenly min-w-full">
<img
class="size-18"
src="/solid.svg"
alt="Solid logo"
/>
<div class="ml-3.5 mr-2 opacity-70">&amp;</div>
<img
class="dark:invert"
src="/bknd.svg"
alt="bknd logo"
width={183}
height={59}
/>
</div>
<List items={(data()?.todo.todos ?? []).map((todo) => todo.title)} />
<Buttons />
<Suspense fallback={<p>Loading...</p>}>
<div>
{data()?.user ? (
<>
Logged in as {data()?.user?.email}.
<A
class="underline"
// target="_self" is required to prevent solid router from intercepting the link
target="_self"
href={"/api/auth/logout"}
>
Logout
</A>
</>
) : (
<div class="flex flex-col gap-1">
<p>
Not logged in.
<A
class="underline"
// target="_self" is required to prevent solid router from intercepting the link
target="_self"
href={"/admin/auth/login"}
>
Login
</A>
</p>
<p class="text-xs opacity-50">
Sign in with:
<b>
<code>test@bknd.io</code>
</b>
/
<b>
<code>12345678</code>
</b>
</p>
</div>
)}
</div>
</Suspense>
</main>
<Footer />
</div>
);
}
function Buttons() {
return (
<div class="flex gap-4 items-center flex-col sm:flex-row">
<a
class="rounded-full border border-solid border-transparent transition-colors flex items-center justify-center bg-foreground gap-2 text-white hover:bg-[#383838] dark:hover:bg-[#ccc] dark:text-black text-sm sm:text-base h-10 sm:h-12 px-4 sm:px-5"
href="https://bknd.io/"
target="_blank"
rel="noopener noreferrer"
>
<img
class="grayscale"
src="/bknd.ico"
alt="bknd logomark"
width={20}
height={20}
/>
Go To Bknd.io
</a>
<a
class="rounded-full border border-solid border-black/[.08] dark:border-white/[.145] transition-colors flex items-center justify-center hover:bg-[#f2f2f2] dark:hover:bg-[#1a1a1a] hover:border-transparent text-sm sm:text-base h-10 sm:h-12 px-4 sm:px-5 sm:min-w-44"
href="https://docs.bknd.io/start"
target="_blank"
rel="noopener noreferrer"
>
Read our docs
</a>
</div>
);
}
-19
View File
@@ -1,19 +0,0 @@
{
"compilerOptions": {
"target": "ESNext",
"module": "ESNext",
"moduleResolution": "bundler",
"allowSyntheticDefaultImports": true,
"esModuleInterop": true,
"jsx": "preserve",
"jsxImportSource": "solid-js",
"allowJs": true,
"strict": true,
"noEmit": true,
"types": ["vite/client"],
"isolatedModules": true,
"paths": {
"~/*": ["./src/*"]
}
}
}
-15
View File
@@ -1,15 +0,0 @@
import { defineConfig } from "vite";
import { nitro } from "nitro/vite";
import { solidStart } from "@solidjs/start/config";
import tailwindcss from "@tailwindcss/vite";
export default defineConfig({
plugins: [
tailwindcss(),
solidStart({
middleware: "./src/middleware/index.ts",
}),
nitro(),
],
});
+2 -2
View File
@@ -5,7 +5,7 @@
"type": "module", "type": "module",
"packageManager": "bun@1.3.3", "packageManager": "bun@1.3.3",
"engines": { "engines": {
"node": ">=22.13" "node": ">=22.18"
}, },
"scripts": { "scripts": {
"updater": "bun x npm-check-updates -ui", "updater": "bun x npm-check-updates -ui",
@@ -18,7 +18,7 @@
"devDependencies": { "devDependencies": {
"@biomejs/biome": "2.3.3", "@biomejs/biome": "2.3.3",
"@tsconfig/strictest": "^2.0.8", "@tsconfig/strictest": "^2.0.8",
"@types/bun": "^1.3.1", "@types/bun": "^1.3.13",
"@types/lodash-es": "^4.17.12", "@types/lodash-es": "^4.17.12",
"miniflare": "^3.20250718.2", "miniflare": "^3.20250718.2",
"typescript": "^6.0.2", "typescript": "^6.0.2",
+3 -2
View File
@@ -12,13 +12,14 @@
"README.md" "README.md"
], ],
"dependencies": { "dependencies": {
"@libsql/client": "^0.14.0", "@libsql/client": "^0.17.2",
"hono": "^4.6.7" "hono": "^4.6.7"
}, },
"tsup": { "tsdown": {
"entry": [ "entry": [
"src/index.ts" "src/index.ts"
], ],
"dts": false,
"minify": true, "minify": true,
"outDir": "dist", "outDir": "dist",
"format": [ "format": [
+7 -5
View File
@@ -4,14 +4,15 @@
"type": "module", "type": "module",
"sideEffects": false, "sideEffects": false,
"scripts": { "scripts": {
"build": "rm -rf dist && bun tsup && bun run build:types", "build": "rm -rf dist && bun tsdown && bun run build:types",
"watch": "bun tsup --watch --onSuccess 'bun run build:types'", "watch": "bun tsdown --watch --onSuccess 'bun run build:types'",
"build:only": "rm -rf dist && bun tsup", "build:only": "rm -rf dist && bun tsdown",
"types": "bun tsc -p tsconfig.json --noEmit --skipLibCheck", "types": "bun tsc -p tsconfig.json --noEmit --skipLibCheck",
"build:types": "bun tsc --emitDeclarationOnly", "build:types": "bun tsc --emitDeclarationOnly",
"updater": "bun x npm-check-updates -ui", "updater": "bun x npm-check-updates -ui",
"pack": "rm -rf *.tgz && npm pack && mv *.tgz latest.tgz", "pack": "rm -rf *.tgz && npm pack && mv *.tgz latest.tgz",
"prepublishOnly": "bun run build" "prepublishOnly": "bun run build",
"tsdown": "bunx tsdown"
}, },
"publishConfig": { "publishConfig": {
"access": "public" "access": "public"
@@ -33,11 +34,12 @@
"optionalDependencies": { "optionalDependencies": {
"@plasmicapp/loader-nextjs": "^1.0.0" "@plasmicapp/loader-nextjs": "^1.0.0"
}, },
"tsup": { "tsdown": {
"entry": [ "entry": [
"src/index.ts", "src/index.ts",
"src/nextjs/index.tsx" "src/nextjs/index.tsx"
], ],
"dts": false,
"minify": true, "minify": true,
"clean": true, "clean": true,
"external": [ "external": [