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

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 (98) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +37 -33
  3. package/dist/adapter/bun.d.ts +17 -1
  4. package/dist/adapter/package.d.ts +26 -0
  5. package/dist/build/client.d.ts +1 -1
  6. package/dist/build/compile-entry.d.ts +3 -3
  7. package/dist/build/compile-entry.ts +114 -109
  8. package/dist/build/entry-template.d.ts +35 -9
  9. package/dist/build/entry-template.ts +206 -156
  10. package/dist/build/hydrate.d.ts +1 -1
  11. package/dist/build/index.js +643 -247
  12. package/dist/build/scan-server.d.ts +10 -4
  13. package/dist/build/server-routes-entry.d.ts +3 -3
  14. package/dist/build/server-routes-entry.ts +30 -36
  15. package/dist/build/ssg-cache.d.ts +1 -1
  16. package/dist/build/types.d.ts +36 -1
  17. package/dist/cli/config.d.ts +6 -1
  18. package/dist/cli/index.js +662 -260
  19. package/dist/client/link.js +163 -16
  20. package/dist/client/router/abort.d.ts +1 -0
  21. package/dist/client/router/sync-catch-up.d.ts +29 -0
  22. package/dist/config.d.ts +11 -2
  23. package/dist/config.js +5 -1
  24. package/dist/furin.d.ts +37 -19
  25. package/dist/furin.js +982 -378
  26. package/dist/server/auto-invalidate/registry.d.ts +8 -1
  27. package/dist/server/cache/dev-loader.d.ts +3 -2
  28. package/dist/server/cache/invalidation.d.ts +19 -0
  29. package/dist/server/cache/isr.d.ts +6 -2
  30. package/dist/server/cache/registry.d.ts +3 -3
  31. package/dist/server/cache/ssg.d.ts +6 -2
  32. package/dist/server/cache/store-view.d.ts +11 -0
  33. package/dist/server/instance.d.ts +86 -0
  34. package/dist/server/internal.d.ts +16 -1
  35. package/dist/server/internal.js +72 -5
  36. package/dist/server/render/template.d.ts +3 -2
  37. package/dist/server/sync/adapter.d.ts +62 -0
  38. package/dist/server/sync/config.d.ts +11 -0
  39. package/dist/server/sync/fingerprint.d.ts +6 -0
  40. package/dist/server/sync/index.d.ts +2 -2
  41. package/dist/server/sync/memory-adapter.d.ts +17 -0
  42. package/dist/server/sync/plugin.d.ts +12 -195
  43. package/dist/server/sync/response.d.ts +4 -0
  44. package/dist/server/sync/stream.d.ts +24 -5
  45. package/dist/shared/prefix.d.ts +15 -0
  46. package/package.json +6 -1
  47. package/src/adapter/README.md +13 -13
  48. package/src/adapter/bun.ts +113 -50
  49. package/src/adapter/package.ts +206 -0
  50. package/src/build/client.ts +158 -152
  51. package/src/build/compile-entry.ts +114 -109
  52. package/src/build/entry-template.ts +206 -156
  53. package/src/build/hydrate.ts +342 -340
  54. package/src/build/index.ts +223 -152
  55. package/src/build/route-types.ts +145 -145
  56. package/src/build/scan-server.ts +111 -95
  57. package/src/build/server-routes-entry.ts +30 -36
  58. package/src/build/shared.ts +80 -80
  59. package/src/build/ssg-cache.ts +36 -32
  60. package/src/build/types.ts +125 -89
  61. package/src/cli/config.ts +9 -3
  62. package/src/cli/index.ts +21 -3
  63. package/src/client/router/abort.ts +5 -0
  64. package/src/client/router/link-utils.ts +184 -184
  65. package/src/client/router/provider.tsx +883 -804
  66. package/src/client/router/sync-catch-up.ts +113 -0
  67. package/src/client/router/types.ts +276 -276
  68. package/src/client/sync.ts +98 -98
  69. package/src/client.ts +369 -369
  70. package/src/config.ts +14 -1
  71. package/src/furin.ts +619 -465
  72. package/src/server/auto-invalidate/registry.ts +23 -1
  73. package/src/server/auto-invalidate/runtime.ts +159 -134
  74. package/src/server/cache/dev-loader.ts +77 -38
  75. package/src/server/cache/invalidation.ts +71 -30
  76. package/src/server/cache/isr.ts +20 -5
  77. package/src/server/cache/registry.ts +17 -20
  78. package/src/server/cache/ssg.ts +19 -4
  79. package/src/server/cache/store-view.ts +30 -0
  80. package/src/server/dev-page-plugin.ts +454 -454
  81. package/src/server/instance.ts +252 -0
  82. package/src/server/internal.ts +100 -5
  83. package/src/server/render/assemble.ts +160 -160
  84. package/src/server/render/isr.ts +323 -323
  85. package/src/server/render/not-found.ts +9 -3
  86. package/src/server/render/ssr.ts +603 -585
  87. package/src/server/render/template.ts +57 -24
  88. package/src/server/router/plugin.ts +384 -384
  89. package/src/server/sync/adapter.ts +65 -0
  90. package/src/server/sync/config.ts +60 -29
  91. package/src/server/sync/fingerprint.ts +44 -0
  92. package/src/server/sync/index.ts +15 -14
  93. package/src/server/sync/memory-adapter.ts +196 -0
  94. package/src/server/sync/plugin.ts +199 -108
  95. package/src/server/sync/response.ts +77 -0
  96. package/src/server/sync/stream.ts +162 -144
  97. package/src/shared/deferred-ndjson.ts +7 -0
  98. package/src/shared/prefix.ts +38 -0
@@ -1,9 +1,10 @@
1
- import { type AfterHandler, Elysia } from "elysia";
1
+ import { Elysia } from "elysia";
2
2
  import type { InvalidationInput } from "../auto-invalidate/types.ts";
3
- export type SyncInput = InvalidationInput | {
3
+ export type SyncRouteOption = false | InvalidationInput | {
4
4
  invalidate: InvalidationInput;
5
5
  };
6
- type AnyHandlerContext = Parameters<AfterHandler>[0];
6
+ /** @deprecated Use SyncRouteOption. */
7
+ export type SyncInput = Exclude<SyncRouteOption, false>;
7
8
  export declare function furinSync(): Elysia<"", {
8
9
  decorator: {};
9
10
  store: {};
@@ -16,11 +17,11 @@ export declare function furinSync(): Elysia<"", {
16
17
  schema: {};
17
18
  standaloneSchema: {};
18
19
  macro: Partial<{
19
- readonly sync: SyncInput;
20
+ readonly sync: SyncRouteOption;
20
21
  }>;
21
22
  macroFn: {
22
- readonly sync: (input: SyncInput) => {
23
- readonly beforeHandle: (ctx: {
23
+ readonly sync: (input: SyncRouteOption) => {
24
+ readonly transform: ({ request }: {
24
25
  body: unknown;
25
26
  query: Record<string, string>;
26
27
  params: {};
@@ -38,7 +39,7 @@ export declare function furinSync(): Elysia<"", {
38
39
  route: string;
39
40
  request: Request;
40
41
  store: {};
41
- status: <const Code extends number | keyof import("elysia").StatusMap, const T = Code extends 301 | 302 | 303 | 307 | 308 | 200 | 300 | 404 | 500 | 304 | 400 | 422 | 100 | 428 | 409 | 101 | 102 | 103 | 201 | 202 | 203 | 204 | 205 | 206 | 207 | 208 | 401 | 402 | 403 | 405 | 406 | 407 | 408 | 410 | 411 | 412 | 413 | 414 | 415 | 416 | 417 | 418 | 420 | 421 | 423 | 424 | 425 | 426 | 429 | 431 | 451 | 501 | 502 | 503 | 504 | 505 | 506 | 507 | 508 | 510 | 511 ? {
42
+ status: <const Code extends number | keyof import("elysia").StatusMap, const T = Code extends 301 | 302 | 303 | 307 | 308 | 200 | 300 | 404 | 500 | 304 | 400 | 422 | 100 | 101 | 102 | 103 | 201 | 202 | 203 | 204 | 205 | 206 | 207 | 208 | 401 | 402 | 403 | 405 | 406 | 407 | 408 | 409 | 410 | 411 | 412 | 413 | 414 | 415 | 416 | 417 | 418 | 420 | 421 | 423 | 424 | 425 | 426 | 428 | 429 | 431 | 451 | 501 | 502 | 503 | 504 | 505 | 506 | 507 | 508 | 510 | 511 ? {
42
43
  readonly 100: "Continue";
43
44
  readonly 101: "Switching Protocols";
44
45
  readonly 102: "Processing";
@@ -163,196 +164,13 @@ export declare function furinSync(): Elysia<"", {
163
164
  readonly "Not Extended": 510;
164
165
  readonly "Network Authentication Required": 511;
165
166
  }[Code] : Code>;
166
- }) => Response | undefined;
167
- readonly afterHandle: (ctx: AnyHandlerContext) => void;
168
- readonly error: ({ request }: {
169
- body: unknown;
170
- query: Record<string, string | undefined>;
171
- params: {};
172
- headers: Record<string, string | undefined>;
173
- cookie: Record<string, import("elysia").Cookie<string | undefined>>;
174
- server: import("elysia/universal/server").Server | null;
175
- redirect: import("elysia").redirect;
176
- set: {
177
- headers: import("elysia").HTTPHeaders;
178
- status?: number | keyof import("elysia").StatusMap;
179
- redirect?: string;
180
- cookie?: Record<string, import("elysia/cookies").ElysiaCookie>;
181
- };
182
- status: <const Code extends number | keyof import("elysia").StatusMap, const T = Code extends 301 | 302 | 303 | 307 | 308 | 200 | 300 | 404 | 500 | 304 | 400 | 422 | 100 | 428 | 409 | 101 | 102 | 103 | 201 | 202 | 203 | 204 | 205 | 206 | 207 | 208 | 401 | 402 | 403 | 405 | 406 | 407 | 408 | 410 | 411 | 412 | 413 | 414 | 415 | 416 | 417 | 418 | 420 | 421 | 423 | 424 | 425 | 426 | 429 | 431 | 451 | 501 | 502 | 503 | 504 | 505 | 506 | 507 | 508 | 510 | 511 ? {
183
- readonly 100: "Continue";
184
- readonly 101: "Switching Protocols";
185
- readonly 102: "Processing";
186
- readonly 103: "Early Hints";
187
- readonly 200: "OK";
188
- readonly 201: "Created";
189
- readonly 202: "Accepted";
190
- readonly 203: "Non-Authoritative Information";
191
- readonly 204: "No Content";
192
- readonly 205: "Reset Content";
193
- readonly 206: "Partial Content";
194
- readonly 207: "Multi-Status";
195
- readonly 208: "Already Reported";
196
- readonly 300: "Multiple Choices";
197
- readonly 301: "Moved Permanently";
198
- readonly 302: "Found";
199
- readonly 303: "See Other";
200
- readonly 304: "Not Modified";
201
- readonly 307: "Temporary Redirect";
202
- readonly 308: "Permanent Redirect";
203
- readonly 400: "Bad Request";
204
- readonly 401: "Unauthorized";
205
- readonly 402: "Payment Required";
206
- readonly 403: "Forbidden";
207
- readonly 404: "Not Found";
208
- readonly 405: "Method Not Allowed";
209
- readonly 406: "Not Acceptable";
210
- readonly 407: "Proxy Authentication Required";
211
- readonly 408: "Request Timeout";
212
- readonly 409: "Conflict";
213
- readonly 410: "Gone";
214
- readonly 411: "Length Required";
215
- readonly 412: "Precondition Failed";
216
- readonly 413: "Payload Too Large";
217
- readonly 414: "URI Too Long";
218
- readonly 415: "Unsupported Media Type";
219
- readonly 416: "Range Not Satisfiable";
220
- readonly 417: "Expectation Failed";
221
- readonly 418: "I'm a teapot";
222
- readonly 420: "Enhance Your Calm";
223
- readonly 421: "Misdirected Request";
224
- readonly 422: "Unprocessable Content";
225
- readonly 423: "Locked";
226
- readonly 424: "Failed Dependency";
227
- readonly 425: "Too Early";
228
- readonly 426: "Upgrade Required";
229
- readonly 428: "Precondition Required";
230
- readonly 429: "Too Many Requests";
231
- readonly 431: "Request Header Fields Too Large";
232
- readonly 451: "Unavailable For Legal Reasons";
233
- readonly 500: "Internal Server Error";
234
- readonly 501: "Not Implemented";
235
- readonly 502: "Bad Gateway";
236
- readonly 503: "Service Unavailable";
237
- readonly 504: "Gateway Timeout";
238
- readonly 505: "HTTP Version Not Supported";
239
- readonly 506: "Variant Also Negotiates";
240
- readonly 507: "Insufficient Storage";
241
- readonly 508: "Loop Detected";
242
- readonly 510: "Not Extended";
243
- readonly 511: "Network Authentication Required";
244
- }[Code] : Code>(code: Code, response?: T) => import("elysia").ElysiaCustomStatusResponse<Code, T, Code extends "Continue" | "Switching Protocols" | "Processing" | "Early Hints" | "OK" | "Created" | "Accepted" | "Non-Authoritative Information" | "No Content" | "Reset Content" | "Partial Content" | "Multi-Status" | "Already Reported" | "Multiple Choices" | "Moved Permanently" | "Found" | "See Other" | "Not Modified" | "Temporary Redirect" | "Permanent Redirect" | "Bad Request" | "Unauthorized" | "Payment Required" | "Forbidden" | "Not Found" | "Method Not Allowed" | "Not Acceptable" | "Proxy Authentication Required" | "Request Timeout" | "Conflict" | "Gone" | "Length Required" | "Precondition Failed" | "Payload Too Large" | "URI Too Long" | "Unsupported Media Type" | "Range Not Satisfiable" | "Expectation Failed" | "I'm a teapot" | "Enhance Your Calm" | "Misdirected Request" | "Unprocessable Content" | "Locked" | "Failed Dependency" | "Too Early" | "Upgrade Required" | "Precondition Required" | "Too Many Requests" | "Request Header Fields Too Large" | "Unavailable For Legal Reasons" | "Internal Server Error" | "Not Implemented" | "Bad Gateway" | "Service Unavailable" | "Gateway Timeout" | "HTTP Version Not Supported" | "Variant Also Negotiates" | "Insufficient Storage" | "Loop Detected" | "Not Extended" | "Network Authentication Required" ? {
245
- readonly Continue: 100;
246
- readonly "Switching Protocols": 101;
247
- readonly Processing: 102;
248
- readonly "Early Hints": 103;
249
- readonly OK: 200;
250
- readonly Created: 201;
251
- readonly Accepted: 202;
252
- readonly "Non-Authoritative Information": 203;
253
- readonly "No Content": 204;
254
- readonly "Reset Content": 205;
255
- readonly "Partial Content": 206;
256
- readonly "Multi-Status": 207;
257
- readonly "Already Reported": 208;
258
- readonly "Multiple Choices": 300;
259
- readonly "Moved Permanently": 301;
260
- readonly Found: 302;
261
- readonly "See Other": 303;
262
- readonly "Not Modified": 304;
263
- readonly "Temporary Redirect": 307;
264
- readonly "Permanent Redirect": 308;
265
- readonly "Bad Request": 400;
266
- readonly Unauthorized: 401;
267
- readonly "Payment Required": 402;
268
- readonly Forbidden: 403;
269
- readonly "Not Found": 404;
270
- readonly "Method Not Allowed": 405;
271
- readonly "Not Acceptable": 406;
272
- readonly "Proxy Authentication Required": 407;
273
- readonly "Request Timeout": 408;
274
- readonly Conflict: 409;
275
- readonly Gone: 410;
276
- readonly "Length Required": 411;
277
- readonly "Precondition Failed": 412;
278
- readonly "Payload Too Large": 413;
279
- readonly "URI Too Long": 414;
280
- readonly "Unsupported Media Type": 415;
281
- readonly "Range Not Satisfiable": 416;
282
- readonly "Expectation Failed": 417;
283
- readonly "I'm a teapot": 418;
284
- readonly "Enhance Your Calm": 420;
285
- readonly "Misdirected Request": 421;
286
- readonly "Unprocessable Content": 422;
287
- readonly Locked: 423;
288
- readonly "Failed Dependency": 424;
289
- readonly "Too Early": 425;
290
- readonly "Upgrade Required": 426;
291
- readonly "Precondition Required": 428;
292
- readonly "Too Many Requests": 429;
293
- readonly "Request Header Fields Too Large": 431;
294
- readonly "Unavailable For Legal Reasons": 451;
295
- readonly "Internal Server Error": 500;
296
- readonly "Not Implemented": 501;
297
- readonly "Bad Gateway": 502;
298
- readonly "Service Unavailable": 503;
299
- readonly "Gateway Timeout": 504;
300
- readonly "HTTP Version Not Supported": 505;
301
- readonly "Variant Also Negotiates": 506;
302
- readonly "Insufficient Storage": 507;
303
- readonly "Loop Detected": 508;
304
- readonly "Not Extended": 510;
305
- readonly "Network Authentication Required": 511;
306
- }[Code] : Code>;
307
- path: string;
308
- route: string;
309
- request: Request;
310
- store: {};
311
- } & ({
312
- request: Request;
313
- code: "UNKNOWN";
314
- error: Readonly<Error>;
315
- set: import("elysia").Context["set"];
316
- } | {
317
- request: Request;
318
- code: "VALIDATION";
319
- error: Readonly<import("elysia").ValidationError>;
320
- set: import("elysia").Context["set"];
321
- } | {
322
- request: Request;
323
- code: "NOT_FOUND";
324
- error: Readonly<import("elysia").NotFoundError>;
325
- set: import("elysia").Context["set"];
326
- } | {
327
- request: Request;
328
- code: "PARSE";
329
- error: Readonly<import("elysia").ParseError>;
330
- set: import("elysia").Context["set"];
331
- } | {
332
- request: Request;
333
- code: "INTERNAL_SERVER_ERROR";
334
- error: Readonly<import("elysia").InternalServerError>;
335
- set: import("elysia").Context["set"];
336
- } | {
337
- request: Request;
338
- code: "INVALID_COOKIE_SIGNATURE";
339
- error: Readonly<import("elysia").InvalidCookieSignature>;
340
- set: import("elysia").Context["set"];
341
- } | {
342
- request: Request;
343
- code: "INVALID_FILE_TYPE";
344
- error: Readonly<import("elysia").InvalidFileType>;
345
- set: import("elysia").Context["set"];
346
- } | {
347
- request: Request;
348
- code: number;
349
- error: Readonly<import("elysia").ElysiaCustomStatusResponse<number>>;
350
- set: import("elysia").Context["set"];
351
- })) => void;
167
+ }) => void;
352
168
  };
353
169
  };
354
170
  parser: {};
355
- response: {};
171
+ response: {
172
+ 200: Response;
173
+ };
356
174
  }, {}, {
357
175
  derive: {};
358
176
  resolve: {};
@@ -366,4 +184,3 @@ export declare function furinSync(): Elysia<"", {
366
184
  standaloneSchema: {};
367
185
  response: {};
368
186
  }>;
369
- export {};
@@ -0,0 +1,4 @@
1
+ import { type Context } from "elysia";
2
+ import type { StoredResponse } from "./adapter.ts";
3
+ export declare function storeResponse(responseValue: unknown, set: Context["set"]): Promise<StoredResponse>;
4
+ export declare function replayResponse(stored: StoredResponse): Response;
@@ -1,9 +1,14 @@
1
1
  import { Elysia } from "elysia";
2
- export interface SyncInvalidationEvent {
3
- invalidations: readonly string[];
4
- }
2
+ export type { ChangePage as SyncChangePage, SyncChange } from "./adapter.ts";
5
3
  export declare function publishSyncInvalidation(invalidations: readonly string[]): void;
6
- export declare function createSyncStreamPlugin(path?: string): Elysia<"", {
4
+ /**
5
+ * Builds the SSE plugin serving one instance's sync stream. Routes are
6
+ * registered at the logical `path` (the parent instance's Elysia prefix makes
7
+ * them physical); `channel` is the adapter key the stream reads from — pass
8
+ * the PHYSICAL path (`prefix + path`) so two mounted apps never share a
9
+ * cursor sequence.
10
+ */
11
+ export declare function createSyncStreamPlugin(path?: string, channel?: string): Elysia<"", {
7
12
  decorator: {};
8
13
  store: {};
9
14
  derive: {};
@@ -19,6 +24,20 @@ export declare function createSyncStreamPlugin(path?: string): Elysia<"", {
19
24
  parser: {};
20
25
  response: {};
21
26
  }, {
27
+ [x: string]: {
28
+ changes: {
29
+ get: {
30
+ body: unknown;
31
+ params: {};
32
+ query: unknown;
33
+ headers: unknown;
34
+ response: {
35
+ 200: Response | import("./adapter.ts").ChangePage;
36
+ };
37
+ };
38
+ };
39
+ };
40
+ } & {
22
41
  [x: string]: {
23
42
  get: {
24
43
  body: unknown;
@@ -43,5 +62,5 @@ export declare function createSyncStreamPlugin(path?: string): Elysia<"", {
43
62
  standaloneSchema: {};
44
63
  response: {};
45
64
  }>;
46
- /** @internal — resets process-local stream subscribers between tests. */
65
+ /** @internal — resets process-local sync state between tests. */
47
66
  export declare function __resetSyncState(): void;
@@ -0,0 +1,15 @@
1
+ /**
2
+ * On-disk client dir name for a mounted app: the root instance keeps the
3
+ * historical `client/`, prefixed instances get `client-<slug>/` next to it.
4
+ */
5
+ export declare function clientDirNameForPrefix(prefix: string): string;
6
+ /** Filesystem-safe slug for a mount prefix (`/admin/v2` → `admin-v2`). */
7
+ export declare function prefixSlug(prefix: string): string;
8
+ /**
9
+ * `prefixSlug` is NOT injective: `/a-b` and `/a/b` both slug to `a-b`, so two
10
+ * distinct prefixes can claim the same client dir and silently overwrite each
11
+ * other's build output. A readable injective encoding is ambiguous anyway
12
+ * (escaping `-` as `--` still confuses `/a-/b` with `/a/-b`), so we detect the
13
+ * collision and fail fast instead.
14
+ */
15
+ export declare function assertNoPrefixSlugCollisions(prefixes: string[]): void;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@teyik0/furin",
3
- "version": "0.2.0-alpha.3",
3
+ "version": "0.2.0-alpha.5",
4
4
  "description": "React meta-framework powered by Elysia and Bun with file-based routing, SSR, SSG, and ISR.",
5
5
  "license": "MIT",
6
6
  "author": "teyik0",
@@ -84,6 +84,11 @@
84
84
  "./env": {
85
85
  "types": "./dist/env.d.ts",
86
86
  "bun": "./src/env.d.ts"
87
+ },
88
+ "./internal": {
89
+ "types": "./dist/server/internal.d.ts",
90
+ "bun": "./src/server/internal.ts",
91
+ "import": "./dist/server/internal.js"
87
92
  }
88
93
  },
89
94
  "scripts": {
@@ -1,13 +1,13 @@
1
- ## Bun adapter
2
-
3
- Goal is having 3 modes:
4
-
5
- - generate server.js + client/
6
- - generate server (compiled to binary) + client/
7
- - generate server (compiled to binary with client/ [embeded](https://bun.com/docs/bundler/executables.md))
8
-
9
- All should be portable.
10
-
11
- ## Cloudflare adapter
12
-
13
- ## Vercel adapter
1
+ ## Bun adapter
2
+
3
+ Goal is having 3 modes:
4
+
5
+ - generate server.js + client/
6
+ - generate server (compiled to binary) + client/
7
+ - generate server (compiled to binary with client/ [embeded](https://bun.com/docs/bundler/executables.md))
8
+
9
+ All should be portable.
10
+
11
+ ## Cloudflare adapter
12
+
13
+ ## Vercel adapter
@@ -3,14 +3,17 @@ import { dirname, join, resolve } from "node:path";
3
3
  import { fileURLToPath } from "node:url";
4
4
  import { buildClient } from "../build/client.ts";
5
5
  import { generateCompileEntry } from "../build/compile-entry.ts";
6
+ import type { BuildEntryOptions, EntryAppContext } from "../build/entry-template.ts";
6
7
  import { generateServerRoutesEntry } from "../build/server-routes-entry.ts";
7
8
  import { buildTargetManifest, copyDirRecursive, ensureDir, toPosixPath } from "../build/shared.ts";
8
9
  import { buildSSGCacheSnapshot } from "../build/ssg-cache.ts";
9
10
  import type { BuildAppOptions, TargetBuildManifest } from "../build/types.ts";
10
11
  import type { BuildTarget } from "../config.ts";
12
+ import { ssgRouteCache } from "../server/cache/ssg.ts";
11
13
  import { generateProdIndexHtml } from "../server/render/shell.ts";
12
14
  import { setProductionTemplateContent } from "../server/render/template.ts";
13
15
  import type { ResolvedRoute, RootLayout } from "../server/router/index.ts";
16
+ import { clientDirNameForPrefix } from "../shared/prefix.ts";
14
17
 
15
18
  // import.meta.resolve() runs at runtime (not inlined at bundle time), resolves
16
19
  // through package exports, and is the Web-standard API. The main entry is
@@ -35,7 +38,15 @@ const BUILD_ID_INPUT_PATHS = [
35
38
  `${_pkgSrcDir}/server/router/index${_ext}`,
36
39
  ];
37
40
 
38
- async function createBuildFingerprint(
41
+ /**
42
+ * Deterministic build-ID input covering everything that can change rendered
43
+ * output: client chunks, route shape, route/root/error/not-found source
44
+ * contents and the framework's own render pipeline sources. Shared with the
45
+ * package target so packaged apps get the same stale-deploy detection —
46
+ * SSR-only changes (loader/page code that never reaches the client bundle)
47
+ * must still produce a new build ID.
48
+ */
49
+ export async function createBuildFingerprint(
39
50
  entryChunk: string,
40
51
  cssChunks: string[],
41
52
  routes: ResolvedRoute[],
@@ -99,8 +110,7 @@ function buildCompileMetadata(root: RootLayout, routes: ResolvedRoute[]) {
99
110
  }
100
111
  : undefined;
101
112
 
102
- const routeMetadata: NonNullable<Parameters<typeof generateCompileEntry>[0]["routeMetadata"]> =
103
- {};
113
+ const routeMetadata: NonNullable<EntryAppContext["routeMetadata"]> = {};
104
114
  for (const route of routes) {
105
115
  routeMetadata[toPosixPath(route.path)] = {
106
116
  segmentBoundaries: route.segmentBoundaries.map((b) => ({
@@ -115,82 +125,135 @@ function buildCompileMetadata(root: RootLayout, routes: ResolvedRoute[]) {
115
125
  return { rootConventions, routeMetadata };
116
126
  }
117
127
 
118
- export async function buildBunTarget(
119
- routes: ResolvedRoute[],
120
- rootDir: string,
121
- buildRoot: string,
122
- root: RootLayout,
128
+ /** One mounted app's build input (root + routes scanned from its pagesDir). */
129
+ export interface BunTargetApp {
130
+ pagesDir: string;
131
+ prefix: string;
132
+ root: RootLayout;
133
+ routes: ResolvedRoute[];
134
+ }
135
+
136
+ /** Builds one app's client bundle + compile context payload for the entry. */
137
+ async function buildOneApp(
138
+ app: BunTargetApp,
139
+ targetDir: string,
123
140
  serverEntry: string | null,
124
141
  options: BuildAppOptions
125
- ): Promise<TargetBuildManifest> {
126
- if (options.compile && !serverEntry) {
127
- throw new Error(
128
- `[furin] \`compile: "${options.compile}"\` requires a server entry point. ` +
129
- "Create src/server.ts or set `serverEntry` in your furin.config.ts."
130
- );
131
- }
132
-
133
- const target = "bun" satisfies BuildTarget;
134
- const targetManifest = buildTargetManifest(rootDir, buildRoot, target, serverEntry);
135
- const targetDir = resolve(rootDir, targetManifest.targetDir);
136
-
137
- rmSync(targetDir, { force: true, recursive: true });
138
- ensureDir(targetDir);
142
+ ): Promise<{
143
+ buildId: string;
144
+ entryApp: BuildEntryOptions["apps"][number];
145
+ hydrateIntermediate: string;
146
+ }> {
147
+ const { prefix, root, routes } = app;
148
+ const clientDirName = clientDirNameForPrefix(prefix);
149
+ const label = prefix === "" ? "root app" : `app "${prefix}"`;
139
150
 
140
151
  const { entryChunk, cssChunks } = await buildClient(routes, {
141
152
  outDir: targetDir,
142
153
  rootLayout: root.path,
143
154
  plugins: options.plugins,
144
- publicPath: "/_client/",
145
- basePath: "",
155
+ publicPath: `${prefix}/_client/`,
156
+ basePath: prefix,
146
157
  clientLogging: options.clientLogging ?? false,
158
+ clientDirName,
147
159
  });
148
160
 
149
161
  const buildFingerprint = await createBuildFingerprint(
150
- entryChunk,
162
+ `${prefix}\n${entryChunk}`,
151
163
  cssChunks,
152
164
  routes,
153
165
  root,
154
166
  serverEntry
155
167
  );
156
168
  const buildId = Bun.hash(buildFingerprint).toString(16).slice(0, 12);
157
- targetManifest.buildId = buildId;
158
169
 
159
170
  // Write index.html with the buildId meta tag injected so the client can
160
171
  // detect stale deploys via X-Furin-Build-ID header comparison.
161
- const clientDir = join(targetDir, "client");
172
+ const clientDir = join(targetDir, clientDirName);
162
173
  const indexHtml = generateProdIndexHtml(entryChunk, cssChunks, buildId, undefined, false);
163
174
  writeFileSync(join(clientDir, "index.html"), indexHtml);
164
- setProductionTemplateContent(indexHtml);
165
175
 
166
- const routeManifest = routes.map((r) => ({ pattern: r.pattern, path: r.path, mode: r.mode }));
176
+ // The SSG snapshot renders through the (build-time) default state bucket:
177
+ // install this app's template, then clear the bucket's html caches so the
178
+ // previous app's prerenders can never leak into this snapshot. The mount
179
+ // prefix is passed explicitly — no instance scope exists at build time.
180
+ setProductionTemplateContent(indexHtml);
181
+ ssgRouteCache().clear();
167
182
  const ssgCache = serverEntry
168
- ? await buildSSGCacheSnapshot(routes, root, "http://localhost")
183
+ ? await buildSSGCacheSnapshot(routes, root, "http://localhost", prefix)
169
184
  : undefined;
185
+
186
+ const { rootConventions, routeMetadata } = buildCompileMetadata(root, routes);
187
+ console.log(`[furin] Built ${label} (buildId ${buildId})`);
188
+
189
+ return {
190
+ buildId,
191
+ entryApp: {
192
+ buildId,
193
+ prefix,
194
+ rootPath: root.path,
195
+ routes: routes.map((r) => ({ pattern: r.pattern, path: r.path, mode: r.mode })),
196
+ rootConventions,
197
+ routeMetadata,
198
+ ssgCache,
199
+ embed: options.compile === "embed" ? { clientDir } : undefined,
200
+ },
201
+ hydrateIntermediate:
202
+ clientDirName === "client" ? "_hydrate.tsx" : `_hydrate-${clientDirName}.tsx`,
203
+ };
204
+ }
205
+
206
+ export async function buildBunTarget(
207
+ apps: BunTargetApp[],
208
+ rootDir: string,
209
+ buildRoot: string,
210
+ serverEntry: string | null,
211
+ options: BuildAppOptions
212
+ ): Promise<TargetBuildManifest> {
213
+ if (options.compile && !serverEntry) {
214
+ throw new Error(
215
+ `[furin] \`compile: "${options.compile}"\` requires a server entry point. ` +
216
+ "Create src/server.ts or set `serverEntry` in your furin.config.ts."
217
+ );
218
+ }
219
+ if (apps.length === 0) {
220
+ throw new Error("[furin] buildBunTarget requires at least one app.");
221
+ }
222
+
223
+ const target = "bun" satisfies BuildTarget;
224
+ const targetManifest = buildTargetManifest(rootDir, buildRoot, target, serverEntry);
225
+ const targetDir = resolve(rootDir, targetManifest.targetDir);
226
+
227
+ rmSync(targetDir, { force: true, recursive: true });
228
+ ensureDir(targetDir);
229
+
170
230
  const publicDir = existsSync(join(rootDir, "public")) ? join(rootDir, "public") : undefined;
171
- const targetPublicDir = publicDir ? join(targetDir, "public") : undefined;
231
+ const entryApps: BuildEntryOptions["apps"] = [];
232
+ const hydrateIntermediates: string[] = [];
172
233
 
234
+ for (const app of apps) {
235
+ const built = await buildOneApp(app, targetDir, serverEntry, options);
236
+ entryApps.push(built.entryApp);
237
+ hydrateIntermediates.push(built.hydrateIntermediate);
238
+ // The ROOT app's buildId is the manifest's headline id (back-compat).
239
+ if (app.prefix === "" || targetManifest.buildId === "") {
240
+ targetManifest.buildId = built.buildId;
241
+ }
242
+ }
243
+
244
+ const targetPublicDir = publicDir ? join(targetDir, "public") : undefined;
173
245
  if (publicDir && targetPublicDir && options.compile !== "embed") {
174
246
  copyDirRecursive(publicDir, targetPublicDir);
175
247
  }
176
248
 
177
- const { rootConventions, routeMetadata } = buildCompileMetadata(root, routes);
178
-
179
249
  if (options.compile && serverEntry) {
180
- const clientDir = join(targetDir, "client");
181
250
  const outfile = join(targetDir, "server");
182
251
 
183
252
  const entryPath = generateCompileEntry({
184
- buildId,
185
- rootPath: root.path,
186
- routes: routeManifest,
253
+ apps: entryApps,
187
254
  serverEntry,
188
255
  outDir: targetDir,
189
- embed: options.compile === "embed" ? { clientDir } : undefined,
190
256
  publicDir,
191
- rootConventions,
192
- routeMetadata,
193
- ssgCache,
194
257
  });
195
258
 
196
259
  await Bun.build({
@@ -206,23 +269,23 @@ export async function buildBunTarget(
206
269
 
207
270
  targetManifest.serverPath = toPosixPath(join(targetManifest.targetDir, "server"));
208
271
 
209
- // Embed mode: assets are in the binary — clean up client dir too.
272
+ // Embed mode: assets are in the binary — clean up client dirs too.
210
273
  if (options.compile === "embed") {
211
- rmSync(clientDir, { force: true, recursive: true });
274
+ for (const app of apps) {
275
+ rmSync(join(targetDir, clientDirNameForPrefix(app.prefix)), {
276
+ force: true,
277
+ recursive: true,
278
+ });
279
+ }
212
280
  targetManifest.clientDir = null;
213
281
  targetManifest.templatePath = null;
214
282
  }
215
283
  } else if (serverEntry) {
216
284
  // Disk mode: generate server.ts then bundle it into self-contained server.js
217
285
  const entryPath = generateServerRoutesEntry({
218
- buildId,
219
- rootPath: root.path,
220
- routes: routeManifest,
286
+ apps: entryApps,
221
287
  serverEntry,
222
288
  outDir: targetDir,
223
- rootConventions,
224
- routeMetadata,
225
- ssgCache,
226
289
  });
227
290
 
228
291
  await Bun.build({
@@ -248,7 +311,7 @@ export async function buildBunTarget(
248
311
  "_compile-entry.ts",
249
312
  "_compile-entry.js.map",
250
313
  "server.ts", // disk mode intermediate
251
- "_hydrate.tsx",
314
+ ...hydrateIntermediates,
252
315
  ]) {
253
316
  rmSync(join(targetDir, file), { force: true });
254
317
  }