@brickkit/core 0.12.0 → 0.13.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.
@@ -0,0 +1,444 @@
1
+ import { Dn as SecretSource, E as Logger, J as ValidationErrorItem, Kn as EventsOptions, R as Service, cn as ServicePort, dr as HttpMethod, ht as EventsHub, mt as EventsDefinition, ot as SocketBroker, qt as InstalledPlugin, rt as BrickSocketSchema, t as Action, wt as DatabaseHandle, yn as PluginInstance } from "./types.js";
2
+ import { Elysia } from "elysia";
3
+ type RouteMethod = HttpMethod;
4
+ interface RouteIR {
5
+ readonly method: RouteMethod;
6
+ readonly path: string;
7
+ readonly service: string;
8
+ readonly action: string;
9
+ readonly kind: "action";
10
+ /** The plugin that registered the action, if one did. */
11
+ readonly plugin?: string;
12
+ readonly input: boolean;
13
+ readonly output: boolean;
14
+ readonly context: boolean;
15
+ readonly authorize: boolean;
16
+ /** Whether the server reads the query first (else path parameters, then body). */
17
+ readonly readLike: boolean;
18
+ /** Where callers send the input: the query (GET, DELETE) or the body. */
19
+ readonly inputSource: "query" | "body";
20
+ readonly coercions: readonly {
21
+ readonly key: string;
22
+ readonly type: "number" | "boolean" | "array";
23
+ }[];
24
+ /** JSON projection for inspection and stale-artifact detection, not runtime validation. */
25
+ readonly inputSchema?: unknown;
26
+ readonly outputSchema?: unknown;
27
+ }
28
+ interface BrickIR {
29
+ readonly version: 1;
30
+ readonly target: "bun-elysia";
31
+ readonly prefix: string;
32
+ readonly services: readonly string[];
33
+ readonly routes: readonly RouteIR[];
34
+ readonly preparations: readonly {
35
+ service: string;
36
+ name: string;
37
+ metadata: unknown;
38
+ }[];
39
+ readonly diagnostics: readonly string[];
40
+ }
41
+ /** An OpenAPI document as plain JSON. */
42
+ type OpenApiDocument = Record<string, unknown>;
43
+ /** An extra OpenAPI document for the API reference, such as Better Auth's. */
44
+ interface ReferenceDocument {
45
+ /** Name in the reference's list of documents. */
46
+ title: string;
47
+ /** The document, or a function returning it; called each time the app starts. */
48
+ document: OpenApiDocument | (() => OpenApiDocument | Promise<OpenApiDocument>);
49
+ }
50
+ /** A named OpenAPI document ready to render. */
51
+ interface ApiDocument {
52
+ title: string;
53
+ document: OpenApiDocument;
54
+ }
55
+ /** Developer documentation for the `brick dev` dashboard. */
56
+ interface DocumentationOptions {
57
+ /**
58
+ * Folder of `.md`/`.mdx` pages. A relative path starts at the folder of the
59
+ * app entry, as it reads in the file that sets it.
60
+ */
61
+ dir: string;
62
+ /**
63
+ * Module whose exports are React components for MDX, added to the built-in
64
+ * ones; a relative path starts where `dir` does. A default export or a
65
+ * `components` export holds the name-to-component map. The dashboard bundles
66
+ * it, so it may import anything the project has.
67
+ */
68
+ components?: string;
69
+ }
70
+ interface ReferenceOptions {
71
+ /** Also serve a standalone Scalar page here. Without a path, no page is served. */
72
+ path?: string;
73
+ title?: string;
74
+ specUrl?: string;
75
+ /** More OpenAPI documents for the `brick dev` dashboard's APIs view. */
76
+ documents?: ReferenceDocument[];
77
+ }
78
+ /** Renders the Scalar API reference page for the given OpenAPI URL. */
79
+ declare function scalarDocsHTML(specUrl: string, title: string): string;
80
+ /**
81
+ * Standalone Elysia plugin serving GET <path> with the Scalar HTML page.
82
+ *
83
+ * @deprecated Use `brick({ reference: true })` or `reference: { path }`.
84
+ */
85
+ declare function referencePlugin(opts?: ReferenceOptions): Elysia;
86
+ /**
87
+ * Mounts the Scalar reference route onto an existing app.
88
+ *
89
+ * @deprecated Use `brick({ reference: true })` or `reference: { path }`.
90
+ */
91
+ declare function registerReferenceRoute(app: Elysia, opts?: ReferenceOptions): Elysia;
92
+ /** Who may open the dashboard that `brick start` serves for monitoring. */
93
+ interface DashboardAuth {
94
+ /**
95
+ * Secrets that let a request in. A browser asks for one in its sign-in
96
+ * prompt (any user name, the secret as the password), and monitors and
97
+ * scripts send `Authorization: Bearer <secret>`. Give several to rotate one
98
+ * while the other still works. Each is at least 16 characters long;
99
+ * `openssl rand -base64 32` makes a good one.
100
+ */
101
+ token?: string | readonly string[];
102
+ /**
103
+ * Your own check, to sign people in with the auth the app already has: read
104
+ * a session cookie, verify a Better Auth or Clerk session, look at a header
105
+ * a proxy adds. It receives the request (method, URL, and headers; no body)
106
+ * and returns `true` to let it in, `false` to refuse it with 401, or a
107
+ * `Response` to send instead, such as a redirect to your login page. If it
108
+ * throws or takes longer than five seconds, the request is refused with 503.
109
+ *
110
+ * A request is let in when it carries a valid `token`, or when this
111
+ * returns `true`; give both to let monitors in by token and people in by
112
+ * sign-in.
113
+ */
114
+ authorize?: (request: Request) => boolean | Response | Promise<boolean | Response>;
115
+ }
116
+ /**
117
+ * The monitoring dashboard `brick start` serves beside the app, on a port of
118
+ * its own: live requests, logs, errors, and the shape of the service, so it
119
+ * stays reachable when the app's own routes are not. `brick dev` has its own
120
+ * dashboard, set by command line options, and ignores this.
121
+ *
122
+ * Setting it turns on `telemetry`, since the dashboard shows what is traced.
123
+ * While it is on, `ctx.logger` and `console` lines written during a request
124
+ * go to the dashboard instead of the console.
125
+ */
126
+ interface DashboardOptions {
127
+ /** Default 9400. */
128
+ port?: number;
129
+ /**
130
+ * The address to listen on. Default `127.0.0.1`, reachable only from the same
131
+ * machine. In a container use `0.0.0.0`, which needs `auth`: the dashboard
132
+ * will not start on any other address without it.
133
+ */
134
+ host?: string;
135
+ auth?: DashboardAuth;
136
+ /**
137
+ * Days of finished requests to keep on disk, in `.brick/` of the working
138
+ * folder. Default 0: only what happened since the process started, which is
139
+ * lost when it restarts. Needs a folder that outlives the container.
140
+ */
141
+ historyDays?: number;
142
+ }
143
+ type EndpointMethod = HttpMethod;
144
+ /** The logger handed to endpoint handlers (the same one actions get). */
145
+ type EndpointLogger = Logger;
146
+ /** Context for raw endpoint handlers: Elysia route fields + Brick extras. */
147
+ interface EndpointContext {
148
+ params: Record<string, string>;
149
+ query: Record<string, string | undefined>;
150
+ body: unknown;
151
+ headers: Record<string, string>;
152
+ request: Request;
153
+ /** Elysia response setter (status/headers). Mutate like in `app.get`. */
154
+ set: {
155
+ status?: number;
156
+ headers: Record<string, string>;
157
+ };
158
+ /** Drizzle db from `service` (or first service with one); `undefined` when none. */
159
+ db: any;
160
+ logger: EndpointLogger;
161
+ traceId: string;
162
+ requestId: string;
163
+ }
164
+ interface EndpointDefinition {
165
+ method: EndpointMethod;
166
+ /** Elysia-style path, e.g. `/p/:slug`. */
167
+ path: string;
168
+ handler: (ctx: EndpointContext) => unknown | Promise<unknown>;
169
+ /** Db source: instance or registered service name. Defaults to first service with a db. */
170
+ service?: Service<any, any> | string;
171
+ /** Explicit database handle, independent of a service. */
172
+ database?: DatabaseHandle<unknown>;
173
+ summary?: string;
174
+ description?: string;
175
+ tags?: string[];
176
+ /** The plugin that contributed it; OpenAPI labels it `x-brick-plugin`. */
177
+ plugin?: string;
178
+ }
179
+ /** The app object returned by `brick`: Elysia plus `endpoint()`. */
180
+ type BrickApp = Elysia<any, any, any, any, any, any, any> & {
181
+ /** Service definitions, prefix, and telemetry setting chosen at construction. */
182
+ readonly definition: {
183
+ readonly routes: readonly RouteIR[];
184
+ readonly sockets: readonly (BrickSocketSchema & {
185
+ service: string;
186
+ path: string;
187
+ })[];
188
+ readonly services: readonly Service<any, any>[];
189
+ readonly prefix: string;
190
+ readonly telemetry: boolean;
191
+ readonly documentation?: DocumentationOptions;
192
+ /** What `brick start` serves for monitoring; its `auth` is not enumerable. */
193
+ readonly dashboard?: DashboardOptions;
194
+ /** The listeners and settings of `events`, as plain data. */
195
+ readonly events?: EventsDefinition;
196
+ /** Every `definePlugin` installation, in install order. */
197
+ readonly plugins?: readonly InstalledPlugin[];
198
+ };
199
+ /**
200
+ * Run the plugins' `on("start")` handlers in install order, once. `listen`
201
+ * calls it; `brick dev` and `brick start` await it before serving. `stop()`
202
+ * runs their `on("stop")` handlers in reverse order.
203
+ */
204
+ start(): Promise<void>;
205
+ /**
206
+ * Start the plugins, listen on `port`, then start event delivery. What
207
+ * `brick dev`, `brick start` and a built server run.
208
+ */
209
+ serve(options: {
210
+ port: number;
211
+ }): Promise<BrickApp>;
212
+ /**
213
+ * Stop event delivery (finishing deliveries in flight), then the server, then
214
+ * the plugins. `closeActiveConnections` is passed to `stop()`.
215
+ */
216
+ shutdown(closeActiveConnections?: boolean): Promise<void>;
217
+ /**
218
+ * The events of this app, when `events` is set: start and stop delivery, drain
219
+ * what is due, and see or retry what is parked. `brick dev` and `brick start`
220
+ * start it for you.
221
+ */
222
+ readonly events?: EventsHub;
223
+ /** Register a raw endpoint (a plain route, not an action). */
224
+ endpoint(def: EndpointDefinition): void;
225
+ /**
226
+ * The OpenAPI documents behind the dashboard's APIs view: this app's own
227
+ * unless `docs` is false, then those from `reference.documents`.
228
+ */
229
+ referenceDocuments(): Promise<ApiDocument[]>;
230
+ /** This app's OpenAPI document, as `/openapi.json` serves it (also when `docs` is false). */
231
+ openApiDocument(): Record<string, any>;
232
+ /** All endpoints registered via `endpoint()` (declaration order). */
233
+ listEndpoints(): EndpointDefinition[];
234
+ };
235
+ type CompiledHandler = (context: any) => unknown | Promise<unknown>;
236
+ /** @deprecated `brick build` no longer emits handler factories; see `bindCompiledApplication`. */
237
+ type HandlerFactory = (binding: CompiledRoutePlan, runtime: typeof compilerRuntime) => CompiledHandler;
238
+ interface Checker {
239
+ Check(value: unknown): boolean;
240
+ Errors(value: unknown): Iterable<any>;
241
+ }
242
+ /** Everything one route needs to answer a request, worked out once at startup. */
243
+ interface CompiledRoutePlan {
244
+ readonly route: RouteIR;
245
+ readonly service: ServicePort;
246
+ readonly action: Action<any, any, any, any>;
247
+ readonly execute: (params: any) => unknown;
248
+ readonly authorize?: (params: any) => boolean | Promise<boolean>;
249
+ readonly contextHook?: (baseCtx: any) => unknown;
250
+ readonly inputChecker?: Checker;
251
+ readonly outputChecker?: Checker;
252
+ /** A plugin's check that runs before `inputChecker`. */
253
+ readonly checkInput?: (input: unknown) => ValidationErrorItem[] | undefined;
254
+ readonly errorBuilder: unknown;
255
+ readonly logger: Logger;
256
+ readonly cachedDb: unknown;
257
+ /** The deps of the plugin install that created the action; else the service's. */
258
+ readonly deps?: Readonly<Record<string, unknown>>;
259
+ }
260
+ /** A refused `authorize`: 401 without a user, 403 with one. */
261
+ declare function deny(action: string, user: unknown): never;
262
+ /** The HTTP handler of one route: the pipeline's stages, synchronous when no stage needs to wait. */
263
+ declare function bindRoute(plan: CompiledRoutePlan): CompiledHandler;
264
+ /** What `bindCompiledApplication`'s handler factories receive. */
265
+ declare const compilerRuntime: Readonly<{
266
+ bindRoute: typeof bindRoute;
267
+ }>;
268
+ /**
269
+ * Build artifact bootstrap: import the app and check that its definitions
270
+ * still match the IR `brick build` compiled.
271
+ *
272
+ * @throws When the app's definitions differ from `ir`.
273
+ */
274
+ declare function loadCompiledBrickApp(load: () => Promise<{
275
+ default: unknown;
276
+ }>, ir: BrickIR): Promise<BrickApp>;
277
+ interface CompiledRoute {
278
+ readonly ir: RouteIR;
279
+ readonly handler: CompiledHandler;
280
+ }
281
+ interface CompiledApplication {
282
+ readonly ir: BrickIR;
283
+ readonly routes: readonly CompiledRoute[];
284
+ }
285
+ /** Startup compiler: analyzes once, then binds live callbacks. */
286
+ declare function compileBrickApplication(options: {
287
+ services: Service<any, any>[];
288
+ prefix?: string;
289
+ /** `"generic"` skips the plugins' preparations (no prewarm). */
290
+ mode?: "specialized" | "generic";
291
+ }): CompiledApplication;
292
+ /**
293
+ * Build artifact binder: consumes emitted functions, with no runtime handler code generation.
294
+ *
295
+ * @deprecated `brick build` no longer emits handler factories; built servers
296
+ * use `loadCompiledBrickApp`. Pass `compileBrickApplication(...)` as
297
+ * `brick({ compilation })` instead.
298
+ */
299
+ declare function bindCompiledApplication(ir: BrickIR, services: Service<any, any>[], factories: readonly HandlerFactory[]): CompiledApplication;
300
+ interface RequestLoggingOptions {
301
+ enabled?: boolean;
302
+ logger?: (msg: string) => void;
303
+ }
304
+ /**
305
+ * Elysia plugin that logs each request as `METHOD path → status (elapsedms)`.
306
+ * Timing is tracked per-Request via a WeakMap. The onError hook only logs and
307
+ * returns undefined so existing error mapping is preserved.
308
+ *
309
+ * Hooks are registered with the "global" scope so they propagate to the
310
+ * parent app when mounted via `app.use(...)` — Elysia scopes plain instance
311
+ * hooks to the plugin's own routes. Timing is captured in beforeHandle
312
+ * because request hooks are not propagated from a
313
+ * used instance. Unmatched routes (no beforeHandle) fall back to Date.now().
314
+ */
315
+ declare function requestLoggingPlugin(opts?: RequestLoggingOptions): Elysia;
316
+ /**
317
+ * Which origins may call the app: an exact origin (`"https://app.example.com"`),
318
+ * a list of them, or a predicate. `true` allows only the app's own origin.
319
+ */
320
+ type CorsOrigin = true | string | readonly string[] | ((origin: string, request: Request) => boolean);
321
+ /** `brick({ cors })`: an origin rule, or the rule plus `credentials`. */
322
+ type CorsOptions = CorsOrigin | {
323
+ /** Default `true`: the app's own origin only. */
324
+ origin?: CorsOrigin;
325
+ /** Send `Access-Control-Allow-Credentials: true` to allowed origins (cookies, auth headers). */
326
+ credentials?: boolean;
327
+ };
328
+ interface CreateServerOptions {
329
+ port?: number;
330
+ /** Run the plugins' preparations (such as CRUD's prepared queries) at startup (default true). */
331
+ compiler?: boolean;
332
+ /** Ahead-of-time handlers already bound to the supplied services. */
333
+ compilation?: CompiledApplication;
334
+ services?: Service<any, any>[];
335
+ prefix?: string;
336
+ title?: string;
337
+ version?: string;
338
+ description?: string;
339
+ docs?: boolean;
340
+ openApiPath?: string;
341
+ docsPath?: string;
342
+ swaggerPath?: string;
343
+ requestLogging?: boolean | RequestLoggingOptions;
344
+ /**
345
+ * `true` serves a Scalar page at /reference. Options serve one only with a
346
+ * `path`; `documents` adds OpenAPI documents to the dashboard's APIs view.
347
+ */
348
+ reference?: boolean | ReferenceOptions;
349
+ secrets?: {
350
+ source?: SecretSource;
351
+ validate?: boolean;
352
+ };
353
+ /** Raw endpoints (plain routes, not actions), mounted at startup. */
354
+ endpoints?: EndpointDefinition[];
355
+ /**
356
+ * Record request, action, and RPC spans with OpenTelemetry (default false).
357
+ * Spans go to the globally registered tracer provider; without one they are
358
+ * no-ops. `brick dev` shows them in its dashboard.
359
+ */
360
+ telemetry?: boolean;
361
+ /**
362
+ * Developer documentation for the `brick dev` dashboard (its Docs tab): a
363
+ * folder of `.md`/`.mdx` pages in Fumadocs' layout, with frontmatter and
364
+ * `meta.json` for ordering. A string is the folder. Relative paths start at
365
+ * the folder of the app entry, as they read in the file that sets them (from
366
+ * `src/app.ts`, `"../docs"` is `docs/` at the project root). Needs
367
+ * `fumadocs-core` and `@mdx-js/mdx` installed.
368
+ */
369
+ documentation?: string | DocumentationOptions;
370
+ /**
371
+ * Monitoring dashboard for `brick start`, on a port of its own and behind
372
+ * `auth`. Setting it turns on `telemetry`. See `DashboardOptions`.
373
+ */
374
+ dashboard?: DashboardOptions;
375
+ /**
376
+ * Record events in the same database transaction as the writes that cause them,
377
+ * and deliver them to listeners after the commit. Generated CRUD writes emit
378
+ * `<resource>.create`, `<resource>.update` and `<resource>.delete`. A service
379
+ * records events once its database holds an `outboxTable()`. Reads emit nothing,
380
+ * and an app without this option behaves exactly as before. See `EventsOptions`.
381
+ */
382
+ events?: EventsOptions;
383
+ /**
384
+ * Socket fan-out. `broker` carries emits and kicks between processes
385
+ * (default: this process only). See `redisBroker`. The app closes it on stop.
386
+ * `secret` signs replay sequences; give every process the same one so a
387
+ * client can resume on any of them (default: random per process).
388
+ */
389
+ sockets?: {
390
+ broker?: SocketBroker;
391
+ secret?: string;
392
+ };
393
+ /**
394
+ * The values of the services' declared `deps` (`port<T>()`), by name. Every
395
+ * declared dep must be provided, and every provided one declared. Actions read
396
+ * them as `ctx.deps`, listeners and workflow steps with `useDeps()`.
397
+ */
398
+ deps?: Record<string, unknown>;
399
+ /**
400
+ * App-wide plugins from `definePlugin`, in install order: their `app` part
401
+ * adds start/stop lifecycle, middleware and listeners. Plugins installed with
402
+ * `service.use()` or `resource.use()` take part too, before these.
403
+ */
404
+ plugins?: readonly PluginInstance<any, any>[];
405
+ /**
406
+ * CORS for browser callers on other origins. `true` allows the app's own
407
+ * origin; a string, list or predicate names the allowed origins, compared
408
+ * exactly. `{ origin, credentials }` adds `credentials: true` for cookies.
409
+ * Other origins get no `Access-Control-Allow-Origin`. Preflights are answered.
410
+ */
411
+ cors?: false | CorsOptions;
412
+ }
413
+ /**
414
+ * Create the HTTP application: an Elysia app that serves every service's
415
+ * actions (and the tools that opt in with `http: true`) as routes, with
416
+ * `/_health`, an OpenAPI document at `/openapi.json`, Scalar at `/docs`,
417
+ * Swagger UI at `/swagger`, and the shape of the services at `/_brick/services`.
418
+ *
419
+ * Services come from the global registry unless `services` is given. The app
420
+ * does not listen by itself: export it from your entry file, where `brick dev`,
421
+ * `brick start`, and the Vite plugin load it, or call `app.listen(port)` in your
422
+ * own server bootstrap.
423
+ *
424
+ * @param options - `prefix` for action routes (default `/api`), `services`,
425
+ * `title`, `version`, and `description` for the OpenAPI document, `docs` and the
426
+ * paths of its pages, `requestLogging`, `reference`, `endpoints`, `secrets`,
427
+ * `telemetry`, `documentation`, `dashboard`, and `deps`. See `CreateServerOptions`.
428
+ * @returns The app, with `definition` (its services, prefix, and routes),
429
+ * `endpoint()` to add raw routes, and `listEndpoints()` to list them.
430
+ * @throws When a required secret is missing, `documentation` or `dashboard`
431
+ * is invalid, or `deps` misses a dep a service declares or has one none declares.
432
+ * @example
433
+ * import { brick } from "@brickkit/core";
434
+ * import { pagesService } from "./services/pages";
435
+ *
436
+ * export default brick({
437
+ * services: [pagesService],
438
+ * title: "Pages API",
439
+ * telemetry: true,
440
+ * });
441
+ */
442
+ declare function brick(options?: CreateServerOptions): BrickApp;
443
+ export { scalarDocsHTML as A, ApiDocument as C, ReferenceOptions as D, ReferenceDocument as E, RouteIR as M, RouteMethod as N, referencePlugin as O, DashboardOptions as S, OpenApiDocument as T, EndpointContext as _, RequestLoggingOptions as a, EndpointMethod as b, CompiledRoute as c, loadCompiledBrickApp as d, CompiledHandler as f, BrickApp as g, deny as h, CorsOrigin as i, BrickIR as j, registerReferenceRoute as k, bindCompiledApplication as l, HandlerFactory as m, brick as n, requestLoggingPlugin as o, CompiledRoutePlan as p, CorsOptions as r, CompiledApplication as s, CreateServerOptions as t, compileBrickApplication as u, EndpointDefinition as v, DocumentationOptions as w, DashboardAuth as x, EndpointLogger as y };
444
+ //# sourceMappingURL=server.d.ts.map