diff --git a/packages/start-plugin-core/tests/createServerFn/ported-nextjs-server-actions.test.ts b/packages/start-plugin-core/tests/createServerFn/ported-nextjs-server-actions.test.ts index 6d0dc61f12..60bd041323 100644 --- a/packages/start-plugin-core/tests/createServerFn/ported-nextjs-server-actions.test.ts +++ b/packages/start-plugin-core/tests/createServerFn/ported-nextjs-server-actions.test.ts @@ -4,146 +4,16 @@ * Each test names the fixture directories (`server-graph/N`, `client-graph/N`) * whose scenario it translates to `createServerFn`. */ -import { transformWithOxc } from 'vite' import { describe, expect, test } from 'vitest' import { - StartCompiler, - detectKindsInCode, - getLookupKindsForEnv, -} from '../../src/start-compiler/compiler' -import { getLookupConfigurationsForEnv } from '../../src/start-compiler/config' -import { declarationOf, getModuleErrors } from '../validate-module' -import type { ServerFn } from '../../src/start-compiler/types' - -type Output = 'client' | 'ssr' | 'provider' -const outputs: Array = ['client', 'ssr', 'provider'] - -async function compileFor( - output: Output, - code: string, - mode: 'build' | 'dev' = 'build', -) { - const env = output === 'client' ? 'client' : 'server' - const serverFns: Record = {} - const compiler = new StartCompiler({ - env, - envName: env === 'client' ? 'client' : 'ssr', - root: '/test', - framework: 'react', - providerEnvName: 'ssr', - mode, - lookupKinds: getLookupKindsForEnv(env), - lookupConfigurations: getLookupConfigurationsForEnv(env, 'react'), - getKnownServerFns: () => ({}), - devServerFnModuleSpecifierEncoder: ({ extractedFilename, root }) => - `/@id${extractedFilename.slice(root.length)}`, - onServerFnsById: (fns) => Object.assign(serverFns, fns), - loadModule: async () => {}, - resolveId: async (id) => (id.startsWith('@tanstack/') ? id : null), - }) - const id = '/test/src/module.tsx' - const result = await compiler.compile({ - code, - id: output === 'provider' ? `${id}?tss-serverfn-split` : id, - detectedKinds: detectKindsInCode(code, env), - }) - return { code: result?.code ?? null, serverFns } -} - -/** Compiles the client, SSR caller and provider outputs and validates each. */ -async function compileAll(code: string) { - const compiled = {} as Record - const errors = {} as Record> - let serverFns: Record = {} - for (const output of outputs) { - const result = await compileFor(output, code) - expect(result.code, output).not.toBeNull() - compiled[output] = result.code! - errors[output] = await getModuleErrors(result.code!) - if (output === 'client') { - serverFns = result.serverFns - } - } - expect(errors).toEqual({ client: [], ssr: [], provider: [] }) - const idOf = (functionName: string) => - Object.values(serverFns).find((fn) => fn.functionName === functionName) - ?.functionId - return { ...compiled, serverFns, idOf } -} - -/** Matches the source of an import or re-export statement. */ -const moduleSource = - /^(\s*import\s*|\s*(?:import|export)\b[^;'"]*?\bfrom\s*)(["'])([^"']+)\2/gm - -/** Project-local import sources of a module, sorted. */ -function importSources(code: string) { - return [...code.matchAll(moduleSource)] - .map((match) => match[3]!) - .filter((source) => !source.startsWith('@tanstack/')) - .sort() -} - -const dataUrl = (code: string) => - `data:text/javascript,${encodeURIComponent(code)}` - -/** - * Minimal Start runtime: callers keep the RPC they were given, providers run - * the original handler through `__executeServer`. - */ -const startRuntime: Record = { - '@tanstack/react-start': ` -const builder = () => { - const self = { - middleware: () => self, - validator: () => self, - inputValidator: () => self, - handler: (rpc, impl) => - impl - ? Object.assign((data) => impl({ data }), { - __executeServer: (opts) => impl(opts), - }) - : { rpc }, - } - return self -} -export const createServerFn = builder`, - '@tanstack/react-start/server-rpc': `export const createServerRpc = (meta, fn) => Object.assign(fn, { meta })`, - '@tanstack/react-start/client-rpc': `export const createClientRpc = (id) => ({ client: id })`, - '@tanstack/react-start/ssr-rpc': `export const createSsrRpc = (id) => ({ ssr: id })`, -} - -/** Evaluates a compiled module, resolving every import to the given stubs. */ -async function importModule( - code: string, - modules: Record = {}, -): Promise> { - const sources = { ...startRuntime, ...modules } - const { code: javascript } = await transformWithOxc(code, 'module.ts') - const linked = javascript.replace( - moduleSource, - (_match, prefix: string, _quote: string, source: string) => { - const stub = sources[source] - if (stub === undefined) { - throw new Error(`No stub for import ${source}`) - } - return `${prefix}${JSON.stringify(dataUrl(stub))}` - }, - ) - return import(/* @vite-ignore */ dataUrl(linked)) -} - -/** Runs a provider's extracted handler the way the server-fn router does. */ -async function callProvider( - provider: string, - name: string, - modules: Record = {}, - data?: unknown, -) { - const module = await importModule(provider, modules) - const handler = module[`${name}_createServerFn_handler`] - expect(handler, name).toBeTypeOf('function') - return handler({ data }) -} + callProvider, + compileAll, + compileFor, + importModule, + importSources, + outputs, +} from '../regression-helpers' +import { declarationOf } from '../validate-module' const dbServer = `export const db = { x: () => 'x', y: () => 'y', z: () => 'z', w: () => 'w', @@ -621,7 +491,7 @@ ${names.map((name) => `export const ${name} = createServerFn().handler(async () expect(await handler({})).toBe(name) } - const dev = await compileFor('client', code, 'dev') + const dev = await compileFor('client', code, { mode: 'dev' }) expect( Object.keys(dev.serverFns) .map( diff --git a/packages/start-plugin-core/tests/hydrate-split-edge-cases.test.ts b/packages/start-plugin-core/tests/hydrate-split-edge-cases.test.ts index 8f9644fa9a..9258ed765c 100644 --- a/packages/start-plugin-core/tests/hydrate-split-edge-cases.test.ts +++ b/packages/start-plugin-core/tests/hydrate-split-edge-cases.test.ts @@ -1,74 +1,14 @@ -import { parseSync, transformWithOxc } from 'vite' +import { parseSync } from 'vite' import { describe, expect, test } from 'vitest' import { createHydrateCompilerPlugin } from '../src/hydrate-when-transform' import { compileStartModule } from './compile-start-module' +import { + compileHydrate, + getChunkParams, + renderChunk, +} from './regression-helpers' import { getModuleErrors } from './validate-module' -/** Compiles a module with `` and loads the split chunks it imports. */ -async function compileHydrate(env: 'client' | 'server', code: string) { - const plugin = createHydrateCompilerPlugin() - const parent = await compileStartModule({ - env, - code, - compilerPlugins: [plugin], - }) - if (parent === null) { - throw new Error('expected the module to be transformed') - } - const chunks = [...parent.matchAll(/import\((["'])(.+?)\1\)/g)].map( - ([, , id]) => { - const chunk = plugin.loadVirtualModule?.({ - id: id!, - root: '/test', - env, - envName: env === 'client' ? 'client' : 'ssr', - }) - if (!chunk) { - throw new Error(`expected virtual module ${id} to load`) - } - return chunk.code - }, - ) - // Order chunks by boundary index, however the parent declares them. - const index = (chunk: string) => - Number(chunk.match(/export function H(\d+)\(/)?.[1] ?? -1) - chunks.sort((a, b) => index(a) - index(b)) - return { parent, chunks, plugin } -} - -/** - * Evaluates a self-contained chunk (no imports) like a bundler would and - * renders one of its exports to a string: JSX becomes plain function calls - * and intrinsic elements become tags. - */ -async function renderChunkExport( - chunk: string, - exportName: string, - props: Record = {}, -) { - const { code } = await transformWithOxc(chunk, 'chunk.tsx', { - jsx: { runtime: 'classic', pragma: 'h', pragmaFrag: 'Fragment' }, - }) - const runtime = `const Fragment = Symbol('Fragment') -const h = (type, props, ...children) => { - const text = children.flat(Infinity).filter((c) => c != null && c !== false).join('') - if (type === Fragment) return text - if (typeof type === 'function') return type({ ...props, children: text }) - return '<' + type + '>' + text + '' -} -` - const module: Record string> = await import( - /* @vite-ignore */ `data:text/javascript,${encodeURIComponent(runtime + code)}` - ) - return module[exportName]!(props) -} - -/** Every split-chunk component name and the props the parent passes to it. */ -function getChunkParams(chunk: string) { - const params = chunk.match(/export function H\d+\(([^)]*)\)/)?.[1] ?? '' - return [...params.matchAll(/[\w$]+/g)].map(([name]) => name).sort() -} - type JsxNode = { type: string name?: { type: string; name?: string } @@ -140,7 +80,7 @@ export function Page() { ) expect(chunks).toHaveLength(1) expect(await getModuleErrors(chunks[0]!)).toEqual([]) - expect(await renderChunkExport(chunks[0]!, 'H0')).toBe(rendered) + expect(await renderChunk(chunks[0]!)).toBe(rendered) }, ) @@ -207,11 +147,11 @@ export function Page({ prefix = 'p', ...rest }) { } // Module-level helpers move into the chunk with the children. expect(parent).not.toMatch(/function Row\b/) + expect(await renderChunk(chunks[0]!, { label: 'p-a', value: 1 })).toBe( + '
  • p-a1
  • ', + ) expect( - await renderChunkExport(chunks[0]!, 'H0', { label: 'p-a', value: 1 }), - ).toBe('
  • p-a1
  • ') - expect( - await renderChunkExport(chunks[1]!, 'H1', { + await renderChunk(chunks[1]!, { item: 'x', i: 0, prefix: 'p', @@ -240,7 +180,7 @@ export function Page() { expect(await getModuleErrors(chunks[0]!)).toEqual([]) expect(getChunkParams(chunks[0]!)).toEqual(['error', 'later', 'value']) expect( - await renderChunkExport(chunks[0]!, 'H0', { + await renderChunk(chunks[0]!, { value: 'local', error: new Error('caught'), later: () => 'hoisted', @@ -277,7 +217,7 @@ export function Page() { `, ) expect(chunks).toHaveLength(1) - expect(await renderChunkExport(chunks[0]!, 'H0')).toBe('

    child

    ') + expect(await renderChunk(chunks[0]!)).toBe('

    child

    ') }, ) @@ -335,9 +275,9 @@ export function Page() { ) expect(await getModuleErrors(parent)).toEqual([]) expect(chunks).toHaveLength(2) - for (const [index, chunk] of chunks.entries()) { + for (const chunk of chunks) { expect(await getModuleErrors(chunk)).toEqual([]) - expect(await renderChunkExport(chunk, `H${index}`)).toBeNull() + expect(await renderChunk(chunk)).toBeNull() } }) diff --git a/packages/start-plugin-core/tests/hydrate-split-modules.test.ts b/packages/start-plugin-core/tests/hydrate-split-modules.test.ts index 1b72bd226b..7c7d8c2be3 100644 --- a/packages/start-plugin-core/tests/hydrate-split-modules.test.ts +++ b/packages/start-plugin-core/tests/hydrate-split-modules.test.ts @@ -1,49 +1,17 @@ -import { transformWithOxc } from 'vite' import { describe, expect, test } from 'vitest' -import { createHydrateCompilerPlugin } from '../src/hydrate-when-transform' -import { compileStartModule } from './compile-start-module' - -/** Compiles a module with `` and loads the split chunks it imports. */ -async function compileHydrate(env: 'client' | 'server', code: string) { - const plugin = createHydrateCompilerPlugin() - const parent = await compileStartModule({ - env, - code, - compilerPlugins: [plugin], - }) - if (parent === null) { - throw new Error('expected the module to be transformed') - } - const chunks = [...parent.matchAll(/import\((["'])(.+?)\1\)/g)].map( - ([, , id]) => { - const chunk = plugin.loadVirtualModule?.({ - id: id!, - root: '/test', - env, - envName: env === 'client' ? 'client' : 'ssr', - }) - if (!chunk) { - throw new Error(`expected virtual module ${id} to load`) - } - return chunk.code - }, - ) - return { parent, chunks } -} +import { compileHydrate, evaluateModule } from './regression-helpers' /** * Compiles a chunk's JSX like a bundler would and returns the text its * components render, so JSX text and string literals are compared by meaning. */ async function renderChunkText(chunk: string) { - const { code } = await transformWithOxc(chunk, 'chunk.tsx', { - jsx: { runtime: 'classic', pragma: 'h', pragmaFrag: 'Fragment' }, - }) - const runtime = `const Fragment = null + const module = await evaluateModule( + chunk, + {}, + `const Fragment = null const h = (type, props, ...children) => children.flat().join('') -` - const module: Record = await import( - /* @vite-ignore */ `data:text/javascript,${encodeURIComponent(runtime + code)}` +`, ) return Object.values(module) .map((value) => (typeof value === 'function' ? value() : '')) diff --git a/packages/start-plugin-core/tests/ported-babel-dce.test.ts b/packages/start-plugin-core/tests/ported-babel-dce.test.ts index 886f51db66..1a78043299 100644 --- a/packages/start-plugin-core/tests/ported-babel-dce.test.ts +++ b/packages/start-plugin-core/tests/ported-babel-dce.test.ts @@ -7,92 +7,10 @@ * then everything only they used; these tests check which bindings that * removal prunes and which it keeps. */ -import { transformWithOxc } from 'vite' import { describe, expect, test } from 'vitest' -import { - StartCompiler, - detectKindsInCode, - getLookupKindsForEnv, -} from '../src/start-compiler/compiler' -import { getLookupConfigurationsForEnv } from '../src/start-compiler/config' +import { compileAll, compileFor, importModule } from './regression-helpers' import { declarationOf, getModuleErrors } from './validate-module' -type Output = 'client' | 'ssr' | 'provider' - -async function compileFor(output: Output, code: string) { - const env = output === 'client' ? 'client' : 'server' - const compiler = new StartCompiler({ - env, - envName: env === 'client' ? 'client' : 'ssr', - root: '/test', - framework: 'react', - providerEnvName: 'ssr', - mode: 'build', - lookupKinds: getLookupKindsForEnv(env), - lookupConfigurations: getLookupConfigurationsForEnv(env, 'react'), - getKnownServerFns: () => ({}), - loadModule: async () => {}, - resolveId: async (id) => (id.startsWith('@tanstack/') ? id : null), - }) - const id = '/test/src/module.tsx' - const result = await compiler.compile({ - code, - id: output === 'provider' ? `${id}?tss-serverfn-split` : id, - detectedKinds: detectKindsInCode(code, env), - }) - expect(result, output).not.toBeNull() - return result!.code -} - -/** Compiles the client, SSR caller and provider outputs and validates each. */ -async function compileAll(code: string) { - const compiled = {} as Record - const errors = {} as Record> - for (const output of ['client', 'ssr', 'provider'] as const) { - compiled[output] = await compileFor(output, code) - errors[output] = await getModuleErrors(compiled[output]) - } - expect(errors).toEqual({ client: [], ssr: [], provider: [] }) - return compiled -} - -/** Matches the source of an import or re-export statement. */ -const moduleSource = - /^(\s*import\s*|\s*(?:import|export)\b[^;'"]*?\bfrom\s*)(["'])([^"']+)\2/gm - -const dataUrl = (code: string) => - `data:text/javascript,${encodeURIComponent(code)}` - -const startRuntime: Record = { - '@tanstack/react-start': ` -const builder = () => { - const self = { handler: (rpc) => ({ rpc }) } - return self -} -export const createServerFn = builder`, - '@tanstack/react-start/client-rpc': `export const createClientRpc = (id) => ({ client: id })`, -} - -/** Evaluates a compiled module, resolving every import to the given stubs. */ -async function importModule( - code: string, - modules: Record, -): Promise> { - const sources = { ...startRuntime, ...modules } - const { code: javascript } = await transformWithOxc(code, 'module.ts') - const linked = javascript.replace( - moduleSource, - (_match, prefix: string, _quote: string, source: string) => { - const stub = sources[source] - if (stub === undefined) { - throw new Error(`No stub for import ${source}`) - } - return `${prefix}${JSON.stringify(dataUrl(stub))}` - }, - ) - return import(/* @vite-ignore */ dataUrl(linked)) -} - const head = `import { createServerFn } from '@tanstack/react-start'\n` describe('ported babel-dead-code-elimination: imports', () => { @@ -250,7 +168,7 @@ export const fn = createServerFn().handler(async () => [flag, conn, mode, labele // Source: dead-code-elimination.test.ts "variable" > "within for...in" test('the client drops a var nested in a function block that only the server implementation reads', async () => { - const client = await compileFor( + const { code: client } = await compileFor( 'client', `import { createIsomorphicFn } from '@tanstack/react-start' import { serverCall } from './db.server' @@ -263,7 +181,8 @@ export function getValue(flag: boolean) { } `, ) - expect(await getModuleErrors(client)).toEqual([]) + expect(client).not.toBeNull() + expect(await getModuleErrors(client!)).toEqual([]) expect(client).not.toContain('./db.server') expect(client).not.toContain('serverCall()') }) diff --git a/packages/start-plugin-core/tests/ported-qwik-optimizer.test.ts b/packages/start-plugin-core/tests/ported-qwik-optimizer.test.ts index a858800d46..c185e810c7 100644 --- a/packages/start-plugin-core/tests/ported-qwik-optimizer.test.ts +++ b/packages/start-plugin-core/tests/ported-qwik-optimizer.test.ts @@ -6,98 +6,31 @@ * code splitting move module-level code between modules. Each test names the * Qwik test it is ported from. */ -import { parseSync, transformWithOxc } from 'vite' +import { parseSync } from 'vite' import { describe, expect, test } from 'vitest' -import { createHydrateCompilerPlugin } from '../src/hydrate-when-transform' -import { - StartCompiler, - detectKindsInCode, - getLookupKindsForEnv, -} from '../src/start-compiler/compiler' -import { getLookupConfigurationsForEnv } from '../src/start-compiler/config' import { compileStartModule } from './compile-start-module' +import { + compileHydrate, + createStartCompiler, + evaluateModule, + getChunkIds, + getChunkParams, + loadChunk, + renderChunk, +} from './regression-helpers' import { getModuleErrors } from './validate-module' +import type { createHydrateCompilerPlugin } from '../src/hydrate-when-transform' -const parentId = '/test/src/module.tsx' -type Env = 'client' | 'server' -type HydratePlugin = ReturnType - -/** - * Compiles one module through `StartCompiler` like the bundler plugins do: the - * parent module, or a loaded split chunk under its virtual module id. - */ -async function compileModule( - plugin: HydratePlugin, - env: Env, +/** Compiles a loaded split chunk under its virtual module id, like the bundler. */ +function compileChunk( + plugin: ReturnType, code: string, - id = parentId, + id: string, ) { - const compiler: StartCompiler = new StartCompiler({ - env, - envName: env === 'client' ? 'client' : 'ssr', - root: '/test', - framework: 'react', - providerEnvName: 'ssr', - mode: 'build', - lookupKinds: getLookupKindsForEnv(env), - lookupConfigurations: getLookupConfigurationsForEnv(env, 'react'), - getKnownServerFns: () => ({}), - loadModule: async () => {}, - resolveId: async (source) => - source.startsWith('@tanstack/') ? source : null, + return createStartCompiler({ + env: 'client', compilerPlugins: [plugin], - }) - const result = await compiler.compile({ - code, - id, - detectedKinds: detectKindsInCode(code, env), - }) - return result?.code ?? null -} - -/** The Hydrate chunk ids a compiled module imports, in source order. */ -function getChunkIds(code: string) { - return [...code.matchAll(/import\((["'])(.+?)\1\)/g)] - .map(([, , id]) => id!) - .filter((id) => id.includes('tss-hydrate=')) -} - -function loadChunk(plugin: HydratePlugin, env: Env, id: string) { - return ( - plugin.loadVirtualModule?.({ - id, - root: '/test', - env, - envName: env === 'client' ? 'client' : 'ssr', - })?.code ?? null - ) -} - -/** Compiles a module with `` and loads the split chunks it imports. */ -async function compileHydrate(env: Env, code: string) { - const plugin = createHydrateCompilerPlugin() - const parent = await compileModule(plugin, env, code) - if (parent === null) { - throw new Error('expected the module to be transformed') - } - const chunks = getChunkIds(parent).map((id) => { - const chunk = loadChunk(plugin, env, id) - if (chunk === null) { - throw new Error(`expected virtual module ${id} to load`) - } - return chunk - }) - // Order chunks by boundary index, however the parent declares them. - const index = (chunk: string) => - Number(chunk.match(/export function H(\d+)\(/)?.[1] ?? -1) - chunks.sort((a, b) => index(a) - index(b)) - return { parent, chunks, plugin } -} - -/** The names a split chunk component receives as props. */ -function getChunkParams(chunk: string) { - const params = chunk.match(/export function H\d+\(([^)]*)\)/)?.[1] ?? '' - return [...params.matchAll(/[\w$]+/g)].map(([name]) => name).sort() + }).compile(code, id) } /** Boundary ids (`h` props) a compiled module renders, in source order. */ @@ -105,79 +38,6 @@ function getBoundaryIds(code: string) { return [...code.matchAll(/\bh=\s*["']([^"']+)["']/g)].map(([, id]) => id!) } -const stubsKey = '__portedQwikOptimizerStubs' -let evaluations = 0 - -/** Renders JSX to text: intrinsic elements become tags, components are called. */ -const renderRuntime = `const Fragment = Symbol('Fragment') -const h = (type, props, ...children) => { - const text = children.flat(Infinity).filter((c) => c != null && c !== false && c !== true).join('') - if (type === Fragment) return text - if (typeof type === 'function') return type({ ...props, children: text }) - if (typeof type !== 'string') throw new Error('cannot render ' + String(type)) - return '<' + type + '>' + text + '' -} -` - -/** - * Evaluates a compiled module like a bundler would: JSX becomes plain calls - * of the `runtime`, and imports are linked to `stubs`, keyed by specifier. - */ -async function evaluate( - code: string, - stubs: Record> = {}, - runtime = renderRuntime, -): Promise) => unknown>> { - const { code: javascript } = await transformWithOxc(code, 'module.tsx', { - jsx: { runtime: 'classic', pragma: 'h', pragmaFrag: 'Fragment' }, - }) - const key = `${stubsKey}${evaluations++}` - ;(globalThis as Record)[key] = stubs - // Imports are hoisted: link them before any other statement runs. - const imports: Array = [] - const body = javascript.replace( - /^import\s+(.+?)\s+from\s+(["'])(.+?)\2;?$/gm, - (_, clause: string, __, source: string) => { - if (!(source in stubs)) { - throw new Error(`no stub for import ${source}`) - } - const from = `globalThis.${key}[${JSON.stringify(source)}]` - const named = clause.match(/\{(.*)\}/)?.[1] - const head = clause - .replace(/\{.*\}/, '') - .replace(/,\s*$/, '') - .trim() - if (named) { - imports.push(`const { ${named.replace(/\bas\b/g, ':')} } = ${from};`) - } - if (head.startsWith('* as ')) { - imports.push(`const ${head.slice(5)} = ${from};`) - } else if (head) { - imports.push(`const ${head} = ${from}.default;`) - } - return '' - }, - ) - const linked = `${imports.join('\n')}\n${body}` - return import( - /* @vite-ignore */ `data:text/javascript,${encodeURIComponent(runtime + linked)}` - ) -} - -/** Renders a chunk's component export with the given props. */ -async function renderChunk( - chunk: string, - props: Record = {}, - stubs: Record> = {}, -) { - const module = await evaluate(chunk, stubs) - const name = Object.keys(module).find((key) => /^H\d+$/.test(key)) - if (!name) { - throw new Error('expected the chunk to export a component') - } - return module[name]!(props) -} - const startStubs = { '@tanstack/react-start': { Hydrate: (props: { children: unknown }) => props.children, @@ -458,7 +318,7 @@ export function Page() { ) expect(await getModuleErrors(parent)).toEqual([]) // The lazy chunk component must not be shadowed by the captured locals. - const module = await evaluate(parent, startStubs) + const module = await evaluateModule(parent, startStubs) expect(module.Page!()).toBe('lazy(_H0=local,_H0_preload=preload)') expect( await renderChunk(chunks[0]!, { _H0: 'local', _H0_preload: 'preload' }), @@ -571,12 +431,12 @@ export function Page() { const propsRuntime = `const Fragment = null const h = (type, props) => JSON.stringify(props) ` - const expected = await evaluate( + const expected = await evaluateModule( `export const H0 = () => ${element}`, {}, propsRuntime, ) - const module = await evaluate(chunks[0]!, {}, propsRuntime) + const module = await evaluateModule(chunks[0]!, {}, propsRuntime) expect(module.H0!({})).toBe(expected.H0!()) }) @@ -627,7 +487,7 @@ export function Page() { `, ) expect(await getModuleErrors(chunks[0]!)).toEqual([]) - const module = await evaluate(chunks[0]!) + const module = await evaluateModule(chunks[0]!) expect(module.H0!({})).toBe('

    1

    ') expect(module.H0!({})).toBe('

    2

    ') }) @@ -655,7 +515,7 @@ export function Page() { expect(await getModuleErrors(parent)).toEqual([]) expect(await getModuleErrors(chunks[0]!)).toEqual([]) expect(getDeclaredNames(parent).has('b')).toBe(true) - const module = await evaluate(parent, startStubs) + const module = await evaluateModule(parent, startStubs) expect(module.fromRoot!()).toMatch(/B/) expect(await renderChunk(chunks[0]!)).toBe('

    A

    ') }, @@ -694,7 +554,7 @@ export function Page() { `, ) expect(await getModuleErrors(parent)).toEqual([]) - const module = await evaluate(parent, startStubs) + const module = await evaluateModule(parent, startStubs) expect(module.exportedValue).toBe('abc') expect(module.readShared!()).toBe('abc') expect(await renderChunk(chunks[0]!)).toBe('

    abc

    ') @@ -717,7 +577,7 @@ export function App() { ) expect(chunks).toHaveLength(2) expect(await getModuleErrors(parent)).toEqual([]) - const module = await evaluate(parent, startStubs) + const module = await evaluateModule(parent, startStubs) expect(module.direct!()).toBe(2) expect(await renderChunk(chunks[0]!)).toBe('

    3

    ') expect(await renderChunk(chunks[1]!)).toBe('

    4

    ') @@ -754,9 +614,8 @@ export function Page({ isOpen, fee }) { const { parent, chunks, plugin } = await compileHydrate('client', code) expect(getChunkParams(chunks[0]!)).toEqual(['fee', 'isOpen', 'label']) // The bundler compiles the loaded chunk like any other module. - const outer = await compileModule( + const outer = await compileChunk( plugin, - 'client', chunks[0]!, getChunkIds(parent)[0]!, ) @@ -837,7 +696,7 @@ export function Card(label, body) { `, ) expect(await getModuleErrors(parent)).toEqual([]) - const module = await evaluate(parent, startStubs) + const module = await evaluateModule(parent, startStubs) expect(module.List!({ items: ['a', 'b'] })).toBe( '
    • 0
    • 1
    ', ) @@ -887,7 +746,7 @@ export function Page(props) { } `, ) - const module = await evaluate(parent, startStubs) + const module = await evaluateModule(parent, startStubs) expect(module.Page!({ a: 'A', b: 'B' })).toBe('

    B

    ') }) }) @@ -929,9 +788,8 @@ export function Page() { 'client: $name calls the provider id from the split chunk', async ({ code }) => { const { parent, chunks, plugin } = await compileHydrate('client', code) - const chunk = await compileModule( + const chunk = await compileChunk( plugin, - 'client', chunks[0]!, getChunkIds(parent)[0]!, ) diff --git a/packages/start-plugin-core/tests/ported-react-compiler-fixtures.test.ts b/packages/start-plugin-core/tests/ported-react-compiler-fixtures.test.ts index c9775b5bd7..3532db5720 100644 --- a/packages/start-plugin-core/tests/ported-react-compiler-fixtures.test.ts +++ b/packages/start-plugin-core/tests/ported-react-compiler-fixtures.test.ts @@ -1,7 +1,6 @@ -import { transformWithOxc } from 'vite' import { afterEach, describe, expect, test } from 'vitest' -import { createHydrateCompilerPlugin } from '../src/hydrate-when-transform' import { compileStartModule } from './compile-start-module' +import { compileHydrate, renderChunk } from './regression-helpers' import { getModuleErrors } from './validate-module' // Inputs adapted from the React Compiler fixture corpus @@ -9,47 +8,9 @@ import { getModuleErrors } from './validate-module' /** Compiles a module with one `` boundary and loads its client chunk. */ async function compileHydrateChunk(code: string) { - const plugin = createHydrateCompilerPlugin() - const parent = await compileStartModule({ - env: 'client', - code, - compilerPlugins: [plugin], - }) - const ids = [...(parent ?? '').matchAll(/import\((["'])(.+?)\1\)/g)] - expect(ids).toHaveLength(1) - const chunk = plugin.loadVirtualModule?.({ - id: ids[0]![2]!, - root: '/test', - env: 'client', - envName: 'client', - }) - if (!chunk) { - throw new Error('expected the Hydrate chunk to load') - } - return { parent: parent!, chunk: chunk.code } -} - -/** - * Evaluates a self-contained chunk (no imports) like a bundler would and - * renders its `H0` export: JSX becomes plain function calls and intrinsic - * elements become tags. - */ -async function renderChunk(chunk: string, props: Record) { - const { code } = await transformWithOxc(chunk, 'chunk.tsx', { - jsx: { runtime: 'classic', pragma: 'h', pragmaFrag: 'Fragment' }, - }) - const runtime = `const Fragment = Symbol('Fragment') -const h = (type, props, ...children) => { - const text = children.flat(Infinity).filter((c) => c != null && c !== false).join('') - if (type === Fragment) return text - if (typeof type === 'function') return type({ ...props, children: text }) - return '<' + type + '>' + text + '' -} -` - const module: Record string> = await import( - /* @vite-ignore */ `data:text/javascript,${encodeURIComponent(runtime + code)}` - ) - return module.H0!({ props }) + const { parent, chunks } = await compileHydrate('client', code) + expect(chunks).toHaveLength(1) + return { parent, chunk: chunks[0]! } } const hydratePage = ( @@ -168,7 +129,7 @@ function Widget() { const { parent, chunk } = await compileHydrateChunk(hydratePage(body)) expect(await getModuleErrors(parent)).toEqual([]) expect(await getModuleErrors(chunk)).toEqual([]) - expect(await renderChunk(chunk, props ?? {})).toBe(expected) + expect(await renderChunk(chunk, { props: props ?? {} })).toBe(expected) }, ) }) @@ -205,7 +166,7 @@ function Widget() { ) const calls: Array = [] ;(globalThis as { __portedTrack?: Array }).__portedTrack = calls - expect(await renderChunk(chunk, {})).toBe('

    widget

    ') + expect(await renderChunk(chunk, { props: {} })).toBe('

    widget

    ') expect(calls).toHaveLength(1) }, ) diff --git a/packages/start-plugin-core/tests/ported-solid-start-directives.test.ts b/packages/start-plugin-core/tests/ported-solid-start-directives.test.ts index 3ba4e4ba12..885ff7f25a 100644 --- a/packages/start-plugin-core/tests/ported-solid-start-directives.test.ts +++ b/packages/start-plugin-core/tests/ported-solid-start-directives.test.ts @@ -5,153 +5,21 @@ * helpers). Each test names the SolidStart test or helper whose scenario it * translates to `createServerFn`, the env-only functions or ``. */ -import { transformWithOxc } from 'vite' import { describe, expect, test } from 'vitest' import { - StartCompiler, - detectKindsInCode, - getLookupKindsForEnv, -} from '../src/start-compiler/compiler' -import { getLookupConfigurationsForEnv } from '../src/start-compiler/config' -import { createHydrateCompilerPlugin } from '../src/hydrate-when-transform' + clientOnlyError as clientOnly, + compileAll, + compileFor, + compileHydrate as compileHydrateModule, + frameworks, + getChunkParams, + importModule, + importSources, + renderChunk, + serverOnlyError as serverOnly, + settle, +} from './regression-helpers' import { getModuleErrors } from './validate-module' -import type { ServerFn } from '../src/start-compiler/types' - -type Output = 'client' | 'ssr' | 'provider' -type Framework = 'react' | 'solid' -const frameworks: Array = ['react', 'solid'] - -async function compile( - output: Output, - code: string, - options: { framework?: Framework; mode?: 'build' | 'dev'; id?: string } = {}, -) { - const env = output === 'client' ? 'client' : 'server' - const framework = options.framework ?? 'react' - const serverFns: Record = {} - const compiler = new StartCompiler({ - env, - envName: env === 'client' ? 'client' : 'ssr', - root: '/test', - framework, - providerEnvName: 'ssr', - mode: options.mode ?? 'build', - lookupKinds: getLookupKindsForEnv(env), - lookupConfigurations: getLookupConfigurationsForEnv(env, framework), - getKnownServerFns: () => ({}), - devServerFnModuleSpecifierEncoder: ({ extractedFilename, root }) => - `/@id${extractedFilename.slice(root.length)}`, - onServerFnsById: (fns) => Object.assign(serverFns, fns), - loadModule: async () => {}, - resolveId: async (id) => (id.startsWith('@tanstack/') ? id : null), - }) - const id = options.id ?? '/test/src/module.tsx' - const result = await compiler.compile({ - code, - id: output === 'provider' ? `${id}?tss-serverfn-split` : id, - detectedKinds: detectKindsInCode(code, env), - }) - return { code: result?.code ?? null, serverFns } -} - -/** Compiles every output, checks each is a valid module and returns them. */ -async function compileAll(code: string, framework: Framework = 'react') { - const compiled = {} as Record - const errors = {} as Record> - for (const output of ['client', 'ssr', 'provider'] as const) { - const { code: result } = await compile(output, code, { framework }) - expect(result, output).not.toBeNull() - compiled[output] = result! - errors[output] = await getModuleErrors(result!) - } - expect(errors).toEqual({ client: [], ssr: [], provider: [] }) - return compiled -} - -/** Matches the source of an import or re-export statement. */ -const moduleSource = - /^(\s*import\s*|\s*(?:import|export)\b[^;'"]*?\bfrom\s*)(["'])([^"']+)\2/gm - -/** Project-local import sources of a module, sorted. */ -function importSources(code: string) { - return [...code.matchAll(moduleSource)] - .map((match) => match[3]!) - .filter((source) => !source.startsWith('@tanstack/')) - .sort() -} - -const dataUrl = (code: string) => - `data:text/javascript,${encodeURIComponent(code)}` - -/** Uncompiled factories throw, so a test only passes if the compiler ran. */ -const startPackage = ` -const uncompiled = () => { throw new Error('uncompiled Start factory') } -const builder = () => { - const self = { - middleware: () => self, - validator: () => self, - handler: (rpc, impl) => - impl ? { __executeServer: (opts) => impl(opts) } : { rpc }, - } - return self -} -export const createServerFn = builder -export const createServerOnlyFn = uncompiled -export const createClientOnlyFn = uncompiled -export const createIsomorphicFn = uncompiled -export const createMiddleware = uncompiled` - -const runtime: Record = {} -for (const framework of frameworks) { - runtime[`@tanstack/${framework}-start`] = startPackage - runtime[`@tanstack/${framework}-start/server-rpc`] = - `export const createServerRpc = (meta, fn) => Object.assign(fn, { meta })` - runtime[`@tanstack/${framework}-start/client-rpc`] = - `export const createClientRpc = (id) => ({ client: id })` - runtime[`@tanstack/${framework}-start/ssr-rpc`] = - `export const createSsrRpc = (id) => ({ ssr: id })` -} - -let evaluations = 0 - -/** - * Evaluates a compiled module, resolving every import to the given stubs. - * Every call evaluates a fresh instance, even for identical code. - */ -async function importModule( - code: string, - modules: Record = {}, -): Promise> { - const sources = { ...runtime, ...modules } - const { code: javascript } = await transformWithOxc(code, 'module.ts') - const linked = javascript.replace( - moduleSource, - (_match, prefix: string, _quote: string, source: string) => { - const stub = sources[source] - if (stub === undefined) { - throw new Error(`No stub for import ${source}`) - } - return `${prefix}${JSON.stringify(dataUrl(stub))}` - }, - ) - return import( - /* @vite-ignore */ dataUrl(`${linked}\n// evaluation ${++evaluations}`) - ) -} - -/** The value of `run`, or the message of the error it throws. */ -function settle(run: () => unknown) { - try { - return run() - } catch (error) { - return `throws: ${(error as Error).message}` - } -} - -const serverOnly = - 'throws: createServerOnlyFn() functions can only be called on the server!' -const clientOnly = - 'throws: createClientOnlyFn() functions can only be called on the client!' describe.each(frameworks)('ported SolidStart directives (%s)', (framework) => { const start = `import { createServerFn, createServerOnlyFn, createClientOnlyFn, createIsomorphicFn } from '@tanstack/${framework}-start'` @@ -167,7 +35,7 @@ describe.each(frameworks)('ported SolidStart directives (%s)', (framework) => { `${start} ${imports} export const serverAction = createServerFn().handler(async (): Promise => verify())`, - framework, + { framework }, ) expect(importSources(compiled.client)).toEqual([]) expect(importSources(compiled.ssr)).toEqual([]) @@ -193,7 +61,7 @@ export const serverAction = createServerFn().handler(async (): Promise => ${call})`, - framework, + { framework }, ) const modules = { './server-module': `export const clientValue = 'client'; export const verify = () => 'verified'; export default verify`, @@ -326,7 +194,7 @@ export class Api extends Base { ])( 'an env-only function keeps $name', async ({ code, run, client, server }) => { - const compiled = await compileAll(`${start}\n${code}`, framework) + const compiled = await compileAll(`${start}\n${code}`, { framework }) expect(importSources(compiled.client)).toEqual([]) const modules = { './db.server': `export const db = { count: () => 41 }` } expect(run(await importModule(compiled.client, modules))).toEqual(client) @@ -375,7 +243,7 @@ describe('ported SolidStart directives', () => { ])('a server fn in $name is rejected', async ({ code }) => { for (const output of ['client', 'ssr', 'provider'] as const) { await expect( - compile(output, `${start}\n${code}`), + compileFor(output, `${start}\n${code}`), output, ).rejects.toThrow('createServerFn must be assigned to a variable!') } @@ -384,9 +252,9 @@ describe('ported SolidStart directives', () => { describe('server function ids', () => { async function idsOf( code: string, - options: Parameters[2] = {}, + options: Parameters[2] = {}, ) { - const { serverFns } = await compile( + const { serverFns } = await compileFor( 'client', `${start}\n${code}`, options, @@ -422,7 +290,7 @@ export const save = createServerFn().handler(async () => 2)` export const loadSecretReport = createServerFn().handler(async () => 1)` const [id] = Object.values(await idsOf(code)) expect(id).not.toMatch(/loadSecretReport|module|src/) - const client = await compile('client', `${start}\n${code}`) + const client = await compileFor('client', `${start}\n${code}`) expect(client.code).toContain(JSON.stringify(id)) expect(client.code).not.toContain('loadSecretReport_createServerFn') }) @@ -433,9 +301,9 @@ export const loadSecretReport = createServerFn().handler(async () => 1)` const code = `${start}\nexport const load = createServerFn().handler(async () => 1)` const ids: Array = [] for (const id of ['/test/src/a.tsx', '/test/src/b/a.tsx']) { - const client = await compile('client', code, { id }) + const client = await compileFor('client', code, { id }) const [functionId] = Object.keys(client.serverFns) - const provider = await compile('provider', code, { id }) + const provider = await compileFor('provider', code, { id }) expect(provider.code).toContain(JSON.stringify(functionId)) ids.push(functionId!) } @@ -468,81 +336,15 @@ export const fn = createServerFn().handler(async () => red)`) }) }) -/** Compiles a module with `` for the client and loads its chunks. */ +/** Compiles a module with `` for the client and checks every module. */ async function compileHydrate(code: string) { - const plugin = createHydrateCompilerPlugin() - const compiler = new StartCompiler({ - env: 'client', - envName: 'client', - root: '/test', - framework: 'react', - providerEnvName: 'ssr', - mode: 'build', - lookupKinds: getLookupKindsForEnv('client'), - lookupConfigurations: getLookupConfigurationsForEnv('client', 'react'), - getKnownServerFns: () => ({}), - loadModule: async () => {}, - resolveId: async (id) => (id.startsWith('@tanstack/') ? id : null), - compilerPlugins: [plugin], - }) - const result = await compiler.compile({ - code, - id: '/test/src/module.tsx', - detectedKinds: detectKindsInCode(code, 'client'), - }) - const parent = result?.code - if (!parent) { - throw new Error('expected the module to be transformed') + const { parent, chunks } = await compileHydrateModule('client', code) + for (const module of [parent, ...chunks]) { + expect(await getModuleErrors(module)).toEqual([]) } - expect(await getModuleErrors(parent)).toEqual([]) - const chunks: Array = [] - for (const [, , id] of parent.matchAll(/import\((["'])(.+?)\1\)/g)) { - const chunk = plugin.loadVirtualModule?.({ - id: id!, - root: '/test', - env: 'client', - envName: 'client', - }) - expect(chunk, id).toBeTruthy() - expect(await getModuleErrors(chunk!.code)).toEqual([]) - chunks.push(chunk!.code) - } - // Order chunks by boundary index, however the parent declares them. - const index = (chunk: string) => - Number(chunk.match(/export function H(\d+)\(/)?.[1] ?? -1) - chunks.sort((a, b) => index(a) - index(b)) return { parent, chunks } } -/** The names a split chunk component receives as props, sorted. */ -function chunkParams(chunk: string) { - const params = chunk.match(/export function H\d+\(([^)]*)\)/)?.[1] ?? '' - return [...params.matchAll(/[\w$]+/g)].map(([name]) => name).sort() -} - -/** Renders a chunk export to a string: JSX becomes nested tags. */ -async function renderChunk( - chunk: string, - exportName: string, - props: Record = {}, -) { - const { code } = await transformWithOxc(chunk, 'chunk.tsx', { - jsx: { runtime: 'classic', pragma: 'h', pragmaFrag: 'Fragment' }, - }) - const jsx = `const Fragment = Symbol('Fragment') -const h = (type, props, ...children) => { - const text = children.flat(Infinity).filter((c) => c != null && c !== false).join('') - if (type === Fragment) return text - if (typeof type === 'function') return type({ ...props, children: text }) - return '<' + type + '>' + text + '' -} -` - const module: Record string> = await import( - /* @vite-ignore */ dataUrl(jsx + code) - ) - return module[exportName]!(props) -} - describe('ported SolidStart directives: Hydrate children captures', () => { // validate.ts (assertHoistable): "does not read type annotations as // captured values". Split children move to a module-level chunk component, @@ -560,9 +362,9 @@ export function Page() { return items={items as Array} />

    {(items[0] satisfies Item).id}

    }`) expect(chunks).toHaveLength(1) - expect(chunkParams(chunks[0]!)).toEqual(['items']) + expect(getChunkParams(chunks[0]!)).toEqual(['items']) expect(parent).not.toMatch(/\b(?:Item|Shape)=\{/) - expect(await renderChunk(chunks[0]!, 'H0', { items: [{ id: 'a' }] })).toBe( + expect(await renderChunk(chunks[0]!, { items: [{ id: 'a' }] })).toBe( '
      1

    a

    ', ) }) @@ -588,7 +390,7 @@ export function Page({ suffix = '!' }: { suffix?: string }) { {(function (..._args: Array) { return arguments.length })(1, 2)} }`) - expect(chunks.map(chunkParams)).toEqual([ + expect(chunks.map(getChunkParams)).toEqual([ ['suffix'], ['Local'], ['label'], @@ -596,14 +398,14 @@ export function Page({ suffix = '!' }: { suffix?: string }) { ]) expect( await Promise.all([ - renderChunk(chunks[0]!, 'H0', { suffix: '!' }), - renderChunk(chunks[1]!, 'H1', { + renderChunk(chunks[0]!, { suffix: '!' }), + renderChunk(chunks[1]!, { Local: class { static label = 'local' }, }), - renderChunk(chunks[2]!, 'H2', { label: 'inner' }), - renderChunk(chunks[3]!, 'H3'), + renderChunk(chunks[2]!, { label: 'inner' }), + renderChunk(chunks[3]!), ]), ).toEqual(['

    module!

    ', '

    local2

    ', 'inner', '2']) }) diff --git a/packages/start-plugin-core/tests/ported-turbopack-tree-shaker.test.ts b/packages/start-plugin-core/tests/ported-turbopack-tree-shaker.test.ts index 3b2b648492..cf1e3539ee 100644 --- a/packages/start-plugin-core/tests/ported-turbopack-tree-shaker.test.ts +++ b/packages/start-plugin-core/tests/ported-turbopack-tree-shaker.test.ts @@ -7,45 +7,7 @@ * statements and imports it needs, in their original order. */ import { describe, expect, test } from 'vitest' -import { - StartCompiler, - detectKindsInCode, - getLookupKindsForEnv, -} from '../src/start-compiler/compiler' -import { getLookupConfigurationsForEnv } from '../src/start-compiler/config' -import { getModuleErrors } from './validate-module' - -type Output = 'client' | 'ssr' | 'provider' - -async function compileAll(code: string) { - const compiled = {} as Record - for (const output of ['client', 'ssr', 'provider'] as const) { - const env = output === 'client' ? 'client' : 'server' - const compiler = new StartCompiler({ - env, - envName: env === 'client' ? 'client' : 'ssr', - root: '/test', - framework: 'react', - providerEnvName: 'ssr', - mode: 'build', - lookupKinds: getLookupKindsForEnv(env), - lookupConfigurations: getLookupConfigurationsForEnv(env, 'react'), - getKnownServerFns: () => ({}), - loadModule: async () => {}, - resolveId: async (id) => (id.startsWith('@tanstack/') ? id : null), - }) - const id = '/test/src/module.tsx' - const result = await compiler.compile({ - code, - id: output === 'provider' ? `${id}?tss-serverfn-split` : id, - detectedKinds: detectKindsInCode(code, env), - }) - expect(result, output).not.toBeNull() - compiled[output] = result!.code - expect(await getModuleErrors(compiled[output]), output).toEqual([]) - } - return compiled -} +import { compileAll } from './regression-helpers' const head = `import { createServerFn } from '@tanstack/react-start'\n` diff --git a/packages/start-plugin-core/tests/ported-vite-plugin-rsc.test.ts b/packages/start-plugin-core/tests/ported-vite-plugin-rsc.test.ts index 2ebabc8352..b462334ee6 100644 --- a/packages/start-plugin-core/tests/ported-vite-plugin-rsc.test.ts +++ b/packages/start-plugin-core/tests/ported-vite-plugin-rsc.test.ts @@ -7,165 +7,19 @@ * of the other environment and resolves factories through re-exports. Each * test names the plugin-rsc test or fixture it is ported from. */ -import { transformWithOxc } from 'vite' import { describe, expect, test } from 'vitest' -import { createHydrateCompilerPlugin } from '../src/hydrate-when-transform' import { - StartCompiler, - detectKindsInCode, - getLookupKindsForEnv, -} from '../src/start-compiler/compiler' -import { getLookupConfigurationsForEnv } from '../src/start-compiler/config' -import { compileStartModule } from './compile-start-module' + callProvider, + compileAll, + compileCode, + compileHydrate, + getChunkParams, + importModule, + importSources, + renderChunk, +} from './regression-helpers' import { getModuleErrors } from './validate-module' -type Output = 'client' | 'ssr' | 'provider' -const outputs: Array = ['client', 'ssr', 'provider'] -const moduleId = '/test/src/module.tsx' - -async function compileFor( - output: Output, - code: string, - options: { - id?: string - files?: Record - directives?: Array - } = {}, -) { - const { files = {}, id = moduleId } = options - const env = output === 'client' ? 'client' : 'server' - const compiler: StartCompiler = new StartCompiler({ - env, - envName: env === 'client' ? 'client' : 'ssr', - root: '/test', - framework: 'react', - providerEnvName: 'ssr', - mode: 'build', - lookupKinds: getLookupKindsForEnv(env), - lookupConfigurations: getLookupConfigurationsForEnv(env, 'react'), - getKnownServerFns: () => ({}), - serverFnProviderModuleDirectives: options.directives, - loadModule: async (moduleId) => { - const source = files[moduleId] - if (source !== undefined) { - compiler.ingestModule({ code: source, id: moduleId }) - } - }, - resolveId: async (source) => { - if (source.startsWith('@tanstack/')) { - return source - } - const file = source.startsWith('./') - ? `/test/src/${source.slice(2)}.ts` - : source - return file in files ? file : null - }, - }) - const result = await compiler.compile({ - code, - id: output === 'provider' ? `${id}?tss-serverfn-split` : id, - detectedKinds: detectKindsInCode(code, env), - }) - return result?.code ?? null -} - -/** Compiles the client, SSR caller and provider outputs and validates each. */ -async function compileAll(code: string, files?: Record) { - const compiled = {} as Record - const errors = {} as Record> - for (const output of outputs) { - const result = await compileFor(output, code, { files }) - expect(result, output).not.toBeNull() - compiled[output] = result! - errors[output] = await getModuleErrors(result!) - } - expect(errors).toEqual({ client: [], ssr: [], provider: [] }) - return compiled -} - -/** Matches the source of an import or re-export statement. */ -const moduleSource = - /^(\s*import\s*|\s*(?:import|export)\b[^;'"]*?\bfrom\s*)(["'])([^"']+)\2/gm - -/** Project-local import sources of a module, sorted. */ -function importSources(code: string) { - return [...code.matchAll(moduleSource)] - .map((match) => match[3]!) - .filter((source) => !source.startsWith('@tanstack/')) - .sort() -} - -const dataUrl = (code: string, type = 'text/javascript') => - `data:${type},${encodeURIComponent(code)}` - -/** - * Minimal Start runtime: callers keep the RPC they were given, providers run - * the original handler. - */ -const startRuntime: Record = { - '@tanstack/react-start': ` -const builder = () => { - const self = { - middleware: () => self, - validator: () => self, - inputValidator: () => self, - handler: (rpc, impl) => - impl - ? Object.assign((opts) => impl(opts ?? {}), { - __executeServer: (opts) => impl(opts), - }) - : { rpc }, - } - return self -} -export const createServerFn = builder`, - '@tanstack/react-start/server-rpc': `export const createServerRpc = (meta, fn) => Object.assign(fn, { meta })`, - '@tanstack/react-start/client-rpc': `export const createClientRpc = (id) => ({ client: id })`, - '@tanstack/react-start/ssr-rpc': `export const createSsrRpc = (id) => ({ ssr: id })`, -} - -/** - * Evaluates a compiled module, resolving every import to the given stubs. - * Stubs of `.json` specifiers are linked as JSON modules. - */ -async function importModule( - code: string, - modules: Record = {}, -): Promise> { - const sources = { ...startRuntime, ...modules } - const { code: javascript } = await transformWithOxc(code, 'module.ts') - const linked = javascript.replace( - moduleSource, - (_match, prefix: string, _quote: string, source: string) => { - const stub = sources[source] - if (stub === undefined) { - throw new Error(`No stub for import ${source}`) - } - const url = source.endsWith('.json') - ? dataUrl(stub, 'application/json') - : dataUrl(stub) - return `${prefix}${JSON.stringify(url)}` - }, - ) - return import(/* @vite-ignore */ dataUrl(linked)) -} - -/** Runs a provider's extracted handler the way the server-fn router does. */ -async function callProvider( - provider: string | Record, - name: string, - modules: Record = {}, - data?: unknown, -) { - const module = - typeof provider === 'string' - ? await importModule(provider, modules) - : provider - const handler = module[`${name}_createServerFn_handler`] - expect(handler, name).toBeTypeOf('function') - return handler({ data }) -} - const head = `import { createServerFn } from '@tanstack/react-start'\n` const dbServer = `export const db = { x: () => 'x' }` @@ -786,8 +640,8 @@ export const createMiddleware = builder`, './chart.client': `export const chart = { draw: () => 'drawn' }`, './db.server': dbServer, } - const client = await compileFor('client', code) - const ssr = await compileFor('ssr', code) + const client = await compileCode('client', code) + const ssr = await compileCode('ssr', code) for (const output of [client, ssr]) { expect(output).not.toBeNull() expect(await getModuleErrors(output!)).toEqual([]) @@ -997,7 +851,7 @@ export const serverOnly = createServerOnlyFn(() => 'server only')`, startServerOnlyFn: true, }, ])('$name', async ({ files, code = user, startServerOnlyFn }) => { - const client = await compileFor('client', code, { files }) + const client = await compileCode('client', code, { files }) expect(client).not.toBeNull() expect(await getModuleErrors(client!)).toEqual([]) expect(client).toMatch(/createServerFn\(\)\.handler\(createClientRpc\(/) @@ -1032,7 +886,7 @@ describe('provider module directives', () => { }, ])('a "use server" string $name', async ({ prologue, existing }) => { const code = `${prologue}${head}export const fn = createServerFn().handler(async () => 1)` - const provider = await compileFor('provider', code, { + const provider = await compileCode('provider', code, { directives: ['use server'], }) expect(provider).not.toBeNull() @@ -1050,7 +904,7 @@ describe('provider module directives', () => { test("a 'use client' directive after 'use strict' stays in the callers' prologue", async () => { const code = `'use strict'\n'use client'\n${head}export const fn = createServerFn().handler(async () => 1)` for (const output of ['client', 'ssr'] as const) { - const caller = await compileFor(output, code) + const caller = await compileCode(output, code) expect(caller).toMatch(/^\s*(["'])use strict\1;?\s*(["'])use client\2/) } }) @@ -1064,64 +918,13 @@ describe('CommonJS and TypeScript module formats', () => { const code = `${head}import { db } from './db.server' const n = (1 as unknown) export const fn = createServerFn().handler(async () => [n, db.x()])` - const client = await compileFor('client', code, { id }) + const client = await compileCode('client', code, { id }) expect(client).toMatch(/createClientRpc\(/) expect(importSources(client!)).toEqual([]) }, ) }) -/** Compiles a module with `` and loads its split chunks, in order. */ -async function compileHydrate(env: 'client' | 'server', code: string) { - const plugin = createHydrateCompilerPlugin() - const parent = await compileStartModule({ - env, - code, - compilerPlugins: [plugin], - }) - expect(parent).not.toBeNull() - const chunks = [...parent!.matchAll(/import\((["'])(.+?)\1\)/g)].map( - ([, , id]) => { - const chunk = plugin.loadVirtualModule?.({ - id: id!, - root: '/test', - env, - envName: env === 'client' ? 'client' : 'ssr', - }) - expect(chunk, id).toBeTruthy() - return chunk!.code - }, - ) - return { parent: parent!, chunks } -} - -/** The names a split chunk component receives as props. */ -function getChunkParams(chunk: string) { - const params = chunk.match(/export function H\d+\(([^)]*)\)/)?.[1] ?? '' - return [...params.matchAll(/[\w$]+/g)].map(([name]) => name).sort() -} - -/** Evaluates a self-contained chunk and renders its component to a string. */ -async function renderChunk(chunk: string, props: Record) { - const { code } = await transformWithOxc(chunk, 'chunk.tsx', { - jsx: { runtime: 'classic', pragma: 'h', pragmaFrag: 'Fragment' }, - }) - const runtime = `const Fragment = Symbol('Fragment') -const h = (type, props, ...children) => { - const text = children.flat(Infinity).filter((c) => c != null && c !== false).join('') - if (type === Fragment) return text - if (typeof type === 'function') return type({ ...props, children: text }) - return '<' + type + '>' + text + '' -} -` - const module: Record string> = await import( - /* @vite-ignore */ dataUrl(runtime + code) - ) - const name = Object.keys(module).find((key) => /^H\d+$/.test(key)) - expect(name).toBeDefined() - return module[name!]!(props) -} - describe('Hydrate children capture the bindings they read', () => { test.each<{ name: string diff --git a/packages/start-plugin-core/tests/ported-waku.test.ts b/packages/start-plugin-core/tests/ported-waku.test.ts index 9c11883bd5..0d25f6028d 100644 --- a/packages/start-plugin-core/tests/ported-waku.test.ts +++ b/packages/start-plugin-core/tests/ported-waku.test.ts @@ -6,146 +6,20 @@ * isomorphic functions, middleware and server functions. Each test names the * Waku test whose scenario it translates. */ -import { transformWithOxc } from 'vite' import { describe, expect, test } from 'vitest' import { - StartCompiler, - detectKindsInCode, - getLookupKindsForEnv, -} from '../src/start-compiler/compiler' -import { getLookupConfigurationsForEnv } from '../src/start-compiler/config' + clientOnlyError as clientOnly, + compileAll, + compileCode, + frameworks, + importModule, + importSources, + outputs, + serverOnlyError as serverOnly, + settle, +} from './regression-helpers' import { getModuleErrors } from './validate-module' - -type Output = 'client' | 'ssr' | 'provider' -type Framework = 'react' | 'solid' -const outputs: Array = ['client', 'ssr', 'provider'] -const frameworks: Array = ['react', 'solid'] - -async function compile( - output: Output, - code: string, - options: { framework?: Framework; mode?: 'build' | 'dev' } = {}, -) { - const env = output === 'client' ? 'client' : 'server' - const framework = options.framework ?? 'react' - const compiler = new StartCompiler({ - env, - envName: env === 'client' ? 'client' : 'ssr', - root: '/test', - framework, - providerEnvName: 'ssr', - mode: options.mode ?? 'build', - lookupKinds: getLookupKindsForEnv(env), - lookupConfigurations: getLookupConfigurationsForEnv(env, framework), - getKnownServerFns: () => ({}), - devServerFnModuleSpecifierEncoder: ({ extractedFilename, root }) => - `/@id${extractedFilename.slice(root.length)}`, - loadModule: async () => {}, - resolveId: async (id) => (id.startsWith('@tanstack/') ? id : null), - }) - const id = '/test/src/module.tsx' - const result = await compiler.compile({ - code, - id: output === 'provider' ? `${id}?tss-serverfn-split` : id, - detectedKinds: detectKindsInCode(code, env), - }) - return result?.code ?? null -} - -/** Compiles every output, checks each is a valid module and returns them. */ -async function compileAll( - code: string, - options: Parameters[2] = {}, -) { - const compiled = {} as Record - const errors = {} as Record> - for (const output of outputs) { - const result = await compile(output, code, options) - expect(result, output).not.toBeNull() - compiled[output] = result! - errors[output] = await getModuleErrors(result!) - } - expect(errors).toEqual({ client: [], ssr: [], provider: [] }) - return compiled -} - -/** Matches the source of an import or re-export statement. */ -const moduleSource = - /^(\s*import\s*|\s*(?:import|export)\b[^;'"]*?\bfrom\s*)(["'])([^"']+)\2/gm - -/** Project-local import and re-export sources of a module, sorted. */ -function importSources(code: string) { - return [...code.matchAll(moduleSource)] - .map((match) => match[3]!) - .filter((source) => !source.startsWith('@tanstack/')) - .sort() -} - -const dataUrl = (code: string) => - `data:text/javascript,${encodeURIComponent(code)}` - -/** Uncompiled factories throw, so a test only passes if the compiler ran. */ -const startPackage = ` -const uncompiled = () => { throw new Error('uncompiled Start factory') } -export const createServerFn = () => ({ - handler: (rpc, impl) => (impl ? { __executeServer: (opts) => impl(opts) } : { rpc }), -}) -export const createServerOnlyFn = uncompiled -export const createClientOnlyFn = uncompiled -export const createIsomorphicFn = uncompiled -export const createMiddleware = () => ({ server: uncompiled })` - -const runtime: Record = {} -for (const framework of frameworks) { - runtime[`@tanstack/${framework}-start`] = startPackage - runtime[`@tanstack/${framework}-start/server-rpc`] = - `export const createServerRpc = (meta, fn) => Object.assign(fn, { meta })` - runtime[`@tanstack/${framework}-start/client-rpc`] = - `export const createClientRpc = (id) => ({ client: id })` - runtime[`@tanstack/${framework}-start/ssr-rpc`] = - `export const createSsrRpc = (id) => ({ ssr: id })` -} - -let evaluations = 0 - -/** - * Evaluates a compiled module, resolving every import to the given stubs. - * Every call evaluates a fresh instance, even for identical code. - */ -async function importModule( - code: string, - modules: Record = {}, -): Promise> { - const sources = { ...runtime, ...modules } - const { code: javascript } = await transformWithOxc(code, 'module.ts') - const linked = javascript.replace( - moduleSource, - (_match, prefix: string, _quote: string, source: string) => { - const stub = sources[source] - if (stub === undefined) { - throw new Error(`No stub for import ${source}`) - } - return `${prefix}${JSON.stringify(dataUrl(stub))}` - }, - ) - return import( - /* @vite-ignore */ dataUrl(`${linked}\n// evaluation ${++evaluations}`) - ) -} - -/** The value of `run`, or the message of the error it throws. */ -function settle(run: () => unknown) { - try { - return run() - } catch (error) { - return `throws: ${(error as Error).message}` - } -} - -const serverOnly = - 'throws: createServerOnlyFn() functions can only be called on the server!' -const clientOnly = - 'throws: createClientOnlyFn() functions can only be called on the client!' +import type { Output } from './regression-helpers' describe('ported Waku allowServer transform tests', () => { // "skips files without a use client directive even if the string exists", @@ -178,7 +52,7 @@ export const value = createServerOnlyFn(() => 'mine')`, }, ])('a module that $name is left untouched', async ({ code }) => { for (const output of outputs) { - expect(await compile(output, code), output).toBeNull() + expect(await compileCode(output, code), output).toBeNull() } }) @@ -207,7 +81,7 @@ export const value = createServerOnlyFn(() => 'mine')`, const rejected: Array = [] for (const output of outputs) { try { - await compile( + await compileCode( output, `import { createServerOnlyFn, createClientOnlyFn, createIsomorphicFn } from '@tanstack/react-start'\n${code}`, ) @@ -352,7 +226,7 @@ export default createMiddleware().server(async ({ next }) => { db.log() return next() })` - const client = await compile('client', code) + const client = await compileCode('client', code) expect(client).not.toBeNull() expect(await getModuleErrors(client!)).toEqual([]) expect(importSources(client!)).toEqual([]) @@ -426,7 +300,7 @@ export const fn = createServerFn().handler(async () => 'handler')${end}` expect(Object.keys(provider)).toEqual(['fn_createServerFn_handler']) expect(await provider.fn_createServerFn_handler({})).toBe('handler') - const dev = await compile('provider', code, { mode: 'dev' }) + const dev = await compileCode('provider', code, { mode: 'dev' }) expect(dev).not.toBeNull() expect(await getModuleErrors(dev!)).toEqual([]) expect(dev).toMatch(/^if \(import\.meta\.hot\)/m) diff --git a/packages/start-plugin-core/tests/regression-helpers.ts b/packages/start-plugin-core/tests/regression-helpers.ts new file mode 100644 index 0000000000..341aa11300 --- /dev/null +++ b/packages/start-plugin-core/tests/regression-helpers.ts @@ -0,0 +1,386 @@ +/** + * Helpers shared by the Start compiler regression suites: compile a module + * into its client, SSR caller and server-function provider outputs, split + * `` children into chunks, and evaluate compiled modules against a + * minimal Start runtime. + */ +import { transformWithOxc } from 'vite' +import { expect } from 'vitest' +import { createHydrateCompilerPlugin } from '../src/hydrate-when-transform' +import { + StartCompiler, + detectKindsInCode, + getLookupKindsForEnv, +} from '../src/start-compiler/compiler' +import { getLookupConfigurationsForEnv } from '../src/start-compiler/config' +import { getModuleErrors } from './validate-module' +import type { ServerFn } from '../src/start-compiler/types' +import type { StartCompilerPlugin } from '../src/types' + +export type Output = 'client' | 'ssr' | 'provider' +export const outputs: Array = ['client', 'ssr', 'provider'] +export type Framework = 'react' | 'solid' +export const frameworks: Array = ['react', 'solid'] +export const moduleId = '/test/src/module.tsx' + +export interface StartCompilerOptions { + env: 'client' | 'server' + framework?: Framework + mode?: 'build' | 'dev' + /** Project modules by absolute id; `./name` resolves to `/test/src/name.ts`. */ + files?: Record + /** `serverFnProviderModuleDirectives` */ + directives?: Array + compilerPlugins?: Array + warn?: (message: string) => void +} + +/** + * Creates a `StartCompiler` configured the way the bundler plugins do, and + * records the server functions it reports. + */ +export function createStartCompiler(options: StartCompilerOptions) { + const { env, files = {}, framework = 'react' } = options + const serverFns: Record = {} + const compiler: StartCompiler = new StartCompiler({ + env, + envName: env === 'client' ? 'client' : 'ssr', + root: '/test', + framework, + providerEnvName: 'ssr', + mode: options.mode ?? 'build', + lookupKinds: getLookupKindsForEnv(env), + lookupConfigurations: getLookupConfigurationsForEnv(env, framework), + getKnownServerFns: () => ({}), + devServerFnModuleSpecifierEncoder: ({ extractedFilename, root }) => + `/@id${extractedFilename.slice(root.length)}`, + serverFnProviderModuleDirectives: options.directives, + onServerFnsById: (fns) => Object.assign(serverFns, fns), + loadModule: async (id) => { + const code = files[id] + if (code !== undefined) { + compiler.ingestModule({ code, id }) + } + }, + resolveId: async (id) => { + if (id.startsWith('@tanstack/')) { + return id + } + const file = id.startsWith('./') ? `/test/src/${id.slice(2)}.ts` : id + return file in files ? file : null + }, + compilerPlugins: options.compilerPlugins, + warn: options.warn, + }) + const compile = async (code: string, id = moduleId) => { + const result = await compiler.compile({ + code, + id, + detectedKinds: detectKindsInCode(code, env), + }) + return result?.code ?? null + } + return { compiler, compile, serverFns } +} + +/** + * Compiles `code` for one output: the client, the SSR caller or the + * server-function provider module (`?tss-serverfn-split`). + */ +export async function compileFor( + output: Output, + code: string, + options: Omit & { id?: string } = {}, +) { + const { compile, serverFns } = createStartCompiler({ + ...options, + env: output === 'client' ? 'client' : 'server', + }) + const id = options.id ?? moduleId + const result = await compile( + code, + output === 'provider' ? `${id}?tss-serverfn-split` : id, + ) + return { code: result, serverFns } +} + +/** Like `compileFor`, returning only the code (null when untouched). */ +export async function compileCode( + ...args: Parameters +): Promise { + return (await compileFor(...args)).code +} + +/** + * Compiles the client, SSR caller and provider outputs, checks that each is + * a valid module and returns them with the server functions the client + * compilation reported. + */ +export async function compileAll( + code: string, + options: Omit = {}, +) { + const compiled = {} as Record + const errors = {} as Record> + let serverFns: Record = {} + for (const output of outputs) { + const result = await compileFor(output, code, options) + expect(result.code, output).not.toBeNull() + compiled[output] = result.code! + errors[output] = await getModuleErrors(result.code!) + if (output === 'client') { + serverFns = result.serverFns + } + } + expect(errors).toEqual({ client: [], ssr: [], provider: [] }) + /** The id of the server function whose handler is named `functionName`. */ + const idOf = (functionName: string) => + Object.values(serverFns).find((fn) => fn.functionName === functionName) + ?.functionId + return { ...compiled, serverFns, idOf } +} + +/** Matches the source of an import or re-export statement. */ +const moduleSource = + /^(\s*import\s*|\s*(?:import|export)\b[^;'"]*?\bfrom\s*)(["'])([^"']+)\2/gm + +/** Project-local import and re-export sources of a module, sorted. */ +export function importSources(code: string) { + return [...code.matchAll(moduleSource)] + .map((match) => match[3]!) + .filter((source) => !source.startsWith('@tanstack/')) + .sort() +} + +const dataUrl = (code: string, type = 'text/javascript') => + `data:${type},${encodeURIComponent(code)}` + +/** + * Minimal Start package: callers keep the RPC they were given, providers run + * the original handler. The other factories throw when they are called + * uncompiled, so a test only passes if the compiler ran. + */ +const startPackage = ` +const uncompiled = () => { throw new Error('uncompiled Start factory') } +const builder = () => { + const self = { + middleware: () => self, + validator: () => self, + inputValidator: () => self, + handler: (rpc, impl) => + impl + ? Object.assign((opts) => impl(opts ?? {}), { + __executeServer: (opts) => impl(opts), + }) + : { rpc }, + } + return self +} +export const createServerFn = builder +export const createServerOnlyFn = uncompiled +export const createClientOnlyFn = uncompiled +export const createIsomorphicFn = uncompiled +export const createMiddleware = () => ({ server: uncompiled })` + +const startRuntime: Record = {} +for (const framework of frameworks) { + startRuntime[`@tanstack/${framework}-start`] = startPackage + startRuntime[`@tanstack/${framework}-start/server-rpc`] = + `export const createServerRpc = (meta, fn) => Object.assign(fn, { meta })` + startRuntime[`@tanstack/${framework}-start/client-rpc`] = + `export const createClientRpc = (id) => ({ client: id })` + startRuntime[`@tanstack/${framework}-start/ssr-rpc`] = + `export const createSsrRpc = (id) => ({ ssr: id })` +} + +let imports = 0 + +/** + * Evaluates a compiled module, resolving every import to the minimal Start + * runtime or to the given stubs (by specifier; `.json` stubs are JSON + * modules). Every call evaluates a fresh instance, even for identical code. + */ +export async function importModule( + code: string, + modules: Record = {}, +): Promise> { + const sources = { ...startRuntime, ...modules } + const { code: javascript } = await transformWithOxc(code, 'module.ts') + const linked = javascript.replace( + moduleSource, + (_match, prefix: string, _quote: string, source: string) => { + const stub = sources[source] + if (stub === undefined) { + throw new Error(`No stub for import ${source}`) + } + const url = source.endsWith('.json') + ? dataUrl(stub, 'application/json') + : dataUrl(stub) + return `${prefix}${JSON.stringify(url)}` + }, + ) + return import( + /* @vite-ignore */ dataUrl(`${linked}\n// evaluation ${++imports}`) + ) +} + +/** Runs a provider's extracted handler the way the server-fn router does. */ +export async function callProvider( + provider: string | Record, + name: string, + modules: Record = {}, + data?: unknown, +) { + const module = + typeof provider === 'string' + ? await importModule(provider, modules) + : provider + const handler = module[`${name}_createServerFn_handler`] + expect(handler, name).toBeTypeOf('function') + return handler({ data }) +} + +/** The value of `run`, or the message of the error it throws. */ +export function settle(run: () => unknown) { + try { + return run() + } catch (error) { + return `throws: ${(error as Error).message}` + } +} + +export const serverOnlyError = + 'throws: createServerOnlyFn() functions can only be called on the server!' +export const clientOnlyError = + 'throws: createClientOnlyFn() functions can only be called on the client!' + +type HydratePlugin = ReturnType + +/** The `` chunk ids a compiled module imports, in source order. */ +export function getChunkIds(code: string) { + return [...code.matchAll(/import\((["'])(.+?)\1\)/g)] + .map(([, , id]) => id!) + .filter((id) => id.includes('tss-hydrate=')) +} + +/** Loads a `` chunk the way the bundler loads the virtual module. */ +export function loadChunk( + plugin: HydratePlugin, + env: 'client' | 'server', + id: string, +) { + return ( + plugin.loadVirtualModule?.({ + id, + root: '/test', + env, + envName: env === 'client' ? 'client' : 'ssr', + })?.code ?? null + ) +} + +/** + * Compiles a module with `` and loads the split chunks it imports, + * ordered by boundary index. + */ +export async function compileHydrate(env: 'client' | 'server', code: string) { + const plugin = createHydrateCompilerPlugin() + const { compile } = createStartCompiler({ env, compilerPlugins: [plugin] }) + const parent = await compile(code) + if (parent === null) { + throw new Error('expected the module to be transformed') + } + const chunks = getChunkIds(parent).map((id) => { + const chunk = loadChunk(plugin, env, id) + if (chunk === null) { + throw new Error(`expected virtual module ${id} to load`) + } + return chunk + }) + // Order chunks by boundary index, however the parent declares them. + const index = (chunk: string) => + Number(chunk.match(/export function H(\d+)\(/)?.[1] ?? -1) + chunks.sort((a, b) => index(a) - index(b)) + return { parent, chunks, plugin } +} + +/** The names a split chunk component receives as props, sorted. */ +export function getChunkParams(chunk: string) { + const params = chunk.match(/export function H\d+\(([^)]*)\)/)?.[1] ?? '' + return [...params.matchAll(/[\w$]+/g)].map(([name]) => name).sort() +} + +/** Renders JSX to text: intrinsic elements become tags, components are called. */ +export const jsxToText = `const Fragment = Symbol('Fragment') +const h = (type, props, ...children) => { + const text = children.flat(Infinity).filter((c) => c != null && c !== false && c !== true).join('') + if (type === Fragment) return text + if (typeof type === 'function') return type({ ...props, children: text }) + if (typeof type !== 'string') throw new Error('cannot render ' + String(type)) + return '<' + type + '>' + text + '' +} +` + +const stubsKey = '__regressionModuleStubs' +let evaluations = 0 + +/** + * Evaluates a compiled module like a bundler would: JSX becomes plain calls + * of `runtime` (which defines `h` and `Fragment`), and imports are linked to + * `stubs`, keyed by specifier. + */ +export async function evaluateModule( + code: string, + stubs: Record> = {}, + runtime = jsxToText, +): Promise) => any>> { + const { code: javascript } = await transformWithOxc(code, 'module.tsx', { + jsx: { runtime: 'classic', pragma: 'h', pragmaFrag: 'Fragment' }, + }) + const key = `${stubsKey}${evaluations++}` + ;(globalThis as Record)[key] = stubs + // Imports are hoisted: link them before any other statement runs. + const linkedImports: Array = [] + const body = javascript.replace( + /^import\s+(.+?)\s+from\s+(["'])(.+?)\2;?$/gm, + (_, clause: string, __, source: string) => { + if (!(source in stubs)) { + throw new Error(`no stub for import ${source}`) + } + const from = `globalThis.${key}[${JSON.stringify(source)}]` + const named = clause.match(/\{(.*)\}/)?.[1] + const head = clause + .replace(/\{.*\}/, '') + .replace(/,\s*$/, '') + .trim() + if (named) { + linkedImports.push( + `const { ${named.replace(/\bas\b/g, ':')} } = ${from};`, + ) + } + if (head.startsWith('* as ')) { + linkedImports.push(`const ${head.slice(5)} = ${from};`) + } else if (head) { + linkedImports.push(`const ${head} = ${from}.default;`) + } + return '' + }, + ) + return import( + /* @vite-ignore */ dataUrl(`${runtime}${linkedImports.join('\n')}\n${body}`) + ) +} + +/** Renders the component a `` chunk exports with the given props. */ +export async function renderChunk( + chunk: string, + props: Record = {}, + stubs: Record> = {}, +) { + const module = await evaluateModule(chunk, stubs) + const name = Object.keys(module).find((key) => /^H\d+$/.test(key)) + if (!name) { + throw new Error('expected the chunk to export a component') + } + return module[name]!(props) +} diff --git a/packages/start-plugin-core/tests/start-compiler-diagnostics.test.ts b/packages/start-plugin-core/tests/start-compiler-diagnostics.test.ts index a864161fea..1b5005f3bf 100644 --- a/packages/start-plugin-core/tests/start-compiler-diagnostics.test.ts +++ b/packages/start-plugin-core/tests/start-compiler-diagnostics.test.ts @@ -1,32 +1,13 @@ import { expect, test } from 'vitest' -import { - StartCompiler, - detectKindsInCode, - getLookupKindsForEnv, -} from '../src/start-compiler/compiler' -import { getLookupConfigurationsForEnv } from '../src/start-compiler/config' +import { createStartCompiler } from './regression-helpers' async function collectWarnings(code: string) { const warnings: Array = [] - const compiler = new StartCompiler({ + const { compile } = createStartCompiler({ env: 'client', - envName: 'client', - root: '/test', - framework: 'react', - providerEnvName: 'ssr', - mode: 'build', - lookupKinds: getLookupKindsForEnv('client'), - lookupConfigurations: getLookupConfigurationsForEnv('client', 'react'), - getKnownServerFns: () => ({}), - loadModule: async () => {}, - resolveId: async (id) => id, warn: (message) => warnings.push(message), }) - await compiler.compile({ - code, - id: '/test/src/module.tsx', - detectedKinds: detectKindsInCode(code, 'client'), - }) + await compile(code) return warnings } diff --git a/packages/start-plugin-core/tests/start-compiler-edge-cases.test.ts b/packages/start-plugin-core/tests/start-compiler-edge-cases.test.ts index 4d9efd4c25..96b802c79d 100644 --- a/packages/start-plugin-core/tests/start-compiler-edge-cases.test.ts +++ b/packages/start-plugin-core/tests/start-compiler-edge-cases.test.ts @@ -1,70 +1,16 @@ import { describe, expect, test } from 'vitest' -import { - StartCompiler, - detectKindsInCode, - getLookupKindsForEnv, -} from '../src/start-compiler/compiler' -import { getLookupConfigurationsForEnv } from '../src/start-compiler/config' +import { createStartCompiler, moduleId } from './regression-helpers' import { getModuleErrors } from './validate-module' -import type { ServerFn } from '../src/start-compiler/types' -const moduleId = '/test/src/module.tsx' const providerId = `${moduleId}?tss-serverfn-split` -function createCompiler(options: { - env: 'client' | 'server' - files?: Record - mode?: 'dev' | 'build' - directives?: Array -}) { - const { env, files = {} } = options - const serverFns: Record = {} - const compiler: StartCompiler = new StartCompiler({ - env, - envName: env === 'client' ? 'client' : 'ssr', - root: '/test', - framework: 'react', - providerEnvName: 'ssr', - mode: options.mode ?? 'build', - lookupKinds: getLookupKindsForEnv(env), - lookupConfigurations: getLookupConfigurationsForEnv(env, 'react'), - getKnownServerFns: () => ({}), - devServerFnModuleSpecifierEncoder: ({ extractedFilename, root }) => - `/@id${extractedFilename.slice(root.length)}`, - serverFnProviderModuleDirectives: options.directives, - onServerFnsById: (fns) => Object.assign(serverFns, fns), - loadModule: async (id) => { - const code = files[id] - if (code !== undefined) { - compiler.ingestModule({ code, id }) - } - }, - resolveId: async (id) => { - if (id.startsWith('@tanstack/')) { - return id - } - const file = id.startsWith('./') ? `/test/src/${id.slice(2)}.ts` : id - return file in files ? file : null - }, - }) - const compile = async (code: string, id = moduleId) => { - const result = await compiler.compile({ - code, - id, - detectedKinds: detectKindsInCode(code, env), - }) - return result?.code ?? null - } - return { compiler, compile, serverFns } -} - async function compileValid( - options: Parameters[0] & { + options: Parameters[0] & { code: string provider?: boolean }, ) { - const { compile, serverFns } = createCompiler(options) + const { compile, serverFns } = createStartCompiler(options) const code = await compile( options.code, options.provider ? providerId : moduleId, @@ -307,7 +253,7 @@ export const c = authed.validator((x: string) => x).handler(async () => db.c())` }) test('a validator without an argument is rejected', async () => { - const { compile } = createCompiler({ env: 'client' }) + const { compile } = createStartCompiler({ env: 'client' }) await expect( compile(`import { createServerFn } from '@tanstack/react-start' export const fn = createServerFn().validator().handler(async () => 1)`), @@ -324,7 +270,7 @@ export const base = createServerFn()`, '/test/src/d.ts': `import { base } from './c' export const alias = base`, } - const { compiler, compile } = createCompiler({ + const { compiler, compile } = createStartCompiler({ env: 'client', mode: 'dev', files,