@rangojs/router 0.0.0-experimental.7dc955ec → 0.0.0-experimental.80

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 (124) hide show
  1. package/README.md +76 -18
  2. package/dist/bin/rango.js +130 -47
  3. package/dist/vite/index.js +700 -236
  4. package/package.json +3 -3
  5. package/skills/handler-use/SKILL.md +362 -0
  6. package/skills/intercept/SKILL.md +20 -0
  7. package/skills/layout/SKILL.md +22 -0
  8. package/skills/links/SKILL.md +3 -1
  9. package/skills/loader/SKILL.md +53 -43
  10. package/skills/middleware/SKILL.md +34 -3
  11. package/skills/migrate-nextjs/SKILL.md +560 -0
  12. package/skills/migrate-react-router/SKILL.md +764 -0
  13. package/skills/parallel/SKILL.md +59 -0
  14. package/skills/prerender/SKILL.md +110 -68
  15. package/skills/rango/SKILL.md +24 -22
  16. package/skills/route/SKILL.md +24 -0
  17. package/skills/router-setup/SKILL.md +87 -2
  18. package/src/__internal.ts +1 -1
  19. package/src/browser/app-version.ts +14 -0
  20. package/src/browser/navigation-bridge.ts +37 -5
  21. package/src/browser/navigation-client.ts +98 -46
  22. package/src/browser/navigation-store.ts +43 -8
  23. package/src/browser/partial-update.ts +41 -7
  24. package/src/browser/prefetch/cache.ts +16 -6
  25. package/src/browser/prefetch/fetch.ts +68 -6
  26. package/src/browser/prefetch/queue.ts +61 -29
  27. package/src/browser/prefetch/resource-ready.ts +77 -0
  28. package/src/browser/react/Link.tsx +67 -8
  29. package/src/browser/react/NavigationProvider.tsx +13 -4
  30. package/src/browser/react/context.ts +7 -2
  31. package/src/browser/react/use-handle.ts +9 -58
  32. package/src/browser/react/use-navigation.ts +22 -2
  33. package/src/browser/react/use-router.ts +21 -8
  34. package/src/browser/rsc-router.tsx +26 -3
  35. package/src/browser/scroll-restoration.ts +10 -8
  36. package/src/browser/segment-reconciler.ts +36 -14
  37. package/src/browser/server-action-bridge.ts +8 -6
  38. package/src/browser/types.ts +27 -5
  39. package/src/build/generate-manifest.ts +6 -6
  40. package/src/build/generate-route-types.ts +3 -0
  41. package/src/build/route-trie.ts +50 -24
  42. package/src/build/route-types/include-resolution.ts +8 -1
  43. package/src/build/route-types/router-processing.ts +211 -72
  44. package/src/build/route-types/scan-filter.ts +8 -1
  45. package/src/client.tsx +84 -230
  46. package/src/handle.ts +40 -0
  47. package/src/index.rsc.ts +3 -1
  48. package/src/index.ts +46 -6
  49. package/src/prerender/store.ts +5 -4
  50. package/src/prerender.ts +138 -77
  51. package/src/reverse.ts +25 -1
  52. package/src/route-definition/dsl-helpers.ts +194 -32
  53. package/src/route-definition/helpers-types.ts +67 -19
  54. package/src/route-definition/index.ts +3 -0
  55. package/src/route-definition/redirect.ts +9 -1
  56. package/src/route-definition/resolve-handler-use.ts +149 -0
  57. package/src/route-types.ts +18 -0
  58. package/src/router/content-negotiation.ts +100 -1
  59. package/src/router/handler-context.ts +51 -15
  60. package/src/router/intercept-resolution.ts +9 -4
  61. package/src/router/lazy-includes.ts +5 -5
  62. package/src/router/loader-resolution.ts +156 -21
  63. package/src/router/manifest.ts +22 -13
  64. package/src/router/match-api.ts +124 -189
  65. package/src/router/match-middleware/cache-lookup.ts +28 -8
  66. package/src/router/match-middleware/segment-resolution.ts +53 -0
  67. package/src/router/match-result.ts +82 -4
  68. package/src/router/middleware-types.ts +0 -6
  69. package/src/router/middleware.ts +0 -3
  70. package/src/router/navigation-snapshot.ts +182 -0
  71. package/src/router/prerender-match.ts +110 -10
  72. package/src/router/preview-match.ts +30 -102
  73. package/src/router/request-classification.ts +310 -0
  74. package/src/router/route-snapshot.ts +245 -0
  75. package/src/router/router-interfaces.ts +36 -4
  76. package/src/router/router-options.ts +37 -11
  77. package/src/router/segment-resolution/fresh.ts +71 -17
  78. package/src/router/segment-resolution/helpers.ts +29 -24
  79. package/src/router/segment-resolution/revalidation.ts +87 -18
  80. package/src/router/types.ts +1 -0
  81. package/src/router.ts +54 -5
  82. package/src/rsc/handler.ts +472 -372
  83. package/src/rsc/loader-fetch.ts +23 -3
  84. package/src/rsc/manifest-init.ts +5 -1
  85. package/src/rsc/progressive-enhancement.ts +14 -2
  86. package/src/rsc/rsc-rendering.ts +10 -1
  87. package/src/rsc/server-action.ts +8 -0
  88. package/src/rsc/ssr-setup.ts +2 -2
  89. package/src/rsc/types.ts +9 -1
  90. package/src/segment-content-promise.ts +67 -0
  91. package/src/segment-loader-promise.ts +122 -0
  92. package/src/segment-system.tsx +11 -61
  93. package/src/server/context.ts +65 -5
  94. package/src/server/handle-store.ts +19 -0
  95. package/src/server/loader-registry.ts +9 -8
  96. package/src/server/request-context.ts +134 -9
  97. package/src/ssr/index.tsx +3 -0
  98. package/src/static-handler.ts +18 -6
  99. package/src/types/cache-types.ts +4 -4
  100. package/src/types/handler-context.ts +30 -20
  101. package/src/types/loader-types.ts +36 -9
  102. package/src/types/route-entry.ts +12 -1
  103. package/src/types/segments.ts +1 -1
  104. package/src/urls/include-helper.ts +24 -14
  105. package/src/urls/path-helper-types.ts +39 -6
  106. package/src/urls/path-helper.ts +47 -12
  107. package/src/urls/pattern-types.ts +12 -0
  108. package/src/urls/response-types.ts +16 -6
  109. package/src/use-loader.tsx +77 -5
  110. package/src/vite/discovery/bundle-postprocess.ts +30 -33
  111. package/src/vite/discovery/discover-routers.ts +5 -1
  112. package/src/vite/discovery/prerender-collection.ts +128 -74
  113. package/src/vite/discovery/state.ts +13 -4
  114. package/src/vite/index.ts +4 -0
  115. package/src/vite/plugin-types.ts +60 -5
  116. package/src/vite/plugins/expose-id-utils.ts +12 -0
  117. package/src/vite/plugins/expose-ids/handler-transform.ts +30 -0
  118. package/src/vite/plugins/expose-internal-ids.ts +257 -40
  119. package/src/vite/plugins/performance-tracks.ts +88 -0
  120. package/src/vite/plugins/refresh-cmd.ts +88 -26
  121. package/src/vite/rango.ts +19 -2
  122. package/src/vite/router-discovery.ts +178 -37
  123. package/src/vite/utils/prerender-utils.ts +37 -5
  124. package/src/vite/utils/shared-utils.ts +3 -2
@@ -44,20 +44,21 @@ export function setLoaderImports(
44
44
  export async function getLoaderLazy(
45
45
  id: string,
46
46
  ): Promise<LoaderRegistryEntry | undefined> {
47
- // Check if already cached in main registry
48
- const existing = loaderRegistry.get(id);
49
- if (existing) {
50
- return existing;
51
- }
52
-
53
- // Check the fetchable loader registry (populated by createLoader)
47
+ // Always check fetchableLoaderRegistry first it's the source of truth.
48
+ // createLoader() updates it during module re-evaluation (HMR), so checking
49
+ // here ensures we pick up the fresh function after a loader file change.
54
50
  const fetchable = getFetchableLoader(id);
55
51
  if (fetchable) {
56
- // Cache in main registry for future requests
57
52
  loaderRegistry.set(id, fetchable);
58
53
  return fetchable;
59
54
  }
60
55
 
56
+ // Fall back to local cache (populated by previous lazy imports in production)
57
+ const existing = loaderRegistry.get(id);
58
+ if (existing) {
59
+ return existing;
60
+ }
61
+
61
62
  // Try to lazy load from the import map (production mode)
62
63
  if (lazyLoaderImports && lazyLoaderImports.size > 0) {
63
64
  const lazyImport = lazyLoaderImports.get(id);
@@ -24,12 +24,16 @@ import {
24
24
  type ContextVar,
25
25
  contextGet,
26
26
  contextSet,
27
- isContextVar,
28
27
  isNonCacheable,
29
28
  } from "../context-var.js";
30
- import { createHandleStore, type HandleStore } from "./handle-store.js";
29
+ import {
30
+ createHandleStore,
31
+ buildHandleSnapshot,
32
+ type HandleStore,
33
+ type HandleData,
34
+ } from "./handle-store.js";
31
35
  import { isHandle } from "../handle.js";
32
- import { track, RSCRouterContext, type MetricsStore } from "./context.js";
36
+ import { track, type MetricsStore } from "./context.js";
33
37
  import { getFetchableLoader } from "./fetchable-loader-store.js";
34
38
  import type { SegmentCacheStore } from "../cache/types.js";
35
39
  import type { Theme, ResolvedThemeConfig } from "../theme/types.js";
@@ -70,8 +74,8 @@ export interface RequestContext<
70
74
  pathname: string;
71
75
  /** URL search params (with internal `_rsc*` params stripped, same as `url.searchParams`) */
72
76
  searchParams: URLSearchParams;
73
- /** Variables set by middleware (same as ctx.var) */
74
- var: Record<string, any>;
77
+ /** @internal Shared variable backing store for ctx.get()/ctx.set(). */
78
+ _variables: Record<string, any>;
75
79
  /** Get a variable set by middleware */
76
80
  get: {
77
81
  <T>(contextVar: ContextVar<T>): T | undefined;
@@ -272,6 +276,54 @@ export interface RequestContext<
272
276
  /** @internal Previous route key (from the navigation source), used for revalidation */
273
277
  _prevRouteKey?: string;
274
278
 
279
+ /**
280
+ * @internal Render barrier for experimental `rendered()` API.
281
+ * Resolves when all non-loader segments have settled and handle data
282
+ * is available. Used by DSL loaders that call `ctx.rendered()`.
283
+ */
284
+ _renderBarrier: Promise<void>;
285
+
286
+ /**
287
+ * @internal Resolve the render barrier. Accepts resolved segments, filters
288
+ * out loaders, and captures non-loader segment IDs as the handle ordering.
289
+ * Called after segment resolution (fresh) or handle replay (cache/prerender).
290
+ */
291
+ _resolveRenderBarrier: (
292
+ segments: Array<{ type: string; id: string }>,
293
+ ) => void;
294
+
295
+ /**
296
+ * @internal Segment order at barrier resolution time, used by loader
297
+ * ctx.use(handle) to collect handle data in correct order.
298
+ */
299
+ _renderBarrierSegmentOrder?: string[];
300
+
301
+ /**
302
+ * @internal Set to true when the matched entry tree contains any `loading()`
303
+ * entries (streaming). Used by rendered() to fail fast.
304
+ */
305
+ _treeHasStreaming?: boolean;
306
+
307
+ /**
308
+ * @internal Loader IDs that have called rendered() and are waiting for the
309
+ * barrier. Used to detect deadlocks when a handler tries to await the same
310
+ * loader via ctx.use(Loader).
311
+ */
312
+ _renderBarrierWaiters?: Set<string>;
313
+
314
+ /**
315
+ * @internal Loader IDs that handlers have started awaiting via ctx.use().
316
+ * Used for bidirectional deadlock detection: if a loader later calls
317
+ * rendered() and a handler already awaits it, we can detect the deadlock.
318
+ */
319
+ _handlerLoaderDeps?: Set<string>;
320
+
321
+ /**
322
+ * @internal Cached HandleData snapshot built at barrier resolution time.
323
+ * Avoids rebuilding the snapshot on every loader ctx.use(handle) call.
324
+ */
325
+ _renderBarrierHandleSnapshot?: HandleData;
326
+
275
327
  /** @internal Per-request error dedup set for onError reporting */
276
328
  _reportedErrors: WeakSet<object>;
277
329
 
@@ -288,6 +340,15 @@ export interface RequestContext<
288
340
 
289
341
  /** @internal Request-scoped performance metrics store */
290
342
  _metricsStore?: MetricsStore;
343
+
344
+ /** @internal Router basename for this request (used by redirect()) */
345
+ _basename?: string;
346
+
347
+ /**
348
+ * @internal RouteSnapshot from classifyRequest, reused by match/matchPartial
349
+ * to avoid a second resolveRoute call. Cleared on HMR invalidation.
350
+ */
351
+ _classifiedRoute?: import("../router/route-snapshot.js").RouteSnapshot;
291
352
  }
292
353
 
293
354
  /**
@@ -314,10 +375,20 @@ export type PublicRequestContext<
314
375
  | "_routeName"
315
376
  | "_prevRouteKey"
316
377
  | "_reportedErrors"
378
+ | "_renderBarrier"
379
+ | "_resolveRenderBarrier"
380
+ | "_renderBarrierSegmentOrder"
381
+ | "_treeHasStreaming"
382
+ | "_renderBarrierWaiters"
383
+ | "_handlerLoaderDeps"
384
+ | "_renderBarrierHandleSnapshot"
317
385
  | "_reportBackgroundError"
318
386
  | "_debugPerformance"
319
387
  | "_metricsStore"
388
+ | "_basename"
320
389
  | "_setStatus"
390
+ | "_variables"
391
+ | "_classifiedRoute"
321
392
  | "res"
322
393
  >;
323
394
 
@@ -592,7 +663,7 @@ export function createRequestContext<TEnv>(
592
663
  originalUrl: new URL(request.url),
593
664
  pathname: url.pathname,
594
665
  searchParams: cleanUrl.searchParams,
595
- var: variables,
666
+ _variables: variables,
596
667
  get: ((keyOrVar: any) => {
597
668
  if (isNonCacheable(variables, keyOrVar) && isInsideCacheScope()) {
598
669
  throw new Error(
@@ -739,9 +810,58 @@ export function createRequestContext<TEnv>(
739
810
  _reportedErrors: new WeakSet<object>(),
740
811
  _metricsStore: undefined,
741
812
 
813
+ // Render barrier: deferred promise resolved after non-loader segments settle.
814
+ _renderBarrier: null as any, // set below
815
+ _resolveRenderBarrier: null as any, // set below
816
+ _renderBarrierSegmentOrder: undefined,
817
+
742
818
  reverse: createReverseFunction(getGlobalRouteMap(), undefined, {}),
743
819
  };
744
820
 
821
+ // Lazy render barrier: only allocate the Promise when a loader actually
822
+ // calls rendered(). Requests that don't use rendered() pay zero cost.
823
+ let barrierResolved = false;
824
+ let resolveBarrier: (() => void) | undefined;
825
+ ctx._renderBarrier = null as any; // lazy — created on first access
826
+ ctx._resolveRenderBarrier = (
827
+ segments: Array<{ type: string; id: string }>,
828
+ ) => {
829
+ if (barrierResolved) return;
830
+ barrierResolved = true;
831
+ const segOrder = segments
832
+ .filter((s) => s.type !== "loader")
833
+ .map((s) => s.id);
834
+ ctx._renderBarrierSegmentOrder = segOrder;
835
+ // Build and cache handle snapshot so loader ctx.use(handle) calls
836
+ // don't rebuild it on every invocation.
837
+ ctx._renderBarrierHandleSnapshot = buildHandleSnapshot(
838
+ handleStore,
839
+ segOrder,
840
+ );
841
+ ctx._renderBarrierWaiters = undefined;
842
+ ctx._handlerLoaderDeps = undefined;
843
+ if (resolveBarrier) resolveBarrier();
844
+ };
845
+ Object.defineProperty(ctx, "_renderBarrier", {
846
+ get() {
847
+ // Barrier already resolved (cache/prerender hit) or first lazy access.
848
+ // Either way, replace the getter with a concrete value to avoid
849
+ // repeated Promise.resolve() allocations on subsequent reads.
850
+ const p = barrierResolved
851
+ ? Promise.resolve()
852
+ : new Promise<void>((resolve) => {
853
+ resolveBarrier = resolve;
854
+ });
855
+ Object.defineProperty(ctx, "_renderBarrier", {
856
+ value: p,
857
+ writable: false,
858
+ configurable: false,
859
+ });
860
+ return p;
861
+ },
862
+ configurable: true,
863
+ });
864
+
745
865
  // Now create use() with access to ctx
746
866
  ctx.use = createUseFunction({
747
867
  handleStore,
@@ -924,14 +1044,13 @@ export function createUseFunction<TEnv>(
924
1044
  pathname: ctx.pathname,
925
1045
  url: ctx.url,
926
1046
  env: ctx.env as any,
927
- var: ctx.var as any,
928
1047
  get: ctx.get as any,
929
- use: <TDep, TDepParams = any>(
1048
+ use: (<TDep, TDepParams = any>(
930
1049
  dep: LoaderDefinition<TDep, TDepParams>,
931
1050
  ): Promise<TDep> => {
932
1051
  // Recursive call - will start dep loader if not already started
933
1052
  return ctx.use(dep);
934
- },
1053
+ }) as LoaderContext["use"],
935
1054
  method: "GET",
936
1055
  body: undefined,
937
1056
  reverse: createReverseFunction(
@@ -940,6 +1059,12 @@ export function createUseFunction<TEnv>(
940
1059
  ctx.params as Record<string, string>,
941
1060
  ctx._routeName ? isRouteRootScoped(ctx._routeName) : undefined,
942
1061
  ),
1062
+ rendered: () => {
1063
+ throw new Error(
1064
+ `ctx.rendered() is only available in DSL loaders (registered via loader() in urls()). ` +
1065
+ `It cannot be used from request-context loaders or server actions.`,
1066
+ );
1067
+ },
943
1068
  };
944
1069
 
945
1070
  const doneLoader = track(`loader:${loader.$$id}`, 2);
package/src/ssr/index.tsx CHANGED
@@ -129,6 +129,7 @@ interface RscPayload {
129
129
  matched?: string[];
130
130
  pathname?: string;
131
131
  params?: Record<string, string>;
132
+ basename?: string;
132
133
  themeConfig?: ResolvedThemeConfig | null;
133
134
  initialTheme?: Theme;
134
135
  version?: string;
@@ -261,6 +262,7 @@ export function createSSRHandler<TEnv = unknown>(deps: SSRDependencies<TEnv>) {
261
262
  function SsrRoot() {
262
263
  payload ??= createFromReadableStream<RscPayload>(rscStream1);
263
264
  const resolved = React.use(payload);
265
+
264
266
  const themeConfig = resolved.metadata?.themeConfig ?? null;
265
267
  const pathname = resolved.metadata?.pathname ?? "/";
266
268
 
@@ -286,6 +288,7 @@ export function createSSRHandler<TEnv = unknown>(deps: SSRDependencies<TEnv>) {
286
288
  navigate: async () => {},
287
289
  refresh: async () => {},
288
290
  version: resolved.metadata?.version,
291
+ basename: resolved.metadata?.basename,
289
292
  };
290
293
 
291
294
  // Build content tree from segments.
@@ -32,11 +32,21 @@
32
32
  */
33
33
  import type { ReactNode } from "react";
34
34
  import type { Handler } from "./types.js";
35
- import type { PrerenderOptions, StaticBuildContext } from "./prerender.js";
35
+ import type { StaticBuildContext } from "./prerender.js";
36
+ import type { UseItems, HandlerUseItem } from "./route-types.js";
36
37
  import { isCachedFunction } from "./cache/taint.js";
37
38
 
38
39
  // -- Types ------------------------------------------------------------------
39
40
 
41
+ export interface StaticHandlerOptions {
42
+ /**
43
+ * Keep handler in server bundle for live fallback (default: false).
44
+ * false: handler replaced with stub, source-only APIs excluded from bundle.
45
+ * true: handler stays in bundle, renders live at request time.
46
+ */
47
+ passthrough?: boolean;
48
+ }
49
+
40
50
  export interface StaticHandlerDefinition<
41
51
  TParams extends Record<string, any> = any,
42
52
  > {
@@ -46,14 +56,16 @@ export interface StaticHandlerDefinition<
46
56
  /** In dev mode, the actual handler function that layout/path/parallel can call. */
47
57
  handler: Handler<TParams>;
48
58
  /** Static handler options (passthrough support). */
49
- options?: PrerenderOptions;
59
+ options?: StaticHandlerOptions;
60
+ /** Composable default DSL items merged when the handler is mounted. */
61
+ use?: () => UseItems<HandlerUseItem>;
50
62
  }
51
63
 
52
64
  // -- Function ---------------------------------------------------------------
53
65
 
54
66
  export function Static<TParams extends Record<string, any> = {}>(
55
67
  handler: (ctx: StaticBuildContext) => ReactNode | Promise<ReactNode>,
56
- options?: PrerenderOptions,
68
+ options?: StaticHandlerOptions,
57
69
  __injectedId?: string,
58
70
  ): StaticHandlerDefinition<TParams>;
59
71
 
@@ -61,7 +73,7 @@ export function Static<TParams extends Record<string, any> = {}>(
61
73
 
62
74
  export function Static<TParams extends Record<string, any>>(
63
75
  handler: Function,
64
- optionsOrId?: PrerenderOptions | string,
76
+ optionsOrId?: StaticHandlerOptions | string,
65
77
  maybeId?: string,
66
78
  ): StaticHandlerDefinition<TParams> {
67
79
  if (isCachedFunction(handler)) {
@@ -72,13 +84,13 @@ export function Static<TParams extends Record<string, any>>(
72
84
  );
73
85
  }
74
86
 
75
- let options: PrerenderOptions | undefined;
87
+ let options: StaticHandlerOptions | undefined;
76
88
  let id: string;
77
89
 
78
90
  if (typeof optionsOrId === "string") {
79
91
  id = optionsOrId;
80
92
  } else {
81
- options = optionsOrId as PrerenderOptions | undefined;
93
+ options = optionsOrId as StaticHandlerOptions | undefined;
82
94
  id = maybeId ?? "";
83
95
  }
84
96
 
@@ -5,8 +5,8 @@
5
5
  * during cache key generation (before middleware runs).
6
6
  *
7
7
  * Note: While the full RequestContext is passed, middleware-set variables
8
- * (ctx.var, ctx.get()) may not be populated yet since cache lookup
9
- * happens before middleware execution.
8
+ * read via `ctx.get()` may not be populated yet since cache lookup happens
9
+ * before middleware execution.
10
10
  */
11
11
  export type { RequestContext as CacheContext } from "../server/request-context.js";
12
12
 
@@ -101,7 +101,7 @@ export interface CacheOptions<TEnv = unknown> {
101
101
  * Return false to skip cache for this request (always fetch fresh).
102
102
  *
103
103
  * Has access to full RequestContext including env, request, params, cookies, etc.
104
- * Note: Middleware-set variables (ctx.var) may not be populated yet.
104
+ * Note: Middleware-set variables read via `ctx.get()` may not be populated yet.
105
105
  *
106
106
  * @example
107
107
  * ```typescript
@@ -123,7 +123,7 @@ export interface CacheOptions<TEnv = unknown> {
123
123
  * Bypasses default key generation AND store's keyGenerator.
124
124
  *
125
125
  * Has access to full RequestContext including env, request, params, cookies, etc.
126
- * Note: Middleware-set variables (ctx.var) may not be populated yet.
126
+ * Note: Middleware-set variables read via `ctx.get()` may not be populated yet.
127
127
  *
128
128
  * @example
129
129
  * ```typescript
@@ -19,6 +19,7 @@ import type {
19
19
  ResolvedRouteMap,
20
20
  } from "./route-config.js";
21
21
  import type { LoaderDefinition } from "./loader-types.js";
22
+ import type { UseItems, HandlerUseItem } from "../route-types.js";
22
23
 
23
24
  // Re-export MiddlewareFn for internal/advanced use
24
25
  export type { MiddlewareFn } from "../router/middleware.js";
@@ -135,7 +136,7 @@ export type Handler<
135
136
  | Record<string, any> = {},
136
137
  TRouteMap extends {} = DefaultHandlerRouteMap,
137
138
  TEnv = DefaultEnv,
138
- > = (
139
+ > = ((
139
140
  ctx: HandlerContext<
140
141
  T extends `.${infer Local}`
141
142
  ? Local extends keyof TRouteMap
@@ -160,7 +161,10 @@ export type Handler<
160
161
  : ExtractSearchFromEntry<DefaultHandlerRouteMap, T>,
161
162
  TRouteMap extends DefaultHandlerRouteMap ? never : TRouteMap
162
163
  >,
163
- ) => ReactNode | Promise<ReactNode> | Response | Promise<Response>;
164
+ ) => ReactNode | Promise<ReactNode> | Response | Promise<Response>) & {
165
+ /** Composable default DSL items merged when the handler is mounted. */
166
+ use?: () => UseItems<HandlerUseItem>;
167
+ };
164
168
 
165
169
  /**
166
170
  * Context passed to handlers (Hono-inspired type-safe context)
@@ -170,7 +174,7 @@ export type Handler<
170
174
  * - Cleaned route URL (`url`, `searchParams`, `pathname` — no `_rsc*` params)
171
175
  * - Original request (`request` — raw transport URL, headers, method, body)
172
176
  * - Platform bindings (env.DB, env.KV, env.SECRETS)
173
- * - Middleware variables (var.user, var.permissions)
177
+ * - Middleware variables (`get("user")`, `get("permissions")`)
174
178
  * - Getter/setter for variables (get('user'), set('user', ...))
175
179
  *
176
180
  * @example
@@ -178,8 +182,7 @@ export type Handler<
178
182
  * const handler = (ctx: HandlerContext<{ slug: string }, AppEnv>) => {
179
183
  * ctx.params.slug // Route param (string)
180
184
  * ctx.env.DB // Binding (D1Database)
181
- * ctx.var.user // Variable (User | undefined)
182
- * ctx.get('user') // Alternative getter
185
+ * ctx.get('user') // Variable (User | undefined)
183
186
  * ctx.set('user', {...}) // Setter
184
187
  * ctx.url // Clean URL (no _rsc* params)
185
188
  * ctx.searchParams // Clean params (no _rsc* params)
@@ -206,6 +209,12 @@ export type HandlerContext<
206
209
  * Live request rendering, including passthrough fallback, uses `false`.
207
210
  */
208
211
  build: boolean;
212
+ /**
213
+ * True when running in Vite dev mode, false during production build or
214
+ * live request rendering. Use this to branch on runtime mode without
215
+ * changing build semantics (e.g., skip expensive operations in dev).
216
+ */
217
+ dev: boolean;
209
218
  /**
210
219
  * The original incoming Request object (transport URL intact).
211
220
  * Use `ctx.url` / `ctx.searchParams` for application logic — those have
@@ -244,14 +253,9 @@ export type HandlerContext<
244
253
  * Access resources like `ctx.env.DB`, `ctx.env.KV`.
245
254
  */
246
255
  env: TEnv;
247
- /**
248
- * Middleware-injected variables.
249
- * Access values like `ctx.var.user`, `ctx.var.permissions`.
250
- */
251
- var: DefaultVars;
252
256
  /**
253
257
  * Type-safe getter for middleware variables.
254
- * Alternative to `ctx.var.key` with better autocomplete.
258
+ * Preferred way to read middleware-injected variables.
255
259
  *
256
260
  * @example
257
261
  * ```typescript
@@ -277,9 +281,9 @@ export type HandlerContext<
277
281
  value: T,
278
282
  options?: { cache?: boolean },
279
283
  ): void;
280
- } & ((
281
- key: keyof DefaultVars,
282
- value: DefaultVars[keyof DefaultVars],
284
+ } & (<K extends keyof DefaultVars>(
285
+ key: K,
286
+ value: DefaultVars[K],
283
287
  options?: { cache?: boolean },
284
288
  ) => void);
285
289
  /**
@@ -301,8 +305,11 @@ export type HandlerContext<
301
305
  * and server components rendered within the request context.
302
306
  *
303
307
  * For loaders: Returns a promise that resolves to the loader data.
304
- * Loaders are executed in parallel and memoized per request — calling
305
- * `ctx.use(SameLoader)` multiple times returns the same promise.
308
+ * Loaders are executed in parallel and memoized per request.
309
+ * Prefer DSL `loader()` + client `useLoader()` over `ctx.use(Loader)`
310
+ * DSL loaders are always fresh and cache-safe. Use `ctx.use(Loader)` only
311
+ * when you need loader data in the handler itself (e.g., to set context
312
+ * variables or make routing decisions).
306
313
  *
307
314
  * For handles: Returns a push function to add data for this segment.
308
315
  * Handle data accumulates across all matched route segments.
@@ -310,10 +317,11 @@ export type HandlerContext<
310
317
  *
311
318
  * @example
312
319
  * ```typescript
313
- * // Loader usage
314
- * route("cart", async (ctx) => {
315
- * const cart = await ctx.use(CartLoader);
316
- * return <CartPage cart={cart} />;
320
+ * // Loader escape hatch — use when handler needs the data directly
321
+ * route("product", async (ctx) => {
322
+ * const { product } = await ctx.use(ProductLoader);
323
+ * ctx.set(Product, product); // make available to children
324
+ * return <ProductPage />;
317
325
  * });
318
326
  *
319
327
  * // Handle usage - direct value
@@ -444,6 +452,8 @@ export type InternalHandlerContext<
444
452
  > = HandlerContext<TParams, TEnv, TSearch> & {
445
453
  /** @internal Stub response for collecting headers/cookies. */
446
454
  res: Response;
455
+ /** @internal Shared variable backing store for ctx.get()/ctx.set(). */
456
+ _variables: Record<string, any>;
447
457
  /** Prerender-only control flow helper, attached when the runtime context supports it. */
448
458
  passthrough?: () => unknown;
449
459
  /** Current segment ID for handle data attribution. */
@@ -1,4 +1,5 @@
1
1
  import type { ContextVar } from "../context-var.js";
2
+ import type { Handle } from "../handle.js";
2
3
  import type { MiddlewareFn } from "../router/middleware.js";
3
4
  import type { ScopedReverseFunction } from "../reverse.js";
4
5
  import type { SearchSchema, ResolveSearchSchema } from "../search-params.js";
@@ -53,16 +54,42 @@ export type LoaderContext<
53
54
  pathname: string;
54
55
  url: URL;
55
56
  env: TEnv;
56
- var: DefaultVars;
57
57
  get: {
58
58
  <T>(contextVar: ContextVar<T>): T | undefined;
59
59
  } & (<K extends keyof DefaultVars>(key: K) => DefaultVars[K]);
60
60
  /**
61
- * Access another loader's data (returns promise since loaders run in parallel)
61
+ * Access another loader's data, or read handle data after rendered().
62
+ *
63
+ * For loaders: returns a promise (loaders run in parallel).
64
+ * For handles: returns collected data (only after `await ctx.rendered()`).
62
65
  */
63
- use: <T, TLoaderParams = any>(
64
- loader: LoaderDefinition<T, TLoaderParams>,
65
- ) => Promise<T>;
66
+ use: {
67
+ <T, TLoaderParams = any>(
68
+ loader: LoaderDefinition<T, TLoaderParams>,
69
+ ): Promise<T>;
70
+ <TData, TAccumulated = TData[]>(
71
+ handle: Handle<TData, TAccumulated>,
72
+ ): TAccumulated;
73
+ };
74
+ /**
75
+ * **Experimental.** Wait for all non-loader segments to settle.
76
+ *
77
+ * After the returned promise resolves, handle data is available via
78
+ * `ctx.use(handle)`. Only supported in DSL loaders on non-streaming
79
+ * trees (no `loading()`). Throws if called from a handler-invoked
80
+ * loader or when the tree uses streaming.
81
+ *
82
+ * @example
83
+ * ```typescript
84
+ * const PricesLoader = createLoader(async (ctx) => {
85
+ * "use server";
86
+ * await ctx.rendered();
87
+ * const products = ctx.use(Products); // reads handle data
88
+ * return pricing.getLive(products.map(p => p.id));
89
+ * });
90
+ * ```
91
+ */
92
+ rendered: () => Promise<void>;
66
93
  /**
67
94
  * HTTP method (GET, POST, PUT, PATCH, DELETE)
68
95
  * Available when loader is called via load({ method: "POST", ... })
@@ -166,11 +193,11 @@ export type LoadOptions =
166
193
  * return await db.products.findBySlug(slug);
167
194
  * });
168
195
  *
169
- * // Server usage
170
- * const cart = ctx.use(CartLoader);
196
+ * // Client usage (preferred — cache-safe, always fresh)
197
+ * const { data } = useLoader(CartLoader);
171
198
  *
172
- * // Client usage (fn is stripped, only name remains)
173
- * const cart = useLoader(CartLoader);
199
+ * // Server escape hatch (handler needs data directly)
200
+ * const cart = await ctx.use(CartLoader);
174
201
  * ```
175
202
  */
176
203
  export type LoaderDefinition<
@@ -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
  /**
@@ -69,7 +80,7 @@ export interface RouteEntry<TEnv = any> {
69
80
  prerenderRouteKeys?: Set<string>;
70
81
 
71
82
  /**
72
- * Route keys in this entry that use `{ passthrough: true }`.
83
+ * Route keys in this entry that are wrapped with `Passthrough()`.
73
84
  * Used by the non-trie match path to set the `pt` flag.
74
85
  */
75
86
  passthroughRouteKeys?: Set<string>;
@@ -50,12 +50,12 @@ export interface ResolvedSegment {
50
50
  parallelName?: string; // For parallels: the parallel group name (used to match with revalidations)
51
51
  // Loader-specific fields
52
52
  loaderId?: string; // For loaders: the loader $$id identifier
53
+ _inherited?: boolean; // For inherited loaders: dedup marker for buildMatchResult
53
54
  loaderData?: any; // For loaders: the resolved data from loader execution
54
55
  parallelLoading?: ReactNode; // For parallel-owned loaders: the parallel's loading fallback
55
56
  // Intercept loader fields (for streaming loader data in parallel segments)
56
57
  loaderDataPromise?: Promise<any[]> | any[]; // Loader data promise or resolved array
57
58
  loaderIds?: string[]; // IDs ($$id) of loaders for this segment
58
- parallelLoaderSources?: any[]; // Internal: preserves stable aggregate promise across renders
59
59
  // Error-specific fields
60
60
  error?: ErrorInfo; // For error segments: the error information
61
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
  };