index.js 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. import { isAbsolute, join, resolve } from "pathe";
  2. import pm from "picomatch";
  3. //#region src/path.ts
  4. function normalizePath(filename) {
  5. return filename.replaceAll("\\", "/");
  6. }
  7. //#endregion
  8. //#region src/utils.ts
  9. const isArray = Array.isArray;
  10. function toArray(thing) {
  11. if (isArray(thing)) return thing;
  12. if (thing == null) return [];
  13. return [thing];
  14. }
  15. //#endregion
  16. //#region src/filter.ts
  17. const escapeMark = "[_#EsCaPe#_]";
  18. function getMatcherString(id, resolutionBase) {
  19. if (resolutionBase === false || isAbsolute(id) || id.startsWith("**")) return normalizePath(id);
  20. const basePath = normalizePath(resolve(resolutionBase || "")).replaceAll(/[-^$*+?.()|[\]{}]/g, `${escapeMark}$&`);
  21. return join(basePath, normalizePath(id)).replaceAll(escapeMark, "\\");
  22. }
  23. function createFilter(include, exclude, options) {
  24. const resolutionBase = options && options.resolve;
  25. const getMatcher = (id) => id instanceof RegExp ? id : { test: (what) => {
  26. const pattern = getMatcherString(id, resolutionBase);
  27. const fn = pm(pattern, { dot: true });
  28. const result = fn(what);
  29. return result;
  30. } };
  31. const includeMatchers = toArray(include).map(getMatcher);
  32. const excludeMatchers = toArray(exclude).map(getMatcher);
  33. if (!includeMatchers.length && !excludeMatchers.length) return (id) => typeof id === "string" && !id.includes("\0");
  34. return function result(id) {
  35. if (typeof id !== "string") return false;
  36. if (id.includes("\0")) return false;
  37. const pathId = normalizePath(id);
  38. for (const matcher of excludeMatchers) {
  39. if (matcher instanceof RegExp) matcher.lastIndex = 0;
  40. if (matcher.test(pathId)) return false;
  41. }
  42. for (const matcher of includeMatchers) {
  43. if (matcher instanceof RegExp) matcher.lastIndex = 0;
  44. if (matcher.test(pathId)) return true;
  45. }
  46. return !includeMatchers.length;
  47. };
  48. }
  49. //#endregion
  50. export { createFilter, normalizePath, toArray };