diff --git a/packages/start-plugin-core/tests/generated-names.ts b/packages/start-plugin-core/tests/generated-names.ts new file mode 100644 index 0000000000..59837ffbd1 --- /dev/null +++ b/packages/start-plugin-core/tests/generated-names.ts @@ -0,0 +1,54 @@ +/** + * Name-agnostic checks of planner outputs: which name the core's allocator + * generates for glue (a lazy component, an import's local, a handler export) + * is free, so tests read it from the output instead of spelling it. + */ + +/** A name the core's name allocator may generate. */ +export const NAME = String.raw`[\p{ID_Start}$_][\p{ID_Continue}$]*` + +const literal = (text: string) => text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + +/** + * `pattern` as a regular expression in which `«x»` is a generated name (the + * first `«x»` captures it as `groups.x`, a later one is the same name) and + * `«…»` is any text. Everything else is literal. + */ +export function shape(pattern: string): RegExp { + const seen = new Set() + let source = '' + let at = 0 + for (const m of pattern.matchAll(/«(\w+|…)»/g)) { + source += literal(pattern.slice(at, m.index)) + const name = m[1]! + source += + name === '…' + ? '[\\s\\S]*?' + : seen.has(name) + ? `\\k<${name}>` + : `(?<${name}>${NAME})` + seen.add(name) + at = m.index + m[0].length + } + source += literal(pattern.slice(at)) + return new RegExp(source, 'u') +} + +/** The groups of `shape(pattern)` in `code` (fails the test when it does not match). */ +export function namesIn(code: string, pattern: string): Record { + const m = shape(pattern).exec(code) + if (!m) { + throw new Error(`no ${pattern} in:\n${code}`) + } + return { ...m.groups } +} + +/** The local name under which `code` imports `imported` from `specifier`. */ +export function importedAs( + code: string, + imported: string, + specifier: string, +): string { + return namesIn(code, `import { ${imported} as «local» } from '${specifier}'`) + .local! +} diff --git a/packages/start-plugin-core/tests/planner-outputs.test.ts b/packages/start-plugin-core/tests/planner-outputs.test.ts index 4ac3719afc..74777c36b4 100644 --- a/packages/start-plugin-core/tests/planner-outputs.test.ts +++ b/packages/start-plugin-core/tests/planner-outputs.test.ts @@ -11,6 +11,7 @@ import { } from '@tanstack/router-utils/compiler' import { startRecognizer } from '../src/compiler/recognizer' import { START_ENV, startPlanners } from '../src/planners' +import { importedAs, namesIn, shape } from './generated-names' import type { StartEnvConfig, StartEnvFacts } from '../src/planners' import type { CompileOutput, @@ -98,6 +99,10 @@ async function compile( const head = `import { createServerFn } from '@tanstack/react-start'\n` +/** The local name of a client output's server-fn stub factory. */ +const clientRpc = (code: string) => + importedAs(code, 'createClientRpc', '@tanstack/react-start/client-rpc') + describe('start-env: server fns', () => { const files = { '/app/module.tsx': `${head}import { db } from './db.server' @@ -112,10 +117,7 @@ export const label = () => 'client' test('client: a stub keeps the builder, drops the validator and the handler-only imports', async () => { const out = (await compile(files, 'client'))! expect(out.code).toContain( - "import { createClientRpc as tsrClientRpc } from '@tanstack/react-start/client-rpc'", - ) - expect(out.code).toContain( - "createServerFn({ method: 'POST' }).handler(tsrClientRpc(", + `createServerFn({ method: 'POST' }).handler(${clientRpc(out.code)}(`, ) expect(out.code).not.toContain('db.server') expect(out.code).not.toContain('schema') @@ -131,17 +133,19 @@ export const label = () => 'client' test('provider: the chain stays next to a createServerRpc export, its handler loads on the first call', async () => { const out = (await compile(files, 'ssr'))! - expect(out.code).toContain( - "import { createServerRpc as tsrServerRpc } from '@tanstack/react-start/server-rpc'", + const rpc = importedAs( + out.code, + 'createServerRpc', + '@tanstack/react-start/server-rpc', ) - expect(out.code).toMatch( - /const fn_createServerFn_handler = tsrServerRpc\(\{ id: '[^']+', name: 'fn', filename: 'module\.tsx' \}, \(opts\) => fn\.__executeServer\(opts\)\)\nexport \{ fn_createServerFn_handler \}/, + // the export the resolver reads, the handler loaded on the first call + const { h } = namesIn( + out.code, + `const «h» = ${rpc}({ id: '«…»', name: 'fn', filename: 'module.tsx' }, («o») => fn.__executeServer(«o»))\nexport { «h» }`, ) - expect(out.code).toContain( - "const tsrLoadHandlers = () => (tsrHandlers ??= import('./module.tsx?tss-serverfn-handler'))", - ) - expect(out.code).toContain( - '.validator(schema).handler(fn_createServerFn_handler, (...args) => tsrLoadHandlers().then((m) => m.tsrHandler$fn(...args)))', + const { impl } = namesIn( + out.code, + `const «load» = () => («memo» ??= import('./module.tsx?tss-serverfn-handler'))«…».validator(schema).handler(${h}, (...args) => «load»().then((m) => m.«impl»(...args)))`, ) expect(out.code).not.toContain('db.server') const handlers = (await compile( @@ -149,16 +153,20 @@ export const label = () => 'client' 'ssr', '/app/module.tsx?tss-serverfn-handler', ))! - expect(handlers.code).toBe(`import { db } from './db.server' -const tsrHandler$fn = async () => db.x() -export { tsrHandler$fn } -`) + expect(handlers.code).toContain("import { db } from './db.server'") + expect(handlers.code).toContain(`const ${impl} = async () => db.x()`) + expect(handlers.code).toContain(`export { ${impl} }`) }) test('ssr caller with a separate provider: an ssr rpc stub keeps the validator', async () => { const out = (await compile(files, 'ssr-caller'))! + const rpc = importedAs( + out.code, + 'createSsrRpc', + '@tanstack/react-start/ssr-rpc', + ) expect(out.code).toContain( - "createServerFn({ method: 'POST' }).validator(schema).handler(tsrSsrRpc(", + `createServerFn({ method: 'POST' }).validator(schema).handler(${rpc}(`, ) expect(out.code).not.toContain('db.server') }) @@ -166,7 +174,9 @@ export { tsrHandler$fn } test('the ids agree between the client and the provider', async () => { const client = (await compile(files, 'client'))! const ssr = (await compile(files, 'ssr'))! - const id = /tsrClientRpc\('([^']+)'\)/.exec(client.code)![1] + const id = client.code + .split(`${clientRpc(client.code)}('`)[1]! + .split("'")[0] expect(ssr.code).toContain(`id: '${id}'`) expect(id).toHaveLength(22) }) @@ -208,7 +218,9 @@ export const authed = () => createServerFn({ method: 'GET' }) }, 'client', ))! - expect(out.code).toContain('authed().middleware([]).handler(tsrClientRpc(') + expect(out.code).toContain( + `authed().middleware([]).handler(${clientRpc(out.code)}(`, + ) expect(out.code).not.toContain('db.server') }) @@ -225,7 +237,9 @@ export const iso = F.createIsomorphicFn().server(() => db.w()).client(() => 'cli }, 'client', ))! - expect(out.code).toContain('F.createServerFn().handler(tsrClientRpc(') + expect(out.code).toContain( + `F.createServerFn().handler(${clientRpc(out.code)}(`, + ) expect(out.code).toContain("export const iso = () => 'client'") expect(out.code).not.toContain('db.server') }) @@ -251,7 +265,7 @@ export default authed 'client', ))! expect(out.code).toContain('export const logged = mw\n') - expect(out.code).toContain('authed.handler(tsrClientRpc(') + expect(out.code).toContain(`authed.handler(${clientRpc(out.code)}(`) expect(out.code).not.toContain('db.server') }) @@ -284,19 +298,20 @@ export const wrapped = wrap(wrap(createServerFn().handler(async () => 'w'))) '/app/schema.ts': `export const schema = (d: unknown) => d\n`, } const client = (await compile(files, 'client'))! + const rpc = clientRpc(client.code) expect(client.code).toContain( - "applyStep(\n createServerFn({ method: 'POST' }),\n).handler(tsrClientRpc(", - ) - expect(client.code).toContain( - 'wrap(wrap(createServerFn().handler(tsrClientRpc(', + `applyStep(\n createServerFn({ method: 'POST' }),\n).handler(${rpc}(`, ) + expect(client.code).toContain(`wrap(wrap(createServerFn().handler(${rpc}(`) expect(client.code).not.toContain('schema') const ssr = (await compile(files, 'ssr'))! - expect(ssr.code).toContain( - '.handler(fn_createServerFn_handler, (...args) => tsrLoadHandlers().then((m) => m.tsrHandler$fn(...args)))', + expect(ssr.code).toMatch( + shape( + `.handler(«h», (...args) => «load»().then((m) => m.«impl»(...args)))`, + ), ) - expect(ssr.code).toContain( - 'wrap(wrap(createServerFn().handler(wrapped_createServerFn_handler, (...args) =>', + expect(ssr.code).toMatch( + shape(`wrap(wrap(createServerFn().handler(«h», (...args) =>`), ) }) @@ -341,12 +356,14 @@ export function make() { } const client = (await compile(files2, 'client'))! expect(client.code).toContain( - 'const inner = createServerFn().handler(tsrClientRpc(', + `const inner = createServerFn().handler(${clientRpc(client.code)}(`, ) expect(client.code).not.toContain('db.server') const ssr = (await compile(files2, 'ssr'))! - expect(ssr.code).toContain( - 'const tsrServerFn$inner = createServerFn().handler(inner_make_createServerFn_handler, (...args) => tsrLoadHandlers().then((m) => m.tsrHandler$inner_make(...args)))', + // hoisted: the module-level fn the nested occurrence reads + const { hoisted } = namesIn( + ssr.code, + `const «hoisted» = createServerFn().handler(«h», (...args) => «load»().then((m) => m.«impl»(...args)))`, ) expect(ssr.code).not.toContain('db.server') const handlers = (await compile( @@ -355,7 +372,7 @@ export function make() { '/app/module.tsx?tss-serverfn-handler', ))! expect(handlers.code).toContain('= async () => db.inner()') - expect(ssr.code).toContain('const inner = tsrServerFn$inner') + expect(ssr.code).toContain(`const inner = ${hoisted}`) expect(ssr.code).toContain("name: 'inner'") }) @@ -581,14 +598,17 @@ export function Page() { '/app/module.tsx?tss-serverfn-split', opts, ))! - expect(env.code).toContain('.handler(tsrSsrRpc(') - expect(env.code).not.toContain('fn_createServerFn_handler') - expect(provider.code).toMatch(/^'use server-entry'/) - expect(provider.code).toContain( - '.handler(fn_createServerFn_handler, async () => render())', + expect(env.code).toContain( + `.handler(${importedAs(env.code, 'createSsrRpc', '@tanstack/react-start/ssr-rpc')}(`, ) + expect(provider.code).toMatch(/^'use server-entry'/) + // the provider owns the handler and exports it; the env module does not + const { h } = namesIn( + provider.code, + `export { «h» }«…».handler(«h», async () => render())`, + ) + expect(env.code).not.toContain(h) expect(provider.code).toContain("import { render } from './render'") - expect(provider.code).toContain('export { fn_createServerFn_handler }') expect(provider.code).not.toContain("from './module.tsx") expect(provider.code).not.toContain('useState') const facts = env.facts.planners[START_ENV] as StartEnvFacts @@ -619,11 +639,11 @@ export const Route = createFileRoute('/posts')({ 'ssr', '/app/src/routes/posts.tsx', ))! - expect(out.code).toContain('export { getPosts_createServerFn_handler }') + // the resolver reads the export the facts name const facts = out.facts.planners[START_ENV] as StartEnvFacts expect(facts.serverFns[0]).toMatchObject({ rootRel: 'src/routes/posts.tsx', - exportName: 'getPosts_createServerFn_handler', }) + expect(out.code).toContain(`export { ${facts.serverFns[0]!.exportName} }`) }) }) diff --git a/packages/start-plugin-core/tests/planners/hydrate.test.ts b/packages/start-plugin-core/tests/planners/hydrate.test.ts index d027a7b6e3..9093a7a834 100644 --- a/packages/start-plugin-core/tests/planners/hydrate.test.ts +++ b/packages/start-plugin-core/tests/planners/hydrate.test.ts @@ -12,6 +12,7 @@ import { tokenOffsets, } from '@tanstack/compiler-test-utils/source-maps' import { createHydratePlanner } from '../../src/planners/hydrate' +import { NAME, shape } from '../generated-names' import { MemoryHost, clientEnv, envInfo, ssrEnv } from './memory-host' import type { CompileOutput, @@ -147,39 +148,31 @@ async function both(code: string, opts: Parameters[1] = {}) { const prefixes = (code: string) => [...code.matchAll(/ h="([^"]+)"/g)].map((m) => m[1]) -describe('recognition (J5.1)', () => { - it.each([ - ['a named import', REACT, '', ''], - [ - 'a renamed import', - `import { Hydrate as HW } from '@tanstack/react-start'\n`, - '', - '', - ], - [ - 'a namespace member', - `import * as Start from '@tanstack/react-start'\n`, - '', - '', - ], - ])('%s is a boundary', async (_, head, open, close) => { - const code = `${head}import { Chart } from './chart'\nexport const Page = ({ w }) => ${open}${close}\n` - const { client, server } = await both(code) - const id = idAt(code, open) - expect(client.extracted).toEqual([ - { id, chunk: `${FILE}?tss-hydrate=${id}` }, - ]) - expect(client.code).toContain( - `${open.slice(0, -1)} h="${id}">${close}`, - ) - expect(client.chunks[id]).toBe( - `import { Chart } from './chart'\nfunction TsrHydrate0() { return () }\nexport { TsrHydrate0 as H0 }\n`, - ) - expect(server.code).toContain( - `${open.slice(0, -1)} h="${id}">${close}`, - ) - }) +/** The lazy component an output renders for boundary `id`, and the chunk export it loads. */ +function lazyOf(code: string, id: string) { + const m = new RegExp( + String.raw`const (${NAME}) = /\* @__PURE__ \*/ ${NAME}\(\(\) => import\('[^']*[?&]tss-hydrate=${id}'\), '(${NAME})'\)`, + 'u', + ).exec(code) + if (!m) { + throw new Error(`no lazy component of the boundary ${id} in:\n${code}`) + } + return { name: m[1]!, exportName: m[2]! } +} +/** The component a chunk exports, and its export name. */ +function chunkComponent(chunk: string) { + const m = new RegExp( + String.raw`export \{ (${NAME}) as (${NAME}) \}`, + 'u', + ).exec(chunk) + if (!m) { + throw new Error(`no chunk component in:\n${chunk}`) + } + return { name: m[1]!, exportName: m[2]! } +} + +describe('recognition (J5.1)', () => { it.each([ [ 'a global Hydrate', @@ -242,22 +235,6 @@ export const Deeper = () =>

local

expect(server.code).toContain('

local

') expect(prefixes(server.code)).toEqual([client.extracted[0]!.id]) }) - - it('splits the split shorthand and a dynamic split', async () => { - const code = `${REACT}export const Page = ({ flag }) => <>

a

b

\n` - const { client, server } = await both(code) - const ids = [idAt(code), idAt(code, ' { - const code = `${SOLID}export const Page = () =>

x

\n` - const client = await compile(code, { env: clientEnv }) - expect(client.code).toContain( - "import { lazyRouteComponent as tsrLazy } from '@tanstack/solid-router'", - ) - }) }) describe('the client output (J5.2)', () => { @@ -272,27 +249,31 @@ export function Page({ label }) { ` const id = idAt(code) const client = await compile(code) - expect(client.code).toBe( - `import { lazyRouteComponent as tsrLazy } from '@tanstack/react-router' -const TsrHydrate0 = /* @__PURE__ */ tsrLazy(() => import('./page.tsx?tss-hydrate=${id}'), 'H0') -import { Hydrate } from '@tanstack/react-start' -import { load } from '@tanstack/react-start/hydration' -export function Page({ label }) { - return -} -`, + // the parent renders a pure lazy component of the chunk in place of the + // children, with what they capture, and loads none of their code + expect(client.code).toMatch( + shape( + `import { lazyRouteComponent as «load» } from '@tanstack/react-router'\nconst «lazy» = /* @__PURE__ */ «load»(() => import('./page.tsx?tss-hydrate=${id}'), '«x»')`, + ), ) + const lazy = lazyOf(client.code, id) + expect(client.code).toContain( + `<${lazy.name} label={label}/>`, + ) + expect(client.code).not.toMatch(/chart|format|title/) // an effectful initialiser only the chunk needs, with nothing effectful after it, moves // (its only needer is the chunk, nothing else writes it and no later effect // could observe the deferred initialisation) - expect(client.chunks[id]).toBe( - `import { Chart } from './chart' -import { formatValue } from './format' -const title = formatValue('Revenue') -function TsrHydrate0({ label }) { return () } -export { TsrHydrate0 as H0 } -`, + const chunk = client.chunks[id]! + expect(chunk).toContain( + `import { Chart } from './chart'\nimport { formatValue } from './format'\nconst title = formatValue('Revenue')`, ) + expect(chunk).toMatch( + shape( + `function «c»({ label }) { return () }`, + ), + ) + expect(chunkComponent(chunk).exportName).toBe(lazy.exportName) }) it('wraps several children, and text, in a fragment that keeps JSX whitespace and entities', async () => { @@ -308,59 +289,22 @@ export { TsrHydrate0 as H0 } ` const client = await compile(code) const ids = client.extracted.map((b) => b.id) - expect(client.chunks[ids[0]!]).toBe( - 'function TsrHydrate0() { return <>

x

}\nexport { TsrHydrate0 as H0 }\n', - ) - expect(client.chunks[ids[1]!]).toBe( - 'function TsrHydrate1() { return <>\n Fish &\n Chips ©\n }\nexport { TsrHydrate1 as H1 }\n', - ) - expect(client.chunks[ids[2]!]).toBe( - 'function TsrHydrate2() { return <>\n }\nexport { TsrHydrate2 as H2 }\n', - ) + const bodies = [ + '<>

x

', + '<>\n Fish &\n Chips ©\n ', + '<>
\n ', + ] + for (const [i, body] of bodies.entries()) { + expect(client.chunks[ids[i]!]).toMatch( + shape(`function «c»() { return ${body} }`), + ) + } // whitespace lines around the region stay in the parent, where JSX drops them expect(client.code).toContain( - `\n \n `, + `\n <${lazyOf(client.code, ids[2]!).name}/>\n `, ) }) - it('returns a single expression child as is', async () => { - const code = `${REACT}export function Page({ label }) { - return {label} -} -` - const client = await compile(code) - const [b] = client.extracted - expect(client.code).toContain( - `{}`, - ) - expect(client.chunks[b!.id]).toBe( - 'function TsrHydrate0({ label }) { return (label) }\nexport { TsrHydrate0 as H0 }\n', - ) - }) - - it('extracts a children prop of a self-closing boundary, and boundaries nested in it', async () => { - const code = `${REACT}import { Chart } from './chart' -export function Page() { - return

inner

} /> -} -` - const outer = idAt(code) - const inner = idAt(code, '} h="${outer}" />`, - ) - expect(client.code).not.toContain('./chart') - expect(client.chunks[outer]).toContain( - `return (
)`, - ) - expect(client.chunks[inner]).toBe( - 'function TsrHydrate1() { return (

inner

) }\nexport { TsrHydrate1 as H1 }\n', - ) - // text order: the nested boundary sits inside the outer opening tag - expect(prefixes(server.code)).toEqual([inner, outer]) - }) - it.each([ ['a string children prop', ''], ['a spread only', ''], @@ -398,38 +342,13 @@ export const Page = (props) => ` const { client, server } = await both(code) const id = idAt(code) + const lazy = lazyOf(client.code, id).name expect(client.code).toContain( - `${attrs} h="${id}"${p ? ' p={TsrHydrate0.preload}' : ''}>`, + `${attrs} h="${id}"${p ? ` p={${lazy}.preload}` : ''}><${lazy}/>`, ) expect(server.code).not.toContain('preload') }) - it('names generated bindings away from the file universe and starts tag names uppercase', async () => { - // (the user's primitives are copied into the chunk: copyable) - const code = `${REACT}const TsrHydrate0 = 'mine' -const tsrLazy = 'mine' -export function Page({ props }) { - return

{TsrHydrate0}{tsrLazy}{props}

-} -` - const client = await compile(code) - const [b] = client.extracted - expect(client.code).toContain( - "import { lazyRouteComponent as tsrLazy$1 } from '@tanstack/react-router'", - ) - expect(client.code).toContain( - `const TsrHydrate0$1 = /* @__PURE__ */ tsrLazy$1(() => import('./page.tsx?tss-hydrate=${b!.id}'), 'H0')`, - ) - expect(client.code).toContain('') - expect(client.chunks[b!.id]).toBe( - `const TsrHydrate0 = 'mine' -const tsrLazy = 'mine' -function TsrHydrate0$1({ props }) { return (

{TsrHydrate0}{tsrLazy}{props}

) } -export { TsrHydrate0$1 as H0 } -`, - ) - }) - it('keeps a foreign query on the chunk id and its specifier', async () => { const code = `${REACT}export const Page = () =>

x

\n` const client = await compile(code, { id: `${FILE}?flavour=b` }) @@ -459,26 +378,6 @@ export const Page = () => ]), ).toEqual([['./chart', 'source', b!.chunk]]) }) - - it('compiles the same chunk from a chunk-first request and from a recompile', async () => { - const code = `${REACT}import { Chart } from './chart' -export const Page = ({ a }) => -` - const client = await compile(code) - const [b] = client.extracted - const fresh = new MemoryHost({ [FILE]: code }) - const config = { - configKey: 'cfg', - perPlanner: { hydrate: { root: ROOT } }, - } - const first = await fresh.compile(b!.chunk, [hydrate], { config }) - expect(first!.code).toBe(client.chunks[b!.id]) - const again = await fresh.compile(b!.chunk, [hydrate], { - config, - code: `${code}`, - }) - expect(again!.code).toBe(first!.code) - }) }) describe('captures (J5.2)', () => { @@ -488,24 +387,6 @@ describe('captures (J5.2)', () => { return { code: client.code, chunk: client.chunks[b!.id]!, client } } - it('passes locals of the enclosing scopes, not module bindings or names declared inside', async () => { - const { code, chunk } = await capturesOf(`const fromModule = 1 -export function Page({ a: [b = 1], ...rest }) { - const value = 'outer' - let latest = 'first' - latest = 'second' - try { throw 1 } catch (error) { - return

{b}{rest.x}{value}{latest}{error}{fromModule}{[1].map((item) => { const inner = item; return inner })}

- } -}`) - expect(code).toContain( - '', - ) - expect(chunk).toContain( - 'function TsrHydrate0({ b, rest, value, latest, error }) {', - ) - }) - it('passes a local shadowing a module binding; the chunk keeps the module binding for code that reads it', async () => { const code = `${REACT}import { label } from './labels' const value = 'module' @@ -518,116 +399,54 @@ export function Page() { ` const client = await compile(code) const [b] = client.extracted - expect(client.code).toContain('') + expect(client.code).toContain( + `<${lazyOf(client.code, b!.id).name} label={label} value={value}/>`, + ) expect(client.code).not.toContain('./labels') - expect(client.chunks[b!.id]).toBe( - `import { label } from './labels' -const value = 'module' -function Show() { return {value + ':' + label} } -function TsrHydrate0({ label, value }) { return <>{label}{value} } -export { TsrHydrate0 as H0 } -`, + const chunk = client.chunks[b!.id]! + expect(chunk).toContain( + `import { label } from './labels'\nconst value = 'module'\nfunction Show() { return {value + ':' + label} }`, + ) + expect(chunk).toMatch( + shape( + `function «c»({ label, value }) { return <>{label}{value} }`, + ), ) }) it('renames props React keeps for itself (key, ref, children)', async () => { - const { code, chunk } = + const { code, chunk, client } = await capturesOf(`export function Page({ children }) { const key = 'k' const ref = 'r' return

{key}{ref}{children}

}`) - expect(code).toContain( - '', - ) - expect(chunk).toContain( - '({ tsrCap$key: key, tsrCap$ref: ref, tsrCap$children: children })', - ) + const lazy = lazyOf(code, client.extracted[0]!.id).name + const { k, r, c } = shape( + `<${lazy} «k»={key} «r»={ref} «c»={children}/>`, + ).exec(code)!.groups! + // the captures travel under props React does not keep for itself + expect( + [k, r, c].filter((n) => ['key', 'ref', 'children'].includes(n!)), + ).toEqual([]) + expect(chunk).toContain(`({ ${k}: key, ${r}: ref, ${c}: children })`) }) - it('takes JSX tags of locals for reads: _, $, non-ASCII and member roots, not intrinsic names', async () => { - const { code } = await capturesOf(`export function Page({ Model }) { - const _Local = () => 1, $Local = () => 2, ÉLocal = () => 3, 组件 = () => 4 - const ui = { Home: () => 5 } - const div = sideEffect('div') - console.log(div) - return <_Local /><$Local /><ÉLocal /><组件 />
x
-}`) - expect(code).toContain( - '', - ) - }) - - it('takes neither property names, method keys, member names nor locals bound inside for reads', async () => { - const { code } = await capturesOf(`import { icons } from './icons' -export function Page({ obj, ids }) { - const el =

{obj?.later + ({ later() { return '!' } }).later()}{ids.map((id) => { const Icon = icons[id]; return })}

- const later = 1 - const Icon = 2 - console.log(later, Icon) - return el -}`) - expect(code).toContain('') - }) - - it('passes a local enum and ignores type positions', async () => { - const { code } = await capturesOf(`import type { Shape } from './types' -export function Page({ v }: { v: unknown }) { - enum Color { Red = 'red' } - type Local = string - return

{Color.Red}{(v as Local as Shape) satisfies unknown}

-}`) - expect(code).toContain('') - }) - - it('keeps the own this and arguments of functions inside the children', async () => { - const { code, chunk, client } = - await capturesOf(`export function Page({ items }) { - return
    {items.map(function (item) { return
  • {this.prefix + item + arguments.length}
  • }, { prefix: '>' })}

{new (class { label = 'x'; read() { return this.label } })().read()}{({ read() { return this.x } }).read()}

-}`) - expect(client.errors).toEqual([]) - expect(code).toContain('') - expect(chunk).toContain('this.prefix + item + arguments.length') - }) - - it('passes the enclosing function’s arguments as tsrArguments, through nested boundaries', async () => { + it('passes the enclosing function’s arguments as a prop, through nested boundaries', async () => { const { code, chunk, client } = await capturesOf(`export function Page() { return

{arguments[0].title}{(() => arguments.length)()}

{arguments.length}
}`) - const [, inner] = client.extracted - expect(code).toContain('') - expect(chunk).toContain( - 'function TsrHydrate0({ tsrArguments }) { return <>

{tsrArguments[0].title}{(() => tsrArguments.length)()}

', - ) - expect(chunk).toContain( - `{}`, - ) - expect(client.chunks[inner!.id]).toBe( - 'function TsrHydrate1({ tsrArguments }) { return (tsrArguments.length) }\nexport { TsrHydrate1 as H1 }\n', - ) - }) - - it('makes an enclosing boundary capture what its nested placeholders read (React)', async () => { - const code = `${REACT}export function Page({ isOpen, fee }) { - const label = 'fee' - return

{label + ':' + (isOpen ? fee : 0)}

-} -` - const client = await compile(code) const [outer, inner] = client.extracted - expect(client.code).toContain( - '', + const lazy = lazyOf(code, outer!.id).name + const args = shape(`<${lazy} «a»={arguments}/>`).exec(code)!.groups!.a! + expect(chunk).toContain( + `({ ${args} }) { return <>

{${args}[0].title}{(() => ${args}.length)()}

`, ) - expect(client.chunks[outer!.id]).toBe( - `import { lazyRouteComponent as tsrLazy$1 } from '@tanstack/react-router' -import { Hydrate } from '@tanstack/react-start' -const TsrHydrate1 = /* @__PURE__ */ tsrLazy$1(() => import('./page.tsx?tss-hydrate=${inner!.id}'), 'H1') -function TsrHydrate0({ label, isOpen, fee }) { return (
) } -export { TsrHydrate0 as H0 } -`, + expect(chunk).toContain( + `{<${lazyOf(chunk, inner!.id).name} ${args}={${args}}/>}`, ) - expect(client.chunks[inner!.id]).toBe( - "function TsrHydrate1({ label, isOpen, fee }) { return (

{label + ':' + (isOpen ? fee : 0)}

) }\nexport { TsrHydrate1 as H1 }\n", + expect(client.chunks[inner!.id]).toMatch( + shape(`function «c»({ ${args} }) { return (${args}.length) }`), ) }) }) @@ -645,13 +464,18 @@ describe('Solid (J5.2)', () => { const client = await compile(code, { env: clientEnv }) const [outer, inner] = client.extracted expect(client.code).toContain( - '', + `<${lazyOf(client.code, outer!.id).name} read={read} value={value} Local={Local} label={label} props={props}/>`, ) - expect(client.chunks[outer!.id]).toContain( - `function TsrHydrate0(props$1) { return (
{(0, props$1.read)()}{ { value: props$1.value }.value }
) }`, + const outerChunk = client.chunks[outer!.id]! + expect(outerChunk).toMatch( + shape( + `function «c»(«p») { return (
{(0, «p».read)()}{ { value: «p».value }.value }<«p».Local><${lazyOf(outerChunk, inner!.id).name} label={«p».label} props={«p».props}/>
) }`, + ), ) - expect(client.chunks[inner!.id]).toBe( - 'function TsrHydrate1(props$1) { return ({props$1.label}{props$1.props.count}) }\nexport { TsrHydrate1 as H1 }\n', + expect(client.chunks[inner!.id]).toMatch( + shape( + `function «c»(«p») { return ({«p».label}{«p».props.count}) }`, + ), ) }) @@ -664,11 +488,14 @@ describe('Solid (J5.2)', () => { ` const client = await compile(code, { env: clientEnv }) const [b] = client.extracted - expect(client.code).toContain( - " typeof input === 'function' ? input(el) : (input = el)}/>", - ) - expect(client.chunks[b!.id]).toContain( - 'return <>
}', + const lazy = lazyOf(client.code, b!.id).name + const setter = shape( + `<${lazy} setOther={setOther} «set»={(«el») => typeof input === 'function' ? input(«el») : (input = «el»)}/>`, + ).exec(client.code)!.groups!.set! + expect(client.chunks[b!.id]).toMatch( + shape( + `return <>
}`, + ), ) }) @@ -684,25 +511,6 @@ describe('Solid (J5.2)', () => { ]) }) - it('makes use: directives reads: a module binding moves with the chunk, a local is passed', async () => { - const code = `${SOLID}import { tip } from './tip' -export function Page() { - const local = (el) => el - return

-} -` - const client = await compile(code, { env: clientEnv }) - const [b] = client.extracted - expect(client.code).not.toContain('./tip') - expect(client.code).toContain('') - expect(client.chunks[b!.id]).toBe( - `import { tip } from './tip' -function TsrHydrate0(props) { const local = props.local; return (

) } -export { TsrHydrate0 as H0 } -`, - ) - }) - it('renames ref and children props for Solid too, and passes arguments through props', async () => { const code = `${SOLID}export function Page() { const ref = 'r' @@ -711,65 +519,18 @@ export { TsrHydrate0 as H0 } ` const client = await compile(code, { env: clientEnv }) const [b] = client.extracted - expect(client.code).toContain( - '', - ) - expect(client.chunks[b!.id]).toContain( - 'return (

{props.tsrCap$ref}{props.tsrArguments.length}

)', + const lazy = lazyOf(client.code, b!.id).name + const { r, a } = shape(`<${lazy} «r»={ref} «a»={arguments}/>`).exec( + client.code, + )!.groups! + expect(r).not.toBe('ref') + expect(client.chunks[b!.id]).toMatch( + shape(`return (

{«p».${r}}{«p».${a}.length}

)`), ) }) }) describe('module-level code the children use', () => { - // A component only the chunk reads moves with its own property writes - // (`Card.Title = …`: nothing outside its cluster augments it). - it('imports exported declarations and Route from the parent; moves what only the chunk uses, augmented components included', async () => { - const code = `${REACT}import { createFileRoute } from '@tanstack/react-router' -import { makeStore } from './store' -export const Route = createFileRoute('/')({ component: Page }) -export const store = makeStore() -let renders = 0 -const label = 'Ada' -const helper = (x) => x + 1 -export const direct = helper(1) -function Card({ children }) { return
{children}
} -Card.Title = () =>

t

-function Widget() { return {label} } -function Page() { - return {++renders}{store.id}{Route.options.id}{helper(2)} -} -` - const client = await compile(code) - const [b] = client.extracted - expect(client.errors).toEqual([]) - expect(client.chunks[b!.id]).toBe( - `import { Route, store, helper } from './page.tsx' -let renders = 0 -const label = 'Ada' -function Card({ children }) { return
{children}
} -Card.Title = () =>

t

-function Widget() { return {label} } -function TsrHydrate0() { return <>{++renders}{store.id}{Route.options.id}{helper(2)} } -export { TsrHydrate0 as H0 } -`, - ) - expect(client.code).not.toContain('let renders') - expect(client.code).not.toContain('function Widget') - expect(client.code).not.toContain('function Card') - expect(client.code).toContain('export { helper }') - }) - - it('moves a let the children only assign into the chunk', async () => { - const code = `${REACT}let renders = 0 -export const Page = () =>

{(() => { renders = 1 })()}

-` - const client = await compile(code) - const [b] = client.extracted - expect(client.errors).toEqual([]) - expect(client.chunks[b!.id]).toContain('let renders = 0') - expect(client.code).not.toContain('renders') - }) - it('rejects children that assign a module binding the parent also uses', async () => { const code = `${REACT}let clicks = 0 export function bump() { clicks++ } @@ -882,13 +643,13 @@ ${REACT}export const Page = () =>
text only
` const client = await compile(code) const [b] = client.extracted - expect(client.chunks[b!.id]).toBe( - `/** @jsxRuntime classic */ -/** @jsx h */ -import { h } from './h' -function TsrHydrate0() { return /* h */ <>text only } -export { TsrHydrate0 as H0 } -`, + const chunk = client.chunks[b!.id]! + // the pragmas still lead the chunk, its fragment reads the factory + expect(chunk).toMatch( + /^\/\*\* @jsxRuntime classic \*\/\n\/\*\* @jsx h \*\/\nimport \{ h \} from '\.\/h'\n/, + ) + expect(chunk).toMatch( + shape(`function «c»() { return /* h */ <>text only }`), ) expect(client.code).toContain("import { h } from './h'") }) @@ -969,13 +730,6 @@ export function Page({ flag }) { expect(Object.keys(client.chunks)).toHaveLength(1) }) - it('accepts a hook in the boundary’s own props', async () => { - const client = await compile( - `${REACT}import { useThing } from './hooks'\nexport const Page = () =>

\n`, - ) - expect(client.errors).toEqual([]) - }) - it('rejects children reading this or super of a class component, not with split={false}', async () => { for (const read of ['this.title', 'super.title']) { const body = ( @@ -1022,17 +776,6 @@ export class Page extends Base { } }) - it('neither extracts nor rejects nor prefixes split={false}, split={(false)}', async () => { - for (const split of ['split={false}', 'split={(false)}']) { - const code = `${REACT}import { useThing } from './hooks'\nexport const Page = () => {() => useThing()}\n` - const { client, server } = await both(code) - expect(client.errors).toEqual([]) - expect(server.errors).toEqual([]) - expect(client.code).toBe(code) - expect(server.code).toBe(code) - } - }) - it('validates a nested boundary on its own (the outer one renders its placeholder)', async () => { const code = `${REACT}import { useThing } from './hooks' export const Page = () =>

{useThing()}

@@ -1045,64 +788,6 @@ export const Page = () =>

{useThing()}

{ - it.each([ - [ - 'a direct fallback', - 'fallback-marker

}>', - ], - [ - 'a direct fallback with split={false}', - 'fallback-marker

}>', - ], - [ - 'a fallback next to prefetch and onHydrated', - ' {}} fallback={

fallback-marker

} onHydrated={() => 1}>', - ], - [ - 'an inline spread', - 'fallback-marker

}}>', - ], - [ - 'a parenthesized inline spread', - 'fallback-marker

})}>', - ], - [ - 'a computed key', - "fallback-marker

}}>", - ], - [ - 'quoted keys', - "fallback-marker

}}>", - ], - [ - 'a spread used once', - '', - 'const opts = { when: 1, fallback:

fallback-marker

}\n', - ], - [ - 'a spread used once, declared after', - '', - '', - 'const opts = { when: 1, fallback:

fallback-marker

}\n', - ], - [ - 'a parenthesized spread used once', - '', - 'const opts = ({ when: 1, fallback:

fallback-marker

})\n', - ], - [ - 'a module-level element', - '', - 'const fallback =

fallback-marker

\n', - ], - ])('strips %s', async (_, open, before = '', after = '') => { - const code = `${REACT}${before}export const Page = ({ w }) => ${open}

child

\n${after}` - const { client, server } = await both(code) - expect(server.code).not.toContain('fallback-marker') - expect(server.code).toContain('

child

') - expect(client.code).toContain('fallback-marker') - }) - it('strips the fallback attribute with the whitespace before it', async () => { const code = `${REACT}export const Page = ({ w }) => } key={1}>

\n` const server = await compile(code, { env: ssrEnv }) @@ -1382,7 +1067,7 @@ export const Page = () =>

b

*/ function toySplitPlanner(): Planner { return { - name: 'route-split', + name: 'toy-split', tier: 1, gate: (t0) => t0.imports.some((i) => i.specifier === '@tanstack/react-router'), @@ -1443,7 +1128,7 @@ function toySplitPlanner(): Planner { effectful: false, anchor: { k: 'after-header' }, home: 'auto', - by: 'route-split', + by: 'toy-split', imports: [ { names: [{ imported: 'lazyRouteComponent', local: lazy }], @@ -1472,7 +1157,7 @@ function toySplitPlanner(): Planner { effectful: false, anchor: { k: 'end' }, home: out, - by: 'route-split', + by: 'toy-split', }) ctx.rewrites.claim({ region, @@ -1488,7 +1173,7 @@ function toySplitPlanner(): Planner { ], }, ], - by: 'route-split', + by: 'toy-split', }) } } @@ -1507,7 +1192,7 @@ export const Route = createFileRoute('/')({ const planners = [hydrate, toySplitPlanner()] const client = await compile(code, { planners }) const id = idAt(code) - expect(client.code).not.toContain('H0') + expect(client.code).not.toContain('tss-hydrate') expect(client.code).not.toContain('./chart') const options = { env: clientEnv, @@ -1518,25 +1203,22 @@ export const Route = createFileRoute('/')({ planners, options, ) - expect(component!.code).toBe( - `import { lazyRouteComponent as tsrLazy } from '@tanstack/react-router' -import { Hydrate } from '@tanstack/react-start' -const TsrHydrate0 = /* @__PURE__ */ tsrLazy(() => import('./page.tsx?tss-hydrate=${id}'), 'H0') -const TsrSplitComponent = () =>
-export { TsrSplitComponent as component } -`, + // the lazy const lives with the split component that renders it + expect(component!.code).toMatch( + shape( + `const «split» = () =>
<${lazyOf(component!.code, id).name}/>
\nexport { «split» as component }`, + ), ) const chunk = await client.host.compile( `${FILE}?tss-hydrate=${id}`, planners, options, ) - expect(chunk!.code).toBe( - `import { Route } from './page.tsx' -import { Chart } from './chart' -function TsrHydrate0() { return <>{Route.id} } -export { TsrHydrate0 as H0 } -`, + expect(chunk!.code).toContain( + `import { Route } from './page.tsx'\nimport { Chart } from './chart'`, + ) + expect(chunk!.code).toMatch( + shape(`function «c»() { return <>{Route.id} }`), ) }) }) @@ -1595,7 +1277,7 @@ describe('placement and markup edge cases (J5.2)', () => { // A recursive component rendering itself inside its own boundary: the // unexported component moves into the chunk with the lazy const only it // reads, next to the chunk component. Their names differ (two - // `TsrHydrate0` declarations were a SyntaxError). + // declarations of one name were a SyntaxError). it('names the lazy const apart from the chunk component when the children reach the component holding the boundary', async () => { const code = `${REACT}export const depth = 2 function Tree({ n }) { @@ -1616,12 +1298,13 @@ function Tree({ n }) { expect(chunk).toContain( 'function Tree({ n }) {\n return n > 0 ? \n `, + `\n <${lazyOf(client.code, b!.id).name}/>`, ) expect(server.code).toContain(``) }) @@ -1690,7 +1373,7 @@ function Tree({ n }) { const client = await compile(code) const [b] = client.extracted expect(client.code).toContain( - `\n `, + `\n <${lazyOf(client.code, b!.id).name}/>`, ) }) @@ -1702,8 +1385,11 @@ function Tree({ n }) { ` const marked = await compile(code, { config: { refreshMarkers: true } }) const [b] = marked.extracted - expect(marked.chunks[b!.id]).toBe( - `function TsrHydrate0() { return (

x

) }\nTsrHydrate0.$$tsrRefreshId = ${JSON.stringify(`${b!.chunk} TsrHydrate0`)}\nexport { TsrHydrate0 as H0 }\n`, + const chunk = marked.chunks[b!.id]! + const component = chunkComponent(chunk).name + // the identity: the chunk id and the binding React Refresh registers + expect(chunk).toContain( + `${component}.$$tsrRefreshId = ${JSON.stringify(`${b!.chunk} ${component}`)}`, ) const plain = await compile(code) expect(plain.chunks[b!.id]).not.toContain('$$tsrRefreshId') @@ -1729,11 +1415,14 @@ function Tree({ n }) { ` const client = await compile(code, { env: clientEnv }) const [b] = client.extracted - expect(client.code).toContain( - " el)()} count={(() => count)()} label={label} tsrRef$el={(el$1) => typeof el === 'function' ? el(el$1) : (el = el$1)}/>", - ) - expect(client.chunks[b!.id]).toContain( - 'return <> props.el?.focus()} />{props.count}{props.label} }', + const lazy = lazyOf(client.code, b!.id).name + const setter = shape( + `<${lazy} el={(() => el)()} count={(() => count)()} label={label} «set»={(«v») => typeof el === 'function' ? el(«v») : (el = «v»)}/>`, + ).exec(client.code)!.groups!.set! + expect(client.chunks[b!.id]).toMatch( + shape( + `return <> «p».el?.focus()} />{«p».count}{«p».label} }`, + ), ) }) }) diff --git a/packages/start-plugin-core/tests/planners/start-env.test.ts b/packages/start-plugin-core/tests/planners/start-env.test.ts index ee3d592525..f3651f2f39 100644 --- a/packages/start-plugin-core/tests/planners/start-env.test.ts +++ b/packages/start-plugin-core/tests/planners/start-env.test.ts @@ -222,17 +222,17 @@ describe('a separate provider env with derived provider modules (Vite RSC)', () [ 'export default', `export default createServerFn().handler(() => db.q())\n`, - /export default createServerFn\(\)\.handler\(tsrSsrRpc\(['"][^'"]+['"]\)\)/, + /export default createServerFn\(\)\.handler\([\w$]+\(['"][^'"]+['"]\)\)/, ], [ 'an object property', `export const api = { get: createServerFn().handler(() => db.q()) }\n`, - /get: createServerFn\(\)\.handler\(tsrSsrRpc\(['"][^'"]+['"]\)\)/, + /get: createServerFn\(\)\.handler\([\w$]+\(['"][^'"]+['"]\)\)/, ], [ 'a class static field', `export class Api { static get = createServerFn().handler(() => db.q()) }\n`, - /static get = createServerFn\(\)\.handler\(tsrSsrRpc\(['"][^'"]+['"]\)\)/, + /static get = createServerFn\(\)\.handler\([\w$]+\(['"][^'"]+['"]\)\)/, ], ])( 'stubs a server fn declared by %s in the env module', @@ -250,7 +250,7 @@ describe('a separate provider env with derived provider modules (Vite RSC)', () expectValid(provider) expect(provider).toContain('db.q()') expect(provider).toContain("from './db.server'") - expect(provider).toMatch(/createServerRpc|tsrServerRpc/) + expect(provider).toContain('createServerRpc') }, ) @@ -302,9 +302,9 @@ ${body}` 'const mw = createMiddleware().server(({ next }) => next())', ) expect(r.code).toMatch( - /createServerFn\(\{ method: METHOD \}\)\.middleware\(\[mw\]\)\.handler\(tsrSsrRpc\(['"][^'"]+['"]\)\)/, + /createServerFn\(\{ method: METHOD \}\)\.middleware\(\[mw\]\)\.handler\([\w$]+\(['"][^'"]+['"]\)\)/, ) - expect(r.code).toContain('tsrSsrRpc } from') + expect(r.code).toMatch(/createSsrRpc as [\w$]+ \} from/) expect(r.code).not.toContain('db.q()') expect(r.code).not.toContain('./db.server') const provider = await r.derived(PROVIDER) @@ -320,7 +320,7 @@ ${body}` { env: rsc, config, files }, ) expect(r.code).toMatch( - /export const fn = createServerFn\(\)\.handler\(tsrSsrRpc\(['"][^'"]+['"]\)\)/, + /export const fn = createServerFn\(\)\.handler\([\w$]+\(['"][^'"]+['"]\)\)/, ) expect(r.code).not.toContain('tss-serverfn-split') }) @@ -452,11 +452,11 @@ import { db } from './db.server' expect(r.out.diagnostics, envName).toEqual([]) expect(r.code, envName).toContain('export function make()') if (env.type === 'client') { - expect(r.code).toContain('tsrClientRpc') + expect(r.code).toContain('createClientRpc') expect(r.code).not.toContain('db.q(1)') expect(r.code).not.toContain('./db.server') } else if (env.isProvider) { - expect(r.code).toContain('tsrSsrRpc') + expect(r.code).toContain('createSsrRpc') expect(r.code).not.toContain('db.q(1)') } else { // the in-place provider's handlers live in its handler module