Open History to see the last commit
1import { describe, expect, it } from 'vitest'
2import {
3 buildAndRun,
4 compileRouteModules,
5 declarationOf,
6 expectValidModules,
7 head,
8 importSources,
9 loadRouteModules,
10 renderEntry,
11} from './regression-helpers'
12β
13/** Stubs `./state`, counting the calls of `init`. */
14function stateStub() {
15 const state = {
16 calls: 0,
17 init: <T>(value: T) => {
18 state.calls++
19 return value
20 },
21 }
22 return state
23}
24β
25/** How many times `pattern` occurs across all emitted modules. */
26function countAcrossModules(modules: Record<string, string>, pattern: RegExp) {
27 return Object.values(modules).reduce(
28 (count, code) =>
29 count + (code.match(new RegExp(pattern.source, 'g'))?.length ?? 0),
30 0,
31 )
32}
33β
34describe('split chunks keep the module state the route relies on', () => {
35 // Route files commonly export a store or helpers over private state next to
36 // the route and use them from the route component as well.
37 it('renders a split component using exported bindings over private state like the unsplit route', async () => {
38 const result = await buildAndRun(
39 `${head}const state = { count: 0 }
40export function increment() {
41 return ++state.count
42}
43let renders = 0
44export function getRenders() {
45 return renders
46}
47const initial = 0
48export const store = { count: initial }
49function Page() {
50 increment()
51 renders++
52 store.count++
53 return <p>{[state.count, getRenders(), store.count - initial].join('/')}</p>
54}
55export const Route = createFileRoute('/')({ component: Page })
56`,
57 `const component = entry.Route.options.component
58return [await entry.render(component), await entry.render(component), entry.store.count]`,
59 )
60 // Known limitation: the chunk gets its own copy of `state` and `renders`,
61 // so callers of the exported functions are not checked here.
62 // `store.count` is 2: the chunk mutated the store the route module exports
63 expect(result).toEqual(['<p>1/1/1</p>', '<p>2/2/2</p>', 2])
64 }, 30_000)
65β
66 // A declaration the loader and a split component both read runs once, with
67 // the route module, before any chunk loads; TypeScript enums and namespaces
68 // compile to such declarations too.
69 it.each([
70 {
71 name: 'a const',
72 declaration: `const value = init(1)
73const read = () => value`,
74 },
75 {
76 name: 'an enum',
77 declaration: `enum Value { One = init(1) }
78const read = () => Value.One`,
79 },
80 {
81 name: 'a namespace',
82 declaration: `namespace Value { export const one = init(1) }
83const read = () => Value.one`,
84 },
85 ])(
86 'initializes $name read by the loader and the split component once',
87 async ({ declaration }) => {
88 const state = stateStub()
89 let callsBeforeChunks: number | undefined
90 const { options, chunks } = await loadRouteModules(
91 `${head}import { init } from './state'
92${declaration}
93export const Route = createFileRoute('/')({
94 loader: () => read(),
95 component: () => <p>{read()}</p>,
96 errorComponent: () => <p>error</p>,
97})`,
98 { './state': state },
99 () => {
100 callsBeforeChunks = state.calls
101 },
102 )
103 expect([
104 options.loader(),
105 chunks.component!.component(),
106 chunks.errorComponent!.errorComponent(),
107 callsBeforeChunks,
108 state.calls,
109 ]).toEqual([1, '<p>1</p>', '<p>error</p>', 1, 1])
110 },
111 )
112β
113 // Source: Next.js ssg/getStaticProps/should-support-export-named-as-default-with-other-specifiers
114 it.each([
115 {
116 name: 'export { store as appStore }',
117 exports: 'export { store as appStore }',
118 read: 'entry.appStore',
119 entry: '',
120 },
121 {
122 name: 'export default store',
123 exports: 'export default store',
124 read: 'entry.default',
125 entry: `export { default } from './routes/index'\n`,
126 },
127 ])(
128 'shares one store exported as $name with the split component',
129 async ({ exports, read, entry }) => {
130 const result = await buildAndRun(
131 `${head}import { createStore } from '../store'
132const store = createStore()
133${exports}
134export const Route = createFileRoute('/')({
135 component: () => <p>{store.count}</p>,
136})`,
137 `${read}.count = 5
138const html = await entry.render(entry.Route.options.component)
139return [html, globalThis.stores]`,
140 {
141 files: {
142 'store.ts': `export function createStore() {
143 ;(globalThis as any).stores = ((globalThis as any).stores ?? 0) + 1
144 return { count: 0 }
145}`,
146 'entry.ts': `${renderEntry}${entry}`,
147 },
148 },
149 )
150 expect(result).toEqual(['<p>5</p>', 1])
151 },
152 30_000,
153 )
154β
155 // Source: Next.js ssg/getStaticProps/should-not-remove-import-used-in-render
156 it('shares a binding the loader reads and the component renders as a JSX member tag', async () => {
157 const result = await buildAndRun(
158 `${head}import { createUi } from '../ui'
159const ui = createUi()
160export const Route = createFileRoute('/')({
161 loader: () => typeof ui.Box,
162 component: () => <ui.Box />,
163})`,
164 `const html = await entry.render(entry.Route.options.component)
165return [html, globalThis.uis]`,
166 {
167 files: {
168 'ui.tsx': `export function createUi() {
169 ;(globalThis as any).uis = ((globalThis as any).uis ?? 0) + 1
170 return { Box: () => <p>box</p> }
171}`,
172 },
173 },
174 )
175 expect(result).toEqual(['<p>box</p>', 1])
176 }, 30_000)
177β
178 // Source: Qwik optimizer test.rs
179 // should_keep_non_migrated_binding_from_shared_destructuring_declarator_with_default (+ _with_rest)
180 it('evaluates a destructuring split between the loader and the component once', async () => {
181 const { modules } =
182 compileRouteModules(`${head}import { makeConfig } from './config'
183const { a = 'A', ...b } = makeConfig()
184export const Route = createFileRoute('/')({
185 loader: () => a,
186 component: () => <div>{JSON.stringify(b)}</div>,
187})
188`)
189 expect(countAcrossModules(modules, /makeConfig\(\)/)).toBe(1)
190 await expectValidModules(modules)
191 })
192β
193 // Source: Qwik optimizer test.rs root_level_self_referential_qrl,
194 // example_self_referential_component_migration
195 it('declares mutually recursive components used by two lazy chunks once', async () => {
196 const { modules } =
197 compileRouteModules(`${head}function A({ depth }) { return depth ? <B depth={depth - 1} /> : <i>a</i> }
198function B({ depth }) { return <b><A depth={depth} /></b> }
199export const Route = createFileRoute('/')({
200 component: () => <A depth={1} />,
201 errorComponent: () => <B depth={0} />,
202})
203`)
204 expect(countAcrossModules(modules, /function A\b/)).toBe(1)
205 expect(countAcrossModules(modules, /function B\b/)).toBe(1)
206 await expectValidModules(modules)
207 })
208β
209 it('shares a class with a static block and private members', async () => {
210 const { modules, sharedBindings } =
211 compileRouteModules(`${head}class Counter {
212 static created = 0
213 static { Counter.created = 1 }
214 #n = 0
215 increment() { return ++this.#n }
216 static owns(value: object) { return #n in value }
217}
218const counter = new Counter()
219export const Route = createFileRoute('/')({
220 loader: () => counter.increment(),
221 component: () => <div>{String(Counter.owns(counter))}</div>,
222})
223`)
224 expect(sharedBindings).toEqual(['Counter', 'counter'])
225 expect(modules['virtual component']).not.toMatch(declarationOf('Counter'))
226 await expectValidModules(modules)
227 })
228β
229 // Source: Turbopack tree-shaker analyzer/nanoid, analyzer/let-bug-1
230 it('shares a let that a shared helper reassigns', async () => {
231 const { modules, sharedBindings } =
232 compileRouteModules(`${head}let pool: Array<number> = [], offset = 0
233const fill = () => { pool = [offset++] }
234export const Route = createFileRoute('/')({
235 loader: () => { fill(); return pool },
236 component: () => { fill(); return <p>{pool.join()}</p> },
237})
238`)
239 expect(sharedBindings).toEqual(['fill', 'offset', 'pool'])
240 expect(modules.reference).not.toMatch(declarationOf('pool'))
241 expect(modules['virtual component']).not.toMatch(declarationOf('pool'))
242 await expectValidModules(modules)
243 })
244})
245β
246describe('split chunks keep reassigned bindings next to their writers', () => {
247 // Source: React Router route-chunks-test.ts "reassignment"; babel-dead-code-elimination
248 // find-removable-bindings.test.ts "constant violations mark as external"
249 it('moves a binding that only the split component reassigns into its chunk', async () => {
250 const { modules, sharedBindings } =
251 compileRouteModules(`${head}import { next } from './next'
252let current = 'initial-marker'
253export const Route = createFileRoute('/')({
254 loader: () => 'data',
255 component: () => {
256 current = next
257 return <p>{current}</p>
258 },
259})
260`)
261 expect(sharedBindings).toEqual([])
262 expect(modules.reference).not.toContain('initial-marker')
263 expect(importSources(modules.reference!)).not.toContain('./next')
264 expect(modules['virtual component']).toMatch(declarationOf('current'))
265 expect(modules['virtual component']).toContain('initial-marker')
266 await expectValidModules(modules)
267 })
268β
269 // Source: Next.js ssg/getStaticProps/should-support-babel-style-memoized-function
270 it.each([
271 { name: 'the component', loader: `'data'`, shared: [] },
272 {
273 name: 'the loader and the component',
274 loader: 'fetchData()',
275 shared: ['fetchData'],
276 },
277 ])(
278 'keeps a self-reassigning function used by $name valid',
279 async ({ loader, shared }) => {
280 const { modules, sharedBindings } =
281 compileRouteModules(`${head}function fetchData() {
282 fetchData = function () {
283 return 'memoized'
284 }
285 return fetchData.apply(this, arguments as any)
286}
287export const Route = createFileRoute('/')({
288 loader: () => ${loader},
289 component: () => <div>{fetchData()}</div>,
290})
291`)
292 expect(sharedBindings).toEqual(shared)
293 const owner = shared.length
294 ? modules.shared!
295 : modules['virtual component']!
296 expect(owner).toMatch(declarationOf('fetchData'))
297 expect(owner).toContain('fetchData = function')
298 await expectValidModules(modules)
299 },
300 )
301})
302β
303describe('split components see the top-level writes to what they read', () => {
304 // Source: React Router route-chunks-test.ts "reassignment with nullish
305 // coalescing" and "destructured reassignment"
306 it('renders bindings reassigned at the top level with their final values', async () => {
307 const result = await buildAndRun(
308 `${head}let plain = 'initial'
309plain = 'assigned'
310let compound = 1
311compound += 1
312let logical = ''
313logical ||= 'logical'
314let handler: (() => string) | undefined
315handler ??= () => 'handler'
316let swapped = () => 'original'
317;[swapped] = [() => 'swapped']
318export const Route = createFileRoute('/')({
319 component: () => <p>{[plain, compound, logical, handler!(), swapped()].join(' ')}</p>,
320})`,
321 `return await entry.render(entry.Route.options.component)`,
322 )
323 expect(result).toBe('<p>assigned 2 logical handler swapped</p>')
324 }, 30_000)
325β
326 // Source: Turbopack tree-shaker analyzer/assign-before-decl-var and
327 // analyzer/assign-before-decl-fn
328 it.each([
329 {
330 name: 'a var',
331 setup: `value = 'assigned'
332var value: string`,
333 render: '{value}',
334 html: '<p>assigned</p>',
335 },
336 {
337 name: 'a function declaration',
338 setup: `value = () => 'reassigned'
339function value() {
340 return 'declared'
341}`,
342 render: '{value()}',
343 html: '<p>reassigned</p>',
344 },
345 ])(
346 'renders $name assigned before its hoisted declaration',
347 async ({ setup, render, html }) => {
348 const result = await buildAndRun(
349 `${head}${setup}
350export const Route = createFileRoute('/')({
351 component: () => <p>${render}</p>,
352})`,
353 `return await entry.render(entry.Route.options.component)`,
354 )
355 expect(result).toBe(html)
356 },
357 30_000,
358 )
359β
360 // Source: React Router remove-exports-test.ts "function statement with
361 // property assignment"
362 it('renders a split component that has properties assigned at the top level', async () => {
363 const result = await buildAndRun(
364 `${head}function Page() {
365 return <p>{(Page as any).label}</p>
366}
367;(Page as any).label = 'page'
368export const Route = createFileRoute('/')({
369 loader: () => 'data',
370 component: Page,
371})`,
372 `return await entry.render(entry.Route.options.component)`,
373 )
374 expect(result).toBe('<p>page</p>')
375 }, 30_000)
376})