@teyik0/furin 0.1.0-alpha.13 → 0.1.0-alpha.15

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 (69) hide show
  1. package/README.md +14 -232
  2. package/dist/auto-invalidate/index.d.ts +4 -0
  3. package/dist/auto-invalidate/plugin.d.ts +38 -0
  4. package/dist/auto-invalidate/registry.d.ts +9 -0
  5. package/dist/auto-invalidate/runtime.d.ts +9 -0
  6. package/dist/auto-invalidate/types.d.ts +12 -0
  7. package/dist/await.d.ts +67 -0
  8. package/dist/build/index.js +2095 -185
  9. package/dist/cli/index.js +2070 -182
  10. package/dist/client.d.ts +51 -4
  11. package/dist/client.js +65 -1
  12. package/dist/deferred-ndjson.d.ts +32 -0
  13. package/dist/error.d.ts +14 -0
  14. package/dist/furin.d.ts +8 -0
  15. package/dist/furin.js +2927 -319
  16. package/dist/lang-detect.d.ts +5 -0
  17. package/dist/link.d.ts +1 -0
  18. package/dist/link.js +1453 -95
  19. package/dist/plugin/index.js +96 -25
  20. package/dist/plugin/transform-client.d.ts +2 -1
  21. package/dist/render/assemble.d.ts +32 -0
  22. package/dist/render/cache.d.ts +7 -0
  23. package/dist/render/element.d.ts +17 -1
  24. package/dist/render/index.d.ts +10 -1
  25. package/dist/render/index.ts +250 -44
  26. package/dist/render/loaders.d.ts +46 -3
  27. package/dist/render/shell.d.ts +16 -6
  28. package/dist/render/shell.ts +27 -12
  29. package/dist/router-provider.d.ts +86 -18
  30. package/dist/router.d.ts +66 -0
  31. package/dist/router.js +2909 -374
  32. package/dist/router.ts +586 -54
  33. package/dist/server-error.d.ts +12 -0
  34. package/dist/utils.d.ts +7 -0
  35. package/package.json +8 -7
  36. package/src/adapter/bun.ts +3 -3
  37. package/src/adapter/static.ts +73 -31
  38. package/src/auto-invalidate/index.ts +10 -0
  39. package/src/auto-invalidate/plugin.ts +25 -0
  40. package/src/auto-invalidate/registry.ts +60 -0
  41. package/src/auto-invalidate/runtime.ts +133 -0
  42. package/src/auto-invalidate/types.ts +16 -0
  43. package/src/await.tsx +175 -0
  44. package/src/build/client.ts +4 -8
  45. package/src/build/hydrate.ts +67 -1
  46. package/src/build/route-types.ts +29 -3
  47. package/src/build/scan-server.ts +6 -23
  48. package/src/client.ts +80 -3
  49. package/src/deferred-ndjson.ts +212 -0
  50. package/src/dev-page-plugin.ts +2 -0
  51. package/src/error.ts +18 -1
  52. package/src/furin.ts +19 -2
  53. package/src/lang-detect.ts +46 -0
  54. package/src/link.tsx +16 -3
  55. package/src/plugin/index.ts +7 -8
  56. package/src/plugin/transform-client.ts +108 -39
  57. package/src/render/assemble.ts +67 -0
  58. package/src/render/boundaries.tsx +23 -5
  59. package/src/render/cache.ts +14 -0
  60. package/src/render/default-screens.tsx +4 -11
  61. package/src/render/dev-cache.ts +5 -0
  62. package/src/render/element.tsx +26 -3
  63. package/src/render/index.ts +250 -44
  64. package/src/render/loaders.ts +219 -18
  65. package/src/render/shell.ts +27 -12
  66. package/src/router-provider.tsx +414 -122
  67. package/src/router.ts +586 -54
  68. package/src/server-error.ts +47 -0
  69. package/src/utils.ts +31 -0
@@ -0,0 +1,12 @@
1
+ export interface FurinServerErrorPayload {
2
+ digest: string;
3
+ message: string;
4
+ status: number;
5
+ }
6
+ export declare class FurinServerError extends Error {
7
+ readonly __furinBrand: "FURIN_SERVER_ERROR";
8
+ readonly digest: string;
9
+ readonly status: number;
10
+ constructor(args: FurinServerErrorPayload);
11
+ }
12
+ export declare function isFurinServerError(err: unknown): err is FurinServerError;
package/dist/utils.d.ts CHANGED
@@ -3,4 +3,11 @@ export declare function isFurinPage(value: unknown): value is RuntimePage;
3
3
  export declare function isFurinRoute(value: unknown): value is RuntimeRoute;
4
4
  export declare function collectRouteChainFromRoute(route: RuntimeRoute): RuntimeRoute[];
5
5
  export declare function hasCycle(route: RuntimeRoute): boolean;
6
+ /**
7
+ * Maps over `items` with a bounded worker pool, preserving input order.
8
+ * Use whenever an `await Promise.all(items.map(...))` would open as many
9
+ * concurrent async operations as there are items — unbounded fan-out can
10
+ * exhaust file descriptors, sockets, or memory on large inputs.
11
+ */
12
+ export declare function mapWithConcurrency<T, R>(items: readonly T[], concurrency: number, fn: (item: T, index: number) => Promise<R>): Promise<R[]>;
6
13
  export declare function validateRouteChain(chain: RuntimeRoute[], root: RuntimeRoute, pagePath?: string): void;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@teyik0/furin",
3
- "version": "0.1.0-alpha.13",
3
+ "version": "0.1.0-alpha.15",
4
4
  "description": "React meta-framework powered by Elysia and Bun with file-based routing, SSR, SSG, and ISR.",
5
5
  "license": "MIT",
6
6
  "author": "teyik0",
@@ -38,7 +38,7 @@
38
38
  "module": "./dist/furin.js",
39
39
  "types": "./dist/furin.d.ts",
40
40
  "bin": {
41
- "furin": "./dist/cli/index.js"
41
+ "furin": "./src/cli/index.ts"
42
42
  },
43
43
  "exports": {
44
44
  ".": {
@@ -91,17 +91,18 @@
91
91
  "dependencies": {
92
92
  "@elysiajs/static": "^1.4.10",
93
93
  "magic-string": "^0.30.21",
94
- "yuku-parser": "^0.4.6"
94
+ "seroval": "^1.5.4",
95
+ "yuku-parser": "^0.5.15"
95
96
  },
96
97
  "devDependencies": {
97
- "@types/react": "^19.2.14",
98
+ "@types/react": "^19.2.15",
98
99
  "@types/react-dom": "^19.2.3",
99
100
  "expect-type": "^1.3.0"
100
101
  },
101
102
  "peerDependencies": {
102
103
  "elysia": "^1.4.28",
103
- "evlog": "^2.14.1",
104
- "react": "^19.2.5",
105
- "react-dom": "^19.2.5"
104
+ "evlog": "^2.17.0",
105
+ "react": "^19.2.6",
106
+ "react-dom": "^19.2.6"
106
107
  }
107
108
  }
@@ -65,7 +65,7 @@ async function createBuildFingerprint(
65
65
  }
66
66
 
67
67
  const fileParts = await Promise.all(
68
- [...fingerprintPaths].sort().map(async (path) => {
68
+ [...fingerprintPaths].toSorted().map(async (path) => {
69
69
  const content = existsSync(path) ? await Bun.file(path).text() : "";
70
70
  return `${toPosixPath(path)}:${content}`;
71
71
  })
@@ -77,7 +77,7 @@ async function createBuildFingerprint(
77
77
  )
78
78
  .sort();
79
79
 
80
- return [entryChunk, ...[...cssChunks].sort(), ...routeParts, ...fileParts].join("\n");
80
+ return [entryChunk, ...[...cssChunks].toSorted(), ...routeParts, ...fileParts].join("\n");
81
81
  }
82
82
 
83
83
  function buildCompileMetadata(root: RootLayout, routes: ResolvedRoute[]) {
@@ -150,7 +150,7 @@ export async function buildBunTarget(
150
150
  const clientDir = join(targetDir, "client");
151
151
  writeFileSync(
152
152
  join(clientDir, "index.html"),
153
- generateProdIndexHtml(entryChunk, cssChunks, buildId)
153
+ generateProdIndexHtml(entryChunk, cssChunks, buildId, undefined, false)
154
154
  );
155
155
 
156
156
  const routeManifest = routes.map((r) => ({ pattern: r.pattern, path: r.path, mode: r.mode }));
@@ -9,6 +9,7 @@ import { prerenderSSG } from "../render/index.ts";
9
9
  import { generateProdIndexHtml } from "../render/shell.ts";
10
10
  import { setProductionTemplateContent } from "../render/template.ts";
11
11
  import type { ResolvedRoute, RootLayout } from "../router.ts";
12
+ import { mapWithConcurrency } from "../utils.ts";
12
13
 
13
14
  /** Maximum concurrent pre-render calls (mirrors warmSSGCache). */
14
15
  const STATIC_CONCURRENCY = 4;
@@ -22,20 +23,21 @@ const TRAILING_SLASHES_RE = /\/+$/;
22
23
  // ── Path helpers ──────────────────────────────────────────────────────────────
23
24
 
24
25
  /**
25
- * Converts a URL path to a filesystem output path.
26
- * "/" → "outDir/index.html"
27
- * "/docs/routing" → "outDir/docs/routing/index.html"
26
+ * Converts a URL path to a filesystem output path for the given file name.
27
+ * "/" + "index.html" → "outDir/index.html"
28
+ * "/docs/routing" + "index.html" → "outDir/docs/routing/index.html"
29
+ * "/docs/routing" + "__furin_data.ndjson" → "outDir/docs/routing/__furin_data.ndjson"
28
30
  *
29
31
  * The resolved path is validated to stay within `outDir` so that `..`
30
32
  * segments injected via dynamic `staticParams()` values cannot escape
31
33
  * the output directory.
32
34
  */
33
- function pathToOutputFile(urlPath: string, outDir: string): string {
35
+ function pathToOutputFile(urlPath: string, outDir: string, fileName: string): string {
34
36
  const normalizedOutDir = resolve(outDir);
35
37
  if (urlPath === "/" || urlPath === "") {
36
- return join(normalizedOutDir, "index.html");
38
+ return join(normalizedOutDir, fileName);
37
39
  }
38
- const resolved = resolve(normalizedOutDir, urlPath.slice(1), "index.html");
40
+ const resolved = resolve(normalizedOutDir, urlPath.slice(1), fileName);
39
41
  if (!resolved.startsWith(`${normalizedOutDir}${sep}`)) {
40
42
  throw new Error(
41
43
  `[furin] static: unsafe output path detected for URL "${urlPath}" — path traversal via ".." is not allowed.`
@@ -56,7 +58,8 @@ async function prerenderAndWrite(
56
58
  basePath: string
57
59
  ): Promise<void> {
58
60
  const urlPath = resolvePath(route.pattern, params);
59
- const outputFile = pathToOutputFile(urlPath, outDir);
61
+ const htmlOutputFile = pathToOutputFile(urlPath, outDir, "index.html");
62
+ const dataOutputFile = pathToOutputFile(urlPath, outDir, "__furin_data.ndjson");
60
63
 
61
64
  try {
62
65
  const entry = await prerenderSSG(route, params, root, "http://localhost", basePath);
@@ -68,10 +71,14 @@ async function prerenderAndWrite(
68
71
  return;
69
72
  }
70
73
 
71
- ensureDir(dirname(outputFile));
72
- writeFileSync(outputFile, entry.html);
74
+ ensureDir(dirname(htmlOutputFile));
75
+ writeFileSync(htmlOutputFile, entry.html);
76
+ // Persist the loader payload at a static-friendly URL: SPA navigation on
77
+ // file-server deployments (GitHub Pages, S3, …) fetches this file instead
78
+ // of the runtime `/_furin/data?path=…` endpoint, which doesn't exist there.
79
+ writeFileSync(dataOutputFile, entry.ndjson);
73
80
  renderedRoutes.push(urlPath);
74
- console.log(`[furin] static: ${urlPath} → ${toPosixPath(outputFile)}`);
81
+ console.log(`[furin] static: ${urlPath} → ${toPosixPath(htmlOutputFile)}`);
75
82
  } catch (err) {
76
83
  console.error(
77
84
  `[furin] static: prerender failed for "${route.pattern}" (params: ${JSON.stringify(params)}):`,
@@ -135,32 +142,67 @@ async function buildTaskQueue(
135
142
  ): Promise<Array<() => Promise<void>>> {
136
143
  const tasks: Array<() => Promise<void>> = [];
137
144
 
138
- for (const route of ssgRoutes) {
139
- if (!DYNAMIC_SEGMENT_RE.test(route.pattern)) {
140
- tasks.push(() =>
141
- prerenderAndWrite(route, {}, root, outDir, renderedRoutes, skippedRoutes, basePath)
145
+ type StaticParamsResult =
146
+ | { paramSets: Record<string, string>[] | null; route: ResolvedRoute }
147
+ | { error: unknown; paramSets: null; route: ResolvedRoute };
148
+
149
+ const staticParamsResults: StaticParamsResult[] = await mapWithConcurrency(
150
+ ssgRoutes,
151
+ STATIC_CONCURRENCY,
152
+ async (route) => {
153
+ if (!DYNAMIC_SEGMENT_RE.test(route.pattern)) {
154
+ return { route, paramSets: [{}] };
155
+ }
156
+ if (!route.page.staticParams) {
157
+ console.warn(
158
+ `[furin] static: skipping dynamic route "${route.pattern}" — no staticParams() defined.`
159
+ );
160
+ skippedRoutes.push(route.pattern);
161
+ return { route, paramSets: null };
162
+ }
163
+ try {
164
+ const paramSets = (await route.page.staticParams()) ?? [];
165
+ return { route, paramSets };
166
+ } catch (err) {
167
+ return { error: err, paramSets: null, route };
168
+ }
169
+ }
170
+ );
171
+
172
+ for (const result of staticParamsResults) {
173
+ if ("error" in result) {
174
+ console.error(
175
+ `[furin] static: staticParams() failed for "${result.route.pattern}":`,
176
+ result.error
142
177
  );
178
+ skippedRoutes.push(result.route.pattern);
143
179
  continue;
144
180
  }
145
-
146
- if (!route.page.staticParams) {
147
- console.warn(
148
- `[furin] static: skipping dynamic route "${route.pattern}" — no staticParams() defined.`
181
+ if (result.paramSets === null) {
182
+ continue;
183
+ }
184
+ // Defend against staticParams() returning a non-array (e.g. a bare object
185
+ // or `null`-after-coercion). Without this guard, a single malformed route
186
+ // would throw out of `for...of` and abort the entire build.
187
+ if (!Array.isArray(result.paramSets)) {
188
+ console.error(
189
+ `[furin] static: staticParams() for "${result.route.pattern}" returned a non-array value; skipping route.`
149
190
  );
150
- skippedRoutes.push(route.pattern);
191
+ skippedRoutes.push(result.route.pattern);
151
192
  continue;
152
193
  }
153
-
154
- try {
155
- const paramSets = (await route.page.staticParams()) ?? [];
156
- for (const params of paramSets) {
157
- tasks.push(() =>
158
- prerenderAndWrite(route, params, root, outDir, renderedRoutes, skippedRoutes, basePath)
159
- );
160
- }
161
- } catch (err) {
162
- console.error(`[furin] static: staticParams() failed for "${route.pattern}":`, err);
163
- skippedRoutes.push(route.pattern);
194
+ for (const params of result.paramSets) {
195
+ tasks.push(() =>
196
+ prerenderAndWrite(
197
+ result.route,
198
+ params,
199
+ root,
200
+ outDir,
201
+ renderedRoutes,
202
+ skippedRoutes,
203
+ basePath
204
+ )
205
+ );
164
206
  }
165
207
  }
166
208
 
@@ -275,7 +317,7 @@ export async function buildStaticTarget(
275
317
  // This ensures the browser finds it even when the site is served from a sub-path.
276
318
  const publicFavicon = join(rootDir, "public", "favicon.ico");
277
319
  const faviconHref = existsSync(publicFavicon) ? `${basePath}/favicon.ico` : undefined;
278
- const shellHtml = generateProdIndexHtml(entryChunk, cssChunks, undefined, faviconHref);
320
+ const shellHtml = generateProdIndexHtml(entryChunk, cssChunks, undefined, faviconHref, true);
279
321
 
280
322
  // ── 5. Prime the renderer with the production shell ──────────────────────
281
323
  // Must be called before any prerenderSSG invocation.
@@ -0,0 +1,10 @@
1
+ // biome-ignore-all lint/performance/noBarrelFile: auto-invalidate has a small public/internal surface gathered for tests and furin.ts exports
2
+ export { furinInvalidate } from "./plugin.ts";
3
+ export { AutoInvalidateRegistry, autoInvalidateRegistry } from "./registry.ts";
4
+ export {
5
+ appendPendingInvalidationHeader,
6
+ isSuccessfulMutationResponse,
7
+ revalidateTag,
8
+ runInvalidationRules,
9
+ } from "./runtime.ts";
10
+ export type { InvalidationInput, InvalidationRule } from "./types.ts";
@@ -0,0 +1,25 @@
1
+ import { type AfterHandler, Elysia } from "elysia";
2
+ import {
3
+ appendPendingInvalidationHeader,
4
+ isSuccessfulMutationResponse,
5
+ runInvalidationRules,
6
+ } from "./runtime.ts";
7
+ import type { InvalidationInput } from "./types.ts";
8
+
9
+ type AnyAfterHandleContext = Parameters<AfterHandler>[0];
10
+
11
+ export function furinInvalidate() {
12
+ return new Elysia({ name: "furin-invalidate" }).macro({
13
+ invalidate(rules: InvalidationInput) {
14
+ return {
15
+ afterHandle(ctx: AnyAfterHandleContext) {
16
+ if (!isSuccessfulMutationResponse(ctx)) {
17
+ return;
18
+ }
19
+ runInvalidationRules(rules);
20
+ appendPendingInvalidationHeader(ctx.set);
21
+ },
22
+ };
23
+ },
24
+ });
25
+ }
@@ -0,0 +1,60 @@
1
+ export class AutoInvalidateRegistry {
2
+ private readonly pathToTags = new Map<string, Set<string>>();
3
+ private readonly tagToPaths = new Map<string, Set<string>>();
4
+
5
+ registerLoaderTags(urlPath: string, tags: readonly string[] | undefined): void {
6
+ if (!tags || tags.length === 0) {
7
+ this.unregisterPath(urlPath);
8
+ return;
9
+ }
10
+
11
+ this.unregisterPath(urlPath);
12
+
13
+ const uniqueTags = new Set(tags);
14
+ this.pathToTags.set(urlPath, uniqueTags);
15
+ for (const tag of uniqueTags) {
16
+ let paths = this.tagToPaths.get(tag);
17
+ if (!paths) {
18
+ paths = new Set<string>();
19
+ this.tagToPaths.set(tag, paths);
20
+ }
21
+ paths.add(urlPath);
22
+ }
23
+ }
24
+
25
+ pathsForTags(tags: readonly string[]): string[] {
26
+ const paths = new Set<string>();
27
+ for (const tag of tags) {
28
+ for (const path of this.tagToPaths.get(tag) ?? []) {
29
+ paths.add(path);
30
+ }
31
+ }
32
+ return [...paths];
33
+ }
34
+
35
+ unregisterPath(urlPath: string): void {
36
+ const tags = this.pathToTags.get(urlPath);
37
+ if (!tags) {
38
+ return;
39
+ }
40
+
41
+ for (const tag of tags) {
42
+ const paths = this.tagToPaths.get(tag);
43
+ if (!paths) {
44
+ continue;
45
+ }
46
+ paths.delete(urlPath);
47
+ if (paths.size === 0) {
48
+ this.tagToPaths.delete(tag);
49
+ }
50
+ }
51
+ this.pathToTags.delete(urlPath);
52
+ }
53
+
54
+ reset(): void {
55
+ this.pathToTags.clear();
56
+ this.tagToPaths.clear();
57
+ }
58
+ }
59
+
60
+ export const autoInvalidateRegistry = new AutoInvalidateRegistry();
@@ -0,0 +1,133 @@
1
+ import type { Context } from "elysia";
2
+ import { consumePendingInvalidations, revalidatePath } from "../render/cache.ts";
3
+ import { autoInvalidateRegistry } from "./registry.ts";
4
+ import type { InvalidationInput, InvalidationRule } from "./types.ts";
5
+
6
+ function toRules(input: InvalidationInput): readonly InvalidationRule[] {
7
+ return Array.isArray(input) ? input : [input as InvalidationRule];
8
+ }
9
+
10
+ function statusFromResponseValue(responseValue: unknown): number | undefined {
11
+ if (responseValue instanceof Response) {
12
+ return responseValue.status;
13
+ }
14
+ if (responseValue && typeof responseValue === "object" && "status" in responseValue) {
15
+ const status = (responseValue as { status?: unknown }).status;
16
+ if (typeof status === "number") {
17
+ return status;
18
+ }
19
+ }
20
+ if (responseValue && typeof responseValue === "object" && "code" in responseValue) {
21
+ const code = (responseValue as { code?: unknown }).code;
22
+ if (typeof code === "number") {
23
+ return code;
24
+ }
25
+ }
26
+ return;
27
+ }
28
+
29
+ export function isSuccessfulMutationResponse(
30
+ ctx: Pick<Context, "set"> & {
31
+ responseValue?: unknown;
32
+ response?: unknown;
33
+ }
34
+ ): boolean {
35
+ const responseStatus =
36
+ statusFromResponseValue(ctx.responseValue) ?? statusFromResponseValue(ctx.response);
37
+ if (responseStatus !== undefined) {
38
+ return responseStatus >= 200 && responseStatus < 400;
39
+ }
40
+
41
+ const setStatus = ctx.set.status;
42
+ if (typeof setStatus === "number") {
43
+ return setStatus >= 200 && setStatus < 400;
44
+ }
45
+ if (typeof setStatus === "string") {
46
+ // Elysia allows string status codes (e.g. "Not Found"). We cannot map
47
+ // every possible string to its numeric code without the StatusMap, so we
48
+ // treat known client-error (4xx) and server-error (5xx) texts as failures
49
+ // and everything else as success (1xx, 2xx, 3xx, and any unknown string).
50
+ const errorStatusTexts = new Set([
51
+ "Bad Request",
52
+ "Unauthorized",
53
+ "Payment Required",
54
+ "Forbidden",
55
+ "Not Found",
56
+ "Method Not Allowed",
57
+ "Not Acceptable",
58
+ "Proxy Authentication Required",
59
+ "Request Timeout",
60
+ "Conflict",
61
+ "Gone",
62
+ "Length Required",
63
+ "Precondition Failed",
64
+ "Payload Too Large",
65
+ "URI Too Long",
66
+ "Unsupported Media Type",
67
+ "Range Not Satisfiable",
68
+ "Expectation Failed",
69
+ "I'm a teapot",
70
+ "Misdirected Request",
71
+ "Unprocessable Content",
72
+ "Locked",
73
+ "Failed Dependency",
74
+ "Too Early",
75
+ "Upgrade Required",
76
+ "Precondition Required",
77
+ "Too Many Requests",
78
+ "Enhance Your Calm",
79
+ "Request Header Fields Too Large",
80
+ "Unavailable For Legal Reasons",
81
+ "Internal Server Error",
82
+ "Not Implemented",
83
+ "Bad Gateway",
84
+ "Service Unavailable",
85
+ "Gateway Timeout",
86
+ "HTTP Version Not Supported",
87
+ "Variant Also Negotiates",
88
+ "Insufficient Storage",
89
+ "Loop Detected",
90
+ "Not Extended",
91
+ "Network Authentication Required",
92
+ ]);
93
+ return !errorStatusTexts.has(setStatus);
94
+ }
95
+ // No explicit status was set — default to success (200).
96
+ return true;
97
+ }
98
+
99
+ export function appendPendingInvalidationHeader(set: Context["set"]): void {
100
+ const pending = consumePendingInvalidations();
101
+ if (pending.length === 0) {
102
+ return;
103
+ }
104
+
105
+ const headerName = "x-furin-revalidate";
106
+ const existing = set.headers[headerName];
107
+ set.headers[headerName] =
108
+ typeof existing === "string" && existing.length > 0
109
+ ? `${existing},${pending.join(",")}`
110
+ : pending.join(",");
111
+ }
112
+
113
+ export function revalidateTag(tags: string | readonly string[]): boolean {
114
+ const tagList = typeof tags === "string" ? [tags] : [...tags];
115
+ let deleted = false;
116
+ for (const path of autoInvalidateRegistry.pathsForTags(tagList)) {
117
+ deleted = revalidatePath(path, "page") || deleted;
118
+ }
119
+ return deleted;
120
+ }
121
+
122
+ export function runInvalidationRules(input: InvalidationInput): boolean {
123
+ let deleted = false;
124
+ for (const rule of toRules(input)) {
125
+ if ("path" in rule && rule.path) {
126
+ deleted = revalidatePath(rule.path, rule.type) || deleted;
127
+ }
128
+ if (rule.tags && rule.tags.length > 0) {
129
+ deleted = revalidateTag(rule.tags) || deleted;
130
+ }
131
+ }
132
+ return deleted;
133
+ }
@@ -0,0 +1,16 @@
1
+ import type { CacheTag } from "../furin.ts";
2
+ import type { RevalidateType } from "../render/route-cache.ts";
3
+
4
+ export type InvalidationRule =
5
+ | {
6
+ path: string;
7
+ tags?: readonly CacheTag[];
8
+ type: RevalidateType;
9
+ }
10
+ | {
11
+ path?: never;
12
+ tags: readonly CacheTag[];
13
+ type?: never;
14
+ };
15
+
16
+ export type InvalidationInput = InvalidationRule | readonly InvalidationRule[];
package/src/await.tsx ADDED
@@ -0,0 +1,175 @@
1
+ import { Component, createContext, createElement, type ReactNode, use } from "react";
2
+
3
+ // ── Async error context ────────────────────────────────────────────────────────
4
+
5
+ /**
6
+ * Context used to pass the caught error from `AsyncErrorBoundary` down to
7
+ * `errorElement` children so they can read it via `useAsyncError()`.
8
+ */
9
+ export const AsyncErrorContext = createContext<unknown>(undefined);
10
+
11
+ /**
12
+ * Inside an `<Await errorElement={...}>`, returns the error that caused the
13
+ * deferred Promise to reject. Throws outside of an error-boundary subtree.
14
+ */
15
+ export function useAsyncError(): unknown {
16
+ return use(AsyncErrorContext);
17
+ }
18
+
19
+ /**
20
+ * Inside a resolved `<Await>`, returns the resolved value via React 19's
21
+ * `use()`. Can be used as an alternative to the render-prop children API.
22
+ *
23
+ * Must be used inside a component that is rendered as children of `<Await>`.
24
+ */
25
+ export function useAsyncValue<T>(): T {
26
+ // This hook is intended to be used inside <Await>'s children renderer.
27
+ // The actual value is accessed via the AwaitValueContext.
28
+ const ctx = use(AwaitValueContext) as { promise: Promise<T> } | undefined;
29
+ if (!ctx) {
30
+ throw new Error("useAsyncValue must be used inside <Await> children");
31
+ }
32
+ return use(ctx.promise);
33
+ }
34
+
35
+ const AwaitValueContext = createContext<{ promise: Promise<unknown> } | undefined>(undefined);
36
+
37
+ // ── Error boundary ─────────────────────────────────────────────────────────────
38
+
39
+ interface AsyncErrorBoundaryProps {
40
+ children?: ReactNode;
41
+ errorElement: ReactNode | undefined;
42
+ resolve: Promise<unknown>;
43
+ }
44
+
45
+ interface AsyncErrorBoundaryState {
46
+ error: unknown;
47
+ hasError: boolean;
48
+ resolve: Promise<unknown> | undefined;
49
+ }
50
+
51
+ /**
52
+ * Class-based error boundary that wraps `<Await>` to catch rejected Promises.
53
+ * When `use(promise)` triggers an unhandled rejection during render, React
54
+ * propagates it to the nearest error boundary — this one catches it and
55
+ * renders the user-provided `errorElement`.
56
+ *
57
+ * NOTE: React error boundaries require `getDerivedStateFromError`, which only
58
+ * exists on class components — this class is intentional and cannot be replaced
59
+ * by a function component.
60
+ */
61
+ // biome-ignore lint/style/useReactFunctionComponents: error boundaries require getDerivedStateFromError, which has no function-component equivalent
62
+ class AsyncErrorBoundary extends Component<AsyncErrorBoundaryProps, AsyncErrorBoundaryState> {
63
+ constructor(props: AsyncErrorBoundaryProps) {
64
+ super(props);
65
+ this.state = { hasError: false, error: undefined, resolve: props.resolve };
66
+ }
67
+
68
+ static getDerivedStateFromProps(
69
+ props: AsyncErrorBoundaryProps,
70
+ state: AsyncErrorBoundaryState
71
+ ): Partial<AsyncErrorBoundaryState> | null {
72
+ if (props.resolve !== state.resolve) {
73
+ return { hasError: false, error: undefined, resolve: props.resolve };
74
+ }
75
+ return null;
76
+ }
77
+
78
+ static getDerivedStateFromError(error: unknown): Partial<AsyncErrorBoundaryState> {
79
+ return { hasError: true, error };
80
+ }
81
+
82
+ override render(): ReactNode {
83
+ const { hasError, error } = this.state;
84
+ const { children, errorElement } = this.props;
85
+
86
+ if (hasError) {
87
+ if (errorElement === undefined) {
88
+ // No errorElement provided — re-throw so the nearest Suspense/parent boundary handles it
89
+ throw error;
90
+ }
91
+ // Provide the error via context so useAsyncError() can access it
92
+ return createElement(AsyncErrorContext.Provider, { value: error }, errorElement);
93
+ }
94
+ return children;
95
+ }
96
+ }
97
+
98
+ // ── <Await> component ──────────────────────────────────────────────────────────
99
+
100
+ export interface AwaitProps<T> {
101
+ /**
102
+ * Render-prop children: called with the resolved value once the Promise
103
+ * settles. The returned `ReactNode` is rendered inside a Suspense boundary.
104
+ *
105
+ * Marked optional here so `createElement(Await, props, renderFn)` is
106
+ * accepted by TypeScript — the 3rd argument to `createElement` becomes
107
+ * `children` at runtime and is always required for correct behaviour.
108
+ */
109
+ children?: (value: T) => ReactNode;
110
+ /**
111
+ * Rendered when the Promise rejects. Inside this subtree, `useAsyncError()`
112
+ * returns the rejection reason. When omitted the error propagates up to the
113
+ * next React error boundary.
114
+ */
115
+ errorElement?: ReactNode;
116
+ /**
117
+ * The deferred Promise to await. Passed as a prop so React's `use()` can
118
+ * suspend the boundary until it resolves. This is the same Promise object
119
+ * that the loader returned inside `defer()`.
120
+ */
121
+ resolve: Promise<T>;
122
+ }
123
+
124
+ /**
125
+ * Deferred-data boundary component. Uses React 19's `use()` to suspend the
126
+ * render until `resolve` settles, then calls the render-prop `children` with
127
+ * the resolved value.
128
+ *
129
+ * Wrap with `<Suspense fallback={…}>` to show a loading indicator while the
130
+ * Promise is pending.
131
+ *
132
+ * @example
133
+ * ```tsx
134
+ * export default route.page({
135
+ * loader: () => defer({ board: "x", stats: fetchStats() }),
136
+ * component: ({ board, stats }) => (
137
+ * <div>
138
+ * <h1>{board}</h1>
139
+ * <Suspense fallback={<Spinner />}>
140
+ * <Await resolve={stats}>
141
+ * {(s) => <StatsBar stats={s} />}
142
+ * </Await>
143
+ * </Suspense>
144
+ * </div>
145
+ * ),
146
+ * });
147
+ * ```
148
+ */
149
+ export function Await<T>({ resolve, errorElement, children }: AwaitProps<T>): ReactNode {
150
+ return createElement(
151
+ AsyncErrorBoundary,
152
+ { errorElement, resolve: resolve as Promise<unknown> },
153
+ // react-doctor-disable-next-line react/no-children-prop
154
+ createElement(AwaitInner<T>, { resolve, children })
155
+ );
156
+ }
157
+
158
+ interface AwaitInnerProps<T> {
159
+ children?: (value: T) => ReactNode;
160
+ resolve: Promise<T>;
161
+ }
162
+
163
+ /**
164
+ * Inner component that calls `use(resolve)` — this is intentionally a
165
+ * separate component so `AsyncErrorBoundary` above it can catch any errors
166
+ * thrown during the `use()` suspension protocol.
167
+ */
168
+ function AwaitInner<T>({ resolve, children }: AwaitInnerProps<T>): ReactNode {
169
+ const value = use(resolve);
170
+ return createElement(
171
+ AwaitValueContext.Provider,
172
+ { value: { promise: resolve as Promise<unknown> } },
173
+ children ? children(value) : null
174
+ );
175
+ }