@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
@@ -0,0 +1,196 @@
1
+ import type {
2
+ AbortMutationInput,
3
+ AppendChangesInput,
4
+ AppendChangesResult,
5
+ BeginMutationInput,
6
+ BeginMutationResult,
7
+ ChangePage,
8
+ CommitMutationInput,
9
+ ReadChangesInput,
10
+ StoredResponse,
11
+ SyncAdapter,
12
+ SyncChange,
13
+ SyncChangeListener,
14
+ } from "./adapter.ts";
15
+
16
+ const MAX_CHANGES = 1000;
17
+ const MAX_MUTATIONS = 10_000;
18
+ const MUTATION_TTL_MS = 24 * 60 * 60 * 1000;
19
+
20
+ interface PendingMutation {
21
+ createdAt: number;
22
+ fingerprint: string;
23
+ mutationId: string;
24
+ state: "in-progress";
25
+ }
26
+
27
+ interface CompletedMutation {
28
+ createdAt: number;
29
+ fingerprint: string;
30
+ mutationId: string;
31
+ response: StoredResponse;
32
+ state: "succeeded";
33
+ }
34
+
35
+ type MutationEntry = CompletedMutation | PendingMutation;
36
+
37
+ interface ChangeState {
38
+ changes: SyncChange[];
39
+ listeners: Set<SyncChangeListener>;
40
+ nextCursor: number;
41
+ }
42
+
43
+ export class MemorySyncAdapter implements SyncAdapter {
44
+ private readonly changes = new Map<string, ChangeState>();
45
+ private readonly mutationKeys = new Map<string, string>();
46
+ private readonly mutations = new Map<string, MutationEntry>();
47
+
48
+ beginMutation(input: BeginMutationInput): BeginMutationResult {
49
+ this.evictMutations();
50
+ const mutationKey = `${input.principal}:${input.key}`;
51
+ const existingId = this.mutationKeys.get(mutationKey);
52
+ const existing = existingId ? this.mutations.get(existingId) : undefined;
53
+ if (existing) {
54
+ if (existing.fingerprint !== input.fingerprint) {
55
+ return { kind: "conflict", reason: "payload-mismatch" };
56
+ }
57
+ if (existing.state === "in-progress") {
58
+ return { kind: "conflict", reason: "in-progress" };
59
+ }
60
+ return { kind: "replay", response: existing.response };
61
+ }
62
+ if (this.mutations.size >= MAX_MUTATIONS) {
63
+ return { kind: "unavailable" };
64
+ }
65
+
66
+ const mutationId = crypto.randomUUID();
67
+ this.mutationKeys.set(mutationKey, mutationId);
68
+ this.mutations.set(mutationId, {
69
+ createdAt: Date.now(),
70
+ fingerprint: input.fingerprint,
71
+ mutationId,
72
+ state: "in-progress",
73
+ });
74
+ return { kind: "execute", mutationId };
75
+ }
76
+
77
+ commitMutation(input: CommitMutationInput): void {
78
+ const existing = this.mutations.get(input.mutationId);
79
+ if (!existing) {
80
+ return;
81
+ }
82
+ this.mutations.set(input.mutationId, {
83
+ ...existing,
84
+ response: input.response,
85
+ state: "succeeded",
86
+ });
87
+ }
88
+
89
+ abortMutation(input: AbortMutationInput): void {
90
+ const existing = this.mutations.get(input.mutationId);
91
+ if (!existing) {
92
+ return;
93
+ }
94
+ this.mutations.delete(input.mutationId);
95
+ for (const [key, mutationId] of this.mutationKeys) {
96
+ if (mutationId === input.mutationId) {
97
+ this.mutationKeys.delete(key);
98
+ break;
99
+ }
100
+ }
101
+ }
102
+
103
+ appendChanges(input: AppendChangesInput): AppendChangesResult {
104
+ const state = this.getChangeState(input.path);
105
+ const change: SyncChange = {
106
+ cursor: String(state.nextCursor),
107
+ invalidations: [...input.invalidations],
108
+ };
109
+ state.nextCursor += 1;
110
+ state.changes.push(change);
111
+ if (state.changes.length > MAX_CHANGES) {
112
+ state.changes.shift();
113
+ }
114
+ for (const listener of [...state.listeners]) {
115
+ listener(change);
116
+ }
117
+ return { change };
118
+ }
119
+
120
+ readChanges(input: ReadChangesInput): ChangePage {
121
+ const state = this.getChangeState(input.path);
122
+ const currentCursor = String(state.nextCursor - 1);
123
+ if (input.after === undefined) {
124
+ return { changes: [], cursor: currentCursor, hasMore: false, reset: false };
125
+ }
126
+
127
+ const after = Number.parseInt(input.after, 10);
128
+ const oldest = Number.parseInt(state.changes[0]?.cursor ?? currentCursor, 10);
129
+ if (after < oldest - 1) {
130
+ return {
131
+ changes: [{ cursor: currentCursor, invalidations: ["/:layout"] }],
132
+ cursor: currentCursor,
133
+ hasMore: false,
134
+ reset: true,
135
+ };
136
+ }
137
+ const available = state.changes.filter((change) => Number.parseInt(change.cursor, 10) > after);
138
+ const changes = available.slice(0, input.limit);
139
+ return {
140
+ changes,
141
+ cursor: changes.at(-1)?.cursor ?? input.after,
142
+ hasMore: available.length > changes.length,
143
+ reset: false,
144
+ };
145
+ }
146
+
147
+ subscribe(path: string, listener: SyncChangeListener): () => void {
148
+ const listeners = this.getChangeState(path).listeners;
149
+ listeners.add(listener);
150
+ return () => listeners.delete(listener);
151
+ }
152
+
153
+ reset(): void {
154
+ this.changes.clear();
155
+ this.mutationKeys.clear();
156
+ this.mutations.clear();
157
+ }
158
+
159
+ private evictMutations(): void {
160
+ const expiredBefore = Date.now() - MUTATION_TTL_MS;
161
+ for (const [mutationId, mutation] of this.mutations) {
162
+ if (mutation.createdAt < expiredBefore) {
163
+ this.deleteMutation(mutationId);
164
+ }
165
+ }
166
+ while (this.mutations.size >= MAX_MUTATIONS) {
167
+ const oldest = [...this.mutations.values()].find((entry) => entry.state === "succeeded");
168
+ if (!oldest) {
169
+ break;
170
+ }
171
+ this.deleteMutation(oldest.mutationId);
172
+ }
173
+ }
174
+
175
+ private deleteMutation(mutationId: string): void {
176
+ this.mutations.delete(mutationId);
177
+ for (const [key, storedId] of this.mutationKeys) {
178
+ if (storedId === mutationId) {
179
+ this.mutationKeys.delete(key);
180
+ return;
181
+ }
182
+ }
183
+ }
184
+
185
+ private getChangeState(path: string): ChangeState {
186
+ const existing = this.changes.get(path);
187
+ if (existing) {
188
+ return existing;
189
+ }
190
+ const state: ChangeState = { changes: [], listeners: new Set(), nextCursor: 1 };
191
+ this.changes.set(path, state);
192
+ return state;
193
+ }
194
+ }
195
+
196
+ export const memorySyncAdapter = new MemorySyncAdapter();
@@ -0,0 +1,200 @@
1
+ import { Elysia } from "elysia";
2
+ import {
3
+ appendPendingInvalidationHeader,
4
+ isSuccessfulMutationResponse,
5
+ runInvalidationRules,
6
+ } from "../auto-invalidate/runtime.ts";
7
+ import type { InvalidationInput } from "../auto-invalidate/types.ts";
8
+ import { getSyncStreamPath } from "./config.ts";
9
+ import { createMutationFingerprint } from "./fingerprint.ts";
10
+ import { memorySyncAdapter } from "./memory-adapter.ts";
11
+ import { replayResponse, storeResponse } from "./response.ts";
12
+
13
+ export type SyncRouteOption =
14
+ | false
15
+ | InvalidationInput
16
+ | {
17
+ invalidate: InvalidationInput;
18
+ };
19
+
20
+ /** @deprecated Use SyncRouteOption. */
21
+ export type SyncInput = Exclude<SyncRouteOption, false>;
22
+
23
+ interface RouteSyncMetadata {
24
+ disabled: boolean;
25
+ invalidate?: InvalidationInput;
26
+ }
27
+
28
+ interface ActiveMutation {
29
+ mutationId: string;
30
+ }
31
+
32
+ interface MutationContext {
33
+ body?: unknown;
34
+ headers: {
35
+ "idempotency-key"?: string | undefined;
36
+ };
37
+ request: Request;
38
+ }
39
+
40
+ const routeMetadata = new WeakMap<Request, RouteSyncMetadata>();
41
+ const activeMutations = new WeakMap<Request, ActiveMutation>();
42
+
43
+ function invalidationInputFromSync(input: Exclude<SyncRouteOption, false>): InvalidationInput {
44
+ if (input && typeof input === "object" && "invalidate" in input) {
45
+ return input.invalidate;
46
+ }
47
+ return input;
48
+ }
49
+
50
+ function isMutationMethod(method: string): boolean {
51
+ return method !== "GET" && method !== "HEAD" && method !== "OPTIONS";
52
+ }
53
+
54
+ function getIdempotencyKey(ctx: MutationContext): string | undefined {
55
+ const fromCtxHeaders = ctx.headers["idempotency-key"];
56
+ if (typeof fromCtxHeaders === "string" && fromCtxHeaders.length > 0) {
57
+ return fromCtxHeaders;
58
+ }
59
+ const fromRequest = ctx.request.headers.get("Idempotency-Key");
60
+ return fromRequest || undefined;
61
+ }
62
+
63
+ async function getPrincipalScope(request: Request): Promise<string> {
64
+ const authorization = request.headers.get("authorization");
65
+ const credentials = authorization
66
+ ? JSON.stringify(["authorization", authorization])
67
+ : JSON.stringify(["cookie", request.headers.get("cookie") ?? ""]);
68
+ const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(credentials));
69
+ return [...new Uint8Array(digest)].map((byte) => byte.toString(16).padStart(2, "0")).join("");
70
+ }
71
+
72
+ function supportsReplayBody(request: Request): boolean {
73
+ const contentType = request.headers.get("content-type")?.toLowerCase();
74
+ const mediaType = contentType?.split(";", 1)[0]?.trim();
75
+ return (
76
+ contentType === undefined ||
77
+ mediaType === "application/json" ||
78
+ (mediaType?.startsWith("application/") === true && mediaType.endsWith("+json")) ||
79
+ contentType.startsWith("application/x-www-form-urlencoded") ||
80
+ contentType.startsWith("text/")
81
+ );
82
+ }
83
+
84
+ function conflictResponse(reason: "in-progress" | "payload-mismatch"): Response {
85
+ const inProgress = reason === "in-progress";
86
+ return Response.json(
87
+ {
88
+ code: inProgress ? "FURIN_MUTATION_IN_PROGRESS" : "FURIN_IDEMPOTENCY_MISMATCH",
89
+ message: inProgress
90
+ ? "A mutation with this Idempotency-Key is still running."
91
+ : "The Idempotency-Key was already used with a different request.",
92
+ },
93
+ {
94
+ status: 409,
95
+ headers: inProgress ? { "retry-after": "1" } : undefined,
96
+ }
97
+ );
98
+ }
99
+
100
+ async function beginMutation(ctx: MutationContext): Promise<Response | undefined> {
101
+ if (!isMutationMethod(ctx.request.method) || routeMetadata.get(ctx.request)?.disabled) {
102
+ return;
103
+ }
104
+ const idempotencyKey = getIdempotencyKey(ctx);
105
+ if (!idempotencyKey) {
106
+ return new Response("Missing Idempotency-Key header", {
107
+ status: 428,
108
+ headers: { "content-type": "text/plain; charset=utf-8" },
109
+ });
110
+ }
111
+ if (!supportsReplayBody(ctx.request)) {
112
+ return Response.json(
113
+ {
114
+ code: "FURIN_UNSUPPORTED_SYNC_BODY",
115
+ message: "This request body cannot be replayed. Set sync: false on the route.",
116
+ },
117
+ { status: 415 }
118
+ );
119
+ }
120
+
121
+ const url = new URL(ctx.request.url);
122
+ const principal = await getPrincipalScope(ctx.request);
123
+ const key = `${ctx.request.method}:${url.pathname}:${idempotencyKey}`;
124
+ const fingerprint = await createMutationFingerprint({ body: ctx.body, request: ctx.request });
125
+ const result = await memorySyncAdapter.beginMutation({ fingerprint, key, principal });
126
+ if (result.kind === "replay") {
127
+ return replayResponse(result.response);
128
+ }
129
+ if (result.kind === "conflict") {
130
+ return conflictResponse(result.reason);
131
+ }
132
+ if (result.kind === "unavailable") {
133
+ return Response.json(
134
+ {
135
+ code: "FURIN_SYNC_CAPACITY_EXCEEDED",
136
+ message: "The mutation replay store is temporarily full.",
137
+ },
138
+ { headers: { "retry-after": "1" }, status: 503 }
139
+ );
140
+ }
141
+ activeMutations.set(ctx.request, { mutationId: result.mutationId });
142
+ }
143
+
144
+ async function abortMutation(request: Request): Promise<void> {
145
+ const active = activeMutations.get(request);
146
+ if (!active) {
147
+ return;
148
+ }
149
+ activeMutations.delete(request);
150
+ await memorySyncAdapter.abortMutation(active);
151
+ }
152
+
153
+ export function furinSync() {
154
+ return new Elysia({ name: "furin-sync" })
155
+ .macro({
156
+ sync(input: SyncRouteOption) {
157
+ return {
158
+ transform({ request }) {
159
+ routeMetadata.set(
160
+ request,
161
+ input === false
162
+ ? { disabled: true }
163
+ : { disabled: false, invalidate: invalidationInputFromSync(input) }
164
+ );
165
+ },
166
+ };
167
+ },
168
+ })
169
+ .onBeforeHandle({ as: "global" }, beginMutation)
170
+ .onAfterHandle({ as: "global" }, async (ctx) => {
171
+ const active = activeMutations.get(ctx.request);
172
+ if (!active) {
173
+ return;
174
+ }
175
+ if (!isSuccessfulMutationResponse(ctx)) {
176
+ await abortMutation(ctx.request);
177
+ return;
178
+ }
179
+
180
+ const invalidate = routeMetadata.get(ctx.request)?.invalidate;
181
+ if (invalidate) {
182
+ runInvalidationRules(invalidate);
183
+ }
184
+ const pending = appendPendingInvalidationHeader(ctx.set);
185
+ if (pending.length > 0) {
186
+ ctx.set.headers["x-furin-sync"] = "1";
187
+ }
188
+ const response = await storeResponse(ctx.responseValue, ctx.set);
189
+ await memorySyncAdapter.commitMutation({ ...active, response });
190
+ activeMutations.delete(ctx.request);
191
+
192
+ if (pending.length > 0) {
193
+ await memorySyncAdapter.appendChanges({
194
+ invalidations: pending,
195
+ path: getSyncStreamPath() ?? "/_furin/sync",
196
+ });
197
+ }
198
+ })
199
+ .onError({ as: "global" }, ({ request }) => abortMutation(request));
200
+ }
@@ -0,0 +1,77 @@
1
+ import { type Context, ElysiaCustomStatusResponse, StatusMap } from "elysia";
2
+ import type { StoredResponse } from "./adapter.ts";
3
+
4
+ const HOP_BY_HOP_HEADERS = new Set(["connection", "keep-alive", "transfer-encoding", "upgrade"]);
5
+
6
+ function statusCode(status: Context["set"]["status"]): number {
7
+ if (typeof status === "number") {
8
+ return status;
9
+ }
10
+ return status === undefined ? 200 : StatusMap[status];
11
+ }
12
+
13
+ function unwrapStatusResponse(value: unknown): { status: number; value: unknown } | undefined {
14
+ if (!(value instanceof ElysiaCustomStatusResponse)) {
15
+ return;
16
+ }
17
+ return { status: value.code, value: value.response };
18
+ }
19
+
20
+ function responseHeaders(headers: Context["set"]["headers"]): Headers {
21
+ const result = new Headers();
22
+ for (const [name, value] of Object.entries(headers)) {
23
+ if (value !== undefined && !HOP_BY_HOP_HEADERS.has(name.toLowerCase())) {
24
+ for (const entry of Array.isArray(value) ? value : [value]) {
25
+ result.append(name, String(entry));
26
+ }
27
+ }
28
+ }
29
+ return result;
30
+ }
31
+
32
+ export async function storeResponse(
33
+ responseValue: unknown,
34
+ set: Context["set"]
35
+ ): Promise<StoredResponse> {
36
+ if (responseValue instanceof Response) {
37
+ const clone = responseValue.clone();
38
+ const headers = [...clone.headers.entries()].filter(
39
+ ([name]) => !HOP_BY_HOP_HEADERS.has(name.toLowerCase())
40
+ );
41
+ return {
42
+ body: new Uint8Array(await clone.arrayBuffer()),
43
+ headers,
44
+ status: clone.status,
45
+ };
46
+ }
47
+
48
+ const headers = responseHeaders(set.headers);
49
+ const statusResponse = unwrapStatusResponse(responseValue);
50
+ const value = statusResponse?.value ?? responseValue;
51
+ let body: Uint8Array;
52
+ if (value === undefined || value === null) {
53
+ body = new Uint8Array();
54
+ } else if (typeof value === "string") {
55
+ headers.set("content-type", headers.get("content-type") ?? "text/plain;charset=utf-8");
56
+ body = new TextEncoder().encode(value);
57
+ } else {
58
+ headers.set("content-type", headers.get("content-type") ?? "application/json");
59
+ body = new TextEncoder().encode(JSON.stringify(value));
60
+ }
61
+ return {
62
+ body,
63
+ headers: [...headers.entries()],
64
+ status: statusResponse?.status ?? statusCode(set.status),
65
+ };
66
+ }
67
+
68
+ export function replayResponse(stored: StoredResponse): Response {
69
+ const body =
70
+ stored.status === 204 || stored.status === 205 || stored.status === 304
71
+ ? null
72
+ : stored.body.slice();
73
+ return new Response(body, {
74
+ headers: new Headers(stored.headers.map(([name, value]) => [name, value] as [string, string])),
75
+ status: stored.status,
76
+ });
77
+ }
@@ -0,0 +1,152 @@
1
+ import { Elysia } from "elysia";
2
+ import type { SyncChange } from "./adapter.ts";
3
+ import { getSyncStreamPath } from "./config.ts";
4
+ import { memorySyncAdapter } from "./memory-adapter.ts";
5
+
6
+ export type { ChangePage as SyncChangePage, SyncChange } from "./adapter.ts";
7
+
8
+ const DEFAULT_CHANGE_LIMIT = 100;
9
+ const MAX_CHANGE_LIMIT = 500;
10
+ const CURSOR_PATTERN = /^\d+$/;
11
+ const defaultStreamPath = "/_furin/sync";
12
+ const encoder = new TextEncoder();
13
+
14
+ interface StreamState {
15
+ clients: Set<ReadableStreamDefaultController<Uint8Array>>;
16
+ heartbeats: Set<ReturnType<typeof setInterval>>;
17
+ unsubscribe: (() => void) | undefined;
18
+ }
19
+
20
+ const streams = new Map<string, StreamState>();
21
+
22
+ function encodeSseChange(change: SyncChange): Uint8Array {
23
+ return encoder.encode(
24
+ `id: ${change.cursor}\nevent: furin.sync\nretry: 3000\ndata: ${JSON.stringify({ cursor: change.cursor })}\n\n`
25
+ );
26
+ }
27
+
28
+ function getStreamState(path: string): StreamState {
29
+ const existing = streams.get(path);
30
+ if (existing) {
31
+ return existing;
32
+ }
33
+ const state: StreamState = {
34
+ clients: new Set(),
35
+ heartbeats: new Set(),
36
+ unsubscribe: undefined,
37
+ };
38
+ state.unsubscribe = memorySyncAdapter.subscribe(path, (change) => {
39
+ const chunk = encodeSseChange(change);
40
+ for (const client of [...state.clients]) {
41
+ try {
42
+ client.enqueue(chunk);
43
+ } catch {
44
+ state.clients.delete(client);
45
+ }
46
+ }
47
+ });
48
+ streams.set(path, state);
49
+ return state;
50
+ }
51
+
52
+ function parseChangeQuery(
53
+ request: Request
54
+ ): { after: string | undefined; limit: number } | { error: Response } {
55
+ const url = new URL(request.url);
56
+ const after = url.searchParams.get("after") ?? undefined;
57
+ if (after !== undefined && !CURSOR_PATTERN.test(after)) {
58
+ return { error: Response.json({ code: "FURIN_INVALID_SYNC_CURSOR" }, { status: 400 }) };
59
+ }
60
+ const limitValue = url.searchParams.get("limit");
61
+ if (limitValue !== null && !CURSOR_PATTERN.test(limitValue)) {
62
+ return { error: Response.json({ code: "FURIN_INVALID_SYNC_LIMIT" }, { status: 400 }) };
63
+ }
64
+ const limit = limitValue === null ? DEFAULT_CHANGE_LIMIT : Number.parseInt(limitValue, 10);
65
+ if (!Number.isInteger(limit) || limit < 1 || limit > MAX_CHANGE_LIMIT) {
66
+ return { error: Response.json({ code: "FURIN_INVALID_SYNC_LIMIT" }, { status: 400 }) };
67
+ }
68
+ return { after, limit };
69
+ }
70
+
71
+ export function publishSyncInvalidation(invalidations: readonly string[]): void {
72
+ if (invalidations.length === 0) {
73
+ return;
74
+ }
75
+ memorySyncAdapter.appendChanges({
76
+ invalidations,
77
+ path: getSyncStreamPath() ?? defaultStreamPath,
78
+ });
79
+ }
80
+
81
+ export function createSyncStreamPlugin(path?: string) {
82
+ const streamPath = path ?? defaultStreamPath;
83
+ return new Elysia({ name: `furin-sync-stream-${streamPath}` })
84
+ .get(`${streamPath}/changes`, ({ request, set }) => {
85
+ set.headers["cache-control"] = "no-store";
86
+ const query = parseChangeQuery(request);
87
+ if ("error" in query) {
88
+ return query.error;
89
+ }
90
+ return memorySyncAdapter.readChanges({ ...query, path: streamPath });
91
+ })
92
+ .get(streamPath, () => {
93
+ const state = getStreamState(streamPath);
94
+ let controllerRef: ReadableStreamDefaultController<Uint8Array> | undefined;
95
+ let heartbeat: ReturnType<typeof setInterval> | undefined;
96
+ const stream = new ReadableStream<Uint8Array>({
97
+ start(controller) {
98
+ controllerRef = controller;
99
+ state.clients.add(controller);
100
+ controller.enqueue(encoder.encode(": connected\nretry: 3000\n\n"));
101
+ heartbeat = setInterval(() => {
102
+ try {
103
+ controller.enqueue(encoder.encode(": heartbeat\n\n"));
104
+ } catch {
105
+ state.clients.delete(controller);
106
+ if (heartbeat) {
107
+ clearInterval(heartbeat);
108
+ state.heartbeats.delete(heartbeat);
109
+ }
110
+ }
111
+ }, 15_000);
112
+ state.heartbeats.add(heartbeat);
113
+ },
114
+ cancel() {
115
+ if (controllerRef) {
116
+ state.clients.delete(controllerRef);
117
+ }
118
+ if (heartbeat) {
119
+ clearInterval(heartbeat);
120
+ state.heartbeats.delete(heartbeat);
121
+ }
122
+ },
123
+ });
124
+
125
+ return new Response(stream, {
126
+ headers: {
127
+ "cache-control": "no-cache, no-transform",
128
+ connection: "keep-alive",
129
+ "content-type": "text/event-stream; charset=utf-8",
130
+ },
131
+ });
132
+ });
133
+ }
134
+
135
+ /** @internal — resets process-local sync state between tests. */
136
+ export function __resetSyncState(): void {
137
+ for (const state of streams.values()) {
138
+ state.unsubscribe?.();
139
+ for (const heartbeat of state.heartbeats) {
140
+ clearInterval(heartbeat);
141
+ }
142
+ for (const client of state.clients) {
143
+ try {
144
+ client.close();
145
+ } catch {
146
+ // already closed
147
+ }
148
+ }
149
+ }
150
+ streams.clear();
151
+ memorySyncAdapter.reset();
152
+ }
@@ -149,6 +149,13 @@ export async function parseDeferredNdjson(
149
149
  }
150
150
  }
151
151
 
152
+ // A superseded navigation may discard deferred values before React observes
153
+ // them. Mark each rejection as handled without changing the original
154
+ // promise, so consumers that do await it still receive the same error.
155
+ for (const promise of Object.values(deferredPromises)) {
156
+ promise.catch(() => undefined);
157
+ }
158
+
152
159
  if (deferredKeys.length === 0) {
153
160
  cleanupAbortHandler();
154
161
  try {