@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
@@ -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
+ }
@@ -1,29 +1,60 @@
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
- }
1
+ import { AsyncLocalStorage } from "node:async_hooks";
2
+ import { allInstances, currentInstance } from "../instance.ts";
3
+
4
+ const SYNC_STREAM_DEFAULT_PATH = "/_furin/sync";
5
+
6
+ // Explicit override scope (tests, synthetic renders). When unset, the sync
7
+ // stream path comes from the current furin instance.
8
+ const requestSyncStreamPath = new AsyncLocalStorage<string | undefined>();
9
+
10
+ export type FurinSyncOption =
11
+ | boolean
12
+ | {
13
+ streamPath?: string;
14
+ };
15
+
16
+ export function resolveSyncStreamPath(sync: FurinSyncOption | undefined): string | undefined {
17
+ if (!sync) {
18
+ return;
19
+ }
20
+ if (sync === true) {
21
+ return SYNC_STREAM_DEFAULT_PATH;
22
+ }
23
+ return sync.streamPath ?? SYNC_STREAM_DEFAULT_PATH;
24
+ }
25
+
26
+ /**
27
+ * Logical (unprefixed) sync stream path for the current request — injected
28
+ * into rendered HTML; the client prepends its own basePath before connecting.
29
+ */
30
+ export function getSyncStreamPath(): string | undefined {
31
+ const override = requestSyncStreamPath.getStore();
32
+ if (override !== undefined) {
33
+ return override;
34
+ }
35
+ return currentInstance().syncStreamPath;
36
+ }
37
+
38
+ export function runWithSyncStreamPath<T>(path: string | undefined, fn: () => T): T {
39
+ return requestSyncStreamPath.run(path, fn);
40
+ }
41
+
42
+ /**
43
+ * Physical adapter channels a sync publication must reach. An explicit
44
+ * override wins (historical single-channel behaviour); otherwise every
45
+ * sync-enabled instance gets notified — a mutation on a shared API must wake
46
+ * the SSE clients of every mounted app.
47
+ */
48
+ export function syncPublishChannels(): string[] {
49
+ const override = requestSyncStreamPath.getStore();
50
+ if (override !== undefined) {
51
+ return [override];
52
+ }
53
+ const channels = allInstances()
54
+ .filter((instance) => instance.syncStreamPath !== undefined)
55
+ .map((instance) => `${instance.prefix}${instance.syncStreamPath}`);
56
+ if (channels.length > 0) {
57
+ return channels;
58
+ }
59
+ return [SYNC_STREAM_DEFAULT_PATH];
60
+ }
@@ -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
+ }
@@ -1,14 +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 } from "./plugin.ts";
9
- export {
10
- __resetSyncState,
11
- createSyncStreamPlugin,
12
- publishSyncInvalidation,
13
- type SyncInvalidationEvent,
14
- } from "./stream.ts";
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";
@@ -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();