@teyik0/furin 0.2.0-alpha.2 → 0.2.0-alpha.4

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 (134) hide show
  1. package/README.md +4 -0
  2. package/dist/adapter/bun.d.ts +3 -0
  3. package/dist/adapter/static.d.ts +3 -0
  4. package/dist/build/client.d.ts +25 -0
  5. package/dist/build/compile-entry.d.ts +9 -0
  6. package/dist/build/compile-entry.ts +109 -0
  7. package/dist/build/entry-template.d.ts +38 -0
  8. package/dist/build/entry-template.ts +156 -0
  9. package/dist/build/hydrate.d.ts +24 -0
  10. package/dist/build/index.d.ts +8 -0
  11. package/dist/build/index.js +8106 -0
  12. package/dist/build/route-types.d.ts +23 -0
  13. package/dist/build/scan-server.d.ts +8 -0
  14. package/dist/build/server-routes-entry.d.ts +13 -0
  15. package/dist/build/server-routes-entry.ts +36 -0
  16. package/dist/build/shared.d.ts +12 -0
  17. package/dist/build/ssg-cache.d.ts +4 -0
  18. package/dist/build/types.d.ts +80 -0
  19. package/dist/cli/config.d.ts +9 -0
  20. package/dist/cli/index.d.ts +2 -0
  21. package/dist/cli/index.js +8097 -0
  22. package/dist/client/boundaries.d.ts +117 -0
  23. package/dist/client/default-screens.d.ts +17 -0
  24. package/dist/client/link.d.ts +22 -0
  25. package/dist/client/link.js +4391 -0
  26. package/dist/client/router/abort.d.ts +1 -0
  27. package/dist/client/router/boundary-tree.d.ts +26 -0
  28. package/dist/client/router/context.d.ts +8 -0
  29. package/dist/client/router/history.d.ts +9 -0
  30. package/dist/client/router/index.d.ts +11 -0
  31. package/dist/client/router/link-utils.d.ts +53 -0
  32. package/dist/client/router/navigation.d.ts +10 -0
  33. package/dist/client/router/provider.d.ts +4 -0
  34. package/dist/client/router/search/index.d.ts +18 -0
  35. package/dist/client/router/search-store.d.ts +21 -0
  36. package/dist/client/router/spa-response.d.ts +58 -0
  37. package/dist/client/router/sync-catch-up.d.ts +29 -0
  38. package/dist/client/router/types.d.ts +292 -0
  39. package/dist/client/server-error.d.ts +12 -0
  40. package/dist/client/sync.d.ts +25 -0
  41. package/dist/client.d.ts +243 -0
  42. package/dist/client.js +140 -0
  43. package/dist/config.d.ts +57 -0
  44. package/dist/config.js +29 -0
  45. package/dist/env.d.ts +50 -0
  46. package/dist/furin.d.ts +77 -0
  47. package/dist/furin.js +8977 -0
  48. package/dist/plugin/index.d.ts +20 -0
  49. package/dist/plugin/index.js +1500 -0
  50. package/dist/plugin/transform-client.d.ts +10 -0
  51. package/dist/server/auto-invalidate/index.d.ts +4 -0
  52. package/dist/server/auto-invalidate/plugin.d.ts +38 -0
  53. package/dist/server/auto-invalidate/registry.d.ts +9 -0
  54. package/dist/server/auto-invalidate/runtime.d.ts +9 -0
  55. package/dist/server/auto-invalidate/types.d.ts +12 -0
  56. package/dist/server/cache/dev-loader.d.ts +28 -0
  57. package/dist/server/cache/index.d.ts +10 -0
  58. package/dist/server/cache/invalidation.d.ts +12 -0
  59. package/dist/server/cache/isr-ssg.d.ts +26 -0
  60. package/dist/server/cache/isr.d.ts +6 -0
  61. package/dist/server/cache/registry.d.ts +5 -0
  62. package/dist/server/cache/route-cache.d.ts +26 -0
  63. package/dist/server/cache/ssg.d.ts +5 -0
  64. package/dist/server/context-logger.d.ts +28 -0
  65. package/dist/server/dev-inspector.d.ts +89 -0
  66. package/dist/server/dev-page-plugin.d.ts +112 -0
  67. package/dist/server/internal.d.ts +35 -0
  68. package/dist/server/internal.js +17 -0
  69. package/dist/server/lang-detect.d.ts +5 -0
  70. package/dist/server/render/assemble.d.ts +49 -0
  71. package/dist/server/render/element.d.ts +24 -0
  72. package/dist/server/render/index.d.ts +7 -0
  73. package/dist/server/render/index.ts +22 -0
  74. package/dist/server/render/isr.d.ts +4 -0
  75. package/dist/server/render/loaders.d.ts +64 -0
  76. package/dist/server/render/not-found.d.ts +6 -0
  77. package/dist/server/render/shell.d.ts +39 -0
  78. package/dist/server/render/shell.ts +202 -0
  79. package/dist/server/render/ssg.d.ts +9 -0
  80. package/dist/server/render/ssr.d.ts +108 -0
  81. package/dist/server/render/template.d.ts +6 -0
  82. package/dist/server/router/discovery.d.ts +16 -0
  83. package/dist/server/router/hmr.d.ts +65 -0
  84. package/dist/server/router/index.d.ts +6 -0
  85. package/dist/server/router/index.js +27 -0
  86. package/dist/server/router/index.ts +28 -0
  87. package/dist/server/router/patterns.d.ts +40 -0
  88. package/dist/server/router/plugin.d.ts +21 -0
  89. package/dist/server/router/schemas.d.ts +59 -0
  90. package/dist/server/router/types.d.ts +60 -0
  91. package/dist/server/runtime-env.d.ts +3 -0
  92. package/dist/server/runtime-env.js +10 -0
  93. package/dist/server/sync/adapter.d.ts +62 -0
  94. package/dist/server/sync/config.d.ts +6 -0
  95. package/dist/server/sync/fingerprint.d.ts +6 -0
  96. package/dist/server/sync/index.d.ts +4 -0
  97. package/dist/server/sync/memory-adapter.d.ts +17 -0
  98. package/dist/server/sync/plugin.d.ts +186 -0
  99. package/dist/server/sync/response.d.ts +4 -0
  100. package/dist/server/sync/stream.d.ts +59 -0
  101. package/dist/shared/await.d.ts +67 -0
  102. package/dist/shared/deferred-ndjson.d.ts +32 -0
  103. package/dist/shared/digest.d.ts +16 -0
  104. package/dist/shared/error.d.ts +37 -0
  105. package/dist/shared/not-found.d.ts +19 -0
  106. package/dist/shared/search-params.d.ts +17 -0
  107. package/dist/shared/utils/ast-walk.d.ts +18 -0
  108. package/dist/shared/utils/index.d.ts +13 -0
  109. package/package.json +5 -5
  110. package/src/build/hydrate.ts +4 -1
  111. package/src/build/shared.ts +4 -3
  112. package/src/client/router/abort.ts +5 -0
  113. package/src/client/router/link-utils.ts +8 -1
  114. package/src/client/router/provider.tsx +130 -6
  115. package/src/client/router/sync-catch-up.ts +113 -0
  116. package/src/client/router/types.ts +5 -0
  117. package/src/client/sync.ts +98 -0
  118. package/src/client.ts +15 -1
  119. package/src/furin.ts +25 -4
  120. package/src/server/auto-invalidate/runtime.ts +3 -2
  121. package/src/server/dev-page-plugin.ts +15 -10
  122. package/src/server/render/assemble.ts +30 -3
  123. package/src/server/render/isr.ts +8 -2
  124. package/src/server/render/ssr.ts +9 -1
  125. package/src/server/router/plugin.ts +2 -2
  126. package/src/server/sync/adapter.ts +65 -0
  127. package/src/server/sync/config.ts +29 -0
  128. package/src/server/sync/fingerprint.ts +44 -0
  129. package/src/server/sync/index.ts +15 -0
  130. package/src/server/sync/memory-adapter.ts +196 -0
  131. package/src/server/sync/plugin.ts +200 -0
  132. package/src/server/sync/response.ts +77 -0
  133. package/src/server/sync/stream.ts +152 -0
  134. package/src/shared/deferred-ndjson.ts +7 -0
package/src/furin.ts CHANGED
@@ -26,6 +26,12 @@ import {
26
26
  loadProdRoutes,
27
27
  } from "./server/router/index.ts";
28
28
  import { IS_DEV } from "./server/runtime-env.ts";
29
+ import {
30
+ createSyncStreamPlugin,
31
+ type FurinSyncOption,
32
+ resolveSyncStreamPath,
33
+ runWithSyncStreamPath,
34
+ } from "./server/sync/index.ts";
29
35
 
30
36
  // biome-ignore lint/suspicious/noEmptyInterface: intentionally augmentable via furin-env.d.ts
31
37
  export interface FurinCacheTags {}
@@ -159,9 +165,12 @@ async function setupProdTemplate(
159
165
  * `.use()`-d by a parent Elysia instance. HigherOrderFunctions survive the
160
166
  * plugin merge and wrap the entire composed `map` handler.
161
167
  */
162
- function wrapWithRequestScope(app: AnyElysia): Elysia {
168
+ function wrapWithRequestScope(app: AnyElysia, syncStreamPath: string | undefined): Elysia {
163
169
  return app.wrap(
164
- (handler, _request) => (ctx: unknown) => _runWithRequestInvalidationScope(() => handler(ctx))
170
+ (handler, _request) => (ctx: unknown) =>
171
+ runWithSyncStreamPath(syncStreamPath, () =>
172
+ _runWithRequestInvalidationScope(() => handler(ctx))
173
+ )
165
174
  );
166
175
  }
167
176
 
@@ -192,6 +201,7 @@ export async function furin({
192
201
  pagesDir,
193
202
  logger,
194
203
  clientLogging,
204
+ sync,
195
205
  }: {
196
206
  pagesDir?: string;
197
207
  logger?: EvlogElysiaOptions;
@@ -202,7 +212,14 @@ export async function furin({
202
212
  * and unaffected.
203
213
  */
204
214
  clientLogging?: boolean;
215
+ /**
216
+ * Enables Furin's built-in sync event stream. The opinionated default mounts
217
+ * Server-Sent Events at `/_furin/sync`; pass an object only for constrained
218
+ * reverse-proxy deployments that need a custom internal path.
219
+ */
220
+ sync?: FurinSyncOption;
205
221
  }) {
222
+ const syncStreamPath = resolveSyncStreamPath(sync);
206
223
  const { exclude: userExclude, ...evlogOptions } = logger ?? {};
207
224
  initLogger({ env: { service: "furin" } });
208
225
 
@@ -215,6 +232,7 @@ export async function furin({
215
232
  "/public/**",
216
233
  "/favicon.ico",
217
234
  "/_bun_hmr_entry/**",
235
+ ...(syncStreamPath ? [syncStreamPath] : []),
218
236
  // Note: /_furin/data is logged with the *logical* path rewritten by
219
237
  // createDataEndpoint via useLogger().set({ path }), so SPA navigations
220
238
  // appear as "GET /board/123 200" — same shape as a normal SSR nav.
@@ -320,6 +338,7 @@ export async function furin({
320
338
  : () => new Response(null, { status: 404 })
321
339
  )
322
340
  .use(createDevInspectorPlugin())
341
+ .use(syncStreamPath ? createSyncStreamPlugin(syncStreamPath) : new Elysia())
323
342
  .use(createDataEndpoint(routes))
324
343
  .use((app) => {
325
344
  for (const route of routes) {
@@ -327,7 +346,7 @@ export async function furin({
327
346
  }
328
347
  return app;
329
348
  });
330
- return wrapWithRequestScope(devApp);
349
+ return wrapWithRequestScope(devApp, syncStreamPath);
331
350
  }
332
351
 
333
352
  // ── Production ──────────────────────────────────────────────────────────
@@ -412,6 +431,7 @@ export async function furin({
412
431
  return app;
413
432
  })()
414
433
  )
434
+ .use(syncStreamPath ? createSyncStreamPlugin(syncStreamPath) : new Elysia())
415
435
  .use(createDataEndpoint(routes))
416
436
  .use((app) => {
417
437
  for (const route of routes) {
@@ -419,7 +439,7 @@ export async function furin({
419
439
  }
420
440
  return app;
421
441
  });
422
- return wrapWithRequestScope(prodApp);
442
+ return wrapWithRequestScope(prodApp, syncStreamPath);
423
443
  }
424
444
 
425
445
  // biome-ignore lint/performance/noBarrelFile: furin.ts is the public package entry
@@ -433,6 +453,7 @@ export { furinInvalidate, revalidateTag } from "./server/auto-invalidate/index.t
433
453
  export { revalidatePath, setCachePurger } from "./server/cache/invalidation.ts";
434
454
  export { buildElement, buildErrorElement, renderRootNotFound } from "./server/render/index.ts";
435
455
  export type { ResolvedRoute, SegmentBoundary } from "./server/router/index.ts";
456
+ export { furinSync, type SyncInput, type SyncRouteOption } from "./server/sync/index.ts";
436
457
  export { Await, useAsyncError, useAsyncValue } from "./shared/await.tsx";
437
458
  export type { ErrorComponent, ErrorProps } from "./shared/error.ts";
438
459
  export type {
@@ -96,10 +96,10 @@ export function isSuccessfulMutationResponse(
96
96
  return true;
97
97
  }
98
98
 
99
- export function appendPendingInvalidationHeader(set: Context["set"]): void {
99
+ export function appendPendingInvalidationHeader(set: Context["set"]): string[] {
100
100
  const pending = consumePendingInvalidations();
101
101
  if (pending.length === 0) {
102
- return;
102
+ return [];
103
103
  }
104
104
 
105
105
  const headerName = "x-furin-revalidate";
@@ -108,6 +108,7 @@ export function appendPendingInvalidationHeader(set: Context["set"]): void {
108
108
  typeof existing === "string" && existing.length > 0
109
109
  ? `${existing},${pending.join(",")}`
110
110
  : pending.join(",");
111
+ return pending;
111
112
  }
112
113
 
113
114
  export function revalidateTag(tags: string | readonly string[]): boolean {
@@ -58,8 +58,8 @@ import { invalidateDevLoaderCacheBySource } from "./cache/dev-loader.ts";
58
58
  // Matches ?furin-server with an optional &t=<ms> cache-buster.
59
59
  const FURIN_SERVER_FILTER = /\?furin-server(?:&t=\d+)?$/;
60
60
  const ANY_FILTER = /.*/;
61
- const WORKSPACE_SOURCE_FILTER =
62
- /^(?!.*(?:\/node_modules\/|\/\.bun\/))(?!.*\.(?:test|spec)\.[jt]sx?$).*\.[jt]sx?$/;
61
+ export const WORKSPACE_SOURCE_FILTER =
62
+ /^(?!.*(?:[\\/]node_modules[\\/]|[\\/]\.bun[\\/]))(?!.*\.(?:test|spec)\.[jt]sx?$).*\.[jt]sx?$/;
63
63
  const T_PARAM_RE = /&t=(\d+)/;
64
64
  const STRIP_FURIN_SERVER_RE = /\?furin-server.*$/;
65
65
  const STRIP_T_PARAM_RE = /\?t=\d+$/;
@@ -93,12 +93,17 @@ const SINGLETON_PKGS = [
93
93
  const SINGLETON_PATHS = new Map<string, string>();
94
94
  for (const pkg of SINGLETON_PKGS) {
95
95
  try {
96
- SINGLETON_PATHS.set(pkg, fileURLToPath(import.meta.resolve(pkg)));
96
+ SINGLETON_PATHS.set(pkg, toImportSpecifier(fileURLToPath(import.meta.resolve(pkg))));
97
97
  } catch {
98
98
  // Package not installed — skip (e.g. react-dom/client in a server-only env)
99
99
  }
100
100
  }
101
101
 
102
+ /** Converts a native absolute path to Bun's cross-platform import format. */
103
+ export function toImportSpecifier(filePath: string): string {
104
+ return filePath.replaceAll("\\", "/");
105
+ }
106
+
102
107
  function escapeRegExp(s: string): string {
103
108
  return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
104
109
  }
@@ -121,7 +126,7 @@ export function rewriteSingletonImports(source: string): string {
121
126
  for (const [pkg, absPath] of SINGLETON_PATHS) {
122
127
  // react-doctor-disable-next-line react-doctor/js-hoist-regexp
123
128
  const re = new RegExp(`((?:from|import(?:\\s+type)?)\\s+)["']${escapeRegExp(pkg)}["']`, "g");
124
- result = result.replace(re, (_, g1: string) => `${g1}"${absPath}"`);
129
+ result = result.replace(re, (_, g1: string) => `${g1}${JSON.stringify(absPath)}`);
125
130
  }
126
131
  return result;
127
132
  }
@@ -175,7 +180,7 @@ export function injectJsxHelperImports(transpiled: string): string {
175
180
  const specifiers = [...devRuntime.entries()]
176
181
  .map(([varName, exportName]) => `${exportName} as ${varName}`)
177
182
  .join(", ");
178
- lines.push(`import { ${specifiers} } from "${absPath}";`);
183
+ lines.push(`import { ${specifiers} } from ${JSON.stringify(absPath)};`);
179
184
  }
180
185
  }
181
186
 
@@ -185,7 +190,7 @@ export function injectJsxHelperImports(transpiled: string): string {
185
190
  const specifiers = [...prodRuntime.entries()]
186
191
  .map(([varName, exportName]) => `${exportName} as ${varName}`)
187
192
  .join(", ");
188
- lines.push(`import { ${specifiers} } from "${absPath}";`);
193
+ lines.push(`import { ${specifiers} } from ${JSON.stringify(absPath)};`);
189
194
  }
190
195
  }
191
196
 
@@ -216,9 +221,9 @@ export function rewriteRelativeImports(source: string, dir: string): string {
216
221
  if (linePrefix.startsWith("//") || linePrefix.startsWith("*")) {
217
222
  return match;
218
223
  }
219
- const absPath = resolve(dir, relPath);
224
+ const absPath = toImportSpecifier(resolve(dir, relPath));
220
225
  const keyword = match.startsWith("import") ? "import" : "from";
221
- return `${keyword} "${absPath}"`;
226
+ return `${keyword} ${JSON.stringify(absPath)}`;
222
227
  });
223
228
  }
224
229
 
@@ -269,7 +274,7 @@ export function rewriteBareImports(source: string, transpiled: string, dir: stri
269
274
 
270
275
  let resolved: string;
271
276
  try {
272
- resolved = Bun.resolveSync(spec, dir);
277
+ resolved = toImportSpecifier(Bun.resolveSync(spec, dir));
273
278
  } catch {
274
279
  // Not resolvable from the file's directory — leave as a bare specifier
275
280
  // so Bun falls back to CWD-relative resolution (adequate for most cases).
@@ -283,7 +288,7 @@ export function rewriteBareImports(source: string, transpiled: string, dir: stri
283
288
  // literals in non-import positions are left untouched.
284
289
  // react-doctor-disable-next-line react-doctor/js-hoist-regexp
285
290
  const re = new RegExp(`((?:from|import(?:\\s+type)?)\\s+)["']${escapeRegExp(spec)}["']`, "g");
286
- result = result.replace(re, (_, g1: string) => `${g1}"${resolved}"`);
291
+ result = result.replace(re, (_, g1: string) => `${g1}${JSON.stringify(resolved)}`);
287
292
  }
288
293
  return result;
289
294
  }
@@ -1,4 +1,5 @@
1
1
  import type { toCrossJSON } from "seroval";
2
+ import { getSyncStreamPath } from "../sync/config.ts";
2
3
  import type { buildHeadInjection } from "./shell";
3
4
  import { safeJson } from "./shell";
4
5
 
@@ -121,13 +122,39 @@ export function assembleHTML(
121
122
  const dataScript = data
122
123
  ? `<script id="__FURIN_DATA__" type="application/json">${safeJson(data)}</script>`
123
124
  : "";
125
+ const syncScript = buildSyncRuntimeScript();
126
+ const runtimeScripts = `${syncScript}${dataScript}`;
124
127
 
125
128
  let injectedBodyPost = bodyPost;
126
- if (dataScript) {
129
+ if (runtimeScripts) {
127
130
  injectedBodyPost = bodyPost.includes("</body>")
128
- ? bodyPost.replace("</body>", `${dataScript}</body>`)
129
- : bodyPost + dataScript;
131
+ ? bodyPost.replace("</body>", `${runtimeScripts}</body>`)
132
+ : bodyPost + runtimeScripts;
130
133
  }
131
134
 
132
135
  return headPre + headData + bodyPre + reactHtml + injectedBodyPost;
133
136
  }
137
+
138
+ export function buildSyncRuntimeScript(): string {
139
+ const syncStreamPath = getSyncStreamPath();
140
+ if (!syncStreamPath) {
141
+ return "";
142
+ }
143
+
144
+ return `<script id="__FURIN_SYNC__" type="application/json">${safeJson({ stream: syncStreamPath })}</script>`;
145
+ }
146
+
147
+ export function injectSyncRuntimeScript(html: string): string {
148
+ if (html.includes('id="__FURIN_SYNC__"')) {
149
+ return html;
150
+ }
151
+
152
+ const syncScript = buildSyncRuntimeScript();
153
+ if (!syncScript) {
154
+ return html;
155
+ }
156
+
157
+ return html.includes("</body>")
158
+ ? html.replace("</body>", `${syncScript}</body>`)
159
+ : html + syncScript;
160
+ }
@@ -7,7 +7,13 @@ import { deleteISRCache, getISRCache, setISRCache } from "../cache/isr.ts";
7
7
  import type { ISRCacheEntry } from "../cache/isr-ssg.ts";
8
8
  import { createLogger, useLogger } from "../context-logger.ts";
9
9
  import type { ResolvedRoute, RootLayout } from "../router/index.ts";
10
- import { assembleHTML, type LoaderContext, resolvePath, streamToString } from "./assemble.ts";
10
+ import {
11
+ assembleHTML,
12
+ injectSyncRuntimeScript,
13
+ type LoaderContext,
14
+ resolvePath,
15
+ streamToString,
16
+ } from "./assemble.ts";
11
17
  import {
12
18
  type PreparedRender,
13
19
  prepareRender,
@@ -69,7 +75,7 @@ function serveISRCacheHit(
69
75
  useLogger().set({
70
76
  furin: { render: "isr", route: route.pattern, cache: isFresh ? "hit" : "stale" },
71
77
  });
72
- return cached.html;
78
+ return injectSyncRuntimeScript(cached.html);
73
79
  }
74
80
 
75
81
  /**
@@ -16,6 +16,7 @@ import {
16
16
  } from "../../client/router/search-store.ts";
17
17
  import { computeErrorDigest } from "../../shared/digest.ts";
18
18
  import type { SearchParamsInput, SearchRouteMetadata } from "../../shared/search-params.ts";
19
+ import { autoInvalidateRegistry } from "../auto-invalidate/registry.ts";
19
20
  import { runInSyntheticRenderScope, useLogger } from "../context-logger.ts";
20
21
  // FurinNotFoundError is used indirectly via buildNotFoundElement in element.tsx
21
22
  import type { ResolvedRoute, RootLayout } from "../router/index.ts";
@@ -24,6 +25,7 @@ import {
24
25
  assembleHTML,
25
26
  buildDeferredResolution,
26
27
  buildDeferredScript,
28
+ buildSyncRuntimeScript,
27
29
  resolvePath,
28
30
  splitTemplate,
29
31
  streamToString,
@@ -465,6 +467,11 @@ export async function renderSSR(
465
467
  return prepared;
466
468
  }
467
469
 
470
+ autoInvalidateRegistry.registerLoaderTags(
471
+ resolvePath(route.pattern, ctx.params ?? {}),
472
+ route.tags
473
+ );
474
+
468
475
  useLogger().set({
469
476
  furin: {
470
477
  render: route.mode,
@@ -522,6 +529,7 @@ export async function renderSSR(
522
529
  const dataScript = `<script id="__FURIN_DATA__" type="application/json">${safeJson(
523
530
  dataPayload
524
531
  )}</script>`;
532
+ const runtimeScripts = `${buildSyncRuntimeScript()}${dataScript}`;
525
533
 
526
534
  const { readable, writable } = new TransformStream<Uint8Array, Uint8Array>();
527
535
  const writer = writable.getWriter();
@@ -542,7 +550,7 @@ export async function renderSSR(
542
550
  const [earlyBodyPost, finalBodyPost] = hasDeferred
543
551
  ? splitBeforeBodyClose(bodyPost)
544
552
  : ["", bodyPost];
545
- await writer.write(enc.encode(dataScript + earlyBodyPost));
553
+ await writer.write(enc.encode(runtimeScripts + earlyBodyPost));
546
554
 
547
555
  if (hasDeferred) {
548
556
  await Promise.all(
@@ -5,7 +5,7 @@ import { computeErrorDigest } from "../../shared/digest.ts";
5
5
  import type { SearchParamsInput, SearchRouteMetadata } from "../../shared/search-params.ts";
6
6
  import { autoInvalidateRegistry } from "../auto-invalidate/registry.ts";
7
7
  import { useLogger } from "../context-logger.ts";
8
- import { resolvePath } from "../render/assemble.ts";
8
+ import { injectSyncRuntimeScript, resolvePath } from "../render/assemble.ts";
9
9
  import {
10
10
  handleISR,
11
11
  prerenderSSG,
@@ -63,7 +63,7 @@ async function handleSSGRequest(
63
63
  ctx.set.headers.etag = etag;
64
64
  }
65
65
  ctx.set.headers["cache-tag"] = resolvedPath;
66
- return entry.html;
66
+ return injectSyncRuntimeScript(entry.html);
67
67
  }
68
68
 
69
69
  export function createRoutePlugin(
@@ -0,0 +1,65 @@
1
+ export interface StoredResponse {
2
+ body: Uint8Array;
3
+ headers: ReadonlyArray<readonly [string, string]>;
4
+ status: number;
5
+ }
6
+
7
+ export interface BeginMutationInput {
8
+ fingerprint: string;
9
+ key: string;
10
+ principal: string;
11
+ }
12
+
13
+ export type BeginMutationResult =
14
+ | { kind: "execute"; mutationId: string }
15
+ | { kind: "replay"; response: StoredResponse }
16
+ | { kind: "conflict"; reason: "in-progress" | "payload-mismatch" }
17
+ | { kind: "unavailable" };
18
+
19
+ export interface CommitMutationInput {
20
+ mutationId: string;
21
+ response: StoredResponse;
22
+ }
23
+
24
+ export interface AbortMutationInput {
25
+ mutationId: string;
26
+ }
27
+
28
+ export interface SyncChange {
29
+ cursor: string;
30
+ invalidations: readonly string[];
31
+ }
32
+
33
+ export interface AppendChangesInput {
34
+ invalidations: readonly string[];
35
+ path: string;
36
+ }
37
+
38
+ export interface AppendChangesResult {
39
+ change: SyncChange;
40
+ }
41
+
42
+ export interface ReadChangesInput {
43
+ after: string | undefined;
44
+ limit: number;
45
+ path: string;
46
+ }
47
+
48
+ export interface ChangePage {
49
+ changes: readonly SyncChange[];
50
+ cursor: string;
51
+ hasMore: boolean;
52
+ reset: boolean;
53
+ }
54
+
55
+ export type SyncChangeListener = (change: SyncChange) => void;
56
+ type MaybePromise<T> = Promise<T> | T;
57
+
58
+ export interface SyncAdapter {
59
+ abortMutation(input: AbortMutationInput): MaybePromise<void>;
60
+ appendChanges(input: AppendChangesInput): MaybePromise<AppendChangesResult>;
61
+ beginMutation(input: BeginMutationInput): MaybePromise<BeginMutationResult>;
62
+ commitMutation(input: CommitMutationInput): MaybePromise<void>;
63
+ readChanges(input: ReadChangesInput): MaybePromise<ChangePage>;
64
+ subscribe(path: string, listener: SyncChangeListener): () => void;
65
+ }
@@ -0,0 +1,29 @@
1
+ import { AsyncLocalStorage } from "node:async_hooks";
2
+
3
+ const SYNC_STREAM_DEFAULT_PATH = "/_furin/sync";
4
+
5
+ const requestSyncStreamPath = new AsyncLocalStorage<string | undefined>();
6
+
7
+ export type FurinSyncOption =
8
+ | boolean
9
+ | {
10
+ streamPath?: string;
11
+ };
12
+
13
+ export function resolveSyncStreamPath(sync: FurinSyncOption | undefined): string | undefined {
14
+ if (!sync) {
15
+ return;
16
+ }
17
+ if (sync === true) {
18
+ return SYNC_STREAM_DEFAULT_PATH;
19
+ }
20
+ return sync.streamPath ?? SYNC_STREAM_DEFAULT_PATH;
21
+ }
22
+
23
+ export function getSyncStreamPath(): string | undefined {
24
+ return requestSyncStreamPath.getStore();
25
+ }
26
+
27
+ export function runWithSyncStreamPath<T>(path: string | undefined, fn: () => T): T {
28
+ return requestSyncStreamPath.run(path, fn);
29
+ }
@@ -0,0 +1,44 @@
1
+ interface FingerprintInput {
2
+ body: unknown;
3
+ request: Request;
4
+ }
5
+
6
+ function compareCodePoints(left: string, right: string): number {
7
+ if (left === right) {
8
+ return 0;
9
+ }
10
+ return left < right ? -1 : 1;
11
+ }
12
+
13
+ function canonicalize(value: unknown): unknown {
14
+ if (Array.isArray(value)) {
15
+ return value.map(canonicalize);
16
+ }
17
+ if (value && typeof value === "object" && Object.getPrototypeOf(value) === Object.prototype) {
18
+ return Object.fromEntries(
19
+ Object.entries(value)
20
+ .sort(([left], [right]) => compareCodePoints(left, right))
21
+ .map(([key, entry]) => [key, canonicalize(entry)])
22
+ );
23
+ }
24
+ return value;
25
+ }
26
+
27
+ export async function createMutationFingerprint(input: FingerprintInput): Promise<string> {
28
+ const url = new URL(input.request.url);
29
+ const query = [...url.searchParams.entries()].sort(
30
+ ([leftKey, leftValue], [rightKey, rightValue]) =>
31
+ leftKey === rightKey
32
+ ? compareCodePoints(leftValue, rightValue)
33
+ : compareCodePoints(leftKey, rightKey)
34
+ );
35
+ const source = JSON.stringify({
36
+ body: canonicalize(input.body) ?? null,
37
+ contentType: input.request.headers.get("content-type") ?? "",
38
+ method: input.request.method,
39
+ pathname: url.pathname,
40
+ query,
41
+ });
42
+ const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(source));
43
+ return [...new Uint8Array(digest)].map((byte) => byte.toString(16).padStart(2, "0")).join("");
44
+ }
@@ -0,0 +1,15 @@
1
+ // biome-ignore-all lint/performance/noBarrelFile: sync has a small public/internal surface
2
+ export type { FurinSyncOption } from "./config.ts";
3
+ export {
4
+ getSyncStreamPath,
5
+ resolveSyncStreamPath,
6
+ runWithSyncStreamPath,
7
+ } from "./config.ts";
8
+ export { furinSync, type SyncInput, type SyncRouteOption } from "./plugin.ts";
9
+ export {
10
+ __resetSyncState,
11
+ createSyncStreamPlugin,
12
+ publishSyncInvalidation,
13
+ type SyncChange,
14
+ type SyncChangePage,
15
+ } from "./stream.ts";