@teyik0/furin 0.8.0-alpha.0 → 0.9.0-alpha.0

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 (143) hide show
  1. package/README.md +37 -0
  2. package/dist/adapter/bun/app.d.ts +1 -0
  3. package/dist/adapter/bun.d.ts +3 -1
  4. package/dist/adapter/runtime-build.d.ts +8 -5
  5. package/dist/adapter/vercel.js +8 -8
  6. package/dist/build/client.d.ts +2 -2
  7. package/dist/build/discover-mounts-process.d.ts +1 -1
  8. package/dist/build/discover-pages-process.d.ts +1 -0
  9. package/dist/build/discover-pages.d.ts +11 -0
  10. package/dist/build/discovery-module.d.ts +3 -0
  11. package/dist/build/discovery-plugins.d.ts +34 -0
  12. package/dist/build/elysia-aot.d.ts +1 -1
  13. package/dist/build/entry-template.ts +6 -1
  14. package/dist/build/hydrate.d.ts +3 -2
  15. package/dist/build/index.js +7688 -8458
  16. package/dist/build/preload-manifest.d.ts +2 -2
  17. package/dist/build/route-metadata.d.ts +31 -0
  18. package/dist/build/route-types.d.ts +1 -1
  19. package/dist/build/shared.d.ts +2 -2
  20. package/dist/build/types.d.ts +11 -0
  21. package/dist/cli/dev-worker.d.ts +1 -0
  22. package/dist/cli/dev-worker.ts +123 -0
  23. package/dist/cli/dev.d.ts +1 -0
  24. package/dist/cli/index.js +7811 -8477
  25. package/dist/client/browser-events-runtime.d.ts +2 -2
  26. package/dist/client/browser-events.d.ts +2 -0
  27. package/dist/client/chunks/{client-brdfd773.js → client-rjhxgt64.js} +187 -4
  28. package/dist/client/dev-error-overlay.ts +18 -1
  29. package/dist/client/link.js +110 -156
  30. package/dist/client/query-store.d.ts +5 -0
  31. package/dist/client/router/navigation-controller.d.ts +2 -0
  32. package/dist/client/router/use-fetch-interception.d.ts +1 -1
  33. package/dist/client/router/use-sync-stream.d.ts +1 -1
  34. package/dist/client/{router/sync-catch-up.d.ts → sync-catch-up.d.ts} +5 -3
  35. package/dist/client/sync-client.d.ts +74 -0
  36. package/dist/client.d.ts +1 -0
  37. package/dist/client.js +533 -145
  38. package/dist/config.d.ts +6 -1
  39. package/dist/config.js +3 -1
  40. package/dist/define-route.d.ts +3 -3
  41. package/dist/furin.d.ts +2 -1
  42. package/dist/furin.js +1119 -346
  43. package/dist/plugin/index.js +5 -5
  44. package/dist/plugin/route-registry.d.ts +22 -2
  45. package/dist/rsc/build/index.d.ts +4 -3
  46. package/dist/server/dev/server-only-module.d.ts +5 -0
  47. package/dist/server/internal.js +201 -91
  48. package/dist/server/logging/ingest-plugin.d.ts +1 -2
  49. package/dist/server/production-server.js +36 -33
  50. package/dist/server/server-entry.d.ts +5 -0
  51. package/dist/server/server-entry.js +36 -0
  52. package/dist/server/static-export.js +201 -91
  53. package/dist/server/sync/adapter.d.ts +4 -3
  54. package/dist/server/sync/config.d.ts +7 -0
  55. package/dist/server/sync/connection.d.ts +13 -0
  56. package/dist/server/sync/drizzle/index.js +5 -4
  57. package/dist/server/sync/index.d.ts +3 -0
  58. package/dist/server/sync/index.js +1361 -243
  59. package/dist/server/sync/invalidate-sync.d.ts +6 -2
  60. package/dist/server/sync/local-client.d.ts +9 -0
  61. package/dist/server/sync/postgres/index.d.ts +1 -1
  62. package/dist/server/sync/postgres/index.js +2 -2
  63. package/dist/server/sync/prisma/index.js +2 -2
  64. package/dist/server/sync/redis/index.d.ts +1 -1
  65. package/dist/server/sync/redis/index.js +4 -3
  66. package/dist/server/sync/redis/scripts.d.ts +1 -1
  67. package/dist/server/sync/runtime.d.ts +3 -0
  68. package/dist/server/sync/sqlite/index.d.ts +1 -1
  69. package/dist/server/sync/sqlite/index.js +3 -2
  70. package/dist/shared/browser-events.d.ts +4 -0
  71. package/dist/sync-client.d.ts +3 -0
  72. package/dist/sync-client.js +1600 -0
  73. package/package.json +12 -7
  74. package/src/adapter/README.md +7 -0
  75. package/src/adapter/build.ts +34 -33
  76. package/src/adapter/bun/app.ts +5 -0
  77. package/src/adapter/bun/server.ts +2 -2
  78. package/src/adapter/bun.ts +18 -2
  79. package/src/adapter/furin-app.d.ts +1 -0
  80. package/src/adapter/package.ts +1 -0
  81. package/src/adapter/runtime-build.ts +18 -12
  82. package/src/adapter/static.ts +17 -13
  83. package/src/build/client.ts +7 -5
  84. package/src/build/discover-mounts-process.ts +5 -1
  85. package/src/build/discover-pages-process.ts +151 -0
  86. package/src/build/discover-pages.ts +69 -0
  87. package/src/build/discovery-module.ts +70 -0
  88. package/src/build/discovery-plugins.ts +101 -0
  89. package/src/build/elysia-aot-worker.ts +9 -8
  90. package/src/build/elysia-aot.ts +110 -75
  91. package/src/build/entry-template.ts +6 -1
  92. package/src/build/hydrate.ts +11 -8
  93. package/src/build/index.ts +6 -50
  94. package/src/build/preload-manifest.ts +3 -3
  95. package/src/build/route-metadata.ts +90 -0
  96. package/src/build/route-types.ts +1 -1
  97. package/src/build/shared.ts +6 -8
  98. package/src/build/types.ts +9 -0
  99. package/src/cli/config.ts +4 -0
  100. package/src/cli/dev-worker.ts +123 -0
  101. package/src/cli/dev.ts +91 -0
  102. package/src/cli/index.ts +24 -1
  103. package/src/client/browser-events-runtime.ts +97 -23
  104. package/src/client/browser-events.ts +8 -0
  105. package/src/client/dev-error-overlay.ts +18 -1
  106. package/src/client/query-store.ts +54 -3
  107. package/src/client/router/navigation-controller.ts +45 -12
  108. package/src/client/router/provider.tsx +6 -2
  109. package/src/client/router/use-fetch-interception.ts +1 -1
  110. package/src/client/router/use-sync-stream.ts +96 -44
  111. package/src/client/{router/sync-catch-up.ts → sync-catch-up.ts} +28 -12
  112. package/src/client/sync-client.ts +528 -0
  113. package/src/client/sync.ts +11 -4
  114. package/src/client.ts +10 -0
  115. package/src/config.ts +17 -10
  116. package/src/furin.ts +5 -0
  117. package/src/plugin/route-registry.ts +53 -7
  118. package/src/rsc/build/index.ts +6 -3
  119. package/src/server/browser-events/plugin.ts +79 -25
  120. package/src/server/dev/rewrite-module-specifiers.ts +2 -1
  121. package/src/server/dev/server-only-module.ts +23 -0
  122. package/src/server/dev/symbolicate.ts +4 -3
  123. package/src/server/dev-page-imports.ts +3 -1
  124. package/src/server/dev-page-plugin.ts +18 -1
  125. package/src/server/logging/ingest-plugin.ts +3 -9
  126. package/src/server/server-entry.ts +39 -0
  127. package/src/server/sync/adapter.ts +7 -3
  128. package/src/server/sync/config.ts +12 -6
  129. package/src/server/sync/connection.ts +71 -0
  130. package/src/server/sync/index.ts +3 -0
  131. package/src/server/sync/invalidate-sync.ts +30 -5
  132. package/src/server/sync/local-client.ts +84 -0
  133. package/src/server/sync/plugin.ts +27 -20
  134. package/src/server/sync/postgres/index.ts +9 -2
  135. package/src/server/sync/redis/index.ts +5 -1
  136. package/src/server/sync/redis/scripts.ts +1 -1
  137. package/src/server/sync/runtime.ts +56 -18
  138. package/src/server/sync/sqlite/index.ts +6 -2
  139. package/src/server/sync/stream.ts +17 -5
  140. package/src/shared/browser-events.ts +1 -1
  141. package/src/sync-client.ts +14 -0
  142. package/dist/server/logger.d.ts +0 -10
  143. package/src/server/logger.ts +0 -34
@@ -0,0 +1,69 @@
1
+ import { mkdtempSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ import { serialize } from "node:v8";
4
+ import { frameworkSourceModule } from "../adapter/runtime-build.ts";
5
+ import type { FurinPlugin } from "../config.ts";
6
+ import type { RouteRegistrySnapshot } from "../plugin/route-registry.ts";
7
+ import type { RouteInstanceSpec } from "../plugin/route-tree.ts";
8
+ import { type DiscoveryPluginRequest, discoveryPlugins } from "./discovery-plugins.ts";
9
+ import type { BuildRoot, BuildRoute } from "./route-metadata.ts";
10
+ import { ensureDir } from "./shared.ts";
11
+
12
+ export interface DiscoveredApp extends RouteInstanceSpec {
13
+ root: BuildRoot;
14
+ routeRegistry: RouteRegistrySnapshot;
15
+ routes: BuildRoute[];
16
+ }
17
+
18
+ /** Await process exit, not just its result: native import-time handles must be closed before AOT. */
19
+ export async function discoverPages(
20
+ apps: RouteInstanceSpec[],
21
+ rootDir: string,
22
+ plugins: FurinPlugin[]
23
+ ): Promise<DiscoveredApp[]> {
24
+ const runtime = await discoveryPlugins(plugins);
25
+ const buildDir = join(rootDir, ".furin/build");
26
+ ensureDir(buildDir);
27
+ const directory = mkdtempSync(join(buildDir, "discovery-"));
28
+ const resultPath = join(directory, "pages.json");
29
+ const child = Bun.spawn(
30
+ [
31
+ process.execPath,
32
+ frameworkSourceModule("build/discover-pages-process.ts"),
33
+ JSON.stringify({ apps, hooks: runtime.hooks, resultPath }),
34
+ ],
35
+ {
36
+ cwd: rootDir,
37
+ env: { ...process.env, NODE_ENV: "production" },
38
+ serialization: "advanced",
39
+ async ipc(request: DiscoveryPluginRequest, subprocess) {
40
+ const response = await runtime.respond(request);
41
+ if (subprocess.exitCode !== null) {
42
+ return;
43
+ }
44
+ if (request.syncPath) {
45
+ const temporary = `${request.syncPath}.tmp`;
46
+ writeFileSync(temporary, serialize(response));
47
+ renameSync(temporary, request.syncPath);
48
+ } else {
49
+ subprocess.send(response);
50
+ }
51
+ },
52
+ stderr: "pipe",
53
+ stdout: "pipe",
54
+ }
55
+ );
56
+ try {
57
+ const [exitCode, stdout, stderr] = await Promise.all([
58
+ child.exited,
59
+ new Response(child.stdout).text(),
60
+ new Response(child.stderr).text(),
61
+ ]);
62
+ if (exitCode !== 0) {
63
+ throw new Error(`[furin] Route discovery failed:\n${stderr}\n${stdout}`);
64
+ }
65
+ return JSON.parse(readFileSync(resultPath, "utf8")) as DiscoveredApp[];
66
+ } finally {
67
+ rmSync(directory, { force: true, recursive: true });
68
+ }
69
+ }
@@ -0,0 +1,70 @@
1
+ import { pruneOrphanedCode } from "../plugin/dead-code-elimination.ts";
2
+ import { parseModule, replaceRange } from "../plugin/module-transform.ts";
3
+ import { collectDefineRouteBindings, exportedRouteChain } from "../plugin/route-chains.ts";
4
+
5
+ /** Stub route behavior while preserving module initialization and public metadata. */
6
+ export function discoveryModule(
7
+ code: string,
8
+ path: string,
9
+ loader: "js" | "jsx" | "ts" | "tsx"
10
+ ): string {
11
+ const module = parseModule(code, `${path}.${loader}`);
12
+ const chain = exportedRouteChain(module.program, collectDefineRouteBindings(module.program));
13
+ const boundary = /[\\/](?:error|not-found)\.[jt]sx?$/.test(path);
14
+ if (!(chain || boundary)) {
15
+ return code;
16
+ }
17
+ for (const { call, method } of chain?.calls ?? []) {
18
+ if (method === "config") {
19
+ continue;
20
+ }
21
+ for (const argument of call.arguments) {
22
+ replaceRange(module, argument.start, argument.end, "() => undefined");
23
+ }
24
+ }
25
+ if (boundary) {
26
+ for (const statement of module.program.body) {
27
+ if (statement.type !== "ExportDefaultDeclaration") {
28
+ continue;
29
+ }
30
+ const declaration = statement.declaration;
31
+ if (declaration.type === "FunctionDeclaration" && declaration.body) {
32
+ replaceRange(module, declaration.body.start, declaration.body.end, "{ return null; }");
33
+ } else if (declaration.type === "ClassDeclaration") {
34
+ for (const member of declaration.body.body) {
35
+ if (
36
+ (member.type === "MethodDefinition" || member.type === "PropertyDefinition") &&
37
+ !member.static &&
38
+ ((member.key.type === "Identifier" && member.key.name === "render") ||
39
+ (member.key.type === "Literal" && member.key.value === "render"))
40
+ ) {
41
+ const render = member.value;
42
+ if (
43
+ (render?.type === "FunctionExpression" ||
44
+ render?.type === "ArrowFunctionExpression") &&
45
+ render.body
46
+ ) {
47
+ replaceRange(
48
+ module,
49
+ render.body.start,
50
+ render.body.end,
51
+ render.body.type === "BlockStatement" ? "{ return null; }" : "null"
52
+ );
53
+ }
54
+ }
55
+ }
56
+ } else {
57
+ replaceRange(module, declaration.start, declaration.end, "() => null");
58
+ }
59
+ }
60
+ }
61
+ pruneOrphanedCode(module, new Set(), new Set());
62
+ return module.source.toString();
63
+ }
64
+
65
+ export function discoveryModuleFilter(pagesDirs: readonly string[]): RegExp {
66
+ const directories = pagesDirs
67
+ .map((path) => path.split(/[\\/]/).map(RegExp.escape).join("[\\\\/]"))
68
+ .join("|");
69
+ return new RegExp(`^(?:${directories})[\\\\/].*\\.[cm]?[jt]sx?$`);
70
+ }
@@ -0,0 +1,101 @@
1
+ // biome-ignore-all lint/performance/noAwaitInLoops: plugin registration order determines module resolution
2
+ import type { FurinPlugin } from "../config.ts";
3
+
4
+ export type DiscoveryHook = { id: number } & (
5
+ | { method: "module"; specifier: string }
6
+ | {
7
+ method: "onLoad" | "onResolve";
8
+ filter: { source: string; flags: string };
9
+ namespace?: string;
10
+ }
11
+ );
12
+
13
+ export interface DiscoveryPluginRequest {
14
+ args: Omit<Bun.OnLoadArgs, "defer"> | Bun.OnResolveArgs | undefined;
15
+ hook: number;
16
+ id: number;
17
+ syncPath?: string;
18
+ }
19
+
20
+ export type DiscoveryPluginResponse =
21
+ | { id: number; ok: true; value: Bun.OnLoadResult | Bun.OnResolveResult | null }
22
+ | { id: number; ok: false; error: string };
23
+
24
+ /** Keep plugin closures in the caller; only module source crosses IPC. */
25
+ export async function discoveryPlugins(plugins: readonly FurinPlugin[]) {
26
+ const hooks: DiscoveryHook[] = [];
27
+ const callbacks: ((
28
+ args: DiscoveryPluginRequest["args"]
29
+ ) => Promise<Bun.OnLoadResult | Bun.OnResolveResult | null>)[] = [];
30
+ for (const plugin of plugins) {
31
+ if (plugin.buildOnly) {
32
+ continue;
33
+ }
34
+ try {
35
+ await Bun.plugin({
36
+ name: plugin.name,
37
+ setup(builder) {
38
+ const proxy = new Proxy(builder, {
39
+ get(target, method) {
40
+ if (method === "onLoad" || method === "onResolve") {
41
+ return (
42
+ constraints: Bun.PluginConstraints,
43
+ callback: Bun.OnLoadCallback | Bun.OnResolveCallback
44
+ ) => {
45
+ const id = callbacks.length;
46
+ callbacks.push(
47
+ async (args) =>
48
+ await (callback as (input: typeof args) => ReturnType<typeof callback>)(args)
49
+ );
50
+ hooks.push({
51
+ id,
52
+ method,
53
+ filter: { source: constraints.filter.source, flags: constraints.filter.flags },
54
+ namespace: constraints.namespace,
55
+ });
56
+ return proxy;
57
+ };
58
+ }
59
+ if (method === "module") {
60
+ return (
61
+ specifier: string,
62
+ callback: () => Bun.OnLoadResult | Promise<Bun.OnLoadResult>
63
+ ) => {
64
+ const id = callbacks.length;
65
+ callbacks.push(async () => await callback());
66
+ hooks.push({ id, method, specifier });
67
+ return proxy;
68
+ };
69
+ }
70
+ const value = Reflect.get(target, method);
71
+ return typeof value === "function" ? value.bind(target) : value;
72
+ },
73
+ });
74
+ return plugin.setup(proxy);
75
+ },
76
+ });
77
+ } catch (error) {
78
+ throw new Error(
79
+ `[furin] Plugin "${plugin.name}" could not be registered for server-side route imports: ${error instanceof Error ? error.message : String(error)}\n` +
80
+ "If it only transforms the client bundle (for example bun-plugin-tailwind), mark it build-only in furin.config.ts:\n" +
81
+ " plugins: [{ ...plugin, buildOnly: true }]",
82
+ { cause: error }
83
+ );
84
+ }
85
+ }
86
+ return {
87
+ hooks,
88
+ async respond(request: DiscoveryPluginRequest): Promise<DiscoveryPluginResponse> {
89
+ try {
90
+ const value = await callbacks[request.hook]?.(request.args);
91
+ return { id: request.id, ok: true, value };
92
+ } catch (error) {
93
+ return {
94
+ id: request.id,
95
+ ok: false,
96
+ error: error instanceof Error ? error.message : String(error),
97
+ };
98
+ }
99
+ },
100
+ };
101
+ }
@@ -1,6 +1,5 @@
1
1
  import { dirname, extname, join } from "node:path";
2
2
  import { fileURLToPath } from "node:url";
3
- import { parentPort, workerData } from "node:worker_threads";
4
3
  import { aotFactory } from "elysia/plugin/aot/unplugin";
5
4
  import { isomorphicTransformPlugin } from "../plugin/transform-isomorphic.ts";
6
5
  import { collectFurinRegistrations, type FurinRegistration } from "../server/registrations.ts";
@@ -23,11 +22,13 @@ export type AotWorkerResponse =
23
22
  | (AotWorkerResult & { id: number; ok: true })
24
23
  | { error: Error; id: number; ok: false; registrations?: FurinRegistration[] };
25
24
 
26
- const port = parentPort;
27
- if (!port) {
28
- throw new Error("[furin] Elysia AOT worker requires a parent port.");
25
+ const send = process.send?.bind(process);
26
+ if (!send) {
27
+ throw new Error("[furin] Elysia AOT process requires IPC.");
29
28
  }
30
- const { entry } = workerData as { entry: string };
29
+ // A dead build parent must not leave its evaluation and native locks behind.
30
+ process.on("disconnect", () => process.exit(0));
31
+ const entry = process.argv[2] as string;
31
32
  const hooks = aotFactory({ entry, strip: false, target: "bun" });
32
33
  Bun.plugin(isomorphicTransformPlugin("server"));
33
34
  const registrations = collectFurinRegistrations(false);
@@ -99,7 +100,7 @@ async function exportInMemoryApps(): Promise<void> {
99
100
  );
100
101
  }
101
102
 
102
- port.on("message", async (request: AotWorkerRequest) => {
103
+ process.on("message", async (request: AotWorkerRequest) => {
103
104
  try {
104
105
  let code: string | undefined;
105
106
  let virtualType: string | undefined;
@@ -115,7 +116,7 @@ port.on("message", async (request: AotWorkerRequest) => {
115
116
  } else {
116
117
  hooks.buildEnd?.();
117
118
  }
118
- port.postMessage({
119
+ send({
119
120
  code,
120
121
  id: request.id,
121
122
  ok: true,
@@ -123,7 +124,7 @@ port.on("message", async (request: AotWorkerRequest) => {
123
124
  virtualType,
124
125
  } satisfies AotWorkerResponse);
125
126
  } catch (error) {
126
- port.postMessage({
127
+ send({
127
128
  error: error instanceof Error ? error : new Error(String(error)),
128
129
  id: request.id,
129
130
  ok: false,
@@ -1,7 +1,7 @@
1
+ import { fork } from "node:child_process";
1
2
  import { existsSync, realpathSync } from "node:fs";
2
3
  import { dirname, join, relative, resolve } from "node:path";
3
4
  import { fileURLToPath } from "node:url";
4
- import { Worker } from "node:worker_threads";
5
5
  import type { RouteInstanceSpec } from "../plugin/route-tree.ts";
6
6
  import type { FurinRegistration } from "../server/registrations.ts";
7
7
  import type {
@@ -15,7 +15,7 @@ const AOT_NAMESPACE = "furin-elysia-aot";
15
15
  const ELYSIA_RESOLVE_DIR = dirname(Bun.resolveSync("elysia", import.meta.dir));
16
16
  // The published package ships src/ too; resolving from the package entry also
17
17
  // works when this adapter is bundled into dist/build/index.js or dist/cli/index.js.
18
- const AOT_WORKER_PATH = join(
18
+ const AOT_PROCESS_PATH = join(
19
19
  dirname(dirname(fileURLToPath(import.meta.resolve("@teyik0/furin")))),
20
20
  "src/build/elysia-aot-worker.ts"
21
21
  );
@@ -103,13 +103,34 @@ export interface AotBuildApps {
103
103
  rootDir: string;
104
104
  }
105
105
 
106
- /** Elysia AOT evaluation has its own module cache, independent of prerender loaders. */
106
+ /** AOT imports own native resources in a separate process, exited before prerender. */
107
107
  export function elysiaAot(entry: string, expected: AotBuildApps): Bun.BunPlugin {
108
108
  const entryPath = resolve(entry);
109
109
  return {
110
110
  name: "elysia-aot",
111
111
  async setup(build) {
112
- const worker = new Worker(AOT_WORKER_PATH, { workerData: { entry: entryPath } });
112
+ const child = fork(AOT_PROCESS_PATH, [entryPath], {
113
+ cwd: expected.rootDir,
114
+ execArgv: [],
115
+ execPath: process.execPath,
116
+ serialization: "advanced",
117
+ stdio: ["ignore", "inherit", "inherit", "ipc"],
118
+ });
119
+ const closed = new Promise<void>((resolveClosed) => {
120
+ child.once("close", () => resolveClosed());
121
+ });
122
+ let stopped: Promise<void> | undefined;
123
+ const stop = (): Promise<void> => {
124
+ stopped ??= (async () => {
125
+ // Application imports can keep timers, signal handlers and native
126
+ // handles alive. Reap the process even when those ignore shutdown.
127
+ if (child.exitCode === null && child.signalCode === null) {
128
+ child.kill("SIGKILL");
129
+ }
130
+ await closed;
131
+ })();
132
+ return stopped;
133
+ };
113
134
  const pending = new Map<
114
135
  number,
115
136
  {
@@ -118,16 +139,16 @@ export function elysiaAot(entry: string, expected: AotBuildApps): Bun.BunPlugin
118
139
  }
119
140
  >();
120
141
  let nextId = 0;
121
- let workerFailure: Error | undefined;
142
+ let childFailure: Error | undefined;
122
143
  let registrations: FurinRegistration[] = [];
123
144
  const fail = (error: Error): void => {
124
- workerFailure = error;
145
+ childFailure = error;
125
146
  for (const request of pending.values()) {
126
147
  request.reject(error);
127
148
  }
128
149
  pending.clear();
129
150
  };
130
- worker.on("message", (response: AotWorkerResponse) => {
151
+ child.on("message", (response: AotWorkerResponse) => {
131
152
  const request = pending.get(response.id);
132
153
  pending.delete(response.id);
133
154
  registrations = response.registrations ?? registrations;
@@ -137,89 +158,103 @@ export function elysiaAot(entry: string, expected: AotBuildApps): Bun.BunPlugin
137
158
  request?.reject(response.error);
138
159
  }
139
160
  });
140
- worker.on("error", fail);
141
- worker.on("exit", (code) => fail(new Error(`[furin] Elysia AOT worker exited (${code}).`)));
161
+ child.on("error", fail);
162
+ child.on("exit", (code, signal) =>
163
+ fail(new Error(`[furin] Elysia AOT process exited (${signal ?? code}).`))
164
+ );
142
165
  const request = (payload: AotWorkerOperation) =>
143
166
  new Promise<AotWorkerResult>((resolveResponse, reject) => {
144
- if (workerFailure) {
145
- reject(workerFailure);
167
+ if (childFailure) {
168
+ reject(childFailure);
146
169
  return;
147
170
  }
148
171
  const id = nextId;
149
172
  nextId += 1;
150
173
  pending.set(id, { reject, resolve: resolveResponse });
151
- worker.postMessage({ ...payload, id } satisfies AotWorkerRequest);
174
+ child.send({ ...payload, id } satisfies AotWorkerRequest, (error) => {
175
+ if (error) {
176
+ fail(error);
177
+ }
178
+ });
152
179
  });
153
- let compiled: string | undefined;
154
- let virtualType: string | undefined;
155
180
  try {
156
- ({ code: compiled, virtualType } = await request({ method: "start" }));
157
- } catch (error) {
158
- await worker.terminate();
159
- const mismatch = registrationMismatch(expected, registrations, false);
181
+ let compiled: string | undefined;
182
+ let virtualType: string | undefined;
183
+ try {
184
+ ({ code: compiled, virtualType } = await request({ method: "start" }));
185
+ } catch (error) {
186
+ await stop();
187
+ const mismatch = registrationMismatch(expected, registrations, false);
188
+ if (mismatch) {
189
+ throw mismatch;
190
+ }
191
+ if (
192
+ error instanceof Error &&
193
+ error.message.startsWith("[elysia-aot]") &&
194
+ error.message.includes("mounts a sub-app")
195
+ ) {
196
+ console.warn("[furin] Elysia AOT skipped because the app uses .mount().");
197
+ return;
198
+ }
199
+ throw error;
200
+ }
201
+ const mismatch = registrationMismatch(expected, registrations, true);
160
202
  if (mismatch) {
161
203
  throw mismatch;
162
204
  }
163
- if (
164
- error instanceof Error &&
165
- error.message.startsWith("[elysia-aot]") &&
166
- error.message.includes("mounts a sub-app")
167
- ) {
168
- console.warn("[furin] Elysia AOT skipped because the app uses .mount().");
169
- return;
205
+ build.onEnd(async () => {
206
+ try {
207
+ await request({ method: "end" });
208
+ } finally {
209
+ await stop();
210
+ }
211
+ });
212
+ const entrySource = await Bun.file(entryPath).text();
213
+ const { code: transformedEntry } = await request({
214
+ code: entrySource,
215
+ method: "transform",
216
+ path: entryPath,
217
+ });
218
+ if (transformedEntry !== undefined) {
219
+ await Bun.write(entryPath, transformedEntry);
170
220
  }
221
+ build.onResolve({ filter: ELYSIA_IMPORT_FILTER }, ({ path }) => ({
222
+ path: Bun.resolveSync(path, ELYSIA_RESOLVE_DIR),
223
+ }));
224
+ build.onResolve({ filter: ELYSIA_VIRTUAL_IMPORT_FILTER }, ({ path }) => {
225
+ if (path === "elysia/type" && virtualType === undefined) {
226
+ return;
227
+ }
228
+ return { namespace: AOT_NAMESPACE, path };
229
+ });
230
+ build.onLoad({ filter: ANY_MODULE_FILTER, namespace: AOT_NAMESPACE }, ({ path }) => {
231
+ const contents = path === "elysia/compiled" ? compiled : virtualType;
232
+ return contents === undefined
233
+ ? undefined
234
+ : { contents, loader: "js", resolveDir: ELYSIA_RESOLVE_DIR };
235
+ });
236
+ build.onLoad({ filter: SOURCE_FILTER }, async ({ path }) => {
237
+ if (resolve(path) === entryPath) {
238
+ return;
239
+ }
240
+ const original = await Bun.file(path).text();
241
+ const { code: transformed } = await request({
242
+ code: original,
243
+ method: "transform",
244
+ path,
245
+ });
246
+ if (transformed === undefined) {
247
+ return;
248
+ }
249
+ return {
250
+ contents: patchElysiaWebSocketStub(transformed),
251
+ loader: loaderFor(path),
252
+ };
253
+ });
254
+ } catch (error) {
255
+ await stop();
171
256
  throw error;
172
257
  }
173
- const mismatch = registrationMismatch(expected, registrations, true);
174
- if (mismatch) {
175
- await worker.terminate();
176
- throw mismatch;
177
- }
178
- build.onEnd(async () => {
179
- try {
180
- await request({ method: "end" });
181
- } finally {
182
- await worker.terminate();
183
- }
184
- });
185
- const entrySource = await Bun.file(entryPath).text();
186
- const { code: transformedEntry } = await request({
187
- code: entrySource,
188
- method: "transform",
189
- path: entryPath,
190
- });
191
- if (transformedEntry !== undefined) {
192
- await Bun.write(entryPath, transformedEntry);
193
- }
194
- build.onResolve({ filter: ELYSIA_IMPORT_FILTER }, ({ path }) => ({
195
- path: Bun.resolveSync(path, ELYSIA_RESOLVE_DIR),
196
- }));
197
- build.onResolve({ filter: ELYSIA_VIRTUAL_IMPORT_FILTER }, ({ path }) => {
198
- if (path === "elysia/type" && virtualType === undefined) {
199
- return;
200
- }
201
- return { namespace: AOT_NAMESPACE, path };
202
- });
203
- build.onLoad({ filter: ANY_MODULE_FILTER, namespace: AOT_NAMESPACE }, ({ path }) => {
204
- const contents = path === "elysia/compiled" ? compiled : virtualType;
205
- return contents === undefined
206
- ? undefined
207
- : { contents, loader: "js", resolveDir: ELYSIA_RESOLVE_DIR };
208
- });
209
- build.onLoad({ filter: SOURCE_FILTER }, async ({ path }) => {
210
- if (resolve(path) === entryPath) {
211
- return;
212
- }
213
- const original = await Bun.file(path).text();
214
- const { code: transformed } = await request({ code: original, method: "transform", path });
215
- if (transformed === undefined) {
216
- return;
217
- }
218
- return {
219
- contents: patchElysiaWebSocketStub(transformed),
220
- loader: loaderFor(path),
221
- };
222
- });
223
258
  },
224
259
  };
225
260
  }
@@ -18,6 +18,7 @@ const _ext = _pkgSrcDir.endsWith("/src") ? ".ts" : ".js";
18
18
  const INTERNAL_MODULE_PATH = `${_pkgSrcDir}/server/internal${_ext}`;
19
19
  const RUNTIME_ENV_MODULE_PATH = `${_pkgSrcDir}/server/runtime-env${_ext}`;
20
20
  const STATIC_EXPORT_MODULE_PATH = `${_pkgSrcDir}/server/static-export${_ext}`;
21
+ const SERVER_ENTRY_MODULE_PATH = `${_pkgSrcDir}/server/server-entry${_ext}`;
21
22
  /** Sidecar holding the SSG documents the production bundle rendered at build time. */
22
23
  export const PRERENDER_SNAPSHOT_FILE = "furin-prerender.json";
23
24
 
@@ -229,6 +230,9 @@ export function buildEntrySource(options: EntryTemplateOptions): string {
229
230
  const lines = [
230
231
  headerComment,
231
232
  `import { __setCompileContext } from ${JSON.stringify(internalSpecifier)};`,
233
+ ...(serverEntry && mode === "app"
234
+ ? [`import { loadServerEntry } from ${JSON.stringify(SERVER_ENTRY_MODULE_PATH)};`]
235
+ : []),
232
236
  ...(productionMode
233
237
  ? [`import { __setDevMode } from ${JSON.stringify(RUNTIME_ENV_MODULE_PATH)};`]
234
238
  : []),
@@ -268,11 +272,12 @@ export function buildEntrySource(options: EntryTemplateOptions): string {
268
272
  ]
269
273
  : serverEntry && mode === "app"
270
274
  ? [
271
- `const __serverModule = await import(${JSON.stringify(serverEntry.replace(/\\/g, "/"))});`,
275
+ `const __serverModule = await loadServerEntry(() => import(${JSON.stringify(serverEntry.replace(/\\/g, "/"))}));`,
272
276
  "export const app = __serverModule.default;",
273
277
  "export const port = __serverModule.port;",
274
278
  "export const idleTimeout = __serverModule.idleTimeout;",
275
279
  "export const startServer = __serverModule.startServer;",
280
+ "export const onStartup = __serverModule.onStartup;",
276
281
  "export const onShutdown = __serverModule.onShutdown;",
277
282
  "export default __serverModule.default;",
278
283
  `export { collectPrerenders as __furinPrerender } from ${JSON.stringify(INTERNAL_MODULE_PATH)};`,
@@ -5,9 +5,8 @@ import {
5
5
  buildRouteRegex,
6
6
  compareRouteSpecificity,
7
7
  } from "../server/router/patterns.ts";
8
- import { mergeRouteSchemas } from "../server/router/schema-merge.ts";
9
8
  import type { ResolvedRoute } from "../server/router/types.ts";
10
- import { collectSearchDefaults } from "../shared/search-params.ts";
9
+ import { type BuildRouteInput, routeBuildInfo } from "./route-metadata.ts";
11
10
  import type { ClientBoundary } from "../rsc/build/discover.ts";
12
11
  import { CLIENT_REFERENCE_RUNTIME_PATH } from "../rsc/build/paths.ts";
13
12
  import { writeRouteTypes } from "./route-types";
@@ -43,7 +42,7 @@ export function generateClientReferenceEntry(boundaries: readonly ClientBoundary
43
42
  * navigation uses the correct physical URLs.
44
43
  */
45
44
  export function generateHydrateEntry(
46
- routes: ResolvedRoute[],
45
+ routes: BuildRouteInput[],
47
46
  rootLayout: string,
48
47
  basePath: string,
49
48
  clientLogging: boolean
@@ -58,7 +57,7 @@ export function generateHydrateEntry(
58
57
  * shipping absolute build paths to browsers.
59
58
  */
60
59
  export function generateProductionHydrateEntry(
61
- routes: ResolvedRoute[],
60
+ routes: BuildRouteInput[],
62
61
  rootLayout: string,
63
62
  basePath: string,
64
63
  clientLogging: boolean
@@ -69,7 +68,7 @@ export function generateProductionHydrateEntry(
69
68
  }
70
69
 
71
70
  function hydrateEntry(
72
- routes: ResolvedRoute[],
71
+ routes: BuildRouteInput[],
73
72
  rootLayout: string,
74
73
  basePath: string,
75
74
  clientLogging: boolean,
@@ -99,9 +98,7 @@ function hydrateEntry(
99
98
  for (const route of clientRoutes) {
100
99
  const resolvedPage = route.path.replace(/\\/g, "/");
101
100
  const regexPattern = buildRouteRegex(route.pattern).regex.source;
102
- const searchDefaults = collectSearchDefaults(
103
- mergeRouteSchemas(route.routeChain ?? [], "query")
104
- );
101
+ const searchDefaults = routeBuildInfo(route).searchDefaults;
105
102
  const boundaryIdents = new Map<string, string>();
106
103
  const layoutPaths = (route.routeChain ?? [])
107
104
  .slice(1)
@@ -209,6 +206,12 @@ const __furinBasePath = ${basePathLiteral};
209
206
  ${loggerSetup}
210
207
 
211
208
  if (import.meta.hot) {
209
+ import.meta.hot.on("bun:beforeUpdate", () => {
210
+ window.dispatchEvent(new Event("furin:hmr-before-update"));
211
+ });
212
+ import.meta.hot.on("bun:afterUpdate", () => {
213
+ window.dispatchEvent(new Event("furin:hmr-after-update"));
214
+ });
212
215
  const connectionState = ((window as unknown as {
213
216
  __FURIN_HMR_CONNECTION__?: { disconnected: boolean; installed: boolean };
214
217
  }).__FURIN_HMR_CONNECTION__ ??= { disconnected: false, installed: false });