|
1 | 1 | import type { NitroAppPlugin } from 'nitropack' |
2 | 2 | import { packString } from 'packrup' |
3 | 3 | import { MODE_DELAY_APP_INIT } from '../module' |
4 | | -import { createFilter } from '../util/filter' |
| 4 | +import { createRouter, toRouteMatcher } from 'radix3' |
5 | 5 | import { useRuntimeConfig } from '#imports' |
6 | 6 |
|
7 | 7 | import { debug, exclude, include, mode, replayScript, script } from '#delay-hydration' |
8 | 8 |
|
9 | 9 | const SCRIPT_REGEX = /<script(.*?)>/gm |
10 | 10 |
|
| 11 | + |
| 12 | +export interface CreateFilterOptions { |
| 13 | + include?: (string | RegExp)[] |
| 14 | + exclude?: (string | RegExp)[] |
| 15 | + strictTrailingSlash?: boolean |
| 16 | +} |
| 17 | + |
| 18 | +export function createFilter(options: CreateFilterOptions = {}): (path: string) => boolean { |
| 19 | + const include = options.include || [] |
| 20 | + const exclude = options.exclude || [] |
| 21 | + |
| 22 | + return function (path: string): boolean { |
| 23 | + for (const v of [{ rules: exclude, result: false }, { rules: include, result: true }]) { |
| 24 | + const regexRules = v.rules.filter(r => r instanceof RegExp) as RegExp[] |
| 25 | + if (regexRules.some(r => r.test(path))) |
| 26 | + return v.result |
| 27 | + |
| 28 | + const stringRules = v.rules.filter(r => typeof r === 'string') as string[] |
| 29 | + if (stringRules.length > 0) { |
| 30 | + const routes = {} |
| 31 | + for (const r of stringRules) { |
| 32 | + // quick scan of literal string matches |
| 33 | + if (r === path) |
| 34 | + return v.result |
| 35 | + |
| 36 | + // need to flip the array data for radix3 format, true value is arbitrary |
| 37 | + routes[r] = true |
| 38 | + } |
| 39 | + const routeRulesMatcher = toRouteMatcher(createRouter({ routes, ...options })) |
| 40 | + if (routeRulesMatcher.matchAll(path).length > 0) |
| 41 | + return Boolean(v.result) |
| 42 | + } |
| 43 | + } |
| 44 | + return include.length === 0 |
| 45 | + } |
| 46 | +} |
| 47 | + |
11 | 48 | export default <NitroAppPlugin> function (nitro) { |
12 | 49 | nitro.hooks.hook('render:html', (htmlContext, { event }) => { |
13 | 50 | if (include.length || exclude.length) { |
|
0 commit comments