@rangojs/router 0.0.0-experimental.d7eeaa75 → 0.0.0-experimental.dcbea258

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.
Files changed (37) hide show
  1. package/dist/vite/index.js +16 -8
  2. package/package.json +3 -3
  3. package/skills/handler-use/SKILL.md +362 -0
  4. package/skills/intercept/SKILL.md +20 -0
  5. package/skills/layout/SKILL.md +22 -0
  6. package/skills/middleware/SKILL.md +32 -3
  7. package/skills/migrate-nextjs/SKILL.md +560 -0
  8. package/skills/migrate-react-router/SKILL.md +764 -0
  9. package/skills/parallel/SKILL.md +59 -0
  10. package/skills/rango/SKILL.md +24 -22
  11. package/skills/route/SKILL.md +24 -0
  12. package/src/browser/navigation-bridge.ts +19 -2
  13. package/src/browser/navigation-client.ts +34 -6
  14. package/src/browser/partial-update.ts +14 -2
  15. package/src/browser/prefetch/cache.ts +16 -6
  16. package/src/browser/prefetch/fetch.ts +60 -4
  17. package/src/browser/react/Link.tsx +25 -2
  18. package/src/browser/segment-reconciler.ts +36 -14
  19. package/src/build/route-trie.ts +50 -24
  20. package/src/client.tsx +82 -174
  21. package/src/index.ts +37 -9
  22. package/src/reverse.ts +4 -1
  23. package/src/route-definition/dsl-helpers.ts +159 -20
  24. package/src/route-definition/helpers-types.ts +57 -13
  25. package/src/route-types.ts +7 -0
  26. package/src/router/handler-context.ts +4 -1
  27. package/src/router/lazy-includes.ts +5 -5
  28. package/src/router/manifest.ts +12 -7
  29. package/src/segment-content-promise.ts +67 -0
  30. package/src/segment-loader-promise.ts +122 -0
  31. package/src/segment-system.tsx +11 -61
  32. package/src/server/context.ts +26 -3
  33. package/src/types/route-entry.ts +11 -0
  34. package/src/types/segments.ts +0 -1
  35. package/src/urls/include-helper.ts +24 -14
  36. package/src/urls/path-helper-types.ts +30 -4
  37. package/src/vite/utils/prerender-utils.ts +20 -6
@@ -2,11 +2,7 @@ import * as React from "react";
2
2
  import { createElement, type ReactNode, type ComponentType } from "react";
3
3
  import { OutletProvider } from "./client.js";
4
4
  import { MountContextProvider } from "./browser/react/mount-context.js";
5
- import type {
6
- ResolvedSegment,
7
- LoaderDataResult,
8
- RootLayoutProps,
9
- } from "./types.js";
5
+ import type { ResolvedSegment, RootLayoutProps } from "./types.js";
10
6
  import { isLoaderDataResult } from "./types.js";
11
7
  import { invariant } from "./errors.js";
12
8
  import {
@@ -14,6 +10,8 @@ import {
14
10
  LoaderBoundary,
15
11
  } from "./route-content-wrapper.js";
16
12
  import { RootErrorBoundary } from "./root-error-boundary.js";
13
+ import { getMemoizedContentPromise } from "./segment-content-promise.js";
14
+ import { getMemoizedLoaderPromise } from "./segment-loader-promise.js";
17
15
 
18
16
  // ViewTransition is only available in React experimental.
19
17
  // Access via namespace import to avoid compile-time errors on stable React.
@@ -61,20 +59,6 @@ function restoreParallelLoaderMarkers(
61
59
  return nextSegments ?? segments;
62
60
  }
63
61
 
64
- function hasSameReferences(a: unknown[] | undefined, b: unknown[]): boolean {
65
- if (!a || a.length !== b.length) {
66
- return false;
67
- }
68
-
69
- for (let i = 0; i < a.length; i++) {
70
- if (a[i] !== b[i]) {
71
- return false;
72
- }
73
- }
74
-
75
- return true;
76
- }
77
-
78
62
  /**
79
63
  * Resolve loader data from raw results, unwrapping LoaderDataResult wrappers
80
64
  */
@@ -278,10 +262,7 @@ export async function renderSegments(
278
262
  loading !== null && loading !== undefined && loading !== false
279
263
  ? createElement(RouteContentWrapper, {
280
264
  key: `suspense-loading-${id}`,
281
- content:
282
- resolvedComponent instanceof Promise
283
- ? resolvedComponent
284
- : Promise.resolve(resolvedComponent),
265
+ content: getMemoizedContentPromise(resolvedComponent),
285
266
  fallback: loading,
286
267
  segmentId: id,
287
268
  })
@@ -305,16 +286,7 @@ export async function renderSegments(
305
286
 
306
287
  // Prepare loader data if there are loaders
307
288
  const loaderIds = loaderEntries.map((loader) => loader.loaderId!);
308
- const loaderDataPromise =
309
- loaderEntries.length > 0
310
- ? Promise.all(
311
- loaderEntries.map((loader) =>
312
- loader.loaderData instanceof Promise
313
- ? loader.loaderData
314
- : Promise.resolve(loader.loaderData),
315
- ),
316
- )
317
- : Promise.resolve([]);
289
+ const loaderDataPromise = getMemoizedLoaderPromise(loaderEntries);
318
290
 
319
291
  // Use LoaderBoundary when loading is defined to maintain consistent tree structure
320
292
  // This ensures cached segments (which may not have loader segments) have the same
@@ -396,34 +368,12 @@ export async function renderSegments(
396
368
  continue;
397
369
  }
398
370
 
399
- const parallelLoaderIds = ownedLoaders.map((l) => l.loaderId!);
400
- const parallelLoaderSources = ownedLoaders.map((l) => l.loaderData);
401
- p.loaderIds = parallelLoaderIds;
402
-
403
- const shouldReuseParallelPromise =
404
- p.loaderDataPromise !== undefined &&
405
- hasSameReferences(p.parallelLoaderSources, parallelLoaderSources);
406
-
407
- const parallelLoaderDataPromise = shouldReuseParallelPromise
408
- ? p.loaderDataPromise
409
- : forceAwait || isAction
410
- ? await Promise.all(
411
- ownedLoaders.map((l) =>
412
- l.loaderData instanceof Promise
413
- ? l.loaderData
414
- : Promise.resolve(l.loaderData),
415
- ),
416
- )
417
- : Promise.all(
418
- ownedLoaders.map((l) =>
419
- l.loaderData instanceof Promise
420
- ? l.loaderData
421
- : Promise.resolve(l.loaderData),
422
- ),
423
- );
424
-
425
- p.loaderDataPromise = parallelLoaderDataPromise;
426
- p.parallelLoaderSources = parallelLoaderSources;
371
+ p.loaderIds = ownedLoaders.map((l) => l.loaderId!);
372
+ const aggregated = getMemoizedLoaderPromise(ownedLoaders);
373
+ p.loaderDataPromise =
374
+ (forceAwait || isAction) && aggregated instanceof Promise
375
+ ? await aggregated
376
+ : aggregated;
427
377
  }
428
378
  }
429
379
 
@@ -280,6 +280,22 @@ interface HelperContext {
280
280
  /** True when resolving handlers inside a cache() DSL boundary.
281
281
  * Read by ctx.get() to guard non-cacheable variable reads. */
282
282
  insideCacheScope?: boolean;
283
+ /**
284
+ * Include scope string applied to direct-descendant shortCodes.
285
+ *
286
+ * Each `include(...)` call allocates a sibling-positional token like `I0`,
287
+ * `I1` from its parent's include counter and stores the composed scope
288
+ * (`${parentScope}I${idx}`) in its lazyContext. When the include's handler
289
+ * evaluates lazily, the store's `includeScope` is set from that context so
290
+ * every direct-descendant shortCode is generated as
291
+ * `${parent.shortCode}${includeScope}${prefix}${index}` — preventing
292
+ * collisions with siblings declared outside the include.
293
+ *
294
+ * The scope is NOT propagated through `store.run(...)`, so layouts /
295
+ * parallels / caches inside the include absorb the scope into their own
296
+ * shortCodes and their children start fresh.
297
+ */
298
+ includeScope?: string;
283
299
  }
284
300
  // Use a global symbol key so the AsyncLocalStorage instance survives HMR
285
301
  // module re-evaluation. Without this, Vite's RSC module runner may create
@@ -382,6 +398,8 @@ export const getContext = (): {
382
398
  const mountPrefix =
383
399
  store.mountIndex !== undefined ? `M${store.mountIndex}` : "";
384
400
 
401
+ const includeScope = store.includeScope ?? "";
402
+
385
403
  if (!parent) {
386
404
  // Root entry: prefix with mount index and use mount-scoped counter
387
405
  const counterKey = mountPrefix
@@ -392,12 +410,16 @@ export const getContext = (): {
392
410
  store.counters[counterKey] = index + 1;
393
411
  return `${mountPrefix}${prefix}${index}`;
394
412
  } else {
395
- // Child entry: use parent-scoped counter (parent already has M prefix)
396
- const counterKey = `${parent.shortCode}_${type}`;
413
+ // Child entry: use parent-scoped counter with includeScope appended.
414
+ // When we're evaluating a lazy include's direct children, includeScope
415
+ // is a per-include token like "I0" / "I1I0" that partitions the
416
+ // parent's counter namespace so routes inside one include cannot
417
+ // collide with siblings declared outside it.
418
+ const counterKey = `${parent.shortCode}${includeScope}_${type}`;
397
419
  store.counters[counterKey] ??= 0;
398
420
  const index = store.counters[counterKey];
399
421
  store.counters[counterKey] = index + 1;
400
- return `${parent.shortCode}${prefix}${index}`;
422
+ return `${parent.shortCode}${includeScope}${prefix}${index}`;
401
423
  }
402
424
  },
403
425
  runWithStore: <T>(
@@ -424,6 +446,7 @@ export const getContext = (): {
424
446
  rootScoped: store.rootScoped,
425
447
  trackedIncludes: store.trackedIncludes,
426
448
  cacheProfiles: store.cacheProfiles,
449
+ includeScope: store.includeScope,
427
450
  },
428
451
  callback,
429
452
  );
@@ -8,10 +8,21 @@ export interface LazyIncludeContext {
8
8
  urlPrefix: string;
9
9
  namePrefix: string | undefined;
10
10
  parent: unknown; // EntryData - avoid circular import
11
+ /** Counter snapshot from pattern extraction for consistent shortCode indices */
12
+ counters?: Record<string, number>;
11
13
  cacheProfiles?: Record<
12
14
  string,
13
15
  import("../cache/profile-registry.js").CacheProfile
14
16
  >;
17
+ /** Root scope flag for dot-local reverse resolution */
18
+ rootScoped?: boolean;
19
+ /**
20
+ * Positional include scope token composed from the parent scope plus this
21
+ * include's sibling index (`${parentScope}I${idx}`). Applied to direct-
22
+ * descendant shortCodes during lazy evaluation so routes inside the
23
+ * include cannot collide with siblings declared outside it.
24
+ */
25
+ includeScope?: string;
15
26
  }
16
27
 
17
28
  /**
@@ -56,7 +56,6 @@ export interface ResolvedSegment {
56
56
  // Intercept loader fields (for streaming loader data in parallel segments)
57
57
  loaderDataPromise?: Promise<any[]> | any[]; // Loader data promise or resolved array
58
58
  loaderIds?: string[]; // IDs ($$id) of loaders for this segment
59
- parallelLoaderSources?: any[]; // Internal: preserves stable aggregate promise across renders
60
59
  // Error-specific fields
61
60
  error?: ErrorInfo; // For error segments: the error information
62
61
  // NotFound-specific fields
@@ -4,7 +4,6 @@ import {
4
4
  runWithPrefixes,
5
5
  getUrlPrefix,
6
6
  getNamePrefix,
7
- getRootScoped,
8
7
  } from "../server/context";
9
8
  import {
10
9
  INTERNAL_INCLUDE_SCOPE_PREFIX,
@@ -149,22 +148,32 @@ export function createIncludeHelper<TEnv>(): IncludeFn<TEnv> {
149
148
  });
150
149
  }
151
150
 
152
- // Snapshot parent's counters so lazy manifest generation starts
153
- // at the correct index, preventing shortCode collisions with
154
- // sibling entries (e.g., BlogLayout and ArticlesLayout under NavLayout).
155
- const capturedCounters = { ...ctx.counters };
156
-
157
- // Reserve a layout slot in the parent's counter so sibling lazy includes
158
- // produce different shortCode indices for their root layout.
159
- // Without this, consecutive include() calls capture identical counters
160
- // and their first child layouts get the same shortCode (e.g., both M0L0L0),
161
- // causing the client partial-update diff to see no changes on navigation.
151
+ // Allocate an include-scope token for this include() call. The token is
152
+ // appended to the parent's shortCode prefix whenever the include's
153
+ // direct-descendant shortCodes are generated (see getShortCode in
154
+ // context.ts), partitioning the parent's counter namespace so routes
155
+ // inside an include cannot collide with siblings declared outside it.
156
+ //
157
+ // Scopes compose: a nested include inside an outer include with scope
158
+ // "I0" allocates against the `${parent.shortCode}I0_include` counter
159
+ // and produces scope "I0I0", "I0I1", etc.
160
+ const parentScope = ctx.includeScope ?? "";
161
+ let includeScope = parentScope;
162
162
  if (capturedParent?.shortCode) {
163
- const layoutCounterKey = `${capturedParent.shortCode}_layout`;
164
- ctx.counters[layoutCounterKey] ??= 0;
165
- ctx.counters[layoutCounterKey]++;
163
+ const includeCounterKey = `${capturedParent.shortCode}${parentScope}_include`;
164
+ ctx.counters[includeCounterKey] ??= 0;
165
+ const includeIdx = ctx.counters[includeCounterKey];
166
+ ctx.counters[includeCounterKey] = includeIdx + 1;
167
+ includeScope = `${parentScope}I${includeIdx}`;
166
168
  }
167
169
 
170
+ // Snapshot parent's counters AFTER allocating the include scope so lazy
171
+ // manifest generation starts with the same counter state this include
172
+ // observed — its descendants still get fresh per-scope counters because
173
+ // they key off `${parent.shortCode}${includeScope}_*` (not shared with
174
+ // siblings outside the include).
175
+ const capturedCounters = { ...ctx.counters };
176
+
168
177
  // Compute rootScoped at capture time, mirroring the logic in runWithPrefixes.
169
178
  // This ensures lazy evaluation restores the correct scope state.
170
179
  const parentRootScoped = ctx.rootScoped;
@@ -191,6 +200,7 @@ export function createIncludeHelper<TEnv>(): IncludeFn<TEnv> {
191
200
  counters: capturedCounters,
192
201
  cacheProfiles: ctx.cacheProfiles,
193
202
  rootScoped: capturedRootScoped,
203
+ includeScope,
194
204
  },
195
205
  } as IncludeItem;
196
206
  };
@@ -233,12 +233,27 @@ export type PathHelpers<TEnv> = {
233
233
  include: IncludeFn<TEnv>;
234
234
 
235
235
  /**
236
- * Define parallel routes that render simultaneously in named slots
236
+ * Define parallel routes that render simultaneously in named slots.
237
+ *
238
+ * A slot value can be a Handler / ReactNode / StaticHandlerDefinition
239
+ * (legacy form, broadcast use applies to every slot) or a slot descriptor
240
+ * `{ handler, use? }` whose `use` is scoped to that slot only. Per-slot
241
+ * merge order is `handler.use` → shared `use` → slot-local `use`, with
242
+ * narrowest scope winning for last-write-wins items like `loading()`.
237
243
  */
238
244
  parallel: <
239
245
  TSlots extends Record<
240
246
  `@${string}`,
241
- Handler<any, any, TEnv> | ReactNode | StaticHandlerDefinition
247
+ | Handler<any, any, TEnv>
248
+ | ReactNode
249
+ | StaticHandlerDefinition
250
+ | {
251
+ handler:
252
+ | Handler<any, any, TEnv>
253
+ | ReactNode
254
+ | StaticHandlerDefinition;
255
+ use?: () => ParallelUseItem[];
256
+ }
242
257
  >,
243
258
  >(
244
259
  slots: TSlots,
@@ -264,9 +279,20 @@ export type PathHelpers<TEnv> = {
264
279
  ) => InterceptItem;
265
280
 
266
281
  /**
267
- * Attach middleware to the current route/layout
282
+ * Attach middleware to the current route/layout, or wrap child segments
268
283
  */
269
- middleware: (...fns: MiddlewareFn<TEnv>[]) => MiddlewareItem;
284
+ middleware: {
285
+ (fn: MiddlewareFn<TEnv>): MiddlewareItem;
286
+ (
287
+ fn: MiddlewareFn<TEnv>,
288
+ children: () => UseItems<LayoutUseItem>,
289
+ ): MiddlewareItem;
290
+ (fns: MiddlewareFn<TEnv>[]): MiddlewareItem;
291
+ (
292
+ fns: MiddlewareFn<TEnv>[],
293
+ children: () => UseItems<LayoutUseItem>,
294
+ ): MiddlewareItem;
295
+ };
270
296
 
271
297
  /**
272
298
  * Control when a segment should revalidate during navigation
@@ -41,14 +41,28 @@ export function substituteRouteParams(
41
41
  let result = pattern;
42
42
  let hadOmittedOptional = false;
43
43
 
44
- // First pass: substitute provided params
44
+ // First pass: substitute provided params.
45
+ // Empty string on an optional placeholder is treated as omitted (the trie
46
+ // matcher fills unmatched optionals with "" — letting the second pass
47
+ // strip them keeps slash cleanup consistent). Empty string on required
48
+ // `:key` or wildcard `*key` still substitutes, matching prior behaviour.
45
49
  for (const [key, value] of Object.entries(params)) {
46
50
  const escaped = escapeRegExp(key);
47
- result = result.replace(
48
- new RegExp(`:${escaped}(\\([^)]*\\))?\\??`),
49
- encode(value),
50
- );
51
- result = result.replace(`*${key}`, encode(value));
51
+ if (value === "") {
52
+ // Only replace required placeholders (negative lookahead for `?`);
53
+ // leave `:key?` for the second pass.
54
+ result = result.replace(
55
+ new RegExp(`:${escaped}(\\([^)]*\\))?(?!\\?)`),
56
+ "",
57
+ );
58
+ result = result.replace(`*${key}`, "");
59
+ } else {
60
+ result = result.replace(
61
+ new RegExp(`:${escaped}(\\([^)]*\\))?\\??`),
62
+ encode(value),
63
+ );
64
+ result = result.replace(`*${key}`, encode(value));
65
+ }
52
66
  }
53
67
 
54
68
  // Second pass: strip remaining optional param placeholders not in params