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

trace.ts

284 lines8.1 KB

1import { getOrCreate, relativizePath } from './utils'
2​
3export interface TraceEdge {
4 importer: string
5 specifier?: string
6}
7​
8/**
9 * Per-environment reverse import graph.
10 * Maps a resolved module id to the set of modules that import it.
11 */
12export class ImportGraph {
13 /**
14 * resolvedId -> Map<importer, specifier>
15 *
16 * We use a Map instead of a Set of objects so edges dedupe correctly.
17 */
18 readonly reverseEdges: Map<string, Map<string, string | undefined>> =
19 new Map()
20​
21 /**
22 * Forward-edge index: importer -> Set<resolvedId>.
23 *
24 * Maintained alongside reverseEdges so that {@link invalidate} can remove
25 * all outgoing edges for a file in O(outgoing-edges) instead of scanning
26 * every reverse-edge map in the graph.
27 */
28 private readonly forwardEdges: Map<string, Set<string>> = new Map()
29​
30 readonly entries: Set<string> = new Set()
31​
32 addEdge(resolved: string, importer: string, specifier?: string): void {
33 getOrCreate(this.reverseEdges, resolved, () => new Map()).set(
34 importer,
35 specifier,
36 )
37 getOrCreate(this.forwardEdges, importer, () => new Set()).add(resolved)
38 }
39​
40 /** Convenience for tests/debugging. */
41 getEdges(resolved: string): Set<TraceEdge> | undefined {
42 const importers = this.reverseEdges.get(resolved)
43 if (!importers) return undefined
44 const out = new Set<TraceEdge>()
45 for (const [importer, specifier] of importers) {
46 out.add({ importer, specifier })
47 }
48 return out
49 }
50​
51 addEntry(id: string): void {
52 this.entries.add(id)
53 }
54​
55 clear(): void {
56 this.reverseEdges.clear()
57 this.forwardEdges.clear()
58 this.entries.clear()
59 }
60​
61 invalidate(id: string): void {
62 // Remove all outgoing edges (id as importer) using the forward index.
63 const targets = this.forwardEdges.get(id)
64 if (targets) {
65 for (const resolved of targets) {
66 this.reverseEdges.get(resolved)?.delete(id)
67 }
68 this.forwardEdges.delete(id)
69 }
70 // Remove as a target (id as resolved module)
71 this.reverseEdges.delete(id)
72 }
74​
75export interface TraceStep {
76 file: string
77 specifier?: string
78 line?: number
79 column?: number
81​
82export interface Loc {
83 file?: string
84 line: number
85 column: number
87​
88/**
89 * BFS from a node upward through reverse edges to find the shortest
90 * path to an entry module.
91 */
92export function buildTrace(
93 graph: ImportGraph,
94 startNode: string,
95 maxDepth: number = 20,
96): Array<TraceStep> {
97 // BFS upward (startNode -> importers -> ...)
98 const visited = new Set<string>([startNode])
99 const depthByNode = new Map<string, number>([[startNode, 0]])
100​
101 // For any importer we visit, store the "down" link back toward startNode.
102 // importer --(specifier)--> next
103 const down = new Map<string, { next: string; specifier?: string }>()
104​
105 const queue: Array<string> = [startNode]
106 let qi = 0
107​
108 let root: string | null = null
109​
110 while (qi < queue.length) {
111 const node = queue[qi++]!
112 const depth = depthByNode.get(node)!
113 const importers = graph.reverseEdges.get(node)
114​
115 if (node !== startNode) {
116 const isEntry =
117 graph.entries.has(node) || !importers || importers.size === 0
118 if (isEntry) {
119 root = node
120 break
121 }
122 }
123​
124 if (depth >= maxDepth) {
125 continue
126 }
127​
128 if (!importers || importers.size === 0) {
129 continue
130 }
131​
132 for (const [importer, specifier] of importers) {
133 if (visited.has(importer)) continue
134 visited.add(importer)
135 depthByNode.set(importer, depth + 1)
136 down.set(importer, { next: node, specifier })
137 queue.push(importer)
138 }
139 }
140​
141 // Best-effort: if we never found a root, just start from the original node.
142 if (!root) {
143 root = startNode
144 }
145​
146 const trace: Array<TraceStep> = []
147 let current = root
148 for (let i = 0; i <= maxDepth + 1; i++) {
149 const link = down.get(current)
150 trace.push({ file: current, specifier: link?.specifier })
151 if (!link) break
152 current = link.next
153 }
154​
155 return trace
157​
158export interface ViolationInfo {
159 env: string
160 envType: 'client' | 'server'
161 type: 'specifier' | 'file' | 'marker'
162 behavior: 'error' | 'mock'
163 pattern?: string | RegExp
164 specifier: string
165 importer: string
166 importerLoc?: Loc
167 resolved?: string
168 trace: Array<TraceStep>
169 /** Vitest-style code snippet showing the offending usage in the leaf module. */
170 snippet?: {
171 lines: Array<string>
172 highlightLine: number
173 location: string
174 }
176​
177/**
178 * Suggestion strings for server-only code leaking into client environments.
179 * Used by both `formatViolation` (terminal) and runtime mock modules (browser).
180 */
181export const CLIENT_ENV_SUGGESTIONS = [
182 'Use createServerFn().handler(() => ...) to keep the logic on the server and call it from the client via an RPC bridge',
183 'Use createServerOnlyFn(() => ...) to mark it as server-only (it will throw if accidentally called from the client)',
184 'Use createIsomorphicFn().client(() => ...).server(() => ...) to provide separate client and server implementations',
185 'Move the server-only import out of this file into a separate .server.ts module that is not imported by any client code',
186] as const
187​
188/**
189 * Suggestion strings for client-only code leaking into server environments.
190 * The JSX-specific suggestion is conditionally prepended by `formatViolation`.
191 */
192export const SERVER_ENV_SUGGESTIONS = [
193 'Use createClientOnlyFn(() => ...) to mark it as client-only (returns undefined on the server)',
194 'Use createIsomorphicFn().client(() => ...).server(() => ...) to provide separate client and server implementations',
195 'Move the client-only import out of this file into a separate .client.ts module that is not imported by any server code',
196] as const
197​
198export function formatViolation(info: ViolationInfo, root: string): string {
199 const rel = (p: string) => relativizePath(p, root)
200​
201 const relLoc = (p: string, loc?: Loc) => {
202 const r = rel(p)
203 const file = loc?.file ? rel(loc.file) : r
204 return loc ? `${file}:${loc.line}:${loc.column}` : r
205 }
206​
207 const relTraceStep = (step: TraceStep): string => {
208 const file = rel(step.file)
209 if (step.line == null) return file
210 const col = step.column ?? 1
211 return `${file}:${step.line}:${col}`
212 }
213​
214 const lines: Array<string> = []
215 lines.push(``)
216 lines.push(`[import-protection] Import denied in ${info.envType} environment`)
217 lines.push(``)
218​
219 if (info.type === 'specifier') {
220 lines.push(` Denied by specifier pattern: ${String(info.pattern)}`)
221 } else if (info.type === 'file') {
222 lines.push(` Denied by file pattern: ${String(info.pattern)}`)
223 } else {
224 lines.push(
225 ` Denied by marker: module is restricted to the opposite environment`,
226 )
227 }
228​
229 lines.push(` Importer: ${relLoc(info.importer, info.importerLoc)}`)
230 lines.push(` Import: "${rel(info.specifier)}"`)
231 if (info.resolved) {
232 lines.push(` Resolved: ${rel(info.resolved)}`)
233 }
234​
235 if (info.trace.length > 0) {
236 lines.push(``)
237 lines.push(` Trace:`)
238 for (let i = 0; i < info.trace.length; i++) {
239 const step = info.trace[i]!
240 const isEntry = i === 0
241 const tag = isEntry ? ' (entry)' : ''
242 const spec = step.specifier ? ` (import "${rel(step.specifier)}")` : ''
243 lines.push(` ${i + 1}. ${relTraceStep(step)}${tag}${spec}`)
244 }
245 }
246​
247 if (info.snippet) {
248 lines.push(``)
249 lines.push(` Code:`)
250 for (const snippetLine of info.snippet.lines) {
251 lines.push(snippetLine)
252 }
253 lines.push(``)
254 lines.push(` ${rel(info.snippet.location)}`)
255 }
256​
257 lines.push(``)
258​
259 // Add suggestions
260 if (info.envType === 'client') {
261 lines.push(` Suggestions:`)
262 for (const s of CLIENT_ENV_SUGGESTIONS) {
263 lines.push(` - ${s}`)
264 }
265 } else {
266 const snippetText = info.snippet?.lines.join('\n') ?? ''
267 const looksLikeJsx =
268 /<[A-Z]/.test(snippetText) ||
269 (/\{.*\(.*\).*\}/.test(snippetText) && /</.test(snippetText))
270​
271 lines.push(` Suggestions:`)
272 if (looksLikeJsx) {
273 lines.push(
274 ` - Wrap the JSX in <ClientOnly fallback={<Loading />}>...</ClientOnly> so it only renders in the browser after hydration`,
275 )
276 }
277 for (const s of SERVER_ENV_SUGGESTIONS) {
278 lines.push(` - ${s}`)
279 }
280 }
281​
282 lines.push(``)
283 return lines.join('\n')