h3 0.4.0 → 0.5.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/dist/index.d.ts CHANGED
@@ -1,54 +1,90 @@
1
- import { IncomingMessage, ServerResponse } from 'http';
1
+ import http from 'http';
2
+ import { CookieSerializeOptions } from 'cookie-es';
2
3
  import * as ufo from 'ufo';
3
4
 
4
- declare type Encoding = false | 'ascii' | 'utf8' | 'utf-8' | 'utf16le' | 'ucs2' | 'ucs-2' | 'base64' | 'latin1' | 'binary' | 'hex';
5
+ interface H3Event {
6
+ '__is_event__': true;
7
+ event: H3Event;
8
+ req: IncomingMessage;
9
+ res: ServerResponse;
10
+ /**
11
+ * Request params only filled with h3 Router handlers
12
+ */
13
+ params?: Record<string, any>;
14
+ }
15
+ declare type CompatibilityEvent = H3Event | IncomingMessage | ServerResponse;
16
+ declare type _JSONValue<T = string | number | boolean> = T | T[] | Record<string, T>;
17
+ declare type JSONValue = _JSONValue<_JSONValue>;
18
+ declare type H3Response = void | JSONValue | Buffer;
19
+ interface EventHandler {
20
+ '__is_handler__'?: true;
21
+ (event: CompatibilityEvent): H3Response | Promise<H3Response>;
22
+ }
23
+ declare function defineEventHandler(handler: EventHandler): EventHandler;
24
+ declare function defineLazyEventHandler(factory: () => EventHandler | Promise<EventHandler>): EventHandler;
25
+ declare function isEventHandler(input: any): input is EventHandler;
26
+ declare type CompatibilityEventHandler = EventHandler | Handler | Middleware;
27
+ declare function toEventHandler(handler: CompatibilityEventHandler): EventHandler;
28
+ declare function createEvent(req: http.IncomingMessage, res: http.ServerResponse): CompatibilityEvent;
29
+ declare function isEvent(input: any): input is H3Event;
5
30
 
6
- declare type Handle<T = any, ReqT = {}> = (req: IncomingMessage & ReqT, res: ServerResponse) => T;
7
- declare type PHandle = Handle<Promise<any>>;
31
+ interface IncomingMessage extends http.IncomingMessage {
32
+ originalUrl?: string;
33
+ event: H3Event;
34
+ req: H3Event['req'];
35
+ res: H3Event['res'];
36
+ }
37
+ interface ServerResponse extends http.ServerResponse {
38
+ event: H3Event;
39
+ res: H3Event['res'];
40
+ req: http.ServerResponse['req'] & {
41
+ event: H3Event;
42
+ originalUrl?: string;
43
+ };
44
+ }
45
+ declare type Handler<T = any, ReqT = {}> = (req: IncomingMessage & ReqT, res: ServerResponse) => T;
46
+ declare type PromisifiedHandler = Handler<Promise<any>>;
8
47
  declare type Middleware = (req: IncomingMessage, res: ServerResponse, next: (err?: Error) => any) => any;
9
- declare type LazyHandle = () => Handle | Promise<Handle>;
10
- declare const defineHandle: <T>(handler: Handle<T, {}>) => Handle<T, {}>;
11
- declare const defineMiddleware: (middleware: Middleware) => Middleware;
12
- declare function promisifyHandle(handle: Handle | Middleware): PHandle;
13
- declare function callHandle(handle: Middleware, req: IncomingMessage, res: ServerResponse): Promise<unknown>;
14
- declare function lazyHandle(handle: LazyHandle, promisify?: boolean): PHandle;
15
- declare function useBase(base: string, handle: PHandle): PHandle;
48
+ declare type LazyHandler = () => Handler | Promise<Handler>;
49
+ declare type Encoding = false | 'ascii' | 'utf8' | 'utf-8' | 'utf16le' | 'ucs2' | 'ucs-2' | 'base64' | 'latin1' | 'binary' | 'hex';
50
+ declare type HTTPMethod = 'GET' | 'HEAD' | 'POST' | 'PUT' | 'DELETE' | 'CONNECT' | 'OPTIONS' | 'TRACE';
16
51
 
17
52
  interface Layer {
18
53
  route: string;
19
54
  match?: Matcher;
20
- handle: Handle;
55
+ handler: EventHandler;
21
56
  }
22
57
  declare type Stack = Layer[];
23
58
  interface InputLayer {
24
59
  route?: string;
25
60
  match?: Matcher;
26
- handle: Handle | LazyHandle;
61
+ handler: Handler | LazyHandler;
27
62
  lazy?: boolean;
63
+ /**
64
+ * @deprecated
65
+ */
28
66
  promisify?: boolean;
29
67
  }
30
68
  declare type InputStack = InputLayer[];
31
- declare type Matcher = (url: string, req?: IncomingMessage) => boolean;
69
+ declare type Matcher = (url: string, event?: CompatibilityEvent) => boolean;
32
70
  interface AppUse {
33
- (route: string | string[], handle: Middleware | Middleware[], options?: Partial<InputLayer>): App;
34
- (route: string | string[], handle: Handle | Handle[], options?: Partial<InputLayer>): App;
35
- (handle: Middleware | Middleware[], options?: Partial<InputLayer>): App;
36
- (handle: Handle | Handle[], options?: Partial<InputLayer>): App;
71
+ (route: string | string[], handler: CompatibilityEventHandler | CompatibilityEventHandler[], options?: Partial<InputLayer>): App;
72
+ (handler: CompatibilityEventHandler | CompatibilityEventHandler[], options?: Partial<InputLayer>): App;
37
73
  (options: InputLayer): App;
38
74
  }
39
- interface App {
40
- (req: IncomingMessage, res: ServerResponse): Promise<any>;
75
+ declare type NodeHandler = (req: http.IncomingMessage, res: http.ServerResponse) => void | Promise<void>;
76
+ interface App extends NodeHandler {
41
77
  stack: Stack;
42
- _handle: PHandle;
78
+ handler: EventHandler;
43
79
  use: AppUse;
44
80
  }
45
81
  interface AppOptions {
46
82
  debug?: boolean;
47
- onError?: (error: Error, req: IncomingMessage, res: ServerResponse) => any;
83
+ onError?: (error: Error, event: CompatibilityEvent) => any;
48
84
  }
49
85
  declare function createApp(options?: AppOptions): App;
50
- declare function use(app: App, arg1: string | Handle | InputLayer | InputLayer[], arg2?: Handle | Partial<InputLayer> | Handle[] | Middleware | Middleware[], arg3?: Partial<InputLayer>): App;
51
- declare function createHandle(stack: Stack, options: AppOptions): PHandle;
86
+ declare function use(app: App, arg1: string | Handler | InputLayer | InputLayer[], arg2?: Handler | Partial<InputLayer> | Handler[] | Middleware | Middleware[], arg3?: Partial<InputLayer>): App;
87
+ declare function createAppEventHandler(stack: Stack, options: AppOptions): EventHandler;
52
88
 
53
89
  /**
54
90
  * H3 Runtime Error
@@ -77,30 +113,37 @@ declare function createError(input: Partial<H3Error>): H3Error;
77
113
  * H3 internally uses this function to handle unhandled errors.<br>
78
114
  * Note that calling this function will close the connection and no other data will be sent to client afterwards.
79
115
  *
80
- * @param res {ServerResponse} The ServerResponse object is passed as the second parameter in the handler function
116
+ @param event {CompatibilityEvent} H3 event or req passed by h3 handler
81
117
  * @param error {H3Error|Error} Raised error
82
118
  * @param debug {Boolean} Whether application is in debug mode.<br>
83
119
  * In the debug mode the stack trace of errors will be return in response.
84
120
  */
85
- declare function sendError(res: ServerResponse, error: Error | H3Error, debug?: boolean): void;
121
+ declare function sendError(event: CompatibilityEvent, error: Error | H3Error, debug?: boolean): void;
122
+
123
+ declare const defineHandler: <T>(handler: Handler<T, {}>) => Handler<T, {}>;
124
+ /** @deprecated Use defineHandler */
125
+ declare const defineHandle: <T>(handler: Handler<T, {}>) => Handler<T, {}>;
126
+ declare const defineMiddleware: (middleware: Middleware) => Middleware;
127
+ declare function promisifyHandler(handler: Handler | Middleware): PromisifiedHandler;
128
+ /** @deprecated Use defineHandler */
129
+ declare const promisifyHandle: typeof promisifyHandler;
130
+ declare function callHandler(handler: Middleware, req: IncomingMessage, res: ServerResponse): Promise<unknown>;
131
+ declare function defineLazyHandler(handler: LazyHandler, promisify?: boolean): PromisifiedHandler;
132
+ /** @deprecated Use defineLazyHandler */
133
+ declare const lazyHandle: typeof defineLazyHandler;
134
+ declare function useBase(base: string, handler: PromisifiedHandler): PromisifiedHandler;
86
135
 
87
- declare const RawBodySymbol: unique symbol;
88
- interface _IncomingMessage extends IncomingMessage {
89
- [RawBodySymbol]?: Promise<Buffer>;
90
- ParsedBodySymbol?: any;
91
- body?: any;
92
- }
93
136
  /**
94
137
  * Reads body of the request and returns encoded raw string (default) or `Buffer` if encoding if falsy.
95
- * @param req {IncomingMessage} An IncomingMessage object is created by [http.Server](https://nodejs.org/api/http.html#http_class_http_server)
138
+ * @param event {CompatibilityEvent} H3 event or req passed by h3 handler
96
139
  * @param encoding {Encoding} encoding="utf-8" - The character encoding to use.
97
140
  *
98
141
  * @return {String|Buffer} Encoded raw string or raw Buffer of the body
99
142
  */
100
- declare function useRawBody(req: _IncomingMessage, encoding?: Encoding): Encoding extends false ? Buffer : Promise<string>;
143
+ declare function useRawBody(event: CompatibilityEvent, encoding?: Encoding): Encoding extends false ? Buffer : Promise<string | Buffer>;
101
144
  /**
102
145
  * Reads request body and try to safely parse using [destr](https://github.com/unjs/destr)
103
- * @param req {IncomingMessage} An IncomingMessage object created by [http.Server](https://nodejs.org/api/http.html#http_class_http_server)
146
+ * @param event {CompatibilityEvent} H3 event or req passed by h3 handler
104
147
  * @param encoding {Encoding} encoding="utf-8" - The character encoding to use.
105
148
  *
106
149
  * @return {*} The `Object`, `Array`, `String`, `Number`, `Boolean`, or `null` value corresponding to the request JSON body
@@ -109,121 +152,35 @@ declare function useRawBody(req: _IncomingMessage, encoding?: Encoding): Encodin
109
152
  * const body = await useBody(req)
110
153
  * ```
111
154
  */
112
- declare function useBody<T = any>(req: _IncomingMessage): Promise<T>;
155
+ declare function useBody<T = any>(event: CompatibilityEvent): Promise<T>;
113
156
 
114
157
  declare const MIMES: {
115
158
  html: string;
116
159
  json: string;
117
160
  };
118
161
 
119
- /**
120
- * Additional serialization options
121
- */
122
- interface CookieSerializeOptions {
123
- /**
124
- * Specifies the value for the {@link https://tools.ietf.org/html/rfc6265#section-5.2.3|Domain Set-Cookie attribute}. By default, no
125
- * domain is set, and most clients will consider the cookie to apply to only
126
- * the current domain.
127
- */
128
- domain?: string;
129
- /**
130
- * Specifies a function that will be used to encode a cookie's value. Since
131
- * value of a cookie has a limited character set (and must be a simple
132
- * string), this function can be used to encode a value into a string suited
133
- * for a cookie's value.
134
- *
135
- * The default function is the global `encodeURIComponent`, which will
136
- * encode a JavaScript string into UTF-8 byte sequences and then URL-encode
137
- * any that fall outside of the cookie range.
138
- */
139
- encode?(value: string): string;
140
- /**
141
- * Specifies the `Date` object to be the value for the {@link https://tools.ietf.org/html/rfc6265#section-5.2.1|`Expires` `Set-Cookie` attribute}. By default,
142
- * no expiration is set, and most clients will consider this a "non-persistent cookie" and will delete
143
- * it on a condition like exiting a web browser application.
144
- *
145
- * *Note* the {@link https://tools.ietf.org/html/rfc6265#section-5.3|cookie storage model specification}
146
- * states that if both `expires` and `maxAge` are set, then `maxAge` takes precedence, but it is
147
- * possible not all clients by obey this, so if both are set, they should
148
- * point to the same date and time.
149
- */
150
- expires?: Date;
151
- /**
152
- * Specifies the boolean value for the {@link https://tools.ietf.org/html/rfc6265#section-5.2.6|`HttpOnly` `Set-Cookie` attribute}.
153
- * When truthy, the `HttpOnly` attribute is set, otherwise it is not. By
154
- * default, the `HttpOnly` attribute is not set.
155
- *
156
- * *Note* be careful when setting this to true, as compliant clients will
157
- * not allow client-side JavaScript to see the cookie in `document.cookie`.
158
- */
159
- httpOnly?: boolean;
160
- /**
161
- * Specifies the number (in seconds) to be the value for the `Max-Age`
162
- * `Set-Cookie` attribute. The given number will be converted to an integer
163
- * by rounding down. By default, no maximum age is set.
164
- *
165
- * *Note* the {@link https://tools.ietf.org/html/rfc6265#section-5.3|cookie storage model specification}
166
- * states that if both `expires` and `maxAge` are set, then `maxAge` takes precedence, but it is
167
- * possible not all clients by obey this, so if both are set, they should
168
- * point to the same date and time.
169
- */
170
- maxAge?: number;
171
- /**
172
- * Specifies the value for the {@link https://tools.ietf.org/html/rfc6265#section-5.2.4|`Path` `Set-Cookie` attribute}.
173
- * By default, the path is considered the "default path".
174
- */
175
- path?: string;
176
- /**
177
- * Specifies the boolean or string to be the value for the {@link https://tools.ietf.org/html/draft-ietf-httpbis-rfc6265bis-03#section-4.1.2.7|`SameSite` `Set-Cookie` attribute}.
178
- *
179
- * - `true` will set the `SameSite` attribute to `Strict` for strict same
180
- * site enforcement.
181
- * - `false` will not set the `SameSite` attribute.
182
- * - `'lax'` will set the `SameSite` attribute to Lax for lax same site
183
- * enforcement.
184
- * - `'strict'` will set the `SameSite` attribute to Strict for strict same
185
- * site enforcement.
186
- * - `'none'` will set the SameSite attribute to None for an explicit
187
- * cross-site cookie.
188
- *
189
- * More information about the different enforcement levels can be found in {@link https://tools.ietf.org/html/draft-ietf-httpbis-rfc6265bis-03#section-4.1.2.7|the specification}.
190
- *
191
- * *note* This is an attribute that has not yet been fully standardized, and may change in the future. This also means many clients may ignore this attribute until they understand it.
192
- */
193
- sameSite?: true | false | 'lax' | 'strict' | 'none';
194
- /**
195
- * Specifies the boolean value for the {@link https://tools.ietf.org/html/rfc6265#section-5.2.5|`Secure` `Set-Cookie` attribute}. When truthy, the
196
- * `Secure` attribute is set, otherwise it is not. By default, the `Secure` attribute is not set.
197
- *
198
- * *Note* be careful when setting this to `true`, as compliant clients will
199
- * not send the cookie back to the server in the future if the browser does
200
- * not have an HTTPS connection.
201
- */
202
- secure?: boolean;
203
- }
204
-
205
162
  /**
206
163
  * Parse the request to get HTTP Cookie header string and returning an object of all cookie name-value pairs.
207
- * @param req {IncomingMessage} An IncomingMessage object created by [http.Server](https://nodejs.org/api/http.html#http_class_http_server)
164
+ * @param event {CompatibilityEvent} H3 event or req passed by h3 handler
208
165
  * @returns Object of cookie name-value pairs
209
166
  * ```ts
210
167
  * const cookies = useCookies(req)
211
168
  * ```
212
169
  */
213
- declare function useCookies(req: IncomingMessage): Record<string, string>;
170
+ declare function useCookies(event: CompatibilityEvent): Record<string, string>;
214
171
  /**
215
172
  * Get a cookie value by name.
216
- * @param req {IncomingMessage} An IncomingMessage object created by [http.Server](https://nodejs.org/api/http.html#http_class_http_server)
173
+ * @param event {CompatibilityEvent} H3 event or req passed by h3 handler
217
174
  * @param name Name of the cookie to get
218
175
  * @returns {*} Value of the cookie (String or undefined)
219
176
  * ```ts
220
177
  * const authorization = useCookie(request, 'Authorization')
221
178
  * ```
222
179
  */
223
- declare function useCookie(req: IncomingMessage, name: string): string | undefined;
180
+ declare function useCookie(event: CompatibilityEvent, name: string): string | undefined;
224
181
  /**
225
182
  * Set a cookie value by name.
226
- * @param res {ServerResponse} A ServerResponse object created by [http.Server](https://nodejs.org/api/http.html#http_class_http_server)
183
+ * @param event {CompatibilityEvent} H3 event or res passed by h3 handler
227
184
  * @param name Name of the cookie to set
228
185
  * @param value Value of the cookie to set
229
186
  * @param serializeOptions {CookieSerializeOptions} Options for serializing the cookie
@@ -231,30 +188,38 @@ declare function useCookie(req: IncomingMessage, name: string): string | undefin
231
188
  * setCookie(res, 'Authorization', '1234567')
232
189
  * ```
233
190
  */
234
- declare function setCookie(res: ServerResponse, name: string, value: string, serializeOptions?: CookieSerializeOptions): void;
235
-
236
- declare type HTTPMethod = 'GET' | 'HEAD' | 'POST' | 'PUT' | 'DELETE' | 'CONNECT' | 'OPTIONS' | 'TRACE';
191
+ declare function setCookie(event: CompatibilityEvent, name: string, value: string, serializeOptions?: CookieSerializeOptions): void;
192
+ /**
193
+ * Set a cookie value by name.
194
+ * @param event {CompatibilityEvent} H3 event or res passed by h3 handler
195
+ * @param name Name of the cookie to delete
196
+ * @param serializeOptions {CookieSerializeOptions} Cookie options
197
+ * ```ts
198
+ * deleteCookie(res, 'SessionId')
199
+ * ```
200
+ */
201
+ declare function deleteCookie(event: CompatibilityEvent, name: string, serializeOptions?: CookieSerializeOptions): void;
237
202
 
238
- declare function useQuery(req: IncomingMessage): ufo.QueryObject;
239
- declare function useMethod(req: IncomingMessage, defaultMethod?: HTTPMethod): HTTPMethod;
240
- declare function isMethod(req: IncomingMessage, expected: HTTPMethod | HTTPMethod[], allowHead?: boolean): boolean;
241
- declare function assertMethod(req: IncomingMessage, expected: HTTPMethod | HTTPMethod[], allowHead?: boolean): void;
203
+ declare function useQuery(event: CompatibilityEvent): ufo.QueryObject;
204
+ declare function useMethod(event: CompatibilityEvent, defaultMethod?: HTTPMethod): HTTPMethod;
205
+ declare function isMethod(event: CompatibilityEvent, expected: HTTPMethod | HTTPMethod[], allowHead?: boolean): boolean;
206
+ declare function assertMethod(event: CompatibilityEvent, expected: HTTPMethod | HTTPMethod[], allowHead?: boolean): void;
242
207
 
243
- declare function send(res: ServerResponse, data: any, type?: string): Promise<unknown>;
244
- declare function defaultContentType(res: ServerResponse, type?: string): void;
245
- declare function sendRedirect(res: ServerResponse, location: string, code?: number): Promise<unknown>;
246
- declare function appendHeader(res: ServerResponse, name: string, value: string): void;
208
+ declare function send(event: CompatibilityEvent, data: any, type?: string): Promise<void>;
209
+ declare function defaultContentType(event: CompatibilityEvent, type?: string): void;
210
+ declare function sendRedirect(event: CompatibilityEvent, location: string, code?: number): Promise<void>;
211
+ declare function appendHeader(event: CompatibilityEvent, name: string, value: string): void;
212
+ declare function isStream(data: any): any;
213
+ declare function sendStream(event: CompatibilityEvent, data: any): Promise<void>;
247
214
 
248
215
  declare type RouterMethod = Lowercase<HTTPMethod>;
249
- declare type HandleWithParams = Handle<any, {
250
- params: Record<string, string>;
251
- }>;
252
- declare type AddWithMethod = (path: string, handle: HandleWithParams) => Router;
253
- declare type AddRouteShortcuts = Record<Lowercase<HTTPMethod>, AddWithMethod>;
216
+ declare type RouterUse = (path: string, handler: CompatibilityEventHandler, method?: RouterMethod) => Router;
217
+ declare type AddRouteShortcuts = Record<RouterMethod, RouterUse>;
254
218
  interface Router extends AddRouteShortcuts {
255
- add: (path: string, handle: HandleWithParams, method?: RouterMethod | 'all') => Router;
256
- handle: Handle;
219
+ add: RouterUse;
220
+ use: RouterUse;
221
+ handler: EventHandler;
257
222
  }
258
223
  declare function createRouter(): Router;
259
224
 
260
- export { AddRouteShortcuts, AddWithMethod, App, AppOptions, AppUse, H3Error, Handle, HandleWithParams, InputLayer, InputStack, Layer, LazyHandle, MIMES, Matcher, Middleware, PHandle, Router, RouterMethod, Stack, appendHeader, assertMethod, callHandle, createApp, createError, createHandle, createRouter, defaultContentType, defineHandle, defineMiddleware, isMethod, lazyHandle, promisifyHandle, send, sendError, sendRedirect, setCookie, use, useBase, useBody, useCookie, useCookies, useMethod, useQuery, useRawBody };
225
+ export { AddRouteShortcuts, App, AppOptions, AppUse, CompatibilityEvent, CompatibilityEventHandler, EventHandler, H3Error, H3Event, H3Response, InputLayer, InputStack, JSONValue, Layer, MIMES, Matcher, NodeHandler, Router, RouterMethod, RouterUse, Stack, _JSONValue, appendHeader, assertMethod, callHandler, createApp, createAppEventHandler, createError, createEvent, createRouter, defaultContentType, defineEventHandler, defineHandle, defineHandler, defineLazyEventHandler, defineLazyHandler, defineMiddleware, deleteCookie, isEvent, isEventHandler, isMethod, isStream, lazyHandle, promisifyHandle, promisifyHandler, send, sendError, sendRedirect, sendStream, setCookie, toEventHandler, use, useBase, useBody, useCookie, useCookies, useMethod, useQuery, useRawBody };