@naturalcycles/js-lib 15.102.0 → 15.103.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.
@@ -0,0 +1,43 @@
1
+ /// <reference lib="dom" preserve="true" />
2
+ import type { HttpRequestErrorData } from '../error/error.model.js';
3
+ import type { NumberOfMilliseconds } from '../types.js';
4
+ import type { HttpMethod } from './http.model.js';
5
+ /**
6
+ * Minimal wrapper around native `fetch`:
7
+ *
8
+ * - returns json output via Promise
9
+ * - throws FetchError (a plain Error with `cause` and `data`) if anything goes wrong
10
+ * - retries 2 times with simple non-configurable exponential back-off
11
+ *
12
+ * For anything more complex - use the Fetcher.
13
+ * Use this wrapper for the simplest use cases, and where bundle size matters.
14
+ */
15
+ export declare function _fetch<T = unknown>(url: string, opt?: FetchOptions): Promise<T>;
16
+ /**
17
+ * Accepts the commonly used RequestInit options.
18
+ * `signal` is replaced by `timeout`.
19
+ */
20
+ export interface FetchOptions extends Pick<RequestInit, 'body' | 'cache' | 'credentials' | 'keepalive' | 'redirect'> {
21
+ /**
22
+ * Defaults to GET
23
+ */
24
+ method?: HttpMethod;
25
+ headers?: Record<string, string>;
26
+ /**
27
+ * Request body. It's JSON.stringified, and the Content-Type header is set to `application/json`.
28
+ * Takes precedence over `body`.
29
+ */
30
+ json?: any;
31
+ /**
32
+ * Defaults to 30 seconds. 0 disables the timeout.
33
+ * Covers the whole request, including reading the body.
34
+ */
35
+ timeout?: NumberOfMilliseconds;
36
+ }
37
+ /**
38
+ * Thrown by `_fetch`: a plain Error, with the response body text (or the underlying error)
39
+ * as `cause`, and a subset of HttpRequestErrorData as `data`.
40
+ */
41
+ export interface FetchError extends Error {
42
+ data: Pick<HttpRequestErrorData, 'responseStatusCode' | 'requestUrl' | 'requestMethod'>;
43
+ }
@@ -0,0 +1,57 @@
1
+ /// <reference lib="dom" preserve="true" />
2
+ /**
3
+ * Minimal wrapper around native `fetch`:
4
+ *
5
+ * - returns json output via Promise
6
+ * - throws FetchError (a plain Error with `cause` and `data`) if anything goes wrong
7
+ * - retries 2 times with simple non-configurable exponential back-off
8
+ *
9
+ * For anything more complex - use the Fetcher.
10
+ * Use this wrapper for the simplest use cases, and where bundle size matters.
11
+ */
12
+ export async function _fetch(url, opt = {}) {
13
+ const { method = 'GET', timeout = 30_000, json, ...init } = opt;
14
+ if (json !== undefined) {
15
+ init.body = JSON.stringify(json);
16
+ init.headers = { 'content-type': 'application/json', ...init.headers };
17
+ }
18
+ let res;
19
+ let cause;
20
+ for (let attempt = 0;; attempt++) {
21
+ res = undefined;
22
+ try {
23
+ res = await fetch(url, {
24
+ ...init,
25
+ method,
26
+ // A fresh signal per attempt, as a timed-out signal stays aborted
27
+ signal: timeout ? AbortSignal.timeout(timeout) : undefined,
28
+ });
29
+ if (res.ok) {
30
+ const text = await res.text();
31
+ return (text ? JSON.parse(text) : {});
32
+ }
33
+ cause = await res.text();
34
+ }
35
+ catch (err) {
36
+ // Network failure, timeout, or failure to read/parse the body
37
+ cause = err;
38
+ }
39
+ if (attempt === 2 || !shouldRetry(method, res))
40
+ break;
41
+ await pDelay(1000 * 2 ** attempt); // 1s, then 2s
42
+ }
43
+ const err = Object.assign(
44
+ // E.g `503 GET https://example.com/api`, or `GET https://example.com/api` on a network failure
45
+ new Error([res?.status, method, url].filter(Boolean).join(' '), { cause }), { data: { responseStatusCode: res?.status || 0, requestUrl: url, requestMethod: method } });
46
+ throw err;
47
+ }
48
+ /**
49
+ * Retries network failures (including timeouts), 5xx, 408 and 429.
50
+ * Never retries a POST.
51
+ */
52
+ function shouldRetry(method, res) {
53
+ return (method !== 'POST' && (!res || res.status >= 500 || res.status === 408 || res.status === 429));
54
+ }
55
+ async function pDelay(ms) {
56
+ await new Promise(resolve => setTimeout(resolve, ms));
57
+ }
@@ -1,3 +1,4 @@
1
1
  export * from './fetcher.js';
2
2
  export type * from './fetcher.model.js';
3
3
  export * from './http.model.js';
4
+ export * from './fetch.js';
@@ -1,2 +1,3 @@
1
1
  export * from './fetcher.js';
2
2
  export * from './http.model.js';
3
+ export * from './fetch.js';
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@naturalcycles/js-lib",
3
3
  "type": "module",
4
- "version": "15.102.0",
4
+ "version": "15.103.0",
5
5
  "dependencies": {
6
6
  "tslib": "^2"
7
7
  },
@@ -14,7 +14,7 @@
14
14
  }
15
15
  },
16
16
  "devDependencies": {
17
- "@naturalcycles/dev-lib": "20.72.0",
17
+ "@naturalcycles/dev-lib": "0.0.0",
18
18
  "@types/node": "^26",
19
19
  "@types/semver": "^7",
20
20
  "rolldown": "^1",
@@ -40,6 +40,7 @@
40
40
  "./error": "./dist/error/index.js",
41
41
  "./error/*.js": "./dist/error/*.js",
42
42
  "./http": "./dist/http/index.js",
43
+ "./http/*.js": "./dist/http/*.js",
43
44
  "./intl": "./dist/intl/intl.js",
44
45
  "./log": "./dist/log/commonLogger.js",
45
46
  "./math": "./dist/math/index.js",
@@ -0,0 +1,102 @@
1
+ /// <reference lib="dom" preserve="true" />
2
+
3
+ import type { HttpRequestErrorData } from '../error/error.model.js'
4
+ import type { NumberOfMilliseconds } from '../types.js'
5
+ import type { HttpMethod } from './http.model.js'
6
+
7
+ /**
8
+ * Minimal wrapper around native `fetch`:
9
+ *
10
+ * - returns json output via Promise
11
+ * - throws FetchError (a plain Error with `cause` and `data`) if anything goes wrong
12
+ * - retries 2 times with simple non-configurable exponential back-off
13
+ *
14
+ * For anything more complex - use the Fetcher.
15
+ * Use this wrapper for the simplest use cases, and where bundle size matters.
16
+ */
17
+ export async function _fetch<T = unknown>(url: string, opt: FetchOptions = {}): Promise<T> {
18
+ const { method = 'GET', timeout = 30_000, json, ...init } = opt
19
+ if (json !== undefined) {
20
+ init.body = JSON.stringify(json)
21
+ init.headers = { 'content-type': 'application/json', ...init.headers }
22
+ }
23
+ let res: Response | undefined
24
+ let cause: unknown
25
+
26
+ for (let attempt = 0; ; attempt++) {
27
+ res = undefined
28
+ try {
29
+ res = await fetch(url, {
30
+ ...init,
31
+ method,
32
+ // A fresh signal per attempt, as a timed-out signal stays aborted
33
+ signal: timeout ? AbortSignal.timeout(timeout) : undefined,
34
+ })
35
+ if (res.ok) {
36
+ const text = await res.text()
37
+ return (text ? JSON.parse(text) : {}) as T
38
+ }
39
+ cause = await res.text()
40
+ } catch (err) {
41
+ // Network failure, timeout, or failure to read/parse the body
42
+ cause = err
43
+ }
44
+
45
+ if (attempt === 2 || !shouldRetry(method, res)) break
46
+ await pDelay(1000 * 2 ** attempt) // 1s, then 2s
47
+ }
48
+
49
+ const err: FetchError = Object.assign(
50
+ // E.g `503 GET https://example.com/api`, or `GET https://example.com/api` on a network failure
51
+ new Error([res?.status, method, url].filter(Boolean).join(' '), { cause }),
52
+ { data: { responseStatusCode: res?.status || 0, requestUrl: url, requestMethod: method } },
53
+ )
54
+ throw err
55
+ }
56
+
57
+ /**
58
+ * Retries network failures (including timeouts), 5xx, 408 and 429.
59
+ * Never retries a POST.
60
+ */
61
+ function shouldRetry(method: HttpMethod, res?: Response): boolean {
62
+ return (
63
+ method !== 'POST' && (!res || res.status >= 500 || res.status === 408 || res.status === 429)
64
+ )
65
+ }
66
+
67
+ /**
68
+ * Accepts the commonly used RequestInit options.
69
+ * `signal` is replaced by `timeout`.
70
+ */
71
+ export interface FetchOptions extends Pick<
72
+ RequestInit,
73
+ 'body' | 'cache' | 'credentials' | 'keepalive' | 'redirect'
74
+ > {
75
+ /**
76
+ * Defaults to GET
77
+ */
78
+ method?: HttpMethod
79
+ headers?: Record<string, string>
80
+ /**
81
+ * Request body. It's JSON.stringified, and the Content-Type header is set to `application/json`.
82
+ * Takes precedence over `body`.
83
+ */
84
+ json?: any
85
+ /**
86
+ * Defaults to 30 seconds. 0 disables the timeout.
87
+ * Covers the whole request, including reading the body.
88
+ */
89
+ timeout?: NumberOfMilliseconds
90
+ }
91
+
92
+ /**
93
+ * Thrown by `_fetch`: a plain Error, with the response body text (or the underlying error)
94
+ * as `cause`, and a subset of HttpRequestErrorData as `data`.
95
+ */
96
+ export interface FetchError extends Error {
97
+ data: Pick<HttpRequestErrorData, 'responseStatusCode' | 'requestUrl' | 'requestMethod'>
98
+ }
99
+
100
+ async function pDelay<T>(ms: NumberOfMilliseconds): Promise<void> {
101
+ await new Promise<T>(resolve => setTimeout(resolve, ms))
102
+ }
package/src/http/index.ts CHANGED
@@ -1,3 +1,4 @@
1
1
  export * from './fetcher.js'
2
2
  export type * from './fetcher.model.js'
3
3
  export * from './http.model.js'
4
+ export * from './fetch.js'