2020-05-12 21:58:21 +02:00
|
|
|
// Polyfill fetch() in the Node.js environment
|
2022-09-27 22:37:28 +02:00
|
|
|
|
2020-05-12 21:58:21 +02:00
|
|
|
if (!global.fetch) {
|
2022-09-27 22:37:28 +02:00
|
|
|
function getFetchImpl() {
|
|
|
|
return global.__NEXT_USE_UNDICI
|
|
|
|
? require('next/dist/compiled/undici')
|
|
|
|
: require('next/dist/compiled/node-fetch')
|
|
|
|
}
|
|
|
|
// Due to limitation of global configuration, we have to do this resolution at runtime
|
|
|
|
global.fetch = (...args) => {
|
|
|
|
const fetchImpl = getFetchImpl()
|
|
|
|
|
|
|
|
if (global.__NEXT_USE_UNDICI) {
|
|
|
|
// Undici does not support the `keepAlive` option,
|
|
|
|
// instead we have to pass a custom dispatcher
|
|
|
|
if (
|
|
|
|
!global.__NEXT_HTTP_AGENT_OPTIONS?.keepAlive &&
|
|
|
|
!global.__NEXT_UNDICI_AGENT_SET
|
|
|
|
) {
|
|
|
|
global.__NEXT_UNDICI_AGENT_SET = true
|
|
|
|
fetchImpl.setGlobalDispatcher(new fetchImpl.Agent({ pipelining: 0 }))
|
|
|
|
}
|
|
|
|
return fetchImpl.fetch(...args)
|
2021-07-22 16:34:33 +02:00
|
|
|
}
|
2022-09-27 22:37:28 +02:00
|
|
|
const agent = ({ protocol }) =>
|
|
|
|
protocol === 'http:'
|
|
|
|
? global.__NEXT_HTTP_AGENT
|
|
|
|
: global.__NEXT_HTTPS_AGENT
|
|
|
|
|
|
|
|
if (!args[1]) {
|
|
|
|
args[1] = { agent }
|
|
|
|
} else if (!args[1].agent) {
|
|
|
|
args[1].agent = agent
|
|
|
|
}
|
|
|
|
|
|
|
|
return fetchImpl(...args)
|
2021-07-22 16:34:33 +02:00
|
|
|
}
|
2022-09-27 22:37:28 +02:00
|
|
|
|
|
|
|
Object.defineProperties(global, {
|
|
|
|
Headers: {
|
|
|
|
get() {
|
|
|
|
return getFetchImpl().Headers
|
|
|
|
},
|
|
|
|
},
|
|
|
|
Request: {
|
|
|
|
get() {
|
|
|
|
return getFetchImpl().Request
|
|
|
|
},
|
|
|
|
},
|
|
|
|
Response: {
|
|
|
|
get() {
|
|
|
|
return getFetchImpl().Response
|
|
|
|
},
|
|
|
|
},
|
|
|
|
})
|
2020-05-12 21:58:21 +02:00
|
|
|
}
|