mirror of
https://github.com/bknd-io/bknd/
synced 2026-08-02 08:06:00 +00:00
Compare commits
244 Commits
v0.19.0
...
web-adapter
| Author | SHA1 | Date | |
|---|---|---|---|
| dfae51c368 | |||
| 9e0382389e | |||
| 62f6985e8f | |||
| 609eeade23 | |||
| 2eba931e39 | |||
| 54aae56734 | |||
| 8a90b9356b | |||
| b070fb591e | |||
| 6489d08434 | |||
| 81bf41ce34 | |||
| d9ab583a16 | |||
| e68df5e606 | |||
| 6304ef81f6 | |||
| 6c7e82781d | |||
| a8e5c45a22 | |||
| ee28c2ef0c | |||
| 9219bf3b3c | |||
| e437ce7120 | |||
| 2417833ed7 | |||
| ab1eddcb6a | |||
| 237b42bb9c | |||
| d206c38d87 | |||
| d160af5cec | |||
| d03cd7f7bc | |||
| 4afba215b9 | |||
| dc8aca6a97 | |||
| 4121597fa2 | |||
| 9628720f87 | |||
| ff216ec4e5 | |||
| 06f9c3ee15 | |||
| 7751ee5db8 | |||
| feb3911d46 | |||
| ab545d3ca2 | |||
| 06c3a6f89b | |||
| 898a825f6e | |||
| a5ddf6aa93 | |||
| 5aa286298c | |||
| 55cb2bacef | |||
| e6ea3f64d7 | |||
| a5f5ea2084 | |||
| 6fb8e9a0e7 | |||
| abc6de6ad3 | |||
| 71b9a0f546 | |||
| 038ec0d672 | |||
| 7832328a50 | |||
| e5bfc602e1 | |||
| 0318e595f2 | |||
| 80b0716a4a | |||
| 3894271b17 | |||
| 8bf8b22e57 | |||
| 367d5878df | |||
| fb429e57e2 | |||
| 9008f9c6a3 | |||
| 6321a9935a | |||
| eb22289460 | |||
| c3198394de | |||
| 51237f5e1a | |||
| 01483b912f | |||
| 6288faef33 | |||
| 384e337bbd | |||
| cc1e1976f7 | |||
| 224d98879a | |||
| d1522c97ea | |||
| 8805f017a1 | |||
| 0ef06375c0 | |||
| 3d5c2cd3a8 | |||
| fc60dfd042 | |||
| c8ee30b3da | |||
| b85c3a8a9b | |||
| e20c2ef92c | |||
| 5873baad3c | |||
| aca162f9c8 | |||
| 9f0997c28a | |||
| 1c114d9533 | |||
| 68063986d1 | |||
| 53f8609e9d | |||
| 833bfa5049 | |||
| defcdfef0b | |||
| 348ac7f8b0 | |||
| 16b1cde8ea | |||
| 436b195242 | |||
| ccd504440e | |||
| 023f5391e4 | |||
| 11e3488917 | |||
| 9685c5d4e1 | |||
| 9b008be512 | |||
| 5352331464 | |||
| d9bce049ef | |||
| 0e4f25cf11 | |||
| 4a5bdade8d | |||
| 047bb80a97 | |||
| d826cb23a3 | |||
| 23a9e7c278 | |||
| a9fe43130e | |||
| 3b7ec06703 | |||
| 55a124b519 | |||
| dc3fe330d7 | |||
| d541167fb3 | |||
| 7e8b357bbb | |||
| 521d8bc6ff | |||
| 19f1941544 | |||
| f9373bd0e6 | |||
| 5384738b67 | |||
| d82e28e6b1 | |||
| c38bc95b1d | |||
| 6651fce099 | |||
| 91a1fc8a0c | |||
| d00e5fe68c | |||
| 6faf0d421f | |||
| 19e51fae63 | |||
| 7e01cc6101 | |||
| 103cbd11df | |||
| 03d3b8e407 | |||
| a97a79f11e | |||
| 90b4de7093 | |||
| 81f3914e7f | |||
| 5163e2142e | |||
| 15ed075de3 | |||
| 09b9a5e857 | |||
| 4f7925dfd8 | |||
| 21e970cd8c | |||
| 40b70e7a20 | |||
| 9958dd7308 | |||
| fef77eea61 | |||
| ed41887d74 | |||
| 8ba4793160 | |||
| 65e17db2a2 | |||
| e21b5e5b55 | |||
| 959dee013e | |||
| a39e76a440 | |||
| acc10377ca | |||
| 506c7d84cc | |||
| 7ba542c040 | |||
| b784d8611a | |||
| a21d4ad6a7 | |||
| 731b7a7e8d | |||
| e56fc9c368 | |||
| d1aa2da5b1 | |||
| 52fe9aa085 | |||
| 065821d9a5 | |||
| 0fc817382a | |||
| 2e6b95e484 | |||
| 4e31f48917 | |||
| b2872eb196 | |||
| 3d804f5ac5 | |||
| da025efee1 | |||
| ab1fa4c895 | |||
| ebe3bc2ff5 | |||
| f792d8b93e | |||
| 319469f44b | |||
| 1359741e5f | |||
| 8f4de33a76 | |||
| 43dbc856ce | |||
| 5a8f2b4894 | |||
| 2627213de7 | |||
| 36e1bb1867 | |||
| 0cf1d86213 | |||
| 3fac740771 | |||
| 5e5dc62304 | |||
| c1d6384271 | |||
| f2bd04770a | |||
| 41d43126cb | |||
| a39407c9a3 | |||
| 5d6046b149 | |||
| 000f8d20a8 | |||
| 9e7547e787 | |||
| c3ae4a3999 | |||
| 5c3eeb7642 | |||
| a2fa11ccd0 | |||
| fdee39da62 | |||
| 16a3a67634 | |||
| 2b5e1771de | |||
| a16e017e39 | |||
| 079d613b2e | |||
| ff56d616d9 | |||
| 5b3d36c527 | |||
| 2885fea077 | |||
| 5ce22162c3 | |||
| 3f55c0f2c5 | |||
| 21f642161d | |||
| 7912729159 | |||
| d3e87be604 | |||
| ba3d11edab | |||
| 9ec31373e1 | |||
| 70b25a9f9b | |||
| b6717f0237 | |||
| c57f3e8070 | |||
| c2f4f92d1a | |||
| 6eb8525656 | |||
| e2ebb57564 | |||
| 2b7bbc5df0 | |||
| 8766b742c6 | |||
| 3befa43a9e | |||
| a842808464 | |||
| bd1ef8ed57 | |||
| a0019e5500 | |||
| 8ec67a5492 | |||
| 960f7c3fb2 | |||
| 793c214e6d | |||
| 4094004b83 | |||
| 300d86ff7c | |||
| 4c9b662f6f | |||
| a862cfdcf1 | |||
| de62f4e729 | |||
| 7e399830e5 | |||
| ee2ab982df | |||
| 5be55a6fa6 | |||
| 341eb13425 | |||
| 68fbb6e933 | |||
| 8b36985252 | |||
| ff86240b0e | |||
| 40bbdb904f | |||
| a333d537b0 | |||
| 108c108d82 | |||
| 4575d89cfe | |||
| 0ca0828581 | |||
| 07a57ebf67 | |||
| e9f1241ec3 | |||
| 80903d4ffa | |||
| c8290802e9 | |||
| ac6cd4a900 | |||
| a91ddb1ec3 | |||
| ed47c5bf51 | |||
| dbb19a27f4 | |||
| 71a17696eb | |||
| 2dbafebcea | |||
| 84d4635ec3 | |||
| e9c92b6086 | |||
| 5fa7601ad5 | |||
| 2c7054c317 | |||
| ac891a4b61 | |||
| 412eab6653 | |||
| 2fb07698d5 | |||
| 64e400c4f1 | |||
| 86d6e891a8 | |||
| 7b86611f35 | |||
| 9e316a92f6 | |||
| 12ef72d595 | |||
| 75c29ae5e2 | |||
| f0551f50d1 | |||
| 03aac3437b | |||
| f07f3d1007 | |||
| c833b2b539 | |||
| 6070394cca |
@@ -9,6 +9,21 @@ jobs:
|
|||||||
test:
|
test:
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
|
|
||||||
|
services:
|
||||||
|
postgres:
|
||||||
|
image: postgres:17
|
||||||
|
env:
|
||||||
|
POSTGRES_PASSWORD: postgres
|
||||||
|
POSTGRES_USER: postgres
|
||||||
|
POSTGRES_DB: bknd
|
||||||
|
ports:
|
||||||
|
- 5430:5432
|
||||||
|
options: >-
|
||||||
|
--health-cmd pg_isready
|
||||||
|
--health-interval 10s
|
||||||
|
--health-timeout 5s
|
||||||
|
--health-retries 5
|
||||||
|
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v4
|
- uses: actions/checkout@v4
|
||||||
|
|
||||||
@@ -20,11 +35,11 @@ jobs:
|
|||||||
- name: Setup Bun
|
- name: Setup Bun
|
||||||
uses: oven-sh/setup-bun@v1
|
uses: oven-sh/setup-bun@v1
|
||||||
with:
|
with:
|
||||||
bun-version: "1.2.22"
|
bun-version: "1.3.3"
|
||||||
|
|
||||||
- name: Install dependencies
|
- name: Install dependencies
|
||||||
working-directory: ./app
|
working-directory: ./app
|
||||||
run: bun install
|
run: bun install #--linker=hoisted
|
||||||
|
|
||||||
- name: Build
|
- name: Build
|
||||||
working-directory: ./app
|
working-directory: ./app
|
||||||
|
|||||||
+2
-1
@@ -27,7 +27,8 @@ packages/media/.env
|
|||||||
.npmrc
|
.npmrc
|
||||||
/.verdaccio
|
/.verdaccio
|
||||||
.idea
|
.idea
|
||||||
.vscode
|
.vscode/*
|
||||||
|
!.vscode/settings.json
|
||||||
.git_old
|
.git_old
|
||||||
docker/tmp
|
docker/tmp
|
||||||
.debug
|
.debug
|
||||||
|
|||||||
Vendored
+19
@@ -0,0 +1,19 @@
|
|||||||
|
{
|
||||||
|
"typescript.tsdk": "node_modules/typescript/lib",
|
||||||
|
"biome.enabled": true,
|
||||||
|
"editor.defaultFormatter": "biomejs.biome",
|
||||||
|
"editor.codeActionsOnSave": {
|
||||||
|
//"source.organizeImports.biome": "explicit",
|
||||||
|
"source.fixAll.biome": "explicit"
|
||||||
|
},
|
||||||
|
"typescript.preferences.importModuleSpecifier": "non-relative",
|
||||||
|
"typescript.preferences.autoImportFileExcludePatterns": [
|
||||||
|
"**/dist/**",
|
||||||
|
"**/node_modules/**/dist/**",
|
||||||
|
"**/node_modules/**/!(src|lib|esm)/**" // optional, stricter
|
||||||
|
],
|
||||||
|
"typescript.preferences.includePackageJsonAutoImports": "on",
|
||||||
|
"typescript.tsserver.watchOptions": {
|
||||||
|
"excludeDirectories": ["**/dist", "**/node_modules/**/dist"]
|
||||||
|
}
|
||||||
|
}
|
||||||
+267
@@ -0,0 +1,267 @@
|
|||||||
|
# Contributing to bknd
|
||||||
|
|
||||||
|
Thank you for your interest in contributing to bknd. This guide will help you get started, understand the codebase, and submit contributions that align with the project's direction.
|
||||||
|
|
||||||
|
## Table of Contents
|
||||||
|
|
||||||
|
- [Before You Start](#before-you-start)
|
||||||
|
- [Important Resources](#important-resources)
|
||||||
|
- [Development Setup](#development-setup)
|
||||||
|
- [Project Structure](#project-structure)
|
||||||
|
- [Understanding the Codebase](#understanding-the-codebase)
|
||||||
|
- [Running Tests](#running-tests)
|
||||||
|
- [Code Style](#code-style)
|
||||||
|
- [Submitting Changes](#submitting-changes)
|
||||||
|
- [AI-Generated Code](#ai-generated-code)
|
||||||
|
- [Contributing to Documentation](#contributing-to-documentation)
|
||||||
|
- [Reporting Bugs](#reporting-bugs)
|
||||||
|
- [Getting Help](#getting-help)
|
||||||
|
- [Contributors](#contributors)
|
||||||
|
- [Maintainers](#maintainers)
|
||||||
|
|
||||||
|
## Before You Start
|
||||||
|
|
||||||
|
**Open a GitHub Issue before writing code.** This is the preferred way to propose any change. It lets maintainers and the community align on the approach before time is spent on implementation. If you have discussed a contribution in the [Discord server](https://discord.com/invite/952SFk8Tb8) instead, include a link to the relevant Discord thread in your pull request. Pull requests submitted without a corresponding issue or Discord discussion may be closed.
|
||||||
|
|
||||||
|
**Unsolicited architectural changes will be closed.** The internal architecture of bknd is intentional. Refactors, restructuring, or changes to core patterns must be discussed and approved before any code is written.
|
||||||
|
|
||||||
|
Contributions that are generally welcome (after opening an issue):
|
||||||
|
|
||||||
|
- Bug fixes
|
||||||
|
- New adapters, strategies, or storage backends
|
||||||
|
- Documentation improvements
|
||||||
|
- New examples
|
||||||
|
- Test coverage improvements
|
||||||
|
|
||||||
|
**A note on versioning**: bknd is pre-1.0 and under active development. Full backward compatibility is not guaranteed before v1.0.0. Contributors should be aware that APIs and internal interfaces may change between releases.
|
||||||
|
|
||||||
|
## Important Resources
|
||||||
|
|
||||||
|
- **Documentation**: https://docs.bknd.io
|
||||||
|
- **Issue Tracker**: https://github.com/bknd-io/bknd/issues
|
||||||
|
- **Discord**: https://discord.com/invite/952SFk8Tb8
|
||||||
|
- **FAQ / Search**: https://www.answeroverflow.com/c/1308395750564302952
|
||||||
|
|
||||||
|
## Development Setup
|
||||||
|
|
||||||
|
### Prerequisites
|
||||||
|
|
||||||
|
- Node.js 22.13 or higher
|
||||||
|
- Bun 1.3.3
|
||||||
|
|
||||||
|
### Getting Started
|
||||||
|
|
||||||
|
1. Fork the repository and clone your fork.
|
||||||
|
|
||||||
|
2. Install dependencies from the repo root:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
bun install
|
||||||
|
```
|
||||||
|
|
||||||
|
3. Navigate to the main app package:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cd app
|
||||||
|
```
|
||||||
|
|
||||||
|
4. Copy the example environment file:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cp .env.example .env
|
||||||
|
```
|
||||||
|
|
||||||
|
The default `.env.example` includes a file-based SQLite database (`file:.db/dev.db`). You can change `VITE_DB_URL` to `:memory:` for an in-memory database instead.
|
||||||
|
|
||||||
|
5. Start the dev server:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
bun run dev
|
||||||
|
```
|
||||||
|
|
||||||
|
The dev server runs on `http://localhost:28623` using Vite with Hono.
|
||||||
|
|
||||||
|
## Project Structure
|
||||||
|
|
||||||
|
This is a Bun monorepo using workspaces. The vast majority of the code lives in `app/`.
|
||||||
|
|
||||||
|
```
|
||||||
|
bknd/
|
||||||
|
app/ # Main "bknd" npm package (this is where most work happens)
|
||||||
|
src/
|
||||||
|
adapter/ # Runtime/framework adapters (node, bun, cloudflare, nextjs, astro, etc.)
|
||||||
|
auth/ # Authentication module (strategies, sessions, user pool)
|
||||||
|
cli/ # CLI commands
|
||||||
|
core/ # Shared utilities, event system, drivers, server helpers
|
||||||
|
data/ # Data module (entities, fields, relations, queries, schema)
|
||||||
|
flows/ # Workflow engine and tasks
|
||||||
|
media/ # Media module (storage adapters, uploads)
|
||||||
|
modes/ # Configuration modes (code, hybrid, db)
|
||||||
|
modules/ # Module system, MCP server, permissions framework
|
||||||
|
plugins/ # Built-in plugins (auth, data, cloudflare, dev)
|
||||||
|
ui/ # All frontend code
|
||||||
|
client/ # TypeScript SDK and React hooks (exported as bknd/client)
|
||||||
|
elements/ # React components for auth/media (exported as bknd/elements)
|
||||||
|
(everything else) # Admin UI (exported as bknd/ui)
|
||||||
|
App.ts # Central application orchestrator
|
||||||
|
index.ts # Main package exports
|
||||||
|
__test__/ # Unit tests (mirrors src/ structure)
|
||||||
|
e2e/ # End-to-end tests (Playwright)
|
||||||
|
build.ts # Build script (tsup/esbuild)
|
||||||
|
build.cli.ts # CLI build script
|
||||||
|
packages/ # Small satellite packages
|
||||||
|
cli/ # Standalone CLI package (bknd-cli)
|
||||||
|
plasmic/ # Plasmic integration
|
||||||
|
postgres/ # Postgres helper
|
||||||
|
sqlocal/ # SQLocal helper
|
||||||
|
docs/ # Documentation site (Next.js + Fumadocs, deployed to docs.bknd.io)
|
||||||
|
examples/ # Example projects across runtimes and frameworks
|
||||||
|
docker/ # Docker configuration
|
||||||
|
```
|
||||||
|
|
||||||
|
## Understanding the Codebase
|
||||||
|
|
||||||
|
### Path Aliases
|
||||||
|
|
||||||
|
The project uses TypeScript path aliases defined in `app/tsconfig.json`. Imports like `core/utils`, `data/connection`, or `auth/authenticate` resolve to directories under `app/src/`. When reading source code, keep this in mind -- an import like `import { Connection } from "data/connection"` refers to `app/src/data/connection`, not an external package.
|
||||||
|
|
||||||
|
### Module System
|
||||||
|
|
||||||
|
bknd is built around four core modules, each with its own schema, API routes, and permissions:
|
||||||
|
|
||||||
|
- **Data** -- entity definitions, field types, relations, queries (backed by Kysely)
|
||||||
|
- **Auth** -- authentication strategies, sessions, user management
|
||||||
|
- **Media** -- file storage with pluggable adapters (S3, Cloudinary, local filesystem, etc.)
|
||||||
|
- **Flows** -- workflow automation and task execution
|
||||||
|
|
||||||
|
These modules are managed by the `ModuleManager` (in `app/src/modules/`), which handles configuration, building, and lifecycle.
|
||||||
|
|
||||||
|
### Adapter Pattern
|
||||||
|
|
||||||
|
Adapters in `app/src/adapter/` allow bknd to run on different runtimes and frameworks. Each adapter provides the glue between bknd's Hono-based server and a specific environment (Node, Bun, Cloudflare Workers, Next.js, Astro, etc.).
|
||||||
|
|
||||||
|
### Plugin System
|
||||||
|
|
||||||
|
Plugins (in `app/src/plugins/`) hook into the app lifecycle via callbacks like `beforeBuild`, `onBuilt`, `onServerInit`, and `schema`. They can add entities, register routes, and extend behavior.
|
||||||
|
|
||||||
|
### 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:
|
||||||
|
|
||||||
|
- **API** -- the core backend
|
||||||
|
- **UI** -- the admin interface
|
||||||
|
- **Elements** -- standalone React components
|
||||||
|
- **Adapters** -- all runtime/framework adapters
|
||||||
|
|
||||||
|
## Running Tests
|
||||||
|
|
||||||
|
All test commands run from the `app/` directory.
|
||||||
|
|
||||||
|
| Command | Runner | What it runs |
|
||||||
|
|---|---|---|
|
||||||
|
| `bun run test` | Bun test | Unit tests (`*.spec.ts` files) |
|
||||||
|
| `bun run test:node` | Vitest | Node-specific tests (`*.vi-test.ts`, `*.vitest.ts`) |
|
||||||
|
| `bun run test:e2e` | Playwright | End-to-end tests (`*.e2e-spec.ts` in `e2e/`) |
|
||||||
|
| `bun run types` | TypeScript | Type checking (no emit) |
|
||||||
|
|
||||||
|
CI runs both Bun and Node tests, with a Postgres 17 service for database integration tests.
|
||||||
|
|
||||||
|
## Code Style
|
||||||
|
|
||||||
|
The project uses **Biome** for formatting and linting.
|
||||||
|
|
||||||
|
- 3-space indentation for JavaScript/TypeScript
|
||||||
|
- 100-character line width
|
||||||
|
- Spaces (not tabs)
|
||||||
|
|
||||||
|
To format and lint, run from the repo root:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
bunx biome format --write ./app
|
||||||
|
bunx biome lint --changed --write ./app
|
||||||
|
```
|
||||||
|
|
||||||
|
Run both before submitting a PR. CI will catch style issues, but it is better to fix them locally first.
|
||||||
|
|
||||||
|
## Submitting Changes
|
||||||
|
|
||||||
|
1. Open a GitHub Issue describing your proposed change, or link to a Discord thread where it was discussed. Wait for feedback before writing code.
|
||||||
|
2. Fork the repo and create a branch from `main`.
|
||||||
|
3. Keep changes focused and minimal. One PR per issue.
|
||||||
|
4. Add or update tests if applicable.
|
||||||
|
5. Run the test suite and linter before pushing.
|
||||||
|
6. Open a pull request against `main`. Reference the issue number in the PR description.
|
||||||
|
|
||||||
|
Expect a response from maintainers, but be patient -- this is an actively developed project and review may take some time.
|
||||||
|
|
||||||
|
## AI-Generated Code
|
||||||
|
|
||||||
|
If you use AI tools to write or assist with your code, you must:
|
||||||
|
|
||||||
|
- **Fully review all AI-generated code yourself** before submitting. You are responsible for understanding and standing behind every line in your PR.
|
||||||
|
- **Include the prompts used** in the PR description. This gives maintainers additional context for reviewing the code.
|
||||||
|
|
||||||
|
Pull requests with unreviewed AI-generated code will be closed.
|
||||||
|
|
||||||
|
## Contributing to Documentation
|
||||||
|
|
||||||
|
The documentation site lives in the `docs/` directory and is a **separate Next.js application** built with [Fumadocs](https://fumadocs.dev). It uses **npm** (not Bun) as its package manager.
|
||||||
|
|
||||||
|
### Docs Setup
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cd docs
|
||||||
|
npm install
|
||||||
|
npm run dev
|
||||||
|
```
|
||||||
|
|
||||||
|
The docs dev server runs on `http://localhost:3000`.
|
||||||
|
|
||||||
|
### Where Documentation Lives
|
||||||
|
|
||||||
|
Documentation content is written in MDX and located in `docs/content/docs/`. The directory is organized into:
|
||||||
|
|
||||||
|
- `(documentation)/` -- core documentation pages
|
||||||
|
- `guide/` -- guides and tutorials
|
||||||
|
- `api-reference/` -- API reference (partially auto-generated from OpenAPI)
|
||||||
|
|
||||||
|
To add or edit a page, create or modify an `.mdx` file in the appropriate directory. Page metadata is defined via frontmatter at the top of each file. Navigation order is controlled by `meta.json` files in each directory.
|
||||||
|
|
||||||
|
### Building the Docs
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npm run build
|
||||||
|
```
|
||||||
|
|
||||||
|
This generates the OpenAPI and MCP reference pages before building the Next.js site. Make sure the build succeeds locally before submitting a docs PR.
|
||||||
|
|
||||||
|
## Reporting Bugs
|
||||||
|
|
||||||
|
Open a GitHub Issue with:
|
||||||
|
|
||||||
|
- A clear title describing the problem.
|
||||||
|
- Steps to reproduce the bug.
|
||||||
|
- Expected behavior vs. actual behavior.
|
||||||
|
- Your environment (runtime, database, adapter, bknd version).
|
||||||
|
- Any relevant error messages or logs.
|
||||||
|
|
||||||
|
## Getting Help
|
||||||
|
|
||||||
|
- **Discord**: https://discord.com/invite/952SFk8Tb8
|
||||||
|
- **FAQ / Search**: https://www.answeroverflow.com/c/1308395750564302952
|
||||||
|
- **GitHub Issues**: https://github.com/bknd-io/bknd/issues
|
||||||
|
|
||||||
|
## Contributors
|
||||||
|
|
||||||
|
Thank you to everyone who has contributed to bknd.
|
||||||
|
|
||||||
|
<a href="https://github.com/bknd-io/bknd/graphs/contributors">
|
||||||
|
<img src="https://contrib.rocks/image?repo=bknd-io/bknd" />
|
||||||
|
</a>
|
||||||
|
|
||||||
|
Made with [contrib.rocks](https://contrib.rocks).
|
||||||
|
|
||||||
|
## Maintainers
|
||||||
|
|
||||||
|
- **Dennis** ([@dswbx](https://github.com/dswbx)) -- Creator and maintainer of bknd
|
||||||
|
- **Cameron Pak** ([@cameronapak](https://github.com/cameronapak)) -- Maintainer of bknd docs
|
||||||
+169
-77
@@ -1,110 +1,202 @@
|
|||||||
# Functional Source License, Version 1.1, MIT Future License
|
|
||||||
|
|
||||||
## Abbreviation
|
Apache License
|
||||||
|
Version 2.0, January 2004
|
||||||
|
http://www.apache.org/licenses/
|
||||||
|
|
||||||
FSL-1.1-MIT
|
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||||
|
|
||||||
## Notice
|
1. Definitions.
|
||||||
|
|
||||||
Copyright 2025 Dennis Senn
|
"License" shall mean the terms and conditions for use, reproduction,
|
||||||
|
and distribution as defined by Sections 1 through 9 of this document.
|
||||||
|
|
||||||
## Terms and Conditions
|
"Licensor" shall mean the copyright owner or entity authorized by
|
||||||
|
the copyright owner that is granting the License.
|
||||||
|
|
||||||
### Licensor ("We")
|
"Legal Entity" shall mean the union of the acting entity and all
|
||||||
|
other entities that control, are controlled by, or are under common
|
||||||
|
control with that entity. For the purposes of this definition,
|
||||||
|
"control" means (i) the power, direct or indirect, to cause the
|
||||||
|
direction or management of such entity, whether by contract or
|
||||||
|
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||||
|
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||||
|
|
||||||
The party offering the Software under these Terms and Conditions.
|
"You" (or "Your") shall mean an individual or Legal Entity
|
||||||
|
exercising permissions granted by this License.
|
||||||
|
|
||||||
### The Software
|
"Source" form shall mean the preferred form for making modifications,
|
||||||
|
including but not limited to software source code, documentation
|
||||||
|
source, and configuration files.
|
||||||
|
|
||||||
The "Software" is each version of the software that we make available under
|
"Object" form shall mean any form resulting from mechanical
|
||||||
these Terms and Conditions, as indicated by our inclusion of these Terms and
|
transformation or translation of a Source form, including but
|
||||||
Conditions with the Software.
|
not limited to compiled object code, generated documentation,
|
||||||
|
and conversions to other media types.
|
||||||
|
|
||||||
### License Grant
|
"Work" shall mean the work of authorship, whether in Source or
|
||||||
|
Object form, made available under the License, as indicated by a
|
||||||
|
copyright notice that is included in or attached to the work
|
||||||
|
(an example is provided in the Appendix below).
|
||||||
|
|
||||||
Subject to your compliance with this License Grant and the Patents,
|
"Derivative Works" shall mean any work, whether in Source or Object
|
||||||
Redistribution and Trademark clauses below, we hereby grant you the right to
|
form, that is based on (or derived from) the Work and for which the
|
||||||
use, copy, modify, create derivative works, publicly perform, publicly display
|
editorial revisions, annotations, elaborations, or other modifications
|
||||||
and redistribute the Software for any Permitted Purpose identified below.
|
represent, as a whole, an original work of authorship. For the purposes
|
||||||
|
of this License, Derivative Works shall not include works that remain
|
||||||
|
separable from, or merely link (or bind by name) to the interfaces of,
|
||||||
|
the Work and Derivative Works thereof.
|
||||||
|
|
||||||
### Permitted Purpose
|
"Contribution" shall mean any work of authorship, including
|
||||||
|
the original version of the Work and any modifications or additions
|
||||||
|
to that Work or Derivative Works thereof, that is intentionally
|
||||||
|
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||||
|
or by an individual or Legal Entity authorized to submit on behalf of
|
||||||
|
the copyright owner. For the purposes of this definition, "submitted"
|
||||||
|
means any form of electronic, verbal, or written communication sent
|
||||||
|
to the Licensor or its representatives, including but not limited to
|
||||||
|
communication on electronic mailing lists, source code control systems,
|
||||||
|
and issue tracking systems that are managed by, or on behalf of, the
|
||||||
|
Licensor for the purpose of discussing and improving the Work, but
|
||||||
|
excluding communication that is conspicuously marked or otherwise
|
||||||
|
designated in writing by the copyright owner as "Not a Contribution."
|
||||||
|
|
||||||
A Permitted Purpose is any purpose other than a Competing Use. A Competing Use
|
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||||
means making the Software available to others in a commercial product or
|
on behalf of whom a Contribution has been received by Licensor and
|
||||||
service that:
|
subsequently incorporated within the Work.
|
||||||
|
|
||||||
1. substitutes for the Software;
|
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||||
|
this License, each Contributor hereby grants to You a perpetual,
|
||||||
|
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||||
|
copyright license to reproduce, prepare Derivative Works of,
|
||||||
|
publicly display, publicly perform, sublicense, and distribute the
|
||||||
|
Work and such Derivative Works in Source or Object form.
|
||||||
|
|
||||||
2. substitutes for any other product or service we offer using the Software
|
3. Grant of Patent License. Subject to the terms and conditions of
|
||||||
that exists as of the date we make the Software available; or
|
this License, each Contributor hereby grants to You a perpetual,
|
||||||
|
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||||
|
(except as stated in this section) patent license to make, have made,
|
||||||
|
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||||
|
where such license applies only to those patent claims licensable
|
||||||
|
by such Contributor that are necessarily infringed by their
|
||||||
|
Contribution(s) alone or by combination of their Contribution(s)
|
||||||
|
with the Work to which such Contribution(s) was submitted. If You
|
||||||
|
institute patent litigation against any entity (including a
|
||||||
|
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||||
|
or a Contribution incorporated within the Work constitutes direct
|
||||||
|
or contributory patent infringement, then any patent licenses
|
||||||
|
granted to You under this License for that Work shall terminate
|
||||||
|
as of the date such litigation is filed.
|
||||||
|
|
||||||
3. offers the same or substantially similar functionality as the Software.
|
4. Redistribution. You may reproduce and distribute copies of the
|
||||||
|
Work or Derivative Works thereof in any medium, with or without
|
||||||
|
modifications, and in Source or Object form, provided that You
|
||||||
|
meet the following conditions:
|
||||||
|
|
||||||
Permitted Purposes specifically include using the Software:
|
(a) You must give any other recipients of the Work or
|
||||||
|
Derivative Works a copy of this License; and
|
||||||
|
|
||||||
1. for your internal use and access;
|
(b) You must cause any modified files to carry prominent notices
|
||||||
|
stating that You changed the files; and
|
||||||
|
|
||||||
2. for non-commercial education;
|
(c) You must retain, in the Source form of any Derivative Works
|
||||||
|
that You distribute, all copyright, patent, trademark, and
|
||||||
|
attribution notices from the Source form of the Work,
|
||||||
|
excluding those notices that do not pertain to any part of
|
||||||
|
the Derivative Works; and
|
||||||
|
|
||||||
3. for non-commercial research; and
|
(d) If the Work includes a "NOTICE" text file as part of its
|
||||||
|
distribution, then any Derivative Works that You distribute must
|
||||||
|
include a readable copy of the attribution notices contained
|
||||||
|
within such NOTICE file, excluding those notices that do not
|
||||||
|
pertain to any part of the Derivative Works, in at least one
|
||||||
|
of the following places: within a NOTICE text file distributed
|
||||||
|
as part of the Derivative Works; within the Source form or
|
||||||
|
documentation, if provided along with the Derivative Works; or,
|
||||||
|
within a display generated by the Derivative Works, if and
|
||||||
|
wherever such third-party notices normally appear. The contents
|
||||||
|
of the NOTICE file are for informational purposes only and
|
||||||
|
do not modify the License. You may add Your own attribution
|
||||||
|
notices within Derivative Works that You distribute, alongside
|
||||||
|
or as an addendum to the NOTICE text from the Work, provided
|
||||||
|
that such additional attribution notices cannot be construed
|
||||||
|
as modifying the License.
|
||||||
|
|
||||||
4. in connection with professional services that you provide to a licensee
|
You may add Your own copyright statement to Your modifications and
|
||||||
using the Software in accordance with these Terms and Conditions.
|
may provide additional or different license terms and conditions
|
||||||
|
for use, reproduction, or distribution of Your modifications, or
|
||||||
|
for any such Derivative Works as a whole, provided Your use,
|
||||||
|
reproduction, and distribution of the Work otherwise complies with
|
||||||
|
the conditions stated in this License.
|
||||||
|
|
||||||
### Patents
|
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||||
|
any Contribution intentionally submitted for inclusion in the Work
|
||||||
|
by You to the Licensor shall be under the terms and conditions of
|
||||||
|
this License, without any additional terms or conditions.
|
||||||
|
Notwithstanding the above, nothing herein shall supersede or modify
|
||||||
|
the terms of any separate license agreement you may have executed
|
||||||
|
with Licensor regarding such Contributions.
|
||||||
|
|
||||||
To the extent your use for a Permitted Purpose would necessarily infringe our
|
6. Trademarks. This License does not grant permission to use the trade
|
||||||
patents, the license grant above includes a license under our patents. If you
|
names, trademarks, service marks, or product names of the Licensor,
|
||||||
make a claim against any party that the Software infringes or contributes to
|
except as required for reasonable and customary use in describing the
|
||||||
the infringement of any patent, then your patent license to the Software ends
|
origin of the Work and reproducing the content of the NOTICE file.
|
||||||
immediately.
|
|
||||||
|
|
||||||
### Redistribution
|
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||||
|
agreed to in writing, Licensor provides the Work (and each
|
||||||
|
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||||
|
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||||
|
implied, including, without limitation, any warranties or conditions
|
||||||
|
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||||
|
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||||
|
appropriateness of using or redistributing the Work and assume any
|
||||||
|
risks associated with Your exercise of permissions under this License.
|
||||||
|
|
||||||
The Terms and Conditions apply to all copies, modifications and derivatives of
|
8. Limitation of Liability. In no event and under no legal theory,
|
||||||
the Software.
|
whether in tort (including negligence), contract, or otherwise,
|
||||||
|
unless required by applicable law (such as deliberate and grossly
|
||||||
|
negligent acts) or agreed to in writing, shall any Contributor be
|
||||||
|
liable to You for damages, including any direct, indirect, special,
|
||||||
|
incidental, or consequential damages of any character arising as a
|
||||||
|
result of this License or out of the use or inability to use the
|
||||||
|
Work (including but not limited to damages for loss of goodwill,
|
||||||
|
work stoppage, computer failure or malfunction, or any and all
|
||||||
|
other commercial damages or losses), even if such Contributor
|
||||||
|
has been advised of the possibility of such damages.
|
||||||
|
|
||||||
If you redistribute any copies, modifications or derivatives of the Software,
|
9. Accepting Warranty or Additional Liability. While redistributing
|
||||||
you must include a copy of or a link to these Terms and Conditions and not
|
the Work or Derivative Works thereof, You may choose to offer,
|
||||||
remove any copyright notices provided in or with the Software.
|
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||||
|
or other liability obligations and/or rights consistent with this
|
||||||
|
License. However, in accepting such obligations, You may act only
|
||||||
|
on Your own behalf and on Your sole responsibility, not on behalf
|
||||||
|
of any other Contributor, and only if You agree to indemnify,
|
||||||
|
defend, and hold each Contributor harmless for any liability
|
||||||
|
incurred by, or claims asserted against, such Contributor by reason
|
||||||
|
of your accepting any such warranty or additional liability.
|
||||||
|
|
||||||
### Disclaimer
|
END OF TERMS AND CONDITIONS
|
||||||
|
|
||||||
THE SOFTWARE IS PROVIDED "AS IS" AND WITHOUT WARRANTIES OF ANY KIND, EXPRESS OR
|
APPENDIX: How to apply the Apache License to your work.
|
||||||
IMPLIED, INCLUDING WITHOUT LIMITATION WARRANTIES OF FITNESS FOR A PARTICULAR
|
|
||||||
PURPOSE, MERCHANTABILITY, TITLE OR NON-INFRINGEMENT.
|
|
||||||
|
|
||||||
IN NO EVENT WILL WE HAVE ANY LIABILITY TO YOU ARISING OUT OF OR RELATED TO THE
|
To apply the Apache License to your work, attach the following
|
||||||
SOFTWARE, INCLUDING INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES,
|
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||||
EVEN IF WE HAVE BEEN INFORMED OF THEIR POSSIBILITY IN ADVANCE.
|
replaced with your own identifying information. (Don't include
|
||||||
|
the brackets!) The text should be enclosed in the appropriate
|
||||||
|
comment syntax for the file format. We also recommend that a
|
||||||
|
file or class name and description of purpose be included on the
|
||||||
|
same "printed page" as the copyright notice for easier
|
||||||
|
identification within third-party archives.
|
||||||
|
|
||||||
### Trademarks
|
Copyright 2026 Dennis Senn
|
||||||
|
|
||||||
Except for displaying the License Details and identifying us as the origin of
|
Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
the Software, you have no right under these Terms and Conditions to use our
|
you may not use this file except in compliance with the License.
|
||||||
trademarks, trade names, service marks or product names.
|
You may obtain a copy of the License at
|
||||||
|
|
||||||
## Grant of Future License
|
http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
|
||||||
We hereby irrevocably grant you an additional license to use the Software under
|
Unless required by applicable law or agreed to in writing, software
|
||||||
the MIT license that is effective on the second anniversary of the date we make
|
distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
the Software available. On or after that date, you may use the Software under
|
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
the MIT license, in which case the following will apply:
|
See the License for the specific language governing permissions and
|
||||||
|
limitations under the License.
|
||||||
Permission is hereby granted, free of charge, to any person obtaining a copy of
|
|
||||||
this software and associated documentation files (the "Software"), to deal in
|
|
||||||
the Software without restriction, including without limitation the rights to
|
|
||||||
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
|
|
||||||
of the Software, and to permit persons to whom the Software is furnished to do
|
|
||||||
so, subject to the following conditions:
|
|
||||||
|
|
||||||
The above copyright notice and this permission notice shall be included in all
|
|
||||||
copies or substantial portions of the Software.
|
|
||||||
|
|
||||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
||||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
||||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
||||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
||||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
||||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
||||||
SOFTWARE.
|
|
||||||
@@ -17,7 +17,7 @@ It's designed to avoid vendor lock-in and architectural limitations. Built exclu
|
|||||||
* SQLite: LibSQL, Node SQLite, Bun SQLite, Cloudflare D1, Cloudflare Durable Objects SQLite, SQLocal
|
* SQLite: LibSQL, Node SQLite, Bun SQLite, Cloudflare D1, Cloudflare Durable Objects SQLite, SQLocal
|
||||||
* Postgres: Vanilla Postgres, Supabase, Neon, Xata
|
* Postgres: Vanilla Postgres, Supabase, Neon, Xata
|
||||||
* **Frameworks**: React, Next.js, React Router, Astro, Vite, Waku
|
* **Frameworks**: React, Next.js, React Router, Astro, Vite, Waku
|
||||||
* **Storage**: AWS S3, S3-compatible (Tigris, R2, Minio, etc.), Cloudflare R2 (binding), Cloudinary, Filesystem
|
* **Storage**: AWS S3, S3-compatible (Tigris, R2, Minio, etc.), Cloudflare R2 (binding), Cloudinary, Filesystem, Origin Private File System (OPFS)
|
||||||
* **Deployment**: Standalone, Docker, Cloudflare Workers, Vercel, Netlify, Deno Deploy, AWS Lambda, Valtown etc.
|
* **Deployment**: Standalone, Docker, Cloudflare Workers, Vercel, Netlify, Deno Deploy, AWS Lambda, Valtown etc.
|
||||||
|
|
||||||
**For documentation and examples, please visit https://docs.bknd.io.**
|
**For documentation and examples, please visit https://docs.bknd.io.**
|
||||||
@@ -165,3 +165,19 @@ npx bknd run
|
|||||||
```bash
|
```bash
|
||||||
npm install bknd
|
npm install bknd
|
||||||
```
|
```
|
||||||
|
|
||||||
|
## Contributing
|
||||||
|
|
||||||
|
We welcome contributions! Please read our [CONTRIBUTING.md](CONTRIBUTING.md) before getting started. It covers dev setup, project structure, testing, code style, and how to submit changes.
|
||||||
|
|
||||||
|
Before writing code, please open a GitHub Issue or start a conversation in [Discord](https://discord.com/invite/952SFk8Tb8) so we can align on the approach.
|
||||||
|
|
||||||
|
## Contributors
|
||||||
|
|
||||||
|
Thank you to everyone who has contributed to bknd.
|
||||||
|
|
||||||
|
<a href="https://github.com/bknd-io/bknd/graphs/contributors">
|
||||||
|
<img src="https://contrib.rocks/image?repo=bknd-io/bknd" />
|
||||||
|
</a>
|
||||||
|
|
||||||
|
Made with [contrib.rocks](https://contrib.rocks).
|
||||||
|
|||||||
@@ -20,6 +20,7 @@ VITE_SHOW_ROUTES=
|
|||||||
|
|
||||||
# ===== Test Credentials =====
|
# ===== Test Credentials =====
|
||||||
RESEND_API_KEY=
|
RESEND_API_KEY=
|
||||||
|
PLUNK_API_KEY=
|
||||||
R2_TOKEN=
|
R2_TOKEN=
|
||||||
|
|
||||||
R2_ACCESS_KEY=
|
R2_ACCESS_KEY=
|
||||||
|
|||||||
@@ -2,3 +2,4 @@ playwright-report
|
|||||||
test-results
|
test-results
|
||||||
bknd.config.*
|
bknd.config.*
|
||||||
__test__/helper.d.ts
|
__test__/helper.d.ts
|
||||||
|
.env.local
|
||||||
Vendored
+12
@@ -0,0 +1,12 @@
|
|||||||
|
{
|
||||||
|
"typescript.preferences.includePackageJsonAutoImports": "off",
|
||||||
|
"typescript.suggest.autoImports": true,
|
||||||
|
"typescript.preferences.importModuleSpecifier": "relative",
|
||||||
|
"search.exclude": {
|
||||||
|
"**/dist/**": true,
|
||||||
|
"**/node_modules/**": true
|
||||||
|
},
|
||||||
|
"files.exclude": {
|
||||||
|
"**/dist/**": true
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -108,7 +108,7 @@ describe("App tests", async () => {
|
|||||||
expect(Array.from(app.plugins.keys())).toEqual(["test"]);
|
expect(Array.from(app.plugins.keys())).toEqual(["test"]);
|
||||||
});
|
});
|
||||||
|
|
||||||
test.only("drivers", async () => {
|
test("drivers", async () => {
|
||||||
const called: string[] = [];
|
const called: string[] = [];
|
||||||
const app = new App(dummyConnection, undefined, {
|
const app = new App(dummyConnection, undefined, {
|
||||||
drivers: {
|
drivers: {
|
||||||
|
|||||||
@@ -1,66 +1,76 @@
|
|||||||
import { expect, describe, it, beforeAll, afterAll, mock } from "bun:test";
|
import { expect, describe, it, beforeAll, afterAll, mock } from "bun:test";
|
||||||
import * as adapter from "adapter";
|
import * as adapter from "adapter";
|
||||||
import { disableConsoleLog, enableConsoleLog } from "core/utils";
|
import { disableConsoleLog, enableConsoleLog, omitKeys } from "core/utils";
|
||||||
import { adapterTestSuite } from "adapter/adapter-test-suite";
|
import { adapterTestSuite } from "adapter/adapter-test-suite";
|
||||||
import { bunTestRunner } from "adapter/bun/test";
|
import { bunTestRunner } from "adapter/bun/test";
|
||||||
import { omitKeys } from "core/utils";
|
|
||||||
|
const stripConnection = <T extends Record<string, any>>(cfg: T) =>
|
||||||
|
omitKeys(cfg, ["connection"]);
|
||||||
|
|
||||||
beforeAll(disableConsoleLog);
|
beforeAll(disableConsoleLog);
|
||||||
afterAll(enableConsoleLog);
|
afterAll(enableConsoleLog);
|
||||||
|
|
||||||
describe("adapter", () => {
|
describe("adapter", () => {
|
||||||
it("makes config", async () => {
|
describe("makeConfig", () => {
|
||||||
expect(omitKeys(await adapter.makeConfig({}), ["connection"])).toEqual({});
|
it("returns empty config for empty inputs", async () => {
|
||||||
expect(
|
const cases: Array<Parameters<typeof adapter.makeConfig>> = [
|
||||||
omitKeys(await adapter.makeConfig({}, { env: { TEST: "test" } }), ["connection"]),
|
[{}],
|
||||||
).toEqual({});
|
[{}, { env: { TEST: "test" } }],
|
||||||
|
];
|
||||||
|
|
||||||
// merges everything returned from `app` with the config
|
for (const args of cases) {
|
||||||
expect(
|
const cfg = await adapter.makeConfig(...(args as any));
|
||||||
omitKeys(
|
expect(stripConnection(cfg)).toEqual({});
|
||||||
await adapter.makeConfig(
|
}
|
||||||
{ app: (a) => ({ config: { server: { cors: { origin: a.env.TEST } } } }) },
|
});
|
||||||
{ env: { TEST: "test" } },
|
|
||||||
),
|
|
||||||
["connection"],
|
|
||||||
),
|
|
||||||
).toEqual({
|
|
||||||
config: { server: { cors: { origin: "test" } } },
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
it("allows all properties in app function", async () => {
|
it("merges app output into config", async () => {
|
||||||
const called = mock(() => null);
|
const cfg = await adapter.makeConfig(
|
||||||
const config = await adapter.makeConfig(
|
{ app: (a) => ({ config: { server: { cors: { origin: a.env.TEST } } } }) },
|
||||||
{
|
{ env: { TEST: "test" } },
|
||||||
app: (env) => ({
|
|
||||||
connection: { url: "test" },
|
|
||||||
config: { server: { cors: { origin: "test" } } },
|
|
||||||
options: {
|
|
||||||
mode: "db",
|
|
||||||
},
|
|
||||||
onBuilt: () => {
|
|
||||||
called();
|
|
||||||
expect(env).toEqual({ foo: "bar" });
|
|
||||||
},
|
|
||||||
}),
|
|
||||||
},
|
|
||||||
{ foo: "bar" },
|
|
||||||
);
|
);
|
||||||
expect(config.connection).toEqual({ url: "test" });
|
|
||||||
expect(config.config).toEqual({ server: { cors: { origin: "test" } } });
|
|
||||||
expect(config.options).toEqual({ mode: "db" });
|
|
||||||
await config.onBuilt?.(null as any);
|
|
||||||
expect(called).toHaveBeenCalled();
|
|
||||||
});
|
|
||||||
|
|
||||||
adapterTestSuite(bunTestRunner, {
|
expect(stripConnection(cfg)).toEqual({
|
||||||
|
config: { server: { cors: { origin: "test" } } },
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it("allows all properties in app() result", async () => {
|
||||||
|
const called = mock(() => null);
|
||||||
|
|
||||||
|
const cfg = await adapter.makeConfig(
|
||||||
|
{
|
||||||
|
app: (env) => ({
|
||||||
|
connection: { url: "test" },
|
||||||
|
config: { server: { cors: { origin: "test" } } },
|
||||||
|
options: { mode: "db" as const },
|
||||||
|
onBuilt: () => {
|
||||||
|
called();
|
||||||
|
expect(env).toEqual({ foo: "bar" });
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
{ foo: "bar" },
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(cfg.connection).toEqual({ url: "test" });
|
||||||
|
expect(cfg.config).toEqual({ server: { cors: { origin: "test" } } });
|
||||||
|
expect(cfg.options).toEqual({ mode: "db" });
|
||||||
|
|
||||||
|
await cfg.onBuilt?.({} as any);
|
||||||
|
expect(called).toHaveBeenCalledTimes(1);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("adapter test suites", () => {
|
||||||
|
adapterTestSuite(bunTestRunner, {
|
||||||
makeApp: adapter.createFrameworkApp,
|
makeApp: adapter.createFrameworkApp,
|
||||||
label: "framework app",
|
label: "framework app",
|
||||||
});
|
});
|
||||||
|
|
||||||
adapterTestSuite(bunTestRunner, {
|
adapterTestSuite(bunTestRunner, {
|
||||||
makeApp: adapter.createRuntimeApp,
|
makeApp: adapter.createRuntimeApp,
|
||||||
label: "runtime app",
|
label: "runtime app",
|
||||||
});
|
});
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -70,4 +70,10 @@ describe("Api", async () => {
|
|||||||
expect(params.token_transport).toBe("header");
|
expect(params.token_transport).toBe("header");
|
||||||
expect(params.host).toBe("http://another.com");
|
expect(params.host).toBe("http://another.com");
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it("should extract tokens case insensitive", async () => {
|
||||||
|
const token = await sign({ sub: "test" }, "1234");
|
||||||
|
expect(new Api({ headers: new Headers({ Authorization: `Bearer ${token}` }) }).getAuthState().token).toBe(token);
|
||||||
|
expect(new Api({ headers: new Headers({ Authorization: `bearer ${token}` }) }).getAuthState().token).toBe(token);
|
||||||
|
})
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
/// <reference types="@types/bun" />
|
/// <reference types="@types/bun" />
|
||||||
import { describe, expect, it } from "bun:test";
|
import { describe, expect, it, mock } from "bun:test";
|
||||||
import { Hono } from "hono";
|
import { Hono } from "hono";
|
||||||
import { getFileFromContext, isFile, isReadableStream } from "core/utils";
|
import { getFileFromContext, isFile, isReadableStream, s, jsc } from "core/utils";
|
||||||
import { MediaApi } from "media/api/MediaApi";
|
import { MediaApi } from "media/api/MediaApi";
|
||||||
import { assetsPath, assetsTmpPath } from "../helper";
|
import { assetsPath, assetsTmpPath } from "../helper";
|
||||||
|
|
||||||
@@ -15,7 +15,7 @@ const mockedBackend = new Hono()
|
|||||||
.get("/file/:name", async (c) => {
|
.get("/file/:name", async (c) => {
|
||||||
const { name } = c.req.param();
|
const { name } = c.req.param();
|
||||||
const file = Bun.file(`${assetsPath}/${name}`);
|
const file = Bun.file(`${assetsPath}/${name}`);
|
||||||
return new Response(file, {
|
return new Response(new File([await file.bytes()], name, { type: file.type }), {
|
||||||
headers: {
|
headers: {
|
||||||
"Content-Type": file.type,
|
"Content-Type": file.type,
|
||||||
"Content-Length": file.size.toString(),
|
"Content-Length": file.size.toString(),
|
||||||
@@ -67,7 +67,7 @@ describe("MediaApi", () => {
|
|||||||
const res = await mockedBackend.request("/api/media/file/" + name);
|
const res = await mockedBackend.request("/api/media/file/" + name);
|
||||||
await Bun.write(path, res);
|
await Bun.write(path, res);
|
||||||
|
|
||||||
const file = await Bun.file(path);
|
const file = Bun.file(path);
|
||||||
expect(file.size).toBeGreaterThan(0);
|
expect(file.size).toBeGreaterThan(0);
|
||||||
expect(file.type).toBe("image/png");
|
expect(file.type).toBe("image/png");
|
||||||
await file.delete();
|
await file.delete();
|
||||||
@@ -98,7 +98,7 @@ describe("MediaApi", () => {
|
|||||||
expect(isReadableStream(res.body)).toBe(true);
|
expect(isReadableStream(res.body)).toBe(true);
|
||||||
expect(isReadableStream(res.res.body)).toBe(true);
|
expect(isReadableStream(res.res.body)).toBe(true);
|
||||||
|
|
||||||
const blob = await res.res.blob();
|
const blob = (await res.res.blob()) as File;
|
||||||
expect(isFile(blob)).toBe(true);
|
expect(isFile(blob)).toBe(true);
|
||||||
expect(blob.size).toBeGreaterThan(0);
|
expect(blob.size).toBeGreaterThan(0);
|
||||||
expect(blob.type).toBe("image/png");
|
expect(blob.type).toBe("image/png");
|
||||||
@@ -110,10 +110,11 @@ describe("MediaApi", () => {
|
|||||||
const api = new MediaApi({}, mockedBackend.request);
|
const api = new MediaApi({}, mockedBackend.request);
|
||||||
|
|
||||||
const name = "image.png";
|
const name = "image.png";
|
||||||
const res = await api.getFileStream(name);
|
const res = await api.getFile(name);
|
||||||
expect(isReadableStream(res)).toBe(true);
|
const stream = await api.getFileStream(name);
|
||||||
|
expect(isReadableStream(stream)).toBe(true);
|
||||||
|
|
||||||
const blob = await new Response(res).blob();
|
const blob = (await res.res.blob()) as File;
|
||||||
expect(isFile(blob)).toBe(true);
|
expect(isFile(blob)).toBe(true);
|
||||||
expect(blob.size).toBeGreaterThan(0);
|
expect(blob.size).toBeGreaterThan(0);
|
||||||
expect(blob.type).toBe("image/png");
|
expect(blob.type).toBe("image/png");
|
||||||
@@ -154,15 +155,38 @@ describe("MediaApi", () => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// upload via readable from bun
|
// upload via readable from bun
|
||||||
await matches(await api.upload(file.stream(), { filename: "readable.png" }), "readable.png");
|
await matches(api.upload(file.stream(), { filename: "readable.png" }), "readable.png");
|
||||||
|
|
||||||
// upload via readable from response
|
// upload via readable from response
|
||||||
{
|
{
|
||||||
const response = (await mockedBackend.request(url)) as Response;
|
const response = (await mockedBackend.request(url)) as Response;
|
||||||
await matches(
|
await matches(api.upload(response.body!, { filename: "readable.png" }), "readable.png");
|
||||||
await api.upload(response.body!, { filename: "readable.png" }),
|
|
||||||
"readable.png",
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it("should add overwrite query for entity upload", async (c) => {
|
||||||
|
const call = mock(() => null);
|
||||||
|
const hono = new Hono().post(
|
||||||
|
"/api/media/entity/:entity/:id/:field",
|
||||||
|
jsc("query", s.object({ overwrite: s.boolean().optional() })),
|
||||||
|
async (c) => {
|
||||||
|
const { overwrite } = c.req.valid("query");
|
||||||
|
expect(overwrite).toBe(true);
|
||||||
|
call();
|
||||||
|
return c.json({ ok: true });
|
||||||
|
},
|
||||||
|
);
|
||||||
|
const api = new MediaApi(
|
||||||
|
{
|
||||||
|
upload_fetcher: hono.request,
|
||||||
|
},
|
||||||
|
hono.request,
|
||||||
|
);
|
||||||
|
const file = Bun.file(`${assetsPath}/image.png`);
|
||||||
|
const res = await api.uploadToEntity("posts", 1, "cover", file as any, {
|
||||||
|
overwrite: true,
|
||||||
|
});
|
||||||
|
expect(res.ok).toBe(true);
|
||||||
|
expect(call).toHaveBeenCalled();
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -1,8 +1,12 @@
|
|||||||
import { describe, expect, mock, test } from "bun:test";
|
import { describe, expect, mock, test, beforeAll, afterAll } from "bun:test";
|
||||||
import { createApp as internalCreateApp, type CreateAppConfig } from "bknd";
|
import { createApp as internalCreateApp, type CreateAppConfig } from "bknd";
|
||||||
import { getDummyConnection } from "../../__test__/helper";
|
import { getDummyConnection } from "../../__test__/helper";
|
||||||
import { ModuleManager } from "modules/ModuleManager";
|
import { ModuleManager } from "modules/ModuleManager";
|
||||||
import { em, entity, text } from "data/prototype";
|
import { em, entity, text } from "data/prototype";
|
||||||
|
import { disableConsoleLog, enableConsoleLog } from "core/utils/test";
|
||||||
|
|
||||||
|
beforeAll(disableConsoleLog);
|
||||||
|
afterAll(enableConsoleLog);
|
||||||
|
|
||||||
async function createApp(config: CreateAppConfig = {}) {
|
async function createApp(config: CreateAppConfig = {}) {
|
||||||
const app = internalCreateApp({
|
const app = internalCreateApp({
|
||||||
|
|||||||
@@ -1,7 +1,11 @@
|
|||||||
import { AppEvents } from "App";
|
import { AppEvents } from "App";
|
||||||
import { describe, test, expect, beforeAll, mock } from "bun:test";
|
import { describe, test, expect, beforeAll, mock, afterAll } from "bun:test";
|
||||||
import { type App, createApp, createMcpToolCaller } from "core/test/utils";
|
import { type App, createApp, createMcpToolCaller } from "core/test/utils";
|
||||||
import type { McpServer } from "bknd/utils";
|
import type { McpServer } from "bknd/utils";
|
||||||
|
import { disableConsoleLog, enableConsoleLog } from "core/utils/test";
|
||||||
|
|
||||||
|
beforeAll(disableConsoleLog);
|
||||||
|
afterAll(enableConsoleLog);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* - [x] system_config
|
* - [x] system_config
|
||||||
|
|||||||
@@ -0,0 +1,42 @@
|
|||||||
|
import { describe, expect, test } from "bun:test";
|
||||||
|
import { code, hybrid } from "modes";
|
||||||
|
|
||||||
|
describe("modes", () => {
|
||||||
|
describe("code", () => {
|
||||||
|
test("verify base configuration", async () => {
|
||||||
|
const c = code({}) as any;
|
||||||
|
const config = await c.app?.({} as any);
|
||||||
|
expect(Object.keys(config)).toEqual(["options"]);
|
||||||
|
expect(config.options.mode).toEqual("code");
|
||||||
|
expect(config.options.plugins).toEqual([]);
|
||||||
|
expect(config.options.manager.skipValidation).toEqual(false);
|
||||||
|
expect(config.options.manager.onModulesBuilt).toBeDefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
test("keeps overrides", async () => {
|
||||||
|
const c = code({
|
||||||
|
connection: {
|
||||||
|
url: ":memory:",
|
||||||
|
},
|
||||||
|
}) as any;
|
||||||
|
const config = await c.app?.({} as any);
|
||||||
|
expect(config.connection.url).toEqual(":memory:");
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("hybrid", () => {
|
||||||
|
test("fails if no reader is provided", () => {
|
||||||
|
// @ts-ignore
|
||||||
|
expect(hybrid({} as any).app?.({} as any)).rejects.toThrow(/reader/);
|
||||||
|
});
|
||||||
|
test("verify base configuration", async () => {
|
||||||
|
const c = hybrid({ reader: async () => ({}) }) as any;
|
||||||
|
const config = await c.app?.({} as any);
|
||||||
|
expect(Object.keys(config)).toEqual(["reader", "beforeBuild", "config", "options"]);
|
||||||
|
expect(config.options.mode).toEqual("db");
|
||||||
|
expect(config.options.plugins).toEqual([]);
|
||||||
|
expect(config.options.manager.skipValidation).toEqual(false);
|
||||||
|
expect(config.options.manager.onModulesBuilt).toBeDefined();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -76,7 +76,7 @@ describe("repros", async () => {
|
|||||||
expect(app.em.entities.map((e) => e.name)).toEqual(["media", "test"]);
|
expect(app.em.entities.map((e) => e.name)).toEqual(["media", "test"]);
|
||||||
});
|
});
|
||||||
|
|
||||||
test.only("verify inversedBy", async () => {
|
test("verify inversedBy", async () => {
|
||||||
const schema = proto.em(
|
const schema = proto.em(
|
||||||
{
|
{
|
||||||
products: proto.entity("products", {
|
products: proto.entity("products", {
|
||||||
|
|||||||
@@ -38,4 +38,27 @@ describe("Authenticator", async () => {
|
|||||||
expect(cookie).toStartWith("auth=");
|
expect(cookie).toStartWith("auth=");
|
||||||
expect(cookie).toEndWith("HttpOnly; Secure; SameSite=Strict");
|
expect(cookie).toEndWith("HttpOnly; Secure; SameSite=Strict");
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test("bearer token is case insensitive", async () => {
|
||||||
|
const auth = new Authenticator({}, null as any, {
|
||||||
|
jwt: {
|
||||||
|
secret: "secret",
|
||||||
|
fields: ["sub"],
|
||||||
|
},
|
||||||
|
cookie: {
|
||||||
|
sameSite: "strict",
|
||||||
|
},
|
||||||
|
});
|
||||||
|
const token = await auth.jwt({ sub: "test" });
|
||||||
|
|
||||||
|
const res = await auth.resolveAuthFromRequest(new Headers({
|
||||||
|
Authorization: `Bearer ${token}`,
|
||||||
|
}));
|
||||||
|
expect((res as any).sub).toBe("test")
|
||||||
|
|
||||||
|
const res2 = await auth.resolveAuthFromRequest(new Headers({
|
||||||
|
Authorization: `bearer ${token}`,
|
||||||
|
}));
|
||||||
|
expect((res2 as any).sub).toBe("test")
|
||||||
|
})
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -1,8 +1,12 @@
|
|||||||
import { describe, expect, test } from "bun:test";
|
import { describe, expect, test, beforeAll, afterAll } from "bun:test";
|
||||||
import { Guard, type GuardConfig } from "auth/authorize/Guard";
|
import { Guard, type GuardConfig } from "auth/authorize/Guard";
|
||||||
import { Permission } from "auth/authorize/Permission";
|
import { Permission } from "auth/authorize/Permission";
|
||||||
import { Role, type RoleSchema } from "auth/authorize/Role";
|
import { Role, type RoleSchema } from "auth/authorize/Role";
|
||||||
import { objectTransform, s } from "bknd/utils";
|
import { objectTransform, s } from "bknd/utils";
|
||||||
|
import { disableConsoleLog, enableConsoleLog } from "core/utils/test";
|
||||||
|
|
||||||
|
beforeAll(disableConsoleLog);
|
||||||
|
afterAll(enableConsoleLog);
|
||||||
|
|
||||||
function createGuard(
|
function createGuard(
|
||||||
permissionNames: string[],
|
permissionNames: string[],
|
||||||
|
|||||||
@@ -7,8 +7,8 @@ import type { App, DB } from "bknd";
|
|||||||
import type { CreateUserPayload } from "auth/AppAuth";
|
import type { CreateUserPayload } from "auth/AppAuth";
|
||||||
import { disableConsoleLog, enableConsoleLog } from "core/utils/test";
|
import { disableConsoleLog, enableConsoleLog } from "core/utils/test";
|
||||||
|
|
||||||
beforeAll(() => disableConsoleLog());
|
beforeAll(disableConsoleLog);
|
||||||
afterAll(() => enableConsoleLog());
|
afterAll(enableConsoleLog);
|
||||||
|
|
||||||
async function makeApp(config: Partial<CreateAppConfig["config"]> = {}) {
|
async function makeApp(config: Partial<CreateAppConfig["config"]> = {}) {
|
||||||
const app = createApp({
|
const app = createApp({
|
||||||
|
|||||||
@@ -0,0 +1,40 @@
|
|||||||
|
import { describe, test, expect, beforeAll, afterAll } from "bun:test";
|
||||||
|
import { createAuthTestApp } from "./shared";
|
||||||
|
import { disableConsoleLog, enableConsoleLog } from "core/utils/test";
|
||||||
|
import { em, entity, text } from "data/prototype";
|
||||||
|
|
||||||
|
beforeAll(disableConsoleLog);
|
||||||
|
afterAll(enableConsoleLog);
|
||||||
|
|
||||||
|
const schema = em(
|
||||||
|
{
|
||||||
|
posts: entity("posts", {
|
||||||
|
title: text(),
|
||||||
|
content: text(),
|
||||||
|
}),
|
||||||
|
comments: entity("comments", {
|
||||||
|
content: text(),
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
({ relation }, { posts, comments }) => {
|
||||||
|
relation(posts).manyToOne(comments);
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
describe("DataController (auth)", () => {
|
||||||
|
test("reading schema.json", async () => {
|
||||||
|
const { request } = await createAuthTestApp(
|
||||||
|
{
|
||||||
|
permission: ["system.access.api", "data.entity.read", "system.schema.read"],
|
||||||
|
request: new Request("http://localhost/api/data/schema.json"),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
config: { data: schema.toJSON() },
|
||||||
|
},
|
||||||
|
);
|
||||||
|
expect((await request.guest()).status).toBe(403);
|
||||||
|
expect((await request.member()).status).toBe(403);
|
||||||
|
expect((await request.authorized()).status).toBe(200);
|
||||||
|
expect((await request.admin()).status).toBe(200);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -1,20 +0,0 @@
|
|||||||
import { describe, it, expect } from "bun:test";
|
|
||||||
import { SystemController } from "modules/server/SystemController";
|
|
||||||
import { createApp } from "core/test/utils";
|
|
||||||
import type { CreateAppConfig } from "App";
|
|
||||||
import { getPermissionRoutes } from "auth/middlewares/permission.middleware";
|
|
||||||
|
|
||||||
async function makeApp(config: Partial<CreateAppConfig> = {}) {
|
|
||||||
const app = createApp(config);
|
|
||||||
await app.build();
|
|
||||||
return app;
|
|
||||||
}
|
|
||||||
|
|
||||||
describe.skip("SystemController", () => {
|
|
||||||
it("...", async () => {
|
|
||||||
const app = await makeApp();
|
|
||||||
const controller = new SystemController(app);
|
|
||||||
const hono = controller.getController();
|
|
||||||
console.log(getPermissionRoutes(hono));
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@@ -0,0 +1,41 @@
|
|||||||
|
import { describe, test, expect, beforeAll, afterAll } from "bun:test";
|
||||||
|
import { createAuthTestApp } from "./shared";
|
||||||
|
import { disableConsoleLog, enableConsoleLog } from "core/utils/test";
|
||||||
|
|
||||||
|
beforeAll(disableConsoleLog);
|
||||||
|
afterAll(enableConsoleLog);
|
||||||
|
|
||||||
|
describe("SystemController (auth)", () => {
|
||||||
|
test("reading info", async () => {
|
||||||
|
const { request } = await createAuthTestApp({
|
||||||
|
permission: ["system.access.api", "system.info"],
|
||||||
|
request: new Request("http://localhost/api/system/info"),
|
||||||
|
});
|
||||||
|
expect((await request.guest()).status).toBe(403);
|
||||||
|
expect((await request.member()).status).toBe(403);
|
||||||
|
expect((await request.authorized()).status).toBe(200);
|
||||||
|
expect((await request.admin()).status).toBe(200);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("reading permissions", async () => {
|
||||||
|
const { request } = await createAuthTestApp({
|
||||||
|
permission: ["system.access.api", "system.schema.read"],
|
||||||
|
request: new Request("http://localhost/api/system/permissions"),
|
||||||
|
});
|
||||||
|
expect((await request.guest()).status).toBe(403);
|
||||||
|
expect((await request.member()).status).toBe(403);
|
||||||
|
expect((await request.authorized()).status).toBe(200);
|
||||||
|
expect((await request.admin()).status).toBe(200);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("access openapi", async () => {
|
||||||
|
const { request } = await createAuthTestApp({
|
||||||
|
permission: ["system.access.api", "system.openapi"],
|
||||||
|
request: new Request("http://localhost/api/system/openapi.json"),
|
||||||
|
});
|
||||||
|
expect((await request.guest()).status).toBe(403);
|
||||||
|
expect((await request.member()).status).toBe(403);
|
||||||
|
expect((await request.authorized()).status).toBe(200);
|
||||||
|
expect((await request.admin()).status).toBe(200);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,171 @@
|
|||||||
|
import { createApp } from "core/test/utils";
|
||||||
|
import type { CreateAppConfig } from "App";
|
||||||
|
import type { RoleSchema } from "auth/authorize/Role";
|
||||||
|
import { isPlainObject } from "core/utils";
|
||||||
|
|
||||||
|
export type AuthTestConfig = {
|
||||||
|
guest?: RoleSchema;
|
||||||
|
member?: RoleSchema;
|
||||||
|
authorized?: RoleSchema;
|
||||||
|
};
|
||||||
|
|
||||||
|
export async function createAuthTestApp(
|
||||||
|
testConfig: {
|
||||||
|
permission: AuthTestConfig | string | string[];
|
||||||
|
request: Request;
|
||||||
|
},
|
||||||
|
config: Partial<CreateAppConfig> = {},
|
||||||
|
) {
|
||||||
|
let member: RoleSchema | undefined;
|
||||||
|
let authorized: RoleSchema | undefined;
|
||||||
|
let guest: RoleSchema | undefined;
|
||||||
|
if (isPlainObject(testConfig.permission)) {
|
||||||
|
if (testConfig.permission.guest)
|
||||||
|
guest = {
|
||||||
|
...testConfig.permission.guest,
|
||||||
|
is_default: true,
|
||||||
|
};
|
||||||
|
if (testConfig.permission.member) member = testConfig.permission.member;
|
||||||
|
if (testConfig.permission.authorized) authorized = testConfig.permission.authorized;
|
||||||
|
} else {
|
||||||
|
member = {
|
||||||
|
permissions: [],
|
||||||
|
};
|
||||||
|
authorized = {
|
||||||
|
permissions: Array.isArray(testConfig.permission)
|
||||||
|
? testConfig.permission
|
||||||
|
: [testConfig.permission],
|
||||||
|
};
|
||||||
|
guest = {
|
||||||
|
permissions: [],
|
||||||
|
is_default: true,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log("authorized", authorized);
|
||||||
|
|
||||||
|
const app = createApp({
|
||||||
|
...config,
|
||||||
|
config: {
|
||||||
|
...config.config,
|
||||||
|
auth: {
|
||||||
|
...config.config?.auth,
|
||||||
|
enabled: true,
|
||||||
|
guard: {
|
||||||
|
enabled: true,
|
||||||
|
...config.config?.auth?.guard,
|
||||||
|
},
|
||||||
|
jwt: {
|
||||||
|
...config.config?.auth?.jwt,
|
||||||
|
secret: "secret",
|
||||||
|
},
|
||||||
|
roles: {
|
||||||
|
...config.config?.auth?.roles,
|
||||||
|
guest,
|
||||||
|
member,
|
||||||
|
authorized,
|
||||||
|
admin: {
|
||||||
|
implicit_allow: true,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
await app.build();
|
||||||
|
|
||||||
|
const users = {
|
||||||
|
guest: null,
|
||||||
|
member: await app.createUser({
|
||||||
|
email: "member@test.com",
|
||||||
|
password: "12345678",
|
||||||
|
role: "member",
|
||||||
|
}),
|
||||||
|
authorized: await app.createUser({
|
||||||
|
email: "authorized@test.com",
|
||||||
|
password: "12345678",
|
||||||
|
role: "authorized",
|
||||||
|
}),
|
||||||
|
admin: await app.createUser({
|
||||||
|
email: "admin@test.com",
|
||||||
|
password: "12345678",
|
||||||
|
role: "admin",
|
||||||
|
}),
|
||||||
|
} as const;
|
||||||
|
|
||||||
|
const tokens = {} as Record<keyof typeof users, string>;
|
||||||
|
for (const [key, user] of Object.entries(users)) {
|
||||||
|
if (user) {
|
||||||
|
tokens[key as keyof typeof users] = await app.module.auth.authenticator.jwt(user);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function makeRequest(user: keyof typeof users, input: string, init: RequestInit = {}) {
|
||||||
|
const headers = new Headers(init.headers ?? {});
|
||||||
|
if (user in tokens) {
|
||||||
|
headers.set("Authorization", `Bearer ${tokens[user as keyof typeof tokens]}`);
|
||||||
|
}
|
||||||
|
const res = await app.server.request(input, {
|
||||||
|
...init,
|
||||||
|
headers,
|
||||||
|
});
|
||||||
|
|
||||||
|
let data: any;
|
||||||
|
if (res.headers.get("Content-Type")?.startsWith("application/json")) {
|
||||||
|
data = await res.json();
|
||||||
|
} else if (res.headers.get("Content-Type")?.startsWith("text/")) {
|
||||||
|
data = await res.text();
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
status: res.status,
|
||||||
|
ok: res.ok,
|
||||||
|
headers: Object.fromEntries(res.headers.entries()),
|
||||||
|
data,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const requestFn = new Proxy(
|
||||||
|
{},
|
||||||
|
{
|
||||||
|
get(_, prop: keyof typeof users) {
|
||||||
|
return async (input: string, init: RequestInit = {}) => {
|
||||||
|
return makeRequest(prop, input, init);
|
||||||
|
};
|
||||||
|
},
|
||||||
|
},
|
||||||
|
) as {
|
||||||
|
[K in keyof typeof users]: (
|
||||||
|
input: string,
|
||||||
|
init?: RequestInit,
|
||||||
|
) => Promise<{
|
||||||
|
status: number;
|
||||||
|
ok: boolean;
|
||||||
|
headers: Record<string, string>;
|
||||||
|
data: any;
|
||||||
|
}>;
|
||||||
|
};
|
||||||
|
|
||||||
|
const request = new Proxy(
|
||||||
|
{},
|
||||||
|
{
|
||||||
|
get(_, prop: keyof typeof users) {
|
||||||
|
return async () => {
|
||||||
|
return makeRequest(prop, testConfig.request.url, {
|
||||||
|
headers: testConfig.request.headers,
|
||||||
|
method: testConfig.request.method,
|
||||||
|
body: testConfig.request.body,
|
||||||
|
});
|
||||||
|
};
|
||||||
|
},
|
||||||
|
},
|
||||||
|
) as {
|
||||||
|
[K in keyof typeof users]: () => Promise<{
|
||||||
|
status: number;
|
||||||
|
ok: boolean;
|
||||||
|
headers: Record<string, string>;
|
||||||
|
data: any;
|
||||||
|
}>;
|
||||||
|
};
|
||||||
|
|
||||||
|
return { app, users, request, requestFn };
|
||||||
|
}
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
import { PasswordStrategy } from "auth/authenticate/strategies/PasswordStrategy";
|
||||||
|
import { describe, expect, it } from "bun:test";
|
||||||
|
|
||||||
|
describe("PasswordStrategy", () => {
|
||||||
|
it("should enforce provided minimum length", async () => {
|
||||||
|
const strategy = new PasswordStrategy({ minLength: 8, hashing: "plain" });
|
||||||
|
|
||||||
|
expect(strategy.verify("password")({} as any)).rejects.toThrow();
|
||||||
|
expect(
|
||||||
|
strategy.verify("password1234")({ strategy_value: "password1234" } as any),
|
||||||
|
).resolves.toBeUndefined();
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,85 @@
|
|||||||
|
import { describe, beforeAll, afterAll, test } from "bun:test";
|
||||||
|
import type { PostgresConnection } from "data/connection/postgres/PostgresConnection";
|
||||||
|
import { pg, postgresJs } from "bknd";
|
||||||
|
import { Pool } from "pg";
|
||||||
|
import postgres from "postgres";
|
||||||
|
import { disableConsoleLog, enableConsoleLog, $waitUntil } from "bknd/utils";
|
||||||
|
import { $ } from "bun";
|
||||||
|
import { connectionTestSuite } from "data/connection/connection-test-suite";
|
||||||
|
import { bunTestRunner } from "adapter/bun/test";
|
||||||
|
|
||||||
|
const credentials = {
|
||||||
|
host: "localhost",
|
||||||
|
port: 5430,
|
||||||
|
user: "postgres",
|
||||||
|
password: "postgres",
|
||||||
|
database: "bknd",
|
||||||
|
};
|
||||||
|
|
||||||
|
async function cleanDatabase(connection: InstanceType<typeof PostgresConnection>) {
|
||||||
|
const kysely = connection.kysely;
|
||||||
|
|
||||||
|
// drop all tables+indexes & create new schema
|
||||||
|
await kysely.schema.dropSchema("public").ifExists().cascade().execute();
|
||||||
|
await kysely.schema.dropIndex("public").ifExists().cascade().execute();
|
||||||
|
await kysely.schema.createSchema("public").execute();
|
||||||
|
}
|
||||||
|
|
||||||
|
async function isPostgresRunning() {
|
||||||
|
try {
|
||||||
|
// Try to actually connect to PostgreSQL
|
||||||
|
const conn = pg({ pool: new Pool(credentials) });
|
||||||
|
await conn.ping();
|
||||||
|
await conn.close();
|
||||||
|
return true;
|
||||||
|
} catch (e) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
describe("postgres", () => {
|
||||||
|
beforeAll(async () => {
|
||||||
|
if (!(await isPostgresRunning())) {
|
||||||
|
await $`docker run --rm --name bknd-test-postgres -d -e POSTGRES_PASSWORD=${credentials.password} -e POSTGRES_USER=${credentials.user} -e POSTGRES_DB=${credentials.database} -p ${credentials.port}:5432 postgres:17`;
|
||||||
|
await $waitUntil("Postgres is running", isPostgresRunning, 500, 20);
|
||||||
|
await new Promise((resolve) => setTimeout(resolve, 500));
|
||||||
|
}
|
||||||
|
|
||||||
|
disableConsoleLog();
|
||||||
|
}, 30000);
|
||||||
|
afterAll(async () => {
|
||||||
|
if (await isPostgresRunning()) {
|
||||||
|
try {
|
||||||
|
await $`docker stop bknd-test-postgres`;
|
||||||
|
} catch (e) {}
|
||||||
|
}
|
||||||
|
|
||||||
|
enableConsoleLog();
|
||||||
|
});
|
||||||
|
|
||||||
|
describe.serial.each([
|
||||||
|
["pg", () => pg({ pool: new Pool(credentials) })],
|
||||||
|
["postgresjs", () => postgresJs({ postgres: postgres(credentials) })],
|
||||||
|
])("%s", (name, createConnection) => {
|
||||||
|
connectionTestSuite(
|
||||||
|
{
|
||||||
|
...bunTestRunner,
|
||||||
|
test: test.serial,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
makeConnection: () => {
|
||||||
|
const connection = createConnection();
|
||||||
|
return {
|
||||||
|
connection,
|
||||||
|
dispose: async () => {
|
||||||
|
await cleanDatabase(connection);
|
||||||
|
await connection.close();
|
||||||
|
},
|
||||||
|
};
|
||||||
|
},
|
||||||
|
rawDialectDetails: [],
|
||||||
|
disableConsoleLog: false,
|
||||||
|
},
|
||||||
|
);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -124,6 +124,81 @@ describe("[Repository]", async () => {
|
|||||||
.then((r) => [r.count, r.total]),
|
.then((r) => [r.count, r.total]),
|
||||||
).resolves.toEqual([undefined, undefined]);
|
).resolves.toEqual([undefined, undefined]);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test("auto join", async () => {
|
||||||
|
const schema = $em(
|
||||||
|
{
|
||||||
|
posts: $entity("posts", {
|
||||||
|
title: $text(),
|
||||||
|
content: $text(),
|
||||||
|
}),
|
||||||
|
comments: $entity("comments", {
|
||||||
|
content: $text(),
|
||||||
|
}),
|
||||||
|
another: $entity("another", {
|
||||||
|
title: $text(),
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
({ relation }, { posts, comments }) => {
|
||||||
|
relation(comments).manyToOne(posts);
|
||||||
|
},
|
||||||
|
);
|
||||||
|
const em = schema.proto.withConnection(getDummyConnection().dummyConnection);
|
||||||
|
await em.schema().sync({ force: true });
|
||||||
|
|
||||||
|
await em.mutator("posts").insertOne({ title: "post1", content: "content1" });
|
||||||
|
await em
|
||||||
|
.mutator("comments")
|
||||||
|
.insertMany([{ content: "comment1", posts_id: 1 }, { content: "comment2" }] as any);
|
||||||
|
|
||||||
|
const res = await em.repo("comments").findMany({
|
||||||
|
where: {
|
||||||
|
"posts.title": "post1",
|
||||||
|
},
|
||||||
|
});
|
||||||
|
expect(res.data as any).toEqual([
|
||||||
|
{
|
||||||
|
id: 1,
|
||||||
|
content: "comment1",
|
||||||
|
posts_id: 1,
|
||||||
|
},
|
||||||
|
]);
|
||||||
|
|
||||||
|
{
|
||||||
|
// manual join should still work
|
||||||
|
const res = await em.repo("comments").findMany({
|
||||||
|
join: ["posts"],
|
||||||
|
where: {
|
||||||
|
"posts.title": "post1",
|
||||||
|
},
|
||||||
|
});
|
||||||
|
expect(res.data as any).toEqual([
|
||||||
|
{
|
||||||
|
id: 1,
|
||||||
|
content: "comment1",
|
||||||
|
posts_id: 1,
|
||||||
|
},
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
// inexistent should be detected and thrown
|
||||||
|
expect(
|
||||||
|
em.repo("comments").findMany({
|
||||||
|
where: {
|
||||||
|
"random.title": "post1",
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
).rejects.toThrow(/Invalid where field/);
|
||||||
|
|
||||||
|
// existing alias, but not a relation should throw
|
||||||
|
expect(
|
||||||
|
em.repo("comments").findMany({
|
||||||
|
where: {
|
||||||
|
"another.title": "post1",
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
).rejects.toThrow(/Invalid where field/);
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
describe("[data] Repository (Events)", async () => {
|
describe("[data] Repository (Events)", async () => {
|
||||||
|
|||||||
@@ -88,7 +88,7 @@ describe("[data] WithBuilder", async () => {
|
|||||||
const res2 = qb2.compile();
|
const res2 = qb2.compile();
|
||||||
|
|
||||||
expect(res2.sql).toBe(
|
expect(res2.sql).toBe(
|
||||||
'select (select json_object(\'id\', "obj"."id", \'username\', "obj"."username") from (select "users"."id" as "id", "users"."username" as "username" from "users" as "author" where "author"."id" = "posts"."author_id" order by "users"."id" asc limit ?) as obj) as "author" from "posts"',
|
'select (select json_object(\'id\', "obj"."id", \'username\', "obj"."username") from (select "author"."id" as "id", "author"."username" as "username" from "users" as "author" where "author"."id" = "posts"."author_id" order by "author"."id" asc limit ?) as obj) as "author" from "posts"',
|
||||||
);
|
);
|
||||||
expect(res2.parameters).toEqual([1]);
|
expect(res2.parameters).toEqual([1]);
|
||||||
});
|
});
|
||||||
@@ -192,9 +192,7 @@ describe("[data] WithBuilder", async () => {
|
|||||||
{ single: {} },
|
{ single: {} },
|
||||||
);
|
);
|
||||||
const res = qb.compile();
|
const res = qb.compile();
|
||||||
expect(res.sql).toBe(
|
expect(res.sql).toMatchSnapshot();
|
||||||
'select (select json_object(\'id\', "obj"."id", \'path\', "obj"."path") from (select "media"."id" as "id", "media"."path" as "path" from "media" where "media"."reference" = ? and "categories"."id" = "media"."entity_id" order by "media"."id" asc limit ?) as obj) as "single" from "categories"',
|
|
||||||
);
|
|
||||||
expect(res.parameters).toEqual(["categories.single", 1]);
|
expect(res.parameters).toEqual(["categories.single", 1]);
|
||||||
|
|
||||||
const qb2 = WithBuilder.addClause(
|
const qb2 = WithBuilder.addClause(
|
||||||
@@ -204,9 +202,7 @@ describe("[data] WithBuilder", async () => {
|
|||||||
{ multiple: {} },
|
{ multiple: {} },
|
||||||
);
|
);
|
||||||
const res2 = qb2.compile();
|
const res2 = qb2.compile();
|
||||||
expect(res2.sql).toBe(
|
expect(res2.sql).toMatchSnapshot();
|
||||||
'select (select coalesce(json_group_array(json_object(\'id\', "agg"."id", \'path\', "agg"."path")), \'[]\') from (select "media"."id" as "id", "media"."path" as "path" from "media" where "media"."reference" = ? and "categories"."id" = "media"."entity_id" order by "media"."id" asc limit ? offset ?) as agg) as "multiple" from "categories"',
|
|
||||||
);
|
|
||||||
expect(res2.parameters).toEqual(["categories.multiple", 10, 0]);
|
expect(res2.parameters).toEqual(["categories.multiple", 10, 0]);
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -271,9 +267,7 @@ describe("[data] WithBuilder", async () => {
|
|||||||
);
|
);
|
||||||
|
|
||||||
//prettyPrintQb(qb);
|
//prettyPrintQb(qb);
|
||||||
expect(qb.compile().sql).toBe(
|
expect(qb.compile().sql).toMatchSnapshot();
|
||||||
'select (select json_object(\'id\', "obj"."id", \'username\', "obj"."username", \'avatar\', "obj"."avatar") from (select "users"."id" as "id", "users"."username" as "username", (select json_object(\'id\', "obj"."id", \'path\', "obj"."path") from (select "media"."id" as "id", "media"."path" as "path" from "media" where "media"."reference" = ? and "users"."id" = "media"."entity_id" order by "media"."id" asc limit ?) as obj) as "avatar" from "users" as "users" where "users"."id" = "posts"."users_id" order by "users"."username" asc limit ?) as obj) as "users" from "posts"',
|
|
||||||
);
|
|
||||||
expect(qb.compile().parameters).toEqual(["users.avatar", 1, 1]);
|
expect(qb.compile().parameters).toEqual(["users.avatar", 1, 1]);
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -313,9 +307,7 @@ describe("[data] WithBuilder", async () => {
|
|||||||
},
|
},
|
||||||
);
|
);
|
||||||
|
|
||||||
expect(qb.compile().sql).toBe(
|
expect(qb.compile().sql).toMatchSnapshot();
|
||||||
'select (select coalesce(json_group_array(json_object(\'id\', "agg"."id", \'posts_id\', "agg"."posts_id", \'users_id\', "agg"."users_id", \'users\', "agg"."users")), \'[]\') from (select "comments"."id" as "id", "comments"."posts_id" as "posts_id", "comments"."users_id" as "users_id", (select json_object(\'username\', "obj"."username") from (select "users"."username" as "username" from "users" as "users" where "users"."id" = "comments"."users_id" order by "users"."id" asc limit ?) as obj) as "users" from "comments" as "comments" where "comments"."posts_id" = "posts"."id" order by "comments"."id" asc limit ? offset ?) as agg) as "comments" from "posts"',
|
|
||||||
);
|
|
||||||
expect(qb.compile().parameters).toEqual([1, 12, 0]);
|
expect(qb.compile().parameters).toEqual([1, 12, 0]);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,9 @@
|
|||||||
|
// Bun Snapshot v1, https://bun.sh/docs/test/snapshots
|
||||||
|
|
||||||
|
exports[`[data] WithBuilder recursive compiles with singles 1`] = `"select (select json_object('id', "obj"."id", 'username', "obj"."username", 'avatar', "obj"."avatar") from (select "users"."id" as "id", "users"."username" as "username", (select json_object('id', "obj"."id", 'path', "obj"."path") from (select "avatar"."id" as "id", "avatar"."path" as "path" from "media" where "media"."reference" = ? and "users"."id" = "media"."entity_id" order by "avatar"."id" asc limit ?) as obj) as "avatar" from "users" as "users" where "users"."id" = "posts"."users_id" order by "users"."username" asc limit ?) as obj) as "users" from "posts""`;
|
||||||
|
|
||||||
|
exports[`[data] WithBuilder recursive compiles with many 1`] = `"select (select coalesce(json_group_array(json_object('id', "agg"."id", 'posts_id', "agg"."posts_id", 'users_id', "agg"."users_id", 'users', "agg"."users")), '[]') from (select "comments"."id" as "id", "comments"."posts_id" as "posts_id", "comments"."users_id" as "users_id", (select json_object('username', "obj"."username") from (select "users"."username" as "username" from "users" as "users" where "users"."id" = "comments"."users_id" order by "users"."id" asc limit ?) as obj) as "users" from "comments" as "comments" where "comments"."posts_id" = "posts"."id" order by "comments"."id" asc limit ? offset ?) as agg) as "comments" from "posts""`;
|
||||||
|
|
||||||
|
exports[`[data] WithBuilder polymorphic 1`] = `"select (select json_object('id', "obj"."id", 'path', "obj"."path") from (select "single"."id" as "id", "single"."path" as "path" from "media" where "media"."reference" = ? and "categories"."id" = "media"."entity_id" order by "single"."id" asc limit ?) as obj) as "single" from "categories""`;
|
||||||
|
|
||||||
|
exports[`[data] WithBuilder polymorphic 2`] = `"select (select coalesce(json_group_array(json_object('id', "agg"."id", 'path', "agg"."path")), '[]') from (select "multiple"."id" as "id", "multiple"."path" as "path" from "media" where "media"."reference" = ? and "categories"."id" = "media"."entity_id" order by "multiple"."id" asc limit ? offset ?) as agg) as "multiple" from "categories""`;
|
||||||
@@ -59,7 +59,7 @@ describe("SqliteIntrospector", () => {
|
|||||||
dataType: "INTEGER",
|
dataType: "INTEGER",
|
||||||
isNullable: false,
|
isNullable: false,
|
||||||
isAutoIncrementing: true,
|
isAutoIncrementing: true,
|
||||||
hasDefaultValue: false,
|
hasDefaultValue: true,
|
||||||
comment: undefined,
|
comment: undefined,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -89,7 +89,7 @@ describe("SqliteIntrospector", () => {
|
|||||||
dataType: "INTEGER",
|
dataType: "INTEGER",
|
||||||
isNullable: false,
|
isNullable: false,
|
||||||
isAutoIncrementing: true,
|
isAutoIncrementing: true,
|
||||||
hasDefaultValue: false,
|
hasDefaultValue: true,
|
||||||
comment: undefined,
|
comment: undefined,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -1,9 +1,15 @@
|
|||||||
import { afterAll, beforeAll, describe, expect, it } from "bun:test";
|
import { afterAll, beforeAll, describe, expect, it } from "bun:test";
|
||||||
import { App, createApp, type AuthResponse } from "../../src";
|
import { App, createApp, type AuthResponse } from "../../src";
|
||||||
import { auth } from "../../src/modules/middlewares";
|
import { auth } from "../../src/modules/middlewares";
|
||||||
import { randomString, secureRandomString, withDisabledConsole } from "../../src/core/utils";
|
import {
|
||||||
|
mergeObject,
|
||||||
|
randomString,
|
||||||
|
secureRandomString,
|
||||||
|
withDisabledConsole,
|
||||||
|
} from "../../src/core/utils";
|
||||||
import { disableConsoleLog, enableConsoleLog } from "core/utils/test";
|
import { disableConsoleLog, enableConsoleLog } from "core/utils/test";
|
||||||
import { getDummyConnection } from "../helper";
|
import { getDummyConnection } from "../helper";
|
||||||
|
import type { AppAuthSchema } from "auth/auth-schema";
|
||||||
|
|
||||||
beforeAll(disableConsoleLog);
|
beforeAll(disableConsoleLog);
|
||||||
afterAll(enableConsoleLog);
|
afterAll(enableConsoleLog);
|
||||||
@@ -62,12 +68,12 @@ const configs = {
|
|||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
function createAuthApp() {
|
function createAuthApp(config?: Partial<AppAuthSchema>) {
|
||||||
const { dummyConnection } = getDummyConnection();
|
const { dummyConnection } = getDummyConnection();
|
||||||
const app = createApp({
|
const app = createApp({
|
||||||
connection: dummyConnection,
|
connection: dummyConnection,
|
||||||
config: {
|
config: {
|
||||||
auth: configs.auth,
|
auth: mergeObject(configs.auth, config ?? {}),
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -132,6 +138,16 @@ const fns = <Mode extends "cookie" | "token" = "token">(app: App, mode?: Mode) =
|
|||||||
|
|
||||||
return { res, data };
|
return { res, data };
|
||||||
},
|
},
|
||||||
|
register: async (user: any): Promise<{ res: Response; data: AuthResponse }> => {
|
||||||
|
const res = (await app.server.request("/api/auth/password/register", {
|
||||||
|
method: "POST",
|
||||||
|
headers: headers(),
|
||||||
|
body: body(user),
|
||||||
|
})) as Response;
|
||||||
|
const data = mode === "cookie" ? getCookie(res, "auth") : await res.json();
|
||||||
|
|
||||||
|
return { res, data };
|
||||||
|
},
|
||||||
me: async (token?: string): Promise<Pick<AuthResponse, "user">> => {
|
me: async (token?: string): Promise<Pick<AuthResponse, "user">> => {
|
||||||
const res = (await app.server.request("/api/auth/me", {
|
const res = (await app.server.request("/api/auth/me", {
|
||||||
method: "GET",
|
method: "GET",
|
||||||
@@ -245,4 +261,61 @@ describe("integration auth", () => {
|
|||||||
expect(await $fns.me()).toEqual({ user: null as any });
|
expect(await $fns.me()).toEqual({ user: null as any });
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it("should register users with default role", async () => {
|
||||||
|
const app = createAuthApp({ default_role_register: "guest" });
|
||||||
|
await app.build();
|
||||||
|
const $fns = fns(app);
|
||||||
|
|
||||||
|
// takes default role
|
||||||
|
expect(
|
||||||
|
await app
|
||||||
|
.createUser({
|
||||||
|
email: "test@bknd.io",
|
||||||
|
password: "12345678",
|
||||||
|
})
|
||||||
|
.then((r) => r.role),
|
||||||
|
).toBe("guest");
|
||||||
|
|
||||||
|
// throws error if role doesn't exist
|
||||||
|
expect(
|
||||||
|
app.createUser({
|
||||||
|
email: "test@bknd.io",
|
||||||
|
password: "12345678",
|
||||||
|
role: "doesnt exist",
|
||||||
|
}),
|
||||||
|
).rejects.toThrow();
|
||||||
|
|
||||||
|
// takes role if provided
|
||||||
|
expect(
|
||||||
|
await app
|
||||||
|
.createUser({
|
||||||
|
email: "test2@bknd.io",
|
||||||
|
password: "12345678",
|
||||||
|
role: "admin",
|
||||||
|
})
|
||||||
|
.then((r) => r.role),
|
||||||
|
).toBe("admin");
|
||||||
|
|
||||||
|
// registering with role is not allowed
|
||||||
|
expect(
|
||||||
|
await $fns
|
||||||
|
.register({
|
||||||
|
email: "test3@bknd.io",
|
||||||
|
password: "12345678",
|
||||||
|
role: "admin",
|
||||||
|
})
|
||||||
|
.then((r) => r.res.ok),
|
||||||
|
).toBe(false);
|
||||||
|
|
||||||
|
// takes default role
|
||||||
|
expect(
|
||||||
|
await $fns
|
||||||
|
.register({
|
||||||
|
email: "test3@bknd.io",
|
||||||
|
password: "12345678",
|
||||||
|
})
|
||||||
|
.then((r) => r.data.user.role),
|
||||||
|
).toBe("guest");
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -8,9 +8,10 @@ import type { TAppMediaConfig } from "../../src/media/media-schema";
|
|||||||
import { StorageLocalAdapter } from "adapter/node/storage/StorageLocalAdapter";
|
import { StorageLocalAdapter } from "adapter/node/storage/StorageLocalAdapter";
|
||||||
import { assetsPath, assetsTmpPath } from "../helper";
|
import { assetsPath, assetsTmpPath } from "../helper";
|
||||||
import { disableConsoleLog, enableConsoleLog } from "core/utils/test";
|
import { disableConsoleLog, enableConsoleLog } from "core/utils/test";
|
||||||
|
import * as proto from "data/prototype";
|
||||||
|
|
||||||
beforeAll(() => {
|
beforeAll(() => {
|
||||||
//disableConsoleLog();
|
disableConsoleLog();
|
||||||
registries.media.register("local", StorageLocalAdapter);
|
registries.media.register("local", StorageLocalAdapter);
|
||||||
});
|
});
|
||||||
afterAll(enableConsoleLog);
|
afterAll(enableConsoleLog);
|
||||||
@@ -128,4 +129,87 @@ describe("MediaController", () => {
|
|||||||
expect(destFile.exists()).resolves.toBe(true);
|
expect(destFile.exists()).resolves.toBe(true);
|
||||||
await destFile.delete();
|
await destFile.delete();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test("entity upload with max_items and overwrite", async () => {
|
||||||
|
const app = createApp({
|
||||||
|
config: {
|
||||||
|
media: mergeObject(
|
||||||
|
{
|
||||||
|
enabled: true,
|
||||||
|
adapter: {
|
||||||
|
type: "local",
|
||||||
|
config: {
|
||||||
|
path: assetsTmpPath,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{},
|
||||||
|
),
|
||||||
|
data: {
|
||||||
|
entities: {
|
||||||
|
posts: proto
|
||||||
|
.entity("posts", {
|
||||||
|
title: proto.text(),
|
||||||
|
cover: proto.medium(),
|
||||||
|
})
|
||||||
|
.toJSON(),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
await app.build();
|
||||||
|
|
||||||
|
// create a post first
|
||||||
|
const createRes = await app.server.request("/api/data/entity/posts", {
|
||||||
|
method: "POST",
|
||||||
|
headers: { "Content-Type": "application/json" },
|
||||||
|
body: JSON.stringify({ title: "Test Post" }),
|
||||||
|
});
|
||||||
|
expect(createRes.status).toBe(201);
|
||||||
|
const { data: post } = (await createRes.json()) as any;
|
||||||
|
|
||||||
|
const file = Bun.file(path);
|
||||||
|
const uploadedFiles: string[] = [];
|
||||||
|
|
||||||
|
// upload first file to entity (should succeed)
|
||||||
|
const res1 = await app.server.request(`/api/media/entity/posts/${post.id}/cover`, {
|
||||||
|
method: "POST",
|
||||||
|
body: file,
|
||||||
|
});
|
||||||
|
expect(res1.status).toBe(201);
|
||||||
|
const result1 = (await res1.json()) as any;
|
||||||
|
uploadedFiles.push(result1.name);
|
||||||
|
|
||||||
|
// upload second file without overwrite (should fail - max_items reached)
|
||||||
|
const res2 = await app.server.request(`/api/media/entity/posts/${post.id}/cover`, {
|
||||||
|
method: "POST",
|
||||||
|
body: file,
|
||||||
|
});
|
||||||
|
expect(res2.status).toBe(400);
|
||||||
|
const result2 = (await res2.json()) as any;
|
||||||
|
expect(result2.error).toContain("Max items");
|
||||||
|
|
||||||
|
// upload third file with overwrite=true (should succeed and delete old file)
|
||||||
|
const res3 = await app.server.request(
|
||||||
|
`/api/media/entity/posts/${post.id}/cover?overwrite=true`,
|
||||||
|
{
|
||||||
|
method: "POST",
|
||||||
|
body: file,
|
||||||
|
},
|
||||||
|
);
|
||||||
|
expect(res3.status).toBe(201);
|
||||||
|
const result3 = (await res3.json()) as any;
|
||||||
|
uploadedFiles.push(result3.name);
|
||||||
|
|
||||||
|
// verify old file was deleted from storage
|
||||||
|
const oldFile = Bun.file(assetsTmpPath + "/" + uploadedFiles[0]);
|
||||||
|
expect(await oldFile.exists()).toBe(false);
|
||||||
|
|
||||||
|
// verify new file exists
|
||||||
|
const newFile = Bun.file(assetsTmpPath + "/" + uploadedFiles[1]);
|
||||||
|
expect(await newFile.exists()).toBe(true);
|
||||||
|
|
||||||
|
// cleanup
|
||||||
|
await newFile.delete();
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -10,12 +10,6 @@ beforeAll(disableConsoleLog);
|
|||||||
afterAll(enableConsoleLog);
|
afterAll(enableConsoleLog);
|
||||||
|
|
||||||
describe("AppAuth", () => {
|
describe("AppAuth", () => {
|
||||||
test.skip("...", () => {
|
|
||||||
const auth = new AppAuth({});
|
|
||||||
console.log(auth.toJSON());
|
|
||||||
console.log(auth.config);
|
|
||||||
});
|
|
||||||
|
|
||||||
moduleTestSuite(AppAuth);
|
moduleTestSuite(AppAuth);
|
||||||
|
|
||||||
let ctx: ModuleBuildContext;
|
let ctx: ModuleBuildContext;
|
||||||
@@ -39,11 +33,9 @@ describe("AppAuth", () => {
|
|||||||
await auth.build();
|
await auth.build();
|
||||||
|
|
||||||
const oldConfig = auth.toJSON(true);
|
const oldConfig = auth.toJSON(true);
|
||||||
//console.log(oldConfig);
|
|
||||||
await auth.schema().patch("enabled", true);
|
await auth.schema().patch("enabled", true);
|
||||||
await auth.build();
|
await auth.build();
|
||||||
const newConfig = auth.toJSON(true);
|
const newConfig = auth.toJSON(true);
|
||||||
//console.log(newConfig);
|
|
||||||
expect(newConfig.jwt.secret).not.toBe(oldConfig.jwt.secret);
|
expect(newConfig.jwt.secret).not.toBe(oldConfig.jwt.secret);
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -69,7 +61,6 @@ describe("AppAuth", () => {
|
|||||||
const app = new AuthController(auth).getController();
|
const app = new AuthController(auth).getController();
|
||||||
|
|
||||||
{
|
{
|
||||||
disableConsoleLog();
|
|
||||||
const res = await app.request("/password/register", {
|
const res = await app.request("/password/register", {
|
||||||
method: "POST",
|
method: "POST",
|
||||||
headers: {
|
headers: {
|
||||||
@@ -80,7 +71,6 @@ describe("AppAuth", () => {
|
|||||||
password: "12345678",
|
password: "12345678",
|
||||||
}),
|
}),
|
||||||
});
|
});
|
||||||
enableConsoleLog();
|
|
||||||
expect(res.status).toBe(200);
|
expect(res.status).toBe(200);
|
||||||
|
|
||||||
const { data: users } = await ctx.em.repository("users").findMany();
|
const { data: users } = await ctx.em.repository("users").findMany();
|
||||||
@@ -119,7 +109,6 @@ describe("AppAuth", () => {
|
|||||||
const app = new AuthController(auth).getController();
|
const app = new AuthController(auth).getController();
|
||||||
|
|
||||||
{
|
{
|
||||||
disableConsoleLog();
|
|
||||||
const res = await app.request("/password/register", {
|
const res = await app.request("/password/register", {
|
||||||
method: "POST",
|
method: "POST",
|
||||||
headers: {
|
headers: {
|
||||||
@@ -130,7 +119,6 @@ describe("AppAuth", () => {
|
|||||||
password: "12345678",
|
password: "12345678",
|
||||||
}),
|
}),
|
||||||
});
|
});
|
||||||
enableConsoleLog();
|
|
||||||
expect(res.status).toBe(200);
|
expect(res.status).toBe(200);
|
||||||
|
|
||||||
const { data: users } = await ctx.em.repository("users").findMany();
|
const { data: users } = await ctx.em.repository("users").findMany();
|
||||||
@@ -161,7 +149,7 @@ describe("AppAuth", () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
await app.build();
|
await app.build();
|
||||||
app.registerAdminController();
|
app.registerAdminController({ forceDev: true });
|
||||||
const spy = spyOn(app.module.auth.authenticator, "requestCookieRefresh");
|
const spy = spyOn(app.module.auth.authenticator, "requestCookieRefresh");
|
||||||
|
|
||||||
// register custom route
|
// register custom route
|
||||||
@@ -235,4 +223,32 @@ describe("AppAuth", () => {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test("default role for registration must be a valid role", async () => {
|
||||||
|
const app = createApp({
|
||||||
|
config: {
|
||||||
|
auth: {
|
||||||
|
enabled: true,
|
||||||
|
jwt: {
|
||||||
|
secret: "123456",
|
||||||
|
},
|
||||||
|
allow_register: true,
|
||||||
|
roles: {
|
||||||
|
guest: {
|
||||||
|
is_default: true,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
await app.build();
|
||||||
|
|
||||||
|
const auth = app.module.auth;
|
||||||
|
// doesn't allow invalid role
|
||||||
|
expect(auth.schema().patch("default_role_register", "admin")).rejects.toThrow();
|
||||||
|
// allows valid role
|
||||||
|
await auth.schema().patch("default_role_register", "guest");
|
||||||
|
expect(auth.toJSON().default_role_register).toBe("guest");
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -1,10 +1,14 @@
|
|||||||
import { describe, expect, test } from "bun:test";
|
import { describe, expect, test, beforeAll, afterAll } from "bun:test";
|
||||||
import { createApp } from "core/test/utils";
|
import { createApp } from "core/test/utils";
|
||||||
import { em, entity, text } from "data/prototype";
|
import { em, entity, text } from "data/prototype";
|
||||||
import { registries } from "modules/registries";
|
import { registries } from "modules/registries";
|
||||||
import { StorageLocalAdapter } from "adapter/node/storage/StorageLocalAdapter";
|
import { StorageLocalAdapter } from "adapter/node/storage/StorageLocalAdapter";
|
||||||
import { AppMedia } from "../../src/media/AppMedia";
|
import { AppMedia } from "../../src/media/AppMedia";
|
||||||
import { moduleTestSuite } from "./module-test-suite";
|
import { moduleTestSuite } from "./module-test-suite";
|
||||||
|
import { disableConsoleLog, enableConsoleLog } from "core/utils/test";
|
||||||
|
|
||||||
|
beforeAll(disableConsoleLog);
|
||||||
|
afterAll(enableConsoleLog);
|
||||||
|
|
||||||
describe("AppMedia", () => {
|
describe("AppMedia", () => {
|
||||||
test.skip("...", () => {
|
test.skip("...", () => {
|
||||||
|
|||||||
@@ -1,7 +1,11 @@
|
|||||||
import { it, expect, describe } from "bun:test";
|
import { it, expect, describe, beforeAll, afterAll } from "bun:test";
|
||||||
import { DbModuleManager } from "modules/db/DbModuleManager";
|
import { DbModuleManager } from "modules/db/DbModuleManager";
|
||||||
import { getDummyConnection } from "../helper";
|
import { getDummyConnection } from "../helper";
|
||||||
import { TABLE_NAME } from "modules/db/migrations";
|
import { TABLE_NAME } from "modules/db/migrations";
|
||||||
|
import { disableConsoleLog, enableConsoleLog } from "core/utils/test";
|
||||||
|
|
||||||
|
beforeAll(disableConsoleLog);
|
||||||
|
afterAll(enableConsoleLog);
|
||||||
|
|
||||||
describe("DbModuleManager", () => {
|
describe("DbModuleManager", () => {
|
||||||
it("should extract secrets", async () => {
|
it("should extract secrets", async () => {
|
||||||
|
|||||||
@@ -11,7 +11,7 @@ import { s, stripMark } from "core/utils/schema";
|
|||||||
import { Connection } from "data/connection/Connection";
|
import { Connection } from "data/connection/Connection";
|
||||||
import { entity, text } from "data/prototype";
|
import { entity, text } from "data/prototype";
|
||||||
|
|
||||||
beforeAll(disableConsoleLog);
|
beforeAll(() => disableConsoleLog());
|
||||||
afterAll(enableConsoleLog);
|
afterAll(enableConsoleLog);
|
||||||
|
|
||||||
describe("ModuleManager", async () => {
|
describe("ModuleManager", async () => {
|
||||||
@@ -82,7 +82,6 @@ describe("ModuleManager", async () => {
|
|||||||
},
|
},
|
||||||
},
|
},
|
||||||
} as any;
|
} as any;
|
||||||
//const { version, ...json } = mm.toJSON() as any;
|
|
||||||
|
|
||||||
const { dummyConnection } = getDummyConnection();
|
const { dummyConnection } = getDummyConnection();
|
||||||
const db = dummyConnection.kysely;
|
const db = dummyConnection.kysely;
|
||||||
@@ -97,10 +96,6 @@ describe("ModuleManager", async () => {
|
|||||||
|
|
||||||
await mm2.build();
|
await mm2.build();
|
||||||
|
|
||||||
/* console.log({
|
|
||||||
json,
|
|
||||||
configs: mm2.configs(),
|
|
||||||
}); */
|
|
||||||
//expect(stripMark(json)).toEqual(stripMark(mm2.configs()));
|
//expect(stripMark(json)).toEqual(stripMark(mm2.configs()));
|
||||||
expect(mm2.configs().data.entities?.test).toBeDefined();
|
expect(mm2.configs().data.entities?.test).toBeDefined();
|
||||||
expect(mm2.configs().data.entities?.test?.fields?.content).toBeDefined();
|
expect(mm2.configs().data.entities?.test?.fields?.content).toBeDefined();
|
||||||
@@ -228,8 +223,6 @@ describe("ModuleManager", async () => {
|
|||||||
const c = getDummyConnection();
|
const c = getDummyConnection();
|
||||||
const mm = new ModuleManager(c.dummyConnection);
|
const mm = new ModuleManager(c.dummyConnection);
|
||||||
await mm.build();
|
await mm.build();
|
||||||
console.log("==".repeat(30));
|
|
||||||
console.log("");
|
|
||||||
const json = mm.configs();
|
const json = mm.configs();
|
||||||
|
|
||||||
const c2 = getDummyConnection();
|
const c2 = getDummyConnection();
|
||||||
@@ -275,7 +268,6 @@ describe("ModuleManager", async () => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
override async build() {
|
override async build() {
|
||||||
//console.log("building FailingModule", this.config);
|
|
||||||
if (this.config.value && this.config.value < 0) {
|
if (this.config.value && this.config.value < 0) {
|
||||||
throw new Error("value must be positive, given: " + this.config.value);
|
throw new Error("value must be positive, given: " + this.config.value);
|
||||||
}
|
}
|
||||||
@@ -296,9 +288,6 @@ describe("ModuleManager", async () => {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
beforeEach(() => disableConsoleLog(["log", "warn", "error"]));
|
|
||||||
afterEach(enableConsoleLog);
|
|
||||||
|
|
||||||
test("it builds", async () => {
|
test("it builds", async () => {
|
||||||
const { dummyConnection } = getDummyConnection();
|
const { dummyConnection } = getDummyConnection();
|
||||||
const mm = new TestModuleManager(dummyConnection);
|
const mm = new TestModuleManager(dummyConnection);
|
||||||
|
|||||||
@@ -0,0 +1,284 @@
|
|||||||
|
import { describe, it, expect, beforeEach } from "vitest";
|
||||||
|
import { AppReduced, type AppType } from "ui/client/utils/AppReduced";
|
||||||
|
import type { BkndAdminProps } from "ui/Admin";
|
||||||
|
|
||||||
|
// Import the normalizeAdminPath function for testing
|
||||||
|
// Note: This assumes the function is exported or we need to test it indirectly through public methods
|
||||||
|
|
||||||
|
describe("AppReduced", () => {
|
||||||
|
let mockAppJson: AppType;
|
||||||
|
let appReduced: AppReduced;
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
mockAppJson = {
|
||||||
|
data: {
|
||||||
|
entities: {},
|
||||||
|
relations: {},
|
||||||
|
},
|
||||||
|
flows: {
|
||||||
|
flows: {},
|
||||||
|
},
|
||||||
|
auth: {},
|
||||||
|
} as AppType;
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("getSettingsPath", () => {
|
||||||
|
it("should return settings path with basepath", () => {
|
||||||
|
const options: BkndAdminProps["config"] = {
|
||||||
|
basepath: "/admin",
|
||||||
|
logo_return_path: "/",
|
||||||
|
};
|
||||||
|
|
||||||
|
appReduced = new AppReduced(mockAppJson, options);
|
||||||
|
const result = appReduced.getSettingsPath();
|
||||||
|
|
||||||
|
expect(result).toBe("~/admin/settings");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("should return settings path with empty basepath", () => {
|
||||||
|
const options: BkndAdminProps["config"] = {
|
||||||
|
basepath: "",
|
||||||
|
logo_return_path: "/",
|
||||||
|
};
|
||||||
|
|
||||||
|
appReduced = new AppReduced(mockAppJson, options);
|
||||||
|
const result = appReduced.getSettingsPath();
|
||||||
|
|
||||||
|
expect(result).toBe("~/settings");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("should append additional path segments", () => {
|
||||||
|
const options: BkndAdminProps["config"] = {
|
||||||
|
basepath: "/admin",
|
||||||
|
logo_return_path: "/",
|
||||||
|
};
|
||||||
|
|
||||||
|
appReduced = new AppReduced(mockAppJson, options);
|
||||||
|
const result = appReduced.getSettingsPath(["user", "profile"]);
|
||||||
|
|
||||||
|
expect(result).toBe("~/admin/settings/user/profile");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("should normalize multiple slashes", () => {
|
||||||
|
const options: BkndAdminProps["config"] = {
|
||||||
|
basepath: "//admin//",
|
||||||
|
logo_return_path: "/",
|
||||||
|
};
|
||||||
|
|
||||||
|
appReduced = new AppReduced(mockAppJson, options);
|
||||||
|
const result = appReduced.getSettingsPath(["//user//"]);
|
||||||
|
|
||||||
|
expect(result).toBe("~/admin/settings/user");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("should handle basepath without leading slash", () => {
|
||||||
|
const options: BkndAdminProps["config"] = {
|
||||||
|
basepath: "admin",
|
||||||
|
logo_return_path: "/",
|
||||||
|
};
|
||||||
|
|
||||||
|
appReduced = new AppReduced(mockAppJson, options);
|
||||||
|
const result = appReduced.getSettingsPath();
|
||||||
|
|
||||||
|
expect(result).toBe("~/admin/settings");
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("getAbsolutePath", () => {
|
||||||
|
it("should return absolute path with basepath", () => {
|
||||||
|
const options: BkndAdminProps["config"] = {
|
||||||
|
basepath: "/admin",
|
||||||
|
logo_return_path: "/",
|
||||||
|
};
|
||||||
|
|
||||||
|
appReduced = new AppReduced(mockAppJson, options);
|
||||||
|
const result = appReduced.getAbsolutePath("dashboard");
|
||||||
|
|
||||||
|
expect(result).toBe("~/admin/dashboard");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("should return base path when no path provided", () => {
|
||||||
|
const options: BkndAdminProps["config"] = {
|
||||||
|
basepath: "/admin",
|
||||||
|
logo_return_path: "/",
|
||||||
|
};
|
||||||
|
|
||||||
|
appReduced = new AppReduced(mockAppJson, options);
|
||||||
|
const result = appReduced.getAbsolutePath();
|
||||||
|
|
||||||
|
expect(result).toBe("~/admin");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("should normalize paths correctly", () => {
|
||||||
|
const options: BkndAdminProps["config"] = {
|
||||||
|
basepath: "//admin//",
|
||||||
|
logo_return_path: "/",
|
||||||
|
};
|
||||||
|
|
||||||
|
appReduced = new AppReduced(mockAppJson, options);
|
||||||
|
const result = appReduced.getAbsolutePath("//dashboard//");
|
||||||
|
|
||||||
|
expect(result).toBe("~/admin/dashboard");
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("options getter", () => {
|
||||||
|
it("should return merged options with defaults", () => {
|
||||||
|
const customOptions: BkndAdminProps["config"] = {
|
||||||
|
basepath: "/custom-admin",
|
||||||
|
logo_return_path: "/custom-home",
|
||||||
|
};
|
||||||
|
|
||||||
|
appReduced = new AppReduced(mockAppJson, customOptions);
|
||||||
|
const options = appReduced.options;
|
||||||
|
|
||||||
|
expect(options).toEqual({
|
||||||
|
logo_return_path: "/custom-home",
|
||||||
|
basepath: "/custom-admin",
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it("should use default logo_return_path when not provided", () => {
|
||||||
|
const customOptions: BkndAdminProps["config"] = {
|
||||||
|
basepath: "/admin",
|
||||||
|
};
|
||||||
|
|
||||||
|
appReduced = new AppReduced(mockAppJson, customOptions);
|
||||||
|
const options = appReduced.options;
|
||||||
|
|
||||||
|
expect(options.logo_return_path).toBe("/");
|
||||||
|
expect(options.basepath).toBe("/admin");
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("path normalization behavior", () => {
|
||||||
|
it("should normalize duplicate slashes in settings path", () => {
|
||||||
|
const options: BkndAdminProps["config"] = {
|
||||||
|
basepath: "/admin",
|
||||||
|
logo_return_path: "/",
|
||||||
|
};
|
||||||
|
|
||||||
|
appReduced = new AppReduced(mockAppJson, options);
|
||||||
|
const result = appReduced.getSettingsPath(["//nested//path//"]);
|
||||||
|
|
||||||
|
expect(result).toBe("~/admin/settings/nested/path");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("should handle root path normalization", () => {
|
||||||
|
const options: BkndAdminProps["config"] = {
|
||||||
|
basepath: "/",
|
||||||
|
logo_return_path: "/",
|
||||||
|
};
|
||||||
|
|
||||||
|
appReduced = new AppReduced(mockAppJson, options);
|
||||||
|
const result = appReduced.getAbsolutePath();
|
||||||
|
|
||||||
|
// The normalizeAdminPath function removes trailing slashes except for root "/"
|
||||||
|
// When basepath is "/", the result is "~/" which becomes "~" after normalization
|
||||||
|
expect(result).toBe("~");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("should preserve entity paths ending with slash", () => {
|
||||||
|
const options: BkndAdminProps["config"] = {
|
||||||
|
basepath: "/admin",
|
||||||
|
logo_return_path: "/",
|
||||||
|
};
|
||||||
|
|
||||||
|
appReduced = new AppReduced(mockAppJson, options);
|
||||||
|
const result = appReduced.getAbsolutePath("entity/");
|
||||||
|
|
||||||
|
expect(result).toBe("~/admin/entity");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("should remove trailing slashes from non-entity paths", () => {
|
||||||
|
const options: BkndAdminProps["config"] = {
|
||||||
|
basepath: "/admin",
|
||||||
|
logo_return_path: "/",
|
||||||
|
};
|
||||||
|
|
||||||
|
appReduced = new AppReduced(mockAppJson, options);
|
||||||
|
const result = appReduced.getAbsolutePath("dashboard/");
|
||||||
|
|
||||||
|
expect(result).toBe("~/admin/dashboard");
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("withBasePath - double slash fix (admin_basepath with trailing slash)", () => {
|
||||||
|
it("should not produce double slashes when admin_basepath has trailing slash", () => {
|
||||||
|
const options: BkndAdminProps["config"] = {
|
||||||
|
basepath: "/admin",
|
||||||
|
logo_return_path: "/",
|
||||||
|
};
|
||||||
|
|
||||||
|
appReduced = new AppReduced(mockAppJson, options);
|
||||||
|
const result = appReduced.withBasePath("/data");
|
||||||
|
|
||||||
|
expect(result).toBe("/admin/data");
|
||||||
|
expect(result).not.toContain("//");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("should work correctly when admin_basepath has no trailing slash", () => {
|
||||||
|
const options: BkndAdminProps["config"] = {
|
||||||
|
basepath: "/admin",
|
||||||
|
logo_return_path: "/",
|
||||||
|
};
|
||||||
|
|
||||||
|
appReduced = new AppReduced(mockAppJson, options);
|
||||||
|
const result = appReduced.withBasePath("/data");
|
||||||
|
|
||||||
|
expect(result).toBe("/admin/data");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("should handle absolute paths with admin_basepath trailing slash", () => {
|
||||||
|
const options: BkndAdminProps["config"] = {
|
||||||
|
basepath: "/admin",
|
||||||
|
logo_return_path: "/",
|
||||||
|
};
|
||||||
|
|
||||||
|
appReduced = new AppReduced(mockAppJson, options);
|
||||||
|
const result = appReduced.getAbsolutePath("data");
|
||||||
|
|
||||||
|
expect(result).toBe("~/admin/data");
|
||||||
|
expect(result).not.toContain("//");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("should handle settings path with admin_basepath trailing slash", () => {
|
||||||
|
const options: BkndAdminProps["config"] = {
|
||||||
|
basepath: "/admin",
|
||||||
|
logo_return_path: "/",
|
||||||
|
};
|
||||||
|
|
||||||
|
appReduced = new AppReduced(mockAppJson, options);
|
||||||
|
const result = appReduced.getSettingsPath(["general"]);
|
||||||
|
|
||||||
|
expect(result).toBe("~/admin/settings/general");
|
||||||
|
expect(result).not.toContain("//");
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("edge cases", () => {
|
||||||
|
it("should handle undefined basepath", () => {
|
||||||
|
const options: BkndAdminProps["config"] = {
|
||||||
|
logo_return_path: "/",
|
||||||
|
};
|
||||||
|
|
||||||
|
appReduced = new AppReduced(mockAppJson, options);
|
||||||
|
const result = appReduced.getSettingsPath();
|
||||||
|
|
||||||
|
// When basepath is undefined, it defaults to empty string
|
||||||
|
expect(result).toBe("~/settings");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("should handle null path segments", () => {
|
||||||
|
const options: BkndAdminProps["config"] = {
|
||||||
|
basepath: "/admin",
|
||||||
|
logo_return_path: "/",
|
||||||
|
};
|
||||||
|
|
||||||
|
appReduced = new AppReduced(mockAppJson, options);
|
||||||
|
const result = appReduced.getSettingsPath(["", "valid", ""]);
|
||||||
|
|
||||||
|
expect(result).toBe("~/admin/settings/valid");
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -1,30 +1,10 @@
|
|||||||
import pkg from "./package.json" with { type: "json" };
|
import pkg from "./package.json" with { type: "json" };
|
||||||
import c from "picocolors";
|
import c from "picocolors";
|
||||||
import { formatNumber } from "bknd/utils";
|
import { formatNumber } from "bknd/utils";
|
||||||
import * as esbuild from "esbuild";
|
|
||||||
|
|
||||||
const deps = Object.keys(pkg.dependencies);
|
const deps = Object.keys(pkg.dependencies);
|
||||||
const external = ["jsonv-ts/*", "wrangler", "bknd", "bknd/*", ...deps];
|
const external = ["jsonv-ts/*", "wrangler", "bknd", "bknd/*", ...deps];
|
||||||
|
|
||||||
if (process.env.DEBUG) {
|
|
||||||
const result = await esbuild.build({
|
|
||||||
entryPoints: ["./src/cli/index.ts"],
|
|
||||||
outdir: "./dist/cli",
|
|
||||||
platform: "node",
|
|
||||||
minify: true,
|
|
||||||
format: "esm",
|
|
||||||
metafile: true,
|
|
||||||
bundle: true,
|
|
||||||
external,
|
|
||||||
define: {
|
|
||||||
__isDev: "0",
|
|
||||||
__version: JSON.stringify(pkg.version),
|
|
||||||
},
|
|
||||||
});
|
|
||||||
await Bun.write("./dist/cli/metafile-esm.json", JSON.stringify(result.metafile, null, 2));
|
|
||||||
process.exit(0);
|
|
||||||
}
|
|
||||||
|
|
||||||
const result = await Bun.build({
|
const result = await Bun.build({
|
||||||
entrypoints: ["./src/cli/index.ts"],
|
entrypoints: ["./src/cli/index.ts"],
|
||||||
target: "node",
|
target: "node",
|
||||||
|
|||||||
+353
-245
@@ -2,6 +2,8 @@ import { $ } from "bun";
|
|||||||
import * as tsup from "tsup";
|
import * as tsup from "tsup";
|
||||||
import pkg from "./package.json" with { type: "json" };
|
import pkg from "./package.json" with { type: "json" };
|
||||||
import c from "picocolors";
|
import c from "picocolors";
|
||||||
|
import { watch as fsWatch, readdirSync, rmSync } from "node:fs";
|
||||||
|
import { join } from "node:path";
|
||||||
|
|
||||||
const args = process.argv.slice(2);
|
const args = process.argv.slice(2);
|
||||||
const watch = args.includes("--watch");
|
const watch = args.includes("--watch");
|
||||||
@@ -12,162 +14,178 @@ const clean = args.includes("--clean");
|
|||||||
|
|
||||||
// silence tsup
|
// silence tsup
|
||||||
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) {
|
||||||
console.info("Cleaning dist (w/o static)");
|
console.info("Cleaning dist (w/o static)");
|
||||||
await $`find dist -mindepth 1 ! -path "dist/static/*" ! -path "dist/static" -exec rm -rf {} +`;
|
// Cross-platform clean: remove all files/folders in dist except static
|
||||||
|
const distPath = join(import.meta.dir, "dist");
|
||||||
|
try {
|
||||||
|
const entries = readdirSync(distPath);
|
||||||
|
for (const entry of entries) {
|
||||||
|
if (entry === "static") continue;
|
||||||
|
const entryPath = join(distPath, entry);
|
||||||
|
rmSync(entryPath, { recursive: true, force: true });
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
// dist may not exist yet, ignore
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
let types_running = false;
|
let types_running = false;
|
||||||
function buildTypes() {
|
function buildTypes() {
|
||||||
if (types_running || !types) return;
|
if (types_running || !types) return;
|
||||||
types_running = true;
|
types_running = true;
|
||||||
|
|
||||||
Bun.spawn(["bun", "build:types"], {
|
Bun.spawn(["bun", "build:types"], {
|
||||||
stdout: "inherit",
|
stdout: "inherit",
|
||||||
onExit: () => {
|
onExit: () => {
|
||||||
oldConsole.log(c.cyan("[Types]"), c.green("built"));
|
oldConsole.log(c.cyan("[Types]"), c.green("built"));
|
||||||
Bun.spawn(["bun", "tsc-alias"], {
|
Bun.spawn(["bun", "tsc-alias"], {
|
||||||
stdout: "inherit",
|
stdout: "inherit",
|
||||||
onExit: () => {
|
onExit: () => {
|
||||||
oldConsole.log(c.cyan("[Types]"), c.green("aliased"));
|
oldConsole.log(c.cyan("[Types]"), c.green("aliased"));
|
||||||
types_running = false;
|
types_running = false;
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
if (types && !watch) {
|
if (types && !watch) {
|
||||||
buildTypes();
|
buildTypes();
|
||||||
}
|
}
|
||||||
|
|
||||||
let watcher_timeout: any;
|
let watcher_timeout: any;
|
||||||
function delayTypes() {
|
function delayTypes() {
|
||||||
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(buildTypes, 1000);
|
||||||
}
|
}
|
||||||
|
|
||||||
const dependencies = Object.keys(pkg.dependencies);
|
const dependencies = Object.keys(pkg.dependencies);
|
||||||
|
|
||||||
// collection of always-external packages
|
// collection of always-external packages
|
||||||
const external = [
|
const external = [
|
||||||
...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 tsup.build({
|
||||||
minify,
|
minify,
|
||||||
sourcemap,
|
sourcemap,
|
||||||
watch,
|
// don't use tsup's broken watch, we'll handle it ourselves
|
||||||
define,
|
watch: false,
|
||||||
entry: [
|
define,
|
||||||
"src/index.ts",
|
entry: [
|
||||||
"src/core/utils/index.ts",
|
"src/index.ts",
|
||||||
"src/plugins/index.ts",
|
"src/core/utils/index.ts",
|
||||||
"src/modes/index.ts",
|
"src/plugins/index.ts",
|
||||||
],
|
"src/modes/index.ts",
|
||||||
outDir: "dist",
|
],
|
||||||
external: [...external],
|
outDir: "dist",
|
||||||
metafile: true,
|
external: [...external],
|
||||||
target: "esnext",
|
metafile: true,
|
||||||
platform: "browser",
|
target: "esnext",
|
||||||
format: ["esm"],
|
platform: "browser",
|
||||||
splitting: false,
|
removeNodeProtocol: false,
|
||||||
loader: {
|
format: ["esm"],
|
||||||
".svg": "dataurl",
|
splitting: false,
|
||||||
},
|
loader: {
|
||||||
onSuccess: async () => {
|
".svg": "dataurl",
|
||||||
delayTypes();
|
},
|
||||||
oldConsole.log(c.cyan("[API]"), c.green("built"));
|
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(path, '"use client";\n' + bundle.replaceAll("ui/client", "bknd/client"));
|
await Bun.write(
|
||||||
|
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,
|
watch: false,
|
||||||
define,
|
define,
|
||||||
external: [
|
external: [
|
||||||
...external,
|
...external,
|
||||||
"react",
|
"react",
|
||||||
"react-dom",
|
"react-dom",
|
||||||
"react/jsx-runtime",
|
"react/jsx-runtime",
|
||||||
"react/jsx-dev-runtime",
|
"react/jsx-dev-runtime",
|
||||||
"use-sync-external-store",
|
"use-sync-external-store",
|
||||||
/codemirror/,
|
/codemirror/,
|
||||||
"@xyflow/react",
|
"@xyflow/react",
|
||||||
"@mantine/core",
|
"@mantine/core",
|
||||||
],
|
],
|
||||||
metafile: true,
|
metafile: true,
|
||||||
platform: "browser",
|
platform: "browser",
|
||||||
format: ["esm"],
|
format: ["esm"],
|
||||||
splitting: false,
|
splitting: false,
|
||||||
bundle: true,
|
bundle: true,
|
||||||
treeshake: true,
|
treeshake: true,
|
||||||
loader: {
|
loader: {
|
||||||
".svg": "dataurl",
|
".svg": "dataurl",
|
||||||
},
|
},
|
||||||
esbuildOptions: (options) => {
|
esbuildOptions: (options) => {
|
||||||
options.logLevel = "silent";
|
options.logLevel = "silent";
|
||||||
},
|
},
|
||||||
} satisfies tsup.Options;
|
} satisfies tsup.Options;
|
||||||
|
|
||||||
await tsup.build({
|
await tsup.build({
|
||||||
...base,
|
...base,
|
||||||
entry: ["src/ui/index.ts", "src/ui/main.css", "src/ui/styles.css"],
|
entry: ["src/ui/index.ts", "src/ui/main.css", "src/ui/styles.css"],
|
||||||
outDir: "dist/ui",
|
outDir: "dist/ui",
|
||||||
onSuccess: async () => {
|
onSuccess: async () => {
|
||||||
await rewriteClient("./dist/ui/index.js");
|
await rewriteClient("./dist/ui/index.js");
|
||||||
delayTypes();
|
delayTypes();
|
||||||
oldConsole.log(c.cyan("[UI]"), c.green("built"));
|
oldConsole.log(c.cyan("[UI]"), c.green("built"));
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
await tsup.build({
|
await tsup.build({
|
||||||
...base,
|
...base,
|
||||||
entry: ["src/ui/client/index.ts"],
|
entry: ["src/ui/client/index.ts"],
|
||||||
outDir: "dist/ui/client",
|
outDir: "dist/ui/client",
|
||||||
onSuccess: async () => {
|
onSuccess: async () => {
|
||||||
await rewriteClient("./dist/ui/client/index.js");
|
await rewriteClient("./dist/ui/client/index.js");
|
||||||
delayTypes();
|
delayTypes();
|
||||||
oldConsole.log(c.cyan("[UI]"), "Client", c.green("built"));
|
oldConsole.log(c.cyan("[UI]"), "Client", c.green("built"));
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -176,153 +194,243 @@ 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 tsup.build({
|
||||||
minify,
|
minify,
|
||||||
sourcemap,
|
sourcemap,
|
||||||
watch,
|
watch: false,
|
||||||
define,
|
define,
|
||||||
entry: ["src/ui/elements/index.ts"],
|
entry: ["src/ui/elements/index.ts"],
|
||||||
outDir: "dist/ui/elements",
|
outDir: "dist/ui/elements",
|
||||||
external: [
|
external: [
|
||||||
"ui/client",
|
"ui/client",
|
||||||
"react",
|
"bknd",
|
||||||
"react-dom",
|
/^bknd\/.*/,
|
||||||
"react/jsx-runtime",
|
"wouter",
|
||||||
"react/jsx-dev-runtime",
|
"react",
|
||||||
"use-sync-external-store",
|
"react-dom",
|
||||||
],
|
"react/jsx-runtime",
|
||||||
metafile: true,
|
"react/jsx-dev-runtime",
|
||||||
platform: "browser",
|
"use-sync-external-store",
|
||||||
format: ["esm"],
|
],
|
||||||
splitting: false,
|
metafile: true,
|
||||||
bundle: true,
|
platform: "browser",
|
||||||
treeshake: true,
|
format: ["esm"],
|
||||||
loader: {
|
splitting: false,
|
||||||
".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",
|
esbuildOptions: (options) => {
|
||||||
};
|
options.alias = {
|
||||||
},
|
// not important for elements, mock to reduce bundle
|
||||||
onSuccess: async () => {
|
"tailwind-merge": "./src/ui/elements/mocks/tailwind-merge.ts",
|
||||||
await rewriteClient("./dist/ui/elements/index.js");
|
};
|
||||||
delayTypes();
|
},
|
||||||
oldConsole.log(c.cyan("[UI]"), "Elements", c.green("built"));
|
onSuccess: async () => {
|
||||||
},
|
await rewriteClient("./dist/ui/elements/index.js");
|
||||||
});
|
delayTypes();
|
||||||
|
oldConsole.log(c.cyan("[UI]"), "Elements", c.green("built"));
|
||||||
|
},
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Building adapters
|
* Building adapters
|
||||||
*/
|
*/
|
||||||
function baseConfig(adapter: string, overrides: Partial<tsup.Options> = {}): tsup.Options {
|
function baseConfig(
|
||||||
return {
|
adapter: string,
|
||||||
minify,
|
overrides: Partial<tsup.Options> = {},
|
||||||
sourcemap,
|
): tsup.Options {
|
||||||
watch,
|
return {
|
||||||
entry: [`src/adapter/${adapter}/index.ts`],
|
minify,
|
||||||
format: ["esm"],
|
sourcemap,
|
||||||
platform: "neutral",
|
watch: false,
|
||||||
outDir: `dist/adapter/${adapter}`,
|
entry: [`src/adapter/${adapter}/index.ts`],
|
||||||
metafile: true,
|
format: ["esm"],
|
||||||
splitting: false,
|
platform: "neutral",
|
||||||
onSuccess: async () => {
|
outDir: `dist/adapter/${adapter}`,
|
||||||
delayTypes();
|
metafile: true,
|
||||||
oldConsole.log(c.cyan("[Adapter]"), adapter || "base", c.green("built"));
|
splitting: false,
|
||||||
},
|
removeNodeProtocol: false,
|
||||||
...overrides,
|
onSuccess: async () => {
|
||||||
define: {
|
delayTypes();
|
||||||
...define,
|
oldConsole.log(c.cyan("[Adapter]"), adapter || "base", c.green("built"));
|
||||||
...overrides.define,
|
},
|
||||||
},
|
...overrides,
|
||||||
external: [
|
define: {
|
||||||
/^cloudflare*/,
|
...define,
|
||||||
/^@?hono.*?/,
|
...overrides.define,
|
||||||
/^(bknd|react|next|node).*?/,
|
},
|
||||||
/.*\.(html)$/,
|
external: [
|
||||||
...external,
|
/^cloudflare*/,
|
||||||
...(Array.isArray(overrides.external) ? overrides.external : []),
|
/^@?hono.*?/,
|
||||||
],
|
/^(bknd|react|next|node).*?/,
|
||||||
};
|
/.*\.(html)$/,
|
||||||
|
...external,
|
||||||
|
...(Array.isArray(overrides.external) ? overrides.external : []),
|
||||||
|
],
|
||||||
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
async function buildAdapters() {
|
async function buildAdapters() {
|
||||||
await Promise.all([
|
await Promise.all([
|
||||||
// base adapter handles
|
// base adapter handles
|
||||||
tsup.build({
|
tsup.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,
|
||||||
}),
|
}),
|
||||||
|
|
||||||
// specific adatpers
|
// specific adatpers
|
||||||
tsup.build(baseConfig("react-router")),
|
tsup.build(baseConfig("react-router")),
|
||||||
tsup.build(
|
tsup.build(
|
||||||
baseConfig("bun", {
|
baseConfig("browser", {
|
||||||
external: [/^bun\:.*/],
|
external: [/^sqlocal\/?.*?/, "wouter"],
|
||||||
}),
|
|
||||||
),
|
|
||||||
tsup.build(baseConfig("astro")),
|
|
||||||
tsup.build(baseConfig("aws")),
|
|
||||||
tsup.build(
|
|
||||||
baseConfig("cloudflare", {
|
|
||||||
external: ["wrangler", "node:process"],
|
|
||||||
}),
|
|
||||||
),
|
|
||||||
tsup.build(
|
|
||||||
baseConfig("cloudflare/proxy", {
|
|
||||||
target: "esnext",
|
|
||||||
entry: ["src/adapter/cloudflare/proxy.ts"],
|
|
||||||
outDir: "dist/adapter/cloudflare",
|
|
||||||
metafile: false,
|
|
||||||
external: [/bknd/, "wrangler", "node:process"],
|
|
||||||
}),
|
|
||||||
),
|
|
||||||
|
|
||||||
tsup.build({
|
|
||||||
...baseConfig("vite"),
|
|
||||||
platform: "node",
|
|
||||||
}),
|
}),
|
||||||
|
),
|
||||||
tsup.build({
|
tsup.build(
|
||||||
...baseConfig("nextjs"),
|
baseConfig("bun", {
|
||||||
platform: "node",
|
external: [/^bun\:.*/],
|
||||||
}),
|
}),
|
||||||
|
),
|
||||||
tsup.build({
|
tsup.build(baseConfig("astro")),
|
||||||
...baseConfig("node"),
|
tsup.build(baseConfig("aws")),
|
||||||
platform: "node",
|
tsup.build(
|
||||||
|
baseConfig("cloudflare", {
|
||||||
|
external: ["wrangler", "node:process"],
|
||||||
}),
|
}),
|
||||||
|
),
|
||||||
tsup.build({
|
tsup.build(
|
||||||
...baseConfig("sqlite/edge"),
|
baseConfig("cloudflare/proxy", {
|
||||||
entry: ["src/adapter/sqlite/edge.ts"],
|
target: "esnext",
|
||||||
outDir: "dist/adapter/sqlite",
|
entry: ["src/adapter/cloudflare/proxy.ts"],
|
||||||
metafile: false,
|
outDir: "dist/adapter/cloudflare",
|
||||||
|
metafile: false,
|
||||||
|
external: [/bknd/, "wrangler", "node:process"],
|
||||||
}),
|
}),
|
||||||
|
),
|
||||||
|
|
||||||
tsup.build({
|
tsup.build({
|
||||||
...baseConfig("sqlite/node"),
|
...baseConfig("vite"),
|
||||||
entry: ["src/adapter/sqlite/node.ts"],
|
platform: "node",
|
||||||
outDir: "dist/adapter/sqlite",
|
}),
|
||||||
platform: "node",
|
|
||||||
metafile: false,
|
|
||||||
}),
|
|
||||||
|
|
||||||
tsup.build({
|
tsup.build({
|
||||||
...baseConfig("sqlite/bun"),
|
...baseConfig("nextjs"),
|
||||||
entry: ["src/adapter/sqlite/bun.ts"],
|
platform: "node",
|
||||||
outDir: "dist/adapter/sqlite",
|
}),
|
||||||
metafile: false,
|
|
||||||
external: [/^bun\:.*/],
|
tsup.build({
|
||||||
}),
|
...baseConfig("tanstack-start"),
|
||||||
]);
|
platform: "node",
|
||||||
|
}),
|
||||||
|
|
||||||
|
tsup.build({
|
||||||
|
...baseConfig("universal"),
|
||||||
|
platform: "neutral",
|
||||||
|
}),
|
||||||
|
|
||||||
|
tsup.build({
|
||||||
|
...baseConfig("sveltekit"),
|
||||||
|
platform: "node",
|
||||||
|
}),
|
||||||
|
|
||||||
|
tsup.build({
|
||||||
|
...baseConfig("nuxt"),
|
||||||
|
platform: "node",
|
||||||
|
}),
|
||||||
|
|
||||||
|
tsup.build({
|
||||||
|
...baseConfig("node"),
|
||||||
|
platform: "node",
|
||||||
|
}),
|
||||||
|
|
||||||
|
tsup.build({
|
||||||
|
...baseConfig("sqlite/edge"),
|
||||||
|
entry: ["src/adapter/sqlite/edge.ts"],
|
||||||
|
outDir: "dist/adapter/sqlite",
|
||||||
|
metafile: false,
|
||||||
|
}),
|
||||||
|
|
||||||
|
tsup.build({
|
||||||
|
...baseConfig("sqlite/node"),
|
||||||
|
entry: ["src/adapter/sqlite/node.ts"],
|
||||||
|
outDir: "dist/adapter/sqlite",
|
||||||
|
platform: "node",
|
||||||
|
metafile: false,
|
||||||
|
}),
|
||||||
|
|
||||||
|
tsup.build({
|
||||||
|
...baseConfig("sqlite/bun"),
|
||||||
|
entry: ["src/adapter/sqlite/bun.ts"],
|
||||||
|
outDir: "dist/adapter/sqlite",
|
||||||
|
metafile: false,
|
||||||
|
external: [/^bun\:.*/],
|
||||||
|
}),
|
||||||
|
|
||||||
|
]);
|
||||||
}
|
}
|
||||||
|
|
||||||
await Promise.all([buildApi(), buildUi(), buildUiElements(), buildAdapters()]);
|
async function buildAll() {
|
||||||
|
await Promise.all([
|
||||||
|
buildApi(),
|
||||||
|
buildUi(),
|
||||||
|
buildUiElements(),
|
||||||
|
buildAdapters(),
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
// initial build
|
||||||
|
await buildAll();
|
||||||
|
|
||||||
|
// custom watcher since tsup's watch is broken in 8.3.5+
|
||||||
|
if (watch) {
|
||||||
|
oldConsole.log(c.cyan("[Watch]"), "watching for changes in src/...");
|
||||||
|
|
||||||
|
let debounceTimer: ReturnType<typeof setTimeout> | null = null;
|
||||||
|
let isBuilding = false;
|
||||||
|
|
||||||
|
const rebuild = async () => {
|
||||||
|
if (isBuilding) return;
|
||||||
|
isBuilding = true;
|
||||||
|
oldConsole.log(c.cyan("[Watch]"), "rebuilding...");
|
||||||
|
try {
|
||||||
|
await buildAll();
|
||||||
|
oldConsole.log(c.cyan("[Watch]"), c.green("done"));
|
||||||
|
} catch (e) {
|
||||||
|
oldConsole.warn(c.cyan("[Watch]"), c.red("build failed"), e);
|
||||||
|
}
|
||||||
|
isBuilding = false;
|
||||||
|
};
|
||||||
|
|
||||||
|
const debouncedRebuild = () => {
|
||||||
|
if (debounceTimer) clearTimeout(debounceTimer);
|
||||||
|
debounceTimer = setTimeout(rebuild, 100);
|
||||||
|
};
|
||||||
|
|
||||||
|
// watch src directory recursively
|
||||||
|
fsWatch(
|
||||||
|
join(import.meta.dir, "src"),
|
||||||
|
{ recursive: true },
|
||||||
|
(event, filename) => {
|
||||||
|
if (!filename) return;
|
||||||
|
// ignore non-source files
|
||||||
|
if (
|
||||||
|
!filename.endsWith(".ts") &&
|
||||||
|
!filename.endsWith(".tsx") &&
|
||||||
|
!filename.endsWith(".css")
|
||||||
|
)
|
||||||
|
return;
|
||||||
|
oldConsole.log(c.cyan("[Watch]"), c.dim(`${event}: ${filename}`));
|
||||||
|
debouncedRebuild();
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
// keep process alive
|
||||||
|
await new Promise(() => {});
|
||||||
|
}
|
||||||
|
|||||||
@@ -1,6 +0,0 @@
|
|||||||
[install]
|
|
||||||
#registry = "http://localhost:4873"
|
|
||||||
|
|
||||||
[test]
|
|
||||||
coverageSkipTestFiles = true
|
|
||||||
console.depth = 10
|
|
||||||
+3
-2
@@ -3,10 +3,11 @@ import path from "node:path";
|
|||||||
import c from "picocolors";
|
import c from "picocolors";
|
||||||
|
|
||||||
const basePath = new URL(import.meta.resolve("../../")).pathname.slice(0, -1);
|
const basePath = new URL(import.meta.resolve("../../")).pathname.slice(0, -1);
|
||||||
|
type RunOptions = Omit<Bun.SpawnOptions.SpawnOptions<"ignore", "pipe", "pipe">, "stdout" | "stderr">;
|
||||||
|
|
||||||
async function run(
|
async function run(
|
||||||
cmd: string[] | string,
|
cmd: string[] | string,
|
||||||
opts: Bun.SpawnOptions.OptionsObject & {},
|
opts: RunOptions,
|
||||||
onChunk: (chunk: string, resolve: (data: any) => void, reject: (err: Error) => void) => void,
|
onChunk: (chunk: string, resolve: (data: any) => void, reject: (err: Error) => void) => void,
|
||||||
): Promise<{ proc: Bun.Subprocess; data: any }> {
|
): Promise<{ proc: Bun.Subprocess; data: any }> {
|
||||||
return new Promise((resolve, reject) => {
|
return new Promise((resolve, reject) => {
|
||||||
@@ -17,7 +18,7 @@ async function run(
|
|||||||
});
|
});
|
||||||
|
|
||||||
// Read from stdout
|
// Read from stdout
|
||||||
const reader = (proc.stdout as ReadableStream).getReader();
|
const reader = proc.stdout.getReader();
|
||||||
const decoder = new TextDecoder();
|
const decoder = new TextDecoder();
|
||||||
|
|
||||||
// Function to read chunks
|
// Function to read chunks
|
||||||
|
|||||||
+42
-33
@@ -1,44 +1,53 @@
|
|||||||
const adapter = process.env.TEST_ADAPTER;
|
const adapter = process.env.TEST_ADAPTER;
|
||||||
|
|
||||||
const default_config = {
|
const default_config = {
|
||||||
media_adapter: "local",
|
media_adapter: "local",
|
||||||
base_path: "",
|
base_path: "",
|
||||||
} as const;
|
} as const;
|
||||||
|
|
||||||
const configs = {
|
const configs = {
|
||||||
cloudflare: {
|
cloudflare: {
|
||||||
media_adapter: "r2",
|
media_adapter: "r2",
|
||||||
},
|
},
|
||||||
"react-router": {
|
"react-router": {
|
||||||
base_path: "/admin",
|
base_path: "/admin",
|
||||||
},
|
},
|
||||||
nextjs: {
|
nextjs: {
|
||||||
base_path: "/admin",
|
base_path: "/admin",
|
||||||
},
|
},
|
||||||
astro: {
|
meta: {
|
||||||
base_path: "/admin",
|
base_path: "/admin",
|
||||||
},
|
},
|
||||||
node: {
|
nuxt: {
|
||||||
base_path: "",
|
base_path: "/admin",
|
||||||
},
|
},
|
||||||
bun: {
|
astro: {
|
||||||
base_path: "",
|
base_path: "/admin",
|
||||||
},
|
},
|
||||||
|
node: {
|
||||||
|
base_path: "",
|
||||||
|
},
|
||||||
|
bun: {
|
||||||
|
base_path: "",
|
||||||
|
},
|
||||||
|
"tanstack-start": {
|
||||||
|
base_path: "/admin",
|
||||||
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
export function getAdapterConfig(): typeof default_config {
|
export function getAdapterConfig(): typeof default_config {
|
||||||
if (adapter) {
|
if (adapter) {
|
||||||
if (!configs[adapter]) {
|
if (!configs[adapter]) {
|
||||||
console.warn(
|
console.warn(
|
||||||
`Adapter "${adapter}" not found. Available adapters: ${Object.keys(configs).join(", ")}`,
|
`Adapter "${adapter}" not found. Available adapters: ${Object.keys(configs).join(", ")}`,
|
||||||
);
|
);
|
||||||
} else {
|
} else {
|
||||||
return {
|
return {
|
||||||
...default_config,
|
...default_config,
|
||||||
...configs[adapter],
|
...configs[adapter],
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return default_config;
|
return default_config;
|
||||||
}
|
}
|
||||||
|
|||||||
+93
-51
@@ -3,7 +3,7 @@
|
|||||||
"type": "module",
|
"type": "module",
|
||||||
"sideEffects": false,
|
"sideEffects": false,
|
||||||
"bin": "./dist/cli/index.js",
|
"bin": "./dist/cli/index.js",
|
||||||
"version": "0.19.0",
|
"version": "0.21.0-rc.1",
|
||||||
"description": "Lightweight Firebase/Supabase alternative built to run anywhere — incl. Next.js, React Router, Astro, Cloudflare, Bun, Node, AWS Lambda & more.",
|
"description": "Lightweight Firebase/Supabase alternative built to run anywhere — incl. Next.js, React Router, Astro, Cloudflare, Bun, Node, AWS Lambda & more.",
|
||||||
"homepage": "https://bknd.io",
|
"homepage": "https://bknd.io",
|
||||||
"repository": {
|
"repository": {
|
||||||
@@ -13,7 +13,7 @@
|
|||||||
"bugs": {
|
"bugs": {
|
||||||
"url": "https://github.com/bknd-io/bknd/issues"
|
"url": "https://github.com/bknd-io/bknd/issues"
|
||||||
},
|
},
|
||||||
"packageManager": "bun@1.2.22",
|
"packageManager": "bun@1.3.3",
|
||||||
"engines": {
|
"engines": {
|
||||||
"node": ">=22.13"
|
"node": ">=22.13"
|
||||||
},
|
},
|
||||||
@@ -46,96 +46,106 @@
|
|||||||
"test:e2e:report": "VITE_DB_URL=:memory: playwright show-report",
|
"test:e2e:report": "VITE_DB_URL=:memory: playwright show-report",
|
||||||
"docs:build-assets": "bun internal/docs.build-assets.ts"
|
"docs:build-assets": "bun internal/docs.build-assets.ts"
|
||||||
},
|
},
|
||||||
"license": "FSL-1.1-MIT",
|
"license": "Apache-2.0",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@cfworker/json-schema": "^4.1.1",
|
"@cfworker/json-schema": "^4.1.1",
|
||||||
"@codemirror/lang-html": "^6.4.9",
|
"@codemirror/lang-html": "^6.4.11",
|
||||||
"@codemirror/lang-json": "^6.0.1",
|
"@codemirror/lang-json": "^6.0.2",
|
||||||
"@hello-pangea/dnd": "^18.0.1",
|
"@hello-pangea/dnd": "^18.0.1",
|
||||||
"@hono/swagger-ui": "^0.5.1",
|
"@hono/swagger-ui": "^0.5.2",
|
||||||
"@mantine/core": "^7.17.1",
|
"@mantine/core": "^7.17.1",
|
||||||
"@mantine/hooks": "^7.17.1",
|
"@mantine/hooks": "^7.17.1",
|
||||||
"@tanstack/react-form": "^1.0.5",
|
"@tanstack/react-form": "^1.0.5",
|
||||||
"@uiw/react-codemirror": "^4.23.10",
|
"@uiw/react-codemirror": "^4.25.2",
|
||||||
"@xyflow/react": "^12.4.4",
|
"@xyflow/react": "^12.9.2",
|
||||||
"aws4fetch": "^1.0.20",
|
"aws4fetch": "^1.0.20",
|
||||||
"bcryptjs": "^3.0.2",
|
"bcryptjs": "^3.0.3",
|
||||||
"dayjs": "^1.11.13",
|
"dayjs": "^1.11.20",
|
||||||
"fast-xml-parser": "^5.0.8",
|
"fast-xml-parser": "^5.3.1",
|
||||||
"hono": "4.8.3",
|
"hono": "4.10.4",
|
||||||
"json-schema-library": "10.0.0-rc7",
|
"json-schema-library": "10.0.0-rc7",
|
||||||
"json-schema-to-ts": "^3.1.1",
|
"json-schema-to-ts": "^3.1.1",
|
||||||
"jsonv-ts": "0.9.1",
|
"jsonv-ts": "^0.10.1",
|
||||||
"kysely": "0.27.6",
|
"kysely": "0.28.8",
|
||||||
"lodash-es": "^4.17.21",
|
"lodash-es": "^4.17.21",
|
||||||
"oauth4webapi": "^2.11.1",
|
"oauth4webapi": "^2.11.1",
|
||||||
"object-path-immutable": "^4.1.2",
|
"object-path-immutable": "^4.1.2",
|
||||||
"radix-ui": "^1.1.3",
|
|
||||||
"picocolors": "^1.1.1",
|
"picocolors": "^1.1.1",
|
||||||
"swr": "^2.3.3"
|
"radix-ui": "^1.1.3",
|
||||||
|
"swr": "^2.3.6",
|
||||||
|
"use-sync-external-store": "^1.6.0",
|
||||||
|
"zustand": "^4"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@aws-sdk/client-s3": "^3.758.0",
|
"@aws-sdk/client-s3": "^3.922.0",
|
||||||
"@bluwy/giget-core": "^0.1.2",
|
"@bluwy/giget-core": "^0.1.6",
|
||||||
"@clack/prompts": "^0.11.0",
|
"@clack/prompts": "^0.11.0",
|
||||||
"@cloudflare/vitest-pool-workers": "^0.9.3",
|
"@cloudflare/vitest-pool-workers": "^0.10.4",
|
||||||
"@cloudflare/workers-types": "^4.20250606.0",
|
"@cloudflare/workers-types": "^4.20251014.0",
|
||||||
"@dagrejs/dagre": "^1.1.4",
|
"@dagrejs/dagre": "^1.1.4",
|
||||||
"@hono/vite-dev-server": "^0.21.0",
|
"@hono/vite-dev-server": "^0.23.0",
|
||||||
"@hookform/resolvers": "^4.1.3",
|
"@hookform/resolvers": "^5.2.2",
|
||||||
"@libsql/client": "^0.15.9",
|
"@libsql/client": "^0.15.15",
|
||||||
"@mantine/modals": "^7.17.1",
|
"@mantine/modals": "^7.17.1",
|
||||||
"@mantine/notifications": "^7.17.1",
|
"@mantine/notifications": "^7.17.1",
|
||||||
"@playwright/test": "^1.51.1",
|
"@playwright/test": "^1.56.1",
|
||||||
"@rjsf/core": "5.22.2",
|
"@rjsf/core": "5.22.2",
|
||||||
|
"@rjsf/utils": "5.22.0",
|
||||||
"@standard-schema/spec": "^1.0.0",
|
"@standard-schema/spec": "^1.0.0",
|
||||||
"@tabler/icons-react": "3.18.0",
|
"@tabler/icons-react": "3.35.0",
|
||||||
"@tailwindcss/postcss": "^4.0.12",
|
"@tailwindcss/postcss": "^4.1.16",
|
||||||
"@tailwindcss/vite": "^4.0.12",
|
"@tailwindcss/vite": "^4.1.16",
|
||||||
|
"@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": "^22.13.10",
|
"@types/node": "^24.10.0",
|
||||||
|
"@types/pg": "^8.15.6",
|
||||||
"@types/react": "^19.0.10",
|
"@types/react": "^19.0.10",
|
||||||
"@types/react-dom": "^19.0.4",
|
"@types/react-dom": "^19.0.4",
|
||||||
"@vitejs/plugin-react": "^4.3.4",
|
"@vitejs/plugin-react": "^5.1.0",
|
||||||
"@vitest/coverage-v8": "^3.0.9",
|
"@vitest/coverage-v8": "3.0.9",
|
||||||
"autoprefixer": "^10.4.21",
|
"autoprefixer": "^10.4.21",
|
||||||
"clsx": "^2.1.1",
|
"clsx": "^2.1.1",
|
||||||
"dotenv": "^16.4.7",
|
"commander": "^14.0.2",
|
||||||
|
"dotenv": "^17.2.3",
|
||||||
"jotai": "^2.12.2",
|
"jotai": "^2.12.2",
|
||||||
"jsdom": "^26.0.0",
|
"jsdom": "^26.1.0",
|
||||||
"kysely-d1": "^0.3.0",
|
|
||||||
"kysely-generic-sqlite": "^1.2.1",
|
"kysely-generic-sqlite": "^1.2.1",
|
||||||
|
"kysely-postgres-js": "^2.0.0",
|
||||||
|
"libsql": "^0.5.22",
|
||||||
"libsql-stateless-easy": "^1.8.0",
|
"libsql-stateless-easy": "^1.8.0",
|
||||||
"open": "^10.1.0",
|
"miniflare": "^4.20251011.2",
|
||||||
|
"open": "^10.2.0",
|
||||||
"openapi-types": "^12.1.3",
|
"openapi-types": "^12.1.3",
|
||||||
|
"pg": "^8.16.3",
|
||||||
"postcss": "^8.5.3",
|
"postcss": "^8.5.3",
|
||||||
"postcss-preset-mantine": "^1.17.0",
|
"postcss-preset-mantine": "^1.18.0",
|
||||||
"postcss-simple-vars": "^7.0.1",
|
"postcss-simple-vars": "^7.0.1",
|
||||||
"posthog-js-lite": "^3.4.2",
|
"postgres": "^3.4.7",
|
||||||
|
"posthog-js-lite": "^3.6.0",
|
||||||
"react": "^19.0.0",
|
"react": "^19.0.0",
|
||||||
"react-dom": "^19.0.0",
|
"react-dom": "^19.0.0",
|
||||||
"react-hook-form": "^7.54.2",
|
"react-hook-form": "^7.66.0",
|
||||||
"react-icons": "5.2.1",
|
"react-icons": "5.5.0",
|
||||||
"react-json-view-lite": "^2.4.1",
|
"react-json-view-lite": "^2.5.0",
|
||||||
"sql-formatter": "^15.4.11",
|
"sql-formatter": "^15.6.10",
|
||||||
|
"sqlocal": "^0.16.0",
|
||||||
"tailwind-merge": "^3.0.2",
|
"tailwind-merge": "^3.0.2",
|
||||||
"tailwindcss": "^4.0.12",
|
"tailwindcss": "^4.1.16",
|
||||||
"tailwindcss-animate": "^1.0.7",
|
"tailwindcss-animate": "^1.0.7",
|
||||||
"tsc-alias": "^1.8.11",
|
"tsc-alias": "^1.8.16",
|
||||||
"tsup": "^8.4.0",
|
"tsup": "^8.5.0",
|
||||||
"tsx": "^4.19.3",
|
"tsx": "^4.20.6",
|
||||||
"uuid": "^11.1.0",
|
"uuid": "^13.0.0",
|
||||||
"vite": "^6.3.5",
|
"vite": "^7.1.12",
|
||||||
"vite-plugin-circular-dependency": "^0.5.0",
|
"vite-plugin-circular-dependency": "^0.5.0",
|
||||||
"vite-tsconfig-paths": "^5.1.4",
|
"vite-tsconfig-paths": "^5.1.4",
|
||||||
"vitest": "^3.0.9",
|
"vitest": "3.0.9",
|
||||||
"wouter": "^3.6.0",
|
"wouter": "^3.7.1",
|
||||||
"wrangler": "^4.37.1",
|
"wrangler": "^4.45.4"
|
||||||
"miniflare": "^4.20250913.0"
|
|
||||||
},
|
},
|
||||||
"optionalDependencies": {
|
"optionalDependencies": {
|
||||||
"@hono/node-server": "^1.14.3"
|
"@hono/node-server": "^1.19.6"
|
||||||
},
|
},
|
||||||
"peerDependencies": {
|
"peerDependencies": {
|
||||||
"react": ">=19",
|
"react": ">=19",
|
||||||
@@ -223,6 +233,16 @@
|
|||||||
"import": "./dist/adapter/nextjs/index.js",
|
"import": "./dist/adapter/nextjs/index.js",
|
||||||
"require": "./dist/adapter/nextjs/index.js"
|
"require": "./dist/adapter/nextjs/index.js"
|
||||||
},
|
},
|
||||||
|
"./adapter/universal": {
|
||||||
|
"types": "./dist/types/adapter/universal/index.d.ts",
|
||||||
|
"import": "./dist/adapter/universal/index.js",
|
||||||
|
"require": "./dist/adapter/universal/index.js"
|
||||||
|
},
|
||||||
|
"./adapter/nuxt": {
|
||||||
|
"types": "./dist/types/adapter/nuxt/index.d.ts",
|
||||||
|
"import": "./dist/adapter/nuxt/index.js",
|
||||||
|
"require": "./dist/adapter/nuxt/index.js"
|
||||||
|
},
|
||||||
"./adapter/react-router": {
|
"./adapter/react-router": {
|
||||||
"types": "./dist/types/adapter/react-router/index.d.ts",
|
"types": "./dist/types/adapter/react-router/index.d.ts",
|
||||||
"import": "./dist/adapter/react-router/index.js",
|
"import": "./dist/adapter/react-router/index.js",
|
||||||
@@ -243,11 +263,26 @@
|
|||||||
"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": {
|
||||||
|
"types": "./dist/types/adapter/sveltekit/index.d.ts",
|
||||||
|
"import": "./dist/adapter/sveltekit/index.js",
|
||||||
|
"require": "./dist/adapter/sveltekit/index.js"
|
||||||
|
},
|
||||||
"./adapter/aws": {
|
"./adapter/aws": {
|
||||||
"types": "./dist/types/adapter/aws/index.d.ts",
|
"types": "./dist/types/adapter/aws/index.d.ts",
|
||||||
"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": {
|
||||||
|
"types": "./dist/types/adapter/browser/index.d.ts",
|
||||||
|
"import": "./dist/adapter/browser/index.js",
|
||||||
|
"require": "./dist/adapter/browser/index.js"
|
||||||
|
},
|
||||||
|
"./adapter/tanstack-start": {
|
||||||
|
"types": "./dist/types/adapter/tanstack-start/index.d.ts",
|
||||||
|
"import": "./dist/adapter/tanstack-start/index.js",
|
||||||
|
"require": "./dist/adapter/tanstack-start/index.js"
|
||||||
|
},
|
||||||
"./dist/main.css": "./dist/ui/main.css",
|
"./dist/main.css": "./dist/ui/main.css",
|
||||||
"./dist/styles.css": "./dist/ui/styles.css",
|
"./dist/styles.css": "./dist/ui/styles.css",
|
||||||
"./dist/manifest.json": "./dist/static/.vite/manifest.json",
|
"./dist/manifest.json": "./dist/static/.vite/manifest.json",
|
||||||
@@ -262,9 +297,13 @@
|
|||||||
"adapter/cloudflare": ["./dist/types/adapter/cloudflare/index.d.ts"],
|
"adapter/cloudflare": ["./dist/types/adapter/cloudflare/index.d.ts"],
|
||||||
"adapter/vite": ["./dist/types/adapter/vite/index.d.ts"],
|
"adapter/vite": ["./dist/types/adapter/vite/index.d.ts"],
|
||||||
"adapter/nextjs": ["./dist/types/adapter/nextjs/index.d.ts"],
|
"adapter/nextjs": ["./dist/types/adapter/nextjs/index.d.ts"],
|
||||||
|
"adapter/universal": ["./dist/types/adapter/universal/index.d.ts"],
|
||||||
|
"adapter/nuxt": ["./dist/types/adapter/nuxt/index.d.ts"],
|
||||||
"adapter/react-router": ["./dist/types/adapter/react-router/index.d.ts"],
|
"adapter/react-router": ["./dist/types/adapter/react-router/index.d.ts"],
|
||||||
"adapter/bun": ["./dist/types/adapter/bun/index.d.ts"],
|
"adapter/bun": ["./dist/types/adapter/bun/index.d.ts"],
|
||||||
"adapter/node": ["./dist/types/adapter/node/index.d.ts"],
|
"adapter/node": ["./dist/types/adapter/node/index.d.ts"],
|
||||||
|
"adapter/sveltekit": ["./dist/types/adapter/sveltekit/index.d.ts"],
|
||||||
|
"adapter/tanstack-start": ["./dist/types/adapter/tanstack-start/index.d.ts"],
|
||||||
"adapter/sqlite": ["./dist/types/adapter/sqlite/edge.d.ts"]
|
"adapter/sqlite": ["./dist/types/adapter/sqlite/edge.d.ts"]
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
@@ -291,9 +330,12 @@
|
|||||||
"serverless",
|
"serverless",
|
||||||
"cloudflare",
|
"cloudflare",
|
||||||
"nextjs",
|
"nextjs",
|
||||||
|
"nuxt",
|
||||||
"remix",
|
"remix",
|
||||||
"react-router",
|
"react-router",
|
||||||
"astro",
|
"astro",
|
||||||
|
"sveltekit",
|
||||||
|
"svelte",
|
||||||
"bun",
|
"bun",
|
||||||
"node"
|
"node"
|
||||||
]
|
]
|
||||||
|
|||||||
+2
-2
@@ -61,7 +61,7 @@ export class Api {
|
|||||||
private token?: string;
|
private token?: string;
|
||||||
private user?: TApiUser;
|
private user?: TApiUser;
|
||||||
private verified = false;
|
private verified = false;
|
||||||
private token_transport: "header" | "cookie" | "none" = "header";
|
public token_transport: "header" | "cookie" | "none" = "header";
|
||||||
|
|
||||||
public system!: SystemApi;
|
public system!: SystemApi;
|
||||||
public data!: DataApi;
|
public data!: DataApi;
|
||||||
@@ -121,7 +121,7 @@ export class Api {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// try authorization header
|
// try authorization header
|
||||||
const headerToken = this.options.headers.get("authorization")?.replace("Bearer ", "");
|
const headerToken = this.options.headers.get("authorization")?.replace(/^Bearer\s+/i, "");
|
||||||
if (headerToken) {
|
if (headerToken) {
|
||||||
this.token_transport = "header";
|
this.token_transport = "header";
|
||||||
this.updateToken(headerToken);
|
this.updateToken(headerToken);
|
||||||
|
|||||||
+3
-2
@@ -5,7 +5,6 @@ import type { em as prototypeEm } from "data/prototype";
|
|||||||
import { Connection } from "data/connection/Connection";
|
import { Connection } from "data/connection/Connection";
|
||||||
import type { Hono } from "hono";
|
import type { Hono } from "hono";
|
||||||
import {
|
import {
|
||||||
type InitialModuleConfigs,
|
|
||||||
type ModuleConfigs,
|
type ModuleConfigs,
|
||||||
type Modules,
|
type Modules,
|
||||||
ModuleManager,
|
ModuleManager,
|
||||||
@@ -381,8 +380,10 @@ export class App<
|
|||||||
if (results.length > 0) {
|
if (results.length > 0) {
|
||||||
for (const { name, result } of results) {
|
for (const { name, result } of results) {
|
||||||
if (result) {
|
if (result) {
|
||||||
$console.log(`[Plugin:${name}] schema`);
|
|
||||||
ctx.helper.ensureSchema(result);
|
ctx.helper.ensureSchema(result);
|
||||||
|
if (ctx.flags.sync_required) {
|
||||||
|
$console.log(`[Plugin:${name}] schema, sync required`);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,153 @@
|
|||||||
|
import {
|
||||||
|
createContext,
|
||||||
|
lazy,
|
||||||
|
Suspense,
|
||||||
|
useContext,
|
||||||
|
useEffect,
|
||||||
|
useState,
|
||||||
|
type ReactNode,
|
||||||
|
} from "react";
|
||||||
|
import { checksum } from "bknd/utils";
|
||||||
|
import { App, registries, sqlocal, type BkndConfig } from "bknd";
|
||||||
|
import { Route, Router, Switch } from "wouter";
|
||||||
|
import { ClientProvider } from "bknd/client";
|
||||||
|
import { SQLocalKysely } from "sqlocal/kysely";
|
||||||
|
import type { ClientConfig, DatabasePath } from "sqlocal";
|
||||||
|
import { OpfsStorageAdapter } from "bknd/adapter/browser";
|
||||||
|
import type { BkndAdminConfig } from "bknd/ui";
|
||||||
|
|
||||||
|
const Admin = lazy(() =>
|
||||||
|
Promise.all([
|
||||||
|
import("bknd/ui"),
|
||||||
|
// @ts-ignore
|
||||||
|
import("bknd/dist/styles.css"),
|
||||||
|
]).then(([mod]) => ({
|
||||||
|
default: mod.Admin,
|
||||||
|
})),
|
||||||
|
);
|
||||||
|
|
||||||
|
function safeViewTransition(fn: () => void) {
|
||||||
|
if (document.startViewTransition) {
|
||||||
|
document.startViewTransition(fn);
|
||||||
|
} else {
|
||||||
|
fn();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export type BrowserBkndConfig<Args = ImportMetaEnv> = Omit<
|
||||||
|
BkndConfig<Args>,
|
||||||
|
"connection" | "app"
|
||||||
|
> & {
|
||||||
|
adminConfig?: BkndAdminConfig;
|
||||||
|
connection?: ClientConfig | DatabasePath;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type BkndBrowserAppProps = {
|
||||||
|
children: ReactNode;
|
||||||
|
header?: ReactNode;
|
||||||
|
loading?: ReactNode;
|
||||||
|
notFound?: ReactNode;
|
||||||
|
} & BrowserBkndConfig;
|
||||||
|
|
||||||
|
const BkndBrowserAppContext = createContext<{
|
||||||
|
app: App;
|
||||||
|
hash: string;
|
||||||
|
}>(undefined!);
|
||||||
|
|
||||||
|
export function BkndBrowserApp({
|
||||||
|
children,
|
||||||
|
adminConfig,
|
||||||
|
header,
|
||||||
|
loading,
|
||||||
|
notFound,
|
||||||
|
...config
|
||||||
|
}: BkndBrowserAppProps) {
|
||||||
|
const [app, setApp] = useState<App | undefined>(undefined);
|
||||||
|
const [hash, setHash] = useState<string>("");
|
||||||
|
const adminRoutePath = (adminConfig?.basepath ?? "") + "/*?";
|
||||||
|
|
||||||
|
async function onBuilt(app: App) {
|
||||||
|
safeViewTransition(async () => {
|
||||||
|
setApp(app);
|
||||||
|
setHash(await checksum(app.toJSON()));
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
setup({ ...config, adminConfig })
|
||||||
|
.then((app) => onBuilt(app as any))
|
||||||
|
.catch(console.error);
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
if (!app) {
|
||||||
|
return (
|
||||||
|
loading ?? (
|
||||||
|
<Center>
|
||||||
|
<span style={{ opacity: 0.2 }}>Loading...</span>
|
||||||
|
</Center>
|
||||||
|
)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<BkndBrowserAppContext.Provider value={{ app, hash }}>
|
||||||
|
<ClientProvider storage={window.localStorage} fetcher={app.server.request}>
|
||||||
|
{header}
|
||||||
|
<Router key={hash}>
|
||||||
|
<Switch>
|
||||||
|
{children}
|
||||||
|
|
||||||
|
<Route path={adminRoutePath}>
|
||||||
|
<Suspense>
|
||||||
|
<Admin config={adminConfig} />
|
||||||
|
</Suspense>
|
||||||
|
</Route>
|
||||||
|
<Route path="*">
|
||||||
|
{notFound ?? (
|
||||||
|
<Center style={{ fontSize: "48px", fontFamily: "monospace" }}>404</Center>
|
||||||
|
)}
|
||||||
|
</Route>
|
||||||
|
</Switch>
|
||||||
|
</Router>
|
||||||
|
</ClientProvider>
|
||||||
|
</BkndBrowserAppContext.Provider>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useApp() {
|
||||||
|
return useContext(BkndBrowserAppContext);
|
||||||
|
}
|
||||||
|
|
||||||
|
const Center = (props: React.HTMLAttributes<HTMLDivElement>) => (
|
||||||
|
<div
|
||||||
|
{...props}
|
||||||
|
style={{
|
||||||
|
width: "100%",
|
||||||
|
minHeight: "100vh",
|
||||||
|
display: "flex",
|
||||||
|
justifyContent: "center",
|
||||||
|
alignItems: "center",
|
||||||
|
...(props.style ?? {}),
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
|
||||||
|
let initialized = false;
|
||||||
|
async function setup(config: BrowserBkndConfig = {}) {
|
||||||
|
if (initialized) return;
|
||||||
|
initialized = true;
|
||||||
|
|
||||||
|
registries.media.register("opfs", OpfsStorageAdapter);
|
||||||
|
|
||||||
|
const app = App.create({
|
||||||
|
...config,
|
||||||
|
// @ts-ignore
|
||||||
|
connection: sqlocal(new SQLocalKysely(config.connection ?? ":localStorage:")),
|
||||||
|
});
|
||||||
|
|
||||||
|
await config.beforeBuild?.(app);
|
||||||
|
await app.build({ sync: true });
|
||||||
|
await config.onBuilt?.(app);
|
||||||
|
|
||||||
|
return app;
|
||||||
|
}
|
||||||
@@ -0,0 +1,34 @@
|
|||||||
|
import { describe, beforeAll, vi, afterAll, spyOn } from "bun:test";
|
||||||
|
import { OpfsStorageAdapter } from "./OpfsStorageAdapter";
|
||||||
|
// @ts-ignore
|
||||||
|
import { assetsPath } from "../../../__test__/helper";
|
||||||
|
import { adapterTestSuite } from "media/storage/adapters/adapter-test-suite";
|
||||||
|
import { bunTestRunner } from "adapter/bun/test";
|
||||||
|
import { MockFileSystemDirectoryHandle } from "adapter/browser/mock";
|
||||||
|
|
||||||
|
describe("OpfsStorageAdapter", async () => {
|
||||||
|
let mockRoot: MockFileSystemDirectoryHandle;
|
||||||
|
let testSuiteAdapter: OpfsStorageAdapter;
|
||||||
|
|
||||||
|
const _mock = spyOn(global, "navigator");
|
||||||
|
|
||||||
|
beforeAll(() => {
|
||||||
|
// mock navigator.storage.getDirectory()
|
||||||
|
mockRoot = new MockFileSystemDirectoryHandle("opfs-root");
|
||||||
|
const mockNavigator = {
|
||||||
|
storage: {
|
||||||
|
getDirectory: vi.fn().mockResolvedValue(mockRoot),
|
||||||
|
},
|
||||||
|
};
|
||||||
|
// @ts-ignore
|
||||||
|
_mock.mockReturnValue(mockNavigator);
|
||||||
|
testSuiteAdapter = new OpfsStorageAdapter();
|
||||||
|
});
|
||||||
|
|
||||||
|
afterAll(() => {
|
||||||
|
_mock.mockRestore();
|
||||||
|
});
|
||||||
|
|
||||||
|
const file = Bun.file(`${assetsPath}/image.png`);
|
||||||
|
await adapterTestSuite(bunTestRunner, () => testSuiteAdapter, file);
|
||||||
|
});
|
||||||
@@ -0,0 +1,265 @@
|
|||||||
|
import type { FileBody, FileListObject, FileMeta, FileUploadPayload } from "bknd";
|
||||||
|
import { StorageAdapter, guessMimeType } from "bknd";
|
||||||
|
import { parse, s, isFile, isBlob } from "bknd/utils";
|
||||||
|
|
||||||
|
export const opfsAdapterConfig = s.object(
|
||||||
|
{
|
||||||
|
root: s.string({ default: "" }).optional(),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: "OPFS",
|
||||||
|
description: "Origin Private File System storage",
|
||||||
|
additionalProperties: false,
|
||||||
|
},
|
||||||
|
);
|
||||||
|
export type OpfsAdapterConfig = s.Static<typeof opfsAdapterConfig>;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Storage adapter for OPFS (Origin Private File System)
|
||||||
|
* Provides browser-based file storage using the File System Access API
|
||||||
|
*/
|
||||||
|
export class OpfsStorageAdapter extends StorageAdapter {
|
||||||
|
private config: OpfsAdapterConfig;
|
||||||
|
private rootPromise: Promise<FileSystemDirectoryHandle>;
|
||||||
|
|
||||||
|
constructor(config: Partial<OpfsAdapterConfig> = {}) {
|
||||||
|
super();
|
||||||
|
this.config = parse(opfsAdapterConfig, config);
|
||||||
|
this.rootPromise = this.initializeRoot();
|
||||||
|
}
|
||||||
|
|
||||||
|
private async initializeRoot(): Promise<FileSystemDirectoryHandle> {
|
||||||
|
const opfsRoot = await navigator.storage.getDirectory();
|
||||||
|
if (!this.config.root) {
|
||||||
|
return opfsRoot;
|
||||||
|
}
|
||||||
|
|
||||||
|
// navigate to or create nested directory structure
|
||||||
|
const parts = this.config.root.split("/").filter(Boolean);
|
||||||
|
let current = opfsRoot;
|
||||||
|
for (const part of parts) {
|
||||||
|
current = await current.getDirectoryHandle(part, { create: true });
|
||||||
|
}
|
||||||
|
return current;
|
||||||
|
}
|
||||||
|
|
||||||
|
getSchema() {
|
||||||
|
return opfsAdapterConfig;
|
||||||
|
}
|
||||||
|
|
||||||
|
getName(): string {
|
||||||
|
return "opfs";
|
||||||
|
}
|
||||||
|
|
||||||
|
async listObjects(prefix?: string): Promise<FileListObject[]> {
|
||||||
|
const root = await this.rootPromise;
|
||||||
|
const files: FileListObject[] = [];
|
||||||
|
|
||||||
|
for await (const [name, handle] of root.entries()) {
|
||||||
|
if (handle.kind === "file") {
|
||||||
|
if (!prefix || name.startsWith(prefix)) {
|
||||||
|
const file = await (handle as FileSystemFileHandle).getFile();
|
||||||
|
files.push({
|
||||||
|
key: name,
|
||||||
|
last_modified: new Date(file.lastModified),
|
||||||
|
size: file.size,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return files;
|
||||||
|
}
|
||||||
|
|
||||||
|
private async computeEtagFromArrayBuffer(buffer: ArrayBuffer): Promise<string> {
|
||||||
|
const hashBuffer = await crypto.subtle.digest("SHA-256", buffer);
|
||||||
|
const hashArray = Array.from(new Uint8Array(hashBuffer));
|
||||||
|
const hashHex = hashArray.map((byte) => byte.toString(16).padStart(2, "0")).join("");
|
||||||
|
|
||||||
|
// wrap the hex string in quotes for ETag format
|
||||||
|
return `"${hashHex}"`;
|
||||||
|
}
|
||||||
|
|
||||||
|
async putObject(key: string, body: FileBody): Promise<string | FileUploadPayload> {
|
||||||
|
if (body === null) {
|
||||||
|
throw new Error("Body is empty");
|
||||||
|
}
|
||||||
|
|
||||||
|
const root = await this.rootPromise;
|
||||||
|
const fileHandle = await root.getFileHandle(key, { create: true });
|
||||||
|
const writable = await fileHandle.createWritable();
|
||||||
|
|
||||||
|
try {
|
||||||
|
let contentBuffer: ArrayBuffer;
|
||||||
|
|
||||||
|
if (isFile(body)) {
|
||||||
|
contentBuffer = await body.arrayBuffer();
|
||||||
|
await writable.write(contentBuffer);
|
||||||
|
} else if (body instanceof ReadableStream) {
|
||||||
|
const chunks: Uint8Array[] = [];
|
||||||
|
const reader = body.getReader();
|
||||||
|
try {
|
||||||
|
while (true) {
|
||||||
|
const { done, value } = await reader.read();
|
||||||
|
if (done) break;
|
||||||
|
chunks.push(value);
|
||||||
|
await writable.write(value);
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
reader.releaseLock();
|
||||||
|
}
|
||||||
|
// compute total size and combine chunks for etag
|
||||||
|
const totalSize = chunks.reduce((sum, chunk) => sum + chunk.length, 0);
|
||||||
|
const combined = new Uint8Array(totalSize);
|
||||||
|
let offset = 0;
|
||||||
|
for (const chunk of chunks) {
|
||||||
|
combined.set(chunk, offset);
|
||||||
|
offset += chunk.length;
|
||||||
|
}
|
||||||
|
contentBuffer = combined.buffer;
|
||||||
|
} else if (isBlob(body)) {
|
||||||
|
contentBuffer = await (body as Blob).arrayBuffer();
|
||||||
|
await writable.write(contentBuffer);
|
||||||
|
} else {
|
||||||
|
// body is ArrayBuffer or ArrayBufferView
|
||||||
|
if (ArrayBuffer.isView(body)) {
|
||||||
|
const view = body as ArrayBufferView;
|
||||||
|
contentBuffer = view.buffer.slice(
|
||||||
|
view.byteOffset,
|
||||||
|
view.byteOffset + view.byteLength,
|
||||||
|
) as ArrayBuffer;
|
||||||
|
} else {
|
||||||
|
contentBuffer = body as ArrayBuffer;
|
||||||
|
}
|
||||||
|
await writable.write(body);
|
||||||
|
}
|
||||||
|
|
||||||
|
await writable.close();
|
||||||
|
return await this.computeEtagFromArrayBuffer(contentBuffer);
|
||||||
|
} catch (error) {
|
||||||
|
await writable.abort();
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async deleteObject(key: string): Promise<void> {
|
||||||
|
try {
|
||||||
|
const root = await this.rootPromise;
|
||||||
|
await root.removeEntry(key);
|
||||||
|
} catch {
|
||||||
|
// file doesn't exist, which is fine
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async objectExists(key: string): Promise<boolean> {
|
||||||
|
try {
|
||||||
|
const root = await this.rootPromise;
|
||||||
|
await root.getFileHandle(key);
|
||||||
|
return true;
|
||||||
|
} catch {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private parseRangeHeader(
|
||||||
|
rangeHeader: string,
|
||||||
|
fileSize: number,
|
||||||
|
): { start: number; end: number } | null {
|
||||||
|
// parse "bytes=start-end" format
|
||||||
|
const match = rangeHeader.match(/^bytes=(\d*)-(\d*)$/);
|
||||||
|
if (!match) return null;
|
||||||
|
|
||||||
|
const [, startStr, endStr] = match;
|
||||||
|
let start = startStr ? Number.parseInt(startStr, 10) : 0;
|
||||||
|
let end = endStr ? Number.parseInt(endStr, 10) : fileSize - 1;
|
||||||
|
|
||||||
|
// handle suffix-byte-range-spec (e.g., "bytes=-500")
|
||||||
|
if (!startStr && endStr) {
|
||||||
|
start = Math.max(0, fileSize - Number.parseInt(endStr, 10));
|
||||||
|
end = fileSize - 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
// validate range
|
||||||
|
if (start < 0 || end >= fileSize || start > end) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
return { start, end };
|
||||||
|
}
|
||||||
|
|
||||||
|
async getObject(key: string, headers: Headers): Promise<Response> {
|
||||||
|
try {
|
||||||
|
const root = await this.rootPromise;
|
||||||
|
const fileHandle = await root.getFileHandle(key);
|
||||||
|
const file = await fileHandle.getFile();
|
||||||
|
const fileSize = file.size;
|
||||||
|
const mimeType = guessMimeType(key);
|
||||||
|
|
||||||
|
const responseHeaders = new Headers({
|
||||||
|
"Accept-Ranges": "bytes",
|
||||||
|
"Content-Type": mimeType || "application/octet-stream",
|
||||||
|
});
|
||||||
|
|
||||||
|
const rangeHeader = headers.get("range");
|
||||||
|
|
||||||
|
if (rangeHeader) {
|
||||||
|
const range = this.parseRangeHeader(rangeHeader, fileSize);
|
||||||
|
|
||||||
|
if (!range) {
|
||||||
|
// invalid range - return 416 Range Not Satisfiable
|
||||||
|
responseHeaders.set("Content-Range", `bytes */${fileSize}`);
|
||||||
|
return new Response("", {
|
||||||
|
status: 416,
|
||||||
|
headers: responseHeaders,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const { start, end } = range;
|
||||||
|
const arrayBuffer = await file.arrayBuffer();
|
||||||
|
const chunk = arrayBuffer.slice(start, end + 1);
|
||||||
|
|
||||||
|
responseHeaders.set("Content-Range", `bytes ${start}-${end}/${fileSize}`);
|
||||||
|
responseHeaders.set("Content-Length", chunk.byteLength.toString());
|
||||||
|
|
||||||
|
return new Response(chunk, {
|
||||||
|
status: 206, // Partial Content
|
||||||
|
headers: responseHeaders,
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
// normal request - return entire file
|
||||||
|
const content = await file.arrayBuffer();
|
||||||
|
responseHeaders.set("Content-Length", content.byteLength.toString());
|
||||||
|
|
||||||
|
return new Response(content, {
|
||||||
|
status: 200,
|
||||||
|
headers: responseHeaders,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
// handle file reading errors
|
||||||
|
return new Response("", { status: 404 });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
getObjectUrl(_key: string): string {
|
||||||
|
throw new Error("Method not implemented.");
|
||||||
|
}
|
||||||
|
|
||||||
|
async getObjectMeta(key: string): Promise<FileMeta> {
|
||||||
|
const root = await this.rootPromise;
|
||||||
|
const fileHandle = await root.getFileHandle(key);
|
||||||
|
const file = await fileHandle.getFile();
|
||||||
|
|
||||||
|
return {
|
||||||
|
type: guessMimeType(key) || "application/octet-stream",
|
||||||
|
size: file.size,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
toJSON(_secrets?: boolean) {
|
||||||
|
return {
|
||||||
|
type: this.getName(),
|
||||||
|
config: this.config,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,2 @@
|
|||||||
|
export * from "./OpfsStorageAdapter";
|
||||||
|
export * from "./BkndBrowserApp";
|
||||||
@@ -0,0 +1,136 @@
|
|||||||
|
// mock OPFS API for testing
|
||||||
|
class MockFileSystemFileHandle {
|
||||||
|
kind: "file" = "file";
|
||||||
|
name: string;
|
||||||
|
private content: ArrayBuffer;
|
||||||
|
private lastModified: number;
|
||||||
|
|
||||||
|
constructor(name: string, content: ArrayBuffer = new ArrayBuffer(0)) {
|
||||||
|
this.name = name;
|
||||||
|
this.content = content;
|
||||||
|
this.lastModified = Date.now();
|
||||||
|
}
|
||||||
|
|
||||||
|
async getFile(): Promise<File> {
|
||||||
|
return new File([this.content], this.name, {
|
||||||
|
lastModified: this.lastModified,
|
||||||
|
type: this.guessMimeType(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async createWritable(): Promise<FileSystemWritableFileStream> {
|
||||||
|
const handle = this;
|
||||||
|
return {
|
||||||
|
async write(data: any) {
|
||||||
|
if (data instanceof ArrayBuffer) {
|
||||||
|
handle.content = data;
|
||||||
|
} else if (ArrayBuffer.isView(data)) {
|
||||||
|
handle.content = data.buffer.slice(
|
||||||
|
data.byteOffset,
|
||||||
|
data.byteOffset + data.byteLength,
|
||||||
|
) as ArrayBuffer;
|
||||||
|
} else if (data instanceof Blob) {
|
||||||
|
handle.content = await data.arrayBuffer();
|
||||||
|
}
|
||||||
|
handle.lastModified = Date.now();
|
||||||
|
},
|
||||||
|
async close() {},
|
||||||
|
async abort() {},
|
||||||
|
async seek(_position: number) {},
|
||||||
|
async truncate(_size: number) {},
|
||||||
|
} as FileSystemWritableFileStream;
|
||||||
|
}
|
||||||
|
|
||||||
|
private guessMimeType(): string {
|
||||||
|
const ext = this.name.split(".").pop()?.toLowerCase();
|
||||||
|
const mimeTypes: Record<string, string> = {
|
||||||
|
png: "image/png",
|
||||||
|
jpg: "image/jpeg",
|
||||||
|
jpeg: "image/jpeg",
|
||||||
|
gif: "image/gif",
|
||||||
|
webp: "image/webp",
|
||||||
|
svg: "image/svg+xml",
|
||||||
|
txt: "text/plain",
|
||||||
|
json: "application/json",
|
||||||
|
pdf: "application/pdf",
|
||||||
|
};
|
||||||
|
return mimeTypes[ext || ""] || "application/octet-stream";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export class MockFileSystemDirectoryHandle {
|
||||||
|
kind: "directory" = "directory";
|
||||||
|
name: string;
|
||||||
|
private files: Map<string, MockFileSystemFileHandle> = new Map();
|
||||||
|
private directories: Map<string, MockFileSystemDirectoryHandle> = new Map();
|
||||||
|
|
||||||
|
constructor(name: string = "root") {
|
||||||
|
this.name = name;
|
||||||
|
}
|
||||||
|
|
||||||
|
async getFileHandle(
|
||||||
|
name: string,
|
||||||
|
options?: FileSystemGetFileOptions,
|
||||||
|
): Promise<FileSystemFileHandle> {
|
||||||
|
if (this.files.has(name)) {
|
||||||
|
return this.files.get(name) as any;
|
||||||
|
}
|
||||||
|
if (options?.create) {
|
||||||
|
const handle = new MockFileSystemFileHandle(name);
|
||||||
|
this.files.set(name, handle);
|
||||||
|
return handle as any;
|
||||||
|
}
|
||||||
|
throw new Error(`File not found: ${name}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
async getDirectoryHandle(
|
||||||
|
name: string,
|
||||||
|
options?: FileSystemGetDirectoryOptions,
|
||||||
|
): Promise<FileSystemDirectoryHandle> {
|
||||||
|
if (this.directories.has(name)) {
|
||||||
|
return this.directories.get(name) as any;
|
||||||
|
}
|
||||||
|
if (options?.create) {
|
||||||
|
const handle = new MockFileSystemDirectoryHandle(name);
|
||||||
|
this.directories.set(name, handle);
|
||||||
|
return handle as any;
|
||||||
|
}
|
||||||
|
throw new Error(`Directory not found: ${name}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
async removeEntry(name: string, _options?: FileSystemRemoveOptions): Promise<void> {
|
||||||
|
this.files.delete(name);
|
||||||
|
this.directories.delete(name);
|
||||||
|
}
|
||||||
|
|
||||||
|
async *entries(): AsyncIterableIterator<[string, FileSystemHandle]> {
|
||||||
|
for (const [name, handle] of this.files) {
|
||||||
|
yield [name, handle as any];
|
||||||
|
}
|
||||||
|
for (const [name, handle] of this.directories) {
|
||||||
|
yield [name, handle as any];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async *keys(): AsyncIterableIterator<string> {
|
||||||
|
for (const name of this.files.keys()) {
|
||||||
|
yield name;
|
||||||
|
}
|
||||||
|
for (const name of this.directories.keys()) {
|
||||||
|
yield name;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async *values(): AsyncIterableIterator<FileSystemHandle> {
|
||||||
|
for (const handle of this.files.values()) {
|
||||||
|
yield handle as any;
|
||||||
|
}
|
||||||
|
for (const handle of this.directories.values()) {
|
||||||
|
yield handle as any;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[Symbol.asyncIterator](): AsyncIterableIterator<[string, FileSystemHandle]> {
|
||||||
|
return this.entries();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,14 +1,12 @@
|
|||||||
/// <reference types="bun-types" />
|
|
||||||
|
|
||||||
import path from "node:path";
|
import path from "node:path";
|
||||||
import { type RuntimeBkndConfig, createRuntimeApp } from "bknd/adapter";
|
import { type RuntimeBkndConfig, createRuntimeApp } from "bknd/adapter";
|
||||||
import { registerLocalMediaAdapter } from ".";
|
import { registerLocalMediaAdapter } from ".";
|
||||||
import { config, type App } from "bknd";
|
import { config, type App } from "bknd";
|
||||||
import type { ServeOptions } from "bun";
|
|
||||||
import { serveStatic } from "hono/bun";
|
import { serveStatic } from "hono/bun";
|
||||||
|
|
||||||
type BunEnv = Bun.Env;
|
type BunEnv = Bun.Env;
|
||||||
export type BunBkndConfig<Env = BunEnv> = RuntimeBkndConfig<Env> & Omit<ServeOptions, "fetch">;
|
export type BunBkndConfig<Env = BunEnv> = RuntimeBkndConfig<Env> &
|
||||||
|
Omit<Bun.Serve.Options<undefined, string>, "fetch">;
|
||||||
|
|
||||||
export async function createApp<Env = BunEnv>(
|
export async function createApp<Env = BunEnv>(
|
||||||
{ distPath, serveStatic: _serveStatic, ...config }: BunBkndConfig<Env> = {},
|
{ distPath, serveStatic: _serveStatic, ...config }: BunBkndConfig<Env> = {},
|
||||||
@@ -45,6 +43,7 @@ export function createHandler<Env = BunEnv>(
|
|||||||
|
|
||||||
export function serve<Env = BunEnv>(
|
export function serve<Env = BunEnv>(
|
||||||
{
|
{
|
||||||
|
app,
|
||||||
distPath,
|
distPath,
|
||||||
connection,
|
connection,
|
||||||
config: _config,
|
config: _config,
|
||||||
@@ -60,10 +59,11 @@ export function serve<Env = BunEnv>(
|
|||||||
args: Env = Bun.env as Env,
|
args: Env = Bun.env as Env,
|
||||||
) {
|
) {
|
||||||
Bun.serve({
|
Bun.serve({
|
||||||
...serveOptions,
|
...(serveOptions as any),
|
||||||
port,
|
port,
|
||||||
fetch: createHandler(
|
fetch: createHandler(
|
||||||
{
|
{
|
||||||
|
app,
|
||||||
connection,
|
connection,
|
||||||
config: _config,
|
config: _config,
|
||||||
options,
|
options,
|
||||||
|
|||||||
@@ -3,7 +3,7 @@
|
|||||||
import type { RuntimeBkndConfig } from "bknd/adapter";
|
import type { RuntimeBkndConfig } from "bknd/adapter";
|
||||||
import { Hono } from "hono";
|
import { Hono } from "hono";
|
||||||
import { serveStatic } from "hono/cloudflare-workers";
|
import { serveStatic } from "hono/cloudflare-workers";
|
||||||
import type { MaybePromise } from "bknd";
|
import type { App, MaybePromise } from "bknd";
|
||||||
import { $console } from "bknd/utils";
|
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";
|
||||||
@@ -55,8 +55,12 @@ export async function createApp<Env extends CloudflareEnv = CloudflareEnv>(
|
|||||||
// compatiblity
|
// compatiblity
|
||||||
export const getFresh = createApp;
|
export const getFresh = createApp;
|
||||||
|
|
||||||
|
let app: App | undefined;
|
||||||
export function serve<Env extends CloudflareEnv = CloudflareEnv>(
|
export function serve<Env extends CloudflareEnv = CloudflareEnv>(
|
||||||
config: CloudflareBkndConfig<Env> = {},
|
config: CloudflareBkndConfig<Env> = {},
|
||||||
|
serveOptions?: (args: Env) => {
|
||||||
|
warm?: boolean;
|
||||||
|
},
|
||||||
) {
|
) {
|
||||||
return {
|
return {
|
||||||
async fetch(request: Request, env: Env, ctx: ExecutionContext) {
|
async fetch(request: Request, env: Env, ctx: ExecutionContext) {
|
||||||
@@ -92,8 +96,11 @@ export function serve<Env extends CloudflareEnv = CloudflareEnv>(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const context = { request, env, ctx } as CloudflareContext<Env>;
|
const { warm } = serveOptions?.(env) ?? {};
|
||||||
const app = await createApp(config, context);
|
if (!app || warm !== true) {
|
||||||
|
const context = { request, env, ctx } as CloudflareContext<Env>;
|
||||||
|
app = await createApp(config, context);
|
||||||
|
}
|
||||||
|
|
||||||
return app.fetch(request, env, ctx);
|
return app.fetch(request, env, ctx);
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -65,37 +65,31 @@ export function withPlatformProxy<Env extends CloudflareEnv>(
|
|||||||
}
|
}
|
||||||
|
|
||||||
return {
|
return {
|
||||||
...config,
|
|
||||||
beforeBuild: async (app, registries) => {
|
|
||||||
if (!use_proxy) return;
|
|
||||||
const env = await getEnv();
|
|
||||||
registerMedia(env, registries as any);
|
|
||||||
await config?.beforeBuild?.(app, registries);
|
|
||||||
},
|
|
||||||
bindings: async (env) => {
|
|
||||||
return (await config?.bindings?.(await getEnv(env))) || {};
|
|
||||||
},
|
|
||||||
// @ts-ignore
|
// @ts-ignore
|
||||||
app: async (_env) => {
|
app: async (_env) => {
|
||||||
const env = await getEnv(_env);
|
const env = await getEnv(_env);
|
||||||
const binding = use_proxy ? getBinding(env, "D1Database") : undefined;
|
const binding = use_proxy ? getBinding(env, "D1Database") : undefined;
|
||||||
|
const appConfig = typeof config.app === "function" ? await config.app(env) : config;
|
||||||
|
const connection =
|
||||||
|
use_proxy && binding
|
||||||
|
? d1Sqlite({
|
||||||
|
binding: binding.value as any,
|
||||||
|
})
|
||||||
|
: appConfig.connection;
|
||||||
|
|
||||||
if (config?.app === undefined && use_proxy && binding) {
|
return {
|
||||||
return {
|
...appConfig,
|
||||||
connection: d1Sqlite({
|
beforeBuild: async (app, registries) => {
|
||||||
binding: binding.value,
|
if (!use_proxy) return;
|
||||||
}),
|
const env = await getEnv();
|
||||||
};
|
registerMedia(env, registries as any);
|
||||||
} else if (typeof config?.app === "function") {
|
await config?.beforeBuild?.(app, registries);
|
||||||
const appConfig = await config?.app(env);
|
},
|
||||||
if (binding) {
|
bindings: async (env) => {
|
||||||
appConfig.connection = d1Sqlite({
|
return (await config?.bindings?.(await getEnv(env))) || {};
|
||||||
binding: binding.value,
|
},
|
||||||
}) as any;
|
connection,
|
||||||
}
|
};
|
||||||
return appConfig;
|
|
||||||
}
|
|
||||||
return config?.app || {};
|
|
||||||
},
|
},
|
||||||
} satisfies CloudflareBkndConfig<Env>;
|
} satisfies CloudflareBkndConfig<Env>;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -14,14 +14,15 @@ import type { AdminControllerOptions } from "modules/server/AdminController";
|
|||||||
import type { Manifest } from "vite";
|
import type { Manifest } from "vite";
|
||||||
|
|
||||||
export type BkndConfig<Args = any, Additional = {}> = Merge<
|
export type BkndConfig<Args = any, Additional = {}> = Merge<
|
||||||
CreateAppConfig & {
|
CreateAppConfig &
|
||||||
app?:
|
Omit<Additional, "app"> & {
|
||||||
| Merge<Omit<BkndConfig, "app"> & Additional>
|
app?:
|
||||||
| ((args: Args) => MaybePromise<Merge<Omit<BkndConfig<Args>, "app"> & Additional>>);
|
| Omit<BkndConfig<Args, Additional>, "app">
|
||||||
onBuilt?: (app: App) => MaybePromise<void>;
|
| ((args: Args) => MaybePromise<Omit<BkndConfig<Args, Additional>, "app">>);
|
||||||
beforeBuild?: (app?: App, registries?: typeof $registries) => MaybePromise<void>;
|
onBuilt?: (app: App) => MaybePromise<void>;
|
||||||
buildConfig?: Parameters<App["build"]>[0];
|
beforeBuild?: (app?: App, registries?: typeof $registries) => MaybePromise<void>;
|
||||||
} & Additional
|
buildConfig?: Parameters<App["build"]>[0];
|
||||||
|
}
|
||||||
>;
|
>;
|
||||||
|
|
||||||
export type FrameworkBkndConfig<Args = any> = BkndConfig<Args>;
|
export type FrameworkBkndConfig<Args = any> = BkndConfig<Args>;
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
import { createFrameworkApp, type FrameworkBkndConfig } from "bknd/adapter";
|
import { createFrameworkApp, type FrameworkBkndConfig } from "bknd/adapter";
|
||||||
import { isNode } from "bknd/utils";
|
import { isNode } from "bknd/utils";
|
||||||
|
// @ts-expect-error next is not installed
|
||||||
import type { NextApiRequest } from "next";
|
import type { NextApiRequest } from "next";
|
||||||
|
|
||||||
type NextjsEnv = NextApiRequest["env"];
|
type NextjsEnv = NextApiRequest["env"];
|
||||||
@@ -18,7 +19,9 @@ function getCleanRequest(req: Request, cleanRequest: NextjsBkndConfig["cleanRequ
|
|||||||
if (!cleanRequest) return req;
|
if (!cleanRequest) return req;
|
||||||
|
|
||||||
const url = new URL(req.url);
|
const url = new URL(req.url);
|
||||||
cleanRequest?.searchParams?.forEach((k) => url.searchParams.delete(k));
|
cleanRequest?.searchParams?.forEach((k) => {
|
||||||
|
url.searchParams.delete(k);
|
||||||
|
});
|
||||||
|
|
||||||
if (isNode()) {
|
if (isNode()) {
|
||||||
return new Request(url.toString(), {
|
return new Request(url.toString(), {
|
||||||
|
|||||||
@@ -24,7 +24,7 @@ export async function createApp<Env = NodeEnv>(
|
|||||||
path.resolve(distPath ?? relativeDistPath ?? "./node_modules/bknd/dist", "static"),
|
path.resolve(distPath ?? relativeDistPath ?? "./node_modules/bknd/dist", "static"),
|
||||||
);
|
);
|
||||||
if (relativeDistPath) {
|
if (relativeDistPath) {
|
||||||
console.warn("relativeDistPath is deprecated, please use distPath instead");
|
$console.warn("relativeDistPath is deprecated, please use distPath instead");
|
||||||
}
|
}
|
||||||
|
|
||||||
registerLocalMediaAdapter();
|
registerLocalMediaAdapter();
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import { describe, beforeAll, afterAll } from "vitest";
|
import { describe } from "vitest";
|
||||||
import * as node from "./node.adapter";
|
import * as node from "./node.adapter";
|
||||||
import { adapterTestSuite } from "adapter/adapter-test-suite";
|
import { adapterTestSuite } from "adapter/adapter-test-suite";
|
||||||
import { viTestRunner } from "adapter/node/vitest";
|
import { viTestRunner } from "adapter/node/vitest";
|
||||||
|
|||||||
@@ -0,0 +1 @@
|
|||||||
|
export * from "./nuxt.adapter";
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
import { afterAll, beforeAll, describe } from "bun:test";
|
||||||
|
import * as nuxt from "./nuxt.adapter";
|
||||||
|
import { disableConsoleLog, enableConsoleLog } from "core/utils";
|
||||||
|
import { adapterTestSuite } from "adapter/adapter-test-suite";
|
||||||
|
import { bunTestRunner } from "adapter/bun/test";
|
||||||
|
|
||||||
|
beforeAll(disableConsoleLog);
|
||||||
|
afterAll(enableConsoleLog);
|
||||||
|
|
||||||
|
describe("nuxt adapter", () => {
|
||||||
|
adapterTestSuite(bunTestRunner, {
|
||||||
|
makeApp: nuxt.getApp,
|
||||||
|
makeHandler: nuxt.serve,
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,30 @@
|
|||||||
|
import { createRuntimeApp, type RuntimeBkndConfig } from "bknd/adapter";
|
||||||
|
|
||||||
|
export type NuxtEnv = NodeJS.ProcessEnv;
|
||||||
|
export type NuxtBkndConfig<Env = NuxtEnv> = RuntimeBkndConfig<Env>;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get bknd app instance
|
||||||
|
* @param config - bknd configuration
|
||||||
|
* @param args - environment variables
|
||||||
|
*/
|
||||||
|
export async function getApp<Env>(
|
||||||
|
config: NuxtBkndConfig<Env> = {} as NuxtBkndConfig<Env>,
|
||||||
|
args: Env,
|
||||||
|
) {
|
||||||
|
return await createRuntimeApp(config, args);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create middleware handler for Nuxt
|
||||||
|
* @param config - bknd configuration
|
||||||
|
* @param args - environment variables
|
||||||
|
*/
|
||||||
|
export function serve<Env>(
|
||||||
|
config: NuxtBkndConfig<Env> = {} as NuxtBkndConfig<Env>,
|
||||||
|
args: Env,
|
||||||
|
) {
|
||||||
|
return async (request: Request) => {
|
||||||
|
return (await getApp(config, args)).fetch(request);
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
export * from "./sveltekit.adapter";
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
import { afterAll, beforeAll, describe } from "bun:test";
|
||||||
|
import * as sveltekit from "./sveltekit.adapter";
|
||||||
|
import { disableConsoleLog, enableConsoleLog } from "core/utils";
|
||||||
|
import { adapterTestSuite } from "adapter/adapter-test-suite";
|
||||||
|
import { bunTestRunner } from "adapter/bun/test";
|
||||||
|
|
||||||
|
beforeAll(disableConsoleLog);
|
||||||
|
afterAll(enableConsoleLog);
|
||||||
|
|
||||||
|
describe("sveltekit adapter", () => {
|
||||||
|
adapterTestSuite(bunTestRunner, {
|
||||||
|
makeApp: (c, a) => sveltekit.getApp(c as any, a ?? ({} as any)),
|
||||||
|
makeHandler: (c, a) => (request: Request) =>
|
||||||
|
sveltekit.serve(c as any, a ?? ({} as any))({ request }),
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
import { createRuntimeApp, type RuntimeBkndConfig } from "bknd/adapter";
|
||||||
|
|
||||||
|
type TSvelteKit = {
|
||||||
|
request: Request;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type SvelteKitBkndConfig<Env> = Pick<RuntimeBkndConfig<Env>, "adminOptions">;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get bknd app instance
|
||||||
|
* @param config - bknd configuration
|
||||||
|
* @param args - environment variables (use $env/dynamic/private for universal runtime support)
|
||||||
|
*/
|
||||||
|
export async function getApp<Env>(
|
||||||
|
config: SvelteKitBkndConfig<Env> = {} as SvelteKitBkndConfig<Env>,
|
||||||
|
args: Env,
|
||||||
|
) {
|
||||||
|
return await createRuntimeApp(config, args);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create request handler for hooks.server.ts
|
||||||
|
* @param config - bknd configuration
|
||||||
|
* @param args - environment variables (use $env/dynamic/private for universal runtime support)
|
||||||
|
*/
|
||||||
|
export function serve<Env>(
|
||||||
|
config: SvelteKitBkndConfig<Env> = {} as SvelteKitBkndConfig<Env>,
|
||||||
|
args: Env,
|
||||||
|
) {
|
||||||
|
return async (fnArgs: TSvelteKit) => {
|
||||||
|
return (await getApp(config, args)).fetch(fnArgs.request);
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
export * from "./tanstack-start.adapter";
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
import { afterAll, beforeAll, describe } from "bun:test";
|
||||||
|
import * as tanstackStart from "./tanstack-start.adapter";
|
||||||
|
import { disableConsoleLog, enableConsoleLog } from "core/utils";
|
||||||
|
import { adapterTestSuite } from "adapter/adapter-test-suite";
|
||||||
|
import { bunTestRunner } from "adapter/bun/test";
|
||||||
|
import type { TanstackStartConfig } from "./tanstack-start.adapter";
|
||||||
|
|
||||||
|
beforeAll(disableConsoleLog);
|
||||||
|
afterAll(enableConsoleLog);
|
||||||
|
|
||||||
|
describe("tanstack start adapter", () => {
|
||||||
|
adapterTestSuite<TanstackStartConfig>(bunTestRunner, {
|
||||||
|
makeApp: tanstackStart.getApp,
|
||||||
|
makeHandler: tanstackStart.serve,
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
import { createFrameworkApp, type FrameworkBkndConfig } from "bknd/adapter";
|
||||||
|
|
||||||
|
export type TanstackStartEnv = NodeJS.ProcessEnv;
|
||||||
|
|
||||||
|
export type TanstackStartConfig<Env = TanstackStartEnv> =
|
||||||
|
FrameworkBkndConfig<Env>;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get bknd app instance
|
||||||
|
* @param config - bknd configuration
|
||||||
|
* @param args - environment variables
|
||||||
|
*/
|
||||||
|
export async function getApp<Env = TanstackStartEnv>(
|
||||||
|
config: TanstackStartConfig<Env> = {},
|
||||||
|
args: Env = process.env as Env,
|
||||||
|
) {
|
||||||
|
return await createFrameworkApp(config, args);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create request handler for src/routes/api.$.ts
|
||||||
|
* @param config - bknd configuration
|
||||||
|
* @param args - environment variables
|
||||||
|
*/
|
||||||
|
export function serve<Env = TanstackStartEnv>(
|
||||||
|
config: TanstackStartConfig<Env> = {},
|
||||||
|
args: Env = process.env as Env,
|
||||||
|
) {
|
||||||
|
return async (request: Request) => {
|
||||||
|
const app = await getApp(config, args);
|
||||||
|
return app.fetch(request);
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
export * from "./universal.adapter";
|
||||||
@@ -0,0 +1,104 @@
|
|||||||
|
import { afterAll, beforeAll, describe, test, expect } from "bun:test";
|
||||||
|
import { createBknd } from "./universal.adapter";
|
||||||
|
import { disableConsoleLog, enableConsoleLog } from "core/utils";
|
||||||
|
import { adapterTestSuite } from "adapter/adapter-test-suite";
|
||||||
|
import { bunTestRunner } from "adapter/bun/test";
|
||||||
|
|
||||||
|
beforeAll(disableConsoleLog);
|
||||||
|
afterAll(enableConsoleLog);
|
||||||
|
|
||||||
|
describe("universal adapter via createBknd", () => {
|
||||||
|
adapterTestSuite(bunTestRunner, {
|
||||||
|
makeApp: (options, args) => createBknd({ mode: "headless", options }, args).getApp(),
|
||||||
|
makeHandler: (options, args) => createBknd({ mode: "headless", options: options ?? {} }, args).serve(),
|
||||||
|
});
|
||||||
|
|
||||||
|
// ------------------------ MODE HEADLESS ------------------------
|
||||||
|
test("caches app instance", async () => {
|
||||||
|
const bknd = createBknd({ mode: "headless", options: { connection: { url: ":memory:" } } });
|
||||||
|
const app1 = await bknd.getApp();
|
||||||
|
const app2 = await bknd.getApp();
|
||||||
|
expect(app1).toBe(app2);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("getApi returns api", async () => {
|
||||||
|
const bknd = createBknd({ mode: "headless", options: { connection: { url: ":memory:" } } });
|
||||||
|
const api = await bknd.getApi();
|
||||||
|
expect(api).toBeDefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
test("uses createFrameworkApp in headless mode", async () => {
|
||||||
|
const bknd = createBknd({ mode: "headless", options: { connection: { url: ":memory:" } } });
|
||||||
|
const app = await bknd.getApp();
|
||||||
|
expect(app).toBeDefined();
|
||||||
|
expect(app.isBuilt()).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("serve returns a fetch handler", async () => {
|
||||||
|
const bknd = createBknd({ mode: "headless", options: { connection: { url: ":memory:" } } });
|
||||||
|
const handler = bknd.serve();
|
||||||
|
const res = await handler(new Request("http://localhost:3000/api/system/config"));
|
||||||
|
expect(res.status).toBe(200);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
|
||||||
|
// ------------------------ MODE ADMIN ------------------------
|
||||||
|
describe("universal adapter via createBknd in admin mode", () => {
|
||||||
|
adapterTestSuite(bunTestRunner, {
|
||||||
|
makeApp: (options, args) => createBknd({ mode: "admin", options }, args).getApp(),
|
||||||
|
makeHandler: (options, args) => createBknd({ mode: "admin", options: options ?? {} }, args).serve(),
|
||||||
|
});
|
||||||
|
|
||||||
|
test("caches app instance", async () => {
|
||||||
|
const bknd = createBknd({ mode: "admin", options: { connection: { url: ":memory:" } } });
|
||||||
|
const app1 = await bknd.getApp();
|
||||||
|
const app2 = await bknd.getApp();
|
||||||
|
expect(app1).toBe(app2);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("getApi returns api", async () => {
|
||||||
|
const bknd = createBknd({ mode: "admin", options: { connection: { url: ":memory:" } } });
|
||||||
|
const api = await bknd.getApi();
|
||||||
|
expect(api).toBeDefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
test("uses createRuntimeApp in admin mode", async () => {
|
||||||
|
const bknd = createBknd({
|
||||||
|
mode: "admin",
|
||||||
|
options: {
|
||||||
|
connection: { url: ":memory:" },
|
||||||
|
adminOptions: { adminBasepath: "/admin" },
|
||||||
|
}
|
||||||
|
});
|
||||||
|
const app = await bknd.getApp();
|
||||||
|
expect(app).toBeDefined();
|
||||||
|
expect(app.isBuilt()).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("serve returns a fetch handler", async () => {
|
||||||
|
const bknd = createBknd({
|
||||||
|
mode: "admin",
|
||||||
|
options: {
|
||||||
|
connection: { url: ":memory:" },
|
||||||
|
adminOptions: { adminBasepath: "/admin" },
|
||||||
|
}
|
||||||
|
});
|
||||||
|
const handler = bknd.serve();
|
||||||
|
const res = await handler(new Request("http://localhost:3000/api/system/config"));
|
||||||
|
expect(res.status).toBe(200);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("check admin route", async () => {
|
||||||
|
const bknd = createBknd({
|
||||||
|
mode: "admin",
|
||||||
|
options: {
|
||||||
|
connection: { url: ":memory:" },
|
||||||
|
adminOptions: { adminBasepath: "/admin" },
|
||||||
|
}
|
||||||
|
});
|
||||||
|
const handler = bknd.serve();
|
||||||
|
const res = await handler(new Request("http://localhost:3000/admin"));
|
||||||
|
expect(res.status).toBe(200);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,71 @@
|
|||||||
|
import {
|
||||||
|
createFrameworkApp,
|
||||||
|
createRuntimeApp,
|
||||||
|
type FrameworkBkndConfig,
|
||||||
|
type RuntimeBkndConfig,
|
||||||
|
} from "bknd/adapter";
|
||||||
|
import { $console } from "core/utils";
|
||||||
|
import type { App } from "App";
|
||||||
|
|
||||||
|
export type AdapterModeWithOptions<Env = Record<string, string | undefined>> =
|
||||||
|
| {
|
||||||
|
/** Serves the API along with the admin UI and static assets */
|
||||||
|
mode: "admin";
|
||||||
|
options: RuntimeBkndConfig<Env>;
|
||||||
|
}
|
||||||
|
| {
|
||||||
|
/** Serves the API only, without the admin UI — use when your framework handles rendering */
|
||||||
|
mode: "headless";
|
||||||
|
options: FrameworkBkndConfig<Env>;
|
||||||
|
};
|
||||||
|
|
||||||
|
export function createBknd<Env>(config: AdapterModeWithOptions<Env>, env?: Env) {
|
||||||
|
let appPromise: Promise<App> | undefined;
|
||||||
|
|
||||||
|
const { mode, options } = config;
|
||||||
|
|
||||||
|
async function getApp(): Promise<App> {
|
||||||
|
if (!appPromise) {
|
||||||
|
if (mode === "admin") {
|
||||||
|
if (options.adminOptions && !options.serveStatic) {
|
||||||
|
$console.warn(
|
||||||
|
"adminOptions provided without serveStatic — admin UI assets may not be served. " +
|
||||||
|
"See `serveStatic`, `serveStaticViaImport`, or add a `package.json` script that runs `bknd copy-assets --out {relative_static_assets_directory_path}`.",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
appPromise = createRuntimeApp(options, env);
|
||||||
|
} else {
|
||||||
|
appPromise = createFrameworkApp(options, env);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return appPromise;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function getApi(opts?: { headers?: Headers; verify?: boolean }) {
|
||||||
|
const app = await getApp();
|
||||||
|
if (opts?.verify) {
|
||||||
|
const api = app.getApi({ headers: opts.headers });
|
||||||
|
await api.verifyAuth();
|
||||||
|
return api;
|
||||||
|
}
|
||||||
|
return app.getApi(opts?.headers ? { headers: opts.headers } : undefined);
|
||||||
|
}
|
||||||
|
|
||||||
|
function serve() {
|
||||||
|
return async (req: Request) => {
|
||||||
|
const app = await getApp();
|
||||||
|
return app.fetch(req);
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
return { getApp, getApi, serve };
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Utility type to determine the config type based on mode,
|
||||||
|
* Usage `Config<"standalone">` or `Config<"api">`
|
||||||
|
*/
|
||||||
|
export type Config<T extends AdapterModeWithOptions["mode"]> = Extract<
|
||||||
|
Parameters<typeof createBknd>[0],
|
||||||
|
{ mode: T }
|
||||||
|
>['options'];
|
||||||
+29
-1
@@ -46,6 +46,22 @@ export class AppAuth extends Module<AppAuthSchema> {
|
|||||||
to.strategies!.password!.enabled = true;
|
to.strategies!.password!.enabled = true;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (to.default_role_register && to.default_role_register?.length > 0) {
|
||||||
|
const valid_to_role = Object.keys(to.roles ?? {}).includes(to.default_role_register);
|
||||||
|
|
||||||
|
if (!valid_to_role) {
|
||||||
|
const msg = `Default role for registration not found: ${to.default_role_register}`;
|
||||||
|
// if changing to a new value
|
||||||
|
if (from.default_role_register !== to.default_role_register) {
|
||||||
|
throw new Error(msg);
|
||||||
|
}
|
||||||
|
|
||||||
|
// resetting gracefully, since role doesn't exist anymore
|
||||||
|
$console.warn(`${msg}, resetting to undefined`);
|
||||||
|
to.default_role_register = undefined;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
return to;
|
return to;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -82,6 +98,7 @@ export class AppAuth extends Module<AppAuthSchema> {
|
|||||||
this._authenticator = new Authenticator(strategies, new AppUserPool(this), {
|
this._authenticator = new Authenticator(strategies, new AppUserPool(this), {
|
||||||
jwt: this.config.jwt,
|
jwt: this.config.jwt,
|
||||||
cookie: this.config.cookie,
|
cookie: this.config.cookie,
|
||||||
|
default_role_register: this.config.default_role_register,
|
||||||
});
|
});
|
||||||
|
|
||||||
this.registerEntities();
|
this.registerEntities();
|
||||||
@@ -171,10 +188,20 @@ export class AppAuth extends Module<AppAuthSchema> {
|
|||||||
} catch (e) {}
|
} catch (e) {}
|
||||||
}
|
}
|
||||||
|
|
||||||
async createUser({ email, password, ...additional }: CreateUserPayload): Promise<DB["users"]> {
|
async createUser({
|
||||||
|
email,
|
||||||
|
password,
|
||||||
|
role,
|
||||||
|
...additional
|
||||||
|
}: CreateUserPayload): Promise<DB["users"]> {
|
||||||
if (!this.enabled) {
|
if (!this.enabled) {
|
||||||
throw new Error("Cannot create user, auth not enabled");
|
throw new Error("Cannot create user, auth not enabled");
|
||||||
}
|
}
|
||||||
|
if (role) {
|
||||||
|
if (!Object.keys(this.config.roles ?? {}).includes(role)) {
|
||||||
|
throw new Error(`Role "${role}" not found`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
const strategy = "password" as const;
|
const strategy = "password" as const;
|
||||||
const pw = this.authenticator.strategy(strategy) as PasswordStrategy;
|
const pw = this.authenticator.strategy(strategy) as PasswordStrategy;
|
||||||
@@ -183,6 +210,7 @@ export class AppAuth extends Module<AppAuthSchema> {
|
|||||||
mutator.__unstable_toggleSystemEntityCreation(false);
|
mutator.__unstable_toggleSystemEntityCreation(false);
|
||||||
const { data: created } = await mutator.insertOne({
|
const { data: created } = await mutator.insertOne({
|
||||||
...(additional as any),
|
...(additional as any),
|
||||||
|
role: role || this.config.default_role_register || undefined,
|
||||||
email,
|
email,
|
||||||
strategy,
|
strategy,
|
||||||
strategy_value,
|
strategy_value,
|
||||||
|
|||||||
@@ -13,6 +13,7 @@ import {
|
|||||||
InvalidSchemaError,
|
InvalidSchemaError,
|
||||||
transformObject,
|
transformObject,
|
||||||
mcpTool,
|
mcpTool,
|
||||||
|
$console,
|
||||||
} from "bknd/utils";
|
} from "bknd/utils";
|
||||||
import type { PasswordStrategy } from "auth/authenticate/strategies";
|
import type { PasswordStrategy } from "auth/authenticate/strategies";
|
||||||
|
|
||||||
@@ -198,7 +199,12 @@ export class AuthController extends Controller {
|
|||||||
for (const [name, strategy] of Object.entries(strategies)) {
|
for (const [name, strategy] of Object.entries(strategies)) {
|
||||||
if (!this.auth.isStrategyEnabled(strategy)) continue;
|
if (!this.auth.isStrategyEnabled(strategy)) continue;
|
||||||
|
|
||||||
hono.route(`/${name}`, strategy.getController(this.auth.authenticator));
|
hono.route(
|
||||||
|
`/${name}`,
|
||||||
|
strategy.getController(this.auth.authenticator, {
|
||||||
|
allow_register: this.auth.config.allow_register,
|
||||||
|
}),
|
||||||
|
);
|
||||||
this.registerStrategyActions(strategy, hono);
|
this.registerStrategyActions(strategy, hono);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -210,7 +216,7 @@ export class AuthController extends Controller {
|
|||||||
const idType = s.anyOf([s.number({ title: "Integer" }), s.string({ title: "UUID" })]);
|
const idType = s.anyOf([s.number({ title: "Integer" }), s.string({ title: "UUID" })]);
|
||||||
|
|
||||||
const getUser = async (params: { id?: string | number; email?: string }) => {
|
const getUser = async (params: { id?: string | number; email?: string }) => {
|
||||||
let user: DB["users"] | undefined = undefined;
|
let user: DB["users"] | undefined;
|
||||||
if (params.id) {
|
if (params.id) {
|
||||||
const { data } = await this.userRepo.findId(params.id);
|
const { data } = await this.userRepo.findId(params.id);
|
||||||
user = data;
|
user = data;
|
||||||
@@ -225,26 +231,33 @@ export class AuthController extends Controller {
|
|||||||
};
|
};
|
||||||
|
|
||||||
const roles = Object.keys(this.auth.config.roles ?? {});
|
const roles = Object.keys(this.auth.config.roles ?? {});
|
||||||
mcp.tool(
|
try {
|
||||||
"auth_user_create",
|
const actions = this.auth.authenticator.strategy("password").getActions();
|
||||||
{
|
if (actions.create) {
|
||||||
description: "Create a new user",
|
const schema = actions.create.schema;
|
||||||
inputSchema: s.object({
|
mcp.tool(
|
||||||
email: s.string({ format: "email" }),
|
"auth_user_create",
|
||||||
password: s.string({ minLength: 8 }),
|
{
|
||||||
role: s
|
description: "Create a new user",
|
||||||
.string({
|
inputSchema: s.object({
|
||||||
enum: roles.length > 0 ? roles : undefined,
|
...schema.properties,
|
||||||
})
|
role: s
|
||||||
.optional(),
|
.string({
|
||||||
}),
|
enum: roles.length > 0 ? roles : undefined,
|
||||||
},
|
})
|
||||||
async (params, c) => {
|
.optional(),
|
||||||
await c.context.ctx().helper.granted(c, AuthPermissions.createUser);
|
}),
|
||||||
|
},
|
||||||
|
async (params, c) => {
|
||||||
|
await c.context.ctx().helper.granted(c, AuthPermissions.createUser);
|
||||||
|
|
||||||
return c.json(await this.auth.createUser(params));
|
return c.json(await this.auth.createUser(params));
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
$console.warn("error creating auth_user_create tool", e);
|
||||||
|
}
|
||||||
|
|
||||||
mcp.tool(
|
mcp.tool(
|
||||||
"auth_user_token",
|
"auth_user_token",
|
||||||
@@ -297,7 +310,9 @@ export class AuthController extends Controller {
|
|||||||
await c.context.ctx().helper.granted(c, AuthPermissions.testPassword);
|
await c.context.ctx().helper.granted(c, AuthPermissions.testPassword);
|
||||||
|
|
||||||
const pw = this.auth.authenticator.strategy("password") as PasswordStrategy;
|
const pw = this.auth.authenticator.strategy("password") as PasswordStrategy;
|
||||||
const controller = pw.getController(this.auth.authenticator);
|
const controller = pw.getController(this.auth.authenticator, {
|
||||||
|
allow_register: this.auth.config.allow_register,
|
||||||
|
});
|
||||||
|
|
||||||
const res = await controller.request(
|
const res = await controller.request(
|
||||||
new Request("https://localhost/login", {
|
new Request("https://localhost/login", {
|
||||||
|
|||||||
@@ -51,6 +51,7 @@ export const authConfigSchema = $object(
|
|||||||
basepath: s.string({ default: "/api/auth" }),
|
basepath: s.string({ default: "/api/auth" }),
|
||||||
entity_name: s.string({ default: "users" }),
|
entity_name: s.string({ default: "users" }),
|
||||||
allow_register: s.boolean({ default: true }).optional(),
|
allow_register: s.boolean({ default: true }).optional(),
|
||||||
|
default_role_register: s.string().optional(),
|
||||||
jwt: jwtConfig,
|
jwt: jwtConfig,
|
||||||
cookie: cookieConfig,
|
cookie: cookieConfig,
|
||||||
strategies: $record(
|
strategies: $record(
|
||||||
|
|||||||
@@ -74,6 +74,7 @@ export const jwtConfig = s.strictObject(
|
|||||||
export const authenticatorConfig = s.object({
|
export const authenticatorConfig = s.object({
|
||||||
jwt: jwtConfig,
|
jwt: jwtConfig,
|
||||||
cookie: cookieConfig,
|
cookie: cookieConfig,
|
||||||
|
default_role_register: s.string().optional(),
|
||||||
});
|
});
|
||||||
|
|
||||||
type AuthConfig = s.Static<typeof authenticatorConfig>;
|
type AuthConfig = s.Static<typeof authenticatorConfig>;
|
||||||
@@ -164,9 +165,13 @@ export class Authenticator<
|
|||||||
if (!("strategy_value" in profile)) {
|
if (!("strategy_value" in profile)) {
|
||||||
throw new InvalidConditionsException("Profile must have a strategy value");
|
throw new InvalidConditionsException("Profile must have a strategy value");
|
||||||
}
|
}
|
||||||
|
if ("role" in profile) {
|
||||||
|
throw new InvalidConditionsException("Role cannot be provided during registration");
|
||||||
|
}
|
||||||
|
|
||||||
const user = await this.userPool.create(strategy.getName(), {
|
const user = await this.userPool.create(strategy.getName(), {
|
||||||
...profile,
|
...profile,
|
||||||
|
role: this.config.default_role_register,
|
||||||
strategy_value: profile.strategy_value,
|
strategy_value: profile.strategy_value,
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -425,7 +430,7 @@ export class Authenticator<
|
|||||||
let token: string | undefined;
|
let token: string | undefined;
|
||||||
if (headers.has("Authorization")) {
|
if (headers.has("Authorization")) {
|
||||||
const bearerHeader = String(headers.get("Authorization"));
|
const bearerHeader = String(headers.get("Authorization"));
|
||||||
token = bearerHeader.replace("Bearer ", "");
|
token = bearerHeader.replace(/^Bearer\s+/i, "");
|
||||||
} else {
|
} else {
|
||||||
const context = is_context ? (c as Context) : ({ req: { raw: { headers } } } as Context);
|
const context = is_context ? (c as Context) : ({ req: { raw: { headers } } } as Context);
|
||||||
token = await this.getAuthCookie(context);
|
token = await this.getAuthCookie(context);
|
||||||
|
|||||||
@@ -10,6 +10,7 @@ const schema = s
|
|||||||
.object({
|
.object({
|
||||||
hashing: s.string({ enum: ["plain", "sha256", "bcrypt"], default: "sha256" }),
|
hashing: s.string({ enum: ["plain", "sha256", "bcrypt"], default: "sha256" }),
|
||||||
rounds: s.number({ minimum: 1, maximum: 10 }).optional(),
|
rounds: s.number({ minimum: 1, maximum: 10 }).optional(),
|
||||||
|
minLength: s.number({ default: 8, minimum: 1 }).optional(),
|
||||||
})
|
})
|
||||||
.strict();
|
.strict();
|
||||||
|
|
||||||
@@ -37,7 +38,7 @@ export class PasswordStrategy extends AuthStrategy<typeof schema> {
|
|||||||
format: "email",
|
format: "email",
|
||||||
}),
|
}),
|
||||||
password: s.string({
|
password: s.string({
|
||||||
minLength: 8, // @todo: this should be configurable
|
minLength: this.config.minLength,
|
||||||
}),
|
}),
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -65,19 +66,28 @@ export class PasswordStrategy extends AuthStrategy<typeof schema> {
|
|||||||
return await bcryptCompare(compare, actual);
|
return await bcryptCompare(compare, actual);
|
||||||
}
|
}
|
||||||
|
|
||||||
return false;
|
return actual === compare;
|
||||||
}
|
}
|
||||||
|
|
||||||
verify(password: string) {
|
verify(password: string) {
|
||||||
return async (user: User) => {
|
return async (user: User) => {
|
||||||
const compare = await this.compare(user?.strategy_value!, password);
|
if (!user || !user.strategy_value) {
|
||||||
|
throw new InvalidCredentialsException();
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!this.getPayloadSchema().properties.password.validate(password).valid) {
|
||||||
|
$console.debug("PasswordStrategy: Invalid password", password);
|
||||||
|
throw new InvalidCredentialsException();
|
||||||
|
}
|
||||||
|
|
||||||
|
const compare = await this.compare(user.strategy_value, password);
|
||||||
if (compare !== true) {
|
if (compare !== true) {
|
||||||
throw new InvalidCredentialsException();
|
throw new InvalidCredentialsException();
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
getController(authenticator: Authenticator): Hono<any> {
|
getController(authenticator: Authenticator, opts: { allow_register?: boolean }): Hono<any> {
|
||||||
const hono = new Hono();
|
const hono = new Hono();
|
||||||
const redirectQuerySchema = s.object({
|
const redirectQuerySchema = s.object({
|
||||||
redirect: s.string().optional(),
|
redirect: s.string().optional(),
|
||||||
@@ -110,41 +120,43 @@ export class PasswordStrategy extends AuthStrategy<typeof schema> {
|
|||||||
},
|
},
|
||||||
);
|
);
|
||||||
|
|
||||||
hono.post(
|
if (opts.allow_register) {
|
||||||
"/register",
|
hono.post(
|
||||||
describeRoute({
|
"/register",
|
||||||
summary: "Register a new user with email and password",
|
describeRoute({
|
||||||
tags: ["auth"],
|
summary: "Register a new user with email and password",
|
||||||
}),
|
tags: ["auth"],
|
||||||
jsc("query", redirectQuerySchema),
|
}),
|
||||||
async (c) => {
|
jsc("query", redirectQuerySchema),
|
||||||
try {
|
async (c) => {
|
||||||
const { redirect } = c.req.valid("query");
|
try {
|
||||||
const { password, email, ...body } = parse(
|
const { redirect } = c.req.valid("query");
|
||||||
payloadSchema,
|
const { password, email, ...body } = parse(
|
||||||
await authenticator.getBody(c),
|
payloadSchema,
|
||||||
{
|
await authenticator.getBody(c),
|
||||||
onError: (errors) => {
|
{
|
||||||
$console.error("Invalid register payload", [...errors]);
|
onError: (errors) => {
|
||||||
new InvalidCredentialsException();
|
$console.error("Invalid register payload", [...errors]);
|
||||||
|
new InvalidCredentialsException();
|
||||||
|
},
|
||||||
},
|
},
|
||||||
},
|
);
|
||||||
);
|
|
||||||
|
|
||||||
const profile = {
|
const profile = {
|
||||||
...body,
|
...body,
|
||||||
email,
|
email,
|
||||||
strategy_value: await this.hash(password),
|
strategy_value: await this.hash(password),
|
||||||
};
|
};
|
||||||
|
|
||||||
return await authenticator.resolveRegister(c, this, profile, async () => void 0, {
|
return await authenticator.resolveRegister(c, this, profile, async () => void 0, {
|
||||||
redirect,
|
redirect,
|
||||||
});
|
});
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
return authenticator.respondWithError(c, e as any);
|
return authenticator.respondWithError(c, e as any);
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
|
}
|
||||||
|
|
||||||
return hono;
|
return hono;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -36,7 +36,7 @@ export abstract class AuthStrategy<Schema extends s.Schema = s.Schema> {
|
|||||||
|
|
||||||
protected abstract getSchema(): Schema;
|
protected abstract getSchema(): Schema;
|
||||||
|
|
||||||
abstract getController(auth: Authenticator): Hono;
|
abstract getController(auth: Authenticator, opts: { allow_register?: boolean }): Hono;
|
||||||
|
|
||||||
getType(): string {
|
getType(): string {
|
||||||
return this.type;
|
return this.type;
|
||||||
|
|||||||
@@ -284,7 +284,7 @@ export class OAuthStrategy extends AuthStrategy<typeof schemaProvided> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
getController(auth: Authenticator): Hono<any> {
|
getController(auth: Authenticator, opts: { allow_register?: boolean }): Hono<any> {
|
||||||
const hono = new Hono();
|
const hono = new Hono();
|
||||||
const secret = "secret";
|
const secret = "secret";
|
||||||
const cookie_name = "_challenge";
|
const cookie_name = "_challenge";
|
||||||
@@ -379,6 +379,10 @@ export class OAuthStrategy extends AuthStrategy<typeof schemaProvided> {
|
|||||||
return c.notFound();
|
return c.notFound();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (action === "register" && !opts.allow_register) {
|
||||||
|
return c.notFound();
|
||||||
|
}
|
||||||
|
|
||||||
const url = new URL(c.req.url);
|
const url = new URL(c.req.url);
|
||||||
const path = url.pathname.replace(`/${action}`, "");
|
const path = url.pathname.replace(`/${action}`, "");
|
||||||
const redirect_uri = url.origin + path + "/callback";
|
const redirect_uri = url.origin + path + "/callback";
|
||||||
|
|||||||
@@ -67,7 +67,10 @@ export async function startServer(
|
|||||||
$console.info("Server listening on", url);
|
$console.info("Server listening on", url);
|
||||||
|
|
||||||
if (options.open) {
|
if (options.open) {
|
||||||
await open(url);
|
const p = await open(url, { wait: false });
|
||||||
|
p.on("error", () => {
|
||||||
|
$console.warn("Couldn't open url in browser");
|
||||||
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -21,46 +21,47 @@ export const sync: CliCommand = (program) => {
|
|||||||
console.info("");
|
console.info("");
|
||||||
if (stmts.length === 0) {
|
if (stmts.length === 0) {
|
||||||
console.info(c.yellow("No changes to sync"));
|
console.info(c.yellow("No changes to sync"));
|
||||||
process.exit(0);
|
} else {
|
||||||
}
|
// @todo: currently assuming parameters aren't used
|
||||||
// @todo: currently assuming parameters aren't used
|
const sql = stmts.map((d) => d.sql).join(";\n") + ";";
|
||||||
const sql = stmts.map((d) => d.sql).join(";\n") + ";";
|
|
||||||
|
|
||||||
if (options.force) {
|
if (options.force) {
|
||||||
console.info(c.dim("Executing:") + "\n" + c.cyan(sql));
|
console.info(c.dim("Executing:") + "\n" + c.cyan(sql));
|
||||||
await schema.sync({ force: true, drop: options.drop });
|
await schema.sync({ force: true, drop: options.drop });
|
||||||
|
|
||||||
console.info(`\n${c.dim(`Executed ${c.cyan(stmts.length)} statement(s)`)}`);
|
console.info(`\n${c.dim(`Executed ${c.cyan(stmts.length)} statement(s)`)}`);
|
||||||
console.info(`${c.green("Database synced")}`);
|
console.info(`${c.green("Database synced")}`);
|
||||||
|
} else {
|
||||||
if (options.seed) {
|
if (options.out) {
|
||||||
console.info(c.dim("\nExecuting seed..."));
|
const output = options.sql ? sql : JSON.stringify(stmts, null, 2);
|
||||||
const seed = app.options?.seed;
|
await writeFile(options.out, output);
|
||||||
if (seed) {
|
console.info(`SQL written to ${c.cyan(options.out)}`);
|
||||||
await app.options?.seed?.({
|
|
||||||
...app.modules.ctx(),
|
|
||||||
app: app,
|
|
||||||
});
|
|
||||||
console.info(c.green("Seed executed"));
|
|
||||||
} else {
|
} else {
|
||||||
console.info(c.yellow("No seed function provided"));
|
console.info(c.dim("DDL to execute:") + "\n" + c.cyan(sql));
|
||||||
|
|
||||||
|
console.info(
|
||||||
|
c.yellow(
|
||||||
|
"\nNo statements have been executed. Use --force to perform database syncing operations",
|
||||||
|
),
|
||||||
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} else {
|
}
|
||||||
if (options.out) {
|
|
||||||
const output = options.sql ? sql : JSON.stringify(stmts, null, 2);
|
|
||||||
await writeFile(options.out, output);
|
|
||||||
console.info(`SQL written to ${c.cyan(options.out)}`);
|
|
||||||
} else {
|
|
||||||
console.info(c.dim("DDL to execute:") + "\n" + c.cyan(sql));
|
|
||||||
|
|
||||||
console.info(
|
if (options.seed) {
|
||||||
c.yellow(
|
console.info(c.dim("\nExecuting seed..."));
|
||||||
"\nNo statements have been executed. Use --force to perform database syncing operations",
|
const seed = app.options?.seed;
|
||||||
),
|
if (seed) {
|
||||||
);
|
await seed({
|
||||||
|
...app.modules.ctx(),
|
||||||
|
app: app,
|
||||||
|
});
|
||||||
|
console.info(c.green("Seed executed"));
|
||||||
|
} else {
|
||||||
|
console.info(c.yellow("No seed function provided"));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
process.exit(0);
|
process.exit(0);
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -0,0 +1,55 @@
|
|||||||
|
import { describe, it, expect } from "bun:test";
|
||||||
|
import { plunkEmail } from "./plunk";
|
||||||
|
|
||||||
|
const ALL_TESTS = !!process.env.ALL_TESTS;
|
||||||
|
|
||||||
|
describe.skipIf(ALL_TESTS)("plunk", () => {
|
||||||
|
it("should throw on failed", async () => {
|
||||||
|
const driver = plunkEmail({ apiKey: "invalid" });
|
||||||
|
expect(driver.send("foo@bar.com", "Test", "Test")).rejects.toThrow();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("should send an email", async () => {
|
||||||
|
const driver = plunkEmail({
|
||||||
|
apiKey: process.env.PLUNK_API_KEY!,
|
||||||
|
from: undefined, // Default to what Plunk sets
|
||||||
|
});
|
||||||
|
const response = await driver.send(
|
||||||
|
"help@bknd.io",
|
||||||
|
"Test Email from Plunk",
|
||||||
|
"This is a test email",
|
||||||
|
);
|
||||||
|
expect(response).toBeDefined();
|
||||||
|
expect(response.success).toBe(true);
|
||||||
|
expect(response.emails).toBeDefined();
|
||||||
|
expect(response.timestamp).toBeDefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("should send HTML email", async () => {
|
||||||
|
const driver = plunkEmail({
|
||||||
|
apiKey: process.env.PLUNK_API_KEY!,
|
||||||
|
from: undefined,
|
||||||
|
});
|
||||||
|
const htmlBody = "<h1>Test Email</h1><p>This is a test email</p>";
|
||||||
|
const response = await driver.send(
|
||||||
|
"help@bknd.io",
|
||||||
|
"HTML Test",
|
||||||
|
htmlBody,
|
||||||
|
);
|
||||||
|
expect(response).toBeDefined();
|
||||||
|
expect(response.success).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("should send with text and html", async () => {
|
||||||
|
const driver = plunkEmail({
|
||||||
|
apiKey: process.env.PLUNK_API_KEY!,
|
||||||
|
from: undefined,
|
||||||
|
});
|
||||||
|
const response = await driver.send("test@example.com", "Test Email", {
|
||||||
|
text: "help@bknd.io",
|
||||||
|
html: "<p>This is HTML</p>",
|
||||||
|
});
|
||||||
|
expect(response).toBeDefined();
|
||||||
|
expect(response.success).toBe(true);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,70 @@
|
|||||||
|
import type { IEmailDriver } from "./index";
|
||||||
|
|
||||||
|
export type PlunkEmailOptions = {
|
||||||
|
apiKey: string;
|
||||||
|
host?: string;
|
||||||
|
from?: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type PlunkEmailSendOptions = {
|
||||||
|
subscribed?: boolean;
|
||||||
|
name?: string;
|
||||||
|
from?: string;
|
||||||
|
reply?: string;
|
||||||
|
headers?: Record<string, string>;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type PlunkEmailResponse = {
|
||||||
|
success: boolean;
|
||||||
|
emails: Array<{
|
||||||
|
contact: {
|
||||||
|
id: string;
|
||||||
|
email: string;
|
||||||
|
};
|
||||||
|
email: string;
|
||||||
|
}>;
|
||||||
|
timestamp: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
export const plunkEmail = (
|
||||||
|
config: PlunkEmailOptions,
|
||||||
|
): IEmailDriver<PlunkEmailResponse, PlunkEmailSendOptions> => {
|
||||||
|
const host = config.host ?? "https://api.useplunk.com/v1/send";
|
||||||
|
const from = config.from;
|
||||||
|
|
||||||
|
return {
|
||||||
|
send: async (
|
||||||
|
to: string,
|
||||||
|
subject: string,
|
||||||
|
body: string | { text: string; html: string },
|
||||||
|
options?: PlunkEmailSendOptions,
|
||||||
|
) => {
|
||||||
|
const payload: any = {
|
||||||
|
from,
|
||||||
|
to,
|
||||||
|
subject,
|
||||||
|
};
|
||||||
|
|
||||||
|
if (typeof body === "string") {
|
||||||
|
payload.body = body;
|
||||||
|
} else {
|
||||||
|
payload.body = body.html;
|
||||||
|
}
|
||||||
|
|
||||||
|
const res = await fetch(host, {
|
||||||
|
method: "POST",
|
||||||
|
headers: {
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
Authorization: `Bearer ${config.apiKey}`,
|
||||||
|
},
|
||||||
|
body: JSON.stringify({ ...payload, ...options }),
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!res.ok) {
|
||||||
|
throw new Error(`Plunk API error: ${await res.text()}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
return (await res.json()) as PlunkEmailResponse;
|
||||||
|
},
|
||||||
|
};
|
||||||
|
};
|
||||||
@@ -4,7 +4,7 @@ import { resendEmail } from "./resend";
|
|||||||
const ALL_TESTS = !!process.env.ALL_TESTS;
|
const ALL_TESTS = !!process.env.ALL_TESTS;
|
||||||
|
|
||||||
describe.skipIf(ALL_TESTS)("resend", () => {
|
describe.skipIf(ALL_TESTS)("resend", () => {
|
||||||
it.only("should throw on failed", async () => {
|
it("should throw on failed", async () => {
|
||||||
const driver = resendEmail({ apiKey: "invalid" } as any);
|
const driver = resendEmail({ apiKey: "invalid" } as any);
|
||||||
expect(driver.send("foo@bar.com", "Test", "Test")).rejects.toThrow();
|
expect(driver.send("foo@bar.com", "Test", "Test")).rejects.toThrow();
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -5,3 +5,4 @@ export type { IEmailDriver } from "./email";
|
|||||||
export { resendEmail } from "./email/resend";
|
export { resendEmail } from "./email/resend";
|
||||||
export { sesEmail } from "./email/ses";
|
export { sesEmail } from "./email/ses";
|
||||||
export { mailchannelsEmail } from "./email/mailchannels";
|
export { mailchannelsEmail } from "./email/mailchannels";
|
||||||
|
export { plunkEmail } from "./email/plunk";
|
||||||
|
|||||||
+1
-1
@@ -8,7 +8,7 @@ export function isDebug(): boolean {
|
|||||||
try {
|
try {
|
||||||
// @ts-expect-error - this is a global variable in dev
|
// @ts-expect-error - this is a global variable in dev
|
||||||
return is_toggled(__isDev);
|
return is_toggled(__isDev);
|
||||||
} catch (e) {
|
} catch (_e) {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
import type { MaybePromise } from "bknd";
|
||||||
import type { Event } from "./Event";
|
import type { Event } from "./Event";
|
||||||
import type { EventClass } from "./EventManager";
|
import type { EventClass } from "./EventManager";
|
||||||
|
|
||||||
@@ -7,7 +8,7 @@ export type ListenerMode = (typeof ListenerModes)[number];
|
|||||||
export type ListenerHandler<E extends Event<any, any>> = (
|
export type ListenerHandler<E extends Event<any, any>> = (
|
||||||
event: E,
|
event: E,
|
||||||
slug: string,
|
slug: string,
|
||||||
) => E extends Event<any, infer R> ? R | Promise<R | void> : never;
|
) => E extends Event<any, infer R> ? MaybePromise<R | void> : never;
|
||||||
|
|
||||||
export class EventListener<E extends Event = Event> {
|
export class EventListener<E extends Event = Event> {
|
||||||
mode: ListenerMode = "async";
|
mode: ListenerMode = "async";
|
||||||
|
|||||||
@@ -32,6 +32,7 @@ export function getFlashMessage(
|
|||||||
): { type: FlashMessageType; message: string } | undefined {
|
): { type: FlashMessageType; message: string } | undefined {
|
||||||
const flash = getCookieValue(flash_key);
|
const flash = getCookieValue(flash_key);
|
||||||
if (flash && clear) {
|
if (flash && clear) {
|
||||||
|
// biome-ignore lint/suspicious/noDocumentCookie: .
|
||||||
document.cookie = `${flash_key}=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;`;
|
document.cookie = `${flash_key}=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;`;
|
||||||
}
|
}
|
||||||
return flash ? JSON.parse(flash) : undefined;
|
return flash ? JSON.parse(flash) : undefined;
|
||||||
|
|||||||
@@ -14,9 +14,9 @@ export function isObject(value: unknown): value is Record<string, unknown> {
|
|||||||
|
|
||||||
export function omitKeys<T extends object, K extends keyof T>(
|
export function omitKeys<T extends object, K extends keyof T>(
|
||||||
obj: T,
|
obj: T,
|
||||||
keys_: readonly K[],
|
keys_: readonly K[] | K[] | string[],
|
||||||
): Omit<T, Extract<K, keyof T>> {
|
): Omit<T, Extract<K, keyof T>> {
|
||||||
const keys = new Set(keys_);
|
const keys = new Set(keys_ as readonly K[]);
|
||||||
const result = {} as Omit<T, Extract<K, keyof T>>;
|
const result = {} as Omit<T, Extract<K, keyof T>>;
|
||||||
for (const [key, value] of Object.entries(obj) as [keyof T, T[keyof T]][]) {
|
for (const [key, value] of Object.entries(obj) as [keyof T, T[keyof T]][]) {
|
||||||
if (!keys.has(key as K)) {
|
if (!keys.has(key as K)) {
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
import type { MaybePromise } from "core/types";
|
||||||
import { getRuntimeKey as honoGetRuntimeKey } from "hono/adapter";
|
import { getRuntimeKey as honoGetRuntimeKey } from "hono/adapter";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -77,3 +78,37 @@ export function threw(fn: () => any, instance?: new (...args: any[]) => Error) {
|
|||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export async function threwAsync(fn: Promise<any>, instance?: new (...args: any[]) => Error) {
|
||||||
|
try {
|
||||||
|
await fn;
|
||||||
|
return false;
|
||||||
|
} catch (e) {
|
||||||
|
if (instance) {
|
||||||
|
if (e instanceof instance) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
// if instance given but not what expected, throw
|
||||||
|
throw e;
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function $waitUntil(
|
||||||
|
message: string,
|
||||||
|
condition: () => MaybePromise<boolean>,
|
||||||
|
delay = 100,
|
||||||
|
maxAttempts = 10,
|
||||||
|
) {
|
||||||
|
let attempts = 0;
|
||||||
|
while (attempts < maxAttempts) {
|
||||||
|
if (await condition()) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
await new Promise((resolve) => setTimeout(resolve, delay));
|
||||||
|
attempts++;
|
||||||
|
}
|
||||||
|
|
||||||
|
throw new Error(`$waitUntil: "${message}" failed after ${maxAttempts} attempts`);
|
||||||
|
}
|
||||||
|
|||||||
@@ -120,17 +120,14 @@ export function patternMatch(target: string, pattern: RegExp | string): boolean
|
|||||||
}
|
}
|
||||||
|
|
||||||
export function slugify(str: string): string {
|
export function slugify(str: string): string {
|
||||||
return (
|
return String(str)
|
||||||
String(str)
|
.normalize("NFKD") // split accented characters into their base characters and diacritical marks
|
||||||
.normalize("NFKD") // split accented characters into their base characters and diacritical marks
|
.replace(/[\u0300-\u036f]/g, "") // remove all the accents, which happen to be all in the \u03xx UNICODE block.
|
||||||
// biome-ignore lint/suspicious/noMisleadingCharacterClass: <explanation>
|
.trim() // trim leading or trailing whitespace
|
||||||
.replace(/[\u0300-\u036f]/g, "") // remove all the accents, which happen to be all in the \u03xx UNICODE block.
|
.toLowerCase() // convert to lowercase
|
||||||
.trim() // trim leading or trailing whitespace
|
.replace(/[^a-z0-9 -]/g, "") // remove non-alphanumeric characters
|
||||||
.toLowerCase() // convert to lowercase
|
.replace(/\s+/g, "-") // replace spaces with hyphens
|
||||||
.replace(/[^a-z0-9 -]/g, "") // remove non-alphanumeric characters
|
.replace(/-+/g, "-"); // remove consecutive hyphens
|
||||||
.replace(/\s+/g, "-") // replace spaces with hyphens
|
|
||||||
.replace(/-+/g, "-") // remove consecutive hyphens
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export function truncate(str: string, length = 50, end = "..."): string {
|
export function truncate(str: string, length = 50, end = "..."): string {
|
||||||
|
|||||||
@@ -96,6 +96,9 @@ export class DataController extends Controller {
|
|||||||
// read entity schema
|
// read entity schema
|
||||||
hono.get(
|
hono.get(
|
||||||
"/schema.json",
|
"/schema.json",
|
||||||
|
permission(SystemPermissions.schemaRead, {
|
||||||
|
context: (_c) => ({ module: "data" }),
|
||||||
|
}),
|
||||||
permission(DataPermissions.entityRead, {
|
permission(DataPermissions.entityRead, {
|
||||||
context: (c) => ({ entity: c.req.param("entity") }),
|
context: (c) => ({ entity: c.req.param("entity") }),
|
||||||
}),
|
}),
|
||||||
@@ -124,6 +127,9 @@ export class DataController extends Controller {
|
|||||||
// read schema
|
// read schema
|
||||||
hono.get(
|
hono.get(
|
||||||
"/schemas/:entity/:context?",
|
"/schemas/:entity/:context?",
|
||||||
|
permission(SystemPermissions.schemaRead, {
|
||||||
|
context: (_c) => ({ module: "data" }),
|
||||||
|
}),
|
||||||
permission(DataPermissions.entityRead, {
|
permission(DataPermissions.entityRead, {
|
||||||
context: (c) => ({ entity: c.req.param("entity") }),
|
context: (c) => ({ entity: c.req.param("entity") }),
|
||||||
}),
|
}),
|
||||||
@@ -161,7 +167,7 @@ export class DataController extends Controller {
|
|||||||
hono.get(
|
hono.get(
|
||||||
"/types",
|
"/types",
|
||||||
permission(SystemPermissions.schemaRead, {
|
permission(SystemPermissions.schemaRead, {
|
||||||
context: (c) => ({ module: "data" }),
|
context: (_c) => ({ module: "data" }),
|
||||||
}),
|
}),
|
||||||
describeRoute({
|
describeRoute({
|
||||||
summary: "Retrieve data typescript definitions",
|
summary: "Retrieve data typescript definitions",
|
||||||
@@ -182,6 +188,9 @@ export class DataController extends Controller {
|
|||||||
*/
|
*/
|
||||||
hono.get(
|
hono.get(
|
||||||
"/info/:entity",
|
"/info/:entity",
|
||||||
|
permission(SystemPermissions.schemaRead, {
|
||||||
|
context: (_c) => ({ module: "data" }),
|
||||||
|
}),
|
||||||
permission(DataPermissions.entityRead, {
|
permission(DataPermissions.entityRead, {
|
||||||
context: (c) => ({ entity: c.req.param("entity") }),
|
context: (c) => ({ entity: c.req.param("entity") }),
|
||||||
}),
|
}),
|
||||||
|
|||||||
@@ -6,17 +6,15 @@ import {
|
|||||||
type CompiledQuery,
|
type CompiledQuery,
|
||||||
type DatabaseIntrospector,
|
type DatabaseIntrospector,
|
||||||
type Dialect,
|
type Dialect,
|
||||||
type Expression,
|
|
||||||
type Kysely,
|
type Kysely,
|
||||||
type KyselyPlugin,
|
type KyselyPlugin,
|
||||||
type OnModifyForeignAction,
|
type OnModifyForeignAction,
|
||||||
type QueryResult,
|
type QueryResult,
|
||||||
type RawBuilder,
|
|
||||||
type SelectQueryBuilder,
|
type SelectQueryBuilder,
|
||||||
type SelectQueryNode,
|
type SelectQueryNode,
|
||||||
type Simplify,
|
|
||||||
sql,
|
sql,
|
||||||
} from "kysely";
|
} from "kysely";
|
||||||
|
import type { jsonArrayFrom, jsonBuildObject, jsonObjectFrom } from "kysely/helpers/sqlite";
|
||||||
import type { BaseIntrospector, BaseIntrospectorConfig } from "./BaseIntrospector";
|
import type { BaseIntrospector, BaseIntrospectorConfig } from "./BaseIntrospector";
|
||||||
import type { DB } from "bknd";
|
import type { DB } from "bknd";
|
||||||
import type { Constructor } from "core/registry/Registry";
|
import type { Constructor } from "core/registry/Registry";
|
||||||
@@ -70,15 +68,9 @@ export type IndexSpec = {
|
|||||||
};
|
};
|
||||||
|
|
||||||
export type DbFunctions = {
|
export type DbFunctions = {
|
||||||
jsonObjectFrom<O>(expr: SelectQueryBuilderExpression<O>): RawBuilder<Simplify<O> | null>;
|
jsonObjectFrom: typeof jsonObjectFrom;
|
||||||
jsonArrayFrom<O>(expr: SelectQueryBuilderExpression<O>): RawBuilder<Simplify<O>[]>;
|
jsonArrayFrom: typeof jsonArrayFrom;
|
||||||
jsonBuildObject<O extends Record<string, Expression<unknown>>>(
|
jsonBuildObject: typeof jsonBuildObject;
|
||||||
obj: O,
|
|
||||||
): RawBuilder<
|
|
||||||
Simplify<{
|
|
||||||
[K in keyof O]: O[K] extends Expression<infer V> ? V : never;
|
|
||||||
}>
|
|
||||||
>;
|
|
||||||
};
|
};
|
||||||
|
|
||||||
export type ConnQuery = CompiledQuery | Compilable;
|
export type ConnQuery = CompiledQuery | Compilable;
|
||||||
|
|||||||
@@ -14,27 +14,31 @@ export function connectionTestSuite(
|
|||||||
{
|
{
|
||||||
makeConnection,
|
makeConnection,
|
||||||
rawDialectDetails,
|
rawDialectDetails,
|
||||||
|
disableConsoleLog: _disableConsoleLog = true,
|
||||||
}: {
|
}: {
|
||||||
makeConnection: () => MaybePromise<{
|
makeConnection: () => MaybePromise<{
|
||||||
connection: Connection;
|
connection: Connection;
|
||||||
dispose: () => MaybePromise<void>;
|
dispose: () => MaybePromise<void>;
|
||||||
}>;
|
}>;
|
||||||
rawDialectDetails: string[];
|
rawDialectDetails: string[];
|
||||||
|
disableConsoleLog?: boolean;
|
||||||
},
|
},
|
||||||
) {
|
) {
|
||||||
const { test, expect, describe, beforeEach, afterEach, afterAll, beforeAll } = testRunner;
|
const { test, expect, describe, beforeEach, afterEach, afterAll, beforeAll } = testRunner;
|
||||||
beforeAll(() => disableConsoleLog());
|
if (_disableConsoleLog) {
|
||||||
afterAll(() => enableConsoleLog());
|
beforeAll(() => disableConsoleLog());
|
||||||
|
afterAll(() => enableConsoleLog());
|
||||||
|
}
|
||||||
|
|
||||||
describe("base", () => {
|
let ctx: Awaited<ReturnType<typeof makeConnection>>;
|
||||||
let ctx: Awaited<ReturnType<typeof makeConnection>>;
|
beforeEach(async () => {
|
||||||
beforeEach(async () => {
|
ctx = await makeConnection();
|
||||||
ctx = await makeConnection();
|
});
|
||||||
});
|
afterEach(async () => {
|
||||||
afterEach(async () => {
|
await ctx.dispose();
|
||||||
await ctx.dispose();
|
});
|
||||||
});
|
|
||||||
|
|
||||||
|
describe("base", async () => {
|
||||||
test("pings", async () => {
|
test("pings", async () => {
|
||||||
const res = await ctx.connection.ping();
|
const res = await ctx.connection.ping();
|
||||||
expect(res).toBe(true);
|
expect(res).toBe(true);
|
||||||
@@ -98,52 +102,54 @@ export function connectionTestSuite(
|
|||||||
});
|
});
|
||||||
|
|
||||||
describe("schema", async () => {
|
describe("schema", async () => {
|
||||||
const { connection, dispose } = await makeConnection();
|
const makeSchema = async () => {
|
||||||
afterAll(async () => {
|
const fields = [
|
||||||
await dispose();
|
{
|
||||||
});
|
type: "integer",
|
||||||
|
name: "id",
|
||||||
|
primary: true,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
type: "text",
|
||||||
|
name: "text",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
type: "json",
|
||||||
|
name: "json",
|
||||||
|
},
|
||||||
|
] as const satisfies FieldSpec[];
|
||||||
|
|
||||||
const fields = [
|
let b = ctx.connection.kysely.schema.createTable("test");
|
||||||
{
|
for (const field of fields) {
|
||||||
type: "integer",
|
// @ts-expect-error
|
||||||
name: "id",
|
b = b.addColumn(...ctx.connection.getFieldSchema(field));
|
||||||
primary: true,
|
}
|
||||||
},
|
await b.execute();
|
||||||
{
|
|
||||||
type: "text",
|
|
||||||
name: "text",
|
|
||||||
},
|
|
||||||
{
|
|
||||||
type: "json",
|
|
||||||
name: "json",
|
|
||||||
},
|
|
||||||
] as const satisfies FieldSpec[];
|
|
||||||
|
|
||||||
let b = connection.kysely.schema.createTable("test");
|
// add index
|
||||||
for (const field of fields) {
|
await ctx.connection.kysely.schema
|
||||||
// @ts-expect-error
|
.createIndex("test_index")
|
||||||
b = b.addColumn(...connection.getFieldSchema(field));
|
.on("test")
|
||||||
}
|
.columns(["id"])
|
||||||
await b.execute();
|
.execute();
|
||||||
|
};
|
||||||
// add index
|
|
||||||
await connection.kysely.schema.createIndex("test_index").on("test").columns(["id"]).execute();
|
|
||||||
|
|
||||||
test("executes query", async () => {
|
test("executes query", async () => {
|
||||||
await connection.kysely
|
await makeSchema();
|
||||||
|
await ctx.connection.kysely
|
||||||
.insertInto("test")
|
.insertInto("test")
|
||||||
.values({ id: 1, text: "test", json: JSON.stringify({ a: 1 }) })
|
.values({ id: 1, text: "test", json: JSON.stringify({ a: 1 }) })
|
||||||
.execute();
|
.execute();
|
||||||
|
|
||||||
const expected = { id: 1, text: "test", json: { a: 1 } };
|
const expected = { id: 1, text: "test", json: { a: 1 } };
|
||||||
|
|
||||||
const qb = connection.kysely.selectFrom("test").selectAll();
|
const qb = ctx.connection.kysely.selectFrom("test").selectAll();
|
||||||
const res = await connection.executeQuery(qb);
|
const res = await ctx.connection.executeQuery(qb);
|
||||||
expect(res.rows).toEqual([expected]);
|
expect(res.rows).toEqual([expected]);
|
||||||
expect(rawDialectDetails.every((detail) => getPath(res, detail) !== undefined)).toBe(true);
|
expect(rawDialectDetails.every((detail) => getPath(res, detail) !== undefined)).toBe(true);
|
||||||
|
|
||||||
{
|
{
|
||||||
const res = await connection.executeQueries(qb, qb);
|
const res = await ctx.connection.executeQueries(qb, qb);
|
||||||
expect(res.length).toBe(2);
|
expect(res.length).toBe(2);
|
||||||
res.map((r) => {
|
res.map((r) => {
|
||||||
expect(r.rows).toEqual([expected]);
|
expect(r.rows).toEqual([expected]);
|
||||||
@@ -155,15 +161,21 @@ export function connectionTestSuite(
|
|||||||
});
|
});
|
||||||
|
|
||||||
test("introspects", async () => {
|
test("introspects", async () => {
|
||||||
const tables = await connection.getIntrospector().getTables({
|
await makeSchema();
|
||||||
|
const tables = await ctx.connection.getIntrospector().getTables({
|
||||||
withInternalKyselyTables: false,
|
withInternalKyselyTables: false,
|
||||||
});
|
});
|
||||||
const clean = tables.map((t) => ({
|
const clean = tables.map((t) => ({
|
||||||
...t,
|
...t,
|
||||||
columns: t.columns.map((c) => ({
|
columns: t.columns
|
||||||
...c,
|
.map((c) => ({
|
||||||
dataType: undefined,
|
...c,
|
||||||
})),
|
// ignore data type
|
||||||
|
dataType: undefined,
|
||||||
|
// ignore default value if "id"
|
||||||
|
hasDefaultValue: c.name !== "id" ? c.hasDefaultValue : undefined,
|
||||||
|
}))
|
||||||
|
.sort((a, b) => a.name.localeCompare(b.name)),
|
||||||
}));
|
}));
|
||||||
|
|
||||||
expect(clean).toEqual([
|
expect(clean).toEqual([
|
||||||
@@ -176,14 +188,8 @@ export function connectionTestSuite(
|
|||||||
dataType: undefined,
|
dataType: undefined,
|
||||||
isNullable: false,
|
isNullable: false,
|
||||||
isAutoIncrementing: true,
|
isAutoIncrementing: true,
|
||||||
hasDefaultValue: false,
|
hasDefaultValue: undefined,
|
||||||
},
|
comment: undefined,
|
||||||
{
|
|
||||||
name: "text",
|
|
||||||
dataType: undefined,
|
|
||||||
isNullable: true,
|
|
||||||
isAutoIncrementing: false,
|
|
||||||
hasDefaultValue: false,
|
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
name: "json",
|
name: "json",
|
||||||
@@ -191,25 +197,34 @@ export function connectionTestSuite(
|
|||||||
isNullable: true,
|
isNullable: true,
|
||||||
isAutoIncrementing: false,
|
isAutoIncrementing: false,
|
||||||
hasDefaultValue: false,
|
hasDefaultValue: false,
|
||||||
|
comment: undefined,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "text",
|
||||||
|
dataType: undefined,
|
||||||
|
isNullable: true,
|
||||||
|
isAutoIncrementing: false,
|
||||||
|
hasDefaultValue: false,
|
||||||
|
comment: undefined,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
]);
|
||||||
|
|
||||||
|
expect(await ctx.connection.getIntrospector().getIndices()).toEqual([
|
||||||
|
{
|
||||||
|
name: "test_index",
|
||||||
|
table: "test",
|
||||||
|
isUnique: false,
|
||||||
|
columns: [
|
||||||
|
{
|
||||||
|
name: "id",
|
||||||
|
order: 0,
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
]);
|
]);
|
||||||
});
|
});
|
||||||
|
|
||||||
expect(await connection.getIntrospector().getIndices()).toEqual([
|
|
||||||
{
|
|
||||||
name: "test_index",
|
|
||||||
table: "test",
|
|
||||||
isUnique: false,
|
|
||||||
columns: [
|
|
||||||
{
|
|
||||||
name: "id",
|
|
||||||
order: 0,
|
|
||||||
},
|
|
||||||
],
|
|
||||||
},
|
|
||||||
]);
|
|
||||||
});
|
});
|
||||||
|
|
||||||
describe("integration", async () => {
|
describe("integration", async () => {
|
||||||
|
|||||||
@@ -0,0 +1,33 @@
|
|||||||
|
import { Kysely, PostgresDialect, type PostgresDialectConfig as KyselyPostgresDialectConfig } from "kysely";
|
||||||
|
import { PostgresIntrospector } from "./PostgresIntrospector";
|
||||||
|
import { PostgresConnection, plugins } from "./PostgresConnection";
|
||||||
|
import { customIntrospector } from "../Connection";
|
||||||
|
import type { Pool } from "pg";
|
||||||
|
|
||||||
|
export type PostgresDialectConfig = Omit<KyselyPostgresDialectConfig, "pool"> & {
|
||||||
|
pool: Pool;
|
||||||
|
};
|
||||||
|
|
||||||
|
export class PgPostgresConnection extends PostgresConnection<Pool> {
|
||||||
|
override name = "pg";
|
||||||
|
|
||||||
|
constructor(config: PostgresDialectConfig) {
|
||||||
|
const kysely = new Kysely({
|
||||||
|
dialect: customIntrospector(PostgresDialect, PostgresIntrospector, {
|
||||||
|
excludeTables: [],
|
||||||
|
}).create(config),
|
||||||
|
plugins,
|
||||||
|
});
|
||||||
|
|
||||||
|
super(kysely);
|
||||||
|
this.client = config.pool;
|
||||||
|
}
|
||||||
|
|
||||||
|
override async close(): Promise<void> {
|
||||||
|
await this.client.end();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function pg(config: PostgresDialectConfig): PgPostgresConnection {
|
||||||
|
return new PgPostgresConnection(config);
|
||||||
|
}
|
||||||
+4
-4
@@ -5,7 +5,7 @@ import {
|
|||||||
type SchemaResponse,
|
type SchemaResponse,
|
||||||
type ConnQuery,
|
type ConnQuery,
|
||||||
type ConnQueryResults,
|
type ConnQueryResults,
|
||||||
} from "bknd";
|
} from "../Connection";
|
||||||
import {
|
import {
|
||||||
ParseJSONResultsPlugin,
|
ParseJSONResultsPlugin,
|
||||||
type ColumnDataType,
|
type ColumnDataType,
|
||||||
@@ -20,7 +20,7 @@ export type QB = SelectQueryBuilder<any, any, any>;
|
|||||||
|
|
||||||
export const plugins = [new ParseJSONResultsPlugin()];
|
export const plugins = [new ParseJSONResultsPlugin()];
|
||||||
|
|
||||||
export abstract class PostgresConnection extends Connection {
|
export abstract class PostgresConnection<Client = unknown> extends Connection<Client> {
|
||||||
protected override readonly supported = {
|
protected override readonly supported = {
|
||||||
batching: true,
|
batching: true,
|
||||||
softscans: true,
|
softscans: true,
|
||||||
@@ -68,7 +68,7 @@ export abstract class PostgresConnection extends Connection {
|
|||||||
type,
|
type,
|
||||||
(col: ColumnDefinitionBuilder) => {
|
(col: ColumnDefinitionBuilder) => {
|
||||||
if (spec.primary) {
|
if (spec.primary) {
|
||||||
return col.primaryKey();
|
return col.primaryKey().notNull();
|
||||||
}
|
}
|
||||||
if (spec.references) {
|
if (spec.references) {
|
||||||
return col
|
return col
|
||||||
@@ -76,7 +76,7 @@ export abstract class PostgresConnection extends Connection {
|
|||||||
.onDelete(spec.onDelete ?? "set null")
|
.onDelete(spec.onDelete ?? "set null")
|
||||||
.onUpdate(spec.onUpdate ?? "no action");
|
.onUpdate(spec.onUpdate ?? "no action");
|
||||||
}
|
}
|
||||||
return spec.nullable ? col : col.notNull();
|
return col;
|
||||||
},
|
},
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
+21
-20
@@ -1,5 +1,5 @@
|
|||||||
import { type SchemaMetadata, sql } from "kysely";
|
import { type SchemaMetadata, sql } from "kysely";
|
||||||
import { BaseIntrospector } from "bknd";
|
import { BaseIntrospector } from "../BaseIntrospector";
|
||||||
|
|
||||||
type PostgresSchemaSpec = {
|
type PostgresSchemaSpec = {
|
||||||
name: string;
|
name: string;
|
||||||
@@ -102,26 +102,27 @@ export class PostgresIntrospector extends BaseIntrospector {
|
|||||||
return tables.map((table) => ({
|
return tables.map((table) => ({
|
||||||
name: table.name,
|
name: table.name,
|
||||||
isView: table.type === "VIEW",
|
isView: table.type === "VIEW",
|
||||||
columns: table.columns.map((col) => {
|
columns: table.columns.map((col) => ({
|
||||||
return {
|
name: col.name,
|
||||||
name: col.name,
|
dataType: col.type,
|
||||||
dataType: col.type,
|
isNullable: !col.notnull,
|
||||||
isNullable: !col.notnull,
|
isAutoIncrementing: col.dflt?.toLowerCase().includes("nextval") ?? false,
|
||||||
// @todo: check default value on 'nextval' see https://www.postgresql.org/docs/17/datatype-numeric.html#DATATYPE-SERIAL
|
hasDefaultValue: col.dflt != null,
|
||||||
isAutoIncrementing: true, // just for now
|
comment: undefined,
|
||||||
hasDefaultValue: col.dflt != null,
|
|
||||||
comment: undefined,
|
|
||||||
};
|
|
||||||
}),
|
|
||||||
indices: table.indices.map((index) => ({
|
|
||||||
name: index.name,
|
|
||||||
table: table.name,
|
|
||||||
isUnique: index.sql?.match(/unique/i) != null,
|
|
||||||
columns: index.columns.map((col) => ({
|
|
||||||
name: col.name,
|
|
||||||
order: col.seqno,
|
|
||||||
})),
|
|
||||||
})),
|
})),
|
||||||
|
indices: table.indices
|
||||||
|
// filter out db-managed primary key index
|
||||||
|
.filter((index) => index.name !== `${table.name}_pkey`)
|
||||||
|
.map((index) => ({
|
||||||
|
name: index.name,
|
||||||
|
table: table.name,
|
||||||
|
isUnique: index.sql?.match(/unique/i) != null,
|
||||||
|
columns: index.columns.map((col) => ({
|
||||||
|
name: col.name,
|
||||||
|
// seqno starts at 1
|
||||||
|
order: col.seqno - 1,
|
||||||
|
})),
|
||||||
|
})),
|
||||||
}));
|
}));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
import { Kysely } from "kysely";
|
||||||
|
import { PostgresIntrospector } from "./PostgresIntrospector";
|
||||||
|
import { PostgresConnection, plugins } from "./PostgresConnection";
|
||||||
|
import { customIntrospector } from "../Connection";
|
||||||
|
import { PostgresJSDialect, type PostgresJSDialectConfig } from "kysely-postgres-js";
|
||||||
|
|
||||||
|
export class PostgresJsConnection extends PostgresConnection<PostgresJSDialectConfig["postgres"]> {
|
||||||
|
override name = "postgres-js";
|
||||||
|
|
||||||
|
constructor(config: PostgresJSDialectConfig) {
|
||||||
|
const kysely = new Kysely({
|
||||||
|
dialect: customIntrospector(PostgresJSDialect, PostgresIntrospector, {
|
||||||
|
excludeTables: [],
|
||||||
|
}).create(config),
|
||||||
|
plugins,
|
||||||
|
});
|
||||||
|
|
||||||
|
super(kysely);
|
||||||
|
this.client = config.postgres;
|
||||||
|
}
|
||||||
|
|
||||||
|
override async close(): Promise<void> {
|
||||||
|
await this.client.end();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function postgresJs(
|
||||||
|
config: PostgresJSDialectConfig,
|
||||||
|
): PostgresJsConnection {
|
||||||
|
return new PostgresJsConnection(config);
|
||||||
|
}
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
import { customIntrospector, type DbFunctions } from "bknd";
|
import { customIntrospector, type DbFunctions } from "../Connection";
|
||||||
import { Kysely, type Dialect, type KyselyPlugin } from "kysely";
|
import { Kysely, type Dialect, type KyselyPlugin } from "kysely";
|
||||||
import { plugins, PostgresConnection } from "./PostgresConnection";
|
import { plugins, PostgresConnection } from "./PostgresConnection";
|
||||||
import { PostgresIntrospector } from "./PostgresIntrospector";
|
import { PostgresIntrospector } from "./PostgresIntrospector";
|
||||||
@@ -6,7 +6,7 @@ import { PostgresIntrospector } from "./PostgresIntrospector";
|
|||||||
export type Constructor<T> = new (...args: any[]) => T;
|
export type Constructor<T> = new (...args: any[]) => T;
|
||||||
|
|
||||||
export type CustomPostgresConnection = {
|
export type CustomPostgresConnection = {
|
||||||
supports?: PostgresConnection["supported"];
|
supports?: Partial<PostgresConnection["supported"]>;
|
||||||
fn?: Partial<DbFunctions>;
|
fn?: Partial<DbFunctions>;
|
||||||
plugins?: KyselyPlugin[];
|
plugins?: KyselyPlugin[];
|
||||||
excludeTables?: string[];
|
excludeTables?: string[];
|
||||||
@@ -13,31 +13,43 @@ import { customIntrospector } from "../Connection";
|
|||||||
import { SqliteIntrospector } from "./SqliteIntrospector";
|
import { SqliteIntrospector } from "./SqliteIntrospector";
|
||||||
import type { Field } from "data/fields/Field";
|
import type { Field } from "data/fields/Field";
|
||||||
|
|
||||||
// @todo: add pragmas
|
|
||||||
export type SqliteConnectionConfig<
|
export type SqliteConnectionConfig<
|
||||||
CustomDialect extends Constructor<Dialect> = Constructor<Dialect>,
|
CustomDialect extends Constructor<Dialect> = Constructor<Dialect>,
|
||||||
> = {
|
> = {
|
||||||
excludeTables?: string[];
|
excludeTables?: string[];
|
||||||
dialect: CustomDialect;
|
|
||||||
dialectArgs?: ConstructorParameters<CustomDialect>;
|
|
||||||
additionalPlugins?: KyselyPlugin[];
|
additionalPlugins?: KyselyPlugin[];
|
||||||
customFn?: Partial<DbFunctions>;
|
customFn?: Partial<DbFunctions>;
|
||||||
};
|
} & (
|
||||||
|
| {
|
||||||
|
dialect: CustomDialect;
|
||||||
|
dialectArgs?: ConstructorParameters<CustomDialect>;
|
||||||
|
}
|
||||||
|
| {
|
||||||
|
kysely: Kysely<any>;
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
export abstract class SqliteConnection<Client = unknown> extends Connection<Client> {
|
export abstract class SqliteConnection<Client = unknown> extends Connection<Client> {
|
||||||
override name = "sqlite";
|
override name = "sqlite";
|
||||||
|
|
||||||
constructor(config: SqliteConnectionConfig) {
|
constructor(config: SqliteConnectionConfig) {
|
||||||
const { excludeTables, dialect, dialectArgs = [], additionalPlugins } = config;
|
const { excludeTables, additionalPlugins } = config;
|
||||||
const plugins = [new ParseJSONResultsPlugin(), ...(additionalPlugins ?? [])];
|
const plugins = [new ParseJSONResultsPlugin(), ...(additionalPlugins ?? [])];
|
||||||
|
|
||||||
const kysely = new Kysely({
|
let kysely: Kysely<any>;
|
||||||
dialect: customIntrospector(dialect, SqliteIntrospector, {
|
if ("dialect" in config) {
|
||||||
excludeTables,
|
kysely = new Kysely({
|
||||||
|
dialect: customIntrospector(config.dialect, SqliteIntrospector, {
|
||||||
|
excludeTables,
|
||||||
|
plugins,
|
||||||
|
}).create(...(config.dialectArgs ?? [])),
|
||||||
plugins,
|
plugins,
|
||||||
}).create(...dialectArgs),
|
});
|
||||||
plugins,
|
} else if ("kysely" in config) {
|
||||||
});
|
kysely = config.kysely;
|
||||||
|
} else {
|
||||||
|
throw new Error("Either dialect or kysely must be provided");
|
||||||
|
}
|
||||||
|
|
||||||
super(
|
super(
|
||||||
kysely,
|
kysely,
|
||||||
|
|||||||
@@ -83,7 +83,7 @@ export class SqliteIntrospector extends BaseIntrospector {
|
|||||||
dataType: col.type,
|
dataType: col.type,
|
||||||
isNullable: !col.notnull,
|
isNullable: !col.notnull,
|
||||||
isAutoIncrementing: col.name === autoIncrementCol,
|
isAutoIncrementing: col.name === autoIncrementCol,
|
||||||
hasDefaultValue: col.dflt_value != null,
|
hasDefaultValue: col.name === autoIncrementCol ? true : col.dflt_value != null,
|
||||||
comment: undefined,
|
comment: undefined,
|
||||||
};
|
};
|
||||||
}) ?? [],
|
}) ?? [],
|
||||||
|
|||||||
@@ -18,7 +18,7 @@ export type LibsqlClientFns = {
|
|||||||
function getClient(clientOrCredentials: Client | LibSqlCredentials | LibsqlClientFns): Client {
|
function getClient(clientOrCredentials: Client | LibSqlCredentials | LibsqlClientFns): Client {
|
||||||
if (clientOrCredentials && "url" in clientOrCredentials) {
|
if (clientOrCredentials && "url" in clientOrCredentials) {
|
||||||
const { url, authToken } = clientOrCredentials;
|
const { url, authToken } = clientOrCredentials;
|
||||||
return createClient({ url, authToken });
|
return createClient({ url, authToken }) as unknown as Client;
|
||||||
}
|
}
|
||||||
|
|
||||||
return clientOrCredentials as Client;
|
return clientOrCredentials as Client;
|
||||||
|
|||||||
@@ -0,0 +1,15 @@
|
|||||||
|
import { describe } from "bun:test";
|
||||||
|
import { SQLocalConnection } from "./SQLocalConnection";
|
||||||
|
import { connectionTestSuite } from "data/connection/connection-test-suite";
|
||||||
|
import { bunTestRunner } from "adapter/bun/test";
|
||||||
|
import { SQLocalKysely } from "sqlocal/kysely";
|
||||||
|
|
||||||
|
describe("SQLocalConnection", () => {
|
||||||
|
connectionTestSuite(bunTestRunner, {
|
||||||
|
makeConnection: () => ({
|
||||||
|
connection: new SQLocalConnection(new SQLocalKysely({ databasePath: ":memory:" })),
|
||||||
|
dispose: async () => {},
|
||||||
|
}),
|
||||||
|
rawDialectDetails: [],
|
||||||
|
});
|
||||||
|
});
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user