diff --git a/.changeset/compiler-per-export-fingerprints.md b/.changeset/compiler-per-export-fingerprints.md new file mode 100644 index 0000000000..8631c0fa76 --- /dev/null +++ b/.changeset/compiler-per-export-fingerprints.md @@ -0,0 +1,5 @@ +--- +'@tanstack/router-utils': patch +--- + +Dev: a plan depends on the exports it reads of another module, not on that module's whole export list. Adding an export to a widely imported module (or changing one an importer doesn't use) no longer re-plans and re-transforms every importer: on a 1,500-route app, appending an export to a module every route imports went from about 6.7 s to 32 ms until the update. diff --git a/packages/router-utils/src/compiler/README.md b/packages/router-utils/src/compiler/README.md index 21ee0e926b..755a481261 100644 --- a/packages/router-utils/src/compiler/README.md +++ b/packages/router-utils/src/compiler/README.md @@ -219,8 +219,9 @@ text compiles waits for it and emits its own output from the result. - `PlanCache`: one plan per (env, canonical id, config key; the late pass is a second config key of a file), the latest revision only. A hit is _validated_ (same canonical identity, input hash, config/env digest, and every dependency fingerprint still current). Live keys (published, or with an attempt active) are indexed by path, so `invalidate()` finds a changed file's plans without scanning. -- `DependencyLedger`: dependencies are recorded as facts are acquired (resolutions, summary digests, target facts, - route registry digests, failed resolutions), and a `DependentsIndex` maps them back to plans: a published plan's +- `DependencyLedger`: dependencies are recorded as facts are acquired (resolutions, the exports a lookup read, a + module's `export *` list when a lookup went through it, whole summaries for a listing of a namespace's exports or a + module without a summary, target facts, route registry digests, failed resolutions), and a `DependentsIndex` maps them back to plans: a published plan's rows until it is evicted or replaced, rows in flight until the key's last compile ends (two quick saves overlap). - `invalidate(caches, change, hosts)` is **the** invalidation operation: hosts call it per file change/add/unlink; it evicts the file's plans in every env, marks its raw facts stale, re-validates dependents' fingerprints with each @@ -228,8 +229,10 @@ text compiles waits for it and emits its own output from the result. add/unlink also retry failed resolutions, and they or a `package.json` change drop the resolution memo; an add also re-asks the resolutions it may take: a file of the same name with another extension, or of a directory a resolution went into; a resolution that found an unlinked file is stale without asking) and returns - `{ evicted, dependents }`, which the host hard-invalidates in the bundler. A summary change invalidates importers - only when its export-facts digest changed. + `{ evicted, dependents }`, which the host hard-invalidates in the bundler. A summary change invalidates an importer + only when what it read changed: the digest of an export it looked up (`ModuleSummary.exportKeys`; an absent name + appearing counts), the `export *` list a lookup walked, or the whole export-facts digest for a listing. An export + added to a widely imported module re-plans none of its importers. - Raw facts validated at the current `RawFactsCache.version` are not asked again on a hit or at publication (`CacheEntry.factsAt`): the version moves on every `markStale`, `forget` and `retain` drop, which is how anything that changes a raw-facts answer reaches the cache (a host that saw a file missing marks it stale when it may have diff --git a/packages/router-utils/src/compiler/cache.ts b/packages/router-utils/src/compiler/cache.ts index 4bffaa361d..930b06d2ea 100644 --- a/packages/router-utils/src/compiler/cache.ts +++ b/packages/router-utils/src/compiler/cache.ts @@ -4,15 +4,22 @@ * validation, and the dependents index. Only plain data is retained. */ import { identify, planKeyString } from './identity' +import { ownEntry } from './strings' import { approxBytes, cacheDisabled } from './stats' import type { OutputId } from './rewrite' import type { PlanKey } from './identity' import type { EmitPlan } from './plan' import type { TargetFacts } from './facts' +import type { ModuleSummary } from './summary' import type { Diagnostic } from './diagnostics' export type DependencyFingerprint = + /** The whole summary (a listing of the module's exports, or a module without one: null). */ | { kind: 'summary'; canonicalId: string; digest: string | null } + /** One export as a lookup read it (`ModuleSummary.exportKeys`; null: the module exports no such name). */ + | { kind: 'export'; canonicalId: string; name: string; key: string | null } + /** The `export *` list, read by a lookup of a name the module does not export itself. */ + | { kind: 'stars'; canonicalId: string; stars: ReadonlyArray } | { kind: 'target-facts'; canonicalId: string; digest: string } /** Only the target's environment marker (a consumer that reads nothing else). */ | { @@ -33,6 +40,10 @@ function fingerprintId(fp: DependencyFingerprint): string { switch (fp.kind) { case 'summary': return `summary:${fp.canonicalId}` + case 'export': + return `export:${fp.canonicalId}\u0000${fp.name}` + case 'stars': + return `stars:${fp.canonicalId}` case 'target-facts': return `target:${fp.canonicalId}` case 'target-marker': @@ -48,6 +59,8 @@ function fingerprintId(fp: DependencyFingerprint): string { export function fingerprintPath(fp: DependencyFingerprint): string | null { switch (fp.kind) { case 'summary': + case 'export': + case 'stars': case 'target-facts': case 'target-marker': return identify(fp.canonicalId).path @@ -85,7 +98,7 @@ export interface PersistedPlan { /** The current values fingerprints are validated against. */ export interface FingerprintSource { - summaryDigest: (canonicalId: string) => Promise + summary: (canonicalId: string) => Promise targetDigest: (canonicalId: string) => Promise targetMarker: (canonicalId: string) => Promise routeRegistryDigest: (path: string) => string | null @@ -99,7 +112,22 @@ export async function fingerprintCurrent( ): Promise { switch (fp.kind) { case 'summary': - return (await src.summaryDigest(fp.canonicalId)) === fp.digest + return ((await src.summary(fp.canonicalId))?.digest ?? null) === fp.digest + case 'export': { + const summary = await src.summary(fp.canonicalId) + return ( + summary !== null && + (ownEntry(summary.exportKeys, fp.name) ?? null) === fp.key + ) + } + case 'stars': { + const stars = (await src.summary(fp.canonicalId))?.stars + return ( + stars !== undefined && + stars.length === fp.stars.length && + stars.every((s, i) => s === fp.stars[i]) + ) + } case 'target-facts': return (await src.targetDigest(fp.canonicalId)) === fp.digest case 'target-marker': diff --git a/packages/router-utils/src/compiler/facts.ts b/packages/router-utils/src/compiler/facts.ts index 14f3818d55..b8e4bf033c 100644 --- a/packages/router-utils/src/compiler/facts.ts +++ b/packages/router-utils/src/compiler/facts.ts @@ -15,7 +15,7 @@ import { digestOf, identify, isCommonJsPath } from './identity' import { parseModule } from './source' import { DEFAULT_MARKERS, ModuleAnalysis } from './analysis' -import { buildSummary } from './summary' +import { buildSummary, exportKeysOf } from './summary' import { ownEntry } from './strings' import { EMPTY_RECOGNIZER, isKnownSpecifier } from './values' import { approxBytes, cacheDisabled } from './stats' @@ -365,11 +365,6 @@ export class RawFactsCache { return false } - async digestOf(canonicalId: string, env: string): Promise { - const f = await this.get(canonicalId, env) - return f.summary?.digest ?? null - } - /** The facts J6 target facts are taken from (`get`, or a fresh read when the target-facts knob is off). */ async getTarget(canonicalId: string, env: string): Promise { if (this.noTargets && !this.isKnownSpecifier(canonicalId)) { @@ -456,7 +451,12 @@ export class RawFactsCache { codeEffects: { client: false, server: false }, } return { - summary: { exports: exportFacts, stars: [], digest }, + summary: { + exports: exportFacts, + stars: [], + exportKeys: exportKeysOf(exportFacts), + digest, + }, targetFacts: { ...tf, digest: digestOf(tf) }, } } diff --git a/packages/router-utils/src/compiler/host.ts b/packages/router-utils/src/compiler/host.ts index 108b8837fd..72615682d2 100644 --- a/packages/router-utils/src/compiler/host.ts +++ b/packages/router-utils/src/compiler/host.ts @@ -433,6 +433,8 @@ export function dependencyPaths( for (const fp of dependencies) { if ( fp.kind === 'summary' || + fp.kind === 'export' || + fp.kind === 'stars' || fp.kind === 'target-facts' || fp.kind === 'target-marker' ) { @@ -550,7 +552,7 @@ export function fingerprintSourceFor( env: string, ): FingerprintSource { return { - summaryDigest: (id) => caches.rawFacts.digestOf(id, env), + summary: async (id) => (await caches.rawFacts.get(id, env)).summary, targetDigest: (id) => caches.rawFacts.targetDigestOf(id, env), targetMarker: (id) => caches.rawFacts.marker(id, env), routeRegistryDigest: (path) => host.routes?.digestFor(path) ?? null, diff --git a/packages/router-utils/src/compiler/pipeline.ts b/packages/router-utils/src/compiler/pipeline.ts index 4566a713fc..bad8ec8edd 100644 --- a/packages/router-utils/src/compiler/pipeline.ts +++ b/packages/router-utils/src/compiler/pipeline.ts @@ -29,6 +29,7 @@ import { resolveForAnalysis, } from './host' import { registerCompilerStats } from './stats' +import { ownEntry } from './strings' import { VERIFY_OUTPUTS, verifyPlan } from './verify' import type { CacheEntry, Settled } from './cache' import type { Diagnostic } from './diagnostics' @@ -480,6 +481,21 @@ async function runAttempt( }) return facts.summary } + // a lookup depends on the export it reads, not on the module's others + const exportOf = async (canonicalId: string, name: string) => { + const { summary } = await host.rawFacts.get(canonicalId, env.name) + ledger.record( + summary === null + ? { kind: 'summary', canonicalId, digest: null } + : { + kind: 'export', + canonicalId, + name, + key: ownEntry(summary.exportKeys, name) ?? null, + }, + ) + return summary + } const targetFactsOf = async (canonicalId: string) => { const facts = await host.rawFacts.getTarget(canonicalId, env.name) ledger.record({ @@ -496,6 +512,21 @@ async function runAttempt( } const resolver = new ExportResolver({ summaryOf, + exportOf, + starsOf: (canonicalId, summary) => + ledger.record({ + kind: 'stars', + canonicalId, + // a copy: the plan keeps it, the cache may drop its summary + stars: [...summary.stars], + }), + readableOf: async (canonicalId) => { + const { summary } = await host.rawFacts.get(canonicalId, env.name) + if (summary === null) { + ledger.record({ kind: 'summary', canonicalId, digest: null }) + } + return summary !== null + }, resolveSpecifier: (spec, importer) => resolveFrom(spec, importer), }) const withdrawn = new Set() diff --git a/packages/router-utils/src/compiler/resolve.ts b/packages/router-utils/src/compiler/resolve.ts index 56e287703e..8909579b78 100644 --- a/packages/router-utils/src/compiler/resolve.ts +++ b/packages/router-utils/src/compiler/resolve.ts @@ -52,8 +52,14 @@ type ResolveOutcome = | { k: 'cycleUnknown' } interface ResolverDeps { - /** The raw-domain summary of a canonical id (null when the module cannot be read). Records the dependency. */ + /** The raw-domain summary of a canonical id (null when the module cannot be read). Records the whole summary as a dependency. */ summaryOf: (canonicalId: string) => Promise + /** The same summary, recording only its export `name` as read (the whole summary when the module has none). */ + exportOf: (canonicalId: string, name: string) => Promise + /** Records the `export *` list of a module's summary as read. */ + starsOf: (canonicalId: string, summary: ModuleSummary) => void + /** Whether the module has a summary, recording only a missing one (the whole null summary) as read. */ + readableOf: (canonicalId: string) => Promise /** Resolves a specifier from an importer to a canonical id (null when unresolvable/external). */ resolveSpecifier: ( specifier: string, @@ -75,6 +81,15 @@ export class ExportResolver { return this.deps.summaryOf(canonicalId) } + /** + * Whether the module has a summary (an unreadable or opaque one exports + * nothing to look up). A readable module's answer depends on nothing but + * what the caller then reads of it, which records itself. + */ + readable(canonicalId: string): Promise { + return this.deps.readableOf(canonicalId) + } + /** * A resolver over the same summaries and resolutions that enters only the * modules `enters` accepts: a re-export of another module stays a symbolic @@ -82,9 +97,9 @@ export class ExportResolver { * apart from this resolver's. */ within(enters: (canonicalId: string) => boolean): ExportResolver { - const { summaryOf, resolveSpecifier } = this.deps + const { resolveSpecifier } = this.deps return new ExportResolver({ - summaryOf, + ...this.deps, resolveSpecifier: async (specifier, importer) => { const target = await resolveSpecifier(specifier, importer) return target !== null && enters(target) ? target : null @@ -108,7 +123,7 @@ export class ExportResolver { if (!inner) { return { k: 'cycleUnknown' } } - const summary = await this.deps.summaryOf(canonicalId) + const summary = await this.deps.exportOf(canonicalId, name) if (!summary) { return { k: 'absent' } } @@ -154,6 +169,7 @@ export class ExportResolver { } let found: Extract | null = null let ambiguous = false + this.deps.starsOf(canonicalId, summary) for (const star of summary.stars) { const target = await this.deps.resolveSpecifier(star, canonicalId) if (target === null) { diff --git a/packages/router-utils/src/compiler/summary.ts b/packages/router-utils/src/compiler/summary.ts index 8ecd438c9f..443ffb2ada 100644 --- a/packages/router-utils/src/compiler/summary.ts +++ b/packages/router-utils/src/compiler/summary.ts @@ -16,10 +16,29 @@ type ExportFact = export interface ModuleSummary { exports: Record stars: Array - /** EXPORT-FACTS DIGEST over {exports (sites stripped), stars, marker}. */ + /** + * Per export, the digest of what an importer reading it observes (the + * fact, sites stripped): an importer depends on the exports it reads + * only, so another export changing leaves its plan current. + */ + exportKeys: Record + /** EXPORT-FACTS DIGEST over {exportKeys, stars, marker}: a reader of the whole summary (a listing of its exports). */ digest: string } +/** The per-export digests of a summary's exports (`ModuleSummary.exportKeys`). */ +export function exportKeysOf( + exports: ModuleSummary['exports'], +): ModuleSummary['exportKeys'] { + const keys: Record = Object.create(null) + for (const [name, f] of Object.entries(exports)) { + keys[name] = digestOf( + f.kind === 'local' ? { kind: 'local', value: stripSites(f.value) } : f, + ) + } + return keys +} + export function buildSummary( analysis: ModuleAnalysis, table: RecognizerTable, @@ -76,19 +95,16 @@ export function buildSummary( break } } + const exportKeys = exportKeysOf(exportFacts) const digest = digestOf({ - exports: Object.fromEntries( - Object.entries(exportFacts).map(([k, f]) => [ - k, - f.kind === 'local' ? { kind: 'local', value: stripSites(f.value) } : f, - ]), - ), + exports: exportKeys, stars, marker: analysis.markers, }) return { exports: exportFacts, stars, + exportKeys, digest, } } diff --git a/packages/router-utils/tests/cache.test.ts b/packages/router-utils/tests/cache.test.ts index a7a821eeca..da85a8428c 100644 --- a/packages/router-utils/tests/cache.test.ts +++ b/packages/router-utils/tests/cache.test.ts @@ -126,11 +126,19 @@ describe('a changed dependency', () => { ) expect(same.dependents).toEqual([]) expect(host.resolveCalls).toEqual([]) - // a change of the export facts: the importer is stale, still without a resolution + // a new export: the importer reads `make` only, and stays current host.write( '/app/shared.ts', - 'export const make = 1\nexport const more = 2\n', + 'export const make = 2\nexport const more = 2\n', ) + const added = await invalidate( + host.caches, + { path: '/app/shared.ts', kind: 'change' }, + host, + ) + expect(added.dependents).toEqual([]) + // a change of the export it reads: the importer is stale, still without a resolution + host.write('/app/shared.ts', "export { make } from './elsewhere'\n") const changed = await invalidate( host.caches, { path: '/app/shared.ts', kind: 'change' }, @@ -316,7 +324,8 @@ describe('plans restored from an earlier process', () => { '/app/page.ts': `import { make } from './helper'\nexport const page = make()\n`, '/app/helper.ts': 'export const make = () => 1\n', } - const edited = 'export const make = () => 1\nexport const more = 2\n' + // the export the page reads changes (an export added beside it would not re-plan the page) + const edited = "export { make } from './elsewhere'\n" /** The persisted plan of `/app/page.ts`, compiled by an earlier process (plain data). */ async function persisted() { diff --git a/packages/router-utils/tests/facts.test.ts b/packages/router-utils/tests/facts.test.ts index a0d9ef0a79..784547d92c 100644 --- a/packages/router-utils/tests/facts.test.ts +++ b/packages/router-utils/tests/facts.test.ts @@ -140,12 +140,8 @@ describe('RawFactsCache', () => { ) expect(cache.stats(false)).toMatchObject({ rawFacts: 1, rawFactsOpaque: 1 }) // a mock of it asks for its target facts: parsed then, and kept; the - // module stays opaque to the summaries (its summary digest never - // changes: no plan that summarised the package is evicted by the question) - const before = await cache.digestOf( - '/app/node_modules/lib/index.js', - 'client', - ) + // module stays opaque to the summaries (its summary stays null: no plan + // that summarised the package is evicted by the question) const target = await cache.getTarget( '/app/node_modules/lib/index.js', 'client', @@ -155,9 +151,6 @@ describe('RawFactsCache', () => { expect( (await cache.get('/app/node_modules/lib/index.js', 'client')).summary, ).toBe(null) - expect( - await cache.digestOf('/app/node_modules/lib/index.js', 'client'), - ).toBe(before) expect( await cache.targetDigestOf('/app/node_modules/lib/index.js', 'client'), ).toBe(target.targetFacts.digest) diff --git a/packages/start-plugin-core/src/compiler/prefetch.ts b/packages/start-plugin-core/src/compiler/prefetch.ts index 9ad8a4efbc..14280db7d6 100644 --- a/packages/start-plugin-core/src/compiler/prefetch.ts +++ b/packages/start-plugin-core/src/compiler/prefetch.ts @@ -564,7 +564,7 @@ export async function prefetchStartValues( ) => { const id = await ctx.resolveFrom(specifier, ctx.identity.canonicalId) // a module without a summary (a package, opaque) exports nothing to follow: every member reads as unknown - if (id !== null && (await ctx.resolver.summary(id)) !== null) { + if (id !== null && (await ctx.resolver.readable(id))) { await followNamespace( specifier, id, diff --git a/packages/start-plugin-core/tests/planners/export-fingerprints.test.ts b/packages/start-plugin-core/tests/planners/export-fingerprints.test.ts new file mode 100644 index 0000000000..2afa003b51 --- /dev/null +++ b/packages/start-plugin-core/tests/planners/export-fingerprints.test.ts @@ -0,0 +1,227 @@ +/** + * An importer's plan depends on the exports it reads, not on every export of + * the module: editing another export (or adding one) leaves it current, and + * editing the one it reads makes it a dependent of the edit. Every step + * compares the importer's output with a fresh session's. + */ +import { describe, expect, it } from 'vitest' +import { invalidate } from '@tanstack/router-utils/compiler' +import { startRecognizer } from '../../src/compiler/recognizer' +import { START_ENV, startEnvPlanner } from '../../src/planners' +import { MemoryHost, clientEnv } from './memory-host' +import type { StartEnvConfig } from '../../src/planners' + +const config = { + configKey: 'cfg', + perPlanner: { + [START_ENV]: { + framework: 'react', + root: '/app', + providerSeparate: false, + idMode: 'dev', + } satisfies StartEnvConfig, + }, +} +const planners = [startEnvPlanner()] +const IMPORT = `import { createServerFn } from '@tanstack/react-start'\n` +const SECRET = 'SECRET_HANDLER_BODY' +/** A client module attaching a handler to `name` imported from `from`: the handler body ships unless `name` is a server-fn builder. */ +const user = (name: string, from: string) => + `import { ${name} } from '${from}'\nexport const fn = ${name}.handler(async () => '${SECRET}')\n` + +function session(files: Record) { + const memory = new MemoryHost(files, { recognizer: startRecognizer() }) + const compile = async (path: string) => + (await memory.compile(path, planners, { env: clientEnv, config }))!.code + /** Edits a file and returns the importers the invalidation re-plans. */ + const edit = async (path: string, text: string) => { + memory.files[path] = text + const res = await invalidate( + memory.caches, + { path, kind: 'change' }, + memory, + ) + return res.dependents.map((k) => k.canonicalId) + } + /** The output a fresh session gives for `path` over the current files. */ + const fresh = async (path: string) => { + const other = new MemoryHost(memory.files, { + recognizer: startRecognizer(), + }) + return (await other.compile(path, planners, { env: clientEnv, config }))! + .code + } + return { memory, compile, edit, fresh } +} + +describe('a dependency on a module is the exports the importer reads', () => { + const LIB = '/app/src/lib.ts' + const USER = '/app/src/user.ts' + const files = { + [LIB]: `${IMPORT}export const factory = createServerFn()\nexport const other = 1\n`, + [USER]: user('factory', './lib'), + } + + it('an added export or an unread export changing re-plans nothing', async () => { + const t = session(files) + expect(await t.compile(USER)).not.toContain(SECRET) + expect( + await t.edit(LIB, `${files[LIB]}export const added = 2\n`), + ).not.toContain(USER) + expect(await t.compile(USER)).toBe(await t.fresh(USER)) + // the unread export becomes a server-fn builder + expect( + await t.edit( + LIB, + `${IMPORT}export const factory = createServerFn()\nexport const other = createServerFn()\n`, + ), + ).not.toContain(USER) + expect(await t.compile(USER)).toBe(await t.fresh(USER)) + }) + + it('the read export changing kind re-plans the importer', async () => { + const t = session(files) + expect(await t.compile(USER)).not.toContain(SECRET) + expect( + await t.edit( + LIB, + `export const factory = (x: any) => x\nexport const other = 1\n`, + ), + ).toContain(USER) + const out = await t.compile(USER) + expect(out).toContain(SECRET) + expect(out).toBe(await t.fresh(USER)) + }) + + it('a name the module did not export appearing re-plans its importer', async () => { + const LATER = '/app/src/later.ts' + const t = session({ ...files, [LATER]: user('later', './lib') }) + expect(await t.compile(LATER)).toContain(SECRET) + expect( + await t.edit(LIB, `${files[LIB]}export const later = createServerFn()\n`), + ).toContain(LATER) + const out = await t.compile(LATER) + expect(out).not.toContain(SECRET) + expect(out).toBe(await t.fresh(LATER)) + }) +}) + +describe('through re-exports', () => { + const A = '/app/src/a.ts' + const B = '/app/src/b.ts' + const STARS = '/app/src/stars.ts' + const NAMED = '/app/src/named.ts' + const VIA_STARS = '/app/src/via-stars.ts' + const VIA_NAMED = '/app/src/via-named.ts' + const files = { + [A]: `${IMPORT}export const factory = createServerFn()\n`, + [B]: `export const unrelated = 1\n`, + [STARS]: `export * from './a'\nexport * from './b'\n`, + [NAMED]: `export { factory } from './a'\nexport const own = 1\n`, + [VIA_STARS]: user('factory', './stars'), + [VIA_NAMED]: user('factory', './named'), + } + + it('another name in a star target re-plans nothing; the same name makes the lookup ambiguous', async () => { + const t = session(files) + expect(await t.compile(VIA_STARS)).not.toContain(SECRET) + expect(await t.edit(B, `${files[B]}export const more = 2\n`)).not.toContain( + VIA_STARS, + ) + expect(await t.compile(VIA_STARS)).toBe(await t.fresh(VIA_STARS)) + expect(await t.edit(B, `${files[B]}export const factory = 1\n`)).toContain( + VIA_STARS, + ) + const out = await t.compile(VIA_STARS) + expect(out).toContain(SECRET) + expect(out).toBe(await t.fresh(VIA_STARS)) + }) + + it('a star added to the barrel re-plans the importers of names it does not export itself', async () => { + const C = '/app/src/c.ts' + const t = session({ ...files, [C]: `export const factory = 1\n` }) + expect(await t.compile(VIA_STARS)).not.toContain(SECRET) + expect( + await t.edit(STARS, `${files[STARS]}export * from './c'\n`), + ).toContain(VIA_STARS) + const out = await t.compile(VIA_STARS) + expect(out).toContain(SECRET) + expect(out).toBe(await t.fresh(VIA_STARS)) + }) + + it('a re-export chain depends on each hop’s read export only', async () => { + const t = session(files) + expect(await t.compile(VIA_NAMED)).not.toContain(SECRET) + expect( + await t.edit(NAMED, `${files[NAMED]}export const own2 = 2\n`), + ).not.toContain(VIA_NAMED) + expect( + await t.edit(A, `${files[A]}export const extra = 2\n`), + ).not.toContain(VIA_NAMED) + expect(await t.compile(VIA_NAMED)).toBe(await t.fresh(VIA_NAMED)) + // the origin of the chain stops being a builder + expect(await t.edit(A, `export const factory = 1\n`)).toContain(VIA_NAMED) + const out = await t.compile(VIA_NAMED) + expect(out).toContain(SECRET) + expect(out).toBe(await t.fresh(VIA_NAMED)) + }) +}) + +describe('a namespace read by member', () => { + const LIB = '/app/src/lib.ts' + const NS = '/app/src/ns.ts' + const CALLS = '/app/src/calls.ts' + const files = { + [LIB]: `${IMPORT}export const factory = createServerFn()\nexport const fin = createServerFn().handler(async () => 1)\n`, + [NS]: `import * as lib from './lib'\nexport const fn = lib.factory.handler(async () => '${SECRET}')\n`, + [CALLS]: `import * as lib from './lib'\nexport const read = () => lib.fin()\n`, + } + + it('depends on the members it reads: an added export re-plans nothing', async () => { + const t = session(files) + expect(await t.compile(NS)).not.toContain(SECRET) + await t.compile(CALLS) + const dependents = await t.edit( + LIB, + `${files[LIB]}export const added = 2\n`, + ) + expect(dependents).not.toContain(NS) + expect(dependents).not.toContain(CALLS) + expect(await t.compile(NS)).toBe(await t.fresh(NS)) + expect(await t.compile(CALLS)).toBe(await t.fresh(CALLS)) + }) + + it('the read member changing kind re-plans the importer', async () => { + const t = session(files) + expect(await t.compile(NS)).not.toContain(SECRET) + expect( + await t.edit( + LIB, + `export const factory = (x: any) => x\nexport const fin = () => 1\n`, + ), + ).toContain(NS) + const out = await t.compile(NS) + expect(out).toContain(SECRET) + expect(out).toBe(await t.fresh(NS)) + }) +}) + +describe('a namespace that escapes the analysis', () => { + it('depends on the whole module: any export change re-plans it', async () => { + const LIB = '/app/src/lib.ts' + const NS = '/app/src/ns.ts' + const t = session({ + [LIB]: `${IMPORT}export const factory = createServerFn()\n`, + [NS]: `import * as lib from './lib'\nexport const all = Object.keys(lib)\n`, + }) + const before = await t.compile(NS) + expect(before).toBe(await t.fresh(NS)) + expect( + await t.edit( + LIB, + `${IMPORT}export const factory = createServerFn()\nexport const added = 2\n`, + ), + ).toContain(NS) + expect(await t.compile(NS)).toBe(await t.fresh(NS)) + }) +}) diff --git a/packages/start-plugin-core/tests/planners/route-registry-prefetch.test.ts b/packages/start-plugin-core/tests/planners/route-registry-prefetch.test.ts index 6174c927ba..e98a5cfb7d 100644 --- a/packages/start-plugin-core/tests/planners/route-registry-prefetch.test.ts +++ b/packages/start-plugin-core/tests/planners/route-registry-prefetch.test.ts @@ -98,7 +98,7 @@ describe('a route file the registry vouches for', () => { d.kind === 'route-registry' ? `registry:${d.path}` : d.kind, ) expect(kinds).toContain(`registry:${OWN}`) - expect(kinds).toContain('summary') + expect(kinds).toContain('export') // the generator reports the own route's constructor as foreign now: the // tree's plan is stale, and its next compile reads the file