diff --git a/.github/workflows/compiler-platforms.yml b/.github/workflows/compiler-platforms.yml index 6185a2edf4..a6f9462b47 100644 --- a/.github/workflows/compiler-platforms.yml +++ b/.github/workflows/compiler-platforms.yml @@ -100,11 +100,6 @@ jobs: pnpm nx run-many --targets=test:unit --projects=@tanstack/router-generator,@tanstack/router-plugin,@tanstack/start-plugin-core --skip-nx-cache --outputStyle=static - - name: Implementation tests (fast tier, outside the corpus) - run: >- - pnpm nx run-many --targets=test:implementation:unit - --projects=@tanstack/router-generator,@tanstack/router-plugin,@tanstack/start-plugin-core - --skip-nx-cache --outputStyle=static - name: Noncompiler tests (runtime and build plumbing) run: >- pnpm nx run-many --targets=test:noncompiler diff --git a/nx.json b/nx.json index d37700fe1d..e068010e05 100644 --- a/nx.json +++ b/nx.json @@ -76,29 +76,6 @@ ], "outputs": ["{projectRoot}/coverage"] }, - "test:implementation": { - "cache": true, - "dependsOn": ["^build"], - "inputs": [ - "default", - "^production", - "{workspaceRoot}/eslint.config.js", - "dependentTaskOutputs" - ], - "outputs": ["{projectRoot}/coverage"] - }, - "test:implementation:unit": { - "cache": true, - "dependsOn": ["^build"], - "inputs": [ - "default", - "!{projectRoot}/tests/integration/**/*", - "^production", - "{workspaceRoot}/eslint.config.js", - "dependentTaskOutputs" - ], - "outputs": ["{projectRoot}/coverage"] - }, "test:integration:smoke": { "cache": true, "dependsOn": ["^build"], diff --git a/package.json b/package.json index 7c3ad2aab4..c84b04f044 100644 --- a/package.json +++ b/package.json @@ -14,12 +14,11 @@ "cleanNodeModules": "pnpm -r exec rm -rf node_modules", "clean": "pnpm --filter \"./packages/**\" run clean", "test": "pnpm run test:ci", - "test:pr": "nx affected --targets=test:eslint,test:unit,test:integration,test:implementation,test:noncompiler,test:e2e,test:types,test:build,build", - "test:ci": "nx run-many --targets=test:eslint,test:unit,test:integration,test:implementation,test:noncompiler,test:e2e,test:types,test:build,build", + "test:pr": "nx affected --targets=test:eslint,test:unit,test:integration,test:noncompiler,test:e2e,test:types,test:build,build", + "test:ci": "nx run-many --targets=test:eslint,test:unit,test:integration,test:noncompiler,test:e2e,test:types,test:build,build", "test:eslint": "nx affected --target=test:eslint --exclude=examples/**,e2e/**", "test:unit": "nx affected --target=test:unit --exclude=examples/**,e2e/**", "test:integration": "nx affected --target=test:integration --exclude=examples/**,e2e/**", - "test:implementation": "nx affected --target=test:implementation --exclude=examples/**,e2e/**", "test:unit:dev": "pnpm run test:unit && nx watch --all -- pnpm run test:unit", "test:build": "nx affected --target=test:build --exclude=examples/**", "test:types": "nx affected --target=test:types --exclude=examples/**", @@ -57,7 +56,7 @@ "ts:symbol-references": "node scripts/ts-symbol-references.mjs", "vite-ecosystem-ci:build": "nx run-many --targets=build --projects=@tanstack/router-plugin,@tanstack/start-plugin-core,@tanstack/react-start,@tanstack/react-start-client,@tanstack/react-start-server --skipRemoteCache", "vite-ecosystem-ci:before-test": "pnpm exec playwright install chromium", - "vite-ecosystem-ci:test": "nx run-many --targets=test:unit,test:integration,test:implementation,test:noncompiler --projects=@tanstack/router-plugin,@tanstack/start-plugin-core,@tanstack/react-start-client --skipRemoteCache && nx run-many --target=test:e2e --projects=tanstack-router-e2e-react-basic-file-based,tanstack-router-e2e-react-basic-file-based-code-splitting,tanstack-react-start-e2e-basic,tanstack-vue-start-e2e-basic,tanstack-solid-start-e2e-basic --skipRemoteCache", + "vite-ecosystem-ci:test": "nx run-many --targets=test:unit,test:integration,test:noncompiler --projects=@tanstack/router-plugin,@tanstack/start-plugin-core,@tanstack/react-start-client --skipRemoteCache && nx run-many --target=test:e2e --projects=tanstack-router-e2e-react-basic-file-based,tanstack-router-e2e-react-basic-file-based-code-splitting,tanstack-react-start-e2e-basic,tanstack-vue-start-e2e-basic,tanstack-solid-start-e2e-basic --skipRemoteCache", "test:noncompiler": "nx affected --target=test:noncompiler --exclude=examples/**,e2e/**" }, "nx": { diff --git a/packages/compiler-test-utils/package.json b/packages/compiler-test-utils/package.json index b39cacef08..1418dbf96e 100644 --- a/packages/compiler-test-utils/package.json +++ b/packages/compiler-test-utils/package.json @@ -17,11 +17,8 @@ "./hmr-sync": "./src/hmr-sync.ts", "./importers": "./src/importers.ts", "./known-globals": "./src/known-globals.ts", - "./lazy-probe": "./src/lazy-probe.ts", - "./module-linker": "./src/module-linker.ts", "./outcome": "./src/outcome.ts", "./plugin-host": "./src/plugin-host.ts", - "./render": "./src/render.ts", "./rsbuild-dev-server": "./src/rsbuild-dev-server.ts", "./rsbuild-plugin-host": "./src/rsbuild-plugin-host.ts", "./run-node": "./src/run-node.ts", diff --git a/packages/compiler-test-utils/src/budget-reporter.ts b/packages/compiler-test-utils/src/budget-reporter.ts index da5c452f60..d6d4868d4b 100644 --- a/packages/compiler-test-utils/src/budget-reporter.ts +++ b/packages/compiler-test-utils/src/budget-reporter.ts @@ -10,9 +10,8 @@ * (Nx adds its own startup), against the edit-to-result hard limit. * * The tier is the Vitest project: `integration` (and `integration-*`, e.g. - * `integration-pages`) is the slow tier, the - * implementation/noncompiler projects (outside the corpus) have no - * budget, any other project is the fast tier. Runs at another worker count (CI, one worker) are + * `integration-pages`) is the slow tier, the noncompiler project (outside + * the corpus) has no budget, any other project is the fast tier. Runs at another worker count (CI, one worker) are * reported only. * * By default the reporter never fails a run: wall-clock times move with the @@ -82,7 +81,7 @@ function moduleSeconds(testModule: TestModule) { const tierOf = (projectName: string): Tier | undefined => projectName === 'integration' || projectName.startsWith('integration-') ? 'integration' - : projectName.startsWith('implementation') || projectName === 'noncompiler' + : projectName === 'noncompiler' ? undefined : 'unit' diff --git a/packages/compiler-test-utils/src/diagnostics.ts b/packages/compiler-test-utils/src/diagnostics.ts index 00a22aa145..4d0bc1162f 100644 --- a/packages/compiler-test-utils/src/diagnostics.ts +++ b/packages/compiler-test-utils/src/diagnostics.ts @@ -432,10 +432,6 @@ function realOf(file: string) { } } -function escape(text: string) { - return text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') -} - /** * Whether `text` reports `position`: `line:column` (the column 1-based or * 0-based, as tools differ); without a column, `file:line`, `line:column` diff --git a/packages/compiler-test-utils/src/importers.ts b/packages/compiler-test-utils/src/importers.ts index 81ad36dc49..357b23a1e8 100644 --- a/packages/compiler-test-utils/src/importers.ts +++ b/packages/compiler-test-utils/src/importers.ts @@ -9,21 +9,16 @@ * - `importerSource(specifier, names)`: the source of a module that * imports `names` from `specifier` (named, `default`, or names that are * not identifiers) and exports them as live getters on `bindings`. Write - * it into a real app (a build entry, a dev-server module) or add it to a - * module graph. - * - `importBindings(graph, specifier, names, options?)`: adds such a module - * to a `createModuleGraph` graph, evaluates it and returns its live - * `bindings`: compare them (`toBe`) with what the module uses, call them. + * it into a real app (a build entry, a dev-server module). * - `loadMarker(name)`: a statement that records `name` when the module it * is in evaluates; put it in a stub or a fixture file. `loadedModules()` * and `resetLoadedModules()` read and clear the records of this realm; * `loadedModulesExpression` reads them in another realm (a child Node * run, a browser page). * - `expectNotLoaded(loaded, forbidden)`: asserts no forbidden module is - * in a list of loaded modules (`loadedModules()`, `graph.evaluated`). + * in a list of loaded modules (`loadedModules()`, a page's records). */ import { expect } from 'vitest' -import type { ModuleGraph } from './module-linker' const identifier = /^[A-Za-z_$][\w$]*$/ @@ -51,26 +46,6 @@ ${getters.join('\n')} ` } -let importers = 0 - -/** - * Adds a module importing `names` from `specifier` to `graph` (as - * `options.id`, by default a fresh `/importer-.ts`), evaluates it and - * returns its live bindings. `specifier` resolves as the graph resolves - * imports of a module at `options.id`. - */ -export async function importBindings( - graph: ModuleGraph, - specifier: string, - names: Array, - options: { id?: string } = {}, -): Promise> { - const id = options.id ?? `/importer-${++importers}.ts` - graph.add(id, importerSource(specifier, names)) - const { bindings } = await graph.import(id) - return bindings as Record -} - const loadedKey = 'tanstack.compiler-test-utils.loaded' /** @@ -104,7 +79,7 @@ export function resetLoadedModules() { /** * Asserts that none of `forbidden` is in `loaded` (names recorded by - * `loadMarker`, or module ids such as `graph.evaluated`). + * `loadMarker`, or module ids). */ export function expectNotLoaded( loaded: ReadonlyArray, diff --git a/packages/compiler-test-utils/src/lazy-probe.ts b/packages/compiler-test-utils/src/lazy-probe.ts deleted file mode 100644 index a83454a26f..0000000000 --- a/packages/compiler-test-utils/src/lazy-probe.ts +++ /dev/null @@ -1,125 +0,0 @@ -/** - * @deprecated Observes laziness in the Node module graph of - * `./module-linker` (RULES-AUDIT §2.D #8): laziness is the bundler's and - * the browser's (`./build-harness` chunk placement, the page's requests in - * `./browser`). Kept for the callers that have not moved yet. - * - * Observes lazy loading in a module graph (`module-linker.ts`) by the modules - * actually evaluated when a value's real trigger completes, never by - * recognising the helper that builds a lazy value (SPEC J2.6, §5.3, §5.8): - * `lazyRouteComponent`, `lazyFn`, `React.lazy`, an equivalent wrapper, a - * wrapper that first awaits something else, or an intermediate module that - * loads the value's module itself (a dynamic facade) all pass. - * - * API: `createLazyProbe(graph, entry, triggers, { owned })` → - * - `isLazy(name)`: completing the trigger of `name` evaluates an owned - * module that did not load with `entry`. - * - `loadedBy(name)`: ids of the owned modules completing it evaluates, in - * evaluation order (one or more: facades and support modules are allowed). - * - `groups(names)`: the lazy `names` grouped by what loads together: once - * one has loaded, completing the trigger of every other of its group - * evaluates nothing new. Each pair is observed on its own, so a name of - * another group may share support modules without joining the group. Each - * group sorted, groups sorted. A group that pulls another group's name in - * without the reverse shows as two overlapping groups. - * - * `triggers[name](exports)` starts loading `name` the way its runtime does, - * given the namespace of `entry` (a router's `component.preload()`, a loader - * call, a Hydrate boundary's `prefetch`…), and returns what it returns: the - * probe awaits it (a rejection is ignored: a value that is not lazy may run - * user code that throws), then lets the modules it started importing - * without awaiting them finish loading. Every observation runs in its own - * fork of the graph (fresh module instances, the same stubs), so the graph - * a test inspects loads nothing it did not ask for, and one observation - * never sees what another loaded. `owned(id)` tells the modules that count - * (default: modules of the graph, not stubs or packages). - */ -import type { ModuleGraph } from './module-linker' - -export interface LazyProbe { - isLazy: (name: string) => Promise - loadedBy: (name: string) => Promise> - groups: (names: Array) => Promise>> -} - -export function createLazyProbe( - graph: ModuleGraph, - entry: string, - triggers: Record) => unknown>, - options: { owned?: (id: string) => boolean } = {}, -): LazyProbe { - const fork = async () => { - const forked = graph.fork() - return { graph: forked, exports: await forked.import(entry) } - } - type Fork = Awaited> - - /** - * Completes the trigger of `name` in `forked` and returns the owned - * modules that evaluated meanwhile, in evaluation order. - */ - const complete = async (forked: Fork, name: string) => { - const owned = options.owned ?? forked.graph.has - const evaluatedBefore = forked.graph.evaluated.length - const requestedBefore = forked.graph.requested.length - try { - await triggers[name]?.(forked.exports) - } catch { - // A value that is not lazy ran (e.g. a loader without arguments) - } - // Imports the trigger started without awaiting them: the same native - // loads, awaited until they settle. - for (const id of forked.graph.requested.slice(requestedBefore)) { - if (owned(id) && !forked.graph.evaluated.includes(id)) { - await forked.graph.import(id).catch(() => undefined) - } - } - return forked.graph.evaluated.slice(evaluatedBefore).filter(owned) - } - - const loaded = new Map>>() - /** The owned modules completing `name`'s trigger evaluates (in a fork). */ - const loadedBy = (name: string) => { - let modules = loaded.get(name) - if (!modules) { - modules = fork().then((forked) => complete(forked, name)) - loaded.set(name, modules) - } - return modules - } - const isLazy = async (name: string) => (await loadedBy(name)).length > 0 - - /** Whether `other` evaluates nothing new once `name` has loaded. */ - const availableAfter = async (name: string, other: string) => { - const forked = await fork() - await complete(forked, name) - return (await complete(forked, other)).length === 0 - } - - return { - isLazy, - loadedBy: async (name) => [...(await loadedBy(name))], - async groups(names) { - const lazy: Array = [] - for (const name of names) { - if (await isLazy(name)) { - lazy.push(name) - } - } - const groups = new Map>() - for (const name of lazy) { - const group = [name] - for (const other of lazy) { - if (other !== name && (await availableAfter(name, other))) { - group.push(other) - } - } - group.sort() - groups.set(group.join('+'), group) - } - return [...groups.values()].sort((a, b) => - a.join('+').localeCompare(b.join('+')), - ) - }, - } -} diff --git a/packages/compiler-test-utils/src/module-linker.ts b/packages/compiler-test-utils/src/module-linker.ts deleted file mode 100644 index 4fb41a6ab2..0000000000 --- a/packages/compiler-test-utils/src/module-linker.ts +++ /dev/null @@ -1,779 +0,0 @@ -/** - * @deprecated A re-implementation of module resolution and evaluation - * (RULES-AUDIT §2.D #4; N9, N24): stubs keyed by the emitted specifier, - * and `fallbackStub` turns a missing import into `undefined`. Kept only - * for callers that have not moved yet. New tests evaluate server code - * through Vite's module runner - * (`./plugin-host` `importServer`, `./dev-server` `import`: real - * resolution by target, a missing import throws, `./strict-runner`) and - * client code in a real browser (`./plugin-host` `runClient`, - * `./browser` `runInPage`). Its own controls (module-linker.test.ts) are - * fixed-input controls, not compiler acceptance. - * - * Evaluates test modules as real ES modules, the way a bundler's output runs: - * Node's own linker links every import and export form (default, namespace, - * side-effect imports, `export * from`, `export { x } from`, JSON modules), - * live bindings and cycles, and a dynamic `import()` evaluates its module - * only when it is called. - * - * Module sources live in memory (a module graph) and are served through - * in-thread module hooks (`module.registerHooks`) under URLs that are unique - * per graph, so every graph evaluates fresh module instances. TypeScript is - * erased and JSX compiles with React's automatic runtime (`react/jsx-runtime`, - * as `@vitejs/plugin-react` compiles it); there is no JSX stand-in. A graph - * renders with the real framework when it links real packages (`packages`). - * - * API (see each member): - * - `createModuleGraph(options)`: `modules`, `stubs`, `resolve`, `load`, - * `packages` (real packages, e.g. `react`, `react-dom/server`, a router), - * `fallbackStub`, `transform`, `scope`, `importMeta`. - * - `graph.import(id)`, `graph.add(id, code)`, `graph.has(id)`. - * - Load observers: `graph.evaluated` (graph modules, in evaluation order), - * and `graph.requested` (every module the graph's modules requested: - * graph modules, stubs, packages). - * - `graph.importPackage(specifier)`: the instance of a real package the - * graph's modules get (to render what they export with the same React). - * - `graph.fork()`: the same modules and options, fresh module instances (to - * observe loading without touching the graph a test inspects). - */ -import { createRequire, registerHooks } from 'node:module' -import path from 'node:path' -import { pathToFileURL } from 'node:url' -import { parseSync, transformWithOxc } from 'vite' - -/** - * A module provided by the test instead of a real module: its exports, or - * its source code (`.json` specifiers: a JSON module). Source stubs are not - * compiled and cannot import other modules. - */ -export type ModuleStub = string | Record - -export interface ModuleGraphOptions { - /** Source of each module of the graph (TypeScript and JSX), by module id. */ - modules?: Record - /** - * Modules by the specifier modules import them with. A stub wins over a - * module of the graph and over a package with the same specifier. - */ - stubs?: Record - /** - * Maps an import specifier to the id of a module of the graph, or - * `undefined` when it names none. By default, an absolute or relative - * specifier names the module at that path, with or without an extension, - * its query kept. - */ - resolve?: (specifier: string, importer: string) => string | undefined - /** - * Source of a module id that is not a module of the graph yet (e.g. a - * virtual module), or `null` when unknown. - */ - load?: ( - id: string, - ) => string | null | undefined | Promise - /** - * Directory real packages resolve from. A bare specifier that is neither a - * stub nor a module of the graph resolves with Node's own resolver (package - * `exports`, conditions `node` and `import`) as if a file of this directory - * imported it, and loads the real package: one instance per test process, - * shared by every graph, like a dependency every chunk of an app shares. - * A specifier that does not resolve there goes to `fallbackStub`. - */ - packages?: string - /** - * Stubs a specifier that is neither a stub, a module of the graph nor a - * package (`packages`), given the names its importer imports from it. - * Without it, such an import fails to link, or a dynamic one fails when it - * runs. One stub serves every importer of the specifier, like one module - * of a bundle: it is called again only for names earlier importers did not - * import, and the values it gave keep their identity. - */ - fallbackStub?: (specifier: string, names: Set) => ModuleStub - /** - * The default transform erases TypeScript the way Vite does in a project - * with `verbatimModuleSyntax` (default `true`): only `import type` - * declarations and `type` specifiers go (`import { type X } from './x'` - * still loads `./x`, as `import './x'`), so an import a module never uses - * still loads its module. A compiler that leaves a dead import of a - * server-only or side-effectful module in its output therefore loads it - * here too (user ruling L3, 2026-10-17: an import left with only type uses - * need not load; dropping it is the compiler's job). `false` erases - * TypeScript like a project without it: imports nothing reads go too. - */ - verbatimModuleSyntax?: boolean - /** - * Package the default transform's automatic JSX runtime imports - * (`/jsx-runtime`); default `react`. - */ - jsxImportSource?: string - /** Compiles a module to JavaScript; by default TS and JSX are erased. */ - transform?: (code: string, id: string) => string | Promise - /** Bindings declared at the top of each module (e.g. `$RefreshReg$`). */ - scope?: (id: string) => Record - /** Properties assigned to `import.meta` of each module before it runs. */ - importMeta?: (id: string) => Record -} - -export interface ModuleGraph { - /** - * Evaluates a module of the graph and what it imports statically (once - * per graph) and returns its namespace. - */ - import: (id: string) => Promise> - /** Adds a module to the graph. */ - add: (id: string, code: string) => void - /** - * Whether the graph has a module with this id (given, added or loaded so - * far; not a stub or a package). - */ - has: (id: string) => boolean - /** Ids of the graph's modules, in the order they started evaluating. */ - evaluated: Array - /** - * Every module the graph's modules requested so far, once each, in the - * order Node resolved them: ids of modules of the graph, specifiers of - * stubs and of packages. A static import is requested when its importer - * links (before any of them evaluates), a dynamic one when it runs. What - * `importPackage` starts is not requested. - */ - requested: Array - /** - * The namespace of a real package (`packages`) as the graph's modules get - * it: the same instance (e.g. the React the modules' JSX creates elements - * of). - */ - importPackage: (specifier: string) => Promise> - /** - * A new graph with the same options and the same modules (those added or - * loaded since included), whose modules evaluate fresh instances. Stubs - * and packages are the same values. Compiled code is reused. - */ - fork: () => ModuleGraph -} - -/** Language of a module id for Oxc, from its file extension. */ -export function moduleLang(id: string) { - const extension = /\.([cm]?[jt]sx?)(?:[?#].*)?$/.exec(id)?.[1] ?? 'tsx' - if (/^[cm]?ts$/.test(extension)) { - return 'ts' as const - } - if (extension === 'tsx') { - return 'tsx' as const - } - return 'jsx' as const -} - -interface ServedModule { - format: 'module' | 'json' - source: string - /** URL each specifier the module imports resolves to. */ - imports: Map - /** - * Specifiers the module imports from real packages, with the names it - * imports from each. - */ - packages?: Map> - /** Why the module could not be prepared; loading it throws this error. */ - failure?: unknown - /** A module of the harness (not the app's): its requests are not recorded. */ - internal?: boolean - /** The specifier a stub serves. */ - specifier?: string -} - -interface Graph { - id: number - options: ModuleGraphOptions - /** Served modules by URL. */ - served: Map - /** Exports of each served object stub, by URL. */ - stubs: Map> - evaluated: Array - requested: Array - /** URL a file of `options.packages` has, to resolve packages from. */ - packagesParent?: string - /** URL of the fallback stub of a specifier, if `fallbackStub` gives one. */ - fallbackUrl: (specifier: string, names: Set) => string | undefined -} - -interface Registry { - graphs: Map - nextGraph: number -} - -const scheme = 'compiler-test-module:' -const registryKey = Symbol.for('tanstack.compiler-test-utils.module-linker') -const registryExpression = `globalThis[Symbol.for(${JSON.stringify(registryKey.description)})]` - -/** Records a module a graph's module requested (see `requested`). */ -function recordRequest(graph: Graph, requested: string) { - if (!graph.requested.includes(requested)) { - graph.requested.push(requested) - } -} - -function getRegistry(): Registry { - const global = globalThis as unknown as Record - if (!global[registryKey]) { - global[registryKey] = { graphs: new Map(), nextGraph: 0 } - registerHooks({ - resolve(specifier, context, nextResolve) { - if (lookup(specifier)) { - return { url: specifier, shortCircuit: true } - } - const parent = context.parentURL ? lookup(context.parentURL) : undefined - if (!parent) { - return nextResolve(specifier, context) - } - const { graph } = parent - const url = parent.module.imports.get(specifier) - const names = parent.module.packages?.get(specifier) - if (url === undefined && names === undefined) { - throw new Error( - `No stub for import ${specifier} (imported by ${parent.id})`, - ) - } - const target = url === undefined ? specifier : targetName(url) - if (!parent.module.internal) { - recordRequest(graph, target) - } - if (url !== undefined) { - return { url, shortCircuit: true } - } - try { - return nextResolve(specifier, { - ...context, - parentURL: graph.packagesParent, - }) - } catch (error) { - const fallback = graph.fallbackUrl(specifier, names!) - if (fallback === undefined) { - throw error - } - return { url: fallback, shortCircuit: true } - } - }, - load(url, context, nextLoad) { - const found = lookup(url) - if (!found) { - return nextLoad(url, context) - } - if (found.module.failure !== undefined) { - throw found.module.failure - } - return { - format: found.module.format, - source: found.module.source, - shortCircuit: true, - } - }, - }) - } - return global[registryKey] -} - -type UrlKind = 'module' | 'stub' | 'failed' | 'package' - -function graphUrl(graph: Graph, kind: UrlKind, id: string) { - return `${scheme}//g${graph.id}/${kind}/${encodeURIComponent(id)}` -} - -/** The served module of a URL of the linker, its id and its graph. */ -function lookup(url: string) { - const match = /^compiler-test-module:\/\/g(\d+)\/(\w+)\/(.*)$/.exec(url) - const graph = match ? getRegistry().graphs.get(Number(match[1])) : undefined - const module = graph?.served.get(url) - return ( - module && { - module, - graph: graph!, - id: decodeURIComponent(match![3]!), - } - ) -} - -/** - * What `requested` names the target of a URL by: a module's id, a - * stub's specifier. - */ -function targetName(url: string) { - const found = lookup(url) - if (!found) { - return url - } - return found.module.specifier ?? found.id -} - -/** The modules a compiled module requests, and the names it imports. */ -function moduleRequests(javascript: string) { - const { module } = parseSync('module.js', javascript, { - sourceType: 'module', - }) - const names = new Map>() - const request = (specifier: string, name?: string) => { - let requested = names.get(specifier) - if (!requested) { - requested = new Set() - names.set(specifier, requested) - } - if (name !== undefined) { - requested.add(name) - } - } - for (const statement of module.staticImports) { - const specifier = statement.moduleRequest.value - request(specifier) - for (const entry of statement.entries) { - if (entry.importName.kind === 'Name') { - request(specifier, entry.importName.name!) - } else if (entry.importName.kind === 'Default') { - request(specifier, 'default') - } - } - } - for (const statement of module.staticExports) { - for (const entry of statement.entries) { - if (entry.moduleRequest) { - request( - entry.moduleRequest.value, - entry.importName.kind === 'Name' ? entry.importName.name! : undefined, - ) - } - } - } - const dynamic: Array = [] - for (const dynamicImport of module.dynamicImports) { - const source = javascript.slice( - dynamicImport.moduleRequest.start, - dynamicImport.moduleRequest.end, - ) - // Only a static specifier (a string literal, or a template literal - // without substitutions) resolves ahead of time; any other fails when - // the import runs. - const literal = /^(?:(["'])([^"'\\]*)\1|`((?:[^`\\$]|\$(?!\{))*)`)$/.exec( - source, - ) - if (literal) { - dynamic.push((literal[2] ?? literal[3])!) - } - } - return { static: [...names.keys()], dynamic, names } -} - -/** - * Erases TypeScript the way Vite does (see `verbatimModuleSyntax`) and - * compiles JSX with React's automatic runtime from `jsxImportSource`, as - * `@vitejs/plugin-react` does. - */ -async function defaultTransform( - code: string, - id: string, - options: ModuleGraphOptions, -) { - const result = await transformWithOxc(code, 'module', { - lang: moduleLang(id), - jsx: { - runtime: 'automatic', - importSource: options.jsxImportSource ?? 'react', - }, - typescript: { - onlyRemoveTypeImports: options.verbatimModuleSyntax ?? true, - }, - }) - return result.code -} - -const extensions = ['', '.ts', '.tsx', '.js', '.jsx', '.mjs', '.json'] - -/** - * Ids an absolute or relative specifier may name: its path with each - * extension, its query kept. - */ -function candidateIds(specifier: string, importer: string) { - if (!specifier.startsWith('/') && !specifier.startsWith('.')) { - return [] - } - const [, file, query] = /^([^?#]*)(.*)$/s.exec(specifier)! - const absolute = file!.startsWith('/') - ? file! - : path.posix.join( - path.posix.dirname(importer.replace(/[?#].*$/, '')), - file!, - ) - return extensions.map((extension) => `${absolute}${extension}${query}`) -} - -/** Whether a specifier names a package (not a path, not a URL). */ -function isBareSpecifier(specifier: string) { - return !/^(?:[./]|[a-zA-Z][\w+.-]*:)/.test(specifier) -} - -// Node's own `import()`, which runs the module hooks (Vitest's module runner -// handles the `import()` calls of test files itself). -const nativeImport = createRequire(import.meta.url)('./native-import.cjs') as ( - specifier: string, -) => Promise> - -/** - * Creates a graph of in-memory modules linked to each other, to stubs and to - * real packages (`packages`). A module imported twice from one graph is - * evaluated once, like in a bundle. - */ -export function createModuleGraph( - options: ModuleGraphOptions = {}, -): ModuleGraph { - return createGraph(options, new Map()) -} - -/** - * `createModuleGraph`, with the compiled code of each module source shared - * with the graph's forks (by id, then by source). - */ -function createGraph( - options: ModuleGraphOptions, - compiled: Map }>, -): ModuleGraph { - const registry = getRegistry() - const sources = new Map(Object.entries(options.modules ?? {})) - const graph: Graph = { - id: registry.nextGraph++, - options, - served: new Map(), - stubs: new Map(), - evaluated: [], - requested: [], - packagesParent: - options.packages === undefined - ? undefined - : pathToFileURL(path.join(options.packages, 'importer.js')).href, - fallbackUrl: (specifier, names) => { - const fallback = fallbackFor(specifier, names) - return fallback === undefined ? undefined : stubUrl(specifier, fallback) - }, - } - registry.graphs.set(graph.id, graph) - const transform = - options.transform ?? - ((code: string, id: string) => defaultTransform(code, id, options)) - const compile = (code: string, id: string) => { - const known = compiled.get(id) - if (known && known.code === code) { - return known.javascript - } - const javascript = Promise.resolve(transform(code, id)) - compiled.set(id, { code, javascript }) - return javascript - } - const graphExpression = `${registryExpression}.graphs.get(${graph.id})` - const preparing = new Map< - string, - Promise> - >() - - /** Whether the graph has a module with this id, loading it if needed. */ - const hasModule = async (id: string) => { - if (sources.has(id)) { - return true - } - const loaded = await options.load?.(id) - if (loaded === null || loaded === undefined) { - return false - } - sources.set(id, loaded) - return true - } - - const resolveModule = async (specifier: string, importer: string) => { - const candidates = options.resolve - ? [options.resolve(specifier, importer)] - : candidateIds(specifier, importer) - for (const id of candidates) { - if (id !== undefined && (await hasModule(id))) { - return id - } - } - return undefined - } - - /** - * URL of a stub. An object stub exports its own keys: a stub whose keys - * grew since it was served (see `fallbackFor`) is served anew, with the - * same values. - */ - const firstStubKeys = new Map() - const stubUrl = (specifier: string, stub: ModuleStub) => { - if (typeof stub === 'string') { - const url = graphUrl(graph, 'stub', specifier) - if (!graph.served.has(url)) { - graph.served.set(url, { - format: specifier.endsWith('.json') ? 'json' : 'module', - source: stub, - imports: new Map(), - specifier, - }) - } - return url - } - const exported = Object.keys(stub) - const keys = exported.join(',') - if (!firstStubKeys.has(specifier)) { - firstStubKeys.set(specifier, keys) - } - const url = graphUrl( - graph, - 'stub', - firstStubKeys.get(specifier) === keys - ? specifier - : `${specifier}#${keys}`, - ) - if (!graph.served.has(url)) { - graph.stubs.set(url, stub) - const lines = [ - `const stub = ${graphExpression}.stubs.get(${JSON.stringify(url)})`, - ] - let index = 0 - for (const name of exported) { - lines.push( - `const value${index} = stub[${JSON.stringify(name)}]`, - `export { value${index} as ${JSON.stringify(name)} }`, - ) - index++ - } - graph.served.set(url, { - format: 'module', - source: lines.join('\n'), - imports: new Map(), - specifier, - }) - } - return url - } - - /** The fallback stub of each specifier (see `fallbackStub`). */ - const fallbacks = new Map() - const fallbackFor = (specifier: string, names: Set) => { - if (!options.fallbackStub) { - return undefined - } - const known = fallbacks.get(specifier) - if (known === undefined) { - const stub = options.fallbackStub(specifier, names) - const merged = typeof stub === 'string' ? stub : { ...stub } - fallbacks.set(specifier, merged) - return merged - } - if (typeof known === 'string') { - return known - } - const missing = new Set([...names].filter((name) => !(name in known))) - if (missing.size > 0) { - const more = options.fallbackStub(specifier, missing) - if (typeof more !== 'string') { - for (const [name, value] of Object.entries(more)) { - if (!(name in known)) { - known[name] = value - } - } - } - } - return known - } - - /** Serves a module that throws `failure` when it loads. */ - const failedUrl = (id: string, failure: unknown) => { - const url = graphUrl(graph, 'failed', id) - graph.served.set(url, { - format: 'module', - source: '', - imports: new Map(), - failure, - }) - return url - } - - const prologue = (id: string) => { - const scope = Object.keys(options.scope?.(id) ?? {}) - return [ - ...(scope.length - ? [ - `const { ${scope.join(', ')} } = ${graphExpression}.options.scope(${JSON.stringify(id)});`, - ] - : []), - ...(options.importMeta - ? [ - `Object.assign(import.meta, ${graphExpression}.options.importMeta(${JSON.stringify(id)}));`, - ] - : []), - `${graphExpression}.evaluated.push(${JSON.stringify(id)});`, - ].join(' ') - } - - /** - * Compiles a module, resolves its imports and returns the modules of the - * graph it imports, statically or dynamically. - */ - const prepareModule = (id: string) => { - let prepared = preparing.get(id) - if (!prepared) { - prepared = (async () => { - const code = sources.get(id) - if (code === undefined) { - throw new Error(`No module ${id} in the graph`) - } - const javascript = await compile(code, id) - // A hashbang must stay first: the prologue goes after its line - const [, hashbang = '', body = javascript] = - /^(#![^\n]*\n)([\s\S]*)$/.exec(javascript) ?? [] - const module: ServedModule = { - format: 'module', - // The prologue is one line, so that line numbers in stack traces - // stay those of the module. - source: `${hashbang}${prologue(id)}${body}`, - imports: new Map(), - packages: new Map(), - } - graph.served.set(graphUrl(graph, 'module', id), module) - const requests = moduleRequests(javascript) - const dependencies: Array<{ id: string; dynamic: boolean }> = [] - const resolve = async (specifier: string, dynamic: boolean) => { - if ( - module.imports.has(specifier) || - module.packages!.has(specifier) - ) { - return - } - const names = requests.names.get(specifier) ?? new Set() - if (options.stubs && Object.hasOwn(options.stubs, specifier)) { - module.imports.set( - specifier, - stubUrl(specifier, options.stubs[specifier]!), - ) - return - } - let target: string | undefined - try { - target = await resolveModule(specifier, id) - } catch (error) { - if (!dynamic) { - throw error - } - // Loading a dynamically imported module failed: the import - // fails when it runs. - module.imports.set( - specifier, - failedUrl(`${id}:${specifier}`, error), - ) - return - } - if (target !== undefined) { - module.imports.set(specifier, graphUrl(graph, 'module', target)) - dependencies.push({ id: target, dynamic }) - return - } - // Resolved by Node when the module links (see the resolve hook), - // falling back to `fallbackStub` then. - if (graph.packagesParent && isBareSpecifier(specifier)) { - module.packages!.set(specifier, names) - return - } - const fallback = fallbackFor(specifier, names) - if (fallback !== undefined) { - module.imports.set(specifier, stubUrl(specifier, fallback)) - return - } - // A dynamic import the graph cannot resolve fails when it runs. - if (!dynamic) { - throw new Error( - `No stub for import ${specifier} (imported by ${id})`, - ) - } - } - for (const specifier of requests.static) { - await resolve(specifier, false) - } - for (const specifier of requests.dynamic) { - await resolve(specifier, true) - } - return dependencies - })() - preparing.set(id, prepared) - } - return prepared - } - - /** - * Prepares a module and every module it reaches. A module only reachable - * through dynamic imports that cannot be prepared fails when it is - * imported, not before. - */ - const prepare = async (entry: string) => { - const queue = [{ id: entry, dynamic: false }] - const seen = new Set([entry]) - for (let item = queue.shift(); item; item = queue.shift()) { - let dependencies: Array<{ id: string; dynamic: boolean }> - try { - dependencies = await prepareModule(item.id) - } catch (error) { - if (!item.dynamic) { - throw error - } - graph.served.set(graphUrl(graph, 'module', item.id), { - format: 'module', - source: '', - imports: new Map(), - failure: error, - }) - continue - } - for (const dependency of dependencies) { - if (!seen.has(dependency.id)) { - seen.add(dependency.id) - queue.push({ - id: dependency.id, - dynamic: item.dynamic || dependency.dynamic, - }) - } - } - } - } - - return { - async import(id) { - if (!(await hasModule(id))) { - throw new Error(`No module ${id} in the graph`) - } - await prepare(id) - return nativeImport(graphUrl(graph, 'module', id)) - }, - has: (id) => sources.has(id), - add(id, code) { - if (sources.has(id) && sources.get(id) !== code) { - throw new Error(`Module ${id} is already in the graph`) - } - sources.set(id, code) - }, - evaluated: graph.evaluated, - requested: graph.requested, - async importPackage(specifier) { - if (!graph.packagesParent) { - throw new Error('importPackage needs the `packages` option') - } - const url = graphUrl(graph, 'package', specifier) - if (!graph.served.has(url)) { - graph.served.set(url, { - format: 'module', - source: `import * as namespace from ${JSON.stringify(specifier)}\nexport { namespace }`, - imports: new Map(), - packages: new Map([[specifier, new Set()]]), - internal: true, - }) - } - return (await nativeImport(url)).namespace - }, - fork() { - return createGraph( - { ...options, modules: Object.fromEntries(sources) }, - compiled, - ) - }, - } -} diff --git a/packages/compiler-test-utils/src/native-import.cjs b/packages/compiler-test-utils/src/native-import.cjs index 6721c3725d..6421862715 100644 --- a/packages/compiler-test-utils/src/native-import.cjs +++ b/packages/compiler-test-utils/src/native-import.cjs @@ -1,4 +1,5 @@ -// Node's own `import()`, outside Vitest's module runner, so that the module -// hooks of `module-linker.ts` resolve and load the modules it imports. +// Node's own `import()`, outside Vitest's module runner: a built server +// bundle then loads its own chunks as Node does (start-plugin-core +// `tests/integration/start-compose-app.ts`). /** @param {string} specifier */ module.exports = (specifier) => import(specifier) diff --git a/packages/compiler-test-utils/src/render.ts b/packages/compiler-test-utils/src/render.ts deleted file mode 100644 index 831ae5635a..0000000000 --- a/packages/compiler-test-utils/src/render.ts +++ /dev/null @@ -1,157 +0,0 @@ -/** - * @deprecated Renders client components in Node with a framework's server - * renderer and a hand-assembled plugin pipeline (RULES-AUDIT §2.D #5, R24): - * client semantics belong in a real browser (`./plugin-host` `runClient` - * on the served module with the real framework plugins). Kept for the - * callers that have not moved yet. - * - * Real framework rendering of module graphs (`module-linker.ts`): compile the - * graph's JSX with the framework's real transform and render what its - * modules export with the framework's real server renderer, all from the - * consumer's own installed packages (`packages` of the graph). No JSX or - * renderer stand-in. - * - * API: - * - `frameworkTransform(framework, packages)`: the `transform` option of a - * graph for `framework`. React: Vite's Oxc transform with React's automatic - * runtime (what `@vitejs/plugin-react` configures; the linker's default). - * Solid: `vite-plugin-solid`'s own transform (SSR output), Vue: - * `@vitejs/plugin-vue-jsx`'s own transform, each then TypeScript erased as - * Vite does after them. - * - `renderToHtml(graph, framework, component, props)`: server-renders a - * component of the graph (a route component, a `RouterProvider`) with - * `react-dom/server`, `solid-js/web` or `vue/server-renderer`, using the - * graph's own instances of the framework. React renders static markup - * (no hydration comments); Solid's SSR output carries its hydration keys. - * - * Mounting, effects and hydration need a browser: see `browser.ts`. - */ -import { transformWithOxc } from 'vite' -import { createModuleGraph, moduleLang } from './module-linker' -import type { ModuleGraph, ModuleGraphOptions } from './module-linker' - -/** A framework the router and Start support. */ -export type Framework = 'react' | 'solid' | 'vue' - -/** A graph that only imports packages, one per `packages` directory. */ -const packageImporters = new Map() - -/** A real package installed for the consumer (`packages`), natively loaded. */ -function importInstalled(specifier: string, packages: string) { - let importer = packageImporters.get(packages) - if (!importer) { - importer = createModuleGraph({ packages }) - packageImporters.set(packages, importer) - } - return importer.importPackage(specifier) -} - -/** A Vite plugin's hook given as a function or as `{ handler }`. */ -type Hook = ((...args: Array) => any) | { handler: (...args: any) => any } - -function handler(hook: Hook | undefined) { - return typeof hook === 'function' ? hook : hook?.handler -} - -/** A Vite plugin configured for a production build, as Vite configures it. */ -async function buildPlugin(plugin: Record) { - await handler(plugin.configResolved)?.call( - {}, - { - command: 'build', - mode: 'production', - isProduction: true, - root: process.cwd(), - build: { sourcemap: false }, - }, - ) - return (code: string, id: string, ssr: boolean): Promise => - Promise.resolve( - handler(plugin.transform)?.call({}, code, id, { ssr }), - ).then((result: string | { code: string } | null | undefined) => - result == null ? null : typeof result === 'string' ? result : result.code, - ) -} - -/** Erases TypeScript as Vite does after a framework plugin's transform. */ -async function eraseTypeScript(code: string, id: string) { - return ( - await transformWithOxc(code, 'module', { - lang: moduleLang(id), - typescript: { onlyRemoveTypeImports: true }, - }) - ).code -} - -/** - * The `transform` option of a module graph whose JSX is `framework`'s, - * compiled by the framework's real Vite plugin (packages installed in - * `packages`). `undefined` for React: the linker's default transform is - * Vite's own React JSX transform. - */ -export function frameworkTransform( - framework: Framework, - packages: string, -): ModuleGraphOptions['transform'] { - if (framework === 'react') { - return undefined - } - let plugin: - | Promise< - (code: string, id: string, ssr: boolean) => Promise - > - | undefined - const pluginTransform = () => { - plugin ??= (async () => { - if (framework === 'solid') { - const { default: solid } = await importInstalled( - 'vite-plugin-solid', - packages, - ) - return buildPlugin(solid({ ssr: true })) - } - const { default: vueJsx } = await importInstalled( - '@vitejs/plugin-vue-jsx', - packages, - ) - return buildPlugin(vueJsx()) - })() - return plugin - } - return async (code, id) => { - // The server output of each framework (rendered by `renderToHtml`) - const compiled = await (await pluginTransform())(code, id, true) - return eraseTypeScript(compiled ?? code, id) - } -} - -/** - * Server-renders `component` with `props` to HTML with the real renderer of - * `framework`, using the framework instance the graph's modules use (the - * graph links real packages: `packages`). A component that suspends without - * a boundary fails the render (React), as on a server that does not wait. - */ -export async function renderToHtml( - graph: ModuleGraph, - framework: Framework, - component: unknown, - props: Record = {}, -): Promise { - if (framework === 'react') { - const [{ createElement }, { renderToStaticMarkup }] = await Promise.all([ - graph.importPackage('react'), - graph.importPackage('react-dom/server'), - ]) - return renderToStaticMarkup(createElement(component, props)) - } - if (framework === 'solid') { - const { createComponent, renderToString } = - await graph.importPackage('solid-js/web') - return renderToString(() => createComponent(component, props)) - } - const [{ createSSRApp, h }, { renderToString }] = await Promise.all([ - graph.importPackage('vue'), - graph.importPackage('vue/server-renderer'), - ]) - return renderToString(createSSRApp({ render: () => h(component, props) })) -} diff --git a/packages/compiler-test-utils/src/validate-module.ts b/packages/compiler-test-utils/src/validate-module.ts index 8365c2a805..aa56a8e7b9 100644 --- a/packages/compiler-test-utils/src/validate-module.ts +++ b/packages/compiler-test-utils/src/validate-module.ts @@ -363,74 +363,6 @@ async function treeShake(javascript: string): Promise { } } -/** - * The modules a compiled module's dynamic `import()`s name (static - * specifiers) that survive a real production bundler: Rolldown, Vite's - * bundler, bundling the module alone with tree-shaking on and its exports - * kept (`treeShake`). An `import()` in code that bundler deletes (e.g. in a - * function nothing calls) is no load; one in code it keeps is. TypeScript - * and JSX are compiled first, from `filename`'s language and `jsx` (default: - * React's automatic runtime). - */ -export async function keptDynamicImports( - code: string, - options: { filename?: string; jsx?: ProjectJsx } = {}, -): Promise> { - const compiled = await compileModule( - code, - options.filename ?? 'module.tsx', - options.jsx, - ) - // Rolldown rewrites relative external specifiers: each static one becomes - // a bare placeholder it keeps as is, named back afterwards. - const targets: Array = [] - const marked = replaceStaticDynamicImports(compiled, (specifier) => { - targets.push(specifier) - return JSON.stringify(`${keptPlaceholder}${targets.length - 1}`) - }) - const kept = new Set() - replaceStaticDynamicImports(await treeShake(marked), (specifier) => { - if (specifier.startsWith(keptPlaceholder)) { - const target = targets[Number(specifier.slice(keptPlaceholder.length))] - if (target !== undefined) { - kept.add(target) - } - } - return undefined - }) - return [...kept] -} - -const keptPlaceholder = 'validate-module-dynamic-import:' - -/** - * Replaces each dynamic `import()` specifier of `javascript` that is a - * string literal (or a template literal without substitutions) with the - * code `replace` returns for its value, when it returns some. - */ -function replaceStaticDynamicImports( - javascript: string, - replace: (specifier: string) => string | undefined, -) { - const { module } = parseSync('module.js', javascript, { - sourceType: 'module', - }) - let result = javascript - for (const { moduleRequest } of [...module.dynamicImports].reverse()) { - const literal = /^(["'`])([^"'`\\$]*)\1$/.exec( - javascript.slice(moduleRequest.start, moduleRequest.end), - ) - const replacement = literal ? replace(literal[2]!) : undefined - if (replacement !== undefined) { - result = - result.slice(0, moduleRequest.start) + - replacement + - result.slice(moduleRequest.end) - } - } - return result -} - /** * Names a JavaScript module binds anywhere: imports, variables, functions, * classes, parameters and catch parameters. diff --git a/packages/compiler-test-utils/tests/determinism.test.ts b/packages/compiler-test-utils/tests/determinism.test.ts index 955b8e8069..34d9eaaa60 100644 --- a/packages/compiler-test-utils/tests/determinism.test.ts +++ b/packages/compiler-test-utils/tests/determinism.test.ts @@ -12,7 +12,6 @@ import { reorderings, withoutRoot, } from '../src/determinism' -import { createModuleGraph } from '../src/module-linker' describe('reorderings', () => { test('give the order, the reverse and an interleaving', () => { @@ -59,64 +58,6 @@ describe('expectDeterministic', () => { }) }) -describe('a semantic projection', () => { - // Three outputs of one module, as a compiler might emit them: the second - // only renames private bindings and prints differently, the third - // computes another value and breaks the shared identity. - const outputs = [ - `const shared = { n: 1 } -export const loader = () => shared.n + 1 -export const read = () => shared`, - `const _shared$1 = {n:1}; -const _load = () => _shared$1.n + 1; -export { _load as loader }; -export const read = () => _shared$1;`, - `export const loader = () => 3 -export const read = () => ({ n: 1 })`, - ] - /** What the module does when it runs: its loader's value, shared identity. */ - const run = async (code: string) => { - const exports = await createModuleGraph({ - modules: { '/output.ts': code }, - }).import('/output.ts') - return { - code, - data: exports.loader(), - sharedIdentity: exports.read() === exports.read(), - } - } - const project = ({ - data, - sharedIdentity, - }: Awaited>) => ({ - data, - sharedIdentity, - }) - - test('ignores private names and printing, and returns the full observations', async () => { - const observations = await expectDeterministic(outputs.slice(0, 2), run, { - project, - }) - expect(observations.map(({ code }) => code)).toEqual(outputs.slice(0, 2)) - }) - - test('detects another value or a broken shared identity', async () => { - await expect( - expectDeterministic([outputs[0]!, outputs[2]!], run, { project }), - ).rejects.toThrow() - await expect( - expectRelocatable( - ['/a', '/b'], - (root) => run(outputs[root === '/a' ? 0 : 2]!), - { - check: () => {}, - portable: project, - }, - ), - ).rejects.toThrow() - }) -}) - describe('expectRelocatable', () => { const observe = (root: string) => ({ // An opaque id may differ between roots. diff --git a/packages/compiler-test-utils/tests/importers.test.ts b/packages/compiler-test-utils/tests/importers.test.ts index 45bcb645c7..01ff88df4d 100644 --- a/packages/compiler-test-utils/tests/importers.test.ts +++ b/packages/compiler-test-utils/tests/importers.test.ts @@ -1,92 +1,27 @@ /** - * Controls of the importer and load probes (importers.ts), linked by the - * module linker as real ES modules: an importer gets the instance the - * module uses (named, default and non-identifier exports, live bindings), - * and load markers record exactly the modules that evaluated. + * Controls of the importer and load probes (importers.ts): an importer is + * a plain module any real app can contain, and load markers record the + * modules that evaluated in any realm. */ import { afterEach, describe, expect, test } from 'vitest' import { - expectNotLoaded, - importBindings, importerSource, loadMarker, - loadedModules, loadedModulesExpression, resetLoadedModules, } from '../src/importers' -import { createModuleGraph } from '../src/module-linker' afterEach(() => { resetLoadedModules() }) -describe('importBindings', () => { - test('a second module gets the instance the module itself uses, live', async () => { - const graph = createModuleGraph({ - modules: { - '/route.tsx': `export const store = { count: 0 } -export let version = 1 -export function bump() { version++ } -const Page = () => store -export default Page -const odd = 'odd' -export { odd as 'not-an-identifier' } -export const Route = { component: Page, store } -`, - }, - }) - const route = await graph.import('/route.tsx') - const bindings = await importBindings(graph, './route', [ - 'store', - 'default', - 'version', - 'bump', - 'not-an-identifier', - ]) - expect(bindings.store).toBe(route.Route.store) - expect(bindings.default).toBe(route.Route.component) - expect(bindings['not-an-identifier']).toBe('odd') - bindings.bump() - expect(bindings.version).toBe(2) - }) - - test('an import of a missing export fails to link, as in a bundle', async () => { - const graph = createModuleGraph({ - modules: { '/route.tsx': `export const Route = {}` }, - }) - await expect( - importBindings(graph, './route', ['missing']), - ).rejects.toThrow() - }) - - test('importerSource is a plain module any real app can contain', () => { +describe('importerSource', () => { + test('is a plain module any real app can contain', () => { expect(importerSource('./route', ['Route'])).toContain(`from "./route"`) }) }) describe('load markers', () => { - test('record exactly the modules that evaluated, in order', async () => { - const graph = createModuleGraph({ - modules: { - '/entry.ts': `import './eager' -export const later = () => import('./lazy') -`, - '/eager.ts': `${loadMarker('eager')}export {}`, - '/lazy.ts': `${loadMarker('lazy')}export {}`, - }, - stubs: { - './db.server': `${loadMarker('db.server')}export const db = 1`, - }, - }) - const entry = await graph.import('/entry.ts') - expect(loadedModules()).toEqual(['eager']) - expectNotLoaded(loadedModules(), ['lazy', 'db.server']) - expectNotLoaded(graph.evaluated, ['/lazy.ts']) - await entry.later() - expect(loadedModules()).toEqual(['eager', 'lazy']) - expect(() => expectNotLoaded(loadedModules(), ['lazy'])).toThrow() - }) - test('loadedModulesExpression reads the records in any realm', () => { const read = new Function(`return ${loadedModulesExpression}`) as () => [ string, diff --git a/packages/compiler-test-utils/tests/lazy-probe.test.ts b/packages/compiler-test-utils/tests/lazy-probe.test.ts deleted file mode 100644 index 9751cd47f3..0000000000 --- a/packages/compiler-test-utils/tests/lazy-probe.test.ts +++ /dev/null @@ -1,147 +0,0 @@ -/** - * Controls of the lazy-loading probe on fixed graphs: laziness, loaded - * modules and groups are observed by the modules evaluated when the real - * trigger completes, whatever builds the lazy value (a wrapper awaiting - * something first, a dynamic facade), and without loading anything in the - * graph a test inspects. - */ -import { describe, expect, it } from 'vitest' -import { createLazyProbe } from '../src/lazy-probe' -import { createModuleGraph } from '../src/module-linker' - -/** A graph whose modules import each other by id. */ -function graphOf(modules: Record, stubs = {}) { - return createModuleGraph({ - modules, - stubs, - resolve: (specifier) => (specifier in modules ? specifier : undefined), - }) -} - -/** Triggers starting to load each export of the entry: `load()` or `preload()`. */ -const triggers = Object.fromEntries( - ['a', 'b', 'c', 'd', 'eager'].map((name) => [ - name, - (exports: Record) => - exports[name]?.preload?.() ?? exports[name]?.load?.(), - ]), -) - -describe('createLazyProbe', () => { - it('tells lazy values from eager ones and the modules loading one evaluates', async () => { - const graph = graphOf( - { - '/entry.ts': `import { shared } from '/shared.ts' -export const eager = { load: () => shared } -// An equivalent wrapper of its own -export const a = { preload: () => import('/a.ts').then((m) => m.value) } -// An intermediate module loading the group's modules -export const b = { load: async () => (await import('/group.ts')).b } -export const c = { load: async () => (await import('/group.ts')).c }`, - '/shared.ts': `export const shared = 'shared'`, - '/a.ts': `import 'lib' -export const value = 'a'`, - '/group.ts': `export { b } from '/b.ts' -export { c } from '/c.ts'`, - '/b.ts': `export const b = 'b'`, - '/c.ts': `export const c = 'c'`, - }, - { lib: {} }, - ) - await graph.import('/entry.ts') - const probe = createLazyProbe(graph, '/entry.ts', triggers) - expect( - await Promise.all(['eager', 'a', 'b', 'c'].map(probe.isLazy)), - ).toEqual([false, true, true, true]) - // Stubs and packages are not the graph's modules. - expect(await probe.loadedBy('a')).toEqual(['/a.ts']) - expect((await probe.loadedBy('b')).sort()).toEqual([ - '/b.ts', - '/c.ts', - '/group.ts', - ]) - expect(await probe.groups(['eager', 'a', 'b', 'c'])).toEqual([ - ['a'], - ['b', 'c'], - ]) - // The graph itself loaded nothing more. - expect([...graph.evaluated]).toEqual(['/shared.ts', '/entry.ts']) - }) - - it('shows a group that loads another one with it', async () => { - const graph = graphOf({ - '/entry.ts': `export const a = { load: () => import('/a.ts') } -export const b = { load: () => import('/b.ts') }`, - '/a.ts': `import '/b.ts'`, - '/b.ts': `export {}`, - }) - const probe = createLazyProbe(graph, '/entry.ts', triggers) - expect(await probe.groups(['a', 'b'])).toEqual([['a', 'b'], ['b']]) - }) - - it('awaits the trigger: a wrapper that awaits first, a dynamic facade and an unawaited import are lazy, with every module they load', async () => { - const graph = graphOf({ - '/entry.ts': `// Awaits something else before importing -export const a = { - preload: async () => { - await Promise.resolve() - return import('/a.ts') - }, -} -// A facade module that loads the value's module itself -export const b = { load: () => import('/facade.ts').then((m) => m.load()) } -// Starts the import without returning it -export const c = { - preload: () => { - void import('/c.ts') - }, -} -export const eager = { load: async () => { await Promise.resolve(); return 'eager' } }`, - '/a.ts': `export const a = 'a'`, - '/facade.ts': `export const load = () => import('/b.ts')`, - '/b.ts': `export const b = 'b'`, - '/c.ts': `export const c = 'c'`, - }) - await graph.import('/entry.ts') - const probe = createLazyProbe(graph, '/entry.ts', triggers) - expect( - await Promise.all(['a', 'b', 'c', 'eager'].map(probe.isLazy)), - ).toEqual([true, true, true, false]) - expect(await probe.loadedBy('a')).toEqual(['/a.ts']) - expect(await probe.loadedBy('b')).toEqual(['/facade.ts', '/b.ts']) - expect(await probe.loadedBy('c')).toEqual(['/c.ts']) - expect(await probe.groups(['a', 'b', 'c', 'eager'])).toEqual([ - ['a'], - ['b'], - ['c'], - ]) - expect([...graph.evaluated]).toEqual(['/entry.ts']) - }) - - it('observes each pair of a group on its own: what one name loads does not make another available', async () => { - const graph = graphOf({ - '/entry.ts': `export const a = { load: () => import('/a.ts') } -// b and c load the same module (one group); d shares only a support module -export const b = { load: () => import('/bc.ts').then((m) => m.b) } -export const c = { load: async () => (await import('/bc.ts')).c } -export const d = { load: () => import('/d.ts') }`, - '/a.ts': `import '/d.ts' -export const a = 'a'`, - '/bc.ts': `import '/support.ts' -export const b = 'b' -export const c = 'c'`, - '/d.ts': `import '/support.ts' -export const d = 'd'`, - '/support.ts': `export const support = 'support'`, - }) - const probe = createLazyProbe(graph, '/entry.ts', triggers) - // a pulls d in: once a loaded, d is available, not the reverse; b and c - // are available after each other, whatever else loaded before. - expect(await probe.groups(['a', 'b', 'c', 'd'])).toEqual([ - ['a', 'd'], - ['b', 'c'], - ['d'], - ]) - expect([...graph.evaluated]).toEqual([]) - }) -}) diff --git a/packages/compiler-test-utils/tests/module-linker.test.ts b/packages/compiler-test-utils/tests/module-linker.test.ts deleted file mode 100644 index ea72dcbb1e..0000000000 --- a/packages/compiler-test-utils/tests/module-linker.test.ts +++ /dev/null @@ -1,454 +0,0 @@ -/** - * Controls of the module linker: modules link like ES modules in a bundle - * (every import and export form, live bindings, cycles), a dynamic import - * evaluates its module only when it runs, and every graph evaluates fresh - * module instances; real packages, JSX, the load observers and forks. - */ -import path from 'node:path' -import { describe, expect, it, test } from 'vitest' -import { createModuleGraph } from '../src/module-linker' -import type { ModuleStub } from '../src/module-linker' - -/** Evaluates `code` as the only module of a new graph. */ -function evaluateModule( - code: string, - stubs: Record = {}, - options: { importMeta?: Record } = {}, -): Promise> { - const id = '/module.tsx' - return createModuleGraph({ - modules: { [id]: code }, - stubs, - ...(options.importMeta && { importMeta: () => options.importMeta! }), - }).import(id) -} - -describe('evaluateModule', () => { - test('links every import and export form as ES modules', async () => { - const module = await evaluateModule( - `import def, { named as alias, 'string name' as str } from './dep' -import * as ns from './dep' -import config from './config.json' with { type: 'json' } -export { named, 'string name' as 'other name' } from './dep' -export * from './star' -export * as starNs from './star' -export default function () { - return [def, alias, str, ns.named, config.theme].join() -}`, - { - './dep': { default: 'D', named: 'N', 'string name': 'S' }, - './star': `export const starred = 1`, - './config.json': `{ "theme": "dark" }`, - }, - ) - expect(module.default()).toBe('D,N,S,N,dark') - expect([ - module.named, - module['other name'], - module.starred, - module.starNs.starred, - ]).toEqual(['N', 'S', 1, 1]) - }) - - test('evaluates a module starting with a hashbang', async () => { - const module = await evaluateModule( - `#!/usr/bin/env node -export const value = import.meta.flag + 1`, - {}, - { importMeta: { flag: 1 } }, - ) - expect(module.value).toBe(2) - }) - - test('exports are live bindings', async () => { - const module = await evaluateModule(`export let count = 0 -export function bump() { count++ }`) - module.bump() - expect(module.count).toBe(1) - }) - - test('an import of an unknown module, or of a name a stub lacks, fails to link', async () => { - await expect( - evaluateModule(`import { x } from './missing'\nexport const y = x`), - ).rejects.toThrow('No stub for import ./missing') - await expect( - evaluateModule(`import { other } from './dep'\nexport const y = other`, { - './dep': { x: 1 }, - }), - ).rejects.toThrow(/other/) - }) - - test('a dynamic import resolves when it runs, and fails then if unknown', async () => { - const module = await evaluateModule( - `export const load = () => import('./dep') -export const loadMissing = () => import('./missing')`, - { './dep': { x: 1 } }, - ) - expect((await module.load()).x).toBe(1) - await expect(module.loadMissing()).rejects.toThrow( - 'No stub for import ./missing', - ) - }) - - // Route files of apps live at paths such as `routes/{-$locale}/index.tsx`. - test('a dynamic import of a static specifier containing $ resolves', async () => { - const module = await evaluateModule( - `export const quoted = () => import('./{-$locale}/dep') -export const template = () => import(\`./{-$locale}/dep\`)`, - { './{-$locale}/dep': { x: 1 } }, - ) - expect([(await module.quoted()).x, (await module.template()).x]).toEqual([ - 1, 1, - ]) - }) -}) - -describe('evaluateModule links every import form like an ES module runtime', () => { - it('links default, named, namespace and side-effect imports', async () => { - const { read } = await evaluateModule( - `import './effects' -import fallback, { value as renamed } from './lib' -import * as lib from './lib' -export const read = () => [fallback, renamed, lib.value, lib.default].join()`, - { - './effects': {}, - './lib': { default: 'default', value: 'value' }, - }, - ) - expect(read!()).toBe('default,value,value,default') - }) - - it('links re-exports', async () => { - const module = await evaluateModule( - `export * from './lib' -export { value as renamed, default as fallback } from './lib'`, - { './lib': { default: 'default', value: 'value' } }, - ) - expect({ ...module }).toEqual({ - fallback: 'default', - renamed: 'value', - value: 'value', - }) - }) - - it('rejects an import of a name the module does not export', async () => { - await expect( - evaluateModule(`import { missing } from './lib'\nexport { missing }`, { - './lib': { value: 1 }, - }), - ).rejects.toThrow("does not provide an export named 'missing'") - }) - - it('assigns import.meta properties before the module runs', async () => { - const hot = { data: {} } - const { read } = await evaluateModule( - `const seen = import.meta.hot\nexport const read = () => seen`, - {}, - { importMeta: { hot } }, - ) - expect(read!()).toBe(hot) - }) -}) - -describe('module sessions', () => { - const modules: Record = { - '/a.tsx': `import { count, increment } from '/b.tsx' -export const read = () => count -export { increment } -export const lazy = () => import('/c.tsx')`, - '/b.tsx': `export let count = 0\nexport function increment() { count++ }`, - '/c.tsx': `export const loaded = { module: 'c' }`, - } - const resolve = (specifier: string) => - specifier in modules ? specifier : undefined - - it('keeps imports live bindings', async () => { - const session = createModuleGraph({ modules, resolve }) - const a = await session.import('/a.tsx') - a.increment() - a.increment() - expect(a.read()).toBe(2) - }) - - it('evaluates a dynamically imported module only when it is imported', async () => { - const session = createModuleGraph({ modules, resolve }) - const a = await session.import('/a.tsx') - expect([...session.evaluated]).toEqual(['/b.tsx', '/a.tsx']) - expect((await a.lazy()).loaded).toEqual({ module: 'c' }) - expect([...session.evaluated]).toEqual(['/b.tsx', '/a.tsx', '/c.tsx']) - }) - - it('evaluates fresh module instances in every session', async () => { - const first = await createModuleGraph({ modules, resolve }).import('/a.tsx') - first.increment() - const second = await createModuleGraph({ modules, resolve }).import( - '/a.tsx', - ) - expect([first.read(), second.read()]).toEqual([1, 0]) - }) -}) - -// Vite erases TypeScript this way in a project with `verbatimModuleSyntax`: -// an unused value import still loads its module, and so does an import of -// `type` specifiers only (as `import './x'`); an `import type` does not. -describe('TypeScript erasure keeps every value import', () => { - it('evaluates a module imported but never used, and not one imported with import type', async () => { - const modules: Record = { - '/entry.ts': `import { unused } from '/unused.ts' -import type { Shape } from '/types.ts' -import { type Other } from '/specifier.ts' -export const value: Shape = { key: 'entry' }`, - '/unused.ts': `export const unused = 'unused'`, - '/types.ts': `export interface Shape { key: string }`, - '/specifier.ts': `export interface Other {}`, - } - const graph = createModuleGraph({ - modules, - resolve: (specifier) => (specifier in modules ? specifier : undefined), - }) - expect((await graph.import('/entry.ts')).value).toEqual({ key: 'entry' }) - expect([...graph.evaluated].sort()).toEqual([ - '/entry.ts', - '/specifier.ts', - '/unused.ts', - ]) - }) - - it('without verbatimModuleSyntax, drops the imports nothing reads', async () => { - const modules: Record = { - '/entry.ts': `import { unused } from '/unused.ts' -import { type Other } from '/specifier.ts' -export const value = 'entry'`, - '/unused.ts': `export const unused = 'unused'`, - '/specifier.ts': `export interface Other {}`, - } - const graph = createModuleGraph({ - modules, - resolve: (specifier) => (specifier in modules ? specifier : undefined), - verbatimModuleSyntax: false, - }) - expect((await graph.import('/entry.ts')).value).toBe('entry') - expect([...graph.evaluated]).toEqual(['/entry.ts']) - }) -}) - -describe('cycles', () => { - const graphOf = (modules: Record) => - createModuleGraph({ - modules, - resolve: (specifier) => (specifier in modules ? specifier : undefined), - }) - - it('links a cycle with live bindings, evaluating the imported module first', async () => { - const graph = graphOf({ - '/a.tsx': `import { b, readA, callA } from '/b.tsx' -export const a = 'A' -export function hoisted() { return 'hoisted' } -export const read = () => [b, readA(), callA]`, - // A function declaration of a module in the cycle is initialised before - // any module of the cycle runs. - '/b.tsx': `import { a, hoisted } from '/a.tsx' -export const b = 'B' -export const readA = () => a -export const callA = hoisted()`, - }) - const a = await graph.import('/a.tsx') - expect(a.read()).toEqual(['B', 'A', 'hoisted']) - expect([...graph.evaluated]).toEqual(['/b.tsx', '/a.tsx']) - }) - - it('a module of a cycle that reads a binding before its module initialised it throws a ReferenceError (TDZ)', async () => { - const graph = graphOf({ - '/a.tsx': `import { b } from '/b.tsx' -export const a = 'A' -export const read = () => b`, - '/b.tsx': `import { a } from '/a.tsx' -export const b = a`, - }) - await expect(graph.import('/a.tsx')).rejects.toThrow( - expect.objectContaining({ - name: 'ReferenceError', - message: expect.stringMatching(/before initialization/), - }), - ) - }) -}) - -describe('fallbackStub', () => { - // Like one module of a bundle, a stubbed package is one instance for every - // module that imports it. - it('gives every importer of a specifier the same stub values, and the names each imports', async () => { - const calls: Array> = [] - const modules: Record = { - '/entry.tsx': `export { fromA } from '/a.tsx' -export { fromB, other } from '/b.tsx'`, - '/a.tsx': `import { createStore } from 'store-lib' -export const fromA = createStore`, - '/b.tsx': `import { createStore, other } from 'store-lib' -export const fromB = createStore -export { other }`, - } - const graph = createModuleGraph({ - modules, - resolve: (specifier) => (specifier in modules ? specifier : undefined), - fallbackStub: (_, names) => { - calls.push([...names]) - return Object.fromEntries( - [...names].map((name) => [name, { stubbed: name }]), - ) - }, - }) - const entry = await graph.import('/entry.tsx') - expect(entry.fromA).toEqual({ stubbed: 'createStore' }) - expect(entry.fromA).toBe(entry.fromB) - expect(entry.other).toEqual({ stubbed: 'other' }) - // Called again only for the name the first importer did not import - expect(calls).toEqual([['createStore'], ['other']]) - }) -}) - -// The package's own directory: its dependencies are the real packages a -// graph can link (`globals` is a CommonJS package, `vite` an ES one). -const packageDirectory = path.join(import.meta.dirname, '..') - -describe('packages', () => { - it('links a bare specifier to the real package, one instance for every graph and for importPackage', async () => { - const modules = { - '/a.ts': `import globals from 'globals' -import { version } from 'vite' -export { globals, version }`, - } - const first = createModuleGraph({ modules, packages: packageDirectory }) - const second = createModuleGraph({ modules, packages: packageDirectory }) - const [a, b] = [await first.import('/a.ts'), await second.import('/a.ts')] - const real = await first.importPackage('globals') - expect(Object.keys(a.globals)).toContain('browser') - expect(a.globals).toBe(real.default) - expect(b.globals).toBe(real.default) - expect(a.version).toBe((await second.importPackage('vite')).version) - }) - - it('stubs win over packages, and a specifier no package provides goes to fallbackStub', async () => { - const graph = createModuleGraph({ - modules: { - '/a.ts': `export { default as globals } from 'globals' -export { missing } from 'not-installed-package'`, - }, - packages: packageDirectory, - stubs: { globals: { default: 'stubbed' } }, - fallbackStub: (_, names) => - Object.fromEntries( - [...names].map((name) => [name, `fallback ${name}`]), - ), - }) - expect({ ...(await graph.import('/a.ts')) }).toEqual({ - globals: 'stubbed', - missing: 'fallback missing', - }) - }) - - it('without a fallback, an import of a package that does not resolve fails to link', async () => { - const graph = createModuleGraph({ - modules: { '/a.ts': `import 'not-installed-package'` }, - packages: packageDirectory, - }) - await expect(graph.import('/a.ts')).rejects.toThrow(/not-installed-package/) - }) -}) - -describe('JSX', () => { - // A control of how the default transform compiles JSX, with a stub that - // records the calls (no renderer): React's automatic runtime, as - // `@vitejs/plugin-react` compiles it. - it('compiles to calls of the automatic runtime of jsxImportSource (default react)', async () => { - const runtime = { - jsx: (type: unknown, props: unknown) => ({ type, props }), - jsxs: (type: unknown, props: unknown) => ({ type, props, static: true }), - Fragment: 'Fragment', - } - const code = `export const element =

{'a'}

-export const fragment = <>` - const react = await createModuleGraph({ - modules: { '/a.tsx': code }, - stubs: { 'react/jsx-runtime': runtime }, - }).import('/a.tsx') - expect(react.element).toEqual({ - type: 'p', - props: { id: 'x', children: 'a' }, - }) - expect(react.fragment).toEqual({ - type: 'Fragment', - props: { - children: [ - { type: 'i', props: {} }, - { type: 'b', props: {} }, - ], - }, - static: true, - }) - const other = await createModuleGraph({ - modules: { '/a.tsx': code }, - jsxImportSource: 'other', - stubs: { 'other/jsx-runtime': runtime }, - }).import('/a.tsx') - expect(other.element).toEqual(react.element) - }) -}) - -describe('requested', () => { - const modules: Record = { - '/route.tsx': `import { helper } from '/shared.tsx' -import { value } from 'lib' -export const read = () => [helper, value] -export const lazy = () => import('/chunk.tsx')`, - '/shared.tsx': `import 'side-effect' -export const helper = 'helper'`, - '/chunk.tsx': `import { helper } from '/shared.tsx' -import { other } from 'lib' -export const chunk = [helper, other]`, - } - const resolve = (specifier: string) => - specifier in modules ? specifier : undefined - const stubs = { lib: { value: 'value', other: 'other' }, 'side-effect': {} } - - it('records each module the graph requests once: static imports when they link, dynamic ones when they run', async () => { - const graph = createModuleGraph({ modules, resolve, stubs }) - const route = await graph.import('/route.tsx') - const eager = ['/shared.tsx', 'lib', 'side-effect'] - expect([...graph.requested].sort()).toEqual(eager) - expect((await route.lazy()).chunk).toEqual(['helper', 'other']) - expect([...graph.requested].sort()).toEqual(['/chunk.tsx', ...eager]) - }) - - it('names packages by their specifier, and not what importPackage loads', async () => { - const graph = createModuleGraph({ - modules: { '/a.ts': `export { default } from 'globals'` }, - packages: packageDirectory, - }) - await graph.importPackage('vite') - await graph.import('/a.ts') - expect(graph.requested).toEqual(['globals']) - }) -}) - -describe('fork', () => { - it('evaluates the same modules, added ones included, as fresh instances with the same stubs', async () => { - const counter = { count: 0 } - const graph = createModuleGraph({ - modules: { - '/a.ts': `import { counter } from 'counter' -export let own = 0 -export const bump = () => [++own, ++counter.count]`, - }, - stubs: { counter: { counter } }, - }) - graph.add('/b.ts', `export { bump } from '/a.ts'`) - const first = await graph.import('/b.ts') - first.bump() - const fork = graph.fork() - const forked = await fork.import('/b.ts') - expect(forked.bump()).toEqual([1, 2]) - expect([...fork.evaluated]).toEqual(['/a.ts', '/b.ts']) - expect([...graph.evaluated]).toEqual(['/a.ts', '/b.ts']) - }) -}) diff --git a/packages/router-generator/package.json b/packages/router-generator/package.json index dbea2327e9..12a209d53c 100644 --- a/packages/router-generator/package.json +++ b/packages/router-generator/package.json @@ -36,8 +36,6 @@ "test:types:ts70": "tsc -p tsconfig.legacy.json", "test:unit": "vitest --project unit --project types", "test:integration": "vitest --project integration", - "test:implementation": "tsc6 -p tests/tsconfig.implementation.json && vitest --project implementation --project implementation-integration", - "test:implementation:unit": "vitest --project implementation", "test:unit:dev": "pnpm run test:unit --watch --hideSkippedTests", "test:build": "publint --strict && attw --ignore-rules no-resolution --pack .", "build": "vite build" diff --git a/packages/router-generator/tests/tsconfig.acceptance.json b/packages/router-generator/tests/tsconfig.acceptance.json index d0b9b70432..504a9e9010 100644 --- a/packages/router-generator/tests/tsconfig.acceptance.json +++ b/packages/router-generator/tests/tsconfig.acceptance.json @@ -2,7 +2,6 @@ "extends": "../tsconfig.json", "include": ["./*.test.ts", "./generator/nested/tests.test-d.ts"], "exclude": [ - "./**/outside-compiler-corpus/**", "./integration/**", "./generator/**/*.tsx", "./generator/**/routeTree.gen.js", diff --git a/packages/router-generator/tests/tsconfig.implementation.json b/packages/router-generator/tests/tsconfig.implementation.json deleted file mode 100644 index 099c50417c..0000000000 --- a/packages/router-generator/tests/tsconfig.implementation.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "extends": "../tsconfig.legacy.json", - "include": ["./outside-compiler-corpus/**/*.ts"], - "exclude": ["./**/node_modules/**"] -} diff --git a/packages/router-generator/vite.config.ts b/packages/router-generator/vite.config.ts index 835e246c85..c9ee945777 100644 --- a/packages/router-generator/vite.config.ts +++ b/packages/router-generator/vite.config.ts @@ -2,12 +2,6 @@ import { configDefaults, defineConfig, mergeConfig } from 'vitest/config' import { tanstackViteConfig } from '@tanstack/vite-config' import packageJson from './package.json' -/** - * Implementation tests: outside the compiler test corpus (see - * packages/compiler-test-utils/AGENTS.md, "Corpus and implementation tests"). - */ -const implementationTests = '**/outside-compiler-corpus/**' - const config = defineConfig({ test: { name: packageJson.name, @@ -26,11 +20,7 @@ const config = defineConfig({ extends: true, test: { name: 'unit', - exclude: [ - ...configDefaults.exclude, - 'integration/**', - implementationTests, - ], + exclude: [...configDefaults.exclude, 'integration/**'], }, }, { @@ -47,7 +37,6 @@ const config = defineConfig({ enabled: true, only: true, include: ['generator/nested/tests.test-d.ts'], - exclude: [...configDefaults.exclude, implementationTests], tsconfig: './tests/tsconfig.acceptance.json', }, }, @@ -60,30 +49,6 @@ const config = defineConfig({ test: { name: 'integration', include: ['integration/**/*.test.ts'], - exclude: [...configDefaults.exclude, implementationTests], - typecheck: { enabled: false }, - testTimeout: 30_000, - hookTimeout: 30_000, - }, - }, - { - // Implementation tests (`test:implementation`, both tiers): files - // under an `outside-compiler-corpus/` directory. They pin choices of - // today's implementation that a correct generator may make - // differently, so the corpus targets above leave them out (see - // packages/compiler-test-utils/AGENTS.md). - extends: true, - test: { - name: 'implementation', - include: ['**/outside-compiler-corpus/**/*.test.ts'], - exclude: [...configDefaults.exclude, 'integration/**'], - }, - }, - { - extends: true, - test: { - name: 'implementation-integration', - include: ['integration/**/outside-compiler-corpus/**/*.test.ts'], typecheck: { enabled: false }, testTimeout: 30_000, hookTimeout: 30_000, diff --git a/packages/router-plugin/package.json b/packages/router-plugin/package.json index f2ea650936..73d3bbcf92 100644 --- a/packages/router-plugin/package.json +++ b/packages/router-plugin/package.json @@ -30,8 +30,6 @@ "test:unit": "vitest --project unit", "test:unit:dev": "vitest --project unit --watch", "test:integration": "vitest --project integration --project integration-pages", - "test:implementation": "vitest --project implementation --project implementation-integration", - "test:implementation:unit": "vitest --project implementation", "test:integration:smoke": "vitest --project integration integration/build-production.test.ts -t \"vite.*a production react client bundle has no dev-only code|autoCodeSplitting: true. has no dev-only code\"", "test:eslint": "eslint ./src ./tests", "test:types": "pnpm run \"/^test:types:ts[0-9]{2}$/\"", diff --git a/packages/router-plugin/tests/route-app.ts b/packages/router-plugin/tests/route-app.ts index 42e3221b50..f09bbb5b82 100644 --- a/packages/router-plugin/tests/route-app.ts +++ b/packages/router-plugin/tests/route-app.ts @@ -1407,32 +1407,3 @@ export function holdsMarker(code: string, marker: string) { } export const head = `import { createFileRoute } from '@tanstack/react-router'\n` - -/** - * The warnings and errors a page run logged (`PageRun.console`, `type: text`) - * as diagnostics of the `page` channel: what a developer reads in the - * browser's console (e.g. a warning a served module prints when it loads). - * Merge them with `route.diagnostics()` to read every channel. - */ -export function pageDiagnostics( - console: Array, -): Array { - const severities: Record = { - warning: 'warning', - error: 'error', - } - return console.flatMap((line) => { - const separator = line.indexOf(': ') - const severity = severities[line.slice(0, separator)] - return severity - ? [ - { - severity, - text: line.slice(separator + 2), - raw: line, - source: 'page' as const, - }, - ] - : [] - }) -} diff --git a/packages/router-plugin/vite.config.ts b/packages/router-plugin/vite.config.ts index f59f0c574d..068c136cb1 100644 --- a/packages/router-plugin/vite.config.ts +++ b/packages/router-plugin/vite.config.ts @@ -14,12 +14,6 @@ if (process.env.VITEST) { ) } -/** - * Implementation tests: outside the compiler test corpus (see - * packages/compiler-test-utils/AGENTS.md, "Corpus and implementation tests"). - */ -const implementationTests = '**/outside-compiler-corpus/**' - /** * The projects whose tests check route apps in pages of a real browser * (`tests/route-app.ts`): the tests of a file run concurrently, each on dev @@ -57,11 +51,7 @@ const config = defineConfig({ test: { ...pagesProject.test, name: 'unit', - exclude: [ - ...configDefaults.exclude, - 'integration/**', - implementationTests, - ], + exclude: [...configDefaults.exclude, 'integration/**'], typecheck: { enabled: true }, }, }, @@ -76,11 +66,7 @@ const config = defineConfig({ // started with (see `test-scope-setup`) isolate: false, include: ['integration/**/*.test.ts'], - exclude: [ - ...configDefaults.exclude, - implementationTests, - 'integration/pages/**', - ], + exclude: [...configDefaults.exclude, 'integration/pages/**'], testTimeout: 30_000, hookTimeout: 30_000, }, @@ -94,30 +80,6 @@ const config = defineConfig({ ...pagesProject.test, name: 'integration-pages', include: ['integration/pages/**/*.test.ts'], - exclude: [...configDefaults.exclude, implementationTests], - hookTimeout: 30_000, - }, - }, - { - // Implementation tests (`test:implementation`, both tiers): files - // under an `outside-compiler-corpus/` directory. They pin choices of - // today's implementation that a correct compiler may make - // differently, so the corpus targets above leave them out (see - // packages/compiler-test-utils/AGENTS.md). - extends: true, - test: { - name: 'implementation', - include: ['**/outside-compiler-corpus/**/*.test.ts'], - exclude: [...configDefaults.exclude, 'integration/**'], - typecheck: { enabled: true }, - }, - }, - { - extends: true, - test: { - name: 'implementation-integration', - include: ['integration/**/outside-compiler-corpus/**/*.test.ts'], - testTimeout: 30_000, hookTimeout: 30_000, }, }, diff --git a/packages/start-plugin-core/package.json b/packages/start-plugin-core/package.json index 1669dcd1b7..89c43a704b 100644 --- a/packages/start-plugin-core/package.json +++ b/packages/start-plugin-core/package.json @@ -30,8 +30,6 @@ "test": "pnpm test:eslint && pnpm test:types && pnpm test:build && pnpm test:unit && pnpm test:integration && pnpm test:noncompiler", "test:unit": "vitest --project unit", "test:integration": "vitest --project integration --project integration-pages", - "test:implementation": "vitest --project implementation --project implementation-integration", - "test:implementation:unit": "vitest --project implementation", "test:integration:smoke": "vitest --project integration integration/importProtection/build.test.ts -t \"build.*a denied re-export barrel the client uses fails the build\"", "test:eslint": "eslint ./src ./tests", "test:types": "pnpm run \"/^test:types:ts[0-9]{2}$/\"", @@ -74,33 +72,6 @@ } ] }, - "test:implementation": { - "dependsOn": [ - "^build", - "build", - { - "projects": [ - "@tanstack/react-start", - "@tanstack/solid-start", - "@tanstack/vue-start" - ], - "target": "build" - } - ] - }, - "test:implementation:unit": { - "dependsOn": [ - "^build", - { - "projects": [ - "@tanstack/react-start", - "@tanstack/solid-start", - "@tanstack/vue-start" - ], - "target": "build" - } - ] - }, "test:integration:smoke": { "dependsOn": [ "^build", diff --git a/packages/start-plugin-core/tests/build-harness.ts b/packages/start-plugin-core/tests/build-harness.ts index 38163ce119..78fcb5114e 100644 --- a/packages/start-plugin-core/tests/build-harness.ts +++ b/packages/start-plugin-core/tests/build-harness.ts @@ -50,7 +50,6 @@ import path from 'node:path' import { fileURLToPath, pathToFileURL } from 'node:url' import { linkWorkspacePackages, - workspacePackage, workspacePackageLinks, } from '@tanstack/compiler-test-utils/workspace-packages' import { @@ -93,13 +92,6 @@ import type { ViolationInfo } from './importProtection/public-types' import type { RsbuildConfig, RsbuildPlugin } from '@rsbuild/core' import type { InlineConfig, Plugin } from 'vite' -/** - * The workspace's built `@tanstack/react-start` package, which apps link - * (`startRuntimeLinks`): the `test:integration` target depends on its - * `build` target, as this package cannot depend on it. - */ -export const reactStartPackage = workspacePackage('@tanstack/react-start') - /** * Links (`AppOptions.symlinks`) that give an app Start's real runtime: * `node_modules/@tanstack/react-start` is the workspace package diff --git a/packages/start-plugin-core/tests/compiler-transforms-seam.ts b/packages/start-plugin-core/tests/compiler-transforms-seam.ts deleted file mode 100644 index 90afe70ff1..0000000000 --- a/packages/start-plugin-core/tests/compiler-transforms-seam.ts +++ /dev/null @@ -1,42 +0,0 @@ -/** - * The test transforms given to the Start plugin's `compilerTransforms` hook - * (`StartCompilerImportTransform`, src/types.ts). - * - * This is the ONLY test file that binds to the AST shape the hook hands to a - * transform (today Babel's: `candidate.path.node`, `context.types`, - * `context.parseExpression`). A compiler rewrite that changes that shape - * adapts this file alone; every test uses these transforms through their - * observable effect (the injected argument), never through the - * AST. - */ -import type { StartCompilerImportTransform } from '../src/types' - -/** - * An external import transform (`compilerTransforms`), shaped like the RSC - * CSS transform: on the server, it injects `{ injected: loadThing() }` as - * the second argument of each direct call of `renderThing` from - * `@example/runtime` given one argument. - */ -export const renderThingTransform: StartCompilerImportTransform = { - name: 'test-render-option-injection', - environment: 'server', - imports: [{ libName: '@example/runtime', rootExport: 'renderThing' }], - detect: /\brenderThing\b/, - transform: (candidates, context) => { - const t = context.types - for (const candidate of candidates) { - const args = candidate.path.node.arguments - if (args.length !== 1) { - continue - } - args.push( - t.objectExpression([ - t.objectProperty( - t.identifier('injected'), - context.parseExpression('loadThing()'), - ), - ]), - ) - } - }, -} diff --git a/packages/start-plugin-core/tests/createServerFn/createServerFn.test.ts b/packages/start-plugin-core/tests/createServerFn/createServerFn.test.ts index c157df6e4f..8f7a9fc897 100644 --- a/packages/start-plugin-core/tests/createServerFn/createServerFn.test.ts +++ b/packages/start-plugin-core/tests/createServerFn/createServerFn.test.ts @@ -76,8 +76,7 @@ describe('createServerFn compiles correctly', () => { // error at the server fn's line (SPEC G5). Editors count \n, \r\n, a // lone \r, U+2028 and U+2029 as line terminators, so the reported line // must count every one. Prose, frame layout and context length are free - // (§5.7). (The column, which Start spells only with the code frame's - // caret: known-bugs-start-compiler-code-frame.test.ts, F1.) + // (§5.7). test.each([ ['\\n', '\n'], ['\\r\\n', '\r\n'], diff --git a/packages/start-plugin-core/tests/importProtection/mock-helpers.ts b/packages/start-plugin-core/tests/importProtection/mock-helpers.ts index 05b9cd9d3d..e921576cb9 100644 --- a/packages/start-plugin-core/tests/importProtection/mock-helpers.ts +++ b/packages/start-plugin-core/tests/importProtection/mock-helpers.ts @@ -16,9 +16,7 @@ * thenable that resolves to itself. * * Pure: only the probe and the readers of the runtime diagnostics, no module - * of the implementation (the evaluators of the generated mock modules are in - * `outside-compiler-corpus/importProtection/mock-modules.ts`, used only by - * implementation tests). + * of the implementation. */ import { expect } from 'vitest' import { findDiagnostics } from '@tanstack/compiler-test-utils/diagnostics' diff --git a/packages/start-plugin-core/tests/integration/importProtection/build-markers.test.ts b/packages/start-plugin-core/tests/integration/importProtection/build-markers.test.ts index e24cb1cc22..f8ec97f4fe 100644 --- a/packages/start-plugin-core/tests/integration/importProtection/build-markers.test.ts +++ b/packages/start-plugin-core/tests/integration/importProtection/build-markers.test.ts @@ -27,14 +27,6 @@ import type { ViolationInfo } from '../../importProtection/public-types' const timeout = 60_000 -/** - * Start's import protection options of a build that fails on a violation, - * denying `files` to the client. - */ -function importProtection(files: Array = []) { - return { importProtection: { behavior: 'error', client: { files } } } as const -} - /** A server-only module (denied to the client by `importedAs`). */ const deniedModules = { 'a denied file': { diff --git a/packages/start-plugin-core/tests/integration/importProtection/build-mock.test.ts b/packages/start-plugin-core/tests/integration/importProtection/build-mock.test.ts index 46c673d39c..247a0b5b75 100644 --- a/packages/start-plugin-core/tests/integration/importProtection/build-mock.test.ts +++ b/packages/start-plugin-core/tests/integration/importProtection/build-mock.test.ts @@ -26,14 +26,6 @@ import type { Diagnostic } from '@tanstack/compiler-test-utils/diagnostics' const timeout = 60_000 -/** - * Start's import protection options of a build that fails on a violation, - * denying `files` to the client. - */ -function importProtection(files: Array = []) { - return { importProtection: { behavior: 'error', client: { files } } } as const -} - /** A server-only module (denied to the client by `importedAs`). */ const deniedModules = { 'a denied file': { diff --git a/packages/start-plugin-core/tests/integration/importProtection/mock-shapes.test.ts b/packages/start-plugin-core/tests/integration/importProtection/mock-shapes.test.ts index 9f3a027cb3..e36fc395de 100644 --- a/packages/start-plugin-core/tests/integration/importProtection/mock-shapes.test.ts +++ b/packages/start-plugin-core/tests/integration/importProtection/mock-shapes.test.ts @@ -14,9 +14,9 @@ * `src/cases/` whose `values()` gives what it read from the denied module; * one app holds every case, so each channel builds or serves it once. * - * Replaces the internal controls that evaluated today's generated mock - * modules in process (`outside-compiler-corpus/importProtection/ - * analysis.exports.test.ts`, `rewrite.test.ts`). The names today's mocks miss + * Replaces main's internal tests that evaluated today's generated mock + * modules in process (`importProtection/analysis.exports.test.ts`, + * `rewrite.test.ts`, deleted). The names today's mocks miss * (reserved words, namespace re-exports, enums, a member read before the * import, computed keys) are pinned in `known-bugs.test.ts` ("app-level * twins of the mock pins"); `export *` and `export * as ns` of a denied diff --git a/packages/start-plugin-core/tests/integration/start-build-warnings.test.ts b/packages/start-plugin-core/tests/integration/start-build-warnings.test.ts index a317c0b304..8a2cf9c47b 100644 --- a/packages/start-plugin-core/tests/integration/start-build-warnings.test.ts +++ b/packages/start-plugin-core/tests/integration/start-build-warnings.test.ts @@ -1,9 +1,6 @@ /** * A failure of the Start compiler fails the build and tells the user which * module it is about, on every bundler, without hanging (SPEC G5, G11). - * (The warning channel of today's compiler extension API is checked by the - * implementation tests in `outside-compiler-corpus/start-build-warnings - * .test.ts`.) */ import { describe, expect, test } from 'vitest' import { problems } from '@tanstack/compiler-test-utils/diagnostic-channel' diff --git a/packages/start-plugin-core/tests/integration/start-compose-app.ts b/packages/start-plugin-core/tests/integration/start-compose-app.ts index 69805f2552..0d57ce6504 100644 --- a/packages/start-plugin-core/tests/integration/start-compose-app.ts +++ b/packages/start-plugin-core/tests/integration/start-compose-app.ts @@ -113,8 +113,7 @@ export interface ServedStartBuild { } /** - * Node's own `import()`, outside Vitest's module runner (the shared - * helper of `@tanstack/compiler-test-utils/module-linker`): a built server + * Node's own `import()`, outside Vitest's module runner: a built server * bundle loads its chunks itself (Rspack's by `file:` URL), which the * runner would try to resolve. */ diff --git a/packages/start-plugin-core/tests/known-bugs-start-compiler-code-frame.test.ts b/packages/start-plugin-core/tests/known-bugs-start-compiler-code-frame.test.ts deleted file mode 100644 index 65c608ccfb..0000000000 --- a/packages/start-plugin-core/tests/known-bugs-start-compiler-code-frame.test.ts +++ /dev/null @@ -1,84 +0,0 @@ -/** - * Known bug of the Start compiler's diagnostics (SPEC G5: a compile error - * points at the user's code, line and column): the code frame of a compile - * error draws its caret one column left of the offending code. - * - * Finding F1 of validation/REPAIR/A2.md (DECISIONS 2026-10-21): the - * compiler hands an AST location's 0-based column to a code-frame API that - * counts columns from 1, so the `^` lands on the character before the call - * (a call at the very start of a line is drawn right: the API reads - * column 0 as "no column"). - * - * The pin is fix-agnostic: the frame's layout, context length and whether - * a frame is drawn at all are free (§5.7); only a caret the error draws - * under the offending line must point at the offending code. - */ -import { stripVTControlCharacters } from 'node:util' -import { describe, expect, test } from 'vitest' -import { diagnosticPosition } from '@tanstack/compiler-test-utils/diagnostics' -import { compileError, useStartHost } from './regression-helpers' - -const host = useStartHost() - -/** - * The 1-based source columns the carets of a code frame in `text` point at - * under line `line` of `source`: for each frame line quoting that source - * line (`> | `), the first `^` of the marker line below it, - * measured from where the quoted code starts. - */ -function caretColumns(text: string, source: string, line: number) { - const sourceLine = source.split(/\r\n|[\n\r\u2028\u2029]/)[line - 1]! - const lines = stripVTControlCharacters(text).split(/\r?\n/) - const columns: Array = [] - for (let index = 0; index < lines.length - 1; index++) { - const frameLine = /^\s*>?\s*(\d+)\s*\|/.exec(lines[index]!) - if (!frameLine || Number(frameLine[1]) !== line) { - continue - } - const marker = lines[index + 1]! - if (!/^\s*>?\s*\|\s*\^/.test(marker)) { - continue - } - const gutter = lines[index]!.indexOf('|') - const start = lines[index]!.indexOf(sourceLine, gutter + 1) - if (start < 0) { - continue - } - columns.push(marker.indexOf('^') - start + 1) - } - return columns -} - -describe('the code frame of a compile error points at the offending code', () => { - // Bug: the caret is drawn one column left of the call (F1). - // Impact: the frame highlights the character before the call. - // Source: validation/REPAIR/A2.md F1. - test.fails.each([ - { - name: 'a call after a declaration', - source: `import { createServerFn } from '@tanstack/react-start' -export const fn = createServerFn().handler()`, - }, - { - name: 'an indented call on a line of its own', - source: `import { createServerFn } from '@tanstack/react-start' -export const fn = - createServerFn().handler()`, - }, - ])('$name', async ({ source }) => { - const startCase = await (await host()).case({ 'module.tsx': source }) - const failure = await compileError(startCase) - expect(failure, 'a compile error').toBeInstanceOf(Error) - const at = diagnosticPosition(source, 'createServerFn()') - // Every frame the failure shows, on any channel - const text = [ - (failure!.error as Error).message, - (failure!.error as { frame?: string }).frame ?? '', - ...failure!.reported.map((diagnostic) => diagnostic.text), - ].join('\n') - const carets = caretColumns(text, source, at.line) - expect(carets, 'columns the carets point at').toEqual( - carets.map(() => at.column), - ) - }) -}) diff --git a/packages/start-plugin-core/tests/outside-compiler-corpus/importProtection/mock-modules.ts b/packages/start-plugin-core/tests/outside-compiler-corpus/importProtection/mock-modules.ts deleted file mode 100644 index 00a0844599..0000000000 --- a/packages/start-plugin-core/tests/outside-compiler-corpus/importProtection/mock-modules.ts +++ /dev/null @@ -1,113 +0,0 @@ -/** - * Evaluators of the mock modules import protection generates, through the - * same internal pipeline the plugins use (the names an importer uses from a - * denied source -> a mock-edge module importing the mock runtime, or the - * self-contained mock of a denied file), linked as ES modules - * (`@tanstack/compiler-test-utils/module-linker`). They call the - * implementation's analysis and generators directly, so only implementation - * tests use them; the corpus judges a mock through a real consumer of the - * public plugin (`mock-helpers.ts`, `probeMock`). - */ -import { createModuleGraph } from '@tanstack/compiler-test-utils/module-linker' -import { - getMockExportNamesBySource, - getNamedExports, -} from '../../../src/import-protection/analysis' -import { MOCK_MODULE_ID } from '../../../src/import-protection/constants' -import { - generateDevSelfDenialModule, - generateSelfContainedMockModule, - makeMockEdgeModuleId, -} from '../../../src/import-protection/virtualModules' -import { - loadResolvedVirtualModule, - resolveInternalVirtualModuleId, -} from '../../../src/vite/import-protection-plugin/virtualModules' -import type { ModuleStub } from '@tanstack/compiler-test-utils/module-linker' - -/** - * Evaluates `importer` with each denied import `source` (one specifier or - * several) replaced by the mock edge import protection serves for it: a - * module exporting a mock for each name the importer uses from that source - * (and a default export), all members of the mock runtime `runtimeId` - * (default: the silent mock). Other imports link to `stubs` (by specifier) or - * fail to link. Returns the importer's namespace. - */ -export async function evaluateWithMock( - importer: string, - source: string | Array, - options: { - /** Id the importer is analysed and evaluated under. */ - id?: string - stubs?: Record - runtimeId?: string - } = {}, -): Promise> { - const id = options.id ?? '/test/src/importer.ts' - const namesBySource = getMockExportNamesBySource(importer, id) - const edgeIds = new Map( - (Array.isArray(source) ? source : [source]).map((denied) => [ - denied, - mockEdgeId(namesBySource.get(denied) ?? [], options.runtimeId), - ]), - ) - const graph = createModuleGraph({ - modules: { [id]: importer }, - stubs: options.stubs, - resolve: (specifier) => - edgeIds.get(specifier) ?? resolveInternalVirtualModuleId(specifier), - load: (virtualId) => loadResolvedVirtualModule(virtualId)?.code, - }) - return graph.import(id) -} - -/** - * Evaluates the self-contained mock import protection serves for a denied - * file in place of the file itself, generated from the names the file - * exports (`code`, analysed under `id`). Returns the mock's namespace. - */ -export async function selfMock( - code: string, - id = '/test/src/denied.server.ts', -): Promise> { - return evaluateMockModule( - generateSelfContainedMockModule(getNamedExports(code, id)).code, - ) -} - -/** - * Evaluates each kind of mock module import protection generates for the - * export names `names` and returns its namespace: the self-contained mock of - * a denied file, the mock edge of a denied import (for an importer using - * `names`) and the module dev serves in place of a denied file exporting - * `names`, the last two importing the silent mock runtime. - */ -export const mockModules: Record< - 'self-contained mock' | 'mock edge' | 'dev self-denial module', - (names: Array) => Promise> -> = { - 'self-contained mock': (names) => - evaluateMockModule(generateSelfContainedMockModule(names).code), - 'mock edge': (names) => - evaluateMockModule(loadResolvedVirtualModule(mockEdgeId(names))!.code), - 'dev self-denial module': (names) => - evaluateMockModule(generateDevSelfDenialModule(names, MOCK_MODULE_ID).code), -} - -/** Resolved id of the mock edge exporting `names` as members of `runtimeId`. */ -function mockEdgeId(names: Array, runtimeId = MOCK_MODULE_ID) { - return resolveInternalVirtualModuleId(makeMockEdgeModuleId(names, runtimeId))! -} - -/** - * Evaluates a generated mock module as an ES module; what it imports links - * to the virtual modules import protection serves (the mock runtime). - */ -export function evaluateMockModule(code: string): Promise> { - const mockId = '/test/mock.js' - return createModuleGraph({ - modules: { [mockId]: code }, - resolve: (specifier) => resolveInternalVirtualModuleId(specifier), - load: (virtualId) => loadResolvedVirtualModule(virtualId)?.code, - }).import(mockId) -} diff --git a/packages/start-plugin-core/tests/outside-compiler-corpus/legacy/regression-helpers.ts b/packages/start-plugin-core/tests/outside-compiler-corpus/legacy/regression-helpers.ts deleted file mode 100644 index af7ce755b9..0000000000 --- a/packages/start-plugin-core/tests/outside-compiler-corpus/legacy/regression-helpers.ts +++ /dev/null @@ -1,547 +0,0 @@ -/** - * LEGACY (outside the compiler corpus): the internal harness the corpus - * used before it was rerouted through the public Start plugin - * (`tests/start-host.ts`, `tests/regression-helpers.ts`). It drives the - * internal `StartCompiler`, the provider query and the server-fn report, - * so only implementation tests (`outside-compiler-corpus/`) may use it. - * - * Compiles a module into its client, SSR caller and server-function - * provider outputs, and evaluates compiled modules (linked as real ES - * modules, `@tanstack/compiler-test-utils/module-linker`) against Start's - * runtime (`../../start-runtime`) and the real packages (React, the - * routers). - */ -import path from 'node:path' -import { fileURLToPath } from 'node:url' -import { createModuleGraph } from '@tanstack/compiler-test-utils/module-linker' -import { identifiesEnvRestriction } from '@tanstack/compiler-test-utils/diagnostics' -import { parseSync } from 'vite' -import { expect } from 'vitest' -import { - StartCompiler, - detectKindsInCode, - getLookupKindsForEnv, -} from '../../../src/start-compiler/compiler' -import { getLookupConfigurationsForEnv } from '../../../src/start-compiler/config' -import { - createClientRpc, - createServerRpc, - createSsrRpc, - startClientCore, -} from '../../start-runtime' -import type { Environment } from '@tanstack/compiler-test-utils/diagnostics' -import type { - ModuleGraphOptions, - ModuleStub, -} from '@tanstack/compiler-test-utils/module-linker' -import type { ServerFn } from '../../../src/start-compiler/types' -import type { - CompileStartFrameworkOptions, - StartCompilerImportTransform, - StartCompilerPlugin, - StartCompilerTransformResult, -} from '../../../src/types' - -export { importSources } from '../../imports' - -export type Output = 'client' | 'ssr' | 'provider' -export const moduleId = '/test/src/module.tsx' - -/** The framework a module is compiled for: its `@tanstack/-*` packages. */ -export type Framework = CompileStartFrameworkOptions - -interface StartCompilerOptions { - env: 'client' | 'server' - mode?: 'build' | 'dev' - /** Default `react`. */ - framework?: Framework - /** Project modules by absolute id; `./name` resolves to `/test/src/name.ts`. */ - files?: Record - /** `serverFnProviderModuleDirectives` */ - directives?: Array - compilerPlugins?: Array - /** External import transforms (`compilerTransforms` of the Start plugin). */ - compilerTransforms?: Array - /** - * Host hooks replacing the default ones (which resolve and load `files` - * and the `@tanstack/*` packages). - */ - host?: { - resolveId?: (id: string, importer?: string) => Promise - loadModule?: (id: string) => Promise - } -} - -/** - * Creates a `StartCompiler` (React unless `framework` says otherwise) - * configured the way the bundler plugins do, and records the server - * functions it reports. `compile` returns the compiled code, `transform` the - * code and its source map (`null` when the module is left untouched). - */ -export function createStartCompiler(options: StartCompilerOptions) { - const { env, files = {}, framework = 'react', compilerTransforms } = 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, { compilerTransforms }), - lookupConfigurations: getLookupConfigurationsForEnv(env, framework, { - compilerTransforms, - }), - 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, - compilerTransforms, - ...options.host, - }) - const transform = async ( - code: string, - id = moduleId, - ): Promise => - (await compiler.compile({ - code, - id, - // Detected the way the bundler plugins detect them. - detectedKinds: detectKindsInCode(code, env, { compilerTransforms }), - })) ?? null - const compile = async (code: string, id = moduleId) => - (await transform(code, id))?.code ?? null - return { compiler, compile, transform, serverFns } -} - -/** - * Compiles `code` for one output: the client, the SSR caller or the - * server-function provider module (`?tss-serverfn-split`). Returns the code - * and its source map (both `null` when the module is left untouched). - */ -export async function compileFor( - output: Output, - code: string, - options: Omit & { id?: string } = {}, -) { - const { transform, serverFns } = createStartCompiler({ - ...options, - env: output === 'client' ? 'client' : 'server', - }) - const id = options.id ?? moduleId - const result = await transform( - code, - output === 'provider' ? `${id}?tss-serverfn-split` : id, - ) - return { code: result?.code ?? null, map: result?.map ?? null, serverFns } -} - -/** Like `compileFor`, returning only the code (null when untouched). */ -export async function compileCode( - ...args: Parameters -): Promise { - return (await compileFor(...args)).code -} - -/** - * The modules of the SSR bundle compiled from one source module: the SSR - * caller, under the module's id, and the server-function provider, under the - * id with `?tss-serverfn-split`. The provider may import the SSR caller (or - * anything else) like any module of the bundle. - */ -export interface ServerOutputs { - /** The SSR caller; `undefined` when compiling it failed. */ - ssr: string | undefined - provider: string - /** Id of the source module. Default `/test/src/module.tsx`. */ - id?: string - /** Default `react`. */ - framework?: Framework - /** - * The server fns the callers reported (`onServerFnsById`), which the - * server-fn resolver serves: an SSR call by id (`createSsrRpc`) runs the - * handler of the provider module and export the report names. - */ - serverFns?: Record - /** Project modules by absolute id, linked as they are (uncompiled). */ - files?: Record -} - -// The `compilerTransforms` test transform lives in the seam module. -export { renderThingTransform } from '../../compiler-transforms-seam' - -/** - * Where an evaluated module runs: in the browser (`client`, the default) or - * in the server bundle (`server`). - */ -export type RuntimeEnv = 'client' | 'server' - -/** An RPC factory that environment's callers must not use. */ -function foreignRpc(factory: string, env: RuntimeEnv) { - return (functionId: string) => { - throw new Error(`${factory}(${functionId}) in the ${env} runtime`) - } -} - -/** - * An SSR RPC evaluated outside an SSR bundle: it carries the id but cannot - * be called (`createServerGraph` links one that resolves the handler). - */ -function unlinkedSsrRpc(functionId: string) { - return Object.assign(() => { - throw new Error( - `createSsrRpc(${functionId}) outside an SSR bundle (createServerGraph)`, - ) - }, createSsrRpc(functionId)) -} - -/** - * A client RPC: the one Start creates (its id, url and marker), except that - * calling it throws instead of fetching a server the harness does not run. - */ -function unlinkedClientRpc(functionId: string) { - return Object.assign(() => { - throw new Error(`client RPC ${functionId} called: no server to fetch`) - }, createClientRpc(functionId)) -} - -/** - * The Start packages of a framework, in `env`: Start's real runtime - * (`../../start-runtime`) for `@tanstack/-start` and its - * `/server-rpc` entry. The RPCs of callers are the only stand-ins: a client - * RPC is Start's own without its fetch (`unlinkedClientRpc`); an SSR RPC - * resolves the provider's handler by id, which only an SSR bundle can do - * (`createServerGraph`), and elsewhere cannot be called. A client RPC in - * the server runtime throws: SSR callers must use their own RPC. - */ -function startRuntime( - framework: Framework, - env: RuntimeEnv = 'client', -): Record { - const start = `@tanstack/${framework}-start` - return { - [start]: startClientCore, - [`${start}/server-rpc`]: { createServerRpc }, - [`${start}/client-rpc`]: { - createClientRpc: - env === 'client' - ? unlinkedClientRpc - : foreignRpc('createClientRpc', env), - }, - [`${start}/ssr-rpc`]: { - createSsrRpc: unlinkedSsrRpc, - }, - } -} - -/** - * The id of the RPC a caller's server fn calls: the id of Start's server-fn - * metadata (`serverFnMeta.id`; other metadata fields are free). - * `undefined` when the server fn carries no id (e.g. an uncompiled one, - * whose handler is left in place). Tests that need the call to reach the - * server prove it through the reported handler (`callServerFnThroughCallers`, - * `callFromClient`). - */ -export function callerRpcId(fn: unknown): string | undefined { - if (typeof fn !== 'function') { - return undefined - } - const meta = (fn as { serverFnMeta?: Record }).serverFnMeta - return typeof meta?.id === 'string' ? meta.id : undefined -} - -/** - * Where the real packages of the test graphs resolve from (this package's - * dependencies: `react`, `react-dom`, the routers). - */ -const testPackagesDir = path.resolve( - path.dirname(fileURLToPath(import.meta.url)), - '../..', -) - -/** - * A graph of linked modules (`createModuleGraph`) whose imports resolve to - * `stubs` (by specifier) over the Start runtime of `framework` - * (default `react`), then to the real packages (`packages`, by default - * this package's): JSX compiles with React's automatic runtime and renders - * with the real React. - */ -export function createTestModuleGraph( - options: ModuleGraphOptions & { framework?: Framework; env?: RuntimeEnv }, -) { - const { framework = 'react', env, ...graphOptions } = options - return createModuleGraph({ - packages: testPackagesDir, - ...graphOptions, - stubs: { ...startRuntime(framework, env), ...graphOptions.stubs }, - }) -} - -/** - * Evaluates a compiled module like a bundler would: TypeScript is erased, JSX - * compiles with React's automatic runtime, and every import is linked, as a - * real ES module, to the Start runtime of `framework` (default `react`) for - * `env` (default `client`), to `stubs` (by specifier; `.json` string stubs - * are JSON modules), to the project modules `files` (by absolute id, linked - * as they are) or to the real packages (`react`, the routers). Every call - * evaluates a fresh instance, even for identical code. - */ -export async function evaluateModule( - code: string, - stubs: Record = {}, - options: { - framework?: Framework - env?: RuntimeEnv - files?: Record - } = {}, -): Promise> { - return createTestModuleGraph({ - modules: { ...options.files, [moduleId]: code }, - stubs, - framework: options.framework, - env: options.env, - }).import(moduleId) -} - -/** - * Renders a React node (e.g. what an evaluated module's component returns) - * to static HTML with the real `react-dom/server`. - */ -export async function renderToHtml(node: unknown) { - const graph = createTestModuleGraph({}) - const { renderToStaticMarkup } = await graph.importPackage('react-dom/server') - return renderToStaticMarkup(node) as string -} - -function isServerOutputs(value: object): value is ServerOutputs { - return ( - typeof (value as Partial).provider === 'string' && - 'ssr' in value - ) -} - -/** - * Links the modules of the SSR bundle (`ServerOutputs`) into one graph, like - * the bundler does: a provider that imports the SSR caller (e.g. its shared - * state or helpers) gets the instance the SSR caller module is. A module is - * evaluated only when it is imported. Imports of other modules link to - * `stubs` (by specifier) over the Start runtime. - */ -export function createServerGraph( - server: ServerOutputs, - stubs: Record = {}, -) { - const id = server.id ?? moduleId - const providerId = `${id}?tss-serverfn-split` - const modules: Record = { - ...server.files, - [providerId]: server.provider, - } - if (server.ssr !== undefined) { - modules[id] = server.ssr - } - // Like the server-fn resolver: the handler a reported id names, in the - // module of this bundle the report names. - const resolve = async (functionId: string) => { - const fn = server.serverFns?.[functionId] - if (!fn) { - throw new Error(`Server function info not found for ${functionId}`) - } - return (await graph.import(fn.extractedFilename))[fn.functionName] - } - const graph = createTestModuleGraph({ - modules, - stubs: { - [`@tanstack/${server.framework ?? 'react'}-start/ssr-rpc`]: { - // Start's createSsrRpc, whose call resolves the handler like the - // server-fn resolver of the app's build does. - createSsrRpc: (functionId: string) => - Object.assign( - async (...args: Array) => - (await resolve(functionId))(...args), - createSsrRpc(functionId), - ), - }, - ...stubs, - }, - framework: server.framework, - env: 'server', - }) - return { - /** Evaluates (once) and returns the provider module. */ - provider: () => graph.import(providerId), - /** Evaluates (once) and returns the SSR caller module. */ - ssr: () => graph.import(id), - /** Evaluates (once) and returns the module of the graph with this id. */ - import: (graphModuleId: string) => graph.import(graphModuleId), - /** Adds a module to the graph (e.g. a server fn resolver). */ - add: (graphModuleId: string, code: string) => - graph.add(graphModuleId, code), - /** Ids of the modules evaluated so far, in order. */ - evaluated: graph.evaluated, - } -} - -/** Evaluates the provider of `server` in its SSR bundle (`createServerGraph`). */ -export function evaluateProvider( - server: ServerOutputs, - stubs: Record = {}, -) { - return createServerGraph(server, stubs).provider() -} - -/** A server fn handler a provider module exports. */ -type ProviderHandler = ((opts: { - data?: unknown - context?: unknown - method?: string -}) => unknown) & { - serverFnMeta?: { id?: string; name?: string } -} - -/** - * The result of a server fn call, from the response its provider handler - * gives the server-fn router: `{ result }` (and the `context` server - * middleware sends back), or `{ error }` for a failed call, which throws. - */ -export function serverFnResult(response: unknown) { - expect(response, 'server fn response').toBeTypeOf('object') - expect(response, 'server fn response').not.toBeNull() - if ('error' in (response as object)) { - throw (response as { error: unknown }).error - } - expect(response, 'server fn response').toHaveProperty('result') - return (response as { result: unknown }).result -} - -/** - * Runs a provider's extracted handler the way the server-fn router does. The - * provider is evaluated in its SSR bundle, linked to the SSR caller - * (`createServerGraph`), or given already evaluated (`evaluateProvider`, to - * call it several times on one instance). The handler is found through the - * metadata the provider gives it at runtime (`serverFnMeta.name`, the name - * of the server fn), not through its export name. Returns the result of the - * call (`serverFnResult`). - */ -export async function callProvider( - server: ServerOutputs | Record, - name: string, - stubs: Record = {}, - data?: unknown, -) { - const module = isServerOutputs(server) - ? await evaluateProvider(server, stubs) - : server - const handlers = new Set( - Object.values(module).filter( - (value): value is ProviderHandler => - typeof value === 'function' && - (value as ProviderHandler).serverFnMeta?.name === name, - ), - ) - expect(handlers.size, `provider handlers named ${name}`).toBe(1) - return serverFnResult(await [...handlers][0]!({ data })) -} - -/** - * Calls every server fn the callers reported (`onServerFnsById`) the way the - * server-fn router does: in the SSR bundle (`createServerGraph`), it imports - * the reported `extractedFilename` (the provider, compiled under that id) and - * calls the reported `functionName` export. Returns the results in the order - * of `serverFns`. - */ -export async function callReportedServerFns( - server: ServerOutputs, - serverFns: Record, - stubs: Record = {}, -) { - const graph = createServerGraph(server, stubs) - const results: Array = [] - for (const fn of Object.values(serverFns)) { - const module = await graph.import(fn.extractedFilename) - const handler = module[fn.functionName] - expect(handler, fn.functionName).toBeTypeOf('function') - results.push(serverFnResult(await handler({ data: undefined }))) - } - return results -} - -/** The directives of a module's directive prologue, in order. */ -export function directivePrologue(code: string) { - const { program } = parseSync('module.tsx', code, { sourceType: 'module' }) - const directives: Array = [] - for (const statement of program.body) { - if ( - statement.type !== 'ExpressionStatement' || - !('directive' in statement) || - typeof statement.directive !== 'string' - ) { - break - } - directives.push(statement.directive) - } - return directives -} - -/** - * What `settle` gives for a call that throws: the thrown value itself, so - * oracles (`throwsError`) read the real error, and a - * value the call returns is never mistaken for a throw. - */ -export class Thrown { - constructor(readonly error: unknown) {} -} - -/** The value of `run`, or `Thrown` with the error it throws. */ -export function settle(run: () => unknown) { - try { - return run() - } catch (error) { - return new Thrown(error) - } -} - -/** - * The value `run` resolves to, or `Thrown` with the error it throws or - * rejects with. - */ -export async function settleAsync(run: () => unknown) { - try { - return await run() - } catch (error) { - return new Thrown(error) - } -} - -/** - * What `settle` gives for a `createServerOnlyFn` called outside the server - * (J4.10): it threw an error restricting the call to the server, whatever - * its prose (`identifiesEnvRestriction`). An asymmetric matcher: compare - * with `toEqual`. - */ -export const serverOnlyError = thrownEnvRestriction('server') -/** `serverOnlyError` for a `createClientOnlyFn` called outside the client. */ -export const clientOnlyError = thrownEnvRestriction('client') - -function thrownEnvRestriction(env: Environment) { - return expect.toSatisfy( - (value: unknown) => - value instanceof Thrown && identifiesEnvRestriction(value.error, env), - `a call that throws an error restricting it to the ${env}`, - ) -} diff --git a/packages/start-plugin-core/tests/start-runtime.ts b/packages/start-plugin-core/tests/start-runtime.ts deleted file mode 100644 index 139bd1053c..0000000000 --- a/packages/start-plugin-core/tests/start-runtime.ts +++ /dev/null @@ -1,81 +0,0 @@ -/** - * Start's real runtime, for the modules the harness evaluates: the - * `@tanstack/start-client-core` package (`createServerFn`, - * `createMiddleware`, `createStart`, the env-only and isomorphic factories, - * everything `@tanstack/-start` re-exports from it) and - * `createServerRpc` of `@tanstack/start-server-core`. - * - * Start runs server fns inside a request context (`runWithStartContext` of - * `@tanstack/start-storage-context`, which its request handler opens). The - * harness calls them outside any request, so the storage falls back to a - * context of an empty request: no request middleware ran, no global - * middleware, default start options. - */ -import { AsyncLocalStorage } from 'node:async_hooks' -import { realpathSync } from 'node:fs' -import { resolveModulePath } from 'exsolve' - -// The key `@tanstack/start-storage-context` shares its storage under. -const storageKey = Symbol.for('tanstack-start:start-storage-context') - -type Storage = AsyncLocalStorage & { tanstackStartTestFallback?: true } -const global = globalThis as unknown as Record -const storage: Storage = (global[storageKey] ??= new AsyncLocalStorage()) -if (!storage.tanstackStartTestFallback) { - const getStore = storage.getStore.bind(storage) - storage.getStore = () => - getStore() ?? { - request: new Request('http://localhost/_serverFn/test'), - startOptions: {}, - contextAfterGlobalMiddlewares: {}, - executedRequestMiddlewares: new Set(), - handlerType: 'serverFn', - getRouter: () => { - throw new Error('no router in the test request context') - }, - } - storage.tanstackStartTestFallback = true -} - -// `@tanstack/start-client-core` is a dependency of -// `@tanstack/start-server-core`, resolved from there. -const startClientCoreEntry = realpathSync( - resolveModulePath('@tanstack/start-client-core', { - from: resolveModulePath('@tanstack/start-server-core/package.json', { - from: import.meta.url, - }), - conditions: ['import', 'node'], - }), -) - -/** The exports of `@tanstack/start-client-core`. */ -export const startClientCore: Record = { - ...((await import(/* @vite-ignore */ startClientCoreEntry)) as Record< - string, - unknown - >), -} - -/** - * `createSsrRpc` of `@tanstack/start-server-core`: its RPCs carry the right - * metadata, but calling one asks the server-fn resolver of the app's build, - * which a test has none of (the harness links its own, `createServerGraph`). - */ -export const createSsrRpc: (functionId: string) => object = ( - await import('@tanstack/start-server-core/createSsrRpc') -).createSsrRpc - -/** `createServerRpc` of `@tanstack/start-server-core`. */ -export const createServerRpc: ( - serverFnMeta: { id: string; name: string; filename: string }, - splitImportFn: (...args: Array) => any, -) => object = (await import('@tanstack/start-server-core/createServerRpc')) - .createServerRpc - -/** `createClientRpc` of `@tanstack/start-client-core/client-rpc`. */ -export const { createClientRpc } = (await import( - /* @vite-ignore */ startClientCoreEntry.replace( - /index\.js$/, - 'client-rpc/index.js', - ) -)) as { createClientRpc: (functionId: string) => object } diff --git a/packages/start-plugin-core/vite.config.ts b/packages/start-plugin-core/vite.config.ts index 0b6cf37710..579f619332 100644 --- a/packages/start-plugin-core/vite.config.ts +++ b/packages/start-plugin-core/vite.config.ts @@ -20,12 +20,6 @@ if (process.env.VITEST) { ) } -/** - * Implementation tests: outside the compiler test corpus (see - * packages/compiler-test-utils/AGENTS.md, "Corpus and implementation tests"). - */ -const implementationTests = '**/outside-compiler-corpus/**' - /** This package's build output (`dist`), as its `exports` name it. */ const builtPackage = new RegExp( `^${path.join(path.dirname(fileURLToPath(import.meta.url)), 'dist').replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}/`, @@ -59,7 +53,6 @@ const config = defineConfig({ exclude: [ ...configDefaults.exclude, 'integration/**', - implementationTests, ...noncompilerTests, ], typecheck: { enabled: true }, @@ -76,11 +69,7 @@ const config = defineConfig({ // started with (see `test-scope-setup`) isolate: false, include: ['integration/**/*.test.ts'], - exclude: [ - ...configDefaults.exclude, - implementationTests, - 'integration/pages/**', - ], + exclude: [...configDefaults.exclude, 'integration/pages/**'], testTimeout: 30_000, hookTimeout: 30_000, // The tests import this package's built public entries @@ -104,37 +93,12 @@ const config = defineConfig({ test: { name: 'integration-pages', include: ['integration/pages/**/*.test.ts'], - exclude: [...configDefaults.exclude, implementationTests], sequence: { concurrent: true }, isolate: false, testTimeout: 30_000, hookTimeout: 60_000, }, }, - { - // Implementation tests (`test:implementation`, both tiers): files - // under an `outside-compiler-corpus/` directory. They pin choices of - // today's implementation that a correct compiler may make - // differently, so the corpus targets above leave them out (see - // packages/compiler-test-utils/AGENTS.md). - extends: true, - test: { - name: 'implementation', - include: ['**/outside-compiler-corpus/**/*.test.ts'], - exclude: [...configDefaults.exclude, 'integration/**'], - typecheck: { enabled: true }, - }, - }, - { - extends: true, - test: { - name: 'implementation-integration', - include: ['integration/**/outside-compiler-corpus/**/*.test.ts'], - testTimeout: 30_000, - hookTimeout: 30_000, - server: { deps: { external: [builtPackage] } }, - }, - }, ], }, })