@eggjs/koa 3.1.0-beta.19 → 3.1.0-beta.20

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/request.js DELETED
@@ -1,459 +0,0 @@
1
- import util from "node:util";
2
- import net from "node:net";
3
- import { format } from "node:url";
4
- import qs from "node:querystring";
5
- import accepts from "accepts";
6
- import contentType from "content-type";
7
- import parse from "parseurl";
8
- import typeis from "type-is";
9
- import fresh from "fresh";
10
-
11
- //#region src/request.ts
12
- var Request = class {
13
- app;
14
- req;
15
- res;
16
- ctx;
17
- response;
18
- originalUrl;
19
- constructor(app, ctx, req, res) {
20
- this.app = app;
21
- this.req = req;
22
- this.res = res;
23
- this.ctx = ctx;
24
- this.originalUrl = req.url ?? "/";
25
- }
26
- /**
27
- * Return request header.
28
- */
29
- get header() {
30
- return this.req.headers;
31
- }
32
- /**
33
- * Set request header.
34
- */
35
- set header(val) {
36
- this.req.headers = val;
37
- }
38
- /**
39
- * Return request header, alias as request.header
40
- */
41
- get headers() {
42
- return this.req.headers;
43
- }
44
- /**
45
- * Set request header, alias as request.header
46
- */
47
- set headers(val) {
48
- this.req.headers = val;
49
- }
50
- /**
51
- * Get request URL.
52
- */
53
- get url() {
54
- return this.req.url ?? "/";
55
- }
56
- /**
57
- * Set request URL.
58
- */
59
- set url(val) {
60
- this.req.url = val;
61
- }
62
- /**
63
- * Get origin of URL.
64
- */
65
- get origin() {
66
- return `${this.protocol}://${this.host}`;
67
- }
68
- /**
69
- * Get full request URL.
70
- */
71
- get href() {
72
- if (/^https?:\/\//i.test(this.originalUrl)) return this.originalUrl;
73
- return this.origin + this.originalUrl;
74
- }
75
- /**
76
- * Get request method.
77
- */
78
- get method() {
79
- return this.req.method ?? "GET";
80
- }
81
- /**
82
- * Set request method.
83
- */
84
- set method(val) {
85
- this.req.method = val;
86
- }
87
- /**
88
- * Get request pathname.
89
- */
90
- get path() {
91
- return parse(this.req)?.pathname ?? "";
92
- }
93
- /**
94
- * Set pathname, retaining the query string when present.
95
- */
96
- set path(pathname) {
97
- const url = parse(this.req);
98
- if (!url) return;
99
- if (url.pathname === pathname) return;
100
- url.pathname = pathname;
101
- url.path = null;
102
- this.url = format(url);
103
- }
104
- _parsedUrlQueryCache;
105
- /**
106
- * Get parsed query string.
107
- */
108
- get query() {
109
- const str = this.querystring;
110
- if (!this._parsedUrlQueryCache) this._parsedUrlQueryCache = {};
111
- let parsedUrlQuery = this._parsedUrlQueryCache[str];
112
- if (!parsedUrlQuery) {
113
- parsedUrlQuery = qs.parse(str);
114
- this._parsedUrlQueryCache[str] = parsedUrlQuery;
115
- }
116
- return parsedUrlQuery;
117
- }
118
- /**
119
- * Set query string as an object.
120
- */
121
- set query(obj) {
122
- this.querystring = qs.stringify(obj);
123
- }
124
- /**
125
- * Get query string.
126
- */
127
- get querystring() {
128
- if (!this.req) return "";
129
- return parse(this.req)?.query ?? "";
130
- }
131
- /**
132
- * Set query string.
133
- */
134
- set querystring(str) {
135
- const url = parse(this.req);
136
- if (!url) return;
137
- if (url.search === `?${str}`) return;
138
- url.search = str;
139
- url.path = null;
140
- this.url = format(url);
141
- }
142
- /**
143
- * Get the search string. Same as the query string
144
- * except it includes the leading ?.
145
- */
146
- get search() {
147
- const querystring = this.querystring;
148
- if (!querystring) return "";
149
- return `?${querystring}`;
150
- }
151
- /**
152
- * Set the search string. Same as
153
- * request.querystring= but included for ubiquity.
154
- */
155
- set search(str) {
156
- this.querystring = str;
157
- }
158
- /**
159
- * Parse the "Host" header field host
160
- * and support X-Forwarded-Host when a
161
- * proxy is enabled.
162
- * return `hostname:port` format
163
- */
164
- get host() {
165
- let host = this.app.proxy ? this.get("X-Forwarded-Host") : "";
166
- if (host) host = splitCommaSeparatedValues(host, 1)[0];
167
- if (!host) {
168
- if (this.req.httpVersionMajor >= 2) host = this.get(":authority");
169
- if (!host) host = this.get("Host");
170
- }
171
- return host;
172
- }
173
- /**
174
- * Parse the "Host" header field hostname
175
- * and support X-Forwarded-Host when a
176
- * proxy is enabled.
177
- */
178
- get hostname() {
179
- const host = this.host;
180
- if (!host) return "";
181
- if (host[0] === "[") return this.URL.hostname || "";
182
- return host.split(":", 1)[0];
183
- }
184
- _memoizedURL;
185
- /**
186
- * Get WHATWG parsed URL.
187
- * Lazily memoized.
188
- */
189
- get URL() {
190
- if (!this._memoizedURL) {
191
- const originalUrl = this.originalUrl || "";
192
- try {
193
- this._memoizedURL = new URL(`${this.origin}${originalUrl}`);
194
- } catch {
195
- this._memoizedURL = Object.create(null);
196
- }
197
- }
198
- return this._memoizedURL;
199
- }
200
- /**
201
- * Check if the request is fresh, aka
202
- * Last-Modified and/or the ETag
203
- * still match.
204
- */
205
- get fresh() {
206
- const method = this.method;
207
- const status = this.response.status;
208
- if (method !== "GET" && method !== "HEAD") return false;
209
- if (status >= 200 && status < 300 || status === 304) return fresh(this.header, this.response.header);
210
- return false;
211
- }
212
- /**
213
- * Check if the request is stale, aka
214
- * "Last-Modified" and / or the "ETag" for the
215
- * resource has changed.
216
- */
217
- get stale() {
218
- return !this.fresh;
219
- }
220
- /**
221
- * Check if the request is idempotent.
222
- */
223
- get idempotent() {
224
- return [
225
- "GET",
226
- "HEAD",
227
- "PUT",
228
- "DELETE",
229
- "OPTIONS",
230
- "TRACE"
231
- ].includes(this.method);
232
- }
233
- /**
234
- * Return the request socket.
235
- */
236
- get socket() {
237
- return this.req.socket;
238
- }
239
- /**
240
- * Get the charset when present or undefined.
241
- */
242
- get charset() {
243
- try {
244
- const { parameters } = contentType.parse(this.req);
245
- return parameters.charset || "";
246
- } catch {
247
- return "";
248
- }
249
- }
250
- /**
251
- * Return parsed Content-Length when present.
252
- */
253
- get length() {
254
- const len = this.get("Content-Length");
255
- if (len === "") return;
256
- return Number.parseInt(len);
257
- }
258
- /**
259
- * Return the protocol string "http" or "https"
260
- * when requested with TLS. When the proxy setting
261
- * is enabled the "X-Forwarded-Proto" header
262
- * field will be trusted. If you're running behind
263
- * a reverse proxy that supplies https for you this
264
- * may be enabled.
265
- */
266
- get protocol() {
267
- if (this.socket.encrypted) return "https";
268
- if (!this.app.proxy) return "http";
269
- let proto = this.get("X-Forwarded-Proto");
270
- if (proto) proto = splitCommaSeparatedValues(proto, 1)[0];
271
- return proto || "http";
272
- }
273
- /**
274
- * Shorthand for:
275
- *
276
- * this.protocol == 'https'
277
- */
278
- get secure() {
279
- return this.protocol === "https";
280
- }
281
- /**
282
- * When `app.proxy` is `true`, parse
283
- * the "X-Forwarded-For" ip address list.
284
- *
285
- * For example if the value was "client, proxy1, proxy2"
286
- * you would receive the array `["client", "proxy1", "proxy2"]`
287
- * where "proxy2" is the furthest down-stream.
288
- */
289
- get ips() {
290
- const proxy = this.app.proxy;
291
- const val = this.get(this.app.proxyIpHeader);
292
- let ips = proxy && val ? splitCommaSeparatedValues(val) : [];
293
- if (this.app.maxIpsCount > 0) ips = ips.slice(-this.app.maxIpsCount);
294
- return ips;
295
- }
296
- _ip;
297
- /**
298
- * Return request's remote address
299
- * When `app.proxy` is `true`, parse
300
- * the "X-Forwarded-For" ip address list and return the first one
301
- */
302
- get ip() {
303
- if (!this._ip) this._ip = this.ips[0] || this.socket.remoteAddress || "";
304
- return this._ip;
305
- }
306
- set ip(ip) {
307
- this._ip = ip;
308
- }
309
- /**
310
- * Return subdomains as an array.
311
- *
312
- * Subdomains are the dot-separated parts of the host before the main domain
313
- * of the app. By default, the domain of the app is assumed to be the last two
314
- * parts of the host. This can be changed by setting `app.subdomainOffset`.
315
- *
316
- * For example, if the domain is "tobi.ferrets.example.com":
317
- * If `app.subdomainOffset` is not set, this.subdomains is
318
- * `["ferrets", "tobi"]`.
319
- * If `app.subdomainOffset` is 3, this.subdomains is `["tobi"]`.
320
- */
321
- get subdomains() {
322
- const offset = this.app.subdomainOffset;
323
- const hostname = this.hostname;
324
- if (net.isIP(hostname)) return [];
325
- return hostname.split(".").reverse().slice(offset);
326
- }
327
- _accept;
328
- /**
329
- * Get accept object.
330
- * Lazily memoized.
331
- */
332
- get accept() {
333
- return this._accept || (this._accept = accepts(this.req));
334
- }
335
- /**
336
- * Set accept object.
337
- */
338
- set accept(obj) {
339
- this._accept = obj;
340
- }
341
- accepts(args, ...others) {
342
- return this.accept.types(args, ...others);
343
- }
344
- acceptsEncodings(encodings, ...others) {
345
- if (!encodings) return this.accept.encodings();
346
- if (Array.isArray(encodings)) encodings = [...encodings, ...others];
347
- else encodings = [encodings, ...others];
348
- return this.accept.encodings(...encodings);
349
- }
350
- acceptsCharsets(charsets, ...others) {
351
- if (!charsets) return this.accept.charsets();
352
- if (Array.isArray(charsets)) charsets = [...charsets, ...others];
353
- else charsets = [charsets, ...others];
354
- return this.accept.charsets(...charsets);
355
- }
356
- acceptsLanguages(languages, ...others) {
357
- if (!languages) return this.accept.languages();
358
- if (Array.isArray(languages)) languages = [...languages, ...others];
359
- else languages = [languages, ...others];
360
- return this.accept.languages(...languages);
361
- }
362
- /**
363
- * Check if the incoming request contains the "Content-Type"
364
- * header field and if it contains any of the given mime `type`s.
365
- * If there is no request body, `null` is returned.
366
- * If there is no content type, `false` is returned.
367
- * Otherwise, it returns the first `type` that matches.
368
- *
369
- * Examples:
370
- *
371
- * // With Content-Type: text/html; charset=utf-8
372
- * this.is('html'); // => 'html'
373
- * this.is('text/html'); // => 'text/html'
374
- * this.is('text/*', 'application/json'); // => 'text/html'
375
- *
376
- * // When Content-Type is application/json
377
- * this.is('json', 'urlencoded'); // => 'json'
378
- * this.is('application/json'); // => 'application/json'
379
- * this.is('html', 'application/*'); // => 'application/json'
380
- *
381
- * this.is('html'); // => false
382
- */
383
- is(type, ...types) {
384
- let testTypes = [];
385
- if (type) testTypes = Array.isArray(type) ? type : [type];
386
- return typeis(this.req, [...testTypes, ...types]);
387
- }
388
- /**
389
- * Return the request mime type void of
390
- * parameters such as "charset".
391
- */
392
- get type() {
393
- const type = this.get("Content-Type");
394
- if (!type) return "";
395
- return type.split(";")[0];
396
- }
397
- /**
398
- * Return request header.
399
- *
400
- * The `Referrer` header field is special-cased,
401
- * both `Referrer` and `Referer` are interchangeable.
402
- *
403
- * Examples:
404
- *
405
- * this.get('Content-Type');
406
- * // => "text/plain"
407
- *
408
- * this.get('content-type');
409
- * // => "text/plain"
410
- *
411
- * this.get('Something');
412
- * // => ''
413
- */
414
- get(field) {
415
- const req = this.req;
416
- switch (field = field.toLowerCase()) {
417
- case "referer":
418
- case "referrer": return req.headers.referrer || req.headers.referer || "";
419
- default: return req.headers[field] || "";
420
- }
421
- }
422
- /**
423
- * Inspect implementation.
424
- */
425
- inspect() {
426
- if (!this.req) return;
427
- return this.toJSON();
428
- }
429
- /**
430
- * Custom inspection implementation for newer Node.js versions.
431
- */
432
- [util.inspect.custom]() {
433
- return this.inspect();
434
- }
435
- /**
436
- * Return JSON representation.
437
- */
438
- toJSON() {
439
- return {
440
- method: this.method,
441
- url: this.url,
442
- header: this.header
443
- };
444
- }
445
- };
446
- /**
447
- * Split a comma-separated value string into an array of values, with an optional limit.
448
- * All the values are trimmed of whitespace and filtered out empty values.
449
- *
450
- * @param {string} value - The comma-separated value string to split.
451
- * @param {number} [limit] - The maximum number of values to return.
452
- * @returns {string[]} An array of values from the comma-separated string.
453
- */
454
- function splitCommaSeparatedValues(value, limit) {
455
- return value.split(",", limit).map((v) => v.trim()).filter((v) => v.length > 0);
456
- }
457
-
458
- //#endregion
459
- export { Request };
@@ -1,231 +0,0 @@
1
- import { Request } from "./request.js";
2
- import { Context } from "./context.js";
3
- import { Application } from "./application.js";
4
- import util from "node:util";
5
- import Stream from "node:stream";
6
- import { IncomingMessage, ServerResponse } from "node:http";
7
- import { Options } from "content-disposition";
8
- import * as http14 from "http";
9
- import * as net0 from "net";
10
-
11
- //#region src/response.d.ts
12
- declare class Response {
13
- [key: symbol]: unknown;
14
- app: Application;
15
- req: IncomingMessage;
16
- res: ServerResponse;
17
- ctx: Context;
18
- request: Request;
19
- constructor(app: Application, ctx: Context, req: IncomingMessage, res: ServerResponse);
20
- /**
21
- * Return the request socket.
22
- */
23
- get socket(): net0.Socket | null;
24
- /**
25
- * Return response header.
26
- */
27
- get header(): http14.OutgoingHttpHeaders;
28
- /**
29
- * Return response header, alias as response.header
30
- */
31
- get headers(): http14.OutgoingHttpHeaders;
32
- _explicitStatus: boolean;
33
- /**
34
- * Get response status code.
35
- */
36
- get status(): number;
37
- /**
38
- * Set response status code.
39
- */
40
- set status(code: number);
41
- /**
42
- * Get response status message
43
- */
44
- get message(): string;
45
- /**
46
- * Set response status message
47
- */
48
- set message(msg: string);
49
- _body: any;
50
- _explicitNullBody: boolean;
51
- /**
52
- * Get response body.
53
- */
54
- get body(): string | Buffer | object | Stream | null | undefined | boolean;
55
- /**
56
- * Set response body.
57
- */
58
- set body(val: string | Buffer | object | Stream | null | undefined | boolean);
59
- /**
60
- * Set Content-Length field to `n`.
61
- */
62
- set length(n: number | string | undefined);
63
- /**
64
- * Return parsed response Content-Length when present.
65
- *
66
- * When Content-Length is not defined it will return `undefined`.
67
- */
68
- get length(): number | undefined;
69
- /**
70
- * Check if a header has been written to the socket.
71
- */
72
- get headerSent(): boolean;
73
- /**
74
- * Vary on `field`.
75
- */
76
- vary(field: string): void;
77
- _getBackReferrer(): string | undefined;
78
- /**
79
- * Perform a 302 redirect to `url`.
80
- *
81
- * The string "back" is special-cased
82
- * to provide Referrer support, when Referrer
83
- * is not present `alt` or "/" is used.
84
- *
85
- * Examples:
86
- *
87
- * this.redirect('back');
88
- * this.redirect('back', '/index.html');
89
- * this.redirect('/login');
90
- * this.redirect('http://google.com'); // will format to 'http://google.com/'
91
- */
92
- redirect(url: string, alt?: string): void;
93
- /**
94
- * Set Content-Disposition header to "attachment" with optional `filename`.
95
- */
96
- attachment(filename?: string, options?: Options): void;
97
- /**
98
- * Set Content-Type response header with `type` through `mime.lookup()`
99
- * when it does not contain a charset.
100
- *
101
- * Examples:
102
- *
103
- * this.type = '.html';
104
- * this.type = 'html';
105
- * this.type = 'json';
106
- * this.type = 'application/json';
107
- * this.type = 'png';
108
- */
109
- set type(type: string | null | undefined);
110
- /**
111
- * Return the response mime type void of
112
- * parameters such as "charset".
113
- */
114
- get type(): string;
115
- /**
116
- * Check whether the response is one of the listed types.
117
- * Pretty much the same as `this.request.is()`.
118
- *
119
- * this.response.is('html')
120
- * this.response.is('html', 'json')
121
- */
122
- is(type?: string | string[], ...types: string[]): string | false;
123
- /**
124
- * Set the Last-Modified date using a string or a Date.
125
- *
126
- * this.response.lastModified = new Date();
127
- * this.response.lastModified = '2013-09-13';
128
- */
129
- set lastModified(val: string | Date | undefined);
130
- /**
131
- * Get the Last-Modified date in Date form, if it exists.
132
- */
133
- get lastModified(): Date | undefined;
134
- /**
135
- * Set the ETag of a response.
136
- * This will normalize the quotes if necessary.
137
- *
138
- * this.response.etag = 'md5-hash-sum';
139
- * this.response.etag = '"md5-hash-sum"';
140
- * this.response.etag = 'W/"123456789"';
141
- */
142
- set etag(val: string);
143
- /**
144
- * Get the ETag of a response.
145
- */
146
- get etag(): string;
147
- /**
148
- * Return response header.
149
- *
150
- * Examples:
151
- *
152
- * this.get('Content-Type');
153
- * // => "text/plain"
154
- *
155
- * this.get('content-type');
156
- * // => "text/plain"
157
- */
158
- get<T = string | string[] | number>(field: string): T;
159
- /**
160
- * Returns true if the header identified by name is currently set in the outgoing headers.
161
- * The header name matching is case-insensitive.
162
- *
163
- * Examples:
164
- *
165
- * this.has('Content-Type');
166
- * // => true
167
- *
168
- * this.get('content-type');
169
- * // => true
170
- */
171
- has(field: string): boolean;
172
- /**
173
- * Set header `field` to `val` or pass
174
- * an object of header fields.
175
- *
176
- * Examples:
177
- *
178
- * this.set('Foo', ['bar', 'baz']);
179
- * this.set('Accept', 'application/json');
180
- * this.set({ Accept: 'text/plain', 'X-API-Key': 'tobi' });
181
- */
182
- set(field: string | Record<string, string>, val?: string | number | unknown[]): void;
183
- /**
184
- * Append additional header `field` with value `val`.
185
- *
186
- * Examples:
187
- *
188
- * ```
189
- * this.append('Link', ['<http://localhost/>', '<http://localhost:3000/>']);
190
- * this.append('Set-Cookie', 'foo=bar; Path=/; HttpOnly');
191
- * this.append('Warning', '199 Miscellaneous warning');
192
- */
193
- append(field: string, val: string | string[]): void;
194
- /**
195
- * Remove header `field`.
196
- */
197
- remove(field: string): void;
198
- /**
199
- * Checks if the request is writable.
200
- * Tests for the existence of the socket
201
- * as node sometimes does not set it.
202
- */
203
- get writable(): boolean;
204
- /**
205
- * Inspect implementation.
206
- */
207
- inspect(): {
208
- status: number;
209
- message: string;
210
- header: http14.OutgoingHttpHeaders;
211
- } | undefined;
212
- [util.inspect.custom](): {
213
- status: number;
214
- message: string;
215
- header: http14.OutgoingHttpHeaders;
216
- } | undefined;
217
- /**
218
- * Return JSON representation.
219
- */
220
- toJSON(): {
221
- status: number;
222
- message: string;
223
- header: http14.OutgoingHttpHeaders;
224
- };
225
- /**
226
- * Flush any set headers and begin the body
227
- */
228
- flushHeaders(): void;
229
- }
230
- //#endregion
231
- export { Response };