@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,5 +1,6 @@
1
- import type { ReactNode } from "react";
1
+ import { createElement, type ReactNode } from "react";
2
2
  import { renderToReadableStream } from "react-dom/server";
3
+ import { RouterContext, type RouterContextValue } from "../link.tsx";
3
4
  import type { RootLayout } from "../router.ts";
4
5
  import { assembleHTML, resolvePath, splitTemplate, streamToString } from "./assemble.ts";
5
6
  import {
@@ -25,6 +26,7 @@ export { type LoaderResult, runLoaders } from "./loaders.ts";
25
26
 
26
27
  import type { Context } from "elysia";
27
28
  import { useLogger } from "evlog/elysia";
29
+ import { runInSyntheticRenderScope } from "../context-logger.ts";
28
30
  import type { ResolvedRoute } from "../router.ts";
29
31
  import { IS_DEV } from "../runtime-env.ts";
30
32
  import type { LoaderContext } from "./assemble.ts";
@@ -57,7 +59,8 @@ interface PreparedRender {
57
59
  async function prepareRender(
58
60
  route: ResolvedRoute,
59
61
  ctx: Context,
60
- root: RootLayout
62
+ root: RootLayout,
63
+ basePath?: string
61
64
  ): Promise<PreparedRender | Response> {
62
65
  const loaderStart = Date.now();
63
66
  const loaderResult = await runLoaders(route, ctx, root.route);
@@ -77,11 +80,38 @@ async function prepareRender(
77
80
 
78
81
  const headData = buildHeadInjection(route.page?.head?.(componentProps));
79
82
 
80
- const template = IS_DEV
81
- ? await getDevTemplate(new URL(ctx.request.url).origin)
82
- : (getProductionTemplate() ?? generateIndexHtml());
83
-
84
- const element = buildElement(route, componentProps, root.route);
83
+ // An explicitly-set production template (static pre-render, compiled Bun server)
84
+ // always wins over the IS_DEV flag. This decouples template resolution from the
85
+ // IS_DEV singleton so callers never need to flip IS_DEV just to get the right shell.
86
+ const prodTemplate = getProductionTemplate();
87
+ const template =
88
+ prodTemplate ??
89
+ (IS_DEV ? await getDevTemplate(new URL(ctx.request.url).origin) : generateIndexHtml());
90
+
91
+ let element = buildElement(route, componentProps, root.route);
92
+
93
+ // During static pre-render, inject a RouterContext so Link components render
94
+ // hrefs with the correct basePath prefix and active-state detection works.
95
+ // Only injected when basePath is explicitly provided (opt-in, static adapter only).
96
+ if (basePath !== undefined) {
97
+ const ssrContext: RouterContextValue = {
98
+ basePath,
99
+ currentHref: ctx.path,
100
+ navigate: () => Promise.resolve(),
101
+ prefetch: () => {
102
+ /* noop */
103
+ },
104
+ invalidatePrefetch: () => {
105
+ /* noop */
106
+ },
107
+ refresh: () => Promise.resolve(),
108
+ isNavigating: false,
109
+ defaultPreload: "intent",
110
+ defaultPreloadDelay: 50,
111
+ defaultPreloadStaleTime: 30_000,
112
+ };
113
+ element = createElement(RouterContext.Provider, { value: ssrContext }, element);
114
+ }
85
115
 
86
116
  return { componentProps, element, headData, headers, loader_ms, template };
87
117
  }
@@ -92,23 +122,36 @@ async function renderForPath(
92
122
  route: ResolvedRoute,
93
123
  params: Record<string, string>,
94
124
  root: RootLayout,
95
- origin: string
125
+ origin: string,
126
+ basePath?: string
96
127
  ): Promise<RenderResult> {
97
128
  const resolvedPath = resolvePath(route.pattern, params);
98
- return await renderToHTML(
99
- route,
100
- {
101
- params,
102
- query: {},
103
- request: new Request(`${origin}${resolvedPath}`),
104
- headers: {},
105
- cookie: {},
106
- redirect: (url, status = 302) => new Response(null, { status, headers: { Location: url } }),
107
- set: { headers: {} },
108
- path: resolvedPath,
109
- } as Context,
110
- root
129
+ const ctx: Context = {
130
+ params,
131
+ query: {},
132
+ request: new Request(`${origin}${resolvedPath}`),
133
+ headers: {},
134
+ cookie: {},
135
+ redirect: (url, status = 302) => new Response(null, { status, headers: { Location: url } }),
136
+ set: { headers: {} },
137
+ path: resolvedPath,
138
+ } as Context;
139
+
140
+ const prepared = await runInSyntheticRenderScope(
141
+ () => prepareRender(route, ctx, root, basePath),
142
+ { route: route.pattern }
111
143
  );
144
+ if (prepared instanceof Response) {
145
+ throw prepared;
146
+ }
147
+ const { componentProps, element, headData, headers, template } = prepared;
148
+ const stream = await renderToReadableStream(element);
149
+ await stream.allReady;
150
+ const reactHtml = await streamToString(stream);
151
+ return {
152
+ html: assembleHTML(template, headData, reactHtml, componentProps),
153
+ headers,
154
+ };
112
155
  }
113
156
 
114
157
  // ── Core pipeline ────────────────────────────────────────────────────────────
@@ -155,7 +198,8 @@ export async function prerenderSSG(
155
198
  route: ResolvedRoute,
156
199
  params: Record<string, string>,
157
200
  root: RootLayout,
158
- origin = "http://localhost:3000"
201
+ origin = "http://localhost:3000",
202
+ basePath?: string
159
203
  ): Promise<SsgCacheEntry | Response> {
160
204
  const resolvedPath = resolvePath(route.pattern, params);
161
205
 
@@ -166,7 +210,7 @@ export async function prerenderSSG(
166
210
 
167
211
  let result: RenderResult;
168
212
  try {
169
- result = await renderForPath(route, params, root, origin);
213
+ result = await renderForPath(route, params, root, origin, basePath);
170
214
  } catch (err) {
171
215
  // A loader called ctx.redirect() — surface it so the SSG handler (and
172
216
  // warm-up caller) can return the redirect response rather than crashing.
@@ -1,62 +1,107 @@
1
1
  import type { Context } from "elysia";
2
- import type { LoaderDeps, RuntimeRoute } from "../client";
2
+ import type { RuntimeRoute } from "../client";
3
+ import { useLogger } from "../context-logger.ts";
3
4
  import type { ResolvedRoute } from "../router";
4
5
 
5
6
  export type LoaderResult =
6
7
  | { type: "data"; data: Record<string, unknown>; headers: Record<string, string> }
7
8
  | { type: "redirect"; response: Response };
8
9
 
10
+ /**
11
+ * Wraps the Elysia context so that any property NOT present on `ctx` is
12
+ * returned as an individual `Promise<value>` resolved from the accumulated
13
+ * parent data. Properties that ARE present on `ctx` (request, params, set, …)
14
+ * are returned as-is.
15
+ *
16
+ * A per-prop cache ensures the same Promise instance is returned on repeated
17
+ * access of the same field (stable reference for Promise.all etc.).
18
+ */
19
+ function createLoaderCtx(
20
+ ctx: Record<string, unknown>,
21
+ accumulatedParentPromise: Promise<Record<string, unknown>>
22
+ ): Record<string, unknown> {
23
+ const cache = new Map<string, Promise<unknown>>();
24
+ return new Proxy(ctx, {
25
+ get(target, prop: string | symbol) {
26
+ if (typeof prop !== "string") {
27
+ return Reflect.get(target, prop);
28
+ }
29
+ // Short-circuit well-known Promise/serialisation introspection keys so
30
+ // the proxy is never treated as a thenable by Promise.resolve() or
31
+ // JSON.stringify(), which would cause silent infinite loops or wrong types.
32
+ if (prop === "then" || prop === "catch" || prop === "finally" || prop === "toJSON") {
33
+ return Reflect.get(target, prop);
34
+ }
35
+ // RouteContext fields (request, params, query, set, headers, cookie,
36
+ // path, redirect) are present on target — return directly.
37
+ // Use hasOwn so prototype keys (toString, constructor, …) are not
38
+ // mistaken for context fields and incorrectly hide parent loader data.
39
+ if (Object.hasOwn(target, prop)) {
40
+ return target[prop];
41
+ }
42
+ // Everything else is a parent-data field → individual lazy Promise.
43
+ let entry = cache.get(prop);
44
+ if (!entry) {
45
+ entry = accumulatedParentPromise.then((data) => data[prop]);
46
+ cache.set(prop, entry);
47
+ }
48
+ return entry;
49
+ },
50
+ });
51
+ }
52
+
53
+ // TODO: remove _rootLayout parameter in next refactor (unused; routeChain[0] is root layout)
9
54
  export async function runLoaders(
10
55
  route: ResolvedRoute,
11
56
  ctx: Context,
12
- rootLayout: RuntimeRoute
57
+ _rootLayout: RuntimeRoute
13
58
  ): Promise<LoaderResult> {
14
59
  try {
15
- // Step 1: root loader runs first — provides global context (user, auth, etc.)
16
- // Root data is merged into ctxWithRoot so all subsequent loaders receive it
17
- // automatically (backward-compatible with the previous waterfall behaviour).
18
- //
19
- // deps is defined here so it can be passed to the root loader too.
20
- // The root has no ancestors, so deps always returns an empty resolved promise.
60
+ // Inject `log` so loaders can destructure it directly as `({ log })`.
61
+ // useLogger() resolves the correct logger for every rendering context:
62
+ // live request → evlog request-scoped logger, synthetic render → detached
63
+ // createLogger() from runInSyntheticRenderScope, outside any context → no-op.
64
+ const ctxRecord = { ...(ctx as Record<string, unknown>), log: useLogger() };
21
65
  const loaderMap = new Map<RuntimeRoute, Promise<Record<string, unknown>>>();
22
66
 
23
- const deps: LoaderDeps = (routeRef) =>
24
- loaderMap.get(routeRef as RuntimeRoute) ?? Promise.resolve({});
67
+ // All loaders in the chain start immediately. Each receives a Proxy where
68
+ // parent-data fields are individually-awaitable Promises. The loader opts
69
+ // in to waiting by doing `await user` (or `Promise.all([user, org])`);
70
+ // if it never awaits a parent field it runs in full parallel.
71
+ let accumulatedParentPromise: Promise<Record<string, unknown>> = Promise.resolve({});
25
72
 
26
- // Run root loader and store its result in loaderMap so that
27
- // deps(rootRoute) returns the actual root data (not empty {}).
28
- const rootPromise: Promise<Record<string, unknown>> = rootLayout.loader
29
- ? Promise.resolve(rootLayout.loader({ ...ctx }, deps)).then((r) => r ?? {})
30
- : Promise.resolve({});
31
- loaderMap.set(rootLayout, rootPromise);
32
- const rootData = await rootPromise;
33
- const ctxWithRoot = { ...ctx, ...rootData };
73
+ for (const r of route.routeChain) {
74
+ const parentAccum = accumulatedParentPromise; // capture for closure
34
75
 
35
- // Step 2: launch all ancestor + page loaders immediately in parallel.
36
- // Each is stored in loaderMap keyed by object identity so that deps()
37
- // can resolve a Promise for any route in the chain.
38
- //
39
- // Loaders are inserted in chain order (index 1, 2, 3 …) so when loader N
40
- // calls `await deps(routeAtIndexM)` where M < N, the Promise is already
41
- // present in the map — no deadlock is possible for backward dependencies.
76
+ if (r.loader) {
77
+ const loaderCtx = createLoaderCtx(ctxRecord, parentAccum);
78
+ const loaderPromise = Promise.resolve(r.loader(loaderCtx)).then((res) => res ?? {});
79
+ loaderMap.set(r, loaderPromise);
42
80
 
43
- for (let i = 1; i < route.routeChain.length; i++) {
44
- const ancestor = route.routeChain[i];
45
- if (ancestor?.loader) {
46
- loaderMap.set(
47
- ancestor,
48
- Promise.resolve(ancestor.loader(ctxWithRoot, deps)).then((r) => r ?? {})
49
- );
81
+ // Accumulate: previous ancestors + this loader's result.
82
+ // A void .catch() suppresses the "unhandled rejection" warning that
83
+ // fires when a sibling or child loader throws — but unlike `.catch(
84
+ // () => ({}))` it does NOT resolve the promise, so child loaders'
85
+ // field-accesses via createLoaderCtx still receive the rejection
86
+ // instead of silently resolving to undefined. The real rejection is
87
+ // re-thrown by the Promise.all below.
88
+ accumulatedParentPromise = Promise.all([parentAccum, loaderPromise]).then(([acc, own]) => ({
89
+ ...acc,
90
+ ...own,
91
+ }));
92
+ accumulatedParentPromise.catch(() => {
93
+ /* suppress unhandled-rejection warning */
94
+ });
50
95
  }
51
96
  }
52
97
 
53
- // Page loader — all ancestors are already in the map at this point.
98
+ // Page loader receives all route-chain fields as individual Promises.
99
+ const pageCtx = createLoaderCtx(ctxRecord, accumulatedParentPromise);
54
100
  const pagePromise: Promise<Record<string, unknown>> = route.page?.loader
55
- ? Promise.resolve(route.page.loader(ctxWithRoot, deps)).then((r) => r ?? {})
101
+ ? Promise.resolve(route.page.loader(pageCtx)).then((r) => r ?? {})
56
102
  : Promise.resolve({});
57
103
 
58
- // Step 3: await all in parallel, then flat-merge results.
59
- // loaderMap already contains the root promise, so we don't merge rootData separately.
104
+ // Await everything in parallel, then flat-merge (same contract as before).
60
105
  const results = await Promise.all([...loaderMap.values(), pagePromise]);
61
106
  const data = Object.assign({}, ...results);
62
107
  const headers: Record<string, string> = {};
@@ -2,14 +2,14 @@ import type { HeadOptions, MetaDescriptor } from "../client.ts";
2
2
 
3
3
  export function extractTitle(meta?: MetaDescriptor[]): string | undefined {
4
4
  if (!meta) {
5
- return undefined;
5
+ return;
6
6
  }
7
7
  for (const entry of meta) {
8
8
  if ("title" in entry) {
9
9
  return (entry as { title: string }).title;
10
10
  }
11
11
  }
12
- return undefined;
12
+ return;
13
13
  }
14
14
 
15
15
  export function isMetaTag(entry: MetaDescriptor): boolean {
@@ -149,11 +149,15 @@ export function generateIndexHtml(): string {
149
149
  *
150
150
  * @param buildId - Short hash identifying this specific build. Injected as a
151
151
  * `<meta name="furin-build-id">` tag so the client can detect stale deploys.
152
+ * @param faviconHref - Absolute href for the favicon (e.g. "/furin/favicon.ico").
153
+ * When provided, a `<link rel="icon">` tag is injected so browsers can locate
154
+ * the favicon even when the site is served from a sub-path.
152
155
  */
153
156
  export function generateProdIndexHtml(
154
157
  entryChunk: string,
155
158
  cssChunks: string[],
156
- buildId?: string
159
+ buildId?: string,
160
+ faviconHref?: string
157
161
  ): string {
158
162
  const cssLinks = cssChunks
159
163
  .map((c) => ` <link rel="stylesheet" crossorigin href="${c}">`)
@@ -162,6 +166,9 @@ export function generateProdIndexHtml(
162
166
  const buildIdMeta = buildId
163
167
  ? ` <meta name="furin-build-id" content="${escapeHtml(buildId)}">\n`
164
168
  : "";
169
+ const faviconLink = faviconHref
170
+ ? ` <link rel="icon" href="${escapeHtml(faviconHref)}">\n`
171
+ : "";
165
172
 
166
173
  return `<!DOCTYPE html>
167
174
  <html lang="en">
@@ -169,7 +176,7 @@ export function generateProdIndexHtml(
169
176
  <meta charset="UTF-8">
170
177
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
171
178
  ${THEME_INIT_SCRIPT}
172
- ${buildIdMeta}${cssLinks ? `${cssLinks}\n` : ""} <!--ssr-head-->
179
+ ${buildIdMeta}${faviconLink}${cssLinks ? `${cssLinks}\n` : ""} <!--ssr-head-->
173
180
  </head>
174
181
  <body>
175
182
  <div id="root"><!--ssr-outlet--></div>
package/src/router.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  import { existsSync } from "node:fs";
2
2
  import { readdir } from "node:fs/promises";
3
3
  import { join, parse } from "node:path";
4
- import { type AnyElysia, type Context, Elysia } from "elysia";
4
+ import { type AnyElysia, type Context, Elysia, t } from "elysia";
5
5
  import type { AnySchema } from "elysia/types";
6
6
  import type { RuntimePage, RuntimeRoute } from "./client.ts";
7
7
  import { type CompileContext, getCompileContext } from "./internal.ts";
@@ -221,11 +221,21 @@ async function handleDevRequest(
221
221
  // --hot's file watcher, then hand off to renderSSR which runs loaders,
222
222
  // renders React to HTML, and injects __FURIN_DATA__.
223
223
  try {
224
+ let currentRoot = root;
225
+ const rootMod = (await import(`${root.path}?furin-server&t=${Date.now()}`)) as Record<
226
+ string,
227
+ unknown
228
+ >;
229
+ const rootExport = rootMod.route ?? rootMod.default;
230
+ if (rootExport && isFurinRoute(rootExport) && rootExport.layout) {
231
+ currentRoot = { path: root.path, route: rootExport };
232
+ }
233
+
224
234
  const pageMod = await import(`${route.path}?furin-server&t=${Date.now()}`);
225
235
  const page = pageMod.default;
226
236
  if (page && isFurinPage(page)) {
227
237
  const chain = collectRouteChainFromRoute(page._route as RuntimeRoute);
228
- return renderSSR({ ...route, page, routeChain: chain }, ctx, root);
238
+ return renderSSR({ ...route, page, routeChain: chain }, ctx, currentRoot);
229
239
  }
230
240
  } catch (err) {
231
241
  console.error(`[furin] Dev page load error for ${route.path}:`, err);
@@ -273,13 +283,52 @@ async function handleSSGRequest(
273
283
  return entry.html;
274
284
  }
275
285
 
286
+ // Standard structural keys on a TObject — everything else is a user-supplied option
287
+ // (e.g. additionalProperties, $id, description, title) and must be preserved.
288
+ const TOBJECT_STRUCTURAL_KEYS = new Set(["type", "properties", "required"]);
289
+
290
+ /**
291
+ * Merges TObject schemas from all routeChain entries for a given key.
292
+ * Properties are spread left-to-right (leaf wins on key conflict).
293
+ * Object-level options (additionalProperties, $id, description, …) are also
294
+ * merged with the same leaf-wins semantics so they are not silently dropped.
295
+ * Returns undefined when no entry in the chain defines the key.
296
+ *
297
+ * @internal Exported for unit testing.
298
+ */
299
+ export function mergeRouteSchemas(
300
+ routeChain: RuntimeRoute[],
301
+ key: "params" | "query"
302
+ ): AnySchema | undefined {
303
+ const schemas = routeChain.map((r) => r[key]).filter(Boolean) as Record<string, unknown>[];
304
+
305
+ if (schemas.length === 0) {
306
+ return;
307
+ }
308
+ if (schemas.length === 1) {
309
+ return schemas[0] as AnySchema;
310
+ }
311
+
312
+ const mergedProperties = Object.assign(
313
+ {},
314
+ ...schemas.map((s) => (s.properties as Record<string, unknown>) ?? {})
315
+ );
316
+
317
+ const mergedOptions = Object.assign(
318
+ {},
319
+ ...schemas.map((s) =>
320
+ Object.fromEntries(Object.entries(s).filter(([k]) => !TOBJECT_STRUCTURAL_KEYS.has(k)))
321
+ )
322
+ );
323
+
324
+ return t.Object(mergedProperties, mergedOptions) as AnySchema;
325
+ }
326
+
276
327
  export function createRoutePlugin(route: ResolvedRoute, root: RootLayout, buildId = ""): AnyElysia {
277
328
  const { pattern, routeChain } = route;
278
329
 
279
- // TODO: merge schemas from all routeChain entries (requires TypeBox t.Object/t.Composite)
280
- // For now, prefer the leaf route's schema (last in chain) over ancestor routes.
281
- const allParams = routeChain.findLast((r) => r.params)?.params;
282
- const allQuery = routeChain.findLast((r) => r.query)?.query;
330
+ const allParams = mergeRouteSchemas(routeChain, "params");
331
+ const allQuery = mergeRouteSchemas(routeChain, "query");
283
332
  const hasQuerySchema = !!allQuery;
284
333
 
285
334
  // Guard and handler MUST live in the same Elysia scope so that validation