@eggjs/koa 3.1.0-beta.9 → 3.1.2-beta.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.
@@ -2,10 +2,9 @@ import { Response } from "./response.js";
2
2
  import { Request } from "./request.js";
3
3
  import { AnyProto, CustomError } from "./types.js";
4
4
  import { Context } from "./context.js";
5
- import util from "node:util";
6
5
  import Emitter from "node:events";
7
6
  import http, { IncomingMessage, ServerResponse } from "node:http";
8
- import * as http_errors0 from "http-errors";
7
+ import { HttpError } from "http-errors";
9
8
  import { AsyncLocalStorage } from "node:async_hooks";
10
9
 
11
10
  //#region src/application.d.ts
@@ -16,16 +15,16 @@ type MiddlewareFunc<T extends Context = Context> = _MiddlewareFunc<T> & {
16
15
  _name?: string;
17
16
  };
18
17
  /**
19
- * Expose `Application` class.
20
- * Inherits from `Emitter.prototype`.
21
- */
18
+ * Expose `Application` class.
19
+ * Inherits from `Emitter.prototype`.
20
+ */
22
21
  declare class Application extends Emitter {
23
22
  [key: symbol]: unknown;
24
23
  /**
25
- * Make HttpError available to consumers of the library so that consumers don't
26
- * have a direct dependency upon `http-errors`
27
- */
28
- static HttpError: http_errors0.HttpErrorConstructor<number>;
24
+ * Make HttpError available to consumers of the library so that consumers don't
25
+ * have a direct dependency upon `http-errors`
26
+ */
27
+ static HttpError: typeof HttpError;
29
28
  protected _proxy: boolean;
30
29
  protected _env: string;
31
30
  subdomainOffset: number;
@@ -42,16 +41,16 @@ declare class Application extends Emitter {
42
41
  ResponseClass: ProtoImplClass<Response>;
43
42
  response: AnyProto;
44
43
  /**
45
- * Initialize a new `Application`.
46
- *
47
- * @param {object} [options] Application options
48
- * @param {string} [options.env] Environment, default is `development`
49
- * @param {string[]} [options.keys] Signed cookie keys
50
- * @param {boolean} [options.proxy] Trust proxy headers
51
- * @param {number} [options.subdomainOffset] Subdomain offset
52
- * @param {string} [options.proxyIpHeader] Proxy IP header, defaults to X-Forwarded-For
53
- * @param {number} [options.maxIpsCount] Max IPs read from proxy IP header, default to 0 (means infinity)
54
- */
44
+ * Initialize a new `Application`.
45
+ *
46
+ * @param {object} [options] Application options
47
+ * @param {string} [options.env] Environment, default is `development`
48
+ * @param {string[]} [options.keys] Signed cookie keys
49
+ * @param {boolean} [options.proxy] Trust proxy headers
50
+ * @param {number} [options.subdomainOffset] Subdomain offset
51
+ * @param {string} [options.proxyIpHeader] Proxy IP header, defaults to X-Forwarded-For
52
+ * @param {number} [options.maxIpsCount] Max IPs read from proxy IP header, default to 0 (means infinity)
53
+ */
55
54
  constructor(options?: {
56
55
  proxy?: boolean;
57
56
  subdomainOffset?: number;
@@ -67,65 +66,52 @@ declare class Application extends Emitter {
67
66
  get proxy(): boolean;
68
67
  set proxy(value: boolean);
69
68
  /**
70
- * Shorthand for:
71
- *
72
- * http.createServer(app.callback()).listen(...)
73
- */
74
- listen(...args: any[]): http.Server<typeof http.IncomingMessage, typeof http.ServerResponse>;
69
+ * Shorthand for:
70
+ *
71
+ * http.createServer(app.callback()).listen(...)
72
+ */
73
+ listen(...args: any[]): http.Server;
75
74
  /**
76
- * Return JSON representation.
77
- * We only bother showing settings.
78
- */
79
- toJSON(): {
80
- subdomainOffset: number;
81
- proxy: boolean;
82
- env: string;
83
- };
75
+ * Return JSON representation.
76
+ * We only bother showing settings.
77
+ */
78
+ toJSON(): object;
84
79
  /**
85
- * Inspect implementation.
86
- */
87
- inspect(): {
88
- subdomainOffset: number;
89
- proxy: boolean;
90
- env: string;
91
- };
92
- [util.inspect.custom](): {
93
- subdomainOffset: number;
94
- proxy: boolean;
95
- env: string;
96
- };
80
+ * Inspect implementation.
81
+ */
82
+ inspect(): object;
97
83
  /**
98
- * Use the given middleware `fn`.
99
- */
84
+ * Use the given middleware `fn`.
85
+ */
100
86
  use<T extends Context = Context>(fn: MiddlewareFunc<T>): this;
101
87
  /**
102
- * Return a request handler callback
103
- * for node's native http server.
104
- */
105
- callback(): (req: IncomingMessage, res: ServerResponse) => Promise<void | http.ServerResponse<http.IncomingMessage>>;
88
+ * Return a request handler callback
89
+ * for node's native http server.
90
+ */
91
+ callback(): (req: IncomingMessage, res: ServerResponse) => Promise<void>;
106
92
  /**
107
- * return current context from async local storage
108
- */
93
+ * return current context from async local storage
94
+ */
109
95
  get currentContext(): Context | undefined;
110
96
  /**
111
- * Handle request in callback.
112
- * @private
113
- */
114
- protected handleRequest(ctx: Context, fnMiddleware: (ctx: Context) => Promise<void>): Promise<void | http.ServerResponse<http.IncomingMessage>>;
97
+ * Handle request in callback.
98
+ * @private
99
+ */
100
+ protected handleRequest(ctx: Context, fnMiddleware: (ctx: Context) => Promise<void>): Promise<void>;
115
101
  /**
116
- * Initialize a new context.
117
- * @private
118
- */
102
+ * Initialize a new context.
103
+ * @private
104
+ */
119
105
  createContext(req: IncomingMessage, res: ServerResponse): Context;
120
106
  /**
121
- * Default error handler.
122
- * @private
123
- */
107
+ * Default error handler.
108
+ * @private
109
+ */
124
110
  protected onerror(err: CustomError): void;
125
111
  /**
126
- * Response helper.
127
- */
128
- protected _respond(ctx: Context): http.ServerResponse<http.IncomingMessage> | undefined;
112
+ * Response helper.
113
+ */
114
+ protected _respond(ctx: Context): void;
129
115
  }
130
116
  //#endregion
131
117
  export { Application, MiddlewareFunc, Next, ProtoImplClass };
@@ -1,16 +1,16 @@
1
1
  import { Context } from "./context.js";
2
2
  import { Request } from "./request.js";
3
3
  import { Response } from "./response.js";
4
- import util, { debuglog } from "node:util";
5
4
  import Emitter from "node:events";
6
- import Stream from "node:stream";
7
5
  import http from "node:http";
6
+ import Stream from "node:stream";
7
+ import util, { debuglog } from "node:util";
8
8
  import { getAsyncLocalStorage } from "gals";
9
+ import { HttpError } from "http-errors";
9
10
  import { isGeneratorFunction } from "is-type-of";
11
+ import compose from "koa-compose";
10
12
  import onFinished from "on-finished";
11
13
  import statuses from "statuses";
12
- import compose from "koa-compose";
13
- import { HttpError } from "http-errors";
14
14
 
15
15
  //#region src/application.ts
16
16
  const debug = debuglog("egg/koa/application");
@@ -68,6 +68,7 @@ var Application = class extends Emitter {
68
68
  this.request = this.RequestClass.prototype;
69
69
  this.ResponseClass = class ApplicationResponse extends Response {};
70
70
  this.response = this.ResponseClass.prototype;
71
+ this[util.inspect.custom] = this.inspect.bind(this);
71
72
  }
72
73
  get keys() {
73
74
  return this._keys;
@@ -113,9 +114,6 @@ var Application = class extends Emitter {
113
114
  inspect() {
114
115
  return this.toJSON();
115
116
  }
116
- [util.inspect.custom]() {
117
- return this.inspect();
118
- }
119
117
  /**
120
118
  * Use the given middleware `fn`.
121
119
  */
@@ -197,20 +195,23 @@ var Application = class extends Emitter {
197
195
  const code = ctx.status;
198
196
  if (statuses.empty[code]) {
199
197
  ctx.body = null;
200
- return res.end();
198
+ res.end();
199
+ return;
201
200
  }
202
201
  if (ctx.method === "HEAD") {
203
202
  if (!res.headersSent && !ctx.response.has("Content-Length")) {
204
203
  const { length } = ctx.response;
205
204
  if (Number.isInteger(length)) ctx.length = length;
206
205
  }
207
- return res.end();
206
+ res.end();
207
+ return;
208
208
  }
209
209
  if (body === null || body === void 0) {
210
210
  if (ctx.response._explicitNullBody) {
211
211
  ctx.response.remove("Content-Type");
212
212
  ctx.response.remove("Transfer-Encoding");
213
- return res.end();
213
+ res.end();
214
+ return;
214
215
  }
215
216
  if (ctx.req.httpVersionMajor >= 2) body = String(code);
216
217
  else body = ctx.message || String(code);
@@ -218,11 +219,21 @@ var Application = class extends Emitter {
218
219
  ctx.type = "text";
219
220
  ctx.length = Buffer.byteLength(body);
220
221
  }
221
- return res.end(body);
222
+ res.end(body);
223
+ return;
224
+ }
225
+ if (Buffer.isBuffer(body)) {
226
+ res.end(body);
227
+ return;
228
+ }
229
+ if (typeof body === "string") {
230
+ res.end(body);
231
+ return;
232
+ }
233
+ if (body instanceof Stream) {
234
+ body.pipe(res);
235
+ return;
222
236
  }
223
- if (Buffer.isBuffer(body)) return res.end(body);
224
- if (typeof body === "string") return res.end(body);
225
- if (body instanceof Stream) return body.pipe(res);
226
237
  body = JSON.stringify(body);
227
238
  if (!res.headersSent) ctx.length = Buffer.byteLength(body);
228
239
  res.end(body);
package/dist/context.d.ts CHANGED
@@ -2,12 +2,10 @@ import { Response } from "./response.js";
2
2
  import { Request, RequestSocket } from "./request.js";
3
3
  import { AnyProto, CustomError } from "./types.js";
4
4
  import { Application } from "./application.js";
5
- import util from "node:util";
6
5
  import { IncomingMessage, ServerResponse } from "node:http";
7
- import Cookies from "cookies";
6
+ import { Cookies } from "@eggjs/cookies";
8
7
  import { ParsedUrlQuery } from "node:querystring";
9
8
  import { Accepts } from "accepts";
10
- import * as http11 from "http";
11
9
 
12
10
  //#region src/context.d.ts
13
11
  declare class Context {
@@ -22,113 +20,49 @@ declare class Context {
22
20
  respond?: boolean;
23
21
  constructor(app: Application, req: IncomingMessage, res: ServerResponse);
24
22
  /**
25
- * util.inspect() implementation, which
26
- * just returns the JSON output.
27
- */
28
- inspect(): {
29
- request: {
30
- method: string;
31
- url: string;
32
- header: http11.IncomingHttpHeaders;
33
- };
34
- response: {
35
- status: number;
36
- message: string;
37
- header: http11.OutgoingHttpHeaders;
38
- };
39
- app: {
40
- subdomainOffset: number;
41
- proxy: boolean;
42
- env: string;
43
- };
44
- originalUrl: string;
45
- req: string;
46
- res: string;
47
- socket: string;
48
- };
23
+ * util.inspect() implementation, which
24
+ * just returns the JSON output.
25
+ */
26
+ inspect(): object;
49
27
  /**
50
- * Custom inspection implementation for newer Node.js versions.
51
- */
52
- [util.inspect.custom](): {
53
- request: {
54
- method: string;
55
- url: string;
56
- header: http11.IncomingHttpHeaders;
57
- };
58
- response: {
59
- status: number;
60
- message: string;
61
- header: http11.OutgoingHttpHeaders;
62
- };
63
- app: {
64
- subdomainOffset: number;
65
- proxy: boolean;
66
- env: string;
67
- };
68
- originalUrl: string;
69
- req: string;
70
- res: string;
71
- socket: string;
72
- };
28
+ * Return JSON representation.
29
+ *
30
+ * Here we explicitly invoke .toJSON() on each
31
+ * object, as iteration will otherwise fail due
32
+ * to the getters and cause utilities such as
33
+ * clone() to fail.
34
+ */
35
+ toJSON(): object;
73
36
  /**
74
- * Return JSON representation.
75
- *
76
- * Here we explicitly invoke .toJSON() on each
77
- * object, as iteration will otherwise fail due
78
- * to the getters and cause utilities such as
79
- * clone() to fail.
80
- */
81
- toJSON(): {
82
- request: {
83
- method: string;
84
- url: string;
85
- header: http11.IncomingHttpHeaders;
86
- };
87
- response: {
88
- status: number;
89
- message: string;
90
- header: http11.OutgoingHttpHeaders;
91
- };
92
- app: {
93
- subdomainOffset: number;
94
- proxy: boolean;
95
- env: string;
96
- };
97
- originalUrl: string;
98
- req: string;
99
- res: string;
100
- socket: string;
101
- };
102
- /**
103
- * Similar to .throw(), adds assertion.
104
- *
105
- * ```ts
106
- * this.assert(this.user, 401, 'Please login!');
107
- * ```
108
- */
37
+ * Similar to .throw(), adds assertion.
38
+ *
39
+ * ```ts
40
+ * this.assert(this.user, 401, 'Please login!');
41
+ * ```
42
+ */
109
43
  assert(value: unknown, status?: number, errorProps?: Record<string, unknown>): void;
110
44
  assert(value: unknown, status?: number, errorMessage?: string, errorProps?: Record<string, unknown>): void;
111
45
  /**
112
- * Throw an error with `status` (default 500) and
113
- * `msg`. Note that these are user-level
114
- * errors, and the message may be exposed to the client.
115
- *
116
- * this.throw(403)
117
- * this.throw(400, 'name required')
118
- * this.throw('something exploded')
119
- * this.throw(new Error('invalid'))
120
- * this.throw(400, new Error('invalid'))
121
- * this.throw(400, new Error('invalid'), { foo: 'bar' })
122
- * this.throw(new Error('invalid'), { foo: 'bar' })
123
- *
124
- * See: https://github.com/jshttp/http-errors
125
- *
126
- * Note: `status` should only be passed as the first parameter.
127
- *
128
- * @param {String|Number|Error} status error, msg or status
129
- * @param {String|Number|Error|Object} [error] error, msg, status or errorProps
130
- * @param {Object} [errorProps] error object properties
131
- */
46
+ * Throw an error with `status` (default 500) and
47
+ * `msg`. Note that these are user-level
48
+ * errors, and the message may be exposed to the client.
49
+ *
50
+ * this.throw(403)
51
+ * this.throw(400, 'name required')
52
+ * this.throw('something exploded')
53
+ * this.throw(new Error('invalid'))
54
+ * this.throw(400, new Error('invalid'))
55
+ * this.throw(400, new Error('invalid'), { foo: 'bar' })
56
+ * this.throw(new Error('invalid'), { foo: 'bar' })
57
+ *
58
+ * See: https://github.com/jshttp/http-errors
59
+ *
60
+ * Note: `status` should only be passed as the first parameter.
61
+ *
62
+ * @param {String|Number|Error} status error, msg or status
63
+ * @param {String|Number|Error|Object} [error] error, msg, status or errorProps
64
+ * @param {Object} [errorProps] error object properties
65
+ */
132
66
  throw(status: number): void;
133
67
  throw(status: number, errorProps: object): void;
134
68
  throw(status: number, errorMessage: string): void;
@@ -144,17 +78,17 @@ declare class Context {
144
78
  throw(error: Error, status: number): void;
145
79
  throw(error: Error, status: number, errorProps: object): void;
146
80
  /**
147
- * Default error handling.
148
- * @private
149
- */
81
+ * Default error handling.
82
+ * @private
83
+ */
150
84
  onerror(err: CustomError): void;
151
85
  protected _cookies: Cookies | undefined;
152
86
  get cookies(): Cookies;
153
87
  set cookies(cookies: Cookies);
154
88
  get state(): Record<string, any>;
155
89
  /**
156
- * Request delegation.
157
- */
90
+ * Request delegation.
91
+ */
158
92
  acceptsLanguages(): string[];
159
93
  acceptsLanguages(languages: string[]): string | false;
160
94
  acceptsLanguages(...languages: string[]): string | false;
@@ -191,24 +125,24 @@ declare class Context {
191
125
  get host(): string;
192
126
  get hostname(): string;
193
127
  get URL(): URL;
194
- get header(): http11.IncomingHttpHeaders;
195
- get headers(): http11.IncomingHttpHeaders;
128
+ get header(): IncomingMessage["headers"];
129
+ get headers(): IncomingMessage["headers"];
196
130
  get secure(): boolean;
197
131
  get stale(): boolean;
198
132
  get fresh(): boolean;
199
133
  get ips(): string[];
200
134
  get ip(): string;
201
135
  /**
202
- * Response delegation.
203
- */
204
- attachment(...args: Parameters<Response['attachment']>): void;
205
- redirect(...args: Parameters<Response['redirect']>): void;
206
- remove(...args: Parameters<Response['remove']>): void;
207
- vary(...args: Parameters<Response['vary']>): void;
208
- has(...args: Parameters<Response['has']>): boolean;
209
- set(...args: Parameters<Response['set']>): void;
210
- append(...args: Parameters<Response['append']>): void;
211
- flushHeaders(...args: Parameters<Response['flushHeaders']>): void;
136
+ * Response delegation.
137
+ */
138
+ attachment(...args: Parameters<Response["attachment"]>): void;
139
+ redirect(...args: Parameters<Response["redirect"]>): void;
140
+ remove(...args: Parameters<Response["remove"]>): void;
141
+ vary(...args: Parameters<Response["vary"]>): void;
142
+ has(...args: Parameters<Response["has"]>): boolean;
143
+ set(...args: Parameters<Response["set"]>): void;
144
+ append(...args: Parameters<Response["append"]>): void;
145
+ flushHeaders(...args: Parameters<Response["flushHeaders"]>): void;
212
146
  get status(): number;
213
147
  set status(status: number);
214
148
  get message(): string;
package/dist/context.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import util from "node:util";
2
- import statuses from "statuses";
3
2
  import createError from "http-errors";
4
- import Cookies from "cookies";
3
+ import statuses from "statuses";
4
+ import { Cookies } from "@eggjs/cookies";
5
5
 
6
6
  //#region src/context.ts
7
7
  var Context = class {
@@ -22,6 +22,7 @@ var Context = class {
22
22
  this.request.response = this.response;
23
23
  this.response.request = this.request;
24
24
  this.originalUrl = req.url ?? "/";
25
+ this[util.inspect.custom] = this.inspect.bind(this);
25
26
  }
26
27
  /**
27
28
  * util.inspect() implementation, which
@@ -31,12 +32,6 @@ var Context = class {
31
32
  return this.toJSON();
32
33
  }
33
34
  /**
34
- * Custom inspection implementation for newer Node.js versions.
35
- */
36
- [util.inspect.custom]() {
37
- return this.inspect();
38
- }
39
- /**
40
35
  * Return JSON representation.
41
36
  *
42
37
  * Here we explicitly invoke .toJSON() on each
@@ -103,10 +98,7 @@ var Context = class {
103
98
  }
104
99
  _cookies;
105
100
  get cookies() {
106
- if (!this._cookies) this._cookies = new Cookies(this.req, this.res, {
107
- keys: this.app.keys,
108
- secure: this.request.secure
109
- });
101
+ if (!this._cookies) this._cookies = new Cookies(this, this.app.keys ?? [], { secure: this.request.secure });
110
102
  return this._cookies;
111
103
  }
112
104
  set cookies(cookies) {