@pnpm/network.fetch 1000.2.6

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/LICENSE ADDED
@@ -0,0 +1,22 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2015-2016 Rico Sta. Cruz and other contributors
4
+ Copyright (c) 2016-2026 Zoltan Kochan and other contributors
5
+
6
+ Permission is hereby granted, free of charge, to any person obtaining a copy
7
+ of this software and associated documentation files (the "Software"), to deal
8
+ in the Software without restriction, including without limitation the rights
9
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
+ copies of the Software, and to permit persons to whom the Software is
11
+ furnished to do so, subject to the following conditions:
12
+
13
+ The above copyright notice and this permission notice shall be included in all
14
+ copies or substantial portions of the Software.
15
+
16
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,17 @@
1
+ # @pnpm/fetch
2
+
3
+ > node-fetch with retries
4
+
5
+ <!--@shields('npm')-->
6
+ [![npm version](https://img.shields.io/npm/v/@pnpm/fetch.svg)](https://www.npmjs.com/package/@pnpm/fetch)
7
+ <!--/@-->
8
+
9
+ ## Installation
10
+
11
+ ```sh
12
+ pnpm add @pnpm/fetch
13
+ ```
14
+
15
+ ## License
16
+
17
+ MIT
package/lib/fetch.d.ts ADDED
@@ -0,0 +1,21 @@
1
+ import { type RetryTimeoutOptions } from '@zkochan/retry';
2
+ import { type Request, type RequestInit as NodeRequestInit, Response } from 'node-fetch';
3
+ export { isRedirect } from 'node-fetch';
4
+ export { Response, type RetryTimeoutOptions };
5
+ interface URLLike {
6
+ href: string;
7
+ }
8
+ export type RequestInfo = string | URLLike | Request;
9
+ export interface RequestInit extends NodeRequestInit {
10
+ retry?: RetryTimeoutOptions;
11
+ timeout?: number;
12
+ }
13
+ export declare function fetch(url: RequestInfo, opts?: RequestInit): Promise<Response>;
14
+ export declare class ResponseError extends Error {
15
+ res: Response;
16
+ code: number;
17
+ status: number;
18
+ statusCode: number;
19
+ url: string;
20
+ constructor(res: Response);
21
+ }
package/lib/fetch.js ADDED
@@ -0,0 +1,85 @@
1
+ import assert from 'node:assert';
2
+ import util from 'node:util';
3
+ import { requestRetryLogger } from '@pnpm/core-loggers';
4
+ import { operation } from '@zkochan/retry';
5
+ import nodeFetch, { Response } from 'node-fetch';
6
+ export { isRedirect } from 'node-fetch';
7
+ export { Response };
8
+ const NO_RETRY_ERROR_CODES = new Set([
9
+ 'SELF_SIGNED_CERT_IN_CHAIN',
10
+ 'ERR_OSSL_PEM_NO_START_LINE',
11
+ ]);
12
+ export async function fetch(url, opts = {}) {
13
+ const retryOpts = opts.retry ?? {};
14
+ const maxRetries = retryOpts.retries ?? 2;
15
+ const op = operation({
16
+ factor: retryOpts.factor ?? 10,
17
+ maxTimeout: retryOpts.maxTimeout ?? 60000,
18
+ minTimeout: retryOpts.minTimeout ?? 10000,
19
+ randomize: false,
20
+ retries: maxRetries,
21
+ });
22
+ try {
23
+ return await new Promise((resolve, reject) => {
24
+ op.attempt(async (attempt) => {
25
+ try {
26
+ // this will be retried
27
+ const res = await nodeFetch(url, opts); // eslint-disable-line
28
+ // A retry on 409 sometimes helps when making requests to the Bit registry.
29
+ if ((res.status >= 500 && res.status < 600) || [408, 409, 420, 429].includes(res.status)) {
30
+ throw new ResponseError(res);
31
+ }
32
+ else {
33
+ resolve(res);
34
+ }
35
+ }
36
+ catch (error) {
37
+ assert(util.types.isNativeError(error));
38
+ if ('code' in error &&
39
+ typeof error.code === 'string' &&
40
+ NO_RETRY_ERROR_CODES.has(error.code)) {
41
+ throw error;
42
+ }
43
+ const timeout = op.retry(error);
44
+ if (timeout === false) {
45
+ reject(op.mainError());
46
+ return;
47
+ }
48
+ requestRetryLogger.debug({
49
+ attempt,
50
+ error,
51
+ maxRetries,
52
+ method: opts.method ?? 'GET',
53
+ timeout,
54
+ url: url.toString(),
55
+ });
56
+ }
57
+ });
58
+ });
59
+ }
60
+ catch (err) {
61
+ if (err instanceof ResponseError) {
62
+ return err.res;
63
+ }
64
+ throw err;
65
+ }
66
+ }
67
+ export class ResponseError extends Error {
68
+ res;
69
+ code;
70
+ status;
71
+ statusCode;
72
+ url;
73
+ constructor(res) {
74
+ super(res.statusText);
75
+ if (Error.captureStackTrace) {
76
+ Error.captureStackTrace(this, ResponseError);
77
+ }
78
+ this.name = this.constructor.name;
79
+ this.res = res;
80
+ // backward compat
81
+ this.code = this.status = this.statusCode = res.status;
82
+ this.url = res.url;
83
+ }
84
+ }
85
+ //# sourceMappingURL=fetch.js.map
@@ -0,0 +1,14 @@
1
+ import type { FetchFromRegistry } from '@pnpm/fetching.types';
2
+ import { type AgentOptions } from '@pnpm/network.agent';
3
+ import type { SslConfig } from '@pnpm/types';
4
+ import { type RequestInfo, type RequestInit, type Response } from './fetch.js';
5
+ export interface FetchWithAgentOptions extends RequestInit {
6
+ agentOptions: AgentOptions;
7
+ }
8
+ export declare function fetchWithAgent(url: RequestInfo, opts: FetchWithAgentOptions): Promise<Response>;
9
+ export type { AgentOptions };
10
+ export interface CreateFetchFromRegistryOptions extends AgentOptions {
11
+ userAgent?: string;
12
+ sslConfigs?: Record<string, SslConfig>;
13
+ }
14
+ export declare function createFetchFromRegistry(defaultOpts: CreateFetchFromRegistryOptions): FetchFromRegistry;
@@ -0,0 +1,91 @@
1
+ import { URL } from 'node:url';
2
+ import { getAgent } from '@pnpm/network.agent';
3
+ import { fetch, isRedirect } from './fetch.js';
4
+ const USER_AGENT = 'pnpm'; // or maybe make it `${pkg.name}/${pkg.version} (+https://npm.im/${pkg.name})`
5
+ const FULL_DOC = 'application/json';
6
+ const ACCEPT_FULL_DOC = `${FULL_DOC}; q=1.0, */*`;
7
+ const ABBREVIATED_DOC = 'application/vnd.npm.install-v1+json';
8
+ const ACCEPT_ABBREVIATED_DOC = `${ABBREVIATED_DOC}; q=1.0, ${FULL_DOC}; q=0.8, */*`;
9
+ const MAX_FOLLOWED_REDIRECTS = 20;
10
+ export function fetchWithAgent(url, opts) {
11
+ const agent = getAgent(url.toString(), {
12
+ ...opts.agentOptions,
13
+ strictSsl: opts.agentOptions.strictSsl ?? true,
14
+ }); // eslint-disable-line
15
+ const headers = opts.headers ?? {};
16
+ // @ts-expect-error
17
+ headers['connection'] = agent ? 'keep-alive' : 'close';
18
+ return fetch(url, {
19
+ ...opts,
20
+ agent,
21
+ });
22
+ }
23
+ export function createFetchFromRegistry(defaultOpts) {
24
+ return async (url, opts) => {
25
+ const headers = {
26
+ 'user-agent': USER_AGENT,
27
+ ...getHeaders({
28
+ auth: opts?.authHeaderValue,
29
+ fullMetadata: opts?.fullMetadata,
30
+ userAgent: defaultOpts.userAgent,
31
+ }),
32
+ };
33
+ let redirects = 0;
34
+ let urlObject = new URL(url);
35
+ const originalHost = urlObject.host;
36
+ /* eslint-disable no-await-in-loop */
37
+ while (true) {
38
+ const agentOptions = {
39
+ ...defaultOpts,
40
+ ...opts,
41
+ strictSsl: defaultOpts.strictSsl ?? true,
42
+ }; // eslint-disable-line
43
+ // We should pass a URL object to node-fetch till this is not resolved:
44
+ // https://github.com/bitinn/node-fetch/issues/245
45
+ const response = await fetchWithAgent(urlObject, {
46
+ agentOptions: {
47
+ ...agentOptions,
48
+ clientCertificates: defaultOpts.sslConfigs,
49
+ },
50
+ // if verifying integrity, node-fetch must not decompress
51
+ compress: opts?.compress ?? false,
52
+ method: opts?.method,
53
+ headers,
54
+ redirect: 'manual',
55
+ retry: opts?.retry,
56
+ timeout: opts?.timeout ?? 60000,
57
+ });
58
+ if (!isRedirect(response.status) || redirects >= MAX_FOLLOWED_REDIRECTS) {
59
+ return response;
60
+ }
61
+ redirects++;
62
+ // This is a workaround to remove authorization headers on redirect.
63
+ // Related pnpm issue: https://github.com/pnpm/pnpm/issues/1815
64
+ urlObject = resolveRedirectUrl(response, urlObject);
65
+ if (!headers['authorization'] || originalHost === urlObject.host)
66
+ continue;
67
+ delete headers.authorization;
68
+ }
69
+ /* eslint-enable no-await-in-loop */
70
+ };
71
+ }
72
+ function getHeaders(opts) {
73
+ const headers = {
74
+ accept: opts.fullMetadata === true ? ACCEPT_FULL_DOC : ACCEPT_ABBREVIATED_DOC,
75
+ };
76
+ if (opts.auth) {
77
+ headers['authorization'] = opts.auth;
78
+ }
79
+ if (opts.userAgent) {
80
+ headers['user-agent'] = opts.userAgent;
81
+ }
82
+ return headers;
83
+ }
84
+ function resolveRedirectUrl(response, currentUrl) {
85
+ const location = response.headers.get('location');
86
+ if (!location) {
87
+ throw new Error(`Redirect location header missing for ${currentUrl.toString()}`);
88
+ }
89
+ return new URL(location, currentUrl);
90
+ }
91
+ //# sourceMappingURL=fetchFromRegistry.js.map
package/lib/index.d.ts ADDED
@@ -0,0 +1,3 @@
1
+ export { fetch, type RetryTimeoutOptions } from './fetch.js';
2
+ export { type AgentOptions, createFetchFromRegistry, type CreateFetchFromRegistryOptions, fetchWithAgent } from './fetchFromRegistry.js';
3
+ export type { FetchFromRegistry } from '@pnpm/fetching.types';
package/lib/index.js ADDED
@@ -0,0 +1,3 @@
1
+ export { fetch } from './fetch.js';
2
+ export { createFetchFromRegistry, fetchWithAgent } from './fetchFromRegistry.js';
3
+ //# sourceMappingURL=index.js.map
package/package.json ADDED
@@ -0,0 +1,57 @@
1
+ {
2
+ "name": "@pnpm/network.fetch",
3
+ "version": "1000.2.6",
4
+ "description": "node-fetch with retries",
5
+ "keywords": [
6
+ "pnpm",
7
+ "pnpm11",
8
+ "fetch",
9
+ "npm"
10
+ ],
11
+ "license": "MIT",
12
+ "funding": "https://opencollective.com/pnpm",
13
+ "repository": "https://github.com/pnpm/pnpm/tree/main/network/fetch",
14
+ "homepage": "https://github.com/pnpm/pnpm/tree/main/network/fetch#readme",
15
+ "bugs": {
16
+ "url": "https://github.com/pnpm/pnpm/issues"
17
+ },
18
+ "type": "module",
19
+ "main": "lib/index.js",
20
+ "types": "lib/index.d.ts",
21
+ "exports": {
22
+ ".": "./lib/index.js"
23
+ },
24
+ "files": [
25
+ "lib",
26
+ "!*.map"
27
+ ],
28
+ "dependencies": {
29
+ "@pnpm/network.agent": "^2.0.3",
30
+ "@zkochan/retry": "^0.2.0",
31
+ "node-fetch": "^3.3.2",
32
+ "@pnpm/core-loggers": "1001.0.4",
33
+ "@pnpm/fetching.types": "1000.2.0",
34
+ "@pnpm/types": "1000.9.0"
35
+ },
36
+ "peerDependencies": {
37
+ "@pnpm/logger": ">=1001.0.0 <1002.0.0"
38
+ },
39
+ "devDependencies": {
40
+ "https-proxy-server-express": "0.1.2",
41
+ "nock": "13.3.4",
42
+ "@pnpm/logger": "1001.0.1",
43
+ "@pnpm/network.fetch": "1000.2.6"
44
+ },
45
+ "engines": {
46
+ "node": ">=22.13"
47
+ },
48
+ "jest": {
49
+ "preset": "@pnpm/jest-config"
50
+ },
51
+ "scripts": {
52
+ "lint": "eslint \"src/**/*.ts\" \"test/**/*.ts\"",
53
+ "_test": "cross-env NODE_OPTIONS=\"$NODE_OPTIONS --experimental-vm-modules --disable-warning=ExperimentalWarning --disable-warning=DEP0169\" jest",
54
+ "test": "pnpm run compile && pnpm run _test",
55
+ "compile": "tsgo --build && pnpm run lint --fix"
56
+ }
57
+ }