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

caller-dead-code.test.ts

713 lines23.0 KB

1import { describe, expect, test } from 'vitest'
2import {
3 callProvider,
4 compileAll,
5 compileCode,
6 evaluateModule,
7 importSources,
8} from '../regression-helpers'
9import { declarationOf, getModuleErrors } from '../validate-module'
10import type { ModuleStub } from '../regression-helpers'
11​
12// Client and SSR callers replace a server fn handler with an RPC, then drop
13// the module code only the handler read, so server-only imports never reach
14// them. Code the callers still read must survive with its values.
15​
16const head = `import { createServerFn } from '@tanstack/react-start'\n`
17const dbServer = `export const db = { x: () => 'x' }`
18​
19describe('callers drop a server import only the handler reads', () => {
20 // Source: Next.js server-actions fixtures server-graph/6 (shadowed bindings)
21 test.each([
22 {
23 name: 'a handler local shadows an import the client uses',
24 code: `import { db } from './db.server'
25import { format } from './format'
26export const label = format('x')
27export const fn = createServerFn().handler(async () => {
28 const format = (value: unknown) => \`local:\${value}\`
29 return format(db.x())
30})`,
31 client: ['./format'],
32 provider: ['./db.server'],
33 expected: 'local:x',
34 },
35 {
36 name: 'a handler parameter shadows an import the client uses',
37 code: `import { db } from './db.server'
38export const fn = createServerFn().handler(async ({ data: db }: { data: string }) => db)
39export const clientDb = db`,
40 client: ['./db.server'],
41 provider: [],
42 expected: 'param',
43 },
44 ])('when $name', async ({ code, client, provider, expected }) => {
45 const compiled = await compileAll(`${head}${code}`)
46 expect(importSources(compiled.client)).toEqual(client)
47 expect(importSources(compiled.provider)).toEqual(provider)
48 expect(
49 await callProvider(
50 compiled.provider,
51 'fn',
52 { './db.server': dbServer },
53 'param',
54 ),
55 ).toBe(expected)
56 })
57​
58 // Each snippet uses the name `db` in a position that is not a reference to
59 // the import the handler reads.
60 test.each<{
61 name: string
62 code: string
63 stubs?: Record<string, ModuleStub>
64 check?: (client: Record<string, any>) => void
65 }>([
66 {
67 // Source: @vitejs/plugin-rsc scope/label.js
68 name: 'a label',
69 code: `export function loop() {
70 db: for (const item of [1, 2]) {
71 if (item) {
72 break db
73 }
74 }
75 return 'loop'
76}`,
77 check: (client) => expect(client.loop()).toBe('loop'),
78 },
79 {
80 // Source: @vitejs/plugin-rsc scope/object-expr-vs-pattern.js
81 name: 'an object key and a pattern key',
82 code: `export const options = { db: 'key' }
83export const pick = ({ db: local }) => local`,
84 check: (client) => expect(client.pick(client.options)).toBe('key'),
85 },
86 {
87 // Source: @vitejs/plugin-rsc scope/member-expr.js
88 name: 'a member property',
89 code: `export const read = (object) => object.db`,
90 check: (client) => expect(client.read({ db: 'member' })).toBe('member'),
91 },
92 {
93 // Source: @vitejs/plugin-rsc scope/method-definition.js,
94 // scope/property-definition.js; typescript-eslint private-identifier.js
95 name: 'method, field and private names',
96 code: `export const api = { db() { return 'method' } }
97export class Store {
98 db = 'field'
99 #db = 'private'
100 static db() {
101 return 'static'
102 }
103 read() {
104 return [this.db, this.#db]
105 }
106}`,
107 check: (client) => {
108 expect(client.api.db()).toBe('method')
109 expect(client.Store.db()).toBe('static')
110 expect(new client.Store().read()).toEqual(['field', 'private'])
111 },
112 },
113 {
114 // Source: @vitejs/plugin-rsc scope/export-specifier.js
115 name: 'an export alias',
116 code: `const local = 'alias'
117export { local as db }`,
118 check: (client) => expect(client.db).toBe('alias'),
119 },
120 {
121 // Source: @vitejs/plugin-rsc scope/destructuring-assignment.js
122 name: 'a destructuring assignment key',
123 code: `let bound
124;({ db: bound } = { db: 'assigned' })
125export { bound }`,
126 check: (client) => expect(client.bound).toBe('assigned'),
127 },
128 {
129 // Source: @vitejs/plugin-rsc scope/catch-param.js
130 name: 'a catch parameter',
131 code: `export function safe() {
132 try {
133 throw 'caught'
134 } catch (db) {
135 return db
136 }
137}`,
138 check: (client) => expect(client.safe()).toBe('caught'),
139 },
140 {
141 // Source: @vitejs/plugin-rsc scope/fn-expr-name.js, scope/class-expr-self.js
142 name: 'function and class expression names',
143 code: `export const self = function db() {
144 return db
146export const Self = class db {
147 static self() {
148 return db
149 }
150}`,
151 check: (client) => {
152 expect(client.self()).toBe(client.self)
153 expect(client.Self.self()).toBe(client.Self)
154 },
155 },
156 {
157 // Source: @vitejs/plugin-rsc scope/var-hoisting.js, scope/fn-decl-hoisting.js
158 name: 'hoisted var and function declarations',
159 code: `export function hoistedVar() {
160 {
161 var db = 'var'
162 }
163 return db
165export function hoistedFunction() {
166 return db()
167 function db() {
168 return 'function'
169 }
170}`,
171 check: (client) => {
172 expect(client.hoistedVar()).toBe('var')
173 expect(client.hoistedFunction()).toBe('function')
174 },
175 },
176 {
177 // Source: @vitejs/plugin-rsc scope/let-const-block.js,
178 // scope/shadowing-block.js; typescript-eslint block/scope.js
179 name: 'loop, switch and static block declarations',
180 code: `export function loops() {
181 const out = []
182 for (let db = 0; db < 1; db++) out.push(db)
183 for (const db of ['of']) out.push(db)
184 for (const db in { in: 1 }) out.push(db)
185 return out
187export function choose(key) {
188 switch (key) {
189 case 1:
190 return 'one'
191 default:
192 const db = 'switch'
193 return db
194 }
196export class Block {
197 static value
198 static {
199 const db = 'static'
200 Block.value = db
201 }
202}`,
203 check: (client) => {
204 expect(client.loops()).toEqual([0, 'of', 'in'])
205 expect(client.choose(2)).toBe('switch')
206 expect(client.Block.value).toBe('static')
207 },
208 },
209 {
210 // Source: @vitejs/plugin-rsc scope/destructured-params.js,
211 // scope/param-defaults.js; typescript-eslint readable-ref-param-shadow.js
212 name: 'parameters, accessor parameters and defaults reading them',
213 code: `export const params = (db, other = db) => other
214export const accessors = {
215 stored: '',
216 set value(db) {
217 this.stored = db
218 },
220export function rest(...db) {
221 return db
222}`,
223 check: (client) => {
224 expect(client.params('param')).toBe('param')
225 client.accessors.value = 'set'
226 expect(client.accessors.stored).toBe('set')
227 expect(client.rest(1, 2)).toEqual([1, 2])
228 },
229 },
230 {
231 // Source: @vitejs/plugin-rsc scope/import-meta.js
232 name: 'an import.meta property',
233 code: `export const meta = typeof import.meta.db`,
234 check: (client) => expect(client.meta).toBe('undefined'),
235 },
236 {
237 // Source: @vitejs/plugin-rsc hoist/reexport-import-not-bound.js
238 name: 'a re-export',
239 code: `export { db } from './other'`,
240 stubs: { './other': `export const db = 'other'` },
241 check: (client) => expect(client.db).toBe('other'),
242 },
243 {
244 // Source: typescript-eslint ts-module/namespace.js, ts-module/scope.js
245 name: 'a namespace member',
246 code: `export namespace Repo {
247 export const db = 'namespace'
248 export const read = () => db
249}`,
250 check: (client) => expect(client.Repo.read()).toBe('namespace'),
251 },
252 {
253 // Source: typescript-eslint type-declaration/interface1.js, type1.js,
254 // function-declaration/type-parameters
255 name: 'type positions',
256 code: `export interface Row {
257 db: string
259export type Shape = { db: number }
260export function identity<db>(value: db): db {
261 return value
262}`,
263 check: (client) => expect(client.identity('id')).toBe('id'),
264 },
265 {
266 // Source: typescript-eslint ts-enum/member-ref.js
267 name: 'an enum member',
268 code: `export enum Flags {
269 db = 1,
270 other = db + 1,
271}`,
272 check: (client) => expect(client.Flags.other).toBe(2),
273 },
274 {
275 // Source: typescript-eslint functions/function-declaration/overload.js
276 name: 'an overload signature parameter',
277 code: `export function call(db: string): string
278export function call(value: string) {
279 return value
280}`,
281 check: (client) => expect(client.call('call')).toBe('call'),
282 },
283 {
284 // Source: typescript-eslint class/declaration/parameter-properties.js
285 name: 'a parameter property',
286 code: `export class Service {
287 constructor(private db: string) {}
288 read() {
289 return this.db
290 }
291}`,
292 check: (client) =>
293 expect(new client.Service('param').read()).toBe('param'),
294 },
295 {
296 // Source: typescript-eslint jsx/attribute.js, jsx/namespaced-attribute.js,
297 // jsx/component-intrinsic-name.js, jsx/this-jsxidentifier.js
298 name: 'JSX attribute names, intrinsic tags and this members',
299 code: `export const element = <svg db="attribute" xlink:db="namespaced" />
300export const intrinsic = <db />
301export const namespaced = <db:tag />
302export class View {
303 db = () => null
304 render() {
305 return <this.db />
306 }
307}`,
308 },
309 ])(
310 'when client code uses its name in $name',
311 async ({ code, stubs = {}, check }) => {
312 const client = await compileCode(
313 'client',
314 `${head}import { db } from './db.server'
315export const fn = createServerFn().handler(async () => db.x())
316${code}`,
317 )
318 expect(await getModuleErrors(client!)).toEqual([])
319 expect(importSources(client!)).toEqual(Object.keys(stubs))
320 check?.(await evaluateModule(client!, stubs))
321 },
322 )
323​
324 // Source: SolidStart compile.spec.ts "removes an import when only type
325 // specifiers remain", "preserves live value specifiers from a mixed
326 // import"; babel-dead-code-elimination "import" > "mixed default and named"
327 test.each([
328 {
329 name: 'only type specifiers remain',
330 code: `import { type Session, verify } from './server-module'`,
331 callers: [],
332 },
333 {
334 name: 'a named client specifier remains',
335 code: `import verify, { type Session, clientValue } from './server-module'
336export const value = clientValue`,
337 callers: ['./server-module'],
338 },
339 {
340 name: 'a default client specifier remains',
341 code: `import clientDefault, { type Session, verify } from './server-module'
342export const value = clientDefault`,
343 callers: ['./server-module'],
344 },
345 ])(
346 'when it shares a mixed import in which $name',
347 async ({ code, callers }) => {
348 const compiled = await compileAll(`${head}${code}
349export const fn = createServerFn().handler(async (): Promise<Session | null> => verify())`)
350 for (const caller of [compiled.client, compiled.ssr]) {
351 expect(importSources(caller)).toEqual(callers)
352 expect(caller).not.toMatch(/\bverify\b/)
353 }
354 expect(compiled.provider).not.toMatch(/\bclient(?:Value|Default)\b/)
355 expect(
356 await callProvider(compiled.provider, 'fn', {
357 './server-module': `export const clientValue = 'client'; export const verify = () => 'verified'; export default verify`,
358 }),
359 ).toBe('verified')
360 },
361 )
362​
363 // Source: Next.js server-actions fixtures server-graph/47, /58
364 test('when the handler only reads it through a validator or a middleware', async () => {
365 const compiled =
366 await compileAll(`import { createMiddleware, createServerFn } from '@tanstack/react-start'
367import { db } from './db.server'
368import { schema } from './schema.server'
369const auth = createMiddleware({ type: 'function' })
370 .client(async ({ next }) => next())
371 .server(async ({ next }) => next({ context: { user: await db.user() } }))
372export const fn = createServerFn()
373 .middleware([auth])
374 .validator((data: unknown) => schema.parse(data))
375 .handler(async () => 'ok')`)
376 expect(importSources(compiled.client)).toEqual([])
377 expect(importSources(compiled.provider)).toEqual([
378 './db.server',
379 './schema.server',
380 ])
381 })
382})
383​
384// Source: Next.js server-actions fixtures server-graph/8 (comments in actions)
385test.each([
386 `// uses SERVICE_ROLE_KEY to bypass row level security\n async () => 1,`,
387 `/*! uses SERVICE_ROLE_KEY to bypass row level security */\n async () => 1,`,
388 `/* SERVICE_ROLE_KEY */ async () => 1,`,
389 `async () => 1, // uses SERVICE_ROLE_KEY`,
390])('callers drop the comments around the handler: %s', async (handler) => {
391 const compiled =
392 await compileAll(`${head}export const fn = createServerFn().handler(
393 ${handler}
394)`)
395 for (const caller of [compiled.client, compiled.ssr]) {
396 expect(caller).not.toContain('SERVICE_ROLE_KEY')
397 }
398})
399​
400// Source: @vitejs/plugin-rsc hoist/function-hoist-block.js,
401// scope/param-default-var-hoisting.js, hoist/shadow-partial-if-block-over-global.js,
402// hoist/catch-binding-shadow.js
403test.each([
404 {
405 name: 'past a function declared in a nested block',
406 code: `export function read() {
407 {
408 function store() {}
409 }
410 return store.value
411}`,
412 },
413 {
414 name: 'from a parameter default next to a var of the same name',
415 code: `export function read(value = store.value) {
416 var store = 'local'
417 return value
418}`,
419 },
420 {
421 name: 'after a block that shadows it',
422 code: `export function read() {
423 if (Math.random() > 2) {
424 const store = { value: 'local' }
425 return store.value
426 }
427 return store.value
428}`,
429 },
430 {
431 name: 'in a try block whose catch parameter shadows it',
432 code: `export function read() {
433 try {
434 return store.value
435 } catch (store) {
436 return store
437 }
438}`,
439 },
440])('client code that reads an import $name keeps it', async ({ code }) => {
441 const client = await compileCode(
442 'client',
443 `${head}import { store } from './store'
444import { db } from './db.server'
445export const fn = createServerFn().handler(async () => db.x())
446${code}`,
447 )
448 expect(importSources(client!)).toEqual(['./store'])
449 const module = await evaluateModule(client!, {
450 './store': `export const store = { value: 'store' }`,
451 })
452 expect(module.read()).toBe('store')
453})
454​
455describe('destructurings shared by the handler and client code', () => {
456 // Source: Next.js server-actions fixtures server-graph/6, client-graph/3
457 test.each<{
458 name: string
459 code: string
460 stubs: Record<string, ModuleStub>
461 clientValue: unknown
462 handlerValue: unknown
463 }>([
464 {
465 name: 'an array pattern',
466 code: `import { values } from './values'
467const [serverOnly, shared] = values
468export const clientValue = shared
469export const fn = createServerFn().handler(async () => serverOnly)`,
470 stubs: { './values': `export const values = ['server', 'shared']` },
471 clientValue: 'shared',
472 handlerValue: 'server',
473 },
474 {
475 // Dropping the handler-only `secretKey` would move it into the rest.
476 name: 'an object pattern whose rest the client uses',
477 code: `import { config } from './config'
478const { secretKey, ...publicConfig } = config
479export const clientValue = publicConfig
480export const fn = createServerFn().handler(async () => secretKey)`,
481 stubs: {
482 './config': `export const config = { secretKey: 'key', theme: 'dark' }`,
483 },
484 clientValue: { theme: 'dark' },
485 handlerValue: 'key',
486 },
487 ])(
488 'keep their values in every output for $name',
489 async ({ code, stubs, clientValue, handlerValue }) => {
490 const compiled = await compileAll(`${head}${code}`)
491 const client = await evaluateModule(compiled.client, stubs)
492 expect(client.clientValue).toEqual(clientValue)
493 expect(await callProvider(compiled.provider, 'fn', stubs)).toEqual(
494 handlerValue,
495 )
496 },
497 )
498​
499 // When one binding of a destructuring stays live, the elements of the
500 // handler-only bindings are pruned, including what their default values or
501 // computed keys read.
502 // Source: Next.js server-actions fixtures server-graph/6, /43
503 test.each([
504 {
505 name: 'an object pattern default',
506 code: `import { readSecret } from './secrets.server'
507const { apiKey = readSecret(), theme } = config`,
508 },
509 {
510 name: 'an array pattern default',
511 code: `import { readSecret } from './secrets.server'
512const [apiKey = readSecret(), theme] = config.list`,
513 },
514 {
515 name: 'a computed key',
516 code: `import { secretKeyName } from './secrets.server'
517const { [secretKeyName]: apiKey, theme } = config`,
518 },
519 {
520 name: 'a nested pattern default',
521 code: `import { readSecret } from './secrets.server'
522const { db: { apiKey = readSecret() } = {}, theme } = config`,
523 },
524 ])(
525 'drop a server import read by $name of a handler-only binding',
526 async ({ code }) => {
527 const compiled =
528 await compileAll(`${head}import { config } from './config'
529${code}
530export const fn = createServerFn().handler(async () => apiKey)
531export const currentTheme = theme`)
532 expect(importSources(compiled.client)).toEqual(['./config'])
533 const client = await evaluateModule(compiled.client, {
534 './config': `export const config = { theme: 'dark', list: [undefined, 'dark'] }`,
535 })
536 expect(client.currentTheme).toBe('dark')
537 },
538 )
539})
540​
541describe('declarations only the handler needs', () => {
542 // Source: babel-dead-code-elimination "function" > "declaration",
543 // "variable" > "identifier" and "repeated elimination"; Next.js
544 // server-actions fixtures server-graph/5, /6
545 test.each([
546 {
547 name: 'a class',
548 declarations: `class Repo extends db.Base {
549 static instance = new Repo()
550 find() { return 'found' }
551}`,
552 use: 'Repo.instance.find()',
553 expected: 'found',
554 },
555 {
556 name: 'an overloaded function',
557 declarations: `function Repo(id: string): string
558function Repo(id: number): string
559function Repo(id: any) { return db.x(id) }`,
560 use: 'Repo(1)',
561 expected: 'x1',
562 },
563 {
564 name: 'an enum and a namespace',
565 declarations: `enum Role { Admin = 'admin' }
566namespace Repo {
567 export const conn = db.connect()
568}`,
569 use: '[Role.Admin, Repo.conn]',
570 expected: ['admin', 'connected'],
571 },
572 {
573 name: 'a redeclared var',
574 declarations: `var Repo = db.a()
575var Repo = db.b()`,
576 use: 'Repo',
577 expected: 'b',
578 },
579 ])(
580 'callers drop $name only the handler uses',
581 async ({ declarations, use, expected }) => {
582 const compiled = await compileAll(`${head}import { db } from './db.server'
583${declarations}
584export const fn = createServerFn().handler(async () => ${use})`)
585 for (const caller of [compiled.client, compiled.ssr]) {
586 expect(importSources(caller)).toEqual([])
587 expect(caller).not.toMatch(/\b(?:Repo|Role)\b/)
588 }
589 expect(
590 await callProvider(compiled.provider, 'fn', {
591 './db.server': `export const db = {
592 Base: class {},
593 x: (id) => 'x' + id,
594 connect: () => 'connected',
595 a: () => 'a',
596 b: () => 'b',
597}`,
598 }),
599 ).toEqual(expected)
600 },
601 )
602​
603 // Source: React Compiler fixture context-variable-as-jsx-element-tag.js
604 test('callers drop a handler-only function that declares a local of its own name', async () => {
605 const compiled =
606 await compileAll(`${head}import { readSecret } from './server-only'
607function Report() {
608 let Report = readSecret()
609 return <Report />
611export const getReport = createServerFn().handler(async () => Report())`)
612 for (const caller of [compiled.client, compiled.ssr]) {
613 expect(importSources(caller)).toEqual([])
614 expect(caller).not.toContain('readSecret')
615 }
616 })
617​
618 // Source: babel-dead-code-elimination "SCC dead code elimination" (mutual
619 // recursion, self-recursive functions, unexported circular references)
620 test('callers drop handler-only cycles and default parameters but keep cycles nothing used', async () => {
621 const compiled =
622 await compileAll(`${head}import { secret, defaultId } from './secret.server'
623function walk(n: number): number { return n > 0 ? walkBack(n - 1) : secret.length }
624function walkBack(n: number): number { return n > 0 ? walk(n - 1) : 0 }
625const loop = (n: number): number => (n > 0 ? loop(n - 1) : 0)
626function load(id = defaultId()) { return id }
627function unusedA(): number { return unusedB() }
628function unusedB(): number { return unusedA() }
629export const fn = createServerFn().handler(async () => [walk(3), loop(2), load()])`)
630 for (const caller of [compiled.client, compiled.ssr]) {
631 expect(importSources(caller)).toEqual([])
632 for (const name of ['walk', 'walkBack', 'loop', 'load']) {
633 expect(caller).not.toMatch(declarationOf(name))
634 }
635 }
636 for (const name of ['walk', 'walkBack', 'loop', 'load']) {
637 expect(compiled.provider).toMatch(declarationOf(name))
638 }
639 for (const output of [compiled.client, compiled.ssr, compiled.provider]) {
640 expect(output).toMatch(declarationOf('unusedA'))
641 expect(output).toMatch(declarationOf('unusedB'))
642 }
643 })
644​
645 // Source: babel-dead-code-elimination "assignment"
646 test('callers keep handler-read bindings that top-level statements assign', async () => {
647 const compiled = await compileAll(`${head}let x: string
648x = 'x-assigned'
649y = 'y-assigned'
650var y: string
651export const fn = createServerFn().handler(async () => [x, y])`)
652 // An assignment left without its declaration throws in a module.
653 await evaluateModule(compiled.client)
654 await evaluateModule(compiled.ssr)
655 expect(await callProvider(compiled.provider, 'fn')).toEqual([
656 'x-assigned',
657 'y-assigned',
658 ])
659 })
660​
661 // Source: babel-dead-code-elimination "repeated elimination"
662 test('callers drop a binding only the handler writes and keep a declarator a kept sibling reads', async () => {
663 const compiled =
664 await compileAll(`${head}import { serverValue } from './db.server'
665let hits = 0
666let a = serverValue(), clientCopy = a
667export const fn = createServerFn().handler(async () => {
668 hits++
669 return a
670})
671export const clientB = clientCopy`)
672 for (const caller of [compiled.client, compiled.ssr]) {
673 expect(caller).not.toMatch(declarationOf('hits'))
674 expect(caller).toMatch(declarationOf('a'))
675 expect(importSources(caller)).toEqual(['./db.server'])
676 }
677 expect(compiled.provider).toMatch(declarationOf('hits'))
678 expect(compiled.provider).not.toContain('clientCopy')
679 })
680​
681 // Source: babel-dead-code-elimination "variable" > "within for...in",
682 // "within for...of" (var bindings declared inside nested statements)
683 test('callers drop handler-only vars declared inside top-level statements', async () => {
684 const calls = ['openFlag', 'connect', 'readMode', 'readLabel', 'createPool']
685 const compiled =
686 await compileAll(`${head}import { ${calls.join(', ')} } from './db.server'
687if (typeof window === 'undefined') {
688 var flag = openFlag()
690try {
691 var conn = connect()
692} catch {}
693switch (process.env.MODE) {
694 case 'x':
695 var mode = readMode()
697outer: {
698 var labeled = readLabel()
699 break outer
701for (var i = 0, pool = createPool(); i < 1; i++) {}
702export const fn = createServerFn().handler(async () => [flag, conn, mode, labeled, pool])`)
703 for (const caller of [compiled.client, compiled.ssr]) {
704 expect(importSources(caller)).toEqual([])
705 for (const call of calls) {
706 expect(caller).not.toContain(call)
707 }
708 }
709 for (const call of calls) {
710 expect(compiled.provider).toContain(`${call}()`)
711 }
712 })
713})