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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (98) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +37 -33
  3. package/dist/adapter/bun.d.ts +17 -1
  4. package/dist/adapter/package.d.ts +26 -0
  5. package/dist/build/client.d.ts +1 -1
  6. package/dist/build/compile-entry.d.ts +3 -3
  7. package/dist/build/compile-entry.ts +114 -109
  8. package/dist/build/entry-template.d.ts +35 -9
  9. package/dist/build/entry-template.ts +206 -156
  10. package/dist/build/hydrate.d.ts +1 -1
  11. package/dist/build/index.js +643 -247
  12. package/dist/build/scan-server.d.ts +10 -4
  13. package/dist/build/server-routes-entry.d.ts +3 -3
  14. package/dist/build/server-routes-entry.ts +30 -36
  15. package/dist/build/ssg-cache.d.ts +1 -1
  16. package/dist/build/types.d.ts +36 -1
  17. package/dist/cli/config.d.ts +6 -1
  18. package/dist/cli/index.js +662 -260
  19. package/dist/client/link.js +163 -16
  20. package/dist/client/router/abort.d.ts +1 -0
  21. package/dist/client/router/sync-catch-up.d.ts +29 -0
  22. package/dist/config.d.ts +11 -2
  23. package/dist/config.js +5 -1
  24. package/dist/furin.d.ts +37 -19
  25. package/dist/furin.js +982 -378
  26. package/dist/server/auto-invalidate/registry.d.ts +8 -1
  27. package/dist/server/cache/dev-loader.d.ts +3 -2
  28. package/dist/server/cache/invalidation.d.ts +19 -0
  29. package/dist/server/cache/isr.d.ts +6 -2
  30. package/dist/server/cache/registry.d.ts +3 -3
  31. package/dist/server/cache/ssg.d.ts +6 -2
  32. package/dist/server/cache/store-view.d.ts +11 -0
  33. package/dist/server/instance.d.ts +86 -0
  34. package/dist/server/internal.d.ts +16 -1
  35. package/dist/server/internal.js +72 -5
  36. package/dist/server/render/template.d.ts +3 -2
  37. package/dist/server/sync/adapter.d.ts +62 -0
  38. package/dist/server/sync/config.d.ts +11 -0
  39. package/dist/server/sync/fingerprint.d.ts +6 -0
  40. package/dist/server/sync/index.d.ts +2 -2
  41. package/dist/server/sync/memory-adapter.d.ts +17 -0
  42. package/dist/server/sync/plugin.d.ts +12 -195
  43. package/dist/server/sync/response.d.ts +4 -0
  44. package/dist/server/sync/stream.d.ts +24 -5
  45. package/dist/shared/prefix.d.ts +15 -0
  46. package/package.json +6 -1
  47. package/src/adapter/README.md +13 -13
  48. package/src/adapter/bun.ts +113 -50
  49. package/src/adapter/package.ts +206 -0
  50. package/src/build/client.ts +158 -152
  51. package/src/build/compile-entry.ts +114 -109
  52. package/src/build/entry-template.ts +206 -156
  53. package/src/build/hydrate.ts +342 -340
  54. package/src/build/index.ts +223 -152
  55. package/src/build/route-types.ts +145 -145
  56. package/src/build/scan-server.ts +111 -95
  57. package/src/build/server-routes-entry.ts +30 -36
  58. package/src/build/shared.ts +80 -80
  59. package/src/build/ssg-cache.ts +36 -32
  60. package/src/build/types.ts +125 -89
  61. package/src/cli/config.ts +9 -3
  62. package/src/cli/index.ts +21 -3
  63. package/src/client/router/abort.ts +5 -0
  64. package/src/client/router/link-utils.ts +184 -184
  65. package/src/client/router/provider.tsx +883 -804
  66. package/src/client/router/sync-catch-up.ts +113 -0
  67. package/src/client/router/types.ts +276 -276
  68. package/src/client/sync.ts +98 -98
  69. package/src/client.ts +369 -369
  70. package/src/config.ts +14 -1
  71. package/src/furin.ts +619 -465
  72. package/src/server/auto-invalidate/registry.ts +23 -1
  73. package/src/server/auto-invalidate/runtime.ts +159 -134
  74. package/src/server/cache/dev-loader.ts +77 -38
  75. package/src/server/cache/invalidation.ts +71 -30
  76. package/src/server/cache/isr.ts +20 -5
  77. package/src/server/cache/registry.ts +17 -20
  78. package/src/server/cache/ssg.ts +19 -4
  79. package/src/server/cache/store-view.ts +30 -0
  80. package/src/server/dev-page-plugin.ts +454 -454
  81. package/src/server/instance.ts +252 -0
  82. package/src/server/internal.ts +100 -5
  83. package/src/server/render/assemble.ts +160 -160
  84. package/src/server/render/isr.ts +323 -323
  85. package/src/server/render/not-found.ts +9 -3
  86. package/src/server/render/ssr.ts +603 -585
  87. package/src/server/render/template.ts +57 -24
  88. package/src/server/router/plugin.ts +384 -384
  89. package/src/server/sync/adapter.ts +65 -0
  90. package/src/server/sync/config.ts +60 -29
  91. package/src/server/sync/fingerprint.ts +44 -0
  92. package/src/server/sync/index.ts +15 -14
  93. package/src/server/sync/memory-adapter.ts +196 -0
  94. package/src/server/sync/plugin.ts +199 -108
  95. package/src/server/sync/response.ts +77 -0
  96. package/src/server/sync/stream.ts +162 -144
  97. package/src/shared/deferred-ndjson.ts +7 -0
  98. package/src/shared/prefix.ts +38 -0
@@ -1,108 +1,199 @@
1
- import { type AfterHandler, 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 { publishSyncInvalidation } from "./stream.ts";
9
-
10
- export type SyncInput =
11
- | InvalidationInput
12
- | {
13
- invalidate: InvalidationInput;
14
- };
15
-
16
- type AnyHandlerContext = Parameters<AfterHandler>[0];
17
- interface IdempotencyContext {
18
- headers: {
19
- "idempotency-key"?: string | undefined;
20
- };
21
- request: Request;
22
- }
23
-
24
- function invalidationInputFromSync(input: SyncInput): InvalidationInput {
25
- if (input && typeof input === "object" && "invalidate" in input) {
26
- return input.invalidate;
27
- }
28
- return input;
29
- }
30
-
31
- function isMutationMethod(method: string): boolean {
32
- return method !== "GET" && method !== "HEAD" && method !== "OPTIONS";
33
- }
34
-
35
- function getIdempotencyKey(ctx: IdempotencyContext): string | undefined {
36
- const fromCtxHeaders = ctx.headers["idempotency-key"];
37
- if (typeof fromCtxHeaders === "string" && fromCtxHeaders.length > 0) {
38
- return fromCtxHeaders;
39
- }
40
- const fromRequest = ctx.request.headers.get("Idempotency-Key");
41
- return fromRequest || undefined;
42
- }
43
-
44
- export function furinSync() {
45
- const idempotencyKeys = new Set<string>();
46
- const requestKeys = new WeakMap<Request, string>();
47
- return new Elysia({ name: "furin-sync" }).macro({
48
- sync(input: SyncInput) {
49
- const invalidate = invalidationInputFromSync(input);
50
- return {
51
- beforeHandle(ctx) {
52
- if (!isMutationMethod(ctx.request.method)) {
53
- return;
54
- }
55
- const key = getIdempotencyKey(ctx);
56
- if (!key) {
57
- return new Response("Missing Idempotency-Key header", {
58
- status: 428,
59
- headers: { "content-type": "text/plain; charset=utf-8" },
60
- });
61
- }
62
- const requestKey = `${ctx.request.method}:${new URL(ctx.request.url).pathname}:${key}`;
63
- if (idempotencyKeys.has(requestKey)) {
64
- return new Response("Duplicate Idempotency-Key header", {
65
- status: 409,
66
- headers: { "content-type": "text/plain; charset=utf-8" },
67
- });
68
- }
69
- idempotencyKeys.add(requestKey);
70
- requestKeys.set(ctx.request, requestKey);
71
- if (idempotencyKeys.size > 1000) {
72
- const oldest = idempotencyKeys.values().next().value;
73
- if (typeof oldest === "string") {
74
- idempotencyKeys.delete(oldest);
75
- }
76
- }
77
- },
78
- afterHandle(ctx: AnyHandlerContext) {
79
- if (!isSuccessfulMutationResponse(ctx)) {
80
- const requestKey = requestKeys.get(ctx.request);
81
- if (requestKey) {
82
- idempotencyKeys.delete(requestKey);
83
- requestKeys.delete(ctx.request);
84
- }
85
- return;
86
- }
87
- requestKeys.delete(ctx.request);
88
-
89
- runInvalidationRules(invalidate);
90
- const pending = appendPendingInvalidationHeader(ctx.set);
91
- if (pending.length === 0) {
92
- return;
93
- }
94
-
95
- ctx.set.headers["x-furin-sync"] = "1";
96
- publishSyncInvalidation(pending);
97
- },
98
- error({ request }) {
99
- const requestKey = requestKeys.get(request);
100
- if (requestKey) {
101
- idempotencyKeys.delete(requestKey);
102
- requestKeys.delete(request);
103
- }
104
- },
105
- };
106
- },
107
- });
108
- }
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 { createMutationFingerprint } from "./fingerprint.ts";
9
+ import { memorySyncAdapter } from "./memory-adapter.ts";
10
+ import { replayResponse, storeResponse } from "./response.ts";
11
+ import { publishSyncInvalidation } from "./stream.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
+ // Notify every mounted app's sync stream — a mutation on a shared API
194
+ // may invalidate pages rendered by any of them.
195
+ publishSyncInvalidation(pending);
196
+ }
197
+ })
198
+ .onError({ as: "global" }, ({ request }) => abortMutation(request));
199
+ }
@@ -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
+ }