UNPKG

@whatwg-node/node-fetch

Version:

Fetch API implementation for Node

164 lines (163 loc) • 6.16 kB
"use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || (function () { var ownKeys = function(o) { ownKeys = Object.getOwnPropertyNames || function (o) { var ar = []; for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; return ar; }; return ownKeys(o); }; return function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); __setModuleDefault(result, mod); return result; }; })(); Object.defineProperty(exports, "__esModule", { value: true }); exports.createFetchPonyfill = createFetchPonyfill; exports.fetchPonyfill = fetchPonyfill; const node_buffer_1 = require("node:buffer"); const node_fs_1 = require("node:fs"); const node_url_1 = require("node:url"); const types_1 = require("node:util/types"); const fetchCurl_js_1 = require("./fetchCurl.js"); const fetchUndici_js_1 = require("./fetchUndici.js"); const Request_js_1 = require("./Request.js"); const Response_js_1 = require("./Response.js"); const URL_js_1 = require("./URL.js"); const utils_js_1 = require("./utils.js"); const BASE64_SUFFIX = ';base64'; function getResponseForFile(url) { const path = (0, node_url_1.fileURLToPath)(url); const readable = (0, node_fs_1.createReadStream)(path); return new Response_js_1.PonyfillResponse(readable); } function getResponseForDataUri(url) { const [mimeType = 'text/plain', ...datas] = url.substring(5).split(','); const data = decodeURIComponent(datas.join(',')); if (mimeType.endsWith(BASE64_SUFFIX)) { const buffer = node_buffer_1.Buffer.from(data, 'base64url'); const realMimeType = mimeType.slice(0, -BASE64_SUFFIX.length); return new Response_js_1.PonyfillResponse(buffer, { status: 200, statusText: 'OK', headers: { 'content-type': realMimeType, }, }); } return new Response_js_1.PonyfillResponse(data, { status: 200, statusText: 'OK', headers: { 'content-type': mimeType, }, }); } function getResponseForBlob(url) { const blob = URL_js_1.PonyfillURL.getBlobFromURL(url); if (!blob) { throw new TypeError('Invalid Blob URL'); } return new Response_js_1.PonyfillResponse(blob, { status: 200, headers: { 'content-type': blob.type, 'content-length': blob.size.toString(), }, }); } function isURL(obj) { return obj != null && obj.href != null; } let fetchFn$; let fetchFn; function getNativeGlobalDispatcher() { // @ts-expect-error - We know it is there return globalThis[Symbol.for('undici.globalDispatcher.1')]; } function createFetchFn() { const libcurlModuleName = 'node-libcurl'; const undiciModuleName = 'undici'; if (process.env.DEBUG) { console.debug(`[@whatwg-node/node-fetch] - Trying to import ${libcurlModuleName} for fetch ponyfill`); } return Promise.resolve(`${libcurlModuleName}`).then(s => __importStar(require(s))).then(libcurl => (0, fetchCurl_js_1.createFetchCurl)(libcurl), () => { if (process.env.DEBUG) { console.debug(`[@whatwg-node/node-fetch] - Failed to import ${libcurlModuleName}, trying ${undiciModuleName}`); } return Promise.resolve(`${undiciModuleName}`).then(s => __importStar(require(s))).then((undici) => (0, fetchUndici_js_1.createFetchUndici)(() => undici.getGlobalDispatcher()), () => { if (process.env.DEBUG) { console.debug(`[@whatwg-node/node-fetch] - Failed to import ${undiciModuleName}, falling back to built-in undici in Node`); } return (0, fetchUndici_js_1.createFetchUndici)(getNativeGlobalDispatcher); }); }); } function fetchNonHttp(fetchRequest) { if (fetchRequest.url.startsWith('data:')) { const response = getResponseForDataUri(fetchRequest.url); return (0, utils_js_1.fakePromise)(response); } if (fetchRequest.url.startsWith('file:')) { const response = getResponseForFile(fetchRequest.url); return (0, utils_js_1.fakePromise)(response); } if (fetchRequest.url.startsWith('blob:')) { const response = getResponseForBlob(fetchRequest.url); return (0, utils_js_1.fakePromise)(response); } } function normalizeInfo(info, init) { if (typeof info === 'string' || isURL(info)) { return new Request_js_1.PonyfillRequest(info, init); } return info; } function createFetchPonyfill(fetchFn) { return function fetchPonyfill(info, init) { info = normalizeInfo(info, init); const nonHttpRes = fetchNonHttp(info); if (nonHttpRes) { return nonHttpRes; } return fetchFn(info); }; } function fetchPonyfill(info, init) { info = normalizeInfo(info, init); const nonHttpRes = fetchNonHttp(info); if (nonHttpRes) { return nonHttpRes; } if (!fetchFn) { fetchFn$ ||= createFetchFn(); if ((0, types_1.isPromise)(fetchFn$)) { return fetchFn$.then(newFetchFn => { fetchFn = newFetchFn; return fetchFn(info); }); } fetchFn = fetchFn$; } return fetchFn(info); }