@teyik0/furin 0.5.0-alpha.1 → 0.5.0-alpha.2

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 (61) hide show
  1. package/dist/build/entry-template.ts +3 -1
  2. package/dist/build/index.js +360 -219
  3. package/dist/build/private-server-sourcemaps.d.ts +2 -0
  4. package/dist/build/types.d.ts +2 -0
  5. package/dist/cli/index.js +363 -221
  6. package/dist/client/document.d.ts +2 -0
  7. package/dist/client/link.js +11 -0
  8. package/dist/client.js +11 -0
  9. package/dist/config.d.ts +7 -2
  10. package/dist/config.js +24 -1
  11. package/dist/furin.js +217 -82
  12. package/dist/rsc-client.js +9 -1
  13. package/dist/rsc.js +19 -7
  14. package/dist/server/browser-events/shutdown.d.ts +3 -0
  15. package/dist/server/cache/redis/index.d.ts +2 -0
  16. package/dist/server/cache/redis/index.js +67 -12
  17. package/dist/server/cache/redis/scripts.d.ts +5 -5
  18. package/dist/server/dev/plugin.d.ts +1 -0
  19. package/dist/server/evlog.d.ts +1 -1
  20. package/dist/server/internal.js +3 -1
  21. package/dist/server/production-server.d.ts +13 -0
  22. package/dist/server/production-server.js +2906 -0
  23. package/dist/server/router/hmr.d.ts +6 -0
  24. package/dist/server/router/hmr.production.d.ts +5 -0
  25. package/dist/server/router/plugin.d.ts +5 -1
  26. package/dist/server/sync/index.js +5 -2
  27. package/dist/server/sync/stream.d.ts +4 -0
  28. package/dist/shared/production-build.d.ts +2 -0
  29. package/package.json +8 -3
  30. package/src/adapter/bun.ts +74 -15
  31. package/src/adapter/vercel.ts +15 -1
  32. package/src/build/elysia-aot.ts +1 -1
  33. package/src/build/entry-template.ts +3 -1
  34. package/src/build/hydrate.ts +5 -1
  35. package/src/build/index.ts +5 -0
  36. package/src/build/private-server-sourcemaps.ts +20 -0
  37. package/src/build/server-app-entry.ts +3 -2
  38. package/src/build/types.ts +2 -0
  39. package/src/cli/index.ts +1 -0
  40. package/src/client/document.tsx +19 -0
  41. package/src/config.ts +30 -2
  42. package/src/furin.ts +37 -12
  43. package/src/rsc/codec.ts +11 -6
  44. package/src/rsc/render-error.ts +3 -1
  45. package/src/server/browser-events/plugin.ts +7 -0
  46. package/src/server/browser-events/shutdown.ts +32 -0
  47. package/src/server/cache/redis/index.ts +19 -2
  48. package/src/server/cache/redis/scripts.ts +47 -7
  49. package/src/server/dev/plugin.ts +10 -1
  50. package/src/server/evlog.ts +11 -4
  51. package/src/server/production-server.ts +135 -0
  52. package/src/server/render/document.tsx +7 -1
  53. package/src/server/render/ssr.ts +2 -1
  54. package/src/server/render/template.ts +5 -1
  55. package/src/server/router/discovery.ts +3 -1
  56. package/src/server/router/hmr.production.ts +11 -0
  57. package/src/server/router/hmr.ts +84 -77
  58. package/src/server/router/plugin.ts +76 -17
  59. package/src/server/router/schema-merge.ts +9 -2
  60. package/src/server/sync/stream.ts +43 -2
  61. package/src/shared/production-build.ts +20 -0
@@ -14,6 +14,7 @@ import type { RouterContextValue } from "../../client/router/types.ts";
14
14
  import type { HeadOptions } from "../../client.ts";
15
15
  import { serializeCompactJsonLine } from "../../shared/compact-json.ts";
16
16
  import { computeErrorDigest } from "../../shared/digest.ts";
17
+ import { isProductionBuild } from "../../shared/production-build.ts";
17
18
  import { containsRscSource, serializeRouteFrames } from "../../shared/route-frame.ts";
18
19
  import type { SearchParamsInput, SearchRouteMetadata } from "../../shared/search-params.ts";
19
20
  import { getLogger, runInSyntheticRenderScope } from "../context-logger.ts";
@@ -915,7 +916,7 @@ export async function renderSSR(
915
916
  }
916
917
  }
917
918
  if (
918
- process.env.NODE_ENV !== "production" &&
919
+ !isProductionBuild() &&
919
920
  dataPayload.__furinError !== undefined &&
920
921
  dataPayload.__furinNotFound !== undefined
921
922
  ) {
@@ -136,7 +136,11 @@ export async function getDevDocumentAssets(origin: string): Promise<DocumentAsse
136
136
  if (state.devAssets && Date.now() - state.devAssets.ts < DEV_TEMPLATE_TTL_MS) {
137
137
  return state.devAssets.assets;
138
138
  }
139
- const assets = documentAssetsFromTemplate(await getDevTemplate(origin));
139
+ const { extensionErrorFilterScript } = await import("../dev/plugin.ts");
140
+ const assets = {
141
+ ...documentAssetsFromTemplate(await getDevTemplate(origin)),
142
+ extensionErrorFilterScript,
143
+ };
140
144
  state.devAssets = { assets, ts: Date.now() };
141
145
  return assets;
142
146
  }
@@ -399,7 +399,9 @@ async function resolveDefinedLayoutParent(
399
399
  if (!existsSync(candidate)) {
400
400
  continue;
401
401
  }
402
- const layoutModule = (await import(candidate)) as { route?: unknown };
402
+ const layoutModule = (await import(
403
+ IS_DEV ? `${candidate}?furin-server&t=${routeModuleSourceVersion(candidate)}` : candidate
404
+ )) as { route?: unknown };
403
405
  const layout = layoutModule.route;
404
406
  if (isDefinedRouteTerminal(layout) && typeof layout.layout === "function") {
405
407
  parent = adaptDefinedLayout(layout, parent, candidate);
@@ -2,6 +2,17 @@ export function handleDevRequest(): Promise<never> {
2
2
  return Promise.reject(new Error("[furin] Development routing is unavailable in production."));
3
3
  }
4
4
 
5
+ export function resolveCurrentDevRoute<Route, Root>(
6
+ route: Route,
7
+ root: Root
8
+ ): Promise<{ route: Route; root: Root }> {
9
+ return Promise.resolve({ root, route });
10
+ }
11
+
12
+ export function reportDevRouteFailure(): void {
13
+ // Development diagnostics are unavailable in production.
14
+ }
15
+
5
16
  export function invalidateStampedRouteModules(): void {
6
17
  // Development route modules do not exist in production.
7
18
  }
@@ -90,6 +90,15 @@ function devFailure(error: unknown): {
90
90
  return { error, phase: "import" };
91
91
  }
92
92
 
93
+ export function reportDevRouteFailure(error: unknown, route: ResolvedRoute): void {
94
+ const failure = devFailure(error);
95
+ publishDevDiagnostic(failure.error, {
96
+ entryPath: route.path,
97
+ phase: failure.phase,
98
+ route: route.pattern,
99
+ });
100
+ }
101
+
93
102
  /**
94
103
  * Reuses one virtual ESM module per source version. A timestamp generated on
95
104
  * every request leaks module-registry entries because Bun cannot release old
@@ -270,6 +279,65 @@ export function rebuildDevRoute(
270
279
  };
271
280
  }
272
281
 
282
+ /** Resolve the current source-version modules for both HTML and data requests. */
283
+ export async function resolveCurrentDevRoute(
284
+ route: ResolvedRoute,
285
+ root: RootLayout
286
+ ): Promise<{ route: ResolvedRoute; root: RootLayout }> {
287
+ let currentRoot = root;
288
+ const rootMod = await importStampedRouteModule(root.path, routeModuleImport);
289
+ const rootExport = rootMod.route;
290
+ if (isDefinedRouteTerminal(rootExport) && typeof rootExport.layout === "function") {
291
+ // Preserve the RootLayout-level convention fields (error, notFound,
292
+ // errorPath, notFoundPath) populated by `scanRootLayout` from
293
+ // `pages/error.tsx` and `pages/not-found.tsx`. Replacing the whole
294
+ // RootLayout with just `{ path, route }` would silently drop these
295
+ // fallbacks — `route.error ?? root.error` would resolve to `undefined`
296
+ // in dev after the first request, making custom 404/500 screens
297
+ // disappear after a HMR refresh.
298
+ currentRoot = {
299
+ ...currentRoot,
300
+ route: adaptDefinedLayout(rootExport, undefined, root.path),
301
+ };
302
+ }
303
+
304
+ const pageMod = await importStampedRouteModule(route.path, routeModuleImport);
305
+ let page: RuntimePage | undefined;
306
+ let chain: RuntimeRoute[] | undefined;
307
+ if (isDefinedRouteTerminal(pageMod.route) && typeof pageMod.route.page === "function") {
308
+ const currentChain = route.routeChain;
309
+ await refreshLayoutChain(currentChain, route.path, root.path, undefined);
310
+ const parent = currentChain.at(-2) ?? currentRoot.route;
311
+ const adaptedPage = adaptDefinedPage(pageMod.route, parent);
312
+ page = adaptedPage;
313
+ chain = collectRouteChainFromRoute(adaptedPage._route);
314
+ }
315
+ if (page && chain) {
316
+ // Patch chain[0] (the root) with the freshly-imported root's loader
317
+ // and layout. `refreshLayoutChain` deliberately starts at chainIdx=1
318
+ // because the root is already loaded separately above; without this
319
+ // patch, chain[0] points to whatever object `_route.parent` captured
320
+ // at _route's first evaluation — a STALE reference if Bun --hot
321
+ // re-evaluated root.tsx without propagating the re-evaluation to
322
+ // _route.tsx (the standard ESM behaviour). Mirroring the pattern
323
+ // used by patchRouteEntryFromFreshModule.
324
+ if (chain[0] && currentRoot.route) {
325
+ chain[0].layout = currentRoot.route.layout;
326
+ chain[0].loader = currentRoot.route.loader;
327
+ chain[0].staticParams = currentRoot.route.staticParams;
328
+ }
329
+
330
+ return { root: currentRoot, route: rebuildDevRoute(route, page, chain) };
331
+ }
332
+ const invalidExport = new Error(`${route.path} must provide a valid Furin page export`);
333
+ Reflect.set(invalidExport, "furinPosition", {
334
+ column: 1,
335
+ file: route.path,
336
+ line: 1,
337
+ });
338
+ throw new DevTransformFailure(invalidExport, { cause: invalidExport });
339
+ }
340
+
273
341
  /** @internal Handles a request in dev mode using the current source-version modules. */
274
342
  export async function handleDevRequest(
275
343
  route: ResolvedRoute,
@@ -281,85 +349,24 @@ export async function handleDevRequest(
281
349
  // --hot's file watcher, then hand off to renderSSR which runs loaders,
282
350
  // renders React to HTML, and injects __FURIN_DATA__.
283
351
  try {
284
- let currentRoot = root;
285
- const rootMod = await importStampedRouteModule(root.path, routeModuleImport);
286
- const rootExport = rootMod.route;
287
- if (isDefinedRouteTerminal(rootExport) && typeof rootExport.layout === "function") {
288
- // Preserve the RootLayout-level convention fields (error, notFound,
289
- // errorPath, notFoundPath) populated by `scanRootLayout` from
290
- // `pages/error.tsx` and `pages/not-found.tsx`. Replacing the whole
291
- // RootLayout with just `{ path, route }` would silently drop these
292
- // fallbacks — `route.error ?? root.error` would resolve to `undefined`
293
- // in dev after the first request, making custom 404/500 screens
294
- // disappear after a HMR refresh.
295
- currentRoot = {
296
- ...currentRoot,
297
- route: adaptDefinedLayout(rootExport, undefined, root.path),
298
- };
299
- }
352
+ const { route: refreshedRoute, root: currentRoot } = await resolveCurrentDevRoute(route, root);
300
353
 
301
- const pageMod = await importStampedRouteModule(route.path, routeModuleImport);
302
- let page: RuntimePage | undefined;
303
- let chain: RuntimeRoute[] | undefined;
304
- if (isDefinedRouteTerminal(pageMod.route) && typeof pageMod.route.page === "function") {
305
- const currentChain = route.routeChain;
306
- await refreshLayoutChain(currentChain, route.path, root.path, undefined);
307
- const parent = currentChain.at(-2) ?? currentRoot.route;
308
- const adaptedPage = adaptDefinedPage(pageMod.route, parent);
309
- page = adaptedPage;
310
- chain = collectRouteChainFromRoute(adaptedPage._route);
311
- }
312
- if (page && chain) {
313
- // Patch chain[0] (the root) with the freshly-imported root's loader
314
- // and layout. `refreshLayoutChain` deliberately starts at chainIdx=1
315
- // because the root is already loaded separately above; without this
316
- // patch, chain[0] points to whatever object `_route.parent` captured
317
- // at _route's first evaluation — a STALE reference if Bun --hot
318
- // re-evaluated root.tsx without propagating the re-evaluation to
319
- // _route.tsx (the standard ESM behaviour). Mirroring the pattern
320
- // used by patchRouteEntryFromFreshModule.
321
- if (chain[0] && currentRoot.route) {
322
- chain[0].layout = currentRoot.route.layout;
323
- chain[0].loader = currentRoot.route.loader;
324
- chain[0].staticParams = currentRoot.route.staticParams;
325
- }
326
-
327
- const refreshedRoute = rebuildDevRoute(route, page, chain);
328
-
329
- // Live ISR — the loader chain is short-circuited by the dev cache when
330
- // a fresh entry exists. HTML re-assembles every time so the dev shell
331
- // chunk URL is always current.
332
- let response: Response;
333
- if (refreshedRoute.mode === "isr") {
334
- response = await renderDevISRWithLoaderCache(
335
- refreshedRoute,
336
- ctx,
337
- currentRoot,
338
- searchRoutes
339
- );
340
- } else if (refreshedRoute.mode === "ssg") {
341
- response = await renderDevSSGWithLoaderCache(
342
- refreshedRoute,
343
- ctx,
344
- currentRoot,
345
- searchRoutes
346
- );
347
- } else {
348
- const loaderResult = await runDevLoaders(refreshedRoute, ctx);
349
- response = await runDevRender(() =>
350
- renderSSR(refreshedRoute, ctx, currentRoot, loaderResult, searchRoutes)
351
- );
352
- }
353
- devDiagnosticStore().markReady(route.pattern);
354
- return response;
354
+ // Live ISR — the loader chain is short-circuited by the dev cache when
355
+ // a fresh entry exists. HTML re-assembles every time so the dev shell
356
+ // chunk URL is always current.
357
+ let response: Response;
358
+ if (refreshedRoute.mode === "isr") {
359
+ response = await renderDevISRWithLoaderCache(refreshedRoute, ctx, currentRoot, searchRoutes);
360
+ } else if (refreshedRoute.mode === "ssg") {
361
+ response = await renderDevSSGWithLoaderCache(refreshedRoute, ctx, currentRoot, searchRoutes);
362
+ } else {
363
+ const loaderResult = await runDevLoaders(refreshedRoute, ctx);
364
+ response = await runDevRender(() =>
365
+ renderSSR(refreshedRoute, ctx, currentRoot, loaderResult, searchRoutes)
366
+ );
355
367
  }
356
- const invalidExport = new Error(`${route.path} must provide a valid Furin page export`);
357
- Reflect.set(invalidExport, "furinPosition", {
358
- column: 1,
359
- file: route.path,
360
- line: 1,
361
- });
362
- throw new DevTransformFailure(invalidExport, { cause: invalidExport });
368
+ devDiagnosticStore().markReady(route.pattern);
369
+ return response;
363
370
  } catch (err) {
364
371
  console.error(`[furin] Dev page load error for ${route.path}:`, err);
365
372
  const failure = devFailure(err);
@@ -1,4 +1,4 @@
1
- import { type AnyElysia, type Context, Elysia, problem, t } from "elysia";
1
+ import { type AnyElysia, type Context, Elysia, problem } from "elysia";
2
2
  import { toCrossJSONAsync } from "seroval";
3
3
  import type { HeadOptions } from "../../client.ts";
4
4
  import { computeErrorDigest } from "../../shared/digest.ts";
@@ -27,7 +27,7 @@ import { extractTitle } from "../render/shell.ts";
27
27
  import { prerenderRoute, prerenderRuntimeSSG } from "../render/ssg.ts";
28
28
  import { renderSSR, serializeLoaderDataNdjson } from "../render/ssr.ts";
29
29
  import { IS_DEV } from "../runtime-env.ts";
30
- import { handleDevRequest } from "./hmr.ts";
30
+ import { handleDevRequest, reportDevRouteFailure } from "./hmr.ts";
31
31
  import { buildRouteMatcher, resolveRouteRevalidate } from "./patterns.ts";
32
32
  import { mergeRouteSchemas } from "./schema-merge.ts";
33
33
  import {
@@ -43,6 +43,12 @@ const MAX_NAVIGATION_HEAD_BYTES = 64 * 1024;
43
43
  type DataResolvedRoutesSource =
44
44
  | ResolvedRoutesSource
45
45
  | ((request: Request) => Promise<ResolvedRoute[]>);
46
+ type RefreshDevRoute = (
47
+ route: ResolvedRoute
48
+ ) => Promise<{ route: ResolvedRoute; root: RootLayout }>;
49
+ type DataRouteResolver = (
50
+ route: ResolvedRoute
51
+ ) => Promise<{ route: ResolvedRoute; root: RootLayout | undefined }>;
46
52
 
47
53
  interface DataRouteParamsInput {
48
54
  [key: string]: unknown;
@@ -207,6 +213,48 @@ async function createRouteDataErrorResponse(
207
213
  });
208
214
  }
209
215
 
216
+ async function resolveDataRoute(
217
+ route: ResolvedRoute,
218
+ resolveRoute: DataRouteResolver
219
+ ): Promise<{ route: ResolvedRoute; root: RootLayout | undefined } | Response> {
220
+ try {
221
+ return await resolveRoute(route);
222
+ } catch (error) {
223
+ getLogger().error(error instanceof Error ? error : new Error(String(error)));
224
+ if (IS_DEV) {
225
+ reportDevRouteFailure(error, route);
226
+ }
227
+ return createRouteDataErrorResponse(error, "Something went wrong", 500, undefined);
228
+ }
229
+ }
230
+
231
+ async function resolveDataRoutes(
232
+ routesSource: DataResolvedRoutesSource,
233
+ request: Request
234
+ ): Promise<ResolvedRoute[] | Response> {
235
+ try {
236
+ return typeof routesSource === "function" ? await routesSource(request) : routesSource;
237
+ } catch (error) {
238
+ getLogger().error(error instanceof Error ? error : new Error(String(error)));
239
+ return createRouteDataErrorResponse(error, "Something went wrong", 500, undefined);
240
+ }
241
+ }
242
+
243
+ function resolvedSearchRoutes(
244
+ routes: ResolvedRoute[],
245
+ matchedRoute: ResolvedRoute,
246
+ currentRoute: ResolvedRoute,
247
+ searchRoutes: SearchRouteMetadata[],
248
+ refreshDevRoute: RefreshDevRoute | undefined
249
+ ): SearchRouteMetadata[] {
250
+ if (refreshDevRoute === undefined) {
251
+ return searchRoutes;
252
+ }
253
+ return createSearchRouteMetadata(
254
+ routes.map((route) => (route === matchedRoute ? currentRoute : route))
255
+ );
256
+ }
257
+
210
258
  /** @internal Handles a production SSG route — sets ETags, Cache-Control, and Cache-Tag. */
211
259
  async function handleSSGRequest(
212
260
  route: ResolvedRoute,
@@ -336,17 +384,20 @@ export function renderResolvedRoute(
336
384
  */
337
385
  export function createDataEndpoint(
338
386
  routesSource: DataResolvedRoutesSource,
339
- root?: RootLayout
387
+ root?: RootLayout,
388
+ refreshDevRoute?: RefreshDevRoute
340
389
  ): AnyElysia {
341
390
  const plugin = new Elysia();
342
391
  let matchedRoutes = Array.isArray(routesSource) ? routesSource : [];
343
392
  let matchRoute = buildRouteMatcher(matchedRoutes);
344
393
  let searchRoutes = createSearchRouteMetadata(matchedRoutes);
394
+ const resolveRoute: DataRouteResolver =
395
+ refreshDevRoute ?? ((route: ResolvedRoute) => Promise.resolve({ root, route }));
345
396
 
346
397
  plugin.get(
347
398
  "/_furin/data",
348
399
  {
349
- query: t.Object({ path: t.Optional(t.String()) }),
400
+ // The transport path is validated below without requiring a TypeBox schema.
350
401
  },
351
402
  async (ctx) => {
352
403
  const rawPath = ctx.query.path;
@@ -368,13 +419,9 @@ export function createDataEndpoint(
368
419
  const wideEventLog = getLogger();
369
420
  wideEventLog.set({ path: rawPath });
370
421
 
371
- let currentRoutes: ResolvedRoute[];
372
- try {
373
- currentRoutes =
374
- typeof routesSource === "function" ? await routesSource(ctx.request) : routesSource;
375
- } catch (error) {
376
- wideEventLog.error(error instanceof Error ? error : new Error(String(error)));
377
- return createRouteDataErrorResponse(error, "Something went wrong", 500, undefined);
422
+ const currentRoutes = await resolveDataRoutes(routesSource, ctx.request);
423
+ if (currentRoutes instanceof Response) {
424
+ return currentRoutes;
378
425
  }
379
426
  if (currentRoutes !== matchedRoutes) {
380
427
  matchedRoutes = currentRoutes;
@@ -391,6 +438,18 @@ export function createDataEndpoint(
391
438
  // key for drains (e.g. "p99 latency by route").
392
439
  wideEventLog.set({ routePattern: matched.route.pattern });
393
440
 
441
+ const current = await resolveDataRoute(matched.route, resolveRoute);
442
+ if (current instanceof Response) {
443
+ return current;
444
+ }
445
+ const currentSearchRoutes = resolvedSearchRoutes(
446
+ matchedRoutes,
447
+ matched.route,
448
+ current.route,
449
+ searchRoutes,
450
+ refreshDevRoute
451
+ );
452
+
394
453
  // Build a synthetic Elysia-compatible context for the matched route.
395
454
  // Loaders receive request, params, query, set, headers, and cookie.
396
455
  // Build the synthetic URL from the parsed `pathname + search` only —
@@ -424,8 +483,8 @@ export function createDataEndpoint(
424
483
 
425
484
  // Normalize params and query through the route chain schemas so SPA and
426
485
  // document requests expose identical typed/defaulted inputs.
427
- const mergedParams = mergeRouteSchemas(matched.route.routeChain, "params");
428
- const mergedQuery = mergeRouteSchemas(matched.route.routeChain, "query");
486
+ const mergedParams = mergeRouteSchemas(current.route.routeChain, "params");
487
+ const mergedQuery = mergeRouteSchemas(current.route.routeChain, "query");
429
488
  const parsedParams = await parseRouteParams(matched.params, mergedParams);
430
489
  if (!parsedParams.ok) {
431
490
  return problem(422, { detail: "Invalid params", errors: parsedParams.errors });
@@ -438,13 +497,13 @@ export function createDataEndpoint(
438
497
  syntheticCtx.query = parsedQuery.query as SearchParamsInput;
439
498
 
440
499
  const result = await runDataEndpointLoaders(
441
- matched.route,
500
+ current.route,
442
501
  syntheticCtx as unknown as Context,
443
- root,
444
- searchRoutes
502
+ current.root,
503
+ currentSearchRoutes
445
504
  );
446
505
 
447
- return createLoaderDataResponse(result, matched.route, syntheticRequest.url, syntheticCtx);
506
+ return createLoaderDataResponse(result, current.route, syntheticRequest.url, syntheticCtx);
448
507
  }
449
508
  );
450
509
 
@@ -1,4 +1,3 @@
1
- import { t } from "elysia";
2
1
  import type { RuntimeRoute } from "../../client/internal/runtime-types.ts";
3
2
  import { type FurinSchema, isTypeBoxObjectSchema } from "../../shared/elysia-contract.ts";
4
3
 
@@ -7,6 +6,7 @@ interface SchemaObject {
7
6
  }
8
7
 
9
8
  const TOBJECT_STRUCTURAL_KEYS = new Set(["type", "properties", "required"]);
9
+ const TYPEBOX_OPTIONAL = Symbol.for("TypeBox.Optional");
10
10
  export function mergeRouteSchemas(
11
11
  routeChain: RuntimeRoute[],
12
12
  key: "params" | "query"
@@ -38,5 +38,12 @@ export function mergeRouteSchemas(
38
38
  )
39
39
  );
40
40
 
41
- return t.Object(properties, options) as FurinSchema;
41
+ // Match t.Object's schema shape without importing TypeBox into schema-free bundles.
42
+ const required = Object.keys(properties).filter((name) => {
43
+ const property = properties[name] as SchemaObject & { [symbolName: symbol]: unknown };
44
+ return !(property["~optional"] || property[TYPEBOX_OPTIONAL]);
45
+ });
46
+ return Object.defineProperty({ ...options, properties, required, type: "object" }, "~kind", {
47
+ value: "Object",
48
+ }) as FurinSchema;
42
49
  }
@@ -26,6 +26,20 @@ interface SyncCursorState {
26
26
 
27
27
  const cursorStates = new Map<SyncAdapter, Promise<SyncCursorState>>();
28
28
  const resolvedStates = new Set<SyncCursorState>();
29
+ const pendingUnsubscriptions = new Set<Promise<void>>();
30
+ const unsubscriptions = new WeakMap<SyncSubscription, Promise<void>>();
31
+
32
+ function trackUnsubscription(subscription: SyncSubscription): Promise<void> {
33
+ const existing = unsubscriptions.get(subscription);
34
+ if (existing) {
35
+ return existing;
36
+ }
37
+ const pending = subscription.unsubscribe();
38
+ unsubscriptions.set(subscription, pending);
39
+ pendingUnsubscriptions.add(pending);
40
+ pending.finally(() => pendingUnsubscriptions.delete(pending)).catch(() => undefined);
41
+ return pending;
42
+ }
29
43
 
30
44
  function notifyState(state: SyncCursorState, cursor: string): void {
31
45
  if (state.cursor === cursor) {
@@ -93,7 +107,7 @@ export async function subscribeSyncCursor(
93
107
  if (state.safetyPoll) {
94
108
  clearInterval(state.safetyPoll);
95
109
  }
96
- state.subscription.unsubscribe().catch(() => undefined);
110
+ trackUnsubscription(state.subscription);
97
111
  },
98
112
  };
99
113
  }
@@ -172,7 +186,7 @@ export function createSyncChangesPlugin(options: FurinSyncOptions) {
172
186
  /** @internal — closes process-local stream state between tests. */
173
187
  export function __resetSyncState(): void {
174
188
  for (const state of resolvedStates) {
175
- state.subscription.unsubscribe().catch(() => undefined);
189
+ trackUnsubscription(state.subscription);
176
190
  if (state.safetyPoll) {
177
191
  clearInterval(state.safetyPoll);
178
192
  }
@@ -181,3 +195,30 @@ export function __resetSyncState(): void {
181
195
  cursorStates.clear();
182
196
  resolvedStates.clear();
183
197
  }
198
+
199
+ /** Release process-local Sync subscriptions after Bun has drained HTTP traffic. */
200
+ export async function closeSyncCursorStates(): Promise<void> {
201
+ const pending = [...cursorStates.values()];
202
+ cursorStates.clear();
203
+ const states = await Promise.allSettled(pending);
204
+ await Promise.allSettled(
205
+ states.flatMap((result) => {
206
+ if (result.status !== "fulfilled") {
207
+ return [];
208
+ }
209
+ const state = result.value;
210
+ if (state.safetyPoll) {
211
+ clearInterval(state.safetyPoll);
212
+ }
213
+ state.listeners.clear();
214
+ resolvedStates.delete(state);
215
+ return [trackUnsubscription(state.subscription)];
216
+ })
217
+ );
218
+ await waitForSyncCursorUnsubscriptions();
219
+ }
220
+
221
+ /** Wait for released connections without closing subscriptions owned by other servers. */
222
+ export async function waitForSyncCursorUnsubscriptions(): Promise<void> {
223
+ await Promise.allSettled([...pendingUnsubscriptions]);
224
+ }
@@ -0,0 +1,20 @@
1
+ let productionBuildScope: import("node:async_hooks").AsyncLocalStorage<boolean> | undefined;
2
+ let productionBuildScopePromise:
3
+ | Promise<import("node:async_hooks").AsyncLocalStorage<boolean>>
4
+ | undefined;
5
+
6
+ export async function withProductionBuild<T>(build: () => Promise<T>): Promise<T> {
7
+ productionBuildScopePromise ??= import("node:async_hooks").then(({ AsyncLocalStorage }) => {
8
+ productionBuildScope = new AsyncLocalStorage<boolean>();
9
+ return productionBuildScope;
10
+ });
11
+ const scope = await productionBuildScopePromise;
12
+ return scope.run(true, build);
13
+ }
14
+
15
+ export function isProductionBuild(): boolean {
16
+ return (
17
+ productionBuildScope?.getStore() === true ||
18
+ (typeof process !== "undefined" && process.env.NODE_ENV === "production")
19
+ );
20
+ }