diff --git a/packages/start-plugin-core/tests/outside-compiler-corpus/start-compiler-runtime-contract.test.ts b/packages/start-plugin-core/tests/outside-compiler-corpus/start-compiler-runtime-contract.test.ts new file mode 100644 index 0000000000..0a49fbfcb3 --- /dev/null +++ b/packages/start-plugin-core/tests/outside-compiler-corpus/start-compiler-runtime-contract.test.ts @@ -0,0 +1,144 @@ +/** + * OUTSIDE THE COMPILER CORPUS (implementation controls). Moved unchanged + * (imports aside) from tests/start-compiler-runtime-contract.test.ts: + * - ":33" and ":44": contract tests of the in-process stand-ins of the + * legacy harness (`./legacy/regression-helpers`: the client RPC without + * its fetch, the SSR RPC calling the handler the server-fn report names); + * the corpus no longer uses them (S4: B-impl, move-out); + * - ":88" and ":122": the same module run through the legacy harness, kept + * as its control; ":122" asserts the `{ error }` answer of a provider + * export, an internal protocol (S4: B-mixed, the `{ error }` shape moves + * out). + * The corpus tests deciding the outcomes are in + * tests/start-compiler-runtime-contract.test.ts (the public Start host). + */ +import { describe, expect, test } from 'vitest' +import { + callFromClient, + callProvider, + callerRpcId, + compileAll, + createServerGraph, + evaluateModule, + serverFnResult, +} from './legacy/regression-helpers' +import { createClientRpc, createSsrRpc } from '../start-runtime' + +/** Own properties (symbols included) of a value, without functions. */ +function metadata(value: object) { + return Object.fromEntries( + Reflect.ownKeys(value) + .filter((key) => !['length', 'name', 'prototype'].includes(String(key))) + .map((key) => [key, (value as Record)[key]]), + ) +} + +describe('the stand-ins carry what Start creates', () => { + test('a client RPC is Start’s own, without the fetch', async () => { + const { rpc } = + await evaluateModule(`import { createClientRpc } from '@tanstack/react-start/client-rpc' +export const rpc = createClientRpc('id-1')`) + const real = createClientRpc('id-1') + expect(rpc).toBeTypeOf('function') + expect(metadata(rpc)).toEqual(metadata(real)) + expect(metadata(real)).toMatchObject({ serverFnMeta: { id: 'id-1' } }) + expect(() => rpc()).toThrow('no server to fetch') + }) + + test('an SSR RPC is Start’s own, calling the handler the report names', async () => { + const provider = `import { createServerRpc } from '@tanstack/react-start/server-rpc' +export const handler = createServerRpc({ id: 'id-1', name: 'fn' }, (opts) => ({ result: opts.data }))` + const { rpc } = await createServerGraph({ + ssr: `import { createSsrRpc } from '@tanstack/react-start/ssr-rpc' +export const rpc = createSsrRpc('id-1')`, + provider, + serverFns: { + 'id-1': { + functionId: 'id-1', + functionName: 'handler', + filename: '/test/src/module.tsx', + extractedFilename: '/test/src/module.tsx?tss-serverfn-split', + }, + }, + }).ssr() + expect(metadata(rpc)).toEqual(metadata(createSsrRpc('id-1'))) + // Start's createSsrRpc forwards its arguments to the resolved handler. + expect(await rpc({ data: 'data' })).toEqual({ result: 'data' }) + }) +}) + +describe('a module with a server fn, a function middleware and an isomorphic fn', () => { + const code = `import { createIsomorphicFn, createMiddleware, createServerFn } from '@tanstack/react-start' +import { db } from './db.server' +const where = createIsomorphicFn().server(() => 'server').client(() => 'client') +export const auth = createMiddleware({ type: 'function' }) + .validator((data: { n: number }) => ({ n: data.n + 1 })) + .client(({ next }) => next({ sendContext: { from: where() } })) + .server(({ next, context }) => next({ context: { user: db.user(context.from) } })) +export const getUser = createServerFn({ method: 'POST' }) + .middleware([auth]) + .handler(async ({ data, context, method, serverFnMeta }) => ({ + n: data.n, + user: context.user, + method, + name: serverFnMeta.name, + where: where(), + })) +export const env = () => where()` + const stubs = { + './db.server': { db: { user: (from: string) => `user-from-${from}` } }, + } + + test('runs on Start’s runtime from the client, the SSR caller and an HTTP call by id', async () => { + const compiled = await compileAll(code) + expect(compiled.client).not.toContain('db.user') + const expected = (from: string) => ({ + n: 2, + user: `user-from-${from}`, + method: 'POST', + name: 'getUser', + where: 'server', + }) + // The client: its middleware's `.client()` runs in the browser. + const client = await evaluateModule(compiled.client, stubs) + expect(client.env()).toBe('client') + expect(callerRpcId(client.getUser)).toEqual(expect.any(String)) + expect( + await callFromClient( + compiled, + (module) => module.getUser, + { n: 1 }, + stubs, + ), + ).toEqual(expected('client')) + // The SSR caller: `.client()` runs on the server, then the handler. + const ssr = await createServerGraph(compiled, stubs).ssr() + expect(ssr.env()).toBe('server') + expect(await ssr.getUser({ data: { n: 1 } })).toEqual(expected('server')) + // An HTTP call by id (Start's server-fn handler calls the provider's + // export with the data, context and method of the request; this one + // sends no client context). + expect(await callProvider(compiled, 'getUser', stubs, { n: 1 })).toEqual( + expected('undefined'), + ) + }) + + test('a failing handler answers { error }, which Start’s handler rethrows', async () => { + const compiled = + await compileAll(`import { createServerFn } from '@tanstack/react-start' +export const fail = createServerFn().handler(async () => { + throw new Error('handler failed') +})`) + const graph = createServerGraph(compiled) + // The handler the id the client calls names (the provider's other + // exports, whatever they are, are not it). + const [reported] = Object.values(compiled.serverFns) + const handler = (await graph.import(reported!.extractedFilename))[ + reported!.functionName + ] + const response = await handler({ data: undefined }) + expect(response).toEqual({ error: new Error('handler failed') }) + expect(() => serverFnResult(response)).toThrow('handler failed') + await expect((await graph.ssr()).fail()).rejects.toThrow('handler failed') + }) +}) diff --git a/packages/start-plugin-core/tests/start-compiler-import-forms.test.ts b/packages/start-plugin-core/tests/start-compiler-import-forms.test.ts index 315b64528d..5434645290 100644 --- a/packages/start-plugin-core/tests/start-compiler-import-forms.test.ts +++ b/packages/start-plugin-core/tests/start-compiler-import-forms.test.ts @@ -1,49 +1,61 @@ /** * Every Start construct is recognised however its factory is imported (a * renamed import, a member of a namespace import) or its result wrapped (a - * TypeScript `as` or `satisfies`), in each framework: the client output - * keeps no server code or import, and each output follows the runtime contract of its - * environment (RPC, environment branch, throwing stub, fallback). + * TypeScript `as` or `satisfies`), in each framework: the client keeps no + * server code or import, and each environment follows the runtime contract + * of its environment (a server fn the client calls through the server, an + * environment branch, a throwing env-only fn, a fallback), observed through + * the public Start host (`./start-host`): the client in a real page, the + * server in the SSR environment and in a real request. * Replaces the Rename / StarImport snapshot fixtures of the createServerFn, * createMiddleware, createIsomorphicFn, envOnly and ClientOnly suites and * envOnlyExportedAlias (N1; gaps SF5, MW4, CO4, SF24). */ -import { describe, expect, test } from 'vitest' -import { getModuleErrors } from '@tanstack/compiler-test-utils/validate-module' +import { beforeAll, describe, expect, test } from 'vitest' import { expectNotLoaded } from '@tanstack/compiler-test-utils/importers' import { - callProvider, - callerRpcId, + callFromClient, + callOnServer, clientOnlyError, - compileCode, - compileFor, - createServerGraph, - evaluateModule, - moduleLoads, - renderToHtml, + fromPage, + inPage, + serveCase, serverOnlyError, settle, + useStartHosts, +} from './regression-helpers' +import type { + Framework, + PageSettled, + ServedCase, + StartCase, } from './regression-helpers' -import type { Framework, ModuleStub, Output } from './regression-helpers' -import type { ServerFn } from '../src/start-compiler/types' const frameworks: Array = ['react', 'solid', 'vue'] -const stubs: Record = { - './db.server': { db: { x: () => 'x' } }, - './chart.client': { chart: () => 'chart', Chart: () => '' }, +const hosts = useStartHosts() + +/** The real modules the constructs read. */ +const moduleFiles = { + 'db.server.ts': `export const db = { x: () => 'x' }\n`, + 'chart.client.ts': `export const chart = () => 'chart'\nexport const Chart = () => ''\n`, } -/** The client output does not load the server-only module. */ -async function expectClientFree(client: string, framework: Framework) { - expectNotLoaded(await moduleLoads(client, { framework }), ['./db.server']) +/** The client does not load the server-only module. */ +async function expectClientFree(served: StartCase) { + expectNotLoaded(await served.loads(), ['./db.server']) } -/** The SSR output does not load the client-only module. */ -async function expectServerFree(ssr: string, framework: Framework) { - expectNotLoaded(await moduleLoads(ssr, { framework, env: 'server' }), [ - './chart.client', - ]) +/** The SSR environment does not load the client-only module. */ +async function expectServerFree(served: StartCase) { + expectNotLoaded(await served.serverLoads(), ['./chart.client']) +} + +/** What calling `call` (a page expression) in the page gives (`settle`). */ +async function settleInPage(served: StartCase, call: string) { + return fromPage( + await inPage(served, `return settle(() => ${call})`), + ) } /** How the factory `name` of `pkg` is imported and its call written. */ @@ -76,20 +88,12 @@ const forms: Record = { }, } -/** A Start construct: the module creating it and the checks of each output. */ +/** A Start construct: the module creating it and the checks of each env. */ interface Construct { name: string /** The export `fn` (or `mw`), created by calling `callee`. */ code: (callee: string, wrap: Form['wrap']) => string - check: (outputs: { - client: string - ssr: string - provider: string - framework: Framework - serverImport: string - /** The server fns the client reported. */ - serverFns: Record - }) => Promise + check: (served: ServedCase) => Promise } const constructs: Array = [ @@ -97,27 +101,20 @@ const constructs: Array = [ name: 'createServerFn', code: (callee, wrap) => `export const fn = ${wrap(`${callee}({ method: 'POST' }).handler(async () => db.x())`)}`, - check: async ({ client, ssr, provider, framework, serverFns }) => { - await expectClientFree(client, framework) - const clientFn = (await evaluateModule(client, stubs, { framework })).fn - expect(callerRpcId(clientFn)).toEqual(expect.any(String)) - expect(serverFns).toHaveProperty(callerRpcId(clientFn)!) - const graph = createServerGraph( - { ssr, provider, framework, serverFns }, - stubs, - ) - const ssrFn = (await graph.ssr()).fn - expect(await ssrFn()).toBe('x') - // The callers keep the builder options (Start exposes `method`). - for (const [output, fn] of [ - ['client', clientFn], - ['ssr', ssrFn], - ] as const) { - expect(fn.method, output).toBe('POST') - } + check: async (served) => { + await expectClientFree(served) + // The callers keep the builder options (Start exposes `method`), and + // the client's server fn is Start's fetcher (its public `url`). expect( - await callProvider({ ssr, provider, framework }, 'fn', stubs), - ).toBe('x') + await inPage( + served, + `return { url: typeof module.fn.url, method: module.fn.method }`, + ), + ).toEqual({ url: 'string', method: 'POST' }) + expect((await served.ssr()).fn.method, 'ssr').toBe('POST') + // Called from server code, and from the client through the server. + expect(await callOnServer(served, 'module.fn')).toBe('x') + expect(await callFromClient(served, 'module.fn')).toBe('x') }, }, { @@ -127,83 +124,104 @@ const constructs: Array = [ db.x() return next() })`)}`, - check: async ({ client, ssr, framework }) => { - await expectClientFree(client, framework) + check: async (served) => { + await expectClientFree(served) // The client drops `.server()`; the server keeps it. expect( - (await evaluateModule(client, stubs, { framework })).mw.options, + await inPage( + served, + `return Object.fromEntries(Object.entries(module.mw.options).filter(([, value]) => value !== undefined).map(([key, value]) => [key, typeof value === 'function' ? '' : value]))`, + ), ).toEqual({ type: 'function' }) - expect( - (await evaluateModule(ssr, stubs, { framework, env: 'server' })).mw - .options.server, - ).toBeTypeOf('function') + expect((await served.ssr()).mw.options.server).toBeTypeOf('function') }, }, { name: 'createIsomorphicFn', code: (callee, wrap) => `export const fn = ${wrap(`${callee}().server(() => db.x()).client(() => chart())`)}`, - check: async ({ client, ssr, framework }) => { - await expectClientFree(client, framework) - await expectServerFree(ssr, framework) - expect((await evaluateModule(client, stubs, { framework })).fn()).toBe( - 'chart', - ) - expect((await evaluateModule(ssr, stubs, { framework })).fn()).toBe('x') + check: async (served) => { + await expectClientFree(served) + await expectServerFree(served) + expect(await inPage(served, 'return module.fn()')).toBe('chart') + expect((await served.ssr()).fn()).toBe('x') }, }, { name: 'createServerOnlyFn', code: (callee, wrap) => `export const fn = ${wrap(`${callee}(() => db.x())`)}`, - check: async ({ client, ssr, framework }) => { - await expectClientFree(client, framework) - expect( - settle((await evaluateModule(client, stubs, { framework })).fn), - ).toEqual(serverOnlyError) - expect((await evaluateModule(ssr, stubs, { framework })).fn()).toBe('x') + check: async (served) => { + await expectClientFree(served) + expect(await settleInPage(served, 'module.fn()')).toEqual(serverOnlyError) + expect((await served.ssr()).fn()).toBe('x') }, }, { name: 'createClientOnlyFn', code: (callee, wrap) => `export const fn = ${wrap(`${callee}(() => chart())`)}`, - check: async ({ client, ssr, framework }) => { - await expectServerFree(ssr, framework) - expect((await evaluateModule(client, stubs, { framework })).fn()).toBe( - 'chart', - ) - expect( - settle((await evaluateModule(ssr, stubs, { framework })).fn), - ).toEqual(clientOnlyError) + check: async (served) => { + await expectServerFree(served) + expect(await inPage(served, 'return module.fn()')).toBe('chart') + const ssr = await served.ssr() + expect(settle(() => ssr.fn())).toEqual(clientOnlyError) }, }, ] -/** - * Compiles every output of `code` (the source itself where the compiler - * leaves it untouched) and checks each is a valid module. - */ -async function compileOutputs(code: string, framework: Framework) { - const compiled = {} as Record - let serverFns: Record = {} - for (const output of ['client', 'ssr', 'provider'] as const) { - const result = await compileFor(output, code, { framework }) - compiled[output] = result.code ?? code - expect(await getModuleErrors(compiled[output]), output).toEqual([]) - if (output === 'client') { - serverFns = result.serverFns - } - } - return { ...compiled, serverFns } -} - /** The imports a construct's code reads, besides the factory. */ const moduleImports = `import { db } from './db.server' import { chart } from './chart.client'` +/** + * What renders a module's `Page` with the framework's real renderers: on + * the server to HTML (`html()`, in the SSR environment), and mounted in the + * page (`mount()`, giving the container). Vue has no renderer here (no Vue + * JSX transform in the host; see the `` tests). + */ +const renderFiles: Partial>> = { + react: { + 'render.server.tsx': `import { createElement } from 'react' +import { renderToString } from 'react-dom/server' +import { Page } from './module' +export const html = () => renderToString(createElement(Page)) +`, + 'render.client.tsx': `import { createElement } from 'react' +import { createRoot } from 'react-dom/client' +import { Page } from './module' +export function mount() { + const container = document.createElement('div') + document.body.append(container) + createRoot(container).render(createElement(Page)) + return container +} +`, + }, + solid: { + 'render.server.tsx': `import { renderToString } from 'solid-js/web' +import { Page } from './module' +export const html = () => renderToString(() => ) +`, + 'render.client.tsx': `import { render } from 'solid-js/web' +import { Page } from './module' +export function mount() { + const container = document.createElement('div') + document.body.append(container) + render(() => , container) + return container +} +`, + }, +} + describe.each(frameworks)('%s', (framework) => { const pkg = `@tanstack/${framework}-start` + const host = () => hosts(framework) + // The framework's host (dev server and page) starts before its tests. + beforeAll(async () => { + await (await host()).page() + }, 60_000) describe.each(constructs)('$name', (construct) => { test.each(Object.keys(forms))('through %s', async (formName) => { @@ -211,15 +229,11 @@ describe.each(frameworks)('%s', (framework) => { const code = `${form.imports(pkg, construct.name)} ${moduleImports} ${construct.code(form.callee(construct.name), form.wrap)}` - const compiled = await compileOutputs(code, framework) - await construct.check({ - client: compiled.client, - ssr: compiled.ssr, - provider: compiled.provider, - framework, - serverImport: './db.server', - serverFns: compiled.serverFns, + const served = await serveCase(await host(), { + 'module.tsx': code, + ...moduleFiles, }) + await construct.check(served) }) }) @@ -229,20 +243,16 @@ ${construct.code(form.callee(construct.name), form.wrap)}` // env-only factory, next to a server fn and alone in its module. describe('a renamed env-only factory read through a namespace import of a project module', () => { const files = { - '/test/src/factory.ts': `export { createServerOnlyFn as serverOnly, createClientOnlyFn as clientOnly } from '${pkg}'`, + 'factory.ts': `export { createServerOnlyFn as serverOnly, createClientOnlyFn as clientOnly } from '${pkg}'\n`, + 'db.server.ts': `export const db = { x: () => 'server-only-value' }\n`, + 'chart.client.ts': `export const chart = () => 'client-only-value'\n`, } - const envStubs: Record = { - './db.server': { db: { x: () => 'server-only-value' } }, - './chart.client': { chart: () => 'client-only-value' }, - } - const options = { framework, files } - const serverOptions = { ...options, env: 'server' as const } /** A call of the namespace member `factory.`, and its checks. */ interface EnvOnlyCall { name: string code: string - check: (outputs: { client: string; ssr: string }) => Promise + check: (served: StartCase) => Promise } const calls: Array = [ @@ -251,17 +261,12 @@ ${construct.code(form.callee(construct.name), form.wrap)}` code: `import * as factory from './factory' import { db } from './db.server' export const impl = factory.serverOnly(() => db.x())`, - check: async ({ client, ssr }) => { - expectNotLoaded( - await moduleLoads(client, { ...options, stubs: envStubs }), - ['./db.server'], + check: async (served) => { + expectNotLoaded(await served.loads(), ['./db.server']) + expect(await settleInPage(served, 'module.impl()')).toEqual( + serverOnlyError, ) - expect( - settle((await evaluateModule(client, envStubs, options)).impl), - ).toEqual(serverOnlyError) - expect( - (await evaluateModule(ssr, envStubs, serverOptions)).impl(), - ).toBe('server-only-value') + expect((await served.ssr()).impl()).toBe('server-only-value') }, }, { @@ -269,29 +274,24 @@ export const impl = factory.serverOnly(() => db.x())`, code: `import * as factory from './factory' import { chart } from './chart.client' export const impl = factory.clientOnly(() => chart())`, - check: async ({ client, ssr }) => { - expectNotLoaded( - await moduleLoads(ssr, { ...serverOptions, stubs: envStubs }), - ['./chart.client'], - ) - expect( - settle((await evaluateModule(ssr, envStubs, serverOptions)).impl), - ).toEqual(clientOnlyError) - expect((await evaluateModule(client, envStubs, options)).impl()).toBe( + check: async (served) => { + expectNotLoaded(await served.serverLoads(), ['./chart.client']) + const ssr = await served.ssr() + expect(settle(() => ssr.impl())).toEqual(clientOnlyError) + expect(await inPage(served, 'return module.impl()')).toBe( 'client-only-value', ) }, }, ] - /** Compiles `code` for the client and SSR, each a valid module, and checks `call`. */ + /** Serves `code` (both environments evaluate it) and checks `call`. */ async function expectEnvOnly(call: EnvOnlyCall, code: string) { - const compiled = {} as Record<'client' | 'ssr', string> - for (const output of ['client', 'ssr'] as const) { - compiled[output] = (await compileCode(output, code, options)) ?? code - expect(await getModuleErrors(compiled[output]), output).toEqual([]) - } - await call.check(compiled) + const served = await serveCase(await host(), { + 'module.tsx': code, + ...files, + }) + await call.check(served) } test.each(calls)( @@ -330,28 +330,12 @@ export const fn = createServerFn().handler(async () => 'fn')`, }) // `` comes from the router package (SPEC J4.11): the server - // outputs render the fallback only, without loading the modules only the - // children use; the client keeps the children. + // renders the fallback only, without loading the modules only the + // children use; the client keeps the children and renders them. describe('', () => { const router = `@tanstack/${framework}-router` - /** - * The router package with a probe `ClientOnly` that renders both the - * fallback and the children it is given (no model of the real one, - * whose client render needs a hydrated page: integration/ - * clientOnlyJSX.test.ts): what each output passes it is visible. - */ - const probeRouter = { - [router]: { - Link: () => null, - ClientOnly: (props: { children?: unknown; fallback?: unknown }) => [ - props.fallback, - '|', - props.children, - ], - }, - } - const chartStub = { - './chart.client': { Chart: () => '' }, + const chartFile = { + 'chart.client.tsx': `export const Chart = () => ''\n`, } /** Checks a `` boundary written as `tag`, imported by `imports`. */ @@ -365,38 +349,36 @@ export const Page = () => ( )` - const compiled = await compileOutputs(code, framework) - expectNotLoaded( - await moduleLoads(compiled.ssr, { - stubs: probeRouter, - framework, - env: 'server', - }), - ['./chart.client'], - ) - const ssr = await evaluateModule( - compiled.ssr, - { ...chartStub, ...probeRouter }, - { framework, env: 'server' }, - ) - const ssrHtml = await renderToHtml(ssr.Page()) - expect(ssrHtml).toContain('

loading

') - expect(ssrHtml).not.toContain('chart') - const client = await evaluateModule( - compiled.client, - { ...chartStub, ...probeRouter }, - { framework }, - ) - expect(await renderToHtml(client.Page())).toContain('<chart>') - if (framework === 'react') { - // The real React `ClientOnly` renders the server output's fallback. - const real = await evaluateModule(compiled.ssr, chartStub, { - env: 'server', - }) - expect(await renderToHtml(real.Page())).toBe( - '

loading

', - ) + const served = await serveCase(await host(), { + 'module.tsx': code, + ...chartFile, + ...renderFiles[framework], + }) + expectNotLoaded(await served.serverLoads(), ['./chart.client']) + // The client keeps the children's module. + expect(await served.loads()).toContain('./chart.client') + if (!renderFiles[framework]) { + return } + // The real renderers: the server renders the fallback, the client the + // children. + const { html } = await served.ssr('render.server.tsx') + const ssrHtml = html() as string + expect(ssrHtml).toContain('loading') + expect(ssrHtml).not.toContain('chart') + expect( + await inPage( + served, + `const container = module.mount() +for (let i = 0; i < 200 && !container.textContent.includes(''); i++) { + await new Promise((resolve) => setTimeout(resolve, 10)) +} +const text = container.textContent +container.remove() +return text`, + { file: 'render.client.tsx' }, + ), + ).toContain('') } test.each([ @@ -410,8 +392,8 @@ export const Page = () => ( // Bug: `` is detected by the ``) is never compiled. - // Impact: the SSR output keeps the children and the client-only modules - // they import: browser-only code runs during SSR. + // Impact: the SSR environment keeps the children and the client-only + // modules they import: browser-only code runs during SSR. // Source: gap CO4 (gaps/start-env.md), N1 import-forms table. test.fails('through a namespace member', async () => { await checkBoundary( diff --git a/packages/start-plugin-core/tests/start-compiler-preserves-user-code.test.ts b/packages/start-plugin-core/tests/start-compiler-preserves-user-code.test.ts index 82698b9588..ce330b4a4e 100644 --- a/packages/start-plugin-core/tests/start-compiler-preserves-user-code.test.ts +++ b/packages/start-plugin-core/tests/start-compiler-preserves-user-code.test.ts @@ -1,85 +1,92 @@ -import { transformWithOxc } from 'vite' -import { describe, expect, test, vi } from 'vitest' -import { getModuleErrors } from '@tanstack/compiler-test-utils/validate-module' +import { pathToFileURL } from 'node:url' +import { beforeAll, describe, expect, test } from 'vitest' import { expectMapsTo, positionAt, tokenOffsets, } from '@tanstack/compiler-test-utils/source-maps' import { - callReportedServerFns, + callFromClient, callServerFnThroughCallers, - compileAll, - compileCode, - compileFor, - compileServer, - createTestModuleGraph, - evaluateModule, - moduleId, - renderToHtml, + inPage, + serveCase, + useStartHost, } from './regression-helpers' -import type { ModuleStub, Output } from './regression-helpers' +import type { StartCase, StartHost } from './regression-helpers' // The compiler removes code that only served a transformed call. Everything // else is user code that must survive, even when nothing seems to read it. +// Observed through the public Start host (`./start-host`): the client in a +// real page, the server in the SSR environment and in real requests. + +const host = useStartHost({ + // Decorated classes are written for TypeScript's `experimentalDecorators` + files: { + 'tsconfig.json': JSON.stringify({ + compilerOptions: { experimentalDecorators: true, jsx: 'react-jsx' }, + }), + }, +}) +beforeAll(async () => { + await (await host()).page() +}, 60_000) + +/** Where the recording modules below record, in the realm they run in. */ +const effectsKey = '__startHostSideEffects' + +/** A recording function `name` (returning `value`) of a recording module. */ +const recorder = (name: string, value: string) => + `export const ${name} = (...args: Array) => { + ;((globalThis as any).${effectsKey} ??= []).push([${JSON.stringify(name)}, ...args.filter((arg) => typeof arg === 'string')].join(':')) + return ${value} +} +` /** - * Runs `evaluate` with recording stubs of the side effects the modules of - * these tests run (`setInterval`, `./persist`, `./registry`, `./analytics`, - * `./store`) and returns what ran, in order. + * The modules of the side effects these tests run (`./persist`, + * `./registry`, `./analytics`, `./store`), each recording its calls, in + * order, and `recorder.ts`, which starts the record and replaces + * `setInterval` with a recording one (`restore()` puts it back). */ -async function recordSideEffectsOf( - evaluate: (stubs: Record) => Promise, -) { - const calls: Array = [] - const record = - (name: string, value: unknown = {}) => - (...args: Array) => { - calls.push( - [name, ...args.filter((arg) => typeof arg === 'string')].join(':'), - ) - return value - } - vi.stubGlobal('setInterval', record('setInterval', 1)) - vi.stubGlobal('clearInterval', () => {}) - try { - await evaluate({ - './persist': { createPersister: record('createPersister') }, - './registry': { register: record('register', 'registered') }, - './analytics': { registerAnalytics: record('registerAnalytics') }, - './store': { createStore: record('createStore') }, - }) - } finally { - vi.unstubAllGlobals() - } - return calls +const effectFiles = { + 'persist.ts': recorder('createPersister', '{}'), + 'registry.ts': recorder('register', "'registered'"), + 'analytics.ts': recorder('registerAnalytics', '{}'), + 'store.ts': recorder('createStore', '{}'), + 'recorder.ts': `const original = { setInterval: globalThis.setInterval, clearInterval: globalThis.clearInterval } +;(globalThis as any).${effectsKey} = [] +;(globalThis as any).setInterval = (...args: Array) => { + ;(globalThis as any).${effectsKey}.push('setInterval') + return 1 +} +;(globalThis as any).clearInterval = () => {} +export function restore() { + Object.assign(globalThis, original) +} +`, } /** - * Evaluates `code` with the recording stubs of `recordSideEffectsOf`, then - * `run` on its exports, and returns what ran, in order. + * Imports the case module in the page after `recorder.ts`, runs `run` (a + * page script with the case module as `m`) and returns what ran, in order. */ -function recordSideEffects( - code: string, - run: (module: Record) => void = () => {}, -) { - return recordSideEffectsOf(async (stubs) => - run(await evaluateModule(code, stubs)), +async function recordClientSideEffects(startCase: StartCase, run = '') { + return inPage( + startCase, + `try { + const m = await load('module.tsx') + ${run} + return globalThis.${effectsKey} +} finally { + module.restore() +}`, + { file: 'recorder.ts' }, ) } -/** - * Compiles `code` into the modules of the SSR bundle, calls each server fn - * the SSR caller reports through the module and export the report names - * (like the server-fn resolver), with the recording stubs of - * `recordSideEffectsOf`, and returns what ran, in order. The SSR caller only - * runs if the provider imports it. - */ -async function recordServerSideEffects(code: string) { - const server = await compileServer(code) - return recordSideEffectsOf((stubs) => - callReportedServerFns(server, server.serverFns, stubs), - ) +/** A case of `code` with the recording modules. */ +async function effectCase(started: StartHost, code: string) { + return started.case({ 'module.tsx': code, ...effectFiles }) } // A declaration that only references itself, or a sibling that references @@ -87,7 +94,8 @@ async function recordServerSideEffects(code: string) { test.each<{ name: string code: string - run?: (module: Record) => void + /** A page script with the module as `m`. */ + run?: string calls: Array }>([ { @@ -172,13 +180,14 @@ export function Page() { return 'page' } export const fn = createServerFn().handler(async () => 1)`, - run: (module) => module.Page(), + run: 'm.Page()', calls: ['register:nested-effect'], }, ])('keeps $name', async ({ code, run, calls }) => { - const client = await compileCode('client', code) - expect(await getModuleErrors(client!)).toEqual([]) - expect(await recordSideEffects(client!, run)).toEqual(calls) + const startCase = await effectCase(await host(), code) + // The client serves a module that imports and runs + await startCase.served() + expect(await recordClientSideEffects(startCase, run)).toEqual(calls) }) // TypeScript erases type positions, so a declaration whose binding only @@ -216,24 +225,30 @@ export const getKind = createIsomorphicFn() test.each([typeQuery, globalAugmentation])( 'client: $name', async ({ code, call }) => { - const compiled = await compileCode('client', code) - expect(await getModuleErrors(compiled!)).toEqual([]) - expect(await recordSideEffects(compiled!)).toEqual([call]) + const startCase = await effectCase(await host(), code) + expect(await recordClientSideEffects(startCase)).toEqual([call]) }, ) - // Handling a server fn call runs the module's initializer, once. + // Handling a server fn call runs the module's initializer, once: what the + // server records while it handles a client's call (the module is first + // evaluated by that request). test(`server: ${typeQuery.name}`, async () => { - expect(await recordServerSideEffects(typeQuery.code)).toEqual([ - typeQuery.call, - ]) + const startCase = await effectCase(await host(), typeQuery.code) + const global = globalThis as Record + global[effectsKey] = [] + try { + expect(await callFromClient(startCase, 'module.getPosts')).toEqual([]) + expect(global[effectsKey]).toEqual([typeQuery.call]) + } finally { + delete global[effectsKey] + } }) }) test('accepts type-only namespace imports and exports, and a type and a value exported under the same name', async () => { - const client = await compileCode( - 'client', - `import { createServerFn } from '@tanstack/react-start' + const served = await serveCase(await host(), { + 'module.tsx': `import { createServerFn } from '@tanstack/react-start' import type * as Start from '@tanstack/react-start' export type * as start from '@tanstack/react-start' export type User = { name: string; register?: Start.Register } @@ -242,54 +257,57 @@ function User(name: string): User { } export { User } export const getUser = createServerFn().handler(async () => User('Ada'))`, - ) - const module = await evaluateModule(client!) - expect(module.User('Ada')).toEqual({ name: 'Ada' }) + }) + expect(await inPage(served, `return module.User('Ada')`)).toEqual({ + name: 'Ada', + }) }) // With the classic runtime the bundler compiles JSX to React.createElement // after this compiler ran, so an import the source only reads in types is -// still needed by the JSX (SPEC J4.17, G12). Checked by rendering the client -// output after a classic JSX transform, with the real React. -test('keeps working with the classic JSX runtime downstream', async () => { - const client = await compileCode( - 'client', - `import * as React from 'react' +// still needed by the JSX (SPEC J4.17, G12). Checked by rendering the +// module of an app whose React plugin uses the classic runtime +// (`react({ jsxRuntime: 'classic' })`), with the real React. +describe('keeps working with the classic JSX runtime downstream', () => { + const classic = useStartHost({ react: { jsxRuntime: 'classic' } }) + + test('the client and the server render it', async () => { + const served = await serveCase(await classic(), { + 'module.tsx': `import * as React from 'react' import { createServerFn } from '@tanstack/react-start' export const getGreeting = createServerFn().handler(async () => 'hi') export function Greeting({ children }: { children: React.ReactNode }) { return

{children}

}`, - ) - const graph = createTestModuleGraph({ - modules: { [moduleId]: client! }, - // What `@vitejs/plugin-react` with `jsxRuntime: 'classic'` (or esbuild's - // default) does after the Start compiler. - transform: async (code, id) => - ( - await transformWithOxc(code, id, { - lang: /\.tsx?$/.test(id) || id === moduleId ? 'tsx' : 'js', - jsx: { runtime: 'classic' }, - }) - ).code, + 'render.tsx': `import * as React from 'react' +import { renderToStaticMarkup } from 'react-dom/server' +import { Greeting } from './module' +export const html = () => renderToStaticMarkup(hi) +`, + }) + expect( + await inPage( + served, + `const element = module.Greeting({ children: 'hi' }) +return { type: element.type, children: element.props.children }`, + ), + ).toEqual({ type: 'p', children: 'hi' }) + expect((await served.ssr('render.tsx')).html()).toBe('

hi

') }) - const { Greeting } = await graph.import(moduleId) - expect(await renderToHtml(Greeting({ children: 'hi' }))).toBe('

hi

') }) test('keeps a namespace only read through a TypeScript import alias', async () => { // `import red = Labels.red` compiles to `var red = Labels.red`. - const client = await compileCode( - 'client', - `import { createServerFn } from '@tanstack/react-start' + const served = await serveCase(await host(), { + 'module.tsx': `import { createServerFn } from '@tanstack/react-start' namespace Labels { export const red = 'red' } import red = Labels.red export const label = red export const fn = createServerFn().handler(async () => red)`, - ) - expect((await evaluateModule(client!)).label).toBe('red') + }) + expect(await inPage(served, 'return module.label')).toBe('red') }) // A JSON import written with the deprecated `assert` keyword (Node 22+ and @@ -297,28 +315,27 @@ export const fn = createServerFn().handler(async () => red)`, // D9: `assert` stays supported; dropping it once nobody writes it is fine). // Source: FIX-PLAN V2-23. test('an import attribute written with assert keeps working in every output', async () => { - const compiled = - await compileAll(`import { createServerFn } from '@tanstack/react-start' + const served = await serveCase(await host(), { + 'module.tsx': `import { createServerFn } from '@tanstack/react-start' import config from './config.json' assert { type: 'json' } import secrets from './secrets.json' assert { type: 'json' } export const theme = config.theme -export const fn = createServerFn().handler(async () => secrets.key)`) - const stubs = { - './config.json': `{ "theme": "dark" }`, - './secrets.json': `{ "key": "MARK_KEY" }`, - } - expect((await evaluateModule(compiled.client, stubs)).theme).toBe('dark') - expect( - await callServerFnThroughCallers(compiled, (module) => module.fn, stubs), - ).toBe('MARK_KEY') +export const fn = createServerFn().handler(async () => secrets.key)`, + 'config.json': `{ "theme": "dark" }`, + 'secrets.json': `{ "key": "MARK_KEY" }`, + }) + expect(await inPage(served, 'return module.theme')).toBe('dark') + expect(await callServerFnThroughCallers(served, 'module.fn')).toBe('MARK_KEY') }) // Decorated classes (TypeScript `experimentalDecorators`) next to a server -// fn: every output is a valid module (running them, decorators included, is -// checked through real builds: integration/start-build-user-code.test.ts). +// fn: every environment serves and evaluates the module (running them, +// decorators included, is checked through real builds too: +// integration/start-build-user-code.test.ts). // Source: FIX-PLAN V2-23. test('decorated classes next to a server fn compile to valid modules', async () => { - await compileAll(`import { createServerFn } from '@tanstack/react-start' + const served = await serveCase(await host(), { + 'module.tsx': `import { createServerFn } from '@tanstack/react-start' const tag = (name: string) => (target: unknown) => target @tag('repository') class Repository { @@ -332,7 +349,12 @@ export class Widget { return 'widget' } } -export const fn = createServerFn().handler(async () => new Repository().read())`) +export const fn = createServerFn().handler(async () => new Repository().read())`, + }) + expect(await inPage(served, 'return new module.Widget().label()')).toBe( + 'widget', + ) + expect(await callFromClient(served, 'module.fn')).toBe('from repository') }) // Bug: the client output prints an asserted update operand without its @@ -342,9 +364,8 @@ export const fn = createServerFn().handler(async () => new Repository().read())` // type-assertion/increment/non-null-increment.js, type-assertion/satisfies.js; // #8504 start-compiler-preserves-user-code.test.ts (red on main) test.fails('keeps the parentheses of asserted update operands', async () => { - const client = await compileCode( - 'client', - `import { createServerFn } from '@tanstack/react-start' + const served = await serveCase(await host(), { + 'module.tsx': `import { createServerFn } from '@tanstack/react-start' export const fn = createServerFn().handler(async () => 1) let count = 0 export function bump() { @@ -354,9 +375,8 @@ export function bump() { ;(count as any) += 1 return count }`, - ) - expect(await getModuleErrors(client!)).toEqual([]) - expect((await evaluateModule(client!)).bump()).toBe(4) + }) + expect(await inPage(served, 'return module.bump()')).toBe(4) }) // Bug: the client output prints a type assertion that is the test of a @@ -372,39 +392,44 @@ export function bump() { test.fails( 'keeps the parentheses of an asserted conditional test', async () => { - const client = await compileCode( - 'client', - `import { createServerFn } from '@tanstack/react-start' + const served = await serveCase(await host(), { + 'module.tsx': `import { createServerFn } from '@tanstack/react-start' export const fn = createServerFn().handler(async () => 1) export function pick(flag: unknown, x: number, y: number) { return ((flag) as any) ? -x : y }`, - ) - expect(await getModuleErrors(client!)).toEqual([]) - expect((await evaluateModule(client!)).pick(true, 1, 2)).toBe(-1) + }) + expect(await inPage(served, 'return module.pick(true, 1, 2)')).toBe(-1) }, ) -/** Compiles a module whose `Page` returns `expression` for the client. */ -async function compilePageReturning(expression: string) { - const client = await compileCode( - 'client', - `import { createServerFn } from '@tanstack/react-start' -export const fn = createServerFn().handler(async () => 1) -export function Page() { - return ${expression} -}`, - ) - return client! -} - // Parenthesized JSX keeps working. test('client: keeps parenthesized JSX working', async () => { - const client = await compilePageReturning('(

page

)') - expect(await getModuleErrors(client)).toEqual([]) - expect(await renderToHtml((await evaluateModule(client)).Page())).toBe( - '

page

', - ) + const served = await serveCase(await host(), { + 'module.tsx': `import { createServerFn } from '@tanstack/react-start' +export const fn = createServerFn().handler(async () => 1) +export function Page() { + return (

page

) +}`, + 'render.client.tsx': `import { createElement } from 'react' +import { flushSync } from 'react-dom' +import { createRoot } from 'react-dom/client' +import { Page } from './module' +export function html() { + const container = document.createElement('div') + const root = createRoot(container) + flushSync(() => root.render(createElement(Page))) + const markup = container.innerHTML + root.unmount() + return markup +} +`, + }) + expect( + await inPage(served, 'return module.html()', { + file: 'render.client.tsx', + }), + ).toBe('

page

') }) // Where license comments end up is free outside the code splitter (SPEC G12, @@ -412,21 +437,30 @@ test('client: keeps parenthesized JSX working', async () => { // checked through a real production build // (integration/start-build-user-code.test.ts). -// Source maps point to the user's code (R6). +// Source maps point to the user's code (R6): the map each environment +// serves with the module (Vite's composed map of every plugin's transform). // Source: #8504 start-compiler-preserves-user-code.test.ts -test.each(['client', 'ssr'] satisfies Array)( +test.each(['client', 'ssr'] as const)( '%s: maps the string value of a JSX attribute to its own source column', - async (output) => { + async (environment) => { const code = `import { createServerFn } from '@tanstack/react-start' export const fn = createServerFn().handler(async () => 1) export const Box = () =>
` - const result = await compileFor(output, code) - const [generated] = tokenOffsets(result.code!, { string: 'box' }) + const started = await host() + const startCase = await started.case({ 'module.tsx': code }) + const result = await started.host.dev.vite.environments[ + environment + ]!.transformRequest(startCase.url()) + expect(result, 'the served module').toBeTruthy() + const [generated] = tokenOffsets(result!.code, { string: 'box' }) expect(generated, 'the attribute value in the output').toBeDefined() const [original] = tokenOffsets(code, { string: 'box' }) - expectMapsTo(result.map as never, positionAt(result.code!, generated!), { - file: '/test/src/module.tsx', + expectMapsTo(result!.map as never, positionAt(result!.code, generated!), { + file: startCase.file(), + root: started.root, + // Vite's map names its sources relative to the served module + mapUrl: pathToFileURL(startCase.file()).href, ...positionAt(code, original!), }) }, diff --git a/packages/start-plugin-core/tests/start-compiler-runtime-contract.test.ts b/packages/start-plugin-core/tests/start-compiler-runtime-contract.test.ts index a2f3006167..b58738fbf2 100644 --- a/packages/start-plugin-core/tests/start-compiler-runtime-contract.test.ts +++ b/packages/start-plugin-core/tests/start-compiler-runtime-contract.test.ts @@ -1,67 +1,29 @@ /** - * The contract between the Start compiler's output and Start's runtime. - * Compiled modules run on the real `@tanstack/start-client-core` and - * `createServerRpc` (regression-helpers.ts, start-runtime.ts); these tests - * pin the few stand-ins the harness keeps where the runtime cannot run - * in-process (the client RPC's fetch, the server-fn resolver behind the SSR - * RPC, the request context), so they cannot drift from the runtime, and run - * one module through all of it. + * One module through the whole of Start's runtime, served by the public + * Start host (`./start-host`): a server fn with a function middleware and + * an isomorphic fn, called from the client in a real page (Start's client + * RPC sends its request to the dev server, whose server entry runs the + * middleware and the handler) and from server code in a real request; and + * a failing handler, whose error reaches both callers. + * The controls of the former in-process stand-ins (the client RPC without + * its fetch, the SSR RPC behind the server-fn report, the `{ error }` answer + * of a provider) moved to outside-compiler-corpus/ + * start-compiler-runtime-contract.test.ts: the corpus no longer uses them. * Source: audit E1 missing coverage 1. */ -import { describe, expect, test } from 'vitest' +import { beforeAll, describe, expect, test } from 'vitest' import { callFromClient, - callProvider, - callerRpcId, - compileAll, - createServerGraph, - evaluateModule, - serverFnResult, + callOnServer, + inPage, + serveCase, + useStartHost, } from './regression-helpers' -import { createClientRpc, createSsrRpc } from './start-runtime' -/** Own properties (symbols included) of a value, without functions. */ -function metadata(value: object) { - return Object.fromEntries( - Reflect.ownKeys(value) - .filter((key) => !['length', 'name', 'prototype'].includes(String(key))) - .map((key) => [key, (value as Record)[key]]), - ) -} - -describe('the stand-ins carry what Start creates', () => { - test('a client RPC is Start’s own, without the fetch', async () => { - const { rpc } = - await evaluateModule(`import { createClientRpc } from '@tanstack/react-start/client-rpc' -export const rpc = createClientRpc('id-1')`) - const real = createClientRpc('id-1') - expect(rpc).toBeTypeOf('function') - expect(metadata(rpc)).toEqual(metadata(real)) - expect(metadata(real)).toMatchObject({ serverFnMeta: { id: 'id-1' } }) - expect(() => rpc()).toThrow('no server to fetch') - }) - - test('an SSR RPC is Start’s own, calling the handler the report names', async () => { - const provider = `import { createServerRpc } from '@tanstack/react-start/server-rpc' -export const handler = createServerRpc({ id: 'id-1', name: 'fn' }, (opts) => ({ result: opts.data }))` - const { rpc } = await createServerGraph({ - ssr: `import { createSsrRpc } from '@tanstack/react-start/ssr-rpc' -export const rpc = createSsrRpc('id-1')`, - provider, - serverFns: { - 'id-1': { - functionId: 'id-1', - functionName: 'handler', - filename: '/test/src/module.tsx', - extractedFilename: '/test/src/module.tsx?tss-serverfn-split', - }, - }, - }).ssr() - expect(metadata(rpc)).toEqual(metadata(createSsrRpc('id-1'))) - // Start's createSsrRpc forwards its arguments to the resolved handler. - expect(await rpc({ data: 'data' })).toEqual({ result: 'data' }) - }) -}) +const host = useStartHost() +beforeAll(async () => { + await (await host()).page() +}, 60_000) describe('a module with a server fn, a function middleware and an isomorphic fn', () => { const code = `import { createIsomorphicFn, createMiddleware, createServerFn } from '@tanstack/react-start' @@ -81,13 +43,16 @@ export const getUser = createServerFn({ method: 'POST' }) where: where(), })) export const env = () => where()` - const stubs = { - './db.server': { db: { user: (from: string) => `user-from-${from}` } }, + const files = { + 'db.server.ts': `export const db = { user: (from: string) => \`user-from-\${from}\` }\n`, } - test('runs on Start’s runtime from the client, the SSR caller and an HTTP call by id', async () => { - const compiled = await compileAll(code) - expect(compiled.client).not.toContain('db.user') + test('runs on Start’s runtime from the client and from server code', async () => { + const served = await serveCase(await host(), { + 'module.tsx': code, + ...files, + }) + expect(served.code.client).not.toContain('db.user') const expected = (from: string) => ({ n: 2, user: `user-from-${from}`, @@ -96,45 +61,37 @@ export const env = () => where()` where: 'server', }) // The client: its middleware's `.client()` runs in the browser. - const client = await evaluateModule(compiled.client, stubs) - expect(client.env()).toBe('client') - expect(callerRpcId(client.getUser)).toEqual(expect.any(String)) expect( - await callFromClient( - compiled, - (module) => module.getUser, - { n: 1 }, - stubs, + await inPage( + served, + `return { env: module.env(), url: typeof module.getUser.url }`, ), - ).toEqual(expected('client')) - // The SSR caller: `.client()` runs on the server, then the handler. - const ssr = await createServerGraph(compiled, stubs).ssr() - expect(ssr.env()).toBe('server') - expect(await ssr.getUser({ data: { n: 1 } })).toEqual(expected('server')) - // An HTTP call by id (Start's server-fn handler calls the provider's - // export with the data, context and method of the request; this one - // sends no client context). - expect(await callProvider(compiled, 'getUser', stubs, { n: 1 })).toEqual( - expected('undefined'), + ).toEqual({ env: 'client', url: 'string' }) + expect(await callFromClient(served, 'module.getUser', { n: 1 })).toEqual( + expected('client'), + ) + // Server code: `.client()` runs on the server, then the handler. + expect((await served.ssr()).env()).toBe('server') + expect(await callOnServer(served, 'module.getUser', { n: 1 })).toEqual( + expected('server'), ) }) - test('a failing handler answers { error }, which Start’s handler rethrows', async () => { - const compiled = - await compileAll(`import { createServerFn } from '@tanstack/react-start' + // Source: the former test "a failing handler answers { error }, which + // Start’s handler rethrows" (S4 B-mixed: the error reaching the callers is + // the concept; the `{ error }` answer of a provider export is internal). + test('a failing handler’s error reaches the client and the server caller', async () => { + const served = await serveCase(await host(), { + 'module.tsx': `import { createServerFn } from '@tanstack/react-start' export const fail = createServerFn().handler(async () => { throw new Error('handler failed') -})`) - const graph = createServerGraph(compiled) - // The handler the id the client calls names (the provider's other - // exports, whatever they are, are not it). - const [reported] = Object.values(compiled.serverFns) - const handler = (await graph.import(reported!.extractedFilename))[ - reported!.functionName - ] - const response = await handler({ data: undefined }) - expect(response).toEqual({ error: new Error('handler failed') }) - expect(() => serverFnResult(response)).toThrow('handler failed') - await expect((await graph.ssr()).fail()).rejects.toThrow('handler failed') +})`, + }) + await expect(callFromClient(served, 'module.fail')).rejects.toThrow( + 'handler failed', + ) + await expect(callOnServer(served, 'module.fail')).rejects.toThrow( + 'handler failed', + ) }) }) diff --git a/packages/start-plugin-core/tests/start-compiler-v2-inputs.test.ts b/packages/start-plugin-core/tests/start-compiler-v2-inputs.test.ts index b0678c0501..f0b5d2ae5f 100644 --- a/packages/start-plugin-core/tests/start-compiler-v2-inputs.test.ts +++ b/packages/start-plugin-core/tests/start-compiler-v2-inputs.test.ts @@ -1,24 +1,42 @@ /** * Inputs the V2 corpus review found untested at the compiler level (FIX-PLAN * §G, W3-start-v2): each is ordinary user code the docs or the public types - * allow, compiled for the client, the SSR caller and the provider, and - * checked through what the outputs load and do (SPEC J4.1, J4.5, J4.8, - * J4.12, §2.1). The real builds of the same inputs are in + * allow, served by the public Start host (`./start-host`) and checked + * through what each environment loads and does (SPEC J4.1, J4.5, J4.8, + * J4.12, §2.1): the client in a real page, server fns called from the + * client through the dev server and from server code in a real request. + * The real builds of the same inputs are in * `integration/start-build-v2-*.test.ts`. */ import { describe, expect, test } from 'vitest' import { expectNotLoaded } from '@tanstack/compiler-test-utils/importers' import { callFromClient, - callProvider, - callerRpcId, - compileAll, - createServerGraph, - evaluateModule, - moduleLoads, - renderToHtml, + callOnServer, + inPage, + serveCase, + useStartHost, } from './regression-helpers' -import type { ModuleStub } from './regression-helpers' +import type { Plugin } from 'vite' + +/** + * `cloudflare:workers` as a Workers platform plugin gives it to the server + * environments (a module the client cannot resolve). + */ +function workersPlatform(): Plugin { + const id = '\0cloudflare:workers' + return { + name: 'test:cloudflare-workers', + applyToEnvironment: (environment) => environment.name !== 'client', + resolveId: (source) => (source === 'cloudflare:workers' ? id : null), + load: (loaded) => + loaded === id + ? `export const env = { SECRET: 'MARK_ENV_SECRET' }\n` + : null, + } +} + +const host = useStartHost({ plugins: [workersPlatform()] }) const head = `import { createMiddleware, createServerFn } from '@tanstack/react-start'\n` @@ -26,7 +44,7 @@ describe('server-only imports the client cannot resolve (V2-02)', () => { // `cloudflare:workers` (241 corpus files) and `node:*` resolve on the // server only; the compiler removes them with the server code that reads // them, before any bundler tries to resolve them for the client (SPEC - // J4.12). The server outputs keep them. + // J4.12). The server keeps them. // Source: FIX-PLAN V2-02 (start-fable SF-22/MW-7; #6185, #7460, #3990). const platform = `import { env } from 'cloudflare:workers' import { readFileSync } from 'node:fs' @@ -37,44 +55,46 @@ export const readConfig = createServerFn() .middleware([withEnv]) .handler(async ({ context }) => [ context.secret, - readFileSync('/config').toString(), + readFileSync(new URL('./config.txt', import.meta.url)).toString(), ]) export const label = () => 'MARK_CLIENT_LABEL' ` const unresolvable = ['cloudflare:workers', 'node:fs'] - const platformStubs: Record = { - 'cloudflare:workers': { env: { SECRET: 'MARK_ENV_SECRET' } }, - 'node:fs': { readFileSync: () => 'MARK_FILE' }, - } - test('the client output compiles and loads neither specifier; the server outputs still read them', async () => { - const compiled = await compileAll(`${head}${platform}`) - expectNotLoaded(await moduleLoads(compiled.client), unresolvable) - const client = await evaluateModule(compiled.client) - expect(client.label()).toBe('MARK_CLIENT_LABEL') - expect(callerRpcId(client.readConfig)).toEqual(expect.any(String)) - // The server runs the middleware and the handler with the platform - // modules (stubbed here: this process is neither a worker nor a server - // bundle). + test('the client compiles and loads neither specifier; the server still reads them', async () => { + const served = await serveCase(await host(), { + 'module.tsx': `${head}${platform}`, + 'config.txt': 'MARK_FILE', + }) + const loads = await served.loads() + expectNotLoaded(loads, unresolvable) expect( - await callFromClient( - compiled, - (module) => module.readConfig, - undefined, - platformStubs, + loads.filter((loaded) => + /cloudflare|node:fs|__vite-browser-external/.test(loaded), ), - ).toEqual(['MARK_ENV_SECRET', 'MARK_FILE']) - // (The handler's `node:fs` read is proven by the result above: the - // linker names Node's builtins differently from stubs.) - for (const output of ['ssr', 'provider'] as const) { - expect( - await moduleLoads(compiled[output], { - env: 'server', - stubs: platformStubs, - }), - output, - ).toContain('cloudflare:workers') - } + ).toEqual([]) + expect( + await inPage( + served, + `return { label: module.label(), url: typeof module.readConfig.url }`, + ), + ).toEqual({ label: 'MARK_CLIENT_LABEL', url: 'string' }) + // The server runs the middleware and the handler with the platform + // modules: a call from the client reaches them through the server. + expect(await callFromClient(served, 'module.readConfig')).toEqual([ + 'MARK_ENV_SECRET', + 'MARK_FILE', + ]) + expect(await callOnServer(served, 'module.readConfig')).toEqual([ + 'MARK_ENV_SECRET', + 'MARK_FILE', + ]) + expect( + (await served.serverLoads()).some((loaded) => + loaded.includes('cloudflare:workers'), + ), + 'the SSR environment loads cloudflare:workers', + ).toBe(true) }) }) @@ -84,7 +104,7 @@ describe('a validator schema the client also uses (V2-08)', () => { // schema only a validator uses is gone (J4.12). // Source: FIX-PLAN V2-08 (start-fable SF-3; ~3,500 validator files). const files = { - '/test/src/post-schema.ts': `export interface Post { + 'post-schema.ts': `export interface Post { title: string } export function PostSchema(input: unknown): Post { @@ -98,16 +118,14 @@ export function PostSchema(input: unknown): Post { return { title: (input as Post).title } } `, - '/test/src/draft-schema.ts': `export function DraftSchema(input: unknown): { body: string } { + 'draft-schema.ts': `export function DraftSchema(input: unknown): { body: string } { if (typeof (input as { body?: unknown }).body !== 'string') { throw new Error('MARK_INVALID_DRAFT') } return { body: String((input as { body: string }).body) } } `, - } - const stubs: Record = { - './db.server': { save: (data: unknown) => ({ saved: data }) }, + 'db.server.ts': `export const save = (data: unknown) => ({ saved: data })\n`, } const code = `${head}import { PostSchema } from './post-schema' import { DraftSchema } from './draft-schema' @@ -123,26 +141,37 @@ export function validateForm(input: unknown) { } ` - test('the client form validates with the schema, the validator-only schema is not loaded, the provider rejects invalid input', async () => { - const compiled = await compileAll(code, { files }) - expectNotLoaded(await moduleLoads(compiled.client, { files }), [ - '/test/src/draft-schema.ts', - './db.server', - ]) - const client = await evaluateModule(compiled.client, stubs, { files }) - expect(client.validateForm({ title: 'hello' })).toEqual({ title: 'hello' }) - expect(() => client.validateForm({})).toThrow('MARK_INVALID_POST') - expect(callerRpcId(client.createPost)).toEqual(expect.any(String)) - expect(callerRpcId(client.saveDraft)).toEqual(expect.any(String)) - // The provider validates: an invalid call is rejected, a valid one saved. + test('the client form validates with the schema, the validator-only schema is not loaded, the server rejects invalid input', async () => { + const served = await serveCase(await host(), { + 'module.tsx': code, + ...files, + }) + expectNotLoaded(await served.loads(), ['./draft-schema', './db.server']) expect( - await callProvider(compiled, 'createPost', stubs, { title: 'hello' }), + await inPage( + served, + `return { + valid: module.validateForm({ title: 'hello' }), + invalid: await settle(() => module.validateForm({})), + urls: [typeof module.createPost.url, typeof module.saveDraft.url], +}`, + ), + ).toEqual({ + valid: { title: 'hello' }, + invalid: { + thrown: { name: 'Error', message: 'MARK_INVALID_POST' }, + }, + urls: ['string', 'string'], + }) + // The server validates: an invalid call is rejected, a valid one saved. + expect( + await callFromClient(served, 'module.createPost', { title: 'hello' }), ).toEqual({ saved: { title: 'hello' } }) await expect( - callProvider(compiled, 'createPost', stubs, { nope: true }), + callFromClient(served, 'module.createPost', { nope: true }), ).rejects.toThrow('MARK_INVALID_POST') expect( - await callProvider(compiled, 'saveDraft', stubs, { body: 'draft' }), + await callFromClient(served, 'module.saveDraft', { body: 'draft' }), ).toEqual({ saved: { body: 'draft' } }) }) }) @@ -150,9 +179,8 @@ export function validateForm(input: unknown) { describe('.jsx modules (V2-11)', () => { // Untyped `.jsx` files with JSX and a server fn (532 corpus files) are // compiled like `.tsx` ones (SPEC §2.1): the client gets the stub and no - // server code, the handler runs on the provider, the JSX renders. + // server code, the handler runs on the server, the JSX renders. // Source: FIX-PLAN V2-11 (start-fable SF-19). - const id = '/test/src/fns.jsx' const code = `import { createServerFn } from '@tanstack/react-start' import { db } from './db.server' export const getUser = createServerFn().handler(async () => db.user()) @@ -160,37 +188,55 @@ export function Badge({ name }) { return {name} } ` - const stubs: Record = { - './db.server': { db: { user: () => 'MARK_USER' } }, - } test('the client calls the server by id without the handler, and renders the JSX', async () => { - const compiled = await compileAll(code, { id }) - expectNotLoaded(await moduleLoads(compiled.client, { id }), ['./db.server']) + const served = await serveCase( + await host(), + { + 'fns.jsx': code, + 'db.server.ts': `export const db = { user: () => 'MARK_USER' }\n`, + 'render.server.tsx': `import { renderToStaticMarkup } from 'react-dom/server' +import { Badge } from './fns.jsx' +export const html = () => renderToStaticMarkup() +`, + 'render.client.tsx': `import { createElement } from 'react' +import { flushSync } from 'react-dom' +import { createRoot } from 'react-dom/client' +import { Badge } from './fns.jsx' +export function html() { + const container = document.createElement('div') + const root = createRoot(container) + flushSync(() => root.render(createElement(Badge, { name: 'Ada' }))) + const markup = container.innerHTML + root.unmount() + return markup +} +`, + }, + { file: 'fns.jsx' }, + ) + expectNotLoaded(await served.loads('fns.jsx'), ['./db.server']) expect( - await callFromClient( - compiled, - (module) => module.getUser, - undefined, - stubs, - ), + await callFromClient(served, 'module.getUser', undefined, { + file: 'fns.jsx', + }), ).toBe('MARK_USER') - for (const output of ['client', 'ssr'] as const) { - const module = - output === 'client' - ? await evaluateModule(compiled.client, stubs) - : await createServerGraph(compiled, stubs).ssr() - expect(await renderToHtml(module.Badge({ name: 'Ada' })), output).toBe( - 'Ada', - ) - } + expect( + await inPage(served, 'return module.html()', { + file: 'render.client.tsx', + }), + 'client', + ).toBe('Ada') + expect((await served.ssr('render.server.tsx')).html(), 'ssr').toBe( + 'Ada', + ) }) }) describe('a server fn builder reused as middleware (V2-25)', () => { // `createServerFn().middleware([auth])` passed in another server fn's // `.middleware([...])` contributes `auth` (SPEC J4.5): the client runs - // `auth.client()` and ships no `auth.server()` code; the provider runs + // `auth.client()` and ships no `auth.server()` code; the server runs // `auth.server()` before the handler (J4.8). // Source: FIX-PLAN V2-25 (start-fable SF-6; runtime createServerFn.ts // TSS_SERVER_FUNCTION_FACTORY). @@ -205,34 +251,29 @@ export const whoAmI = createServerFn() .middleware([authed]) .handler(async ({ context }) => context.user) ` - const stubs: Record = { - './audit.server': { audit: (from: string) => `user(${from})` }, - } - test('the client call runs auth.client(), the provider runs auth.server() then the handler', async () => { - const compiled = await compileAll(code) - expectNotLoaded(await moduleLoads(compiled.client), ['./audit.server']) - const client = await evaluateModule(compiled.client, stubs) - expect(client.auth.options.server).toBeUndefined() - expect(client.auth.options.client).toBeTypeOf('function') - // `from: 'client'` reaches the server only when `auth.client()` ran. + test('the client call runs auth.client(), the server runs auth.server() then the handler', async () => { + const served = await serveCase(await host(), { + 'module.tsx': code, + 'audit.server.ts': `export const audit = (from: string) => \`user(\${from})\`\n`, + }) + expectNotLoaded(await served.loads(), ['./audit.server']) expect( - await callFromClient( - compiled, - (module) => module.whoAmI, - undefined, - stubs, + await inPage( + served, + `return { server: module.auth.options.server === undefined, client: typeof module.auth.options.client }`, ), - ).toBe('user(client)') - const ssr = await createServerGraph(compiled, stubs).ssr() - expect(await ssr.whoAmI()).toBe('user(client)') + ).toEqual({ server: true, client: 'function' }) + // `from: 'client'` reaches the server only when `auth.client()` ran. + expect(await callFromClient(served, 'module.whoAmI')).toBe('user(client)') + expect(await callOnServer(served, 'module.whoAmI')).toBe('user(client)') }) }) describe('createServerFn options by identifier or spread (V2-31)', () => { // `createServerFn(opts)` and `createServerFn({ ...opts })` are ordinary - // input (SPEC J4.5): each env keeps the options' `method`, the client gets - // a stub, the provider the handler. + // input (SPEC J4.5): each env keeps the options' `method`, the client + // calls through the server, the server runs the handler. // Source: FIX-PLAN V2-31 (start-fable SF-2; 26 corpus files). const code = `import { createServerFn } from '@tanstack/react-start' import { db } from './db.server' @@ -240,35 +281,26 @@ const opts = { method: 'POST' } as const export const byIdentifier = createServerFn(opts).handler(async () => db.x()) export const bySpread = createServerFn({ ...opts }).handler(async () => db.x()) ` - const stubs: Record = { - './db.server': { db: { x: () => 'MARK_X' } }, - } test.each(['byIdentifier', 'bySpread'])( - '%s: each env keeps the method, the client calls by id, the provider runs the handler', + '%s: each env keeps the method, the client calls by id, the server runs the handler', async (name) => { - const compiled = await compileAll(code) - expectNotLoaded(await moduleLoads(compiled.client), ['./db.server']) - const client = await evaluateModule(compiled.client, stubs) - const ssr = await createServerGraph(compiled, stubs).ssr() - for (const [output, fn] of [ - ['client', client[name]], - ['ssr', ssr[name]], - ] as const) { - // Start exposes the declared method on the server fn. - expect(fn.method, output).toBe('POST') - } - expect(callerRpcId(client[name])).toEqual(expect.any(String)) + const served = await serveCase(await host(), { + 'module.tsx': code, + 'db.server.ts': `export const db = { x: () => 'MARK_X' }\n`, + }) + expectNotLoaded(await served.loads(), ['./db.server']) + // Start exposes the declared method on the server fn. expect( - await callFromClient( - compiled, - (module) => module[name], - undefined, - stubs, + await inPage( + served, + `return { method: module.${name}.method, url: typeof module.${name}.url }`, ), - ).toBe('MARK_X') - expect(await ssr[name]()).toBe('MARK_X') - expect(await callProvider(compiled, name, stubs)).toBe('MARK_X') + 'client', + ).toEqual({ method: 'POST', url: 'string' }) + expect((await served.ssr())[name].method, 'ssr').toBe('POST') + expect(await callFromClient(served, `module.${name}`)).toBe('MARK_X') + expect(await callOnServer(served, `module.${name}`)).toBe('MARK_X') }, ) }) diff --git a/packages/start-plugin-core/tests/start-host.ts b/packages/start-plugin-core/tests/start-host.ts index 4587ede6ee..91b20b3921 100644 --- a/packages/start-plugin-core/tests/start-host.ts +++ b/packages/start-plugin-core/tests/start-host.ts @@ -89,6 +89,11 @@ export interface StartHostOptions { * `false`: no dev server (a host for `build()` only). Default `true`. */ serve?: boolean + /** + * Options of the React app's `@vitejs/plugin-react` (`react(options)`), + * e.g. `{ jsxRuntime: 'classic' }`. + */ + react?: Parameters[0] } const harnessDir = path.dirname(fileURLToPath(import.meta.url)) @@ -135,9 +140,12 @@ export function startPluginFactory( } /** The framework's own Vite plugin, as a user configures it. */ -function frameworkPlugins(framework: StartFramework): Array { +function frameworkPlugins( + framework: StartFramework, + options: StartHostOptions = {}, +): Array { if (framework === 'react') { - return [react()] + return [react(options.react)] } if (framework === 'solid') { return [solid({ ssr: true })] @@ -460,7 +468,7 @@ export async function createStartHost( plugins: (app) => [ ...(serve ? [] : [absoluteOutDir(app.root)]), tanstackStart(options.start), - ...frameworkPlugins(framework), + ...frameworkPlugins(framework, options), ...(typeof userPlugins === 'function' ? userPlugins(app) : userPlugins), ], config: { @@ -801,7 +809,7 @@ try { plugins: [ absoluteOutDir(root), tanstackStart(options.start), - ...frameworkPlugins(framework), + ...frameworkPlugins(framework, options), ...(typeof userPlugins === 'function' ? userPlugins({ root, command: 'build' }) : userPlugins),