diff --git a/.changeset/pure-framework-calls.md b/.changeset/pure-framework-calls.md index 0ebd70240c..ab3eb3041c 100644 --- a/.changeset/pure-framework-calls.md +++ b/.changeset/pure-framework-calls.md @@ -4,6 +4,6 @@ '@tanstack/router-utils': patch --- -React's `memo`, `forwardRef` and `lazy`, Solid's `lazy`, and Vue's `defineComponent` and `defineAsyncComponent` are known to have no side effects when called with arguments that have none, like the router's own APIs (`getRouteApi` & co.): a top-level `const Page = memo(Inner)` or `const Panel = defineComponent({ … })` only split code reads loads with its chunk even when a call that stays in the route module follows it (an inline `validateSearch: z.object({ … })`), instead of staying in the route module with a warning. They count when imported from the framework package itself, also under another name or as a namespace member (`import * as React from 'react'`); a re-export through one of the app's modules and a member of a default import (`import React from 'react'`) do not. Import protection counts a module whose top level only makes such calls as one without side effects. +React's `memo`, `forwardRef` and `lazy`, Solid's `lazy`, and Vue's `defineComponent` and `defineAsyncComponent` are known to have no side effects when called with arguments that have none, like the router's own APIs (`getRouteApi` & co.): a top-level `const Page = memo(Inner)` or `const Panel = defineComponent({ … })` only split code reads loads with its chunk even when a call that stays in the route module follows it (an inline `validateSearch: z.object({ … })`), instead of staying in the route module with a warning. They count when imported from the framework package itself, also under another name, as a namespace member (`import * as React from 'react'`) or as a member of React's default import (`import React from 'react'`; React's default export is the package itself); a re-export through one of the app's modules does not. Import protection counts a module whose top level only makes such calls as one without side effects. -In a TanStack Start client build, server-function, middleware and isomorphic-function builder chains with arguments that have no side effects (the arguments the client build removes do not count) are no side effect either: a page-only `createServerFn()…handler(…)` or `createMiddleware(…).client(…)` loads with the split chunk instead of staying in the route module with a warning. A link called on a `const` holding a builder stays a side effect, and the server build is unchanged. +In TanStack Start's client and server builds, server-function, middleware, isomorphic-function and server-only/client-only function builder chains with arguments that have no side effects (the arguments that build removes do not count) are no side effect either: a page-only `createServerFn()…handler(…)`, `createMiddleware(…).client(…)` or `createIsomorphicFn()…` loads with the split chunk instead of staying in the route module with a warning, and both builds agree, so a server function nested in a function may take such a chain in its options (`.middleware([createMiddleware(…).server(…)])`): it builds and runs instead of failing the server build. A link called on a `const` holding a builder stays a side effect. diff --git a/docs/router/guide/automatic-code-splitting.md b/docs/router/guide/automatic-code-splitting.md index 8b022be7f6..210ccaafc8 100644 --- a/docs/router/guide/automatic-code-splitting.md +++ b/docs/router/guide/automatic-code-splitting.md @@ -117,9 +117,9 @@ create that value in a `const` before `confetti`, or mark the call `/* @__PURE__ effects, so `confetti` can load with the split `component`. (src/routes/account.tsx:12:7) ``` -A call the compiler knows to have no side effects is no side effect here: it neither stays for this reason nor keeps a declaration before it. These are TanStack Router's `getRouteApi`, `linkOptions`, `createLink`, `createRouteMask`, `lazyRouteComponent`, `lazyFn`, `retainSearchParams`, `stripSearchParams`, `parseSearchWith`, `stringifySearchWith` and `createRouterConfig` (React and Vue), React's `memo`, `forwardRef` and `lazy`, Solid's `lazy`, and Vue's `defineComponent` and `defineAsyncComponent`, called with arguments that have no side effects and imported from the package itself: a renamed import and a namespace member (`React.memo` after `import * as React from 'react'`) count, a re-export through one of the app's modules and a member of a default import (`import React from 'react'`) do not. So `const Page = memo(Inner)` or `const Panel = defineComponent({ … })` above `validateSearch: z.object({ … })` loads with the split `component`. +A call the compiler knows to have no side effects is no side effect here: it neither stays for this reason nor keeps a declaration before it. These are TanStack Router's `getRouteApi`, `linkOptions`, `createLink`, `createRouteMask`, `lazyRouteComponent`, `lazyFn`, `retainSearchParams`, `stripSearchParams`, `parseSearchWith`, `stringifySearchWith` and `createRouterConfig` (React and Vue), React's `memo`, `forwardRef` and `lazy`, Solid's `lazy`, and Vue's `defineComponent` and `defineAsyncComponent`, called with arguments that have no side effects and imported from the package itself: a renamed import, a namespace member (`React.memo` after `import * as React from 'react'`) and a member of React's default import (`import React from 'react'`) count, a re-export through one of the app's modules does not. So `const Page = memo(Inner)` or `const Panel = defineComponent({ … })` above `validateSearch: z.object({ … })` loads with the split `component`. -In a TanStack Start app's client build, the builder chains of server functions, middleware and isomorphic functions (`createServerFn(…)…handler(…)`, `createMiddleware(…).client(…)`, `createIsomorphicFn()…`) have no side effects either when their arguments have none; the arguments the client build removes (a handler, a validator, a middleware's `server`) do not count. A link called on a `const` that holds a builder (`const base = createMiddleware(…)`, then `base.client(…)`) is a side effect: a middleware's links change the builder they are called on. The server build keeps these chains in order, so it can still report an isomorphic function only split code reads. +In a TanStack Start app's client and server builds, the builder chains of server functions, middleware, isomorphic functions and server-only or client-only functions (`createServerFn(…)…handler(…)`, `createMiddleware(…).client(…)`, `createIsomorphicFn()…`, `createServerOnlyFn(…)`) have no side effects either when their arguments have none; the arguments a build removes (on the client a handler, a validator, a middleware's `server`) do not count. A link called on a `const` that holds a builder (`const base = createMiddleware(…)`, then `base.client(…)`) is a side effect: a middleware's links change the builder they are called on. Each builder still exists once per environment: two split chunks reading one share the module that holds it. Every host prints the file and one position: a Vite build at the end of the message, as above (line and column counted from 1); the Vite dev server in its own `File:` line and code frame, mapped to the file as written; Rsbuild, Rspack and webpack in their own header (`File: ./src/routes/account.tsx:12:7`, `WARNING in ./src/routes/account.tsx 12:7`). diff --git a/packages/router-plugin/src/hosts/session.ts b/packages/router-plugin/src/hosts/session.ts index e07e219ec4..ce6cc85e6e 100644 --- a/packages/router-plugin/src/hosts/session.ts +++ b/packages/router-plugin/src/hosts/session.ts @@ -122,7 +122,7 @@ export class RouterCompiler { readFile: (p) => fs.promises.readFile(p, 'utf8').catch(() => null), loadVirtual: () => Promise.resolve(null), // the router's and the frameworks' pure APIs - recognizer: { ...EMPTY_RECOGNIZER, pureCalls: knownPureCalls() }, + recognizer: { ...EMPTY_RECOGNIZER, ...knownPureCalls() }, }) this.caches = createCompilerCaches( rawFacts, diff --git a/packages/router-plugin/src/planners/pure-calls.ts b/packages/router-plugin/src/planners/pure-calls.ts index d5d9ff858a..ab3e93221b 100644 --- a/packages/router-plugin/src/planners/pure-calls.ts +++ b/packages/router-plugin/src/planners/pure-calls.ts @@ -1,8 +1,11 @@ +import type { RecognizerTable } from '@tanstack/router-utils/compiler' + /** * The package exports whose call is pure when its arguments are * (`RecognizerTable.pureCalls`), for every host of the router planner and * Start's: the core recognises them by import binding from these packages - * (renamed, or a namespace member; app re-exports are not followed), so a + * (renamed, a namespace member, or a member of React's default import; app + * re-exports are not followed), so a * module-level declaration they create is no effect and loads with the * split code that reads it. Each was read in the package's source, * development builds included: the call constructs and returns a value, @@ -33,30 +36,42 @@ const ROUTER_EXPORTS = [ 'stringifySearchWith', ] -let pureCalls: Record> | null = null +type PureCallTable = Required< + Pick +> -/** `RecognizerTable.pureCalls`: the router's and the frameworks' pure exports, one table for every host. */ -export function knownPureCalls(): Record> { - pureCalls ??= { - '@tanstack/react-router': new Set([ - ...ROUTER_EXPORTS, - 'createRouterConfig', - ]), - '@tanstack/solid-router': new Set(ROUTER_EXPORTS), - '@tanstack/vue-router': new Set([...ROUTER_EXPORTS, 'createRouterConfig']), - // the frameworks' component wrappers: React `memo` and `forwardRef` return - // an element type (development warns on an invalid argument, stateless, and - // reads only its `length`, `defaultProps` or `$$typeof`); `lazy` (React, - // Solid) and Vue's `defineAsyncComponent` wrap a loader they call on first - // render; Vue's `defineComponent` returns its options (or wraps a setup - // function, reading its `name`). Not pure: `createContext` (React, Solid: - // two instances are two contexts), `createRef`, React's `cache` (its - // identity keys the cache), Solid's signals, stores and computations, Vue's - // `ref`/`reactive` & co. (state), `markRaw` (writes its argument), `h` - // (reads the current render instance), `defineCustomElement` (a class). - react: new Set(['memo', 'forwardRef', 'lazy']), - 'solid-js': new Set(['lazy']), - vue: new Set(['defineComponent', 'defineAsyncComponent']), +let table: PureCallTable | null = null + +/** The router's and the frameworks' pure exports, one table for every host (`RecognizerTable.pureCalls`). */ +export function knownPureCalls(): PureCallTable { + table ??= { + pureCalls: { + '@tanstack/react-router': new Set([ + ...ROUTER_EXPORTS, + 'createRouterConfig', + ]), + '@tanstack/solid-router': new Set(ROUTER_EXPORTS), + '@tanstack/vue-router': new Set([ + ...ROUTER_EXPORTS, + 'createRouterConfig', + ]), + // the frameworks' component wrappers: React `memo` and `forwardRef` return + // an element type (development warns on an invalid argument, stateless, and + // reads only its `length`, `defaultProps` or `$$typeof`); `lazy` (React, + // Solid) and Vue's `defineAsyncComponent` wrap a loader they call on first + // render; Vue's `defineComponent` returns its options (or wraps a setup + // function, reading its `name`). Not pure: `createContext` (React, Solid: + // two instances are two contexts), `createRef`, React's `cache` (its + // identity keys the cache), Solid's signals, stores and computations, Vue's + // `ref`/`reactive` & co. (state), `markRaw` (writes its argument), `h` + // (reads the current render instance), `defineCustomElement` (a class). + react: new Set(['memo', 'forwardRef', 'lazy']), + 'solid-js': new Set(['lazy']), + vue: new Set(['defineComponent', 'defineAsyncComponent']), + }, + // React is CommonJS without `__esModule`: every bundler binds its + // default import to its exports (Vue and Solid have no default export) + pureDefaultNamespaces: new Set(['react']), } - return pureCalls + return table } diff --git a/packages/router-utils/src/compiler/README.md b/packages/router-utils/src/compiler/README.md index e2b05bf260..6a45cfad11 100644 --- a/packages/router-utils/src/compiler/README.md +++ b/packages/router-utils/src/compiler/README.md @@ -190,7 +190,8 @@ directives, never license comments. `#__NO_SIDE_EFFECTS__` in the module, or is a known package's export the recognizer lists in `pureCalls` (audited APIs of TanStack's router packages, e.g. `getRouteApi`, and of the frameworks, e.g. React `memo`, Vue `defineComponent`; the router planners own the table, Start's recognizer reuses it). - Tier 0 recognises imports of such an export from the package itself by binding (renamed, or a namespace member); + Tier 0 recognises imports of such an export from the package itself by binding (renamed, a namespace member, or a + member of a default import the recognizer lists in `pureDefaultNamespaces`: React's, a CommonJS package's exports); an app module re-exporting it is not followed, and no other package's purity is assumed. A member of a namespace import (`Icons.Home` of `import * as Icons`) is a pure read: a module namespace's [[Get]] reads the module's binding and runs no code, as an imported identifier does. So is a member of a plain enum of the module (`E.A`, a data property): diff --git a/packages/router-utils/src/compiler/analysis.ts b/packages/router-utils/src/compiler/analysis.ts index 41e63e7751..d88896afdb 100644 --- a/packages/router-utils/src/compiler/analysis.ts +++ b/packages/router-utils/src/compiler/analysis.ts @@ -293,18 +293,25 @@ interface ModuleAnalysisOptions { path: string /** Bare import specifiers that mark a module (default: 'server-only' / 'client-only'). */ markerSpecifiers?: Record - /** The pure exports of known packages (`RecognizerTable.pureCalls`): their imports are pure callees. */ - pureCalls?: RecognizerTable['pureCalls'] /** - * A client compile's recognizer: its builder chains with pure arguments - * are no effect in the planners' purity (`builderCall`; what the client - * compile erases does not count). A link called on a `const` holding a - * builder stays an effect: a middleware's links write the options of the - * builder they are called on, which another link of it then reads. The - * server compile's purity takes none: its server-fn provider copies what - * it reaches, and a builder has an identity. + * The recognizer: the pure exports of its known packages + * (`RecognizerTable.pureCalls`, members of the default imports of + * `pureDefaultNamespaces`) are pure callees. */ - clientBuilders?: RecognizerTable + recognizer?: RecognizerTable + /** + * A compile's environment type: the planners' purity takes the + * recognizer's builder chains with pure arguments as no effect there + * (`builderCall`; what that environment's compile erases does not count). + * Both types take them, so both compiles home a builder alike. A builder + * is one instance in every output of an environment: a call result is + * never copied (the server-fn provider, the module's instance in another + * layer, copies what it reaches whatever its purity). A link called on a + * `const` holding a builder stays an effect: a middleware's links write + * the options of the builder they are called on, which another link of it + * then reads. Raw reads give none (`effects()` derives each one's). + */ + env?: 'client' | 'server' } /** Per environment type, whether a module's own statements have effects there. */ @@ -352,7 +359,7 @@ export class ModuleAnalysis { readonly markers: Marker readonly sourceType: 'module' | 'script' | 'commonjs' readonly hasImportOrExport: boolean - /** The planners' purity (with a client compile's builder chains: `clientBuilders`). */ + /** The planners' purity (with a compile's builder chains: `env`). */ readonly purity: PurityContext /** The purity of the module's own statements, whatever the environment (`effects()` derives each one's). */ private readonly ownPurity: PurityContext @@ -381,7 +388,8 @@ export class ModuleAnalysis { const noSideEffectCallees = new Set() const pureNamespaces = new Map>() let namespaceImports: Set | null = null - const pureCalls = opts.pureCalls + const pureCalls = opts.recognizer?.pureCalls + const pureDefaults = opts.recognizer?.pureDefaultNamespaces const markers = opts.markerSpecifiers ?? DEFAULT_MARKERS this.markerSpecifiers = markers const imports: Array = [] @@ -411,7 +419,11 @@ export class ModuleAnalysis { // statement is classified (a call may precede its hoisted import) const pure = pureCalls && ownEntry(pureCalls, record.specifier) if (pure && !record.typeOnly) { - if (record.kind === 'namespace') { + if ( + record.kind === 'namespace' || + (record.name === 'default' && + pureDefaults?.has(record.specifier) === true) + ) { pureNamespaces.set(local.id, pure) } else if ( record.kind === 'named' && @@ -444,12 +456,13 @@ export class ModuleAnalysis { const body = file.program.body seedNoSideEffectDeclarations(ownPurity, noSideEffectCallees, body) this.ownPurity = ownPurity - const client = opts.clientBuilders?.builderLinks - ? builderPurityOf(ownPurity, opts.clientBuilders)?.find( - (p) => p.env === 'client', - ) - : undefined - this.purity = client?.ctx ?? ownPurity + const envPurity = + opts.env && opts.recognizer?.builderLinks + ? builderPurityOf(ownPurity, opts.recognizer)?.find( + (p) => p.env === opts.env, + ) + : undefined + this.purity = envPurity?.ctx ?? ownPurity for (let i = this.header.directiveCount; i < body.length; i++) { const stmt = body[i]! switch (stmt.type) { @@ -702,8 +715,8 @@ export class ModuleAnalysis { * The module's own effects, classified statement by statement (raw facts * ask, for a module read as a target; a compile never does). `builders`: * the recognizer whose builder chains are no effect per environment - * (`RecognizerTable.builderLinks`; the planners' purity takes the client's - * in a client compile: `clientBuilders`). + * (`RecognizerTable.builderLinks`; the planners' purity takes the + * compile's environment's: `env`). */ effects(builders?: RecognizerTable): ModuleEffects { const file = this.file diff --git a/packages/router-utils/src/compiler/facts.ts b/packages/router-utils/src/compiler/facts.ts index 97cf3eb8ef..84542ee211 100644 --- a/packages/router-utils/src/compiler/facts.ts +++ b/packages/router-utils/src/compiler/facts.ts @@ -161,14 +161,9 @@ export class RawFactsCache { return this.opts.markerSpecifiers } - /** The pure exports of the recognizer's known packages, for the analyses of compiled modules. */ - get pureCalls(): RecognizerTable['pureCalls'] { - return this.opts.recognizer?.pureCalls - } - - /** The recognizer when it has builder chains, for the analyses of client compiles (`clientBuilders`). */ - get builders(): RecognizerTable | undefined { - return this.opts.recognizer?.builderLinks ? this.opts.recognizer : undefined + /** The recognizer every analysis of this session uses (its pure calls; a compile's builder chains). */ + get recognizer(): RecognizerTable | undefined { + return this.opts.recognizer } markStale(path: string): void { @@ -587,7 +582,7 @@ export class RawFactsCache { const analysis = new ModuleAnalysis(parsed.file, parsed.source, { path: id.path, markerSpecifiers: this.opts.markerSpecifiers, - pureCalls: this.opts.recognizer?.pureCalls, + recognizer: this.opts.recognizer, }) return this.fromAnalysis(analysis) } diff --git a/packages/router-utils/src/compiler/pipeline.ts b/packages/router-utils/src/compiler/pipeline.ts index 9ffde5ac15..3b36c63ecf 100644 --- a/packages/router-utils/src/compiler/pipeline.ts +++ b/packages/router-utils/src/compiler/pipeline.ts @@ -425,8 +425,8 @@ async function runAttempt( const t0 = new ModuleAnalysis(parsed.file, parsed.source, { path: identity.path, markerSpecifiers: host.rawFacts.markerSpecifiers, - pureCalls: host.rawFacts.pureCalls, - clientBuilders: env.type === 'client' ? host.rawFacts.builders : undefined, + recognizer: host.rawFacts.recognizer, + env: env.type, }) const cjs = t0.sourceType !== 'module' || isCommonJsPath(identity.path) const gateCtx = (p: Planner) => ({ diff --git a/packages/router-utils/src/compiler/purity.ts b/packages/router-utils/src/compiler/purity.ts index 2b44c1c07b..860c8cc1d3 100644 --- a/packages/router-utils/src/compiler/purity.ts +++ b/packages/router-utils/src/compiler/purity.ts @@ -4,7 +4,8 @@ * templates, `/*#__PURE__*\/` calls with pure arguments, calls with pure * arguments of `#__NO_SIDE_EFFECTS__` callee declarations and of the pure * exports of known packages (`RecognizerTable.pureCalls`: by import - * binding or namespace member; re-exports are not followed), JSX with bound/intrinsic tags and + * binding, namespace member or a member of a default import that is the + * package's namespace, `pureDefaultNamespaces`; re-exports are not followed), JSX with bound/intrinsic tags and * pure attributes and children, and a member of a module namespace import (`ns.x`: its [[Get]] * reads the module's binding and runs no code, as an imported identifier does) or of a * plain enum of the module (`isPlainEnum`; a property of any other object may be a getter). @@ -33,7 +34,7 @@ export interface PurityContext { * known package. */ noSideEffectCallees: ReadonlySet - /** Namespace imports (binding ids) of known packages → their pure exports. */ + /** Namespace imports (binding ids) of known packages, and default imports that are their namespace (`pureDefaultNamespaces`) → their pure exports. */ pureNamespaces: ReadonlyMap> /** Value namespace imports (binding ids): `import * as ns from '…'`. */ namespaceImports: ReadonlySet @@ -43,8 +44,8 @@ export interface PurityContext { * Builder chains whose calls are no effect in one environment * (`RecognizerTable.builderLinks`): on the contexts of the * per-environment code effects of raw facts (`ModuleAnalysis.effects()`) - * and on the planners' of a client compile (`clientBuilders`, where no - * `locals` are noted). + * and on the planners' of a compile, for its environment type + * (`ModuleAnalysisOptions.env`, where no `locals` are noted). */ builders?: BuilderPurity } diff --git a/packages/router-utils/src/compiler/values.ts b/packages/router-utils/src/compiler/values.ts index 073525d98a..f0a7db5144 100644 --- a/packages/router-utils/src/compiler/values.ts +++ b/packages/router-utils/src/compiler/values.ts @@ -85,6 +85,13 @@ export interface RecognizerTable { * pure. */ pureCalls?: Record> + /** + * Specifiers of `pureCalls` whose default export is the module's + * namespace (a CommonJS package without `__esModule`, whose default import + * every bundler binds to its `module.exports`: React): a default import's + * members are recognised as a namespace import's. + */ + pureDefaultNamespaces?: ReadonlySet /** * Builder kind → the link methods of its runtime builder → the * environment whose compile keeps the method's argument (`both`: every @@ -93,8 +100,9 @@ export interface RecognizerTable { * module-level `const` holding one) with pure arguments is no effect, and * an argument the environment erases is not evaluated there; an env-only * kind's argument is kept in its environment alone (`envOnlyKinds`). Read - * by the per-environment code effects of raw facts (import protection), - * never by the planners' purity. + * by the per-environment code effects of raw facts (import protection) + * and by the planners' purity of every compile, for its environment type + * (there, a link called on a `const` is an effect: `ModuleAnalysisOptions.env`). */ builderLinks?: Record> } diff --git a/packages/router-utils/tests/placement.test.ts b/packages/router-utils/tests/placement.test.ts index bc7e0fe8b2..281da4dedd 100644 --- a/packages/router-utils/tests/placement.test.ts +++ b/packages/router-utils/tests/placement.test.ts @@ -5121,11 +5121,16 @@ describe('declarations only split code needs that stay in the route module', () // A call of a known package's pure export (`RecognizerTable.pureCalls`) // with pure arguments is pure, recognised by import binding to the package's -// export (renamed, namespace member). +// export (renamed, namespace member, a member of the default import of a +// package whose default export is its namespace: `pureDefaultNamespaces`). describe('pure calls of known packages', () => { const recognizer = { ...EMPTY_RECOGNIZER, - pureCalls: { 'toy-router': new Set(['getRouteApi']) }, + pureCalls: { + 'toy-router': new Set(['getRouteApi']), + 'toy-cjs': new Set(['getRouteApi']), + }, + pureDefaultNamespaces: new Set(['toy-cjs']), } async function compile(code: string, files: Record = {}) { const host = new MemoryHost({ @@ -5179,6 +5184,8 @@ describe('pure calls of known packages', () => { ["import { getRouteApi } from 'toy-router'", "getRouteApi('/x')"], ["import { getRouteApi as g } from 'toy-router'", "g('/x')"], ["import * as R from 'toy-router'", "R.getRouteApi('/x')"], + ["import C from 'toy-cjs'", "C.getRouteApi('/x')"], + ["import { default as C } from 'toy-cjs'", "C.getRouteApi('/x')"], ] as const it('moves a declaration calling one into the chunk: only an effect before it stays', async () => { @@ -5209,6 +5216,8 @@ describe('pure calls of known packages', () => { { '/app/lib.ts': "export const id = () => '/x'" }, ], ["import { useRouteApi } from 'toy-router'", "useRouteApi('/x')", {}], + // a default import of a package not listed: not its namespace + ["import R from 'toy-router'", "R.getRouteApi('/x')", {}], [ "import { getRouteApi } from './lib'", "getRouteApi('/x')", @@ -5225,12 +5234,12 @@ describe('pure calls of known packages', () => { }) }) -// A client compile's builder chains (`RecognizerTable.builderLinks`) with -// pure arguments are no effect for the planners: what the client erases (a -// server fn's handler) does not count. The server compile's purity takes -// none, and a link on a `const` holding a builder stays an effect (a -// middleware's links write that builder's options). -describe('builder chains in a client compile', () => { +// A compile's builder chains (`RecognizerTable.builderLinks`) with pure +// arguments are no effect for the planners, in either environment: what the +// environment erases (on the client a server fn's validator and handler) +// does not count, what it keeps does. A link on a `const` holding a builder +// stays an effect (a middleware's links write that builder's options). +describe('builder chains in a compile', () => { const recognizer: RecognizerTable = { ...EMPTY_RECOGNIZER, factories: { 'toy-start': { createServerFn: 'serverFn' } }, @@ -5272,10 +5281,21 @@ describe('builder chains in a client compile', () => { }) `) - it('moves a page-only chain into the chunk on the client only', async () => { + it('moves a page-only chain into the chunk in both environments', async () => { const code = route( 'const fn = createServerFn().middleware([]).validator(track).handler(async () => track())', ) + for (const type of ['client', 'server'] as const) { + const r = await compile(code, type) + expect(r.env, type).not.toContain('createServerFn()') + expect(r.kept, type).toEqual([]) + } + }) + + it('counts an argument where its environment keeps it', async () => { + const code = route( + 'const fn = createServerFn().validator(track()).handler(async () => 1)', + ) const client = await compile(code, 'client') expect(client.env).not.toContain('createServerFn()') expect(client.kept).toEqual([]) @@ -5289,9 +5309,11 @@ describe('builder chains in a client compile', () => { 'const base = createServerFn()\nconst fn = base.handler(async () => 1)', 'const fn = createServerFn().middleware([track()]).handler(async () => 1)', ]) { - const r = await compile(route(declarations), 'client') - expect(r.env, declarations).toContain('const fn =') - expect(r.kept, declarations).toContain('fn') + for (const type of ['client', 'server'] as const) { + const r = await compile(route(declarations), type) + expect(r.env, `${type}: ${declarations}`).toContain('const fn =') + expect(r.kept, `${type}: ${declarations}`).toContain('fn') + } } }) }) diff --git a/packages/start-plugin-core/src/compiler/recognizer.ts b/packages/start-plugin-core/src/compiler/recognizer.ts index 1dabf75981..06428db4da 100644 --- a/packages/start-plugin-core/src/compiler/recognizer.ts +++ b/packages/start-plugin-core/src/compiler/recognizer.ts @@ -126,7 +126,7 @@ export function startRecognizer(): RecognizerTable { startKind: START_KINDS.start, startMembers: { createMiddleware: START_KINDS.middleware }, // the router's and the frameworks' pure APIs: the router planner's table, not a copy - pureCalls: knownPureCalls(), + ...knownPureCalls(), } return table }