Skip to content

Commit 97ac52c

Browse files
committed
feat(router): createLocationState can reject an older stored shape
The slot key is the file path and export name, so it survives a deploy that changes the value's shape. A tab that stays open then restores the old value typed as the new one. version stores { v, value } and a missing or different v reads as undefined. validate checks the value on read and a failure reads as undefined too. Closes #994.
1 parent 456ed18 commit 97ac52c

10 files changed

Lines changed: 527 additions & 20 deletions

File tree

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

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -533,7 +533,7 @@ Server action execution pipeline, `useAction()` state tracking, action ID extrac
533533

534534
### Location State
535535

536-
- `createLocationState()` -- typed state definitions; each definition exposes `.read()`, `.write()`, and `.delete()` for static (non-reactive) access to its slot in `history.state`
536+
- `createLocationState()` -- typed state definitions; each definition exposes `.read()`, `.write()`, and `.delete()` for static (non-reactive) access to its slot in `history.state`. `LocationStateOptions` is `{ flash?, version?, validate? }` (`LocationStateValidate<TState>` is `(value: unknown) => value is TState`). `version` stores `{ v, value }` and a missing or different `v` reads as `undefined` (the key is stable across deploys, so an old tab must not see the new shape). `validate` runs on read; `false` reads as `undefined`. Together, a version mismatch does not call `validate`. Neither option keeps the raw slot.
537537
- `useLocationState()` -- reactive hook; updates on popstate / `__rsc_locationstate` (does NOT update on static `.write()` / `.delete()`)
538538
- `redirect()` integration with location state
539539
- Serializability check: `ValidateLocationState<T>` rejects values `history.state` cannot structured-clone; the `LocationStateUnsafe<reason, path>` brand names each failing field (`items[].info.values`; an object's own unsafe fields first, so a DOM node stops at its methods; depth-bounded at 8)

‎packages/rangojs-router/skills/hooks/state.md‎

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -230,6 +230,40 @@ Or via `ctx.setLocationState()` on any response (handlers and middleware):
230230
};
231231
```
232232

233+
### Version and validate
234+
235+
The slot key is the file path plus the export name, so it stays the same across
236+
deploys. History entries survive reloads and back/forward. A tab left open
237+
across a release that changed the shape would otherwise restore the old value
238+
typed as the new one.
239+
240+
`version` is the cheap check for a deliberate shape change. Writers store
241+
`{ v, value }`. A missing `v`, a different `v`, or a non-object reads as
242+
`undefined` — the same as no state. A pre-version raw object is not treated as
243+
the new state. The value you get back is the inner `value`, the same reference
244+
that was stored.
245+
246+
```ts
247+
export const GridState = createLocationState<GridSnapshot>({ version: 2 });
248+
// stored as { v: 2, value }; a different or missing version reads as undefined
249+
```
250+
251+
`validate` also covers state written by other code under the same key. The
252+
stored shape stays the raw value. The check runs on read; `false` reads as
253+
`undefined`.
254+
255+
```ts
256+
export const GridState = createLocationState<GridSnapshot>({
257+
validate: (value): value is GridSnapshot => isGridSnapshot(value),
258+
});
259+
// run on read; a failing value reads as undefined
260+
```
261+
262+
Both may be set. A version mismatch returns `undefined` without calling
263+
`validate`. A match runs `validate` on the inner value. `flash: true` still
264+
clears the slot after paint; when `version` is set the slot holds the envelope
265+
and readers still see `TState | undefined`.
266+
233267
### .read() (non-hook access)
234268

235269
Read current location state outside React components (client-side only):

‎packages/rangojs-router/src/__tests__/location-state-shared.test.ts‎

Lines changed: 250 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -365,3 +365,253 @@ describe("location-state-shared", () => {
365365
});
366366
});
367367
});
368+
369+
type GridSnapshot = { rows: number[] };
370+
371+
function historyWithReplace(): {
372+
state: unknown;
373+
replaceState: ReturnType<typeof vi.fn>;
374+
} {
375+
const history: {
376+
state: unknown;
377+
replaceState: ReturnType<typeof vi.fn>;
378+
} = {
379+
state: { idx: 1 },
380+
replaceState: vi.fn(),
381+
};
382+
history.replaceState.mockImplementation((next: unknown) => {
383+
history.state = next;
384+
});
385+
return history;
386+
}
387+
388+
describe("createLocationState version", () => {
389+
afterEach(() => {
390+
restoreWindow();
391+
vi.unstubAllEnvs();
392+
});
393+
394+
it("write stores { v, value } and read returns the same inner reference", () => {
395+
const Grid = createLocationState<GridSnapshot>({ version: 2 });
396+
(Grid as any).__rsc_ls_key = "grid";
397+
const history = historyWithReplace();
398+
vi.stubGlobal("window", {
399+
history,
400+
location: { href: "https://example.test/grid" },
401+
});
402+
403+
const snapshot = { rows: [1, 2] };
404+
Grid.write(snapshot);
405+
406+
expect(history.state).toEqual({
407+
idx: 1,
408+
grid: { v: 2, value: snapshot },
409+
});
410+
expect(Grid.read()).toBe(snapshot);
411+
expect(Grid.read({ state: history.state })).toBe(snapshot);
412+
expect(Grid.read()).toBe(Grid.read());
413+
414+
Grid.delete();
415+
expect(history.state).toEqual({ idx: 1 });
416+
expect(Grid.read()).toBeUndefined();
417+
});
418+
419+
it("version 0 still stores an envelope", () => {
420+
const Grid = createLocationState<GridSnapshot>({ version: 0 });
421+
(Grid as any).__rsc_ls_key = "grid";
422+
const history = historyWithReplace();
423+
vi.stubGlobal("window", {
424+
history,
425+
location: { href: "https://example.test/grid" },
426+
});
427+
const snapshot = { rows: [0] };
428+
Grid.write(snapshot);
429+
expect((history.state as { grid: unknown }).grid).toEqual({
430+
v: 0,
431+
value: snapshot,
432+
});
433+
expect(Grid.read()).toBe(snapshot);
434+
});
435+
436+
it("a raw object, a different version, and a non-object read as undefined", () => {
437+
const Grid = createLocationState<GridSnapshot>({ version: 2 });
438+
(Grid as any).__rsc_ls_key = "grid";
439+
const snapshot = { rows: [1] };
440+
const cases = [
441+
{ grid: snapshot },
442+
{ grid: { v: 1, value: snapshot } },
443+
{ grid: "stale" },
444+
];
445+
for (const state of cases) {
446+
vi.stubGlobal("window", { history: { state } });
447+
expect(Grid.read()).toBeUndefined();
448+
expect(Grid.read({ state })).toBeUndefined();
449+
}
450+
});
451+
452+
it("flash with version stores the envelope and read returns the inner value", () => {
453+
const Grid = createLocationState<GridSnapshot>({
454+
flash: true,
455+
version: 2,
456+
});
457+
(Grid as any).__rsc_ls_key = "grid";
458+
const history = historyWithReplace();
459+
vi.stubGlobal("window", {
460+
history,
461+
location: { href: "https://example.test/grid" },
462+
});
463+
const snapshot = { rows: [4] };
464+
Grid.write(snapshot);
465+
expect((history.state as { grid: { value: unknown } }).grid.value).toBe(
466+
snapshot,
467+
);
468+
expect(Grid.read()).toBe(snapshot);
469+
expect(history.state).toEqual({
470+
idx: 1,
471+
grid: { v: 2, value: snapshot },
472+
});
473+
});
474+
475+
it("a direct entry and a lazy getter persist the envelope", () => {
476+
const Grid = createLocationState<GridSnapshot>({ version: 2 });
477+
(Grid as any).__rsc_ls_key = "grid";
478+
const snapshot = { rows: [1] };
479+
const eager = Grid(snapshot);
480+
expect(eager).toEqual({
481+
__rsc_ls_key: "grid",
482+
__rsc_ls_value: { v: 2, value: snapshot },
483+
});
484+
expect((eager.__rsc_ls_value as { value: GridSnapshot }).value).toBe(
485+
snapshot,
486+
);
487+
488+
let current = snapshot;
489+
const lazy = Grid(() => current);
490+
expect(lazy.__rsc_ls_lazy).toBe(true);
491+
expect(resolveLocationStateEntries([eager, lazy])).toEqual({
492+
grid: { v: 2, value: snapshot },
493+
});
494+
495+
const next = { rows: [9] };
496+
current = next;
497+
const resolved = resolveLocationStateEntries([lazy]);
498+
expect(resolved).toEqual({ grid: { v: 2, value: next } });
499+
expect((resolved.grid as { value: GridSnapshot }).value).toBe(next);
500+
});
501+
});
502+
503+
function isGridSnapshot(value: unknown): value is GridSnapshot {
504+
return (
505+
value !== null &&
506+
typeof value === "object" &&
507+
Array.isArray((value as { rows?: unknown }).rows)
508+
);
509+
}
510+
511+
describe("createLocationState validate", () => {
512+
afterEach(() => {
513+
restoreWindow();
514+
vi.unstubAllEnvs();
515+
});
516+
517+
it("keeps the raw stored value and returns it only when validate passes", () => {
518+
const validate = vi.fn(isGridSnapshot);
519+
const Grid = createLocationState<GridSnapshot>({ validate });
520+
(Grid as any).__rsc_ls_key = "grid";
521+
const history = historyWithReplace();
522+
vi.stubGlobal("window", {
523+
history,
524+
location: { href: "https://example.test/grid" },
525+
});
526+
527+
const snapshot = { rows: [1] };
528+
Grid.write(snapshot);
529+
expect(history.state).toEqual({ idx: 1, grid: snapshot });
530+
expect(Grid(snapshot).__rsc_ls_value).toBe(snapshot);
531+
expect(resolveLocationStateEntries([Grid(() => snapshot)])).toEqual({
532+
grid: snapshot,
533+
});
534+
535+
expect(Grid.read()).toBe(snapshot);
536+
expect(Grid.read({ state: history.state })).toBe(snapshot);
537+
expect(validate).toHaveBeenCalledWith(snapshot);
538+
539+
const rejected = { rows: "nope" };
540+
history.state = { idx: 1, grid: rejected };
541+
validate.mockClear();
542+
expect(Grid.read()).toBeUndefined();
543+
expect(Grid.read({ state: history.state })).toBeUndefined();
544+
expect(validate).toHaveBeenCalledWith(rejected);
545+
});
546+
547+
it("does not unwrap a value that only looks like a version envelope", () => {
548+
const stored = { v: 2, value: { rows: [1] } };
549+
const validate = vi.fn(
550+
(value: unknown): value is typeof stored => value === stored,
551+
);
552+
const Grid = createLocationState<typeof stored>({ validate });
553+
(Grid as any).__rsc_ls_key = "grid";
554+
const state = { grid: stored };
555+
vi.stubGlobal("window", { history: { state } });
556+
557+
expect(Grid.read()).toBe(stored);
558+
expect(Grid.read({ state })).toBe(stored);
559+
expect(validate).toHaveBeenCalledWith(stored);
560+
});
561+
});
562+
563+
describe("createLocationState version and validate", () => {
564+
afterEach(() => {
565+
restoreWindow();
566+
vi.unstubAllEnvs();
567+
});
568+
569+
it("does not validate a version mismatch, and drops a match that fails validate", () => {
570+
const snapshot = { rows: [1] };
571+
const validate = vi.fn(isGridSnapshot);
572+
const Grid = createLocationState<GridSnapshot>({ version: 2, validate });
573+
(Grid as any).__rsc_ls_key = "grid";
574+
575+
const mismatches = [
576+
{ grid: snapshot },
577+
{ grid: { v: 1, value: snapshot } },
578+
{ grid: "stale" },
579+
];
580+
for (const state of mismatches) {
581+
vi.stubGlobal("window", { history: { state } });
582+
expect(Grid.read()).toBeUndefined();
583+
expect(Grid.read({ state })).toBeUndefined();
584+
}
585+
expect(validate).not.toHaveBeenCalled();
586+
587+
const badInner = { rows: "nope" };
588+
const matchedBad = { grid: { v: 2, value: badInner } };
589+
vi.stubGlobal("window", { history: { state: matchedBad } });
590+
expect(Grid.read()).toBeUndefined();
591+
expect(Grid.read({ state: matchedBad })).toBeUndefined();
592+
expect(validate).toHaveBeenCalledWith(badInner);
593+
594+
validate.mockClear();
595+
const matched = { grid: { v: 2, value: snapshot } };
596+
vi.stubGlobal("window", { history: { state: matched } });
597+
expect(Grid.read()).toBe(snapshot);
598+
expect(Grid.read({ state: matched })).toBe(snapshot);
599+
expect(validate).toHaveBeenCalledWith(snapshot);
600+
601+
const history = historyWithReplace();
602+
vi.stubGlobal("window", {
603+
history,
604+
location: { href: "https://example.test/grid" },
605+
});
606+
Grid.write(snapshot);
607+
expect(Grid(snapshot).__rsc_ls_value).toEqual({ v: 2, value: snapshot });
608+
expect(resolveLocationStateEntries([Grid(() => snapshot)])).toEqual({
609+
grid: { v: 2, value: snapshot },
610+
});
611+
expect(history.state).toEqual({
612+
idx: 1,
613+
grid: { v: 2, value: snapshot },
614+
});
615+
expect(Grid.read()).toBe(snapshot);
616+
});
617+
});

0 commit comments

Comments
 (0)