@kaito-http/core 2.9.5 → 3.0.0-beta.10

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/dist/index.js ADDED
@@ -0,0 +1,256 @@
1
+ // src/error.ts
2
+ var WrappedError = class _WrappedError extends Error {
3
+ constructor(data) {
4
+ super("Something was thrown, but it was not an instance of Error, so a WrappedError was created.");
5
+ this.data = data;
6
+ }
7
+ static maybe(maybeError) {
8
+ if (maybeError instanceof Error) {
9
+ return maybeError;
10
+ }
11
+ return _WrappedError.from(maybeError);
12
+ }
13
+ static from(data) {
14
+ return new _WrappedError(data);
15
+ }
16
+ };
17
+ var KaitoError = class extends Error {
18
+ constructor(status, message) {
19
+ super(message);
20
+ this.status = status;
21
+ }
22
+ };
23
+
24
+ // src/request.ts
25
+ var KaitoRequest = class {
26
+ request;
27
+ _url;
28
+ constructor(request) {
29
+ this.request = request;
30
+ }
31
+ get headers() {
32
+ return this.request.headers;
33
+ }
34
+ get method() {
35
+ return this.request.method;
36
+ }
37
+ get url() {
38
+ return this.request.url;
39
+ }
40
+ parseURL() {
41
+ if (!this._url) {
42
+ this._url = new URL(this.url);
43
+ }
44
+ return this._url;
45
+ }
46
+ async arrayBuffer() {
47
+ return this.request.arrayBuffer();
48
+ }
49
+ async blob() {
50
+ return this.request.blob();
51
+ }
52
+ async formData() {
53
+ return this.request.formData();
54
+ }
55
+ async bytes() {
56
+ const buffer = await this.arrayBuffer();
57
+ return new Uint8Array(buffer);
58
+ }
59
+ async json() {
60
+ return this.request.json();
61
+ }
62
+ async text() {
63
+ return this.request.text();
64
+ }
65
+ };
66
+
67
+ // src/util.ts
68
+ function apiresponse(status, response) {
69
+ return Response.json(response, {
70
+ status
71
+ });
72
+ }
73
+ function createUtilities(getContext) {
74
+ return {
75
+ getContext,
76
+ router: () => Router.create()
77
+ };
78
+ }
79
+ function parsable(parse) {
80
+ return {
81
+ parse
82
+ };
83
+ }
84
+
85
+ // src/router/router.ts
86
+ var Router = class _Router {
87
+ state;
88
+ static create = () => new _Router({
89
+ through: async (context) => context,
90
+ routes: /* @__PURE__ */ new Set()
91
+ });
92
+ static parseQuery(schema, url) {
93
+ if (!schema) {
94
+ return {};
95
+ }
96
+ const result = {};
97
+ for (const [key, parsable2] of Object.entries(schema)) {
98
+ const value = url.searchParams.get(key);
99
+ result[key] = parsable2.parse(value);
100
+ }
101
+ return result;
102
+ }
103
+ constructor(options) {
104
+ this.state = options;
105
+ }
106
+ get routes() {
107
+ return this.state.routes;
108
+ }
109
+ add = (method, path, route) => {
110
+ const merged = {
111
+ ...typeof route === "object" ? route : { run: route },
112
+ method,
113
+ path,
114
+ through: this.state.through
115
+ };
116
+ return new _Router({
117
+ ...this.state,
118
+ routes: /* @__PURE__ */ new Set([...this.state.routes, merged])
119
+ });
120
+ };
121
+ merge = (pathPrefix, other) => {
122
+ const newRoutes = [...other.state.routes].map((route) => ({
123
+ ...route,
124
+ path: `${pathPrefix}${route.path}`
125
+ }));
126
+ return new _Router({
127
+ ...this.state,
128
+ routes: /* @__PURE__ */ new Set([...this.state.routes, ...newRoutes])
129
+ });
130
+ };
131
+ freeze = (server) => {
132
+ const routes = /* @__PURE__ */ new Map();
133
+ for (const route of this.state.routes) {
134
+ if (!routes.has(route.path)) {
135
+ routes.set(route.path, /* @__PURE__ */ new Map());
136
+ }
137
+ routes.get(route.path).set(route.method, route);
138
+ }
139
+ const findRoute = (method, path) => {
140
+ const params = {};
141
+ const pathParts = path.split("/").filter(Boolean);
142
+ for (const [routePath, methodHandlers] of routes) {
143
+ const routeParts = routePath.split("/").filter(Boolean);
144
+ if (routeParts.length !== pathParts.length) continue;
145
+ let matches = true;
146
+ for (let i = 0; i < routeParts.length; i++) {
147
+ const routePart = routeParts[i];
148
+ const pathPart = pathParts[i];
149
+ if (routePart && pathPart && routePart.startsWith(":")) {
150
+ params[routePart.slice(1)] = pathPart;
151
+ } else if (routePart !== pathPart) {
152
+ matches = false;
153
+ break;
154
+ }
155
+ }
156
+ if (matches) {
157
+ const route = methodHandlers.get(method);
158
+ if (route) return { route, params };
159
+ }
160
+ }
161
+ return { params };
162
+ };
163
+ return async (req) => {
164
+ const url = new URL(req.url);
165
+ const method = req.method;
166
+ const { route, params } = findRoute(method, url.pathname);
167
+ if (!route) {
168
+ return apiresponse(404, {
169
+ success: false,
170
+ data: null,
171
+ message: `Cannot ${method} ${url.pathname}`
172
+ });
173
+ }
174
+ const request = new KaitoRequest(req);
175
+ try {
176
+ const rootCtx = await server.getContext(request);
177
+ const ctx = await route.through(rootCtx);
178
+ const body = route.body ? await route.body.parse(await req.json()) : void 0;
179
+ const query = _Router.parseQuery(route.query, url);
180
+ const result = await route.run({
181
+ ctx,
182
+ body,
183
+ query,
184
+ params
185
+ });
186
+ return apiresponse(200, {
187
+ success: true,
188
+ data: result,
189
+ message: "OK"
190
+ });
191
+ } catch (e) {
192
+ const error = WrappedError.maybe(e);
193
+ if (error instanceof KaitoError) {
194
+ return apiresponse(error.status, {
195
+ success: false,
196
+ data: null,
197
+ message: error.message
198
+ });
199
+ }
200
+ const { status, message } = await server.onError({ error, req: request }).catch(() => ({ status: 500, message: "Internal Server Error" }));
201
+ return apiresponse(status, {
202
+ success: false,
203
+ data: null,
204
+ message
205
+ });
206
+ }
207
+ };
208
+ };
209
+ method = (method) => (path, route) => {
210
+ return this.add(method, path, route);
211
+ };
212
+ get = this.method("GET");
213
+ post = this.method("POST");
214
+ put = this.method("PUT");
215
+ patch = this.method("PATCH");
216
+ delete = this.method("DELETE");
217
+ head = this.method("HEAD");
218
+ options = this.method("OPTIONS");
219
+ through = (transform) => new _Router({
220
+ routes: this.state.routes,
221
+ through: async (context) => {
222
+ const fromCurrentRouter = await this.state.through(context);
223
+ return transform(fromCurrentRouter);
224
+ }
225
+ });
226
+ };
227
+
228
+ // src/server.ts
229
+ function createKaitoHandler(config) {
230
+ const match = config.router.freeze(config);
231
+ return async (request) => {
232
+ let before = void 0;
233
+ if (config.before) {
234
+ const result = await config.before(request);
235
+ if (result instanceof Response) {
236
+ return result;
237
+ }
238
+ before = result;
239
+ }
240
+ const response = await match(request);
241
+ if ("after" in config && config.after) {
242
+ await config.after(before, response);
243
+ }
244
+ return response;
245
+ };
246
+ }
247
+ export {
248
+ KaitoError,
249
+ KaitoRequest,
250
+ Router,
251
+ WrappedError,
252
+ apiresponse,
253
+ createKaitoHandler,
254
+ createUtilities,
255
+ parsable
256
+ };
package/package.json CHANGED
@@ -1,41 +1,38 @@
1
1
  {
2
2
  "name": "@kaito-http/core",
3
- "version": "2.9.5",
3
+ "version": "3.0.0-beta.10",
4
+ "type": "module",
5
+ "author": "Alistair Smith <hi@alistair.sh>",
4
6
  "description": "Functional HTTP Framework for TypeScript",
7
+ "scripts": {
8
+ "build": "tsup"
9
+ },
10
+ "exports": {
11
+ "./package.json": "./package.json",
12
+ ".": {
13
+ "import": "./dist/index.js",
14
+ "require": "./dist/index.cjs"
15
+ }
16
+ },
17
+ "homepage": "https://github.com/kaito-http/kaito",
5
18
  "repository": "https://github.com/kaito-http/kaito",
6
- "author": "Alistair Smith <hi@alistair.sh>",
19
+ "keywords": [
20
+ "typescript",
21
+ "http",
22
+ "framework"
23
+ ],
7
24
  "license": "MIT",
8
- "main": "dist/kaito-http-core.cjs.js",
9
- "module": "dist/kaito-http-core.esm.js",
10
- "types": "dist/kaito-http-core.cjs.d.ts",
11
25
  "devDependencies": {
12
- "@types/content-type": "^1.1.5",
13
- "@types/cookie": "^0.5.1",
14
- "@types/node": "^18.11.9",
15
- "typescript": "4.9",
16
- "zod": "^3.19.1"
26
+ "@types/node": "^22.10.2",
27
+ "tsup": "^8.3.5",
28
+ "typescript": "^5.7.2"
17
29
  },
18
30
  "files": [
19
31
  "package.json",
20
- "readme.md",
32
+ "README.md",
21
33
  "dist"
22
34
  ],
23
35
  "bugs": {
24
36
  "url": "https://github.com/kaito-http/kaito/issues"
25
- },
26
- "homepage": "https://github.com/kaito-http/kaito",
27
- "peerDependencies": {
28
- "zod": "*"
29
- },
30
- "keywords": [
31
- "typescript",
32
- "http",
33
- "framework"
34
- ],
35
- "dependencies": {
36
- "content-type": "^1.0.4",
37
- "cookie": "^0.5.0",
38
- "find-my-way": "^7.3.1",
39
- "raw-body": "^2.5.1"
40
37
  }
41
38
  }
@@ -1,10 +0,0 @@
1
- export declare class WrappedError<T> extends Error {
2
- readonly data: T;
3
- static maybe<T>(maybeError: T): (T & Error) | WrappedError<T>;
4
- static from<T>(data: T): WrappedError<T>;
5
- private constructor();
6
- }
7
- export declare class KaitoError extends Error {
8
- readonly status: number;
9
- constructor(status: number, message: string);
10
- }
@@ -1,8 +0,0 @@
1
- export type { HTTPMethod } from 'find-my-way';
2
- export * from './error';
3
- export * from './req';
4
- export * from './res';
5
- export * from './route';
6
- export * from './router';
7
- export * from './server';
8
- export * from './util';
@@ -1,33 +0,0 @@
1
- /// <reference types="node" />
2
- import type { HTTPMethod } from 'find-my-way';
3
- import type { IncomingMessage } from 'node:http';
4
- export declare class KaitoRequest {
5
- readonly raw: IncomingMessage;
6
- private _url;
7
- constructor(raw: IncomingMessage);
8
- /**
9
- * The full URL of the request, including the protocol, hostname, and path.
10
- * Note: does not include the query string or hash
11
- */
12
- get fullURL(): string;
13
- /**
14
- * A new URL instance for the full URL of the request.
15
- */
16
- get url(): URL;
17
- /**
18
- * The HTTP method of the request.
19
- */
20
- get method(): HTTPMethod;
21
- /**
22
- * The protocol of the request, either `http` or `https`.
23
- */
24
- get protocol(): 'http' | 'https';
25
- /**
26
- * The request headers
27
- */
28
- get headers(): import("http").IncomingHttpHeaders;
29
- /**
30
- * The hostname of the request.
31
- */
32
- get hostname(): string;
33
- }
@@ -1,46 +0,0 @@
1
- /// <reference types="node" />
2
- import type { ServerResponse } from 'node:http';
3
- import type { CookieSerializeOptions } from 'cookie';
4
- export type ErroredAPIResponse = {
5
- success: false;
6
- data: null;
7
- message: string;
8
- };
9
- export type SuccessfulAPIResponse<T> = {
10
- success: true;
11
- data: T;
12
- message: 'OK';
13
- };
14
- export type APIResponse<T> = ErroredAPIResponse | SuccessfulAPIResponse<T>;
15
- export type AnyResponse = APIResponse<unknown>;
16
- export declare class KaitoResponse<T = unknown> {
17
- readonly raw: ServerResponse;
18
- constructor(raw: ServerResponse);
19
- /**
20
- * Send a response
21
- * @param key The key of the header
22
- * @param value The value of the header
23
- * @returns The response object
24
- */
25
- header(key: string, value: string | readonly string[]): this;
26
- /**
27
- * Set the status code of the response
28
- * @param code The status code
29
- * @returns The response object
30
- */
31
- status(code: number): this;
32
- /**
33
- * Set a cookie
34
- * @param name The name of the cookie
35
- * @param value The value of the cookie
36
- * @param options The options for the cookie
37
- * @returns The response object
38
- */
39
- cookie(name: string, value: string, options: CookieSerializeOptions): this;
40
- /**
41
- * Send a JSON APIResponse body
42
- * @param data The data to send
43
- * @returns The response object
44
- */
45
- json(data: APIResponse<T>): this;
46
- }
@@ -1,18 +0,0 @@
1
- import type { z } from 'zod';
2
- import type { ExtractRouteParams, KaitoMethod } from './util';
3
- export type RouteArgument<Path extends string, Context, QueryOutput, BodyOutput> = {
4
- ctx: Context;
5
- body: BodyOutput;
6
- query: QueryOutput;
7
- params: ExtractRouteParams<Path>;
8
- };
9
- export type AnyQueryDefinition = Record<string, z.ZodTypeAny>;
10
- export type Route<ContextFrom, ContextTo, Result, Path extends string, Method extends KaitoMethod, Query extends AnyQueryDefinition, BodyOutput, BodyDef extends z.ZodTypeDef, BodyInput> = {
11
- through: (context: ContextFrom) => Promise<ContextTo>;
12
- body?: z.ZodType<BodyOutput, BodyDef, BodyInput>;
13
- query?: Query;
14
- path: Path;
15
- method: Method;
16
- run(args: RouteArgument<Path, ContextTo, z.infer<z.ZodObject<Query>>, BodyOutput>): Promise<Result>;
17
- };
18
- export type AnyRoute<FromContext = any, ToContext = any> = Route<FromContext, ToContext, any, any, any, AnyQueryDefinition, any, any, any>;
@@ -1,41 +0,0 @@
1
- import fmw from 'find-my-way';
2
- import { z } from 'zod';
3
- import type { AnyQueryDefinition, AnyRoute, Route } from './route';
4
- import type { ServerConfig } from './server';
5
- import type { KaitoMethod } from './util';
6
- type Routes = readonly AnyRoute[];
7
- type RemapRoutePrefix<R extends AnyRoute, Prefix extends `/${string}`> = R extends Route<infer ContextFrom, infer ContextTo, infer Result, infer Path, infer Method, infer Query, infer BodyOutput, infer BodyDef, infer BodyInput> ? Route<ContextFrom, ContextTo, Result, `${Prefix}${Path}`, Method, Query, BodyOutput, BodyDef, BodyInput> : never;
8
- type PrefixRoutesPath<Prefix extends `/${string}`, R extends Routes> = R extends [infer First, ...infer Rest] ? [
9
- RemapRoutePrefix<Extract<First, AnyRoute>, Prefix>,
10
- ...PrefixRoutesPath<Prefix, Extract<Rest, readonly AnyRoute[]>>
11
- ] : [];
12
- export type RouterOptions<ContextFrom, ContextTo> = {
13
- through: (context: ContextFrom) => Promise<ContextTo>;
14
- };
15
- export declare class Router<ContextFrom, ContextTo, R extends Routes> {
16
- private readonly routerOptions;
17
- readonly routes: R;
18
- static create: <Context>() => Router<Context, Context, []>;
19
- private static handle;
20
- constructor(routes: R, options: RouterOptions<ContextFrom, ContextTo>);
21
- /**
22
- * Adds a new route to the router
23
- * @param method The HTTP method to add a route for
24
- * @param path The path to add a route for
25
- * @param route The route specification to add to this router
26
- * @returns A new router with this route added
27
- */
28
- add: <Result, Path extends string, Method extends KaitoMethod, Query extends AnyQueryDefinition = {}, BodyOutput = never, BodyDef extends z.ZodTypeDef = z.ZodTypeDef, BodyInput = BodyOutput>(method: Method, path: Path, route: ((args: import("./route").RouteArgument<Path, ContextTo, z.objectUtil.addQuestionMarks<{ [k_1 in keyof Query]: Query[k_1]["_output"]; }> extends infer T extends object ? { [k in keyof T]: z.objectUtil.addQuestionMarks<{ [k_1 in keyof Query]: Query[k_1]["_output"]; }>[k]; } : never, BodyOutput>) => Promise<Result>) | (Method extends "GET" ? Omit<Route<ContextFrom, ContextTo, Result, Path, Method, Query, BodyOutput, BodyDef, BodyInput>, "path" | "body" | "method" | "through"> : Omit<Route<ContextFrom, ContextTo, Result, Path, Method, Query, BodyOutput, BodyDef, BodyInput>, "path" | "method" | "through">)) => Router<ContextFrom, ContextTo, [...R, Route<ContextFrom, ContextTo, Result, Path, Method, Query, BodyOutput, BodyDef, BodyInput>]>;
29
- readonly merge: <PathPrefix extends `/${string}`, OtherRoutes extends Routes>(pathPrefix: PathPrefix, other: Router<ContextFrom, unknown, OtherRoutes>) => Router<ContextFrom, ContextTo, [...R, ...PrefixRoutesPath<PathPrefix, OtherRoutes>]>;
30
- freeze: (server: ServerConfig<ContextFrom, any>) => fmw.Instance<fmw.HTTPVersion.V1>;
31
- private readonly method;
32
- get: <Result, Path extends string, Query extends AnyQueryDefinition = {}, BodyOutput = never, BodyDef extends z.ZodTypeDef = z.ZodTypeDef, BodyInput = BodyOutput>(path: Path, route: ((args: import("./route").RouteArgument<Path, ContextTo, z.objectUtil.addQuestionMarks<{ [k_1 in keyof Query]: Query[k_1]["_output"]; }> extends infer T extends object ? { [k in keyof T]: z.objectUtil.addQuestionMarks<{ [k_1 in keyof Query]: Query[k_1]["_output"]; }>[k]; } : never, BodyOutput>) => Promise<Result>) | Omit<Route<ContextFrom, ContextTo, Result, Path, "GET", Query, BodyOutput, BodyDef, BodyInput>, "path" | "body" | "method" | "through">) => Router<ContextFrom, ContextTo, [...R, Route<ContextFrom, ContextTo, Result, Path, "GET", Query, BodyOutput, BodyDef, BodyInput>]>;
33
- post: <Result, Path extends string, Query extends AnyQueryDefinition = {}, BodyOutput = never, BodyDef extends z.ZodTypeDef = z.ZodTypeDef, BodyInput = BodyOutput>(path: Path, route: ((args: import("./route").RouteArgument<Path, ContextTo, z.objectUtil.addQuestionMarks<{ [k_1 in keyof Query]: Query[k_1]["_output"]; }> extends infer T extends object ? { [k in keyof T]: z.objectUtil.addQuestionMarks<{ [k_1 in keyof Query]: Query[k_1]["_output"]; }>[k]; } : never, BodyOutput>) => Promise<Result>) | Omit<Route<ContextFrom, ContextTo, Result, Path, "POST", Query, BodyOutput, BodyDef, BodyInput>, "path" | "method" | "through">) => Router<ContextFrom, ContextTo, [...R, Route<ContextFrom, ContextTo, Result, Path, "POST", Query, BodyOutput, BodyDef, BodyInput>]>;
34
- put: <Result, Path extends string, Query extends AnyQueryDefinition = {}, BodyOutput = never, BodyDef extends z.ZodTypeDef = z.ZodTypeDef, BodyInput = BodyOutput>(path: Path, route: ((args: import("./route").RouteArgument<Path, ContextTo, z.objectUtil.addQuestionMarks<{ [k_1 in keyof Query]: Query[k_1]["_output"]; }> extends infer T extends object ? { [k in keyof T]: z.objectUtil.addQuestionMarks<{ [k_1 in keyof Query]: Query[k_1]["_output"]; }>[k]; } : never, BodyOutput>) => Promise<Result>) | Omit<Route<ContextFrom, ContextTo, Result, Path, "PUT", Query, BodyOutput, BodyDef, BodyInput>, "path" | "method" | "through">) => Router<ContextFrom, ContextTo, [...R, Route<ContextFrom, ContextTo, Result, Path, "PUT", Query, BodyOutput, BodyDef, BodyInput>]>;
35
- patch: <Result, Path extends string, Query extends AnyQueryDefinition = {}, BodyOutput = never, BodyDef extends z.ZodTypeDef = z.ZodTypeDef, BodyInput = BodyOutput>(path: Path, route: ((args: import("./route").RouteArgument<Path, ContextTo, z.objectUtil.addQuestionMarks<{ [k_1 in keyof Query]: Query[k_1]["_output"]; }> extends infer T extends object ? { [k in keyof T]: z.objectUtil.addQuestionMarks<{ [k_1 in keyof Query]: Query[k_1]["_output"]; }>[k]; } : never, BodyOutput>) => Promise<Result>) | Omit<Route<ContextFrom, ContextTo, Result, Path, "PATCH", Query, BodyOutput, BodyDef, BodyInput>, "path" | "method" | "through">) => Router<ContextFrom, ContextTo, [...R, Route<ContextFrom, ContextTo, Result, Path, "PATCH", Query, BodyOutput, BodyDef, BodyInput>]>;
36
- delete: <Result, Path extends string, Query extends AnyQueryDefinition = {}, BodyOutput = never, BodyDef extends z.ZodTypeDef = z.ZodTypeDef, BodyInput = BodyOutput>(path: Path, route: ((args: import("./route").RouteArgument<Path, ContextTo, z.objectUtil.addQuestionMarks<{ [k_1 in keyof Query]: Query[k_1]["_output"]; }> extends infer T extends object ? { [k in keyof T]: z.objectUtil.addQuestionMarks<{ [k_1 in keyof Query]: Query[k_1]["_output"]; }>[k]; } : never, BodyOutput>) => Promise<Result>) | Omit<Route<ContextFrom, ContextTo, Result, Path, "DELETE", Query, BodyOutput, BodyDef, BodyInput>, "path" | "method" | "through">) => Router<ContextFrom, ContextTo, [...R, Route<ContextFrom, ContextTo, Result, Path, "DELETE", Query, BodyOutput, BodyDef, BodyInput>]>;
37
- head: <Result, Path extends string, Query extends AnyQueryDefinition = {}, BodyOutput = never, BodyDef extends z.ZodTypeDef = z.ZodTypeDef, BodyInput = BodyOutput>(path: Path, route: ((args: import("./route").RouteArgument<Path, ContextTo, z.objectUtil.addQuestionMarks<{ [k_1 in keyof Query]: Query[k_1]["_output"]; }> extends infer T extends object ? { [k in keyof T]: z.objectUtil.addQuestionMarks<{ [k_1 in keyof Query]: Query[k_1]["_output"]; }>[k]; } : never, BodyOutput>) => Promise<Result>) | Omit<Route<ContextFrom, ContextTo, Result, Path, "HEAD", Query, BodyOutput, BodyDef, BodyInput>, "path" | "method" | "through">) => Router<ContextFrom, ContextTo, [...R, Route<ContextFrom, ContextTo, Result, Path, "HEAD", Query, BodyOutput, BodyDef, BodyInput>]>;
38
- options: <Result, Path extends string, Query extends AnyQueryDefinition = {}, BodyOutput = never, BodyDef extends z.ZodTypeDef = z.ZodTypeDef, BodyInput = BodyOutput>(path: Path, route: ((args: import("./route").RouteArgument<Path, ContextTo, z.objectUtil.addQuestionMarks<{ [k_1 in keyof Query]: Query[k_1]["_output"]; }> extends infer T extends object ? { [k in keyof T]: z.objectUtil.addQuestionMarks<{ [k_1 in keyof Query]: Query[k_1]["_output"]; }>[k]; } : never, BodyOutput>) => Promise<Result>) | Omit<Route<ContextFrom, ContextTo, Result, Path, "OPTIONS", Query, BodyOutput, BodyDef, BodyInput>, "path" | "method" | "through">) => Router<ContextFrom, ContextTo, [...R, Route<ContextFrom, ContextTo, Result, Path, "OPTIONS", Query, BodyOutput, BodyDef, BodyInput>]>;
39
- through: <NextContext>(transform: (context: ContextTo) => Promise<NextContext>) => Router<ContextFrom, NextContext, R>;
40
- }
41
- export {};
@@ -1,46 +0,0 @@
1
- /// <reference types="node" />
2
- import * as http from 'node:http';
3
- import type { KaitoError } from './error';
4
- import type { KaitoRequest } from './req';
5
- import type { KaitoResponse } from './res';
6
- import type { Router } from './router';
7
- import type { GetContext, KaitoMethod } from './util';
8
- export type Before<BeforeAfterContext> = (req: http.IncomingMessage, res: http.ServerResponse) => Promise<BeforeAfterContext>;
9
- export type HandlerResult = {
10
- success: true;
11
- data: unknown;
12
- } | {
13
- success: false;
14
- data: {
15
- status: number;
16
- message: string;
17
- };
18
- };
19
- export type After<BeforeAfterContext> = (ctx: BeforeAfterContext, result: HandlerResult) => Promise<void>;
20
- export type ServerConfigWithBefore<BeforeAfterContext> = {
21
- before: Before<BeforeAfterContext>;
22
- after?: After<BeforeAfterContext>;
23
- } | {
24
- before?: undefined;
25
- };
26
- export type ServerConfig<ContextFrom, BeforeAfterContext> = ServerConfigWithBefore<BeforeAfterContext> & {
27
- router: Router<ContextFrom, unknown, any>;
28
- getContext: GetContext<ContextFrom>;
29
- rawRoutes?: Partial<Record<KaitoMethod, Array<{
30
- path: string;
31
- handler: (request: http.IncomingMessage, response: http.ServerResponse) => unknown;
32
- }>>>;
33
- onError(arg: {
34
- error: Error;
35
- req: KaitoRequest;
36
- res: KaitoResponse;
37
- }): Promise<KaitoError | {
38
- status: number;
39
- message: string;
40
- }>;
41
- };
42
- export declare function createFMWServer<Context, BeforeAfterContext = null>(config: ServerConfig<Context, BeforeAfterContext>): {
43
- readonly server: http.Server<typeof http.IncomingMessage, typeof http.ServerResponse>;
44
- readonly fmw: import("find-my-way").Instance<import("find-my-way").HTTPVersion.V1>;
45
- };
46
- export declare function createServer<Context, BeforeAfterContext = null>(config: ServerConfig<Context, BeforeAfterContext>): http.Server<typeof http.IncomingMessage, typeof http.ServerResponse>;
@@ -1,46 +0,0 @@
1
- import type { HTTPMethod } from 'find-my-way';
2
- import type { KaitoRequest } from './req';
3
- import type { KaitoResponse } from './res';
4
- import { Router } from './router';
5
- export type ExtractRouteParams<T extends string> = string extends T ? Record<string, string> : T extends `${string}:${infer Param}/${infer Rest}` ? {
6
- [k in Param | keyof ExtractRouteParams<Rest>]: string;
7
- } : T extends `${string}:${infer Param}` ? {
8
- [k in Param]: string;
9
- } : {};
10
- export type KaitoMethod = HTTPMethod | '*';
11
- export type GetContext<Result> = (req: KaitoRequest, res: KaitoResponse) => Promise<Result>;
12
- /**
13
- * @deprecated use `createUtilities` instead
14
- */
15
- export declare function createGetContext<Context>(callback: GetContext<Context>): GetContext<Context>;
16
- /**
17
- * A helper function to create typed necessary functions
18
- *
19
- * @example
20
- * ```ts
21
- * const {router, getContext} = createUtilities(async (req, res) => {
22
- * // Return context here
23
- * })
24
- *
25
- * const app = router().get('/', async () => "hello");
26
- *
27
- * const server = createServer({
28
- * router: app,
29
- * getContext,
30
- * // ...
31
- * });
32
- * ```
33
- */
34
- export declare function createUtilities<Context>(getContext: GetContext<Context>): {
35
- getContext: GetContext<Context>;
36
- router: () => Router<Context, Context, []>;
37
- };
38
- export type InferContext<T> = T extends (req: KaitoRequest, res: KaitoResponse) => Promise<infer U> ? U : never;
39
- export declare function getLastEntryInMultiHeaderValue(headerValue: string | string[]): string;
40
- type RemoveEndSlashes<T extends string> = T extends `${infer U}/` ? U : T;
41
- type AddStartSlashes<T extends string> = T extends `/${infer U}` ? `/${U}` : `/${T}`;
42
- export type NormalizePath<T extends string> = AddStartSlashes<RemoveEndSlashes<T>>;
43
- export type Values<T> = T[keyof T];
44
- export type NoEmpty<T> = [keyof T] extends [never] ? never : T;
45
- export declare function getBody(req: KaitoRequest): Promise<unknown>;
46
- export {};
@@ -1 +0,0 @@
1
- export * from "./declarations/src/index";