@whatwg-node/server 0.6.7 → 0.7.0-alpha-20230215085143-56e6bef

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/index.mjs DELETED
@@ -1,577 +0,0 @@
1
- import { URL, Request, Response } from '@whatwg-node/fetch';
2
- export { Response } from '@whatwg-node/fetch';
3
-
4
- function isAsyncIterable(body) {
5
- return (body != null && typeof body === 'object' && typeof body[Symbol.asyncIterator] === 'function');
6
- }
7
- function getPort(nodeRequest) {
8
- var _a, _b, _c, _d, _e;
9
- if ((_a = nodeRequest.socket) === null || _a === void 0 ? void 0 : _a.localPort) {
10
- return (_b = nodeRequest.socket) === null || _b === void 0 ? void 0 : _b.localPort;
11
- }
12
- const hostInHeader = ((_c = nodeRequest.headers) === null || _c === void 0 ? void 0 : _c[':authority']) || ((_d = nodeRequest.headers) === null || _d === void 0 ? void 0 : _d.host);
13
- const portInHeader = (_e = hostInHeader === null || hostInHeader === void 0 ? void 0 : hostInHeader.split(':')) === null || _e === void 0 ? void 0 : _e[1];
14
- if (portInHeader) {
15
- return portInHeader;
16
- }
17
- return 80;
18
- }
19
- function getHostnameWithPort(nodeRequest) {
20
- var _a, _b, _c, _d, _e;
21
- if ((_a = nodeRequest.headers) === null || _a === void 0 ? void 0 : _a[':authority']) {
22
- return (_b = nodeRequest.headers) === null || _b === void 0 ? void 0 : _b[':authority'];
23
- }
24
- if ((_c = nodeRequest.headers) === null || _c === void 0 ? void 0 : _c.host) {
25
- return (_d = nodeRequest.headers) === null || _d === void 0 ? void 0 : _d.host;
26
- }
27
- const port = getPort(nodeRequest);
28
- if (nodeRequest.hostname) {
29
- return nodeRequest.hostname + ':' + port;
30
- }
31
- const localIp = (_e = nodeRequest.socket) === null || _e === void 0 ? void 0 : _e.localAddress;
32
- if (localIp && !(localIp === null || localIp === void 0 ? void 0 : localIp.includes('::')) && !(localIp === null || localIp === void 0 ? void 0 : localIp.includes('ffff'))) {
33
- return `${localIp}:${port}`;
34
- }
35
- return 'localhost';
36
- }
37
- function buildFullUrl(nodeRequest) {
38
- const hostnameWithPort = getHostnameWithPort(nodeRequest);
39
- const protocol = nodeRequest.protocol || 'http';
40
- const endpoint = nodeRequest.originalUrl || nodeRequest.url || '/graphql';
41
- return `${protocol}://${hostnameWithPort}${endpoint}`;
42
- }
43
- function isRequestBody(body) {
44
- const stringTag = body[Symbol.toStringTag];
45
- if (typeof body === 'string' ||
46
- stringTag === 'Uint8Array' ||
47
- stringTag === 'Blob' ||
48
- stringTag === 'FormData' ||
49
- stringTag === 'URLSearchParams' ||
50
- isAsyncIterable(body)) {
51
- return true;
52
- }
53
- return false;
54
- }
55
- function normalizeNodeRequest(nodeRequest, RequestCtor) {
56
- var _a;
57
- const rawRequest = nodeRequest.raw || nodeRequest.req || nodeRequest;
58
- let fullUrl = buildFullUrl(rawRequest);
59
- if (nodeRequest.query) {
60
- const url = new URL(fullUrl);
61
- for (const key in nodeRequest.query) {
62
- url.searchParams.set(key, nodeRequest.query[key]);
63
- }
64
- fullUrl = url.toString();
65
- }
66
- if (nodeRequest.method === 'GET' || nodeRequest.method === 'HEAD') {
67
- return new RequestCtor(fullUrl, {
68
- method: nodeRequest.method,
69
- headers: nodeRequest.headers,
70
- });
71
- }
72
- /**
73
- * Some Node server frameworks like Serverless Express sends a dummy object with body but as a Buffer not string
74
- * so we do those checks to see is there something we can use directly as BodyInit
75
- * because the presence of body means the request stream is already consumed and,
76
- * rawRequest cannot be used as BodyInit/ReadableStream by Fetch API in this case.
77
- */
78
- const maybeParsedBody = nodeRequest.body;
79
- if (maybeParsedBody != null && Object.keys(maybeParsedBody).length > 0) {
80
- if (isRequestBody(maybeParsedBody)) {
81
- return new RequestCtor(fullUrl, {
82
- method: nodeRequest.method,
83
- headers: nodeRequest.headers,
84
- body: maybeParsedBody,
85
- });
86
- }
87
- const request = new RequestCtor(fullUrl, {
88
- method: nodeRequest.method,
89
- headers: nodeRequest.headers,
90
- });
91
- if (!((_a = request.headers.get('content-type')) === null || _a === void 0 ? void 0 : _a.includes('json'))) {
92
- request.headers.set('content-type', 'application/json');
93
- }
94
- return new Proxy(request, {
95
- get: (target, prop, receiver) => {
96
- switch (prop) {
97
- case 'json':
98
- return async () => maybeParsedBody;
99
- case 'text':
100
- return async () => JSON.stringify(maybeParsedBody);
101
- default:
102
- return Reflect.get(target, prop, receiver);
103
- }
104
- },
105
- });
106
- }
107
- // perf: instead of spreading the object, we can just pass it as is and it performs better
108
- return new RequestCtor(fullUrl, {
109
- method: nodeRequest.method,
110
- headers: nodeRequest.headers,
111
- body: rawRequest,
112
- });
113
- }
114
- function isReadable(stream) {
115
- return stream.read != null;
116
- }
117
- function isNodeRequest(request) {
118
- return isReadable(request);
119
- }
120
- function isServerResponse(stream) {
121
- // Check all used functions are defined
122
- return (stream != null &&
123
- stream.setHeader != null &&
124
- stream.end != null &&
125
- stream.once != null &&
126
- stream.write != null);
127
- }
128
- function isReadableStream(stream) {
129
- return stream != null && stream.getReader != null;
130
- }
131
- function isFetchEvent(event) {
132
- return event != null && event.request != null && event.respondWith != null;
133
- }
134
- function configureSocket(rawRequest) {
135
- var _a, _b, _c, _d, _e, _f;
136
- (_b = (_a = rawRequest === null || rawRequest === void 0 ? void 0 : rawRequest.socket) === null || _a === void 0 ? void 0 : _a.setTimeout) === null || _b === void 0 ? void 0 : _b.call(_a, 0);
137
- (_d = (_c = rawRequest === null || rawRequest === void 0 ? void 0 : rawRequest.socket) === null || _c === void 0 ? void 0 : _c.setNoDelay) === null || _d === void 0 ? void 0 : _d.call(_c, true);
138
- (_f = (_e = rawRequest === null || rawRequest === void 0 ? void 0 : rawRequest.socket) === null || _e === void 0 ? void 0 : _e.setKeepAlive) === null || _f === void 0 ? void 0 : _f.call(_e, true);
139
- }
140
- function endResponse(serverResponse) {
141
- // @ts-expect-error Avoid arguments adaptor trampoline https://v8.dev/blog/adaptor-frame
142
- serverResponse.end(null, null, null);
143
- }
144
- function getHeadersObj(headers) {
145
- return new Proxy({}, {
146
- get(_target, prop) {
147
- return headers.get(prop);
148
- },
149
- set(_target, prop, value) {
150
- headers.set(prop, value);
151
- return true;
152
- },
153
- has(_target, prop) {
154
- return headers.has(prop);
155
- },
156
- deleteProperty(_target, prop) {
157
- headers.delete(prop);
158
- return true;
159
- },
160
- ownKeys() {
161
- const keys = [];
162
- headers.forEach((_, key) => keys.push(key));
163
- return keys;
164
- },
165
- getOwnPropertyDescriptor() {
166
- return {
167
- enumerable: true,
168
- configurable: true,
169
- };
170
- },
171
- });
172
- }
173
- async function sendNodeResponse(fetchResponse, serverResponse, nodeRequest) {
174
- const headersObj = getHeadersObj(fetchResponse.headers);
175
- serverResponse.writeHead(fetchResponse.status, fetchResponse.statusText, headersObj);
176
- // eslint-disable-next-line no-async-promise-executor
177
- return new Promise(async (resolve) => {
178
- serverResponse.once('close', resolve);
179
- // Our Node-fetch enhancements
180
- if ('bodyType' in fetchResponse &&
181
- fetchResponse.bodyType != null &&
182
- (fetchResponse.bodyType === 'String' || fetchResponse.bodyType === 'Uint8Array')) {
183
- // @ts-expect-error http and http2 writes are actually compatible
184
- serverResponse.write(fetchResponse.bodyInit);
185
- endResponse(serverResponse);
186
- return;
187
- }
188
- // Other fetch implementations
189
- const fetchBody = fetchResponse.body;
190
- if (fetchBody == null) {
191
- endResponse(serverResponse);
192
- return;
193
- }
194
- if (fetchBody[Symbol.toStringTag] === 'Uint8Array') {
195
- serverResponse
196
- // @ts-expect-error http and http2 writes are actually compatible
197
- .write(fetchBody);
198
- endResponse(serverResponse);
199
- return;
200
- }
201
- configureSocket(nodeRequest);
202
- if (isReadable(fetchBody)) {
203
- serverResponse.once('close', () => {
204
- fetchBody.destroy();
205
- });
206
- fetchBody.pipe(serverResponse);
207
- return;
208
- }
209
- if (isAsyncIterable(fetchBody)) {
210
- for await (const chunk of fetchBody) {
211
- if (!serverResponse
212
- // @ts-expect-error http and http2 writes are actually compatible
213
- .write(chunk)) {
214
- break;
215
- }
216
- }
217
- endResponse(serverResponse);
218
- }
219
- });
220
- }
221
- function isRequestInit(val) {
222
- return (val != null &&
223
- typeof val === 'object' &&
224
- ('body' in val ||
225
- 'cache' in val ||
226
- 'credentials' in val ||
227
- 'headers' in val ||
228
- 'integrity' in val ||
229
- 'keepalive' in val ||
230
- 'method' in val ||
231
- 'mode' in val ||
232
- 'redirect' in val ||
233
- 'referrer' in val ||
234
- 'referrerPolicy' in val ||
235
- 'signal' in val ||
236
- 'window' in val));
237
- }
238
-
239
- /* eslint-disable @typescript-eslint/ban-types */
240
- async function handleWaitUntils(waitUntilPromises) {
241
- const waitUntils = await Promise.allSettled(waitUntilPromises);
242
- waitUntils.forEach(waitUntil => {
243
- if (waitUntil.status === 'rejected') {
244
- console.error(waitUntil.reason);
245
- }
246
- });
247
- }
248
- function createServerAdapter(serverAdapterBaseObject,
249
- /**
250
- * WHATWG Fetch spec compliant `Request` constructor.
251
- */
252
- RequestCtor = Request) {
253
- const handleRequest = typeof serverAdapterBaseObject === 'function'
254
- ? serverAdapterBaseObject
255
- : serverAdapterBaseObject.handle;
256
- function handleNodeRequest(nodeRequest, ...ctx) {
257
- const serverContext = ctx.length > 1 ? completeAssign({}, ...ctx) : ctx[0];
258
- const request = normalizeNodeRequest(nodeRequest, RequestCtor);
259
- return handleRequest(request, serverContext);
260
- }
261
- async function requestListener(nodeRequest, serverResponse, ...ctx) {
262
- const waitUntilPromises = [];
263
- const defaultServerContext = {
264
- req: nodeRequest,
265
- res: serverResponse,
266
- waitUntil(promise) {
267
- if (promise != null) {
268
- waitUntilPromises.push(promise);
269
- }
270
- },
271
- };
272
- const response = await handleNodeRequest(nodeRequest, defaultServerContext, ...ctx);
273
- if (response) {
274
- await sendNodeResponse(response, serverResponse, nodeRequest);
275
- }
276
- else {
277
- await new Promise(resolve => {
278
- serverResponse.statusCode = 404;
279
- serverResponse.once('end', resolve);
280
- serverResponse.end();
281
- });
282
- }
283
- if (waitUntilPromises.length > 0) {
284
- await handleWaitUntils(waitUntilPromises);
285
- }
286
- }
287
- function handleEvent(event, ...ctx) {
288
- if (!event.respondWith || !event.request) {
289
- throw new TypeError(`Expected FetchEvent, got ${event}`);
290
- }
291
- const serverContext = ctx.length > 0 ? Object.assign({}, event, ...ctx) : event;
292
- const response$ = handleRequest(event.request, serverContext);
293
- event.respondWith(response$);
294
- }
295
- function handleRequestWithWaitUntil(request, ...ctx) {
296
- const serverContext = ctx.length > 1 ? completeAssign({}, ...ctx) : ctx[0] || {};
297
- if (!('waitUntil' in serverContext)) {
298
- const waitUntilPromises = [];
299
- const response$ = handleRequest(request, {
300
- ...serverContext,
301
- waitUntil(promise) {
302
- if (promise != null) {
303
- waitUntilPromises.push(promise);
304
- }
305
- },
306
- });
307
- if (waitUntilPromises.length > 0) {
308
- return handleWaitUntils(waitUntilPromises).then(() => response$);
309
- }
310
- return response$;
311
- }
312
- return handleRequest(request, serverContext);
313
- }
314
- const fetchFn = (input, ...maybeCtx) => {
315
- if (typeof input === 'string' || 'href' in input) {
316
- const [initOrCtx, ...restOfCtx] = maybeCtx;
317
- if (isRequestInit(initOrCtx)) {
318
- return handleRequestWithWaitUntil(new RequestCtor(input, initOrCtx), ...restOfCtx);
319
- }
320
- return handleRequestWithWaitUntil(new RequestCtor(input), ...maybeCtx);
321
- }
322
- return handleRequestWithWaitUntil(input, ...maybeCtx);
323
- };
324
- const genericRequestHandler = (input, ...maybeCtx) => {
325
- // If it is a Node request
326
- const [initOrCtxOrRes, ...restOfCtx] = maybeCtx;
327
- if (isNodeRequest(input)) {
328
- if (!isServerResponse(initOrCtxOrRes)) {
329
- throw new TypeError(`Expected ServerResponse, got ${initOrCtxOrRes}`);
330
- }
331
- return requestListener(input, initOrCtxOrRes, ...restOfCtx);
332
- }
333
- if (isServerResponse(initOrCtxOrRes)) {
334
- throw new TypeError('Got Node response without Node request');
335
- }
336
- // Is input a container object over Request?
337
- if (typeof input === 'object' && 'request' in input) {
338
- // Is it FetchEvent?
339
- if (isFetchEvent(input)) {
340
- return handleEvent(input, ...maybeCtx);
341
- }
342
- // In this input is also the context
343
- return handleRequestWithWaitUntil(input.request, input, ...maybeCtx);
344
- }
345
- // Or is it Request itself?
346
- // Then ctx is present and it is the context
347
- return fetchFn(input, ...maybeCtx);
348
- };
349
- const adapterObj = {
350
- handleRequest,
351
- fetch: fetchFn,
352
- handleNodeRequest,
353
- requestListener,
354
- handleEvent,
355
- handle: genericRequestHandler,
356
- };
357
- return new Proxy(genericRequestHandler, {
358
- // It should have all the attributes of the handler function and the server instance
359
- has: (_, prop) => {
360
- return (prop in adapterObj ||
361
- prop in genericRequestHandler ||
362
- (serverAdapterBaseObject && prop in serverAdapterBaseObject));
363
- },
364
- get: (_, prop) => {
365
- const adapterProp = adapterObj[prop];
366
- if (adapterProp) {
367
- if (adapterProp.bind) {
368
- return adapterProp.bind(adapterObj);
369
- }
370
- return adapterProp;
371
- }
372
- const handleProp = genericRequestHandler[prop];
373
- if (handleProp) {
374
- if (handleProp.bind) {
375
- return handleProp.bind(genericRequestHandler);
376
- }
377
- return handleProp;
378
- }
379
- if (serverAdapterBaseObject) {
380
- const serverAdapterBaseObjectProp = serverAdapterBaseObject[prop];
381
- if (serverAdapterBaseObjectProp) {
382
- if (serverAdapterBaseObjectProp.bind) {
383
- return serverAdapterBaseObjectProp.bind(serverAdapterBaseObject);
384
- }
385
- return serverAdapterBaseObjectProp;
386
- }
387
- }
388
- },
389
- apply(_, __, args) {
390
- return genericRequestHandler(...args);
391
- },
392
- }); // 😡
393
- }
394
- // from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign#copying_accessors
395
- function completeAssign(target, ...sources) {
396
- sources.forEach(source => {
397
- if (source != null && typeof source === 'object') {
398
- // modified Object.keys to Object.getOwnPropertyNames
399
- // because Object.keys only returns enumerable properties
400
- const descriptors = Object.getOwnPropertyNames(source).reduce((descriptors, key) => {
401
- descriptors[key] = Object.getOwnPropertyDescriptor(source, key);
402
- return descriptors;
403
- }, {});
404
- // By default, Object.assign copies enumerable Symbols, too
405
- Object.getOwnPropertySymbols(source).forEach(sym => {
406
- const descriptor = Object.getOwnPropertyDescriptor(source, sym);
407
- if (descriptor.enumerable) {
408
- descriptors[sym] = descriptor;
409
- }
410
- });
411
- Object.defineProperties(target, descriptors);
412
- }
413
- });
414
- return target;
415
- }
416
-
417
- /* eslint-disable @typescript-eslint/ban-types */
418
- function getCORSHeadersByRequestAndOptions(request, corsOptions) {
419
- var _a, _b;
420
- const headers = {};
421
- if (corsOptions === false) {
422
- return headers;
423
- }
424
- // If defined origins have '*' or undefined by any means, we should allow all origins
425
- if (corsOptions.origin == null ||
426
- corsOptions.origin.length === 0 ||
427
- corsOptions.origin.includes('*')) {
428
- const currentOrigin = request.headers.get('origin');
429
- // If origin is available in the headers, use it
430
- if (currentOrigin != null) {
431
- headers['Access-Control-Allow-Origin'] = currentOrigin;
432
- // Vary by origin because there are multiple origins
433
- headers['Vary'] = 'Origin';
434
- }
435
- else {
436
- headers['Access-Control-Allow-Origin'] = '*';
437
- }
438
- }
439
- else if (typeof corsOptions.origin === 'string') {
440
- // If there is one specific origin is specified, use it directly
441
- headers['Access-Control-Allow-Origin'] = corsOptions.origin;
442
- }
443
- else if (Array.isArray(corsOptions.origin)) {
444
- // If there is only one origin defined in the array, consider it as a single one
445
- if (corsOptions.origin.length === 1) {
446
- headers['Access-Control-Allow-Origin'] = corsOptions.origin[0];
447
- }
448
- else {
449
- const currentOrigin = request.headers.get('origin');
450
- if (currentOrigin != null && corsOptions.origin.includes(currentOrigin)) {
451
- // If origin is available in the headers, use it
452
- headers['Access-Control-Allow-Origin'] = currentOrigin;
453
- // Vary by origin because there are multiple origins
454
- headers['Vary'] = 'Origin';
455
- }
456
- else {
457
- // There is no origin found in the headers, so we should return null
458
- headers['Access-Control-Allow-Origin'] = 'null';
459
- }
460
- }
461
- }
462
- if ((_a = corsOptions.methods) === null || _a === void 0 ? void 0 : _a.length) {
463
- headers['Access-Control-Allow-Methods'] = corsOptions.methods.join(', ');
464
- }
465
- else {
466
- const requestMethod = request.headers.get('access-control-request-method');
467
- if (requestMethod) {
468
- headers['Access-Control-Allow-Methods'] = requestMethod;
469
- }
470
- }
471
- if ((_b = corsOptions.allowedHeaders) === null || _b === void 0 ? void 0 : _b.length) {
472
- headers['Access-Control-Allow-Headers'] = corsOptions.allowedHeaders.join(', ');
473
- }
474
- else {
475
- const requestHeaders = request.headers.get('access-control-request-headers');
476
- if (requestHeaders) {
477
- headers['Access-Control-Allow-Headers'] = requestHeaders;
478
- if (headers['Vary']) {
479
- headers['Vary'] += ', Access-Control-Request-Headers';
480
- }
481
- headers['Vary'] = 'Access-Control-Request-Headers';
482
- }
483
- }
484
- if (corsOptions.credentials != null) {
485
- if (corsOptions.credentials === true) {
486
- headers['Access-Control-Allow-Credentials'] = 'true';
487
- }
488
- }
489
- else if (headers['Access-Control-Allow-Origin'] !== '*') {
490
- headers['Access-Control-Allow-Credentials'] = 'true';
491
- }
492
- if (corsOptions.exposedHeaders) {
493
- headers['Access-Control-Expose-Headers'] = corsOptions.exposedHeaders.join(', ');
494
- }
495
- if (corsOptions.maxAge) {
496
- headers['Access-Control-Max-Age'] = corsOptions.maxAge.toString();
497
- }
498
- return headers;
499
- }
500
- async function getCORSResponseHeaders(request, corsOptionsFactory, serverContext) {
501
- const corsOptions = await corsOptionsFactory(request, serverContext);
502
- return getCORSHeadersByRequestAndOptions(request, corsOptions);
503
- }
504
- function withCORS(obj, options, ResponseCtor = Response) {
505
- let corsOptionsFactory = () => ({});
506
- if (options != null) {
507
- if (typeof options === 'function') {
508
- corsOptionsFactory = options;
509
- }
510
- else if (typeof options === 'object') {
511
- const corsOptions = {
512
- ...options,
513
- };
514
- corsOptionsFactory = () => corsOptions;
515
- }
516
- else if (options === false) {
517
- corsOptionsFactory = () => false;
518
- }
519
- }
520
- async function handleWithCORS(request, serverContext) {
521
- let response;
522
- if (request.method.toUpperCase() === 'OPTIONS') {
523
- response = new ResponseCtor(null, {
524
- status: 204,
525
- });
526
- }
527
- else {
528
- response = await obj.handle(request, serverContext);
529
- }
530
- if (response != null) {
531
- const headers = await getCORSResponseHeaders(request, corsOptionsFactory, serverContext);
532
- for (const headerName in headers) {
533
- response.headers.set(headerName, headers[headerName]);
534
- }
535
- return response;
536
- }
537
- }
538
- return new Proxy(obj, {
539
- get(_, prop, receiver) {
540
- if (prop === 'handle') {
541
- return handleWithCORS;
542
- }
543
- return Reflect.get(obj, prop, receiver);
544
- },
545
- });
546
- }
547
-
548
- /* eslint-disable @typescript-eslint/ban-types */
549
- function createDefaultErrorHandler(ResponseCtor = Response) {
550
- return function defaultErrorHandler(e) {
551
- return new ResponseCtor(e.stack || e.message || e.toString(), {
552
- status: e.statusCode || e.status || 500,
553
- statusText: e.statusText || 'Internal Server Error',
554
- });
555
- };
556
- }
557
- function withErrorHandling(obj, onError = createDefaultErrorHandler()) {
558
- async function handleWithErrorHandling(request, ctx) {
559
- try {
560
- const res = await obj.handle(request, ctx);
561
- return res;
562
- }
563
- catch (e) {
564
- return onError(e, request, ctx);
565
- }
566
- }
567
- return new Proxy(obj, {
568
- get(obj, prop, receiver) {
569
- if (prop === 'handle') {
570
- return handleWithErrorHandling;
571
- }
572
- return Reflect.get(obj, prop, receiver);
573
- },
574
- });
575
- }
576
-
577
- export { createDefaultErrorHandler, createServerAdapter, getCORSHeadersByRequestAndOptions, isAsyncIterable, isFetchEvent, isNodeRequest, isReadable, isReadableStream, isRequestInit, isServerResponse, normalizeNodeRequest, sendNodeResponse, withCORS, withErrorHandling };