@sveltejs/kit 1.0.0-next.32 → 1.0.0-next.320

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.
Files changed (73) hide show
  1. package/README.md +12 -9
  2. package/assets/app/env.js +20 -0
  3. package/assets/app/navigation.js +24 -0
  4. package/assets/app/paths.js +1 -0
  5. package/assets/app/stores.js +97 -0
  6. package/assets/client/singletons.js +13 -0
  7. package/assets/client/start.js +1687 -0
  8. package/assets/components/error.svelte +18 -2
  9. package/assets/env.js +8 -0
  10. package/assets/paths.js +13 -0
  11. package/assets/server/index.js +3411 -0
  12. package/dist/chunks/amp_hook.js +56 -0
  13. package/dist/chunks/cert.js +28154 -0
  14. package/dist/chunks/constants.js +663 -0
  15. package/dist/chunks/filesystem.js +110 -0
  16. package/dist/chunks/index.js +515 -0
  17. package/dist/chunks/index2.js +1335 -0
  18. package/dist/chunks/index3.js +118 -0
  19. package/dist/chunks/index4.js +186 -0
  20. package/dist/chunks/index5.js +251 -0
  21. package/dist/chunks/index6.js +15737 -0
  22. package/dist/chunks/index7.js +4207 -0
  23. package/dist/chunks/misc.js +78 -0
  24. package/dist/chunks/multipart-parser.js +449 -0
  25. package/dist/chunks/object.js +83 -0
  26. package/dist/chunks/sync.js +974 -0
  27. package/dist/chunks/url.js +56 -0
  28. package/dist/cli.js +1024 -65
  29. package/dist/hooks.js +28 -0
  30. package/dist/install-fetch.js +6518 -0
  31. package/dist/node.js +94 -0
  32. package/package.json +95 -62
  33. package/svelte-kit.js +0 -1
  34. package/types/ambient.d.ts +298 -0
  35. package/types/index.d.ts +278 -0
  36. package/types/internal.d.ts +320 -0
  37. package/types/private.d.ts +242 -0
  38. package/CHANGELOG.md +0 -350
  39. package/assets/runtime/app/navigation.js +0 -23
  40. package/assets/runtime/app/navigation.js.map +0 -1
  41. package/assets/runtime/app/paths.js +0 -2
  42. package/assets/runtime/app/paths.js.map +0 -1
  43. package/assets/runtime/app/stores.js +0 -78
  44. package/assets/runtime/app/stores.js.map +0 -1
  45. package/assets/runtime/internal/singletons.js +0 -15
  46. package/assets/runtime/internal/singletons.js.map +0 -1
  47. package/assets/runtime/internal/start.js +0 -591
  48. package/assets/runtime/internal/start.js.map +0 -1
  49. package/assets/runtime/utils-85ebcc60.js +0 -18
  50. package/assets/runtime/utils-85ebcc60.js.map +0 -1
  51. package/dist/api.js +0 -32
  52. package/dist/api.js.map +0 -1
  53. package/dist/cli.js.map +0 -1
  54. package/dist/create_app.js +0 -577
  55. package/dist/create_app.js.map +0 -1
  56. package/dist/index.js +0 -329
  57. package/dist/index.js.map +0 -1
  58. package/dist/index2.js +0 -14363
  59. package/dist/index2.js.map +0 -1
  60. package/dist/index3.js +0 -544
  61. package/dist/index3.js.map +0 -1
  62. package/dist/index4.js +0 -71
  63. package/dist/index4.js.map +0 -1
  64. package/dist/index5.js +0 -465
  65. package/dist/index5.js.map +0 -1
  66. package/dist/index6.js +0 -727
  67. package/dist/index6.js.map +0 -1
  68. package/dist/renderer.js +0 -2413
  69. package/dist/renderer.js.map +0 -1
  70. package/dist/standard.js +0 -100
  71. package/dist/standard.js.map +0 -1
  72. package/dist/utils.js +0 -57
  73. package/dist/utils.js.map +0 -1
package/dist/renderer.js DELETED
@@ -1,2413 +0,0 @@
1
- import { createHash } from 'crypto';
2
- import Stream from 'stream';
3
- import http from 'http';
4
- import Url, { parse, resolve, URLSearchParams } from 'url';
5
- import https from 'https';
6
- import zlib from 'zlib';
7
-
8
- var chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_$';
9
- var unsafeChars = /[<>\b\f\n\r\t\0\u2028\u2029]/g;
10
- var reserved = /^(?:do|if|in|for|int|let|new|try|var|byte|case|char|else|enum|goto|long|this|void|with|await|break|catch|class|const|final|float|short|super|throw|while|yield|delete|double|export|import|native|return|switch|throws|typeof|boolean|default|extends|finally|package|private|abstract|continue|debugger|function|volatile|interface|protected|transient|implements|instanceof|synchronized)$/;
11
- var escaped = {
12
- '<': '\\u003C',
13
- '>': '\\u003E',
14
- '/': '\\u002F',
15
- '\\': '\\\\',
16
- '\b': '\\b',
17
- '\f': '\\f',
18
- '\n': '\\n',
19
- '\r': '\\r',
20
- '\t': '\\t',
21
- '\0': '\\0',
22
- '\u2028': '\\u2028',
23
- '\u2029': '\\u2029'
24
- };
25
- var objectProtoOwnPropertyNames = Object.getOwnPropertyNames(Object.prototype).sort().join('\0');
26
- function devalue(value) {
27
- var counts = new Map();
28
- function walk(thing) {
29
- if (typeof thing === 'function') {
30
- throw new Error("Cannot stringify a function");
31
- }
32
- if (counts.has(thing)) {
33
- counts.set(thing, counts.get(thing) + 1);
34
- return;
35
- }
36
- counts.set(thing, 1);
37
- if (!isPrimitive(thing)) {
38
- var type = getType(thing);
39
- switch (type) {
40
- case 'Number':
41
- case 'String':
42
- case 'Boolean':
43
- case 'Date':
44
- case 'RegExp':
45
- return;
46
- case 'Array':
47
- thing.forEach(walk);
48
- break;
49
- case 'Set':
50
- case 'Map':
51
- Array.from(thing).forEach(walk);
52
- break;
53
- default:
54
- var proto = Object.getPrototypeOf(thing);
55
- if (proto !== Object.prototype &&
56
- proto !== null &&
57
- Object.getOwnPropertyNames(proto).sort().join('\0') !== objectProtoOwnPropertyNames) {
58
- throw new Error("Cannot stringify arbitrary non-POJOs");
59
- }
60
- if (Object.getOwnPropertySymbols(thing).length > 0) {
61
- throw new Error("Cannot stringify POJOs with symbolic keys");
62
- }
63
- Object.keys(thing).forEach(function (key) { return walk(thing[key]); });
64
- }
65
- }
66
- }
67
- walk(value);
68
- var names = new Map();
69
- Array.from(counts)
70
- .filter(function (entry) { return entry[1] > 1; })
71
- .sort(function (a, b) { return b[1] - a[1]; })
72
- .forEach(function (entry, i) {
73
- names.set(entry[0], getName(i));
74
- });
75
- function stringify(thing) {
76
- if (names.has(thing)) {
77
- return names.get(thing);
78
- }
79
- if (isPrimitive(thing)) {
80
- return stringifyPrimitive(thing);
81
- }
82
- var type = getType(thing);
83
- switch (type) {
84
- case 'Number':
85
- case 'String':
86
- case 'Boolean':
87
- return "Object(" + stringify(thing.valueOf()) + ")";
88
- case 'RegExp':
89
- return "new RegExp(" + stringifyString(thing.source) + ", \"" + thing.flags + "\")";
90
- case 'Date':
91
- return "new Date(" + thing.getTime() + ")";
92
- case 'Array':
93
- var members = thing.map(function (v, i) { return i in thing ? stringify(v) : ''; });
94
- var tail = thing.length === 0 || (thing.length - 1 in thing) ? '' : ',';
95
- return "[" + members.join(',') + tail + "]";
96
- case 'Set':
97
- case 'Map':
98
- return "new " + type + "([" + Array.from(thing).map(stringify).join(',') + "])";
99
- default:
100
- var obj = "{" + Object.keys(thing).map(function (key) { return safeKey(key) + ":" + stringify(thing[key]); }).join(',') + "}";
101
- var proto = Object.getPrototypeOf(thing);
102
- if (proto === null) {
103
- return Object.keys(thing).length > 0
104
- ? "Object.assign(Object.create(null)," + obj + ")"
105
- : "Object.create(null)";
106
- }
107
- return obj;
108
- }
109
- }
110
- var str = stringify(value);
111
- if (names.size) {
112
- var params_1 = [];
113
- var statements_1 = [];
114
- var values_1 = [];
115
- names.forEach(function (name, thing) {
116
- params_1.push(name);
117
- if (isPrimitive(thing)) {
118
- values_1.push(stringifyPrimitive(thing));
119
- return;
120
- }
121
- var type = getType(thing);
122
- switch (type) {
123
- case 'Number':
124
- case 'String':
125
- case 'Boolean':
126
- values_1.push("Object(" + stringify(thing.valueOf()) + ")");
127
- break;
128
- case 'RegExp':
129
- values_1.push(thing.toString());
130
- break;
131
- case 'Date':
132
- values_1.push("new Date(" + thing.getTime() + ")");
133
- break;
134
- case 'Array':
135
- values_1.push("Array(" + thing.length + ")");
136
- thing.forEach(function (v, i) {
137
- statements_1.push(name + "[" + i + "]=" + stringify(v));
138
- });
139
- break;
140
- case 'Set':
141
- values_1.push("new Set");
142
- statements_1.push(name + "." + Array.from(thing).map(function (v) { return "add(" + stringify(v) + ")"; }).join('.'));
143
- break;
144
- case 'Map':
145
- values_1.push("new Map");
146
- statements_1.push(name + "." + Array.from(thing).map(function (_a) {
147
- var k = _a[0], v = _a[1];
148
- return "set(" + stringify(k) + ", " + stringify(v) + ")";
149
- }).join('.'));
150
- break;
151
- default:
152
- values_1.push(Object.getPrototypeOf(thing) === null ? 'Object.create(null)' : '{}');
153
- Object.keys(thing).forEach(function (key) {
154
- statements_1.push("" + name + safeProp(key) + "=" + stringify(thing[key]));
155
- });
156
- }
157
- });
158
- statements_1.push("return " + str);
159
- return "(function(" + params_1.join(',') + "){" + statements_1.join(';') + "}(" + values_1.join(',') + "))";
160
- }
161
- else {
162
- return str;
163
- }
164
- }
165
- function getName(num) {
166
- var name = '';
167
- do {
168
- name = chars[num % chars.length] + name;
169
- num = ~~(num / chars.length) - 1;
170
- } while (num >= 0);
171
- return reserved.test(name) ? name + "_" : name;
172
- }
173
- function isPrimitive(thing) {
174
- return Object(thing) !== thing;
175
- }
176
- function stringifyPrimitive(thing) {
177
- if (typeof thing === 'string')
178
- return stringifyString(thing);
179
- if (thing === void 0)
180
- return 'void 0';
181
- if (thing === 0 && 1 / thing < 0)
182
- return '-0';
183
- var str = String(thing);
184
- if (typeof thing === 'number')
185
- return str.replace(/^(-)?0\./, '$1.');
186
- return str;
187
- }
188
- function getType(thing) {
189
- return Object.prototype.toString.call(thing).slice(8, -1);
190
- }
191
- function escapeUnsafeChar(c) {
192
- return escaped[c] || c;
193
- }
194
- function escapeUnsafeChars(str) {
195
- return str.replace(unsafeChars, escapeUnsafeChar);
196
- }
197
- function safeKey(key) {
198
- return /^[_$a-zA-Z][_$a-zA-Z0-9]*$/.test(key) ? key : escapeUnsafeChars(JSON.stringify(key));
199
- }
200
- function safeProp(key) {
201
- return /^[_$a-zA-Z][_$a-zA-Z0-9]*$/.test(key) ? "." + key : "[" + escapeUnsafeChars(JSON.stringify(key)) + "]";
202
- }
203
- function stringifyString(str) {
204
- var result = '"';
205
- for (var i = 0; i < str.length; i += 1) {
206
- var char = str.charAt(i);
207
- var code = char.charCodeAt(0);
208
- if (char === '"') {
209
- result += '\\"';
210
- }
211
- else if (char in escaped) {
212
- result += escaped[char];
213
- }
214
- else if (code >= 0xd800 && code <= 0xdfff) {
215
- var next = str.charCodeAt(i + 1);
216
- // If this is the beginning of a [high, low] surrogate pair,
217
- // add the next two characters, otherwise escape
218
- if (code <= 0xdbff && (next >= 0xdc00 && next <= 0xdfff)) {
219
- result += char + str[++i];
220
- }
221
- else {
222
- result += "\\u" + code.toString(16).toUpperCase();
223
- }
224
- }
225
- else {
226
- result += char;
227
- }
228
- }
229
- result += '"';
230
- return result;
231
- }
232
-
233
- // Based on https://github.com/tmpvar/jsdom/blob/aa85b2abf07766ff7bf5c1f6daafb3726f2f2db5/lib/jsdom/living/blob.js
234
-
235
- // fix for "Readable" isn't a named export issue
236
- const Readable = Stream.Readable;
237
-
238
- const BUFFER = Symbol('buffer');
239
- const TYPE = Symbol('type');
240
-
241
- class Blob {
242
- constructor() {
243
- this[TYPE] = '';
244
-
245
- const blobParts = arguments[0];
246
- const options = arguments[1];
247
-
248
- const buffers = [];
249
- let size = 0;
250
-
251
- if (blobParts) {
252
- const a = blobParts;
253
- const length = Number(a.length);
254
- for (let i = 0; i < length; i++) {
255
- const element = a[i];
256
- let buffer;
257
- if (element instanceof Buffer) {
258
- buffer = element;
259
- } else if (ArrayBuffer.isView(element)) {
260
- buffer = Buffer.from(element.buffer, element.byteOffset, element.byteLength);
261
- } else if (element instanceof ArrayBuffer) {
262
- buffer = Buffer.from(element);
263
- } else if (element instanceof Blob) {
264
- buffer = element[BUFFER];
265
- } else {
266
- buffer = Buffer.from(typeof element === 'string' ? element : String(element));
267
- }
268
- size += buffer.length;
269
- buffers.push(buffer);
270
- }
271
- }
272
-
273
- this[BUFFER] = Buffer.concat(buffers);
274
-
275
- let type = options && options.type !== undefined && String(options.type).toLowerCase();
276
- if (type && !/[^\u0020-\u007E]/.test(type)) {
277
- this[TYPE] = type;
278
- }
279
- }
280
- get size() {
281
- return this[BUFFER].length;
282
- }
283
- get type() {
284
- return this[TYPE];
285
- }
286
- text() {
287
- return Promise.resolve(this[BUFFER].toString());
288
- }
289
- arrayBuffer() {
290
- const buf = this[BUFFER];
291
- const ab = buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength);
292
- return Promise.resolve(ab);
293
- }
294
- stream() {
295
- const readable = new Readable();
296
- readable._read = function () {};
297
- readable.push(this[BUFFER]);
298
- readable.push(null);
299
- return readable;
300
- }
301
- toString() {
302
- return '[object Blob]';
303
- }
304
- slice() {
305
- const size = this.size;
306
-
307
- const start = arguments[0];
308
- const end = arguments[1];
309
- let relativeStart, relativeEnd;
310
- if (start === undefined) {
311
- relativeStart = 0;
312
- } else if (start < 0) {
313
- relativeStart = Math.max(size + start, 0);
314
- } else {
315
- relativeStart = Math.min(start, size);
316
- }
317
- if (end === undefined) {
318
- relativeEnd = size;
319
- } else if (end < 0) {
320
- relativeEnd = Math.max(size + end, 0);
321
- } else {
322
- relativeEnd = Math.min(end, size);
323
- }
324
- const span = Math.max(relativeEnd - relativeStart, 0);
325
-
326
- const buffer = this[BUFFER];
327
- const slicedBuffer = buffer.slice(relativeStart, relativeStart + span);
328
- const blob = new Blob([], { type: arguments[2] });
329
- blob[BUFFER] = slicedBuffer;
330
- return blob;
331
- }
332
- }
333
-
334
- Object.defineProperties(Blob.prototype, {
335
- size: { enumerable: true },
336
- type: { enumerable: true },
337
- slice: { enumerable: true }
338
- });
339
-
340
- Object.defineProperty(Blob.prototype, Symbol.toStringTag, {
341
- value: 'Blob',
342
- writable: false,
343
- enumerable: false,
344
- configurable: true
345
- });
346
-
347
- /**
348
- * fetch-error.js
349
- *
350
- * FetchError interface for operational errors
351
- */
352
-
353
- /**
354
- * Create FetchError instance
355
- *
356
- * @param String message Error message for human
357
- * @param String type Error type for machine
358
- * @param String systemError For Node.js system error
359
- * @return FetchError
360
- */
361
- function FetchError(message, type, systemError) {
362
- Error.call(this, message);
363
-
364
- this.message = message;
365
- this.type = type;
366
-
367
- // when err.type is `system`, err.code contains system error code
368
- if (systemError) {
369
- this.code = this.errno = systemError.code;
370
- }
371
-
372
- // hide custom error implementation details from end-users
373
- Error.captureStackTrace(this, this.constructor);
374
- }
375
-
376
- FetchError.prototype = Object.create(Error.prototype);
377
- FetchError.prototype.constructor = FetchError;
378
- FetchError.prototype.name = 'FetchError';
379
-
380
- let convert;
381
- try {
382
- convert = require('encoding').convert;
383
- } catch (e) {}
384
-
385
- const INTERNALS = Symbol('Body internals');
386
-
387
- // fix an issue where "PassThrough" isn't a named export for node <10
388
- const PassThrough = Stream.PassThrough;
389
-
390
- /**
391
- * Body mixin
392
- *
393
- * Ref: https://fetch.spec.whatwg.org/#body
394
- *
395
- * @param Stream body Readable stream
396
- * @param Object opts Response options
397
- * @return Void
398
- */
399
- function Body(body) {
400
- var _this = this;
401
-
402
- var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {},
403
- _ref$size = _ref.size;
404
-
405
- let size = _ref$size === undefined ? 0 : _ref$size;
406
- var _ref$timeout = _ref.timeout;
407
- let timeout = _ref$timeout === undefined ? 0 : _ref$timeout;
408
-
409
- if (body == null) {
410
- // body is undefined or null
411
- body = null;
412
- } else if (isURLSearchParams(body)) {
413
- // body is a URLSearchParams
414
- body = Buffer.from(body.toString());
415
- } else if (isBlob(body)) ; else if (Buffer.isBuffer(body)) ; else if (Object.prototype.toString.call(body) === '[object ArrayBuffer]') {
416
- // body is ArrayBuffer
417
- body = Buffer.from(body);
418
- } else if (ArrayBuffer.isView(body)) {
419
- // body is ArrayBufferView
420
- body = Buffer.from(body.buffer, body.byteOffset, body.byteLength);
421
- } else if (body instanceof Stream) ; else {
422
- // none of the above
423
- // coerce to string then buffer
424
- body = Buffer.from(String(body));
425
- }
426
- this[INTERNALS] = {
427
- body,
428
- disturbed: false,
429
- error: null
430
- };
431
- this.size = size;
432
- this.timeout = timeout;
433
-
434
- if (body instanceof Stream) {
435
- body.on('error', function (err) {
436
- const error = err.name === 'AbortError' ? err : new FetchError(`Invalid response body while trying to fetch ${_this.url}: ${err.message}`, 'system', err);
437
- _this[INTERNALS].error = error;
438
- });
439
- }
440
- }
441
-
442
- Body.prototype = {
443
- get body() {
444
- return this[INTERNALS].body;
445
- },
446
-
447
- get bodyUsed() {
448
- return this[INTERNALS].disturbed;
449
- },
450
-
451
- /**
452
- * Decode response as ArrayBuffer
453
- *
454
- * @return Promise
455
- */
456
- arrayBuffer() {
457
- return consumeBody.call(this).then(function (buf) {
458
- return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength);
459
- });
460
- },
461
-
462
- /**
463
- * Return raw response as Blob
464
- *
465
- * @return Promise
466
- */
467
- blob() {
468
- let ct = this.headers && this.headers.get('content-type') || '';
469
- return consumeBody.call(this).then(function (buf) {
470
- return Object.assign(
471
- // Prevent copying
472
- new Blob([], {
473
- type: ct.toLowerCase()
474
- }), {
475
- [BUFFER]: buf
476
- });
477
- });
478
- },
479
-
480
- /**
481
- * Decode response as json
482
- *
483
- * @return Promise
484
- */
485
- json() {
486
- var _this2 = this;
487
-
488
- return consumeBody.call(this).then(function (buffer) {
489
- try {
490
- return JSON.parse(buffer.toString());
491
- } catch (err) {
492
- return Body.Promise.reject(new FetchError(`invalid json response body at ${_this2.url} reason: ${err.message}`, 'invalid-json'));
493
- }
494
- });
495
- },
496
-
497
- /**
498
- * Decode response as text
499
- *
500
- * @return Promise
501
- */
502
- text() {
503
- return consumeBody.call(this).then(function (buffer) {
504
- return buffer.toString();
505
- });
506
- },
507
-
508
- /**
509
- * Decode response as buffer (non-spec api)
510
- *
511
- * @return Promise
512
- */
513
- buffer() {
514
- return consumeBody.call(this);
515
- },
516
-
517
- /**
518
- * Decode response as text, while automatically detecting the encoding and
519
- * trying to decode to UTF-8 (non-spec api)
520
- *
521
- * @return Promise
522
- */
523
- textConverted() {
524
- var _this3 = this;
525
-
526
- return consumeBody.call(this).then(function (buffer) {
527
- return convertBody(buffer, _this3.headers);
528
- });
529
- }
530
- };
531
-
532
- // In browsers, all properties are enumerable.
533
- Object.defineProperties(Body.prototype, {
534
- body: { enumerable: true },
535
- bodyUsed: { enumerable: true },
536
- arrayBuffer: { enumerable: true },
537
- blob: { enumerable: true },
538
- json: { enumerable: true },
539
- text: { enumerable: true }
540
- });
541
-
542
- Body.mixIn = function (proto) {
543
- for (const name of Object.getOwnPropertyNames(Body.prototype)) {
544
- // istanbul ignore else: future proof
545
- if (!(name in proto)) {
546
- const desc = Object.getOwnPropertyDescriptor(Body.prototype, name);
547
- Object.defineProperty(proto, name, desc);
548
- }
549
- }
550
- };
551
-
552
- /**
553
- * Consume and convert an entire Body to a Buffer.
554
- *
555
- * Ref: https://fetch.spec.whatwg.org/#concept-body-consume-body
556
- *
557
- * @return Promise
558
- */
559
- function consumeBody() {
560
- var _this4 = this;
561
-
562
- if (this[INTERNALS].disturbed) {
563
- return Body.Promise.reject(new TypeError(`body used already for: ${this.url}`));
564
- }
565
-
566
- this[INTERNALS].disturbed = true;
567
-
568
- if (this[INTERNALS].error) {
569
- return Body.Promise.reject(this[INTERNALS].error);
570
- }
571
-
572
- let body = this.body;
573
-
574
- // body is null
575
- if (body === null) {
576
- return Body.Promise.resolve(Buffer.alloc(0));
577
- }
578
-
579
- // body is blob
580
- if (isBlob(body)) {
581
- body = body.stream();
582
- }
583
-
584
- // body is buffer
585
- if (Buffer.isBuffer(body)) {
586
- return Body.Promise.resolve(body);
587
- }
588
-
589
- // istanbul ignore if: should never happen
590
- if (!(body instanceof Stream)) {
591
- return Body.Promise.resolve(Buffer.alloc(0));
592
- }
593
-
594
- // body is stream
595
- // get ready to actually consume the body
596
- let accum = [];
597
- let accumBytes = 0;
598
- let abort = false;
599
-
600
- return new Body.Promise(function (resolve, reject) {
601
- let resTimeout;
602
-
603
- // allow timeout on slow response body
604
- if (_this4.timeout) {
605
- resTimeout = setTimeout(function () {
606
- abort = true;
607
- reject(new FetchError(`Response timeout while trying to fetch ${_this4.url} (over ${_this4.timeout}ms)`, 'body-timeout'));
608
- }, _this4.timeout);
609
- }
610
-
611
- // handle stream errors
612
- body.on('error', function (err) {
613
- if (err.name === 'AbortError') {
614
- // if the request was aborted, reject with this Error
615
- abort = true;
616
- reject(err);
617
- } else {
618
- // other errors, such as incorrect content-encoding
619
- reject(new FetchError(`Invalid response body while trying to fetch ${_this4.url}: ${err.message}`, 'system', err));
620
- }
621
- });
622
-
623
- body.on('data', function (chunk) {
624
- if (abort || chunk === null) {
625
- return;
626
- }
627
-
628
- if (_this4.size && accumBytes + chunk.length > _this4.size) {
629
- abort = true;
630
- reject(new FetchError(`content size at ${_this4.url} over limit: ${_this4.size}`, 'max-size'));
631
- return;
632
- }
633
-
634
- accumBytes += chunk.length;
635
- accum.push(chunk);
636
- });
637
-
638
- body.on('end', function () {
639
- if (abort) {
640
- return;
641
- }
642
-
643
- clearTimeout(resTimeout);
644
-
645
- try {
646
- resolve(Buffer.concat(accum, accumBytes));
647
- } catch (err) {
648
- // handle streams that have accumulated too much data (issue #414)
649
- reject(new FetchError(`Could not create Buffer from response body for ${_this4.url}: ${err.message}`, 'system', err));
650
- }
651
- });
652
- });
653
- }
654
-
655
- /**
656
- * Detect buffer encoding and convert to target encoding
657
- * ref: http://www.w3.org/TR/2011/WD-html5-20110113/parsing.html#determining-the-character-encoding
658
- *
659
- * @param Buffer buffer Incoming buffer
660
- * @param String encoding Target encoding
661
- * @return String
662
- */
663
- function convertBody(buffer, headers) {
664
- if (typeof convert !== 'function') {
665
- throw new Error('The package `encoding` must be installed to use the textConverted() function');
666
- }
667
-
668
- const ct = headers.get('content-type');
669
- let charset = 'utf-8';
670
- let res, str;
671
-
672
- // header
673
- if (ct) {
674
- res = /charset=([^;]*)/i.exec(ct);
675
- }
676
-
677
- // no charset in content type, peek at response body for at most 1024 bytes
678
- str = buffer.slice(0, 1024).toString();
679
-
680
- // html5
681
- if (!res && str) {
682
- res = /<meta.+?charset=(['"])(.+?)\1/i.exec(str);
683
- }
684
-
685
- // html4
686
- if (!res && str) {
687
- res = /<meta[\s]+?http-equiv=(['"])content-type\1[\s]+?content=(['"])(.+?)\2/i.exec(str);
688
- if (!res) {
689
- res = /<meta[\s]+?content=(['"])(.+?)\1[\s]+?http-equiv=(['"])content-type\3/i.exec(str);
690
- if (res) {
691
- res.pop(); // drop last quote
692
- }
693
- }
694
-
695
- if (res) {
696
- res = /charset=(.*)/i.exec(res.pop());
697
- }
698
- }
699
-
700
- // xml
701
- if (!res && str) {
702
- res = /<\?xml.+?encoding=(['"])(.+?)\1/i.exec(str);
703
- }
704
-
705
- // found charset
706
- if (res) {
707
- charset = res.pop();
708
-
709
- // prevent decode issues when sites use incorrect encoding
710
- // ref: https://hsivonen.fi/encoding-menu/
711
- if (charset === 'gb2312' || charset === 'gbk') {
712
- charset = 'gb18030';
713
- }
714
- }
715
-
716
- // turn raw buffers into a single utf-8 buffer
717
- return convert(buffer, 'UTF-8', charset).toString();
718
- }
719
-
720
- /**
721
- * Detect a URLSearchParams object
722
- * ref: https://github.com/bitinn/node-fetch/issues/296#issuecomment-307598143
723
- *
724
- * @param Object obj Object to detect by type or brand
725
- * @return String
726
- */
727
- function isURLSearchParams(obj) {
728
- // Duck-typing as a necessary condition.
729
- if (typeof obj !== 'object' || typeof obj.append !== 'function' || typeof obj.delete !== 'function' || typeof obj.get !== 'function' || typeof obj.getAll !== 'function' || typeof obj.has !== 'function' || typeof obj.set !== 'function') {
730
- return false;
731
- }
732
-
733
- // Brand-checking and more duck-typing as optional condition.
734
- return obj.constructor.name === 'URLSearchParams' || Object.prototype.toString.call(obj) === '[object URLSearchParams]' || typeof obj.sort === 'function';
735
- }
736
-
737
- /**
738
- * Check if `obj` is a W3C `Blob` object (which `File` inherits from)
739
- * @param {*} obj
740
- * @return {boolean}
741
- */
742
- function isBlob(obj) {
743
- return typeof obj === 'object' && typeof obj.arrayBuffer === 'function' && typeof obj.type === 'string' && typeof obj.stream === 'function' && typeof obj.constructor === 'function' && typeof obj.constructor.name === 'string' && /^(Blob|File)$/.test(obj.constructor.name) && /^(Blob|File)$/.test(obj[Symbol.toStringTag]);
744
- }
745
-
746
- /**
747
- * Clone body given Res/Req instance
748
- *
749
- * @param Mixed instance Response or Request instance
750
- * @return Mixed
751
- */
752
- function clone(instance) {
753
- let p1, p2;
754
- let body = instance.body;
755
-
756
- // don't allow cloning a used body
757
- if (instance.bodyUsed) {
758
- throw new Error('cannot clone body after it is used');
759
- }
760
-
761
- // check that body is a stream and not form-data object
762
- // note: we can't clone the form-data object without having it as a dependency
763
- if (body instanceof Stream && typeof body.getBoundary !== 'function') {
764
- // tee instance body
765
- p1 = new PassThrough();
766
- p2 = new PassThrough();
767
- body.pipe(p1);
768
- body.pipe(p2);
769
- // set instance body to teed body and return the other teed body
770
- instance[INTERNALS].body = p1;
771
- body = p2;
772
- }
773
-
774
- return body;
775
- }
776
-
777
- /**
778
- * Performs the operation "extract a `Content-Type` value from |object|" as
779
- * specified in the specification:
780
- * https://fetch.spec.whatwg.org/#concept-bodyinit-extract
781
- *
782
- * This function assumes that instance.body is present.
783
- *
784
- * @param Mixed instance Any options.body input
785
- */
786
- function extractContentType(body) {
787
- if (body === null) {
788
- // body is null
789
- return null;
790
- } else if (typeof body === 'string') {
791
- // body is string
792
- return 'text/plain;charset=UTF-8';
793
- } else if (isURLSearchParams(body)) {
794
- // body is a URLSearchParams
795
- return 'application/x-www-form-urlencoded;charset=UTF-8';
796
- } else if (isBlob(body)) {
797
- // body is blob
798
- return body.type || null;
799
- } else if (Buffer.isBuffer(body)) {
800
- // body is buffer
801
- return null;
802
- } else if (Object.prototype.toString.call(body) === '[object ArrayBuffer]') {
803
- // body is ArrayBuffer
804
- return null;
805
- } else if (ArrayBuffer.isView(body)) {
806
- // body is ArrayBufferView
807
- return null;
808
- } else if (typeof body.getBoundary === 'function') {
809
- // detect form data input from form-data module
810
- return `multipart/form-data;boundary=${body.getBoundary()}`;
811
- } else if (body instanceof Stream) {
812
- // body is stream
813
- // can't really do much about this
814
- return null;
815
- } else {
816
- // Body constructor defaults other things to string
817
- return 'text/plain;charset=UTF-8';
818
- }
819
- }
820
-
821
- /**
822
- * The Fetch Standard treats this as if "total bytes" is a property on the body.
823
- * For us, we have to explicitly get it with a function.
824
- *
825
- * ref: https://fetch.spec.whatwg.org/#concept-body-total-bytes
826
- *
827
- * @param Body instance Instance of Body
828
- * @return Number? Number of bytes, or null if not possible
829
- */
830
- function getTotalBytes(instance) {
831
- const body = instance.body;
832
-
833
-
834
- if (body === null) {
835
- // body is null
836
- return 0;
837
- } else if (isBlob(body)) {
838
- return body.size;
839
- } else if (Buffer.isBuffer(body)) {
840
- // body is buffer
841
- return body.length;
842
- } else if (body && typeof body.getLengthSync === 'function') {
843
- // detect form data input from form-data module
844
- if (body._lengthRetrievers && body._lengthRetrievers.length == 0 || // 1.x
845
- body.hasKnownLength && body.hasKnownLength()) {
846
- // 2.x
847
- return body.getLengthSync();
848
- }
849
- return null;
850
- } else {
851
- // body is stream
852
- return null;
853
- }
854
- }
855
-
856
- /**
857
- * Write a Body to a Node.js WritableStream (e.g. http.Request) object.
858
- *
859
- * @param Body instance Instance of Body
860
- * @return Void
861
- */
862
- function writeToStream(dest, instance) {
863
- const body = instance.body;
864
-
865
-
866
- if (body === null) {
867
- // body is null
868
- dest.end();
869
- } else if (isBlob(body)) {
870
- body.stream().pipe(dest);
871
- } else if (Buffer.isBuffer(body)) {
872
- // body is buffer
873
- dest.write(body);
874
- dest.end();
875
- } else {
876
- // body is stream
877
- body.pipe(dest);
878
- }
879
- }
880
-
881
- // expose Promise
882
- Body.Promise = global.Promise;
883
-
884
- /**
885
- * headers.js
886
- *
887
- * Headers class offers convenient helpers
888
- */
889
-
890
- const invalidTokenRegex = /[^\^_`a-zA-Z\-0-9!#$%&'*+.|~]/;
891
- const invalidHeaderCharRegex = /[^\t\x20-\x7e\x80-\xff]/;
892
-
893
- function validateName(name) {
894
- name = `${name}`;
895
- if (invalidTokenRegex.test(name) || name === '') {
896
- throw new TypeError(`${name} is not a legal HTTP header name`);
897
- }
898
- }
899
-
900
- function validateValue(value) {
901
- value = `${value}`;
902
- if (invalidHeaderCharRegex.test(value)) {
903
- throw new TypeError(`${value} is not a legal HTTP header value`);
904
- }
905
- }
906
-
907
- /**
908
- * Find the key in the map object given a header name.
909
- *
910
- * Returns undefined if not found.
911
- *
912
- * @param String name Header name
913
- * @return String|Undefined
914
- */
915
- function find(map, name) {
916
- name = name.toLowerCase();
917
- for (const key in map) {
918
- if (key.toLowerCase() === name) {
919
- return key;
920
- }
921
- }
922
- return undefined;
923
- }
924
-
925
- const MAP = Symbol('map');
926
- class Headers {
927
- /**
928
- * Headers class
929
- *
930
- * @param Object headers Response headers
931
- * @return Void
932
- */
933
- constructor() {
934
- let init = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : undefined;
935
-
936
- this[MAP] = Object.create(null);
937
-
938
- if (init instanceof Headers) {
939
- const rawHeaders = init.raw();
940
- const headerNames = Object.keys(rawHeaders);
941
-
942
- for (const headerName of headerNames) {
943
- for (const value of rawHeaders[headerName]) {
944
- this.append(headerName, value);
945
- }
946
- }
947
-
948
- return;
949
- }
950
-
951
- // We don't worry about converting prop to ByteString here as append()
952
- // will handle it.
953
- if (init == null) ; else if (typeof init === 'object') {
954
- const method = init[Symbol.iterator];
955
- if (method != null) {
956
- if (typeof method !== 'function') {
957
- throw new TypeError('Header pairs must be iterable');
958
- }
959
-
960
- // sequence<sequence<ByteString>>
961
- // Note: per spec we have to first exhaust the lists then process them
962
- const pairs = [];
963
- for (const pair of init) {
964
- if (typeof pair !== 'object' || typeof pair[Symbol.iterator] !== 'function') {
965
- throw new TypeError('Each header pair must be iterable');
966
- }
967
- pairs.push(Array.from(pair));
968
- }
969
-
970
- for (const pair of pairs) {
971
- if (pair.length !== 2) {
972
- throw new TypeError('Each header pair must be a name/value tuple');
973
- }
974
- this.append(pair[0], pair[1]);
975
- }
976
- } else {
977
- // record<ByteString, ByteString>
978
- for (const key of Object.keys(init)) {
979
- const value = init[key];
980
- this.append(key, value);
981
- }
982
- }
983
- } else {
984
- throw new TypeError('Provided initializer must be an object');
985
- }
986
- }
987
-
988
- /**
989
- * Return combined header value given name
990
- *
991
- * @param String name Header name
992
- * @return Mixed
993
- */
994
- get(name) {
995
- name = `${name}`;
996
- validateName(name);
997
- const key = find(this[MAP], name);
998
- if (key === undefined) {
999
- return null;
1000
- }
1001
-
1002
- return this[MAP][key].join(', ');
1003
- }
1004
-
1005
- /**
1006
- * Iterate over all headers
1007
- *
1008
- * @param Function callback Executed for each item with parameters (value, name, thisArg)
1009
- * @param Boolean thisArg `this` context for callback function
1010
- * @return Void
1011
- */
1012
- forEach(callback) {
1013
- let thisArg = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : undefined;
1014
-
1015
- let pairs = getHeaders(this);
1016
- let i = 0;
1017
- while (i < pairs.length) {
1018
- var _pairs$i = pairs[i];
1019
- const name = _pairs$i[0],
1020
- value = _pairs$i[1];
1021
-
1022
- callback.call(thisArg, value, name, this);
1023
- pairs = getHeaders(this);
1024
- i++;
1025
- }
1026
- }
1027
-
1028
- /**
1029
- * Overwrite header values given name
1030
- *
1031
- * @param String name Header name
1032
- * @param String value Header value
1033
- * @return Void
1034
- */
1035
- set(name, value) {
1036
- name = `${name}`;
1037
- value = `${value}`;
1038
- validateName(name);
1039
- validateValue(value);
1040
- const key = find(this[MAP], name);
1041
- this[MAP][key !== undefined ? key : name] = [value];
1042
- }
1043
-
1044
- /**
1045
- * Append a value onto existing header
1046
- *
1047
- * @param String name Header name
1048
- * @param String value Header value
1049
- * @return Void
1050
- */
1051
- append(name, value) {
1052
- name = `${name}`;
1053
- value = `${value}`;
1054
- validateName(name);
1055
- validateValue(value);
1056
- const key = find(this[MAP], name);
1057
- if (key !== undefined) {
1058
- this[MAP][key].push(value);
1059
- } else {
1060
- this[MAP][name] = [value];
1061
- }
1062
- }
1063
-
1064
- /**
1065
- * Check for header name existence
1066
- *
1067
- * @param String name Header name
1068
- * @return Boolean
1069
- */
1070
- has(name) {
1071
- name = `${name}`;
1072
- validateName(name);
1073
- return find(this[MAP], name) !== undefined;
1074
- }
1075
-
1076
- /**
1077
- * Delete all header values given name
1078
- *
1079
- * @param String name Header name
1080
- * @return Void
1081
- */
1082
- delete(name) {
1083
- name = `${name}`;
1084
- validateName(name);
1085
- const key = find(this[MAP], name);
1086
- if (key !== undefined) {
1087
- delete this[MAP][key];
1088
- }
1089
- }
1090
-
1091
- /**
1092
- * Return raw headers (non-spec api)
1093
- *
1094
- * @return Object
1095
- */
1096
- raw() {
1097
- return this[MAP];
1098
- }
1099
-
1100
- /**
1101
- * Get an iterator on keys.
1102
- *
1103
- * @return Iterator
1104
- */
1105
- keys() {
1106
- return createHeadersIterator(this, 'key');
1107
- }
1108
-
1109
- /**
1110
- * Get an iterator on values.
1111
- *
1112
- * @return Iterator
1113
- */
1114
- values() {
1115
- return createHeadersIterator(this, 'value');
1116
- }
1117
-
1118
- /**
1119
- * Get an iterator on entries.
1120
- *
1121
- * This is the default iterator of the Headers object.
1122
- *
1123
- * @return Iterator
1124
- */
1125
- [Symbol.iterator]() {
1126
- return createHeadersIterator(this, 'key+value');
1127
- }
1128
- }
1129
- Headers.prototype.entries = Headers.prototype[Symbol.iterator];
1130
-
1131
- Object.defineProperty(Headers.prototype, Symbol.toStringTag, {
1132
- value: 'Headers',
1133
- writable: false,
1134
- enumerable: false,
1135
- configurable: true
1136
- });
1137
-
1138
- Object.defineProperties(Headers.prototype, {
1139
- get: { enumerable: true },
1140
- forEach: { enumerable: true },
1141
- set: { enumerable: true },
1142
- append: { enumerable: true },
1143
- has: { enumerable: true },
1144
- delete: { enumerable: true },
1145
- keys: { enumerable: true },
1146
- values: { enumerable: true },
1147
- entries: { enumerable: true }
1148
- });
1149
-
1150
- function getHeaders(headers) {
1151
- let kind = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'key+value';
1152
-
1153
- const keys = Object.keys(headers[MAP]).sort();
1154
- return keys.map(kind === 'key' ? function (k) {
1155
- return k.toLowerCase();
1156
- } : kind === 'value' ? function (k) {
1157
- return headers[MAP][k].join(', ');
1158
- } : function (k) {
1159
- return [k.toLowerCase(), headers[MAP][k].join(', ')];
1160
- });
1161
- }
1162
-
1163
- const INTERNAL = Symbol('internal');
1164
-
1165
- function createHeadersIterator(target, kind) {
1166
- const iterator = Object.create(HeadersIteratorPrototype);
1167
- iterator[INTERNAL] = {
1168
- target,
1169
- kind,
1170
- index: 0
1171
- };
1172
- return iterator;
1173
- }
1174
-
1175
- const HeadersIteratorPrototype = Object.setPrototypeOf({
1176
- next() {
1177
- // istanbul ignore if
1178
- if (!this || Object.getPrototypeOf(this) !== HeadersIteratorPrototype) {
1179
- throw new TypeError('Value of `this` is not a HeadersIterator');
1180
- }
1181
-
1182
- var _INTERNAL = this[INTERNAL];
1183
- const target = _INTERNAL.target,
1184
- kind = _INTERNAL.kind,
1185
- index = _INTERNAL.index;
1186
-
1187
- const values = getHeaders(target, kind);
1188
- const len = values.length;
1189
- if (index >= len) {
1190
- return {
1191
- value: undefined,
1192
- done: true
1193
- };
1194
- }
1195
-
1196
- this[INTERNAL].index = index + 1;
1197
-
1198
- return {
1199
- value: values[index],
1200
- done: false
1201
- };
1202
- }
1203
- }, Object.getPrototypeOf(Object.getPrototypeOf([][Symbol.iterator]())));
1204
-
1205
- Object.defineProperty(HeadersIteratorPrototype, Symbol.toStringTag, {
1206
- value: 'HeadersIterator',
1207
- writable: false,
1208
- enumerable: false,
1209
- configurable: true
1210
- });
1211
-
1212
- /**
1213
- * Export the Headers object in a form that Node.js can consume.
1214
- *
1215
- * @param Headers headers
1216
- * @return Object
1217
- */
1218
- function exportNodeCompatibleHeaders(headers) {
1219
- const obj = Object.assign({ __proto__: null }, headers[MAP]);
1220
-
1221
- // http.request() only supports string as Host header. This hack makes
1222
- // specifying custom Host header possible.
1223
- const hostHeaderKey = find(headers[MAP], 'Host');
1224
- if (hostHeaderKey !== undefined) {
1225
- obj[hostHeaderKey] = obj[hostHeaderKey][0];
1226
- }
1227
-
1228
- return obj;
1229
- }
1230
-
1231
- /**
1232
- * Create a Headers object from an object of headers, ignoring those that do
1233
- * not conform to HTTP grammar productions.
1234
- *
1235
- * @param Object obj Object of headers
1236
- * @return Headers
1237
- */
1238
- function createHeadersLenient(obj) {
1239
- const headers = new Headers();
1240
- for (const name of Object.keys(obj)) {
1241
- if (invalidTokenRegex.test(name)) {
1242
- continue;
1243
- }
1244
- if (Array.isArray(obj[name])) {
1245
- for (const val of obj[name]) {
1246
- if (invalidHeaderCharRegex.test(val)) {
1247
- continue;
1248
- }
1249
- if (headers[MAP][name] === undefined) {
1250
- headers[MAP][name] = [val];
1251
- } else {
1252
- headers[MAP][name].push(val);
1253
- }
1254
- }
1255
- } else if (!invalidHeaderCharRegex.test(obj[name])) {
1256
- headers[MAP][name] = [obj[name]];
1257
- }
1258
- }
1259
- return headers;
1260
- }
1261
-
1262
- const INTERNALS$1 = Symbol('Response internals');
1263
-
1264
- // fix an issue where "STATUS_CODES" aren't a named export for node <10
1265
- const STATUS_CODES = http.STATUS_CODES;
1266
-
1267
- /**
1268
- * Response class
1269
- *
1270
- * @param Stream body Readable stream
1271
- * @param Object opts Response options
1272
- * @return Void
1273
- */
1274
- class Response {
1275
- constructor() {
1276
- let body = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null;
1277
- let opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
1278
-
1279
- Body.call(this, body, opts);
1280
-
1281
- const status = opts.status || 200;
1282
- const headers = new Headers(opts.headers);
1283
-
1284
- if (body != null && !headers.has('Content-Type')) {
1285
- const contentType = extractContentType(body);
1286
- if (contentType) {
1287
- headers.append('Content-Type', contentType);
1288
- }
1289
- }
1290
-
1291
- this[INTERNALS$1] = {
1292
- url: opts.url,
1293
- status,
1294
- statusText: opts.statusText || STATUS_CODES[status],
1295
- headers,
1296
- counter: opts.counter
1297
- };
1298
- }
1299
-
1300
- get url() {
1301
- return this[INTERNALS$1].url || '';
1302
- }
1303
-
1304
- get status() {
1305
- return this[INTERNALS$1].status;
1306
- }
1307
-
1308
- /**
1309
- * Convenience property representing if the request ended normally
1310
- */
1311
- get ok() {
1312
- return this[INTERNALS$1].status >= 200 && this[INTERNALS$1].status < 300;
1313
- }
1314
-
1315
- get redirected() {
1316
- return this[INTERNALS$1].counter > 0;
1317
- }
1318
-
1319
- get statusText() {
1320
- return this[INTERNALS$1].statusText;
1321
- }
1322
-
1323
- get headers() {
1324
- return this[INTERNALS$1].headers;
1325
- }
1326
-
1327
- /**
1328
- * Clone this response
1329
- *
1330
- * @return Response
1331
- */
1332
- clone() {
1333
- return new Response(clone(this), {
1334
- url: this.url,
1335
- status: this.status,
1336
- statusText: this.statusText,
1337
- headers: this.headers,
1338
- ok: this.ok,
1339
- redirected: this.redirected
1340
- });
1341
- }
1342
- }
1343
-
1344
- Body.mixIn(Response.prototype);
1345
-
1346
- Object.defineProperties(Response.prototype, {
1347
- url: { enumerable: true },
1348
- status: { enumerable: true },
1349
- ok: { enumerable: true },
1350
- redirected: { enumerable: true },
1351
- statusText: { enumerable: true },
1352
- headers: { enumerable: true },
1353
- clone: { enumerable: true }
1354
- });
1355
-
1356
- Object.defineProperty(Response.prototype, Symbol.toStringTag, {
1357
- value: 'Response',
1358
- writable: false,
1359
- enumerable: false,
1360
- configurable: true
1361
- });
1362
-
1363
- const INTERNALS$2 = Symbol('Request internals');
1364
-
1365
- // fix an issue where "format", "parse" aren't a named export for node <10
1366
- const parse_url = Url.parse;
1367
- const format_url = Url.format;
1368
-
1369
- const streamDestructionSupported = 'destroy' in Stream.Readable.prototype;
1370
-
1371
- /**
1372
- * Check if a value is an instance of Request.
1373
- *
1374
- * @param Mixed input
1375
- * @return Boolean
1376
- */
1377
- function isRequest(input) {
1378
- return typeof input === 'object' && typeof input[INTERNALS$2] === 'object';
1379
- }
1380
-
1381
- function isAbortSignal(signal) {
1382
- const proto = signal && typeof signal === 'object' && Object.getPrototypeOf(signal);
1383
- return !!(proto && proto.constructor.name === 'AbortSignal');
1384
- }
1385
-
1386
- /**
1387
- * Request class
1388
- *
1389
- * @param Mixed input Url or Request instance
1390
- * @param Object init Custom options
1391
- * @return Void
1392
- */
1393
- class Request {
1394
- constructor(input) {
1395
- let init = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
1396
-
1397
- let parsedURL;
1398
-
1399
- // normalize input
1400
- if (!isRequest(input)) {
1401
- if (input && input.href) {
1402
- // in order to support Node.js' Url objects; though WHATWG's URL objects
1403
- // will fall into this branch also (since their `toString()` will return
1404
- // `href` property anyway)
1405
- parsedURL = parse_url(input.href);
1406
- } else {
1407
- // coerce input to a string before attempting to parse
1408
- parsedURL = parse_url(`${input}`);
1409
- }
1410
- input = {};
1411
- } else {
1412
- parsedURL = parse_url(input.url);
1413
- }
1414
-
1415
- let method = init.method || input.method || 'GET';
1416
- method = method.toUpperCase();
1417
-
1418
- if ((init.body != null || isRequest(input) && input.body !== null) && (method === 'GET' || method === 'HEAD')) {
1419
- throw new TypeError('Request with GET/HEAD method cannot have body');
1420
- }
1421
-
1422
- let inputBody = init.body != null ? init.body : isRequest(input) && input.body !== null ? clone(input) : null;
1423
-
1424
- Body.call(this, inputBody, {
1425
- timeout: init.timeout || input.timeout || 0,
1426
- size: init.size || input.size || 0
1427
- });
1428
-
1429
- const headers = new Headers(init.headers || input.headers || {});
1430
-
1431
- if (inputBody != null && !headers.has('Content-Type')) {
1432
- const contentType = extractContentType(inputBody);
1433
- if (contentType) {
1434
- headers.append('Content-Type', contentType);
1435
- }
1436
- }
1437
-
1438
- let signal = isRequest(input) ? input.signal : null;
1439
- if ('signal' in init) signal = init.signal;
1440
-
1441
- if (signal != null && !isAbortSignal(signal)) {
1442
- throw new TypeError('Expected signal to be an instanceof AbortSignal');
1443
- }
1444
-
1445
- this[INTERNALS$2] = {
1446
- method,
1447
- redirect: init.redirect || input.redirect || 'follow',
1448
- headers,
1449
- parsedURL,
1450
- signal
1451
- };
1452
-
1453
- // node-fetch-only options
1454
- this.follow = init.follow !== undefined ? init.follow : input.follow !== undefined ? input.follow : 20;
1455
- this.compress = init.compress !== undefined ? init.compress : input.compress !== undefined ? input.compress : true;
1456
- this.counter = init.counter || input.counter || 0;
1457
- this.agent = init.agent || input.agent;
1458
- }
1459
-
1460
- get method() {
1461
- return this[INTERNALS$2].method;
1462
- }
1463
-
1464
- get url() {
1465
- return format_url(this[INTERNALS$2].parsedURL);
1466
- }
1467
-
1468
- get headers() {
1469
- return this[INTERNALS$2].headers;
1470
- }
1471
-
1472
- get redirect() {
1473
- return this[INTERNALS$2].redirect;
1474
- }
1475
-
1476
- get signal() {
1477
- return this[INTERNALS$2].signal;
1478
- }
1479
-
1480
- /**
1481
- * Clone this request
1482
- *
1483
- * @return Request
1484
- */
1485
- clone() {
1486
- return new Request(this);
1487
- }
1488
- }
1489
-
1490
- Body.mixIn(Request.prototype);
1491
-
1492
- Object.defineProperty(Request.prototype, Symbol.toStringTag, {
1493
- value: 'Request',
1494
- writable: false,
1495
- enumerable: false,
1496
- configurable: true
1497
- });
1498
-
1499
- Object.defineProperties(Request.prototype, {
1500
- method: { enumerable: true },
1501
- url: { enumerable: true },
1502
- headers: { enumerable: true },
1503
- redirect: { enumerable: true },
1504
- clone: { enumerable: true },
1505
- signal: { enumerable: true }
1506
- });
1507
-
1508
- /**
1509
- * Convert a Request to Node.js http request options.
1510
- *
1511
- * @param Request A Request instance
1512
- * @return Object The options object to be passed to http.request
1513
- */
1514
- function getNodeRequestOptions(request) {
1515
- const parsedURL = request[INTERNALS$2].parsedURL;
1516
- const headers = new Headers(request[INTERNALS$2].headers);
1517
-
1518
- // fetch step 1.3
1519
- if (!headers.has('Accept')) {
1520
- headers.set('Accept', '*/*');
1521
- }
1522
-
1523
- // Basic fetch
1524
- if (!parsedURL.protocol || !parsedURL.hostname) {
1525
- throw new TypeError('Only absolute URLs are supported');
1526
- }
1527
-
1528
- if (!/^https?:$/.test(parsedURL.protocol)) {
1529
- throw new TypeError('Only HTTP(S) protocols are supported');
1530
- }
1531
-
1532
- if (request.signal && request.body instanceof Stream.Readable && !streamDestructionSupported) {
1533
- throw new Error('Cancellation of streamed requests with AbortSignal is not supported in node < 8');
1534
- }
1535
-
1536
- // HTTP-network-or-cache fetch steps 2.4-2.7
1537
- let contentLengthValue = null;
1538
- if (request.body == null && /^(POST|PUT)$/i.test(request.method)) {
1539
- contentLengthValue = '0';
1540
- }
1541
- if (request.body != null) {
1542
- const totalBytes = getTotalBytes(request);
1543
- if (typeof totalBytes === 'number') {
1544
- contentLengthValue = String(totalBytes);
1545
- }
1546
- }
1547
- if (contentLengthValue) {
1548
- headers.set('Content-Length', contentLengthValue);
1549
- }
1550
-
1551
- // HTTP-network-or-cache fetch step 2.11
1552
- if (!headers.has('User-Agent')) {
1553
- headers.set('User-Agent', 'node-fetch/1.0 (+https://github.com/bitinn/node-fetch)');
1554
- }
1555
-
1556
- // HTTP-network-or-cache fetch step 2.15
1557
- if (request.compress && !headers.has('Accept-Encoding')) {
1558
- headers.set('Accept-Encoding', 'gzip,deflate');
1559
- }
1560
-
1561
- let agent = request.agent;
1562
- if (typeof agent === 'function') {
1563
- agent = agent(parsedURL);
1564
- }
1565
-
1566
- if (!headers.has('Connection') && !agent) {
1567
- headers.set('Connection', 'close');
1568
- }
1569
-
1570
- // HTTP-network fetch step 4.2
1571
- // chunked encoding is handled by Node.js
1572
-
1573
- return Object.assign({}, parsedURL, {
1574
- method: request.method,
1575
- headers: exportNodeCompatibleHeaders(headers),
1576
- agent
1577
- });
1578
- }
1579
-
1580
- /**
1581
- * abort-error.js
1582
- *
1583
- * AbortError interface for cancelled requests
1584
- */
1585
-
1586
- /**
1587
- * Create AbortError instance
1588
- *
1589
- * @param String message Error message for human
1590
- * @return AbortError
1591
- */
1592
- function AbortError(message) {
1593
- Error.call(this, message);
1594
-
1595
- this.type = 'aborted';
1596
- this.message = message;
1597
-
1598
- // hide custom error implementation details from end-users
1599
- Error.captureStackTrace(this, this.constructor);
1600
- }
1601
-
1602
- AbortError.prototype = Object.create(Error.prototype);
1603
- AbortError.prototype.constructor = AbortError;
1604
- AbortError.prototype.name = 'AbortError';
1605
-
1606
- // fix an issue where "PassThrough", "resolve" aren't a named export for node <10
1607
- const PassThrough$1 = Stream.PassThrough;
1608
- const resolve_url = Url.resolve;
1609
-
1610
- /**
1611
- * Fetch function
1612
- *
1613
- * @param Mixed url Absolute url or Request instance
1614
- * @param Object opts Fetch options
1615
- * @return Promise
1616
- */
1617
- function fetch(url, opts) {
1618
-
1619
- // allow custom promise
1620
- if (!fetch.Promise) {
1621
- throw new Error('native promise missing, set fetch.Promise to your favorite alternative');
1622
- }
1623
-
1624
- Body.Promise = fetch.Promise;
1625
-
1626
- // wrap http.request into fetch
1627
- return new fetch.Promise(function (resolve, reject) {
1628
- // build request object
1629
- const request = new Request(url, opts);
1630
- const options = getNodeRequestOptions(request);
1631
-
1632
- const send = (options.protocol === 'https:' ? https : http).request;
1633
- const signal = request.signal;
1634
-
1635
- let response = null;
1636
-
1637
- const abort = function abort() {
1638
- let error = new AbortError('The user aborted a request.');
1639
- reject(error);
1640
- if (request.body && request.body instanceof Stream.Readable) {
1641
- request.body.destroy(error);
1642
- }
1643
- if (!response || !response.body) return;
1644
- response.body.emit('error', error);
1645
- };
1646
-
1647
- if (signal && signal.aborted) {
1648
- abort();
1649
- return;
1650
- }
1651
-
1652
- const abortAndFinalize = function abortAndFinalize() {
1653
- abort();
1654
- finalize();
1655
- };
1656
-
1657
- // send request
1658
- const req = send(options);
1659
- let reqTimeout;
1660
-
1661
- if (signal) {
1662
- signal.addEventListener('abort', abortAndFinalize);
1663
- }
1664
-
1665
- function finalize() {
1666
- req.abort();
1667
- if (signal) signal.removeEventListener('abort', abortAndFinalize);
1668
- clearTimeout(reqTimeout);
1669
- }
1670
-
1671
- if (request.timeout) {
1672
- req.once('socket', function (socket) {
1673
- reqTimeout = setTimeout(function () {
1674
- reject(new FetchError(`network timeout at: ${request.url}`, 'request-timeout'));
1675
- finalize();
1676
- }, request.timeout);
1677
- });
1678
- }
1679
-
1680
- req.on('error', function (err) {
1681
- reject(new FetchError(`request to ${request.url} failed, reason: ${err.message}`, 'system', err));
1682
- finalize();
1683
- });
1684
-
1685
- req.on('response', function (res) {
1686
- clearTimeout(reqTimeout);
1687
-
1688
- const headers = createHeadersLenient(res.headers);
1689
-
1690
- // HTTP fetch step 5
1691
- if (fetch.isRedirect(res.statusCode)) {
1692
- // HTTP fetch step 5.2
1693
- const location = headers.get('Location');
1694
-
1695
- // HTTP fetch step 5.3
1696
- const locationURL = location === null ? null : resolve_url(request.url, location);
1697
-
1698
- // HTTP fetch step 5.5
1699
- switch (request.redirect) {
1700
- case 'error':
1701
- reject(new FetchError(`uri requested responds with a redirect, redirect mode is set to error: ${request.url}`, 'no-redirect'));
1702
- finalize();
1703
- return;
1704
- case 'manual':
1705
- // node-fetch-specific step: make manual redirect a bit easier to use by setting the Location header value to the resolved URL.
1706
- if (locationURL !== null) {
1707
- // handle corrupted header
1708
- try {
1709
- headers.set('Location', locationURL);
1710
- } catch (err) {
1711
- // istanbul ignore next: nodejs server prevent invalid response headers, we can't test this through normal request
1712
- reject(err);
1713
- }
1714
- }
1715
- break;
1716
- case 'follow':
1717
- // HTTP-redirect fetch step 2
1718
- if (locationURL === null) {
1719
- break;
1720
- }
1721
-
1722
- // HTTP-redirect fetch step 5
1723
- if (request.counter >= request.follow) {
1724
- reject(new FetchError(`maximum redirect reached at: ${request.url}`, 'max-redirect'));
1725
- finalize();
1726
- return;
1727
- }
1728
-
1729
- // HTTP-redirect fetch step 6 (counter increment)
1730
- // Create a new Request object.
1731
- const requestOpts = {
1732
- headers: new Headers(request.headers),
1733
- follow: request.follow,
1734
- counter: request.counter + 1,
1735
- agent: request.agent,
1736
- compress: request.compress,
1737
- method: request.method,
1738
- body: request.body,
1739
- signal: request.signal,
1740
- timeout: request.timeout,
1741
- size: request.size
1742
- };
1743
-
1744
- // HTTP-redirect fetch step 9
1745
- if (res.statusCode !== 303 && request.body && getTotalBytes(request) === null) {
1746
- reject(new FetchError('Cannot follow redirect with body being a readable stream', 'unsupported-redirect'));
1747
- finalize();
1748
- return;
1749
- }
1750
-
1751
- // HTTP-redirect fetch step 11
1752
- if (res.statusCode === 303 || (res.statusCode === 301 || res.statusCode === 302) && request.method === 'POST') {
1753
- requestOpts.method = 'GET';
1754
- requestOpts.body = undefined;
1755
- requestOpts.headers.delete('content-length');
1756
- }
1757
-
1758
- // HTTP-redirect fetch step 15
1759
- resolve(fetch(new Request(locationURL, requestOpts)));
1760
- finalize();
1761
- return;
1762
- }
1763
- }
1764
-
1765
- // prepare response
1766
- res.once('end', function () {
1767
- if (signal) signal.removeEventListener('abort', abortAndFinalize);
1768
- });
1769
- let body = res.pipe(new PassThrough$1());
1770
-
1771
- const response_options = {
1772
- url: request.url,
1773
- status: res.statusCode,
1774
- statusText: res.statusMessage,
1775
- headers: headers,
1776
- size: request.size,
1777
- timeout: request.timeout,
1778
- counter: request.counter
1779
- };
1780
-
1781
- // HTTP-network fetch step 12.1.1.3
1782
- const codings = headers.get('Content-Encoding');
1783
-
1784
- // HTTP-network fetch step 12.1.1.4: handle content codings
1785
-
1786
- // in following scenarios we ignore compression support
1787
- // 1. compression support is disabled
1788
- // 2. HEAD request
1789
- // 3. no Content-Encoding header
1790
- // 4. no content response (204)
1791
- // 5. content not modified response (304)
1792
- if (!request.compress || request.method === 'HEAD' || codings === null || res.statusCode === 204 || res.statusCode === 304) {
1793
- response = new Response(body, response_options);
1794
- resolve(response);
1795
- return;
1796
- }
1797
-
1798
- // For Node v6+
1799
- // Be less strict when decoding compressed responses, since sometimes
1800
- // servers send slightly invalid responses that are still accepted
1801
- // by common browsers.
1802
- // Always using Z_SYNC_FLUSH is what cURL does.
1803
- const zlibOptions = {
1804
- flush: zlib.Z_SYNC_FLUSH,
1805
- finishFlush: zlib.Z_SYNC_FLUSH
1806
- };
1807
-
1808
- // for gzip
1809
- if (codings == 'gzip' || codings == 'x-gzip') {
1810
- body = body.pipe(zlib.createGunzip(zlibOptions));
1811
- response = new Response(body, response_options);
1812
- resolve(response);
1813
- return;
1814
- }
1815
-
1816
- // for deflate
1817
- if (codings == 'deflate' || codings == 'x-deflate') {
1818
- // handle the infamous raw deflate response from old servers
1819
- // a hack for old IIS and Apache servers
1820
- const raw = res.pipe(new PassThrough$1());
1821
- raw.once('data', function (chunk) {
1822
- // see http://stackoverflow.com/questions/37519828
1823
- if ((chunk[0] & 0x0F) === 0x08) {
1824
- body = body.pipe(zlib.createInflate());
1825
- } else {
1826
- body = body.pipe(zlib.createInflateRaw());
1827
- }
1828
- response = new Response(body, response_options);
1829
- resolve(response);
1830
- });
1831
- return;
1832
- }
1833
-
1834
- // for br
1835
- if (codings == 'br' && typeof zlib.createBrotliDecompress === 'function') {
1836
- body = body.pipe(zlib.createBrotliDecompress());
1837
- response = new Response(body, response_options);
1838
- resolve(response);
1839
- return;
1840
- }
1841
-
1842
- // otherwise, use response as-is
1843
- response = new Response(body, response_options);
1844
- resolve(response);
1845
- });
1846
-
1847
- writeToStream(req, request);
1848
- });
1849
- }
1850
- /**
1851
- * Redirect code matching
1852
- *
1853
- * @param Number code Status code
1854
- * @return Boolean
1855
- */
1856
- fetch.isRedirect = function (code) {
1857
- return code === 301 || code === 302 || code === 303 || code === 307 || code === 308;
1858
- };
1859
-
1860
- // expose Promise
1861
- fetch.Promise = global.Promise;
1862
-
1863
- function noop() { }
1864
- function safe_not_equal(a, b) {
1865
- return a != a ? b == b : a !== b || ((a && typeof a === 'object') || typeof a === 'function');
1866
- }
1867
-
1868
- const subscriber_queue = [];
1869
- /**
1870
- * Create a `Writable` store that allows both updating and reading by subscription.
1871
- * @param {*=}value initial value
1872
- * @param {StartStopNotifier=}start start and stop notifications for subscriptions
1873
- */
1874
- function writable(value, start = noop) {
1875
- let stop;
1876
- const subscribers = [];
1877
- function set(new_value) {
1878
- if (safe_not_equal(value, new_value)) {
1879
- value = new_value;
1880
- if (stop) { // store is ready
1881
- const run_queue = !subscriber_queue.length;
1882
- for (let i = 0; i < subscribers.length; i += 1) {
1883
- const s = subscribers[i];
1884
- s[1]();
1885
- subscriber_queue.push(s, value);
1886
- }
1887
- if (run_queue) {
1888
- for (let i = 0; i < subscriber_queue.length; i += 2) {
1889
- subscriber_queue[i][0](subscriber_queue[i + 1]);
1890
- }
1891
- subscriber_queue.length = 0;
1892
- }
1893
- }
1894
- }
1895
- }
1896
- function update(fn) {
1897
- set(fn(value));
1898
- }
1899
- function subscribe(run, invalidate = noop) {
1900
- const subscriber = [run, invalidate];
1901
- subscribers.push(subscriber);
1902
- if (subscribers.length === 1) {
1903
- stop = start(set) || noop;
1904
- }
1905
- run(value);
1906
- return () => {
1907
- const index = subscribers.indexOf(subscriber);
1908
- if (index !== -1) {
1909
- subscribers.splice(index, 1);
1910
- }
1911
- if (subscribers.length === 0) {
1912
- stop();
1913
- stop = null;
1914
- }
1915
- };
1916
- }
1917
- return { set, update, subscribe };
1918
- }
1919
-
1920
- async function get_response({ request, options, $session, route, status = 200, error }) {
1921
- const host = options.host || request.headers[options.host_header];
1922
-
1923
- const dependencies = {};
1924
-
1925
- const serialized_session = try_serialize($session, (err) => {
1926
- throw new Error(`Failed to serialize session data: ${err.message}`);
1927
- });
1928
-
1929
- const serialized_data = [];
1930
-
1931
- const match = route && route.pattern.exec(request.path);
1932
- const params = route && route.params(match);
1933
-
1934
- const page = {
1935
- host,
1936
- path: request.path,
1937
- query: request.query,
1938
- params
1939
- };
1940
-
1941
- let uses_credentials = false;
1942
-
1943
- const fetcher = async (url, opts = {}) => {
1944
- if (options.local && url.startsWith(options.paths.assets)) {
1945
- // when running `start`, or prerendering, `assets` should be
1946
- // config.paths.assets, but we should still be able to fetch
1947
- // assets directly from `static`
1948
- url = url.replace(options.paths.assets, '');
1949
- }
1950
-
1951
- const parsed = parse(url);
1952
-
1953
- if (opts.credentials !== 'omit') {
1954
- uses_credentials = true;
1955
- }
1956
-
1957
- let response;
1958
-
1959
- if (parsed.protocol) {
1960
- // external fetch
1961
- response = await fetch(parsed.href, opts);
1962
- } else {
1963
- // otherwise we're dealing with an internal fetch
1964
- const resolved = resolve(request.path, parsed.pathname);
1965
-
1966
- // is this a request for a static asset?
1967
- const filename = resolved.slice(1);
1968
- const filename_html = `${filename}/index.html`;
1969
- const asset = options.manifest.assets.find(
1970
- (d) => d.file === filename || d.file === filename_html
1971
- );
1972
-
1973
- if (asset) {
1974
- if (options.get_static_file) {
1975
- response = new Response(options.get_static_file(asset.file), {
1976
- headers: {
1977
- 'content-type': asset.type
1978
- }
1979
- });
1980
- } else {
1981
- // TODO we need to know what protocol to use
1982
- response = await fetch(`http://${page.host}/${asset.file}`, opts);
1983
- }
1984
- }
1985
-
1986
- if (!response) {
1987
- const rendered = await render(
1988
- {
1989
- host: request.host,
1990
- method: opts.method || 'GET',
1991
- headers: opts.headers || {}, // TODO inject credentials...
1992
- path: resolved,
1993
- body: opts.body,
1994
- query: new URLSearchParams(parsed.query || '')
1995
- },
1996
- {
1997
- ...options,
1998
- fetched: true
1999
- }
2000
- );
2001
-
2002
- if (rendered) {
2003
- // TODO this is primarily for the benefit of the static case,
2004
- // but could it be used elsewhere?
2005
- dependencies[resolved] = rendered;
2006
-
2007
- response = new Response(rendered.body, {
2008
- status: rendered.status,
2009
- headers: rendered.headers
2010
- });
2011
- }
2012
- }
2013
- }
2014
-
2015
- if (response) {
2016
- const clone = response.clone();
2017
-
2018
- const headers = {};
2019
- clone.headers.forEach((value, key) => {
2020
- if (key !== 'etag') headers[key] = value;
2021
- });
2022
-
2023
- const payload = JSON.stringify({
2024
- status: clone.status,
2025
- statusText: clone.statusText,
2026
- headers,
2027
- body: await clone.text() // TODO handle binary data
2028
- });
2029
-
2030
- // TODO i guess we need to sanitize/escape this... somehow?
2031
- serialized_data.push({ url, payload });
2032
-
2033
- return response;
2034
- }
2035
-
2036
- return new Response('Not found', {
2037
- status: 404
2038
- });
2039
- };
2040
-
2041
- const parts = error ? [options.manifest.layout] : [options.manifest.layout, ...route.parts];
2042
-
2043
- const component_promises = parts.map((loader) => loader());
2044
- const components = [];
2045
- const props_promises = [];
2046
-
2047
- let context = {};
2048
- let maxage;
2049
-
2050
- for (let i = 0; i < component_promises.length; i += 1) {
2051
- let loaded;
2052
-
2053
- try {
2054
- const mod = await component_promises[i];
2055
- components[i] = mod.default;
2056
-
2057
- if (options.only_prerender && !mod.prerender) {
2058
- return;
2059
- }
2060
-
2061
- loaded =
2062
- mod.load &&
2063
- (await mod.load.call(null, {
2064
- page,
2065
- get session() {
2066
- uses_credentials = true;
2067
- return $session;
2068
- },
2069
- fetch: fetcher,
2070
- context: { ...context }
2071
- }));
2072
- } catch (e) {
2073
- // if load fails when we're already rendering the
2074
- // error page, there's not a lot we can do
2075
- if (error) throw e;
2076
-
2077
- loaded = { error: e };
2078
- }
2079
-
2080
- if (loaded) {
2081
- if (loaded.error) {
2082
- return await get_response({
2083
- request,
2084
- options,
2085
- $session,
2086
- route,
2087
- status: loaded.status || 500,
2088
- error: loaded.error
2089
- });
2090
- }
2091
-
2092
- if (loaded.redirect) {
2093
- return {
2094
- status: loaded.redirect.status,
2095
- headers: {
2096
- location: loaded.redirect.to
2097
- }
2098
- };
2099
- }
2100
-
2101
- if (loaded.context) {
2102
- context = {
2103
- ...context,
2104
- ...loaded.context
2105
- };
2106
- }
2107
-
2108
- maxage = loaded.maxage || 0;
2109
-
2110
- props_promises[i] = loaded.props;
2111
- }
2112
- }
2113
-
2114
- const session = writable($session);
2115
- let session_tracking_active = false;
2116
- const unsubscribe = session.subscribe(() => {
2117
- if (session_tracking_active) uses_credentials = true;
2118
- });
2119
- session_tracking_active = true;
2120
-
2121
- if (error) {
2122
- if (options.dev) {
2123
- error.stack = await options.get_stack(error);
2124
- } else {
2125
- // remove error.stack in production
2126
- error.stack = String(error);
2127
- }
2128
- }
2129
-
2130
- const props = {
2131
- status,
2132
- error,
2133
- stores: {
2134
- page: writable(null),
2135
- navigating: writable(null),
2136
- session
2137
- },
2138
- page,
2139
- components
2140
- };
2141
-
2142
- // leveln (instead of levels[n]) makes it easy to avoid
2143
- // unnecessary updates for layout components
2144
- for (let i = 0; i < props_promises.length; i += 1) {
2145
- props[`props_${i}`] = await props_promises[i];
2146
- }
2147
-
2148
- let rendered;
2149
-
2150
- try {
2151
- rendered = options.root.render(props);
2152
- } catch (e) {
2153
- if (error) throw e;
2154
-
2155
- return await get_response({
2156
- request,
2157
- options,
2158
- $session,
2159
- route,
2160
- status: 500,
2161
- error: e
2162
- });
2163
- }
2164
-
2165
- unsubscribe();
2166
-
2167
- // TODO all the `route &&` stuff is messy
2168
- const js_deps = route ? route.js : [];
2169
- const css_deps = route ? route.css : [];
2170
-
2171
- const s = JSON.stringify;
2172
-
2173
- // TODO strip the AMP stuff out of the build if not relevant
2174
- const links = options.amp
2175
- ? `<style amp-custom>${(
2176
- await Promise.all(css_deps.map((dep) => options.get_amp_css(dep)))
2177
- ).join('\n')}</style>`
2178
- : [
2179
- ...js_deps.map((dep) => `<link rel="modulepreload" href="${dep}">`),
2180
- ...css_deps.map((dep) => `<link rel="stylesheet" href="${dep}">`)
2181
- ].join('\n\t\t\t');
2182
-
2183
- const init = options.amp
2184
- ? `
2185
- <style amp-boilerplate>body{-webkit-animation:-amp-start 8s steps(1,end) 0s 1 normal both;-moz-animation:-amp-start 8s steps(1,end) 0s 1 normal both;-ms-animation:-amp-start 8s steps(1,end) 0s 1 normal both;animation:-amp-start 8s steps(1,end) 0s 1 normal both}@-webkit-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@-moz-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@-ms-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@-o-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}</style>
2186
- <noscript><style amp-boilerplate>body{-webkit-animation:none;-moz-animation:none;-ms-animation:none;animation:none}</style></noscript>
2187
- <script async src="https://cdn.ampproject.org/v0.js"></script>`
2188
- : `
2189
- <script type="module">
2190
- import { start } from '${options.paths.assets}/${options.app_dir}/${options.entry}';
2191
- ${options.start_global ? `window.${options.start_global} = () => ` : ''}start({
2192
- target: ${options.target ? `document.querySelector(${s(options.target)})` : 'document.body'},
2193
- host: ${host ? s(host) : 'location.host'},
2194
- paths: ${s(options.paths)},
2195
- status: ${status},
2196
- error: ${serialize_error(error)},
2197
- session: ${serialized_session}
2198
- });
2199
- </script>`;
2200
-
2201
- const head = [rendered.head, links, init].join('\n\n');
2202
-
2203
- const body = options.amp
2204
- ? rendered.html
2205
- : `${rendered.html}
2206
-
2207
- ${serialized_data
2208
- .map(({ url, payload }) => `<script type="svelte-data" url="${url}">${payload}</script>`)
2209
- .join('\n\n\t\t\t')}
2210
- `.replace(/^\t{2}/gm, '');
2211
-
2212
- const headers = {
2213
- 'content-type': 'text/html'
2214
- };
2215
-
2216
- if (maxage) {
2217
- headers['cache-control'] = `${uses_credentials ? 'private' : 'public'}, max-age=${maxage}`;
2218
- }
2219
-
2220
- return {
2221
- status,
2222
- headers,
2223
- body: options.template({ head, body }),
2224
- dependencies
2225
- };
2226
- }
2227
-
2228
- async function render_page(request, context, options) {
2229
- const route = options.manifest.pages.find((route) => route.pattern.test(request.path));
2230
-
2231
- const $session = await (options.setup.getSession && options.setup.getSession(context));
2232
-
2233
- if (!route) {
2234
- if (options.fetched) {
2235
- // we came here because of a bad request in a `load` function.
2236
- // rather than render the error page — which could lead to an
2237
- // infinite loop, if the `load` belonged to the root layout,
2238
- // we respond with a bare-bones 500
2239
- throw new Error('Bad request in load function');
2240
- }
2241
-
2242
- return await get_response({
2243
- request,
2244
- options,
2245
- $session,
2246
- route,
2247
- status: 404,
2248
- error: new Error(`Not found: ${request.path}`)
2249
- });
2250
- }
2251
-
2252
- return await get_response({
2253
- request,
2254
- options,
2255
- $session,
2256
- route,
2257
- status: 200,
2258
- error: null
2259
- });
2260
- }
2261
-
2262
- function try_serialize(data, fail) {
2263
- try {
2264
- return devalue(data);
2265
- } catch (err) {
2266
- if (fail) fail(err);
2267
- return null;
2268
- }
2269
- }
2270
-
2271
- // Ensure we return something truthy so the client will not re-render the page over the error
2272
- function serialize_error(error) {
2273
- if (!error) return null;
2274
- let serialized = try_serialize(error);
2275
- if (!serialized) {
2276
- const { name, message, stack } = error;
2277
- serialized = try_serialize({ name, message, stack });
2278
- }
2279
- if (!serialized) {
2280
- serialized = '{}';
2281
- }
2282
- return serialized;
2283
- }
2284
-
2285
- function render_route(request, context, options) {
2286
- const route = options.manifest.endpoints.find((route) => route.pattern.test(request.path));
2287
- if (!route) return null;
2288
-
2289
- return route.load().then(async (mod) => {
2290
- const handler = mod[request.method.toLowerCase().replace('delete', 'del')]; // 'delete' is a reserved word
2291
-
2292
- if (handler) {
2293
- const match = route.pattern.exec(request.path);
2294
- const params = route.params(match);
2295
-
2296
- const response = await handler(
2297
- {
2298
- host: options.host || request.headers[options.host_header || 'host'],
2299
- path: request.path,
2300
- headers: request.headers,
2301
- query: request.query,
2302
- body: request.body,
2303
- params
2304
- },
2305
- context
2306
- );
2307
-
2308
- if (typeof response !== 'object' || response.body == null) {
2309
- return {
2310
- status: 500,
2311
- body: `Invalid response from route ${request.path}; ${
2312
- response.body == null ? 'body is missing' : `expected an object, got ${typeof response}`
2313
- }`,
2314
- headers: {}
2315
- };
2316
- }
2317
-
2318
- let { status = 200, body, headers = {} } = response;
2319
-
2320
- headers = lowercase_keys(headers);
2321
-
2322
- if (
2323
- (typeof body === 'object' && !('content-type' in headers)) ||
2324
- headers['content-type'] === 'application/json'
2325
- ) {
2326
- headers = { ...headers, 'content-type': 'application/json' };
2327
- body = JSON.stringify(body);
2328
- }
2329
-
2330
- return { status, body, headers };
2331
- } else {
2332
- return {
2333
- status: 501,
2334
- body: `${request.method} is not implemented for ${request.path}`,
2335
- headers: {}
2336
- };
2337
- }
2338
- });
2339
- }
2340
-
2341
- function lowercase_keys(obj) {
2342
- const clone = {};
2343
- for (const key in obj) {
2344
- clone[key.toLowerCase()] = obj[key];
2345
- }
2346
- return clone;
2347
- }
2348
-
2349
- function md5(body) {
2350
- return createHash('md5').update(body).digest('hex');
2351
- }
2352
-
2353
- async function render(request, options) {
2354
- if (request.path.endsWith('/') && request.path !== '/') {
2355
- const q = request.query.toString();
2356
-
2357
- return {
2358
- status: 301,
2359
- headers: {
2360
- location: request.path.slice(0, -1) + (q ? `?${q}` : '')
2361
- }
2362
- };
2363
- }
2364
-
2365
- const { context, headers = {} } =
2366
- (await (options.setup.prepare && options.setup.prepare(request.headers))) || {};
2367
-
2368
- try {
2369
- const response = await (render_route(request, context, options) ||
2370
- render_page(request, context, options));
2371
-
2372
- if (response) {
2373
- // inject ETags for 200 responses
2374
- if (response.status === 200) {
2375
- if (!/(no-store|immutable)/.test(response.headers['cache-control'])) {
2376
- const etag = `"${md5(response.body)}"`;
2377
-
2378
- if (request.headers['if-none-match'] === etag) {
2379
- return {
2380
- status: 304,
2381
- headers: {},
2382
- body: null
2383
- };
2384
- }
2385
-
2386
- response.headers['etag'] = etag;
2387
- }
2388
- }
2389
-
2390
- return {
2391
- status: response.status,
2392
- headers: { ...headers, ...response.headers },
2393
- body: response.body,
2394
- dependencies: response.dependencies
2395
- };
2396
- }
2397
- } catch (e) {
2398
- if (e && e.stack) {
2399
- e.stack = await options.get_stack(e);
2400
- }
2401
-
2402
- console.error((e && e.stack) || e);
2403
-
2404
- return {
2405
- status: 500,
2406
- headers,
2407
- body: options.dev ? e.stack : e.message
2408
- };
2409
- }
2410
- }
2411
-
2412
- export { render };
2413
- //# sourceMappingURL=renderer.js.map