@gjsify/fetch 0.0.4 → 0.1.1

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 (88) hide show
  1. package/README.md +27 -2
  2. package/globals.mjs +12 -0
  3. package/lib/body.d.ts +69 -0
  4. package/lib/body.js +375 -0
  5. package/lib/errors/abort-error.d.ts +7 -0
  6. package/lib/errors/abort-error.js +9 -0
  7. package/lib/errors/base.d.ts +6 -0
  8. package/lib/errors/base.js +17 -0
  9. package/lib/errors/fetch-error.d.ts +16 -0
  10. package/lib/errors/fetch-error.js +23 -0
  11. package/lib/esm/body.js +104 -56
  12. package/lib/esm/errors/base.js +3 -1
  13. package/lib/esm/headers.js +116 -131
  14. package/lib/esm/index.js +145 -190
  15. package/lib/esm/request.js +42 -41
  16. package/lib/esm/response.js +19 -4
  17. package/lib/esm/utils/blob-from.js +2 -98
  18. package/lib/esm/utils/data-uri.js +23 -0
  19. package/lib/esm/utils/is.js +7 -3
  20. package/lib/esm/utils/multipart-parser.js +5 -2
  21. package/lib/esm/utils/referrer.js +10 -10
  22. package/lib/esm/utils/soup-helpers.js +22 -0
  23. package/lib/headers.d.ts +33 -0
  24. package/lib/headers.js +195 -0
  25. package/lib/index.d.ts +18 -0
  26. package/lib/index.js +205 -0
  27. package/lib/request.d.ts +101 -0
  28. package/lib/request.js +308 -0
  29. package/lib/response.d.ts +73 -0
  30. package/lib/response.js +158 -0
  31. package/lib/types/index.d.ts +1 -0
  32. package/lib/types/index.js +1 -0
  33. package/lib/types/system-error.d.ts +11 -0
  34. package/lib/types/system-error.js +2 -0
  35. package/lib/utils/blob-from.d.ts +2 -0
  36. package/lib/utils/blob-from.js +4 -0
  37. package/lib/utils/data-uri.d.ts +10 -0
  38. package/lib/utils/data-uri.js +27 -0
  39. package/lib/utils/get-search.d.ts +1 -0
  40. package/lib/utils/get-search.js +8 -0
  41. package/lib/utils/is-redirect.d.ts +7 -0
  42. package/lib/utils/is-redirect.js +10 -0
  43. package/lib/utils/is.d.ts +35 -0
  44. package/lib/utils/is.js +74 -0
  45. package/lib/utils/multipart-parser.d.ts +2 -0
  46. package/lib/utils/multipart-parser.js +396 -0
  47. package/lib/utils/referrer.d.ts +76 -0
  48. package/lib/utils/referrer.js +283 -0
  49. package/lib/utils/soup-helpers.d.ts +12 -0
  50. package/lib/utils/soup-helpers.js +25 -0
  51. package/package.json +23 -27
  52. package/src/body.ts +181 -169
  53. package/src/errors/base.ts +3 -1
  54. package/src/headers.ts +155 -202
  55. package/src/index.spec.ts +268 -3
  56. package/src/index.ts +199 -312
  57. package/src/request.ts +84 -75
  58. package/src/response.ts +48 -18
  59. package/src/test.mts +1 -1
  60. package/src/utils/blob-from.ts +4 -164
  61. package/src/utils/data-uri.ts +29 -0
  62. package/src/utils/is.ts +15 -15
  63. package/src/utils/multipart-parser.ts +3 -3
  64. package/src/utils/referrer.ts +11 -11
  65. package/src/utils/soup-helpers.ts +37 -0
  66. package/tsconfig.json +4 -4
  67. package/tsconfig.tsbuildinfo +1 -0
  68. package/lib/cjs/body.js +0 -255
  69. package/lib/cjs/errors/abort-error.js +0 -9
  70. package/lib/cjs/errors/base.js +0 -17
  71. package/lib/cjs/errors/fetch-error.js +0 -21
  72. package/lib/cjs/headers.js +0 -202
  73. package/lib/cjs/index.js +0 -224
  74. package/lib/cjs/request.js +0 -281
  75. package/lib/cjs/response.js +0 -133
  76. package/lib/cjs/types/index.js +0 -1
  77. package/lib/cjs/types/system-error.js +0 -1
  78. package/lib/cjs/utils/blob-from.js +0 -101
  79. package/lib/cjs/utils/get-search.js +0 -11
  80. package/lib/cjs/utils/is-redirect.js +0 -7
  81. package/lib/cjs/utils/is.js +0 -28
  82. package/lib/cjs/utils/multipart-parser.js +0 -353
  83. package/lib/cjs/utils/referrer.js +0 -153
  84. package/test.gjs.js +0 -34758
  85. package/test.gjs.mjs +0 -53172
  86. package/test.node.js +0 -1226
  87. package/test.node.mjs +0 -6273
  88. package/tsconfig.types.json +0 -8
@@ -0,0 +1,396 @@
1
+ import { File } from './blob-from.js';
2
+ import { FormData } from '@gjsify/formdata';
3
+ // let s = 0;
4
+ // const S = {
5
+ // START_BOUNDARY: s++,
6
+ // HEADER_FIELD_START: s++,
7
+ // HEADER_FIELD: s++,
8
+ // HEADER_VALUE_START: s++,
9
+ // HEADER_VALUE: s++,
10
+ // HEADER_VALUE_ALMOST_DONE: s++,
11
+ // HEADERS_ALMOST_DONE: s++,
12
+ // PART_DATA_START: s++,
13
+ // PART_DATA: s++,
14
+ // END: s++
15
+ // };
16
+ var S;
17
+ (function (S) {
18
+ S[S["START_BOUNDARY"] = 0] = "START_BOUNDARY";
19
+ S[S["HEADER_FIELD_START"] = 1] = "HEADER_FIELD_START";
20
+ S[S["HEADER_FIELD"] = 2] = "HEADER_FIELD";
21
+ S[S["HEADER_VALUE_START"] = 3] = "HEADER_VALUE_START";
22
+ S[S["HEADER_VALUE"] = 4] = "HEADER_VALUE";
23
+ S[S["HEADER_VALUE_ALMOST_DONE"] = 5] = "HEADER_VALUE_ALMOST_DONE";
24
+ S[S["HEADERS_ALMOST_DONE"] = 6] = "HEADERS_ALMOST_DONE";
25
+ S[S["PART_DATA_START"] = 7] = "PART_DATA_START";
26
+ S[S["PART_DATA"] = 8] = "PART_DATA";
27
+ S[S["END"] = 9] = "END";
28
+ })(S || (S = {}));
29
+ let f = 1;
30
+ const F = {
31
+ PART_BOUNDARY: f,
32
+ LAST_BOUNDARY: f *= 2
33
+ };
34
+ const LF = 10;
35
+ const CR = 13;
36
+ const SPACE = 32;
37
+ const HYPHEN = 45;
38
+ const COLON = 58;
39
+ const A = 97;
40
+ const Z = 122;
41
+ const lower = c => c | 0x20;
42
+ const noop = (..._args) => { };
43
+ class MultipartParser {
44
+ index = 0;
45
+ flags = 0;
46
+ boundary;
47
+ lookbehind;
48
+ state = S.START_BOUNDARY;
49
+ onHeaderEnd = noop;
50
+ onHeaderField = noop;
51
+ onHeadersEnd = noop;
52
+ onHeaderValue = noop;
53
+ onPartBegin = noop;
54
+ onPartData = noop;
55
+ onPartEnd = noop;
56
+ boundaryChars = {};
57
+ /**
58
+ * @param boundary
59
+ */
60
+ constructor(boundary) {
61
+ boundary = '\r\n--' + boundary;
62
+ const ui8a = new Uint8Array(boundary.length);
63
+ for (let i = 0; i < boundary.length; i++) {
64
+ ui8a[i] = boundary.charCodeAt(i);
65
+ this.boundaryChars[ui8a[i]] = true;
66
+ }
67
+ this.boundary = ui8a;
68
+ this.lookbehind = new Uint8Array(this.boundary.length + 8);
69
+ }
70
+ /**
71
+ * @param data
72
+ */
73
+ write(data) {
74
+ let i = 0;
75
+ const length_ = data.length;
76
+ let previousIndex = this.index;
77
+ let { lookbehind, boundary, boundaryChars, index, state, flags } = this;
78
+ const boundaryLength = this.boundary.length;
79
+ const boundaryEnd = boundaryLength - 1;
80
+ const bufferLength = data.length;
81
+ let c;
82
+ let cl;
83
+ const mark = (name) => {
84
+ this[name + 'Mark'] = i;
85
+ };
86
+ const clear = (name) => {
87
+ delete this[name + 'Mark'];
88
+ };
89
+ const callback = (callbackSymbol, start, end, ui8a) => {
90
+ if (start === undefined || start !== end) {
91
+ this[callbackSymbol](ui8a && ui8a.subarray(start, end));
92
+ }
93
+ };
94
+ const dataCallback = (name, clear = false) => {
95
+ const markSymbol = name + 'Mark';
96
+ if (!(markSymbol in this)) {
97
+ return;
98
+ }
99
+ if (clear) {
100
+ callback(name, this[markSymbol], i, data);
101
+ delete this[markSymbol];
102
+ }
103
+ else {
104
+ callback(name, this[markSymbol], data.length, data);
105
+ this[markSymbol] = 0;
106
+ }
107
+ };
108
+ for (i = 0; i < length_; i++) {
109
+ c = data[i];
110
+ switch (state) {
111
+ case S.START_BOUNDARY:
112
+ if (index === boundary.length - 2) {
113
+ if (c === HYPHEN) {
114
+ flags |= F.LAST_BOUNDARY;
115
+ }
116
+ else if (c !== CR) {
117
+ return;
118
+ }
119
+ index++;
120
+ break;
121
+ }
122
+ else if (index - 1 === boundary.length - 2) {
123
+ if (flags & F.LAST_BOUNDARY && c === HYPHEN) {
124
+ state = S.END;
125
+ flags = 0;
126
+ }
127
+ else if (!(flags & F.LAST_BOUNDARY) && c === LF) {
128
+ index = 0;
129
+ callback('onPartBegin');
130
+ state = S.HEADER_FIELD_START;
131
+ }
132
+ else {
133
+ return;
134
+ }
135
+ break;
136
+ }
137
+ if (c !== boundary[index + 2]) {
138
+ index = -2;
139
+ }
140
+ if (c === boundary[index + 2]) {
141
+ index++;
142
+ }
143
+ break;
144
+ case S.HEADER_FIELD_START:
145
+ state = S.HEADER_FIELD;
146
+ mark('onHeaderField');
147
+ index = 0;
148
+ // falls through
149
+ case S.HEADER_FIELD:
150
+ if (c === CR) {
151
+ clear('onHeaderField');
152
+ state = S.HEADERS_ALMOST_DONE;
153
+ break;
154
+ }
155
+ index++;
156
+ if (c === HYPHEN) {
157
+ break;
158
+ }
159
+ if (c === COLON) {
160
+ if (index === 1) {
161
+ // empty header field
162
+ return;
163
+ }
164
+ dataCallback('onHeaderField', true);
165
+ state = S.HEADER_VALUE_START;
166
+ break;
167
+ }
168
+ cl = lower(c);
169
+ if (cl < A || cl > Z) {
170
+ return;
171
+ }
172
+ break;
173
+ case S.HEADER_VALUE_START:
174
+ if (c === SPACE) {
175
+ break;
176
+ }
177
+ mark('onHeaderValue');
178
+ state = S.HEADER_VALUE;
179
+ // falls through
180
+ case S.HEADER_VALUE:
181
+ if (c === CR) {
182
+ dataCallback('onHeaderValue', true);
183
+ callback('onHeaderEnd');
184
+ state = S.HEADER_VALUE_ALMOST_DONE;
185
+ }
186
+ break;
187
+ case S.HEADER_VALUE_ALMOST_DONE:
188
+ if (c !== LF) {
189
+ return;
190
+ }
191
+ state = S.HEADER_FIELD_START;
192
+ break;
193
+ case S.HEADERS_ALMOST_DONE:
194
+ if (c !== LF) {
195
+ return;
196
+ }
197
+ callback('onHeadersEnd');
198
+ state = S.PART_DATA_START;
199
+ break;
200
+ case S.PART_DATA_START:
201
+ state = S.PART_DATA;
202
+ mark('onPartData');
203
+ // falls through
204
+ case S.PART_DATA:
205
+ previousIndex = index;
206
+ if (index === 0) {
207
+ // boyer-moore derrived algorithm to safely skip non-boundary data
208
+ i += boundaryEnd;
209
+ while (i < bufferLength && !(data[i] in boundaryChars)) {
210
+ i += boundaryLength;
211
+ }
212
+ i -= boundaryEnd;
213
+ c = data[i];
214
+ }
215
+ if (index < boundary.length) {
216
+ if (boundary[index] === c) {
217
+ if (index === 0) {
218
+ dataCallback('onPartData', true);
219
+ }
220
+ index++;
221
+ }
222
+ else {
223
+ index = 0;
224
+ }
225
+ }
226
+ else if (index === boundary.length) {
227
+ index++;
228
+ if (c === CR) {
229
+ // CR = part boundary
230
+ flags |= F.PART_BOUNDARY;
231
+ }
232
+ else if (c === HYPHEN) {
233
+ // HYPHEN = end boundary
234
+ flags |= F.LAST_BOUNDARY;
235
+ }
236
+ else {
237
+ index = 0;
238
+ }
239
+ }
240
+ else if (index - 1 === boundary.length) {
241
+ if (flags & F.PART_BOUNDARY) {
242
+ index = 0;
243
+ if (c === LF) {
244
+ // unset the PART_BOUNDARY flag
245
+ flags &= ~F.PART_BOUNDARY;
246
+ callback('onPartEnd');
247
+ callback('onPartBegin');
248
+ state = S.HEADER_FIELD_START;
249
+ break;
250
+ }
251
+ }
252
+ else if (flags & F.LAST_BOUNDARY) {
253
+ if (c === HYPHEN) {
254
+ callback('onPartEnd');
255
+ state = S.END;
256
+ flags = 0;
257
+ }
258
+ else {
259
+ index = 0;
260
+ }
261
+ }
262
+ else {
263
+ index = 0;
264
+ }
265
+ }
266
+ if (index > 0) {
267
+ // when matching a possible boundary, keep a lookbehind reference
268
+ // in case it turns out to be a false lead
269
+ lookbehind[index - 1] = c;
270
+ }
271
+ else if (previousIndex > 0) {
272
+ // if our boundary turned out to be rubbish, the captured lookbehind
273
+ // belongs to partData
274
+ const _lookbehind = new Uint8Array(lookbehind.buffer, lookbehind.byteOffset, lookbehind.byteLength);
275
+ callback('onPartData', 0, previousIndex, _lookbehind);
276
+ previousIndex = 0;
277
+ mark('onPartData');
278
+ // reconsider the current character even so it interrupted the sequence
279
+ // it could be the beginning of a new sequence
280
+ i--;
281
+ }
282
+ break;
283
+ case S.END:
284
+ break;
285
+ default:
286
+ throw new Error(`Unexpected state entered: ${state}`);
287
+ }
288
+ }
289
+ dataCallback('onHeaderField');
290
+ dataCallback('onHeaderValue');
291
+ dataCallback('onPartData');
292
+ // Update properties for the next call
293
+ this.index = index;
294
+ this.state = state;
295
+ this.flags = flags;
296
+ }
297
+ end() {
298
+ if ((this.state === S.HEADER_FIELD_START && this.index === 0) ||
299
+ (this.state === S.PART_DATA && this.index === this.boundary.length)) {
300
+ this.onPartEnd();
301
+ }
302
+ else if (this.state !== S.END) {
303
+ throw new Error('MultipartParser.end(): stream ended unexpectedly');
304
+ }
305
+ }
306
+ }
307
+ function _fileName(headerValue) {
308
+ // matches either a quoted-string or a token (RFC 2616 section 19.5.1)
309
+ const m = headerValue.match(/\bfilename=("(.*?)"|([^()<>@,;:\\"/[\]?={}\s\t]+))($|;\s)/i);
310
+ if (!m) {
311
+ return;
312
+ }
313
+ const match = m[2] || m[3] || '';
314
+ let filename = match.slice(match.lastIndexOf('\\') + 1);
315
+ filename = filename.replace(/%22/g, '"');
316
+ filename = filename.replace(/&#(\d{4});/g, (m, code) => {
317
+ return String.fromCharCode(code);
318
+ });
319
+ return filename;
320
+ }
321
+ export async function toFormData(Body, ct) {
322
+ if (!/multipart/i.test(ct)) {
323
+ throw new TypeError('Failed to fetch');
324
+ }
325
+ const m = ct.match(/boundary=(?:"([^"]+)"|([^;]+))/i);
326
+ if (!m) {
327
+ throw new TypeError('no or bad content-type header, no multipart boundary');
328
+ }
329
+ const parser = new MultipartParser(m[1] || m[2]);
330
+ let headerField;
331
+ let headerValue;
332
+ let entryValue;
333
+ let entryName;
334
+ let contentType;
335
+ let filename;
336
+ const entryChunks = [];
337
+ const formData = new FormData();
338
+ const onPartData = (ui8a) => {
339
+ entryValue += decoder.decode(ui8a, { stream: true });
340
+ };
341
+ const appendToFile = (ui8a) => {
342
+ entryChunks.push(ui8a);
343
+ };
344
+ const appendFileToFormData = () => {
345
+ const file = new File(entryChunks, filename, { type: contentType });
346
+ formData.append(entryName, file);
347
+ };
348
+ const appendEntryToFormData = () => {
349
+ formData.append(entryName, entryValue);
350
+ };
351
+ const decoder = new TextDecoder('utf-8');
352
+ decoder.decode();
353
+ parser.onPartBegin = function () {
354
+ parser.onPartData = onPartData;
355
+ parser.onPartEnd = appendEntryToFormData;
356
+ headerField = '';
357
+ headerValue = '';
358
+ entryValue = '';
359
+ entryName = '';
360
+ contentType = '';
361
+ filename = null;
362
+ entryChunks.length = 0;
363
+ };
364
+ parser.onHeaderField = function (ui8a) {
365
+ headerField += decoder.decode(ui8a, { stream: true });
366
+ };
367
+ parser.onHeaderValue = function (ui8a) {
368
+ headerValue += decoder.decode(ui8a, { stream: true });
369
+ };
370
+ parser.onHeaderEnd = function () {
371
+ headerValue += decoder.decode();
372
+ headerField = headerField.toLowerCase();
373
+ if (headerField === 'content-disposition') {
374
+ // matches either a quoted-string or a token (RFC 2616 section 19.5.1)
375
+ const m = headerValue.match(/\bname=("([^"]*)"|([^()<>@,;:\\"/[\]?={}\s\t]+))/i);
376
+ if (m) {
377
+ entryName = m[2] || m[3] || '';
378
+ }
379
+ filename = _fileName(headerValue);
380
+ if (filename) {
381
+ parser.onPartData = appendToFile;
382
+ parser.onPartEnd = appendFileToFormData;
383
+ }
384
+ }
385
+ else if (headerField === 'content-type') {
386
+ contentType = headerValue;
387
+ }
388
+ headerValue = '';
389
+ headerField = '';
390
+ };
391
+ for await (const chunk of Body) {
392
+ parser.write(chunk);
393
+ }
394
+ parser.end();
395
+ return formData;
396
+ }
@@ -0,0 +1,76 @@
1
+ import { URL } from '@gjsify/url';
2
+ import Request from '../request.js';
3
+ /**
4
+ * @external URL
5
+ * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/URL URL}
6
+ */
7
+ /**
8
+ * @module utils/referrer
9
+ * @private
10
+ */
11
+ /**
12
+ * @see {@link https://w3c.github.io/webappsec-referrer-policy/#strip-url Referrer Policy §8.4. Strip url for use as a referrer}
13
+ * @param url
14
+ * @param originOnly
15
+ */
16
+ export declare function stripURLForUseAsAReferrer(url: null | URL | "no-referrer", originOnly?: boolean): URL | "no-referrer";
17
+ /**
18
+ * @see {@link https://w3c.github.io/webappsec-referrer-policy/#enumdef-referrerpolicy enum ReferrerPolicy}
19
+ */
20
+ export declare const ReferrerPolicy: Set<string>;
21
+ /**
22
+ * @see {@link https://w3c.github.io/webappsec-referrer-policy/#default-referrer-policy default referrer policy}
23
+ */
24
+ export declare const DEFAULT_REFERRER_POLICY = "strict-origin-when-cross-origin";
25
+ /**
26
+ * @see {@link https://w3c.github.io/webappsec-referrer-policy/#referrer-policies Referrer Policy §3. Referrer Policies}
27
+ * @param referrerPolicy
28
+ * @returns referrerPolicy
29
+ */
30
+ export declare function validateReferrerPolicy(referrerPolicy: ReferrerPolicy): ReferrerPolicy;
31
+ /**
32
+ * @see {@link https://w3c.github.io/webappsec-secure-contexts/#is-origin-trustworthy Referrer Policy §3.2. Is origin potentially trustworthy?}
33
+ * @param url
34
+ * @returns `true`: "Potentially Trustworthy", `false`: "Not Trustworthy"
35
+ */
36
+ export declare function isOriginPotentiallyTrustworthy(url: URL): boolean;
37
+ /**
38
+ * @see {@link https://w3c.github.io/webappsec-secure-contexts/#is-url-trustworthy Referrer Policy §3.3. Is url potentially trustworthy?}
39
+ * @param url
40
+ * @returns `true`: "Potentially Trustworthy", `false`: "Not Trustworthy"
41
+ */
42
+ export declare function isUrlPotentiallyTrustworthy(url: URL | 'no-referrer'): boolean;
43
+ /**
44
+ * Modifies the referrerURL to enforce any extra security policy considerations.
45
+ * @see {@link https://w3c.github.io/webappsec-referrer-policy/#determine-requests-referrer Referrer Policy §8.3. Determine request's Referrer}, step 7
46
+ * @callback module:utils/referrer~referrerURLCallback
47
+ * @param {external:URL} referrerURL
48
+ * @returns {external:URL} modified referrerURL
49
+ */
50
+ /**
51
+ * Modifies the referrerOrigin to enforce any extra security policy considerations.
52
+ * @see {@link https://w3c.github.io/webappsec-referrer-policy/#determine-requests-referrer Referrer Policy §8.3. Determine request's Referrer}, step 7
53
+ * @callback module:utils/referrer~referrerOriginCallback
54
+ * @param {external:URL} referrerOrigin
55
+ * @returns {external:URL} modified referrerOrigin
56
+ */
57
+ /**
58
+ * @see {@link https://w3c.github.io/webappsec-referrer-policy/#determine-requests-referrer Referrer Policy §8.3. Determine request's Referrer}
59
+ * @param request
60
+ * @param {object} o
61
+ * @param {module:utils/referrer~referrerURLCallback} o.referrerURLCallback
62
+ * @param {module:utils/referrer~referrerOriginCallback} o.referrerOriginCallback
63
+ * @returns {external:URL} Request's referrer
64
+ */
65
+ export declare function determineRequestsReferrer(request: Request, obj?: {
66
+ referrerURLCallback?: (url: URL | 'no-referrer') => URL;
67
+ referrerOriginCallback?: (url: URL | 'no-referrer') => URL;
68
+ }): URL | string;
69
+ /**
70
+ * @see {@link https://w3c.github.io/webappsec-referrer-policy/#parse-referrer-policy-from-header|Referrer Policy §8.1. Parse a referrer policy from a Referrer-Policy header}
71
+ * @param {Headers} headers Response headers
72
+ * @returns {string} policy
73
+ */
74
+ export declare function parseReferrerPolicyFromHeader(headers: {
75
+ get(name: string): string | null;
76
+ }): ReferrerPolicy;