Create the request middleware deduplication set only when request
middleware is configured, and pass Start's serialization adapters to the
router without copying them when the router adds none.
Server route handlers and route middleware now receive the router's
decoded pathname, the one used for route matching.
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
* fix(start-plugin-core): preload transitive static imports and fix Rsbuild shared-chunk CSS
Route preloads read a chunk's `imports` as a complete list, which only
holds when the bundler hoists transitive imports. Walk the static import
graph instead, and derive Rsbuild chunk imports from the module graph
rather than chunk-group siblings so shared chunks stop attaching
unrelated route CSS to the SSR response.
Fixes#8415Fixes#8511
* refactor(start-plugin-core): share one static import walk for preloads and CSS
The manifest builder walked the static import graph twice, once breadth-first
for preloads and once recursively for stylesheets. A single memoized
depth-first walk now records discovered file names for preloads and chunks in
post-order for stylesheets, which also keeps every chunk in an import cycle
seeing the whole cycle instead of a partially cached result.
The Rsbuild adapter resolved static dependency chunks again for every CSS-only
chunk reached from each importer; the resolution is now memoized per chunk.
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
* docs(start-plugin-core): drop Rollup from the imports contract comments
Rollup is no longer a supported client bundler, so the `imports` contract is
described in terms of the direct-imports-only lists Rolldown and Rsbuild emit.
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
---------
Co-authored-by: Manuel Schiller <6340397+schiller-manuel@users.noreply.github.com>
Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
* refactor(start)!: remove the deprecated inputValidator
createServerFn().inputValidator() and createMiddleware().inputValidator()
were deprecated aliases of validator(). Remove both, the inputValidator
option the builders set, and the compiler's deprecation warnings, so
validator() is the only way to declare a validator. Server functions now
store their validator under the key middleware reads.
The compiler test of diagnostic locations across line terminators now
checks the code frame of the destructuring diagnostic instead of the
removed warning.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* docs(agents): do not test that a removed API is gone
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
The sitemap writer emitted image:* and news:* elements, but <urlset> only
declared the default sitemap namespace and xmlns:xhtml. xmlbuilder2
serialized those elements with xmlns="" and an undeclared prefix, so
sitemaps with images or news were not namespace-well-formed XML. Declare
xmlns:image and xmlns:news on <urlset>.
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
* fix(start-plugin-core): keep prerender credentials out of public pages.json
pages.json and sitemap.xml are now built from schema-validated public page
fields, so prerender headers and extra data returned by prerender.onSuccess
are stripped from the published files. Invalid sitemap metadata returned by
prerender.onSuccess now fails the build with an error naming the page and
the offending field.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* docs(changeset): describe previous onSuccess sitemap behavior accurately
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
* fix(router-generator): don't scaffold over a route file mid in-place save
An in-place save truncates the file and then writes it. If the generator
reads the route file in between, it sees empty content and scaffolds a
template. Its mtime guard before renaming the template into place does not
catch the completed save, because the truncation and the write usually share
one mtime tick on Linux, so the user's content was replaced by the template.
Route file writes now also confirm the file still has the content the
generator read before replacing it.
This was the main cause of flaky tanstack-react-start-e2e-hmr runs, where SSR
rendered `Hello "/route"!` after the test restored a route file.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* fix(router-generator): check for concurrent saves right before the rename
safeFileWrite compared the target's mtime and content before preparing the
temporary file's mode and owner, so a save completing during those steps was
still replaced. Run the check last, immediately before the rename.
The regression test now also completes the save during the temporary file
stat, and keeps the generator's tmpDir inside the test directory so the
rename never crosses filesystems (EXDEV on CI).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* test(router-generator): match generator paths on Windows in concurrent save test
The generator reads route files through forward-slash paths, also on Windows,
so compare resolved paths when injecting the concurrent save.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* perf(router-generator): only read files whose content is compared
The final concurrent-change check before the rename read the whole target
file even for the route tree, whose content is never compared. Stat it
instead, as before, and read only route files.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
* fix(start): preserve dev SSR CSS order
fixes#7794
* add e2e tests for solid and vue, handle vue style urls
* test(start): cover bundled dev styles and SSR reload lifecycle
* fix(start): use completed bundled graph for dev SSR styles
* fix(start): preserve import reachability across bundled dev variants
* test(start): cover layered inline CSS without build observers
* test(start): wait for bundled HMR route registration
* test(start): await HMR readiness in both Vite modes
* test(start): trace initial bundled HMR update in CI
* test(start): trace native bundled HMR watcher in CI
* test(start): inspect initial native watch registrations
* fix(start): support the latest bundled dev toolchain
This reverts commit ff9f753c09.
#8643 introduced a React hydration mismatch for `ssr: false` and
`ssr: 'data-only'` routes without a pending component: the client load can
commit before React hydrates the route's Suspense boundary, which then
hydrates the route component against the server's pending UI. Revert while a
proper fix is worked on.
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
* fix: keep server-rendered pending UI of no-SSR routes through hydration
Fixes#8640. The server rendered a no-SSR match's pending UI in a
ClientOnly fallback, while the hydrating client renders the presented
pending match through MatchInner. After hydration the switch replaced
(React: hid and duplicated) the server node. Render the server pending UI
through the same MatchInner pending path and drop the ClientOnly wrapper.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* test: cover terminal no-SSR boundaries through hydration
Add error, notFound and URL not-found cases for `ssr: 'data-only'` and
`ssr: false` boundaries (plus a terminal child below a data-only boundary)
in React, Solid and Vue. Each case asserts the server payload, that the
server skeleton is the only one and is held for `pendingMinMs`, and that no
hydration mismatch is reported. The hold check catches mismatches that React
and Solid error boundaries replace silently.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
* fix(router-core): avoid null bytes in dehydrated SSR match ids
dehydrateSsrMatchId replaced "/" with U+0000 so dehydrated ids would not
look like crawlable URLs (#6739). U+0000 is forbidden in the HTML input
stream though, so the inlined hydration payload tripped a
control-character-in-input-stream parse error and failed markup
validation. Encode with U+FFFD instead, which is valid in HTML and which
hydrateSsrMatchId already decodes back to "/".
* test(router-core): cover legacy null-byte decode in hydrateSsrMatchId
The codec keeps the U+0000 -> "/" decode branch so SSR payloads from a deploy before the U+FFFD switch still hydrate. That branch was the one path the suite didn't exercise, so add a test for it.
* fix(router-core): compare SSR match ids in encoded form
Encode slashes as U+FFFD with no further escaping, and have the client
encode its own match id instead of decoding the server's. Payload and
client always ship from the same build, so the legacy null-byte decode
and the reversible escape scheme are no longer needed.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* perf(router-core): keep dehydrated SSR match ids one-byte
A U+FFFD delimiter made V8 widen the encoded ids, and every HTML string
concatenated with them, to two-byte strings, slowing Solid SSR
serialization by ~5%. Use ASCII `|` instead.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* fix(router-core): delimit dehydrated SSR match ids with '#'
`|` is a valid static route character, so `/a/b` and `/a|b` encoded to
the same id. A decoded pathname keeps `%23` encoded and params encode
`#`, so a matched id cannot get a '#' from the URL. Seroval emits it
unescaped and it keeps the HTML one-byte.
Tighten the regression test to reject any non-whitespace control
character and any char above U+00FF in the inlined hydration HTML.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
---------
Co-authored-by: Flo <me@florianpellet.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
* perf(solid-router): let mergeProps memoize the Link's own props
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
* test(solid-router): pin how Link element props, state props and handlers reach the anchor
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
* ci: retrigger benchmarks against refreshed main baselines
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
* test(benchmarks): add departing and retained Link navigation cases
Add lane-* cases to the React Link performance harness, with per-navigation
sync, onLoad and total timings in the paired runner.
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
* perf(react-router): share one location subscription per route's Links
Links subscribe to a scope owned by their match context instead of each
subscribing to the location store. A scope skips a location publication
whose navigation leaves its route, so Links that are about to unmount do
no work. Clicks and preloads resolve from the location a Link displays,
and mask builds use the same source location as their destination.
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
* test(benchmarks): add Solid departing and retained Link navigation harness
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* perf(solid-router): hold the location of Links in a departing match
Each Match owns one memo that keeps its Links' source location when the
publishing navigation leaves the route, so those Links do no work.
Clicks and preloads resolve from that source.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* perf(react-router): trim the Link scope's bundle cost
Key each router's link scopes by route id instead of carrying them in a
`[routeId, linkScope]` match context tuple. `matchContext` provides the
route id again, so `Match`, `Outlet`, `useMatch` and `useParentMatches` /
`useChildMatches` match main, and the outside-every-match holder becomes
the `undefined` key of the same registry. A scope without links still
releases its location, so keeping one per route id holds none.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* test(benchmarks): add Vue departing and retained Link navigation harness
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* perf(vue-router): hold the location of Links in a departing match
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* test(benchmarks): add a real-browser Link INP harness
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* perf(solid-router): gate departing Links in their own location memo
Drop the per-Match memo and the third match-context slot. Each Link reads
its route id once at setup and, while the publishing navigation leaves
that route, keeps its previous location in the memo it already owns.
Links mounting in an already-departing route read the pending location.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* test(benchmarks): add Vue to the real-browser Link INP harness
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* fix(solid-router): build Link navigations from the live location state
The Link location memo deduplicated by href, so a same-href navigation that only changed history state left clicks and preloads building from the previous location's state.
Compare by identity instead; downstream href and active memos still compare by value, so unchanged Links do not touch the DOM.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* perf(react-router): drop the Link scope's reentrant publication re-check
A listener that publishes a new location while a route's Links derive is not a
supported use case, so the scope no longer re-reads the store after notifying.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* perf(react-router, router-core): follow-up Link improvements (#8607)
* perf(router-core): cache location-independent masked destinations
A mask that reads the current location already marks the result as
source-dependent through the shared usedCurrent flag, and route masks
belong to the route tree and options whose updates replace the cache.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* perf(react-router): hydrate hash-sensitive Links through the scope's server snapshot
The Link's location subscription already has a server-snapshot slot.
Reporting an active hash-sensitive Link as inactive there replaces the
per-Link useHydrated subscription with identical hydration output.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* fix(react-router): follow href and reloadDocument changes of a mounted Link
The destination memo did not depend on href, so a Link whose href alone
changed kept displaying, preloading and navigating to the old target.
Clicks also navigated with the memo's copy of the options, so a changed
reloadDocument only applied once another destination prop changed.
Navigate with the current options and the displayed source location.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* perf(react-router): hold a Link's intent preload timer on its own ref
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* perf(history): avoid copying navigation arguments when checking blockers
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* test(benchmarks): opt-in intent preloading for the Link lane cases
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* chore: changeset
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
* perf(solid-router, vue-router): follow-up Link improvements (#8609)
* test(benchmarks): measure Solid and Vue Link lanes with intent preloading
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* perf(solid-router): reuse a Link-owned destination so fixed Links hit the location cache
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* perf(solid-router): pass navigation controls through the Link-owned options
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* test(solid-router): cover Link clicks after a state-only navigation
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* perf(solid-router): read Link options directly with a single splitProps
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* perf(solid-router): keep the Link preload timer in a closure
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* perf(solid-router): let the Link observer read the preload mode directly
The internal useIntersectionObserver no longer returns an unused accessor and
takes the preload mode instead of two predicates (its unit test is updated).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* perf(solid-router): create the Link hydration signal only for SSR routers
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* perf(solid-router): let element insertion track Link children without a memo
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* fix(solid-router): call a Link's ref once per element
The ref no longer comes from the props memo, so href/active changes do not
re-run the element's ref effect. Drops the mergeRefs import.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* perf(solid-router): derive a Link's href and active state in one computation
The destination build, href, external/blocked classification and active state
share one memo whose unchanged result keeps its identity, so a navigation that
leaves a Link as it was notifies nothing downstream. Presentation props only
rerun the props memo. The server derives the same values once, without memos.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* test(benchmarks): use the t quantile for the lane comparison's round count
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* perf(solid-router): split a Link's props once
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* perf(vue-router): reuse a Link-owned destination so fixed Links hit the location cache
Navigation controls travel on the same object, so clicks no longer re-list them.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* perf(vue-router): pick a Link's element props with one shared key set
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* perf(vue-router): derive a Link's href and active state in one computed
The preload effects read a location-independent mode, so a navigation no
longer queues them for every Link. A Link whose destination updater navigates
while it derives derives again for the newer location.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* perf(vue-router): keep the Link preload timer in a closure
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* perf(vue-router): drop the unused IntersectionObserver ref per Link
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* perf(vue-router): return plain empty Link props without a router
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* perf(vue-router): render server Links without reactive wrappers
The server returns shallow refs and reads Link props directly, without the
attrs snapshot, its update hook, the props computed or a template ref.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* perf(vue-router): drop the deferred re-derivation for updaters that navigate
A search updater that navigates while a Link derives is not a supported use
case; remove the retry that existed only for it, and its test.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* chore: add changeset for the Solid and Vue Link follow-up
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
* chore(benchmarks): remove the real-browser Link INP harness
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* fix(solid-router, vue-router): rebuild masks whose options are stores
Router core now reuses masked locations built from the same options object
when the mask does not read the current location. Solid and Vue Links keep
one destination object while their navigation options keep their identity,
and only a store/reactive option value forced a fresh object per location.
A plain mask object holding a store (e.g. `mask={{ to, params: store }}`)
therefore kept the mask built from the store's first value. The mask's own
values are destination options too, so check them for stores as well.
React has no in-place reactive values: a changed mask prop changes identity
and rebuilds. Add the equivalent React coverage for prop and inherited masks.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* chore(benchmarks): remove the ad-hoc Link lane harnesses
The link-churn scenario covers this work in CodSpeed. Removes the Solid and
Vue lane harnesses and restores link-performance to its main content.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* style: name tuple indexes in Link code
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* refactor(react-router): stop treating _fromLocation as a Link prop
`_fromLocation` is an internal router option, not a Link prop: the Link
always builds from its own scope's location. It stays among the stripped
router option keys so code that still passes it does not leak an attribute
to the element.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* refactor(solid-router): stop treating _fromLocation as a Link prop
`_fromLocation` is an internal router option, not a Link prop: the Link
always builds from the location its match presents.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* refactor(vue-router): stop treating _fromLocation as a Link prop
`_fromLocation` is an internal router option, not a Link prop: the Link
always builds from the location its match presents.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* refactor(react-router): drop _fromLocation from the Link's option keys
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
---------
Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
* fix(history): keep a leading query or fragment out of parseHref's pathname
parseHref compared the '?' and '#' indexes with '> 0', so an href that
starts with a query or fragment (reachable via hash history '/#?x=1'
or memory entries) kept it in the pathname as well, and the router
location became '?x=1?x=1'.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* perf(history): read hash-history locations with indexOf/slice
Replace split('#').slice(1)/join('#') with one indexOf and two slices
when reading the hash-history location. Characterization tests from
#8351 cover nested fragments, encoded '#', and an empty hash.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* perf(router-core,history): use slice where substring bounds are ordered
Every converted call has non-negative, ordered bounds (fixed offsets,
indexOf results within the same segment, or guarded by a '<' check).
extractParams' affix-stripping calls and the wildcard-tail suffix in
parseSegments keep substring: their bounds can cross.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* perf(router-core,history): drop a duplicated flag and a createHref wrapper
buildLocation's currentMatch now reads the location through current(),
which already marks the build as location-dependent. Browser history
passes its createHref directly; createHistory already wraps it.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
* test(react-router): cover cached link selector reruns
* test(react-router): type configurable trailing slash fixture
* test(react-router): use type import in selector benchmark
* test(react-router): benchmark inactive dynamic destinations
* perf(react-router): reuse link selector results
* perf(react-router): resolve external links once per selector
* perf(react-router): shrink link state classification
* perf(react-router): shrink external link expression
* perf(react-router): shrink link state classification [Self-Healing CI Rerun]
* test(react-router): address link selector review cleanup
---------
Co-authored-by: nx-cloud[bot] <71083854+nx-cloud[bot]@users.noreply.github.com>
* perf(router,start): update Seroval to 1.6.6
* perf(router,start): update Seroval to 1.6.7
* chore: update seroval to 1.6.7
seroval and seroval-plugins were pinned to ^1.6.2 while 1.6.7 is the
current release. The type surface is additive: two new options
(maxBase64Length, compactArrayBufferViews) and an isStream export.
Bundle (gzip): router-only scenarios unchanged; Start client bundles
grow 532-642 bytes from the upstream typed array and base64 handling.
react-start.minimal 98504 -> 99039 (+535).
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
---------
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
* perf(router-core): split replaceEqualDeep into an equality scan and a copy phase
`replaceEqualDeep` compared and copied in one loop. Every entry, also on
the common all-equal path, paid for the copy bookkeeping (`copy ??=`,
`if (copy) copy[key] = n`), an `equal` flag and — for objects — a
`hasOwn.call(prev, key)` lookup, while arrays and objects shared the
same keyed accesses through `array ? i : keys[i]`, so every access site
saw both element and named keys.
The function now runs in two phases:
- Scan: walk `next` up to the first difference, sharing equal children
on the way. Arrays and objects have their own loop, so each keyed
access only ever sees one kind of key and nothing is allocated while
entries keep matching. A key at the same position of both key lists
is proven to be `prev`'s own key; only reordered keys still need
`hasOwn`. When everything matched and the key counts agree, `prev` is
returned.
- Copy: equality is ruled out, so the loop only builds the result. The
scanned prefix is shared from `prev`, the first differing entry keeps
the value the scan already computed, and the rest is resolved without
any equality bookkeeping.
Only an object entry of `prev` can share anything, so the recursion is
guarded by a single `typeof` check; `null` and mismatched types return
`next`'s entry through the entry checks. `isPlainArray` is no longer
used here: the array check reuses the `Object.keys` result that the
scan needs anyway. Semantics are unchanged: pass-through for
non-enumerable keys and for symbol keys on `next`, null-prototype
copies, the depth limit and the SSR early return all stay as they were,
and the tests pass against both implementations.
Bundle size (`benchmark:bundle-size`, gzip): react-router.minimal -1 B,
react-router.full -18 B, all 18 scenarios net -110 B (13 down, 5 up,
max +20 B on react-start.full for identical code).
Paired runs against the previous version (hz medians of 3 runs,
1000 calls per iteration; the machine was under load, so single-digit
differences are noise):
equal flat search 5.96k -> 6.98k (+17%)
equal nested search 2.47k -> 2.83k (+14%)
equal array of objects 524 -> 579 (+10%)
equal long primitive array (1024) 49 -> 69 (+39%)
long primitive array, last item changed 37 -> 41 (+11%)
wider flat object (64 keys), last changed 218 -> 229 (+5%)
flat search, one changed leaf 5.31k -> 5.59k (+5%)
array of objects, one changed item 483 -> 513 (+6%)
flat search, all leaves changed 5.29k -> 5.35k (+1%)
array of shared objects, one changed 1.61k -> 1.44k (-10%, ±29%)
Entries that change between an object and a primitive now pay one
recursive call instead of an inline four-way type check; guarding both
sides costs more bundle bytes than this branch is worth.
Adds tests for the scan/copy boundary (equal children and next-only
keys after the first difference, reordered keys, object/primitive
transitions, shorter and longer arrays, a change in the last of 1024
entries, the depth limit) and bench cases for the shapes that told the
candidate implementations apart.
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
* fix(router-core): keep sparse arrays with extra keys opaque in replaceEqualDeep
The plain-array check compares `Object.keys(array).length` with
`array.length`. A hole and an extra enumerable key cancel out in that
count, so `Object.assign([1, ,], { extra: 'x' })` was admitted: the
index-based copy dropped `extra` and turned the hole into an explicit
`undefined`, and an index-wise equal `prev` was returned for it. The
same blind spot exists in the exported `isPlainArray`, which the
previous implementation used for this check.
Extra string keys always sort after the index keys, so once the count
matches, `next` is a dense index-only array exactly when its last key
is its last index. That is one string comparison per array instead of
a per-key validation, and it stays inline with the existing count
check. `prev` keeps the count check only: a result is either a copy
built from `next`'s entries or `prev` itself, which the caller already
holds.
Symbol keys on arrays stay admitted, as before this stack: checking
them costs an `Object.getOwnPropertySymbols` call per array pair, which
measured ~8% on the equal nested search shape (a record holding a
four-element array), and `react-router.minimal` +3 B on top of the
+13 B gzip of this fix.
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
---------
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Every object pair `replaceEqualDeep` visited paid for three native key
lookups per side: `Object.keys`, `Object.getOwnPropertyNames` (to detect
non-enumerable props) and `Object.getOwnPropertySymbols`. Measured on a
4-key literal the first two cost 7.6 ns and 10 ns, the symbol lookup
34 ns — 31 ns even on `{}` — so two thirds of the enumeration cost went
into a key type that router data never carries. (`Reflect.ownKeys` as a
single replacement call was tried and is 100 ns.)
Symbol keys and non-enumerable keys still have to be handled correctly:
Apollo's `preloadQuery` refs carry symbol keys and broke under
`defaultStructuralSharing` when copies dropped them (#4237). Instead of
comparing and copying such objects key by key, they are now opaque: an
object with non-enumerable own keys on either side, or symbol keys on
`next`, makes `next` pass through untouched. That keeps both guarantees
that matter — no partial copy, no stale `prev` returned for it — and only
gives up structural sharing for those objects.
`prev` is not scanned for symbols on purpose. It is normally an earlier
`next`, so a symbol-carrying `prev` meets a symbol-carrying `next` and the
`next` check fires; a symbol-carrying `prev` with a symbol-free, otherwise
equal `next` returns `prev` (covered by a test). Plain objects are now
compared and copied by `Object.keys` alone, and `getEnumerableOwnKeys`
is gone.
Paired runs against the previous version (hz, 1000 calls per iteration):
equal empty objects 14.8k -> 18.3k (+24%)
equal empty null-proto objects 5.1k -> 6.3k (+24%)
equal flat search 7.3k -> 8.2k (+12%)
flat, one changed leaf 6.1k -> 6.9k (+12%)
equal nested search 3.0k -> 3.1k (+4%)
nested, sharing subtrees 2.6k -> 2.7k (+7%)
equal array of objects 609 -> 729 (+20%)
array, one changed item 551 -> 640 (+16%)
wide (12 keys) changed, null-proto 1.8k -> 2.0k (+9%)
Tests now document the pass-through contract for symbol-keyed objects,
including the deliberate `prev`-only asymmetry.
* perf(router-core): check plain objects by constructor
`isPlainObject` gates every recursion step of `replaceEqualDeep` and
`deepEqual`, so it runs at least twice per object pair, on every nested
level, on every navigation and Link build. The previous implementation
(copied from `is-plain-object`) called `Object.prototype.toString` on the
value and again on its constructor's prototype, plus a `hasOwnProperty`
lookup: up to four `toString` dispatches per compared pair, most of them
spent confirming that `{}` is a plain object.
The check is now a single expression:
!!o && typeof o === 'object' && (o.constructor ?? Object) === Object
Object literals, `JSON.parse` output and `Object.create(literal)` inherit
`Object` as their constructor; `Object.create(null)` objects (the router's
search and params objects) have none, which `?? Object` accepts. Class
instances, arrays, `Map`, `Date`, functions and primitives fail it, as
before. The only accept-set differences are objects from another realm
(an iframe's `Object` is not `===` ours) and objects with a custom
`Symbol.toStringTag`; neither occurs in router state.
Paired runs against the previous version (hz, 1000 calls per iteration):
deepEqual equal empty objects 25.6k -> 59.4k (+132%)
deepEqual nested, one changed leaf 11.3k -> 22.8k (+102%)
deepEqual equal flat (partial) 23.0k -> 39.7k (+73%)
replaceEqualDeep equal empty objects 10.6k -> 14.9k (+40%)
replaceEqualDeep equal array of objs 489 -> 604 (+24%)
replaceEqualDeep equal nested 2.4k -> 2.8k (+19%)
replaceEqualDeep equal flat search 6.0k -> 7.0k (+17%)
Adds an accept/reject table for `isPlainObject` and checks that class
instances stay opaque to structural sharing while null-prototype and
literal objects compare as equal.
* fix(router-core): keep records with a constructor key plain
`?constructor=foo` decodes to an own `constructor` data key on the
null-prototype search record, and `(o.constructor ?? Object) === Object`
read that key. Such records (and the `{ ...search }` copies of them) were
classified as non-plain, so `replaceEqualDeep` handed back `next` without
sharing and `deepEqual` reported them unequal.
Keep the constructor comparison as the fast accept: it is an inline-cache
load for literals and null-prototype records and is what the PR's speedup
comes from. When `constructor` is anything else, consult the actual
prototype instead of rejecting: `null` or one whose `constructor` is
`Object` means a record, anything else a class instance. The prototype
lookup is a builtin call (~6ns in megamorphic optimized code), so running
it unconditionally would return most of the gain: median hz over 3
rotated rounds, `replaceEqualDeep` equal empty 10.9k -> 8.6k (-21%),
equal array of objects 470 -> 386 (-18%), `deepEqual` equal empty
58.0k -> 35.9k (-38%). With the fallback only on the mismatch path the
hot cases stay within noise of the shortcut and the constructor-key
cases now do the sharing work at the same cost as other null-prototype
records. `react-router.minimal` gzip is +15 B against the shortcut and
still 44 B below the `toString` implementation.
Benchmarks the predicate directly (literal, null-prototype record, record
with a constructor key, class instance) and sharing of a search record
that carries a constructor key. Tests both record shapes and parser
output, all `constructor` value types, and that a class instance with an
own `constructor` key stays opaque.
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
---------
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
`replaceEqualDeep` runs on every navigation and Link build: search,
params, state and loader data all go through it, and in the common case
`next` turns out to be deeply equal to `prev`. Until now the function
still allocated the result object (or array) up front and filled it key
by key while comparing, only to throw it away and return `prev`.
The copy is now created at the first difference. Everything compared
before that point is known to be equal and is taken from `prev` in one
pass (`copyItems`), so unchanged subtrees are shared exactly as before.
When nothing differs, nothing is allocated; when only the key sets
differ, the copy is built after the loop.
Smaller changes in the same function:
- deep equality is a single `equal` flag instead of a matched-key count
compared against the sizes afterwards; once unequal, the `hasOwn`
check for keys that only `next` has is skipped
- `nullReplaceEqualDeep` passes a boolean instead of an object factory,
so the plain variant no longer evaluates a default `() => ({})` per
call and the copy site has no indirect call
- an overload signature keeps the generic return type without the
`_next` alias in the emitted code
- `getEnumerableOwnKeys` loops over `getOwnPropertySymbols` directly;
an empty loop needs no early return
`tests/replace-equal-deep.bench.ts` was added first, with the shapes the
router feeds these helpers. Paired runs against the previous version
(hz, 1000 calls per iteration):
equal empty objects 10.0k -> 10.6k (+6%)
equal flat search 5.3k -> 5.9k (+12%)
equal nested search 2.2k -> 2.4k (+13%)
equal array of objects 445 -> 485 (+9%)
flat, one changed leaf 5.4k -> 5.2k (-3%)
wide (12 keys) changed 2.4k -> 2.2k (-11%)
The equal paths win and allocate nothing; the copy paths pay for the
extra call and the per-key `copy` check.