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

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 (132) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +33 -33
  3. package/dist/adapter/bun.d.ts +3 -0
  4. package/dist/adapter/static.d.ts +3 -0
  5. package/dist/build/client.d.ts +25 -0
  6. package/dist/build/compile-entry.d.ts +9 -0
  7. package/dist/build/compile-entry.ts +109 -0
  8. package/dist/build/entry-template.d.ts +38 -0
  9. package/dist/build/entry-template.ts +156 -0
  10. package/dist/build/hydrate.d.ts +24 -0
  11. package/dist/build/index.d.ts +8 -0
  12. package/dist/build/index.js +8106 -0
  13. package/dist/build/route-types.d.ts +23 -0
  14. package/dist/build/scan-server.d.ts +8 -0
  15. package/dist/build/server-routes-entry.d.ts +13 -0
  16. package/dist/build/server-routes-entry.ts +36 -0
  17. package/dist/build/shared.d.ts +12 -0
  18. package/dist/build/ssg-cache.d.ts +4 -0
  19. package/dist/build/types.d.ts +80 -0
  20. package/dist/cli/config.d.ts +9 -0
  21. package/dist/cli/index.d.ts +2 -0
  22. package/dist/cli/index.js +8097 -0
  23. package/dist/client/boundaries.d.ts +117 -0
  24. package/dist/client/default-screens.d.ts +17 -0
  25. package/dist/client/link.d.ts +22 -0
  26. package/dist/client/link.js +4244 -0
  27. package/dist/client/router/boundary-tree.d.ts +26 -0
  28. package/dist/client/router/context.d.ts +8 -0
  29. package/dist/client/router/history.d.ts +9 -0
  30. package/dist/client/router/index.d.ts +11 -0
  31. package/dist/client/router/link-utils.d.ts +53 -0
  32. package/dist/client/router/navigation.d.ts +10 -0
  33. package/dist/client/router/provider.d.ts +4 -0
  34. package/dist/client/router/search/index.d.ts +18 -0
  35. package/dist/client/router/search-store.d.ts +21 -0
  36. package/dist/client/router/spa-response.d.ts +58 -0
  37. package/dist/client/router/types.d.ts +292 -0
  38. package/dist/client/server-error.d.ts +12 -0
  39. package/dist/client/sync.d.ts +25 -0
  40. package/dist/client.d.ts +243 -0
  41. package/dist/client.js +140 -0
  42. package/dist/config.d.ts +57 -0
  43. package/dist/config.js +29 -0
  44. package/dist/env.d.ts +50 -0
  45. package/dist/furin.d.ts +77 -0
  46. package/dist/furin.js +8693 -0
  47. package/dist/plugin/index.d.ts +20 -0
  48. package/dist/plugin/index.js +1500 -0
  49. package/dist/plugin/transform-client.d.ts +10 -0
  50. package/dist/server/auto-invalidate/index.d.ts +4 -0
  51. package/dist/server/auto-invalidate/plugin.d.ts +38 -0
  52. package/dist/server/auto-invalidate/registry.d.ts +9 -0
  53. package/dist/server/auto-invalidate/runtime.d.ts +9 -0
  54. package/dist/server/auto-invalidate/types.d.ts +12 -0
  55. package/dist/server/cache/dev-loader.d.ts +28 -0
  56. package/dist/server/cache/index.d.ts +10 -0
  57. package/dist/server/cache/invalidation.d.ts +12 -0
  58. package/dist/server/cache/isr-ssg.d.ts +26 -0
  59. package/dist/server/cache/isr.d.ts +6 -0
  60. package/dist/server/cache/registry.d.ts +5 -0
  61. package/dist/server/cache/route-cache.d.ts +26 -0
  62. package/dist/server/cache/ssg.d.ts +5 -0
  63. package/dist/server/context-logger.d.ts +28 -0
  64. package/dist/server/dev-inspector.d.ts +89 -0
  65. package/dist/server/dev-page-plugin.d.ts +112 -0
  66. package/dist/server/internal.d.ts +35 -0
  67. package/dist/server/internal.js +17 -0
  68. package/dist/server/lang-detect.d.ts +5 -0
  69. package/dist/server/render/assemble.d.ts +49 -0
  70. package/dist/server/render/element.d.ts +24 -0
  71. package/dist/server/render/index.d.ts +7 -0
  72. package/dist/server/render/index.ts +22 -0
  73. package/dist/server/render/isr.d.ts +4 -0
  74. package/dist/server/render/loaders.d.ts +64 -0
  75. package/dist/server/render/not-found.d.ts +6 -0
  76. package/dist/server/render/shell.d.ts +39 -0
  77. package/dist/server/render/shell.ts +202 -0
  78. package/dist/server/render/ssg.d.ts +9 -0
  79. package/dist/server/render/ssr.d.ts +108 -0
  80. package/dist/server/render/template.d.ts +6 -0
  81. package/dist/server/router/discovery.d.ts +16 -0
  82. package/dist/server/router/hmr.d.ts +65 -0
  83. package/dist/server/router/index.d.ts +6 -0
  84. package/dist/server/router/index.js +27 -0
  85. package/dist/server/router/index.ts +28 -0
  86. package/dist/server/router/patterns.d.ts +40 -0
  87. package/dist/server/router/plugin.d.ts +21 -0
  88. package/dist/server/router/schemas.d.ts +59 -0
  89. package/dist/server/router/types.d.ts +60 -0
  90. package/dist/server/runtime-env.d.ts +3 -0
  91. package/dist/server/runtime-env.js +10 -0
  92. package/dist/server/sync/config.d.ts +6 -0
  93. package/dist/server/sync/index.d.ts +4 -0
  94. package/dist/server/sync/plugin.d.ts +369 -0
  95. package/dist/server/sync/stream.d.ts +47 -0
  96. package/dist/shared/await.d.ts +67 -0
  97. package/dist/shared/deferred-ndjson.d.ts +32 -0
  98. package/dist/shared/digest.d.ts +16 -0
  99. package/dist/shared/error.d.ts +37 -0
  100. package/dist/shared/not-found.d.ts +19 -0
  101. package/dist/shared/search-params.d.ts +17 -0
  102. package/dist/shared/utils/ast-walk.d.ts +18 -0
  103. package/dist/shared/utils/index.d.ts +13 -0
  104. package/package.json +5 -5
  105. package/src/adapter/README.md +13 -13
  106. package/src/build/client.ts +152 -152
  107. package/src/build/compile-entry.ts +109 -109
  108. package/src/build/entry-template.ts +156 -156
  109. package/src/build/hydrate.ts +340 -337
  110. package/src/build/index.ts +152 -152
  111. package/src/build/route-types.ts +145 -145
  112. package/src/build/scan-server.ts +95 -95
  113. package/src/build/server-routes-entry.ts +36 -36
  114. package/src/build/shared.ts +80 -79
  115. package/src/build/ssg-cache.ts +32 -32
  116. package/src/build/types.ts +89 -89
  117. package/src/client/router/link-utils.ts +184 -177
  118. package/src/client/router/provider.tsx +804 -759
  119. package/src/client/router/types.ts +276 -271
  120. package/src/client/sync.ts +98 -0
  121. package/src/client.ts +369 -355
  122. package/src/furin.ts +465 -444
  123. package/src/server/auto-invalidate/runtime.ts +134 -133
  124. package/src/server/dev-page-plugin.ts +454 -449
  125. package/src/server/render/assemble.ts +160 -133
  126. package/src/server/render/isr.ts +323 -317
  127. package/src/server/render/ssr.ts +585 -583
  128. package/src/server/router/plugin.ts +384 -384
  129. package/src/server/sync/config.ts +29 -0
  130. package/src/server/sync/index.ts +14 -0
  131. package/src/server/sync/plugin.ts +108 -0
  132. package/src/server/sync/stream.ts +144 -0
package/src/furin.ts CHANGED
@@ -1,444 +1,465 @@
1
- import { existsSync } from "node:fs";
2
- import { basename, dirname, join, resolve } from "node:path";
3
- import { fileURLToPath } from "node:url";
4
- import { staticPlugin } from "@elysiajs/static";
5
- import { type AnyElysia, Elysia, file } from "elysia";
6
- import { type DrainContext, initLogger } from "evlog";
7
- import { type EvlogElysiaOptions, evlog } from "evlog/elysia";
8
- import {
9
- _runWithRequestInvalidationScope,
10
- consumePendingInvalidations,
11
- getBuildId,
12
- setBuildId,
13
- } from "./server/cache/invalidation.ts";
14
- import { setSSGCache } from "./server/cache/ssg.ts";
15
- import type { CompileContext, EmbeddedAppData } from "./server/internal.ts";
16
- import { getCompileContext } from "./server/internal.ts";
17
- import { renderRootNotFound, warmSSGCache } from "./server/render/index.ts";
18
- import {
19
- setProductionTemplateContent,
20
- setProductionTemplatePath,
21
- } from "./server/render/template.ts";
22
- import {
23
- createDataEndpoint,
24
- createRoutePlugin,
25
- createSearchRouteMetadata,
26
- loadProdRoutes,
27
- } from "./server/router/index.ts";
28
- import { IS_DEV } from "./server/runtime-env.ts";
29
-
30
- // biome-ignore lint/suspicious/noEmptyInterface: intentionally augmentable via furin-env.d.ts
31
- export interface FurinCacheTags {}
32
-
33
- export type CacheTag = keyof FurinCacheTags extends never ? string : keyof FurinCacheTags;
34
-
35
- function resolveClientDirFromArgv(): string {
36
- return (
37
- resolveClientDirFromEnv() ??
38
- resolveClientDirFromModuleUrl() ??
39
- resolveClientDirFromProcessArgs() ??
40
- resolveFallbackClientDir()
41
- );
42
- }
43
-
44
- function resolveClientDirFromEnv(): string | null {
45
- const envClientDir = process.env.FURIN_CLIENT_DIR;
46
- if (!envClientDir) {
47
- return null;
48
- }
49
- return envClientDir.startsWith("/") ? envClientDir : resolve(process.cwd(), envClientDir);
50
- }
51
-
52
- function resolveClientDirFromModuleUrl(): string | null {
53
- try {
54
- const moduleUrl = new URL(import.meta.url);
55
- if (moduleUrl.protocol !== "file:") {
56
- return null;
57
- }
58
- const modulePath = fileURLToPath(moduleUrl);
59
- if (modulePath.includes("/$bunfs/")) {
60
- return null;
61
- }
62
- const moduleClientDir = join(dirname(modulePath), "client");
63
- if (existsSync(join(moduleClientDir, "index.html"))) {
64
- return moduleClientDir;
65
- }
66
- } catch {
67
- // ignore, fallback to argv-based resolution
68
- }
69
- return null;
70
- }
71
-
72
- function resolveClientDirFromProcessArgs(): string | null {
73
- const candidates = [
74
- process.argv[1],
75
- process.argv[0],
76
- (process as { argv0?: string }).argv0,
77
- process.execPath,
78
- ].filter((value): value is string => typeof value === "string" && value.length > 0);
79
-
80
- for (const candidate of candidates) {
81
- const resolved = resolveClientDirFromCandidate(candidate);
82
- if (resolved) {
83
- return resolved;
84
- }
85
- }
86
-
87
- return null;
88
- }
89
-
90
- function resolveClientDirFromCandidate(candidate: string): string | null {
91
- const name = basename(candidate);
92
- if (name === "bun" || name === "node") {
93
- return null;
94
- }
95
- if (candidate.includes("/$bunfs/") || candidate.startsWith("bunfs:")) {
96
- return null;
97
- }
98
-
99
- const absolute = candidate.startsWith("/") ? candidate : resolve(process.cwd(), candidate);
100
- if (existsSync(absolute)) {
101
- return join(dirname(absolute), "client");
102
- }
103
-
104
- if (!candidate.includes("/")) {
105
- return resolveClientDirFromPath(candidate);
106
- }
107
-
108
- return null;
109
- }
110
-
111
- function resolveClientDirFromPath(candidate: string): string | null {
112
- const pathEntries = process.env.PATH?.split(":") ?? [];
113
- for (const dir of pathEntries) {
114
- const fullPath = join(dir, candidate);
115
- if (existsSync(fullPath)) {
116
- return join(dirname(fullPath), "client");
117
- }
118
- }
119
- return null;
120
- }
121
-
122
- function resolveFallbackClientDir(): string {
123
- const defaultClientDir = resolve(process.cwd(), ".furin/build/bun/client");
124
- if (existsSync(join(defaultClientDir, "index.html"))) {
125
- return defaultClientDir;
126
- }
127
-
128
- return join(process.cwd(), "client");
129
- }
130
-
131
- async function setupProdTemplate(
132
- embedded: EmbeddedAppData | undefined,
133
- clientDir: string
134
- ): Promise<void> {
135
- if (embedded) {
136
- if (!embedded.template) {
137
- throw new Error("[furin] Embedded app is missing its HTML template (index.html).");
138
- }
139
- const html = await Bun.file(embedded.template).text();
140
- setProductionTemplateContent(html);
141
- return;
142
- }
143
-
144
- const templatePath = join(clientDir, "index.html");
145
- if (!existsSync(templatePath)) {
146
- throw new Error("[furin] No pre-built assets found. Run `bun run build` first.");
147
- }
148
- setProductionTemplatePath(templatePath);
149
- }
150
-
151
- /**
152
- * Registers a HigherOrderFunction on the Elysia instance so that every request
153
- * runs inside a fresh `AsyncLocalStorage` scope. This isolates
154
- * `pendingInvalidations` per request, preventing concurrent requests from
155
- * stealing each other's `revalidatePath()` calls.
156
- *
157
- * Uses `app.wrap()` (Elysia HigherOrderFunction) instead of mutating
158
- * `app.handle`, because handle mutations are lost when the Furin plugin is
159
- * `.use()`-d by a parent Elysia instance. HigherOrderFunctions survive the
160
- * plugin merge and wrap the entire composed `map` handler.
161
- */
162
- function wrapWithRequestScope(app: AnyElysia): Elysia {
163
- return app.wrap(
164
- (handler, _request) => (ctx: unknown) => _runWithRequestInvalidationScope(() => handler(ctx))
165
- );
166
- }
167
-
168
- function hydrateSSGCacheFromCompileContext(ctx: CompileContext): void {
169
- if (!ctx.ssgCache) {
170
- return;
171
- }
172
- for (const [path, entry] of Object.entries(ctx.ssgCache)) {
173
- setSSGCache(path, entry);
174
- }
175
- }
176
-
177
- /**
178
- * Main Furin plugin.
179
- *
180
- * Returns a standalone Elysia instance (async function) so that routes are
181
- * properly registered in Elysia's router for SPA navigation to work.
182
- *
183
- * ## Usage
184
- *
185
- * ```ts
186
- * new Elysia()
187
- * .use(await furin({ ... }))
188
- * .listen(3000)
189
- * ```
190
- */
191
- export async function furin({
192
- pagesDir,
193
- logger,
194
- clientLogging,
195
- }: {
196
- pagesDir?: string;
197
- logger?: EvlogElysiaOptions;
198
- /**
199
- * Initialize the browser HTTP log drain in the hydration entry. Off by
200
- * default — enabling it adds `evlog/http` drain setup and points browser
201
- * events at `/_furin/ingest`. Server-side logging is configured via `logger`
202
- * and unaffected.
203
- */
204
- clientLogging?: boolean;
205
- }) {
206
- const { exclude: userExclude, ...evlogOptions } = logger ?? {};
207
- initLogger({ env: { service: "furin" } });
208
-
209
- const loggerPlugin = new Elysia()
210
- .use(
211
- evlog({
212
- ...evlogOptions,
213
- exclude: [
214
- "/_client/**",
215
- "/public/**",
216
- "/favicon.ico",
217
- "/_bun_hmr_entry/**",
218
- // Note: /_furin/data is logged with the *logical* path rewritten by
219
- // createDataEndpoint via useLogger().set({ path }), so SPA navigations
220
- // appear as "GET /board/123 200" — same shape as a normal SSR nav.
221
- // /_furin/ingest is kept loggable so browser-side events show up.
222
- // evlog's `matchesPattern` only supports `*`, `**`, `?` — extglob
223
- // like `!(...)` matches nothing, so don't add patterns relying on it.
224
- ...(userExclude ?? []),
225
- ],
226
- })
227
- )
228
- .post(
229
- "/_furin/ingest",
230
- ({ body, log, status }) => {
231
- if (!Array.isArray(body)) {
232
- return status("Bad Request");
233
- }
234
- // Cap batch size to prevent abuse
235
- const batch = (body as DrainContext[]).slice(0, 100);
236
- for (const entry of batch) {
237
- if (!entry || typeof entry !== "object" || !("event" in entry)) {
238
- log.set({ msg: "[furin] ingest: skipping malformed entry" });
239
- continue;
240
- }
241
- // Pick only safe, known fields from the event to prevent prototype pollution
242
- const event = entry.event as Record<string, unknown> | undefined;
243
- if (!event || typeof event !== "object") {
244
- continue;
245
- }
246
- const {
247
- __proto__,
248
- constructor: _ctor,
249
- prototype,
250
- environment: _browserEnv,
251
- ...safeEvent
252
- } = event as Record<string, unknown>;
253
- log.set({ ...safeEvent, service: "furin:browser" });
254
- }
255
- return status("No Content");
256
- },
257
- { parse: "json" }
258
- );
259
-
260
- const cwd = process.cwd();
261
- const ctx = getCompileContext();
262
- const resolvedPagesDir = ctx?.rootPath
263
- ? dirname(ctx.rootPath)
264
- : resolve(cwd, pagesDir ?? "src/pages");
265
-
266
- // Unique name per pagesDir to avoid Elysia's name-based plugin dedup.
267
- const instanceName = `furin-${resolvedPagesDir.replaceAll("\\", "/")}`;
268
-
269
- // ── Dev: Bun native HMR ────────────────────────────────────────────────
270
- if (IS_DEV) {
271
- const furinDir = resolve(cwd, ".furin");
272
- // Lazy import — build pipeline has native deps not available in compiled binaries
273
- const { registerDevPagePlugin } = await import("./server/dev-page-plugin.ts");
274
- registerDevPagePlugin();
275
-
276
- const { createDevInspectorPlugin } = await import("./server/dev-inspector.ts");
277
-
278
- const { scanPages } = await import("./server/router/index.ts");
279
- const { root, routes } = await scanPages(resolvedPagesDir);
280
- const searchRoutes = createSearchRouteMetadata(routes);
281
-
282
- const { writeDevFiles } = await import("./build/hydrate.ts");
283
- writeDevFiles(
284
- routes,
285
- {
286
- outDir: furinDir,
287
- rootLayout: root.path,
288
- basePath: "",
289
- publicPath: "/_client/",
290
- clientLogging: clientLogging ?? false,
291
- },
292
- cwd
293
- );
294
-
295
- const publicDir = resolve(cwd, "public");
296
- const publicExists = existsSync(publicDir);
297
-
298
- const devApp = new Elysia({ name: instanceName, seed: resolvedPagesDir })
299
- .use(loggerPlugin)
300
- .onError({ as: "global" }, async ({ code, request }) => {
301
- if (code === "NOT_FOUND") {
302
- return await renderRootNotFound(root, request);
303
- }
304
- })
305
- .onAfterHandle({ as: "global" }, ({ set }) => {
306
- // Forward pending revalidation paths so the client can bust its prefetch cache
307
- const pending = consumePendingInvalidations();
308
- if (pending.length > 0) {
309
- set.headers["x-furin-revalidate"] = pending.join(",");
310
- }
311
- })
312
- .use(await staticPlugin({ assets: furinDir, prefix: "/_bun_hmr_entry", bunFullstack: true }))
313
- .use(
314
- publicExists ? await staticPlugin({ assets: publicDir, prefix: "/public" }) : new Elysia()
315
- )
316
- .get(
317
- "/favicon.ico",
318
- publicExists
319
- ? file(join(publicDir, "favicon.ico"))
320
- : () => new Response(null, { status: 404 })
321
- )
322
- .use(createDevInspectorPlugin())
323
- .use(createDataEndpoint(routes))
324
- .use((app) => {
325
- for (const route of routes) {
326
- app.use(createRoutePlugin(route, root, undefined, searchRoutes));
327
- }
328
- return app;
329
- });
330
- return wrapWithRequestScope(devApp);
331
- }
332
-
333
- // ── Production ──────────────────────────────────────────────────────────
334
- if (!ctx) {
335
- throw new Error("[furin] No pre-built assets found. Run `bunx furin build` first.");
336
- }
337
- const { root, routes } = loadProdRoutes(ctx);
338
- const searchRoutes = createSearchRouteMetadata(routes);
339
- const prodBuildId = ctx.buildId ?? "";
340
- setBuildId(prodBuildId);
341
- hydrateSSGCacheFromCompileContext(ctx);
342
-
343
- const embedded = ctx?.embedded;
344
- const clientDir = embedded ? "" : resolveClientDirFromArgv();
345
- await setupProdTemplate(embedded, clientDir);
346
-
347
- const prodApp = new Elysia({ name: instanceName, seed: resolvedPagesDir })
348
- .use(loggerPlugin)
349
- .onError({ as: "global" }, async ({ code, request }) => {
350
- if (code === "NOT_FOUND") {
351
- return await renderRootNotFound(root, request);
352
- }
353
- })
354
- .onAfterHandle({ as: "global" }, ({ path, set }) => {
355
- // Content-hashed client assets are permanently cacheable — browsers never need to
356
- // revalidate them because any change produces a new filename.
357
- if (path.startsWith("/_client/")) {
358
- set.headers["cache-control"] = "public, max-age=31536000, immutable";
359
- }
360
- // Forward pending revalidation paths so the client can bust its prefetch cache
361
- const pending = consumePendingInvalidations();
362
- if (pending.length > 0) {
363
- set.headers["x-furin-revalidate"] = pending.join(",");
364
- }
365
- // Tell the client the current build ID so it can detect stale deploys
366
- const buildId = getBuildId();
367
- if (buildId) {
368
- set.headers["x-furin-build-id"] = buildId;
369
- }
370
- })
371
- .onStart(async ({ server }) => {
372
- if (ctx.ssgCache) {
373
- return;
374
- }
375
- const origin = server?.url?.origin ?? "http://localhost:3000";
376
- await warmSSGCache(routes, root, origin, searchRoutes);
377
- })
378
- .use(
379
- await (async () => {
380
- if (embedded) {
381
- return new Elysia()
382
- .get("/favicon.ico", ({ status }) => {
383
- const asset = embedded.assets["/public/favicon.ico"];
384
- if (!asset) {
385
- return status("Not Found");
386
- }
387
- return Bun.file(asset);
388
- })
389
- .get("/_client/*", ({ params, status }) => {
390
- const asset = embedded.assets[`/_client/${params["*"]}`];
391
- if (!asset) {
392
- return status("Not Found");
393
- }
394
- return Bun.file(asset);
395
- })
396
- .get("/public/*", ({ params, status }) => {
397
- const asset = embedded.assets[`/public/${params["*"]}`];
398
- if (!asset) {
399
- return status("Not Found");
400
- }
401
- return Bun.file(asset);
402
- });
403
- }
404
- const publicDir = join(dirname(clientDir), "public");
405
- const app = new Elysia();
406
- if (existsSync(publicDir)) {
407
- app
408
- .get("/favicon.ico", file(join(publicDir, "favicon.ico")))
409
- .use(await staticPlugin({ assets: publicDir, prefix: "/public" }));
410
- }
411
- app.use(await staticPlugin({ assets: clientDir, prefix: "/_client" }));
412
- return app;
413
- })()
414
- )
415
- .use(createDataEndpoint(routes))
416
- .use((app) => {
417
- for (const route of routes) {
418
- app.use(createRoutePlugin(route, root, prodBuildId, searchRoutes));
419
- }
420
- return app;
421
- });
422
- return wrapWithRequestScope(prodApp);
423
- }
424
-
425
- // biome-ignore lint/performance/noBarrelFile: furin.ts is the public package entry
426
- export { FurinErrorBoundary, FurinNotFoundBoundary } from "./client/boundaries.tsx";
427
- // ── Public API re-export ──────────────────────────────────────────────────────
428
- // biome-ignore-start lint/performance/noBarrelFile: intentional — furin.ts is the public package entry
429
- export type { DeferredData, RuntimePage, RuntimeRoute } from "./client.ts";
430
- export { defer, isDeferred } from "./client.ts";
431
- export type { InvalidationInput, InvalidationRule } from "./server/auto-invalidate/index.ts";
432
- export { furinInvalidate, revalidateTag } from "./server/auto-invalidate/index.ts";
433
- export { revalidatePath, setCachePurger } from "./server/cache/invalidation.ts";
434
- export { buildElement, buildErrorElement, renderRootNotFound } from "./server/render/index.ts";
435
- export type { ResolvedRoute, SegmentBoundary } from "./server/router/index.ts";
436
- export { Await, useAsyncError, useAsyncValue } from "./shared/await.tsx";
437
- export type { ErrorComponent, ErrorProps } from "./shared/error.ts";
438
- export type {
439
- NotFoundComponent,
440
- NotFoundOptions,
441
- NotFoundProps,
442
- } from "./shared/not-found.ts";
443
- export { isNotFoundError, notFound } from "./shared/not-found.ts";
444
- // biome-ignore-end lint/performance/noBarrelFile: intentional — furin.ts is the public package entry
1
+ import { existsSync } from "node:fs";
2
+ import { basename, dirname, join, resolve } from "node:path";
3
+ import { fileURLToPath } from "node:url";
4
+ import { staticPlugin } from "@elysiajs/static";
5
+ import { type AnyElysia, Elysia, file } from "elysia";
6
+ import { type DrainContext, initLogger } from "evlog";
7
+ import { type EvlogElysiaOptions, evlog } from "evlog/elysia";
8
+ import {
9
+ _runWithRequestInvalidationScope,
10
+ consumePendingInvalidations,
11
+ getBuildId,
12
+ setBuildId,
13
+ } from "./server/cache/invalidation.ts";
14
+ import { setSSGCache } from "./server/cache/ssg.ts";
15
+ import type { CompileContext, EmbeddedAppData } from "./server/internal.ts";
16
+ import { getCompileContext } from "./server/internal.ts";
17
+ import { renderRootNotFound, warmSSGCache } from "./server/render/index.ts";
18
+ import {
19
+ setProductionTemplateContent,
20
+ setProductionTemplatePath,
21
+ } from "./server/render/template.ts";
22
+ import {
23
+ createDataEndpoint,
24
+ createRoutePlugin,
25
+ createSearchRouteMetadata,
26
+ loadProdRoutes,
27
+ } from "./server/router/index.ts";
28
+ import { IS_DEV } from "./server/runtime-env.ts";
29
+ import {
30
+ createSyncStreamPlugin,
31
+ type FurinSyncOption,
32
+ resolveSyncStreamPath,
33
+ runWithSyncStreamPath,
34
+ } from "./server/sync/index.ts";
35
+
36
+ // biome-ignore lint/suspicious/noEmptyInterface: intentionally augmentable via furin-env.d.ts
37
+ export interface FurinCacheTags {}
38
+
39
+ export type CacheTag = keyof FurinCacheTags extends never ? string : keyof FurinCacheTags;
40
+
41
+ function resolveClientDirFromArgv(): string {
42
+ return (
43
+ resolveClientDirFromEnv() ??
44
+ resolveClientDirFromModuleUrl() ??
45
+ resolveClientDirFromProcessArgs() ??
46
+ resolveFallbackClientDir()
47
+ );
48
+ }
49
+
50
+ function resolveClientDirFromEnv(): string | null {
51
+ const envClientDir = process.env.FURIN_CLIENT_DIR;
52
+ if (!envClientDir) {
53
+ return null;
54
+ }
55
+ return envClientDir.startsWith("/") ? envClientDir : resolve(process.cwd(), envClientDir);
56
+ }
57
+
58
+ function resolveClientDirFromModuleUrl(): string | null {
59
+ try {
60
+ const moduleUrl = new URL(import.meta.url);
61
+ if (moduleUrl.protocol !== "file:") {
62
+ return null;
63
+ }
64
+ const modulePath = fileURLToPath(moduleUrl);
65
+ if (modulePath.includes("/$bunfs/")) {
66
+ return null;
67
+ }
68
+ const moduleClientDir = join(dirname(modulePath), "client");
69
+ if (existsSync(join(moduleClientDir, "index.html"))) {
70
+ return moduleClientDir;
71
+ }
72
+ } catch {
73
+ // ignore, fallback to argv-based resolution
74
+ }
75
+ return null;
76
+ }
77
+
78
+ function resolveClientDirFromProcessArgs(): string | null {
79
+ const candidates = [
80
+ process.argv[1],
81
+ process.argv[0],
82
+ (process as { argv0?: string }).argv0,
83
+ process.execPath,
84
+ ].filter((value): value is string => typeof value === "string" && value.length > 0);
85
+
86
+ for (const candidate of candidates) {
87
+ const resolved = resolveClientDirFromCandidate(candidate);
88
+ if (resolved) {
89
+ return resolved;
90
+ }
91
+ }
92
+
93
+ return null;
94
+ }
95
+
96
+ function resolveClientDirFromCandidate(candidate: string): string | null {
97
+ const name = basename(candidate);
98
+ if (name === "bun" || name === "node") {
99
+ return null;
100
+ }
101
+ if (candidate.includes("/$bunfs/") || candidate.startsWith("bunfs:")) {
102
+ return null;
103
+ }
104
+
105
+ const absolute = candidate.startsWith("/") ? candidate : resolve(process.cwd(), candidate);
106
+ if (existsSync(absolute)) {
107
+ return join(dirname(absolute), "client");
108
+ }
109
+
110
+ if (!candidate.includes("/")) {
111
+ return resolveClientDirFromPath(candidate);
112
+ }
113
+
114
+ return null;
115
+ }
116
+
117
+ function resolveClientDirFromPath(candidate: string): string | null {
118
+ const pathEntries = process.env.PATH?.split(":") ?? [];
119
+ for (const dir of pathEntries) {
120
+ const fullPath = join(dir, candidate);
121
+ if (existsSync(fullPath)) {
122
+ return join(dirname(fullPath), "client");
123
+ }
124
+ }
125
+ return null;
126
+ }
127
+
128
+ function resolveFallbackClientDir(): string {
129
+ const defaultClientDir = resolve(process.cwd(), ".furin/build/bun/client");
130
+ if (existsSync(join(defaultClientDir, "index.html"))) {
131
+ return defaultClientDir;
132
+ }
133
+
134
+ return join(process.cwd(), "client");
135
+ }
136
+
137
+ async function setupProdTemplate(
138
+ embedded: EmbeddedAppData | undefined,
139
+ clientDir: string
140
+ ): Promise<void> {
141
+ if (embedded) {
142
+ if (!embedded.template) {
143
+ throw new Error("[furin] Embedded app is missing its HTML template (index.html).");
144
+ }
145
+ const html = await Bun.file(embedded.template).text();
146
+ setProductionTemplateContent(html);
147
+ return;
148
+ }
149
+
150
+ const templatePath = join(clientDir, "index.html");
151
+ if (!existsSync(templatePath)) {
152
+ throw new Error("[furin] No pre-built assets found. Run `bun run build` first.");
153
+ }
154
+ setProductionTemplatePath(templatePath);
155
+ }
156
+
157
+ /**
158
+ * Registers a HigherOrderFunction on the Elysia instance so that every request
159
+ * runs inside a fresh `AsyncLocalStorage` scope. This isolates
160
+ * `pendingInvalidations` per request, preventing concurrent requests from
161
+ * stealing each other's `revalidatePath()` calls.
162
+ *
163
+ * Uses `app.wrap()` (Elysia HigherOrderFunction) instead of mutating
164
+ * `app.handle`, because handle mutations are lost when the Furin plugin is
165
+ * `.use()`-d by a parent Elysia instance. HigherOrderFunctions survive the
166
+ * plugin merge and wrap the entire composed `map` handler.
167
+ */
168
+ function wrapWithRequestScope(app: AnyElysia, syncStreamPath: string | undefined): Elysia {
169
+ return app.wrap(
170
+ (handler, _request) => (ctx: unknown) =>
171
+ runWithSyncStreamPath(syncStreamPath, () =>
172
+ _runWithRequestInvalidationScope(() => handler(ctx))
173
+ )
174
+ );
175
+ }
176
+
177
+ function hydrateSSGCacheFromCompileContext(ctx: CompileContext): void {
178
+ if (!ctx.ssgCache) {
179
+ return;
180
+ }
181
+ for (const [path, entry] of Object.entries(ctx.ssgCache)) {
182
+ setSSGCache(path, entry);
183
+ }
184
+ }
185
+
186
+ /**
187
+ * Main Furin plugin.
188
+ *
189
+ * Returns a standalone Elysia instance (async function) so that routes are
190
+ * properly registered in Elysia's router for SPA navigation to work.
191
+ *
192
+ * ## Usage
193
+ *
194
+ * ```ts
195
+ * new Elysia()
196
+ * .use(await furin({ ... }))
197
+ * .listen(3000)
198
+ * ```
199
+ */
200
+ export async function furin({
201
+ pagesDir,
202
+ logger,
203
+ clientLogging,
204
+ sync,
205
+ }: {
206
+ pagesDir?: string;
207
+ logger?: EvlogElysiaOptions;
208
+ /**
209
+ * Initialize the browser HTTP log drain in the hydration entry. Off by
210
+ * default — enabling it adds `evlog/http` drain setup and points browser
211
+ * events at `/_furin/ingest`. Server-side logging is configured via `logger`
212
+ * and unaffected.
213
+ */
214
+ clientLogging?: boolean;
215
+ /**
216
+ * Enables Furin's built-in sync event stream. The opinionated default mounts
217
+ * Server-Sent Events at `/_furin/sync`; pass an object only for constrained
218
+ * reverse-proxy deployments that need a custom internal path.
219
+ */
220
+ sync?: FurinSyncOption;
221
+ }) {
222
+ const syncStreamPath = resolveSyncStreamPath(sync);
223
+ const { exclude: userExclude, ...evlogOptions } = logger ?? {};
224
+ initLogger({ env: { service: "furin" } });
225
+
226
+ const loggerPlugin = new Elysia()
227
+ .use(
228
+ evlog({
229
+ ...evlogOptions,
230
+ exclude: [
231
+ "/_client/**",
232
+ "/public/**",
233
+ "/favicon.ico",
234
+ "/_bun_hmr_entry/**",
235
+ ...(syncStreamPath ? [syncStreamPath] : []),
236
+ // Note: /_furin/data is logged with the *logical* path rewritten by
237
+ // createDataEndpoint via useLogger().set({ path }), so SPA navigations
238
+ // appear as "GET /board/123 200" — same shape as a normal SSR nav.
239
+ // /_furin/ingest is kept loggable so browser-side events show up.
240
+ // evlog's `matchesPattern` only supports `*`, `**`, `?` — extglob
241
+ // like `!(...)` matches nothing, so don't add patterns relying on it.
242
+ ...(userExclude ?? []),
243
+ ],
244
+ })
245
+ )
246
+ .post(
247
+ "/_furin/ingest",
248
+ ({ body, log, status }) => {
249
+ if (!Array.isArray(body)) {
250
+ return status("Bad Request");
251
+ }
252
+ // Cap batch size to prevent abuse
253
+ const batch = (body as DrainContext[]).slice(0, 100);
254
+ for (const entry of batch) {
255
+ if (!entry || typeof entry !== "object" || !("event" in entry)) {
256
+ log.set({ msg: "[furin] ingest: skipping malformed entry" });
257
+ continue;
258
+ }
259
+ // Pick only safe, known fields from the event to prevent prototype pollution
260
+ const event = entry.event as Record<string, unknown> | undefined;
261
+ if (!event || typeof event !== "object") {
262
+ continue;
263
+ }
264
+ const {
265
+ __proto__,
266
+ constructor: _ctor,
267
+ prototype,
268
+ environment: _browserEnv,
269
+ ...safeEvent
270
+ } = event as Record<string, unknown>;
271
+ log.set({ ...safeEvent, service: "furin:browser" });
272
+ }
273
+ return status("No Content");
274
+ },
275
+ { parse: "json" }
276
+ );
277
+
278
+ const cwd = process.cwd();
279
+ const ctx = getCompileContext();
280
+ const resolvedPagesDir = ctx?.rootPath
281
+ ? dirname(ctx.rootPath)
282
+ : resolve(cwd, pagesDir ?? "src/pages");
283
+
284
+ // Unique name per pagesDir to avoid Elysia's name-based plugin dedup.
285
+ const instanceName = `furin-${resolvedPagesDir.replaceAll("\\", "/")}`;
286
+
287
+ // ── Dev: Bun native HMR ────────────────────────────────────────────────
288
+ if (IS_DEV) {
289
+ const furinDir = resolve(cwd, ".furin");
290
+ // Lazy import — build pipeline has native deps not available in compiled binaries
291
+ const { registerDevPagePlugin } = await import("./server/dev-page-plugin.ts");
292
+ registerDevPagePlugin();
293
+
294
+ const { createDevInspectorPlugin } = await import("./server/dev-inspector.ts");
295
+
296
+ const { scanPages } = await import("./server/router/index.ts");
297
+ const { root, routes } = await scanPages(resolvedPagesDir);
298
+ const searchRoutes = createSearchRouteMetadata(routes);
299
+
300
+ const { writeDevFiles } = await import("./build/hydrate.ts");
301
+ writeDevFiles(
302
+ routes,
303
+ {
304
+ outDir: furinDir,
305
+ rootLayout: root.path,
306
+ basePath: "",
307
+ publicPath: "/_client/",
308
+ clientLogging: clientLogging ?? false,
309
+ },
310
+ cwd
311
+ );
312
+
313
+ const publicDir = resolve(cwd, "public");
314
+ const publicExists = existsSync(publicDir);
315
+
316
+ const devApp = new Elysia({ name: instanceName, seed: resolvedPagesDir })
317
+ .use(loggerPlugin)
318
+ .onError({ as: "global" }, async ({ code, request }) => {
319
+ if (code === "NOT_FOUND") {
320
+ return await renderRootNotFound(root, request);
321
+ }
322
+ })
323
+ .onAfterHandle({ as: "global" }, ({ set }) => {
324
+ // Forward pending revalidation paths so the client can bust its prefetch cache
325
+ const pending = consumePendingInvalidations();
326
+ if (pending.length > 0) {
327
+ set.headers["x-furin-revalidate"] = pending.join(",");
328
+ }
329
+ })
330
+ .use(await staticPlugin({ assets: furinDir, prefix: "/_bun_hmr_entry", bunFullstack: true }))
331
+ .use(
332
+ publicExists ? await staticPlugin({ assets: publicDir, prefix: "/public" }) : new Elysia()
333
+ )
334
+ .get(
335
+ "/favicon.ico",
336
+ publicExists
337
+ ? file(join(publicDir, "favicon.ico"))
338
+ : () => new Response(null, { status: 404 })
339
+ )
340
+ .use(createDevInspectorPlugin())
341
+ .use(syncStreamPath ? createSyncStreamPlugin(syncStreamPath) : new Elysia())
342
+ .use(createDataEndpoint(routes))
343
+ .use((app) => {
344
+ for (const route of routes) {
345
+ app.use(createRoutePlugin(route, root, undefined, searchRoutes));
346
+ }
347
+ return app;
348
+ });
349
+ return wrapWithRequestScope(devApp, syncStreamPath);
350
+ }
351
+
352
+ // ── Production ──────────────────────────────────────────────────────────
353
+ if (!ctx) {
354
+ throw new Error("[furin] No pre-built assets found. Run `bunx furin build` first.");
355
+ }
356
+ const { root, routes } = loadProdRoutes(ctx);
357
+ const searchRoutes = createSearchRouteMetadata(routes);
358
+ const prodBuildId = ctx.buildId ?? "";
359
+ setBuildId(prodBuildId);
360
+ hydrateSSGCacheFromCompileContext(ctx);
361
+
362
+ const embedded = ctx?.embedded;
363
+ const clientDir = embedded ? "" : resolveClientDirFromArgv();
364
+ await setupProdTemplate(embedded, clientDir);
365
+
366
+ const prodApp = new Elysia({ name: instanceName, seed: resolvedPagesDir })
367
+ .use(loggerPlugin)
368
+ .onError({ as: "global" }, async ({ code, request }) => {
369
+ if (code === "NOT_FOUND") {
370
+ return await renderRootNotFound(root, request);
371
+ }
372
+ })
373
+ .onAfterHandle({ as: "global" }, ({ path, set }) => {
374
+ // Content-hashed client assets are permanently cacheable — browsers never need to
375
+ // revalidate them because any change produces a new filename.
376
+ if (path.startsWith("/_client/")) {
377
+ set.headers["cache-control"] = "public, max-age=31536000, immutable";
378
+ }
379
+ // Forward pending revalidation paths so the client can bust its prefetch cache
380
+ const pending = consumePendingInvalidations();
381
+ if (pending.length > 0) {
382
+ set.headers["x-furin-revalidate"] = pending.join(",");
383
+ }
384
+ // Tell the client the current build ID so it can detect stale deploys
385
+ const buildId = getBuildId();
386
+ if (buildId) {
387
+ set.headers["x-furin-build-id"] = buildId;
388
+ }
389
+ })
390
+ .onStart(async ({ server }) => {
391
+ if (ctx.ssgCache) {
392
+ return;
393
+ }
394
+ const origin = server?.url?.origin ?? "http://localhost:3000";
395
+ await warmSSGCache(routes, root, origin, searchRoutes);
396
+ })
397
+ .use(
398
+ await (async () => {
399
+ if (embedded) {
400
+ return new Elysia()
401
+ .get("/favicon.ico", ({ status }) => {
402
+ const asset = embedded.assets["/public/favicon.ico"];
403
+ if (!asset) {
404
+ return status("Not Found");
405
+ }
406
+ return Bun.file(asset);
407
+ })
408
+ .get("/_client/*", ({ params, status }) => {
409
+ const asset = embedded.assets[`/_client/${params["*"]}`];
410
+ if (!asset) {
411
+ return status("Not Found");
412
+ }
413
+ return Bun.file(asset);
414
+ })
415
+ .get("/public/*", ({ params, status }) => {
416
+ const asset = embedded.assets[`/public/${params["*"]}`];
417
+ if (!asset) {
418
+ return status("Not Found");
419
+ }
420
+ return Bun.file(asset);
421
+ });
422
+ }
423
+ const publicDir = join(dirname(clientDir), "public");
424
+ const app = new Elysia();
425
+ if (existsSync(publicDir)) {
426
+ app
427
+ .get("/favicon.ico", file(join(publicDir, "favicon.ico")))
428
+ .use(await staticPlugin({ assets: publicDir, prefix: "/public" }));
429
+ }
430
+ app.use(await staticPlugin({ assets: clientDir, prefix: "/_client" }));
431
+ return app;
432
+ })()
433
+ )
434
+ .use(syncStreamPath ? createSyncStreamPlugin(syncStreamPath) : new Elysia())
435
+ .use(createDataEndpoint(routes))
436
+ .use((app) => {
437
+ for (const route of routes) {
438
+ app.use(createRoutePlugin(route, root, prodBuildId, searchRoutes));
439
+ }
440
+ return app;
441
+ });
442
+ return wrapWithRequestScope(prodApp, syncStreamPath);
443
+ }
444
+
445
+ // biome-ignore lint/performance/noBarrelFile: furin.ts is the public package entry
446
+ export { FurinErrorBoundary, FurinNotFoundBoundary } from "./client/boundaries.tsx";
447
+ // ── Public API re-export ──────────────────────────────────────────────────────
448
+ // biome-ignore-start lint/performance/noBarrelFile: intentional — furin.ts is the public package entry
449
+ export type { DeferredData, RuntimePage, RuntimeRoute } from "./client.ts";
450
+ export { defer, isDeferred } from "./client.ts";
451
+ export type { InvalidationInput, InvalidationRule } from "./server/auto-invalidate/index.ts";
452
+ export { furinInvalidate, revalidateTag } from "./server/auto-invalidate/index.ts";
453
+ export { revalidatePath, setCachePurger } from "./server/cache/invalidation.ts";
454
+ export { buildElement, buildErrorElement, renderRootNotFound } from "./server/render/index.ts";
455
+ export type { ResolvedRoute, SegmentBoundary } from "./server/router/index.ts";
456
+ export { furinSync, type SyncInput } from "./server/sync/index.ts";
457
+ export { Await, useAsyncError, useAsyncValue } from "./shared/await.tsx";
458
+ export type { ErrorComponent, ErrorProps } from "./shared/error.ts";
459
+ export type {
460
+ NotFoundComponent,
461
+ NotFoundOptions,
462
+ NotFoundProps,
463
+ } from "./shared/not-found.ts";
464
+ export { isNotFoundError, notFound } from "./shared/not-found.ts";
465
+ // biome-ignore-end lint/performance/noBarrelFile: intentional — furin.ts is the public package entry