Repository: zeit/fetch Branch: main Commit: d858e2ca1bea Files: 33 Total size: 41.2 KB Directory structure: gitextract_bc4d8nlq/ ├── .changeset/ │ ├── README.md │ └── config.json ├── .eslintrc.js ├── .github/ │ └── workflows/ │ ├── ci.yml │ └── release.yml ├── .gitignore ├── .husky/ │ └── pre-commit ├── CODE_OF_CONDUCT.md ├── CONTRIBUTING.md ├── package.json ├── packages/ │ ├── fetch/ │ │ ├── CHANGELOG.md │ │ ├── LICENSE │ │ ├── index.d.ts │ │ ├── index.js │ │ ├── package.json │ │ ├── readme.md │ │ └── test/ │ │ └── index.js │ ├── fetch-cached-dns/ │ │ ├── CHANGELOG.md │ │ ├── LICENSE │ │ ├── README.md │ │ ├── index.d.ts │ │ ├── index.js │ │ ├── package.json │ │ ├── test.js │ │ └── util.js │ └── fetch-retry/ │ ├── LICENSE │ ├── index.js │ ├── package.json │ ├── readme.md │ └── test.js ├── pnpm-workspace.yaml ├── readme.md └── turbo.json ================================================ FILE CONTENTS ================================================ ================================================ FILE: .changeset/README.md ================================================ # Changesets Hello and welcome! This folder has been automatically generated by `@changesets/cli`, a build tool that works with multi-package repos, or single-package repos to help you version and publish your code. You can find the full documentation for it [in our repository](https://github.com/changesets/changesets) We have a quick list of common questions to get you started engaging with this project in [our documentation](https://github.com/changesets/changesets/blob/main/docs/common-questions.md) ================================================ FILE: .changeset/config.json ================================================ { "$schema": "https://unpkg.com/@changesets/config@2.1.1/schema.json", "changelog": "@changesets/cli/changelog", "commit": false, "fixed": [], "linked": [], "access": "public", "baseBranch": "main", "updateInternalDependencies": "patch", "ignore": [] } ================================================ FILE: .eslintrc.js ================================================ module.exports = { extends: [require.resolve('@vercel/style-guide/eslint/node')], overrides: [ { files: ['**/__tests__/**/*.[jt]s?(x)', '**/?(*.)+(spec|test).[jt]s?(x)'], extends: [require.resolve('@vercel/style-guide/eslint/jest')], rules: { 'jest/no-disabled-tests': 'off', 'jest/expect-expect': 'off', 'jest/no-conditional-expect': 'off', }, }, ], rules: { /* These rules are temporarily disabled. The TypeScript rewrite will resolve all outstanding issues. */ 'no-multi-assign': 'off', 'no-param-reassign': 'off', 'no-bitwise': 'off', camelcase: 'off', 'func-names': 'off', eqeqeq: 'off', }, }; ================================================ FILE: .github/workflows/ci.yml ================================================ name: CI on: push: branches: ['main'] pull_request: type: [opened, synchronize] jobs: test: name: Test Node.js ${{ matrix.node-version }} on ${{ matrix.os }} strategy: matrix: os: [ubuntu-latest, macos-latest, windows-latest] node-version: [12.x, 14.x, 16.x] runs-on: ${{ matrix.os }} steps: - uses: actions/checkout@v2 - uses: pnpm/action-setup@v2.2.2 with: version: 6.34.0 - uses: actions/setup-node@v2 with: node-version: ${{ matrix.node-version }} cache: 'pnpm' - name: Install Dependencies run: pnpm install - name: Run Linter run: pnpm lint - name: Run Tests run: pnpm test ================================================ FILE: .github/workflows/release.yml ================================================ name: Release on: push: branches: - main concurrency: group: ${{ github.workflow }}-${{ github.ref }} jobs: release: name: Release runs-on: ubuntu-latest steps: - name: Checkout uses: actions/checkout@v3 - name: Setup pnpm uses: pnpm/action-setup@v2.2.2 with: version: 6.34.0 - name: Setup Node uses: actions/setup-node@v2 with: node-version: 16 cache: 'pnpm' - name: Install Dependencies run: pnpm install - name: Create Release PR or Publish Packages uses: changesets/action@v1 with: publish: pnpm release version: pnpm version-packages commit: 'chore: update package versions' title: 'chore: update package versions' env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} NPM_TOKEN: ${{ secrets.NPM_TOKEN_ELEVATED }} ================================================ FILE: .gitignore ================================================ # See https://help.github.com/articles/ignoring-files/ for more about ignoring files. # dependencies node_modules .pnp .pnp.js # testing coverage # next.js .next/ out/ build # misc .DS_Store *.pem # debug npm-debug.log* yarn-debug.log* yarn-error.log* .pnpm-debug.log* # local env files .env.local .env.development.local .env.test.local .env.production.local # turbo .turbo ================================================ FILE: .husky/pre-commit ================================================ #!/bin/sh . "$(dirname "$0")/_/husky.sh" pnpm pretty-quick --staged ================================================ FILE: CODE_OF_CONDUCT.md ================================================ ## Code of Conduct ### Our Pledge We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, caste, color, religion, or sexual identity and orientation. We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community. ### Our Standards Examples of behavior that contributes to a positive environment for our community include: - Demonstrating empathy and kindness toward other people - Being respectful of differing opinions, viewpoints, and experiences - Giving and gracefully accepting constructive feedback - Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience - Focusing on what is best not just for us as individuals, but for the overall community Examples of unacceptable behavior include: - The use of sexualized language or imagery, and sexual attention or advances of any kind - Trolling, insulting or derogatory comments, and personal or political attacks - Public or private harassment - Publishing others’ private information, such as a physical or email address, without their explicit permission - Other conduct which could reasonably be considered inappropriate in a professional setting ### Enforcement Responsibilities Project maintainers are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful. Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for moderation decisions when appropriate. ### Scope This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. ### Enforcement Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the project team responsible for enforcement at [coc@vercel.com](mailto:coc@vercel.com). All complaints will be reviewed and investigated promptly and fairly. All project maintainers are obligated to respect the privacy and security of the reporter of any incident. Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership. ### Attribution This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.1, available at [https://www.contributor-covenant.org/version/2/1/code_of_conduct/][version] [homepage]: http://contributor-covenant.org [version]: https://www.contributor-covenant.org/version/2/1 ================================================ FILE: CONTRIBUTING.md ================================================ # Contributing Read about our [Commitment to Open Source](https://vercel.com/oss). Before jumping into a PR be sure to search [existing PRs](https://github.com/vercel/fetch/pulls) or [issues](https://github.com/vercel/fetch/issues) for an open or closed item that relates to your submission. ## Developing The development branch is `main`. This is the branch that all pull requests should be made against. To develop locally: 1. [Fork](https://help.github.com/articles/fork-a-repo/) this repository to your own GitHub account and then [clone](https://help.github.com/articles/cloning-a-repository/) it to your local device. 2. Create a new branch: ``` git checkout -b MY_BRANCH_NAME ``` 3. Install pnpm: ``` npm install -g pnpm ``` 4. Install the dependencies with: ``` pnpm i ``` 5. Make changes and run tests using: ``` pnpm test ``` > This repo is powered by [Turborepo](https://turborepo.org/). Running commands such as `test`, `build`, and `lint` from the project root will utilize caching techniques to maximize developer productivity. ## Testing Each package has its own approach to testing. They can be executed independantly or as a group using `turbo`. The easiest way to run the complete test suite is to run `pnpm test` from the root of this repository. ## Linting > 🏗 Coming Soon! ================================================ FILE: package.json ================================================ { "private": true, "workspaces": [ "packages/fetch", "packages/fetch-cached-dns", "packages/fetch-retry" ], "scripts": { "lint": "turbo run lint", "test": "turbo run test", "prettier": "prettier -w .", "prepare": "husky install", "eslint": "cross-env TIMING=1 eslint --max-warnings 0 --config .eslintrc.js", "changeset": "changeset", "release": "changeset publish", "version-packages": "changeset version" }, "devDependencies": { "@babel/core": "^7.17.10", "@changesets/cli": "^2.24.4", "@vercel/style-guide": "^3.0.0", "cross-env": "^7.0.3", "eslint": "^8.12.0", "husky": "^7.0.4", "prettier": "^2.6.1", "pretty-quick": "^3.1.3", "turbo": "^1.2.6", "typescript": "^4.6.4" }, "engines": { "node": ">=12.0.0" }, "packageManager": "pnpm@6.34.0", "prettier": "@vercel/style-guide/prettier" } ================================================ FILE: packages/fetch/CHANGELOG.md ================================================ # @vercel/fetch ## 7.0.0 ### Major Changes - 714c01e: Fix how default agent options are applied ================================================ FILE: packages/fetch/LICENSE ================================================ MIT License Copyright (c) 2017, 2018 ZEIT, Inc. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ================================================ FILE: packages/fetch/index.d.ts ================================================ import * as http from 'http'; import * as https from 'http'; import { Options as BaseRetryOptions } from 'async-retry'; import { Headers, Request, RequestInit, Response } from 'node-fetch'; export interface RetryOptions extends BaseRetryOptions { maxRetryAfter?: number; } export type FetchOptions = RequestInit & { agent?: https.Agent | http.Agent; retry?: RetryOptions; }; export type Fetch = ( url: string | Request, options?: FetchOptions, ) => Promise; export type FetchModule = { default: Fetch; Headers: typeof Headers; }; export default function SetupFetch( fetchModule?: FetchModule, agentOptions?: http.AgentOptions | https.AgentOptions, ): Fetch; export * from 'node-fetch'; ================================================ FILE: packages/fetch/index.js ================================================ const { URLSearchParams, parse: parseUrl } = require('url'); const HttpAgent = require('agentkeepalive'); const debug = require('debug')('@vercel/fetch'); const setupFetchRetry = require('@vercel/fetch-retry'); const setupFetchCachedDns = require('@vercel/fetch-cached-dns'); const AGENT_OPTIONS = { maxSockets: 200, maxFreeSockets: 20, timeout: 60000, freeSocketTimeout: 30000, freeSocketKeepAliveTimeout: 30000, // free socket keepalive for 30 seconds }; let defaultHttpGlobalAgent; let defaultHttpsGlobalAgent; function getDefaultHttpGlobalAgent(agentOpts) { return (defaultHttpGlobalAgent = defaultHttpGlobalAgent || (debug('init http agent'), new HttpAgent(agentOpts))); } function getDefaultHttpsGlobalAgent(agentOpts) { return (defaultHttpsGlobalAgent = defaultHttpsGlobalAgent || (debug('init https agent'), new HttpAgent.HttpsAgent(agentOpts))); } function getAgent(url, agentOpts) { return /^https/.test(url) ? getDefaultHttpsGlobalAgent(agentOpts) : getDefaultHttpGlobalAgent(agentOpts); } function setupVercelFetch(fetch, agentOpts = {}) { return async function vercelFetch(url, opts = {}) { if (!opts.agent) { // Add default `agent` if none was provided opts.agent = getAgent(url, { ...AGENT_OPTIONS, ...agentOpts }); } opts.redirect = 'manual'; opts.headers = new fetch.Headers(opts.headers); // Workaround for node-fetch + agentkeepalive bug/issue opts.headers.set('host', opts.headers.get('host') || parseUrl(url).host); // Convert Object bodies to JSON if they are JS objects if ( opts.body && !(opts.body instanceof URLSearchParams) && typeof opts.body === 'object' && !Buffer.isBuffer(opts.body) ) { opts.body = JSON.stringify(opts.body); opts.headers.set('Content-Type', 'application/json'); opts.headers.set('Content-Length', Buffer.byteLength(opts.body)); } // Check the agent on redirections opts.onRedirect = (res, redirectOpts) => { redirectOpts.agent = getAgent(res.headers.get('Location')); }; try { debug('%s %s', opts.method || 'GET', url); return await fetch(url, opts); } catch (err) { err.url = url; err.opts = opts; throw err; } }; } function setup(fetch, options) { if (!fetch) { fetch = require('node-fetch'); } const fd = fetch.default; if (fd) { // combines "fetch.Headers" with "fetch.default" function. // workaround for "fetch.Headers is not a constructor" fetch = Object.assign((...args) => fd(...args), fd, fetch); } if (typeof fetch !== 'function') { throw new Error( "fetch() argument isn't a function; did you forget to initialize your `@vercel/fetch` import?", ); } fetch = setupFetchCachedDns(fetch); fetch = setupFetchRetry(fetch); fetch = setupVercelFetch(fetch, options); return fetch; } module.exports = setup; ================================================ FILE: packages/fetch/package.json ================================================ { "name": "@vercel/fetch", "version": "7.0.0", "description": "Opinionated `fetch` optimized for use inside microservices", "license": "MIT", "main": "index.js", "types": "index.d.ts", "files": [ "index.js", "index.d.ts" ], "scripts": { "test": "best --verbose", "lint": "cd ../.. && pnpm eslint packages/fetch/**/*.js" }, "repository": { "type": "git", "url": "https://github.com/vercel/fetch.git", "directory": "packages/fetch" }, "contributors": [ "Nathan Rajlich ", "Ethan Arrowood " ], "dependencies": { "@types/async-retry": "^1.4.3", "@vercel/fetch-cached-dns": "^2.0.2", "@vercel/fetch-retry": "^5.0.3", "agentkeepalive": "^4.2.1", "debug": "^4.3.3" }, "peerDependencies": { "@types/node-fetch": "^2.6.1", "node-fetch": "^2.6.7" }, "devDependencies": { "@zeit/best": "0.7.3", "async-listen": "^1.2.0", "node-fetch": "^2.6.7", "raw-body": "^2.5.0" } } ================================================ FILE: packages/fetch/readme.md ================================================ # @vercel/fetch [![Build Status](https://github.com/vercel/fetch/workflows/CI/badge.svg)](https://github.com/vercel/fetch/actions?workflow=CI) Opinionated `fetch` optimized for use inside microservices. Bundles: - https://github.com/vercel/fetch/tree/main/packages/fetch-retry - https://github.com/vercel/fetch/tree/main/packages/fetch-cached-dns - https://github.com/node-modules/agentkeepalive It automatically configures an `agent` via [agentkeepalive](https://github.com/node-modules/agentkeepalive), if not provided, with the following settings: | Name | Value | | ---------------------------- | ----- | | `maxSockets` | 200 | | `maxFreeSockets` | 20 | | `timeout` | 60000 | | `freeSocketKeepAliveTimeout` | 30000 | ## How to use JavaScript ```js const fetch = require('@vercel/fetch')(require('some-fetch-implementation')); ``` TypeScript ```typescript import createFetch from '@vercel/fetch'; import * as fetch from 'some-fetch-implementation'; const fetch = createFetch(fetch); ``` If no fetch implementation is supplied, it will attempt to use peerDep `node-fetch`. ================================================ FILE: packages/fetch/test/index.js ================================================ const assert = require('assert'); const { createServer } = require('http'); const url = require('url'); const toBuffer = require('raw-body'); const listen = require('async-listen').default; const fetch = require('../index')(); exports.retriesUponHttp500 = async () => { let i = 0; const server = createServer((req, res) => { if (i++ < 2) { res.writeHead(500); res.end(); } else { res.end('ha'); } }); await listen(server); const { port } = server.address(); const res = await fetch(`http://127.0.0.1:${port}`); const resBody = await res.text(); server.close(); assert.equal(resBody, 'ha'); }; exports.worksWithHttps = async () => { const res = await fetch('https://vercel.com'); assert.equal(res.headers.get('Server'), 'Vercel'); }; /** * We know that http://zeit.co redirects to https so we can use it * as a test to make sure that we switch the agent when the it * happens */ exports.switchesAgentsOnRedirect = async () => { const res = await fetch('http://vercel.com'); assert.equal(res.url, 'https://vercel.com/'); }; exports.supportsBufferRequestBody = async () => { const server = createServer(async (req, res) => { const body = await toBuffer(req); assert(Buffer.isBuffer(body)); assert.equal(body.toString(), 'foo'); res.end(JSON.stringify({ body: body.toString() })); }); await listen(server); const { port } = server.address(); const res = await fetch(`http://127.0.0.1:${port}`, { method: 'POST', body: Buffer.from('foo'), }); const body = await res.json(); server.close(); assert.deepEqual(body, { body: 'foo' }); }; exports.supportsObjectRequestBody = async () => { const server = createServer(async (req, res) => { const body = await toBuffer(req); assert(Buffer.isBuffer(body)); assert.deepEqual(JSON.parse(body.toString()), { foo: 'bar' }); assert.equal(req.headers['content-type'], 'application/json'); res.end(); }); await listen(server); const { port } = server.address(); const res = await fetch(`http://127.0.0.1:${port}`, { method: 'POST', body: { foo: 'bar' }, }); await res.text(); server.close(); }; exports.supportsSearchParamsRequestBody = async () => { const server = createServer(async (req, res) => { const body = await toBuffer(req); assert(Buffer.isBuffer(body)); assert.equal(body.toString(), 'foo=bar'); assert.equal( req.headers['content-type'], 'application/x-www-form-urlencoded;charset=UTF-8', ); res.end(); }); await listen(server); const { port } = server.address(); const res = await fetch(`http://127.0.0.1:${port}`, { method: 'POST', body: new url.URLSearchParams({ foo: 'bar' }), }); await res.text(); server.close(); }; // Similar to the other unescaped character test in fetch-retry, this is no // longer an error case as node-fetch has switched to using URL instead of // url.parse in its latest versions. This is only an assumption from a quick // investigation into the change history of node-fetch. We should keep this // code here until a more thorough investigation can be done to make sure it // cannot still occur in another way. // // exports.errorContext = async () => { // let err; // const u = `http://127.0.0.1/\u0019`; // try { // await fetch(u); // } catch (_err) { // err = _err; // } // assert(err); // assert.equal(err.message, 'Request path contains unescaped characters'); // assert.equal(err.url, u); // assert.equal(err.opts.redirect, 'manual'); // }; ================================================ FILE: packages/fetch-cached-dns/CHANGELOG.md ================================================ # @vercel/fetch-cached-dns ## 2.1.2 ### Patch Changes - 98cba6d: Fix typings ================================================ FILE: packages/fetch-cached-dns/LICENSE ================================================ MIT License Copyright (c) 2022 Vercel, Inc. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ================================================ FILE: packages/fetch-cached-dns/README.md ================================================ # @vercel/fetch-cached-dns [![Build Status](https://github.com/vercel/fetch/workflows/CI/badge.svg)](https://github.com/vercel/fetch/actions?workflow=CI) A decorator on top of `fetch` that caches the DNS query of the `hostname` of the passed URL. ## How to use ```js const fetch = require('@vercel/fetch-cached-dns')(require('node-fetch')); ``` Since this implementation is implementing redirects we are providing an `onRedirect` extra option to the `fetch` call that gets called with the response object and the options that will be used for the next request. This allows to access the request from outside and to modify the options. _NOTE: if the fetch implementation is not supplied, it will attempt to use peerDep `node-fetch`_ ================================================ FILE: packages/fetch-cached-dns/index.d.ts ================================================ import NodeFetch, { Request, RequestInit, Response } from 'node-fetch'; export default function createFetch(fetch?: typeof NodeFetch): ( url: string | Request, init?: RequestInit, ) => Promise; ================================================ FILE: packages/fetch-cached-dns/index.js ================================================ const { isIP } = require('net'); const { format, parse } = require('url'); const resolve = require('@zeit/dns-cached-resolve').default; const { dnsCachedUrl } = require('./util'); module.exports = setup; const isRedirect = (v) => ((v / 100) | 0) === 3; function setup(fetch) { if (!fetch) { fetch = require('node-fetch'); } const { Headers } = fetch; async function fetchCachedDns(url, opts) { const parsed = parse(url); const originalHost = parsed.host; const ip = isIP(parsed.hostname); if (ip === 0) { if (!opts) opts = {}; opts.headers = new Headers(opts.headers); if (!opts.headers.has('Host')) { opts.headers.set('Host', parsed.host); } opts.redirect = 'manual'; parsed.host = await resolve(parsed.hostname); if (parsed.port) { parsed.host += `:${parsed.port}`; } url = format(parsed); } const res = await fetch(url, opts); // Update `res.url` to contain the original hostname instead of the IP address res[dnsCachedUrl] = url; Object.defineProperty(res, 'url', { get() { return parsed.href; }, }); if (isRedirect(res.status)) { const redirectOpts = { ...opts }; redirectOpts.headers = new Headers(opts.headers); // Per fetch spec, for POST request with 301/302 response, or any // request with 303 response, use GET when following redirect if ( res.status === 303 || ((res.status === 301 || res.status === 302) && opts.method === 'POST') ) { redirectOpts.method = 'GET'; redirectOpts.body = null; redirectOpts.headers.delete('content-length'); } // Set the proper `Host` request header, considering that node-fetch will // absolutize a relative redirect URL, so the IP address needs to be // replaced with the original hostname as well. const location = res.headers.get('Location'); const parsedLocation = parse(location); if (parsedLocation.host === parsed.host) { parsedLocation.host = originalHost; } redirectOpts.headers.set('Host', parsedLocation.host); if (opts.onRedirect) { opts.onRedirect(res, redirectOpts); } return fetchCachedDns(format(parsedLocation), redirectOpts); } return res; } for (const key of Object.keys(fetch)) { fetchCachedDns[key] = fetch[key]; } fetchCachedDns.default = fetchCachedDns; return fetchCachedDns; } ================================================ FILE: packages/fetch-cached-dns/package.json ================================================ { "name": "@vercel/fetch-cached-dns", "version": "2.1.2", "description": "A decorator on top of `fetch` that caches the DNS query of the `hostname` of the passed URL", "license": "MIT", "main": "index.js", "types": "index.d.ts", "files": [ "index.js", "index.d.ts", "util.js" ], "scripts": { "test": "jest test", "lint": "cd ../.. && pnpm eslint packages/fetch-cached-dns/**/*.js" }, "repository": { "type": "git", "url": "https://github.com/vercel/fetch.git", "directory": "packages/fetch-cached-dns" }, "contributors": [ "Nathan Rajlich ", "Ethan Arrowood " ], "dependencies": { "@types/node-fetch": "^2.6.1", "@zeit/dns-cached-resolve": "^2.1.2" }, "peerDependencies": { "node-fetch": "^2.6.1" }, "devDependencies": { "async-listen": "^1.2.0", "jest": "^27.5.1", "node-fetch": "^2.6.1" } } ================================================ FILE: packages/fetch-cached-dns/test.js ================================================ const { createServer } = require('http'); const listen = require('async-listen').default; const { dnsCachedUrl } = require('./util'); const cachedDNSFetch = require('./index')(require('node-fetch')); /** * Using `localtest.me` to use DNS to resolve to localhost * http://readme.localtest.me/ */ test('works with localtest.me', async () => { const server = createServer((req, res) => { res.end(JSON.stringify({ url: req.url, headers: req.headers })); }); await listen(server); const { port } = server.address(); try { const host = `localtest.me:${port}`; const res = await cachedDNSFetch(`http://${host}`); const body = await res.json(); expect(res.url).toBe(`http://${host}/`); expect(res[dnsCachedUrl]).toBe(`http://127.0.0.1:${port}/`); expect(body.url).toBe(`/`); expect(body.headers.host).toBe(host); } finally { server.close(); } }); test('works with absolute redirects', async () => { const serverA = createServer((req, res) => { res.setHeader('Location', `http://localtest.me:${portB}`); res.statusCode = 302; res.end(); }); const serverB = createServer((req, res) => { // ensure the Host header is properly re-written upon redirect res.end(req.headers.host); }); await listen(serverA); await listen(serverB); const portA = serverA.address().port; const portB = serverB.address().port; try { const res = await cachedDNSFetch(`http://localtest.me:${portA}`); expect(res.url).toBe(`http://localtest.me:${portB}/`); expect(res[dnsCachedUrl]).toBe(`http://127.0.0.1:${portB}/`); expect(await res.status).toBe(200); expect(await res.text()).toBe(`localtest.me:${portB}`); } finally { serverA.close(); serverB.close(); } }); test('works with relative redirects', async () => { let count = 0; const server = createServer((req, res) => { if (count++ === 0) { res.setHeader('Location', `/foo`); res.statusCode = 302; res.end(); } else { res.end( JSON.stringify({ url: req.url, headers: req.headers, }), ); } }); await listen(server); const { port } = server.address(); try { const host = `localtest.me:${port}`; const res = await cachedDNSFetch(`http://${host}`); expect(count).toBe(2); expect(res.url).toBe(`http://${host}/foo`); expect(res[dnsCachedUrl]).toBe(`http://127.0.0.1:${port}/foo`); expect(await res.status).toBe(200); const body = await res.json(); expect(body.url).toBe(`/foo`); expect(body.headers.host).toBe(host); } finally { server.close(); } }); test('works with `headers` as an Object', async () => { const server = createServer((req, res) => { res.end(req.headers['x-vercel']); }); await listen(server); const { port } = server.address(); try { const res = await cachedDNSFetch(`http://localtest.me:${port}`, { headers: { 'X-Vercel': 'geist', }, }); expect(await res.text()).toBe('geist'); } finally { server.close(); } }); test('works with `onRedirect` option to customize opts', async () => { let count = 0; const server = createServer((req, res) => { if (count === 0) { res.setHeader('Location', `/foo`); res.statusCode = 302; res.end(); } else { res.end(req.url); } count++; }); await listen(server); const { port } = server.address(); try { const options = { onRedirect: jest.fn((res, opts) => { opts.randomOption = true; }), }; await cachedDNSFetch(`http://localtest.me:${port}`, options); expect(options.onRedirect.mock.calls.length).toBe(1); const [res, opts] = options.onRedirect.mock.calls[0]; expect(res.status).toEqual(302); expect(opts.headers).toBeDefined(); expect(opts.randomOption).toBe(true); } finally { server.close(); } }); ================================================ FILE: packages/fetch-cached-dns/util.js ================================================ // Used for testing exports.dnsCachedUrl = Symbol('dnsCachedUrl'); ================================================ FILE: packages/fetch-retry/LICENSE ================================================ MIT License Copyright (c) 2022 Vercel, Inc. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ================================================ FILE: packages/fetch-retry/index.js ================================================ const retry = require('async-retry'); const debug = require('debug')('fetch-retry'); // retry settings const MIN_TIMEOUT = 10; const MAX_RETRIES = 5; const MAX_RETRY_AFTER = 20; const FACTOR = 6; module.exports = exports = setup; function isClientError(err) { if (!err) return false; return ( err.code === 'ERR_UNESCAPED_CHARACTERS' || err.message === 'Request path contains unescaped characters' ); } function setup(fetch) { if (!fetch) { fetch = require('node-fetch'); } async function fetchRetry(url, opts = {}) { const retryOpts = { // timeouts will be [10, 60, 360, 2160, 12960] // (before randomization is added) minTimeout: MIN_TIMEOUT, retries: MAX_RETRIES, factor: FACTOR, maxRetryAfter: MAX_RETRY_AFTER, ...opts.retry, }; if (opts.onRetry) { retryOpts.onRetry = (error) => { opts.onRetry(error, opts); if (opts.retry && opts.retry.onRetry) { opts.retry.onRetry(error); } }; } try { return await retry(async (bail, attempt) => { const { method = 'GET' } = opts; try { // this will be retried const res = await fetch(url, opts); debug('status %d', res.status); if ((res.status >= 500 && res.status < 600) || res.status === 429) { // NOTE: doesn't support http-date format const retryAfter = parseInt(res.headers.get('retry-after'), 10); if (retryAfter) { if (retryAfter > retryOpts.maxRetryAfter) { return res; } await new Promise((r) => { setTimeout(r, retryAfter * 1e3); }); } throw new ResponseError(res); } else { return res; } } catch (err) { if (err.type === 'aborted') { return bail(err); } const clientError = isClientError(err); const isRetry = !clientError && attempt <= retryOpts.retries; debug( `${method} ${url} error (status = ${err.status}). ${ isRetry ? 'retrying' : '' }`, err, ); if (clientError) { return bail(err); } throw err; } }, retryOpts); } catch (err) { if (err instanceof ResponseError) { return err.res; } throw err; } } for (const key of Object.keys(fetch)) { fetchRetry[key] = fetch[key]; } fetchRetry.default = fetchRetry; return fetchRetry; } class ResponseError extends Error { constructor(res) { super(res.statusText); if (Error.captureStackTrace) { Error.captureStackTrace(this, ResponseError); } this.name = this.constructor.name; this.res = res; // backward compat this.code = this.status = this.statusCode = res.status; this.url = res.url; } } exports.ResponseError = ResponseError; ================================================ FILE: packages/fetch-retry/package.json ================================================ { "name": "@vercel/fetch-retry", "version": "5.1.3", "license": "MIT", "main": "index.js", "files": [ "index.js" ], "scripts": { "test": "jest test", "lint": "cd ../.. && pnpm eslint packages/fetch-retry/**/*.js" }, "repository": { "type": "git", "url": "https://github.com/vercel/fetch.git", "directory": "packages/fetch-retry" }, "contributors": [ "Nathan Rajlich ", "Ethan Arrowood " ], "dependencies": { "async-retry": "^1.3.3", "debug": "^4.3.3" }, "peerDependencies": { "node-fetch": "^2.6.7" }, "devDependencies": { "abort-controller": "^3.0.0", "jest": "^27.5.1", "node-fetch": "^2.6.7" } } ================================================ FILE: packages/fetch-retry/readme.md ================================================ # @vercel/fetch-retry [![Build Status](https://github.com/vercel/fetch/workflows/CI/badge.svg)](https://github.com/vercel/fetch/actions?workflow=CI) A layer on top of `fetch` (via [node-fetch](https://www.npmjs.com/package/node-fetch)) with sensible defaults for retrying to prevent common errors. ## How to use `fetch-retry` is a drop-in replacement for `fetch`: ```js const fetch = require('@vercel/fetch-retry')(require('node-fetch')); module.exports = async () => { const res = await fetch('http://localhost:3000'); console.log(res.status); }; ``` Make sure to `yarn add @vercel/fetch-retry` in your main package. Note that you can pass [retry options](https://github.com/vercel/async-retry) to using `opts.retry`. We also provide a `opts.onRetry` and `opts.retry.maxRetryAfter` options. `opts.onRetry` is a customized version of `opts.retry.onRetry` and passes not only the `error` object in each retry but also the current `opts` object. `opts.retry.maxRetryAfter` is the max wait time according to the `Retry-After` header. If it exceeds the option value, stop retrying and returns the error response. It defaults to `20`. ## Rationale Some errors are very common in production (like the underlying `Socket` yielding `ECONNRESET`), and can easily and instantly be remediated by retrying. The default behavior of `fetch-retry` is to attempt retries **10**, **60** **360**, **2160** and **12960** milliseconds (a total of 5 retries) after a _network error_, _429_ or _5xx_ error occur. The idea is to provide a sensible default: most applications should continue to perform correctly with a worst case scenario of a given request having an additional 15550ms overhead. On the other hand, most applications that use `fetch-retry` instead of vanilla `fetch` should see lower rates of common errors and fewer 'glitches' in production. ## Tests To run rests, execute ```console npm test ``` ================================================ FILE: packages/fetch-retry/test.js ================================================ const assert = require('assert'); const { createServer } = require('http'); const AbortController = require('abort-controller'); const setup = require('./index'); const { ResponseError } = setup; const retryFetch = setup(); test('retries upon 500', async () => { let i = 0; const server = createServer((req, res) => { if (i++ < 2) { res.writeHead(500); res.end(); } else { res.end('ha'); } }); return new Promise((resolve, reject) => { server.listen(async () => { try { const { port } = server.address(); const res = await retryFetch(`http://127.0.0.1:${port}`); expect(await res.text()).toBe('ha'); resolve(); } catch (err) { reject(err); } finally { server.close(); } }); server.on('error', reject); }); }); test('resolves on >MAX_RETRIES', async () => { const server = createServer((req, res) => { res.writeHead(500); res.end(); }); return new Promise((resolve, reject) => { server.listen(async () => { try { const { port } = server.address(); const res = await retryFetch(`http://127.0.0.1:${port}`, { retry: { retries: 3, }, }); expect(res.status).toBe(500); return resolve(); } finally { server.close(); } }); server.on('error', reject); }); }); test('accepts a custom onRetry option', async () => { const server = createServer((req, res) => { res.writeHead(500); res.end(); }); return new Promise((resolve, reject) => { const opts = { onRetry: jest.fn(), retry: { retries: 3, }, }; server.listen(async () => { try { const { port } = server.address(); const res = await retryFetch(`http://127.0.0.1:${port}`, opts); expect(opts.onRetry.mock.calls.length).toBe(3); expect(opts.onRetry.mock.calls[0][0]).toBeInstanceOf(ResponseError); expect(opts.onRetry.mock.calls[0][1]).toEqual(opts); expect(res.status).toBe(500); return resolve(); } finally { server.close(); } }); server.on('error', reject); }); }); test('handles the Retry-After header', async () => { const server = createServer((req, res) => { res.writeHead(429, { 'Retry-After': 1 }); res.end(); }); return new Promise((resolve, reject) => { server.listen(async () => { const { port } = server.address(); try { const startedAt = Date.now(); await retryFetch(`http://127.0.0.1:${port}`, { retry: { minTimeout: 10, retries: 1, }, }); expect(Date.now() - startedAt).toBeGreaterThanOrEqual(1010); resolve(); } catch (err) { reject(err); } finally { server.close(); } }); server.on('error', reject); }); }); test('stops retrying when the Retry-After header exceeds the maxRetryAfter option', async () => { const server = createServer((req, res) => { res.writeHead(429, { 'Retry-After': 21 }); res.end(); }); return new Promise((resolve, reject) => { const opts = { onRetry: jest.fn(), }; server.listen(async () => { const { port } = server.address(); try { const res = await retryFetch(`http://127.0.0.1:${port}`, opts); expect(opts.onRetry.mock.calls.length).toBe(0); expect(res.status).toBe(429); resolve(); } catch (err) { reject(err); } finally { server.close(); } }); server.on('error', reject); }); }); test.skip('stops retrying when fetch throws `ERR_UNESCAPED_CHARACTERS` error', async () => { const opts = { onRetry: jest.fn(), }; let err; try { await retryFetch(`http://127.0.0.1/\u0019`, opts); } catch (_err) { err = _err; } assert(err); assert.equal(err.message, 'Request path contains unescaped characters'); assert.equal(opts.onRetry.mock.calls.length, 0); }); test("don't retry if the request was aborted after timeout", async () => { const timeout = 50; const responseAfter = 100; const server = createServer((req, res) => { setTimeout(() => { res.end('ha'); }, responseAfter); }); const controller = new AbortController(); const timeoutHandler = setTimeout(() => { controller.abort(); }, timeout); const opts = { onRetry: jest.fn(), signal: controller.signal, }; return new Promise((resolve, reject) => { server.listen(async () => { try { const { port } = server.address(); await retryFetch(`http://127.0.0.1:${port}`, opts); resolve(); } catch (err) { expect(opts.onRetry.mock.calls.length).toBe(0); resolve(); } finally { server.close(); clearTimeout(timeoutHandler); } }); server.on('error', reject); }); }); ================================================ FILE: pnpm-workspace.yaml ================================================ packages: - 'packages/**' ================================================ FILE: readme.md ================================================ This repository is now **archived**. See this post for more details: https://github.com/vercel/fetch/issues/83 # Fetch Monorepo This fetch monorepo contains three packages: - `@vercel/fetch` - `@vercel/fetch-retry` - `@vercel/fetch-cached-dns` These packages are designed for use with Node.js in order to bring the familiarity of the Fetch API to the backend. There are future plans to make this project interoperable between both browser and server environments. ## Getting Started `@vercel/fetch` bundles all packages inside this monorepo together into a super-powered [fetch](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) client. By default, this package will use its peer dependency [node-fetch](https://github.com/node-fetch/node-fetch), but it also supports other fetch implementations. ```js // Basic Usage import fetch from '@vercel/fetch'; ``` ```js // Bring your own fetch implementation import createFetch from '@vercel/fetch'; import fetchImpl from 'some-fetch-implementation'; const fetch = createFetch(fetchImpl); ``` ## Contributing Please see our [CONTRIBUTING.md](./CONTRIBUTING.md) ## Code of Conduct Please see our [CODE_OF_CONDUCT.md](./CODE_OF_CONDUCT.md) ================================================ FILE: turbo.json ================================================ { "baseBranch": "origin/main", "pipeline": { "test": {}, "lint": {} } }