@teyik0/furin 0.2.0-alpha.1 → 0.2.0-alpha.3
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.
- package/LICENSE +21 -21
- package/README.md +33 -33
- package/dist/adapter/static.d.ts +1 -1
- package/dist/build/compile-entry.ts +109 -109
- package/dist/build/entry-template.ts +156 -156
- package/dist/build/index.js +1724 -687
- package/dist/build/route-types.d.ts +3 -1
- package/dist/build/server-routes-entry.ts +36 -36
- package/dist/build/shared.d.ts +1 -0
- package/dist/build/ssg-cache.d.ts +1 -1
- package/dist/cli/index.js +1673 -658
- package/dist/client/link.js +883 -89
- package/dist/client/router/index.d.ts +4 -0
- package/dist/client/router/link-utils.d.ts +3 -1
- package/dist/client/router/navigation.d.ts +10 -0
- package/dist/client/router/provider.d.ts +1 -1
- package/dist/client/router/search/index.d.ts +18 -0
- package/dist/client/router/search-store.d.ts +21 -0
- package/dist/client/router/types.d.ts +14 -1
- package/dist/client/sync.d.ts +25 -0
- package/dist/client.d.ts +1 -0
- package/dist/client.js +44 -0
- package/dist/furin.d.ts +9 -1
- package/dist/furin.js +1578 -258
- package/dist/server/auto-invalidate/runtime.d.ts +1 -1
- package/dist/server/dev-page-plugin.d.ts +3 -0
- package/dist/server/render/assemble.d.ts +2 -0
- package/dist/server/render/isr.d.ts +2 -1
- package/dist/server/render/ssg.d.ts +3 -2
- package/dist/server/render/ssr.d.ts +5 -4
- package/dist/server/router/hmr.d.ts +4 -3
- package/dist/server/router/index.d.ts +1 -1
- package/dist/server/router/index.js +1 -2
- package/dist/server/router/index.ts +1 -2
- package/dist/server/router/plugin.d.ts +2 -1
- package/dist/server/router/schemas.d.ts +25 -17
- package/dist/server/sync/config.d.ts +6 -0
- package/dist/server/sync/index.d.ts +4 -0
- package/dist/server/sync/plugin.d.ts +369 -0
- package/dist/server/sync/stream.d.ts +47 -0
- package/dist/shared/search-params.d.ts +17 -0
- package/package.json +10 -5
- package/src/adapter/README.md +13 -13
- package/src/adapter/static.ts +23 -6
- package/src/build/client.ts +152 -149
- package/src/build/compile-entry.ts +109 -109
- package/src/build/entry-template.ts +156 -156
- package/src/build/hydrate.ts +340 -331
- package/src/build/index.ts +152 -152
- package/src/build/route-types.ts +145 -115
- package/src/build/scan-server.ts +95 -95
- package/src/build/server-routes-entry.ts +36 -36
- package/src/build/shared.ts +80 -78
- package/src/build/ssg-cache.ts +32 -31
- package/src/build/types.ts +89 -89
- package/src/client/link.tsx +13 -4
- package/src/client/router/context.ts +2 -0
- package/src/client/router/index.ts +9 -0
- package/src/client/router/link-utils.ts +184 -180
- package/src/client/router/navigation.ts +61 -0
- package/src/client/router/provider.tsx +804 -723
- package/src/client/router/search/index.ts +99 -0
- package/src/client/router/search-store.ts +86 -0
- package/src/client/router/types.ts +276 -263
- package/src/client/sync.ts +98 -0
- package/src/client.ts +369 -355
- package/src/furin.ts +465 -437
- package/src/server/auto-invalidate/runtime.ts +134 -133
- package/src/server/dev-page-plugin.ts +454 -449
- package/src/server/render/assemble.ts +160 -133
- package/src/server/render/isr.ts +323 -295
- package/src/server/render/not-found.ts +2 -0
- package/src/server/render/ssg.ts +15 -4
- package/src/server/render/ssr.ts +585 -545
- package/src/server/router/hmr.ts +14 -10
- package/src/server/router/index.ts +1 -2
- package/src/server/router/patterns.ts +5 -0
- package/src/server/router/plugin.ts +384 -401
- package/src/server/router/schemas.ts +172 -57
- package/src/server/sync/config.ts +29 -0
- package/src/server/sync/index.ts +14 -0
- package/src/server/sync/plugin.ts +108 -0
- package/src/server/sync/stream.ts +144 -0
- package/src/shared/search-params.ts +182 -0
|
@@ -1,54 +1,21 @@
|
|
|
1
|
-
import type { Context } from "elysia";
|
|
2
1
|
import { t } from "elysia";
|
|
2
|
+
import { parseQueryFromURL, parseQueryStandardSchema } from "elysia/parse-query";
|
|
3
|
+
import { getSchemaValidator } from "elysia/schema";
|
|
3
4
|
import type { AnySchema } from "elysia/types";
|
|
4
5
|
import type { RuntimeRoute } from "../../client.ts";
|
|
6
|
+
import {
|
|
7
|
+
collectSearchDefaults,
|
|
8
|
+
type SearchParamsInput,
|
|
9
|
+
type SearchRouteMetadata,
|
|
10
|
+
} from "../../shared/search-params.ts";
|
|
11
|
+
import { buildRouteRegex } from "./patterns.ts";
|
|
5
12
|
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
// contains keys absent from the URL, defaults were applied → 302 redirect to
|
|
10
|
-
// the canonical URL so the address bar always reflects the actual app state.
|
|
11
|
-
|
|
12
|
-
/**
|
|
13
|
-
* Detects whether a validator filled in default query values that the original
|
|
14
|
-
* URL did not carry, and returns the canonical `pathname + search` to redirect
|
|
15
|
-
* to — or `undefined` when the URL already reflects the resolved query.
|
|
16
|
-
*
|
|
17
|
-
* Pure helper extracted from `queryDefaultRedirectHook` so the `/_furin/data`
|
|
18
|
-
* NDJSON endpoint can detect the same condition without going through
|
|
19
|
-
* Elysia's `status()` shim (which only emits HTTP 302s, unparseable by the
|
|
20
|
-
* SPA client).
|
|
21
|
-
*
|
|
22
|
-
* @internal Exported for unit testing.
|
|
23
|
-
*/
|
|
24
|
-
export function detectQueryDefaultRedirect(
|
|
25
|
-
request: Request,
|
|
26
|
-
resolvedQuery: Record<string, unknown>
|
|
27
|
-
): string | undefined {
|
|
28
|
-
const queryKeys = Object.keys(resolvedQuery);
|
|
29
|
-
if (queryKeys.length === 0) {
|
|
30
|
-
return;
|
|
31
|
-
}
|
|
32
|
-
|
|
33
|
-
const rawParams = new URL(request.url).searchParams;
|
|
34
|
-
let needsRedirect = false;
|
|
35
|
-
for (const key of queryKeys) {
|
|
36
|
-
if (!rawParams.has(key) && resolvedQuery[key] != null) {
|
|
37
|
-
needsRedirect = true;
|
|
38
|
-
break;
|
|
39
|
-
}
|
|
40
|
-
}
|
|
41
|
-
if (!needsRedirect) {
|
|
42
|
-
return;
|
|
43
|
-
}
|
|
13
|
+
interface UnknownObject {
|
|
14
|
+
[key: string]: unknown;
|
|
15
|
+
}
|
|
44
16
|
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
if (v != null) {
|
|
48
|
-
url.searchParams.set(k, String(v));
|
|
49
|
-
}
|
|
50
|
-
}
|
|
51
|
-
return url.pathname + url.search;
|
|
17
|
+
interface QueryKeyMap {
|
|
18
|
+
[key: string]: 1;
|
|
52
19
|
}
|
|
53
20
|
|
|
54
21
|
/**
|
|
@@ -80,19 +47,143 @@ export function parseDataEndpointPath(rawPath: string): { url: URL; pathname: st
|
|
|
80
47
|
return { url, pathname: url.pathname };
|
|
81
48
|
}
|
|
82
49
|
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
50
|
+
function isObjectSchema(schema: unknown): schema is UnknownObject {
|
|
51
|
+
return !!schema && typeof schema === "object";
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
function isStandardSchema(schema: unknown): boolean {
|
|
55
|
+
return isObjectSchema(schema) && "~standard" in schema;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
function collectQueryArrayKeys(schema: unknown): QueryKeyMap | undefined {
|
|
59
|
+
if (!(isObjectSchema(schema) && isObjectSchema(schema.properties))) {
|
|
60
|
+
return;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
const keys: QueryKeyMap = {};
|
|
64
|
+
for (const [key, value] of Object.entries(schema.properties)) {
|
|
65
|
+
const effectiveSchema = findEffectiveAnyOfMember(value, "array") ?? value;
|
|
66
|
+
if (isObjectSchema(effectiveSchema) && effectiveSchema.type === "array") {
|
|
67
|
+
keys[key] = 1;
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
return Object.keys(keys).length > 0 ? keys : undefined;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
function collectQueryObjectKeys(schema: unknown): QueryKeyMap | undefined {
|
|
75
|
+
if (!(isObjectSchema(schema) && isObjectSchema(schema.properties))) {
|
|
87
76
|
return;
|
|
88
77
|
}
|
|
89
|
-
|
|
90
|
-
|
|
78
|
+
|
|
79
|
+
const keys: QueryKeyMap = {};
|
|
80
|
+
for (const [key, value] of Object.entries(schema.properties)) {
|
|
81
|
+
const effectiveSchema = findEffectiveAnyOfMember(value, "object") ?? value;
|
|
82
|
+
if (isObjectSchema(effectiveSchema) && effectiveSchema.type === "object") {
|
|
83
|
+
keys[key] = 1;
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
return Object.keys(keys).length > 0 ? keys : undefined;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
function findEffectiveAnyOfMember(
|
|
91
|
+
schema: unknown,
|
|
92
|
+
type: "array" | "object"
|
|
93
|
+
): UnknownObject | undefined {
|
|
94
|
+
if (!(isObjectSchema(schema) && Array.isArray(schema.anyOf))) {
|
|
95
|
+
return;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
for (const member of schema.anyOf) {
|
|
99
|
+
if (isObjectSchema(member) && member.type === type) {
|
|
100
|
+
return member;
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
function parseJsonQueryObjects(
|
|
106
|
+
query: UnknownObject,
|
|
107
|
+
objectKeys: QueryKeyMap | undefined
|
|
108
|
+
): UnknownObject {
|
|
109
|
+
if (!objectKeys) {
|
|
110
|
+
return query;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
const parsed = { ...query };
|
|
114
|
+
for (const key of Object.keys(objectKeys)) {
|
|
115
|
+
const value = parsed[key];
|
|
116
|
+
if (typeof value !== "string") {
|
|
117
|
+
continue;
|
|
118
|
+
}
|
|
119
|
+
try {
|
|
120
|
+
parsed[key] = JSON.parse(value);
|
|
121
|
+
} catch {
|
|
122
|
+
parsed[key] = value;
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
return parsed;
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
export type ParseRouteQueryResult =
|
|
129
|
+
| { ok: true; query: SearchParamsInput }
|
|
130
|
+
| { errors: unknown; ok: false };
|
|
131
|
+
|
|
132
|
+
/**
|
|
133
|
+
* Parses and validates a logical route URL's search string for the synthetic
|
|
134
|
+
* `/_furin/data` request path. This keeps SPA navigations aligned with the
|
|
135
|
+
* Elysia guard used by the full SSR route.
|
|
136
|
+
*
|
|
137
|
+
* @internal Exported for unit testing.
|
|
138
|
+
*/
|
|
139
|
+
export async function parseRouteQuery(
|
|
140
|
+
url: URL,
|
|
141
|
+
schema: AnySchema | undefined
|
|
142
|
+
): Promise<ParseRouteQueryResult> {
|
|
143
|
+
if (!schema) {
|
|
144
|
+
return { ok: true, query: parseQueryFromURL(url.search, 1) as SearchParamsInput };
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
if (isStandardSchema(schema)) {
|
|
148
|
+
const rawQuery = parseQueryStandardSchema(url.search, 1) as UnknownObject;
|
|
149
|
+
const validator = getSchemaValidator(schema, { dynamic: true });
|
|
150
|
+
const checked = await validator?.Check(rawQuery);
|
|
151
|
+
if (checked && typeof checked === "object" && "issues" in checked) {
|
|
152
|
+
return { errors: checked.issues, ok: false };
|
|
153
|
+
}
|
|
154
|
+
if (checked && typeof checked === "object" && "value" in checked) {
|
|
155
|
+
return { ok: true, query: checked.value as SearchParamsInput };
|
|
156
|
+
}
|
|
157
|
+
return { ok: true, query: rawQuery as SearchParamsInput };
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
const rawQuery = parseJsonQueryObjects(
|
|
161
|
+
parseQueryFromURL(url.search, 1, collectQueryArrayKeys(schema)) as UnknownObject,
|
|
162
|
+
collectQueryObjectKeys(schema)
|
|
163
|
+
);
|
|
164
|
+
const queryWithDefaults = applySchemaDefaults(schema as UnknownObject, rawQuery);
|
|
165
|
+
const validator = getSchemaValidator(schema, { coerce: true, dynamic: true });
|
|
166
|
+
if (validator?.Check(queryWithDefaults) === false) {
|
|
167
|
+
return { errors: [...(validator?.Errors(queryWithDefaults) ?? [])], ok: false };
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
return {
|
|
171
|
+
ok: true,
|
|
172
|
+
query: (validator?.parse(queryWithDefaults) ?? queryWithDefaults) as SearchParamsInput,
|
|
173
|
+
};
|
|
91
174
|
}
|
|
92
175
|
|
|
93
176
|
// Standard structural keys on a TObject — everything else is a user-supplied option
|
|
94
177
|
// (e.g. additionalProperties, $id, description, title) and must be preserved.
|
|
95
178
|
const TOBJECT_STRUCTURAL_KEYS = new Set(["type", "properties", "required"]);
|
|
179
|
+
const TYPEBOX_KIND = Symbol.for("TypeBox.Kind");
|
|
180
|
+
|
|
181
|
+
function isTypeBoxObjectSchema(schema: unknown): schema is UnknownObject {
|
|
182
|
+
return (
|
|
183
|
+
isObjectSchema(schema) &&
|
|
184
|
+
(schema as UnknownObject & { [key: symbol]: unknown })[TYPEBOX_KIND] === "Object"
|
|
185
|
+
);
|
|
186
|
+
}
|
|
96
187
|
|
|
97
188
|
/**
|
|
98
189
|
* Merges TObject schemas from all routeChain entries for a given key.
|
|
@@ -116,6 +207,12 @@ export function mergeRouteSchemas(
|
|
|
116
207
|
return schemas[0] as AnySchema;
|
|
117
208
|
}
|
|
118
209
|
|
|
210
|
+
if (schemas.some((s) => !isTypeBoxObjectSchema(s))) {
|
|
211
|
+
throw new Error(
|
|
212
|
+
`[furin] Merging ${key} schemas across the route chain requires TypeBox in V1. Use TypeBox for parent/child ${key}, or define ${key} only on leaf routes.`
|
|
213
|
+
);
|
|
214
|
+
}
|
|
215
|
+
|
|
119
216
|
const mergedProperties = Object.assign(
|
|
120
217
|
{},
|
|
121
218
|
...schemas.map((s) => (s.properties as Record<string, unknown>) ?? {})
|
|
@@ -131,24 +228,42 @@ export function mergeRouteSchemas(
|
|
|
131
228
|
return t.Object(mergedProperties, mergedOptions) as AnySchema;
|
|
132
229
|
}
|
|
133
230
|
|
|
231
|
+
export function createSearchRouteMetadata(
|
|
232
|
+
routes: Array<{ pattern: string; routeChain: RuntimeRoute[] }>
|
|
233
|
+
): SearchRouteMetadata[] {
|
|
234
|
+
const metadata: SearchRouteMetadata[] = [];
|
|
235
|
+
for (const route of routes) {
|
|
236
|
+
const searchDefaults = collectSearchDefaults(mergeRouteSchemas(route.routeChain, "query"));
|
|
237
|
+
if (!searchDefaults) {
|
|
238
|
+
continue;
|
|
239
|
+
}
|
|
240
|
+
metadata.push({
|
|
241
|
+
pattern: route.pattern,
|
|
242
|
+
regex: buildRouteRegex(route.pattern).regex,
|
|
243
|
+
searchDefaults,
|
|
244
|
+
});
|
|
245
|
+
}
|
|
246
|
+
return metadata;
|
|
247
|
+
}
|
|
248
|
+
|
|
134
249
|
/**
|
|
135
250
|
* Applies top-level `default` values from a TypeBox TObject schema to a
|
|
136
251
|
* values record. Used in the `/_furin/data` endpoint so loaders see the same
|
|
137
252
|
* defaulted query objects that the SSR path produces via Elysia's guard.
|
|
138
253
|
*/
|
|
139
254
|
export function applySchemaDefaults(
|
|
140
|
-
schema:
|
|
141
|
-
values:
|
|
142
|
-
):
|
|
255
|
+
schema: UnknownObject | undefined,
|
|
256
|
+
values: UnknownObject
|
|
257
|
+
): UnknownObject {
|
|
143
258
|
if (!schema || typeof schema !== "object") {
|
|
144
259
|
return values;
|
|
145
260
|
}
|
|
146
|
-
const s = schema
|
|
261
|
+
const s = schema;
|
|
147
262
|
if (s.type !== "object" || !s.properties || typeof s.properties !== "object") {
|
|
148
263
|
return values;
|
|
149
264
|
}
|
|
150
265
|
const result = { ...values };
|
|
151
|
-
const properties = s.properties as
|
|
266
|
+
const properties = s.properties as { [key: string]: UnknownObject };
|
|
152
267
|
for (const [key, propSchema] of Object.entries(properties)) {
|
|
153
268
|
if (
|
|
154
269
|
!(key in result) &&
|
|
@@ -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,14 @@
|
|
|
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";
|
|
@@ -0,0 +1,108 @@
|
|
|
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
|
+
}
|
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
import { Elysia } from "elysia";
|
|
2
|
+
import { getSyncStreamPath } from "./config.ts";
|
|
3
|
+
|
|
4
|
+
export interface SyncInvalidationEvent {
|
|
5
|
+
invalidations: readonly string[];
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
const encoder = new TextEncoder();
|
|
9
|
+
const defaultStreamPath = "/_furin/sync";
|
|
10
|
+
interface StreamState {
|
|
11
|
+
clients: Set<ReadableStreamDefaultController<Uint8Array>>;
|
|
12
|
+
heartbeats: Set<ReturnType<typeof setInterval>>;
|
|
13
|
+
history: Array<{ chunk: Uint8Array; id: number }>;
|
|
14
|
+
nextEventId: number;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
const streams = new Map<string, StreamState>();
|
|
18
|
+
|
|
19
|
+
function getStreamState(path: string): StreamState {
|
|
20
|
+
const existing = streams.get(path);
|
|
21
|
+
if (existing) {
|
|
22
|
+
return existing;
|
|
23
|
+
}
|
|
24
|
+
const state: StreamState = {
|
|
25
|
+
clients: new Set(),
|
|
26
|
+
heartbeats: new Set(),
|
|
27
|
+
history: [],
|
|
28
|
+
nextEventId: 1,
|
|
29
|
+
};
|
|
30
|
+
streams.set(path, state);
|
|
31
|
+
return state;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
function encodeSseEvent(id: number, event: string, data: unknown): Uint8Array {
|
|
35
|
+
return encoder.encode(
|
|
36
|
+
`id: ${id}\nevent: ${event}\nretry: 3000\ndata: ${JSON.stringify(data)}\n\n`
|
|
37
|
+
);
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export function publishSyncInvalidation(invalidations: readonly string[]): void {
|
|
41
|
+
if (invalidations.length === 0) {
|
|
42
|
+
return;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
const state = getStreamState(getSyncStreamPath() ?? defaultStreamPath);
|
|
46
|
+
const id = state.nextEventId++;
|
|
47
|
+
const chunk = encodeSseEvent(id, "furin.invalidate", {
|
|
48
|
+
invalidations,
|
|
49
|
+
} satisfies SyncInvalidationEvent);
|
|
50
|
+
state.history.push({ chunk, id });
|
|
51
|
+
if (state.history.length > 100) {
|
|
52
|
+
state.history.shift();
|
|
53
|
+
}
|
|
54
|
+
for (const client of [...state.clients]) {
|
|
55
|
+
try {
|
|
56
|
+
client.enqueue(chunk);
|
|
57
|
+
} catch {
|
|
58
|
+
state.clients.delete(client);
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
export function createSyncStreamPlugin(path?: string) {
|
|
64
|
+
const streamPath = path ?? defaultStreamPath;
|
|
65
|
+
return new Elysia({ name: `furin-sync-stream-${streamPath}` }).get(streamPath, ({ request }) => {
|
|
66
|
+
const state = getStreamState(streamPath);
|
|
67
|
+
let controllerRef: ReadableStreamDefaultController<Uint8Array> | undefined;
|
|
68
|
+
let heartbeat: ReturnType<typeof setInterval> | undefined;
|
|
69
|
+
const stream = new ReadableStream<Uint8Array>({
|
|
70
|
+
start(controller) {
|
|
71
|
+
controllerRef = controller;
|
|
72
|
+
state.clients.add(controller);
|
|
73
|
+
const lastEventId = Number.parseInt(request.headers.get("Last-Event-ID") ?? "", 10);
|
|
74
|
+
const oldestEventId = state.history[0]?.id;
|
|
75
|
+
const hasReplayGap =
|
|
76
|
+
!Number.isNaN(lastEventId) &&
|
|
77
|
+
oldestEventId !== undefined &&
|
|
78
|
+
lastEventId < oldestEventId - 1;
|
|
79
|
+
const replay = Number.isNaN(lastEventId)
|
|
80
|
+
? []
|
|
81
|
+
: state.history.filter((entry) => entry.id > lastEventId);
|
|
82
|
+
if (hasReplayGap) {
|
|
83
|
+
controller.enqueue(
|
|
84
|
+
encodeSseEvent(state.nextEventId - 1, "furin.invalidate", {
|
|
85
|
+
invalidations: ["/:layout"],
|
|
86
|
+
} satisfies SyncInvalidationEvent)
|
|
87
|
+
);
|
|
88
|
+
} else if (replay.length > 0) {
|
|
89
|
+
for (const entry of replay) {
|
|
90
|
+
controller.enqueue(entry.chunk);
|
|
91
|
+
}
|
|
92
|
+
} else {
|
|
93
|
+
controller.enqueue(encoder.encode(": connected\nretry: 3000\n\n"));
|
|
94
|
+
}
|
|
95
|
+
heartbeat = setInterval(() => {
|
|
96
|
+
try {
|
|
97
|
+
controller.enqueue(encoder.encode(": heartbeat\n\n"));
|
|
98
|
+
} catch {
|
|
99
|
+
state.clients.delete(controller);
|
|
100
|
+
if (heartbeat) {
|
|
101
|
+
clearInterval(heartbeat);
|
|
102
|
+
state.heartbeats.delete(heartbeat);
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
}, 15_000);
|
|
106
|
+
state.heartbeats.add(heartbeat);
|
|
107
|
+
},
|
|
108
|
+
cancel() {
|
|
109
|
+
if (controllerRef) {
|
|
110
|
+
state.clients.delete(controllerRef);
|
|
111
|
+
}
|
|
112
|
+
if (heartbeat) {
|
|
113
|
+
clearInterval(heartbeat);
|
|
114
|
+
state.heartbeats.delete(heartbeat);
|
|
115
|
+
}
|
|
116
|
+
},
|
|
117
|
+
});
|
|
118
|
+
|
|
119
|
+
return new Response(stream, {
|
|
120
|
+
headers: {
|
|
121
|
+
"cache-control": "no-cache, no-transform",
|
|
122
|
+
connection: "keep-alive",
|
|
123
|
+
"content-type": "text/event-stream; charset=utf-8",
|
|
124
|
+
},
|
|
125
|
+
});
|
|
126
|
+
});
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/** @internal — resets process-local stream subscribers between tests. */
|
|
130
|
+
export function __resetSyncState(): void {
|
|
131
|
+
for (const state of streams.values()) {
|
|
132
|
+
for (const heartbeat of state.heartbeats) {
|
|
133
|
+
clearInterval(heartbeat);
|
|
134
|
+
}
|
|
135
|
+
for (const client of state.clients) {
|
|
136
|
+
try {
|
|
137
|
+
client.close();
|
|
138
|
+
} catch {
|
|
139
|
+
// already closed
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
streams.clear();
|
|
144
|
+
}
|