@shaferllc/keel 0.36.0 → 0.58.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 +14 -2
- package/dist/core/application.d.ts +58 -2
- package/dist/core/application.js +99 -3
- package/dist/core/authorization.d.ts +52 -0
- package/dist/core/authorization.js +97 -0
- package/dist/core/broadcasting.d.ts +49 -0
- package/dist/core/broadcasting.js +84 -0
- package/dist/core/broker.d.ts +398 -0
- package/dist/core/broker.js +602 -0
- package/dist/core/crypto.d.ts +1 -1
- package/dist/core/crypto.js +12 -3
- package/dist/core/database.d.ts +26 -1
- package/dist/core/database.js +65 -2
- package/dist/core/decorators.d.ts +39 -0
- package/dist/core/decorators.js +72 -0
- package/dist/core/exceptions.d.ts +77 -6
- package/dist/core/exceptions.js +168 -10
- package/dist/core/helpers.d.ts +6 -0
- package/dist/core/helpers.js +12 -0
- package/dist/core/http/kernel.js +14 -2
- package/dist/core/http/router.d.ts +14 -0
- package/dist/core/http/router.js +30 -1
- package/dist/core/index.d.ts +28 -6
- package/dist/core/index.js +15 -3
- package/dist/core/logger.d.ts +5 -0
- package/dist/core/logger.js +24 -2
- package/dist/core/migrations.js +3 -3
- package/dist/core/model.d.ts +19 -1
- package/dist/core/model.js +72 -4
- package/dist/core/provider.d.ts +13 -4
- package/dist/core/provider.js +12 -2
- package/dist/core/redis.d.ts +78 -0
- package/dist/core/redis.js +176 -0
- package/dist/core/request-logger.d.ts +26 -0
- package/dist/core/request-logger.js +48 -0
- package/dist/core/request.d.ts +17 -1
- package/dist/core/request.js +27 -1
- package/dist/core/scheduler.d.ts +60 -0
- package/dist/core/scheduler.js +166 -0
- package/dist/core/session.js +17 -2
- package/dist/core/storage.d.ts +57 -0
- package/dist/core/storage.js +98 -0
- package/dist/core/template.d.ts +50 -0
- package/dist/core/template.js +753 -0
- package/dist/core/testing.d.ts +54 -0
- package/dist/core/testing.js +141 -0
- package/dist/core/transformer.d.ts +89 -0
- package/dist/core/transformer.js +152 -0
- package/dist/core/validation.d.ts +20 -0
- package/dist/core/validation.js +52 -1
- package/dist/core/vite.d.ts +117 -0
- package/dist/core/vite.js +258 -0
- package/dist/vite/index.d.ts +40 -0
- package/dist/vite/index.js +146 -0
- package/package.json +16 -1
package/dist/core/database.js
CHANGED
|
@@ -65,10 +65,30 @@ export class QueryBuilder {
|
|
|
65
65
|
this.wheres.push({ boolean: "AND", sql: `${column} IS NOT NULL`, bindings: [] });
|
|
66
66
|
return this;
|
|
67
67
|
}
|
|
68
|
+
whereNotIn(column, values) {
|
|
69
|
+
const marks = values.map(() => "?").join(", ");
|
|
70
|
+
this.wheres.push({ boolean: "AND", sql: `${column} NOT IN (${marks})`, bindings: values });
|
|
71
|
+
return this;
|
|
72
|
+
}
|
|
73
|
+
whereBetween(column, [min, max]) {
|
|
74
|
+
this.wheres.push({ boolean: "AND", sql: `${column} BETWEEN ? AND ?`, bindings: [min, max] });
|
|
75
|
+
return this;
|
|
76
|
+
}
|
|
77
|
+
whereLike(column, pattern) {
|
|
78
|
+
this.wheres.push({ boolean: "AND", sql: `${column} LIKE ?`, bindings: [pattern] });
|
|
79
|
+
return this;
|
|
80
|
+
}
|
|
68
81
|
orderBy(column, direction = "asc") {
|
|
69
82
|
this.orders.push(`${column} ${direction.toUpperCase()}`);
|
|
70
83
|
return this;
|
|
71
84
|
}
|
|
85
|
+
/** Newest-first / oldest-first by a timestamp column (default `created_at`). */
|
|
86
|
+
latest(column = "created_at") {
|
|
87
|
+
return this.orderBy(column, "desc");
|
|
88
|
+
}
|
|
89
|
+
oldest(column = "created_at") {
|
|
90
|
+
return this.orderBy(column, "asc");
|
|
91
|
+
}
|
|
72
92
|
limit(n) {
|
|
73
93
|
this._limit = n;
|
|
74
94
|
return this;
|
|
@@ -94,7 +114,7 @@ export class QueryBuilder {
|
|
|
94
114
|
sql += ` LIMIT ${this._limit}`;
|
|
95
115
|
if (this._offset != null)
|
|
96
116
|
sql += ` OFFSET ${this._offset}`;
|
|
97
|
-
return conn().select(placeholders(sql), where.bindings);
|
|
117
|
+
return (await conn().select(placeholders(sql), where.bindings));
|
|
98
118
|
}
|
|
99
119
|
async first() {
|
|
100
120
|
this._limit = 1;
|
|
@@ -103,12 +123,55 @@ export class QueryBuilder {
|
|
|
103
123
|
}
|
|
104
124
|
async count() {
|
|
105
125
|
const where = this.whereClause();
|
|
106
|
-
const rows = await conn().select(placeholders(`SELECT COUNT(*) AS count FROM ${this.table}${where.sql}`), where.bindings);
|
|
126
|
+
const rows = (await conn().select(placeholders(`SELECT COUNT(*) AS count FROM ${this.table}${where.sql}`), where.bindings));
|
|
107
127
|
return Number(rows[0]?.count ?? 0);
|
|
108
128
|
}
|
|
109
129
|
async exists() {
|
|
110
130
|
return (await this.count()) > 0;
|
|
111
131
|
}
|
|
132
|
+
async aggregate(fn, column) {
|
|
133
|
+
const where = this.whereClause();
|
|
134
|
+
const rows = (await conn().select(placeholders(`SELECT ${fn}(${column}) AS agg FROM ${this.table}${where.sql}`), where.bindings));
|
|
135
|
+
return Number(rows[0]?.agg ?? 0);
|
|
136
|
+
}
|
|
137
|
+
sum(column) {
|
|
138
|
+
return this.aggregate("SUM", column);
|
|
139
|
+
}
|
|
140
|
+
avg(column) {
|
|
141
|
+
return this.aggregate("AVG", column);
|
|
142
|
+
}
|
|
143
|
+
min(column) {
|
|
144
|
+
return this.aggregate("MIN", column);
|
|
145
|
+
}
|
|
146
|
+
max(column) {
|
|
147
|
+
return this.aggregate("MAX", column);
|
|
148
|
+
}
|
|
149
|
+
/** The value of a single column from the first matching row (or null). */
|
|
150
|
+
async value(column) {
|
|
151
|
+
this.columns = column;
|
|
152
|
+
const row = await this.first();
|
|
153
|
+
return row ? row[column] : null;
|
|
154
|
+
}
|
|
155
|
+
/** An array of a single column across all matching rows. */
|
|
156
|
+
async pluck(column) {
|
|
157
|
+
this.columns = column;
|
|
158
|
+
const rows = await this.get();
|
|
159
|
+
return rows.map((row) => row[column]);
|
|
160
|
+
}
|
|
161
|
+
/** A page of results plus pagination metadata. */
|
|
162
|
+
async paginate(page = 1, perPage = 15) {
|
|
163
|
+
const total = await this.count();
|
|
164
|
+
this._limit = perPage;
|
|
165
|
+
this._offset = (Math.max(1, page) - 1) * perPage;
|
|
166
|
+
const data = await this.get();
|
|
167
|
+
return {
|
|
168
|
+
data,
|
|
169
|
+
total,
|
|
170
|
+
perPage,
|
|
171
|
+
currentPage: page,
|
|
172
|
+
lastPage: Math.max(1, Math.ceil(total / perPage)),
|
|
173
|
+
};
|
|
174
|
+
}
|
|
112
175
|
/* ------------------------------- writes ------------------------------ */
|
|
113
176
|
async insert(data) {
|
|
114
177
|
const keys = Object.keys(data);
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Request decorators — attach named, computed values to the current request,
|
|
3
|
+
* resolved lazily and memoized for the life of that request. Inspired by
|
|
4
|
+
* Fastify's `decorateRequest`, but without its footguns: you register a resolver
|
|
5
|
+
* once, and Keel computes it on first access and caches it per request (keyed off
|
|
6
|
+
* the Hono context via a WeakMap, so there's no shared-state leak between
|
|
7
|
+
* requests and no V8 shape deopt to design around).
|
|
8
|
+
*
|
|
9
|
+
* decorateRequest("user", async (c) => findUser(c.req.header("authorization")));
|
|
10
|
+
*
|
|
11
|
+
* // anywhere in the request — computed once, then cached:
|
|
12
|
+
* const user = await decorated<User>("user");
|
|
13
|
+
*
|
|
14
|
+
* (Decorating the *application* is already the service container's job —
|
|
15
|
+
* `bind` / `singleton` / `instance` / `make`, with `bound()` as `hasDecorator`.)
|
|
16
|
+
*/
|
|
17
|
+
import type { Context } from "hono";
|
|
18
|
+
/** Resolves a decorator's value from the current request context. */
|
|
19
|
+
export type RequestResolver<T = unknown> = (c: Context) => T | Promise<T>;
|
|
20
|
+
/**
|
|
21
|
+
* Register a request decorator. Throws if `name` is already registered — a
|
|
22
|
+
* collision guard, like Fastify's.
|
|
23
|
+
*/
|
|
24
|
+
export declare function decorateRequest<T>(name: string, resolver: RequestResolver<T>): void;
|
|
25
|
+
/** Whether a request decorator has been registered. */
|
|
26
|
+
export declare function hasRequestDecorator(name: string): boolean;
|
|
27
|
+
/**
|
|
28
|
+
* The value of a decorator for the current request — computed on first access
|
|
29
|
+
* via its resolver, then cached for the rest of the request. Always returns a
|
|
30
|
+
* promise (resolvers may be async).
|
|
31
|
+
*/
|
|
32
|
+
export declare function decorated<T = unknown>(name: string): Promise<T>;
|
|
33
|
+
/**
|
|
34
|
+
* Imperatively set a decorator's value for the current request, overriding the
|
|
35
|
+
* resolver — e.g. from an auth middleware that already resolved the user.
|
|
36
|
+
*/
|
|
37
|
+
export declare function setRequestValue<T>(name: string, value: T): void;
|
|
38
|
+
/** Clear all registered decorators (test helper). */
|
|
39
|
+
export declare function clearRequestDecorators(): void;
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Request decorators — attach named, computed values to the current request,
|
|
3
|
+
* resolved lazily and memoized for the life of that request. Inspired by
|
|
4
|
+
* Fastify's `decorateRequest`, but without its footguns: you register a resolver
|
|
5
|
+
* once, and Keel computes it on first access and caches it per request (keyed off
|
|
6
|
+
* the Hono context via a WeakMap, so there's no shared-state leak between
|
|
7
|
+
* requests and no V8 shape deopt to design around).
|
|
8
|
+
*
|
|
9
|
+
* decorateRequest("user", async (c) => findUser(c.req.header("authorization")));
|
|
10
|
+
*
|
|
11
|
+
* // anywhere in the request — computed once, then cached:
|
|
12
|
+
* const user = await decorated<User>("user");
|
|
13
|
+
*
|
|
14
|
+
* (Decorating the *application* is already the service container's job —
|
|
15
|
+
* `bind` / `singleton` / `instance` / `make`, with `bound()` as `hasDecorator`.)
|
|
16
|
+
*/
|
|
17
|
+
import { ctx } from "./request.js";
|
|
18
|
+
const resolvers = new Map();
|
|
19
|
+
// Per-request memo, keyed by the context object so it's GC'd with the request.
|
|
20
|
+
const memo = new WeakMap();
|
|
21
|
+
function bag(c) {
|
|
22
|
+
let b = memo.get(c);
|
|
23
|
+
if (!b) {
|
|
24
|
+
b = new Map();
|
|
25
|
+
memo.set(c, b);
|
|
26
|
+
}
|
|
27
|
+
return b;
|
|
28
|
+
}
|
|
29
|
+
/**
|
|
30
|
+
* Register a request decorator. Throws if `name` is already registered — a
|
|
31
|
+
* collision guard, like Fastify's.
|
|
32
|
+
*/
|
|
33
|
+
export function decorateRequest(name, resolver) {
|
|
34
|
+
if (resolvers.has(name)) {
|
|
35
|
+
throw new Error(`Request decorator "${name}" is already registered.`);
|
|
36
|
+
}
|
|
37
|
+
resolvers.set(name, resolver);
|
|
38
|
+
}
|
|
39
|
+
/** Whether a request decorator has been registered. */
|
|
40
|
+
export function hasRequestDecorator(name) {
|
|
41
|
+
return resolvers.has(name);
|
|
42
|
+
}
|
|
43
|
+
/**
|
|
44
|
+
* The value of a decorator for the current request — computed on first access
|
|
45
|
+
* via its resolver, then cached for the rest of the request. Always returns a
|
|
46
|
+
* promise (resolvers may be async).
|
|
47
|
+
*/
|
|
48
|
+
export function decorated(name) {
|
|
49
|
+
const c = ctx();
|
|
50
|
+
const b = bag(c);
|
|
51
|
+
if (b.has(name))
|
|
52
|
+
return Promise.resolve(b.get(name));
|
|
53
|
+
const resolver = resolvers.get(name);
|
|
54
|
+
if (!resolver) {
|
|
55
|
+
throw new Error(`No request decorator "${name}". Register it with decorateRequest().`);
|
|
56
|
+
}
|
|
57
|
+
// Memoize the promise so concurrent access computes once.
|
|
58
|
+
const result = Promise.resolve(resolver(c));
|
|
59
|
+
b.set(name, result);
|
|
60
|
+
return result;
|
|
61
|
+
}
|
|
62
|
+
/**
|
|
63
|
+
* Imperatively set a decorator's value for the current request, overriding the
|
|
64
|
+
* resolver — e.g. from an auth middleware that already resolved the user.
|
|
65
|
+
*/
|
|
66
|
+
export function setRequestValue(name, value) {
|
|
67
|
+
bag(ctx()).set(name, value);
|
|
68
|
+
}
|
|
69
|
+
/** Clear all registered decorators (test helper). */
|
|
70
|
+
export function clearRequestDecorators() {
|
|
71
|
+
resolvers.clear();
|
|
72
|
+
}
|
|
@@ -17,19 +17,90 @@ export declare class HttpException extends Error {
|
|
|
17
17
|
readonly headers?: Record<string, string>;
|
|
18
18
|
/** A machine-readable error code, e.g. "E_VALIDATION". */
|
|
19
19
|
code?: string;
|
|
20
|
-
|
|
20
|
+
/** Structured context attached to the error; surfaced in the JSON body as `data`. */
|
|
21
|
+
data?: unknown;
|
|
22
|
+
constructor(status: number, message?: string, headers?: Record<string, string>, data?: unknown);
|
|
23
|
+
/**
|
|
24
|
+
* The error as a plain object, matching the JSON body the HTTP kernel renders:
|
|
25
|
+
* `{ error, status }` plus `code` and `data` when present. Subclasses that add
|
|
26
|
+
* fields (e.g. `ValidationException.errors`) override this to include them.
|
|
27
|
+
*/
|
|
28
|
+
toJSON(): Record<string, unknown>;
|
|
21
29
|
}
|
|
22
|
-
|
|
23
|
-
|
|
30
|
+
/** 400 — the request was malformed or failed validation. */
|
|
31
|
+
export declare class BadRequestException extends HttpException {
|
|
32
|
+
constructor(message?: string, data?: unknown);
|
|
24
33
|
}
|
|
25
34
|
export declare class UnauthorizedException extends HttpException {
|
|
26
|
-
constructor(message?: string);
|
|
35
|
+
constructor(message?: string, data?: unknown);
|
|
36
|
+
}
|
|
37
|
+
/** 402 — payment is required to access the resource. */
|
|
38
|
+
export declare class PaymentRequiredException extends HttpException {
|
|
39
|
+
constructor(message?: string, data?: unknown);
|
|
27
40
|
}
|
|
28
41
|
export declare class ForbiddenException extends HttpException {
|
|
29
|
-
constructor(message?: string);
|
|
42
|
+
constructor(message?: string, data?: unknown);
|
|
43
|
+
}
|
|
44
|
+
export declare class NotFoundException extends HttpException {
|
|
45
|
+
constructor(message?: string, data?: unknown);
|
|
46
|
+
}
|
|
47
|
+
/** 405 — the HTTP method isn't allowed for this resource. */
|
|
48
|
+
export declare class MethodNotAllowedException extends HttpException {
|
|
49
|
+
constructor(message?: string, data?: unknown);
|
|
50
|
+
}
|
|
51
|
+
/** 406 — no representation matches the request's `Accept` header. */
|
|
52
|
+
export declare class NotAcceptableException extends HttpException {
|
|
53
|
+
constructor(message?: string, data?: unknown);
|
|
54
|
+
}
|
|
55
|
+
/** 408 — the client took too long to send the request. */
|
|
56
|
+
export declare class RequestTimeoutException extends HttpException {
|
|
57
|
+
constructor(message?: string, data?: unknown);
|
|
58
|
+
}
|
|
59
|
+
/** 409 — the request conflicts with the current state (e.g. a duplicate). */
|
|
60
|
+
export declare class ConflictException extends HttpException {
|
|
61
|
+
constructor(message?: string, data?: unknown);
|
|
62
|
+
}
|
|
63
|
+
/** 411 — a `Content-Length` header is required and was missing. */
|
|
64
|
+
export declare class LengthRequiredException extends HttpException {
|
|
65
|
+
constructor(message?: string, data?: unknown);
|
|
30
66
|
}
|
|
31
|
-
/** 422 with per-field messages. Pairs with
|
|
67
|
+
/** 422 with per-field messages. Pairs with the validation layer. */
|
|
32
68
|
export declare class ValidationException extends HttpException {
|
|
33
69
|
readonly errors: Record<string, string[]>;
|
|
34
70
|
constructor(errors: Record<string, string[]>, message?: string);
|
|
71
|
+
toJSON(): Record<string, unknown>;
|
|
35
72
|
}
|
|
73
|
+
/** 429 — the client has sent too many requests in a given window. */
|
|
74
|
+
export declare class TooManyRequestsException extends HttpException {
|
|
75
|
+
constructor(message?: string, data?: unknown);
|
|
76
|
+
}
|
|
77
|
+
/** 500 — a catch-all server error you want to raise deliberately. */
|
|
78
|
+
export declare class ServerErrorException extends HttpException {
|
|
79
|
+
constructor(message?: string, data?: unknown);
|
|
80
|
+
}
|
|
81
|
+
/** 501 — the requested functionality isn't implemented. */
|
|
82
|
+
export declare class NotImplementedException extends HttpException {
|
|
83
|
+
constructor(message?: string, data?: unknown);
|
|
84
|
+
}
|
|
85
|
+
/** 502 — an upstream server returned an invalid response. */
|
|
86
|
+
export declare class BadGatewayException extends HttpException {
|
|
87
|
+
constructor(message?: string, data?: unknown);
|
|
88
|
+
}
|
|
89
|
+
/** 503 — the service is temporarily unavailable (down, overloaded). */
|
|
90
|
+
export declare class ServiceUnavailableException extends HttpException {
|
|
91
|
+
constructor(message?: string, data?: unknown);
|
|
92
|
+
}
|
|
93
|
+
/**
|
|
94
|
+
* Mint a reusable, coded `HttpException` subclass — the ergonomic way to define
|
|
95
|
+
* app-specific errors with a stable, machine-readable `code`. Inspired by
|
|
96
|
+
* `@fastify/error`. The `message` may carry `%s` placeholders, filled in order
|
|
97
|
+
* from the constructor arguments.
|
|
98
|
+
*
|
|
99
|
+
* const InsufficientFunds = createError("E_FUNDS", "Balance too low: need %s", 402);
|
|
100
|
+
* throw new InsufficientFunds("$40");
|
|
101
|
+
* // → 402 { error: "Balance too low: need $40", status: 402, code: "E_FUNDS" }
|
|
102
|
+
*
|
|
103
|
+
* The returned class extends `HttpException`, so it renders through the same
|
|
104
|
+
* path — `code` lands in the JSON body — and passes `instanceof HttpException`.
|
|
105
|
+
*/
|
|
106
|
+
export declare function createError(code: string, message: string, status?: number): new (...args: (string | number)[]) => HttpException;
|
package/dist/core/exceptions.js
CHANGED
|
@@ -6,14 +6,20 @@
|
|
|
6
6
|
export const STATUS_TEXT = {
|
|
7
7
|
400: "Bad Request",
|
|
8
8
|
401: "Unauthorized",
|
|
9
|
+
402: "Payment Required",
|
|
9
10
|
403: "Forbidden",
|
|
10
11
|
404: "Not Found",
|
|
11
12
|
405: "Method Not Allowed",
|
|
13
|
+
406: "Not Acceptable",
|
|
14
|
+
408: "Request Timeout",
|
|
12
15
|
409: "Conflict",
|
|
16
|
+
411: "Length Required",
|
|
13
17
|
419: "Page Expired",
|
|
14
18
|
422: "Unprocessable Entity",
|
|
15
19
|
429: "Too Many Requests",
|
|
16
20
|
500: "Internal Server Error",
|
|
21
|
+
501: "Not Implemented",
|
|
22
|
+
502: "Bad Gateway",
|
|
17
23
|
503: "Service Unavailable",
|
|
18
24
|
};
|
|
19
25
|
/**
|
|
@@ -29,37 +35,189 @@ export class HttpException extends Error {
|
|
|
29
35
|
headers;
|
|
30
36
|
/** A machine-readable error code, e.g. "E_VALIDATION". */
|
|
31
37
|
code;
|
|
32
|
-
|
|
38
|
+
/** Structured context attached to the error; surfaced in the JSON body as `data`. */
|
|
39
|
+
data;
|
|
40
|
+
constructor(status, message, headers, data) {
|
|
33
41
|
super(message ?? STATUS_TEXT[status] ?? "Error");
|
|
34
42
|
this.name = "HttpException";
|
|
35
43
|
this.status = status;
|
|
36
44
|
this.headers = headers;
|
|
45
|
+
this.data = data;
|
|
46
|
+
}
|
|
47
|
+
/**
|
|
48
|
+
* The error as a plain object, matching the JSON body the HTTP kernel renders:
|
|
49
|
+
* `{ error, status }` plus `code` and `data` when present. Subclasses that add
|
|
50
|
+
* fields (e.g. `ValidationException.errors`) override this to include them.
|
|
51
|
+
*/
|
|
52
|
+
toJSON() {
|
|
53
|
+
const body = { error: this.message, status: this.status };
|
|
54
|
+
if (this.code)
|
|
55
|
+
body.code = this.code;
|
|
56
|
+
if (this.data !== undefined)
|
|
57
|
+
body.data = this.data;
|
|
58
|
+
return body;
|
|
37
59
|
}
|
|
38
60
|
}
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
61
|
+
/*
|
|
62
|
+
* The standard HTTP error family. Each carries a fixed status and a stable
|
|
63
|
+
* `code`, and takes an optional `data` bag that lands in the JSON body. Throw
|
|
64
|
+
* any of them from a handler, middleware, or service to short-circuit with the
|
|
65
|
+
* right status. Ordered by status code.
|
|
66
|
+
*/
|
|
67
|
+
/** 400 — the request was malformed or failed validation. */
|
|
68
|
+
export class BadRequestException extends HttpException {
|
|
69
|
+
constructor(message = "Bad Request", data) {
|
|
70
|
+
super(400, message, undefined, data);
|
|
71
|
+
this.name = "BadRequestException";
|
|
72
|
+
this.code = "E_BAD_REQUEST";
|
|
43
73
|
}
|
|
44
74
|
}
|
|
45
75
|
export class UnauthorizedException extends HttpException {
|
|
46
|
-
constructor(message = "Unauthorized") {
|
|
47
|
-
super(401, message);
|
|
76
|
+
constructor(message = "Unauthorized", data) {
|
|
77
|
+
super(401, message, undefined, data);
|
|
48
78
|
this.name = "UnauthorizedException";
|
|
79
|
+
this.code = "E_UNAUTHORIZED";
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
/** 402 — payment is required to access the resource. */
|
|
83
|
+
export class PaymentRequiredException extends HttpException {
|
|
84
|
+
constructor(message = "Payment Required", data) {
|
|
85
|
+
super(402, message, undefined, data);
|
|
86
|
+
this.name = "PaymentRequiredException";
|
|
87
|
+
this.code = "E_PAYMENT_REQUIRED";
|
|
49
88
|
}
|
|
50
89
|
}
|
|
51
90
|
export class ForbiddenException extends HttpException {
|
|
52
|
-
constructor(message = "Forbidden") {
|
|
53
|
-
super(403, message);
|
|
91
|
+
constructor(message = "Forbidden", data) {
|
|
92
|
+
super(403, message, undefined, data);
|
|
54
93
|
this.name = "ForbiddenException";
|
|
94
|
+
this.code = "E_FORBIDDEN";
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
export class NotFoundException extends HttpException {
|
|
98
|
+
constructor(message = "Not Found", data) {
|
|
99
|
+
super(404, message, undefined, data);
|
|
100
|
+
this.name = "NotFoundException";
|
|
101
|
+
this.code = "E_NOT_FOUND";
|
|
55
102
|
}
|
|
56
103
|
}
|
|
57
|
-
/**
|
|
104
|
+
/** 405 — the HTTP method isn't allowed for this resource. */
|
|
105
|
+
export class MethodNotAllowedException extends HttpException {
|
|
106
|
+
constructor(message = "Method Not Allowed", data) {
|
|
107
|
+
super(405, message, undefined, data);
|
|
108
|
+
this.name = "MethodNotAllowedException";
|
|
109
|
+
this.code = "E_METHOD_NOT_ALLOWED";
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
/** 406 — no representation matches the request's `Accept` header. */
|
|
113
|
+
export class NotAcceptableException extends HttpException {
|
|
114
|
+
constructor(message = "Not Acceptable", data) {
|
|
115
|
+
super(406, message, undefined, data);
|
|
116
|
+
this.name = "NotAcceptableException";
|
|
117
|
+
this.code = "E_NOT_ACCEPTABLE";
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
/** 408 — the client took too long to send the request. */
|
|
121
|
+
export class RequestTimeoutException extends HttpException {
|
|
122
|
+
constructor(message = "Request Timeout", data) {
|
|
123
|
+
super(408, message, undefined, data);
|
|
124
|
+
this.name = "RequestTimeoutException";
|
|
125
|
+
this.code = "E_REQUEST_TIMEOUT";
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
/** 409 — the request conflicts with the current state (e.g. a duplicate). */
|
|
129
|
+
export class ConflictException extends HttpException {
|
|
130
|
+
constructor(message = "Conflict", data) {
|
|
131
|
+
super(409, message, undefined, data);
|
|
132
|
+
this.name = "ConflictException";
|
|
133
|
+
this.code = "E_CONFLICT";
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
/** 411 — a `Content-Length` header is required and was missing. */
|
|
137
|
+
export class LengthRequiredException extends HttpException {
|
|
138
|
+
constructor(message = "Length Required", data) {
|
|
139
|
+
super(411, message, undefined, data);
|
|
140
|
+
this.name = "LengthRequiredException";
|
|
141
|
+
this.code = "E_LENGTH_REQUIRED";
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
/** 422 with per-field messages. Pairs with the validation layer. */
|
|
58
145
|
export class ValidationException extends HttpException {
|
|
59
146
|
errors;
|
|
60
147
|
constructor(errors, message = "The given data was invalid.") {
|
|
61
148
|
super(422, message);
|
|
62
149
|
this.name = "ValidationException";
|
|
150
|
+
this.code = "E_VALIDATION";
|
|
63
151
|
this.errors = errors;
|
|
64
152
|
}
|
|
153
|
+
toJSON() {
|
|
154
|
+
return { ...super.toJSON(), errors: this.errors };
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
/** 429 — the client has sent too many requests in a given window. */
|
|
158
|
+
export class TooManyRequestsException extends HttpException {
|
|
159
|
+
constructor(message = "Too Many Requests", data) {
|
|
160
|
+
super(429, message, undefined, data);
|
|
161
|
+
this.name = "TooManyRequestsException";
|
|
162
|
+
this.code = "E_TOO_MANY_REQUESTS";
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
/** 500 — a catch-all server error you want to raise deliberately. */
|
|
166
|
+
export class ServerErrorException extends HttpException {
|
|
167
|
+
constructor(message = "Internal Server Error", data) {
|
|
168
|
+
super(500, message, undefined, data);
|
|
169
|
+
this.name = "ServerErrorException";
|
|
170
|
+
this.code = "E_SERVER_ERROR";
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
/** 501 — the requested functionality isn't implemented. */
|
|
174
|
+
export class NotImplementedException extends HttpException {
|
|
175
|
+
constructor(message = "Not Implemented", data) {
|
|
176
|
+
super(501, message, undefined, data);
|
|
177
|
+
this.name = "NotImplementedException";
|
|
178
|
+
this.code = "E_NOT_IMPLEMENTED";
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
/** 502 — an upstream server returned an invalid response. */
|
|
182
|
+
export class BadGatewayException extends HttpException {
|
|
183
|
+
constructor(message = "Bad Gateway", data) {
|
|
184
|
+
super(502, message, undefined, data);
|
|
185
|
+
this.name = "BadGatewayException";
|
|
186
|
+
this.code = "E_BAD_GATEWAY";
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
/** 503 — the service is temporarily unavailable (down, overloaded). */
|
|
190
|
+
export class ServiceUnavailableException extends HttpException {
|
|
191
|
+
constructor(message = "Service Unavailable", data) {
|
|
192
|
+
super(503, message, undefined, data);
|
|
193
|
+
this.name = "ServiceUnavailableException";
|
|
194
|
+
this.code = "E_SERVICE_UNAVAILABLE";
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
/**
|
|
198
|
+
* Mint a reusable, coded `HttpException` subclass — the ergonomic way to define
|
|
199
|
+
* app-specific errors with a stable, machine-readable `code`. Inspired by
|
|
200
|
+
* `@fastify/error`. The `message` may carry `%s` placeholders, filled in order
|
|
201
|
+
* from the constructor arguments.
|
|
202
|
+
*
|
|
203
|
+
* const InsufficientFunds = createError("E_FUNDS", "Balance too low: need %s", 402);
|
|
204
|
+
* throw new InsufficientFunds("$40");
|
|
205
|
+
* // → 402 { error: "Balance too low: need $40", status: 402, code: "E_FUNDS" }
|
|
206
|
+
*
|
|
207
|
+
* The returned class extends `HttpException`, so it renders through the same
|
|
208
|
+
* path — `code` lands in the JSON body — and passes `instanceof HttpException`.
|
|
209
|
+
*/
|
|
210
|
+
export function createError(code, message, status = 500) {
|
|
211
|
+
return class extends HttpException {
|
|
212
|
+
constructor(...args) {
|
|
213
|
+
super(status, formatMessage(message, args));
|
|
214
|
+
this.name = code;
|
|
215
|
+
this.code = code;
|
|
216
|
+
}
|
|
217
|
+
};
|
|
218
|
+
}
|
|
219
|
+
/** printf-lite: replace each `%s` with the next argument, in order. */
|
|
220
|
+
function formatMessage(template, args) {
|
|
221
|
+
let index = 0;
|
|
222
|
+
return template.replace(/%s/g, () => (index < args.length ? String(args[index++]) : "%s"));
|
|
65
223
|
}
|
package/dist/core/helpers.d.ts
CHANGED
|
@@ -17,6 +17,12 @@ import { Logger } from "./logger.js";
|
|
|
17
17
|
export declare function setApplication(app: Application): void;
|
|
18
18
|
/** The active application container. Throws if none has been created. */
|
|
19
19
|
export declare function app(): Application;
|
|
20
|
+
/** Run a callback once the active application has booted (see `Application.onReady`). */
|
|
21
|
+
export declare function onReady(hook: (app: Application) => void | Promise<void>): void;
|
|
22
|
+
/** Register a graceful-shutdown hook on the active application (see `Application.onShutdown`). */
|
|
23
|
+
export declare function onShutdown(hook: (app: Application) => void | Promise<void>): void;
|
|
24
|
+
/** Gracefully terminate the active application, running its shutdown hooks. */
|
|
25
|
+
export declare function terminate(): Promise<void>;
|
|
20
26
|
/**
|
|
21
27
|
* Read configuration with dot notation: `config('app.name')`, or with a
|
|
22
28
|
* fallback: `config('app.port', 3000)`.
|
package/dist/core/helpers.js
CHANGED
|
@@ -24,6 +24,18 @@ export function app() {
|
|
|
24
24
|
}
|
|
25
25
|
return current;
|
|
26
26
|
}
|
|
27
|
+
/** Run a callback once the active application has booted (see `Application.onReady`). */
|
|
28
|
+
export function onReady(hook) {
|
|
29
|
+
app().onReady(hook);
|
|
30
|
+
}
|
|
31
|
+
/** Register a graceful-shutdown hook on the active application (see `Application.onShutdown`). */
|
|
32
|
+
export function onShutdown(hook) {
|
|
33
|
+
app().onShutdown(hook);
|
|
34
|
+
}
|
|
35
|
+
/** Gracefully terminate the active application, running its shutdown hooks. */
|
|
36
|
+
export function terminate() {
|
|
37
|
+
return app().terminate();
|
|
38
|
+
}
|
|
27
39
|
/**
|
|
28
40
|
* Read configuration with dot notation: `config('app.name')`, or with a
|
|
29
41
|
* fallback: `config('app.port', 3000)`.
|
package/dist/core/http/kernel.js
CHANGED
|
@@ -101,8 +101,18 @@ export class HttpKernel {
|
|
|
101
101
|
}
|
|
102
102
|
for (const route of routes) {
|
|
103
103
|
const fn = router.resolve(route.handler);
|
|
104
|
+
// Set the matched-route context *before* this route's middleware, so both
|
|
105
|
+
// route middleware and the handler can read `request.route` (incl. config).
|
|
106
|
+
const setRoute = async (c, next) => {
|
|
107
|
+
c.set("route", {
|
|
108
|
+
name: route.name,
|
|
109
|
+
pattern: route.path,
|
|
110
|
+
methods: route.methods,
|
|
111
|
+
config: route.config,
|
|
112
|
+
});
|
|
113
|
+
await next();
|
|
114
|
+
};
|
|
104
115
|
const honoHandler = async (c) => {
|
|
105
|
-
c.set("route", { name: route.name, pattern: route.path, methods: route.methods });
|
|
106
116
|
const result = await fn(c);
|
|
107
117
|
return typeof result === "string" ? c.html(result) : result;
|
|
108
118
|
};
|
|
@@ -111,7 +121,7 @@ export class HttpKernel {
|
|
|
111
121
|
for (const [param, rgx] of Object.entries(route.wheres)) {
|
|
112
122
|
path = path.replace(new RegExp(`:${param}(\\??)`), `:${param}{${rgx}}$1`);
|
|
113
123
|
}
|
|
114
|
-
const middleware = route.middleware.map((m) => router.resolveMiddleware(m));
|
|
124
|
+
const middleware = [setRoute, ...route.middleware.map((m) => router.resolveMiddleware(m))];
|
|
115
125
|
hono.on(route.methods, [path], ...middleware, honoHandler);
|
|
116
126
|
}
|
|
117
127
|
hono.notFound((c) => this.handle(new NotFoundException(`No route for ${c.req.method} ${c.req.path}`), c));
|
|
@@ -159,6 +169,8 @@ export class HttpKernel {
|
|
|
159
169
|
const body = { error: message, status };
|
|
160
170
|
if (isHttp && err.code)
|
|
161
171
|
body.code = err.code;
|
|
172
|
+
if (isHttp && err.data !== undefined)
|
|
173
|
+
body.data = err.data;
|
|
162
174
|
if (err instanceof ValidationException)
|
|
163
175
|
body.errors = err.errors;
|
|
164
176
|
if (debug && !isHttp && err instanceof Error) {
|
|
@@ -53,6 +53,8 @@ export interface RouteDefinition {
|
|
|
53
53
|
wheres: Record<string, string>;
|
|
54
54
|
/** Host pattern this route is bound to, e.g. ":tenant.example.com". */
|
|
55
55
|
domain?: string;
|
|
56
|
+
/** Arbitrary per-route metadata, readable in the handler via `request.route.config`. */
|
|
57
|
+
config: Record<string, unknown>;
|
|
56
58
|
}
|
|
57
59
|
/** A single registered route — chain to name it, guard it, or constrain params. */
|
|
58
60
|
export declare class Route {
|
|
@@ -70,6 +72,8 @@ export declare class Route {
|
|
|
70
72
|
where(param: string, matcher: Matcher): this;
|
|
71
73
|
/** Bind this route to a host pattern (supports `:subdomain` segments). */
|
|
72
74
|
domain(pattern: string): this;
|
|
75
|
+
/** Attach arbitrary metadata to the route — read it via `request.route.config`. */
|
|
76
|
+
config(data: Record<string, unknown>): this;
|
|
73
77
|
}
|
|
74
78
|
/** A group of routes sharing a prefix, middleware, and/or name prefix. */
|
|
75
79
|
export declare class RouteGroup {
|
|
@@ -79,6 +83,8 @@ export declare class RouteGroup {
|
|
|
79
83
|
middleware(mw: MiddlewareRef | MiddlewareRef[]): this;
|
|
80
84
|
/** Alias for middleware(), matching AdonisJS. */
|
|
81
85
|
use(mw: MiddlewareRef | MiddlewareRef[]): this;
|
|
86
|
+
/** Attach metadata to every route in the group (a route's own config wins). */
|
|
87
|
+
config(data: Record<string, unknown>): this;
|
|
82
88
|
/** Constrain a parameter across every route in the group. */
|
|
83
89
|
where(param: string, matcher: Matcher): this;
|
|
84
90
|
as(namePrefix: string): this;
|
|
@@ -165,6 +171,14 @@ export declare class Router {
|
|
|
165
171
|
*/
|
|
166
172
|
resource(name: string, controller: ControllerRef): RouteResource;
|
|
167
173
|
private add;
|
|
174
|
+
private routeHooks;
|
|
175
|
+
/**
|
|
176
|
+
* Observe route registration — called with each route's definition as it's
|
|
177
|
+
* added (and replayed for routes already registered). Handy for logging or
|
|
178
|
+
* building an API map. The `def` is live, so reading it later reflects fluent
|
|
179
|
+
* config (`.name()`, `.middleware()`) applied after registration.
|
|
180
|
+
*/
|
|
181
|
+
onRoute(hook: (def: RouteDefinition) => void): this;
|
|
168
182
|
/** Register a global parameter constraint, applied to every matching route. */
|
|
169
183
|
where(param: string, matcher: Matcher): this;
|
|
170
184
|
/** All registered routes (excluding those trimmed to zero methods). */
|