@cacheable/net 2.0.8 → 2.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js DELETED
@@ -1,677 +0,0 @@
1
- // src/index.ts
2
- import { Cacheable } from "cacheable";
3
- import { Hookified } from "hookified";
4
-
5
- // src/fetch.ts
6
- import CachePolicy from "http-cache-semantics";
7
- var runtimeFetch = globalThis.fetch.bind(globalThis);
8
- async function fetch(url, options) {
9
- const fetchOptions = {
10
- ...options,
11
- cache: "no-cache"
12
- };
13
- if (!options.cache) {
14
- const response2 = await runtimeFetch(url, fetchOptions);
15
- if (!response2.ok) {
16
- throw new Error(`Fetch failed with status ${response2.status}`);
17
- }
18
- return response2;
19
- }
20
- if (options.method === "POST" || options.method === "PATCH" || options.method === "DELETE" || options.method === "HEAD") {
21
- const response2 = await runtimeFetch(url, fetchOptions);
22
- if (!response2.ok) {
23
- throw new Error(`Fetch failed with status ${response2.status}`);
24
- }
25
- return response2;
26
- }
27
- const httpCachePolicy = options.httpCachePolicy !== false;
28
- const method = options.method || "GET";
29
- const cacheKey = `${method}:${url}`;
30
- if (!httpCachePolicy) {
31
- const cachedData = await options.cache.getOrSet(cacheKey, async () => {
32
- const response2 = await runtimeFetch(url, fetchOptions);
33
- if (!response2.ok) {
34
- throw new Error(`Fetch failed with status ${response2.status}`);
35
- }
36
- const body2 = await response2.text();
37
- return {
38
- body: body2,
39
- status: response2.status,
40
- statusText: response2.statusText,
41
- headers: Object.fromEntries(response2.headers.entries())
42
- };
43
- });
44
- if (!cachedData) {
45
- throw new Error("Failed to get or set cache data");
46
- }
47
- return new Response(cachedData.body, {
48
- status: cachedData.status,
49
- statusText: cachedData.statusText,
50
- headers: cachedData.headers
51
- });
52
- }
53
- const policyKey = `${cacheKey}:policy`;
54
- const [cachedResponse, cachedPolicyData] = await Promise.all([
55
- options.cache.get(cacheKey),
56
- options.cache.get(policyKey)
57
- ]);
58
- let policy;
59
- let cachedBody;
60
- let cachedStatus;
61
- let cachedStatusText;
62
- let cachedHeaders;
63
- if (cachedPolicyData && cachedResponse) {
64
- policy = CachePolicy.fromObject(
65
- cachedPolicyData
66
- );
67
- cachedBody = cachedResponse.body;
68
- cachedStatus = cachedResponse.status;
69
- cachedStatusText = cachedResponse.statusText;
70
- cachedHeaders = cachedResponse.headers;
71
- }
72
- const requestHeaders = fetchOptions.headers || {};
73
- const request = {
74
- url,
75
- method,
76
- headers: requestHeaders
77
- };
78
- if (policy?.satisfiesWithoutRevalidation(request)) {
79
- const headers = policy.responseHeaders();
80
- return new Response(cachedBody, {
81
- status: cachedStatus,
82
- statusText: cachedStatusText,
83
- headers
84
- });
85
- }
86
- let revalidationHeaders = {};
87
- if (policy?.revalidationHeaders(request)) {
88
- revalidationHeaders = policy.revalidationHeaders(request);
89
- }
90
- const response = await runtimeFetch(url, {
91
- ...fetchOptions,
92
- headers: {
93
- ...fetchOptions.headers,
94
- ...revalidationHeaders
95
- }
96
- });
97
- if (response.status === 304 && policy) {
98
- const { policy: updatedPolicy, modified } = policy.revalidatedPolicy(
99
- request,
100
- {
101
- status: response.status,
102
- headers: Object.fromEntries(response.headers.entries())
103
- }
104
- );
105
- if (!modified) {
106
- const ttl = updatedPolicy.timeToLive();
107
- await options.cache.set(policyKey, updatedPolicy.toObject(), ttl);
108
- await options.cache.set(
109
- cacheKey,
110
- {
111
- body: cachedBody,
112
- status: cachedStatus,
113
- statusText: cachedStatusText,
114
- headers: cachedHeaders
115
- },
116
- ttl
117
- );
118
- const headers = updatedPolicy.responseHeaders();
119
- return new Response(cachedBody, {
120
- status: cachedStatus,
121
- statusText: cachedStatusText,
122
- headers
123
- });
124
- }
125
- }
126
- if (!response.ok && response.status !== 304) {
127
- throw new Error(`Fetch failed with status ${response.status}`);
128
- }
129
- const body = await response.text();
130
- const responseForPolicy = {
131
- status: response.status,
132
- statusText: response.statusText,
133
- headers: Object.fromEntries(response.headers.entries())
134
- };
135
- const newPolicy = new CachePolicy(request, responseForPolicy);
136
- if (newPolicy.storable()) {
137
- const ttl = newPolicy.timeToLive();
138
- await Promise.all([
139
- options.cache.set(
140
- cacheKey,
141
- {
142
- body,
143
- status: response.status,
144
- statusText: response.statusText,
145
- headers: responseForPolicy.headers
146
- },
147
- ttl
148
- ),
149
- options.cache.set(policyKey, newPolicy.toObject(), ttl)
150
- ]);
151
- }
152
- return new Response(body, {
153
- status: response.status,
154
- statusText: response.statusText,
155
- headers: response.headers
156
- });
157
- }
158
- async function get(url, options) {
159
- const response = await fetch(url, { ...options, method: "GET" });
160
- const text = await response.text();
161
- let data;
162
- try {
163
- data = JSON.parse(text);
164
- } catch {
165
- data = text;
166
- }
167
- const newResponse = new Response(text, {
168
- status: response.status,
169
- statusText: response.statusText,
170
- headers: response.headers
171
- });
172
- return {
173
- data,
174
- response: newResponse
175
- };
176
- }
177
- async function post(url, data, options) {
178
- let body;
179
- const headers = { ...options.headers };
180
- if (typeof data === "string") {
181
- body = data;
182
- } else if (data instanceof FormData || data instanceof URLSearchParams || data instanceof Blob) {
183
- body = data;
184
- } else {
185
- body = JSON.stringify(data);
186
- if (!headers["Content-Type"] && !headers["content-type"]) {
187
- headers["Content-Type"] = "application/json";
188
- }
189
- }
190
- const response = await fetch(url, {
191
- ...options,
192
- headers,
193
- body,
194
- method: "POST"
195
- });
196
- const text = await response.text();
197
- let responseData;
198
- try {
199
- responseData = JSON.parse(text);
200
- } catch {
201
- responseData = text;
202
- }
203
- const newResponse = new Response(text, {
204
- status: response.status,
205
- statusText: response.statusText,
206
- headers: response.headers
207
- });
208
- return {
209
- data: responseData,
210
- response: newResponse
211
- };
212
- }
213
- async function patch(url, data, options) {
214
- let body;
215
- const headers = { ...options.headers };
216
- if (typeof data === "string") {
217
- body = data;
218
- } else if (data instanceof FormData || data instanceof URLSearchParams || data instanceof Blob) {
219
- body = data;
220
- } else {
221
- body = JSON.stringify(data);
222
- if (!headers["Content-Type"] && !headers["content-type"]) {
223
- headers["Content-Type"] = "application/json";
224
- }
225
- }
226
- const response = await fetch(url, {
227
- ...options,
228
- headers,
229
- body,
230
- method: "PATCH"
231
- });
232
- const text = await response.text();
233
- let responseData;
234
- try {
235
- responseData = JSON.parse(text);
236
- } catch {
237
- responseData = text;
238
- }
239
- const newResponse = new Response(text, {
240
- status: response.status,
241
- statusText: response.statusText,
242
- headers: response.headers
243
- });
244
- return {
245
- data: responseData,
246
- response: newResponse
247
- };
248
- }
249
- async function del(url, data, options) {
250
- let actualData;
251
- let actualOptions;
252
- if (data !== void 0 && typeof data === "object" && data !== null && "cache" in data) {
253
- actualData = void 0;
254
- actualOptions = data;
255
- } else if (options) {
256
- actualData = data;
257
- actualOptions = options;
258
- } else {
259
- throw new Error("Fetch options must include a cache instance or options.");
260
- }
261
- let body;
262
- const headers = { ...actualOptions.headers };
263
- if (actualData !== void 0) {
264
- if (typeof actualData === "string") {
265
- body = actualData;
266
- } else if (actualData instanceof FormData || actualData instanceof URLSearchParams || actualData instanceof Blob) {
267
- body = actualData;
268
- } else {
269
- body = JSON.stringify(actualData);
270
- if (!headers["Content-Type"] && !headers["content-type"]) {
271
- headers["Content-Type"] = "application/json";
272
- }
273
- }
274
- }
275
- const response = await fetch(url, {
276
- ...actualOptions,
277
- headers,
278
- body,
279
- method: "DELETE"
280
- });
281
- const text = await response.text();
282
- let responseData;
283
- try {
284
- responseData = JSON.parse(text);
285
- } catch {
286
- responseData = text;
287
- }
288
- const newResponse = new Response(text, {
289
- status: response.status,
290
- statusText: response.statusText,
291
- headers: response.headers
292
- });
293
- return {
294
- data: responseData,
295
- response: newResponse
296
- };
297
- }
298
- async function head(url, options) {
299
- const response = await fetch(url, { ...options, method: "HEAD" });
300
- return response;
301
- }
302
-
303
- // src/index.ts
304
- var CacheableNet = class extends Hookified {
305
- _cache = new Cacheable();
306
- _httpCachePolicy = true;
307
- _stringify = JSON.stringify;
308
- _parse = JSON.parse;
309
- constructor(options) {
310
- super(options);
311
- if (options?.cache) {
312
- this._cache = options.cache instanceof Cacheable ? options.cache : new Cacheable(options.cache);
313
- }
314
- if (options?.httpCachePolicy !== void 0) {
315
- this._httpCachePolicy = options.httpCachePolicy;
316
- }
317
- if (options?.stringify) {
318
- this._stringify = options?.stringify;
319
- }
320
- if (options?.parse) {
321
- this._parse = options?.parse;
322
- }
323
- }
324
- /**
325
- * Get the stringify function used for converting objects to strings.
326
- * @returns {StringifyType} The current stringify function
327
- */
328
- get stringify() {
329
- return this._stringify;
330
- }
331
- /**
332
- * Set the stringify function for converting objects to strings.
333
- * @param {StringifyType} value - The stringify function to use
334
- */
335
- set stringify(value) {
336
- this._stringify = value;
337
- }
338
- /**
339
- * Get the parse function used for converting strings to objects.
340
- * @returns {ParseType} The current parse function
341
- */
342
- get parse() {
343
- return this._parse;
344
- }
345
- /**
346
- * Set the parse function for converting strings to objects.
347
- * @param {ParseType} value - The parse function to use
348
- */
349
- set parse(value) {
350
- this._parse = value;
351
- }
352
- /**
353
- * Get the Cacheable instance used for caching fetch operations.
354
- * @returns {Cacheable} The current Cacheable instance
355
- */
356
- get cache() {
357
- return this._cache;
358
- }
359
- /**
360
- * Set the Cacheable instance for caching fetch operations.
361
- * @param {Cacheable} value - The Cacheable instance to use for caching
362
- */
363
- set cache(value) {
364
- this._cache = value;
365
- }
366
- /**
367
- * Get the current HTTP cache policy setting.
368
- * @returns {boolean} Whether HTTP cache semantics are enabled
369
- */
370
- get httpCachePolicy() {
371
- return this._httpCachePolicy;
372
- }
373
- /**
374
- * Set whether to use HTTP cache semantics.
375
- * @param {boolean} value - Enable or disable HTTP cache semantics
376
- */
377
- set httpCachePolicy(value) {
378
- this._httpCachePolicy = value;
379
- }
380
- /**
381
- * Fetch data from a URL with optional request options. Will use the cache that is already set in the instance.
382
- *
383
- * When `httpCachePolicy` is enabled (default), cache entries will have their TTL
384
- * set based on HTTP cache headers (e.g., Cache-Control: max-age). When disabled,
385
- * the default TTL from the Cacheable instance is used.
386
- *
387
- * @param {string} url The URL to fetch.
388
- * @param {Omit<FetchOptions, "cache">} options Optional request options.
389
- * @returns {Promise<FetchResponse>} The response from the fetch.
390
- */
391
- async fetch(url, options) {
392
- const fetchOptions = {
393
- ...options,
394
- cache: this._cache,
395
- httpCachePolicy: this._httpCachePolicy
396
- };
397
- return fetch(url, fetchOptions);
398
- }
399
- /**
400
- * Perform a GET request to a URL with optional request options. By default caching is enabled on all requests. To
401
- * disable set `options.caching` to false.
402
- * @param {string} url The URL to fetch.
403
- * @param {NetFetchOptions} options Optional request options (method will be set to GET).
404
- * @returns {Promise<DataResponse<T>>} The typed data and response from the fetch.
405
- */
406
- async get(url, options) {
407
- const fetchOptions = {
408
- ...options,
409
- cache: this._cache,
410
- httpCachePolicy: this._httpCachePolicy,
411
- method: "GET"
412
- };
413
- if (options?.caching !== void 0) {
414
- delete fetchOptions.cache;
415
- }
416
- const response = await fetch(url, fetchOptions);
417
- const text = await response.text();
418
- let data;
419
- const parseFn = options?.parse || this._parse;
420
- try {
421
- data = parseFn(text);
422
- } catch {
423
- data = text;
424
- }
425
- const newResponse = new Response(text, {
426
- status: response.status,
427
- statusText: response.statusText,
428
- headers: response.headers
429
- });
430
- return {
431
- data,
432
- response: newResponse
433
- };
434
- }
435
- /**
436
- * Perform a POST request to a URL with data and optional request options. By default caching is not enabled. To enable it
437
- * set `options.caching` to true. Note, setting caching to tru means it will not post if the data is the same.
438
- * @param {string} url The URL to fetch.
439
- * @param {unknown} data The data to send in the request body.
440
- * @param {Omit<NetFetchOptions, "method" | "body" >} options Optional request options (method and body will be set).
441
- * @returns {Promise<DataResponse<T>>} The typed data and response from the fetch.
442
- */
443
- async post(url, data, options) {
444
- let body;
445
- const headers = { ...options?.headers };
446
- if (typeof data === "string") {
447
- body = data;
448
- } else if (data instanceof FormData || data instanceof URLSearchParams || data instanceof Blob) {
449
- body = data;
450
- } else {
451
- const stringifyFn = options?.stringify || this._stringify;
452
- body = stringifyFn(data);
453
- this.setContentType(headers);
454
- }
455
- const fetchOptions = {
456
- ...options,
457
- headers,
458
- body,
459
- httpCachePolicy: this._httpCachePolicy,
460
- method: "POST"
461
- };
462
- if (options?.caching === true) {
463
- fetchOptions.cache = this._cache;
464
- }
465
- const response = await fetch(url, fetchOptions);
466
- const text = await response.text();
467
- let responseData;
468
- const parseFn = options?.parse || this._parse;
469
- try {
470
- responseData = parseFn(text);
471
- } catch {
472
- responseData = text;
473
- }
474
- const newResponse = new Response(text, {
475
- status: response.status,
476
- statusText: response.statusText,
477
- headers: response.headers
478
- });
479
- return {
480
- data: responseData,
481
- response: newResponse
482
- };
483
- }
484
- /**
485
- * Perform a HEAD request to a URL with optional request options. By default caching is enabled on all requests. To
486
- * disable set `options.caching` to false.
487
- * @param {string} url The URL to fetch.
488
- * @param {NetFetchOptions} options Optional request options (method will be set to HEAD).
489
- * @returns {Promise<FetchResponse>} The response from the fetch (no body).
490
- */
491
- async head(url, options) {
492
- const fetchOptions = {
493
- ...options,
494
- cache: this._cache,
495
- httpCachePolicy: this._httpCachePolicy,
496
- method: "HEAD"
497
- };
498
- if (options?.caching !== void 0 && !options.caching) {
499
- delete fetchOptions.cache;
500
- }
501
- const response = await fetch(url, fetchOptions);
502
- return response;
503
- }
504
- /**
505
- * Perform a PUT request to a URL with data and optional request options. By default caching is not enabled. To enable it
506
- * set `options.caching` to true. Note, setting caching to true means it will not put if the data is the same.
507
- * @param {string} url The URL to fetch.
508
- * @param {unknown} data The data to send in the request body.
509
- * @param {Omit<NetFetchOptions, 'method' | 'body'>} options Optional request options (method and body will be set).
510
- * @returns {Promise<DataResponse<T>>} The typed data and response from the fetch.
511
- */
512
- async put(url, data, options) {
513
- let body;
514
- const headers = { ...options?.headers };
515
- if (typeof data === "string") {
516
- body = data;
517
- } else if (data instanceof FormData || data instanceof URLSearchParams || data instanceof Blob) {
518
- body = data;
519
- } else {
520
- const stringifyFn = options?.stringify || this._stringify;
521
- body = stringifyFn(data);
522
- this.setContentType(headers);
523
- }
524
- const fetchOptions = {
525
- ...options,
526
- headers,
527
- body,
528
- httpCachePolicy: this._httpCachePolicy,
529
- method: "PUT"
530
- };
531
- if (options?.caching === true) {
532
- fetchOptions.cache = this._cache;
533
- }
534
- const response = await fetch(url, fetchOptions);
535
- const text = await response.text();
536
- let responseData;
537
- const parseFn = options?.parse || this._parse;
538
- try {
539
- responseData = parseFn(text);
540
- } catch {
541
- responseData = text;
542
- }
543
- const newResponse = new Response(text, {
544
- status: response.status,
545
- statusText: response.statusText,
546
- headers: response.headers
547
- });
548
- return {
549
- data: responseData,
550
- response: newResponse
551
- };
552
- }
553
- /**
554
- * Perform a PATCH request to a URL with data and optional request options. By default caching is not enabled. To enable it
555
- * set `options.caching` to true. Note, setting caching to true means it will not patch if the data is the same.
556
- * @param {string} url The URL to fetch.
557
- * @param {unknown} data The data to send in the request body.
558
- * @param {Omit<NetFetchOptions, 'method' | 'body'>} options Optional request options (method and body will be set).
559
- * @returns {Promise<DataResponse<T>>} The typed data and response from the fetch.
560
- */
561
- async patch(url, data, options) {
562
- let body;
563
- const headers = { ...options?.headers };
564
- if (typeof data === "string") {
565
- body = data;
566
- } else if (data instanceof FormData || data instanceof URLSearchParams || data instanceof Blob) {
567
- body = data;
568
- } else {
569
- const stringifyFn = options?.stringify || this._stringify;
570
- body = stringifyFn(data);
571
- this.setContentType(headers);
572
- }
573
- const fetchOptions = {
574
- ...options,
575
- headers,
576
- body,
577
- httpCachePolicy: this._httpCachePolicy,
578
- method: "PATCH"
579
- };
580
- if (options?.caching === true) {
581
- fetchOptions.cache = this._cache;
582
- }
583
- const response = await fetch(url, fetchOptions);
584
- const text = await response.text();
585
- let responseData;
586
- const parseFn = options?.parse || this._parse;
587
- try {
588
- responseData = parseFn(text);
589
- } catch {
590
- responseData = text;
591
- }
592
- const newResponse = new Response(text, {
593
- status: response.status,
594
- statusText: response.statusText,
595
- headers: response.headers
596
- });
597
- return {
598
- data: responseData,
599
- response: newResponse
600
- };
601
- }
602
- /**
603
- * Perform a DELETE request to a URL with optional data and request options. By default caching is not enabled. To enable it
604
- * set `options.caching` to true. Note, setting caching to true means it will not delete if the data is the same.
605
- * @param {string} url The URL to fetch.
606
- * @param {unknown} data Optional data to send in the request body.
607
- * @param {Omit<NetFetchOptions, 'method' | 'body'>} options Optional request options (method and body will be set).
608
- * @returns {Promise<DataResponse<T>>} The typed data and response from the fetch.
609
- */
610
- async delete(url, data, options) {
611
- let body;
612
- const headers = { ...options?.headers };
613
- if (data !== void 0) {
614
- if (typeof data === "string") {
615
- body = data;
616
- } else if (data instanceof FormData || data instanceof URLSearchParams || data instanceof Blob) {
617
- body = data;
618
- } else {
619
- const stringifyFn = options?.stringify || this._stringify;
620
- body = stringifyFn(data);
621
- this.setContentType(headers);
622
- }
623
- }
624
- const fetchOptions = {
625
- ...options,
626
- headers,
627
- body,
628
- httpCachePolicy: this._httpCachePolicy,
629
- method: "DELETE"
630
- };
631
- if (options?.caching === true) {
632
- fetchOptions.cache = this._cache;
633
- }
634
- const response = await fetch(url, fetchOptions);
635
- const text = await response.text();
636
- let responseData;
637
- const parseFn = options?.parse || this._parse;
638
- try {
639
- responseData = parseFn(text);
640
- } catch {
641
- responseData = text;
642
- }
643
- const newResponse = new Response(text, {
644
- status: response.status,
645
- statusText: response.statusText,
646
- headers: response.headers
647
- });
648
- return {
649
- data: responseData,
650
- response: newResponse
651
- };
652
- }
653
- /**
654
- * Sets the Content-Type header if not already set.
655
- * Checks both "Content-Type" and "content-type" to handle case variations.
656
- * @param headers - The headers object to modify
657
- * @param contentType - The content type to set (defaults to "application/json")
658
- * @private
659
- */
660
- setContentType(headers, contentType = "application/json") {
661
- if (!headers["Content-Type"] && !headers["content-type"]) {
662
- headers["Content-Type"] = contentType;
663
- }
664
- }
665
- };
666
- var Net = CacheableNet;
667
- export {
668
- CacheableNet,
669
- Net,
670
- del,
671
- fetch,
672
- get,
673
- head,
674
- patch,
675
- post
676
- };
677
- /* v8 ignore next -- @preserve */