Skip to content

Commit b3f999b

Browse files
committed
docs(router): location state is versioned by the app version; the version option is gone (#994)
Changelog: a Breaking entry for the implicit version (what is dropped, when, and that there is nothing to configure), validate as its own Added entry, and the clearOnReload entry without the version option. The hooks and testing skill pages, docs/testing.md and the internal feature maps drop the option and describe the per-entry record and why the comparison uses the version met at document load.
1 parent b27247e commit b3f999b

12 files changed

Lines changed: 175 additions & 162 deletions

File tree

‎packages/rangojs-router/CHANGELOG.md‎

Lines changed: 66 additions & 45 deletions
Original file line numberDiff line numberDiff line change
@@ -2,64 +2,81 @@
22

33
## Unreleased
44

5-
### Added: `createLocationState({ version, validate })` reads state written by another deploy as no state ([#1020](https://github.com/rangojs/rango/pull/1020))
5+
### Breaking: location state written by another app version reads as no state ([#1020](https://github.com/rangojs/rango/pull/1020))
66

7-
A location state key is the file path plus the export name, so it is the same
8-
in every deploy, and a history entry outlives a deploy: a tab left open across
9-
a release keeps its `history.state` through reloads and back/forward. The read
10-
was an unchecked cast, so after a release that changed a state's shape the new
7+
A history entry outlives a deploy: a tab left open across a release keeps its
8+
`history.state` through reloads and back/forward. A location state key is the
9+
file path plus the export name, so it is the same in every deploy, and the read
10+
was an unchecked cast. After a release that changed a state's shape, the new
1111
code got the old value typed as the new one (#994).
1212

13-
Two options make such a value read as `undefined`, which is what a reader
14-
already handles for "no state":
13+
Location state is now versioned by the app version, the one the router already
14+
uses to reload a client that is behind the server. Every history entry records
15+
the version its location state was written under, and a read returns only
16+
state recorded under the version the page was loaded with. This covers all
17+
location state: `createLocationState` definitions (`useLocationState(Def)`,
18+
`Def.read()`, `flash` included), plain state (`<Link state={{ ... }}>` read
19+
with `useLocationState()`), and state the server sets
20+
(`ctx.setLocationState()`, `redirect(url, { state })`).
21+
22+
There is nothing to configure and no version to manage: no option sets it and
23+
no API returns it.
24+
25+
| An entry's location state, read by | Before | After |
26+
| ---------------------------------------------------------------- | ------------------------------- | -------------------------------------- |
27+
| the build that wrote it: navigation, back/forward, refresh | the value | the value (unchanged) |
28+
| a later build, after a refresh or a restored tab | the old value, typed as the new | `undefined` |
29+
| a later build, on back/forward to an entry the older build wrote | the old value, typed as the new | `undefined` |
30+
| any build, when a release older than this one wrote the entry | the value | `undefined` |
31+
| a release older than this one, after a rollback | the value | the value: it does not read the record |
32+
33+
- **This happens on every deploy.** The default app version is generated per
34+
build, so each deploy is another version. State a user had in an open tab (a
35+
filter carried on a link, a flash message not shown yet) is gone after the
36+
deploy, as if the entry never had any. Readers already handle `undefined`.
37+
State that has to outlive a deploy belongs in the URL, a cookie or storage.
38+
- If you set `version` on the router yourself, location state lives as long
39+
as that value does.
40+
- On the first release with this change, every entry written before the
41+
upgrade counts as another version: open tabs lose their location state once.
42+
- Keys and values are stored as before. The record is one extra field on the
43+
entry (`__rsc_lsv`). A write into an entry another version wrote drops that
44+
entry's older location state first; the router's own bookkeeping on the
45+
entry (scroll key, intercept context) is kept.
46+
- In development a server-module edit changes the version (HMR). The running
47+
page keeps its location state; a document load after the edit drops it, as
48+
after a deploy.
49+
- Unit tests need no version: `renderRoute` seeds read back as before, and the
50+
`.locationState` of `runMiddleware`, `runLoaderResult`,
51+
`runInRequestContext` and `renderHandler` is still
52+
`{ [Def.__rsc_ls_key]: value }`.
53+
54+
### Added: `createLocationState({ validate })` checks a stored value on every read ([#1020](https://github.com/rangojs/rango/pull/1020))
55+
56+
For state whose shape you want checked at the read instead of trusted from its
57+
type:
1558

1659
```ts
17-
// A deliberate shape change: bump the number.
18-
export const GridState = createLocationState<GridSnapshot>({ version: 2 });
19-
20-
// Check the value itself on every read.
2160
export const GridState = createLocationState<GridSnapshot>({
2261
validate: (value): value is GridSnapshot => isGridSnapshot(value),
2362
});
2463
```
2564

26-
`version` is part of the slot's key in `history.state`; the value is stored
27-
as-is. With `<key>` for the key the Vite plugin injects:
28-
29-
| Definition | Reads and writes | A read returns |
30-
| --------------- | ---------------- | --------------------------------------------------------------------------------------- |
31-
| no options | `<key>` | the value, unchecked (unchanged) |
32-
| `version: 2` | `<key>~v2` | the value stored under version 2; `undefined` for anything stored under another key |
33-
| `validate` | `<key>` | the value when `validate` returns `true`; `undefined` when it returns `false` or throws |
34-
| both | `<key>~v2` | `validate` runs on what version 2 stored |
35-
| any, empty slot | nothing | `undefined`; `validate` is not called |
36-
37-
- A reader of version 2 never sees what version 1, or the definition before it
38-
had a version, stored: it is under another key. Nothing is decoded and no
39-
stored format exists to get out of date.
40-
- **Rollback is safe.** A release that predates the option, or the previous
41-
release of your app, reads its own key and finds its own state or nothing.
42-
- **What a version bump leaves behind:** the previous version's slot stays in
43-
each history entry that has it, as a key nothing reads, until that entry is
44-
replaced or dropped by the browser.
45-
- Removing `version` is not a reset: the definition reads `<key>` again,
46-
including a value stored before the option was added. To drop state, bump
47-
the version.
65+
| The slot holds | A read returns |
66+
| -------------------------------------------- | ------------------------------------- |
67+
| a value `validate` returns `true` for | the value |
68+
| a value it returns `false` for, or throws on | `undefined` |
69+
| nothing | `undefined`; `validate` is not called |
70+
4871
- A `validate` that throws never fails a render or a navigation. In
4972
development the error is logged once per definition, with its key.
73+
- The key and the stored value do not change, so adding or removing the option
74+
needs no migration.
5075
- The type of `validate` is exported as `LocationStateGuard<TState>` from
5176
`@rangojs/router` and `@rangojs/router/client`. It is unrelated to
5277
`ValidateLocationState<T>`, the existing compile-time serializability check.
5378
`LocationStateOptions` now takes the state type
5479
(`LocationStateOptions<TState>`, default `unknown`).
55-
- `Def.__rsc_ls_key` returns the key with its suffix. In unit tests
56-
`withLocationStateKey(GridState, "GridState")` still names the definition,
57-
the key is then `__rsc_ls_GridState~v2`, and
58-
`{ [GridState.__rsc_ls_key]: value }` is the assertion that holds for any
59-
definition. The helper rejects a name that contains `~`.
60-
61-
Definitions that set none of the options store and read exactly as before:
62-
same key, same value, no added work on a read or a write.
6380

6481
### Added: `createLocationState({ clearOnReload: true })` drops the state when the entry's document is loaded ([#1020](https://github.com/rangojs/rango/pull/1020))
6582

@@ -103,8 +120,8 @@ const products = [
103120
| Later on that page: a reader mounts, or a navigation returns to the entry | state applied | still `undefined` until the next write |
104121
| The page is restored from the back/forward cache | state and DOM kept | unchanged |
105122

106-
- The slot is stored under `<key>~r` (`<key>~v2~r` with a version), value
107-
as-is. When the client starts, before it hydrates, the router removes every
123+
- The slot is stored under `<key>~r` (`<key>` is the key the Vite plugin
124+
injects), value as-is. When the client starts, before it hydrates, the router removes every
108125
`~r` key from the entry. It goes by the key alone, so it does not depend on
109126
a reader being mounted, on where the reader sits (a `<Suspense>` boundary
110127
that hydrates late included), or on the definition's module being loaded.
@@ -121,7 +138,7 @@ const products = [
121138
was stored before, under the plain key, is no longer read and is not
122139
removed. Removing the option moves it back; what was stored under `~r` is
123140
removed at the next document load. A rollback behaves like removing it.
124-
- `version` and `validate` combine with it. `flash` does not:
141+
- `validate` combines with it. `flash` does not:
125142
`createLocationState` throws in development, since flash state is removed at
126143
its first read and the option could only drop a message nobody has seen.
127144
- The `carriedIds` filter in the example works around a known ordering in the
@@ -132,7 +149,11 @@ const products = [
132149
To test it, plain `renderRoute(routes, { locationState })` is the client
133150
navigation and `renderRoute(routes, { hydrate: true, locationState })` is the
134151
document load: hydrate mode removes the seeded slot with the same function the
135-
client start-up calls.
152+
client start-up calls. `Def.__rsc_ls_key` returns the key with its suffix:
153+
`withLocationStateKey(CarriedProducts, "CarriedProducts")` still names the
154+
definition, the key is then `__rsc_ls_CarriedProducts~r`, and
155+
`{ [CarriedProducts.__rsc_ls_key]: value }` is the assertion that holds for
156+
any definition. The helper rejects a name that contains `~`.
136157

137158
Definitions that do not set the option store and read exactly as before, and
138159
the client start-up writes nothing to `history.state` when no key carries the

‎packages/rangojs-router/docs/internal/feature-file-map.md‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -36,8 +36,9 @@ which shares action-id resolution with `runClientRevalidate` through
3636

3737
Location state is owned by
3838
[`browser/react/location-state-shared.ts`](../../src/browser/react/location-state-shared.ts)
39-
(`createLocationState`, its options, the `__rsc_ls_` key prefix and the key
40-
suffixes `version` / `clearOnReload` add; importable from server code) and
39+
(`createLocationState`, its options, the `__rsc_ls_` key prefix, the key
40+
suffix `clearOnReload` adds, and the per-entry app version stamp with its
41+
readers and writers; importable from server code) and
4142
[`browser/react/location-state.ts`](../../src/browser/react/location-state.ts)
4243
(`useLocationState`). How a slot reaches or leaves `history.state` is owned by
4344
[`browser/history-state.ts`](../../src/browser/history-state.ts): navigation

‎packages/rangojs-router/docs/internal/feature-map.md‎

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -560,10 +560,11 @@ Server action execution pipeline, `useAction()` state tracking, action ID extrac
560560

561561
### Location State
562562

563-
- `createLocationState()` -- typed state definitions; each definition exposes `.read()`, `.write()`, and `.delete()` for static (non-reactive) access to its slot in `history.state`. `LocationStateOptions` is one interface, `{ flash?, clearOnReload?, version?, validate? }`; `flash` with `clearOnReload` throws in `createLocationState` outside production (folded away in a production build, like the missing-key check). `LocationStateGuard<TState>` is the type of `validate`, `(value: unknown) => value is TState` (not the compile-time `ValidateLocationState<T>` below). All of it lives in `browser/react/location-state-shared.ts`.
564-
- Storage key. The value is always stored raw; `version` and `clearOnReload` are a suffix on the key the Vite plugin injects: `<key>~v<n>`, `<key>~r`, `<key>~v<n>~r` (`Def.__rsc_ls_key` returns it). Why the key and not a wrapper around the value: slots outlive deploys, and a stored format would have to be understood by every release that ever reads the slot. With the key, a release without the options (a rollback included) and a definition without them read the plain key and never see such a slot; another version reads another key; a definition without options runs the same read and write as before the options existed. Collision-free because an injected key ends in `#<ExportName>` (`vite/plugins/expose-id-utils.ts` `makeStubId`; only identifier exports are keyed) and `~` is not an identifier character, so the first `~` after the last `#` always starts a suffix; `withLocationStateKey` rejects `~` in a name. The prefix and the predicates are `LOCATION_STATE_KEY_PREFIX`, `isLocationStateKey`, `isClearOnReloadLocationStateKey`.
565-
- What a version bump leaves behind: the previous version's slot stays in every history entry that has it, as a key nobody reads, until that entry is replaced or dropped. Writers do not delete sibling versions: it would put new code on the write paths every app runs (`mergeLocationState`, the navigation commit) to reclaim a slot per superseded version, and leaving it means a rollback finds its own state again. Removing `version` reads the plain key again, values from before the option included.
566-
- `validate` wraps `.read()` only when set: an empty slot never reaches it, `false` or a throw reads `undefined`, and a throw is logged once per definition outside production. The hook reads through `.read()`, so a throw cannot escape into render or its popstate / `__rsc_locationstate` listeners.
563+
- `createLocationState()` -- typed state definitions; each definition exposes `.read()`, `.write()`, and `.delete()` for static (non-reactive) access to its slot in `history.state`. `LocationStateOptions` is one interface, `{ flash?, clearOnReload?, validate? }`; `flash` with `clearOnReload` throws in `createLocationState` outside production (folded away in a production build, like the missing-key check). `LocationStateGuard<TState>` is the type of `validate`, `(value: unknown) => value is TState` (not the compile-time `ValidateLocationState<T>` below). All of it lives in `browser/react/location-state-shared.ts`.
564+
- App version. Location state is versioned by the app version, with no option and no API: a history entry records the version its location state (typed slots and plain `state`) was written under in one field, `__rsc_lsv`, and a read returns only state recorded under the version the document loaded with. You will not find a version in a key or a value. Why a stamp on the entry and not a version in each key: the key is injected at build time and written by the server as well, while the version is a runtime value (the handler's `version` can be set by the app); keys that change per deploy would leave a dead slot per deploy in every entry, and plain state has no key to version at all. The stamp is written by the only three writers (`buildHistoryState`, `mergeLocationState` and `Def.write()`, the last two through `addLocationState`), and checked by the only two readers (`Def.read()` and the hook's plain read, through `readableLocationState`). A write into an entry another version wrote drops that entry's location state first, because re-stamping it would make the old state readable again; `idx`, the scroll `key` and the intercept fields are kept. An entry without the stamp counts as another version, so state from a release before the stamp is dropped once; a release before the stamp (a rollback) ignores it and reads values as it always did.
565+
- Which version: the one the document loaded with (`setLocationStateVersion`, called by `initBrowserApp` from the payload's `metadata.version`), not `getAppVersion()`. They differ in development, where an RSC edit bumps the app version inside a running page (`bridge.updateVersion`): comparing against the live version would drop the session's state on every server-module save. With the document-load version an HMR bump keeps it and the next document load drops it, which is what a deploy does. A client without a version (a `renderRoute` tree, which resets it) writes no stamp and reads only unstamped entries, so test seeds and the server primitives' `locationState` need none.
566+
- Storage key. The value is always stored raw; `clearOnReload` is a suffix on the key the Vite plugin injects: `<key>~r` (`Def.__rsc_ls_key` returns it). Why the key and not a wrapper around the value: slots outlive deploys, and a stored format would have to be understood by every release that ever reads the slot. With the key, a release without the option (a rollback included) and a definition without it read the plain key and never see such a slot; a definition without options runs the same read and write as before the option existed. Collision-free because an injected key ends in `#<ExportName>` (`vite/plugins/expose-id-utils.ts` `makeStubId`; only identifier exports are keyed) and `~` is not an identifier character, so the first `~` after the last `#` always starts a suffix; `withLocationStateKey` rejects `~` in a name. The prefix, its predicate and the suffix are `LOCATION_STATE_KEY_PREFIX`, `isLocationStateKey` and `CLEAR_ON_RELOAD_KEY_SUFFIX`.
567+
- `validate` is the last step of `.read()`: an empty slot and a slot another app version wrote never reach it, `false` or a throw reads `undefined`, and a throw is logged once per definition outside production. The hook reads through `.read()`, so a throw cannot escape into render or its popstate / `__rsc_locationstate` listeners. It is three lines in `read` plus the option and `LocationStateGuard`, on purpose: nothing else knows about it. The hook's flash clear goes through `Def.delete()`.
567568
- `clearOnReload` -- the slot does not survive a document load of its entry. `clearLocationStateOnDocumentLoad()` (`browser/history-state.ts`) removes every `~r` key from the current entry, by key alone because at start-up the defining module may not be loaded; `initBrowserApp` (`browser/rsc-router.tsx`) calls it in its synchronous prefix, before the payload is decoded, the store records the entry, or anything hydrates. Nothing is timed per reader: a reader in a late-hydrating boundary, a reader mounted later and a navigation back to the entry all find the slot gone. Server-set state cannot be dropped by it: a document response carries no location state (`rsc/rsc-rendering.ts` attaches it to partial payloads only), and navigation payloads, action payloads and `LoaderRedirect` write after start-up. Client mounts, popstate and `__rsc_locationstate` are unchanged, and a bfcache restore runs none of this. A slot stored before the definition adopted the option is under the plain key: not read, not removed.
568569
- `useLocationState()` -- reactive hook; updates on popstate / `__rsc_locationstate` (does NOT update on static `.write()` / `.delete()`)
569570
- `redirect()` integration with location state

0 commit comments

Comments
 (0)