Skip to content
Source
Sign inSign up
TanStack/router
Open History to see the last commit

utils.ts

223 lines6.4 KB

1import {
2 extname,
3 isAbsolute,
4 relative,
5 resolve as resolvePath,
6} from 'node:path'
7import { normalizePath } from '../utils'
8​
9import {
10 IMPORT_PROTECTION_DEBUG,
11 IMPORT_PROTECTION_DEBUG_FILTER,
12 KNOWN_SOURCE_EXTENSIONS,
13} from './constants'
14​
15export type Pattern = string | RegExp
16​
17export function dedupePatterns(patterns: Array<Pattern>): Array<Pattern> {
18 const out: Array<Pattern> = []
19 const seen = new Set<string>()
20 for (const p of patterns) {
21 const key = typeof p === 'string' ? `s:${p}` : `r:${p.toString()}`
22 if (seen.has(key)) continue
23 seen.add(key)
24 out.push(p)
25 }
26 return out
28​
29export interface FileMatchers {
30 files: Array<{ pattern: Pattern; test: (value: string) => boolean }>
31 excludeFiles: Array<{ pattern: Pattern; test: (value: string) => boolean }>
33​
34export function isFileExcluded(
35 relativePath: string,
36 matchers: Pick<FileMatchers, 'excludeFiles'>,
37): boolean {
38 return (
39 matchers.excludeFiles.length > 0 &&
40 matchers.excludeFiles.some((matcher) => matcher.test(relativePath))
41 )
43​
44export function checkFileDenial(
45 relativePath: string,
46 matchers: FileMatchers,
47): FileMatchers['files'][number] | undefined {
48 if (isFileExcluded(relativePath, matchers)) {
49 return undefined
50 }
51​
52 return matchers.files.find((matcher) => matcher.test(relativePath))
54​
55export function dedupeViolationKey(info: {
56 type: string
57 importer: string
58 specifier: string
59 resolved?: string
60}): string {
61 return `${info.type}:${info.importer}:${info.specifier}:${info.resolved ?? ''}`
63​
64/** Strip both `?query` and `#hash` from a module ID. */
65export function stripQueryAndHash(id: string): string {
66 const q = id.indexOf('?')
67 const h = id.indexOf('#')
68 if (q === -1 && h === -1) return id
69 if (q === -1) return id.slice(0, h)
70 if (h === -1) return id.slice(0, q)
71 return id.slice(0, Math.min(q, h))
73​
74/**
75 * Strip Vite query/hash parameters and normalize the path in one step.
76 *
77 * Results are memoized because the same module IDs are processed many
78 * times across resolveId, transform, and trace-building hooks.
79 */
80const normalizeFilePathCache = new Map<string, string>()
81export function normalizeFilePath(id: string): string {
82 let result = normalizeFilePathCache.get(id)
83 if (result === undefined) {
84 result = normalizePath(stripQueryAndHash(id))
85 normalizeFilePathCache.set(id, result)
86 }
87 return result
89​
90/** Clear the memoization cache (call from buildStart to bound growth). */
91export function clearNormalizeFilePathCache(): void {
92 normalizeFilePathCache.clear()
94​
95/** Get a value from a Map, creating it with `factory` if absent. */
96export function getOrCreate<TKey, TValue>(
97 map: Map<TKey, TValue>,
98 key: TKey,
99 factory: () => TValue,
100): TValue {
101 let value = map.get(key)
102 if (value === undefined) {
103 value = factory()
104 map.set(key, value)
105 }
106 return value
108​
109/** Make a path relative to `root`, keeping non-rooted paths as-is. */
110export function relativizePath(p: string, root: string): string {
111 if (!p.startsWith(root)) return p
112 const ch = p.charCodeAt(root.length)
113 // Must be followed by a separator or end-of-string to be a true child
114 if (ch !== 47 && !Number.isNaN(ch)) return p
115 return ch === 47 ? p.slice(root.length + 1) : p.slice(root.length)
117​
118/** Log import-protection debug output when debug mode is enabled. */
119export function debugLog(...args: Array<unknown>): void {
120 if (!IMPORT_PROTECTION_DEBUG) return
121 console.warn('[import-protection:debug]', ...args)
123​
124/** Check if any value matches the configured debug filter (if present). */
125export function matchesDebugFilter(...values: Array<string>): boolean {
126 const debugFilter = IMPORT_PROTECTION_DEBUG_FILTER
127 if (!debugFilter) return true
128 return values.some((v) => v.includes(debugFilter))
130​
131/** Strip `?query` (but not `#hash`) from a module ID. */
132export function stripQuery(id: string): string {
133 const queryIndex = id.indexOf('?')
134 return queryIndex === -1 ? id : id.slice(0, queryIndex)
136​
137export function withoutKnownExtension(id: string): string {
138 const ext = extname(id)
139 return KNOWN_SOURCE_EXTENSIONS.has(ext) ? id.slice(0, -ext.length) : id
141​
142/**
143 * Check whether `filePath` is contained inside `directory` using a
144 * boundary-safe comparison. A naΓ―ve `filePath.startsWith(directory)`
145 * would incorrectly treat `/app/src2/foo.ts` as inside `/app/src`.
146 */
147export function isInsideDirectory(
148 filePath: string,
149 directory: string,
150): boolean {
151 const rel = relative(resolvePath(directory), resolvePath(filePath))
152 return rel.length > 0 && !rel.startsWith('..') && !isAbsolute(rel)
154​
155/**
156 * Decide whether a violation should be deferred for later verification
157 * rather than reported immediately.
158 *
159 * Build mode: always defer β€” generateBundle checks tree-shaking.
160 * Dev mock mode: always defer β€” edge-survival verifies whether the Start
161 * compiler strips the import (factory-safe pattern). All violation
162 * types and specifier formats are handled uniformly by the
163 * edge-survival mechanism in processPendingViolations.
164 * Dev error mode: never defer β€” throw immediately (no mock fallback).
165 */
166export function shouldDeferViolation(opts: {
167 isBuild: boolean
168 isDevMock: boolean
169}): boolean {
170 return opts.isBuild || opts.isDevMock
172​
173export function buildSourceCandidates(
174 source: string,
175 resolved: string | undefined,
176 root: string,
177): Set<string> {
178 const candidates = new Set<string>()
179 const push = (value: string | undefined) => {
180 if (!value) return
181 candidates.add(value)
182 candidates.add(stripQuery(value))
183 candidates.add(withoutKnownExtension(stripQuery(value)))
184 }
185​
186 push(source)
187 if (resolved) {
188 push(resolved)
189 const relativeResolved = relativizePath(resolved, root)
190 push(relativeResolved)
191 push(`./${relativeResolved}`)
192 push(`/${relativeResolved}`)
193 }
194​
195 return candidates
197​
198export function buildResolutionCandidates(id: string): Array<string> {
199 const normalized = normalizeFilePath(id)
200 const stripped = stripQuery(normalized)
201​
202 return [...new Set([id, normalized, stripped])]
204​
205export function canonicalizeResolvedId(
206 id: string,
207 root: string,
208 resolveExtensionlessAbsoluteId: (value: string) => string,
209): string {
210 const stripped = stripQuery(id)
211 let normalized = normalizeFilePath(stripped)
212​
213 if (
214 !isAbsolute(normalized) &&
215 !normalized.startsWith('.') &&
216 !normalized.startsWith('\0') &&
217 !/^[a-zA-Z]+:/.test(normalized)
218 ) {
219 normalized = normalizeFilePath(resolvePath(root, normalized))
220 }
221​
222 return resolveExtensionlessAbsoluteId(normalized)