@tanstack/start-plugin-core 1.163.3 → 1.163.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. package/dist/esm/constants.d.ts +1 -0
  2. package/dist/esm/constants.js +2 -0
  3. package/dist/esm/constants.js.map +1 -1
  4. package/dist/esm/import-protection-plugin/ast.d.ts +3 -0
  5. package/dist/esm/import-protection-plugin/ast.js +8 -0
  6. package/dist/esm/import-protection-plugin/ast.js.map +1 -0
  7. package/dist/esm/import-protection-plugin/constants.d.ts +6 -0
  8. package/dist/esm/import-protection-plugin/constants.js +24 -0
  9. package/dist/esm/import-protection-plugin/constants.js.map +1 -0
  10. package/dist/esm/import-protection-plugin/extensionlessAbsoluteIdResolver.d.ts +22 -0
  11. package/dist/esm/import-protection-plugin/extensionlessAbsoluteIdResolver.js +95 -0
  12. package/dist/esm/import-protection-plugin/extensionlessAbsoluteIdResolver.js.map +1 -0
  13. package/dist/esm/import-protection-plugin/plugin.d.ts +2 -13
  14. package/dist/esm/import-protection-plugin/plugin.js +684 -299
  15. package/dist/esm/import-protection-plugin/plugin.js.map +1 -1
  16. package/dist/esm/import-protection-plugin/postCompileUsage.js +4 -2
  17. package/dist/esm/import-protection-plugin/postCompileUsage.js.map +1 -1
  18. package/dist/esm/import-protection-plugin/rewriteDeniedImports.d.ts +4 -5
  19. package/dist/esm/import-protection-plugin/rewriteDeniedImports.js +225 -3
  20. package/dist/esm/import-protection-plugin/rewriteDeniedImports.js.map +1 -1
  21. package/dist/esm/import-protection-plugin/sourceLocation.d.ts +4 -7
  22. package/dist/esm/import-protection-plugin/sourceLocation.js +18 -73
  23. package/dist/esm/import-protection-plugin/sourceLocation.js.map +1 -1
  24. package/dist/esm/import-protection-plugin/types.d.ts +94 -0
  25. package/dist/esm/import-protection-plugin/utils.d.ts +33 -1
  26. package/dist/esm/import-protection-plugin/utils.js +69 -3
  27. package/dist/esm/import-protection-plugin/utils.js.map +1 -1
  28. package/dist/esm/import-protection-plugin/virtualModules.d.ts +30 -2
  29. package/dist/esm/import-protection-plugin/virtualModules.js +66 -23
  30. package/dist/esm/import-protection-plugin/virtualModules.js.map +1 -1
  31. package/dist/esm/start-compiler-plugin/plugin.d.ts +2 -1
  32. package/dist/esm/start-compiler-plugin/plugin.js +1 -2
  33. package/dist/esm/start-compiler-plugin/plugin.js.map +1 -1
  34. package/package.json +4 -4
  35. package/src/constants.ts +2 -0
  36. package/src/import-protection-plugin/INTERNALS.md +462 -60
  37. package/src/import-protection-plugin/ast.ts +7 -0
  38. package/src/import-protection-plugin/constants.ts +25 -0
  39. package/src/import-protection-plugin/extensionlessAbsoluteIdResolver.ts +121 -0
  40. package/src/import-protection-plugin/plugin.ts +1080 -597
  41. package/src/import-protection-plugin/postCompileUsage.ts +8 -2
  42. package/src/import-protection-plugin/rewriteDeniedImports.ts +141 -9
  43. package/src/import-protection-plugin/sourceLocation.ts +19 -89
  44. package/src/import-protection-plugin/types.ts +103 -0
  45. package/src/import-protection-plugin/utils.ts +123 -4
  46. package/src/import-protection-plugin/virtualModules.ts +117 -31
  47. package/src/start-compiler-plugin/plugin.ts +7 -2
@@ -1 +1 @@
1
- {"version":3,"file":"plugin.js","sources":["../../../src/import-protection-plugin/plugin.ts"],"sourcesContent":["import { normalizePath } from 'vite'\n\nimport { resolveViteId } from '../utils'\nimport { VITE_ENVIRONMENT_NAMES } from '../constants'\nimport { SERVER_FN_LOOKUP } from '../start-compiler-plugin/plugin'\nimport { ImportGraph, buildTrace, formatViolation } from './trace'\nimport {\n getDefaultImportProtectionRules,\n getMarkerSpecifiers,\n} from './defaults'\nimport { findPostCompileUsagePos } from './postCompileUsage'\nimport { compileMatchers, matchesAny } from './matchers'\nimport {\n clearNormalizeFilePathCache,\n dedupePatterns,\n escapeRegExp,\n extractImportSources,\n getOrCreate,\n normalizeFilePath,\n relativizePath,\n} from './utils'\nimport { collectMockExportNamesBySource } from './rewriteDeniedImports'\nimport {\n MOCK_BUILD_PREFIX,\n getResolvedVirtualModuleMatchers,\n loadResolvedVirtualModule,\n makeMockEdgeModuleId,\n mockRuntimeModuleIdFromViolation,\n resolveInternalVirtualModuleId,\n resolvedMarkerVirtualModuleId,\n} from './virtualModules'\nimport {\n ImportLocCache,\n addTraceImportLocations,\n buildCodeSnippet,\n buildLineIndex,\n clearImportPatternCache,\n findImportStatementLocationFromTransformed,\n findPostCompileUsageLocation,\n pickOriginalCodeFromSourcesContent,\n} from './sourceLocation'\nimport type { PluginOption, ViteDevServer } from 'vite'\nimport type { CompiledMatcher } from './matchers'\nimport type { Loc, TraceStep, ViolationInfo } from './trace'\nimport type {\n SourceMapLike,\n TransformResult,\n TransformResultProvider,\n} from './sourceLocation'\nimport type {\n ImportProtectionBehavior,\n ImportProtectionOptions,\n} from '../schema'\nimport type { CompileStartFrameworkOptions, GetConfigFn } from '../types'\n\nconst SERVER_FN_LOOKUP_QUERY = '?' + SERVER_FN_LOOKUP\nconst IMPORT_PROTECTION_DEBUG =\n process.env.TSR_IMPORT_PROTECTION_DEBUG === '1' ||\n process.env.TSR_IMPORT_PROTECTION_DEBUG === 'true'\nconst IMPORT_PROTECTION_DEBUG_FILTER =\n process.env.TSR_IMPORT_PROTECTION_DEBUG_FILTER\n\nfunction debugLog(...args: Array<unknown>) {\n if (!IMPORT_PROTECTION_DEBUG) return\n console.warn('[import-protection:debug]', ...args)\n}\n\n/** Check if a value matches the debug filter (when set). */\nfunction matchesDebugFilter(...values: Array<string>): boolean {\n if (!IMPORT_PROTECTION_DEBUG_FILTER) return true\n return values.some((v) => v.includes(IMPORT_PROTECTION_DEBUG_FILTER))\n}\n\nexport { rewriteDeniedImports } from './rewriteDeniedImports'\nexport { dedupePatterns, extractImportSources } from './utils'\nexport type { Pattern } from './utils'\n\n/**\n * Immutable plugin configuration — set once in `configResolved`, never mutated\n * per-env or per-request afterward.\n */\ninterface PluginConfig {\n enabled: boolean\n root: string\n command: 'build' | 'serve'\n srcDirectory: string\n framework: CompileStartFrameworkOptions\n\n /** Absolute, query-free entry file ids used for trace roots. */\n entryFiles: Array<string>\n\n effectiveBehavior: ImportProtectionBehavior\n mockAccess: 'error' | 'warn' | 'off'\n logMode: 'once' | 'always'\n maxTraceDepth: number\n\n compiledRules: {\n client: {\n specifiers: Array<CompiledMatcher>\n files: Array<CompiledMatcher>\n excludeFiles: Array<CompiledMatcher>\n }\n server: {\n specifiers: Array<CompiledMatcher>\n files: Array<CompiledMatcher>\n excludeFiles: Array<CompiledMatcher>\n }\n }\n includeMatchers: Array<CompiledMatcher>\n excludeMatchers: Array<CompiledMatcher>\n ignoreImporterMatchers: Array<CompiledMatcher>\n\n markerSpecifiers: { serverOnly: Set<string>; clientOnly: Set<string> }\n envTypeMap: Map<string, 'client' | 'server'>\n\n onViolation?: (\n info: ViolationInfo,\n ) => boolean | void | Promise<boolean | void>\n}\n\n/**\n * Per-Vite-environment mutable state. One instance per environment name,\n * stored in `envStates: Map<string, EnvState>`.\n *\n * All caches that previously lived on `PluginState` with `${envName}:` key\n * prefixes now live here without any prefix.\n */\ninterface EnvState {\n graph: ImportGraph\n /** Specifiers that resolved to the mock module (for transform-time rewriting). */\n deniedSources: Set<string>\n /** Per-importer denied edges (for dev ESM mock modules). */\n deniedEdges: Map<string, Set<string>>\n /**\n * During `vite dev` in mock mode, we generate a per-importer mock module that\n * exports the names the importer expects.\n * Populated in the transform hook (no disk reads).\n */\n mockExportsByImporter: Map<string, Map<string, Array<string>>>\n\n /** Resolve cache. Key: `${normalizedImporter}:${source}` (no env prefix). */\n resolveCache: Map<string, string | null>\n /** Reverse index: file path → Set of resolveCache keys involving that file. */\n resolveCacheByFile: Map<string, Set<string>>\n\n /** Import location cache. Key: `${importerFile}::${source}`. */\n importLocCache: ImportLocCache\n\n /** Deduplication of logged violations (no env prefix in key). */\n seenViolations: Set<string>\n\n /**\n * Modules transitively loaded during a `fetchModule(?SERVER_FN_LOOKUP)` call.\n * In dev mode the compiler calls `fetchModule(id + '?' + SERVER_FN_LOOKUP)` to\n * analyse a module's exports. The direct target carries the query parameter so\n * `isPreTransformResolve` is `true`. But Vite also resolves the target's own\n * imports (and their imports, etc.) with the plain file path as the importer —\n * those would otherwise fire false-positive violations.\n *\n * We record every module resolved while walking a SERVER_FN_LOOKUP chain so\n * that their child imports are also treated as pre-transform resolves.\n */\n serverFnLookupModules: Set<string>\n\n /** Transform result cache (code + composed sourcemap + original source). */\n transformResultCache: Map<string, TransformResult>\n /** Reverse index: physical file path → Set of transformResultCache keys. */\n transformResultKeysByFile: Map<string, Set<string>>\n\n /** Cached provider that reads from {@link transformResultCache}. */\n transformResultProvider: TransformResultProvider\n\n /**\n * Post-transform resolved imports. Populated by the transform-cache hook\n * after resolving every import source found in the transformed code.\n * Key: transform cache key (normalised module ID incl. query params).\n * Value: set of resolved child file paths.\n */\n postTransformImports: Map<string, Set<string>>\n\n /**\n * Violations deferred in dev mock mode. Keyed by the violating importer's\n * normalized file path. Violations are confirmed or discarded by the\n * transform-cache hook once enough post-transform data is available to\n * determine whether the importer is still reachable from an entry point.\n */\n pendingViolations: Map<string, Array<PendingViolation>>\n\n /**\n * Violations deferred in build mode (both mock and error). Each gets a\n * unique mock module ID so we can check which ones survived tree-shaking\n * in `generateBundle`.\n */\n deferredBuildViolations: Array<DeferredBuildViolation>\n}\n\ninterface PendingViolation {\n info: ViolationInfo\n /** The mock module ID that resolveId already returned for this violation. */\n mockReturnValue: string\n}\n\ninterface DeferredBuildViolation {\n info: ViolationInfo\n /** Unique mock module ID assigned to this violation. */\n mockModuleId: string\n\n /**\n * Module ID to check for tree-shaking survival in `generateBundle`.\n *\n * For most violations we check the unique mock module ID.\n * For `marker` violations the import is a bare side-effect import that often\n * gets optimized away regardless of whether the importer survives, so we\n * instead check whether the importer module itself survived.\n */\n checkModuleId?: string\n}\n\n/**\n * Intentionally cross-env shared mutable state.\n *\n * A file's `'use server'`/`'use client'` directive is inherent to the file\n * content, not the environment that happens to discover it first.\n */\ninterface SharedState {\n fileMarkerKind: Map<string, 'server' | 'client'>\n}\n\nexport interface ImportProtectionPluginOptions {\n getConfig: GetConfigFn\n framework: CompileStartFrameworkOptions\n environments: Array<{ name: string; type: 'client' | 'server' }>\n providerEnvName: string\n}\n\nexport function importProtectionPlugin(\n opts: ImportProtectionPluginOptions,\n): PluginOption {\n let devServer: ViteDevServer | null = null\n\n type ModuleGraphNode = {\n id?: string | null\n url?: string\n importers: Set<ModuleGraphNode>\n }\n\n /**\n * Build an import trace using Vite's per-environment module graph, which\n * is authoritative even on warm starts when the plugin's own ImportGraph\n * may be incomplete (Vite skips resolveId for cached modules).\n */\n function buildTraceFromModuleGraph(\n envName: string,\n env: EnvState,\n targetFile: string,\n ): Array<TraceStep> | null {\n if (!devServer) return null\n const environment = devServer.environments[envName]\n if (!environment) return null\n\n const file = normalizeFilePath(targetFile)\n const start = environment.moduleGraph.getModuleById(file)\n if (!start) return null\n\n // Resolve a module graph node to its normalized file path once and\n // cache the result so BFS + reconstruction don't recompute.\n const nodeIds = new Map<ModuleGraphNode, string>()\n function nodeId(n: ModuleGraphNode): string {\n let cached = nodeIds.get(n)\n if (cached === undefined) {\n cached = n.id\n ? normalizeFilePath(n.id)\n : n.url\n ? normalizeFilePath(n.url)\n : ''\n nodeIds.set(n, cached)\n }\n return cached\n }\n\n const queue: Array<ModuleGraphNode> = [start]\n const visited = new Set<ModuleGraphNode>([start])\n const parent = new Map<ModuleGraphNode, ModuleGraphNode>()\n\n let entryRoot: ModuleGraphNode | null = null\n let fallbackRoot: ModuleGraphNode | null = null\n let qi = 0\n while (qi < queue.length) {\n const node = queue[qi++]!\n const id = nodeId(node)\n\n if (id && env.graph.entries.has(id)) {\n entryRoot = node\n break\n }\n\n const importers = node.importers\n if (importers.size === 0) {\n if (!fallbackRoot) fallbackRoot = node\n continue\n }\n\n for (const imp of importers) {\n if (visited.has(imp)) continue\n visited.add(imp)\n parent.set(imp, node)\n queue.push(imp)\n }\n }\n\n const root = entryRoot ?? fallbackRoot\n\n if (!root) return null\n\n // Reconstruct: root -> ... -> start\n const chain: Array<ModuleGraphNode> = []\n let cur: ModuleGraphNode | undefined = root\n for (let i = 0; i < config.maxTraceDepth + 2 && cur; i++) {\n chain.push(cur)\n if (cur === start) break\n cur = parent.get(cur)\n }\n\n const steps: Array<TraceStep> = []\n for (let i = 0; i < chain.length; i++) {\n const id = nodeId(chain[i]!)\n if (!id) continue\n let specifier: string | undefined\n if (i + 1 < chain.length) {\n const nextId = nodeId(chain[i + 1]!)\n if (nextId) {\n specifier = env.graph.reverseEdges.get(nextId)?.get(id)\n }\n }\n steps.push(specifier ? { file: id, specifier } : { file: id })\n }\n\n return steps.length ? steps : null\n }\n\n const config: PluginConfig = {\n enabled: true,\n root: '',\n command: 'build',\n srcDirectory: '',\n framework: opts.framework,\n entryFiles: [],\n effectiveBehavior: 'error',\n mockAccess: 'error',\n logMode: 'once',\n maxTraceDepth: 20,\n compiledRules: {\n client: { specifiers: [], files: [], excludeFiles: [] },\n server: { specifiers: [], files: [], excludeFiles: [] },\n },\n includeMatchers: [],\n excludeMatchers: [],\n ignoreImporterMatchers: [],\n markerSpecifiers: { serverOnly: new Set(), clientOnly: new Set() },\n envTypeMap: new Map(opts.environments.map((e) => [e.name, e.type])),\n onViolation: undefined,\n }\n\n const envStates = new Map<string, EnvState>()\n const shared: SharedState = { fileMarkerKind: new Map() }\n\n function getMarkerKindForFile(\n fileId: string,\n ): 'server' | 'client' | undefined {\n const file = normalizeFilePath(fileId)\n return shared.fileMarkerKind.get(file)\n }\n\n type ViolationReporter = {\n warn: (msg: string) => void\n error: (msg: string) => never\n }\n\n /**\n * Build the best available trace for a module and enrich each step with\n * line/column locations. Tries the plugin's own ImportGraph first, then\n * Vite's moduleGraph (authoritative on warm start), keeping whichever is\n * longer. Annotates the last step with the denied specifier + location.\n *\n * Shared by {@link buildViolationInfo} and {@link processPendingViolations}.\n */\n async function rebuildAndAnnotateTrace(\n provider: TransformResultProvider,\n env: EnvState,\n envName: string,\n normalizedImporter: string,\n specifier: string,\n importerLoc: Loc | undefined,\n traceOverride?: Array<TraceStep>,\n ): Promise<Array<TraceStep>> {\n let trace =\n traceOverride ??\n buildTrace(env.graph, normalizedImporter, config.maxTraceDepth)\n\n if (config.command === 'serve') {\n const mgTrace = buildTraceFromModuleGraph(\n envName,\n env,\n normalizedImporter,\n )\n if (mgTrace && mgTrace.length > trace.length) {\n trace = mgTrace\n }\n }\n await addTraceImportLocations(provider, trace, env.importLocCache)\n\n if (trace.length > 0) {\n const last = trace[trace.length - 1]!\n if (!last.specifier) last.specifier = specifier\n if (importerLoc && last.line == null) {\n last.line = importerLoc.line\n last.column = importerLoc.column\n }\n }\n\n return trace\n }\n\n /**\n * Build a complete {@link ViolationInfo} with trace, location, and snippet.\n *\n * This is the single path that all violation types go through: specifier,\n * file, and marker.\n */\n async function buildViolationInfo(\n provider: TransformResultProvider,\n env: EnvState,\n envName: string,\n envType: 'client' | 'server',\n importer: string,\n normalizedImporter: string,\n source: string,\n overrides: Omit<\n ViolationInfo,\n | 'env'\n | 'envType'\n | 'behavior'\n | 'specifier'\n | 'importer'\n | 'trace'\n | 'snippet'\n | 'importerLoc'\n >,\n traceOverride?: Array<TraceStep>,\n ): Promise<ViolationInfo> {\n const loc =\n (await findPostCompileUsageLocation(\n provider,\n importer,\n source,\n findPostCompileUsagePos,\n )) ||\n (await findImportStatementLocationFromTransformed(\n provider,\n importer,\n source,\n env.importLocCache,\n ))\n\n const trace = await rebuildAndAnnotateTrace(\n provider,\n env,\n envName,\n normalizedImporter,\n source,\n loc,\n traceOverride,\n )\n\n const snippet = loc ? buildCodeSnippet(provider, importer, loc) : undefined\n\n return {\n env: envName,\n envType,\n behavior: config.effectiveBehavior,\n specifier: source,\n importer: normalizedImporter,\n ...(loc ? { importerLoc: loc } : {}),\n trace,\n snippet,\n ...overrides,\n }\n }\n\n /**\n * Check if a resolved import violates marker restrictions (e.g. importing\n * a server-only module in the client env). If so, build and return the\n * {@link ViolationInfo} — the caller is responsible for reporting/deferring.\n *\n * Returns `undefined` when the resolved import has no marker conflict.\n */\n async function buildMarkerViolationFromResolvedImport(\n provider: TransformResultProvider,\n env: EnvState,\n envName: string,\n envType: 'client' | 'server',\n importer: string,\n source: string,\n resolvedId: string,\n relativePath: string,\n traceOverride?: Array<TraceStep>,\n ): Promise<ViolationInfo | undefined> {\n const markerKind = getMarkerKindForFile(resolvedId)\n const violates =\n (envType === 'client' && markerKind === 'server') ||\n (envType === 'server' && markerKind === 'client')\n if (!violates) return undefined\n\n const normalizedImporter = normalizeFilePath(importer)\n\n return buildViolationInfo(\n provider,\n env,\n envName,\n envType,\n importer,\n normalizedImporter,\n source,\n {\n type: 'marker',\n resolved: normalizeFilePath(resolvedId),\n message:\n markerKind === 'server'\n ? `Module \"${relativePath}\" is marked server-only but is imported in the client environment`\n : `Module \"${relativePath}\" is marked client-only but is imported in the server environment`,\n },\n traceOverride,\n )\n }\n\n function getEnvType(envName: string): 'client' | 'server' {\n return config.envTypeMap.get(envName) ?? 'server'\n }\n\n function getRulesForEnvironment(envName: string): {\n specifiers: Array<CompiledMatcher>\n files: Array<CompiledMatcher>\n excludeFiles: Array<CompiledMatcher>\n } {\n const type = getEnvType(envName)\n return type === 'client'\n ? config.compiledRules.client\n : config.compiledRules.server\n }\n\n const environmentNames = new Set<string>([\n VITE_ENVIRONMENT_NAMES.client,\n VITE_ENVIRONMENT_NAMES.server,\n ])\n if (opts.providerEnvName !== VITE_ENVIRONMENT_NAMES.server) {\n environmentNames.add(opts.providerEnvName)\n }\n\n /** Get (or lazily create) the per-env state for the given environment name. */\n function getEnv(envName: string): EnvState {\n let envState = envStates.get(envName)\n if (!envState) {\n const transformResultCache = new Map<string, TransformResult>()\n envState = {\n graph: new ImportGraph(),\n deniedSources: new Set(),\n deniedEdges: new Map(),\n mockExportsByImporter: new Map(),\n resolveCache: new Map(),\n resolveCacheByFile: new Map(),\n importLocCache: new ImportLocCache(),\n seenViolations: new Set(),\n transformResultCache,\n transformResultKeysByFile: new Map(),\n transformResultProvider: {\n getTransformResult(id: string) {\n const fullKey = normalizePath(id)\n const exact = transformResultCache.get(fullKey)\n if (exact) return exact\n const strippedKey = normalizeFilePath(id)\n return strippedKey !== fullKey\n ? transformResultCache.get(strippedKey)\n : undefined\n },\n },\n postTransformImports: new Map(),\n serverFnLookupModules: new Set(),\n pendingViolations: new Map(),\n deferredBuildViolations: [],\n }\n envStates.set(envName, envState)\n }\n return envState\n }\n\n const shouldCheckImporterCache = new Map<string, boolean>()\n function shouldCheckImporter(importer: string): boolean {\n let result = shouldCheckImporterCache.get(importer)\n if (result !== undefined) return result\n\n const relativePath = relativizePath(importer, config.root)\n\n if (\n config.excludeMatchers.length > 0 &&\n matchesAny(relativePath, config.excludeMatchers)\n ) {\n result = false\n } else if (\n config.ignoreImporterMatchers.length > 0 &&\n matchesAny(relativePath, config.ignoreImporterMatchers)\n ) {\n result = false\n } else if (config.includeMatchers.length > 0) {\n result = !!matchesAny(relativePath, config.includeMatchers)\n } else if (config.srcDirectory) {\n result = importer.startsWith(config.srcDirectory)\n } else {\n result = true\n }\n\n shouldCheckImporterCache.set(importer, result)\n return result\n }\n\n function dedupeKey(\n type: string,\n importer: string,\n specifier: string,\n resolved?: string,\n ): string {\n return `${type}:${importer}:${specifier}:${resolved ?? ''}`\n }\n\n function hasSeen(env: EnvState, key: string): boolean {\n if (config.logMode === 'always') return false\n if (env.seenViolations.has(key)) return true\n env.seenViolations.add(key)\n return false\n }\n\n function getRelativePath(absolutePath: string): string {\n return relativizePath(normalizePath(absolutePath), config.root)\n }\n\n /** Register known Start entrypoints as trace roots for all environments. */\n function registerEntries(): void {\n const { resolvedStartConfig } = opts.getConfig()\n for (const envDef of opts.environments) {\n const envState = getEnv(envDef.name)\n if (resolvedStartConfig.routerFilePath) {\n envState.graph.addEntry(\n normalizePath(resolvedStartConfig.routerFilePath),\n )\n }\n if (resolvedStartConfig.startFilePath) {\n envState.graph.addEntry(\n normalizePath(resolvedStartConfig.startFilePath),\n )\n }\n }\n }\n\n function checkPostTransformReachability(\n env: EnvState,\n file: string,\n ): 'reachable' | 'unreachable' | 'unknown' {\n const visited = new Set<string>()\n const queue: Array<string> = [file]\n let hasUnknownEdge = false\n let qi = 0\n\n while (qi < queue.length) {\n const current = queue[qi++]!\n if (visited.has(current)) continue\n visited.add(current)\n\n if (env.graph.entries.has(current)) {\n return 'reachable'\n }\n\n // Walk reverse edges\n const importers = env.graph.reverseEdges.get(current)\n if (!importers) continue\n\n for (const [parent] of importers) {\n if (visited.has(parent)) continue\n\n // Check all code-split variants for this parent. The edge is\n // live if ANY variant's resolved imports include `current`.\n // Skip SERVER_FN_LOOKUP variants — they contain untransformed\n // code (the compiler excludes them), so their import lists\n // include imports that the compiler would normally strip.\n const keySet = env.transformResultKeysByFile.get(parent)\n let anyVariantCached = false\n let edgeLive = false\n\n if (keySet) {\n for (const k of keySet) {\n if (k.includes(SERVER_FN_LOOKUP_QUERY)) continue\n const resolvedImports = env.postTransformImports.get(k)\n if (resolvedImports) {\n anyVariantCached = true\n if (resolvedImports.has(current)) {\n edgeLive = true\n break\n }\n }\n }\n }\n\n // Fallback: direct file-path key\n if (!anyVariantCached) {\n const resolvedImports = env.postTransformImports.get(parent)\n if (resolvedImports) {\n anyVariantCached = true\n if (resolvedImports.has(current)) {\n edgeLive = true\n }\n }\n }\n\n if (!anyVariantCached) {\n const hasTransformResult =\n env.transformResultCache.has(parent) ||\n (keySet ? keySet.size > 0 : false)\n\n if (hasTransformResult) {\n // Transform ran but postTransformImports not yet populated\n hasUnknownEdge = true\n continue\n }\n\n // Transform never ran — Vite served from cache (warm start).\n // Conservatively treat edge as live.\n queue.push(parent)\n continue\n }\n\n if (edgeLive) {\n queue.push(parent)\n }\n }\n }\n\n return hasUnknownEdge ? 'unknown' : 'unreachable'\n }\n\n /**\n * Process pending violations for the given environment. Called from the\n * transform-cache hook after each module transform is cached, because new\n * transform data may allow us to confirm or discard pending violations.\n *\n * @param warnFn - `this.warn` from the transform hook context\n */\n async function processPendingViolations(\n env: EnvState,\n warnFn: (msg: string) => void,\n ): Promise<void> {\n if (env.pendingViolations.size === 0) return\n\n const toDelete: Array<string> = []\n\n for (const [file, violations] of env.pendingViolations) {\n // Wait for entries before running reachability. registerEntries()\n // populates entries at buildStart; resolveId(!importer) may add more.\n const status =\n env.graph.entries.size > 0\n ? checkPostTransformReachability(env, file)\n : 'unknown'\n\n if (status === 'reachable') {\n for (const pv of violations) {\n const key = dedupeKey(\n pv.info.type,\n pv.info.importer,\n pv.info.specifier,\n pv.info.resolved,\n )\n if (!hasSeen(env, key)) {\n const freshTrace = await rebuildAndAnnotateTrace(\n env.transformResultProvider,\n env,\n pv.info.env,\n pv.info.importer,\n pv.info.specifier,\n pv.info.importerLoc,\n )\n if (freshTrace.length > pv.info.trace.length) {\n pv.info.trace = freshTrace\n }\n\n if (config.onViolation) {\n const result = await config.onViolation(pv.info)\n if (result === false) continue\n }\n warnFn(formatViolation(pv.info, config.root))\n }\n }\n toDelete.push(file)\n } else if (status === 'unreachable') {\n toDelete.push(file)\n }\n // 'unknown' — keep pending for next transform-cache invocation.\n }\n\n for (const file of toDelete) {\n env.pendingViolations.delete(file)\n }\n }\n\n /**\n * Record a violation as pending for later confirmation via graph\n * reachability. Called from `resolveId` when `shouldDefer` is true.\n */\n function deferViolation(\n env: EnvState,\n importerFile: string,\n info: ViolationInfo,\n mockReturnValue: string | undefined,\n ): void {\n getOrCreate(env.pendingViolations, importerFile, () => []).push({\n info,\n mockReturnValue: mockReturnValue ?? '',\n })\n }\n\n /** Counter for generating unique per-violation mock module IDs in build mode. */\n let buildViolationCounter = 0\n\n type HandleViolationResult = string | undefined\n\n async function handleViolation(\n ctx: ViolationReporter,\n env: EnvState,\n info: ViolationInfo,\n violationOpts?: { silent?: boolean },\n ): Promise<HandleViolationResult> {\n const key = dedupeKey(\n info.type,\n info.importer,\n info.specifier,\n info.resolved,\n )\n\n if (!violationOpts?.silent) {\n if (config.onViolation) {\n const result = await config.onViolation(info)\n if (result === false) {\n return undefined\n }\n }\n\n if (config.effectiveBehavior === 'error') {\n // Dev+error: throw immediately.\n // Always throw on error — do NOT deduplicate via hasSeen().\n // Rollup may resolve the same specifier multiple times (e.g.\n // commonjs--resolver's nested this.resolve() fires before\n // getResolveStaticDependencyPromises). If we record the key\n // on the first (nested) throw, the second (real) resolve\n // silently returns undefined and the build succeeds — which\n // is the bug this fixes.\n //\n // Build mode never reaches here — all build violations are\n // deferred via shouldDefer and handled silently.\n\n return ctx.error(formatViolation(info, config.root))\n }\n\n const seen = hasSeen(env, key)\n\n if (!seen) {\n ctx.warn(formatViolation(info, config.root))\n }\n } else {\n if (config.effectiveBehavior === 'error' && config.command !== 'build') {\n return undefined\n }\n }\n\n env.deniedSources.add(info.specifier)\n getOrCreate(env.deniedEdges, info.importer, () => new Set<string>()).add(\n info.specifier,\n )\n\n if (config.command === 'serve') {\n const runtimeId = mockRuntimeModuleIdFromViolation(\n info,\n config.mockAccess,\n config.root,\n )\n const importerFile = normalizeFilePath(info.importer)\n const exports =\n env.mockExportsByImporter.get(importerFile)?.get(info.specifier) ?? []\n return resolveViteId(\n makeMockEdgeModuleId(exports, info.specifier, runtimeId),\n )\n }\n\n // Build: unique per-violation mock IDs so generateBundle can check\n // which violations survived tree-shaking (both mock and error mode).\n // We wrap the base mock in a mock-edge module that provides explicit\n // named exports — Rolldown doesn't support Rollup's\n // syntheticNamedExports, so without this named imports like\n // `import { Foo } from \"denied-pkg\"` would fail with MISSING_EXPORT.\n //\n // Use the unresolved MOCK_BUILD_PREFIX (without \\0) as the runtimeId\n // so the mock-edge module's `import mock from \"...\"` goes through\n // resolveId, which adds the \\0 prefix. Using the resolved ID directly\n // would cause Rollup/Vite to skip resolveId and fail to find the module.\n const baseMockId = `${MOCK_BUILD_PREFIX}${buildViolationCounter++}`\n const importerFile = normalizeFilePath(info.importer)\n const exports =\n env.mockExportsByImporter.get(importerFile)?.get(info.specifier) ?? []\n return resolveViteId(\n makeMockEdgeModuleId(exports, info.specifier, baseMockId),\n )\n }\n\n /**\n * Unified violation dispatch: either defers or reports immediately.\n *\n * When `shouldDefer` is true, calls `handleViolation` silently to obtain\n * the mock module ID, then stores the violation for later verification:\n * - Dev mock mode: defers to `pendingViolations` for graph-reachability\n * checking via `processPendingViolations`.\n * - Build mode (mock + error): defers to `deferredBuildViolations` for\n * tree-shaking verification in `generateBundle`.\n *\n * Otherwise reports (or silences for pre-transform resolves) immediately.\n *\n * Returns the mock module ID / resolve result from `handleViolation`.\n */\n async function reportOrDeferViolation(\n ctx: ViolationReporter,\n env: EnvState,\n importerFile: string,\n info: ViolationInfo,\n shouldDefer: boolean,\n isPreTransformResolve: boolean,\n ): Promise<HandleViolationResult> {\n if (shouldDefer) {\n const result = await handleViolation(ctx, env, info, { silent: true })\n\n if (config.command === 'build') {\n // Build mode: store for generateBundle tree-shaking check.\n // The mock-edge module ID is returned as a plain string.\n const mockId = result ?? ''\n env.deferredBuildViolations.push({\n info,\n mockModuleId: mockId,\n // For marker violations, check importer survival instead of mock.\n checkModuleId: info.type === 'marker' ? info.importer : undefined,\n })\n } else {\n // Dev mock: store for graph-reachability check.\n deferViolation(env, importerFile, info, result)\n await processPendingViolations(env, ctx.warn.bind(ctx))\n }\n\n return result\n }\n return await handleViolation(ctx, env, info, {\n silent: isPreTransformResolve,\n })\n }\n\n return [\n {\n name: 'tanstack-start-core:import-protection',\n enforce: 'pre',\n\n applyToEnvironment(env) {\n if (!config.enabled) return false\n // Start's environments are named `client` and `ssr` (not `server`), plus\n // an optional serverFn provider environment (eg `rsc`) when configured.\n return environmentNames.has(env.name)\n },\n\n configResolved(viteConfig) {\n config.root = viteConfig.root\n config.command = viteConfig.command\n\n const { startConfig, resolvedStartConfig } = opts.getConfig()\n config.srcDirectory = resolvedStartConfig.srcDirectory\n\n config.entryFiles = [\n resolvedStartConfig.routerFilePath,\n resolvedStartConfig.startFilePath,\n ].filter((f): f is string => Boolean(f))\n\n const userOpts: ImportProtectionOptions | undefined =\n startConfig.importProtection\n\n if (userOpts?.enabled === false) {\n config.enabled = false\n return\n }\n\n config.enabled = true\n\n if (userOpts?.behavior) {\n if (typeof userOpts.behavior === 'string') {\n config.effectiveBehavior = userOpts.behavior\n } else {\n config.effectiveBehavior =\n viteConfig.command === 'serve'\n ? (userOpts.behavior.dev ?? 'mock')\n : (userOpts.behavior.build ?? 'error')\n }\n } else {\n config.effectiveBehavior =\n viteConfig.command === 'serve' ? 'mock' : 'error'\n }\n\n config.logMode = userOpts?.log ?? 'once'\n config.mockAccess = userOpts?.mockAccess ?? 'error'\n config.maxTraceDepth = userOpts?.maxTraceDepth ?? 20\n if (userOpts?.onViolation) {\n const fn = userOpts.onViolation\n config.onViolation = (info) => fn(info)\n }\n\n const defaults = getDefaultImportProtectionRules()\n\n // Client specifier denies always include framework defaults even\n // when the user provides a custom list.\n const clientSpecifiers = dedupePatterns([\n ...defaults.client.specifiers,\n ...(userOpts?.client?.specifiers ?? []),\n ])\n\n const clientFiles = userOpts?.client?.files\n ? [...userOpts.client.files]\n : [...defaults.client.files]\n const clientExcludeFiles = userOpts?.client?.excludeFiles\n ? [...userOpts.client.excludeFiles]\n : [...defaults.client.excludeFiles]\n const serverSpecifiers = userOpts?.server?.specifiers\n ? dedupePatterns([...userOpts.server.specifiers])\n : dedupePatterns([...defaults.server.specifiers])\n const serverFiles = userOpts?.server?.files\n ? [...userOpts.server.files]\n : [...defaults.server.files]\n const serverExcludeFiles = userOpts?.server?.excludeFiles\n ? [...userOpts.server.excludeFiles]\n : [...defaults.server.excludeFiles]\n\n config.compiledRules.client = {\n specifiers: compileMatchers(clientSpecifiers),\n files: compileMatchers(clientFiles),\n excludeFiles: compileMatchers(clientExcludeFiles),\n }\n config.compiledRules.server = {\n specifiers: compileMatchers(serverSpecifiers),\n files: compileMatchers(serverFiles),\n excludeFiles: compileMatchers(serverExcludeFiles),\n }\n\n // Include/exclude\n if (userOpts?.include) {\n config.includeMatchers = compileMatchers(userOpts.include)\n }\n if (userOpts?.exclude) {\n config.excludeMatchers = compileMatchers(userOpts.exclude)\n }\n if (userOpts?.ignoreImporters) {\n config.ignoreImporterMatchers = compileMatchers(\n userOpts.ignoreImporters,\n )\n }\n\n // Marker specifiers\n const markers = getMarkerSpecifiers()\n config.markerSpecifiers = {\n serverOnly: new Set(markers.serverOnly),\n clientOnly: new Set(markers.clientOnly),\n }\n },\n\n configureServer(server) {\n devServer = server\n },\n\n buildStart() {\n if (!config.enabled) return\n // Clear memoization caches that grow unboundedly across builds\n clearNormalizeFilePathCache()\n clearImportPatternCache()\n shouldCheckImporterCache.clear()\n\n // Clear per-env caches\n for (const envState of envStates.values()) {\n envState.resolveCache.clear()\n envState.resolveCacheByFile.clear()\n envState.importLocCache.clear()\n envState.seenViolations.clear()\n envState.transformResultCache.clear()\n envState.transformResultKeysByFile.clear()\n envState.postTransformImports.clear()\n envState.serverFnLookupModules.clear()\n envState.pendingViolations.clear()\n envState.deferredBuildViolations.length = 0\n envState.graph.clear()\n envState.deniedSources.clear()\n envState.deniedEdges.clear()\n envState.mockExportsByImporter.clear()\n }\n\n // Clear shared state\n shared.fileMarkerKind.clear()\n\n registerEntries()\n },\n\n hotUpdate(ctx) {\n if (!config.enabled) return\n // Invalidate caches for updated files\n for (const mod of ctx.modules) {\n if (mod.id) {\n const id = mod.id\n const importerFile = normalizeFilePath(id)\n shared.fileMarkerKind.delete(importerFile)\n\n // Invalidate per-env caches\n for (const envState of envStates.values()) {\n envState.importLocCache.deleteByFile(importerFile)\n\n // Invalidate resolve cache using reverse index\n const resolveKeys = envState.resolveCacheByFile.get(importerFile)\n if (resolveKeys) {\n for (const key of resolveKeys) {\n envState.resolveCache.delete(key)\n }\n envState.resolveCacheByFile.delete(importerFile)\n }\n\n // Invalidate graph edges\n envState.graph.invalidate(importerFile)\n envState.deniedEdges.delete(importerFile)\n envState.mockExportsByImporter.delete(importerFile)\n envState.serverFnLookupModules.delete(importerFile)\n envState.pendingViolations.delete(importerFile)\n\n // Invalidate transform result cache for this file.\n const transformKeys =\n envState.transformResultKeysByFile.get(importerFile)\n if (transformKeys) {\n for (const key of transformKeys) {\n envState.transformResultCache.delete(key)\n envState.postTransformImports.delete(key)\n }\n envState.transformResultKeysByFile.delete(importerFile)\n } else {\n // Fallback: at least clear the physical-file entry.\n envState.transformResultCache.delete(importerFile)\n envState.postTransformImports.delete(importerFile)\n }\n }\n }\n }\n },\n\n async resolveId(source, importer, _options) {\n const envName = this.environment.name\n const env = getEnv(envName)\n const envType = getEnvType(envName)\n const provider = env.transformResultProvider\n const isScanResolve = !!(_options as Record<string, unknown>).scan\n\n if (IMPORT_PROTECTION_DEBUG) {\n const importerPath = importer\n ? normalizeFilePath(importer)\n : '(entry)'\n const isEntryResolve = !importer\n const filtered =\n IMPORT_PROTECTION_DEBUG_FILTER === 'entry'\n ? isEntryResolve\n : matchesDebugFilter(source, importerPath)\n if (filtered) {\n debugLog('resolveId', {\n env: envName,\n envType,\n source,\n importer: importerPath,\n isEntryResolve,\n command: config.command,\n behavior: config.effectiveBehavior,\n })\n }\n }\n\n // Internal virtual modules\n const internalVirtualId = resolveInternalVirtualModuleId(source)\n if (internalVirtualId) return internalVirtualId\n\n if (!importer) {\n env.graph.addEntry(source)\n // Flush pending violations now that an additional entry is known\n // and reachability analysis may have new roots.\n await processPendingViolations(env, this.warn.bind(this))\n return undefined\n }\n\n if (source.startsWith('\\0') || source.startsWith('virtual:')) {\n return undefined\n }\n\n const normalizedImporter = normalizeFilePath(importer)\n const isDirectLookup = importer.includes(SERVER_FN_LOOKUP_QUERY)\n\n if (isDirectLookup) {\n env.serverFnLookupModules.add(normalizedImporter)\n }\n\n const isPreTransformResolve =\n isDirectLookup ||\n env.serverFnLookupModules.has(normalizedImporter) ||\n isScanResolve\n\n // Dev mock mode: defer violations until post-transform data is\n // available, then confirm/discard via graph reachability.\n // Build mode (both mock and error): defer violations until\n // generateBundle so tree-shaking can eliminate false positives.\n const isDevMock =\n config.command === 'serve' && config.effectiveBehavior === 'mock'\n const isBuild = config.command === 'build'\n\n const shouldDefer = (isDevMock && !isPreTransformResolve) || isBuild\n\n // Check if this is a marker import\n const markerKind = config.markerSpecifiers.serverOnly.has(source)\n ? ('server' as const)\n : config.markerSpecifiers.clientOnly.has(source)\n ? ('client' as const)\n : undefined\n\n if (markerKind) {\n const existing = shared.fileMarkerKind.get(normalizedImporter)\n if (existing && existing !== markerKind) {\n this.error(\n `[import-protection] File \"${getRelativePath(normalizedImporter)}\" has both server-only and client-only markers. This is not allowed.`,\n )\n }\n shared.fileMarkerKind.set(normalizedImporter, markerKind)\n\n const violatesEnv =\n (envType === 'client' && markerKind === 'server') ||\n (envType === 'server' && markerKind === 'client')\n\n if (violatesEnv) {\n const info = await buildViolationInfo(\n provider,\n env,\n envName,\n envType,\n importer,\n normalizedImporter,\n source,\n {\n type: 'marker',\n message:\n markerKind === 'server'\n ? `Module \"${getRelativePath(normalizedImporter)}\" is marked server-only but is imported in the client environment`\n : `Module \"${getRelativePath(normalizedImporter)}\" is marked client-only but is imported in the server environment`,\n },\n )\n const markerResult = await reportOrDeferViolation(\n this,\n env,\n normalizedImporter,\n info,\n shouldDefer,\n isPreTransformResolve,\n )\n\n // In build mode, if the violation was deferred, return the unique\n // build mock ID instead of the marker module. This lets\n // generateBundle check whether the importer (and thus its marker\n // import) survived tree-shaking. The mock is side-effect-free just\n // like the marker module, and the bare import has no bindings, so\n // replacing it is transparent.\n if (isBuild && markerResult != null) {\n return markerResult\n }\n }\n\n return markerKind === 'server'\n ? resolvedMarkerVirtualModuleId('server')\n : resolvedMarkerVirtualModuleId('client')\n }\n\n // Check if the importer is within our scope\n if (!shouldCheckImporter(normalizedImporter)) {\n return undefined\n }\n\n const matchers = getRulesForEnvironment(envName)\n\n // 1. Specifier-based denial\n const specifierMatch = matchesAny(source, matchers.specifiers)\n if (specifierMatch) {\n env.graph.addEdge(source, normalizedImporter, source)\n const info = await buildViolationInfo(\n provider,\n env,\n envName,\n envType,\n importer,\n normalizedImporter,\n source,\n {\n type: 'specifier',\n pattern: specifierMatch.pattern,\n message: `Import \"${source}\" is denied in the ${envType} environment`,\n },\n )\n return reportOrDeferViolation(\n this,\n env,\n normalizedImporter,\n info,\n shouldDefer,\n isPreTransformResolve,\n )\n }\n\n // 2. Resolve the import (cached)\n const cacheKey = `${normalizedImporter}:${source}`\n let resolved: string | null\n\n if (env.resolveCache.has(cacheKey)) {\n resolved = env.resolveCache.get(cacheKey) ?? null\n } else {\n const result = await this.resolve(source, importer, {\n skipSelf: true,\n })\n resolved = result ? normalizeFilePath(result.id) : null\n env.resolveCache.set(cacheKey, resolved)\n getOrCreate(\n env.resolveCacheByFile,\n normalizedImporter,\n () => new Set(),\n ).add(cacheKey)\n }\n\n if (resolved) {\n const relativePath = getRelativePath(resolved)\n\n // Propagate pre-transform status transitively\n if (isPreTransformResolve && !isScanResolve) {\n env.serverFnLookupModules.add(resolved)\n }\n\n env.graph.addEdge(resolved, normalizedImporter, source)\n\n // Skip file-based and marker-based denial for resolved paths that\n // match the per-environment `excludeFiles` patterns. By default\n // this includes `**/node_modules/**` so that third-party packages\n // using `.client.` / `.server.` in their filenames (e.g. react-tweet\n // exports `index.client.js`) are not treated as user-authored\n // environment boundaries. Users can override `excludeFiles` per\n // environment to narrow or widen this exclusion.\n const isExcludedFile =\n matchers.excludeFiles.length > 0 &&\n matchesAny(relativePath, matchers.excludeFiles)\n\n if (!isExcludedFile) {\n const fileMatch =\n matchers.files.length > 0\n ? matchesAny(relativePath, matchers.files)\n : undefined\n\n if (fileMatch) {\n const info = await buildViolationInfo(\n provider,\n env,\n envName,\n envType,\n importer,\n normalizedImporter,\n source,\n {\n type: 'file',\n pattern: fileMatch.pattern,\n resolved,\n message: `Import \"${source}\" (resolved to \"${relativePath}\") is denied in the ${envType} environment`,\n },\n )\n return reportOrDeferViolation(\n this,\n env,\n normalizedImporter,\n info,\n shouldDefer,\n isPreTransformResolve,\n )\n }\n\n const markerInfo = await buildMarkerViolationFromResolvedImport(\n provider,\n env,\n envName,\n envType,\n importer,\n source,\n resolved,\n relativePath,\n )\n if (markerInfo) {\n return reportOrDeferViolation(\n this,\n env,\n normalizedImporter,\n markerInfo,\n shouldDefer,\n isPreTransformResolve,\n )\n }\n }\n }\n\n return undefined\n },\n\n load: {\n filter: {\n id: new RegExp(\n getResolvedVirtualModuleMatchers().map(escapeRegExp).join('|'),\n ),\n },\n handler(id) {\n if (IMPORT_PROTECTION_DEBUG) {\n if (matchesDebugFilter(id)) {\n debugLog('load:handler', {\n env: this.environment.name,\n id: normalizePath(id),\n })\n }\n }\n\n return loadResolvedVirtualModule(id)\n },\n },\n\n async generateBundle(_options, bundle) {\n const envName = this.environment.name\n const env = envStates.get(envName)\n if (!env || env.deferredBuildViolations.length === 0) return\n\n // Collect all module IDs that survived tree-shaking in this bundle.\n const survivingModules = new Set<string>()\n for (const chunk of Object.values(bundle)) {\n if (chunk.type === 'chunk') {\n for (const moduleId of Object.keys(chunk.modules)) {\n survivingModules.add(moduleId)\n }\n }\n }\n\n // Check each deferred violation: if its check module survived\n // in the bundle, the import was NOT tree-shaken — real leak.\n const realViolations: Array<ViolationInfo> = []\n for (const {\n info,\n mockModuleId,\n checkModuleId,\n } of env.deferredBuildViolations) {\n const checkId = checkModuleId ?? mockModuleId\n if (!survivingModules.has(checkId)) continue\n\n if (config.onViolation) {\n const result = await config.onViolation(info)\n if (result === false) continue\n }\n\n realViolations.push(info)\n }\n\n if (realViolations.length === 0) return\n\n if (config.effectiveBehavior === 'error') {\n // Error mode: fail the build on the first real violation.\n this.error(formatViolation(realViolations[0]!, config.root))\n } else {\n // Mock mode: warn for each surviving violation.\n const seen = new Set<string>()\n for (const info of realViolations) {\n const key = dedupeKey(\n info.type,\n info.importer,\n info.specifier,\n info.resolved,\n )\n if (!seen.has(key)) {\n seen.add(key)\n this.warn(formatViolation(info, config.root))\n }\n }\n }\n },\n },\n {\n // Captures transformed code + composed sourcemap for location mapping.\n // Runs after all `enforce: 'pre'` hooks (including the Start compiler).\n // Only files under `srcDirectory` are cached.\n name: 'tanstack-start-core:import-protection-transform-cache',\n\n applyToEnvironment(env) {\n if (!config.enabled) return false\n return environmentNames.has(env.name)\n },\n\n transform: {\n filter: {\n id: {\n include: [/\\.[cm]?[tj]sx?($|\\?)/],\n },\n },\n async handler(code, id) {\n const envName = this.environment.name\n const file = normalizeFilePath(id)\n\n if (IMPORT_PROTECTION_DEBUG) {\n if (matchesDebugFilter(file)) {\n debugLog('transform-cache', {\n env: envName,\n id: normalizePath(id),\n file,\n })\n }\n }\n\n if (!shouldCheckImporter(file)) {\n return undefined\n }\n\n // getCombinedSourcemap() returns the composed sourcemap\n let map: SourceMapLike | undefined\n try {\n map = this.getCombinedSourcemap()\n } catch {\n map = undefined\n }\n\n let originalCode: string | undefined\n if (map?.sourcesContent) {\n originalCode = pickOriginalCodeFromSourcesContent(\n map,\n file,\n config.root,\n )\n }\n\n const lineIndex = buildLineIndex(code)\n const cacheKey = normalizePath(id)\n\n const envState = getEnv(envName)\n\n // Propagate SERVER_FN_LOOKUP status before import-analysis\n if (id.includes(SERVER_FN_LOOKUP_QUERY)) {\n envState.serverFnLookupModules.add(file)\n }\n\n envState.transformResultCache.set(cacheKey, {\n code,\n map,\n originalCode,\n lineIndex,\n })\n\n const keySet = getOrCreate(\n envState.transformResultKeysByFile,\n file,\n () => new Set<string>(),\n )\n keySet.add(cacheKey)\n\n // Also store stripped-path entry for physical-file lookups.\n if (cacheKey !== file) {\n envState.transformResultCache.set(file, {\n code,\n map,\n originalCode,\n lineIndex,\n })\n keySet.add(file)\n }\n\n // Resolve import sources to canonical paths for reachability checks.\n const importSources = extractImportSources(code)\n const resolvedChildren = new Set<string>()\n for (const src of importSources) {\n try {\n const resolved = await this.resolve(src, id, { skipSelf: true })\n if (resolved && !resolved.external) {\n const resolvedPath = normalizeFilePath(resolved.id)\n resolvedChildren.add(resolvedPath)\n // Populate import graph edges for warm-start trace accuracy\n envState.graph.addEdge(resolvedPath, file, src)\n }\n } catch {\n // Non-fatal\n }\n }\n envState.postTransformImports.set(cacheKey, resolvedChildren)\n if (cacheKey !== file) {\n envState.postTransformImports.set(file, resolvedChildren)\n }\n\n await processPendingViolations(envState, this.warn.bind(this))\n\n return undefined\n },\n },\n },\n {\n // Separate plugin so the transform can be enabled/disabled per-environment.\n name: 'tanstack-start-core:import-protection-mock-rewrite',\n enforce: 'pre',\n\n applyToEnvironment(env) {\n if (!config.enabled) return false\n // We record expected named exports per importer so mock-edge modules\n // can provide explicit ESM named exports. This is needed in both dev\n // and build: native ESM (dev) requires real named exports, and\n // Rolldown (used in Vite 6+) doesn't support Rollup's\n // syntheticNamedExports flag which was previously relied upon in build.\n //\n // In build+error mode we still emit mock modules for deferred\n // violations (checked at generateBundle time), so we always need the\n // export name data when import protection is active.\n return environmentNames.has(env.name)\n },\n\n transform: {\n filter: {\n id: {\n include: [/\\.[cm]?[tj]sx?($|\\?)/],\n },\n },\n handler(code, id) {\n const envName = this.environment.name\n const envState = envStates.get(envName)\n if (!envState) return undefined\n\n // Record export names per source for this importer so we can generate\n // dev mock-edge modules without any disk reads.\n try {\n const importerFile = normalizeFilePath(id)\n envState.mockExportsByImporter.set(\n importerFile,\n collectMockExportNamesBySource(code),\n )\n } catch {\n // Best-effort only\n }\n\n // Note: we no longer rewrite imports here.\n // Dev uses per-importer mock-edge modules in resolveId so native ESM\n // has explicit named exports, and runtime diagnostics are handled by\n // the mock runtime proxy when those mocks are actually invoked.\n return undefined\n },\n },\n },\n ] satisfies Array<PluginOption>\n}\n"],"names":["importerFile","exports"],"mappings":";;;;;;;;;;;;AAuDA,MAAM,yBAAyB,MAAM;AACrC,MAAM,0BACJ,QAAQ,IAAI,gCAAgC,OAC5C,QAAQ,IAAI,gCAAgC;AAC9C,MAAM,iCACJ,QAAQ,IAAI;AAEd,SAAS,YAAY,MAAsB;AACzC,MAAI,CAAC,wBAAyB;AAC9B,UAAQ,KAAK,6BAA6B,GAAG,IAAI;AACnD;AAGA,SAAS,sBAAsB,QAAgC;AAC7D,MAAI,CAAC,+BAAgC,QAAO;AAC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,CAAC,SAAU,QAAO;AAItB,cAAI;AACF,kBAAM,eAAe,kBAAkB,EAAE;AACzC,qBAAS,sBAAsB;AAAA,cAC7B;AAAA,cACA,+BAA+B,IAAI;AAAA,YAAA;AAAA,UAEvC,QAAQ;AAAA,UAER;AAMA,iBAAO;AAAA,QACT;AAAA,MAAA;AAAA,IACF;AAAA,EACF;AAEJ;"}
1
+ {"version":3,"file":"plugin.js","sources":["../../../src/import-protection-plugin/plugin.ts"],"sourcesContent":["import { normalizePath } from 'vite'\n\nimport { resolveViteId } from '../utils'\nimport { VITE_ENVIRONMENT_NAMES } from '../constants'\nimport { ImportGraph, buildTrace, formatViolation } from './trace'\nimport {\n getDefaultImportProtectionRules,\n getMarkerSpecifiers,\n} from './defaults'\nimport { compileMatchers, matchesAny } from './matchers'\nimport {\n buildResolutionCandidates,\n buildSourceCandidates,\n canonicalizeResolvedId,\n clearNormalizeFilePathCache,\n debugLog,\n dedupePatterns,\n escapeRegExp,\n extractImportSources,\n getOrCreate,\n isInsideDirectory,\n matchesDebugFilter,\n normalizeFilePath,\n relativizePath,\n shouldDeferViolation,\n} from './utils'\nimport {\n collectMockExportNamesBySource,\n collectNamedExports,\n rewriteDeniedImports,\n} from './rewriteDeniedImports'\nimport {\n MOCK_BUILD_PREFIX,\n generateDevSelfDenialModule,\n generateSelfContainedMockModule,\n getResolvedVirtualModuleMatchers,\n loadResolvedVirtualModule,\n makeMockEdgeModuleId,\n mockRuntimeModuleIdFromViolation,\n resolveInternalVirtualModuleId,\n resolvedMarkerVirtualModuleId,\n} from './virtualModules'\nimport { ExtensionlessAbsoluteIdResolver } from './extensionlessAbsoluteIdResolver'\nimport {\n IMPORT_PROTECTION_DEBUG,\n SERVER_FN_LOOKUP_QUERY,\n VITE_BROWSER_VIRTUAL_PREFIX,\n} from './constants'\nimport {\n ImportLocCache,\n addTraceImportLocations,\n buildCodeSnippet,\n buildLineIndex,\n findImportStatementLocationFromTransformed,\n findPostCompileUsageLocation,\n pickOriginalCodeFromSourcesContent,\n} from './sourceLocation'\nimport type { PluginOption, ViteDevServer } from 'vite'\nimport type { CompiledMatcher } from './matchers'\nimport type { Loc, TraceStep, ViolationInfo } from './trace'\nimport type {\n SourceMapLike,\n TransformResult,\n TransformResultProvider,\n} from './sourceLocation'\nimport type { ImportProtectionOptions } from '../schema'\nimport type {\n EnvRules,\n EnvState,\n HandleViolationResult,\n ImportProtectionPluginOptions,\n ModuleGraphNode,\n PendingViolation,\n PluginConfig,\n SharedState,\n ViolationReporter,\n} from './types'\n\nexport type { ImportProtectionPluginOptions } from './types'\n\nexport function importProtectionPlugin(\n opts: ImportProtectionPluginOptions,\n): PluginOption {\n let devServer: ViteDevServer | null = null\n const extensionlessIdResolver = new ExtensionlessAbsoluteIdResolver()\n const resolveExtensionlessAbsoluteId = (id: string) =>\n extensionlessIdResolver.resolve(id)\n\n const importPatternCache = new Map<string, Array<RegExp>>()\n\n function findFirstImportSpecifierIndex(code: string, source: string): number {\n let patterns = importPatternCache.get(source)\n if (!patterns) {\n const escaped = escapeRegExp(source)\n patterns = [\n new RegExp(`\\\\bimport\\\\s+(['\"])${escaped}\\\\1`),\n new RegExp(`\\\\bfrom\\\\s+(['\"])${escaped}\\\\1`),\n new RegExp(`\\\\bimport\\\\s*\\\\(\\\\s*(['\"])${escaped}\\\\1\\\\s*\\\\)`),\n ]\n importPatternCache.set(source, patterns)\n }\n\n let best = -1\n for (const re of patterns) {\n const m = re.exec(code)\n if (!m) continue\n const idx = m.index + m[0].indexOf(source)\n if (idx === -1) continue\n if (best === -1 || idx < best) best = idx\n }\n return best\n }\n\n /**\n * Build an import trace using Vite's per-environment module graph, which\n * is authoritative even on warm starts when the plugin's own ImportGraph\n * may be incomplete (Vite skips resolveId for cached modules).\n */\n function buildTraceFromModuleGraph(\n envName: string,\n env: EnvState,\n targetFile: string,\n ): Array<TraceStep> | null {\n if (!devServer) return null\n const environment = devServer.environments[envName]\n if (!environment) return null\n\n const file = normalizeFilePath(targetFile)\n const start = environment.moduleGraph.getModuleById(file)\n if (!start) return null\n\n // Resolve a module graph node to its normalized file path once and\n // cache the result so BFS + reconstruction don't recompute.\n const nodeIds = new Map<ModuleGraphNode, string>()\n function nodeId(n: ModuleGraphNode): string {\n let cached = nodeIds.get(n)\n if (cached === undefined) {\n cached = n.id\n ? normalizeFilePath(n.id)\n : n.url\n ? normalizeFilePath(n.url)\n : ''\n nodeIds.set(n, cached)\n }\n return cached\n }\n\n const queue: Array<ModuleGraphNode> = [start]\n const visited = new Set<ModuleGraphNode>([start])\n const parent = new Map<ModuleGraphNode, ModuleGraphNode>()\n\n let entryRoot: ModuleGraphNode | null = null\n let fallbackRoot: ModuleGraphNode | null = null\n let qi = 0\n while (qi < queue.length) {\n const node = queue[qi++]!\n const id = nodeId(node)\n\n if (id && env.graph.entries.has(id)) {\n entryRoot = node\n break\n }\n\n const importers = node.importers\n if (importers.size === 0) {\n if (!fallbackRoot) fallbackRoot = node\n continue\n }\n\n for (const imp of importers) {\n if (visited.has(imp)) continue\n visited.add(imp)\n parent.set(imp, node)\n queue.push(imp)\n }\n }\n\n const root = entryRoot ?? fallbackRoot\n\n if (!root) return null\n\n // Reconstruct: root -> ... -> start\n const chain: Array<ModuleGraphNode> = []\n let cur: ModuleGraphNode | undefined = root\n for (let i = 0; i < config.maxTraceDepth + 2 && cur; i++) {\n chain.push(cur)\n if (cur === start) break\n cur = parent.get(cur)\n }\n\n const steps: Array<TraceStep> = []\n for (let i = 0; i < chain.length; i++) {\n const id = nodeId(chain[i]!)\n if (!id) continue\n let specifier: string | undefined\n if (i + 1 < chain.length) {\n const nextId = nodeId(chain[i + 1]!)\n if (nextId) {\n specifier = env.graph.reverseEdges.get(nextId)?.get(id)\n }\n }\n steps.push(specifier ? { file: id, specifier } : { file: id })\n }\n\n return steps.length ? steps : null\n }\n\n const config: PluginConfig = {\n enabled: true,\n root: '',\n command: 'build',\n srcDirectory: '',\n framework: opts.framework,\n effectiveBehavior: 'error',\n mockAccess: 'error',\n logMode: 'once',\n maxTraceDepth: 20,\n compiledRules: {\n client: { specifiers: [], files: [], excludeFiles: [] },\n server: { specifiers: [], files: [], excludeFiles: [] },\n },\n includeMatchers: [],\n excludeMatchers: [],\n ignoreImporterMatchers: [],\n markerSpecifiers: { serverOnly: new Set(), clientOnly: new Set() },\n envTypeMap: new Map(opts.environments.map((e) => [e.name, e.type])),\n onViolation: undefined,\n }\n\n const envStates = new Map<string, EnvState>()\n const shared: SharedState = { fileMarkerKind: new Map() }\n\n /**\n * Build the best available trace for a module and enrich each step with\n * line/column locations. Tries the plugin's own ImportGraph first, then\n * Vite's moduleGraph (authoritative on warm start), keeping whichever is\n * longer. Annotates the last step with the denied specifier + location.\n *\n * Shared by {@link buildViolationInfo} and {@link processPendingViolations}.\n */\n async function rebuildAndAnnotateTrace(\n provider: TransformResultProvider,\n env: EnvState,\n envName: string,\n normalizedImporter: string,\n specifier: string,\n importerLoc: Loc | undefined,\n traceOverride?: Array<TraceStep>,\n ): Promise<Array<TraceStep>> {\n let trace =\n traceOverride ??\n buildTrace(env.graph, normalizedImporter, config.maxTraceDepth)\n\n if (config.command === 'serve') {\n const mgTrace = buildTraceFromModuleGraph(\n envName,\n env,\n normalizedImporter,\n )\n if (mgTrace && mgTrace.length > trace.length) {\n trace = mgTrace\n }\n }\n await addTraceImportLocations(\n provider,\n trace,\n env.importLocCache,\n findFirstImportSpecifierIndex,\n )\n\n if (trace.length > 0) {\n const last = trace[trace.length - 1]!\n if (!last.specifier) last.specifier = specifier\n if (importerLoc && last.line == null) {\n last.line = importerLoc.line\n last.column = importerLoc.column\n }\n }\n\n return trace\n }\n\n /**\n * Build a complete {@link ViolationInfo} with trace, location, and snippet.\n *\n * This is the single path that all violation types go through: specifier,\n * file, and marker.\n */\n async function buildViolationInfo(\n provider: TransformResultProvider,\n env: EnvState,\n envName: string,\n envType: 'client' | 'server',\n importer: string,\n normalizedImporter: string,\n source: string,\n overrides: Omit<\n ViolationInfo,\n | 'env'\n | 'envType'\n | 'behavior'\n | 'specifier'\n | 'importer'\n | 'trace'\n | 'snippet'\n | 'importerLoc'\n >,\n traceOverride?: Array<TraceStep>,\n ): Promise<ViolationInfo> {\n const sourceCandidates = buildSourceCandidates(\n source,\n 'resolved' in overrides && typeof overrides.resolved === 'string'\n ? overrides.resolved\n : undefined,\n config.root,\n )\n\n const loc = await resolveImporterLocation(\n provider,\n env,\n importer,\n sourceCandidates,\n )\n\n const trace = await rebuildAndAnnotateTrace(\n provider,\n env,\n envName,\n normalizedImporter,\n source,\n loc,\n traceOverride,\n )\n\n const snippet = loc ? buildCodeSnippet(provider, importer, loc) : undefined\n\n return {\n env: envName,\n envType,\n behavior: config.effectiveBehavior,\n specifier: source,\n importer: normalizedImporter,\n ...(loc ? { importerLoc: loc } : {}),\n trace,\n snippet,\n ...overrides,\n }\n }\n\n async function resolveImporterLocation(\n provider: TransformResultProvider,\n env: EnvState,\n importer: string,\n sourceCandidates: Iterable<string>,\n ): Promise<Loc | undefined> {\n for (const candidate of sourceCandidates) {\n const loc =\n (await findPostCompileUsageLocation(provider, importer, candidate)) ||\n (await findImportStatementLocationFromTransformed(\n provider,\n importer,\n candidate,\n env.importLocCache,\n findFirstImportSpecifierIndex,\n ))\n if (loc) return loc\n }\n return undefined\n }\n\n /**\n * Check if a resolved import violates marker restrictions (e.g. importing\n * a server-only module in the client env). If so, build and return the\n * {@link ViolationInfo} — the caller is responsible for reporting/deferring.\n *\n * Returns `undefined` when the resolved import has no marker conflict.\n */\n async function buildMarkerViolationFromResolvedImport(\n provider: TransformResultProvider,\n env: EnvState,\n envName: string,\n envType: 'client' | 'server',\n importer: string,\n source: string,\n resolvedId: string,\n relativePath: string,\n traceOverride?: Array<TraceStep>,\n ): Promise<ViolationInfo | undefined> {\n const normalizedResolvedId = normalizeFilePath(resolvedId)\n const markerKind = shared.fileMarkerKind.get(normalizedResolvedId)\n const violates =\n (envType === 'client' && markerKind === 'server') ||\n (envType === 'server' && markerKind === 'client')\n if (!violates) return undefined\n\n const normalizedImporter = normalizeFilePath(importer)\n\n return buildViolationInfo(\n provider,\n env,\n envName,\n envType,\n importer,\n normalizedImporter,\n source,\n {\n type: 'marker',\n resolved: normalizedResolvedId,\n message: buildMarkerViolationMessage(relativePath, markerKind),\n },\n traceOverride,\n )\n }\n\n function buildMarkerViolationMessage(\n relativePath: string,\n markerKind: 'server' | 'client' | undefined,\n ): string {\n return markerKind === 'server'\n ? `Module \"${relativePath}\" is marked server-only but is imported in the client environment`\n : `Module \"${relativePath}\" is marked client-only but is imported in the server environment`\n }\n\n async function buildFileViolationInfo(\n provider: TransformResultProvider,\n env: EnvState,\n envName: string,\n envType: 'client' | 'server',\n importer: string,\n normalizedImporter: string,\n source: string,\n resolvedPath: string,\n pattern: string | RegExp,\n traceOverride?: Array<TraceStep>,\n ): Promise<ViolationInfo> {\n const relativePath = getRelativePath(resolvedPath)\n\n return buildViolationInfo(\n provider,\n env,\n envName,\n envType,\n importer,\n normalizedImporter,\n source,\n {\n type: 'file',\n pattern,\n resolved: resolvedPath,\n message: `Import \"${source}\" (resolved to \"${relativePath}\") is denied in the ${envType} environment`,\n },\n traceOverride,\n )\n }\n\n function getEnvType(envName: string): 'client' | 'server' {\n return config.envTypeMap.get(envName) ?? 'server'\n }\n\n function getRulesForEnvironment(envName: string): EnvRules {\n const type = getEnvType(envName)\n return type === 'client'\n ? config.compiledRules.client\n : config.compiledRules.server\n }\n\n /**\n * Check if a relative path matches any denied file pattern for the given\n * environment, respecting `excludeFiles`. Returns the matching pattern\n * or `undefined` if the file is not denied.\n */\n function checkFileDenial(\n relativePath: string,\n matchers: {\n files: Array<CompiledMatcher>\n excludeFiles: Array<CompiledMatcher>\n },\n ): CompiledMatcher | undefined {\n if (\n matchers.excludeFiles.length > 0 &&\n matchesAny(relativePath, matchers.excludeFiles)\n ) {\n return undefined\n }\n return matchers.files.length > 0\n ? matchesAny(relativePath, matchers.files)\n : undefined\n }\n\n const environmentNames = new Set<string>([\n VITE_ENVIRONMENT_NAMES.client,\n VITE_ENVIRONMENT_NAMES.server,\n ])\n if (opts.providerEnvName !== VITE_ENVIRONMENT_NAMES.server) {\n environmentNames.add(opts.providerEnvName)\n }\n\n /** Get (or lazily create) the per-env state for the given environment name. */\n function getEnv(envName: string): EnvState {\n let envState = envStates.get(envName)\n if (!envState) {\n const transformResultCache = new Map<string, TransformResult>()\n envState = {\n graph: new ImportGraph(),\n mockExportsByImporter: new Map(),\n resolveCache: new Map(),\n resolveCacheByFile: new Map(),\n importLocCache: new ImportLocCache(),\n seenViolations: new Set(),\n transformResultCache,\n transformResultKeysByFile: new Map(),\n transformResultProvider: {\n getTransformResult(id: string) {\n const fullKey = normalizePath(id)\n const exact = transformResultCache.get(fullKey)\n if (exact) return exact\n const strippedKey = normalizeFilePath(id)\n return strippedKey !== fullKey\n ? transformResultCache.get(strippedKey)\n : undefined\n },\n },\n postTransformImports: new Map(),\n serverFnLookupModules: new Set(),\n pendingViolations: new Map(),\n deferredBuildViolations: [],\n }\n envStates.set(envName, envState)\n }\n return envState\n }\n\n /**\n * Search a parsed export-names map for an entry matching any of the\n * specifier candidates. Returns matching names or empty array.\n */\n function findExportsInMap(\n exportMap: Map<string, Array<string>>,\n candidates: Array<string>,\n ): Array<string> {\n for (const candidate of candidates) {\n const hit = exportMap.get(candidate)\n if (hit && hit.length > 0) return hit\n }\n return []\n }\n\n /**\n * Build deduped resolution candidates for a module ID, including the\n * extensionless absolute path when the ID looks like a file path.\n */\n function buildIdCandidates(id: string, extra?: string): Array<string> {\n const set = new Set(buildResolutionCandidates(id))\n if (extra) {\n for (const c of buildResolutionCandidates(extra)) set.add(c)\n set.add(resolveExtensionlessAbsoluteId(extra))\n }\n return Array.from(set)\n }\n\n /**\n * Resolve which named exports the importer needs from a denied specifier,\n * so mock-edge modules can provide explicit ESM named exports.\n *\n * Tries multiple strategies: cached export maps, AST parsing, and\n * resolver-based comparison.\n */\n async function resolveExportsForDeniedSpecifier(\n env: EnvState,\n ctx: ViolationReporter,\n info: ViolationInfo,\n importerIdHint?: string,\n ): Promise<Array<string>> {\n const importerFile = normalizeFilePath(info.importer)\n const specifierCandidates = buildIdCandidates(info.specifier, info.resolved)\n\n // Only parse AST when a violation occurs (this function is only called\n // while handling a violation). Cache per-importer to avoid repeated parses\n // across multiple violations.\n let parsedBySource = env.mockExportsByImporter.get(importerFile)\n if (!parsedBySource) {\n // Try transform-cache result first, then moduleInfo fallback.\n const importerCode =\n env.transformResultProvider.getTransformResult(importerFile)?.code ??\n (importerIdHint && ctx.getModuleInfo\n ? (ctx.getModuleInfo(importerIdHint)?.code ?? undefined)\n : undefined)\n if (typeof importerCode !== 'string' || importerCode.length === 0)\n return []\n\n try {\n parsedBySource = collectMockExportNamesBySource(importerCode)\n\n // Also index by resolved physical IDs so later lookups match.\n await recordMockExportsForImporter(\n env,\n importerFile,\n parsedBySource,\n async (src) => {\n const cacheKey = `${importerFile}:${src}`\n if (env.resolveCache.has(cacheKey)) {\n return env.resolveCache.get(cacheKey) ?? undefined\n }\n if (!ctx.resolve) return undefined\n const resolved = await ctx.resolve(src, info.importer, {\n skipSelf: true,\n })\n if (!resolved || resolved.external) return undefined\n return resolved.id\n },\n )\n\n // Keep the parsed-by-source map for direct lookups.\n parsedBySource =\n env.mockExportsByImporter.get(importerFile) ?? parsedBySource\n } catch {\n return []\n }\n }\n\n // 1. Direct candidate match\n const direct = findExportsInMap(parsedBySource, specifierCandidates)\n if (direct.length > 0) return direct\n\n // 2. Resolve each source key and compare candidates.\n const candidateSet = new Set(specifierCandidates)\n for (const [sourceKey, names] of parsedBySource) {\n if (!names.length) continue\n\n const resolvedId = await resolveSourceKey(\n env,\n ctx,\n importerFile,\n sourceKey,\n info.importer,\n )\n if (!resolvedId) continue\n\n const resolvedCandidates = buildIdCandidates(resolvedId)\n resolvedCandidates.push(resolveExtensionlessAbsoluteId(resolvedId))\n if (resolvedCandidates.some((v) => candidateSet.has(v))) {\n return names\n }\n }\n\n return []\n }\n\n /** Best-effort resolve a source key using the cache or ctx.resolve. */\n async function resolveSourceKey(\n env: EnvState,\n ctx: ViolationReporter,\n importerFile: string,\n sourceKey: string,\n importerId: string,\n ): Promise<string | undefined> {\n const cacheKey = `${importerFile}:${sourceKey}`\n if (env.resolveCache.has(cacheKey)) {\n return env.resolveCache.get(cacheKey) ?? undefined\n }\n if (!ctx.resolve) return undefined\n try {\n const resolved = await ctx.resolve(sourceKey, importerId, {\n skipSelf: true,\n })\n if (!resolved || resolved.external) return undefined\n return resolved.id\n } catch {\n return undefined\n }\n }\n\n async function recordMockExportsForImporter(\n env: EnvState,\n importerId: string,\n namesBySource: Map<string, Array<string>>,\n resolveSource: (source: string) => Promise<string | undefined>,\n ): Promise<void> {\n const importerFile = normalizeFilePath(importerId)\n\n if (namesBySource.size === 0) return\n\n for (const [source, names] of namesBySource) {\n try {\n const resolvedId = await resolveSource(source)\n if (!resolvedId) continue\n\n namesBySource.set(normalizeFilePath(resolvedId), names)\n namesBySource.set(resolveExtensionlessAbsoluteId(resolvedId), names)\n } catch {\n // Best-effort only\n }\n }\n\n const existing = env.mockExportsByImporter.get(importerFile)\n if (!existing) {\n env.mockExportsByImporter.set(importerFile, namesBySource)\n return\n }\n\n for (const [source, names] of namesBySource) {\n const prev = existing.get(source)\n if (!prev) {\n existing.set(source, names)\n continue\n }\n\n const union = new Set([...prev, ...names])\n existing.set(source, Array.from(union).sort())\n }\n }\n\n const shouldCheckImporterCache = new Map<string, boolean>()\n function shouldCheckImporter(importer: string): boolean {\n let result = shouldCheckImporterCache.get(importer)\n if (result !== undefined) return result\n\n const relativePath = relativizePath(importer, config.root)\n\n // Excluded or ignored importers are never checked.\n const excluded =\n (config.excludeMatchers.length > 0 &&\n matchesAny(relativePath, config.excludeMatchers)) ||\n (config.ignoreImporterMatchers.length > 0 &&\n matchesAny(relativePath, config.ignoreImporterMatchers))\n\n if (excluded) {\n result = false\n } else if (config.includeMatchers.length > 0) {\n result = !!matchesAny(relativePath, config.includeMatchers)\n } else if (config.srcDirectory) {\n result = isInsideDirectory(importer, config.srcDirectory)\n } else {\n result = true\n }\n\n shouldCheckImporterCache.set(importer, result)\n return result\n }\n\n function dedupeKey(info: ViolationInfo): string {\n return `${info.type}:${info.importer}:${info.specifier}:${info.resolved ?? ''}`\n }\n\n function hasSeen(env: EnvState, key: string): boolean {\n if (config.logMode === 'always') return false\n if (env.seenViolations.has(key)) return true\n env.seenViolations.add(key)\n return false\n }\n\n function getRelativePath(absolutePath: string): string {\n return relativizePath(normalizePath(absolutePath), config.root)\n }\n\n /** Reset all caches on an EnvState (called from buildStart). */\n function clearEnvState(envState: EnvState): void {\n envState.resolveCache.clear()\n envState.resolveCacheByFile.clear()\n envState.importLocCache.clear()\n envState.seenViolations.clear()\n envState.transformResultCache.clear()\n envState.transformResultKeysByFile.clear()\n envState.postTransformImports.clear()\n envState.serverFnLookupModules.clear()\n envState.pendingViolations.clear()\n envState.deferredBuildViolations.length = 0\n envState.graph.clear()\n envState.mockExportsByImporter.clear()\n }\n\n /** Invalidate all env-level caches that reference a specific file. */\n function invalidateFileFromEnv(envState: EnvState, file: string): void {\n envState.importLocCache.deleteByFile(file)\n\n // Resolve cache (keyed \"importer:source\")\n const resolveKeys = envState.resolveCacheByFile.get(file)\n if (resolveKeys) {\n for (const key of resolveKeys) envState.resolveCache.delete(key)\n envState.resolveCacheByFile.delete(file)\n }\n\n envState.graph.invalidate(file)\n envState.mockExportsByImporter.delete(file)\n envState.serverFnLookupModules.delete(file)\n envState.pendingViolations.delete(file)\n\n // Transform result cache + post-transform imports\n const transformKeys = envState.transformResultKeysByFile.get(file)\n if (transformKeys) {\n for (const key of transformKeys) {\n envState.transformResultCache.delete(key)\n envState.postTransformImports.delete(key)\n }\n envState.transformResultKeysByFile.delete(file)\n } else {\n envState.transformResultCache.delete(file)\n envState.postTransformImports.delete(file)\n }\n }\n\n /** Store a transform result under both the cacheKey and physical file path. */\n function cacheTransformResult(\n envState: EnvState,\n file: string,\n cacheKey: string,\n result: TransformResult,\n ): void {\n envState.transformResultCache.set(cacheKey, result)\n const keySet = getOrCreate(\n envState.transformResultKeysByFile,\n file,\n () => new Set<string>(),\n )\n keySet.add(cacheKey)\n if (cacheKey !== file) {\n envState.transformResultCache.set(file, result)\n keySet.add(file)\n }\n }\n\n /** Register known Start entrypoints as trace roots for all environments. */\n function registerEntries(): void {\n const { resolvedStartConfig } = opts.getConfig()\n for (const envDef of opts.environments) {\n const envState = getEnv(envDef.name)\n if (resolvedStartConfig.routerFilePath) {\n envState.graph.addEntry(\n normalizePath(resolvedStartConfig.routerFilePath),\n )\n }\n if (resolvedStartConfig.startFilePath) {\n envState.graph.addEntry(\n normalizePath(resolvedStartConfig.startFilePath),\n )\n }\n }\n }\n\n /**\n * Get the merged set of post-transform imports for a file, checking all\n * code-split variants. Returns `null` if no post-transform data exists\n * yet (transform hasn't run).\n *\n * Skips `SERVER_FN_LOOKUP` variants because they contain untransformed\n * code — the Start compiler excludes them.\n */\n function getPostTransformImports(\n env: EnvState,\n file: string,\n ): Set<string> | null {\n const keySet = env.transformResultKeysByFile.get(file)\n let merged: Set<string> | null = null\n\n if (keySet) {\n for (const k of keySet) {\n if (k.includes(SERVER_FN_LOOKUP_QUERY)) continue\n const imports = env.postTransformImports.get(k)\n if (imports) {\n if (!merged) merged = new Set(imports)\n else for (const v of imports) merged.add(v)\n }\n }\n }\n\n // Fallback: direct file-path key\n if (!merged) {\n const imports = env.postTransformImports.get(file)\n if (imports) merged = new Set(imports)\n }\n\n return merged\n }\n\n /**\n * Check whether an import edge from `parent` to `target` survived\n * post-transform compilation.\n *\n * Returns:\n * - `'live'` — target appears in a non-lookup variant's post-transform imports\n * - `'dead'` — post-transform data exists but target is absent (compiler stripped it)\n * - `'pending'` — transform ran but import data not yet posted\n * - `'no-data'` — transform never ran (warm-start cached module)\n */\n function checkEdgeLiveness(\n env: EnvState,\n parent: string,\n target: string,\n ): 'live' | 'dead' | 'pending' | 'no-data' {\n const keySet = env.transformResultKeysByFile.get(parent)\n let anyVariantCached = false\n\n if (keySet) {\n for (const k of keySet) {\n if (k.includes(SERVER_FN_LOOKUP_QUERY)) continue\n const imports = env.postTransformImports.get(k)\n if (imports) {\n anyVariantCached = true\n if (imports.has(target)) return 'live'\n }\n }\n }\n\n if (!anyVariantCached) {\n const imports = env.postTransformImports.get(parent)\n if (imports) return imports.has(target) ? 'live' : 'dead'\n const hasTransformResult =\n env.transformResultCache.has(parent) ||\n (keySet ? keySet.size > 0 : false)\n return hasTransformResult ? 'pending' : 'no-data'\n }\n\n return 'dead'\n }\n\n function checkPostTransformReachability(\n env: EnvState,\n file: string,\n ): 'reachable' | 'unreachable' | 'unknown' {\n const visited = new Set<string>()\n const queue: Array<string> = [file]\n let hasUnknownEdge = false\n let qi = 0\n\n while (qi < queue.length) {\n const current = queue[qi++]!\n if (visited.has(current)) continue\n visited.add(current)\n\n if (env.graph.entries.has(current)) {\n return 'reachable'\n }\n\n const importers = env.graph.reverseEdges.get(current)\n if (!importers) continue\n\n for (const [parent] of importers) {\n if (visited.has(parent)) continue\n const liveness = checkEdgeLiveness(env, parent, current)\n if (liveness === 'live' || liveness === 'no-data') {\n // Live edge or warm-start (no transform data) — follow it\n queue.push(parent)\n } else if (liveness === 'pending') {\n hasUnknownEdge = true\n }\n // 'dead' — edge was stripped by compiler, skip\n }\n }\n\n return hasUnknownEdge ? 'unknown' : 'unreachable'\n }\n\n /**\n * Filter pending violations using edge-survival data. Returns the subset\n * of violations whose resolved import survived the Start compiler (or all\n * violations when no post-transform data is available yet).\n *\n * Returns `undefined` when all violations were stripped or when we must wait\n * for post-transform data before proceeding.\n */\n function filterEdgeSurvival(\n env: EnvState,\n file: string,\n violations: Array<PendingViolation>,\n ):\n | { active: Array<PendingViolation>; edgeSurvivalApplied: boolean }\n | 'all-stripped'\n | 'await-transform' {\n const postTransform = getPostTransformImports(env, file)\n\n if (postTransform) {\n const surviving = violations.filter(\n (pv) => !pv.info.resolved || postTransform.has(pv.info.resolved),\n )\n if (surviving.length === 0) return 'all-stripped'\n env.pendingViolations.set(file, surviving)\n return { active: surviving, edgeSurvivalApplied: true }\n }\n\n // Pre-transform violations need edge-survival verification first.\n if (violations.some((pv) => pv.fromPreTransformResolve)) {\n return 'await-transform'\n }\n\n return { active: violations, edgeSurvivalApplied: false }\n }\n\n /**\n * Process pending violations for the given environment. Called from the\n * transform-cache hook after each module transform is cached, because new\n * transform data may allow us to confirm or discard pending violations.\n *\n * @param warnFn - `this.warn` from the transform hook context\n */\n async function processPendingViolations(\n env: EnvState,\n warnFn: (msg: string) => void,\n ): Promise<void> {\n if (env.pendingViolations.size === 0) return\n\n const toDelete: Array<string> = []\n\n for (const [file, violations] of env.pendingViolations) {\n const filtered = filterEdgeSurvival(env, file, violations)\n\n if (filtered === 'all-stripped') {\n toDelete.push(file)\n continue\n }\n if (filtered === 'await-transform') continue\n\n const { active, edgeSurvivalApplied } = filtered\n\n // Wait for entries before running reachability. registerEntries()\n // populates entries at buildStart; resolveId(!importer) may add more.\n const status =\n env.graph.entries.size > 0\n ? checkPostTransformReachability(env, file)\n : 'unknown'\n\n if (status === 'reachable') {\n for (const pv of active) {\n await emitPendingViolation(env, warnFn, pv)\n }\n toDelete.push(file)\n } else if (status === 'unreachable') {\n toDelete.push(file)\n } else if (config.command === 'serve') {\n // 'unknown' reachability — some graph edges lack transform data.\n // When edge-survival was applied, surviving violations are confirmed\n // real. Without it (warm start), emit conservatively.\n let emittedAny = false\n for (const pv of active) {\n if (pv.fromPreTransformResolve) continue\n\n const shouldEmit =\n edgeSurvivalApplied ||\n (pv.info.type === 'file' &&\n !!pv.info.resolved &&\n isInsideDirectory(pv.info.resolved, config.srcDirectory))\n\n if (shouldEmit) {\n emittedAny =\n (await emitPendingViolation(env, warnFn, pv)) || emittedAny\n }\n }\n\n if (emittedAny) {\n toDelete.push(file)\n }\n }\n // 'unknown' — keep pending for next transform-cache invocation.\n }\n\n for (const file of toDelete) {\n env.pendingViolations.delete(file)\n }\n }\n\n async function emitPendingViolation(\n env: EnvState,\n warnFn: (msg: string) => void,\n pv: PendingViolation,\n ): Promise<boolean> {\n if (!pv.info.importerLoc) {\n const sourceCandidates = buildSourceCandidates(\n pv.info.specifier,\n pv.info.resolved,\n config.root,\n )\n const loc = await resolveImporterLocation(\n env.transformResultProvider,\n env,\n pv.info.importer,\n sourceCandidates,\n )\n\n if (loc) {\n pv.info.importerLoc = loc\n pv.info.snippet = buildCodeSnippet(\n env.transformResultProvider,\n pv.info.importer,\n loc,\n )\n }\n }\n\n if (hasSeen(env, dedupeKey(pv.info))) {\n return false\n }\n\n const freshTrace = await rebuildAndAnnotateTrace(\n env.transformResultProvider,\n env,\n pv.info.env,\n pv.info.importer,\n pv.info.specifier,\n pv.info.importerLoc,\n )\n if (freshTrace.length > pv.info.trace.length) {\n pv.info.trace = freshTrace\n }\n\n if (config.onViolation) {\n const result = await config.onViolation(pv.info)\n if (result === false) return false\n }\n\n warnFn(formatViolation(pv.info, config.root))\n return true\n }\n\n /**\n * Record a violation as pending for later confirmation via graph\n * reachability. Called from `resolveId` when `shouldDefer` is true.\n */\n function deferViolation(\n env: EnvState,\n importerFile: string,\n info: ViolationInfo,\n isPreTransformResolve?: boolean,\n ): void {\n getOrCreate(env.pendingViolations, importerFile, () => []).push({\n info,\n fromPreTransformResolve: isPreTransformResolve,\n })\n }\n\n /** Counter for generating unique per-violation mock module IDs in build mode. */\n let buildViolationCounter = 0\n\n async function handleViolation(\n ctx: ViolationReporter,\n env: EnvState,\n info: ViolationInfo,\n importerIdHint?: string,\n violationOpts?: { silent?: boolean },\n ): Promise<HandleViolationResult> {\n if (!violationOpts?.silent) {\n if (config.onViolation) {\n const result = await config.onViolation(info)\n if (result === false) return undefined\n }\n\n if (config.effectiveBehavior === 'error') {\n // Dev+error: throw immediately.\n // Always throw on error — do NOT deduplicate via hasSeen().\n // Rollup may resolve the same specifier multiple times (e.g.\n // commonjs--resolver's nested this.resolve() fires before\n // getResolveStaticDependencyPromises). If we record the key\n // on the first (nested) throw, the second (real) resolve\n // silently returns undefined and the build succeeds — which\n // is the bug this fixes.\n //\n // Build mode never reaches here — all build violations are\n // deferred via shouldDefer and handled silently.\n return ctx.error(formatViolation(info, config.root))\n }\n\n if (!hasSeen(env, dedupeKey(info))) {\n ctx.warn(formatViolation(info, config.root))\n }\n } else if (\n config.effectiveBehavior === 'error' &&\n config.command !== 'build'\n ) {\n return undefined\n }\n\n // File violations: return resolved path — the self-denial transform\n // will replace the file's content with a mock module. This avoids\n // virtual module IDs that could leak across environments via\n // third-party resolver caches.\n if (info.type === 'file') return info.resolved\n\n // Non-file violations (specifier/marker): create mock-edge module.\n // Dev mode uses a runtime diagnostics ID; build mode uses a unique\n // per-violation ID so generateBundle can check tree-shaking survival.\n const exports = await resolveExportsForDeniedSpecifier(\n env,\n ctx,\n info,\n importerIdHint,\n )\n const baseMockId =\n config.command === 'serve'\n ? mockRuntimeModuleIdFromViolation(info, config.mockAccess, config.root)\n : `${MOCK_BUILD_PREFIX}${buildViolationCounter++}`\n return resolveViteId(makeMockEdgeModuleId(exports, baseMockId))\n }\n\n /**\n * Unified violation dispatch: either defers or reports immediately.\n *\n * When `shouldDefer` is true (dev mock + build modes), calls\n * `handleViolation` silently to obtain the mock module ID, then stores\n * the violation for later verification:\n * - Dev mock mode: all violations are deferred to `pendingViolations`\n * for edge-survival and graph-reachability checking via\n * `processPendingViolations`.\n * - Build mode (mock + error): defers to `deferredBuildViolations` for\n * tree-shaking verification in `generateBundle`.\n *\n * Otherwise reports immediately (dev error mode). Pre-transform\n * resolves are silenced in error mode because they fire before the\n * compiler runs and there is no deferred verification path.\n *\n * Returns the mock module ID / resolve result from `handleViolation`.\n */\n async function reportOrDeferViolation(\n ctx: ViolationReporter,\n env: EnvState,\n importerFile: string,\n importerIdHint: string | undefined,\n info: ViolationInfo,\n shouldDefer: boolean,\n isPreTransformResolve: boolean,\n ): Promise<HandleViolationResult> {\n if (shouldDefer) {\n const result = await handleViolation(ctx, env, info, importerIdHint, {\n silent: true,\n })\n\n if (config.command === 'build') {\n // Build mode: store for generateBundle tree-shaking check.\n // The mock-edge module ID is returned as a plain string.\n const mockId = result ?? ''\n env.deferredBuildViolations.push({\n info,\n mockModuleId: mockId,\n // For marker violations, check importer survival instead of mock.\n checkModuleId: info.type === 'marker' ? info.importer : undefined,\n })\n } else {\n // Dev mock: store for graph-reachability check.\n deferViolation(env, importerFile, info, isPreTransformResolve)\n await processPendingViolations(env, ctx.warn.bind(ctx))\n }\n\n return result\n }\n\n // Non-deferred path: dev error mode only.\n // Pre-transform resolves are silenced because they fire before the\n // compiler runs — imports inside `.server()` callbacks haven't been\n // stripped yet and error mode has no deferred verification.\n return handleViolation(ctx, env, info, importerIdHint, {\n silent: isPreTransformResolve,\n })\n }\n\n return [\n {\n name: 'tanstack-start-core:import-protection',\n enforce: 'pre',\n\n applyToEnvironment(env) {\n if (!config.enabled) return false\n // Start's environments are named `client` and `ssr` (not `server`), plus\n // an optional serverFn provider environment (eg `rsc`) when configured.\n return environmentNames.has(env.name)\n },\n\n configResolved(viteConfig) {\n config.root = viteConfig.root\n config.command = viteConfig.command\n\n const { startConfig, resolvedStartConfig } = opts.getConfig()\n config.srcDirectory = resolvedStartConfig.srcDirectory\n\n const userOpts: ImportProtectionOptions | undefined =\n startConfig.importProtection\n\n if (userOpts?.enabled === false) {\n config.enabled = false\n return\n }\n\n config.enabled = true\n\n const behavior = userOpts?.behavior\n if (typeof behavior === 'string') {\n config.effectiveBehavior = behavior\n } else {\n config.effectiveBehavior =\n viteConfig.command === 'serve'\n ? (behavior?.dev ?? 'mock')\n : (behavior?.build ?? 'error')\n }\n\n config.logMode = userOpts?.log ?? 'once'\n config.mockAccess = userOpts?.mockAccess ?? 'error'\n config.maxTraceDepth = userOpts?.maxTraceDepth ?? 20\n if (userOpts?.onViolation) {\n const fn = userOpts.onViolation\n config.onViolation = (info) => fn(info)\n }\n\n const defaults = getDefaultImportProtectionRules()\n // Use user-provided patterns when available, otherwise defaults.\n const pick = <T>(user: Array<T> | undefined, fallback: Array<T>) =>\n user ? [...user] : [...fallback]\n\n // Client specifier denies always include framework defaults even\n // when the user provides a custom list.\n const clientSpecifiers = dedupePatterns([\n ...defaults.client.specifiers,\n ...(userOpts?.client?.specifiers ?? []),\n ])\n\n config.compiledRules.client = {\n specifiers: compileMatchers(clientSpecifiers),\n files: compileMatchers(\n pick(userOpts?.client?.files, defaults.client.files),\n ),\n excludeFiles: compileMatchers(\n pick(userOpts?.client?.excludeFiles, defaults.client.excludeFiles),\n ),\n }\n config.compiledRules.server = {\n specifiers: compileMatchers(\n dedupePatterns(\n pick(userOpts?.server?.specifiers, defaults.server.specifiers),\n ),\n ),\n files: compileMatchers(\n pick(userOpts?.server?.files, defaults.server.files),\n ),\n excludeFiles: compileMatchers(\n pick(userOpts?.server?.excludeFiles, defaults.server.excludeFiles),\n ),\n }\n\n config.includeMatchers = compileMatchers(userOpts?.include ?? [])\n config.excludeMatchers = compileMatchers(userOpts?.exclude ?? [])\n config.ignoreImporterMatchers = compileMatchers(\n userOpts?.ignoreImporters ?? [],\n )\n\n // Marker specifiers\n const markers = getMarkerSpecifiers()\n config.markerSpecifiers = {\n serverOnly: new Set(markers.serverOnly),\n clientOnly: new Set(markers.clientOnly),\n }\n },\n\n configureServer(server) {\n devServer = server\n },\n\n buildStart() {\n if (!config.enabled) return\n // Clear memoization caches that grow unboundedly across builds\n clearNormalizeFilePathCache()\n extensionlessIdResolver.clear()\n importPatternCache.clear()\n shouldCheckImporterCache.clear()\n\n // Clear per-env caches\n for (const envState of envStates.values()) {\n clearEnvState(envState)\n }\n\n // Clear shared state\n shared.fileMarkerKind.clear()\n\n registerEntries()\n },\n\n hotUpdate(ctx) {\n if (!config.enabled) return\n // Invalidate caches for updated files\n for (const mod of ctx.modules) {\n if (mod.id) {\n const id = mod.id\n const importerFile = normalizeFilePath(id)\n\n // Invalidate extensionless-resolution cache entries affected by this file.\n extensionlessIdResolver.invalidateByFile(importerFile)\n shared.fileMarkerKind.delete(importerFile)\n\n // Invalidate per-env caches\n for (const envState of envStates.values()) {\n invalidateFileFromEnv(envState, importerFile)\n }\n }\n }\n },\n\n async resolveId(source, importer, _options) {\n const envName = this.environment.name\n const env = getEnv(envName)\n const envType = getEnvType(envName)\n const provider = env.transformResultProvider\n const isScanResolve = !!(_options as Record<string, unknown>).scan\n\n if (IMPORT_PROTECTION_DEBUG) {\n const importerPath = importer\n ? normalizeFilePath(importer)\n : '(entry)'\n const isEntryResolve = !importer\n const filtered =\n process.env.TSR_IMPORT_PROTECTION_DEBUG_FILTER === 'entry'\n ? isEntryResolve\n : matchesDebugFilter(source, importerPath)\n if (filtered) {\n debugLog('resolveId', {\n env: envName,\n envType,\n source,\n importer: importerPath,\n isEntryResolve,\n command: config.command,\n })\n }\n }\n\n // Internal virtual modules (mock:build:N, mock-edge, mock-runtime, marker)\n const internalVirtualId = resolveInternalVirtualModuleId(source)\n if (internalVirtualId) return internalVirtualId\n\n if (!importer) {\n env.graph.addEntry(source)\n // Flush pending violations now that an additional entry is known\n // and reachability analysis may have new roots.\n await processPendingViolations(env, this.warn.bind(this))\n return undefined\n }\n\n if (source.startsWith('\\0') || source.startsWith('virtual:')) {\n return undefined\n }\n\n const normalizedImporter = normalizeFilePath(importer)\n const isDirectLookup = importer.includes(SERVER_FN_LOOKUP_QUERY)\n\n if (isDirectLookup) {\n env.serverFnLookupModules.add(normalizedImporter)\n }\n\n const isPreTransformResolve =\n isDirectLookup ||\n env.serverFnLookupModules.has(normalizedImporter) ||\n isScanResolve\n\n // Dev mock mode: defer all violations (including pre-transform\n // resolves) until post-transform data is available, then\n // confirm/discard via graph reachability.\n // Build mode (both mock and error): defer violations until\n // generateBundle so tree-shaking can eliminate false positives.\n const isDevMock =\n config.command === 'serve' && config.effectiveBehavior === 'mock'\n const isBuild = config.command === 'build'\n const shouldDefer = shouldDeferViolation({ isBuild, isDevMock })\n\n const resolveAgainstImporter = async (): Promise<string | null> => {\n const primary = await this.resolve(source, importer, {\n skipSelf: true,\n })\n if (primary) {\n return canonicalizeResolvedId(\n primary.id,\n config.root,\n resolveExtensionlessAbsoluteId,\n )\n }\n\n return null\n }\n\n // Check if this is a marker import\n const markerKind = config.markerSpecifiers.serverOnly.has(source)\n ? ('server' as const)\n : config.markerSpecifiers.clientOnly.has(source)\n ? ('client' as const)\n : undefined\n\n if (markerKind) {\n const existing = shared.fileMarkerKind.get(normalizedImporter)\n if (existing && existing !== markerKind) {\n this.error(\n `[import-protection] File \"${getRelativePath(normalizedImporter)}\" has both server-only and client-only markers. This is not allowed.`,\n )\n }\n shared.fileMarkerKind.set(normalizedImporter, markerKind)\n\n const violatesEnv =\n (envType === 'client' && markerKind === 'server') ||\n (envType === 'server' && markerKind === 'client')\n\n if (violatesEnv) {\n const info = await buildViolationInfo(\n provider,\n env,\n envName,\n envType,\n importer,\n normalizedImporter,\n source,\n {\n type: 'marker',\n message: buildMarkerViolationMessage(\n getRelativePath(normalizedImporter),\n markerKind,\n ),\n },\n )\n const markerResult = await reportOrDeferViolation(\n this,\n env,\n normalizedImporter,\n importer,\n info,\n shouldDefer,\n isPreTransformResolve,\n )\n\n // In build mode, if the violation was deferred, return the unique\n // build mock ID instead of the marker module. This lets\n // generateBundle check whether the importer (and thus its marker\n // import) survived tree-shaking. The mock is side-effect-free just\n // like the marker module, and the bare import has no bindings, so\n // replacing it is transparent.\n if (isBuild && markerResult != null) {\n return markerResult\n }\n }\n\n // Retroactive marker violation detection: on cold starts, module\n // A may import module B before B's marker is set (because B hasn't\n // been processed yet). When B's marker is set (here),\n // retroactively check all known importers of B in the graph and\n // create deferred marker violations for them. Without this,\n // cold-start ordering can miss marker violations that warm starts\n // detect (warm starts see markers early from cached transforms).\n //\n // Uses lightweight `deferViolation` to avoid heavy side effects\n // (mock module creation, export resolution). Immediately calls\n // `processPendingViolations` to flush the deferred violations,\n // because the marker resolveId fires during Vite's import\n // analysis (after our transform hook) — there may be no\n // subsequent transform invocation to flush them.\n //\n // Guarded by `violatesEnv` (per-environment) plus a per-env\n // seen-set. The marker is shared across environments but each\n // env's graph has its own edges; this ensures the check runs\n // at most once per (env, module) pair.\n const envRetroKey = `retro-marker:${normalizedImporter}`\n if (violatesEnv && !env.seenViolations.has(envRetroKey)) {\n env.seenViolations.add(envRetroKey)\n let retroDeferred = false\n const importersMap = env.graph.reverseEdges.get(normalizedImporter)\n if (importersMap && importersMap.size > 0) {\n for (const [importerFile, specifier] of importersMap) {\n if (!specifier) continue\n if (!shouldCheckImporter(importerFile)) continue\n const markerInfo = await buildMarkerViolationFromResolvedImport(\n provider,\n env,\n envName,\n envType,\n importerFile,\n specifier,\n normalizedImporter,\n getRelativePath(normalizedImporter),\n )\n if (markerInfo) {\n deferViolation(\n env,\n importerFile,\n markerInfo,\n isPreTransformResolve,\n )\n retroDeferred = true\n }\n }\n }\n if (retroDeferred) {\n await processPendingViolations(env, this.warn.bind(this))\n }\n }\n\n return markerKind === 'server'\n ? resolvedMarkerVirtualModuleId('server')\n : resolvedMarkerVirtualModuleId('client')\n }\n\n // Check if the importer is within our scope\n if (!shouldCheckImporter(normalizedImporter)) {\n return undefined\n }\n\n const matchers = getRulesForEnvironment(envName)\n\n // 1. Specifier-based denial\n const specifierMatch = matchesAny(source, matchers.specifiers)\n if (specifierMatch) {\n if (!isPreTransformResolve) {\n env.graph.addEdge(source, normalizedImporter, source)\n }\n const info = await buildViolationInfo(\n provider,\n env,\n envName,\n envType,\n importer,\n normalizedImporter,\n source,\n {\n type: 'specifier',\n pattern: specifierMatch.pattern,\n message: `Import \"${source}\" is denied in the ${envType} environment`,\n },\n )\n\n // Resolve the specifier so edge-survival can verify whether\n // the import survives the Start compiler transform (e.g.\n // factory-safe pattern strips imports inside .server() callbacks).\n if (shouldDefer && !info.resolved) {\n try {\n const resolvedForInfo = await resolveAgainstImporter()\n if (resolvedForInfo) info.resolved = resolvedForInfo\n } catch {\n // Non-fatal: edge-survival will skip unresolved specifiers\n }\n }\n\n return reportOrDeferViolation(\n this,\n env,\n normalizedImporter,\n importer,\n info,\n shouldDefer,\n isPreTransformResolve,\n )\n }\n\n // 2. Resolve the import (cached)\n const cacheKey = `${normalizedImporter}:${source}`\n let resolved: string | null\n\n if (env.resolveCache.has(cacheKey)) {\n resolved = env.resolveCache.get(cacheKey) ?? null\n } else {\n resolved = await resolveAgainstImporter()\n\n // Only cache successful resolves. Null resolves can be\n // order-dependent across importer variants (e.g. code-split\n // `?tsr-split=...` ids) and may poison later lookups.\n if (resolved !== null) {\n env.resolveCache.set(cacheKey, resolved)\n getOrCreate(\n env.resolveCacheByFile,\n normalizedImporter,\n () => new Set(),\n ).add(cacheKey)\n }\n }\n\n if (resolved) {\n const relativePath = getRelativePath(resolved)\n\n // Propagate pre-transform status transitively\n if (isPreTransformResolve && !isScanResolve) {\n env.serverFnLookupModules.add(resolved)\n }\n\n if (!isPreTransformResolve) {\n env.graph.addEdge(resolved, normalizedImporter, source)\n }\n\n // Skip file-based and marker-based denial for resolved paths that\n // match the per-environment `excludeFiles` patterns. By default\n // this includes `**/node_modules/**` so that third-party packages\n // using `.client.` / `.server.` in their filenames (e.g. react-tweet\n // exports `index.client.js`) are not treated as user-authored\n // environment boundaries. Users can override `excludeFiles` per\n // environment to narrow or widen this exclusion.\n const isExcludedFile =\n matchers.excludeFiles.length > 0 &&\n matchesAny(relativePath, matchers.excludeFiles)\n\n if (!isExcludedFile) {\n const fileMatch =\n matchers.files.length > 0\n ? matchesAny(relativePath, matchers.files)\n : undefined\n\n if (fileMatch) {\n const info = await buildFileViolationInfo(\n provider,\n env,\n envName,\n envType,\n importer,\n normalizedImporter,\n source,\n resolved,\n fileMatch.pattern,\n )\n return reportOrDeferViolation(\n this,\n env,\n normalizedImporter,\n importer,\n info,\n shouldDefer,\n isPreTransformResolve,\n )\n }\n\n const markerInfo = await buildMarkerViolationFromResolvedImport(\n provider,\n env,\n envName,\n envType,\n importer,\n source,\n resolved,\n relativePath,\n )\n if (markerInfo) {\n return reportOrDeferViolation(\n this,\n env,\n normalizedImporter,\n importer,\n markerInfo,\n shouldDefer,\n isPreTransformResolve,\n )\n }\n }\n }\n\n return undefined\n },\n\n load: {\n filter: {\n id: new RegExp(\n getResolvedVirtualModuleMatchers().map(escapeRegExp).join('|'),\n ),\n },\n handler(id) {\n if (IMPORT_PROTECTION_DEBUG) {\n if (matchesDebugFilter(id)) {\n debugLog('load:handler', {\n env: this.environment.name,\n id: normalizePath(id),\n })\n }\n }\n\n return loadResolvedVirtualModule(id)\n },\n },\n\n async generateBundle(_options, bundle) {\n const envName = this.environment.name\n const env = envStates.get(envName)\n if (!env || env.deferredBuildViolations.length === 0) return\n\n const candidateCache = new Map<string, Array<string>>()\n const toModuleIdCandidates = (id: string): Array<string> => {\n let cached = candidateCache.get(id)\n if (cached) return cached\n\n const out = new Set<string>()\n const normalized = normalizeFilePath(id)\n out.add(id)\n out.add(normalized)\n out.add(relativizePath(normalized, config.root))\n\n if (normalized.startsWith(VITE_BROWSER_VIRTUAL_PREFIX)) {\n const internal = `\\0${normalized.slice(VITE_BROWSER_VIRTUAL_PREFIX.length)}`\n out.add(internal)\n out.add(relativizePath(normalizeFilePath(internal), config.root))\n }\n\n if (normalized.startsWith('\\0')) {\n const browser = `${VITE_BROWSER_VIRTUAL_PREFIX}${normalized.slice(1)}`\n out.add(browser)\n out.add(relativizePath(normalizeFilePath(browser), config.root))\n }\n\n cached = Array.from(out)\n candidateCache.set(id, cached)\n return cached\n }\n\n // Collect all module IDs that survived tree-shaking in this bundle.\n const survivingModules = new Set<string>()\n for (const chunk of Object.values(bundle)) {\n if (chunk.type === 'chunk') {\n for (const moduleId of Object.keys(chunk.modules)) {\n for (const candidate of toModuleIdCandidates(moduleId)) {\n survivingModules.add(candidate)\n }\n }\n }\n }\n\n const didModuleSurvive = (moduleId: string): boolean =>\n toModuleIdCandidates(moduleId).some((candidate) =>\n survivingModules.has(candidate),\n )\n\n // Check each deferred violation: if its check module survived\n // in the bundle, the import was NOT tree-shaken — real leak.\n const realViolations: Array<ViolationInfo> = []\n for (const {\n info,\n mockModuleId,\n checkModuleId,\n } of env.deferredBuildViolations) {\n let survived: boolean\n if (checkModuleId != null) {\n // Marker violation: check if the importer survived\n // (marker is about the file's directive, not a binding).\n // Include transform-result keys (e.g. code-split variants)\n // to cover all bundle representations of the importer.\n const importerVariantIds = new Set<string>([info.importer])\n const importerKeys = env.transformResultKeysByFile.get(\n normalizeFilePath(info.importer),\n )\n if (importerKeys) {\n for (const key of importerKeys) {\n importerVariantIds.add(key)\n }\n }\n survived = false\n for (const importerId of importerVariantIds) {\n if (didModuleSurvive(importerId)) {\n survived = true\n break\n }\n }\n } else {\n // File/specifier violation: check if the mock module survived.\n survived = didModuleSurvive(mockModuleId)\n }\n\n if (!survived) continue\n\n if (config.onViolation) {\n const result = await config.onViolation(info)\n if (result === false) continue\n }\n\n realViolations.push(info)\n }\n\n if (realViolations.length === 0) return\n\n if (config.effectiveBehavior === 'error') {\n // Error mode: fail the build on the first real violation.\n this.error(formatViolation(realViolations[0]!, config.root))\n } else {\n // Mock mode: warn for each surviving violation.\n const seen = new Set<string>()\n for (const info of realViolations) {\n const key = dedupeKey(info)\n if (!seen.has(key)) {\n seen.add(key)\n this.warn(formatViolation(info, config.root))\n }\n }\n }\n },\n },\n {\n // Captures transformed code + composed sourcemap for location mapping.\n // Runs after all `enforce: 'pre'` hooks (including the Start compiler).\n // Only files under `srcDirectory` are cached.\n name: 'tanstack-start-core:import-protection-transform-cache',\n\n applyToEnvironment(env) {\n if (!config.enabled) return false\n return environmentNames.has(env.name)\n },\n\n transform: {\n filter: {\n id: {\n include: [/\\.[cm]?[tj]sx?($|\\?)/],\n },\n },\n async handler(code, id) {\n const envName = this.environment.name\n const file = normalizeFilePath(id)\n const envType = getEnvType(envName)\n const matchers = getRulesForEnvironment(envName)\n const isBuild = config.command === 'build'\n\n if (IMPORT_PROTECTION_DEBUG) {\n if (matchesDebugFilter(file)) {\n debugLog('transform-cache', {\n env: envName,\n id: normalizePath(id),\n file,\n })\n }\n }\n\n if (!shouldCheckImporter(file)) {\n return undefined\n }\n\n // Self-denial: if this file is denied in the current environment\n // (e.g. a `.server` file transformed in the client environment),\n // replace its entire content with a mock module.\n //\n // This is the core mechanism for preventing cross-environment\n // cache contamination: resolveId never returns virtual module\n // IDs for file-based violations, so there is nothing for\n // third-party resolver caches (e.g. vite-tsconfig-paths) to\n // leak across environments. Each environment's transform\n // independently decides whether the file is denied.\n //\n // In dev mode, this also solves the cold-start problem where\n // the importer's AST is unavailable for export resolution:\n // the denied file's own source code is always available here,\n // so we parse its exports directly.\n const selfFileMatch = checkFileDenial(getRelativePath(file), matchers)\n if (selfFileMatch) {\n // Parse exports once — shared by build and dev paths.\n // Falls back to empty list on non-standard syntax.\n let exportNames: Array<string> = []\n try {\n exportNames = collectNamedExports(code)\n } catch {\n // Parsing may fail on non-standard syntax\n }\n\n if (isBuild) {\n return generateSelfContainedMockModule(exportNames)\n }\n\n // Dev mode: generate a mock that imports mock-runtime for\n // runtime diagnostics (error/warn on property access).\n const runtimeId = mockRuntimeModuleIdFromViolation(\n {\n type: 'file',\n env: envType,\n envType,\n behavior:\n config.effectiveBehavior === 'error' ? 'error' : 'mock',\n importer: file,\n specifier: relativizePath(file, config.root),\n resolved: file,\n pattern: selfFileMatch.pattern,\n message: `File \"${relativizePath(file, config.root)}\" is denied in the ${envType} environment`,\n trace: [],\n },\n config.mockAccess,\n config.root,\n )\n return generateDevSelfDenialModule(exportNames, runtimeId)\n }\n\n // getCombinedSourcemap() returns the composed sourcemap\n let map: SourceMapLike | undefined\n try {\n map = this.getCombinedSourcemap()\n } catch {\n map = undefined\n }\n\n let originalCode: string | undefined\n if (map?.sourcesContent) {\n originalCode = pickOriginalCodeFromSourcesContent(\n map,\n file,\n config.root,\n )\n }\n\n const lineIndex = buildLineIndex(code)\n const cacheKey = normalizePath(id)\n\n const envState = getEnv(envName)\n const isServerFnLookup = id.includes(SERVER_FN_LOOKUP_QUERY)\n\n // Propagate SERVER_FN_LOOKUP status before import-analysis\n if (isServerFnLookup) {\n envState.serverFnLookupModules.add(file)\n }\n\n const result: TransformResult = {\n code,\n map,\n originalCode,\n lineIndex,\n }\n cacheTransformResult(envState, file, cacheKey, result)\n\n // Build mode: only self-denial (above) and transform caching are\n // needed. All violations are detected and deferred in resolveId;\n // self-denial replaces denied file content; generateBundle checks\n // tree-shaking survival. The import resolution loop below is\n // dev-mode only — it resolves imports for graph reachability,\n // catches violations missed on warm starts (where Vite caches\n // resolveId), and rewrites denied imports to mock modules.\n if (isBuild) return undefined\n\n // Dev mode: resolve imports, populate graph, detect violations,\n // and rewrite denied imports.\n const isDevMock = config.effectiveBehavior === 'mock'\n const importSources = extractImportSources(code)\n const resolvedChildren = new Set<string>()\n const deniedSourceReplacements = new Map<string, string>()\n for (const src of importSources) {\n try {\n const resolved = await this.resolve(src, id, { skipSelf: true })\n if (resolved && !resolved.external) {\n const resolvedPath = canonicalizeResolvedId(\n resolved.id,\n config.root,\n resolveExtensionlessAbsoluteId,\n )\n\n resolvedChildren.add(resolvedPath)\n\n // When the resolved ID is a mock-module (from our\n // resolveId returning a mock-edge ID), postTransformImports\n // would only contain the mock ID. Edge-survival needs the\n // real physical path so pending violations can be matched.\n //\n // For relative specifiers we can compute the physical path\n // directly. For bare/alias specifiers, look up the real\n // resolved path from the pending violations that were\n // already stored by resolveId before this transform ran.\n if (resolved.id.includes('tanstack-start-import-protection:')) {\n let physicalPath: string | undefined\n // Look up real resolved path from pending violations\n const pending = envState.pendingViolations.get(file)\n if (pending) {\n const match = pending.find(\n (pv) => pv.info.specifier === src && pv.info.resolved,\n )\n if (match) physicalPath = match.info.resolved\n }\n if (physicalPath && physicalPath !== resolvedPath) {\n resolvedChildren.add(physicalPath)\n envState.graph.addEdge(physicalPath, file, src)\n }\n }\n\n // Populate import graph edges for warm-start trace accuracy\n envState.graph.addEdge(resolvedPath, file, src)\n\n if (isDevMock) {\n const relativePath = getRelativePath(resolvedPath)\n const fileMatch = checkFileDenial(relativePath, matchers)\n\n if (fileMatch) {\n const info = await buildFileViolationInfo(\n envState.transformResultProvider,\n envState,\n envName,\n envType,\n id,\n file,\n src,\n resolvedPath,\n fileMatch.pattern,\n )\n\n const replacement = await reportOrDeferViolation(\n this,\n envState,\n file,\n id,\n info,\n isDevMock,\n isServerFnLookup,\n )\n\n if (replacement) {\n deniedSourceReplacements.set(\n src,\n replacement.startsWith('\\0')\n ? VITE_BROWSER_VIRTUAL_PREFIX + replacement.slice(1)\n : replacement,\n )\n }\n }\n }\n }\n } catch {\n // Non-fatal\n }\n }\n envState.postTransformImports.set(cacheKey, resolvedChildren)\n if (cacheKey !== file && !isServerFnLookup) {\n envState.postTransformImports.set(file, resolvedChildren)\n }\n\n await processPendingViolations(envState, this.warn.bind(this))\n\n if (deniedSourceReplacements.size > 0) {\n try {\n const rewritten = rewriteDeniedImports(\n code,\n id,\n new Set(deniedSourceReplacements.keys()),\n (source: string) =>\n deniedSourceReplacements.get(source) ?? source,\n )\n\n if (!rewritten) {\n return undefined\n }\n\n const normalizedMap = rewritten.map\n ? {\n ...rewritten.map,\n version: Number(rewritten.map.version),\n sourcesContent:\n rewritten.map.sourcesContent?.map(\n (s: string | null) => s ?? '',\n ) ?? [],\n }\n : {\n version: 3,\n file: id,\n names: [],\n sources: [id],\n sourcesContent: [code],\n mappings: '',\n }\n\n return {\n code: rewritten.code,\n map: normalizedMap,\n }\n } catch {\n // Non-fatal: keep original code when rewrite fails.\n }\n }\n\n return undefined\n },\n },\n },\n ] satisfies Array<PluginOption>\n}\n"],"names":[],"mappings":";;;;;;;;;;;;AAgFO,SAAS,uBACd,MACc;AACd,MAAI,YAAkC;AACtC,QAAM,0BAA0B,IAAI,gCAAA;AACpC,QAAM,iCAAiC,CAAC,OACtC,wBAAwB,QAAQ,EAAE;AAEpC,QAAM,yCAAyB,IAAA;AAE/B,WAAS,8BAA8B,MAAc,QAAwB;AAC3E,QAAI,WAAW,mBAAmB,IAAI,MAAM;AAC5C,QAAI,CAAC,UAAU;AACb,YAAM,UAAU,aAAa,MAAM;AACnC,iBAAW;AAAA,QACT,IAAI,OAAO,s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babel from "@babel/core";
2
2
  import * as t from "@babel/types";
3
- import { parseAst } from "@tanstack/router-utils";
3
+ import { parseImportProtectionAst } from "./ast.js";
4
4
  function findPostCompileUsagePos(code, source) {
5
- const ast = parseAst({ code });
5
+ return findPostCompileUsagePosFromAst(parseImportProtectionAst(code), source);
6
+ }
7
+ function findPostCompileUsagePosFromAst(ast, source) {
6
8
  const imported = /* @__PURE__ */ new Set();
7
9
  for (const node of ast.program.body) {
8
10
  if (t.isImportDeclaration(node) && node.source.value === source) {
@@ -1 +1 @@
1
- {"version":3,"file":"postCompileUsage.js","sources":["../../../src/import-protection-plugin/postCompileUsage.ts"],"sourcesContent":["import babel from '@babel/core'\nimport * as t from '@babel/types'\nimport { parseAst } from '@tanstack/router-utils'\n\ntype UsagePos = { line: number; column0: number }\n\n/**\n * Given transformed code, returns the first \"meaningful\" usage position for an\n * import from `source` that survives compilation.\n *\n * \"Preferred\" positions (call, new, member-access) take priority over bare\n * identifier references. The returned column is 0-based (Babel loc semantics).\n */\nexport function findPostCompileUsagePos(\n code: string,\n source: string,\n): UsagePos | undefined {\n const ast = parseAst({ code })\n\n // Collect local names bound from this specifier\n const imported = new Set<string>()\n for (const node of ast.program.body) {\n if (t.isImportDeclaration(node) && node.source.value === source) {\n if (node.importKind === 'type') continue\n for (const s of node.specifiers) {\n if (t.isImportSpecifier(s) && s.importKind === 'type') continue\n imported.add(s.local.name)\n }\n }\n }\n if (imported.size === 0) return undefined\n\n let preferred: UsagePos | undefined\n let anyUsage: UsagePos | undefined\n\n // babel.traverse can throw on malformed scopes (e.g. duplicate bindings from\n // import + const re-declaration) because parseAst doesn't attach a hub\n try {\n babel.traverse(ast, {\n ImportDeclaration(path) {\n path.skip()\n },\n\n Identifier(path: babel.NodePath<t.Identifier>) {\n if (preferred && anyUsage) {\n path.stop()\n return\n }\n\n const { node, parent, scope } = path\n if (!imported.has(node.name)) return\n\n // Skip binding positions (declarations, import specifiers, etc.)\n if (path.isBindingIdentifier()) return\n\n // Skip non-shorthand object property keys — they don't reference the import\n if (\n t.isObjectProperty(parent) &&\n parent.key === node &&\n !parent.computed &&\n !parent.shorthand\n )\n return\n if (t.isObjectMethod(parent) && parent.key === node && !parent.computed)\n return\n if (t.isExportSpecifier(parent) && parent.exported === node) return\n\n // Skip if shadowed by a closer binding\n const binding = scope.getBinding(node.name)\n if (binding && binding.kind !== 'module') return\n\n const loc = node.loc?.start\n if (!loc) return\n const pos: UsagePos = { line: loc.line, column0: loc.column }\n\n const isPreferred =\n (t.isCallExpression(parent) && parent.callee === node) ||\n (t.isNewExpression(parent) && parent.callee === node) ||\n (t.isMemberExpression(parent) && parent.object === node)\n\n if (isPreferred) {\n preferred ||= pos\n } else {\n anyUsage ||= pos\n }\n },\n })\n } catch {\n // Scope analysis failed — cannot determine usage positions reliably\n return undefined\n }\n\n return preferred ?? anyUsage\n}\n"],"names":[],"mappings":";;;AAaO,SAAS,wBACd,MACA,QACsB;AACtB,QAAM,MAAM,SAAS,EAAE,MAAM;AAG7B,QAAM,+BAAe,IAAA;AACrB,aAAW,QAAQ,IAAI,QAAQ,MAAM;AACnC,QAAI,EAAE,oBAAoB,IAAI,KAAK,KAAK,OAAO,UAAU,QAAQ;AAC/D,UAAI,KAAK,eAAe,OAAQ;AAChC,iBAAW,KAAK,KAAK,YAAY;AAC/B,YAAI,EAAE,kBAAkB,CAAC,KAAK,EAAE,eAAe,OAAQ;AACvD,iBAAS,IAAI,EAAE,MAAM,IAAI;AAAA,MAC3B;AAAA,IACF;AAAA,EACF;AACA,MAAI,SAAS,SAAS,EAAG,QAAO;AAEhC,MAAI;AACJ,MAAI;AAIJ,MAAI;AACF,UAAM,SAAS,KAAK;AAAA,MAClB,kBAAkB,MAAM;AACtB,aAAK,KAAA;AAAA,MACP;AAAA,MAEA,WAAW,MAAoC;AAC7C,YAAI,aAAa,UAAU;AACzB,eAAK,KAAA;AACL;AAAA,QACF;AAEA,cAAM,EAAE,MAAM,QAAQ,MAAA,IAAU;AAChC,YAAI,CAAC,SAAS,IAAI,KAAK,IAAI,EAAG;AAG9B,YAAI,KAAK,sBAAuB;AAGhC,YACE,EAAE,iBAAiB,MAAM,KACzB,OAAO,QAAQ,QACf,CAAC,OAAO,YACR,CAAC,OAAO;AAER;AACF,YAAI,EAAE,eAAe,MAAM,KAAK,OAAO,QAAQ,QAAQ,CAAC,OAAO;AAC7D;AACF,YAAI,EAAE,kBAAkB,MAAM,KAAK,OAAO,aAAa,KAAM;AAG7D,cAAM,UAAU,MAAM,WAAW,KAAK,IAAI;AAC1C,YAAI,WAAW,QAAQ,SAAS,SAAU;AAE1C,cAAM,MAAM,KAAK,KAAK;AACtB,YAAI,CAAC,IAAK;AACV,cAAM,MAAgB,EAAE,MAAM,IAAI,MAAM,SAAS,IAAI,OAAA;AAErD,cAAM,cACH,EAAE,iBAAiB,MAAM,KAAK,OAAO,WAAW,QAChD,EAAE,gBAAgB,MAAM,KAAK,OAAO,WAAW,QAC/C,EAAE,mBAAmB,MAAM,KAAK,OAAO,WAAW;AAErD,YAAI,aAAa;AACf,wBAAc;AAAA,QAChB,OAAO;AACL,uBAAa;AAAA,QACf;AAAA,MACF;AAAA,IAAA,CACD;AAAA,EACH,QAAQ;AAEN,WAAO;AAAA,EACT;AAEA,SAAO,aAAa;AACtB;"}
1
+ {"version":3,"file":"postCompileUsage.js","sources":["../../../src/import-protection-plugin/postCompileUsage.ts"],"sourcesContent":["import babel from '@babel/core'\nimport * as t from '@babel/types'\nimport { parseImportProtectionAst } from './ast'\nimport type { ParsedAst } from './ast'\n\ntype UsagePos = { line: number; column0: number }\n\n/**\n * Given transformed code, returns the first \"meaningful\" usage position for an\n * import from `source` that survives compilation.\n *\n * \"Preferred\" positions (call, new, member-access) take priority over bare\n * identifier references. The returned column is 0-based (Babel loc semantics).\n */\nexport function findPostCompileUsagePos(\n code: string,\n source: string,\n): UsagePos | undefined {\n return findPostCompileUsagePosFromAst(parseImportProtectionAst(code), source)\n}\n\nfunction findPostCompileUsagePosFromAst(\n ast: ParsedAst,\n source: string,\n): UsagePos | undefined {\n // Collect local names bound from this specifier\n const imported = new Set<string>()\n for (const node of ast.program.body) {\n if (t.isImportDeclaration(node) && node.source.value === source) {\n if (node.importKind === 'type') continue\n for (const s of node.specifiers) {\n if (t.isImportSpecifier(s) && s.importKind === 'type') continue\n imported.add(s.local.name)\n }\n }\n }\n if (imported.size === 0) return undefined\n\n let preferred: UsagePos | undefined\n let anyUsage: UsagePos | undefined\n\n // babel.traverse can throw on malformed scopes (e.g. duplicate bindings from\n // import + const re-declaration) because parseAst doesn't attach a hub\n try {\n babel.traverse(ast, {\n ImportDeclaration(path) {\n path.skip()\n },\n\n Identifier(path: babel.NodePath<t.Identifier>) {\n if (preferred && anyUsage) {\n path.stop()\n return\n }\n\n const { node, parent, scope } = path\n if (!imported.has(node.name)) return\n\n // Skip binding positions (declarations, import specifiers, etc.)\n if (path.isBindingIdentifier()) return\n\n // Skip non-shorthand object property keys — they don't reference the import\n if (\n t.isObjectProperty(parent) &&\n parent.key === node &&\n !parent.computed &&\n !parent.shorthand\n )\n return\n if (t.isObjectMethod(parent) && parent.key === node && !parent.computed)\n return\n if (t.isExportSpecifier(parent) && parent.exported === node) return\n\n // Skip if shadowed by a closer binding\n const binding = scope.getBinding(node.name)\n if (binding && binding.kind !== 'module') return\n\n const loc = node.loc?.start\n if (!loc) return\n const pos: UsagePos = { line: loc.line, column0: loc.column }\n\n const isPreferred =\n (t.isCallExpression(parent) && parent.callee === node) ||\n (t.isNewExpression(parent) && parent.callee === node) ||\n (t.isMemberExpression(parent) && parent.object === node)\n\n if (isPreferred) {\n preferred ||= pos\n } else {\n anyUsage ||= pos\n }\n },\n })\n } catch {\n // Scope analysis failed — cannot determine usage positions reliably\n return undefined\n }\n\n return preferred ?? anyUsage\n}\n"],"names":[],"mappings":";;;AAcO,SAAS,wBACd,MACA,QACsB;AACtB,SAAO,+BAA+B,yBAAyB,IAAI,GAAG,MAAM;AAC9E;AAEA,SAAS,+BACP,KACA,QACsB;A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O,WAAW;AAErD,YAAI,aAAa;AACf,wBAAc;AAAA,QAChB,OAAO;AACL,uBAAa;AAAA,QACf;AAAA,MACF;AAAA,IAAA,CACD;AAAA,EACH,QAAQ;AAEN,WAAO;AAAA,EACT;AAEA,SAAO,aAAa;AACtB;"}
@@ -1,9 +1,8 @@
1
+ import { SourceMapLike } from './sourceLocation.js';
1
2
  export declare function isValidExportName(name: string): boolean;
2
- /**
3
- * Best-effort static analysis of an importer's source to determine which
4
- * named exports are needed per specifier, to keep native ESM valid in dev.
5
- */
6
3
  export declare function collectMockExportNamesBySource(code: string): Map<string, Array<string>>;
4
+ /** Collect all valid named export identifiers from the given code. */
5
+ export declare function collectNamedExports(code: string): Array<string>;
7
6
  /**
8
7
  * Rewrite static imports/re-exports from denied sources using Babel AST transforms.
9
8
  *
@@ -23,5 +22,5 @@ export declare function collectMockExportNamesBySource(code: string): Map<string
23
22
  */
24
23
  export declare function rewriteDeniedImports(code: string, id: string, deniedSources: Set<string>, getMockModuleId?: (source: string) => string): {
25
24
  code: string;
26
- map?: object | null;
25
+ map?: SourceMapLike;
27
26
  } | undefined;