better-call 1.1.6 → 1.1.8
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 +35 -0
- package/dist/_virtual/rolldown_runtime.cjs +29 -0
- package/dist/adapters/node/request.cjs +125 -0
- package/dist/adapters/node/request.cjs.map +1 -0
- package/dist/{node.d.ts → adapters/node/request.d.cts} +2 -6
- package/dist/adapters/node/request.d.mts +16 -0
- package/dist/{node.js → adapters/node/request.mjs} +2 -13
- package/dist/adapters/node/request.mjs.map +1 -0
- package/dist/client.cjs +3 -3
- package/dist/client.cjs.map +1 -1
- package/dist/client.d.cts +13 -15
- package/dist/client.d.mts +53 -0
- package/dist/{client.js → client.mjs} +3 -3
- package/dist/client.mjs.map +1 -0
- package/dist/context.cjs +103 -0
- package/dist/context.cjs.map +1 -0
- package/dist/context.d.cts +340 -0
- package/dist/context.d.mts +340 -0
- package/dist/context.mjs +103 -0
- package/dist/context.mjs.map +1 -0
- package/dist/cookies.cjs +87 -0
- package/dist/cookies.cjs.map +1 -0
- package/dist/cookies.d.cts +103 -0
- package/dist/cookies.d.mts +103 -0
- package/dist/cookies.mjs +84 -0
- package/dist/cookies.mjs.map +1 -0
- package/dist/crypto.cjs +39 -0
- package/dist/crypto.cjs.map +1 -0
- package/dist/crypto.mjs +36 -0
- package/dist/crypto.mjs.map +1 -0
- package/dist/endpoint.cjs +70 -0
- package/dist/endpoint.cjs.map +1 -0
- package/dist/endpoint.d.cts +428 -0
- package/dist/endpoint.d.mts +428 -0
- package/dist/endpoint.mjs +70 -0
- package/dist/endpoint.mjs.map +1 -0
- package/dist/error.cjs +140 -7
- package/dist/error.cjs.map +1 -0
- package/dist/error.d.cts +103 -2
- package/dist/{error2.d.ts → error.d.mts} +5 -59
- package/dist/{error2.js → error.mjs} +2 -2
- package/dist/{error2.js.map → error.mjs.map} +1 -1
- package/dist/helper.d.cts +12 -0
- package/dist/helper.d.mts +12 -0
- package/dist/index.cjs +19 -829
- package/dist/index.d.cts +11 -15
- package/dist/index.d.mts +11 -0
- package/dist/index.mjs +10 -0
- package/dist/middleware.cjs +39 -0
- package/dist/middleware.cjs.map +1 -0
- package/dist/middleware.d.cts +123 -0
- package/dist/middleware.d.mts +123 -0
- package/dist/middleware.mjs +39 -0
- package/dist/middleware.mjs.map +1 -0
- package/dist/node.cjs +4 -151
- package/dist/node.cjs.map +1 -1
- package/dist/node.d.cts +2 -13
- package/dist/node.d.mts +9 -0
- package/dist/node.mjs +15 -0
- package/dist/node.mjs.map +1 -0
- package/dist/openapi.cjs +191 -0
- package/dist/openapi.cjs.map +1 -0
- package/dist/openapi.d.cts +113 -0
- package/dist/openapi.d.mts +113 -0
- package/dist/openapi.mjs +189 -0
- package/dist/openapi.mjs.map +1 -0
- package/dist/router.cjs +117 -0
- package/dist/router.cjs.map +1 -0
- package/dist/router.d.cts +3 -1088
- package/dist/router.d.mts +97 -0
- package/dist/router.mjs +116 -0
- package/dist/router.mjs.map +1 -0
- package/dist/standard-schema.d.cts +59 -0
- package/dist/standard-schema.d.mts +59 -0
- package/dist/to-response.cjs +96 -0
- package/dist/to-response.cjs.map +1 -0
- package/dist/to-response.d.cts +12 -0
- package/dist/to-response.d.mts +12 -0
- package/dist/to-response.mjs +96 -0
- package/dist/to-response.mjs.map +1 -0
- package/dist/utils.cjs +86 -0
- package/dist/utils.cjs.map +1 -0
- package/dist/utils.mjs +82 -0
- package/dist/utils.mjs.map +1 -0
- package/dist/validator.cjs +58 -0
- package/dist/validator.cjs.map +1 -0
- package/dist/validator.mjs +57 -0
- package/dist/validator.mjs.map +1 -0
- package/package.json +15 -15
- package/dist/client.d.ts +0 -55
- package/dist/client.js.map +0 -1
- package/dist/error.d.ts +0 -2
- package/dist/error.js +0 -3
- package/dist/error2.cjs +0 -171
- package/dist/error2.cjs.map +0 -1
- package/dist/error2.d.cts +0 -157
- package/dist/index.cjs.map +0 -1
- package/dist/index.d.ts +0 -15
- package/dist/index.js +0 -819
- package/dist/index.js.map +0 -1
- package/dist/node.js.map +0 -1
- package/dist/router.d.ts +0 -1182
package/dist/index.d.cts
CHANGED
|
@@ -1,15 +1,11 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
};
|
|
12
|
-
declare function toResponse(data?: any, init?: ResponseInit): Response;
|
|
13
|
-
//#endregion
|
|
14
|
-
export { APIError, BetterCallError, CookieOptions, CookiePrefixOptions, Endpoint, EndpointBaseOptions, EndpointBodyMethodOptions, EndpointContext, EndpointOptions, HTTPMethod, HasRequiredKeys, InferBody, InferBodyInput, InferHeaders, InferHeadersInput, InferInputMethod, InferMethod, InferMiddlewareBody, InferMiddlewareQuery, InferParam, InferParamInput, InferParamPath, InferParamWildCard, InferQuery, InferQueryInput, InferRequest, InferRequestInput, InferUse, InputContext, IsEmptyObject, JSONResponse, MergeObject, Method, Middleware, MiddlewareContext, MiddlewareInputContext, MiddlewareOptions, MiddlewareResponse, OpenAPIParameter, OpenAPISchemaType, Path, Prettify, RequiredKeysOf, Router, RouterConfig, StandardSchemaV1, Status, StrictEndpoint, UnionToIntersection, ValidationError, createEndpoint, createInternalContext, createMiddleware, createRouter, generator, getCookieKey, getHTML, hideInternalStackFrames, makeErrorForHideStackFrame, parseCookies, serializeCookie, serializeSignedCookie, statusCodes, toResponse };
|
|
15
|
-
//# sourceMappingURL=index.d.cts.map
|
|
1
|
+
import { HasRequiredKeys, InferParamPath, InferParamWildCard, IsEmptyObject, MergeObject, Prettify, RequiredKeysOf, UnionToIntersection } from "./helper.cjs";
|
|
2
|
+
import { StandardSchemaV1 } from "./standard-schema.cjs";
|
|
3
|
+
import { APIError, BetterCallError, Status, ValidationError, hideInternalStackFrames, makeErrorForHideStackFrame, statusCodes } from "./error.cjs";
|
|
4
|
+
import { CookieOptions, CookiePrefixOptions, getCookieKey, parseCookies, serializeCookie, serializeSignedCookie } from "./cookies.cjs";
|
|
5
|
+
import { HTTPMethod, InferBody, InferBodyInput, InferHeaders, InferHeadersInput, InferInputMethod, InferMethod, InferMiddlewareBody, InferMiddlewareQuery, InferParam, InferParamInput, InferQuery, InferQueryInput, InferRequest, InferRequestInput, InferUse, InputContext, Method, createInternalContext } from "./context.cjs";
|
|
6
|
+
import { Middleware, MiddlewareContext, MiddlewareInputContext, MiddlewareOptions, MiddlewareResponse, createMiddleware } from "./middleware.cjs";
|
|
7
|
+
import { OpenAPIParameter, OpenAPISchemaType, Path, generator, getHTML } from "./openapi.cjs";
|
|
8
|
+
import { Endpoint, EndpointBaseOptions, EndpointBodyMethodOptions, EndpointContext, EndpointOptions, StrictEndpoint, createEndpoint } from "./endpoint.cjs";
|
|
9
|
+
import { Router, RouterConfig, createRouter } from "./router.cjs";
|
|
10
|
+
import { JSONResponse, toResponse } from "./to-response.cjs";
|
|
11
|
+
export { APIError, BetterCallError, CookieOptions, CookiePrefixOptions, Endpoint, EndpointBaseOptions, EndpointBodyMethodOptions, EndpointContext, EndpointOptions, HTTPMethod, HasRequiredKeys, InferBody, InferBodyInput, InferHeaders, InferHeadersInput, InferInputMethod, InferMethod, InferMiddlewareBody, InferMiddlewareQuery, InferParam, InferParamInput, InferParamPath, InferParamWildCard, InferQuery, InferQueryInput, InferRequest, InferRequestInput, InferUse, InputContext, IsEmptyObject, JSONResponse, MergeObject, Method, Middleware, MiddlewareContext, MiddlewareInputContext, MiddlewareOptions, MiddlewareResponse, OpenAPIParameter, OpenAPISchemaType, Path, Prettify, RequiredKeysOf, Router, RouterConfig, StandardSchemaV1, Status, StrictEndpoint, UnionToIntersection, ValidationError, createEndpoint, createInternalContext, createMiddleware, createRouter, generator, getCookieKey, getHTML, hideInternalStackFrames, makeErrorForHideStackFrame, parseCookies, serializeCookie, serializeSignedCookie, statusCodes, toResponse };
|
package/dist/index.d.mts
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import { HasRequiredKeys, InferParamPath, InferParamWildCard, IsEmptyObject, MergeObject, Prettify, RequiredKeysOf, UnionToIntersection } from "./helper.mjs";
|
|
2
|
+
import { StandardSchemaV1 } from "./standard-schema.mjs";
|
|
3
|
+
import { APIError, BetterCallError, Status, ValidationError, hideInternalStackFrames, makeErrorForHideStackFrame, statusCodes } from "./error.mjs";
|
|
4
|
+
import { CookieOptions, CookiePrefixOptions, getCookieKey, parseCookies, serializeCookie, serializeSignedCookie } from "./cookies.mjs";
|
|
5
|
+
import { HTTPMethod, InferBody, InferBodyInput, InferHeaders, InferHeadersInput, InferInputMethod, InferMethod, InferMiddlewareBody, InferMiddlewareQuery, InferParam, InferParamInput, InferQuery, InferQueryInput, InferRequest, InferRequestInput, InferUse, InputContext, Method, createInternalContext } from "./context.mjs";
|
|
6
|
+
import { Middleware, MiddlewareContext, MiddlewareInputContext, MiddlewareOptions, MiddlewareResponse, createMiddleware } from "./middleware.mjs";
|
|
7
|
+
import { OpenAPIParameter, OpenAPISchemaType, Path, generator, getHTML } from "./openapi.mjs";
|
|
8
|
+
import { Endpoint, EndpointBaseOptions, EndpointBodyMethodOptions, EndpointContext, EndpointOptions, StrictEndpoint, createEndpoint } from "./endpoint.mjs";
|
|
9
|
+
import { Router, RouterConfig, createRouter } from "./router.mjs";
|
|
10
|
+
import { JSONResponse, toResponse } from "./to-response.mjs";
|
|
11
|
+
export { APIError, BetterCallError, CookieOptions, CookiePrefixOptions, Endpoint, EndpointBaseOptions, EndpointBodyMethodOptions, EndpointContext, EndpointOptions, HTTPMethod, HasRequiredKeys, InferBody, InferBodyInput, InferHeaders, InferHeadersInput, InferInputMethod, InferMethod, InferMiddlewareBody, InferMiddlewareQuery, InferParam, InferParamInput, InferParamPath, InferParamWildCard, InferQuery, InferQueryInput, InferRequest, InferRequestInput, InferUse, InputContext, IsEmptyObject, JSONResponse, MergeObject, Method, Middleware, MiddlewareContext, MiddlewareInputContext, MiddlewareOptions, MiddlewareResponse, OpenAPIParameter, OpenAPISchemaType, Path, Prettify, RequiredKeysOf, Router, RouterConfig, StandardSchemaV1, Status, StrictEndpoint, UnionToIntersection, ValidationError, createEndpoint, createInternalContext, createMiddleware, createRouter, generator, getCookieKey, getHTML, hideInternalStackFrames, makeErrorForHideStackFrame, parseCookies, serializeCookie, serializeSignedCookie, statusCodes, toResponse };
|
package/dist/index.mjs
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import { APIError, BetterCallError, ValidationError, hideInternalStackFrames, makeErrorForHideStackFrame, statusCodes } from "./error.mjs";
|
|
2
|
+
import { toResponse } from "./to-response.mjs";
|
|
3
|
+
import { getCookieKey, parseCookies, serializeCookie, serializeSignedCookie } from "./cookies.mjs";
|
|
4
|
+
import { createInternalContext } from "./context.mjs";
|
|
5
|
+
import { createEndpoint } from "./endpoint.mjs";
|
|
6
|
+
import { createMiddleware } from "./middleware.mjs";
|
|
7
|
+
import { generator, getHTML } from "./openapi.mjs";
|
|
8
|
+
import { createRouter } from "./router.mjs";
|
|
9
|
+
|
|
10
|
+
export { APIError, BetterCallError, ValidationError, createEndpoint, createInternalContext, createMiddleware, createRouter, generator, getCookieKey, getHTML, hideInternalStackFrames, makeErrorForHideStackFrame, parseCookies, serializeCookie, serializeSignedCookie, statusCodes, toResponse };
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
const require_context = require('./context.cjs');
|
|
2
|
+
require('./endpoint.cjs');
|
|
3
|
+
|
|
4
|
+
//#region src/middleware.ts
|
|
5
|
+
function createMiddleware(optionsOrHandler, handler) {
|
|
6
|
+
const internalHandler = async (inputCtx) => {
|
|
7
|
+
const context = inputCtx;
|
|
8
|
+
const _handler = typeof optionsOrHandler === "function" ? optionsOrHandler : handler;
|
|
9
|
+
const internalContext = await require_context.createInternalContext(context, {
|
|
10
|
+
options: typeof optionsOrHandler === "function" ? {} : optionsOrHandler,
|
|
11
|
+
path: "/"
|
|
12
|
+
});
|
|
13
|
+
if (!_handler) throw new Error("handler must be defined");
|
|
14
|
+
const response = await _handler(internalContext);
|
|
15
|
+
const headers = internalContext.responseHeaders;
|
|
16
|
+
return context.returnHeaders ? {
|
|
17
|
+
headers,
|
|
18
|
+
response
|
|
19
|
+
} : response;
|
|
20
|
+
};
|
|
21
|
+
internalHandler.options = typeof optionsOrHandler === "function" ? {} : optionsOrHandler;
|
|
22
|
+
return internalHandler;
|
|
23
|
+
}
|
|
24
|
+
createMiddleware.create = (opts) => {
|
|
25
|
+
function fn(optionsOrHandler, handler) {
|
|
26
|
+
if (typeof optionsOrHandler === "function") return createMiddleware({ use: opts?.use }, optionsOrHandler);
|
|
27
|
+
if (!handler) throw new Error("Middleware handler is required");
|
|
28
|
+
return createMiddleware({
|
|
29
|
+
...optionsOrHandler,
|
|
30
|
+
method: "*",
|
|
31
|
+
use: [...opts?.use || [], ...optionsOrHandler.use || []]
|
|
32
|
+
}, handler);
|
|
33
|
+
}
|
|
34
|
+
return fn;
|
|
35
|
+
};
|
|
36
|
+
|
|
37
|
+
//#endregion
|
|
38
|
+
exports.createMiddleware = createMiddleware;
|
|
39
|
+
//# sourceMappingURL=middleware.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"middleware.cjs","names":["createInternalContext"],"sources":["../src/middleware.ts"],"sourcesContent":["import {\n\tcreateEndpoint,\n\ttype Endpoint,\n\ttype EndpointContext,\n\ttype EndpointOptions,\n} from \"./endpoint\";\nimport {\n\tcreateInternalContext,\n\ttype InferBody,\n\ttype InferBodyInput,\n\ttype InferHeaders,\n\ttype InferHeadersInput,\n\ttype InferMiddlewareBody,\n\ttype InferMiddlewareQuery,\n\ttype InferQuery,\n\ttype InferQueryInput,\n\ttype InferRequest,\n\ttype InferRequestInput,\n\ttype InferUse,\n\ttype InputContext,\n} from \"./context\";\nimport type { Prettify } from \"./helper\";\n\nexport interface MiddlewareOptions extends Omit<EndpointOptions, \"method\"> {}\n\nexport type MiddlewareResponse = null | void | undefined | Record<string, any>;\n\nexport type MiddlewareContext<Options extends MiddlewareOptions, Context = {}> = EndpointContext<\n\tstring,\n\tOptions & {\n\t\tmethod: \"*\";\n\t}\n> & {\n\t/**\n\t * Method\n\t *\n\t * The request method\n\t */\n\tmethod: string;\n\t/**\n\t * Path\n\t *\n\t * The path of the endpoint\n\t */\n\tpath: string;\n\t/**\n\t * Body\n\t *\n\t * The body object will be the parsed JSON from the request and validated\n\t * against the body schema if it exists\n\t */\n\tbody: InferMiddlewareBody<Options>;\n\t/**\n\t * Query\n\t *\n\t * The query object will be the parsed query string from the request\n\t * and validated against the query schema if it exists\n\t */\n\tquery: InferMiddlewareQuery<Options>;\n\t/**\n\t * Params\n\t *\n\t * If the path is `/user/:id` and the request is `/user/1` then the\n\t * params will\n\t * be `{ id: \"1\" }` and if the path includes a wildcard like `/user/*`\n\t * then the\n\t * params will be `{ _: \"1\" }` where `_` is the wildcard key. If the\n\t * wildcard\n\t * is named like `/user/**:name` then the params will be `{ name: string }`\n\t */\n\tparams: string;\n\t/**\n\t * Request object\n\t *\n\t * If `requireRequest` is set to true in the endpoint options this will be\n\t * required\n\t */\n\trequest: InferRequest<Options>;\n\t/**\n\t * Headers\n\t *\n\t * If `requireHeaders` is set to true in the endpoint options this will be\n\t * required\n\t */\n\theaders: InferHeaders<Options>;\n\t/**\n\t * Set header\n\t *\n\t * If it's called outside of a request it will just be ignored.\n\t */\n\tsetHeader: (key: string, value: string) => void;\n\t/**\n\t * Get header\n\t *\n\t * If it's called outside of a request it will just return null\n\t *\n\t * @param key - The key of the header\n\t * @returns\n\t */\n\tgetHeader: (key: string) => string | null;\n\t/**\n\t * JSON\n\t *\n\t * a helper function to create a JSON response with\n\t * the correct headers\n\t * and status code. If `asResponse` is set to true in\n\t * the context then\n\t * it will return a Response object instead of the\n\t * JSON object.\n\t *\n\t * @param json - The JSON object to return\n\t * @param routerResponse - The response object to\n\t * return if `asResponse` is\n\t * true in the context this will take precedence\n\t */\n\tjson: <R extends Record<string, any> | null>(\n\t\tjson: R,\n\t\trouterResponse?:\n\t\t\t| {\n\t\t\t\t\tstatus?: number;\n\t\t\t\t\theaders?: Record<string, string>;\n\t\t\t\t\tresponse?: Response;\n\t\t\t }\n\t\t\t| Response,\n\t) => Promise<R>;\n\t/**\n\t * Middleware context\n\t */\n\tcontext: Prettify<Context>;\n};\n\nexport function createMiddleware<Options extends MiddlewareOptions, R>(\n\toptions: Options,\n\thandler: (context: MiddlewareContext<Options>) => Promise<R>,\n): <InputCtx extends MiddlewareInputContext<Options>>(inputContext: InputCtx) => Promise<R>;\nexport function createMiddleware<Options extends MiddlewareOptions, R>(\n\thandler: (context: MiddlewareContext<Options>) => Promise<R>,\n): <InputCtx extends MiddlewareInputContext<Options>>(inputContext: InputCtx) => Promise<R>;\nexport function createMiddleware(optionsOrHandler: any, handler?: any) {\n\tconst internalHandler = async (inputCtx: InputContext<any, any>) => {\n\t\tconst context = inputCtx as InputContext<any, any>;\n\t\tconst _handler = typeof optionsOrHandler === \"function\" ? optionsOrHandler : handler;\n\t\tconst options = typeof optionsOrHandler === \"function\" ? {} : optionsOrHandler;\n\t\tconst internalContext = await createInternalContext(context, {\n\t\t\toptions,\n\t\t\tpath: \"/\",\n\t\t});\n\n\t\tif (!_handler) {\n\t\t\tthrow new Error(\"handler must be defined\");\n\t\t}\n\t\tconst response = await _handler(internalContext as any);\n\t\tconst headers = internalContext.responseHeaders;\n\t\treturn context.returnHeaders\n\t\t\t? {\n\t\t\t\t\theaders,\n\t\t\t\t\tresponse,\n\t\t\t\t}\n\t\t\t: response;\n\t};\n\tinternalHandler.options = typeof optionsOrHandler === \"function\" ? {} : optionsOrHandler;\n\treturn internalHandler;\n}\n\nexport type MiddlewareInputContext<Options extends MiddlewareOptions> = InferBodyInput<Options> &\n\tInferQueryInput<Options> &\n\tInferRequestInput<Options> &\n\tInferHeadersInput<Options> & {\n\t\tasResponse?: boolean;\n\t\treturnHeaders?: boolean;\n\t\tuse?: Middleware[];\n\t};\n\nexport type Middleware<\n\tOptions extends MiddlewareOptions = MiddlewareOptions,\n\tHandler extends (inputCtx: any) => Promise<any> = any,\n> = Handler & {\n\toptions: Options;\n};\n\ncreateMiddleware.create = <\n\tE extends {\n\t\tuse?: Middleware[];\n\t},\n>(\n\topts?: E,\n) => {\n\ttype InferredContext = InferUse<E[\"use\"]>;\n\tfunction fn<Options extends MiddlewareOptions, R>(\n\t\toptions: Options,\n\t\thandler: (ctx: MiddlewareContext<Options, InferredContext>) => Promise<R>,\n\t): (inputContext: MiddlewareInputContext<Options>) => Promise<R>;\n\tfunction fn<Options extends MiddlewareOptions, R>(\n\t\thandler: (ctx: MiddlewareContext<Options, InferredContext>) => Promise<R>,\n\t): (inputContext: MiddlewareInputContext<Options>) => Promise<R>;\n\tfunction fn(optionsOrHandler: any, handler?: any) {\n\t\tif (typeof optionsOrHandler === \"function\") {\n\t\t\treturn createMiddleware(\n\t\t\t\t{\n\t\t\t\t\tuse: opts?.use,\n\t\t\t\t},\n\t\t\t\toptionsOrHandler,\n\t\t\t);\n\t\t}\n\t\tif (!handler) {\n\t\t\tthrow new Error(\"Middleware handler is required\");\n\t\t}\n\t\tconst middleware = createMiddleware(\n\t\t\t{\n\t\t\t\t...optionsOrHandler,\n\t\t\t\tmethod: \"*\",\n\t\t\t\tuse: [...(opts?.use || []), ...(optionsOrHandler.use || [])],\n\t\t\t},\n\t\t\thandler,\n\t\t);\n\t\treturn middleware as any;\n\t}\n\treturn fn;\n};\n"],"mappings":";;;;AA0IA,SAAgB,iBAAiB,kBAAuB,SAAe;CACtE,MAAM,kBAAkB,OAAO,aAAqC;EACnE,MAAM,UAAU;EAChB,MAAM,WAAW,OAAO,qBAAqB,aAAa,mBAAmB;EAE7E,MAAM,kBAAkB,MAAMA,sCAAsB,SAAS;GAC5D,SAFe,OAAO,qBAAqB,aAAa,EAAE,GAAG;GAG7D,MAAM;GACN,CAAC;AAEF,MAAI,CAAC,SACJ,OAAM,IAAI,MAAM,0BAA0B;EAE3C,MAAM,WAAW,MAAM,SAAS,gBAAuB;EACvD,MAAM,UAAU,gBAAgB;AAChC,SAAO,QAAQ,gBACZ;GACA;GACA;GACA,GACA;;AAEJ,iBAAgB,UAAU,OAAO,qBAAqB,aAAa,EAAE,GAAG;AACxE,QAAO;;AAmBR,iBAAiB,UAKhB,SACI;CASJ,SAAS,GAAG,kBAAuB,SAAe;AACjD,MAAI,OAAO,qBAAqB,WAC/B,QAAO,iBACN,EACC,KAAK,MAAM,KACX,EACD,iBACA;AAEF,MAAI,CAAC,QACJ,OAAM,IAAI,MAAM,iCAAiC;AAUlD,SARmB,iBAClB;GACC,GAAG;GACH,QAAQ;GACR,KAAK,CAAC,GAAI,MAAM,OAAO,EAAE,EAAG,GAAI,iBAAiB,OAAO,EAAE,CAAE;GAC5D,EACD,QACA;;AAGF,QAAO"}
|
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
import { Prettify } from "./helper.cjs";
|
|
2
|
+
import { InferBodyInput, InferHeaders, InferHeadersInput, InferMiddlewareBody, InferMiddlewareQuery, InferQueryInput, InferRequest, InferRequestInput, InferUse } from "./context.cjs";
|
|
3
|
+
import { EndpointContext, EndpointOptions } from "./endpoint.cjs";
|
|
4
|
+
|
|
5
|
+
//#region src/middleware.d.ts
|
|
6
|
+
interface MiddlewareOptions extends Omit<EndpointOptions, "method"> {}
|
|
7
|
+
type MiddlewareResponse = null | void | undefined | Record<string, any>;
|
|
8
|
+
type MiddlewareContext<Options extends MiddlewareOptions, Context = {}> = EndpointContext<string, Options & {
|
|
9
|
+
method: "*";
|
|
10
|
+
}> & {
|
|
11
|
+
/**
|
|
12
|
+
* Method
|
|
13
|
+
*
|
|
14
|
+
* The request method
|
|
15
|
+
*/
|
|
16
|
+
method: string;
|
|
17
|
+
/**
|
|
18
|
+
* Path
|
|
19
|
+
*
|
|
20
|
+
* The path of the endpoint
|
|
21
|
+
*/
|
|
22
|
+
path: string;
|
|
23
|
+
/**
|
|
24
|
+
* Body
|
|
25
|
+
*
|
|
26
|
+
* The body object will be the parsed JSON from the request and validated
|
|
27
|
+
* against the body schema if it exists
|
|
28
|
+
*/
|
|
29
|
+
body: InferMiddlewareBody<Options>;
|
|
30
|
+
/**
|
|
31
|
+
* Query
|
|
32
|
+
*
|
|
33
|
+
* The query object will be the parsed query string from the request
|
|
34
|
+
* and validated against the query schema if it exists
|
|
35
|
+
*/
|
|
36
|
+
query: InferMiddlewareQuery<Options>;
|
|
37
|
+
/**
|
|
38
|
+
* Params
|
|
39
|
+
*
|
|
40
|
+
* If the path is `/user/:id` and the request is `/user/1` then the
|
|
41
|
+
* params will
|
|
42
|
+
* be `{ id: "1" }` and if the path includes a wildcard like `/user/*`
|
|
43
|
+
* then the
|
|
44
|
+
* params will be `{ _: "1" }` where `_` is the wildcard key. If the
|
|
45
|
+
* wildcard
|
|
46
|
+
* is named like `/user/**:name` then the params will be `{ name: string }`
|
|
47
|
+
*/
|
|
48
|
+
params: string;
|
|
49
|
+
/**
|
|
50
|
+
* Request object
|
|
51
|
+
*
|
|
52
|
+
* If `requireRequest` is set to true in the endpoint options this will be
|
|
53
|
+
* required
|
|
54
|
+
*/
|
|
55
|
+
request: InferRequest<Options>;
|
|
56
|
+
/**
|
|
57
|
+
* Headers
|
|
58
|
+
*
|
|
59
|
+
* If `requireHeaders` is set to true in the endpoint options this will be
|
|
60
|
+
* required
|
|
61
|
+
*/
|
|
62
|
+
headers: InferHeaders<Options>;
|
|
63
|
+
/**
|
|
64
|
+
* Set header
|
|
65
|
+
*
|
|
66
|
+
* If it's called outside of a request it will just be ignored.
|
|
67
|
+
*/
|
|
68
|
+
setHeader: (key: string, value: string) => void;
|
|
69
|
+
/**
|
|
70
|
+
* Get header
|
|
71
|
+
*
|
|
72
|
+
* If it's called outside of a request it will just return null
|
|
73
|
+
*
|
|
74
|
+
* @param key - The key of the header
|
|
75
|
+
* @returns
|
|
76
|
+
*/
|
|
77
|
+
getHeader: (key: string) => string | null;
|
|
78
|
+
/**
|
|
79
|
+
* JSON
|
|
80
|
+
*
|
|
81
|
+
* a helper function to create a JSON response with
|
|
82
|
+
* the correct headers
|
|
83
|
+
* and status code. If `asResponse` is set to true in
|
|
84
|
+
* the context then
|
|
85
|
+
* it will return a Response object instead of the
|
|
86
|
+
* JSON object.
|
|
87
|
+
*
|
|
88
|
+
* @param json - The JSON object to return
|
|
89
|
+
* @param routerResponse - The response object to
|
|
90
|
+
* return if `asResponse` is
|
|
91
|
+
* true in the context this will take precedence
|
|
92
|
+
*/
|
|
93
|
+
json: <R extends Record<string, any> | null>(json: R, routerResponse?: {
|
|
94
|
+
status?: number;
|
|
95
|
+
headers?: Record<string, string>;
|
|
96
|
+
response?: Response;
|
|
97
|
+
} | Response) => Promise<R>;
|
|
98
|
+
/**
|
|
99
|
+
* Middleware context
|
|
100
|
+
*/
|
|
101
|
+
context: Prettify<Context>;
|
|
102
|
+
};
|
|
103
|
+
declare function createMiddleware<Options extends MiddlewareOptions, R>(options: Options, handler: (context: MiddlewareContext<Options>) => Promise<R>): <InputCtx extends MiddlewareInputContext<Options>>(inputContext: InputCtx) => Promise<R>;
|
|
104
|
+
declare function createMiddleware<Options extends MiddlewareOptions, R>(handler: (context: MiddlewareContext<Options>) => Promise<R>): <InputCtx extends MiddlewareInputContext<Options>>(inputContext: InputCtx) => Promise<R>;
|
|
105
|
+
declare namespace createMiddleware {
|
|
106
|
+
var create: <E extends {
|
|
107
|
+
use?: Middleware[];
|
|
108
|
+
}>(opts?: E) => {
|
|
109
|
+
<Options extends MiddlewareOptions, R>(options: Options, handler: (ctx: MiddlewareContext<Options, InferUse<E["use"]>>) => Promise<R>): (inputContext: MiddlewareInputContext<Options>) => Promise<R>;
|
|
110
|
+
<Options extends MiddlewareOptions, R_1>(handler: (ctx: MiddlewareContext<Options, InferUse<E["use"]>>) => Promise<R_1>): (inputContext: MiddlewareInputContext<Options>) => Promise<R_1>;
|
|
111
|
+
};
|
|
112
|
+
}
|
|
113
|
+
type MiddlewareInputContext<Options extends MiddlewareOptions> = InferBodyInput<Options> & InferQueryInput<Options> & InferRequestInput<Options> & InferHeadersInput<Options> & {
|
|
114
|
+
asResponse?: boolean;
|
|
115
|
+
returnHeaders?: boolean;
|
|
116
|
+
use?: Middleware[];
|
|
117
|
+
};
|
|
118
|
+
type Middleware<Options extends MiddlewareOptions = MiddlewareOptions, Handler extends (inputCtx: any) => Promise<any> = any> = Handler & {
|
|
119
|
+
options: Options;
|
|
120
|
+
};
|
|
121
|
+
//#endregion
|
|
122
|
+
export { Middleware, MiddlewareContext, MiddlewareInputContext, MiddlewareOptions, MiddlewareResponse, createMiddleware };
|
|
123
|
+
//# sourceMappingURL=middleware.d.cts.map
|
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
import { Prettify } from "./helper.mjs";
|
|
2
|
+
import { InferBodyInput, InferHeaders, InferHeadersInput, InferMiddlewareBody, InferMiddlewareQuery, InferQueryInput, InferRequest, InferRequestInput, InferUse } from "./context.mjs";
|
|
3
|
+
import { EndpointContext, EndpointOptions } from "./endpoint.mjs";
|
|
4
|
+
|
|
5
|
+
//#region src/middleware.d.ts
|
|
6
|
+
interface MiddlewareOptions extends Omit<EndpointOptions, "method"> {}
|
|
7
|
+
type MiddlewareResponse = null | void | undefined | Record<string, any>;
|
|
8
|
+
type MiddlewareContext<Options extends MiddlewareOptions, Context = {}> = EndpointContext<string, Options & {
|
|
9
|
+
method: "*";
|
|
10
|
+
}> & {
|
|
11
|
+
/**
|
|
12
|
+
* Method
|
|
13
|
+
*
|
|
14
|
+
* The request method
|
|
15
|
+
*/
|
|
16
|
+
method: string;
|
|
17
|
+
/**
|
|
18
|
+
* Path
|
|
19
|
+
*
|
|
20
|
+
* The path of the endpoint
|
|
21
|
+
*/
|
|
22
|
+
path: string;
|
|
23
|
+
/**
|
|
24
|
+
* Body
|
|
25
|
+
*
|
|
26
|
+
* The body object will be the parsed JSON from the request and validated
|
|
27
|
+
* against the body schema if it exists
|
|
28
|
+
*/
|
|
29
|
+
body: InferMiddlewareBody<Options>;
|
|
30
|
+
/**
|
|
31
|
+
* Query
|
|
32
|
+
*
|
|
33
|
+
* The query object will be the parsed query string from the request
|
|
34
|
+
* and validated against the query schema if it exists
|
|
35
|
+
*/
|
|
36
|
+
query: InferMiddlewareQuery<Options>;
|
|
37
|
+
/**
|
|
38
|
+
* Params
|
|
39
|
+
*
|
|
40
|
+
* If the path is `/user/:id` and the request is `/user/1` then the
|
|
41
|
+
* params will
|
|
42
|
+
* be `{ id: "1" }` and if the path includes a wildcard like `/user/*`
|
|
43
|
+
* then the
|
|
44
|
+
* params will be `{ _: "1" }` where `_` is the wildcard key. If the
|
|
45
|
+
* wildcard
|
|
46
|
+
* is named like `/user/**:name` then the params will be `{ name: string }`
|
|
47
|
+
*/
|
|
48
|
+
params: string;
|
|
49
|
+
/**
|
|
50
|
+
* Request object
|
|
51
|
+
*
|
|
52
|
+
* If `requireRequest` is set to true in the endpoint options this will be
|
|
53
|
+
* required
|
|
54
|
+
*/
|
|
55
|
+
request: InferRequest<Options>;
|
|
56
|
+
/**
|
|
57
|
+
* Headers
|
|
58
|
+
*
|
|
59
|
+
* If `requireHeaders` is set to true in the endpoint options this will be
|
|
60
|
+
* required
|
|
61
|
+
*/
|
|
62
|
+
headers: InferHeaders<Options>;
|
|
63
|
+
/**
|
|
64
|
+
* Set header
|
|
65
|
+
*
|
|
66
|
+
* If it's called outside of a request it will just be ignored.
|
|
67
|
+
*/
|
|
68
|
+
setHeader: (key: string, value: string) => void;
|
|
69
|
+
/**
|
|
70
|
+
* Get header
|
|
71
|
+
*
|
|
72
|
+
* If it's called outside of a request it will just return null
|
|
73
|
+
*
|
|
74
|
+
* @param key - The key of the header
|
|
75
|
+
* @returns
|
|
76
|
+
*/
|
|
77
|
+
getHeader: (key: string) => string | null;
|
|
78
|
+
/**
|
|
79
|
+
* JSON
|
|
80
|
+
*
|
|
81
|
+
* a helper function to create a JSON response with
|
|
82
|
+
* the correct headers
|
|
83
|
+
* and status code. If `asResponse` is set to true in
|
|
84
|
+
* the context then
|
|
85
|
+
* it will return a Response object instead of the
|
|
86
|
+
* JSON object.
|
|
87
|
+
*
|
|
88
|
+
* @param json - The JSON object to return
|
|
89
|
+
* @param routerResponse - The response object to
|
|
90
|
+
* return if `asResponse` is
|
|
91
|
+
* true in the context this will take precedence
|
|
92
|
+
*/
|
|
93
|
+
json: <R extends Record<string, any> | null>(json: R, routerResponse?: {
|
|
94
|
+
status?: number;
|
|
95
|
+
headers?: Record<string, string>;
|
|
96
|
+
response?: Response;
|
|
97
|
+
} | Response) => Promise<R>;
|
|
98
|
+
/**
|
|
99
|
+
* Middleware context
|
|
100
|
+
*/
|
|
101
|
+
context: Prettify<Context>;
|
|
102
|
+
};
|
|
103
|
+
declare function createMiddleware<Options extends MiddlewareOptions, R>(options: Options, handler: (context: MiddlewareContext<Options>) => Promise<R>): <InputCtx extends MiddlewareInputContext<Options>>(inputContext: InputCtx) => Promise<R>;
|
|
104
|
+
declare function createMiddleware<Options extends MiddlewareOptions, R>(handler: (context: MiddlewareContext<Options>) => Promise<R>): <InputCtx extends MiddlewareInputContext<Options>>(inputContext: InputCtx) => Promise<R>;
|
|
105
|
+
declare namespace createMiddleware {
|
|
106
|
+
var create: <E extends {
|
|
107
|
+
use?: Middleware[];
|
|
108
|
+
}>(opts?: E) => {
|
|
109
|
+
<Options extends MiddlewareOptions, R>(options: Options, handler: (ctx: MiddlewareContext<Options, InferUse<E["use"]>>) => Promise<R>): (inputContext: MiddlewareInputContext<Options>) => Promise<R>;
|
|
110
|
+
<Options extends MiddlewareOptions, R_1>(handler: (ctx: MiddlewareContext<Options, InferUse<E["use"]>>) => Promise<R_1>): (inputContext: MiddlewareInputContext<Options>) => Promise<R_1>;
|
|
111
|
+
};
|
|
112
|
+
}
|
|
113
|
+
type MiddlewareInputContext<Options extends MiddlewareOptions> = InferBodyInput<Options> & InferQueryInput<Options> & InferRequestInput<Options> & InferHeadersInput<Options> & {
|
|
114
|
+
asResponse?: boolean;
|
|
115
|
+
returnHeaders?: boolean;
|
|
116
|
+
use?: Middleware[];
|
|
117
|
+
};
|
|
118
|
+
type Middleware<Options extends MiddlewareOptions = MiddlewareOptions, Handler extends (inputCtx: any) => Promise<any> = any> = Handler & {
|
|
119
|
+
options: Options;
|
|
120
|
+
};
|
|
121
|
+
//#endregion
|
|
122
|
+
export { Middleware, MiddlewareContext, MiddlewareInputContext, MiddlewareOptions, MiddlewareResponse, createMiddleware };
|
|
123
|
+
//# sourceMappingURL=middleware.d.mts.map
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import { createInternalContext } from "./context.mjs";
|
|
2
|
+
import "./endpoint.mjs";
|
|
3
|
+
|
|
4
|
+
//#region src/middleware.ts
|
|
5
|
+
function createMiddleware(optionsOrHandler, handler) {
|
|
6
|
+
const internalHandler = async (inputCtx) => {
|
|
7
|
+
const context = inputCtx;
|
|
8
|
+
const _handler = typeof optionsOrHandler === "function" ? optionsOrHandler : handler;
|
|
9
|
+
const internalContext = await createInternalContext(context, {
|
|
10
|
+
options: typeof optionsOrHandler === "function" ? {} : optionsOrHandler,
|
|
11
|
+
path: "/"
|
|
12
|
+
});
|
|
13
|
+
if (!_handler) throw new Error("handler must be defined");
|
|
14
|
+
const response = await _handler(internalContext);
|
|
15
|
+
const headers = internalContext.responseHeaders;
|
|
16
|
+
return context.returnHeaders ? {
|
|
17
|
+
headers,
|
|
18
|
+
response
|
|
19
|
+
} : response;
|
|
20
|
+
};
|
|
21
|
+
internalHandler.options = typeof optionsOrHandler === "function" ? {} : optionsOrHandler;
|
|
22
|
+
return internalHandler;
|
|
23
|
+
}
|
|
24
|
+
createMiddleware.create = (opts) => {
|
|
25
|
+
function fn(optionsOrHandler, handler) {
|
|
26
|
+
if (typeof optionsOrHandler === "function") return createMiddleware({ use: opts?.use }, optionsOrHandler);
|
|
27
|
+
if (!handler) throw new Error("Middleware handler is required");
|
|
28
|
+
return createMiddleware({
|
|
29
|
+
...optionsOrHandler,
|
|
30
|
+
method: "*",
|
|
31
|
+
use: [...opts?.use || [], ...optionsOrHandler.use || []]
|
|
32
|
+
}, handler);
|
|
33
|
+
}
|
|
34
|
+
return fn;
|
|
35
|
+
};
|
|
36
|
+
|
|
37
|
+
//#endregion
|
|
38
|
+
export { createMiddleware };
|
|
39
|
+
//# sourceMappingURL=middleware.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"middleware.mjs","names":[],"sources":["../src/middleware.ts"],"sourcesContent":["import {\n\tcreateEndpoint,\n\ttype Endpoint,\n\ttype EndpointContext,\n\ttype EndpointOptions,\n} from \"./endpoint\";\nimport {\n\tcreateInternalContext,\n\ttype InferBody,\n\ttype InferBodyInput,\n\ttype InferHeaders,\n\ttype InferHeadersInput,\n\ttype InferMiddlewareBody,\n\ttype InferMiddlewareQuery,\n\ttype InferQuery,\n\ttype InferQueryInput,\n\ttype InferRequest,\n\ttype InferRequestInput,\n\ttype InferUse,\n\ttype InputContext,\n} from \"./context\";\nimport type { Prettify } from \"./helper\";\n\nexport interface MiddlewareOptions extends Omit<EndpointOptions, \"method\"> {}\n\nexport type MiddlewareResponse = null | void | undefined | Record<string, any>;\n\nexport type MiddlewareContext<Options extends MiddlewareOptions, Context = {}> = EndpointContext<\n\tstring,\n\tOptions & {\n\t\tmethod: \"*\";\n\t}\n> & {\n\t/**\n\t * Method\n\t *\n\t * The request method\n\t */\n\tmethod: string;\n\t/**\n\t * Path\n\t *\n\t * The path of the endpoint\n\t */\n\tpath: string;\n\t/**\n\t * Body\n\t *\n\t * The body object will be the parsed JSON from the request and validated\n\t * against the body schema if it exists\n\t */\n\tbody: InferMiddlewareBody<Options>;\n\t/**\n\t * Query\n\t *\n\t * The query object will be the parsed query string from the request\n\t * and validated against the query schema if it exists\n\t */\n\tquery: InferMiddlewareQuery<Options>;\n\t/**\n\t * Params\n\t *\n\t * If the path is `/user/:id` and the request is `/user/1` then the\n\t * params will\n\t * be `{ id: \"1\" }` and if the path includes a wildcard like `/user/*`\n\t * then the\n\t * params will be `{ _: \"1\" }` where `_` is the wildcard key. If the\n\t * wildcard\n\t * is named like `/user/**:name` then the params will be `{ name: string }`\n\t */\n\tparams: string;\n\t/**\n\t * Request object\n\t *\n\t * If `requireRequest` is set to true in the endpoint options this will be\n\t * required\n\t */\n\trequest: InferRequest<Options>;\n\t/**\n\t * Headers\n\t *\n\t * If `requireHeaders` is set to true in the endpoint options this will be\n\t * required\n\t */\n\theaders: InferHeaders<Options>;\n\t/**\n\t * Set header\n\t *\n\t * If it's called outside of a request it will just be ignored.\n\t */\n\tsetHeader: (key: string, value: string) => void;\n\t/**\n\t * Get header\n\t *\n\t * If it's called outside of a request it will just return null\n\t *\n\t * @param key - The key of the header\n\t * @returns\n\t */\n\tgetHeader: (key: string) => string | null;\n\t/**\n\t * JSON\n\t *\n\t * a helper function to create a JSON response with\n\t * the correct headers\n\t * and status code. If `asResponse` is set to true in\n\t * the context then\n\t * it will return a Response object instead of the\n\t * JSON object.\n\t *\n\t * @param json - The JSON object to return\n\t * @param routerResponse - The response object to\n\t * return if `asResponse` is\n\t * true in the context this will take precedence\n\t */\n\tjson: <R extends Record<string, any> | null>(\n\t\tjson: R,\n\t\trouterResponse?:\n\t\t\t| {\n\t\t\t\t\tstatus?: number;\n\t\t\t\t\theaders?: Record<string, string>;\n\t\t\t\t\tresponse?: Response;\n\t\t\t }\n\t\t\t| Response,\n\t) => Promise<R>;\n\t/**\n\t * Middleware context\n\t */\n\tcontext: Prettify<Context>;\n};\n\nexport function createMiddleware<Options extends MiddlewareOptions, R>(\n\toptions: Options,\n\thandler: (context: MiddlewareContext<Options>) => Promise<R>,\n): <InputCtx extends MiddlewareInputContext<Options>>(inputContext: InputCtx) => Promise<R>;\nexport function createMiddleware<Options extends MiddlewareOptions, R>(\n\thandler: (context: MiddlewareContext<Options>) => Promise<R>,\n): <InputCtx extends MiddlewareInputContext<Options>>(inputContext: InputCtx) => Promise<R>;\nexport function createMiddleware(optionsOrHandler: any, handler?: any) {\n\tconst internalHandler = async (inputCtx: InputContext<any, any>) => {\n\t\tconst context = inputCtx as InputContext<any, any>;\n\t\tconst _handler = typeof optionsOrHandler === \"function\" ? optionsOrHandler : handler;\n\t\tconst options = typeof optionsOrHandler === \"function\" ? {} : optionsOrHandler;\n\t\tconst internalContext = await createInternalContext(context, {\n\t\t\toptions,\n\t\t\tpath: \"/\",\n\t\t});\n\n\t\tif (!_handler) {\n\t\t\tthrow new Error(\"handler must be defined\");\n\t\t}\n\t\tconst response = await _handler(internalContext as any);\n\t\tconst headers = internalContext.responseHeaders;\n\t\treturn context.returnHeaders\n\t\t\t? {\n\t\t\t\t\theaders,\n\t\t\t\t\tresponse,\n\t\t\t\t}\n\t\t\t: response;\n\t};\n\tinternalHandler.options = typeof optionsOrHandler === \"function\" ? {} : optionsOrHandler;\n\treturn internalHandler;\n}\n\nexport type MiddlewareInputContext<Options extends MiddlewareOptions> = InferBodyInput<Options> &\n\tInferQueryInput<Options> &\n\tInferRequestInput<Options> &\n\tInferHeadersInput<Options> & {\n\t\tasResponse?: boolean;\n\t\treturnHeaders?: boolean;\n\t\tuse?: Middleware[];\n\t};\n\nexport type Middleware<\n\tOptions extends MiddlewareOptions = MiddlewareOptions,\n\tHandler extends (inputCtx: any) => Promise<any> = any,\n> = Handler & {\n\toptions: Options;\n};\n\ncreateMiddleware.create = <\n\tE extends {\n\t\tuse?: Middleware[];\n\t},\n>(\n\topts?: E,\n) => {\n\ttype InferredContext = InferUse<E[\"use\"]>;\n\tfunction fn<Options extends MiddlewareOptions, R>(\n\t\toptions: Options,\n\t\thandler: (ctx: MiddlewareContext<Options, InferredContext>) => Promise<R>,\n\t): (inputContext: MiddlewareInputContext<Options>) => Promise<R>;\n\tfunction fn<Options extends MiddlewareOptions, R>(\n\t\thandler: (ctx: MiddlewareContext<Options, InferredContext>) => Promise<R>,\n\t): (inputContext: MiddlewareInputContext<Options>) => Promise<R>;\n\tfunction fn(optionsOrHandler: any, handler?: any) {\n\t\tif (typeof optionsOrHandler === \"function\") {\n\t\t\treturn createMiddleware(\n\t\t\t\t{\n\t\t\t\t\tuse: opts?.use,\n\t\t\t\t},\n\t\t\t\toptionsOrHandler,\n\t\t\t);\n\t\t}\n\t\tif (!handler) {\n\t\t\tthrow new Error(\"Middleware handler is required\");\n\t\t}\n\t\tconst middleware = createMiddleware(\n\t\t\t{\n\t\t\t\t...optionsOrHandler,\n\t\t\t\tmethod: \"*\",\n\t\t\t\tuse: [...(opts?.use || []), ...(optionsOrHandler.use || [])],\n\t\t\t},\n\t\t\thandler,\n\t\t);\n\t\treturn middleware as any;\n\t}\n\treturn fn;\n};\n"],"mappings":";;;;AA0IA,SAAgB,iBAAiB,kBAAuB,SAAe;CACtE,MAAM,kBAAkB,OAAO,aAAqC;EACnE,MAAM,UAAU;EAChB,MAAM,WAAW,OAAO,qBAAqB,aAAa,mBAAmB;EAE7E,MAAM,kBAAkB,MAAM,sBAAsB,SAAS;GAC5D,SAFe,OAAO,qBAAqB,aAAa,EAAE,GAAG;GAG7D,MAAM;GACN,CAAC;AAEF,MAAI,CAAC,SACJ,OAAM,IAAI,MAAM,0BAA0B;EAE3C,MAAM,WAAW,MAAM,SAAS,gBAAuB;EACvD,MAAM,UAAU,gBAAgB;AAChC,SAAO,QAAQ,gBACZ;GACA;GACA;GACA,GACA;;AAEJ,iBAAgB,UAAU,OAAO,qBAAqB,aAAa,EAAE,GAAG;AACxE,QAAO;;AAmBR,iBAAiB,UAKhB,SACI;CASJ,SAAS,GAAG,kBAAuB,SAAe;AACjD,MAAI,OAAO,qBAAqB,WAC/B,QAAO,iBACN,EACC,KAAK,MAAM,KACX,EACD,iBACA;AAEF,MAAI,CAAC,QACJ,OAAM,IAAI,MAAM,iCAAiC;AAUlD,SARmB,iBAClB;GACC,GAAG;GACH,QAAQ;GACR,KAAK,CAAC,GAAI,MAAM,OAAO,EAAE,EAAG,GAAI,iBAAiB,OAAO,EAAE,CAAE;GAC5D,EACD,QACA;;AAGF,QAAO"}
|
package/dist/node.cjs
CHANGED
|
@@ -1,155 +1,9 @@
|
|
|
1
|
-
|
|
2
|
-
var __create = Object.create;
|
|
3
|
-
var __defProp = Object.defineProperty;
|
|
4
|
-
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
5
|
-
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
6
|
-
var __getProtoOf = Object.getPrototypeOf;
|
|
7
|
-
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
8
|
-
var __copyProps = (to, from, except, desc) => {
|
|
9
|
-
if (from && typeof from === "object" || typeof from === "function") {
|
|
10
|
-
for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
|
|
11
|
-
key = keys[i];
|
|
12
|
-
if (!__hasOwnProp.call(to, key) && key !== except) {
|
|
13
|
-
__defProp(to, key, {
|
|
14
|
-
get: ((k) => from[k]).bind(null, key),
|
|
15
|
-
enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
|
|
16
|
-
});
|
|
17
|
-
}
|
|
18
|
-
}
|
|
19
|
-
}
|
|
20
|
-
return to;
|
|
21
|
-
};
|
|
22
|
-
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
|
|
23
|
-
value: mod,
|
|
24
|
-
enumerable: true
|
|
25
|
-
}) : target, mod));
|
|
1
|
+
const require_request = require('./adapters/node/request.cjs');
|
|
26
2
|
|
|
27
|
-
//#endregion
|
|
28
|
-
let set_cookie_parser = require("set-cookie-parser");
|
|
29
|
-
set_cookie_parser = __toESM(set_cookie_parser);
|
|
30
|
-
|
|
31
|
-
//#region src/adapters/node/request.ts
|
|
32
|
-
function get_raw_body(req, body_size_limit) {
|
|
33
|
-
const h = req.headers;
|
|
34
|
-
if (!h["content-type"]) return null;
|
|
35
|
-
const content_length = Number(h["content-length"]);
|
|
36
|
-
if (req.httpVersionMajor === 1 && isNaN(content_length) && h["transfer-encoding"] == null || content_length === 0) return null;
|
|
37
|
-
let length = content_length;
|
|
38
|
-
if (body_size_limit) {
|
|
39
|
-
if (!length) length = body_size_limit;
|
|
40
|
-
else if (length > body_size_limit) throw Error(`Received content-length of ${length}, but only accept up to ${body_size_limit} bytes.`);
|
|
41
|
-
}
|
|
42
|
-
if (req.destroyed) {
|
|
43
|
-
const readable = new ReadableStream();
|
|
44
|
-
readable.cancel();
|
|
45
|
-
return readable;
|
|
46
|
-
}
|
|
47
|
-
let size = 0;
|
|
48
|
-
let cancelled = false;
|
|
49
|
-
return new ReadableStream({
|
|
50
|
-
start(controller) {
|
|
51
|
-
req.on("error", (error) => {
|
|
52
|
-
cancelled = true;
|
|
53
|
-
controller.error(error);
|
|
54
|
-
});
|
|
55
|
-
req.on("end", () => {
|
|
56
|
-
if (cancelled) return;
|
|
57
|
-
controller.close();
|
|
58
|
-
});
|
|
59
|
-
req.on("data", (chunk) => {
|
|
60
|
-
if (cancelled) return;
|
|
61
|
-
size += chunk.length;
|
|
62
|
-
if (size > length) {
|
|
63
|
-
cancelled = true;
|
|
64
|
-
controller.error(/* @__PURE__ */ new Error(`request body size exceeded ${content_length ? "'content-length'" : "BODY_SIZE_LIMIT"} of ${length}`));
|
|
65
|
-
return;
|
|
66
|
-
}
|
|
67
|
-
controller.enqueue(chunk);
|
|
68
|
-
if (controller.desiredSize === null || controller.desiredSize <= 0) req.pause();
|
|
69
|
-
});
|
|
70
|
-
},
|
|
71
|
-
pull() {
|
|
72
|
-
req.resume();
|
|
73
|
-
},
|
|
74
|
-
cancel(reason) {
|
|
75
|
-
cancelled = true;
|
|
76
|
-
req.destroy(reason);
|
|
77
|
-
}
|
|
78
|
-
});
|
|
79
|
-
}
|
|
80
|
-
function getRequest({ request, base, bodySizeLimit }) {
|
|
81
|
-
const baseUrl = request?.baseUrl;
|
|
82
|
-
const fullPath = baseUrl ? baseUrl + request.url : request.url;
|
|
83
|
-
const maybeConsumedReq = request;
|
|
84
|
-
let body = void 0;
|
|
85
|
-
const method = request.method;
|
|
86
|
-
if (method !== "GET" && method !== "HEAD") if (maybeConsumedReq.body !== void 0) {
|
|
87
|
-
const bodyContent = typeof maybeConsumedReq.body === "string" ? maybeConsumedReq.body : JSON.stringify(maybeConsumedReq.body);
|
|
88
|
-
body = new ReadableStream({ start(controller) {
|
|
89
|
-
controller.enqueue(new TextEncoder().encode(bodyContent));
|
|
90
|
-
controller.close();
|
|
91
|
-
} });
|
|
92
|
-
} else body = get_raw_body(request, bodySizeLimit);
|
|
93
|
-
return new Request(base + fullPath, {
|
|
94
|
-
duplex: "half",
|
|
95
|
-
method: request.method,
|
|
96
|
-
body,
|
|
97
|
-
headers: request.headers
|
|
98
|
-
});
|
|
99
|
-
}
|
|
100
|
-
async function setResponse(res, response) {
|
|
101
|
-
for (const [key, value] of response.headers) try {
|
|
102
|
-
res.setHeader(key, key === "set-cookie" ? set_cookie_parser.splitCookiesString(response.headers.get(key)) : value);
|
|
103
|
-
} catch (error) {
|
|
104
|
-
res.getHeaderNames().forEach((name) => res.removeHeader(name));
|
|
105
|
-
res.writeHead(500).end(String(error));
|
|
106
|
-
return;
|
|
107
|
-
}
|
|
108
|
-
res.writeHead(response.status);
|
|
109
|
-
if (!response.body) {
|
|
110
|
-
res.end();
|
|
111
|
-
return;
|
|
112
|
-
}
|
|
113
|
-
if (response.body.locked) {
|
|
114
|
-
res.end("Fatal error: Response body is locked. This can happen when the response was already read (for example through 'response.json()' or 'response.text()').");
|
|
115
|
-
return;
|
|
116
|
-
}
|
|
117
|
-
const reader = response.body.getReader();
|
|
118
|
-
if (res.destroyed) {
|
|
119
|
-
reader.cancel();
|
|
120
|
-
return;
|
|
121
|
-
}
|
|
122
|
-
const cancel = (error) => {
|
|
123
|
-
res.off("close", cancel);
|
|
124
|
-
res.off("error", cancel);
|
|
125
|
-
reader.cancel(error).catch(() => {});
|
|
126
|
-
if (error) res.destroy(error);
|
|
127
|
-
};
|
|
128
|
-
res.on("close", cancel);
|
|
129
|
-
res.on("error", cancel);
|
|
130
|
-
next();
|
|
131
|
-
async function next() {
|
|
132
|
-
try {
|
|
133
|
-
for (;;) {
|
|
134
|
-
const { done, value } = await reader.read();
|
|
135
|
-
if (done) break;
|
|
136
|
-
if (!res.write(value)) {
|
|
137
|
-
res.once("drain", next);
|
|
138
|
-
return;
|
|
139
|
-
}
|
|
140
|
-
}
|
|
141
|
-
res.end();
|
|
142
|
-
} catch (error) {
|
|
143
|
-
cancel(error instanceof Error ? error : new Error(String(error)));
|
|
144
|
-
}
|
|
145
|
-
}
|
|
146
|
-
}
|
|
147
|
-
|
|
148
|
-
//#endregion
|
|
149
3
|
//#region src/adapters/node/index.ts
|
|
150
4
|
function toNodeHandler(handler) {
|
|
151
5
|
return async (req, res) => {
|
|
152
|
-
return setResponse(res, await handler(getRequest({
|
|
6
|
+
return require_request.setResponse(res, await handler(require_request.getRequest({
|
|
153
7
|
base: `${req.headers["x-forwarded-proto"] || (req.socket.encrypted ? "https" : "http")}://${req.headers[":authority"] || req.headers.host}`,
|
|
154
8
|
request: req
|
|
155
9
|
})));
|
|
@@ -157,8 +11,7 @@ function toNodeHandler(handler) {
|
|
|
157
11
|
}
|
|
158
12
|
|
|
159
13
|
//#endregion
|
|
160
|
-
exports.
|
|
161
|
-
exports.
|
|
162
|
-
exports.setResponse = setResponse;
|
|
14
|
+
exports.getRequest = require_request.getRequest;
|
|
15
|
+
exports.setResponse = require_request.setResponse;
|
|
163
16
|
exports.toNodeHandler = toNodeHandler;
|
|
164
17
|
//# sourceMappingURL=node.cjs.map
|
package/dist/node.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"node.cjs","names":[],"sources":["../src/adapters/node/
|
|
1
|
+
{"version":3,"file":"node.cjs","names":["setResponse","getRequest"],"sources":["../src/adapters/node/index.ts"],"sourcesContent":["import type { IncomingMessage, ServerResponse } from \"node:http\";\n\nimport { getRequest, setResponse } from \"./request\";\nimport type { Router } from \"../../router.js\";\n\nexport function toNodeHandler(handler: Router[\"handler\"]) {\n\treturn async (req: IncomingMessage, res: ServerResponse) => {\n\t\tconst protocol =\n\t\t\treq.headers[\"x-forwarded-proto\"] || ((req.socket as any).encrypted ? \"https\" : \"http\");\n\t\tconst base = `${protocol}://${req.headers[\":authority\"] || req.headers.host}`;\n\t\tconst response = await handler(getRequest({ base, request: req }));\n\t\treturn setResponse(res, response);\n\t};\n}\n\nexport { getRequest, setResponse };\n"],"mappings":";;;AAKA,SAAgB,cAAc,SAA4B;AACzD,QAAO,OAAO,KAAsB,QAAwB;AAK3D,SAAOA,4BAAY,KADF,MAAM,QAAQC,2BAAW;GAAE,MAD/B,GADZ,IAAI,QAAQ,yBAA0B,IAAI,OAAe,YAAY,UAAU,QACvD,KAAK,IAAI,QAAQ,iBAAiB,IAAI,QAAQ;GACrB,SAAS;GAAK,CAAC,CAAC,CACjC"}
|
package/dist/node.d.cts
CHANGED
|
@@ -1,18 +1,7 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { getRequest, setResponse } from "./adapters/node/request.cjs";
|
|
2
|
+
import { Router } from "./router.cjs";
|
|
2
3
|
import { IncomingMessage, ServerResponse } from "node:http";
|
|
3
4
|
|
|
4
|
-
//#region src/adapters/node/request.d.ts
|
|
5
|
-
declare function getRequest({
|
|
6
|
-
request,
|
|
7
|
-
base,
|
|
8
|
-
bodySizeLimit
|
|
9
|
-
}: {
|
|
10
|
-
base: string;
|
|
11
|
-
bodySizeLimit?: number;
|
|
12
|
-
request: IncomingMessage;
|
|
13
|
-
}): Request;
|
|
14
|
-
declare function setResponse(res: ServerResponse, response: Response): Promise<void>;
|
|
15
|
-
//#endregion
|
|
16
5
|
//#region src/adapters/node/index.d.ts
|
|
17
6
|
declare function toNodeHandler(handler: Router["handler"]): (req: IncomingMessage, res: ServerResponse) => Promise<void>;
|
|
18
7
|
//#endregion
|
package/dist/node.d.mts
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import { getRequest, setResponse } from "./adapters/node/request.mjs";
|
|
2
|
+
import { Router } from "./router.mjs";
|
|
3
|
+
import { IncomingMessage, ServerResponse } from "node:http";
|
|
4
|
+
|
|
5
|
+
//#region src/adapters/node/index.d.ts
|
|
6
|
+
declare function toNodeHandler(handler: Router["handler"]): (req: IncomingMessage, res: ServerResponse) => Promise<void>;
|
|
7
|
+
//#endregion
|
|
8
|
+
export { getRequest, setResponse, toNodeHandler };
|
|
9
|
+
//# sourceMappingURL=node.d.mts.map
|