From af3c5063a68f37b6ecb2c94a3a92d10b72afc5a5 Mon Sep 17 00:00:00 2001 From: JJ Kasper Date: Sun, 6 Nov 2022 15:23:02 -0800 Subject: [PATCH] Fix replaceAll usage in font loader (#42550) This removes usage of `replaceAll` as it wasn't introduced [until Node.js v15](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replaceAll#browser_compatibility) although we support v14 still. x-ref: https://dev.azure.com/nextjs/next.js/_build/results?buildId=43457&view=logs&jobId=8af7cf9c-43a1-584d-6f5c-57bad8880974 ## Bug - [ ] Related issues linked using `fixes #number` - [ ] Integration tests added - [ ] Errors have a helpful link attached, see `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` - [ ] Integration 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` ## 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) --- packages/font/src/google/loader.ts | 16 ++++++++++++++-- 1 file changed, 14 insertions(+), 2 deletions(-) diff --git a/packages/font/src/google/loader.ts b/packages/font/src/google/loader.ts index d584742bfc4d..6a4c3a19b066 100644 --- a/packages/font/src/google/loader.ts +++ b/packages/font/src/google/loader.ts @@ -17,6 +17,18 @@ import { const cssCache = new Map>() const fontCache = new Map() +// regexp is based on https://github.com/sindresorhus/escape-string-regexp +const reHasRegExp = /[|\\{}()[\]^$+*?.-]/ +const reReplaceRegExp = /[|\\{}()[\]^$+*?.-]/g + +function escapeStringRegexp(str: string) { + // see also: https://github.com/lodash/lodash/blob/2da024c3b4f9947a48517639de7560457cd4ec6c/escapeRegExp.js#L23 + if (reHasRegExp.test(str)) { + return str.replace(reReplaceRegExp, '\\$&') + } + return str +} + const downloadGoogleFonts: FontLoader = async ({ functionName, data, @@ -124,8 +136,8 @@ const downloadGoogleFonts: FontLoader = async ({ // Replace @font-face sources with self-hosted files let updatedCssResponse = fontFaceDeclarations for (const { googleFontFileUrl, selfHostedFileUrl } of downloadedFiles) { - updatedCssResponse = updatedCssResponse.replaceAll( - googleFontFileUrl, + updatedCssResponse = updatedCssResponse.replace( + new RegExp(escapeStringRegexp(googleFontFileUrl), 'g'), selfHostedFileUrl ) }