Open History to see the last commit
1import { SourceMapConsumer } from 'source-map'
2import * as path from 'pathe'
3β
4import {
5 findOriginalUnsafeUsagePosFromResult,
6 findPostCompileUsagePosFromResult,
7 getImportSpecifierLocationFromResult,
8} from './analysis'
9import { getOrCreate, normalizeFilePath } from './utils'
10import type { ImportAnalysis } from './analysis'
11import type { Loc } from './trace'
12import type { Module } from 'yuku-analyzer'
13import type { RawSourceMap } from 'source-map'
14β
15// Source-map type compatible with both Rollup's SourceMap and source-map's
16// RawSourceMap. Structural type avoids version: number vs string mismatch.
17β
18/**
19 * Minimal source-map shape used throughout the import-protection plugin.
20 */
21export interface SourceMapLike {
22 file?: string
23 sourceRoot?: string
24 version: number | string
25 sources: Array<string>
26 names: Array<string>
27 sourcesContent?: Array<string | null>
28 mappings: string
29}
30β
31export interface ImportProtectionPerfRecorder {
32 count: (name: string, value?: number) => void
33 time: (name: string, startedAt: number) => void
34}
35β
36// Transform result provider (replaces ctx.load() which doesn't work in dev)
37export interface TransformResult {
38 code: string
39 filename?: string
40 map: SourceMapLike | undefined
41 originalCode: string | undefined
42 originalResult?: TransformResult
43 /** Precomputed line index for `code` (index β line/col). */
44 lineIndex?: LineIndex
45 analyzedModule?: Module
46 analysis?: ImportAnalysis
47 perf?: ImportProtectionPerfRecorder
48}
49β
50/**
51 * Provides the transformed code and composed sourcemap for a module.
52 *
53 * Populated from a late-running transform hook. By the time `resolveId`
54 * fires for an import, the importer has already been fully transformed.
55 */
56export interface TransformResultProvider {
57 getTransformResult: (id: string) => TransformResult | undefined
58}
59β
60export interface ImportSpecifierLocationIndex {
61 find: FindImportSpecifierLocationIndex
62}
63β
64// Index β line/column conversion
65β
66export type LineIndex = {
67 offsets: Array<number>
68}
69β
70export function buildLineIndex(code: string): LineIndex {
71 const offsets: Array<number> = [0]
72 for (let i = 0; i < code.length; i++) {
73 if (code.charCodeAt(i) === 10) {
74 offsets.push(i + 1)
75 }
76 }
77 return { offsets }
78}
79β
80function upperBound(values: Array<number>, x: number): number {
81 let lo = 0
82 let hi = values.length
83 while (lo < hi) {
84 const mid = (lo + hi) >> 1
85 if (values[mid]! <= x) lo = mid + 1
86 else hi = mid
87 }
88 return lo
89}
90β
91function indexToLineColWithIndex(
92 lineIndex: LineIndex,
93 idx: number,
94): { line: number; column0: number } {
95 const offsets = lineIndex.offsets
96 const ub = upperBound(offsets, idx)
97 const lineIdx = Math.max(0, ub - 1)
98 const line = lineIdx + 1
99β
100 const lineStart = offsets[lineIdx] ?? 0
101 return { line, column0: Math.max(0, idx - lineStart) }
102}
103β
104export function indexToLineColumn(
105 lineIndex: LineIndex,
106 idx: number,
107): { line: number; column: number } {
108 const { line, column0 } = indexToLineColWithIndex(lineIndex, idx)
109 return {
110 line,
111 column: column0 + 1,
112 }
113}
114β
115export function normalizeSourceMap(map: SourceMapLike | null | undefined):
116 | {
117 version: number
118 file: string
119 sourceRoot?: string
120 sources: Array<string>
121 names: Array<string>
122 sourcesContent?: Array<string>
123 mappings: string
124 }
125 | undefined {
126 if (!map) {
127 return undefined
128 }
129β
130 return {
131 ...map,
132 version: Number(map.version),
133 file: map.file ?? '',
134 names: Array.isArray(map.names) ? map.names : [],
135 sourcesContent:
136 map.sourcesContent?.map((value) => value ?? '') ?? undefined,
137 }
138}
139β
140/**
141 * Pick the most-likely original source text for `importerFile` from
142 * a sourcemap that may contain multiple sources.
143 */
144export function pickOriginalCodeFromSourcesContent(
145 map: SourceMapLike | undefined,
146 importerFile: string,
147 root: string,
148): string | undefined {
149 if (!map?.sourcesContent || map.sources.length === 0) {
150 return undefined
151 }
152β
153 const file = normalizeFilePath(importerFile)
154 const sourceRoot = map.sourceRoot
155 const fileSeg = file.split('/').filter(Boolean)
156β
157 const resolveBase = sourceRoot ? path.resolve(root, sourceRoot) : root
158β
159 let bestIdx = -1
160 let bestScore = -1
161β
162 for (let i = 0; i < map.sources.length; i++) {
163 const content = map.sourcesContent[i]
164 if (typeof content !== 'string') continue
165β
166 const src = map.sources[i] ?? ''
167β
168 const normalizedSrc = normalizeFilePath(src)
169 if (normalizedSrc === file) {
170 return content
171 }
172β
173 let resolved: string
174 if (!src) {
175 resolved = ''
176 } else if (path.isAbsolute(src)) {
177 resolved = normalizeFilePath(src)
178 } else {
179 resolved = normalizeFilePath(path.resolve(resolveBase, src))
180 }
181 if (resolved === file) {
182 return content
183 }
184β
185 // Count matching path segments from the end.
186 const normalizedSrcSeg = normalizedSrc.split('/').filter(Boolean)
187 const resolvedSeg =
188 resolved !== normalizedSrc
189 ? resolved.split('/').filter(Boolean)
190 : normalizedSrcSeg
191 const score = Math.max(
192 segmentSuffixScore(normalizedSrcSeg, fileSeg),
193 segmentSuffixScore(resolvedSeg, fileSeg),
194 )
195β
196 if (score > bestScore) {
197 bestScore = score
198 bestIdx = i
199 }
200 }
201β
202 if (bestIdx !== -1 && bestScore >= 1) {
203 return map.sourcesContent[bestIdx] ?? undefined
204 }
205β
206 return map.sourcesContent[0] ?? undefined
207}
208β
209/** Count matching path segments from the end of `aSeg` against `bSeg`. */
210function segmentSuffixScore(aSeg: Array<string>, bSeg: Array<string>): number {
211 let score = 0
212 for (
213 let i = aSeg.length - 1, j = bSeg.length - 1;
214 i >= 0 && j >= 0;
215 i--, j--
216 ) {
217 if (aSeg[i] !== bSeg[j]) break
218 score++
219 }
220 return score
221}
222β
223async function mapGeneratedToOriginal(
224 map: SourceMapLike | undefined,
225 generated: { line: number; column0: number },
226 fallbackFile: string,
227): Promise<Loc> {
228 const fallback: Loc = {
229 file: fallbackFile,
230 line: generated.line,
231 column: generated.column0 + 1,
232 }
233β
234 if (!map) {
235 return fallback
236 }
237β
238 const consumer = await getSourceMapConsumer(map)
239 if (!consumer) return fallback
240β
241 try {
242 const orig = consumer.originalPositionFor({
243 line: generated.line,
244 column: generated.column0,
245 })
246 if (orig.line != null && orig.column != null) {
247 return {
248 file: orig.source ? normalizeFilePath(orig.source) : fallbackFile,
249 line: orig.line,
250 column: orig.column + 1,
251 }
252 }
253 } catch {
254 // Malformed sourcemap
255 }
256β
257 return fallback
258}
259β
260const consumerCache = new WeakMap<object, Promise<SourceMapConsumer | null>>()
261β
262function getOriginalCode(
263 result: TransformResult,
264 importerFile: string | undefined,
265 root: string | undefined,
266): string | undefined {
267 if (result.originalCode === undefined && importerFile && root) {
268 const map = result.map
269 if (map?.sourcesContent) {
270 result.originalCode = pickOriginalCodeFromSourcesContent(
271 map,
272 importerFile,
273 root,
274 )
275 }
276 }
277β
278 return result.originalCode
279}
280β
281function toRawSourceMap(map: SourceMapLike): RawSourceMap {
282 return {
283 ...map,
284 file: map.file ?? '',
285 version: Number(map.version),
286 sourcesContent: map.sourcesContent?.map((s) => s ?? '') ?? [],
287 }
288}
289β
290async function getSourceMapConsumer(
291 map: SourceMapLike,
292): Promise<SourceMapConsumer | null> {
293 const cached = consumerCache.get(map)
294 if (cached) return cached
295β
296 const promise = (async () => {
297 try {
298 return await new SourceMapConsumer(toRawSourceMap(map))
299 } catch {
300 return null
301 }
302 })()
303β
304 consumerCache.set(map, promise)
305 return promise
306}
307β
308export type ImportLocEntry = { file?: string; line: number; column: number }
309β
310/**
311 * Cache for import statement locations with reverse index for O(1)
312 * invalidation by file. Keys: `${importerFile}::${source}`.
313 */
314export class ImportLocCache {
315 private cache = new Map<string, ImportLocEntry | null>()
316 private reverseIndex = new Map<string, Set<string>>()
317β
318 has(key: string): boolean {
319 return this.cache.has(key)
320 }
321β
322 get(key: string): ImportLocEntry | null | undefined {
323 return this.cache.get(key)
324 }
325β
326 set(key: string, value: ImportLocEntry | null): void {
327 this.cache.set(key, value)
328 const file = key.slice(0, key.indexOf('::'))
329 getOrCreate(this.reverseIndex, file, () => new Set()).add(key)
330 }
331β
332 clear(): void {
333 this.cache.clear()
334 this.reverseIndex.clear()
335 }
336β
337 /** Remove all cache entries where the importer matches `file`. */
338 deleteByFile(file: string): void {
339 const keys = this.reverseIndex.get(file)
340 if (keys) {
341 for (const key of keys) {
342 this.cache.delete(key)
343 }
344 this.reverseIndex.delete(file)
345 }
346 }
347}
348β
349export type FindImportSpecifierLocationIndex = (
350 result: TransformResult,
351 source: string,
352) => number
353β
354export function getOrCreateOriginalTransformResult(
355 result: TransformResult,
356 importerFile?: string,
357 root?: string,
358): TransformResult | undefined {
359 getOriginalCode(result, importerFile, root)
360β
361 if (!result.originalCode) {
362 return undefined
363 }
364β
365 if (!result.originalResult) {
366 result.originalResult = {
367 code: result.originalCode,
368 filename: result.filename,
369 map: undefined,
370 originalCode: result.originalCode,
371 }
372β
373 if (result.perf) {
374 result.originalResult.perf = result.perf
375 }
376 }
377β
378 return result.originalResult
379}
380β
381export function createImportSpecifierLocationIndex(): ImportSpecifierLocationIndex {
382 return {
383 find(result: TransformResult, source: string): number {
384 if (!result.code.includes(source)) {
385 return -1
386 }
387β
388 return getImportSpecifierLocationFromResult(result, source)
389 },
390 }
391}
392β
393/**
394 * Find the location of an import statement in a transformed module
395 * by searching the post-transform code and mapping back via sourcemap.
396 * Results are cached in `importLocCache`.
397 */
398export async function findImportStatementLocationFromTransformed(
399 provider: TransformResultProvider,
400 importerId: string,
401 source: string,
402 importLocCache: ImportLocCache,
403 findImportSpecifierLocationIndex: FindImportSpecifierLocationIndex,
404): Promise<Loc | undefined> {
405 const importerFile = normalizeFilePath(importerId)
406 const cacheKey = `${importerFile}::${source}`
407 if (importLocCache.has(cacheKey)) {
408 return importLocCache.get(cacheKey) ?? undefined
409 }
410β
411 try {
412 const res = provider.getTransformResult(importerId)
413 if (!res) {
414 importLocCache.set(cacheKey, null)
415 return undefined
416 }
417β
418 const { map } = res
419β
420 const lineIndex =
421 res.lineIndex ?? (res.lineIndex = buildLineIndex(res.code))
422β
423 const idx = findImportSpecifierLocationIndex(res, source)
424 if (idx === -1) {
425 importLocCache.set(cacheKey, null)
426 return undefined
427 }
428β
429 const generated = indexToLineColWithIndex(lineIndex, idx)
430 const loc = await mapGeneratedToOriginal(map, generated, importerFile)
431 importLocCache.set(cacheKey, loc)
432 return loc
433 } catch {
434 importLocCache.set(cacheKey, null)
435 return undefined
436 }
437}
438β
439/**
440 * Find the first post-compile usage location for a denied import specifier.
441 * Best-effort: searches transformed code for non-import uses of imported
442 * bindings and maps back to original source via sourcemap.
443 */
444export async function findPostCompileUsageLocation(
445 provider: TransformResultProvider,
446 importerId: string,
447 source: string,
448): Promise<Loc | undefined> {
449 try {
450 const importerFile = normalizeFilePath(importerId)
451 const res = provider.getTransformResult(importerId)
452 if (!res) return undefined
453 const { code, map } = res
454β
455 if (!res.lineIndex) {
456 res.lineIndex = buildLineIndex(code)
457 }
458β
459 const pos = findPostCompileUsagePosFromResult(res, source)
460 if (!pos) return undefined
461β
462 return await mapGeneratedToOriginal(map, pos, importerFile)
463 } catch {
464 return undefined
465 }
466}
467β
468/**
469 * Best-effort original-source usage lookup for cases where a later transform
470 * removes or rewrites the import from emitted code but preserves the original
471 * source in `sourcesContent`.
472 */
473export function findOriginalUsageLocation(
474 provider: TransformResultProvider,
475 importerId: string,
476 source: string,
477 envType?: 'client' | 'server',
478 root?: string,
479): Loc | undefined {
480 try {
481 const importerFile = normalizeFilePath(importerId)
482 const res = provider.getTransformResult(importerId)
483 if (!res) return undefined
484 const originalResult = getOrCreateOriginalTransformResult(
485 res,
486 importerFile,
487 root,
488 )
489 if (!originalResult) return undefined
490β
491 const pos = envType
492 ? findOriginalUnsafeUsagePosFromResult(originalResult, source, envType)
493 : findPostCompileUsagePosFromResult(originalResult, source)
494 if (!pos) return undefined
495β
496 return {
497 file: importerFile,
498 line: pos.line,
499 column: pos.column0 + 1,
500 }
501 } catch {
502 return undefined
503 }
504}
505β
506/**
507 * Annotate each trace hop with the location of the import that created the
508 * edge (file:line:col). Skips steps that already have a location.
509 */
510export async function addTraceImportLocations(
511 provider: TransformResultProvider,
512 trace: Array<{
513 file: string
514 specifier?: string
515 line?: number
516 column?: number
517 }>,
518 importLocCache: ImportLocCache,
519 findImportSpecifierLocationIndex: FindImportSpecifierLocationIndex,
520): Promise<void> {
521 for (const step of trace) {
522 if (!step.specifier) continue
523 if (step.line != null && step.column != null) continue
524 const loc = await findImportStatementLocationFromTransformed(
525 provider,
526 step.file,
527 step.specifier,
528 importLocCache,
529 findImportSpecifierLocationIndex,
530 )
531 if (!loc) continue
532 step.line = loc.line
533 step.column = loc.column
534 }
535}
536β
537// Code snippet extraction (vitest-style context around a location)
538β
539export interface CodeSnippet {
540 /** Source lines with line numbers, e.g. `[" 6 | import { getSecret } from './secret.server'", ...]` */
541 lines: Array<string>
542 /** The highlighted line (1-indexed original line number) */
543 highlightLine: number
544 /** Clickable file:line reference */
545 location: string
546}
547β
548/**
549 * Build a vitest-style code snippet showing lines surrounding a location.
550 *
551 * Prefers `originalCode` from the sourcemap's sourcesContent; falls back
552 * to transformed code when unavailable.
553 */
554export function buildCodeSnippet(
555 provider: TransformResultProvider,
556 moduleId: string,
557 loc: Loc,
558 contextLines: number = 2,
559 root?: string,
560): CodeSnippet | undefined {
561 try {
562 const importerFile = normalizeFilePath(moduleId)
563 const res = provider.getTransformResult(moduleId)
564 if (!res) return undefined
565β
566 const sourceCode = getOriginalCode(res, importerFile, root) ?? res.code
567 const targetLine = loc.line // 1-indexed
568 const targetCol = loc.column // 1-indexed
569β
570 if (targetLine < 1) return undefined
571β
572 const allLines = sourceCode.split('\n')
573 // Strip trailing \r from \r\n line endings
574 for (let i = 0; i < allLines.length; i++) {
575 const line = allLines[i]!
576 if (line.endsWith('\r')) allLines[i] = line.slice(0, -1)
577 }
578β
579 const wantStart = Math.max(1, targetLine - contextLines)
580 const wantEnd = Math.min(allLines.length, targetLine + contextLines)
581β
582 if (targetLine > allLines.length) return undefined
583β
584 const lines = allLines.slice(wantStart - 1, wantEnd)
585 const gutterWidth = String(wantEnd).length
586β
587 const sourceFile = loc.file ?? importerFile
588 const snippetLines: Array<string> = []
589 for (let i = 0; i < lines.length; i++) {
590 const ln = wantStart + i
591 const lineContent = lines[i]!
592 const lineNumStr = String(ln).padStart(gutterWidth, ' ')
593 const marker = ln === targetLine ? '>' : ' '
594 snippetLines.push(` ${marker} ${lineNumStr} | ${lineContent}`)
595β
596 if (ln === targetLine && targetCol > 0) {
597 const padding = ' '.repeat(targetCol - 1)
598 snippetLines.push(` ${' '.repeat(gutterWidth)} | ${padding}^`)
599 }
600 }
601β
602 return {
603 lines: snippetLines,
604 highlightLine: targetLine,
605 location: `${sourceFile}:${targetLine}:${targetCol}`,
606 }
607 } catch {
608 return undefined
609 }
610}