@real-router/angular 0.18.4 → 0.19.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,9 +1,9 @@
1
1
  import * as i0 from '@angular/core';
2
2
  import { InjectionToken, inject, DestroyRef, ApplicationRef, signal, provideEnvironmentInitializer, makeEnvironmentProviders, makeStateKey, REQUEST, provideAppInitializer, TransferState, assertInInjectionContext, ChangeDetectorRef, effect, untracked, input, TemplateRef, Directive, contentChildren, computed, Component, output, ElementRef } from '@angular/core';
3
- import { getNavigator, UNKNOWN_ROUTE } from '@real-router/core';
3
+ import { events, getNavigator, UNKNOWN_ROUTE } from '@real-router/core';
4
4
  import { getTransitionSource, createRouteSource, primeErrorSource, createRouteNodeSource, createActiveSource, guardLeaveListener, createRouteEnterGate, createDismissableError } from '@real-router/sources';
5
+ import { getPluginApi, cloneRouter } from '@real-router/core/api';
5
6
  import { putField } from '@real-router/core/utils';
6
- import { cloneRouter, getPluginApi } from '@real-router/core/api';
7
7
  import { hydrateRouter, serializeRouterState } from '@real-router/ssr-utils';
8
8
  import { getRouteUtils, startsWithSegment } from '@real-router/route-utils';
9
9
  import { NgTemplateOutlet } from '@angular/common';
@@ -40,8 +40,27 @@ function createDirectionTracker(router) {
40
40
  }
41
41
  let popstateFlag = false;
42
42
  document.documentElement.dataset.navDirection = "forward";
43
+ let transitionInFlight = false;
44
+ let armedMidTransition = false;
45
+ // ⚑ The flag is SPENT by the transition it belongs to, whether or not that
46
+ // transition reaches a leave phase (#1924). It is armed by any `popstate` on
47
+ // `globalThis`, not only one the router consumes, so `history.back()` onto an
48
+ // entry that resolves to the current state — core answers `SAME_STATES`, and
49
+ // measured, that arc emits `TRANSITION_ERROR` with no `TRANSITION_START` and
50
+ // no leave — would otherwise leave it armed indefinitely and publish the next
51
+ // FORWARD navigation as "back".
52
+ //
53
+ // ⚠ A clock has no correct value to be set to. The leave phase is separated
54
+ // from its popstate by every deactivation guard, and a guard may await
55
+ // anything; the plugin also DEFERS a popstate that arrives during an
56
+ // in-flight transition and replays it from that transition's `finally`. The
57
+ // gap has no upper bound. Measured on the obvious choice: a task-boundary
58
+ // expiry disarms a live navigation on ONE async `canDeactivate`.
43
59
  const onPopstate = () => {
44
60
  popstateFlag = true;
61
+ // A deferred event belongs to the replay, not to the transition running
62
+ // now, so that transition's terminal event must not spend it.
63
+ armedMidTransition = transitionInFlight;
45
64
  };
46
65
  // IMPORTANT — listener-ordering: `popstate` fires on `window`, which
47
66
  // has no DOM descendants, so capture phase is moot. Listeners are
@@ -51,15 +70,35 @@ function createDirectionTracker(router) {
51
70
  // the plugin's handler runs first and synchronously fires
52
71
  // `subscribeLeave` while `popstateFlag` is still `false`.
53
72
  globalThis.addEventListener("popstate", onPopstate);
54
- const offLeave = router.subscribeLeave(() => {
55
- document.documentElement.dataset.navDirection = popstateFlag
56
- ? "back"
57
- : "forward";
73
+ const api = getPluginApi(router);
74
+ const onSettled = () => {
75
+ transitionInFlight = false;
76
+ if (armedMidTransition) {
77
+ armedMidTransition = false;
78
+ return;
79
+ }
58
80
  popstateFlag = false;
59
- });
81
+ };
82
+ const unsubs = [
83
+ api.addEventListener(events.TRANSITION_START, () => {
84
+ transitionInFlight = true;
85
+ }),
86
+ api.addEventListener(events.TRANSITION_SUCCESS, onSettled),
87
+ api.addEventListener(events.TRANSITION_ERROR, onSettled),
88
+ api.addEventListener(events.TRANSITION_CANCEL, onSettled),
89
+ router.subscribeLeave(() => {
90
+ document.documentElement.dataset.navDirection = popstateFlag
91
+ ? "back"
92
+ : "forward";
93
+ popstateFlag = false;
94
+ armedMidTransition = false;
95
+ }),
96
+ ];
60
97
  return {
61
98
  destroy: () => {
62
- offLeave();
99
+ for (const unsub of unsubs) {
100
+ unsub();
101
+ }
63
102
  globalThis.removeEventListener("popstate", onPopstate);
64
103
  delete document.documentElement.dataset.navDirection;
65
104
  },
@@ -83,14 +122,31 @@ const NOOP_INSTANCE$3 = Object.freeze({
83
122
  // destroy() would detach the shared node while sibling providers (micro-
84
123
  // frontends — the same multi-provider scenario `scroll-restore`'s `storageKey`
85
124
  // exists for) keep writing to the now-orphaned node → silent screen reader (#783).
86
- let announcerRefCount = 0;
125
+ // ⚑ The ref-count and the generation live ON THE ELEMENT (#1924). The element
126
+ // is found with `document.querySelector`, so it is document-scoped, while a
127
+ // module variable is bundle-scoped — and a page carrying a second adapter
128
+ // bundle, the micro-frontend case the ref-count exists for, shares the element
129
+ // and not the scope.
130
+ //
131
+ // ⚠ Module-scoped counters reach #783 verbatim through that seam: the second
132
+ // bundle takes the `existing` branch, reads its own generation, passes the
133
+ // #1217 ownership guard, decrements its own count to zero and removes the live
134
+ // element.
135
+ const REFS_ATTR = "data-rr-announcer-refs";
136
+ const GENERATION_ATTR = "data-rr-announcer-generation";
137
+ function readCount(element) {
138
+ // `Number(null)` is 0, so an absent attribute needs no fallback term.
139
+ return Number(element.getAttribute(REFS_ATTR));
140
+ }
141
+ function writeCount(element, value) {
142
+ element.setAttribute(REFS_ATTR, String(value));
143
+ }
87
144
  // Generation token (#1217): bumped each time a FRESH shared element is created.
88
145
  // Each instance captures the generation live at construction; on destroy it
89
146
  // touches the shared refcount / element ONLY if its generation is still current.
90
147
  // A stale instance — whose element a host wiped without calling destroy() — must
91
148
  // not decrement the new generation's refcount (→ negative) or remove its live
92
149
  // element (a selector-based removeAnnouncer takes whoever is in the DOM).
93
- let announcerGeneration = 0;
94
150
  function createRouteAnnouncer(router, options) {
95
151
  // Defensive SSR / non-browser guard: in SSR (Node.js) or non-DOM
96
152
  // environments, `document` is undefined and the announcer cannot
@@ -113,7 +169,7 @@ function createRouteAnnouncer(router, options) {
113
169
  let pendingText = null;
114
170
  let clearTimeoutId;
115
171
  const { element: announcer, generation: myGeneration } = getOrCreateAnnouncer();
116
- announcerRefCount += 1;
172
+ writeCount(announcer, readCount(announcer) + 1);
117
173
  const doAnnounce = (text, h1) => {
118
174
  lastAnnouncedText = text;
119
175
  clearTimeout(clearTimeoutId);
@@ -182,23 +238,44 @@ function createRouteAnnouncer(router, options) {
182
238
  // under us, the next getOrCreateAnnouncer bumped the generation for the
183
239
  // fresh element. A stale instance must NOT decrement the new generation's
184
240
  // refcount (→ negative) or remove its live element — bail if not current.
185
- if (myGeneration !== announcerGeneration) {
241
+ // ⚠ Against the DOCUMENT's generation, never the captured element's: the
242
+ // element a stale instance holds was removed, and its own attribute
243
+ // still reads its own generation, so comparing the two can only ever be
244
+ // equal and the guard would be dead.
245
+ if (myGeneration !== currentGeneration()) {
186
246
  return;
187
247
  }
188
- announcerRefCount -= 1;
248
+ const remaining = readCount(announcer) - 1;
249
+ writeCount(announcer, remaining);
189
250
  // Only the last holder tears down the shared element — via our captured
190
251
  // ref, not a selector query (which would delete whoever's element is
191
252
  // currently in the DOM, i.e. a newer generation's).
192
- if (announcerRefCount === 0) {
253
+ if (remaining === 0) {
193
254
  removeAnnouncer(announcer);
194
255
  }
195
256
  },
196
257
  };
197
258
  }
259
+ /**
260
+ * The next generation, derived from the document rather than a module counter:
261
+ * a wiped element leaves no node to read, so the value is kept on `<html>`.
262
+ */
263
+ function currentGeneration() {
264
+ return Number(document.documentElement.getAttribute(GENERATION_ATTR));
265
+ }
266
+ function nextGeneration() {
267
+ const root = document.documentElement;
268
+ const next = currentGeneration() + 1;
269
+ root.setAttribute(GENERATION_ATTR, String(next));
270
+ return next;
271
+ }
198
272
  function getOrCreateAnnouncer() {
199
273
  const existing = document.querySelector(`[${ANNOUNCER_ATTR}]`);
200
274
  if (existing) {
201
- return { element: existing, generation: announcerGeneration };
275
+ return {
276
+ element: existing,
277
+ generation: Number(existing.getAttribute(GENERATION_ATTR)),
278
+ };
202
279
  }
203
280
  // Creating a FRESH element means no live instance is validly sharing one, so
204
281
  // the ref-count restarts from zero (the caller increments immediately after).
@@ -208,13 +285,17 @@ function getOrCreateAnnouncer() {
208
285
  // count that prevents the new element from ever being torn down (#783).
209
286
  // The generation bump (#1217) lets the wiped element's instances recognize
210
287
  // themselves as stale so their destroy() does not touch this fresh element.
211
- announcerRefCount = 0;
212
- announcerGeneration += 1;
213
288
  const element = document.createElement("div");
214
289
  element.setAttribute("style", VISUALLY_HIDDEN);
215
290
  element.setAttribute("aria-live", "assertive");
216
291
  element.setAttribute("aria-atomic", "true");
217
292
  element.setAttribute(ANNOUNCER_ATTR, "");
293
+ // A fresh element restarts the count at zero (the caller increments straight
294
+ // after) and takes the next generation, so instances holding the element a
295
+ // host wiped recognise themselves as stale. Both live on the node, so every
296
+ // bundle reads the same values.
297
+ writeCount(element, 0);
298
+ element.setAttribute(GENERATION_ATTR, String(nextGeneration()));
218
299
  // Defensive SSR / pre-`<body>` guard: in some environments (early
219
300
  // injection, deferred-body documents, certain SSR rehydration paths)
220
301
  // `document.body` can be null when the announcer is constructed.
@@ -228,7 +309,10 @@ function getOrCreateAnnouncer() {
228
309
  // runtime can return null per spec. The `as` cast narrows the type to
229
310
  // include null so the `??` short-circuit is type-safe.
230
311
  (document.body ?? document.documentElement).prepend(element);
231
- return { element, generation: announcerGeneration };
312
+ return {
313
+ element,
314
+ generation: Number(element.getAttribute(GENERATION_ATTR)),
315
+ };
232
316
  }
233
317
  function removeAnnouncer(element) {
234
318
  element.remove();
@@ -276,20 +360,6 @@ function manageFocus(h1) {
276
360
 
277
361
  /** Captured like the deciding seven, but this one BUILDS the guarantee (#2072). */
278
362
  const objectCreate = Object.create;
279
- /**
280
- * Intrinsics captured at module load (#1971).
281
- *
282
- * ⚑ These DECIDE — they answer "what is on this object" for a value this module
283
- * did not build. Read off the live global they can be re-pointed after boot, and
284
- * `shared/` is the half where that fails OPEN: measured in `browser-env`, a
285
- * re-pointed `getPrototypeOf` admits a `Date` into `state.params` and a
286
- * re-pointed `keys` skips option validation entirely.
287
- *
288
- * ⚠ Capture narrows the window from "any time after boot" to "before this module
289
- * loads". It does not close it — a shim evaluated ahead of core still wins
290
- * (#1798), which is the doctrine's own caveat and travels with it.
291
- */
292
- const objectKeys$1 = Object.keys;
293
363
  const DEFAULT_STORAGE_KEY = "real-router:scroll";
294
364
  // Bounded retry budget for resolving a late-mounting scroll container on the
295
365
  // restore path. A per-route container (e.g. an `overflow:auto` div rendered
@@ -426,14 +496,23 @@ function createScrollRestoration(router, options) {
426
496
  // smooth restores animate asynchronously, so they run the full budget. The
427
497
  // frame budget is the hard backstop against an unreachable target (saved
428
498
  // position taller than the restored content).
499
+ let restoreToken = 0;
429
500
  const restorePos = (top) => {
430
501
  if (!getContainer) {
431
502
  globalThis.scrollTo({ top, left: 0, behavior });
432
503
  return;
433
504
  }
434
505
  let frames = 0;
506
+ // ⚑ A per-restore token, the idea `view-transitions.ts` carries as
507
+ // `scheduledVT` (#781) and this file already carries as `scrollSettled` on
508
+ // the capture side (#782). Without it the budget is gated by `destroyed`
509
+ // alone, so a loop whose target is unreachable — a container that clamps
510
+ // short and keeps retrying — is still running when the next navigation
511
+ // lands, and writes the PREVIOUS route's offset onto the current page the
512
+ // moment that container's layout grows (#1924).
513
+ const token = (restoreToken += 1);
435
514
  const attempt = () => {
436
- if (destroyed) {
515
+ if (destroyed || token !== restoreToken) {
437
516
  return;
438
517
  }
439
518
  const element = getContainer();
@@ -499,7 +578,6 @@ function createScrollRestoration(router, options) {
499
578
  writePos(0);
500
579
  };
501
580
  let destroyed = false;
502
- let unserializableWarned = false;
503
581
  // Capture/effect seam guard (#782). previousRoute's position is captured
504
582
  // synchronously in `subscribe`, but the snap/restore effect runs a frame
505
583
  // later in rAF. Across that window the viewport still shows the route BEFORE
@@ -509,26 +587,6 @@ function createScrollRestoration(router, options) {
509
587
  // value survives the transit). A real user scroll in this <16ms window is
510
588
  // physically impossible.
511
589
  let scrollSettled = true;
512
- // `keyOf` defers to `canonicalJson` which calls `JSON.stringify`. Two
513
- // realistic inputs blow up the serializer and would otherwise crash the
514
- // subscribe callback (taking scroll-restore offline for the whole session):
515
- // - `BigInt` params → `TypeError: Do not know how to serialize a BigInt`
516
- // - cyclic params (reactive proxies, DOM-ref back-pointers) → stack
517
- // overflow.
518
- // The defensive wrapper drops capture/restore for that specific navigation
519
- // and warns once per provider — the rest of the cache stays usable.
520
- const safeKeyOf = (state) => {
521
- try {
522
- return keyOf(state);
523
- }
524
- catch {
525
- if (!unserializableWarned) {
526
- unserializableWarned = true;
527
- console.error(`[real-router] scroll-restore: route "${state.name}" has params that cannot be canonicalized (e.g. BigInt or cyclic structure). Scroll position will not be captured or restored for this route.`);
528
- }
529
- return null;
530
- }
531
- };
532
590
  const unsubscribe = router.subscribe(({ route, previousRoute }) => {
533
591
  const nav = route.context
534
592
  .navigation;
@@ -538,10 +596,7 @@ function createScrollRestoration(router, options) {
538
596
  // skipped while the scroll is unsettled — a second navigation in the same
539
597
  // frame, before the prior nav's rAF snap (see `scrollSettled`, #782).
540
598
  if (previousRoute && scrollSettled) {
541
- const prevKey = safeKeyOf(previousRoute);
542
- if (prevKey !== null) {
543
- putPos(prevKey, readPos());
544
- }
599
+ putPos(keyOf(previousRoute), readPos());
545
600
  }
546
601
  // This navigation's scroll effect is now pending: the viewport position no
547
602
  // longer belongs to `route` until the rAF below runs and settles it.
@@ -579,13 +634,11 @@ function createScrollRestoration(router, options) {
579
634
  // arm, which is the pre-#1976 answer for a state carrying no meta.
580
635
  // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition -- the required field is genuinely absent on a foreign committed State
581
636
  if (route.transition?.reload || nav?.navigationType === "reload") {
582
- const key = safeKeyOf(route);
583
- restorePos(key === null ? 0 : (loadStore()[key] ?? 0));
637
+ restorePos(loadStore()[keyOf(route)] ?? 0);
584
638
  return;
585
639
  }
586
640
  if (nav?.direction === "back" || nav?.navigationType === "traverse") {
587
- const key = safeKeyOf(route);
588
- restorePos(key === null ? 0 : (loadStore()[key] ?? 0));
641
+ restorePos(loadStore()[keyOf(route)] ?? 0);
589
642
  return;
590
643
  }
591
644
  // Genuine in-place replace (not a traversal) — leave scroll untouched.
@@ -600,10 +653,7 @@ function createScrollRestoration(router, options) {
600
653
  const onPageHide = () => {
601
654
  const current = router.getState();
602
655
  if (current) {
603
- const key = safeKeyOf(current);
604
- if (key !== null) {
605
- putPos(key, readPos());
606
- }
656
+ putPos(keyOf(current), readPos());
607
657
  }
608
658
  };
609
659
  globalThis.addEventListener("pagehide", onPageHide);
@@ -631,111 +681,26 @@ function createScrollRestoration(router, options) {
631
681
  * Internal cache-key builder for scroll-position storage.
632
682
  *
633
683
  * **Exported for testing only — not part of the public API** (intentionally
634
- * excluded from `index.ts` barrel). Adapter property tests import it via
635
- * the direct path to lock the `(name, canonicalJson(params))` key shape
636
- * as a regression guard (§8b H20 / audit-2026-05-16 #S3). A change to
637
- * key format would silently lose scroll positions across an upgrade —
638
- * the test set is the contract.
639
- *
640
- * ## Identity-based memoization (audit-2026-05-17 §8b #2)
684
+ * excluded from `index.ts` barrel). Adapter property tests import it rather
685
+ * than replicating it (§8b H20 / audit-2026-05-16 #S3): a replica drifts
686
+ * silently the moment the key changes. A change to the key format loses saved
687
+ * positions across an upgrade, so the test set is the contract.
641
688
  *
642
- * `State` objects emitted by core are frozen per-navigation: their
643
- * `name` / `params` are immutable for the lifetime of the snapshot, and
644
- * any change produces a new `State` reference. A `WeakMap<State, string>`
645
- * therefore safely caches the canonicalised key by identity — repeat
646
- * `keyOf(state)` calls on the same snapshot (typical on
647
- * back/forward/traverse where the same prior `State` is re-emitted)
648
- * skip the recursive `canonicalJson` pass entirely.
689
+ * ## Not memoized
649
690
  *
650
- * The cache key is the `State` reference, so entries auto-release when
651
- * the snapshot is GC'd — no eviction needed.
691
+ * The key is a string property read, which is cheaper than the `WeakMap`
692
+ * lookup any cache would need — so there is nothing here to cache.
652
693
  */
653
- const KEY_CACHE = new WeakMap();
654
694
  function keyOf(state) {
655
- const cached = KEY_CACHE.get(state);
656
- if (cached !== undefined) {
657
- return cached;
658
- }
659
- // Key over BOTH channels — path params AND query (RFC-4 M2 / #1548). Merged
660
- // (not `params:search`) so a query-less route keeps its v1 key shape
661
- // (`name:{}`), and an unserializable value (BigInt / cyclic) in EITHER channel
662
- // still throws in `canonicalJson` → `safeKeyOf` drops+warns.
663
- const key = `${state.name}:${canonicalJson({ ...state.params, ...state.search })}`;
664
- KEY_CACHE.set(state, key);
665
- return key;
666
- }
667
- /**
668
- * Stable JSON serializer with sorted object keys.
669
- *
670
- * **Exported for testing only — not part of the public API** (intentionally
671
- * excluded from `index.ts` barrel). Adapter property tests import it via
672
- * the direct path to lock the key-order-insensitive property
673
- * (`canonicalJson({a:1,b:2}) === canonicalJson({b:2,a:1})`).
674
- *
675
- * ## Divergence from `@real-router/sources/canonicalJson` — by design
676
- *
677
- * Two independent implementations live in the monorepo:
678
- *
679
- * - **`shared/dom-utils/scroll-restore.canonicalJson`** (this file) — scroll
680
- * cache key builder. Uses `localeCompare` and a plain-object accumulator;
681
- * tolerates `__proto__`-keyed inputs only insofar as `JSON.stringify`'s
682
- * replacer happens to sort them; relies on `JSON.stringify`'s native cycle
683
- * detector. Designed to be cheap on the navigation hot path. The
684
- * surrounding [[safeKeyOf]] wrapper catches the two crash inputs (`BigInt`,
685
- * cyclic) and skips the offending capture/restore.
686
- *
687
- * - **`@real-router/sources/canonicalJson`** — sources cache key builder.
688
- * Uses byte-order compare (`< / >`) for locale-independence, a
689
- * `Object.create(null)` accumulator to prevent prototype pollution, and a
690
- * bespoke path-based cycle detector (the native one cannot see the cloned
691
- * graph). Throws eagerly on `Map`/`Set`/`RegExp`/cycles — the caller falls
692
- * back to a non-cached source.
693
- *
694
- * **They are intentionally NOT interchangeable.** Aligning them would either
695
- * regress scroll-restore performance (byte-order + recursive clone is heavier
696
- * per call) or weaken the sources cache (locale dependence breaks
697
- * deterministic cache keys across machines). No cross-package equivalence
698
- * test exists or should be added; the relationship is "different invariants,
699
- * different costs, different consumers." Audit-2 / audit-2026-05-17 §2
700
- * documents the choice.
701
- */
702
- function canonicalJson(value) {
703
- return JSON.stringify(value, canonicalReplacer);
704
- }
705
- function canonicalReplacer(_key, val) {
706
- // audit-2026-05-17 §5 MEDIUM (Sprint A.3) — function/Symbol marker.
707
- // `JSON.stringify` silently drops function and symbol values from
708
- // object output. Two routes that differ ONLY in a function/Symbol
709
- // value would canonicalize to the same string → silent scroll-cache
710
- // key collision (positions clobber each other). Replacing the value
711
- // with a sentinel string breaks the collision while keeping the
712
- // canonical form deterministic. The sentinels are intentionally
713
- // ASCII-only and lexically distinct from valid JSON-stringified
714
- // values; consumers will see `"<fn>"` / `"<sym>"` if they ever
715
- // round-trip the cache key, signalling the substitution clearly.
716
- if (typeof val === "function") {
717
- return "<fn>";
718
- }
719
- if (typeof val === "symbol") {
720
- return "<sym>";
721
- }
722
- if (val !== null && typeof val === "object" && !Array.isArray(val)) {
723
- // Null-prototype accumulator: a plain `{}` would interpret
724
- // `sorted["__proto__"] = x` as a prototype assignment (silently dropped
725
- // from JSON.stringify output AND a prototype-pollution vector). Mirrors
726
- // the same guard in `@real-router/sources/canonicalJson`. The two
727
- // implementations are still intentionally divergent (see the doc-block
728
- // on [[canonicalJson]] above), but prototype-safety is non-negotiable
729
- // on both. Lock-test: scrollRestoreKey.properties.ts Invariant 11.
730
- const sorted = objectCreate(null);
731
- // eslint-disable-next-line unicorn/no-array-sort -- ng-packagr uses pre-ES2023 lib; toSorted unavailable
732
- const keys = objectKeys$1(val).sort((left, right) => left.localeCompare(right));
733
- for (const key of keys) {
734
- sorted[key] = val[key];
735
- }
736
- return sorted;
737
- }
738
- return val;
695
+ // The key is the LOCATION, and `state.path` is the form core prints it in
696
+ // (#1923). Deriving it from the bags instead makes this a SECOND place that
697
+ // has to know how a value prints — and the two domains disagree there: the
698
+ // URL direction parses `?page=2` into the number `2`, an intent keeps `"2"`,
699
+ // and `packages/core/src/helpers.ts` says comparison is the single place that
700
+ // knows they describe one location. Reading the printed form asks core rather
701
+ // than re-deriving it, so a route's query, its `?id` carve-out twin and the
702
+ // order its params were written in are all already settled here.
703
+ return state.path;
739
704
  }
740
705
 
741
706
  const NOOP_INSTANCE$1 = Object.freeze({