Skip to content

Commit 24a018b

Browse files
fix: avoid false positives in import-protection plugin
1 parent c3ad063 commit 24a018b

8 files changed

Lines changed: 207 additions & 146 deletions

File tree

‎e2e/react-start/import-protection/src/routes/index.tsx‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,12 @@ import { getWrappedSecret1 } from '../violations/edge-1'
77
// index.tsx -> violations/marked-server-only-edge.ts -> violations/marked-server-only.ts
88
import { getServerOnlyDataViaEdge } from '../violations/marked-server-only-edge'
99
import { secretServerFn } from '../violations/compiler-leak'
10+
import { factorySafeServerFn } from '../violations/factory-safe/usage'
11+
import {
12+
safeIsomorphic,
13+
safeServerFn,
14+
safeServerOnly,
15+
} from '../violations/boundary-safe'
1016

1117
export const Route = createFileRoute('/')({
1218
component: Home,
@@ -21,6 +27,10 @@ function Home() {
2127
<p data-testid="secret-deep">{getWrappedSecret1()}</p>
2228
<p data-testid="server-only-data">{getServerOnlyDataViaEdge()}</p>
2329
<p data-testid="compiler-ok">{String(typeof secretServerFn)}</p>
30+
<p data-testid="factory-safe">{String(typeof factorySafeServerFn)}</p>
31+
<p data-testid="boundary-safe-so">{String(typeof safeServerOnly)}</p>
32+
<p data-testid="boundary-safe-sf">{String(typeof safeServerFn)}</p>
33+
<p data-testid="boundary-safe-iso">{String(typeof safeIsomorphic)}</p>
2434
</div>
2535
)
2636
}
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
import {
2+
createIsomorphicFn,
3+
createServerFn,
4+
createServerOnlyFn,
5+
} from '@tanstack/react-start'
6+
7+
import { getSecret } from './secret.server'
8+
9+
// NOTE: `getSecret` is only referenced inside compiler-recognized boundaries.
10+
// The Start compiler should prune the `./secret.server` import from the client
11+
// build output.
12+
13+
export const safeServerOnly = createServerOnlyFn(() => {
14+
return getSecret()
15+
})
16+
17+
export const safeServerFn = createServerFn().handler(async () => {
18+
return getSecret()
19+
})
20+
21+
export const safeIsomorphic = createIsomorphicFn()
22+
.server(() => {
23+
return getSecret()
24+
})
25+
.client(() => {
26+
return 'client'
27+
})
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
import { createMiddleware, createServerFn } from '@tanstack/react-start'
2+
import { getRequest } from '@tanstack/react-start/server'
3+
4+
import { getSecret } from '../secret.server'
5+
6+
// This file intentionally contains denied imports (./secret.server and
7+
// @tanstack/react-start/server), but they are only referenced inside
8+
// compiler-recognized server boundaries.
9+
10+
const secretMiddleware = createMiddleware({ type: 'function' }).server(
11+
({ next }) => {
12+
const req = getRequest()
13+
const secret = getSecret()
14+
return next({
15+
context: { method: req.method, secret } as const,
16+
})
17+
},
18+
)
19+
20+
export const createSecretFactoryServerFn = createServerFn().middleware([
21+
secretMiddleware,
22+
])
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
import { createSecretFactoryServerFn } from './createSecretFactory'
2+
3+
export const factorySafeServerFn = createSecretFactoryServerFn().handler(
4+
async ({ context, method }) => {
5+
return {
6+
name: 'factorySafeServerFn',
7+
method,
8+
context,
9+
}
10+
},
11+
)

‎e2e/react-start/import-protection/tests/import-protection.spec.ts‎

Lines changed: 54 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -154,7 +154,7 @@ test('all trace steps include line numbers', async () => {
154154
// The entry (step 0) may not have one if it has no specifier pointing into it.
155155
// All non-entry steps should have line numbers since they import something.
156156
for (let i = 1; i < v!.trace.length; i++) {
157-
const step = v!.trace[i]!
157+
const step = v!.trace[i]
158158
expect(
159159
step.line,
160160
`trace step ${i} (${step.file}) should have a line number`,
@@ -172,7 +172,7 @@ test('leaf trace step includes the denied import specifier', async () => {
172172
expect(v).toBeDefined()
173173

174174
// The last trace step should be the leaf (edge-a) and include the specifier
175-
const last = v!.trace[v!.trace.length - 1]!
175+
const last = v!.trace[v!.trace.length - 1]
176176
expect(last.file).toContain('edge-a')
177177
expect(last.specifier).toContain('secret.server')
178178
expect(last.line).toBeDefined()
@@ -267,6 +267,22 @@ test('dev violations include code snippets', async () => {
267267
}
268268
})
269269

270+
test('no violation for .server import used only inside compiler boundaries', async () => {
271+
const violations = await readViolations('build')
272+
273+
// boundary-safe.ts imports secret.server.ts, but the import should be pruned
274+
// from the client build because it is only referenced inside compiler
275+
// boundaries (createServerFn/createServerOnlyFn/createIsomorphicFn).
276+
const safeHits = violations.filter(
277+
(v) =>
278+
v.envType === 'client' &&
279+
(v.importer.includes('boundary-safe') ||
280+
v.trace.some((s) => s.file.includes('boundary-safe'))),
281+
)
282+
283+
expect(safeHits).toEqual([])
284+
})
285+
270286
test('compiler-processed module has code snippet in dev', async () => {
271287
const violations = await readViolations('dev')
272288

@@ -365,3 +381,39 @@ test('build has violations in both client and SSR environments', async () => {
365381
expect(clientViolations.length).toBeGreaterThanOrEqual(2)
366382
expect(ssrViolations.length).toBeGreaterThanOrEqual(2)
367383
})
384+
385+
test('no false positive for factory-safe middleware pattern in dev', async () => {
386+
const violations = await readViolations('dev')
387+
388+
// createSecretFactory.ts uses @tanstack/react-start/server and ../secret.server
389+
// ONLY inside createMiddleware().server() callbacks. The compiler strips these
390+
// on the client, so import-protection must not fire for them.
391+
const factoryHits = violations.filter(
392+
(v) =>
393+
v.envType === 'client' &&
394+
(v.importer.includes('createSecretFactory') ||
395+
v.importer.includes('factory-safe') ||
396+
v.trace.some(
397+
(s) =>
398+
s.file.includes('createSecretFactory') ||
399+
s.file.includes('factory-safe'),
400+
)),
401+
)
402+
403+
expect(factoryHits).toEqual([])
404+
})
405+
406+
test('no false positive for boundary-safe pattern in dev', async () => {
407+
const violations = await readViolations('dev')
408+
409+
// boundary-safe.ts imports secret.server.ts but only uses it inside
410+
// compiler boundaries (createServerFn/createServerOnlyFn/createIsomorphicFn).
411+
const safeHits = violations.filter(
412+
(v) =>
413+
v.envType === 'client' &&
414+
(v.importer.includes('boundary-safe') ||
415+
v.trace.some((s) => s.file.includes('boundary-safe'))),
416+
)
417+
418+
expect(safeHits).toEqual([])
419+
})

‎e2e/react-start/import-protection/tests/violations.setup.ts‎

Lines changed: 23 additions & 124 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import fs from 'node:fs'
22
import path from 'node:path'
33
import { spawn } from 'node:child_process'
4-
import type { FullConfig } from '@playwright/test'
4+
import { chromium, type FullConfig } from '@playwright/test'
55
import { getTestServerPort } from '@tanstack/router-e2e-utils'
66
import packageJson from '../package.json' with { type: 'json' }
77

@@ -77,96 +77,11 @@ const routes = [
7777
'/client-only-jsx',
7878
]
7979

80-
const extraModulePaths = [
81-
'/src/routes/leaky-server-import.tsx',
82-
'/src/violations/leaky-server-import.ts',
83-
'/src/routes/client-only-violations.tsx',
84-
'/src/routes/client-only-jsx.tsx',
85-
'/src/violations/window-size.client.tsx',
86-
// Index route violation modules: triggers client-env violations for
87-
// file-based (edge-a, edge-3, compiler-leak → secret.server) and
88-
// marker-based (marked-server-only) denials.
89-
'/src/routes/index.tsx',
90-
'/src/violations/edge-a.ts',
91-
'/src/violations/edge-1.ts',
92-
'/src/violations/edge-2.ts',
93-
'/src/violations/edge-3.ts',
94-
'/src/violations/compiler-leak.ts',
95-
'/src/violations/marked-server-only-edge.ts',
96-
'/src/violations/marked-server-only.ts',
97-
]
98-
99-
/**
100-
* Warmup pass: start a throwaway Vite dev server, hit all routes and module
101-
* URLs so that Vite's dep optimization runs and populates the
102-
* `node_modules/.vite` cache, then kill the server.
103-
*
104-
* On a cold start (no `.vite` cache), Vite's dep optimization runs lazily on
105-
* first request. During that burst, `resolveId` can fire before the
106-
* transform-cache plugin has stored `{code, map}` for importers, which means
107-
* violations logged in this window may lack snippets.
108-
*
109-
* By running the warmup in a separate server instance we ensure the `.vite`
110-
* dep cache exists before the real capture pass starts. The second server
111-
* boots with a warm dep cache so all transforms are populated before
112-
* `resolveId` fires for violation edges.
113-
*/
114-
async function warmupDepOptimization(
115-
cwd: string,
116-
port: number,
117-
baseURL: string,
118-
): Promise<void> {
119-
const child = startDevServer(cwd, port)
120-
121-
// Drain output to /dev/null — we don't need warmup logs.
122-
child.stdout?.resume()
123-
child.stderr?.resume()
124-
125-
try {
126-
await waitForHttpOk(baseURL, 30_000)
127-
128-
// Fetch HTML pages to trigger SSR transforms + dep discovery.
129-
for (const route of routes) {
130-
try {
131-
await fetch(`${baseURL}${route}`, {
132-
signal: AbortSignal.timeout(10_000),
133-
})
134-
} catch {
135-
// ignore
136-
}
137-
}
138-
139-
// Fetch module URLs to trigger client-env transforms and ensure all
140-
// external deps are discovered and optimized.
141-
const moduleUrls = ['/@vite/client', ...extraModulePaths].map((u) =>
142-
u.startsWith('http') ? u : `${baseURL}${u}`,
143-
)
144-
for (const url of moduleUrls) {
145-
try {
146-
await fetch(url, { signal: AbortSignal.timeout(10_000) })
147-
} catch {
148-
// ignore
149-
}
150-
}
151-
152-
// Wait for dep optimization to finish writing the .vite cache.
153-
await new Promise((r) => setTimeout(r, 2000))
154-
} finally {
155-
await killChild(child)
156-
}
157-
}
158-
15980
async function captureDevViolations(cwd: string): Promise<void> {
16081
const port = await getTestServerPort(`${packageJson.name}_dev`)
16182
const baseURL = `http://localhost:${port}`
16283
const logFile = path.resolve(cwd, 'webserver-dev.log')
16384

164-
// --- Warmup pass ----------------------------------------------------------
165-
// Run a throwaway dev server to populate the .vite dep cache. This is a
166-
// no-op when the cache already exists (warm start).
167-
await warmupDepOptimization(cwd, port, baseURL)
168-
169-
// --- Capture pass (warm dep cache) ----------------------------------------
17085
const out = fs.createWriteStream(logFile)
17186
const child = startDevServer(cwd, port)
17287

@@ -176,46 +91,30 @@ async function captureDevViolations(cwd: string): Promise<void> {
17691
try {
17792
await waitForHttpOk(baseURL, 30_000)
17893

179-
const htmlPages: Array<string> = []
180-
for (const route of routes) {
181-
try {
182-
const htmlRes = await fetch(`${baseURL}${route}`, {
183-
signal: AbortSignal.timeout(5000),
184-
})
185-
htmlPages.push(await htmlRes.text())
186-
} catch {
187-
// ignore
94+
// Use a real browser to navigate to every route. This triggers SSR
95+
// (server-env transforms + compiler cross-module resolution) AND client
96+
// module loading (client-env transforms), exactly mirroring real usage.
97+
// Direct HTTP fetches of module URLs do NOT trigger the compiler's
98+
// cross-module resolution path that surfaces certain violations.
99+
const browser = await chromium.launch()
100+
try {
101+
const context = await browser.newContext()
102+
const page = await context.newPage()
103+
104+
for (const route of routes) {
105+
try {
106+
await page.goto(`${baseURL}${route}`, {
107+
waitUntil: 'networkidle',
108+
timeout: 15_000,
109+
})
110+
} catch {
111+
// ignore navigation errors — we only care about server logs
112+
}
188113
}
189-
}
190-
191-
const scriptSrcs = htmlPages
192-
.flatMap((html) =>
193-
Array.from(
194-
html.matchAll(/<script[^>]*type="module"[^>]*src="([^"]+)"/g),
195-
).map((m) => m[1]),
196-
)
197-
.filter(Boolean)
198-
.slice(0, 10)
199-
200-
// Trigger module transforms by fetching module scripts referenced from
201-
// HTML, plus known module paths to ensure code-split routes are
202-
// transformed. Fetching these via HTTP triggers Vite's client-environment
203-
// transform pipeline, which fires resolveId for each import and surfaces
204-
// violations.
205-
const moduleUrls = Array.from(
206-
new Set(['/@vite/client', ...scriptSrcs, ...extraModulePaths]),
207-
)
208-
.map((u) => (u.startsWith('http') ? u : `${baseURL}${u}`))
209-
.slice(0, 30)
210114

211-
for (const url of moduleUrls) {
212-
try {
213-
await fetch(url, {
214-
signal: AbortSignal.timeout(10_000),
215-
})
216-
} catch {
217-
// ignore
218-
}
115+
await context.close()
116+
} finally {
117+
await browser.close()
219118
}
220119

221120
// Give the server a moment to flush logs.

0 commit comments

Comments
 (0)