-
-
Notifications
You must be signed in to change notification settings - Fork 110
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
fix: more accurate filtering for
include
, exclude
- Loading branch information
Showing
2 changed files
with
46 additions
and
10 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,39 @@ | ||
import { createRouter, toRouteMatcher } from 'radix3' | ||
|
||
interface CreateFilterOptions { | ||
include?: (string | RegExp)[] | ||
exclude?: (string | RegExp)[] | ||
} | ||
|
||
export function createFilter(options: CreateFilterOptions = {}): (path: string) => boolean { | ||
const include = options.include || [] | ||
const exclude = options.exclude || [] | ||
if (include.length === 0 && exclude.length === 0) | ||
return () => true | ||
|
||
return function (path: string): boolean { | ||
for (const v of [{ rules: exclude, result: false }, { rules: include, result: true }]) { | ||
const regexRules = v.rules.filter(r => r instanceof RegExp) as RegExp[] | ||
if (regexRules.some(r => r.test(path))) | ||
return v.result | ||
|
||
const stringRules = v.rules.filter(r => typeof r === 'string') as string[] | ||
if (stringRules.length > 0) { | ||
const routes = {} | ||
for (const r of stringRules) { | ||
// quick scan of literal string matches | ||
if (r === path) | ||
return v.result | ||
|
||
// need to flip the array data for radix3 format, true value is arbitrary | ||
// @ts-expect-error untyped | ||
routes[r] = true | ||
} | ||
const routeRulesMatcher = toRouteMatcher(createRouter({ routes, strictTrailingSlash: false })) | ||
if (routeRulesMatcher.matchAll(path).length > 0) | ||
return Boolean(v.result) | ||
} | ||
} | ||
return include.length === 0 | ||
} | ||
} |