@rangojs/router 0.0.0-experimental.7 → 0.0.0-experimental.70
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.
- package/AGENTS.md +9 -0
- package/README.md +942 -4
- package/dist/bin/rango.js +1689 -0
- package/dist/vite/index.js +4951 -930
- package/package.json +70 -60
- package/skills/breadcrumbs/SKILL.md +250 -0
- package/skills/cache-guide/SKILL.md +294 -0
- package/skills/caching/SKILL.md +93 -23
- package/skills/composability/SKILL.md +172 -0
- package/skills/debug-manifest/SKILL.md +12 -8
- package/skills/document-cache/SKILL.md +18 -16
- package/skills/fonts/SKILL.md +167 -0
- package/skills/hooks/SKILL.md +334 -72
- package/skills/host-router/SKILL.md +218 -0
- package/skills/intercept/SKILL.md +131 -8
- package/skills/layout/SKILL.md +100 -3
- package/skills/links/SKILL.md +92 -31
- package/skills/loader/SKILL.md +404 -44
- package/skills/middleware/SKILL.md +173 -34
- package/skills/mime-routes/SKILL.md +128 -0
- package/skills/parallel/SKILL.md +204 -1
- package/skills/prerender/SKILL.md +685 -0
- package/skills/rango/SKILL.md +85 -16
- package/skills/response-routes/SKILL.md +411 -0
- package/skills/route/SKILL.md +257 -14
- package/skills/router-setup/SKILL.md +210 -32
- package/skills/tailwind/SKILL.md +129 -0
- package/skills/theme/SKILL.md +9 -8
- package/skills/typesafety/SKILL.md +328 -89
- package/skills/use-cache/SKILL.md +324 -0
- package/src/__internal.ts +102 -4
- package/src/bin/rango.ts +321 -0
- package/src/browser/action-coordinator.ts +97 -0
- package/src/browser/action-response-classifier.ts +99 -0
- package/src/browser/app-version.ts +14 -0
- package/src/browser/event-controller.ts +92 -64
- package/src/browser/history-state.ts +80 -0
- package/src/browser/intercept-utils.ts +52 -0
- package/src/browser/link-interceptor.ts +24 -4
- package/src/browser/logging.ts +55 -0
- package/src/browser/merge-segment-loaders.ts +20 -12
- package/src/browser/navigation-bridge.ts +296 -558
- package/src/browser/navigation-client.ts +179 -69
- package/src/browser/navigation-store.ts +73 -55
- package/src/browser/navigation-transaction.ts +297 -0
- package/src/browser/network-error-handler.ts +61 -0
- package/src/browser/partial-update.ts +328 -313
- package/src/browser/prefetch/cache.ts +206 -0
- package/src/browser/prefetch/fetch.ts +150 -0
- package/src/browser/prefetch/observer.ts +65 -0
- package/src/browser/prefetch/policy.ts +48 -0
- package/src/browser/prefetch/queue.ts +160 -0
- package/src/browser/prefetch/resource-ready.ts +77 -0
- package/src/browser/rango-state.ts +112 -0
- package/src/browser/react/Link.tsx +230 -74
- package/src/browser/react/NavigationProvider.tsx +87 -11
- package/src/browser/react/context.ts +11 -0
- package/src/browser/react/filter-segment-order.ts +11 -0
- package/src/browser/react/index.ts +12 -12
- package/src/browser/react/location-state-shared.ts +95 -53
- package/src/browser/react/location-state.ts +60 -15
- package/src/browser/react/mount-context.ts +6 -1
- package/src/browser/react/nonce-context.ts +23 -0
- package/src/browser/react/shallow-equal.ts +27 -0
- package/src/browser/react/use-action.ts +29 -51
- package/src/browser/react/use-client-cache.ts +5 -3
- package/src/browser/react/use-handle.ts +30 -126
- package/src/browser/react/use-href.tsx +2 -2
- package/src/browser/react/use-link-status.ts +6 -5
- package/src/browser/react/use-navigation.ts +22 -63
- package/src/browser/react/use-params.ts +65 -0
- package/src/browser/react/use-pathname.ts +47 -0
- package/src/browser/react/use-router.ts +76 -0
- package/src/browser/react/use-search-params.ts +56 -0
- package/src/browser/react/use-segments.ts +80 -97
- package/src/browser/response-adapter.ts +73 -0
- package/src/browser/rsc-router.tsx +214 -58
- package/src/browser/scroll-restoration.ts +127 -52
- package/src/browser/segment-reconciler.ts +221 -0
- package/src/browser/segment-structure-assert.ts +16 -0
- package/src/browser/server-action-bridge.ts +510 -603
- package/src/browser/shallow.ts +6 -1
- package/src/browser/types.ts +141 -48
- package/src/browser/validate-redirect-origin.ts +29 -0
- package/src/build/generate-manifest.ts +235 -24
- package/src/build/generate-route-types.ts +39 -0
- package/src/build/index.ts +13 -0
- package/src/build/route-trie.ts +265 -0
- package/src/build/route-types/ast-helpers.ts +25 -0
- package/src/build/route-types/ast-route-extraction.ts +98 -0
- package/src/build/route-types/codegen.ts +102 -0
- package/src/build/route-types/include-resolution.ts +418 -0
- package/src/build/route-types/param-extraction.ts +48 -0
- package/src/build/route-types/per-module-writer.ts +128 -0
- package/src/build/route-types/router-processing.ts +618 -0
- package/src/build/route-types/scan-filter.ts +85 -0
- package/src/build/runtime-discovery.ts +231 -0
- package/src/cache/background-task.ts +34 -0
- package/src/cache/cache-key-utils.ts +44 -0
- package/src/cache/cache-policy.ts +125 -0
- package/src/cache/cache-runtime.ts +342 -0
- package/src/cache/cache-scope.ts +167 -309
- package/src/cache/cf/cf-cache-store.ts +571 -17
- package/src/cache/cf/index.ts +13 -3
- package/src/cache/document-cache.ts +116 -77
- package/src/cache/handle-capture.ts +81 -0
- package/src/cache/handle-snapshot.ts +41 -0
- package/src/cache/index.ts +1 -15
- package/src/cache/memory-segment-store.ts +191 -13
- package/src/cache/profile-registry.ts +73 -0
- package/src/cache/read-through-swr.ts +134 -0
- package/src/cache/segment-codec.ts +256 -0
- package/src/cache/taint.ts +153 -0
- package/src/cache/types.ts +72 -122
- package/src/client.rsc.tsx +3 -1
- package/src/client.tsx +105 -179
- package/src/component-utils.ts +4 -4
- package/src/components/DefaultDocument.tsx +5 -1
- package/src/context-var.ts +156 -0
- package/src/debug.ts +19 -9
- package/src/errors.ts +108 -2
- package/src/handle.ts +55 -29
- package/src/handles/MetaTags.tsx +73 -20
- package/src/handles/breadcrumbs.ts +66 -0
- package/src/handles/index.ts +1 -0
- package/src/handles/meta.ts +30 -13
- package/src/host/cookie-handler.ts +21 -15
- package/src/host/errors.ts +8 -8
- package/src/host/index.ts +4 -7
- package/src/host/pattern-matcher.ts +27 -27
- package/src/host/router.ts +61 -39
- package/src/host/testing.ts +8 -8
- package/src/host/types.ts +15 -7
- package/src/host/utils.ts +1 -1
- package/src/href-client.ts +119 -29
- package/src/index.rsc.ts +155 -19
- package/src/index.ts +223 -30
- package/src/internal-debug.ts +11 -0
- package/src/loader.rsc.ts +26 -157
- package/src/loader.ts +27 -10
- package/src/network-error-thrower.tsx +3 -1
- package/src/outlet-provider.tsx +45 -0
- package/src/prerender/param-hash.ts +37 -0
- package/src/prerender/store.ts +186 -0
- package/src/prerender.ts +524 -0
- package/src/reverse.ts +351 -0
- package/src/root-error-boundary.tsx +41 -29
- package/src/route-content-wrapper.tsx +7 -4
- package/src/route-definition/dsl-helpers.ts +982 -0
- package/src/route-definition/helper-factories.ts +200 -0
- package/src/route-definition/helpers-types.ts +434 -0
- package/src/route-definition/index.ts +55 -0
- package/src/route-definition/redirect.ts +101 -0
- package/src/route-definition/resolve-handler-use.ts +149 -0
- package/src/route-definition.ts +1 -1428
- package/src/route-map-builder.ts +217 -123
- package/src/route-name.ts +53 -0
- package/src/route-types.ts +70 -8
- package/src/router/content-negotiation.ts +215 -0
- package/src/router/debug-manifest.ts +72 -0
- package/src/router/error-handling.ts +9 -9
- package/src/router/find-match.ts +160 -0
- package/src/router/handler-context.ts +435 -86
- package/src/router/intercept-resolution.ts +402 -0
- package/src/router/lazy-includes.ts +237 -0
- package/src/router/loader-resolution.ts +356 -128
- package/src/router/logging.ts +251 -0
- package/src/router/manifest.ts +154 -35
- package/src/router/match-api.ts +555 -0
- package/src/router/match-context.ts +5 -3
- package/src/router/match-handlers.ts +440 -0
- package/src/router/match-middleware/background-revalidation.ts +108 -93
- package/src/router/match-middleware/cache-lookup.ts +459 -10
- package/src/router/match-middleware/cache-store.ts +98 -26
- package/src/router/match-middleware/intercept-resolution.ts +57 -17
- package/src/router/match-middleware/segment-resolution.ts +80 -6
- package/src/router/match-pipelines.ts +10 -45
- package/src/router/match-result.ts +55 -33
- package/src/router/metrics.ts +240 -15
- package/src/router/middleware-cookies.ts +55 -0
- package/src/router/middleware-types.ts +220 -0
- package/src/router/middleware.ts +324 -369
- package/src/router/navigation-snapshot.ts +182 -0
- package/src/router/pattern-matching.ts +211 -43
- package/src/router/prerender-match.ts +502 -0
- package/src/router/preview-match.ts +98 -0
- package/src/router/request-classification.ts +310 -0
- package/src/router/revalidation.ts +137 -38
- package/src/router/route-snapshot.ts +245 -0
- package/src/router/router-context.ts +41 -21
- package/src/router/router-interfaces.ts +484 -0
- package/src/router/router-options.ts +618 -0
- package/src/router/router-registry.ts +24 -0
- package/src/router/segment-resolution/fresh.ts +743 -0
- package/src/router/segment-resolution/helpers.ts +268 -0
- package/src/router/segment-resolution/loader-cache.ts +199 -0
- package/src/router/segment-resolution/revalidation.ts +1373 -0
- package/src/router/segment-resolution/static-store.ts +67 -0
- package/src/router/segment-resolution.ts +21 -0
- package/src/router/segment-wrappers.ts +291 -0
- package/src/router/telemetry-otel.ts +299 -0
- package/src/router/telemetry.ts +300 -0
- package/src/router/timeout.ts +148 -0
- package/src/router/trie-matching.ts +239 -0
- package/src/router/types.ts +78 -3
- package/src/router.ts +740 -4252
- package/src/rsc/handler-context.ts +45 -0
- package/src/rsc/handler.ts +907 -797
- package/src/rsc/helpers.ts +140 -6
- package/src/rsc/index.ts +0 -20
- package/src/rsc/loader-fetch.ts +229 -0
- package/src/rsc/manifest-init.ts +90 -0
- package/src/rsc/nonce.ts +14 -0
- package/src/rsc/origin-guard.ts +141 -0
- package/src/rsc/progressive-enhancement.ts +391 -0
- package/src/rsc/response-error.ts +37 -0
- package/src/rsc/response-route-handler.ts +347 -0
- package/src/rsc/rsc-rendering.ts +246 -0
- package/src/rsc/runtime-warnings.ts +42 -0
- package/src/rsc/server-action.ts +356 -0
- package/src/rsc/ssr-setup.ts +128 -0
- package/src/rsc/types.ts +46 -11
- package/src/search-params.ts +230 -0
- package/src/segment-system.tsx +165 -17
- package/src/server/context.ts +315 -58
- package/src/server/cookie-store.ts +190 -0
- package/src/server/fetchable-loader-store.ts +37 -0
- package/src/server/handle-store.ts +113 -15
- package/src/server/loader-registry.ts +24 -64
- package/src/server/request-context.ts +607 -81
- package/src/server.ts +35 -130
- package/src/ssr/index.tsx +103 -30
- package/src/static-handler.ts +126 -0
- package/src/theme/ThemeProvider.tsx +21 -15
- package/src/theme/ThemeScript.tsx +5 -5
- package/src/theme/constants.ts +5 -2
- package/src/theme/index.ts +4 -14
- package/src/theme/theme-context.ts +4 -30
- package/src/theme/theme-script.ts +21 -18
- package/src/types/boundaries.ts +158 -0
- package/src/types/cache-types.ts +198 -0
- package/src/types/error-types.ts +192 -0
- package/src/types/global-namespace.ts +100 -0
- package/src/types/handler-context.ts +791 -0
- package/src/types/index.ts +88 -0
- package/src/types/loader-types.ts +210 -0
- package/src/types/route-config.ts +170 -0
- package/src/types/route-entry.ts +109 -0
- package/src/types/segments.ts +150 -0
- package/src/types.ts +1 -1623
- package/src/urls/include-helper.ts +197 -0
- package/src/urls/index.ts +53 -0
- package/src/urls/path-helper-types.ts +346 -0
- package/src/urls/path-helper.ts +364 -0
- package/src/urls/pattern-types.ts +107 -0
- package/src/urls/response-types.ts +116 -0
- package/src/urls/type-extraction.ts +372 -0
- package/src/urls/urls-function.ts +98 -0
- package/src/urls.ts +1 -802
- package/src/use-loader.tsx +161 -81
- package/src/vite/discovery/bundle-postprocess.ts +181 -0
- package/src/vite/discovery/discover-routers.ts +348 -0
- package/src/vite/discovery/prerender-collection.ts +439 -0
- package/src/vite/discovery/route-types-writer.ts +258 -0
- package/src/vite/discovery/self-gen-tracking.ts +47 -0
- package/src/vite/discovery/state.ts +117 -0
- package/src/vite/discovery/virtual-module-codegen.ts +203 -0
- package/src/vite/index.ts +15 -1129
- package/src/vite/plugin-types.ts +103 -0
- package/src/vite/plugins/cjs-to-esm.ts +93 -0
- package/src/vite/plugins/client-ref-dedup.ts +115 -0
- package/src/vite/plugins/client-ref-hashing.ts +105 -0
- package/src/vite/{expose-action-id.ts → plugins/expose-action-id.ts} +72 -53
- package/src/vite/plugins/expose-id-utils.ts +299 -0
- package/src/vite/plugins/expose-ids/export-analysis.ts +296 -0
- package/src/vite/plugins/expose-ids/handler-transform.ts +209 -0
- package/src/vite/plugins/expose-ids/loader-transform.ts +74 -0
- package/src/vite/plugins/expose-ids/router-transform.ts +110 -0
- package/src/vite/plugins/expose-ids/types.ts +45 -0
- package/src/vite/plugins/expose-internal-ids.ts +786 -0
- package/src/vite/plugins/performance-tracks.ts +88 -0
- package/src/vite/plugins/refresh-cmd.ts +127 -0
- package/src/vite/plugins/use-cache-transform.ts +323 -0
- package/src/vite/plugins/version-injector.ts +83 -0
- package/src/vite/plugins/version-plugin.ts +266 -0
- package/src/vite/{virtual-entries.ts → plugins/virtual-entries.ts} +23 -14
- package/src/vite/plugins/virtual-stub-plugin.ts +29 -0
- package/src/vite/rango.ts +462 -0
- package/src/vite/router-discovery.ts +918 -0
- package/src/vite/utils/ast-handler-extract.ts +517 -0
- package/src/vite/utils/banner.ts +36 -0
- package/src/vite/utils/bundle-analysis.ts +137 -0
- package/src/vite/utils/manifest-utils.ts +70 -0
- package/src/vite/{package-resolution.ts → utils/package-resolution.ts} +25 -29
- package/src/vite/utils/prerender-utils.ts +207 -0
- package/src/vite/utils/shared-utils.ts +170 -0
- package/CLAUDE.md +0 -43
- package/src/browser/lru-cache.ts +0 -69
- package/src/browser/request-controller.ts +0 -164
- package/src/cache/memory-store.ts +0 -253
- package/src/href-context.ts +0 -33
- package/src/href.ts +0 -255
- package/src/server/route-manifest-cache.ts +0 -173
- package/src/vite/expose-handle-id.ts +0 -209
- package/src/vite/expose-loader-id.ts +0 -426
- package/src/vite/expose-location-state-id.ts +0 -177
- /package/src/vite/{version.d.ts → plugins/version.d.ts} +0 -0
|
@@ -0,0 +1,791 @@
|
|
|
1
|
+
import type { ReactNode } from "react";
|
|
2
|
+
import type { Handle } from "../handle.js";
|
|
3
|
+
import type { ContextVar } from "../context-var.js";
|
|
4
|
+
import type { MiddlewareFn } from "../router/middleware.js";
|
|
5
|
+
import type { Theme } from "../theme/types.js";
|
|
6
|
+
import type { ScopedReverseFunction } from "../reverse.js";
|
|
7
|
+
import type { SearchSchema, ResolveSearchSchema } from "../search-params.js";
|
|
8
|
+
import type { LocationStateEntry } from "../browser/react/location-state-shared.js";
|
|
9
|
+
import type {
|
|
10
|
+
DefaultEnv,
|
|
11
|
+
DefaultHandlerRouteMap,
|
|
12
|
+
DefaultReverseRouteMap,
|
|
13
|
+
DefaultRouteName,
|
|
14
|
+
DefaultVars,
|
|
15
|
+
} from "./global-namespace.js";
|
|
16
|
+
import type {
|
|
17
|
+
ExtractParams,
|
|
18
|
+
RouteDefinition,
|
|
19
|
+
ResolvedRouteMap,
|
|
20
|
+
} from "./route-config.js";
|
|
21
|
+
import type { LoaderDefinition } from "./loader-types.js";
|
|
22
|
+
import type { UseItems, HandlerUseItem } from "../route-types.js";
|
|
23
|
+
|
|
24
|
+
// Re-export MiddlewareFn for internal/advanced use
|
|
25
|
+
export type { MiddlewareFn } from "../router/middleware.js";
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* Create a scoped view of a route map by stripping a name prefix.
|
|
29
|
+
* Useful for handlers in modules mounted via include() -- use the local
|
|
30
|
+
* route name instead of the fully qualified global name.
|
|
31
|
+
*
|
|
32
|
+
* @example
|
|
33
|
+
* ```typescript
|
|
34
|
+
* // Given GeneratedRouteMap: { "blog.index": "/blog"; "blog.post": "/blog/:postId"; ... }
|
|
35
|
+
* type BlogRoutes = ScopedRouteMap<"blog">;
|
|
36
|
+
* // Resolves to: { "index": "/blog"; "post": "/blog/:postId" }
|
|
37
|
+
*
|
|
38
|
+
* const handler: Handler<"post", BlogRoutes> = (ctx) => {
|
|
39
|
+
* ctx.params.postId // string
|
|
40
|
+
* };
|
|
41
|
+
* ```
|
|
42
|
+
*/
|
|
43
|
+
export type ScopedRouteMap<
|
|
44
|
+
TPrefix extends string,
|
|
45
|
+
TMap = RSCRouter.GeneratedRouteMap,
|
|
46
|
+
> = {
|
|
47
|
+
[K in keyof TMap as K extends `${TPrefix}.${infer Rest}`
|
|
48
|
+
? Rest
|
|
49
|
+
: never]: TMap[K];
|
|
50
|
+
};
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* Extract the search schema from a route map entry.
|
|
54
|
+
* - string value (old format): no search schema -> {}
|
|
55
|
+
* - { path, search } value: extract search
|
|
56
|
+
* - { path, response } value (no search): -> {}
|
|
57
|
+
*/
|
|
58
|
+
/** Extract params from a route map entry (string pattern or { path } object). */
|
|
59
|
+
type ExtractParamsFromEntry<TEntry, TFallback> = TEntry extends string
|
|
60
|
+
? ExtractParams<TEntry>
|
|
61
|
+
: TEntry extends { readonly path: infer P extends string }
|
|
62
|
+
? ExtractParams<P>
|
|
63
|
+
: TFallback;
|
|
64
|
+
|
|
65
|
+
/** Extract search schema from a route map entry. */
|
|
66
|
+
type ExtractSearchFromEntry<TMap, TKey> = TKey extends keyof TMap
|
|
67
|
+
? TMap[TKey] extends { readonly search: infer S extends SearchSchema }
|
|
68
|
+
? S
|
|
69
|
+
: {}
|
|
70
|
+
: {};
|
|
71
|
+
|
|
72
|
+
type IsEmptyObject<T> = keyof T extends never ? true : false;
|
|
73
|
+
|
|
74
|
+
type AutofillParamsFromEntry<TEntry> = TEntry extends string
|
|
75
|
+
? string extends TEntry
|
|
76
|
+
? Record<string, string>
|
|
77
|
+
: Partial<ExtractParams<TEntry>>
|
|
78
|
+
: TEntry extends { readonly path: infer P extends string }
|
|
79
|
+
? string extends P
|
|
80
|
+
? Record<string, string>
|
|
81
|
+
: Partial<ExtractParams<P>>
|
|
82
|
+
: Record<string, string>;
|
|
83
|
+
|
|
84
|
+
type AutofillSearchFromEntry<TMap, TKey> = TKey extends keyof TMap
|
|
85
|
+
? TMap[TKey] extends { readonly search: infer S extends SearchSchema }
|
|
86
|
+
? ResolveSearchSchema<S>
|
|
87
|
+
: Record<string, unknown>
|
|
88
|
+
: Record<string, unknown>;
|
|
89
|
+
|
|
90
|
+
type AutofillAwareReverseFunction<TLocalRoutes, TGlobalRoutes> =
|
|
91
|
+
ScopedReverseFunction<TLocalRoutes, TGlobalRoutes> & {
|
|
92
|
+
<TName extends keyof TGlobalRoutes & string>(
|
|
93
|
+
name: TName,
|
|
94
|
+
params?: AutofillParamsFromEntry<TGlobalRoutes[TName]>,
|
|
95
|
+
search?: AutofillSearchFromEntry<TGlobalRoutes, TName>,
|
|
96
|
+
): string;
|
|
97
|
+
<TName extends keyof TLocalRoutes & string>(
|
|
98
|
+
name: `.${TName}`,
|
|
99
|
+
params?: AutofillParamsFromEntry<TLocalRoutes[TName]>,
|
|
100
|
+
search?: AutofillSearchFromEntry<TLocalRoutes, TName>,
|
|
101
|
+
): string;
|
|
102
|
+
};
|
|
103
|
+
|
|
104
|
+
type StrictLocalParamsWithExtras<TEntry> =
|
|
105
|
+
IsEmptyObject<ExtractParamsFromEntry<TEntry, {}>> extends true
|
|
106
|
+
? Record<string, string>
|
|
107
|
+
: ExtractParamsFromEntry<TEntry, {}> & Record<string, string>;
|
|
108
|
+
|
|
109
|
+
// HandlerContext.reverse is the only reverse surface with runtime param autofill
|
|
110
|
+
// from the current matched request. Middleware/loaders/request context do not
|
|
111
|
+
// have the same local-route guarantees, so they keep plain ScopedReverseFunction.
|
|
112
|
+
//
|
|
113
|
+
// When a handler has an explicit local route map, enforce that local route
|
|
114
|
+
// params declared by that map are present while still allowing extra mount
|
|
115
|
+
// params to be passed through. Global names remain autofill-friendly because
|
|
116
|
+
// parent include() params are often unknown at the module definition site.
|
|
117
|
+
type StrictLocalAutofillGlobalReverseFunction<TLocalRoutes, TGlobalRoutes> =
|
|
118
|
+
ScopedReverseFunction<TLocalRoutes, TGlobalRoutes> & {
|
|
119
|
+
<TName extends keyof TGlobalRoutes & string>(
|
|
120
|
+
name: TName,
|
|
121
|
+
params?: AutofillParamsFromEntry<TGlobalRoutes[TName]>,
|
|
122
|
+
search?: AutofillSearchFromEntry<TGlobalRoutes, TName>,
|
|
123
|
+
): string;
|
|
124
|
+
<TName extends keyof TLocalRoutes & string>(
|
|
125
|
+
name: `.${TName}`,
|
|
126
|
+
params: StrictLocalParamsWithExtras<TLocalRoutes[TName]>,
|
|
127
|
+
search?: AutofillSearchFromEntry<TLocalRoutes, TName>,
|
|
128
|
+
): string;
|
|
129
|
+
};
|
|
130
|
+
|
|
131
|
+
export type Handler<
|
|
132
|
+
T extends
|
|
133
|
+
| keyof DefaultHandlerRouteMap
|
|
134
|
+
| `.${keyof TRouteMap & string}`
|
|
135
|
+
| `/${string}`
|
|
136
|
+
| Record<string, any> = {},
|
|
137
|
+
TRouteMap extends {} = DefaultHandlerRouteMap,
|
|
138
|
+
TEnv = DefaultEnv,
|
|
139
|
+
> = ((
|
|
140
|
+
ctx: HandlerContext<
|
|
141
|
+
T extends `.${infer Local}`
|
|
142
|
+
? Local extends keyof TRouteMap
|
|
143
|
+
? ExtractParamsFromEntry<
|
|
144
|
+
TRouteMap[Local],
|
|
145
|
+
T extends string ? ExtractParams<T> : T
|
|
146
|
+
>
|
|
147
|
+
: T extends string
|
|
148
|
+
? ExtractParams<T>
|
|
149
|
+
: T
|
|
150
|
+
: T extends keyof DefaultHandlerRouteMap
|
|
151
|
+
? ExtractParamsFromEntry<
|
|
152
|
+
DefaultHandlerRouteMap[T],
|
|
153
|
+
T extends string ? ExtractParams<T> : T
|
|
154
|
+
>
|
|
155
|
+
: T extends string
|
|
156
|
+
? ExtractParams<T>
|
|
157
|
+
: T,
|
|
158
|
+
TEnv,
|
|
159
|
+
T extends `.${infer Local}`
|
|
160
|
+
? ExtractSearchFromEntry<TRouteMap, Local>
|
|
161
|
+
: ExtractSearchFromEntry<DefaultHandlerRouteMap, T>,
|
|
162
|
+
TRouteMap extends DefaultHandlerRouteMap ? never : TRouteMap
|
|
163
|
+
>,
|
|
164
|
+
) => ReactNode | Promise<ReactNode> | Response | Promise<Response>) & {
|
|
165
|
+
/** Composable default DSL items merged when the handler is mounted. */
|
|
166
|
+
use?: () => UseItems<HandlerUseItem>;
|
|
167
|
+
};
|
|
168
|
+
|
|
169
|
+
/**
|
|
170
|
+
* Context passed to handlers (Hono-inspired type-safe context)
|
|
171
|
+
*
|
|
172
|
+
* Provides type-safe access to:
|
|
173
|
+
* - Route params (from URL pattern)
|
|
174
|
+
* - Cleaned route URL (`url`, `searchParams`, `pathname` — no `_rsc*` params)
|
|
175
|
+
* - Original request (`request` — raw transport URL, headers, method, body)
|
|
176
|
+
* - Platform bindings (env.DB, env.KV, env.SECRETS)
|
|
177
|
+
* - Middleware variables (`get("user")`, `get("permissions")`)
|
|
178
|
+
* - Getter/setter for variables (get('user'), set('user', ...))
|
|
179
|
+
*
|
|
180
|
+
* @example
|
|
181
|
+
* ```typescript
|
|
182
|
+
* const handler = (ctx: HandlerContext<{ slug: string }, AppEnv>) => {
|
|
183
|
+
* ctx.params.slug // Route param (string)
|
|
184
|
+
* ctx.env.DB // Binding (D1Database)
|
|
185
|
+
* ctx.get('user') // Variable (User | undefined)
|
|
186
|
+
* ctx.set('user', {...}) // Setter
|
|
187
|
+
* ctx.url // Clean URL (no _rsc* params)
|
|
188
|
+
* ctx.searchParams // Clean params (no _rsc* params)
|
|
189
|
+
* ctx.request // Raw transport request (original URL intact)
|
|
190
|
+
* }
|
|
191
|
+
* ```
|
|
192
|
+
*/
|
|
193
|
+
export type HandlerContext<
|
|
194
|
+
TParams = {},
|
|
195
|
+
TEnv = DefaultEnv,
|
|
196
|
+
TSearch extends SearchSchema = {},
|
|
197
|
+
TRouteMap = never,
|
|
198
|
+
> = {
|
|
199
|
+
/**
|
|
200
|
+
* Route parameters extracted from the URL pattern.
|
|
201
|
+
* Type-safe when using Handler<"/path/:param"> or Handler<{ param: string }>.
|
|
202
|
+
*/
|
|
203
|
+
params: TParams;
|
|
204
|
+
/** @internal Phantom property for params type invariance. Prevents mounting handlers on wrong routes. */
|
|
205
|
+
readonly _paramCheck?: (params: TParams) => TParams;
|
|
206
|
+
/**
|
|
207
|
+
* True during build-time pre-rendering, false at runtime.
|
|
208
|
+
* Build-time collection and dev on-demand prerender use `true`.
|
|
209
|
+
* Live request rendering, including passthrough fallback, uses `false`.
|
|
210
|
+
*/
|
|
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;
|
|
218
|
+
/**
|
|
219
|
+
* The original incoming Request object (transport URL intact).
|
|
220
|
+
* Use `ctx.url` / `ctx.searchParams` for application logic — those have
|
|
221
|
+
* internal `_rsc*` params stripped. `ctx.request` preserves the raw URL
|
|
222
|
+
* for cases where you need original headers, method, or body.
|
|
223
|
+
*/
|
|
224
|
+
request: Request;
|
|
225
|
+
/**
|
|
226
|
+
* Query parameters from the URL (system params like `_rsc*` are filtered).
|
|
227
|
+
* Always a standard URLSearchParams instance.
|
|
228
|
+
*/
|
|
229
|
+
searchParams: URLSearchParams;
|
|
230
|
+
/**
|
|
231
|
+
* Typed search parameters parsed from URL query string via the route's
|
|
232
|
+
* search schema. Empty object when no schema is defined.
|
|
233
|
+
*/
|
|
234
|
+
search: {} extends TSearch ? {} : ResolveSearchSchema<TSearch>;
|
|
235
|
+
/**
|
|
236
|
+
* The pathname portion of the request URL.
|
|
237
|
+
*/
|
|
238
|
+
pathname: string;
|
|
239
|
+
/**
|
|
240
|
+
* The full URL object (with internal `_rsc*` params stripped).
|
|
241
|
+
* Use this for application logic — routing, link generation, display.
|
|
242
|
+
*/
|
|
243
|
+
url: URL;
|
|
244
|
+
/**
|
|
245
|
+
* The original request URL with all parameters intact, including
|
|
246
|
+
* internal `_rsc*` transport params. Use `ctx.url` for application
|
|
247
|
+
* logic — this is only needed for advanced cases like debugging
|
|
248
|
+
* or custom cache keying.
|
|
249
|
+
*/
|
|
250
|
+
originalUrl: URL;
|
|
251
|
+
/**
|
|
252
|
+
* Platform bindings (DB, KV, secrets, etc.).
|
|
253
|
+
* Access resources like `ctx.env.DB`, `ctx.env.KV`.
|
|
254
|
+
*/
|
|
255
|
+
env: TEnv;
|
|
256
|
+
/**
|
|
257
|
+
* Type-safe getter for middleware variables.
|
|
258
|
+
* Preferred way to read middleware-injected variables.
|
|
259
|
+
*
|
|
260
|
+
* @example
|
|
261
|
+
* ```typescript
|
|
262
|
+
* const user = ctx.get("user"); // Type-safe!
|
|
263
|
+
* ```
|
|
264
|
+
*/
|
|
265
|
+
get: {
|
|
266
|
+
<T>(contextVar: ContextVar<T>): T | undefined;
|
|
267
|
+
} & (<K extends keyof DefaultVars>(key: K) => DefaultVars[K]);
|
|
268
|
+
/**
|
|
269
|
+
* Type-safe setter for middleware variables.
|
|
270
|
+
* Use in middleware to pass data to handlers.
|
|
271
|
+
*
|
|
272
|
+
* @example
|
|
273
|
+
* ```typescript
|
|
274
|
+
* ctx.set("user", { id: "123", name: "John" }); // Type-safe!
|
|
275
|
+
* ctx.set(MyVar, { ... }); // Type-safe via ContextVar token!
|
|
276
|
+
* ```
|
|
277
|
+
*/
|
|
278
|
+
set: {
|
|
279
|
+
<T>(
|
|
280
|
+
contextVar: ContextVar<T>,
|
|
281
|
+
value: T,
|
|
282
|
+
options?: { cache?: boolean },
|
|
283
|
+
): void;
|
|
284
|
+
} & (<K extends keyof DefaultVars>(
|
|
285
|
+
key: K,
|
|
286
|
+
value: DefaultVars[K],
|
|
287
|
+
options?: { cache?: boolean },
|
|
288
|
+
) => void);
|
|
289
|
+
/**
|
|
290
|
+
* Response headers. Headers set here are merged into the final response.
|
|
291
|
+
*
|
|
292
|
+
* @example
|
|
293
|
+
* ```typescript
|
|
294
|
+
* route("product", (ctx) => {
|
|
295
|
+
* ctx.headers.set("Cache-Control", "s-maxage=60");
|
|
296
|
+
* return <ProductPage />;
|
|
297
|
+
* });
|
|
298
|
+
* ```
|
|
299
|
+
*/
|
|
300
|
+
headers: Headers;
|
|
301
|
+
/**
|
|
302
|
+
* Access loader data or push handle data.
|
|
303
|
+
*
|
|
304
|
+
* Available in route handlers, layout handlers, middleware, server actions,
|
|
305
|
+
* and server components rendered within the request context.
|
|
306
|
+
*
|
|
307
|
+
* For loaders: Returns a promise that resolves to the loader data.
|
|
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).
|
|
313
|
+
*
|
|
314
|
+
* For handles: Returns a push function to add data for this segment.
|
|
315
|
+
* Handle data accumulates across all matched route segments.
|
|
316
|
+
* Push accepts: direct value, Promise, or async callback (executed immediately).
|
|
317
|
+
*
|
|
318
|
+
* @example
|
|
319
|
+
* ```typescript
|
|
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 />;
|
|
325
|
+
* });
|
|
326
|
+
*
|
|
327
|
+
* // Handle usage - direct value
|
|
328
|
+
* route("shop", (ctx) => {
|
|
329
|
+
* const push = ctx.use(Breadcrumbs);
|
|
330
|
+
* push({ label: "Shop", href: "/shop" });
|
|
331
|
+
* return <ShopPage />;
|
|
332
|
+
* });
|
|
333
|
+
*
|
|
334
|
+
* // Handle usage - Promise
|
|
335
|
+
* route("product", (ctx) => {
|
|
336
|
+
* const push = ctx.use(Breadcrumbs);
|
|
337
|
+
* push(fetchProductBreadcrumb(ctx.params.id));
|
|
338
|
+
* return <ProductPage />;
|
|
339
|
+
* });
|
|
340
|
+
*
|
|
341
|
+
* // Handle usage - async callback (executed immediately)
|
|
342
|
+
* route("product", (ctx) => {
|
|
343
|
+
* const push = ctx.use(Breadcrumbs);
|
|
344
|
+
* push(async () => {
|
|
345
|
+
* const product = await db.getProduct(ctx.params.id);
|
|
346
|
+
* return { label: product.name, href: `/product/${product.id}` };
|
|
347
|
+
* });
|
|
348
|
+
* return <ProductPage />;
|
|
349
|
+
* });
|
|
350
|
+
* ```
|
|
351
|
+
*/
|
|
352
|
+
use: {
|
|
353
|
+
<T, TLoaderParams = any>(
|
|
354
|
+
loader: LoaderDefinition<T, TLoaderParams>,
|
|
355
|
+
): Promise<T>;
|
|
356
|
+
<TData, TAccumulated = TData[]>(
|
|
357
|
+
handle: Handle<TData, TAccumulated>,
|
|
358
|
+
): (data: TData | Promise<TData> | (() => Promise<TData>)) => void;
|
|
359
|
+
};
|
|
360
|
+
/**
|
|
361
|
+
* Current theme (from cookie or default).
|
|
362
|
+
* Only available when theme is enabled in router config.
|
|
363
|
+
*
|
|
364
|
+
* @example
|
|
365
|
+
* ```typescript
|
|
366
|
+
* route("settings", (ctx) => {
|
|
367
|
+
* const currentTheme = ctx.theme; // "light" | "dark" | "system" | undefined
|
|
368
|
+
* return <SettingsPage theme={currentTheme} />;
|
|
369
|
+
* });
|
|
370
|
+
* ```
|
|
371
|
+
*/
|
|
372
|
+
theme?: Theme;
|
|
373
|
+
/**
|
|
374
|
+
* Set the theme (only available when theme is enabled in router config).
|
|
375
|
+
* Sets a cookie with the new theme value.
|
|
376
|
+
*
|
|
377
|
+
* @example
|
|
378
|
+
* ```typescript
|
|
379
|
+
* route("settings", async (ctx) => {
|
|
380
|
+
* if (ctx.request.method === "POST") {
|
|
381
|
+
* const formData = await ctx.request.formData();
|
|
382
|
+
* const newTheme = formData.get("theme") as Theme;
|
|
383
|
+
* ctx.setTheme?.(newTheme);
|
|
384
|
+
* }
|
|
385
|
+
* return <SettingsPage />;
|
|
386
|
+
* });
|
|
387
|
+
* ```
|
|
388
|
+
*/
|
|
389
|
+
setTheme?: (theme: Theme) => void;
|
|
390
|
+
/**
|
|
391
|
+
* Attach location state entries to this response.
|
|
392
|
+
* State is delivered to the client via history.pushState and accessible
|
|
393
|
+
* through the useLocationState() hook.
|
|
394
|
+
*
|
|
395
|
+
* @example
|
|
396
|
+
* ```typescript
|
|
397
|
+
* route("product", (ctx) => {
|
|
398
|
+
* ctx.setLocationState(ServerInfo({ data: "value" }));
|
|
399
|
+
* return <ProductPage />;
|
|
400
|
+
* });
|
|
401
|
+
* ```
|
|
402
|
+
*/
|
|
403
|
+
setLocationState(entries: LocationStateEntry | LocationStateEntry[]): void;
|
|
404
|
+
/**
|
|
405
|
+
* The matched route name, if the route has an explicit name.
|
|
406
|
+
* Undefined for unnamed routes (those without a `name` option in path()).
|
|
407
|
+
* Includes the namespace prefix from include() (e.g., "blog.post").
|
|
408
|
+
*
|
|
409
|
+
* @example
|
|
410
|
+
* ```typescript
|
|
411
|
+
* route("product", (ctx) => {
|
|
412
|
+
* ctx.routeName // "product"
|
|
413
|
+
* return <ProductPage />;
|
|
414
|
+
* });
|
|
415
|
+
* ```
|
|
416
|
+
*/
|
|
417
|
+
routeName?: DefaultRouteName;
|
|
418
|
+
/**
|
|
419
|
+
* Generate URLs from route names.
|
|
420
|
+
*
|
|
421
|
+
* - `.name` -- local route, resolved within current include() scope
|
|
422
|
+
* - `name` -- global route, from the named-routes definition
|
|
423
|
+
*
|
|
424
|
+
* @example
|
|
425
|
+
* ```typescript
|
|
426
|
+
* ctx.reverse(".article", { slug: "hello" }) // Local: magazine.article
|
|
427
|
+
* ctx.reverse(".index") // Local: magazine.index
|
|
428
|
+
* ctx.reverse("magazine.index") // Global: magazine.index
|
|
429
|
+
* ctx.reverse("blog.post", { slug: "hello" }) // Global: blog.post
|
|
430
|
+
* ```
|
|
431
|
+
*/
|
|
432
|
+
reverse: [TRouteMap] extends [never]
|
|
433
|
+
? AutofillAwareReverseFunction<
|
|
434
|
+
Record<string, string>,
|
|
435
|
+
DefaultReverseRouteMap
|
|
436
|
+
>
|
|
437
|
+
: StrictLocalAutofillGlobalReverseFunction<
|
|
438
|
+
TRouteMap,
|
|
439
|
+
DefaultReverseRouteMap
|
|
440
|
+
>;
|
|
441
|
+
};
|
|
442
|
+
|
|
443
|
+
/**
|
|
444
|
+
* Internal handler context with additional props for router internals.
|
|
445
|
+
* Use `HandlerContext` for user-facing code.
|
|
446
|
+
* @internal
|
|
447
|
+
*/
|
|
448
|
+
export type InternalHandlerContext<
|
|
449
|
+
TParams = {},
|
|
450
|
+
TEnv = DefaultEnv,
|
|
451
|
+
TSearch extends SearchSchema = {},
|
|
452
|
+
> = HandlerContext<TParams, TEnv, TSearch> & {
|
|
453
|
+
/** @internal Stub response for collecting headers/cookies. */
|
|
454
|
+
res: Response;
|
|
455
|
+
/** @internal Shared variable backing store for ctx.get()/ctx.set(). */
|
|
456
|
+
_variables: Record<string, any>;
|
|
457
|
+
/** Prerender-only control flow helper, attached when the runtime context supports it. */
|
|
458
|
+
passthrough?: () => unknown;
|
|
459
|
+
/** Current segment ID for handle data attribution. */
|
|
460
|
+
_currentSegmentId?: string;
|
|
461
|
+
/** Response type tag (json, text, html, etc.) for cache key differentiation. */
|
|
462
|
+
_responseType?: string;
|
|
463
|
+
/** Route name for cache key scoping (prevents cross-route collisions). */
|
|
464
|
+
_routeName?: string;
|
|
465
|
+
};
|
|
466
|
+
|
|
467
|
+
/**
|
|
468
|
+
* Generic params type - flexible object with string keys
|
|
469
|
+
* Users can narrow this by explicitly typing their params:
|
|
470
|
+
*
|
|
471
|
+
* @example
|
|
472
|
+
* ```typescript
|
|
473
|
+
* [revalidate('post')]: (({ currentParams, nextParams }: RevalidateParams<{ slug: string }>) => {
|
|
474
|
+
* currentParams.slug // typed as string
|
|
475
|
+
* return currentParams.slug !== nextParams.slug;
|
|
476
|
+
* })
|
|
477
|
+
* ```
|
|
478
|
+
*/
|
|
479
|
+
export type GenericParams = { [key: string]: string | undefined };
|
|
480
|
+
|
|
481
|
+
/**
|
|
482
|
+
* Helper type for revalidation handler params
|
|
483
|
+
* Allows inline type annotation for stricter param typing
|
|
484
|
+
*
|
|
485
|
+
* @example
|
|
486
|
+
* ```typescript
|
|
487
|
+
* [revalidate('post')]: (params: RevalidateParams<{ slug: string }>) => {
|
|
488
|
+
* params.currentParams.slug // typed as string
|
|
489
|
+
* return params.defaultShouldRevalidate;
|
|
490
|
+
* }
|
|
491
|
+
* ```
|
|
492
|
+
*/
|
|
493
|
+
export type RevalidateParams<TParams = GenericParams, TEnv = any> = Parameters<
|
|
494
|
+
ShouldRevalidateFn<TParams, TEnv>
|
|
495
|
+
>[0];
|
|
496
|
+
|
|
497
|
+
/**
|
|
498
|
+
* Should revalidate function signature (inspired by React Router)
|
|
499
|
+
*
|
|
500
|
+
* Determines whether a route segment should re-render during partial navigation.
|
|
501
|
+
* Multiple revalidation functions can be defined per route - they execute in order.
|
|
502
|
+
*
|
|
503
|
+
* **Return Types:**
|
|
504
|
+
* - `boolean` - Hard decision: immediately returns this value (short-circuits)
|
|
505
|
+
* - `{ defaultShouldRevalidate: boolean }` - Soft decision: updates suggestion for next revalidator
|
|
506
|
+
*
|
|
507
|
+
* **Execution Flow:**
|
|
508
|
+
* 1. Start with built-in `defaultShouldRevalidate` (true if params changed)
|
|
509
|
+
* 2. Execute global revalidators first, then route-specific
|
|
510
|
+
* 3. Hard decision (boolean): stop immediately and use that value
|
|
511
|
+
* 4. Soft decision (object): update suggestion and continue to next revalidator
|
|
512
|
+
* 5. If all return soft decisions: use the final suggestion
|
|
513
|
+
*
|
|
514
|
+
* @param args.currentParams - Previous route params (generic by default, can be narrowed)
|
|
515
|
+
* @param args.currentUrl - Previous URL
|
|
516
|
+
* @param args.nextParams - Next route params (generic by default, can be narrowed)
|
|
517
|
+
* @param args.nextUrl - Next URL
|
|
518
|
+
* @param args.defaultShouldRevalidate - Current suggestion (updated by soft decisions)
|
|
519
|
+
* @param args.context - App context (db, user, etc.)
|
|
520
|
+
* @param args.actionResult - Result from action (future support)
|
|
521
|
+
* @param args.formData - Form data from action (future support)
|
|
522
|
+
* @param args.formMethod - HTTP method from action (future support)
|
|
523
|
+
*
|
|
524
|
+
* @returns Hard decision (boolean) or soft suggestion (object)
|
|
525
|
+
*
|
|
526
|
+
* @example
|
|
527
|
+
* ```typescript
|
|
528
|
+
* // Hard decision - definitive answer
|
|
529
|
+
* [revalidate('post')]: ({ currentParams, nextParams }) => {
|
|
530
|
+
* return currentParams.slug !== nextParams.slug; // boolean - short-circuits
|
|
531
|
+
* }
|
|
532
|
+
*
|
|
533
|
+
* // Soft decision - allows downstream revalidators to override
|
|
534
|
+
* [revalidate('*', 'global')]: ({ defaultShouldRevalidate }) => {
|
|
535
|
+
* return { defaultShouldRevalidate: true }; // object - continues to next
|
|
536
|
+
* }
|
|
537
|
+
*
|
|
538
|
+
* // Explicit typing for stricter params
|
|
539
|
+
* [revalidate('post')]: ((params: RevalidateParams<{ slug: string }>) => {
|
|
540
|
+
* return params.currentParams.slug !== params.nextParams.slug;
|
|
541
|
+
* })
|
|
542
|
+
* ```
|
|
543
|
+
*/
|
|
544
|
+
/**
|
|
545
|
+
* Revalidation function called during client-side navigation to decide whether
|
|
546
|
+
* a segment (layout, route, parallel slot, or loader) should be re-rendered.
|
|
547
|
+
*
|
|
548
|
+
* Return `true` to re-render, `false` to skip (keep client's current version),
|
|
549
|
+
* or `{ defaultShouldRevalidate: boolean }` to override the default for
|
|
550
|
+
* downstream segments.
|
|
551
|
+
*
|
|
552
|
+
* @example
|
|
553
|
+
* ```ts
|
|
554
|
+
* // Re-render only when a cart action happened or browser signals staleness
|
|
555
|
+
* revalidate(({ actionId, stale }) =>
|
|
556
|
+
* actionId?.includes("cart") || stale || false
|
|
557
|
+
* )
|
|
558
|
+
*
|
|
559
|
+
* // Always re-render when params change (default behavior made explicit)
|
|
560
|
+
* revalidate(({ defaultShouldRevalidate }) => defaultShouldRevalidate)
|
|
561
|
+
* ```
|
|
562
|
+
*/
|
|
563
|
+
export type ShouldRevalidateFn<TParams = GenericParams, TEnv = any> = (args: {
|
|
564
|
+
/** Route params from the page being navigated away from. */
|
|
565
|
+
currentParams: TParams;
|
|
566
|
+
/** Full URL of the page being navigated away from. */
|
|
567
|
+
currentUrl: URL;
|
|
568
|
+
/** Route params for the navigation target. */
|
|
569
|
+
nextParams: TParams;
|
|
570
|
+
/** Full URL of the navigation target. */
|
|
571
|
+
nextUrl: URL;
|
|
572
|
+
/**
|
|
573
|
+
* The router's default revalidation decision for this segment.
|
|
574
|
+
* `true` when params changed or the segment is new to the client.
|
|
575
|
+
* Return this when you want default behavior plus your own conditions.
|
|
576
|
+
*/
|
|
577
|
+
defaultShouldRevalidate: boolean;
|
|
578
|
+
/** Full handler context — access to `ctx.use()`, `ctx.env`, `ctx.params`, etc. */
|
|
579
|
+
context: HandlerContext<TParams, TEnv>;
|
|
580
|
+
|
|
581
|
+
// ── Segment metadata (which segment is being evaluated) ──────────────
|
|
582
|
+
|
|
583
|
+
/** The type of segment being revalidated. */
|
|
584
|
+
segmentType: "layout" | "route" | "parallel";
|
|
585
|
+
/** Layout name (e.g., `"root"`, `"shop"`, `"auth"`). Only set for layout segments. */
|
|
586
|
+
layoutName?: string;
|
|
587
|
+
/** Slot name (e.g., `"@sidebar"`, `"@modal"`). Only set for parallel segments. */
|
|
588
|
+
slotName?: string;
|
|
589
|
+
|
|
590
|
+
// ── Action context (populated when revalidation is triggered by a server action) ──
|
|
591
|
+
|
|
592
|
+
/**
|
|
593
|
+
* Identifier of the server action that triggered revalidation.
|
|
594
|
+
* `undefined` during normal navigation (no action involved).
|
|
595
|
+
*
|
|
596
|
+
* Format: `"src/<path>#<exportName>"` — the file path is the source path
|
|
597
|
+
* relative to the project root, followed by `#` and the exported function name.
|
|
598
|
+
*
|
|
599
|
+
* This is stable and can be used for path-based matching to revalidate
|
|
600
|
+
* when any action in a module or directory fires:
|
|
601
|
+
*
|
|
602
|
+
* @example
|
|
603
|
+
* ```ts
|
|
604
|
+
* // Match a specific action
|
|
605
|
+
* revalidate(({ actionId }) => actionId === "src/actions/cart.ts#addToCart")
|
|
606
|
+
*
|
|
607
|
+
* // Match any action in the cart module
|
|
608
|
+
* revalidate(({ actionId }) => actionId?.includes("cart") ?? false)
|
|
609
|
+
*
|
|
610
|
+
* // Match any action under src/apps/store/actions/
|
|
611
|
+
* revalidate(({ actionId }) => actionId?.startsWith("src/apps/store/actions/") ?? false)
|
|
612
|
+
* ```
|
|
613
|
+
*/
|
|
614
|
+
actionId?: string;
|
|
615
|
+
/** URL where the action was executed (the page the user was on when they triggered the action). */
|
|
616
|
+
actionUrl?: URL;
|
|
617
|
+
/** Return value from the action execution. Can be used to conditionally revalidate based on the action's outcome. */
|
|
618
|
+
actionResult?: any;
|
|
619
|
+
/** FormData from the action request body. Only set for form-based actions (not inline `"use server"` actions). */
|
|
620
|
+
formData?: FormData;
|
|
621
|
+
/** HTTP method: `"GET"` for navigation, `"POST"` for server actions. */
|
|
622
|
+
method?: string;
|
|
623
|
+
|
|
624
|
+
// ── Route identity ───────────────────────────────────────────────────
|
|
625
|
+
|
|
626
|
+
/** Route name of the navigation target. Alias for `toRouteName`. */
|
|
627
|
+
routeName?: DefaultRouteName;
|
|
628
|
+
/**
|
|
629
|
+
* Route name being navigated away from.
|
|
630
|
+
* `undefined` for unnamed internal routes (those without a `name` option).
|
|
631
|
+
*/
|
|
632
|
+
fromRouteName?: DefaultRouteName;
|
|
633
|
+
/**
|
|
634
|
+
* Route name being navigated to.
|
|
635
|
+
* `undefined` for unnamed internal routes (those without a `name` option).
|
|
636
|
+
*/
|
|
637
|
+
toRouteName?: DefaultRouteName;
|
|
638
|
+
|
|
639
|
+
// ── Staleness signal ─────────────────────────────────────────────────
|
|
640
|
+
|
|
641
|
+
/**
|
|
642
|
+
* `true` when the browser signals that data may be stale — typically because
|
|
643
|
+
* a server action was executed in this or another tab (`_rsc_stale` header).
|
|
644
|
+
*
|
|
645
|
+
* This is NOT segment cache staleness (loaders are never segment-cached).
|
|
646
|
+
* Use this to decide whether loader data should be re-fetched after an
|
|
647
|
+
* action that may have mutated backend state.
|
|
648
|
+
*/
|
|
649
|
+
stale?: boolean;
|
|
650
|
+
}) => boolean | { defaultShouldRevalidate: boolean };
|
|
651
|
+
|
|
652
|
+
// MiddlewareFn is imported from "../router/middleware.js" and re-exported
|
|
653
|
+
|
|
654
|
+
/**
|
|
655
|
+
* Extract all route keys from a route definition (includes flattened nested routes)
|
|
656
|
+
*/
|
|
657
|
+
export type RouteKeys<T extends RouteDefinition> = keyof ResolvedRouteMap<T> &
|
|
658
|
+
string;
|
|
659
|
+
|
|
660
|
+
/**
|
|
661
|
+
* Valid layout value - component or handler function
|
|
662
|
+
* Note: Arrays are not supported. Use separate layout() declarations with unique names instead.
|
|
663
|
+
*/
|
|
664
|
+
type LayoutValue<TEnv = any> = ReactNode | Handler<any, any, TEnv>;
|
|
665
|
+
|
|
666
|
+
/**
|
|
667
|
+
* Helper to extract params from a route key using the resolved (flattened) route map
|
|
668
|
+
*/
|
|
669
|
+
export type ExtractRouteParams<
|
|
670
|
+
T extends RouteDefinition,
|
|
671
|
+
K extends string,
|
|
672
|
+
> = K extends keyof ResolvedRouteMap<T>
|
|
673
|
+
? ResolvedRouteMap<T>[K] extends string
|
|
674
|
+
? ExtractParams<ResolvedRouteMap<T>[K]>
|
|
675
|
+
: GenericParams
|
|
676
|
+
: GenericParams;
|
|
677
|
+
|
|
678
|
+
/**
|
|
679
|
+
* Handlers object that maps route names to handler functions with type-safe string patterns
|
|
680
|
+
*/
|
|
681
|
+
export type HandlersForRouteMap<T extends RouteDefinition, TEnv = any> = {
|
|
682
|
+
// Route handlers - type-safe params extracted from route patterns
|
|
683
|
+
[K in RouteKeys<T>]?: Handler<ExtractRouteParams<T, K & string>, any, TEnv>;
|
|
684
|
+
} & {
|
|
685
|
+
// Layout patterns: $layout.{routeName}.{layoutName}
|
|
686
|
+
[K in `$layout.${RouteKeys<T> | "*"}.${string}`]?: LayoutValue<TEnv>;
|
|
687
|
+
} & {
|
|
688
|
+
// Parallel route patterns: $parallel.{routeName}.{parallelName}
|
|
689
|
+
[K in `$parallel.${RouteKeys<T>}.${string}`]?: Record<
|
|
690
|
+
`@${string}`,
|
|
691
|
+
Handler<
|
|
692
|
+
K extends `$parallel.${infer RouteKey}.${string}`
|
|
693
|
+
? RouteKey extends RouteKeys<T>
|
|
694
|
+
? ExtractRouteParams<T, RouteKey & string>
|
|
695
|
+
: GenericParams
|
|
696
|
+
: GenericParams,
|
|
697
|
+
any,
|
|
698
|
+
TEnv
|
|
699
|
+
>
|
|
700
|
+
>;
|
|
701
|
+
} & {
|
|
702
|
+
// Global parallel routes (with '*') use GenericParams
|
|
703
|
+
[K in `$parallel.${"*"}.${string}`]?: Record<
|
|
704
|
+
`@${string}`,
|
|
705
|
+
Handler<GenericParams, any, TEnv>
|
|
706
|
+
>;
|
|
707
|
+
} & {
|
|
708
|
+
// Middleware patterns: $middleware.{routeName}.{middlewareName}
|
|
709
|
+
[K in `$middleware.${RouteKeys<T> | "*"}.${string}`]?: MiddlewareFn<
|
|
710
|
+
TEnv,
|
|
711
|
+
GenericParams
|
|
712
|
+
>[];
|
|
713
|
+
} & {
|
|
714
|
+
// Route revalidate patterns: $revalidate.route.{routeName}.{revalidateName}
|
|
715
|
+
[K in `$revalidate.route.${RouteKeys<T> | "*"}.${string}`]?: ShouldRevalidateFn<
|
|
716
|
+
GenericParams,
|
|
717
|
+
TEnv
|
|
718
|
+
>;
|
|
719
|
+
} & {
|
|
720
|
+
// Layout revalidate patterns: $revalidate.layout.{routeName}.{layoutName}.{revalidateName}
|
|
721
|
+
[K in `$revalidate.layout.${RouteKeys<T> | "*"}.${string}.${string}`]?: ShouldRevalidateFn<
|
|
722
|
+
GenericParams,
|
|
723
|
+
TEnv
|
|
724
|
+
>;
|
|
725
|
+
} & {
|
|
726
|
+
// Parallel revalidate patterns: $revalidate.parallel.{routeName}.{parallelName}.{slotName}.{revalidateName}
|
|
727
|
+
[K in `$revalidate.parallel.${RouteKeys<T> | "*"}.${string}.${string}.${string}`]?: ShouldRevalidateFn<
|
|
728
|
+
GenericParams,
|
|
729
|
+
TEnv
|
|
730
|
+
>;
|
|
731
|
+
};
|
|
732
|
+
|
|
733
|
+
/**
|
|
734
|
+
* Revalidation function with typed params
|
|
735
|
+
*
|
|
736
|
+
* @template T - Params object
|
|
737
|
+
* @template TEnv - Environment type
|
|
738
|
+
*
|
|
739
|
+
* @example
|
|
740
|
+
* ```typescript
|
|
741
|
+
* const revalidate: Revalidate<{ slug: string }> = ({ currentParams, nextParams }) => {
|
|
742
|
+
* return currentParams.slug !== nextParams.slug;
|
|
743
|
+
* }
|
|
744
|
+
* ```
|
|
745
|
+
*/
|
|
746
|
+
export type Revalidate<
|
|
747
|
+
T = GenericParams,
|
|
748
|
+
TEnv = DefaultEnv,
|
|
749
|
+
> = ShouldRevalidateFn<T, TEnv>;
|
|
750
|
+
|
|
751
|
+
/**
|
|
752
|
+
* Middleware function with typed params and environment
|
|
753
|
+
*
|
|
754
|
+
* @template TParams - Params object (defaults to generic)
|
|
755
|
+
* @template TEnv - Environment type (defaults to global RSCRouter.Env)
|
|
756
|
+
*
|
|
757
|
+
* Note: Middleware cannot directly use route names for params typing because
|
|
758
|
+
* middleware is defined during router setup, before RegisteredRoutes is populated.
|
|
759
|
+
* Use ExtractParams<"/path/:id"> for typed params from a path pattern.
|
|
760
|
+
*
|
|
761
|
+
* @example
|
|
762
|
+
* ```typescript
|
|
763
|
+
* // Basic middleware (uses global RSCRouter.Env via module augmentation)
|
|
764
|
+
* const middleware: Middleware = async (ctx, next) => {
|
|
765
|
+
* ctx.set("user", { id: "123" }); // Type-safe!
|
|
766
|
+
* await next();
|
|
767
|
+
* }
|
|
768
|
+
*
|
|
769
|
+
* // With explicit params (most common)
|
|
770
|
+
* const middleware: Middleware<{ id: string }> = async (ctx, next) => {
|
|
771
|
+
* console.log(ctx.params.id);
|
|
772
|
+
* await next();
|
|
773
|
+
* }
|
|
774
|
+
*
|
|
775
|
+
* // With params from path pattern
|
|
776
|
+
* const middleware: Middleware<ExtractParams<"/products/:id">> = async (ctx, next) => {
|
|
777
|
+
* console.log(ctx.params.id);
|
|
778
|
+
* await next();
|
|
779
|
+
* }
|
|
780
|
+
*
|
|
781
|
+
* // With both params and explicit env
|
|
782
|
+
* const middleware: Middleware<{ id: string }, AppEnv> = async (ctx, next) => {
|
|
783
|
+
* ctx.set("user", { id: ctx.params.id });
|
|
784
|
+
* await next();
|
|
785
|
+
* }
|
|
786
|
+
* ```
|
|
787
|
+
*/
|
|
788
|
+
export type Middleware<
|
|
789
|
+
TParams = GenericParams,
|
|
790
|
+
TEnv = DefaultEnv,
|
|
791
|
+
> = MiddlewareFn<TEnv, TParams>;
|