@nadeshikon/plugin-nextjs
Version:
Run Next.js seamlessly on Netlify
32 lines (28 loc) • 1.04 kB
text/typescript
import { transform } from 'regexp-tree'
// The Go regexp lib doesn't support lookaheads, so we need to remove them
export const stripLookahead = (regex: string) => {
// Early return if there's no lookahead
if (!regex?.includes('(?!')) {
return regex
}
try {
// Parse the regexp into an AST
const re = transform(`/${regex}/`, {
Assertion(path) {
// Remove the lookahead
if (path.node.kind === 'Lookahead') {
path.remove()
}
},
})
// Strip the leading and trailing slashes
return re.toString().slice(1, -1)
} catch {
// Failed to parse regex, so return unchanged
return regex
}
}
const LOCALIZED_REGEX_PREFIX = '(?:\\/(_next\\/data\\/[^/]{1,}))?(?:\\/([^/.]{1,}))'
const OPTIONAL_REGEX_PREFIX = '(?:\\/(_next\\/data\\/[^/]{1,}))?(?:\\/([^/.]{1,}))?'
// Make the locale section of the matcher regex optional
export const makeLocaleOptional = (regex: string) => regex.replace(LOCALIZED_REGEX_PREFIX, OPTIONAL_REGEX_PREFIX)