Unverified Commit 02eb34db authored by Hannes Bornö's avatar Hannes Bornö Committed by GitHub

Use https_proxy environment variable in next/font/google (#46822)

When fetching CSS or font files from Google Fonts, it won't work if
you're required to use a proxy. This change makes it look for the
`http(s)_proxy` environment variable, and if it's defined it creates a
fetch agent using
[https-proxy-agent](https://github.com/TooTallNate/node-https-proxy-agent).

Also fixes fetch errors not being properly logged.

Fixes #45034
Closes NEXT-690

## Bug

- [ ] Related issues linked using `fixes #number`
- [ ] Integration tests added
- [ ] Errors have a helpful link attached, see
[`contributing.md`](https://github.com/vercel/next.js/blob/canary/contributing.md)

## Feature

- [ ] Implements an existing feature request or RFC. Make sure the
feature request has been accepted for implementation before opening a
PR.
- [ ] Related issues linked using `fixes #number`
- [ ]
[e2e](https://github.com/vercel/next.js/blob/canary/contributing/core/testing.md#writing-tests-for-nextjs)
tests added
- [ ] Documentation added
- [ ] Telemetry added. In case of a feature if it's used or not.
- [ ] Errors have a helpful link attached, see
[`contributing.md`](https://github.com/vercel/next.js/blob/canary/contributing.md)

## Documentation / Examples

- [ ] Make sure the linting passes by running `pnpm build && pnpm lint`
- [ ] The "examples guidelines" are followed from [our contributing
doc](https://github.com/vercel/next.js/blob/canary/contributing/examples/adding-examples.md)
parent f99ae5af
// @ts-ignore
import fetch from 'next/dist/compiled/node-fetch'
import { nextFontError } from '../next-font-error'
import { getProxyAgent } from './get-proxy-agent'
/**
* Fetches the CSS containing the @font-face declarations from Google Fonts.
* The fetch has a user agent header with a modern browser to ensure we'll get .woff2 files.
*
* The env variable NEXT_FONT_GOOGLE_MOCKED_RESPONSES may be set containing a path to mocked data.
* It's used to defined mocked data to avoid hitting the Google Fonts API during tests.
* It's used to define mocked data to avoid hitting the Google Fonts API during tests.
*/
export async function fetchCSSFromGoogleFonts(
url: string,
......@@ -32,6 +33,7 @@ export async function fetchCSSFromGoogleFonts(
const controller = new AbortController()
const timeoutId = setTimeout(() => controller.abort(), 3000)
const res = await fetch(url, {
agent: getProxyAgent(),
// Add a timeout in dev
signal: isDev ? controller.signal : undefined,
headers: {
......
// @ts-ignore
import fetch from 'next/dist/compiled/node-fetch'
import { getProxyAgent } from './get-proxy-agent'
/**
* Fetch the url and return a buffer with the font file.
......@@ -18,6 +19,7 @@ export async function fetchFontFile(url: string, isDev: boolean) {
const controller = new AbortController()
const timeoutId = setTimeout(() => controller.abort(), 3000)
const arrayBuffer = await fetch(url, {
agent: getProxyAgent(),
// Add a timeout in dev
signal: isDev ? controller.signal : undefined,
})
......
// @ts-ignore
import HttpsProxyAgent from 'next/dist/compiled/https-proxy-agent'
// @ts-ignore
import HttpProxyAgent from 'next/dist/compiled/http-proxy-agent'
import { Agent } from 'https'
/**
* If the http(s)_proxy environment variables is set, return a proxy agent.
*/
export function getProxyAgent(): Agent | undefined {
const httpsProxy = process.env['https_proxy'] || process.env['HTTPS_PROXY']
if (httpsProxy) {
return new HttpsProxyAgent(httpsProxy)
}
const httpProxy = process.env['http_proxy'] || process.env['HTTP_PROXY']
if (httpProxy) {
return new HttpProxyAgent(httpProxy)
}
}
......@@ -82,7 +82,10 @@ const nextFontGoogleFontLoader: FontLoader = async ({
// Fetch CSS from Google Fonts or get it from the cache
let fontFaceDeclarations = hasCachedCSS
? cssCache.get(url)
: await fetchCSSFromGoogleFonts(url, fontFamily, isDev).catch(() => null)
: await fetchCSSFromGoogleFonts(url, fontFamily, isDev).catch((err) => {
console.error(err)
return null
})
if (!hasCachedCSS) {
cssCache.set(url, fontFaceDeclarations ?? null)
} else {
......@@ -108,7 +111,10 @@ const nextFontGoogleFontLoader: FontLoader = async ({
// Download the font file or get it from cache
const fontFileBuffer = hasCachedFont
? fontCache.get(googleFontFileUrl)
: await fetchFontFile(googleFontFileUrl, isDev).catch(() => null)
: await fetchFontFile(googleFontFileUrl, isDev).catch((err) => {
console.error(err)
return null
})
if (!hasCachedFont) {
fontCache.set(googleFontFileUrl, fontFileBuffer ?? null)
} else {
......@@ -158,7 +164,6 @@ const nextFontGoogleFontLoader: FontLoader = async ({
} catch (err) {
if (isDev) {
if (isServer) {
console.error(err)
Log.error(
`Failed to download \`${fontFamily}\` from Google Fonts. Using fallback font instead.`
)
......
......@@ -225,7 +225,9 @@
"glob": "7.1.7",
"gzip-size": "5.1.1",
"http-proxy": "1.18.1",
"http-proxy-agent": "5.0.0",
"https-browserify": "1.0.0",
"https-proxy-agent": "5.0.1",
"icss-utils": "5.1.0",
"ignore-loader": "0.1.2",
"image-size": "1.0.0",
......
(()=>{"use strict";var t={862:(t,e)=>{Object.defineProperty(e,"__esModule",{value:true});function once(t,e,{signal:o}={}){return new Promise(((r,n)=>{function cleanup(){o===null||o===void 0?void 0:o.removeEventListener("abort",cleanup);t.removeListener(e,onEvent);t.removeListener("error",onError)}function onEvent(...t){cleanup();r(t)}function onError(t){cleanup();n(t)}o===null||o===void 0?void 0:o.addEventListener("abort",cleanup);t.on(e,onEvent);t.on("error",onError)}))}e["default"]=once},448:function(t,e,o){var r=this&&this.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};const n=o(361);const i=r(o(937));const s=r(o(457));const u=i.default("agent-base");function isAgent(t){return Boolean(t)&&typeof t.addRequest==="function"}function isSecureEndpoint(){const{stack:t}=new Error;if(typeof t!=="string")return false;return t.split("\n").some((t=>t.indexOf("(https.js:")!==-1||t.indexOf("node:https:")!==-1))}function createAgent(t,e){return new createAgent.Agent(t,e)}(function(t){class Agent extends n.EventEmitter{constructor(t,e){super();let o=e;if(typeof t==="function"){this.callback=t}else if(t){o=t}this.timeout=null;if(o&&typeof o.timeout==="number"){this.timeout=o.timeout}this.maxFreeSockets=1;this.maxSockets=1;this.maxTotalSockets=Infinity;this.sockets={};this.freeSockets={};this.requests={};this.options={}}get defaultPort(){if(typeof this.explicitDefaultPort==="number"){return this.explicitDefaultPort}return isSecureEndpoint()?443:80}set defaultPort(t){this.explicitDefaultPort=t}get protocol(){if(typeof this.explicitProtocol==="string"){return this.explicitProtocol}return isSecureEndpoint()?"https:":"http:"}set protocol(t){this.explicitProtocol=t}callback(t,e,o){throw new Error('"agent-base" has no default implementation, you must subclass and override `callback()`')}addRequest(t,e){const o=Object.assign({},e);if(typeof o.secureEndpoint!=="boolean"){o.secureEndpoint=isSecureEndpoint()}if(o.host==null){o.host="localhost"}if(o.port==null){o.port=o.secureEndpoint?443:80}if(o.protocol==null){o.protocol=o.secureEndpoint?"https:":"http:"}if(o.host&&o.path){delete o.path}delete o.agent;delete o.hostname;delete o._defaultAgent;delete o.defaultPort;delete o.createConnection;t._last=true;t.shouldKeepAlive=false;let r=false;let n=null;const i=o.timeout||this.timeout;const onerror=e=>{if(t._hadError)return;t.emit("error",e);t._hadError=true};const ontimeout=()=>{n=null;r=true;const t=new Error(`A "socket" was not created for HTTP request before ${i}ms`);t.code="ETIMEOUT";onerror(t)};const callbackError=t=>{if(r)return;if(n!==null){clearTimeout(n);n=null}onerror(t)};const onsocket=e=>{if(r)return;if(n!=null){clearTimeout(n);n=null}if(isAgent(e)){u("Callback returned another Agent instance %o",e.constructor.name);e.addRequest(t,o);return}if(e){e.once("free",(()=>{this.freeSocket(e,o)}));t.onSocket(e);return}const i=new Error(`no Duplex stream was returned to agent-base for \`${t.method} ${t.path}\``);onerror(i)};if(typeof this.callback!=="function"){onerror(new Error("`callback` is not defined"));return}if(!this.promisifiedCallback){if(this.callback.length>=3){u("Converting legacy callback function to promise");this.promisifiedCallback=s.default(this.callback)}else{this.promisifiedCallback=this.callback}}if(typeof i==="number"&&i>0){n=setTimeout(ontimeout,i)}if("port"in o&&typeof o.port!=="number"){o.port=Number(o.port)}try{u("Resolving socket for %o request: %o",o.protocol,`${t.method} ${t.path}`);Promise.resolve(this.promisifiedCallback(t,o)).then(onsocket,callbackError)}catch(t){Promise.reject(t).catch(callbackError)}}freeSocket(t,e){u("Freeing socket %o %o",t.constructor.name,e);t.destroy()}destroy(){u("Destroying agent %o",this.constructor.name)}}t.Agent=Agent;t.prototype=t.Agent.prototype})(createAgent||(createAgent={}));t.exports=createAgent},457:(t,e)=>{Object.defineProperty(e,"__esModule",{value:true});function promisify(t){return function(e,o){return new Promise(((r,n)=>{t.call(this,e,o,((t,e)=>{if(t){n(t)}else{r(e)}}))}))}}e["default"]=promisify},386:function(t,e,o){var r=this&&this.__awaiter||function(t,e,o,r){function adopt(t){return t instanceof o?t:new o((function(e){e(t)}))}return new(o||(o=Promise))((function(o,n){function fulfilled(t){try{step(r.next(t))}catch(t){n(t)}}function rejected(t){try{step(r["throw"](t))}catch(t){n(t)}}function step(t){t.done?o(t.value):adopt(t.value).then(fulfilled,rejected)}step((r=r.apply(t,e||[])).next())}))};var n=this&&this.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(e,"__esModule",{value:true});const i=n(o(808));const s=n(o(404));const u=n(o(310));const a=n(o(937));const c=n(o(862));const l=o(448);const f=(0,a.default)("http-proxy-agent");function isHTTPS(t){return typeof t==="string"?/^https:?$/i.test(t):false}class HttpProxyAgent extends l.Agent{constructor(t){let e;if(typeof t==="string"){e=u.default.parse(t)}else{e=t}if(!e){throw new Error("an HTTP(S) proxy server `host` and `port` must be specified!")}f("Creating new HttpProxyAgent instance: %o",e);super(e);const o=Object.assign({},e);this.secureProxy=e.secureProxy||isHTTPS(o.protocol);o.host=o.hostname||o.host;if(typeof o.port==="string"){o.port=parseInt(o.port,10)}if(!o.port&&o.host){o.port=this.secureProxy?443:80}if(o.host&&o.path){delete o.path;delete o.pathname}this.proxy=o}callback(t,e){return r(this,void 0,void 0,(function*(){const{proxy:o,secureProxy:r}=this;const n=u.default.parse(t.path);if(!n.protocol){n.protocol="http:"}if(!n.hostname){n.hostname=e.hostname||e.host||null}if(n.port==null&&typeof e.port){n.port=String(e.port)}if(n.port==="80"){n.port=""}t.path=u.default.format(n);if(o.auth){t.setHeader("Proxy-Authorization",`Basic ${Buffer.from(o.auth).toString("base64")}`)}let a;if(r){f("Creating `tls.Socket`: %o",o);a=s.default.connect(o)}else{f("Creating `net.Socket`: %o",o);a=i.default.connect(o)}if(t._header){let e;let o;f("Regenerating stored HTTP header string for request");t._header=null;t._implicitHeader();if(t.output&&t.output.length>0){f("Patching connection write() output buffer with updated header");e=t.output[0];o=e.indexOf("\r\n\r\n")+4;t.output[0]=t._header+e.substring(o);f("Output buffer: %o",t.output)}else if(t.outputData&&t.outputData.length>0){f("Patching connection write() output buffer with updated header");e=t.outputData[0].data;o=e.indexOf("\r\n\r\n")+4;t.outputData[0].data=t._header+e.substring(o);f("Output buffer: %o",t.outputData[0].data)}}yield(0,c.default)(a,"connect");return a}))}}e["default"]=HttpProxyAgent},289:function(t,e,o){var r=this&&this.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};const n=r(o(386));function createHttpProxyAgent(t){return new n.default(t)}(function(t){t.HttpProxyAgent=n.default;t.prototype=n.default.prototype})(createHttpProxyAgent||(createHttpProxyAgent={}));t.exports=createHttpProxyAgent},361:t=>{t.exports=require("events")},808:t=>{t.exports=require("net")},937:t=>{t.exports=require("next/dist/compiled/debug")},404:t=>{t.exports=require("tls")},310:t=>{t.exports=require("url")}};var e={};function __nccwpck_require__(o){var r=e[o];if(r!==undefined){return r.exports}var n=e[o]={exports:{}};var i=true;try{t[o].call(n.exports,n,n.exports,__nccwpck_require__);i=false}finally{if(i)delete e[o]}return n.exports}if(typeof __nccwpck_require__!=="undefined")__nccwpck_require__.ab=__dirname+"/";var o=__nccwpck_require__(289);module.exports=o})();
\ No newline at end of file
{"name":"http-proxy-agent","main":"index.js","author":"Nathan Rajlich <nathan@tootallnate.net> (http://n8.io/)","license":"MIT"}
(()=>{"use strict";var e={448:function(e,t,o){var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};const n=o(361);const s=r(o(937));const i=r(o(457));const c=s.default("agent-base");function isAgent(e){return Boolean(e)&&typeof e.addRequest==="function"}function isSecureEndpoint(){const{stack:e}=new Error;if(typeof e!=="string")return false;return e.split("\n").some((e=>e.indexOf("(https.js:")!==-1||e.indexOf("node:https:")!==-1))}function createAgent(e,t){return new createAgent.Agent(e,t)}(function(e){class Agent extends n.EventEmitter{constructor(e,t){super();let o=t;if(typeof e==="function"){this.callback=e}else if(e){o=e}this.timeout=null;if(o&&typeof o.timeout==="number"){this.timeout=o.timeout}this.maxFreeSockets=1;this.maxSockets=1;this.maxTotalSockets=Infinity;this.sockets={};this.freeSockets={};this.requests={};this.options={}}get defaultPort(){if(typeof this.explicitDefaultPort==="number"){return this.explicitDefaultPort}return isSecureEndpoint()?443:80}set defaultPort(e){this.explicitDefaultPort=e}get protocol(){if(typeof this.explicitProtocol==="string"){return this.explicitProtocol}return isSecureEndpoint()?"https:":"http:"}set protocol(e){this.explicitProtocol=e}callback(e,t,o){throw new Error('"agent-base" has no default implementation, you must subclass and override `callback()`')}addRequest(e,t){const o=Object.assign({},t);if(typeof o.secureEndpoint!=="boolean"){o.secureEndpoint=isSecureEndpoint()}if(o.host==null){o.host="localhost"}if(o.port==null){o.port=o.secureEndpoint?443:80}if(o.protocol==null){o.protocol=o.secureEndpoint?"https:":"http:"}if(o.host&&o.path){delete o.path}delete o.agent;delete o.hostname;delete o._defaultAgent;delete o.defaultPort;delete o.createConnection;e._last=true;e.shouldKeepAlive=false;let r=false;let n=null;const s=o.timeout||this.timeout;const onerror=t=>{if(e._hadError)return;e.emit("error",t);e._hadError=true};const ontimeout=()=>{n=null;r=true;const e=new Error(`A "socket" was not created for HTTP request before ${s}ms`);e.code="ETIMEOUT";onerror(e)};const callbackError=e=>{if(r)return;if(n!==null){clearTimeout(n);n=null}onerror(e)};const onsocket=t=>{if(r)return;if(n!=null){clearTimeout(n);n=null}if(isAgent(t)){c("Callback returned another Agent instance %o",t.constructor.name);t.addRequest(e,o);return}if(t){t.once("free",(()=>{this.freeSocket(t,o)}));e.onSocket(t);return}const s=new Error(`no Duplex stream was returned to agent-base for \`${e.method} ${e.path}\``);onerror(s)};if(typeof this.callback!=="function"){onerror(new Error("`callback` is not defined"));return}if(!this.promisifiedCallback){if(this.callback.length>=3){c("Converting legacy callback function to promise");this.promisifiedCallback=i.default(this.callback)}else{this.promisifiedCallback=this.callback}}if(typeof s==="number"&&s>0){n=setTimeout(ontimeout,s)}if("port"in o&&typeof o.port!=="number"){o.port=Number(o.port)}try{c("Resolving socket for %o request: %o",o.protocol,`${e.method} ${e.path}`);Promise.resolve(this.promisifiedCallback(e,o)).then(onsocket,callbackError)}catch(e){Promise.reject(e).catch(callbackError)}}freeSocket(e,t){c("Freeing socket %o %o",e.constructor.name,t);e.destroy()}destroy(){c("Destroying agent %o",this.constructor.name)}}e.Agent=Agent;e.prototype=e.Agent.prototype})(createAgent||(createAgent={}));e.exports=createAgent},457:(e,t)=>{Object.defineProperty(t,"__esModule",{value:true});function promisify(e){return function(t,o){return new Promise(((r,n)=>{e.call(this,t,o,((e,t)=>{if(e){n(e)}else{r(t)}}))}))}}t["default"]=promisify},44:function(e,t,o){var r=this&&this.__awaiter||function(e,t,o,r){function adopt(e){return e instanceof o?e:new o((function(t){t(e)}))}return new(o||(o=Promise))((function(o,n){function fulfilled(e){try{step(r.next(e))}catch(e){n(e)}}function rejected(e){try{step(r["throw"](e))}catch(e){n(e)}}function step(e){e.done?o(e.value):adopt(e.value).then(fulfilled,rejected)}step((r=r.apply(e,t||[])).next())}))};var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:true});const s=n(o(808));const i=n(o(404));const c=n(o(310));const u=n(o(491));const a=n(o(937));const l=o(448);const f=n(o(357));const p=a.default("https-proxy-agent:agent");class HttpsProxyAgent extends l.Agent{constructor(e){let t;if(typeof e==="string"){t=c.default.parse(e)}else{t=e}if(!t){throw new Error("an HTTP(S) proxy server `host` and `port` must be specified!")}p("creating new HttpsProxyAgent instance: %o",t);super(t);const o=Object.assign({},t);this.secureProxy=t.secureProxy||isHTTPS(o.protocol);o.host=o.hostname||o.host;if(typeof o.port==="string"){o.port=parseInt(o.port,10)}if(!o.port&&o.host){o.port=this.secureProxy?443:80}if(this.secureProxy&&!("ALPNProtocols"in o)){o.ALPNProtocols=["http 1.1"]}if(o.host&&o.path){delete o.path;delete o.pathname}this.proxy=o}callback(e,t){return r(this,void 0,void 0,(function*(){const{proxy:o,secureProxy:r}=this;let n;if(r){p("Creating `tls.Socket`: %o",o);n=i.default.connect(o)}else{p("Creating `net.Socket`: %o",o);n=s.default.connect(o)}const c=Object.assign({},o.headers);const a=`${t.host}:${t.port}`;let l=`CONNECT ${a} HTTP/1.1\r\n`;if(o.auth){c["Proxy-Authorization"]=`Basic ${Buffer.from(o.auth).toString("base64")}`}let{host:d,port:h,secureEndpoint:m}=t;if(!isDefaultPort(h,m)){d+=`:${h}`}c.Host=d;c.Connection="close";for(const e of Object.keys(c)){l+=`${e}: ${c[e]}\r\n`}const y=f.default(n);n.write(`${l}\r\n`);const{statusCode:g,buffered:x}=yield y;if(g===200){e.once("socket",resume);if(t.secureEndpoint){p("Upgrading socket connection to TLS");const e=t.servername||t.host;return i.default.connect(Object.assign(Object.assign({},omit(t,"host","hostname","path","port")),{socket:n,servername:e}))}return n}n.destroy();const _=new s.default.Socket({writable:false});_.readable=true;e.once("socket",(e=>{p("replaying proxy buffer for failed request");u.default(e.listenerCount("data")>0);e.push(x);e.push(null)}));return _}))}}t["default"]=HttpsProxyAgent;function resume(e){e.resume()}function isDefaultPort(e,t){return Boolean(!t&&e===80||t&&e===443)}function isHTTPS(e){return typeof e==="string"?/^https:?$/i.test(e):false}function omit(e,...t){const o={};let r;for(r in e){if(!t.includes(r)){o[r]=e[r]}}return o}},157:function(e,t,o){var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};const n=r(o(44));function createHttpsProxyAgent(e){return new n.default(e)}(function(e){e.HttpsProxyAgent=n.default;e.prototype=n.default.prototype})(createHttpsProxyAgent||(createHttpsProxyAgent={}));e.exports=createHttpsProxyAgent},357:function(e,t,o){var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:true});const n=r(o(937));const s=n.default("https-proxy-agent:parse-proxy-response");function parseProxyResponse(e){return new Promise(((t,o)=>{let r=0;const n=[];function read(){const t=e.read();if(t)ondata(t);else e.once("readable",read)}function cleanup(){e.removeListener("end",onend);e.removeListener("error",onerror);e.removeListener("close",onclose);e.removeListener("readable",read)}function onclose(e){s("onclose had error %o",e)}function onend(){s("onend")}function onerror(e){cleanup();s("onerror %o",e);o(e)}function ondata(e){n.push(e);r+=e.length;const o=Buffer.concat(n,r);const i=o.indexOf("\r\n\r\n");if(i===-1){s("have not received end of HTTP headers yet...");read();return}const c=o.toString("ascii",0,o.indexOf("\r\n"));const u=+c.split(" ")[1];s("got proxy server response: %o",c);t({statusCode:u,buffered:o})}e.on("error",onerror);e.on("close",onclose);e.on("end",onend);read()}))}t["default"]=parseProxyResponse},491:e=>{e.exports=require("assert")},361:e=>{e.exports=require("events")},808:e=>{e.exports=require("net")},937:e=>{e.exports=require("next/dist/compiled/debug")},404:e=>{e.exports=require("tls")},310:e=>{e.exports=require("url")}};var t={};function __nccwpck_require__(o){var r=t[o];if(r!==undefined){return r.exports}var n=t[o]={exports:{}};var s=true;try{e[o].call(n.exports,n,n.exports,__nccwpck_require__);s=false}finally{if(s)delete t[o]}return n.exports}if(typeof __nccwpck_require__!=="undefined")__nccwpck_require__.ab=__dirname+"/";var o=__nccwpck_require__(157);module.exports=o})();
\ No newline at end of file
{"name":"https-proxy-agent","main":"index.js","author":"Nathan Rajlich <nathan@tootallnate.net> (http://n8.io/)","license":"MIT"}
......@@ -2023,6 +2023,24 @@ export async function ncc_opentelemetry_api(task, opts) {
.target('src/compiled/@opentelemetry/api')
}
// eslint-disable-next-line camelcase
externals['http-proxy-agent'] = 'next/dist/compiled/http-proxy-agent'
export async function ncc_http_proxy_agent(task, opts) {
await task
.source(relative(__dirname, require.resolve('http-proxy-agent')))
.ncc({ packageName: 'http-proxy-agent', externals })
.target('src/compiled/http-proxy-agent')
}
// eslint-disable-next-line camelcase
externals['https-proxy-agent'] = 'next/dist/compiled/https-proxy-agent'
export async function ncc_https_proxy_agent(task, opts) {
await task
.source(relative(__dirname, require.resolve('https-proxy-agent')))
.ncc({ packageName: 'https-proxy-agent', externals })
.target('src/compiled/https-proxy-agent')
}
export async function precompile(task, opts) {
await task.parallel(
[
......@@ -2156,6 +2174,8 @@ export async function ncc(task, opts) {
'ncc_ua_parser_js',
'ncc_minimatch',
'ncc_opentelemetry_api',
'ncc_http_proxy_agent',
'ncc_https_proxy_agent',
'ncc_mini_css_extract_plugin',
],
opts
......
......@@ -607,7 +607,9 @@ importers:
glob: 7.1.7
gzip-size: 5.1.1
http-proxy: 1.18.1
http-proxy-agent: 5.0.0
https-browserify: 1.0.0
https-proxy-agent: 5.0.1
icss-utils: 5.1.0
ignore-loader: 0.1.2
image-size: 1.0.0
......@@ -817,7 +819,9 @@ importers:
glob: 7.1.7
gzip-size: 5.1.1
http-proxy: 1.18.1
http-proxy-agent: 5.0.0
https-browserify: 1.0.0
https-proxy-agent: 5.0.1
icss-utils: 5.1.0_postcss@8.4.14
ignore-loader: 0.1.2
image-size: 1.0.0
......@@ -5832,7 +5836,7 @@ packages:
hasBin: true
dependencies:
detect-libc: 1.0.3
https-proxy-agent: 5.0.0
https-proxy-agent: 5.0.1
make-dir: 3.1.0
node-fetch: 2.6.7
nopt: 5.0.0
......@@ -6718,6 +6722,11 @@ packages:
resolution: {integrity: sha512-RbzJvlNzmRq5c3O09UipeuXno4tA1FE6ikOjxZK0tuxVv3412l64l5t1W5pj4+rJq9vpkm/kwiR07aZXnsKPxw==}
engines: {node: '>= 6'}
/@tootallnate/once/2.0.0:
resolution: {integrity: sha512-XCuKFP5PS55gnMVu3dty8KPatLqUoy/ZYzDzAGCQ8JNFCkLXzmI7vNHCR+XpbZaMWQK/vQubr7PkYq8g470J/A==}
engines: {node: '>= 10'}
dev: true
/@trysound/sax/0.2.0:
resolution: {integrity: sha512-L7z9BgrNEcYyUYtF+HaEfiS5ebkh9jXqbszz7pC0hRBPaatV0XjSD3+eHrpqFemQfgwiFF0QPIarnIihIDn7OA==}
engines: {node: '>=10.13.0'}
......@@ -13904,6 +13913,17 @@ packages:
transitivePeerDependencies:
- supports-color
/http-proxy-agent/5.0.0:
resolution: {integrity: sha512-n2hY8YdoRE1i7r6M0w9DIw5GgZN0G25P8zLCRQ8rjXtTU3vsNFBI/vWK/UIeE6g5MUUz6avwAPXmL6Fy9D/90w==}
engines: {node: '>= 6'}
dependencies:
'@tootallnate/once': 2.0.0
agent-base: 6.0.2
debug: 4.3.4
transitivePeerDependencies:
- supports-color
dev: true
/http-proxy/1.18.1:
resolution: {integrity: sha512-7mz/721AbnJwIVbnaSv1Cz3Am0ZLT/UBwkC92VlxhXv/k/BBQfM2fXElQNC27BVGr0uwUpplYPQM9LnaBMR5NQ==}
engines: {node: '>=8.0.0'}
......@@ -13950,6 +13970,16 @@ packages:
debug: 4.3.4
transitivePeerDependencies:
- supports-color
dev: true
/https-proxy-agent/5.0.1:
resolution: {integrity: sha512-dFcAjpTQFgoLMzC2VwU+C/CbS7uRL0lWmxDITmqm7C+7F0Odmj6s9l6alZc6AELXhrnggM2CeWSXHGOdX2YtwA==}
engines: {node: '>= 6'}
dependencies:
agent-base: 6.0.2
debug: 4.3.4
transitivePeerDependencies:
- supports-color
/human-signals/1.1.1:
resolution: {integrity: sha512-SEQu7vl8KjNL2eoGBLF3+wAjpsNfA9XMlXAYj/3EdaNfAlxKthD1xjEQfGOUhllCGGJVNY34bRr6lPINhNjyZw==}
......@@ -15732,7 +15762,7 @@ packages:
form-data: 3.0.1
html-encoding-sniffer: 2.0.1
http-proxy-agent: 4.0.1
https-proxy-agent: 5.0.0
https-proxy-agent: 5.0.1
is-potential-custom-element-name: 1.0.1
nwsapi: 2.2.0
parse5: 6.0.1
......@@ -16603,7 +16633,7 @@ packages:
cacache: 15.3.0
http-cache-semantics: 4.1.0
http-proxy-agent: 4.0.1
https-proxy-agent: 5.0.0
https-proxy-agent: 5.0.1
is-lambda: 1.0.1
lru-cache: 6.0.0
minipass: 3.1.3
......@@ -16627,7 +16657,7 @@ packages:
cacache: 15.3.0
http-cache-semantics: 4.1.0
http-proxy-agent: 4.0.1
https-proxy-agent: 5.0.0
https-proxy-agent: 5.0.1
is-lambda: 1.0.1
lru-cache: 6.0.0
minipass: 3.1.3
......
import { FileRef, createNext, NextInstance } from 'e2e-utils'
import { findPort, renderViaHTTP, fetchViaHTTP } from 'next-test-utils'
import { join } from 'path'
import { spawn } from 'cross-spawn'
describe('next/font/google with proxy', () => {
let next: NextInstance
let proxy: any
let PROXY_PORT: number
let SERVER_PORT: number
if ((global as any).isNextDeploy) {
it('should skip next deploy', () => {})
return
}
beforeAll(async () => {
PROXY_PORT = await findPort()
SERVER_PORT = await findPort()
proxy = spawn('node', [require.resolve('./with-proxy/server.js')], {
stdio: 'inherit',
env: {
...process.env,
PROXY_PORT,
SERVER_PORT,
},
})
next = await createNext({
files: new FileRef(join(__dirname, 'with-proxy')),
dependencies: {
react: 'latest',
'react-dom': 'latest',
},
env: {
http_proxy: 'http://localhost:' + PROXY_PORT,
},
})
})
afterAll(async () => {
await next.destroy()
proxy.kill('SIGKILL')
})
it('should use a proxy agent when proxy environment variable is set', async () => {
await renderViaHTTP(next.url, '/')
const proxiedRequests = await fetchViaHTTP(SERVER_PORT, '/requests').then(
(r) => r.json()
)
expect(proxiedRequests).toContain(
'/css2?family=Oswald:wght@200..700&display=swap'
)
expect(proxiedRequests).toContain(
'/s/oswald/v49/TK3iWkUHHAIjg752FD8Gl-1PK62t.woff2'
)
expect(proxiedRequests).toContain(
'/s/oswald/v49/TK3iWkUHHAIjg752HT8Gl-1PK62t.woff2'
)
expect(proxiedRequests).toContain(
'/s/oswald/v49/TK3iWkUHHAIjg752Fj8Gl-1PK62t.woff2'
)
expect(proxiedRequests).toContain(
'/s/oswald/v49/TK3iWkUHHAIjg752GT8Gl-1PKw.woff2'
)
expect(proxiedRequests).toContain(
'/s/oswald/v49/TK3iWkUHHAIjg752Fz8Gl-1PK62t.woff2'
)
})
})
import { Oswald } from 'next/font/google'
const oswald = Oswald({ subsets: ['latin'] })
export default function Index() {
return <p className={oswald.className}>Hello world</p>
}
const http = require('http')
const httpProxy = require('next/dist/compiled/http-proxy')
const PROXY_PORT = process.env.PROXY_PORT
const SERVER_PORT = process.env.SERVER_PORT
httpProxy
.createProxyServer({ target: 'http://localhost:' + SERVER_PORT })
.listen(PROXY_PORT)
const cssResponse = `
/* cyrillic-ext */
@font-face {
font-family: 'Oswald';
font-style: normal;
font-weight: 200 700;
font-display: swap;
src: url(https://fonts.gstatic.com/s/oswald/v49/TK3iWkUHHAIjg752FD8Gl-1PK62t.woff2) format('woff2');
unicode-range: U+0460-052F, U+1C80-1C88, U+20B4, U+2DE0-2DFF, U+A640-A69F, U+FE2E-FE2F;
}
/* cyrillic */
@font-face {
font-family: 'Oswald';
font-style: normal;
font-weight: 200 700;
font-display: swap;
src: url(https://fonts.gstatic.com/s/oswald/v49/TK3iWkUHHAIjg752HT8Gl-1PK62t.woff2) format('woff2');
unicode-range: U+0301, U+0400-045F, U+0490-0491, U+04B0-04B1, U+2116;
}
/* vietnamese */
@font-face {
font-family: 'Oswald';
font-style: normal;
font-weight: 200 700;
font-display: swap;
src: url(https://fonts.gstatic.com/s/oswald/v49/TK3iWkUHHAIjg752Fj8Gl-1PK62t.woff2) format('woff2');
unicode-range: U+0102-0103, U+0110-0111, U+0128-0129, U+0168-0169, U+01A0-01A1, U+01AF-01B0, U+1EA0-1EF9, U+20AB;
}
/* latin-ext */
@font-face {
font-family: 'Oswald';
font-style: normal;
font-weight: 200 700;
font-display: swap;
src: url(https://fonts.gstatic.com/s/oswald/v49/TK3iWkUHHAIjg752Fz8Gl-1PK62t.woff2) format('woff2');
unicode-range: U+0100-024F, U+0259, U+1E00-1EFF, U+2020, U+20A0-20AB, U+20AD-20CF, U+2113, U+2C60-2C7F, U+A720-A7FF;
}
/* latin */
@font-face {
font-family: 'Oswald';
font-style: normal;
font-weight: 200 700;
font-display: swap;
src: url(https://fonts.gstatic.com/s/oswald/v49/TK3iWkUHHAIjg752GT8Gl-1PKw.woff2) format('woff2');
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
}
`
const requestedUrls = []
http
.createServer(function (req, res) {
if (req.url === '/requests') {
res.writeHead(200, { 'Content-Type': 'application/json' })
res.write(JSON.stringify(requestedUrls))
res.end()
return
}
requestedUrls.push(req.url)
res.writeHead(200, { 'Content-Type': 'text/css' })
res.write(cssResponse)
res.end()
})
.listen(SERVER_PORT)
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment