@teyik0/furin 0.2.0-alpha.3 → 0.2.0-alpha.5

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 (98) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +37 -33
  3. package/dist/adapter/bun.d.ts +17 -1
  4. package/dist/adapter/package.d.ts +26 -0
  5. package/dist/build/client.d.ts +1 -1
  6. package/dist/build/compile-entry.d.ts +3 -3
  7. package/dist/build/compile-entry.ts +114 -109
  8. package/dist/build/entry-template.d.ts +35 -9
  9. package/dist/build/entry-template.ts +206 -156
  10. package/dist/build/hydrate.d.ts +1 -1
  11. package/dist/build/index.js +643 -247
  12. package/dist/build/scan-server.d.ts +10 -4
  13. package/dist/build/server-routes-entry.d.ts +3 -3
  14. package/dist/build/server-routes-entry.ts +30 -36
  15. package/dist/build/ssg-cache.d.ts +1 -1
  16. package/dist/build/types.d.ts +36 -1
  17. package/dist/cli/config.d.ts +6 -1
  18. package/dist/cli/index.js +662 -260
  19. package/dist/client/link.js +163 -16
  20. package/dist/client/router/abort.d.ts +1 -0
  21. package/dist/client/router/sync-catch-up.d.ts +29 -0
  22. package/dist/config.d.ts +11 -2
  23. package/dist/config.js +5 -1
  24. package/dist/furin.d.ts +37 -19
  25. package/dist/furin.js +982 -378
  26. package/dist/server/auto-invalidate/registry.d.ts +8 -1
  27. package/dist/server/cache/dev-loader.d.ts +3 -2
  28. package/dist/server/cache/invalidation.d.ts +19 -0
  29. package/dist/server/cache/isr.d.ts +6 -2
  30. package/dist/server/cache/registry.d.ts +3 -3
  31. package/dist/server/cache/ssg.d.ts +6 -2
  32. package/dist/server/cache/store-view.d.ts +11 -0
  33. package/dist/server/instance.d.ts +86 -0
  34. package/dist/server/internal.d.ts +16 -1
  35. package/dist/server/internal.js +72 -5
  36. package/dist/server/render/template.d.ts +3 -2
  37. package/dist/server/sync/adapter.d.ts +62 -0
  38. package/dist/server/sync/config.d.ts +11 -0
  39. package/dist/server/sync/fingerprint.d.ts +6 -0
  40. package/dist/server/sync/index.d.ts +2 -2
  41. package/dist/server/sync/memory-adapter.d.ts +17 -0
  42. package/dist/server/sync/plugin.d.ts +12 -195
  43. package/dist/server/sync/response.d.ts +4 -0
  44. package/dist/server/sync/stream.d.ts +24 -5
  45. package/dist/shared/prefix.d.ts +15 -0
  46. package/package.json +6 -1
  47. package/src/adapter/README.md +13 -13
  48. package/src/adapter/bun.ts +113 -50
  49. package/src/adapter/package.ts +206 -0
  50. package/src/build/client.ts +158 -152
  51. package/src/build/compile-entry.ts +114 -109
  52. package/src/build/entry-template.ts +206 -156
  53. package/src/build/hydrate.ts +342 -340
  54. package/src/build/index.ts +223 -152
  55. package/src/build/route-types.ts +145 -145
  56. package/src/build/scan-server.ts +111 -95
  57. package/src/build/server-routes-entry.ts +30 -36
  58. package/src/build/shared.ts +80 -80
  59. package/src/build/ssg-cache.ts +36 -32
  60. package/src/build/types.ts +125 -89
  61. package/src/cli/config.ts +9 -3
  62. package/src/cli/index.ts +21 -3
  63. package/src/client/router/abort.ts +5 -0
  64. package/src/client/router/link-utils.ts +184 -184
  65. package/src/client/router/provider.tsx +883 -804
  66. package/src/client/router/sync-catch-up.ts +113 -0
  67. package/src/client/router/types.ts +276 -276
  68. package/src/client/sync.ts +98 -98
  69. package/src/client.ts +369 -369
  70. package/src/config.ts +14 -1
  71. package/src/furin.ts +619 -465
  72. package/src/server/auto-invalidate/registry.ts +23 -1
  73. package/src/server/auto-invalidate/runtime.ts +159 -134
  74. package/src/server/cache/dev-loader.ts +77 -38
  75. package/src/server/cache/invalidation.ts +71 -30
  76. package/src/server/cache/isr.ts +20 -5
  77. package/src/server/cache/registry.ts +17 -20
  78. package/src/server/cache/ssg.ts +19 -4
  79. package/src/server/cache/store-view.ts +30 -0
  80. package/src/server/dev-page-plugin.ts +454 -454
  81. package/src/server/instance.ts +252 -0
  82. package/src/server/internal.ts +100 -5
  83. package/src/server/render/assemble.ts +160 -160
  84. package/src/server/render/isr.ts +323 -323
  85. package/src/server/render/not-found.ts +9 -3
  86. package/src/server/render/ssr.ts +603 -585
  87. package/src/server/render/template.ts +57 -24
  88. package/src/server/router/plugin.ts +384 -384
  89. package/src/server/sync/adapter.ts +65 -0
  90. package/src/server/sync/config.ts +60 -29
  91. package/src/server/sync/fingerprint.ts +44 -0
  92. package/src/server/sync/index.ts +15 -14
  93. package/src/server/sync/memory-adapter.ts +196 -0
  94. package/src/server/sync/plugin.ts +199 -108
  95. package/src/server/sync/response.ts +77 -0
  96. package/src/server/sync/stream.ts +162 -144
  97. package/src/shared/deferred-ndjson.ts +7 -0
  98. package/src/shared/prefix.ts +38 -0
package/src/client.ts CHANGED
@@ -1,369 +1,369 @@
1
- /*
2
- biome-ignore-all lint/complexity/noBannedTypes: The fundamental problem is that
3
- `Record<string, unknown>` requires an index signature, and any type without one
4
- (like `{}`, `object`, or a named interface) won't satisfy it. But `{}` is the only type that:
5
- 1. Satisfies `Record<string, unknown>` as a generic default (TS special-cases `{}`)
6
- 2. Doesn't have an index signature (so unknown prop access errors)
7
- 3. Is transparent in intersections(`{} & T = T`)
8
- */
9
- /*
10
- biome-ignore-all lint/performance/noBarrelFile: client.ts is the canonical DX
11
- entry for furin/client consumers, not a generic internal barrel.
12
- */
13
-
14
- import type { Cookie, StatusMap } from "elysia";
15
- import type { AnySchema, HTTPHeaders, UnwrapSchema } from "elysia/types";
16
- import type { RequestLogger } from "evlog";
17
-
18
- export {
19
- type SyncMutation,
20
- type SyncMutationContext,
21
- type SyncMutationErrorContext,
22
- type SyncMutationHeaders,
23
- type SyncMutationOptions,
24
- type SyncMutationRunner,
25
- type SyncMutationSuccessContext,
26
- type UseSyncOptions,
27
- useSync,
28
- } from "./client/sync.ts";
29
- export { Await, useAsyncError, useAsyncValue } from "./shared/await.tsx";
30
-
31
- declare const UNSET: unique symbol;
32
- type Unset = typeof UNSET;
33
-
34
- // Expands interfaces into plain mapped types so they satisfy Record<string, unknown>.
35
- // Interfaces lack an implicit index signature; mapped types have one.
36
- type ToRecord<T> = { [K in keyof T]: T[K] };
37
-
38
- type ResolvedSchema<T> = [T] extends [Unset]
39
- ? Unset
40
- : T extends AnySchema
41
- ? UnwrapSchema<T>
42
- : Unset;
43
-
44
- type MergeSchema<TParent, TOwn> = [TParent] extends [Unset]
45
- ? TOwn
46
- : [TOwn] extends [Unset]
47
- ? TParent
48
- : TParent & TOwn;
49
-
50
- type NormalizeUnset<T> = [T] extends [Unset] ? {} : T;
51
-
52
- /**
53
- * Transforms each key of a parent-data record into an individual `Promise<T>`.
54
- * This is what child loaders see for inherited fields — direct values from
55
- * `RouteContext` (request, params, set, …) remain unchanged.
56
- *
57
- * `Awaited<T[K]>` mirrors the JS Promise-chaining auto-flatten used by
58
- * `createLoaderCtx`: when an ancestor wrapped a field with `defer()` (so the
59
- * raw value is itself a `Promise<U>`), the type collapses to `Promise<U>`
60
- * instead of `Promise<Promise<U>>`. Otherwise TypeScript would force a
61
- * redundant `await await ctx.field` dance.
62
- */
63
- type PromisifyData<T extends Record<string, unknown>> = {
64
- [K in keyof T]: Promise<Awaited<T[K]>>;
65
- };
66
-
67
- export interface RouteContext<TParams = {}, TQuery = {}> {
68
- cookie: Record<string, Cookie<unknown>>;
69
- headers: Record<string, string | undefined>;
70
- /** Request-scoped logger. Call `log.set({})` to attach fields to the wide event for this render. */
71
- log: RequestLogger;
72
- params: NormalizeUnset<TParams>;
73
- path: string;
74
- query: NormalizeUnset<TQuery>;
75
- redirect: (url: string, status?: 301 | 302 | 303 | 307 | 308) => Response;
76
- request: Request;
77
- set: {
78
- headers: HTTPHeaders;
79
- status?: number | keyof StatusMap;
80
- };
81
- }
82
-
83
- export interface ComponentProps<TParams = {}, TQuery = {}> {
84
- params: NormalizeUnset<TParams>;
85
- path: string;
86
- query: NormalizeUnset<TQuery>;
87
- }
88
-
89
- type ResolveParent<T> =
90
- T extends RouteRef<infer D, infer P, infer Q>
91
- ? { data: D; params: P; query: Q }
92
- : { data: {}; params: Unset; query: Unset };
93
-
94
- interface Resolved<TParentRef, TLoaderData, TParamsSchema = Unset, TQuerySchema = Unset> {
95
- // `Omit<TLoaderData, "__isDeferred">` strips the runtime brand that `defer()`
96
- // attaches to its return value. A layout/route loader wrapped with `defer()`
97
- // would otherwise leak `__isDeferred: true` into descendant loader contexts
98
- // and component props.
99
- data: ToRecord<ResolveParent<TParentRef>["data"] & Omit<TLoaderData, "__isDeferred">>;
100
- params: MergeSchema<ResolveParent<TParentRef>["params"], ResolvedSchema<TParamsSchema>>;
101
- query: MergeSchema<ResolveParent<TParentRef>["query"], ResolvedSchema<TQuerySchema>>;
102
- }
103
-
104
- export type MetaDescriptor =
105
- | { charSet: "utf-8" }
106
- | { title: string }
107
- | { name: string; content: string }
108
- | { property: string; content: string }
109
- | { httpEquiv: string; content: string }
110
- | { "script:ld+json": object }
111
- | { tagName: "meta" | "link"; [name: string]: string | undefined };
112
-
113
- export interface HeadOptions {
114
- links?: Array<{ rel: string; href: string; [key: string]: string }>;
115
- meta?: MetaDescriptor[];
116
- /**
117
- * Inline scripts injected into `<head>`.
118
- *
119
- * **Security warning:** `children` is injected as raw HTML — never pass
120
- * user-controlled or loader-derived data here without sanitisation.
121
- */
122
- scripts?: Array<{
123
- src?: string;
124
- type?: string;
125
- children?: string;
126
- [key: string]: string | undefined;
127
- }>;
128
- /**
129
- * Inline styles injected into `<head>`.
130
- *
131
- * **Security warning:** `children` is injected as raw HTML — never pass
132
- * user-controlled or loader-derived data here without sanitisation.
133
- */
134
- styles?: Array<{ type?: string; children: string }>;
135
- }
136
-
137
- // Extracts the resolved return type from a loader function type.
138
- // Using ReturnType + Awaited here means TLoader is inferred as the whole function
139
- // first, and then we extract the data — so inference is order-independent.
140
- // The `__isDeferred` key (DEFERRED_BRAND, see below) is stripped: a `defer()`
141
- // return carries that runtime marker, but it must never surface as a
142
- // component / head() prop — it is an internal implementation detail.
143
- type ExtractLoaderReturn<TLoader> = TLoader extends (...args: never[]) => unknown
144
- ? Awaited<ReturnType<TLoader>> extends object
145
- ? ToRecord<Omit<Awaited<ReturnType<TLoader>>, "__isDeferred">>
146
- : {}
147
- : {};
148
-
149
- export interface PageConfig<
150
- TParentData extends Record<string, unknown>,
151
- TParams,
152
- TQuery,
153
- TPageLoaderData extends object = {},
154
- > {
155
- component: React.FC<TParentData & TPageLoaderData & ComponentProps<TParams, TQuery>>;
156
- head?: (ctx: ComponentProps<TParams, TQuery> & TParentData & TPageLoaderData) => HeadOptions;
157
- loader?: (
158
- ctx: RouteContext<TParams, TQuery> & PromisifyData<TParentData>
159
- ) => Promise<TPageLoaderData> | TPageLoaderData;
160
- staticParams?: () => Promise<NormalizeUnset<TParams>[]> | NormalizeUnset<TParams>[];
161
- tags?: string[];
162
- }
163
-
164
- export interface RuntimeRoute {
165
- __type: "FURIN_ROUTE";
166
- layout?: React.FC<Record<string, unknown> & { children: React.ReactNode }>;
167
- loader?(ctx: Record<string, unknown>): Promise<Record<string, unknown>> | Record<string, unknown>;
168
- mode?: "ssr" | "ssg" | "isr";
169
- params?: unknown;
170
- parent?: RuntimeRoute;
171
- query?: unknown;
172
- revalidate?: number;
173
- tags?: string[];
174
- }
175
-
176
- export interface RuntimePage {
177
- __type: "FURIN_PAGE";
178
- _route: RuntimeRoute;
179
- component: React.FC<Record<string, unknown>>;
180
- head?(ctx: Record<string, unknown>): HeadOptions;
181
- loader?(ctx: Record<string, unknown>): Promise<Record<string, unknown>> | Record<string, unknown>;
182
- staticParams?(): Promise<Record<string, string>[]> | Record<string, string>[];
183
- tags?: string[];
184
- }
185
-
186
- export interface RouteRef<
187
- TData extends Record<string, unknown> = Record<string, unknown>,
188
- TParams = unknown,
189
- TQuery = unknown,
190
- > {
191
- readonly __brand: "FURIN_ROUTE_REF";
192
- readonly __phantom: { data: TData; params: TParams; query: TQuery };
193
- }
194
-
195
- interface PageResult<
196
- TData extends Record<string, unknown>,
197
- TParams,
198
- TQuery,
199
- TPageLoaderData extends object,
200
- > {
201
- __type: "FURIN_PAGE";
202
- _route: Route<TData, TParams, TQuery>;
203
- component: React.FC<TData & TPageLoaderData & ComponentProps<TParams, TQuery>>;
204
- head?: (ctx: ComponentProps<TParams, TQuery> & TData & TPageLoaderData) => HeadOptions;
205
- loader?: (
206
- ctx: RouteContext<TParams, TQuery> & PromisifyData<TData>
207
- ) => Promise<TPageLoaderData> | TPageLoaderData;
208
- tags?: string[];
209
- }
210
-
211
- export interface Route<TParentData extends Record<string, unknown>, TParams, TQuery> {
212
- __type: "FURIN_ROUTE";
213
- layout?: React.FC<TParentData & { children: React.ReactNode } & ComponentProps<TParams, TQuery>>;
214
- loader?(
215
- ctx: RouteContext<TParams, TQuery> & PromisifyData<TParentData>
216
- ): Promise<TParentData> | TParentData;
217
- mode?: "ssr" | "ssg" | "isr";
218
-
219
- // Overload 1 — loader present (required).
220
- // Two type params: TLoader is inferred solely from the `loader` position; TPageLoaderData
221
- // has no inference sites (all NoInfer) so TypeScript applies its default AFTER TLoader is
222
- // resolved — making declaration order of head/component irrelevant.
223
- page<
224
- TLoader extends (ctx: RouteContext<TParams, TQuery> & PromisifyData<TParentData>) => unknown,
225
- TPageLoaderData extends object = ExtractLoaderReturn<TLoader>,
226
- >(config: {
227
- loader: TLoader;
228
- mode?: "ssr" | "ssg" | "isr";
229
- revalidate?: number;
230
- staticParams?: () => Promise<NormalizeUnset<TParams>[]> | NormalizeUnset<TParams>[];
231
- tags?: string[];
232
- component: React.FC<NoInfer<TParentData & TPageLoaderData & ComponentProps<TParams, TQuery>>>;
233
- head?: (
234
- ctx: NoInfer<ComponentProps<TParams, TQuery> & TParentData & TPageLoaderData>
235
- ) => HeadOptions;
236
- }): PageResult<TParentData, TParams, TQuery, TPageLoaderData>;
237
-
238
- // Overload 2 — no loader.
239
- page(config: {
240
- mode?: "ssr" | "ssg" | "isr";
241
- revalidate?: number;
242
- staticParams?: () => Promise<NormalizeUnset<TParams>[]> | NormalizeUnset<TParams>[];
243
- tags?: string[];
244
- component: React.FC<TParentData & ComponentProps<TParams, TQuery>>;
245
- head?: (ctx: ComponentProps<TParams, TQuery> & TParentData) => HeadOptions;
246
- }): PageResult<TParentData, TParams, TQuery, {}>;
247
-
248
- params?: unknown;
249
- parent?: RuntimeRoute;
250
- query?: unknown;
251
-
252
- /** Branded ref for type inference when used as a parent. */
253
- ref: RouteRef<TParentData, TParams, TQuery>;
254
- revalidate?: number;
255
- tags?: string[];
256
- }
257
-
258
- export function createRoute<
259
- TParentRef extends RouteRef | undefined = undefined,
260
- TParamsSchema extends AnySchema | Unset = Unset,
261
- TQuerySchema extends AnySchema | Unset = Unset,
262
- TLoaderData extends object = {},
263
- >(config?: {
264
- parent?: { ref: TParentRef } & { __type: "FURIN_ROUTE" };
265
- mode?: "ssr" | "ssg" | "isr";
266
- revalidate?: number;
267
- params?: TParamsSchema;
268
- query?: TQuerySchema;
269
- tags?: string[];
270
- loader?: (
271
- ctx: RouteContext<
272
- Resolved<TParentRef, TLoaderData, TParamsSchema, TQuerySchema>["params"],
273
- Resolved<TParentRef, TLoaderData, TParamsSchema, TQuerySchema>["query"]
274
- > &
275
- PromisifyData<ResolveParent<TParentRef>["data"]>
276
- ) => Promise<TLoaderData> | TLoaderData;
277
- layout?: React.FC<
278
- Resolved<TParentRef, TLoaderData, TParamsSchema, TQuerySchema>["data"] & {
279
- children: React.ReactNode;
280
- } & ComponentProps<
281
- Resolved<TParentRef, TLoaderData, TParamsSchema, TQuerySchema>["params"],
282
- Resolved<TParentRef, TLoaderData, TParamsSchema, TQuerySchema>["query"]
283
- >
284
- >;
285
- }): Route<
286
- Resolved<TParentRef, TLoaderData, TParamsSchema, TQuerySchema>["data"],
287
- Resolved<TParentRef, TLoaderData, TParamsSchema, TQuerySchema>["params"],
288
- Resolved<TParentRef, TLoaderData, TParamsSchema, TQuerySchema>["query"]
289
- > {
290
- type R = Resolved<TParentRef, TLoaderData, TParamsSchema, TQuerySchema>;
291
-
292
- const route = {
293
- ...config,
294
- __type: "FURIN_ROUTE" as const,
295
- ref: {} as RouteRef<R["data"], R["params"], R["query"]>,
296
-
297
- // biome-ignore lint/suspicious/noExplicitAny: implementation signature for both overloads
298
- page(pageConfig: any) {
299
- return {
300
- ...pageConfig,
301
- __type: "FURIN_PAGE" as const,
302
- _route: route,
303
- };
304
- },
305
- };
306
- return route as Route<R["data"], R["params"], R["query"]>;
307
- }
308
-
309
- export type InferProps<T> = T extends {
310
- __type: "FURIN_PAGE";
311
- component: React.FC<infer P>;
312
- }
313
- ? P
314
- : T extends Route<infer D, infer P, infer Q>
315
- ? D & { children: React.ReactNode } & ComponentProps<P, Q>
316
- : never;
317
-
318
- // ── Deferred data ──────────────────────────────────────────────────────────────
319
-
320
- /**
321
- * Brand key that marks an object as deferred. Using a `const` string avoids
322
- * a `unique symbol` that would complicate cross-module inference.
323
- */
324
- const DEFERRED_BRAND = "__isDeferred" as const;
325
-
326
- /**
327
- * A loader return value that contains a mix of synchronous scalar fields and
328
- * lazy `Promise<T>` fields. Scalar fields are serialised into the initial HTML
329
- * shell; Promise fields are streamed as late `<script>` resolution chunks.
330
- *
331
- * @example
332
- * loader: () => defer({
333
- * title: "My Board", // synchronous — available immediately
334
- * stats: fetchStats(), // Promise — streamed when it resolves
335
- * })
336
- */
337
- export type DeferredData<T extends Record<string, unknown>> = T & {
338
- readonly [DEFERRED_BRAND]: true;
339
- };
340
-
341
- /**
342
- * Wraps loader data so that Promise-valued fields are streamed lazily while
343
- * scalar fields are embedded in the initial HTML shell immediately.
344
- *
345
- * Use in any loader — page (`route.page({ loader })`) or route/layout
346
- * (`createRoute({ loader })`). Promise-valued fields are streamed lazily;
347
- * scalar fields are embedded in the initial HTML shell.
348
- */
349
- export function defer<T extends Record<string, unknown>>(data: T): DeferredData<T> {
350
- if (Object.hasOwn(data, DEFERRED_BRAND)) {
351
- throw new Error(
352
- `[furin] defer() received an object with a reserved key "${DEFERRED_BRAND}". Rename this field to avoid conflicts with the deferred-data runtime.`
353
- );
354
- }
355
- return { ...data, [DEFERRED_BRAND]: true } as DeferredData<T>;
356
- }
357
-
358
- /**
359
- * Type guard for DeferredData. Used by the render pipeline to distinguish a
360
- * plain loader return from a deferred one.
361
- */
362
- export function isDeferred(v: unknown): v is DeferredData<Record<string, unknown>> {
363
- return (
364
- typeof v === "object" &&
365
- v !== null &&
366
- Object.hasOwn(v, DEFERRED_BRAND) &&
367
- (v as Record<typeof DEFERRED_BRAND, unknown>)[DEFERRED_BRAND] === true
368
- );
369
- }
1
+ /*
2
+ biome-ignore-all lint/complexity/noBannedTypes: The fundamental problem is that
3
+ `Record<string, unknown>` requires an index signature, and any type without one
4
+ (like `{}`, `object`, or a named interface) won't satisfy it. But `{}` is the only type that:
5
+ 1. Satisfies `Record<string, unknown>` as a generic default (TS special-cases `{}`)
6
+ 2. Doesn't have an index signature (so unknown prop access errors)
7
+ 3. Is transparent in intersections(`{} & T = T`)
8
+ */
9
+ /*
10
+ biome-ignore-all lint/performance/noBarrelFile: client.ts is the canonical DX
11
+ entry for furin/client consumers, not a generic internal barrel.
12
+ */
13
+
14
+ import type { Cookie, StatusMap } from "elysia";
15
+ import type { AnySchema, HTTPHeaders, UnwrapSchema } from "elysia/types";
16
+ import type { RequestLogger } from "evlog";
17
+
18
+ export {
19
+ type SyncMutation,
20
+ type SyncMutationContext,
21
+ type SyncMutationErrorContext,
22
+ type SyncMutationHeaders,
23
+ type SyncMutationOptions,
24
+ type SyncMutationRunner,
25
+ type SyncMutationSuccessContext,
26
+ type UseSyncOptions,
27
+ useSync,
28
+ } from "./client/sync.ts";
29
+ export { Await, useAsyncError, useAsyncValue } from "./shared/await.tsx";
30
+
31
+ declare const UNSET: unique symbol;
32
+ type Unset = typeof UNSET;
33
+
34
+ // Expands interfaces into plain mapped types so they satisfy Record<string, unknown>.
35
+ // Interfaces lack an implicit index signature; mapped types have one.
36
+ type ToRecord<T> = { [K in keyof T]: T[K] };
37
+
38
+ type ResolvedSchema<T> = [T] extends [Unset]
39
+ ? Unset
40
+ : T extends AnySchema
41
+ ? UnwrapSchema<T>
42
+ : Unset;
43
+
44
+ type MergeSchema<TParent, TOwn> = [TParent] extends [Unset]
45
+ ? TOwn
46
+ : [TOwn] extends [Unset]
47
+ ? TParent
48
+ : TParent & TOwn;
49
+
50
+ type NormalizeUnset<T> = [T] extends [Unset] ? {} : T;
51
+
52
+ /**
53
+ * Transforms each key of a parent-data record into an individual `Promise<T>`.
54
+ * This is what child loaders see for inherited fields — direct values from
55
+ * `RouteContext` (request, params, set, …) remain unchanged.
56
+ *
57
+ * `Awaited<T[K]>` mirrors the JS Promise-chaining auto-flatten used by
58
+ * `createLoaderCtx`: when an ancestor wrapped a field with `defer()` (so the
59
+ * raw value is itself a `Promise<U>`), the type collapses to `Promise<U>`
60
+ * instead of `Promise<Promise<U>>`. Otherwise TypeScript would force a
61
+ * redundant `await await ctx.field` dance.
62
+ */
63
+ type PromisifyData<T extends Record<string, unknown>> = {
64
+ [K in keyof T]: Promise<Awaited<T[K]>>;
65
+ };
66
+
67
+ export interface RouteContext<TParams = {}, TQuery = {}> {
68
+ cookie: Record<string, Cookie<unknown>>;
69
+ headers: Record<string, string | undefined>;
70
+ /** Request-scoped logger. Call `log.set({})` to attach fields to the wide event for this render. */
71
+ log: RequestLogger;
72
+ params: NormalizeUnset<TParams>;
73
+ path: string;
74
+ query: NormalizeUnset<TQuery>;
75
+ redirect: (url: string, status?: 301 | 302 | 303 | 307 | 308) => Response;
76
+ request: Request;
77
+ set: {
78
+ headers: HTTPHeaders;
79
+ status?: number | keyof StatusMap;
80
+ };
81
+ }
82
+
83
+ export interface ComponentProps<TParams = {}, TQuery = {}> {
84
+ params: NormalizeUnset<TParams>;
85
+ path: string;
86
+ query: NormalizeUnset<TQuery>;
87
+ }
88
+
89
+ type ResolveParent<T> =
90
+ T extends RouteRef<infer D, infer P, infer Q>
91
+ ? { data: D; params: P; query: Q }
92
+ : { data: {}; params: Unset; query: Unset };
93
+
94
+ interface Resolved<TParentRef, TLoaderData, TParamsSchema = Unset, TQuerySchema = Unset> {
95
+ // `Omit<TLoaderData, "__isDeferred">` strips the runtime brand that `defer()`
96
+ // attaches to its return value. A layout/route loader wrapped with `defer()`
97
+ // would otherwise leak `__isDeferred: true` into descendant loader contexts
98
+ // and component props.
99
+ data: ToRecord<ResolveParent<TParentRef>["data"] & Omit<TLoaderData, "__isDeferred">>;
100
+ params: MergeSchema<ResolveParent<TParentRef>["params"], ResolvedSchema<TParamsSchema>>;
101
+ query: MergeSchema<ResolveParent<TParentRef>["query"], ResolvedSchema<TQuerySchema>>;
102
+ }
103
+
104
+ export type MetaDescriptor =
105
+ | { charSet: "utf-8" }
106
+ | { title: string }
107
+ | { name: string; content: string }
108
+ | { property: string; content: string }
109
+ | { httpEquiv: string; content: string }
110
+ | { "script:ld+json": object }
111
+ | { tagName: "meta" | "link"; [name: string]: string | undefined };
112
+
113
+ export interface HeadOptions {
114
+ links?: Array<{ rel: string; href: string; [key: string]: string }>;
115
+ meta?: MetaDescriptor[];
116
+ /**
117
+ * Inline scripts injected into `<head>`.
118
+ *
119
+ * **Security warning:** `children` is injected as raw HTML — never pass
120
+ * user-controlled or loader-derived data here without sanitisation.
121
+ */
122
+ scripts?: Array<{
123
+ src?: string;
124
+ type?: string;
125
+ children?: string;
126
+ [key: string]: string | undefined;
127
+ }>;
128
+ /**
129
+ * Inline styles injected into `<head>`.
130
+ *
131
+ * **Security warning:** `children` is injected as raw HTML — never pass
132
+ * user-controlled or loader-derived data here without sanitisation.
133
+ */
134
+ styles?: Array<{ type?: string; children: string }>;
135
+ }
136
+
137
+ // Extracts the resolved return type from a loader function type.
138
+ // Using ReturnType + Awaited here means TLoader is inferred as the whole function
139
+ // first, and then we extract the data — so inference is order-independent.
140
+ // The `__isDeferred` key (DEFERRED_BRAND, see below) is stripped: a `defer()`
141
+ // return carries that runtime marker, but it must never surface as a
142
+ // component / head() prop — it is an internal implementation detail.
143
+ type ExtractLoaderReturn<TLoader> = TLoader extends (...args: never[]) => unknown
144
+ ? Awaited<ReturnType<TLoader>> extends object
145
+ ? ToRecord<Omit<Awaited<ReturnType<TLoader>>, "__isDeferred">>
146
+ : {}
147
+ : {};
148
+
149
+ export interface PageConfig<
150
+ TParentData extends Record<string, unknown>,
151
+ TParams,
152
+ TQuery,
153
+ TPageLoaderData extends object = {},
154
+ > {
155
+ component: React.FC<TParentData & TPageLoaderData & ComponentProps<TParams, TQuery>>;
156
+ head?: (ctx: ComponentProps<TParams, TQuery> & TParentData & TPageLoaderData) => HeadOptions;
157
+ loader?: (
158
+ ctx: RouteContext<TParams, TQuery> & PromisifyData<TParentData>
159
+ ) => Promise<TPageLoaderData> | TPageLoaderData;
160
+ staticParams?: () => Promise<NormalizeUnset<TParams>[]> | NormalizeUnset<TParams>[];
161
+ tags?: string[];
162
+ }
163
+
164
+ export interface RuntimeRoute {
165
+ __type: "FURIN_ROUTE";
166
+ layout?: React.FC<Record<string, unknown> & { children: React.ReactNode }>;
167
+ loader?(ctx: Record<string, unknown>): Promise<Record<string, unknown>> | Record<string, unknown>;
168
+ mode?: "ssr" | "ssg" | "isr";
169
+ params?: unknown;
170
+ parent?: RuntimeRoute;
171
+ query?: unknown;
172
+ revalidate?: number;
173
+ tags?: string[];
174
+ }
175
+
176
+ export interface RuntimePage {
177
+ __type: "FURIN_PAGE";
178
+ _route: RuntimeRoute;
179
+ component: React.FC<Record<string, unknown>>;
180
+ head?(ctx: Record<string, unknown>): HeadOptions;
181
+ loader?(ctx: Record<string, unknown>): Promise<Record<string, unknown>> | Record<string, unknown>;
182
+ staticParams?(): Promise<Record<string, string>[]> | Record<string, string>[];
183
+ tags?: string[];
184
+ }
185
+
186
+ export interface RouteRef<
187
+ TData extends Record<string, unknown> = Record<string, unknown>,
188
+ TParams = unknown,
189
+ TQuery = unknown,
190
+ > {
191
+ readonly __brand: "FURIN_ROUTE_REF";
192
+ readonly __phantom: { data: TData; params: TParams; query: TQuery };
193
+ }
194
+
195
+ interface PageResult<
196
+ TData extends Record<string, unknown>,
197
+ TParams,
198
+ TQuery,
199
+ TPageLoaderData extends object,
200
+ > {
201
+ __type: "FURIN_PAGE";
202
+ _route: Route<TData, TParams, TQuery>;
203
+ component: React.FC<TData & TPageLoaderData & ComponentProps<TParams, TQuery>>;
204
+ head?: (ctx: ComponentProps<TParams, TQuery> & TData & TPageLoaderData) => HeadOptions;
205
+ loader?: (
206
+ ctx: RouteContext<TParams, TQuery> & PromisifyData<TData>
207
+ ) => Promise<TPageLoaderData> | TPageLoaderData;
208
+ tags?: string[];
209
+ }
210
+
211
+ export interface Route<TParentData extends Record<string, unknown>, TParams, TQuery> {
212
+ __type: "FURIN_ROUTE";
213
+ layout?: React.FC<TParentData & { children: React.ReactNode } & ComponentProps<TParams, TQuery>>;
214
+ loader?(
215
+ ctx: RouteContext<TParams, TQuery> & PromisifyData<TParentData>
216
+ ): Promise<TParentData> | TParentData;
217
+ mode?: "ssr" | "ssg" | "isr";
218
+
219
+ // Overload 1 — loader present (required).
220
+ // Two type params: TLoader is inferred solely from the `loader` position; TPageLoaderData
221
+ // has no inference sites (all NoInfer) so TypeScript applies its default AFTER TLoader is
222
+ // resolved — making declaration order of head/component irrelevant.
223
+ page<
224
+ TLoader extends (ctx: RouteContext<TParams, TQuery> & PromisifyData<TParentData>) => unknown,
225
+ TPageLoaderData extends object = ExtractLoaderReturn<TLoader>,
226
+ >(config: {
227
+ loader: TLoader;
228
+ mode?: "ssr" | "ssg" | "isr";
229
+ revalidate?: number;
230
+ staticParams?: () => Promise<NormalizeUnset<TParams>[]> | NormalizeUnset<TParams>[];
231
+ tags?: string[];
232
+ component: React.FC<NoInfer<TParentData & TPageLoaderData & ComponentProps<TParams, TQuery>>>;
233
+ head?: (
234
+ ctx: NoInfer<ComponentProps<TParams, TQuery> & TParentData & TPageLoaderData>
235
+ ) => HeadOptions;
236
+ }): PageResult<TParentData, TParams, TQuery, TPageLoaderData>;
237
+
238
+ // Overload 2 — no loader.
239
+ page(config: {
240
+ mode?: "ssr" | "ssg" | "isr";
241
+ revalidate?: number;
242
+ staticParams?: () => Promise<NormalizeUnset<TParams>[]> | NormalizeUnset<TParams>[];
243
+ tags?: string[];
244
+ component: React.FC<TParentData & ComponentProps<TParams, TQuery>>;
245
+ head?: (ctx: ComponentProps<TParams, TQuery> & TParentData) => HeadOptions;
246
+ }): PageResult<TParentData, TParams, TQuery, {}>;
247
+
248
+ params?: unknown;
249
+ parent?: RuntimeRoute;
250
+ query?: unknown;
251
+
252
+ /** Branded ref for type inference when used as a parent. */
253
+ ref: RouteRef<TParentData, TParams, TQuery>;
254
+ revalidate?: number;
255
+ tags?: string[];
256
+ }
257
+
258
+ export function createRoute<
259
+ TParentRef extends RouteRef | undefined = undefined,
260
+ TParamsSchema extends AnySchema | Unset = Unset,
261
+ TQuerySchema extends AnySchema | Unset = Unset,
262
+ TLoaderData extends object = {},
263
+ >(config?: {
264
+ parent?: { ref: TParentRef } & { __type: "FURIN_ROUTE" };
265
+ mode?: "ssr" | "ssg" | "isr";
266
+ revalidate?: number;
267
+ params?: TParamsSchema;
268
+ query?: TQuerySchema;
269
+ tags?: string[];
270
+ loader?: (
271
+ ctx: RouteContext<
272
+ Resolved<TParentRef, TLoaderData, TParamsSchema, TQuerySchema>["params"],
273
+ Resolved<TParentRef, TLoaderData, TParamsSchema, TQuerySchema>["query"]
274
+ > &
275
+ PromisifyData<ResolveParent<TParentRef>["data"]>
276
+ ) => Promise<TLoaderData> | TLoaderData;
277
+ layout?: React.FC<
278
+ Resolved<TParentRef, TLoaderData, TParamsSchema, TQuerySchema>["data"] & {
279
+ children: React.ReactNode;
280
+ } & ComponentProps<
281
+ Resolved<TParentRef, TLoaderData, TParamsSchema, TQuerySchema>["params"],
282
+ Resolved<TParentRef, TLoaderData, TParamsSchema, TQuerySchema>["query"]
283
+ >
284
+ >;
285
+ }): Route<
286
+ Resolved<TParentRef, TLoaderData, TParamsSchema, TQuerySchema>["data"],
287
+ Resolved<TParentRef, TLoaderData, TParamsSchema, TQuerySchema>["params"],
288
+ Resolved<TParentRef, TLoaderData, TParamsSchema, TQuerySchema>["query"]
289
+ > {
290
+ type R = Resolved<TParentRef, TLoaderData, TParamsSchema, TQuerySchema>;
291
+
292
+ const route = {
293
+ ...config,
294
+ __type: "FURIN_ROUTE" as const,
295
+ ref: {} as RouteRef<R["data"], R["params"], R["query"]>,
296
+
297
+ // biome-ignore lint/suspicious/noExplicitAny: implementation signature for both overloads
298
+ page(pageConfig: any) {
299
+ return {
300
+ ...pageConfig,
301
+ __type: "FURIN_PAGE" as const,
302
+ _route: route,
303
+ };
304
+ },
305
+ };
306
+ return route as Route<R["data"], R["params"], R["query"]>;
307
+ }
308
+
309
+ export type InferProps<T> = T extends {
310
+ __type: "FURIN_PAGE";
311
+ component: React.FC<infer P>;
312
+ }
313
+ ? P
314
+ : T extends Route<infer D, infer P, infer Q>
315
+ ? D & { children: React.ReactNode } & ComponentProps<P, Q>
316
+ : never;
317
+
318
+ // ── Deferred data ──────────────────────────────────────────────────────────────
319
+
320
+ /**
321
+ * Brand key that marks an object as deferred. Using a `const` string avoids
322
+ * a `unique symbol` that would complicate cross-module inference.
323
+ */
324
+ const DEFERRED_BRAND = "__isDeferred" as const;
325
+
326
+ /**
327
+ * A loader return value that contains a mix of synchronous scalar fields and
328
+ * lazy `Promise<T>` fields. Scalar fields are serialised into the initial HTML
329
+ * shell; Promise fields are streamed as late `<script>` resolution chunks.
330
+ *
331
+ * @example
332
+ * loader: () => defer({
333
+ * title: "My Board", // synchronous — available immediately
334
+ * stats: fetchStats(), // Promise — streamed when it resolves
335
+ * })
336
+ */
337
+ export type DeferredData<T extends Record<string, unknown>> = T & {
338
+ readonly [DEFERRED_BRAND]: true;
339
+ };
340
+
341
+ /**
342
+ * Wraps loader data so that Promise-valued fields are streamed lazily while
343
+ * scalar fields are embedded in the initial HTML shell immediately.
344
+ *
345
+ * Use in any loader — page (`route.page({ loader })`) or route/layout
346
+ * (`createRoute({ loader })`). Promise-valued fields are streamed lazily;
347
+ * scalar fields are embedded in the initial HTML shell.
348
+ */
349
+ export function defer<T extends Record<string, unknown>>(data: T): DeferredData<T> {
350
+ if (Object.hasOwn(data, DEFERRED_BRAND)) {
351
+ throw new Error(
352
+ `[furin] defer() received an object with a reserved key "${DEFERRED_BRAND}". Rename this field to avoid conflicts with the deferred-data runtime.`
353
+ );
354
+ }
355
+ return { ...data, [DEFERRED_BRAND]: true } as DeferredData<T>;
356
+ }
357
+
358
+ /**
359
+ * Type guard for DeferredData. Used by the render pipeline to distinguish a
360
+ * plain loader return from a deferred one.
361
+ */
362
+ export function isDeferred(v: unknown): v is DeferredData<Record<string, unknown>> {
363
+ return (
364
+ typeof v === "object" &&
365
+ v !== null &&
366
+ Object.hasOwn(v, DEFERRED_BRAND) &&
367
+ (v as Record<typeof DEFERRED_BRAND, unknown>)[DEFERRED_BRAND] === true
368
+ );
369
+ }