@brickkit/core 0.6.0 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,100 +1,207 @@
1
1
  # @brickkit/core
2
2
 
3
- The Effect-native kernel of Brick. Declare typed actions once; Brick serves them
4
- as HTTP endpoints (with OpenAPI), RPC methods, and MCP tools.
3
+ Services, actions, resources, and databases for the Brick-TS framework. You define typed services with TypeBox schemas, mount them with `brick()`, and get an Elysia HTTP server with OpenAPI output and a typed client.
4
+
5
+ You need Bun 1.2 or later. Bun-only APIs are lazy-loaded, so the package imports cleanly under strict Node ESM too.
6
+
7
+ ```sh
8
+ bun add @brickkit/core
9
+ ```
10
+
11
+ ## Define a service
12
+
13
+ Create a service, register an action on it, and serve it. Each action exposes one route: `POST /api/{service}/{action}` by default.
5
14
 
6
15
  ```ts
7
- import { Brick } from "@brickkit/core";
8
- import { NotFound } from "@brickkit/core/contracts";
9
- import { Effect, Layer, Schema } from "effect";
10
-
11
- const GetUser = Brick.action("getUser", "/api/users/getUser", {
12
- input: Schema.Struct({ id: Schema.String }),
13
- output: Schema.Struct({ id: Schema.String, name: Schema.String }),
14
- errors: [NotFound],
16
+ import { brick, defineAction, defineService } from "@brickkit/core";
17
+
18
+ const healthService = defineService("system");
19
+ const ping = defineAction({
20
+ name: "ping",
21
+ execute: async () => ({ status: "ok" }),
15
22
  });
23
+ healthService.action(ping);
24
+
25
+ const app = brick({ services: [healthService] });
26
+ app.listen(4000);
27
+ ```
28
+
29
+ Set `method: "GET"` on the action config to serve reads over GET, or `path` to replace the default route. Add `input` and `output` TypeBox schemas to validate at the boundary. Add `authorize` to require a user; without it the action is public. To call an action in process with the same pipeline, use `action.run(input, ctx)` or `service.getAction("ping")`.
30
+
31
+ `brick()` also accepts `prefix`, `title`, and `version`. `generateOpenApiSpec({ services, prefix })` returns the OpenAPI 3.1 document without starting a server.
16
32
 
17
- // Handlers are Effects: failures must be declared in `errors`, and any
18
- // service they require must be provided by the app's `layer`.
19
- const getUser = GetUser(({ id }) =>
20
- id === "usr_42"
21
- ? Effect.succeed({ id, name: "Ada" })
22
- : Effect.fail(new NotFound({ message: "User not found" })),
23
- );
33
+ ## Exports
24
34
 
25
- const users = Brick.service("users", { actions: { getUser } });
26
- export const app = Brick.app({ services: [users], layer: Layer.empty });
35
+ | Path | What it holds |
36
+ | ----------------------- | --------------------------------------------------------------- |
37
+ | `@brickkit/core` | `brick`, `defineService`, `defineAction`, `defineDatabase`, MCP |
38
+ | `@brickkit/core/client` | `createBrickClient`, the Eden-style typed browser client |
39
+ | `@brickkit/core/pg` | Postgres Drizzle table helpers such as `pgTable` |
27
40
 
28
- Bun.serve({ port: 3000, fetch: app.fetch });
41
+ Databases use Drizzle tables through `defineDatabase({ engine, tables, url })` with `"sqlite"` or `"postgres"` engines. Database setup is documented in `DATABASES.md`.
42
+
43
+ ```sh
44
+ bun add @brickkit/core drizzle-orm postgres
29
45
  ```
30
46
 
31
- ## API
47
+ ```ts
48
+ import { defineDatabase } from "@brickkit/core";
49
+ import { pgTable, text } from "@brickkit/core/pg";
32
50
 
33
- | Export | Purpose |
34
- | ------------------------------------------------------------- | -------------------------------------------------------------------------------------------------- |
35
- | `Brick.action(name, path, schemas)` | Contract + handler factory: input, output, declared errors, optional `mcp`, `title`, `description` |
36
- | `Brick.endpoint(name, method, path, schemas)` | Like `action`, with typed `params`, `query`, `payload`, `headers` |
37
- | `Brick.service(name, { actions })` | Groups actions into an HTTP API group |
38
- | `Brick.app({ services, layer, transports?, routes?, docs? })` | Compiles services into one scoped application |
39
- | `Brick.route(method, path, effect)` | Raw HTTP route outside the action contract |
40
- | `Brick.rpcGroup(actions)` | Effect RPC group for service-to-service calls |
41
- | `secret`, `envSource`, ... | Typed secrets, validated at startup |
51
+ const pages = pgTable("pages", {
52
+ id: text("id").primaryKey(),
53
+ title: text("title").notNull(),
54
+ });
55
+
56
+ export const db = defineDatabase({
57
+ engine: "postgres",
58
+ tables: { pages },
59
+ url: process.env.DATABASE_URL!,
60
+ });
61
+ ```
42
62
 
43
- `Brick.app` returns `{ fetch, ready, dispose, layer, api, openApi() }`.
44
- `fetch` starts the application lazily; `dispose` interrupts in-flight
45
- requests and releases every scoped resource once.
63
+ ## Typed client
46
64
 
47
- ## Typed errors
65
+ `@brickkit/core/client` (also re-exported from the package root) offers an Eden-style HTTP client inferred from your contract type — no OpenAPI codegen:
48
66
 
49
- Errors are `Schema.TaggedError` classes, so they are values in the type
50
- system, carry their HTTP status, and cross the wire with their type intact.
51
- `@brickkit/core/contracts` exports `BadRequest`, `Unauthorized`, `Forbidden`,
52
- `NotFound`, `Conflict`, and `InternalServerError`. Define your own:
67
+ With the Brick Vite plugin configured for your default-exported app, Vite creates `_brick/contract.ts` automatically:
53
68
 
54
69
  ```ts
55
- export class SlugTaken extends Schema.TaggedError<SlugTaken>()(
56
- "SlugTaken",
57
- { slug: Schema.String },
58
- { httpApiStatus: 409 },
59
- ) {}
70
+ import { createBrickClient } from "@brickkit/core/client";
71
+ import { contract } from "../_brick/contract";
72
+
73
+ const api = createBrickClient({ baseUrl: "http://localhost:4000", contract });
74
+ const pages = await api.page.list({ limit: 10 });
60
75
  ```
61
76
 
62
- Failing with an error that the action did not declare is a compile error.
63
- Unexpected failures are defects and are returned as a redacted 500.
77
+ The generated contract contains browser-safe route metadata and inferred input/output/error types. It honors custom action paths and methods, encodes path parameters, and removes them from the remaining payload. No backend handlers are bundled. See the CLI README and `www/content/docs/(brick)/typed-client.mdx` for Vite setup and error handling.
64
78
 
65
- ## Dependencies
79
+ ## MCP tools
66
80
 
67
- Provide services through the app's `layer`. An action that requires a service
68
- the layer does not supply does not type-check.
81
+ Define tools like actions, with typed input/output schemas and inline metadata:
69
82
 
70
- ## Transports
83
+ ```ts
84
+ import {
85
+ defineService,
86
+ createMcpRegistry,
87
+ createMcpHandler,
88
+ t,
89
+ } from "@brickkit/core";
90
+
91
+ const crm = defineService("crm");
92
+ const whoami = crm.tool({
93
+ name: "crm_whoami",
94
+ title: "View Connected CRM Account",
95
+ annotations: { readOnlyHint: true },
96
+ input: t.Object({}),
97
+ output: t.String(),
98
+ authorize: ({ user }) => !!user?.id,
99
+ execute: ({ ctx }) => ctx.user.id,
100
+ });
101
+
102
+ const registry = createMcpRegistry({ services: [crm] });
103
+ registry.listTools();
104
+ await registry.callTool("crm_whoami", {}, { user: { id: "user_1" } });
105
+
106
+ const handleMcp = createMcpHandler({
107
+ registry,
108
+ serverInfo: { name: "crm", version: "1.0.0" },
109
+ });
110
+ // After your app authenticates a request:
111
+ // return handleMcp(request, { user: { id: verifiedSubject } });
112
+ ```
113
+
114
+ Tools use action validation, authorization, and service context. They are stored separately from HTTP actions and stay out of routes and OpenAPI by default, including when their service is passed to `brick()`. Add `http: true` to a tool definition, or register it with `crm.action(whoami)`, to expose it over HTTP as well.
115
+
116
+ The registry accepts `services` and/or an explicit `tools` array, rejects duplicate names, and reads annotations directly from definitions. The handler is a stateless POST JSON-RPC helper for initialize, ping, tools/list, and tools/call; notifications receive an empty 202 response. Authentication and mounting remain in your app. Its default protocol version is `2025-06-18`, following the [MCP tools specification](https://modelcontextprotocol.io/specification/2025-06-18/server/tools).
117
+
118
+ Source: <https://github.com/Chandraprakash-Darji/brick>.
119
+
120
+ ## Effect APIs
121
+
122
+ `@brickkit/core` keeps the existing synchronous declarations and Promise APIs.
123
+ `@brickkit/core/effect` provides Effect callbacks for services, actions, tools,
124
+ resource plugins, endpoints, and application lifecycle hooks. Declarations and
125
+ plugin setup stay synchronous so the compiler can inspect them and plugin
126
+ installation can roll back failed declarations.
71
127
 
72
128
  ```ts
73
- import { McpProtocol } from "effect/ai";
74
-
75
- Brick.app({
76
- services: [users],
77
- layer,
78
- transports: {
79
- rpc: { path: "/rpc" },
80
- mcp: {
81
- name: "users",
82
- version: "1.0.0",
83
- path: "/mcp",
84
- protocols: [McpProtocol.v2025_11_25],
85
- },
129
+ import { Context, Effect, Layer } from "effect";
130
+ import { brick, defineService, t } from "@brickkit/core/effect";
131
+
132
+ class Greeting extends Context.Service<Greeting, { text: string }>()(
133
+ "Greeting",
134
+ ) {}
135
+
136
+ const service = defineService("greetings", {
137
+ context: () => Effect.map(Greeting, ({ text }) => ({ greeting: text })),
138
+ lifecycle: {
139
+ onInit: () => Effect.void,
140
+ onDestroy: () => Effect.void,
86
141
  },
87
- docs: { path: "/reference" },
88
142
  });
89
- ```
90
143
 
91
- Only actions declared with `mcp: true` are exposed as MCP tools. The MCP
92
- options are those of Effect's `McpServer.layerHttp`.
144
+ const hello = service.action({
145
+ name: "hello",
146
+ output: t.String(),
147
+ authorize: () => Effect.succeed(true),
148
+ execute: ({ ctx }) => Effect.succeed(ctx.greeting),
149
+ });
93
150
 
94
- ## Entry points
151
+ const app = brick({
152
+ services: [service],
153
+ layer: Layer.succeed(Greeting, { text: "Hello" }),
154
+ endpoints: [
155
+ {
156
+ method: "GET",
157
+ path: "/greeting",
158
+ handler: () => Effect.map(Greeting, ({ text }) => ({ text })),
159
+ },
160
+ ],
161
+ });
162
+
163
+ await app.initialize();
164
+ await hello.run(); // "Hello"
165
+ await app.handle(new Request("http://localhost/greeting"));
166
+ await app.dispose();
167
+ ```
95
168
 
96
- | Import | Contents |
97
- | -------------------------- | ----------------------------------------------------------------------- |
98
- | `@brickkit/core` | `Brick`, `isNativeBrickApp`, secrets |
99
- | `@brickkit/core/contracts` | `action`, `endpoint`, and standard errors; browser-safe, no server code |
100
- | `@brickkit/core/pg` | Drizzle `pg-core` re-exports, for a single Drizzle copy |
169
+ The app acquires its Layer once and shares it across service contexts, actions,
170
+ tools, resource policies, plugin endpoints, and HTTP routes. Initialization runs
171
+ before the first HTTP request or server startup. `initialize()` also lets scripts
172
+ initialize explicitly before direct action or tool calls. `dispose()` runs service
173
+ destruction hooks, releases the Layer, and releases database handles — closing
174
+ the ones no remaining app uses. Injected database clients remain owned by their
175
+ callers. Services may be shared across apps; the newest live binding wins for
176
+ direct calls, and disposing an app restores the previous binding.
177
+
178
+ The app exposes `initializeEffect`, `disposeEffect`, `handleEffect(request)`, and
179
+ `listenEffect(port)` for Effect composition. The normal `.handle()`, `.listen()`,
180
+ and `.stop()` methods remain available. HTTP request cancellation interrupts
181
+ native callbacks and runs their finalizers.
182
+
183
+ Actions and tools expose lazy `executeEffect(params)`, including context
184
+ resolution, input validation, authorization, execution, and output validation.
185
+ Calling an action, `.run`, or `.execute` returns a Promise. Native action
186
+ requirements remain in the Effect type; provide dependencies with `Effect.provide`
187
+ when composing outside an app. Service context resolution also exposes
188
+ `resolveContextEffect`. Resource plugin and CRUD callbacks inherit that caller's
189
+ runtime across the Promise-based database code.
190
+
191
+ Use `service.tool` for native tools. `createMcpRegistry` retains the MCP Promise
192
+ interface and adds `callToolEffect`. `createServiceProxy` returns Effects for local
193
+ RPC calls and preserves the caller's Layer. Remote dispatch is not implemented.
194
+
195
+ Use `defineServicePlugin` and `defineResourcePlugin` from the Effect entrypoint
196
+ for native `routes.action` and `routes.endpoint` callbacks. `defineResource` and
197
+ `service.resource` share the existing resource identity and plugin host.
198
+ For CRUD policies, hooks, SQL scopes, and field scrubbers, use `crud` from
199
+ `@brickkit/crud/effect`.
200
+
201
+ `Effect.fail` preserves failure values at the Promise boundary. Use
202
+ `ActionExecutionError` for a specific HTTP status. Throwing `error` helpers also
203
+ work. Action errors include framework validation and context errors; service,
204
+ CRUD, and dynamic MCP failure types remain broad because plugins and providers
205
+ can reject arbitrary values. Dynamic registration does not prove at compile time
206
+ that an application's Layer supplies every registered callback's dependencies.
207
+ The framework uses Effect 4.