UNPKG

@winter-love/vite-plugin-monorepo-alias

Version:
81 lines (80 loc) 2.26 kB
import k from "node:path"; const l = (e, t) => e.replace(/\\?\/*$/u, t), A = (e, t) => e.replace(/^\\?\/*/u, t), g = (e) => { const t = l(A(e, "/"), "/[-._a-zA-Z0-9]+/"); return new RegExp(`${t}`, "u"); }, x = (e) => g(typeof e == "string" ? e : e.source), z = (e) => e.map(x), w = (e, t, r) => { for (const s of t) { const n = r.match(s); if (n) { const [o] = n, [c, i] = r.split(o); if (typeof i == "string" && c === l(e, "")) return { relativePath: i, relativeWorkspaceRoot: o, root: e, workspaceRoot: `${c}${l(o, "")}` }; } } }, v = (e, t = []) => { for (const [r, s] of t) { const n = e.replace(r, ""); if (n !== e) return `${s}${n}`; } return e; }, E = (e) => e.replaceAll(new RegExp(String.raw`[.*+?^${"$"}()|[\]\\]`, "gu"), (t) => `\\${t}`), W = (e) => new RegExp(`^${E(e)}`, "u"), L = (e) => Object.entries(e).map(([t, r]) => [W(t), r]), y = (e) => l(A(e, "/"), "/"), I = (e) => Object.fromEntries( Object.entries(e).map(([t, r]) => [y(t), L(r)]) ), h = (e, t) => e.replaceAll(t, "/"), P = (e, t) => e.replaceAll("/", t), S = (e) => { const { workspacePaths: t = [], alias: r = { DEFAULT: { src: "src" } }, root: s = process.cwd(), separator: n = k.sep } = e, o = I({ DEFAULT: { src: "src" }, ...r }), c = z(t), i = h(s, n); return { name: "monorepo-alias", resolveId(a, p, R) { if (!p || a.startsWith("virtual:")) return a; if (a.includes("\0")) return null; const d = h(p, n), u = w(i, c, d); if (!u) return a; const $ = o[u.relativeWorkspaceRoot] ?? o["/DEFAULT/"], m = P( `${u.workspaceRoot}/${v(a, $)}`, n ); return this.resolve(m, p, { skipSelf: !0, ...R }).then( (f) => f || { id: m } ); } }; }, F = S; export { S as createAlias, v as getAliasId, x as getWorkspaceRegex, z as getWorkspaceRegexList, g as getWorkspaceRegexString, w as matchWorkspace, F as monorepoAlias, L as normalizeAlias, W as normalizeAliasKey, I as normalizeAliasTree, y as normalizeAliasTreeKey, A as trimFirstSlash, l as trimLastSlash };