@teyik0/furin 0.1.0-alpha.7 → 0.1.0-alpha.9

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 (46) hide show
  1. package/dist/adapter/static.d.ts +3 -0
  2. package/dist/build/client.d.ts +3 -3
  3. package/dist/build/compile-entry.d.ts +4 -4
  4. package/dist/build/entry-template.d.ts +2 -2
  5. package/dist/build/hydrate.d.ts +6 -2
  6. package/dist/build/index.d.ts +1 -1
  7. package/dist/build/index.js +1491 -78
  8. package/dist/build/types.d.ts +26 -3
  9. package/dist/cli/index.js +1525 -91
  10. package/dist/client.d.ts +18 -11
  11. package/dist/config.d.ts +33 -2
  12. package/dist/config.js +6 -1
  13. package/dist/context-logger.d.ts +26 -0
  14. package/dist/dev-page-plugin.d.ts +77 -0
  15. package/dist/furin.js +459 -69
  16. package/dist/link.d.ts +31 -3
  17. package/dist/link.js +198 -51
  18. package/dist/render/assemble.d.ts +4 -2
  19. package/dist/render/index.d.ts +1 -1
  20. package/dist/render/loaders.d.ts +1 -1
  21. package/dist/render/shell.d.ts +4 -1
  22. package/dist/router.d.ts +11 -0
  23. package/dist/router.js +942 -41
  24. package/package.json +6 -5
  25. package/src/adapter/bun.ts +20 -0
  26. package/src/adapter/static.ts +341 -0
  27. package/src/build/client.ts +21 -11
  28. package/src/build/compile-entry.ts +5 -3
  29. package/src/build/entry-template.ts +2 -2
  30. package/src/build/hydrate.ts +37 -9
  31. package/src/build/index.ts +56 -21
  32. package/src/build/scan-server.ts +43 -21
  33. package/src/build/types.ts +28 -3
  34. package/src/cli/index.ts +13 -5
  35. package/src/client.ts +19 -25
  36. package/src/config.ts +35 -1
  37. package/src/context-logger.ts +71 -0
  38. package/src/dev-page-plugin.ts +339 -4
  39. package/src/furin.ts +6 -2
  40. package/src/link.tsx +355 -64
  41. package/src/plugin/index.ts +2 -2
  42. package/src/render/assemble.ts +4 -2
  43. package/src/render/index.ts +67 -23
  44. package/src/render/loaders.ts +81 -36
  45. package/src/render/shell.ts +11 -4
  46. package/src/router.ts +55 -6
@@ -1,20 +1,17 @@
1
1
  import { existsSync, writeFileSync } from "node:fs";
2
2
  import { join, relative, resolve } from "node:path";
3
3
  import { buildBunTarget } from "../adapter/bun";
4
+ import { buildStaticTarget } from "../adapter/static";
4
5
  import { BUILD_TARGETS, type BuildTarget } from "../config";
5
6
  import { scanPages } from "../router";
6
7
  import { scanFurinInstances } from "./scan-server";
7
- import {
8
- ensureDir,
9
- toBuildRouteManifestEntry,
10
- toPosixPath,
11
- } from "./shared";
12
- import type {
13
- BuildAppOptions,
14
- BuildAppResult,
15
- BuildManifest,
16
- } from "./types";
8
+ import { ensureDir, toBuildRouteManifestEntry, toPosixPath } from "./shared";
9
+ import type { BuildAppOptions, BuildAppResult, BuildManifest } from "./types";
17
10
 
11
+ // biome-ignore lint/performance/noBarrelFile: intentional — build/index.ts is the public build API entry
12
+ export { buildClient } from "./client";
13
+ export { writeDevFiles } from "./hydrate";
14
+ export { patternToTypeString, schemaToTypeString, writeRouteTypes } from "./route-types";
18
15
  export type {
19
16
  BuildAppOptions,
20
17
  BuildAppResult,
@@ -23,17 +20,18 @@ export type {
23
20
  BuildRouteManifestEntry,
24
21
  TargetBuildManifest,
25
22
  } from "./types";
26
- export { buildClient } from "./client";
27
- export { writeDevFiles } from "./hydrate";
28
- export { patternToTypeString, schemaToTypeString, writeRouteTypes } from "./route-types";
29
23
 
30
- const IMPLEMENTED_TARGETS = ["bun"] as const satisfies BuildTarget[];
24
+ const IMPLEMENTED_TARGETS = ["bun", "static"] as const satisfies BuildTarget[];
31
25
  export const BUILD_OUTPUT_DIR = ".furin/build";
32
26
 
33
27
  function resolvePagesDirFromServer(serverEntry: string | null, rootDir: string): string | null {
34
- if (!serverEntry) return null;
28
+ if (!serverEntry) {
29
+ return null;
30
+ }
35
31
  const detected = scanFurinInstances(serverEntry);
36
- if (detected.length === 0) return null;
32
+ if (detected.length === 0) {
33
+ return null;
34
+ }
37
35
  // Use the first detected pagesDir relative to rootDir
38
36
  return resolve(rootDir, detected[0] as string);
39
37
  }
@@ -42,17 +40,45 @@ export async function buildApp(options: BuildAppOptions): Promise<BuildAppResult
42
40
  const rootDir = resolve(options.rootDir ?? process.cwd());
43
41
  const buildRoot = join(rootDir, BUILD_OUTPUT_DIR);
44
42
  const serverEntry = (() => {
43
+ // Static-only builds don't need a server entry point
44
+ if (options.target === "static") {
45
+ return null;
46
+ }
45
47
  if (options.serverEntry) {
46
48
  const resolved = resolve(rootDir, options.serverEntry);
47
- if (existsSync(resolved)) return resolved;
49
+ if (existsSync(resolved)) {
50
+ return resolved;
51
+ }
48
52
  }
49
- const serverEntry = resolve(rootDir, "src/server.ts");
50
- if (!existsSync(serverEntry)) {
53
+ const entry = resolve(rootDir, "src/server.ts");
54
+ if (!existsSync(entry)) {
51
55
  throw new Error("[furin] Entrypoint server.ts not found");
52
56
  }
53
- return serverEntry
57
+ return entry;
54
58
  })();
55
59
 
60
+ // Register user plugins as runtime module loaders BEFORE scanPages.
61
+ //
62
+ // scanPages() calls import() on every page file, which triggers all their
63
+ // static imports (e.g. ".mdx" files). If the loader is not yet registered
64
+ // at that point, Bun caches the raw/unprocessed result — and that cached
65
+ // value is reused for every subsequent import(), including prerenderSSG().
66
+ //
67
+ // Build-only plugins (e.g. bun-plugin-tailwind uses onBeforeParse which
68
+ // doesn't exist in the runtime context) are skipped silently — they only
69
+ // affect the Bun.build() client bundle, not server-side rendering.
70
+ for (const plugin of options.plugins ?? []) {
71
+ try {
72
+ Bun.plugin(plugin);
73
+ } catch (err) {
74
+ // Build-only plugins (e.g. bun-plugin-tailwind uses onBeforeParse which
75
+ // does not exist in the runtime context) are expected to throw here —
76
+ // they only affect the Bun.build() client bundle, not server-side rendering.
77
+ // Log at debug level so genuine plugin registration errors remain visible.
78
+ console.debug("[furin] Skipped build-only plugin at runtime:", err);
79
+ }
80
+ }
81
+
56
82
  // Priority: explicit config > auto-detected from server entry > default
57
83
  const rawPagesDir =
58
84
  options.pagesDir ?? resolvePagesDirFromServer(serverEntry, rootDir) ?? "src/pages";
@@ -96,6 +122,15 @@ export async function buildApp(options: BuildAppOptions): Promise<BuildAppResult
96
122
  options
97
123
  );
98
124
  break;
125
+ case "static":
126
+ manifest.targets.static = await buildStaticTarget(
127
+ routes,
128
+ rootDir,
129
+ buildRoot,
130
+ root,
131
+ options
132
+ );
133
+ break;
99
134
  case "node":
100
135
  case "vercel":
101
136
  case "cloudflare":
@@ -107,7 +142,7 @@ export async function buildApp(options: BuildAppOptions): Promise<BuildAppResult
107
142
  }
108
143
  }
109
144
 
110
- writeFileSync(join(buildRoot, "manifest.json"), `${JSON.stringify(manifest, null, 2)}\n`)
145
+ writeFileSync(join(buildRoot, "manifest.json"), `${JSON.stringify(manifest, null, 2)}\n`);
111
146
 
112
147
  return {
113
148
  manifest,
@@ -26,30 +26,36 @@ export function scanFurinInstances(serverEntryPath: string): string[] {
26
26
  return results;
27
27
  }
28
28
 
29
- function walkNode(node: AstNode, out: string[]): void {
30
- if (!node || typeof node !== "object") return;
29
+ const SKIP_KEYS = new Set(["type", "start", "end"]);
31
30
 
32
- if (node.type === "CallExpression") {
33
- const callee = node.callee as AstNode | undefined;
34
- const args = node.arguments as AstNode[] | undefined;
31
+ /** Checks whether `node` is a `furin({ pagesDir: "..." })` call and, if so, pushes the value. */
32
+ function checkFurinCall(node: AstNode, out: string[]): void {
33
+ const callee = node.callee as AstNode | undefined;
34
+ const args = node.arguments as AstNode[] | undefined;
35
+ const isFurinCall =
36
+ callee?.type === "Identifier" && (callee as { name?: string }).name === "furin";
35
37
 
36
- const isFurinCall =
37
- callee?.type === "Identifier" && (callee as { name?: string }).name === "furin";
38
+ if (!(isFurinCall && Array.isArray(args)) || args.length === 0) {
39
+ return;
40
+ }
38
41
 
39
- if (isFurinCall && Array.isArray(args) && args.length > 0) {
40
- const firstArg = args[0] as AstNode;
41
- if (firstArg?.type === "ObjectExpression") {
42
- const pagesDir = extractStringProperty(firstArg, "pagesDir");
43
- if (pagesDir !== null) {
44
- out.push(pagesDir);
45
- }
46
- }
47
- }
42
+ const firstArg = args[0] as AstNode;
43
+ if (firstArg?.type !== "ObjectExpression") {
44
+ return;
48
45
  }
49
46
 
50
- // Recurse into all child node values
47
+ const pagesDir = extractStringProperty(firstArg, "pagesDir");
48
+ if (pagesDir !== null) {
49
+ out.push(pagesDir);
50
+ }
51
+ }
52
+
53
+ /** Recurses into all child AST node values (arrays and plain objects). */
54
+ function walkChildren(node: AstNode, out: string[]): void {
51
55
  for (const key of Object.keys(node)) {
52
- if (key === "type" || key === "start" || key === "end") continue;
56
+ if (SKIP_KEYS.has(key)) {
57
+ continue;
58
+ }
53
59
  const child = node[key];
54
60
  if (Array.isArray(child)) {
55
61
  for (const item of child) {
@@ -63,12 +69,26 @@ function walkNode(node: AstNode, out: string[]): void {
63
69
  }
64
70
  }
65
71
 
72
+ function walkNode(node: AstNode, out: string[]): void {
73
+ if (!node || typeof node !== "object") {
74
+ return;
75
+ }
76
+ if (node.type === "CallExpression") {
77
+ checkFurinCall(node, out);
78
+ }
79
+ walkChildren(node, out);
80
+ }
81
+
66
82
  function extractStringProperty(obj: AstNode, propName: string): string | null {
67
83
  const properties = obj.properties as AstNode[] | undefined;
68
- if (!Array.isArray(properties)) return null;
84
+ if (!Array.isArray(properties)) {
85
+ return null;
86
+ }
69
87
 
70
88
  for (const prop of properties) {
71
- if (prop.type !== "Property") continue;
89
+ if (prop.type !== "Property") {
90
+ continue;
91
+ }
72
92
  const key = prop.key as AstNode & { name?: string; value?: unknown };
73
93
  const value = prop.value as AstNode & { value?: unknown };
74
94
 
@@ -76,7 +96,9 @@ function extractStringProperty(obj: AstNode, propName: string): string | null {
76
96
  (key.type === "Identifier" && key.name === propName) ||
77
97
  (key.type === "Literal" && key.value === propName);
78
98
 
79
- if (!keyMatches) continue;
99
+ if (!keyMatches) {
100
+ continue;
101
+ }
80
102
 
81
103
  // Only accept string literals — ignore template literals, identifiers, etc.
82
104
  if (value?.type === "Literal" && typeof value.value === "string") {
@@ -1,10 +1,22 @@
1
- import type { BuildTarget } from "../config";
1
+ import type { BuildTarget, StaticExportConfig } from "../config";
2
2
  import type { ResolvedRoute } from "../router";
3
3
 
4
4
  export interface BuildClientOptions {
5
+ /**
6
+ * Sub-path prefix for the deployment (e.g. "/furin" for GitHub Pages).
7
+ * Passed through to the generated hydrate entry so SPA navigation uses
8
+ * correct physical URLs. Pass "" for root deployments.
9
+ */
10
+ basePath: string;
5
11
  outDir: string;
6
12
  pagesDir?: string;
7
13
  plugins?: Bun.BunPlugin[];
14
+ /**
15
+ * Public path prefix for all emitted JS/CSS chunks.
16
+ * Pass "/_client/" for root deployments; override for basePath deployments,
17
+ * e.g. "/furin/_client/".
18
+ */
19
+ publicPath: string;
8
20
  rootLayout: string;
9
21
  }
10
22
 
@@ -27,6 +39,8 @@ export interface TargetBuildManifest {
27
39
  templatePath: string | null;
28
40
  }
29
41
 
42
+ export type AnyTargetManifest = TargetBuildManifest | StaticTargetBuildManifest;
43
+
30
44
  export interface BuildManifest {
31
45
  generatedAt: string;
32
46
  pagesDir: string;
@@ -34,7 +48,7 @@ export interface BuildManifest {
34
48
  rootPath: string;
35
49
  routes: BuildRouteManifestEntry[];
36
50
  serverEntry: string | null;
37
- targets: Partial<Record<BuildTarget, TargetBuildManifest>>;
51
+ targets: Partial<Record<BuildTarget, AnyTargetManifest>>;
38
52
  version: 1;
39
53
  }
40
54
 
@@ -44,12 +58,23 @@ export interface BuildAppOptions {
44
58
  plugins?: Bun.BunPlugin[];
45
59
  rootDir?: string;
46
60
  serverEntry?: string;
61
+ /** Configuration for the `static` build target. */
62
+ staticConfig?: StaticExportConfig;
47
63
  target: BuildTarget | "all";
48
64
  }
49
65
 
66
+ /** Build manifest entry produced by the `static` adapter. */
67
+ export interface StaticTargetBuildManifest {
68
+ basePath: string;
69
+ generatedAt: string;
70
+ outDir: string;
71
+ renderedRoutes: string[];
72
+ skippedRoutes: string[];
73
+ }
74
+
50
75
  export interface BuildAppResult {
51
76
  manifest: BuildManifest;
52
- targets: Partial<Record<BuildTarget, TargetBuildManifest>>;
77
+ targets: Partial<Record<BuildTarget, AnyTargetManifest>>;
53
78
  }
54
79
 
55
80
  export type BunBuildAliasConfig = Bun.BuildConfig & {
package/src/cli/index.ts CHANGED
@@ -70,11 +70,18 @@ if (command === "build") {
70
70
 
71
71
  const config = await loadCliConfig(process.cwd(), values.config);
72
72
 
73
- const resolvedServerEntry = resolve(config.rootDir, config.serverEntry ?? "src/server.ts");
74
- if (!existsSync(resolvedServerEntry)) {
75
- const expected = config.serverEntry ?? "src/server.ts";
76
- throw new Error(`[furin] Entrypoint ${expected} not found`);
77
- }
73
+ const isStaticTarget = target === "static";
74
+
75
+ const resolvedServerEntry = isStaticTarget
76
+ ? undefined
77
+ : (() => {
78
+ const entry = resolve(config.rootDir, config.serverEntry ?? "src/server.ts");
79
+ if (!existsSync(entry)) {
80
+ const expected = config.serverEntry ?? "src/server.ts";
81
+ throw new Error(`[furin] Entrypoint ${expected} not found`);
82
+ }
83
+ return entry;
84
+ })();
78
85
 
79
86
  log(`Building Furin for ${target}…`);
80
87
 
@@ -85,6 +92,7 @@ if (command === "build") {
85
92
  pagesDir: values.pagesDir ?? config.pagesDir,
86
93
  serverEntry: resolvedServerEntry,
87
94
  plugins: config.plugins,
95
+ staticConfig: config.static,
88
96
  });
89
97
 
90
98
  const built = Object.keys(result.targets).join(", ") || "none";
package/src/client.ts CHANGED
@@ -9,6 +9,7 @@
9
9
 
10
10
  import type { Cookie, StatusMap } from "elysia";
11
11
  import type { AnySchema, HTTPHeaders, UnwrapSchema } from "elysia/types";
12
+ import type { RequestLogger } from "evlog";
12
13
 
13
14
  declare const UNSET: unique symbol;
14
15
  type Unset = typeof UNSET;
@@ -31,9 +32,20 @@ type MergeSchema<TParent, TOwn> = [TParent] extends [Unset]
31
32
 
32
33
  type NormalizeUnset<T> = [T] extends [Unset] ? {} : T;
33
34
 
35
+ /**
36
+ * Transforms each key of a parent-data record into an individual `Promise<T>`.
37
+ * This is what child loaders see for inherited fields — direct values from
38
+ * `RouteContext` (request, params, set, …) remain unchanged.
39
+ */
40
+ type PromisifyData<T extends Record<string, unknown>> = {
41
+ [K in keyof T]: Promise<T[K]>;
42
+ };
43
+
34
44
  export interface RouteContext<TParams = {}, TQuery = {}> {
35
45
  cookie: Record<string, Cookie<unknown>>;
36
46
  headers: Record<string, string | undefined>;
47
+ /** Request-scoped logger. Call `log.set({})` to attach fields to the wide event for this render. */
48
+ log: RequestLogger;
37
49
  params: NormalizeUnset<TParams>;
38
50
  path: string;
39
51
  query: NormalizeUnset<TQuery>;
@@ -95,8 +107,6 @@ export interface HeadOptions {
95
107
  styles?: Array<{ type?: string; children: string }>;
96
108
  }
97
109
 
98
- export type LoaderDeps = (route: { __type: string }) => Promise<Record<string, unknown>>;
99
-
100
110
  // Extracts the resolved return type from a loader function type.
101
111
  // Using ReturnType + Awaited here means TLoader is inferred as the whole function
102
112
  // first, and then we extract the data — so inference is order-independent.
@@ -115,8 +125,7 @@ export interface PageConfig<
115
125
  component: React.FC<TParentData & TPageLoaderData & ComponentProps<TParams, TQuery>>;
116
126
  head?: (ctx: ComponentProps<TParams, TQuery> & TParentData & TPageLoaderData) => HeadOptions;
117
127
  loader?: (
118
- ctx: RouteContext<TParams, TQuery> & TParentData,
119
- deps: TypedDeps
128
+ ctx: RouteContext<TParams, TQuery> & PromisifyData<TParentData>
120
129
  ) => Promise<TPageLoaderData> | TPageLoaderData;
121
130
  staticParams?: () => Promise<NormalizeUnset<TParams>[]> | NormalizeUnset<TParams>[];
122
131
  }
@@ -124,10 +133,7 @@ export interface PageConfig<
124
133
  export interface RuntimeRoute {
125
134
  __type: "FURIN_ROUTE";
126
135
  layout?: React.FC<Record<string, unknown> & { children: React.ReactNode }>;
127
- loader?(
128
- ctx: Record<string, unknown>,
129
- deps: LoaderDeps
130
- ): Promise<Record<string, unknown>> | Record<string, unknown>;
136
+ loader?(ctx: Record<string, unknown>): Promise<Record<string, unknown>> | Record<string, unknown>;
131
137
  mode?: "ssr" | "ssg" | "isr";
132
138
  params?: unknown;
133
139
  parent?: RuntimeRoute;
@@ -140,10 +146,7 @@ export interface RuntimePage {
140
146
  _route: RuntimeRoute;
141
147
  component: React.FC<Record<string, unknown>>;
142
148
  head?(ctx: Record<string, unknown>): HeadOptions;
143
- loader?(
144
- ctx: Record<string, unknown>,
145
- deps: LoaderDeps
146
- ): Promise<Record<string, unknown>> | Record<string, unknown>;
149
+ loader?(ctx: Record<string, unknown>): Promise<Record<string, unknown>> | Record<string, unknown>;
147
150
  staticParams?(): Promise<Record<string, string>[]> | Record<string, string>[];
148
151
  }
149
152
 
@@ -167,8 +170,7 @@ interface PageResult<
167
170
  component: React.FC<TData & TPageLoaderData & ComponentProps<TParams, TQuery>>;
168
171
  head?: (ctx: ComponentProps<TParams, TQuery> & TData & TPageLoaderData) => HeadOptions;
169
172
  loader?: (
170
- ctx: RouteContext<TParams, TQuery> & TData,
171
- deps: TypedDeps
173
+ ctx: RouteContext<TParams, TQuery> & PromisifyData<TData>
172
174
  ) => Promise<TPageLoaderData> | TPageLoaderData;
173
175
  }
174
176
 
@@ -176,8 +178,7 @@ export interface Route<TParentData extends Record<string, unknown>, TParams, TQu
176
178
  __type: "FURIN_ROUTE";
177
179
  layout?: React.FC<TParentData & { children: React.ReactNode } & ComponentProps<TParams, TQuery>>;
178
180
  loader?(
179
- ctx: RouteContext<TParams, TQuery> & TParentData,
180
- deps: TypedDeps
181
+ ctx: RouteContext<TParams, TQuery> & PromisifyData<TParentData>
181
182
  ): Promise<TParentData> | TParentData;
182
183
  mode?: "ssr" | "ssg" | "isr";
183
184
 
@@ -186,7 +187,7 @@ export interface Route<TParentData extends Record<string, unknown>, TParams, TQu
186
187
  // has no inference sites (all NoInfer) so TypeScript applies its default AFTER TLoader is
187
188
  // resolved — making declaration order of head/component irrelevant.
188
189
  page<
189
- TLoader extends (ctx: RouteContext<TParams, TQuery> & TParentData, deps: TypedDeps) => unknown,
190
+ TLoader extends (ctx: RouteContext<TParams, TQuery> & PromisifyData<TParentData>) => unknown,
190
191
  TPageLoaderData extends object = ExtractLoaderReturn<TLoader>,
191
192
  >(config: {
192
193
  loader: TLoader;
@@ -217,12 +218,6 @@ export interface Route<TParentData extends Record<string, unknown>, TParams, TQu
217
218
  revalidate?: number;
218
219
  }
219
220
 
220
- // User-facing typed deps: infers the loader data type from the route ref.
221
- type TypedDeps = <TData extends Record<string, unknown>>(
222
- // biome-ignore lint/suspicious/noExplicitAny: any needed for flexible route type inference
223
- route: Route<TData, any, any>
224
- ) => Promise<TData>;
225
-
226
221
  export function createRoute<
227
222
  TParentRef extends RouteRef | undefined = undefined,
228
223
  TParamsSchema extends AnySchema | Unset = Unset,
@@ -239,8 +234,7 @@ export function createRoute<
239
234
  Resolved<TParentRef, TLoaderData, TParamsSchema, TQuerySchema>["params"],
240
235
  Resolved<TParentRef, TLoaderData, TParamsSchema, TQuerySchema>["query"]
241
236
  > &
242
- ResolveParent<TParentRef>["data"],
243
- deps: TypedDeps
237
+ PromisifyData<ResolveParent<TParentRef>["data"]>
244
238
  ) => Promise<TLoaderData> | TLoaderData;
245
239
  layout?: React.FC<
246
240
  Resolved<TParentRef, TLoaderData, TParamsSchema, TQuerySchema>["data"] & {
package/src/config.ts CHANGED
@@ -2,10 +2,36 @@ export type { BunPlugin } from "bun";
2
2
 
3
3
  import { t } from "elysia";
4
4
 
5
- export const BUILD_TARGETS = ["bun", "node", "vercel", "cloudflare"] as const;
5
+ export const BUILD_TARGETS = ["bun", "node", "vercel", "cloudflare", "static"] as const;
6
6
 
7
7
  export type BuildTarget = (typeof BUILD_TARGETS)[number];
8
8
 
9
+ /**
10
+ * Configuration for the `static` build target.
11
+ * Produces a fully pre-rendered directory deployable to any static host
12
+ * (GitHub Pages, Netlify, Surge.sh, …).
13
+ */
14
+ export interface StaticExportConfig {
15
+ /**
16
+ * Sub-path prefix for GitHub Pages sub-path deployments.
17
+ * e.g. "/furin" when the site is served at `https://user.github.io/furin/`.
18
+ * Must start with "/" and have no trailing slash.
19
+ * Default: "" (site served at root).
20
+ */
21
+ basePath?: string;
22
+ /**
23
+ * Behaviour when SSR or ISR routes are encountered during a static build.
24
+ * - "error" (default): throw at build time with the list of incompatible routes.
25
+ * - "skip": emit a warning and omit those routes from the output.
26
+ */
27
+ onSSR?: "error" | "skip";
28
+ /**
29
+ * Output directory for the static export.
30
+ * Default: "dist".
31
+ */
32
+ outDir?: string;
33
+ }
34
+
9
35
  const buildTargetSchema = t.Union(BUILD_TARGETS.map((v) => t.Literal(v)));
10
36
  const compileTargetSchema = t.Union([t.Literal("server"), t.Literal("embed")]);
11
37
 
@@ -19,11 +45,19 @@ export const configSchema = t.Object({
19
45
  compile: t.Optional(compileTargetSchema),
20
46
  })
21
47
  ),
48
+ static: t.Optional(
49
+ t.Object({
50
+ basePath: t.Optional(t.String()),
51
+ outDir: t.Optional(t.String()),
52
+ onSSR: t.Optional(t.Union([t.Literal("error"), t.Literal("skip")])),
53
+ })
54
+ ),
22
55
  // plugins omitted : TypeBox can't validate Bun.BunPlugin[] (functions)
23
56
  });
24
57
 
25
58
  export type FurinConfig = (typeof configSchema)["static"] & {
26
59
  plugins?: Bun.BunPlugin[];
60
+ static?: StaticExportConfig;
27
61
  };
28
62
 
29
63
  export function defineConfig(config: FurinConfig): FurinConfig {
@@ -0,0 +1,71 @@
1
+ import { AsyncLocalStorage } from "node:async_hooks";
2
+ import type { RequestLogger } from "evlog";
3
+ import { createLogger } from "evlog";
4
+ import { useLogger as _evlogUseLogger } from "evlog/elysia";
5
+
6
+ /**
7
+ * Fallback used when useLogger() is called completely outside any context
8
+ * (not in a live request, not in a synthetic render scope).
9
+ */
10
+ const noopLogger: RequestLogger = {
11
+ // biome-ignore lint/suspicious/noEmptyBlockStatements: intentional no-op
12
+ set: () => {},
13
+ // biome-ignore lint/suspicious/noEmptyBlockStatements: intentional no-op
14
+ error: () => {},
15
+ // biome-ignore lint/suspicious/noEmptyBlockStatements: intentional no-op
16
+ info: () => {},
17
+ // biome-ignore lint/suspicious/noEmptyBlockStatements: intentional no-op
18
+ warn: () => {},
19
+ emit: () => null,
20
+ getContext: () => ({}),
21
+ fork: (_label, fn) => fn() as undefined,
22
+ };
23
+
24
+ const syntheticRenderStorage = new AsyncLocalStorage<RequestLogger>();
25
+
26
+ /**
27
+ * Returns the current request-scoped logger.
28
+ *
29
+ * Priority:
30
+ * 1. Live Elysia request handled by the evlog() plugin → full request-scoped wide event
31
+ * 2. Synthetic render scope (ISR revalidation, SSG pre-render) → detached createLogger()
32
+ * that still drains to the configured adapter (Datadog, Axiom, etc.)
33
+ * 3. Completely outside any context → no-op
34
+ *
35
+ * Import from `@teyik0/furin` instead of `evlog/elysia` so this fallback chain
36
+ * applies in all rendering contexts.
37
+ */
38
+ export function useLogger(): RequestLogger {
39
+ try {
40
+ return _evlogUseLogger();
41
+ } catch {
42
+ return syntheticRenderStorage.getStore() ?? noopLogger;
43
+ }
44
+ }
45
+
46
+ /**
47
+ * Runs `fn` inside a synthetic render scope.
48
+ *
49
+ * Creates a detached `createLogger()` instance for the duration of `fn`.
50
+ * `useLogger()` calls inside `fn` (including user loaders) return this logger
51
+ * instead of throwing. On completion, the accumulated wide event is emitted to
52
+ * the global drain with the provided initial context (e.g. route pattern).
53
+ *
54
+ * Used by renderForPath() which drives both ISR background revalidation and
55
+ * SSG pre-renders — neither has a live Elysia request context.
56
+ */
57
+ export async function runInSyntheticRenderScope<T>(
58
+ fn: () => Promise<T> | T,
59
+ initialContext: Record<string, unknown>
60
+ ): Promise<T> {
61
+ const logger = createLogger(initialContext);
62
+ try {
63
+ const result = await syntheticRenderStorage.run(logger, () => Promise.resolve(fn()));
64
+ logger.emit();
65
+ return result;
66
+ } catch (err) {
67
+ logger.error(err instanceof Error ? err : new Error(String(err)));
68
+ logger.emit();
69
+ throw err;
70
+ }
71
+ }