@teyik0/furin 0.6.0-alpha.1 → 0.7.0-alpha.2
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/dist/adapter/runtime-build.d.ts +1 -1
- package/dist/build/client.d.ts +4 -1
- package/dist/build/elysia-aot-worker.d.ts +22 -0
- package/dist/build/elysia-aot.d.ts +1 -1
- package/dist/build/entry-template.d.ts +3 -0
- package/dist/build/entry-template.ts +7 -0
- package/dist/build/hydrate.d.ts +1 -1
- package/dist/build/index.js +1880 -401
- package/dist/build/preload-manifest.d.ts +17 -0
- package/dist/build/types.d.ts +6 -0
- package/dist/cli/index.js +1878 -408
- package/dist/client/client-module.d.ts +26 -0
- package/dist/client/define-route.d.ts +9 -0
- package/dist/client/document.d.ts +2 -0
- package/dist/client/internal/runtime-types.d.ts +2 -0
- package/dist/client/link.js +942 -122
- package/dist/client/mutation.d.ts +38 -0
- package/dist/client/query-store.d.ts +85 -0
- package/dist/client/query.d.ts +14 -0
- package/dist/client/route-api.d.ts +11 -0
- package/dist/client/router/context.d.ts +3 -2
- package/dist/client/router/index.d.ts +1 -1
- package/dist/client/router/link-utils.d.ts +8 -1
- package/dist/client/router/navigation.d.ts +2 -9
- package/dist/client/router/optimistic.d.ts +41 -0
- package/dist/client/router/search/index.d.ts +3 -3
- package/dist/client/router/search-store.d.ts +1 -0
- package/dist/client/router/sync-catch-up.d.ts +3 -0
- package/dist/client/router/types.d.ts +51 -7
- package/dist/client/sync.d.ts +39 -22
- package/dist/client.d.ts +11 -33
- package/dist/client.js +1219 -59
- package/dist/config.d.ts +7 -0
- package/dist/config.js +1 -0
- package/dist/define-route.d.ts +78 -32
- package/dist/env.d.ts +2 -2
- package/dist/furin.d.ts +1 -2
- package/dist/furin.js +2484 -708
- package/dist/plugin/hmr-dependencies.d.ts +2 -0
- package/dist/plugin/index.js +349 -18
- package/dist/plugin/transform-client-module.d.ts +16 -0
- package/dist/plugin/transform-client.d.ts +2 -0
- package/dist/plugin/transform-isomorphic.d.ts +1 -1
- package/dist/routes.d.ts +6 -0
- package/dist/rsc-client.js +87 -16
- package/dist/rsc.js +87 -16
- package/dist/server/auto-invalidate/registry.d.ts +1 -0
- package/dist/server/auto-invalidate/types.d.ts +2 -0
- package/dist/server/cache/isr.d.ts +2 -4
- package/dist/server/cache/route-cache.d.ts +5 -0
- package/dist/server/dev/graph.d.ts +1 -0
- package/dist/server/dev-page-plugin.d.ts +5 -19
- package/dist/server/internal.d.ts +3 -0
- package/dist/server/internal.js +55 -35
- package/dist/server/production-server.js +54 -34
- package/dist/server/render/loaders.d.ts +4 -2
- package/dist/server/render/react-stream.d.ts +3 -0
- package/dist/server/render/ssr.d.ts +2 -1
- package/dist/server/render/template.d.ts +4 -0
- package/dist/server/router/defined-route.d.ts +2 -0
- package/dist/server/router/hmr.d.ts +1 -1
- package/dist/server/router/patterns.d.ts +2 -0
- package/dist/server/router/types.d.ts +1 -1
- package/dist/server/sync/adapter.d.ts +25 -4
- package/dist/server/sync/atomic.d.ts +25 -0
- package/dist/server/sync/drizzle/index.d.ts +45 -0
- package/dist/server/sync/drizzle/index.js +540 -0
- package/dist/server/sync/execution-error.d.ts +2 -0
- package/dist/server/sync/index.d.ts +2 -1
- package/dist/server/sync/index.js +533 -105
- package/dist/server/sync/mutation-handler.d.ts +4 -0
- package/dist/server/sync/plugin.d.ts +34 -11
- package/dist/server/sync/postgres/execute.d.ts +3 -0
- package/dist/server/sync/postgres/index.d.ts +12 -1
- package/dist/server/sync/postgres/index.js +34 -13
- package/dist/server/sync/postgres/sql.d.ts +8 -0
- package/dist/server/sync/prisma/index.d.ts +24 -0
- package/dist/server/sync/prisma/index.js +340 -0
- package/dist/server/sync/queries.d.ts +21 -0
- package/dist/server/sync/query-context.d.ts +5 -0
- package/dist/server/sync/redis/index.js +3 -3
- package/dist/server/sync/redis/scripts.d.ts +1 -1
- package/dist/server/sync/response.d.ts +1 -0
- package/dist/server/sync/sqlite/index.d.ts +3 -0
- package/dist/server/sync/sqlite/index.js +10 -4
- package/dist/server/sync/stream.d.ts +2 -5
- package/dist/server/sync/validation.d.ts +4 -0
- package/dist/shared/defer.d.ts +31 -0
- package/dist/shared/error.d.ts +2 -2
- package/dist/shared/page-key.d.ts +7 -0
- package/dist/shared/query-bindings.d.ts +12 -0
- package/dist/shared/route-frame.d.ts +1 -0
- package/dist/shared/sync-query.d.ts +40 -0
- package/package.json +29 -6
- package/src/adapter/package.ts +12 -2
- package/src/adapter/runtime-build.ts +63 -12
- package/src/adapter/static.ts +7 -2
- package/src/adapter/vercel.ts +15 -13
- package/src/build/client.ts +23 -5
- package/src/build/elysia-aot-worker.ts +51 -0
- package/src/build/elysia-aot.ts +83 -19
- package/src/build/entry-template.ts +7 -0
- package/src/build/hydrate.ts +21 -3
- package/src/build/preload-manifest.ts +100 -0
- package/src/build/production-instrumentation.ts +6 -3
- package/src/build/types.ts +4 -0
- package/src/cli/index.ts +1 -0
- package/src/client/browser-events-runtime.ts +4 -0
- package/src/client/client-module.ts +57 -0
- package/src/client/define-route.ts +11 -1
- package/src/client/document.tsx +28 -18
- package/src/client/hmr.ts +2 -1
- package/src/client/internal/runtime-types.ts +2 -0
- package/src/client/link.tsx +8 -8
- package/src/client/mutation.ts +136 -0
- package/src/client/query-store.ts +418 -0
- package/src/client/query.tsx +67 -0
- package/src/client/route-api.tsx +75 -0
- package/src/client/router/boundary-tree.tsx +19 -12
- package/src/client/router/context.ts +57 -4
- package/src/client/router/index.ts +3 -0
- package/src/client/router/link-utils.ts +29 -1
- package/src/client/router/navigation.ts +3 -50
- package/src/client/router/optimistic.ts +233 -0
- package/src/client/router/provider.tsx +306 -46
- package/src/client/router/search/index.ts +37 -17
- package/src/client/router/search-store.ts +4 -0
- package/src/client/router/sync-catch-up.ts +7 -0
- package/src/client/router/types.ts +73 -9
- package/src/client/sync.ts +438 -65
- package/src/client.ts +20 -60
- package/src/config.ts +5 -0
- package/src/define-route.ts +113 -55
- package/src/env.d.ts +2 -2
- package/src/furin.ts +75 -13
- package/src/plugin/hmr-dependencies.ts +58 -0
- package/src/plugin/index.ts +38 -2
- package/src/plugin/routes.ts +28 -16
- package/src/plugin/transform-client-module.ts +123 -0
- package/src/plugin/transform-client.ts +293 -13
- package/src/plugin/transform-isomorphic.ts +11 -5
- package/src/routes.ts +8 -0
- package/src/rsc/shared.tsx +104 -18
- package/src/server/auto-invalidate/registry.ts +4 -0
- package/src/server/auto-invalidate/runtime.ts +17 -0
- package/src/server/auto-invalidate/types.ts +6 -0
- package/src/server/cache/isr.ts +6 -34
- package/src/server/cache/route-cache.ts +40 -4
- package/src/server/dev/graph.ts +16 -2
- package/src/server/dev-page-plugin.ts +93 -59
- package/src/server/internal.ts +3 -0
- package/src/server/render/document.tsx +10 -1
- package/src/server/render/element.tsx +21 -11
- package/src/server/render/isr.ts +61 -29
- package/src/server/render/loaders.ts +118 -47
- package/src/server/render/mixed-cache.ts +33 -4
- package/src/server/render/not-found.ts +4 -7
- package/src/server/render/ppr-document.ts +2 -1
- package/src/server/render/ppr-route.ts +30 -10
- package/src/server/render/react-stream.ts +17 -0
- package/src/server/render/route-frame-transport.ts +3 -0
- package/src/server/render/ssg.ts +51 -18
- package/src/server/render/ssr.ts +53 -8
- package/src/server/render/template.ts +23 -0
- package/src/server/router/defined-route.ts +3 -0
- package/src/server/router/discovery.ts +25 -9
- package/src/server/router/hmr.ts +3 -2
- package/src/server/router/patterns.ts +16 -0
- package/src/server/router/plugin.ts +27 -12
- package/src/server/router/types.ts +1 -1
- package/src/server/sync/adapter.ts +41 -4
- package/src/server/sync/atomic.ts +303 -0
- package/src/server/sync/drizzle/index.ts +145 -0
- package/src/server/sync/execution-error.ts +1 -0
- package/src/server/sync/fingerprint.ts +2 -6
- package/src/server/sync/index.ts +6 -0
- package/src/server/sync/mutation-handler.ts +69 -0
- package/src/server/sync/plugin.ts +177 -60
- package/src/server/sync/postgres/execute.ts +20 -0
- package/src/server/sync/postgres/index.ts +52 -16
- package/src/server/sync/postgres/sql.ts +20 -0
- package/src/server/sync/prisma/index.ts +70 -0
- package/src/server/sync/queries.ts +75 -0
- package/src/server/sync/query-context.ts +85 -0
- package/src/server/sync/redis/index.ts +7 -3
- package/src/server/sync/redis/scripts.ts +1 -1
- package/src/server/sync/response.ts +21 -0
- package/src/server/sync/sqlite/index.ts +19 -8
- package/src/server/sync/stream.ts +14 -22
- package/src/server/sync/validation.ts +34 -0
- package/src/shared/defer.ts +48 -0
- package/src/shared/error.ts +2 -2
- package/src/shared/page-key.ts +36 -0
- package/src/shared/query-bindings.ts +138 -0
- package/src/shared/route-frame.ts +13 -1
- package/src/shared/route-map.ts +12 -2
- package/src/shared/sync-query.ts +138 -0
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
import { AsyncLocalStorage } from "node:async_hooks";
|
|
2
|
+
import type { Context } from "elysia";
|
|
3
|
+
import { QueryStore, setServerQueryEnvironment } from "../../client/query-store.ts";
|
|
4
|
+
import { toLogical } from "../../client/router/link-utils.ts";
|
|
5
|
+
import { bindQueryData } from "../../shared/query-bindings.ts";
|
|
6
|
+
import { mergeQuerySeeds, type QuerySeed, queryTag } from "../../shared/sync-query.ts";
|
|
7
|
+
import { getAutoInvalidateRegistry } from "../auto-invalidate/registry.ts";
|
|
8
|
+
import { currentInstance, instanceSlot } from "../instance.ts";
|
|
9
|
+
import type { LoaderResult } from "../render/loaders.ts";
|
|
10
|
+
|
|
11
|
+
interface QueryContext {
|
|
12
|
+
onRead: () => void;
|
|
13
|
+
origin: string;
|
|
14
|
+
store: QueryStore;
|
|
15
|
+
}
|
|
16
|
+
const QUERY_CONTEXT = Symbol.for("furin.query.server-context.v1");
|
|
17
|
+
const contextGlobal = globalThis as typeof globalThis & {
|
|
18
|
+
[QUERY_CONTEXT]?: AsyncLocalStorage<QueryContext>;
|
|
19
|
+
};
|
|
20
|
+
const contexts = (contextGlobal[QUERY_CONTEXT] ??= new AsyncLocalStorage<QueryContext>());
|
|
21
|
+
setServerQueryEnvironment(() => contexts.getStore());
|
|
22
|
+
const trackedQueryPaths = instanceSlot(() => new Set<string>());
|
|
23
|
+
const deferredQueries = new WeakMap<Promise<unknown>, QuerySeed[]>();
|
|
24
|
+
|
|
25
|
+
export function deferredQuerySeeds(promise: Promise<unknown>): QuerySeed[] | undefined {
|
|
26
|
+
return deferredQueries.get(promise);
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export function captureQueryReads<Result extends LoaderResult>(
|
|
30
|
+
ctx: Context,
|
|
31
|
+
run: () => Promise<Result>,
|
|
32
|
+
owner?: "eden-request-queries"
|
|
33
|
+
): Promise<Result> {
|
|
34
|
+
const { origin } = new URL(ctx.request.url);
|
|
35
|
+
const store = new QueryStore(origin);
|
|
36
|
+
const registry = getAutoInvalidateRegistry();
|
|
37
|
+
const trackedPaths = trackedQueryPaths();
|
|
38
|
+
const requestUrl = new URL(ctx.request.url);
|
|
39
|
+
const path = toLogical(requestUrl.pathname, currentInstance().prefix) + requestUrl.search;
|
|
40
|
+
const onRead = () => {
|
|
41
|
+
const seeds = store.dehydrate();
|
|
42
|
+
registry.registerLoaderTags(
|
|
43
|
+
path,
|
|
44
|
+
seeds.map((seed) => queryTag(seed.identity)),
|
|
45
|
+
owner ?? "eden-queries"
|
|
46
|
+
);
|
|
47
|
+
trackedPaths.delete(path);
|
|
48
|
+
if (seeds.length > 0) {
|
|
49
|
+
trackedPaths.add(path);
|
|
50
|
+
}
|
|
51
|
+
// Discovery metadata is bounded like the render caches, including uncached SSR paths.
|
|
52
|
+
if (trackedPaths.size > 1000) {
|
|
53
|
+
const oldest = trackedPaths.values().next().value;
|
|
54
|
+
if (oldest !== undefined) {
|
|
55
|
+
trackedPaths.delete(oldest);
|
|
56
|
+
registry.unregisterPath(oldest, "eden-queries");
|
|
57
|
+
registry.unregisterPath(oldest, "eden-request-queries");
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
};
|
|
61
|
+
return contexts.run({ origin, store, onRead }, async () => {
|
|
62
|
+
const result = { ...(await run()) };
|
|
63
|
+
const seeds = store.dehydrate();
|
|
64
|
+
if (result.type === "data" && seeds.length > 0) {
|
|
65
|
+
const captured = [...((result.syncData.__furinQueries as QuerySeed[] | undefined) ?? [])];
|
|
66
|
+
mergeQuerySeeds(captured, bindQueryData(result.syncData, seeds));
|
|
67
|
+
result.syncData = { ...result.syncData, __furinQueries: captured };
|
|
68
|
+
}
|
|
69
|
+
if (result.type === "data" && result.deferredPromises) {
|
|
70
|
+
for (const [key, promise] of Object.entries(result.deferredPromises)) {
|
|
71
|
+
promise
|
|
72
|
+
.then((value) => {
|
|
73
|
+
const completed = store.dehydrate();
|
|
74
|
+
if (completed.length > 0) {
|
|
75
|
+
const captured = deferredQueries.get(promise) ?? [];
|
|
76
|
+
mergeQuerySeeds(captured, bindQueryData({ [key]: value }, completed));
|
|
77
|
+
deferredQueries.set(promise, captured);
|
|
78
|
+
}
|
|
79
|
+
})
|
|
80
|
+
.catch(() => undefined);
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
return result;
|
|
84
|
+
});
|
|
85
|
+
}
|
|
@@ -41,7 +41,7 @@ interface MutationDocument {
|
|
|
41
41
|
fingerprint: string;
|
|
42
42
|
id: string;
|
|
43
43
|
leaseUntil?: number;
|
|
44
|
-
response?: SerializedResponse;
|
|
44
|
+
response?: SerializedResponse | string;
|
|
45
45
|
state: "in-progress" | "succeeded";
|
|
46
46
|
}
|
|
47
47
|
|
|
@@ -92,13 +92,17 @@ function parseMutation(raw: string): MutationDocument {
|
|
|
92
92
|
}
|
|
93
93
|
|
|
94
94
|
function deserializeResponse(document: MutationDocument): StoredResponse {
|
|
95
|
-
const
|
|
95
|
+
const response =
|
|
96
|
+
typeof document.response === "string"
|
|
97
|
+
? (JSON.parse(document.response) as SerializedResponse)
|
|
98
|
+
: document.response;
|
|
96
99
|
if (response === undefined) {
|
|
97
100
|
throw new Error("[furin-sync-redis] Succeeded mutation has no replay response.");
|
|
98
101
|
}
|
|
99
102
|
return {
|
|
100
103
|
body: Uint8Array.fromBase64(response.body),
|
|
101
|
-
|
|
104
|
+
// Legacy Lua receipts encoded an empty header array as an empty object.
|
|
105
|
+
headers: Array.isArray(response.headers) ? response.headers : [],
|
|
102
106
|
status: response.status,
|
|
103
107
|
};
|
|
104
108
|
}
|
|
@@ -48,7 +48,7 @@ if value.state ~= 'in-progress' or value.id ~= ARGV[1] or value.leaseUntil <= no
|
|
|
48
48
|
return {'lost'}
|
|
49
49
|
end
|
|
50
50
|
value.state = 'succeeded'
|
|
51
|
-
value.response =
|
|
51
|
+
value.response = ARGV[2]
|
|
52
52
|
value.leaseUntil = nil
|
|
53
53
|
local cursor = ''
|
|
54
54
|
if ARGV[3] ~= '[]' then
|
|
@@ -171,6 +171,27 @@ export async function storeResponse(
|
|
|
171
171
|
return storedResponseResult(headers, body, clone.status);
|
|
172
172
|
}
|
|
173
173
|
|
|
174
|
+
return storeResponseSync(responseValue, set);
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
export function storeResponseSync(
|
|
178
|
+
responseValue: unknown,
|
|
179
|
+
set: Context["set"]
|
|
180
|
+
): StoreResponseResult {
|
|
181
|
+
if (responseValue instanceof Response) {
|
|
182
|
+
if (responseValue.body !== null) {
|
|
183
|
+
return unreplayable();
|
|
184
|
+
}
|
|
185
|
+
return storedResponseResult(
|
|
186
|
+
new Headers(
|
|
187
|
+
[...responseValue.headers.entries()].filter(
|
|
188
|
+
([name]) => !NON_REPLAYABLE_HEADERS.has(name.toLowerCase())
|
|
189
|
+
)
|
|
190
|
+
),
|
|
191
|
+
new Uint8Array(),
|
|
192
|
+
responseValue.status
|
|
193
|
+
);
|
|
194
|
+
}
|
|
174
195
|
const headers = responseHeaders(set.headers);
|
|
175
196
|
const statusResponse = unwrapStatusResponse(responseValue);
|
|
176
197
|
const value = statusResponse?.value ?? responseValue;
|
|
@@ -87,6 +87,10 @@ export class SqliteSyncAdapter implements SyncAdapter {
|
|
|
87
87
|
}
|
|
88
88
|
|
|
89
89
|
async beginMutation(input: BeginMutationInput): Promise<BeginMutationResult> {
|
|
90
|
+
return this.beginMutationSync(input);
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
protected beginMutationSync(input: BeginMutationInput): BeginMutationResult {
|
|
90
94
|
const transaction = this.database.transaction(
|
|
91
95
|
(mutation: BeginMutationInput): BeginMutationResult => {
|
|
92
96
|
const now = Date.now();
|
|
@@ -165,18 +169,15 @@ export class SqliteSyncAdapter implements SyncAdapter {
|
|
|
165
169
|
}
|
|
166
170
|
|
|
167
171
|
async completeMutation(input: CompleteMutationInput): Promise<CompleteMutationResult> {
|
|
172
|
+
return this.completeMutationSync(input);
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
protected completeMutationSync(input: CompleteMutationInput): CompleteMutationResult {
|
|
168
176
|
const transaction = this.database.transaction(
|
|
169
177
|
(completion: CompleteMutationInput): CompleteMutationResult => {
|
|
170
178
|
const now = Date.now();
|
|
171
179
|
const key = mutationKey(completion.lease);
|
|
172
|
-
|
|
173
|
-
.query<{ mutation_id: string }, [string, string, string, number]>(
|
|
174
|
-
`SELECT mutation_id FROM furin_sync_mutations
|
|
175
|
-
WHERE namespace = ? AND mutation_key = ? AND mutation_id = ?
|
|
176
|
-
AND state = 'in-progress' AND lease_expires_at > ?`
|
|
177
|
-
)
|
|
178
|
-
.get(this.namespace, key, completion.lease.id, now);
|
|
179
|
-
if (!active) {
|
|
180
|
+
if (!this.hasMutationLeaseSync(completion.lease)) {
|
|
180
181
|
return { kind: "lost" };
|
|
181
182
|
}
|
|
182
183
|
|
|
@@ -259,6 +260,16 @@ export class SqliteSyncAdapter implements SyncAdapter {
|
|
|
259
260
|
return transaction.immediate(input);
|
|
260
261
|
}
|
|
261
262
|
|
|
263
|
+
protected hasMutationLeaseSync(lease: MutationLease): boolean {
|
|
264
|
+
return (
|
|
265
|
+
this.database
|
|
266
|
+
.query<{ mutation_id: string }, [string, string, string, number]>(
|
|
267
|
+
`SELECT mutation_id FROM furin_sync_mutations WHERE namespace = ? AND mutation_key = ? AND mutation_id = ? AND state = 'in-progress' AND lease_expires_at > ?`
|
|
268
|
+
)
|
|
269
|
+
.get(this.namespace, mutationKey(lease), lease.id, Date.now()) !== null
|
|
270
|
+
);
|
|
271
|
+
}
|
|
272
|
+
|
|
262
273
|
async abortMutation(lease: MutationLease): Promise<void> {
|
|
263
274
|
this.database
|
|
264
275
|
.query<never, [string, string, string]>(
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { Elysia } from "elysia";
|
|
2
2
|
import { IS_DEV } from "../runtime-env.ts";
|
|
3
|
-
import type { SyncAdapter,
|
|
3
|
+
import type { SyncAdapter, SyncSubscription } from "./adapter.ts";
|
|
4
4
|
import type { FurinSyncOptions } from "./config.ts";
|
|
5
5
|
import { syncRuntimeOptions } from "./config.ts";
|
|
6
6
|
import { type ResolvedSyncRuntime, resolveSyncRuntime } from "./runtime.ts";
|
|
@@ -146,38 +146,30 @@ function parseChangeQuery(
|
|
|
146
146
|
return { after, limit };
|
|
147
147
|
}
|
|
148
148
|
|
|
149
|
-
function clientInvalidations(change: SyncChange): string[] {
|
|
150
|
-
const entries = new Set<string>();
|
|
151
|
-
for (const invalidation of change.invalidations) {
|
|
152
|
-
if (invalidation.kind === "tags") {
|
|
153
|
-
entries.add("/:layout");
|
|
154
|
-
} else {
|
|
155
|
-
entries.add(
|
|
156
|
-
invalidation.type === "layout" ? `${invalidation.path}:layout` : invalidation.path
|
|
157
|
-
);
|
|
158
|
-
}
|
|
159
|
-
}
|
|
160
|
-
return [...entries];
|
|
161
|
-
}
|
|
162
|
-
|
|
163
149
|
export function createSyncChangesPlugin(options: FurinSyncOptions) {
|
|
164
150
|
const syncPath = options.path ?? defaultSyncPath;
|
|
165
151
|
const runtime = resolveSyncRuntime(syncRuntimeOptions(options));
|
|
166
152
|
return new Elysia({ name: `furin-sync-changes-${syncPath}` }).get(
|
|
167
153
|
`${syncPath}/changes`,
|
|
168
|
-
async (
|
|
154
|
+
async (context) => {
|
|
155
|
+
const { request, set } = context;
|
|
169
156
|
set.headers["cache-control"] = "no-store";
|
|
170
157
|
const query = parseChangeQuery(request);
|
|
171
158
|
if ("error" in query) {
|
|
172
159
|
return query.error;
|
|
173
160
|
}
|
|
174
|
-
const
|
|
161
|
+
const principal = await options.principal(context);
|
|
162
|
+
if (principal.length === 0) {
|
|
163
|
+
return new Response("Unauthorized", { status: 401 });
|
|
164
|
+
}
|
|
165
|
+
const cursor = await runtime.adapter.currentCursor();
|
|
166
|
+
// The journal is shared across principals. Resource paths and query scopes
|
|
167
|
+
// are private; clients refresh their authorized reads when its cursor moves.
|
|
175
168
|
return {
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
})),
|
|
169
|
+
changes: [],
|
|
170
|
+
cursor,
|
|
171
|
+
hasMore: false,
|
|
172
|
+
reset: query.after !== undefined && query.after !== cursor,
|
|
181
173
|
};
|
|
182
174
|
}
|
|
183
175
|
);
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import type { Context, Elysia } from "elysia";
|
|
2
|
+
import { createContext } from "elysia/context";
|
|
3
|
+
import { installMutationHandlers } from "./mutation-handler.ts";
|
|
4
|
+
|
|
5
|
+
const applications = new WeakMap<object, Elysia>();
|
|
6
|
+
const boundApplications = new WeakSet<Elysia>();
|
|
7
|
+
|
|
8
|
+
/** Bind the final application's models, guards and normalization to native request contexts. */
|
|
9
|
+
export function bindSyncValidation(app: Elysia): void {
|
|
10
|
+
installMutationHandlers(app);
|
|
11
|
+
if (boundApplications.has(app)) {
|
|
12
|
+
return;
|
|
13
|
+
}
|
|
14
|
+
boundApplications.add(app);
|
|
15
|
+
// Elysia shares its empty Context class; a decoration gives each app its own class.
|
|
16
|
+
app.decorate("_furinSyncValidation", true);
|
|
17
|
+
app.wrap((fetch) => {
|
|
18
|
+
applications.set(createContext(app), app);
|
|
19
|
+
return fetch;
|
|
20
|
+
});
|
|
21
|
+
app.setup((root) => {
|
|
22
|
+
applications.set(createContext(root), root);
|
|
23
|
+
});
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export function syncValidationApp(context: Context): Elysia {
|
|
27
|
+
const app = applications.get(context.constructor);
|
|
28
|
+
if (!app) {
|
|
29
|
+
throw new Error(
|
|
30
|
+
"[furin] Install furinSync on the final Elysia application, or mount furin({ sync }), before using mutation()."
|
|
31
|
+
);
|
|
32
|
+
}
|
|
33
|
+
return app;
|
|
34
|
+
}
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
const DEFERRED_BRAND: unique symbol = Symbol.for("@teyik0/furin/deferred");
|
|
2
|
+
|
|
3
|
+
// ── Deferred data ──────────────────────────────────────────────────────────────
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* A loader return value that contains a mix of synchronous scalar fields and
|
|
7
|
+
* lazy `Promise<T>` fields. Scalar fields are serialised into the initial HTML
|
|
8
|
+
* shell; Promise fields are streamed as late `<script>` resolution chunks.
|
|
9
|
+
*
|
|
10
|
+
* @example
|
|
11
|
+
* loader: () => defer({
|
|
12
|
+
* title: "My Board", // synchronous — available immediately
|
|
13
|
+
* stats: fetchStats(), // Promise — streamed when it resolves
|
|
14
|
+
* })
|
|
15
|
+
*/
|
|
16
|
+
export type DeferredData<T extends object> = T & {
|
|
17
|
+
readonly [DEFERRED_BRAND]: true;
|
|
18
|
+
};
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* Wraps loader data so that Promise-valued fields are streamed lazily while
|
|
22
|
+
* scalar fields are embedded in the initial HTML shell immediately.
|
|
23
|
+
*
|
|
24
|
+
* Use in any `defineRoute().loader()`. Promise-valued fields are streamed lazily;
|
|
25
|
+
* scalar fields are embedded in the initial HTML shell.
|
|
26
|
+
*/
|
|
27
|
+
export function defer<T extends object>(
|
|
28
|
+
data: T & { readonly [DEFERRED_BRAND]?: never }
|
|
29
|
+
): DeferredData<T> {
|
|
30
|
+
if (Object.hasOwn(data, DEFERRED_BRAND)) {
|
|
31
|
+
throw new Error("[furin] defer() received data that is already deferred.");
|
|
32
|
+
}
|
|
33
|
+
return { ...data, [DEFERRED_BRAND]: true };
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* Type guard for DeferredData. Used by the render pipeline to distinguish a
|
|
38
|
+
* plain loader return from a deferred one.
|
|
39
|
+
*/
|
|
40
|
+
export function isDeferred(value: unknown): value is DeferredData<object> {
|
|
41
|
+
return (
|
|
42
|
+
typeof value === "object" &&
|
|
43
|
+
value !== null &&
|
|
44
|
+
DEFERRED_BRAND in value &&
|
|
45
|
+
Object.hasOwn(value, DEFERRED_BRAND) &&
|
|
46
|
+
value[DEFERRED_BRAND] === true
|
|
47
|
+
);
|
|
48
|
+
}
|
package/src/shared/error.ts
CHANGED
|
@@ -13,9 +13,9 @@ export interface ErrorProps {
|
|
|
13
13
|
digest: string;
|
|
14
14
|
/**
|
|
15
15
|
* HTTP status associated with the error.
|
|
16
|
-
* - For thrown `Response` objects
|
|
16
|
+
* - For thrown `Response` objects and Eden problem errors: their HTTP
|
|
17
17
|
* status (e.g. 401, 403, 404, 500).
|
|
18
|
-
* - For
|
|
18
|
+
* - For other errors (thrown `Error`, non-Error throws, shell-render
|
|
19
19
|
* crashes): always `500`.
|
|
20
20
|
*
|
|
21
21
|
* Always present so consumers never need a `?? 500` fallback. Note that
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
export type RemountDependency = string | number | boolean | null | undefined;
|
|
2
|
+
|
|
3
|
+
export type RemountDeps<Params, Query> = (context: {
|
|
4
|
+
readonly params: Params;
|
|
5
|
+
readonly query: Query;
|
|
6
|
+
}) => readonly RemountDependency[];
|
|
7
|
+
|
|
8
|
+
function identityValue(value: unknown): string {
|
|
9
|
+
return Object.is(value, -0) ? "-0" : String(value);
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
/** Shared by SSR and navigation; loader data never participates in page identity. */
|
|
13
|
+
export function pageKey(
|
|
14
|
+
pattern: string,
|
|
15
|
+
data: object,
|
|
16
|
+
remountDeps: RemountDeps<object, object> | undefined
|
|
17
|
+
): string {
|
|
18
|
+
const { params, query } = data as { params?: object; query?: object };
|
|
19
|
+
if (remountDeps) {
|
|
20
|
+
const deps = remountDeps({ params: params ?? {}, query: query ?? {} });
|
|
21
|
+
return JSON.stringify([pattern, deps.map((value) => [typeof value, identityValue(value)])]);
|
|
22
|
+
}
|
|
23
|
+
const entries = Object.entries(params ?? {}).sort(([left], [right]) => {
|
|
24
|
+
if (left < right) {
|
|
25
|
+
return -1;
|
|
26
|
+
}
|
|
27
|
+
return left > right ? 1 : 0;
|
|
28
|
+
});
|
|
29
|
+
return JSON.stringify([
|
|
30
|
+
pattern,
|
|
31
|
+
entries.map(([name, value]) => [
|
|
32
|
+
name,
|
|
33
|
+
Array.isArray(value) ? value.map(identityValue) : identityValue(value),
|
|
34
|
+
]),
|
|
35
|
+
]);
|
|
36
|
+
}
|
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
import type { QueryBinding, QuerySeed } from "./sync-query.ts";
|
|
2
|
+
|
|
3
|
+
export interface DeferredQueryValue {
|
|
4
|
+
projection?: { value: unknown; promise: Promise<unknown> };
|
|
5
|
+
value: unknown;
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
function isContainer(value: unknown): value is { [key: string]: unknown } {
|
|
9
|
+
if (!value || typeof value !== "object") {
|
|
10
|
+
return false;
|
|
11
|
+
}
|
|
12
|
+
const prototype = Object.getPrototypeOf(value);
|
|
13
|
+
return Array.isArray(value) || prototype === Object.prototype || prototype === null;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/** Track returned objects by reference; computed scalars have no reliable provenance. */
|
|
17
|
+
export function bindQueryData(data: object, seeds: readonly QuerySeed[]): QuerySeed[] {
|
|
18
|
+
return seeds.map((seed) => {
|
|
19
|
+
const sources = new WeakMap<object, string[]>();
|
|
20
|
+
const index = (value: unknown, path: string[]) => {
|
|
21
|
+
if (!isContainer(value) || sources.has(value)) {
|
|
22
|
+
return;
|
|
23
|
+
}
|
|
24
|
+
sources.set(value, path);
|
|
25
|
+
// An array element's position does not identify an entity after an optimistic reorder.
|
|
26
|
+
if (!Array.isArray(value)) {
|
|
27
|
+
for (const [key, child] of Object.entries(value)) {
|
|
28
|
+
index(child, [...path, key]);
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
};
|
|
32
|
+
index(seed.data, []);
|
|
33
|
+
const bindings: QueryBinding[] = [];
|
|
34
|
+
const visiting = new WeakSet<object>();
|
|
35
|
+
const visit = (value: unknown, target: string[]) => {
|
|
36
|
+
if (!isContainer(value) || visiting.has(value)) {
|
|
37
|
+
return;
|
|
38
|
+
}
|
|
39
|
+
const source = sources.get(value);
|
|
40
|
+
if (source) {
|
|
41
|
+
bindings.push({ source, target });
|
|
42
|
+
return;
|
|
43
|
+
}
|
|
44
|
+
visiting.add(value);
|
|
45
|
+
for (const [key, child] of Object.entries(value)) {
|
|
46
|
+
visit(child, [...target, key]);
|
|
47
|
+
}
|
|
48
|
+
visiting.delete(value);
|
|
49
|
+
};
|
|
50
|
+
visit(data, []);
|
|
51
|
+
return { ...seed, bindings };
|
|
52
|
+
});
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function replace(value: unknown, path: readonly string[], next: unknown): unknown {
|
|
56
|
+
const [key, ...rest] = path;
|
|
57
|
+
if (key === undefined) {
|
|
58
|
+
return next;
|
|
59
|
+
}
|
|
60
|
+
if (!(isContainer(value) && Object.hasOwn(value, key))) {
|
|
61
|
+
return value;
|
|
62
|
+
}
|
|
63
|
+
const child = replace(value[key], rest, next);
|
|
64
|
+
if (child === value[key]) {
|
|
65
|
+
return value;
|
|
66
|
+
}
|
|
67
|
+
const copy = Array.isArray(value) ? [...value] : { ...value };
|
|
68
|
+
Object.defineProperty(copy, key, {
|
|
69
|
+
configurable: true,
|
|
70
|
+
enumerable: true,
|
|
71
|
+
value: child,
|
|
72
|
+
writable: true,
|
|
73
|
+
});
|
|
74
|
+
return copy;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
function isDeferredTarget(data: object, target: readonly string[]): boolean {
|
|
78
|
+
const [key] = target;
|
|
79
|
+
return key !== undefined && isContainer(data) && data[key] instanceof Promise;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
export function projectQueryData<Data extends object>(
|
|
83
|
+
data: Data,
|
|
84
|
+
seeds: readonly QuerySeed[],
|
|
85
|
+
read: (seed: QuerySeed) => unknown
|
|
86
|
+
): Data {
|
|
87
|
+
let projected: unknown = data;
|
|
88
|
+
for (const seed of seeds) {
|
|
89
|
+
const snapshot = read(seed);
|
|
90
|
+
if (snapshot === undefined) {
|
|
91
|
+
continue;
|
|
92
|
+
}
|
|
93
|
+
for (const binding of seed.bindings ?? []) {
|
|
94
|
+
if (isDeferredTarget(data, binding.target)) {
|
|
95
|
+
continue;
|
|
96
|
+
}
|
|
97
|
+
let value: unknown = snapshot;
|
|
98
|
+
for (const key of binding.source) {
|
|
99
|
+
value = isContainer(value) && Object.hasOwn(value, key) ? value[key] : undefined;
|
|
100
|
+
}
|
|
101
|
+
projected = replace(projected, binding.target, value);
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
return projected as Data;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
export function projectDeferredQueryData<Data extends object>(
|
|
108
|
+
data: Data,
|
|
109
|
+
seeds: readonly QuerySeed[],
|
|
110
|
+
read: (seed: QuerySeed) => unknown,
|
|
111
|
+
resolved: WeakMap<Promise<unknown>, DeferredQueryValue>
|
|
112
|
+
): Data {
|
|
113
|
+
let base: object = data;
|
|
114
|
+
const deferred = new Map<string, { promise: Promise<unknown>; state: DeferredQueryValue }>();
|
|
115
|
+
for (const [key, promise] of Object.entries(data)) {
|
|
116
|
+
if (!(promise instanceof Promise)) {
|
|
117
|
+
continue;
|
|
118
|
+
}
|
|
119
|
+
const state = resolved.get(promise);
|
|
120
|
+
if (state) {
|
|
121
|
+
deferred.set(key, { promise, state });
|
|
122
|
+
base = replace(base, [key], state.value) as object;
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
let projected: unknown = projectQueryData(base, seeds, read);
|
|
126
|
+
for (const [key, { promise, state }] of deferred) {
|
|
127
|
+
const value = isContainer(projected) ? projected[key] : undefined;
|
|
128
|
+
if (value === state.value) {
|
|
129
|
+
projected = replace(projected, [key], promise);
|
|
130
|
+
continue;
|
|
131
|
+
}
|
|
132
|
+
if (!state.projection || state.projection.value !== value) {
|
|
133
|
+
state.projection = { value, promise: Promise.resolve(value) };
|
|
134
|
+
}
|
|
135
|
+
projected = replace(projected, [key], state.projection.promise);
|
|
136
|
+
}
|
|
137
|
+
return projected as Data;
|
|
138
|
+
}
|
|
@@ -7,6 +7,7 @@ import {
|
|
|
7
7
|
type RscSourceKind,
|
|
8
8
|
restoreRscSource,
|
|
9
9
|
} from "../rsc/shared.tsx";
|
|
10
|
+
import { mergeQuerySeeds, type QuerySeed } from "./sync-query.ts";
|
|
10
11
|
|
|
11
12
|
const FRAME_VERSION = 3;
|
|
12
13
|
const MAX_FRAME_BYTES = 1024 * 1024;
|
|
@@ -20,7 +21,7 @@ interface RouteFrameEnvelope {
|
|
|
20
21
|
|
|
21
22
|
export type RouteFrame =
|
|
22
23
|
| { type: "data"; deferredKeys: readonly string[]; value: SerovalNode }
|
|
23
|
-
| { type: "defer-resolve"; key: string; value: SerovalNode }
|
|
24
|
+
| { type: "defer-resolve"; key: string; value: SerovalNode; queries?: SerovalNode }
|
|
24
25
|
| { type: "defer-reject"; key: string; value: SerovalNode }
|
|
25
26
|
| { type: "rsc-start"; id: string; kind: RscSourceKind }
|
|
26
27
|
| { type: "rsc-chunk"; id: string; value: string }
|
|
@@ -331,6 +332,10 @@ export async function parseRouteFrameLines(
|
|
|
331
332
|
const { frame } = envelope;
|
|
332
333
|
if (frame.type === "data") {
|
|
333
334
|
dataValue = fromCrossJSON(frame.value, {});
|
|
335
|
+
if (frame.deferredKeys.length > 0 && dataValue && typeof dataValue === "object") {
|
|
336
|
+
const data = dataValue as { __furinQueries?: QuerySeed[] };
|
|
337
|
+
data.__furinQueries ??= [];
|
|
338
|
+
}
|
|
334
339
|
for (const key of frame.deferredKeys) {
|
|
335
340
|
deferredPromises[key] = new Promise((resolve, reject) => {
|
|
336
341
|
resolvers.set(key, { reject, resolve });
|
|
@@ -363,6 +368,13 @@ export async function parseRouteFrameLines(
|
|
|
363
368
|
} else if (frame.type === "rsc-error") {
|
|
364
369
|
throw new Error(`[furin] RSC stream failed (${frame.digest})`);
|
|
365
370
|
} else if (frame.type === "defer-resolve") {
|
|
371
|
+
if (frame.queries && dataValue && typeof dataValue === "object") {
|
|
372
|
+
const data = dataValue as { __furinQueries?: QuerySeed[] };
|
|
373
|
+
mergeQuerySeeds(
|
|
374
|
+
(data.__furinQueries ??= []),
|
|
375
|
+
fromCrossJSON(frame.queries, {}) as QuerySeed[]
|
|
376
|
+
);
|
|
377
|
+
}
|
|
366
378
|
const value = fromCrossJSON(frame.value, {});
|
|
367
379
|
const ids = new Set<string>();
|
|
368
380
|
collectRscDescriptorIds(value, ids);
|
package/src/shared/route-map.ts
CHANGED
|
@@ -31,16 +31,26 @@ function compareRouteProperties(left: RouteMapEntry, right: RouteMapEntry): numb
|
|
|
31
31
|
}
|
|
32
32
|
|
|
33
33
|
export function routeMapDeclaration(entries: RouteMapEntry[]): string {
|
|
34
|
-
const
|
|
35
|
-
|
|
34
|
+
const sorted = entries.toSorted(compareRouteProperties);
|
|
35
|
+
const body = sorted
|
|
36
36
|
.map(
|
|
37
37
|
(entry) =>
|
|
38
38
|
` ${routeTypeProperty(entry.pattern)}: typeof import(${JSON.stringify(entry.importSpecifier)}).route;`
|
|
39
39
|
)
|
|
40
40
|
.join("\n");
|
|
41
|
+
const patterns = sorted
|
|
42
|
+
.map(
|
|
43
|
+
(entry) =>
|
|
44
|
+
` ${JSON.stringify(entry.pattern)}: typeof import(${JSON.stringify(entry.importSpecifier)}).route;`
|
|
45
|
+
)
|
|
46
|
+
.join("\n");
|
|
41
47
|
return `declare module "@teyik0/furin/routes" {
|
|
42
48
|
interface RouteMap {
|
|
43
49
|
${body}
|
|
44
50
|
}
|
|
51
|
+
|
|
52
|
+
interface RoutePatternMap {
|
|
53
|
+
${patterns}
|
|
54
|
+
}
|
|
45
55
|
}`;
|
|
46
56
|
}
|