@teyik0/furin 0.5.0-alpha.2 → 0.7.0-alpha.1

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 (230) hide show
  1. package/dist/adapter/runtime-build.d.ts +3 -1
  2. package/dist/build/client.d.ts +4 -1
  3. package/dist/build/entry-template.d.ts +5 -0
  4. package/dist/build/entry-template.ts +9 -0
  5. package/dist/build/hydrate.d.ts +1 -1
  6. package/dist/build/index.js +9589 -6685
  7. package/dist/build/preload-manifest.d.ts +17 -0
  8. package/dist/build/request-keys.d.ts +4 -0
  9. package/dist/build/types.d.ts +6 -0
  10. package/dist/cli/index.js +9539 -6644
  11. package/dist/client/browser-events-runtime.d.ts +2 -1
  12. package/dist/client/client-module.d.ts +26 -0
  13. package/dist/client/define-route.d.ts +9 -1
  14. package/dist/client/dev-error-overlay.ts +1 -0
  15. package/dist/client/document.d.ts +3 -0
  16. package/dist/client/hmr.d.ts +1 -1
  17. package/dist/client/internal/runtime-types.d.ts +2 -0
  18. package/dist/client/link.js +1011 -157
  19. package/dist/client/mutation.d.ts +38 -0
  20. package/dist/client/query-store.d.ts +85 -0
  21. package/dist/client/query.d.ts +14 -0
  22. package/dist/client/route-api.d.ts +11 -0
  23. package/dist/client/router/context.d.ts +3 -2
  24. package/dist/client/router/index.d.ts +1 -1
  25. package/dist/client/router/link-utils.d.ts +8 -1
  26. package/dist/client/router/navigation.d.ts +2 -9
  27. package/dist/client/router/optimistic.d.ts +41 -0
  28. package/dist/client/router/search/index.d.ts +3 -3
  29. package/dist/client/router/search-store.d.ts +1 -0
  30. package/dist/client/router/sync-catch-up.d.ts +3 -0
  31. package/dist/client/router/types.d.ts +49 -7
  32. package/dist/client/sync.d.ts +39 -22
  33. package/dist/client.d.ts +11 -33
  34. package/dist/client.js +1222 -57
  35. package/dist/config.d.ts +7 -0
  36. package/dist/config.js +1 -0
  37. package/dist/define-route.d.ts +231 -123
  38. package/dist/env.d.ts +2 -2
  39. package/dist/furin.d.ts +4 -2
  40. package/dist/furin.js +9717 -6796
  41. package/dist/plugin/hmr-dependencies.d.ts +2 -0
  42. package/dist/plugin/index.js +811 -145
  43. package/dist/plugin/transform-client-module.d.ts +16 -0
  44. package/dist/plugin/transform-client.d.ts +2 -0
  45. package/dist/plugin/transform-dev-page.d.ts +7 -0
  46. package/dist/plugin/transform-isomorphic.d.ts +1 -1
  47. package/dist/routes.d.ts +6 -0
  48. package/dist/rsc-client.js +87 -16
  49. package/dist/rsc.js +87 -16
  50. package/dist/server/auto-invalidate/registry.d.ts +5 -2
  51. package/dist/server/auto-invalidate/types.d.ts +2 -0
  52. package/dist/server/browser-events/plugin.d.ts +3 -0
  53. package/dist/server/cache/isr.d.ts +2 -4
  54. package/dist/server/cache/route-cache.d.ts +5 -0
  55. package/dist/server/dev/graph.d.ts +1 -0
  56. package/dist/server/dev/runtime.production.d.ts +1 -0
  57. package/dist/server/dev-page-plugin.d.ts +6 -19
  58. package/dist/server/internal.d.ts +5 -0
  59. package/dist/server/internal.js +105 -57
  60. package/dist/server/production-server.js +104 -56
  61. package/dist/server/render/assemble.d.ts +6 -6
  62. package/dist/server/render/document.d.ts +1 -1
  63. package/dist/server/render/element.d.ts +1 -1
  64. package/dist/server/render/loaders.d.ts +15 -5
  65. package/dist/server/render/mixed-cache.d.ts +6 -0
  66. package/dist/server/render/react-stream.d.ts +3 -0
  67. package/dist/server/render/ssr.d.ts +5 -4
  68. package/dist/server/render/template.d.ts +4 -0
  69. package/dist/server/router/defined-route.d.ts +2 -0
  70. package/dist/server/router/discovery.d.ts +1 -0
  71. package/dist/server/router/hmr.d.ts +1 -1
  72. package/dist/server/router/patterns.d.ts +3 -0
  73. package/dist/server/router/plugin.d.ts +3 -0
  74. package/dist/server/router/types.d.ts +4 -0
  75. package/dist/server/security/csp.d.ts +12 -0
  76. package/dist/server/sync/adapter.d.ts +25 -4
  77. package/dist/server/sync/atomic.d.ts +25 -0
  78. package/dist/server/sync/drizzle/index.d.ts +45 -0
  79. package/dist/server/sync/drizzle/index.js +540 -0
  80. package/dist/server/sync/execution-error.d.ts +2 -0
  81. package/dist/server/sync/index.d.ts +2 -1
  82. package/dist/server/sync/index.js +580 -124
  83. package/dist/server/sync/mutation-handler.d.ts +4 -0
  84. package/dist/server/sync/plugin.d.ts +34 -11
  85. package/dist/server/sync/postgres/execute.d.ts +3 -0
  86. package/dist/server/sync/postgres/index.d.ts +12 -1
  87. package/dist/server/sync/postgres/index.js +42 -13
  88. package/dist/server/sync/postgres/sql.d.ts +8 -0
  89. package/dist/server/sync/prisma/index.d.ts +24 -0
  90. package/dist/server/sync/prisma/index.js +340 -0
  91. package/dist/server/sync/queries.d.ts +21 -0
  92. package/dist/server/sync/query-context.d.ts +5 -0
  93. package/dist/server/sync/redis/index.js +3 -3
  94. package/dist/server/sync/redis/scripts.d.ts +1 -1
  95. package/dist/server/sync/response.d.ts +1 -0
  96. package/dist/server/sync/sqlite/index.d.ts +3 -0
  97. package/dist/server/sync/sqlite/index.js +10 -4
  98. package/dist/server/sync/stream.d.ts +2 -5
  99. package/dist/server/sync/validation.d.ts +4 -0
  100. package/dist/shared/defer.d.ts +31 -0
  101. package/dist/shared/error.d.ts +2 -2
  102. package/dist/shared/page-key.d.ts +7 -0
  103. package/dist/shared/query-bindings.d.ts +12 -0
  104. package/dist/shared/route-frame.d.ts +1 -0
  105. package/dist/shared/sync-query.d.ts +40 -0
  106. package/package.json +40 -16
  107. package/src/adapter/README.md +3 -0
  108. package/src/adapter/bun.ts +3 -0
  109. package/src/adapter/package.ts +16 -2
  110. package/src/adapter/runtime-build.ts +99 -14
  111. package/src/adapter/static.ts +17 -6
  112. package/src/adapter/vercel.ts +33 -23
  113. package/src/build/client.ts +23 -5
  114. package/src/build/entry-template.ts +9 -0
  115. package/src/build/hydrate.ts +18 -3
  116. package/src/build/preload-manifest.ts +100 -0
  117. package/src/build/production-instrumentation.ts +6 -3
  118. package/src/build/request-keys.ts +93 -0
  119. package/src/build/ssg-cache.ts +9 -4
  120. package/src/build/types.ts +4 -0
  121. package/src/cli/index.ts +1 -0
  122. package/src/client/boundaries.tsx +1 -1
  123. package/src/client/browser-events-runtime.ts +73 -16
  124. package/src/client/client-module.ts +57 -0
  125. package/src/client/define-route.ts +11 -2
  126. package/src/client/dev-error-overlay.ts +1 -0
  127. package/src/client/document.tsx +47 -20
  128. package/src/client/hmr.ts +4 -2
  129. package/src/client/internal/runtime-types.ts +2 -0
  130. package/src/client/link.tsx +8 -8
  131. package/src/client/mutation.ts +136 -0
  132. package/src/client/query-store.ts +418 -0
  133. package/src/client/query.tsx +67 -0
  134. package/src/client/route-api.tsx +75 -0
  135. package/src/client/router/boundary-tree.tsx +10 -6
  136. package/src/client/router/context.ts +57 -4
  137. package/src/client/router/index.ts +3 -0
  138. package/src/client/router/link-utils.ts +29 -1
  139. package/src/client/router/navigation.ts +3 -50
  140. package/src/client/router/optimistic.ts +233 -0
  141. package/src/client/router/provider.tsx +404 -96
  142. package/src/client/router/search/index.ts +37 -17
  143. package/src/client/router/search-store.ts +4 -0
  144. package/src/client/router/sync-catch-up.ts +7 -0
  145. package/src/client/router/types.ts +71 -9
  146. package/src/client/sync.ts +438 -65
  147. package/src/client.ts +20 -60
  148. package/src/config.ts +5 -0
  149. package/src/define-route.ts +442 -155
  150. package/src/env.d.ts +2 -2
  151. package/src/furin.ts +213 -38
  152. package/src/plugin/hmr-dependencies.ts +58 -0
  153. package/src/plugin/index.ts +38 -2
  154. package/src/plugin/route-config-autofix.ts +2 -2
  155. package/src/plugin/routes.ts +19 -8
  156. package/src/plugin/transform-client-module.ts +123 -0
  157. package/src/plugin/transform-client.ts +293 -13
  158. package/src/plugin/transform-dev-page.ts +231 -0
  159. package/src/plugin/transform-isomorphic.ts +11 -5
  160. package/src/routes.ts +8 -0
  161. package/src/rsc/shared.tsx +104 -18
  162. package/src/rsc/version.ts +5 -0
  163. package/src/server/auto-invalidate/registry.ts +56 -24
  164. package/src/server/auto-invalidate/runtime.ts +17 -0
  165. package/src/server/auto-invalidate/types.ts +6 -0
  166. package/src/server/browser-events/plugin.ts +112 -1
  167. package/src/server/cache/dev-loader.ts +1 -1
  168. package/src/server/cache/invalidation.ts +2 -0
  169. package/src/server/cache/isr-ssg.ts +1 -1
  170. package/src/server/cache/isr.ts +6 -34
  171. package/src/server/cache/route-cache.ts +40 -4
  172. package/src/server/cache/ssg.ts +1 -1
  173. package/src/server/dev/diagnostics.ts +4 -2
  174. package/src/server/dev/error.ts +2 -1
  175. package/src/server/dev/graph.ts +70 -7
  176. package/src/server/dev/runtime.production.ts +4 -0
  177. package/src/server/dev/symbolicate.ts +2 -0
  178. package/src/server/dev-page-plugin.ts +160 -63
  179. package/src/server/evlog.ts +1 -1
  180. package/src/server/internal.ts +5 -0
  181. package/src/server/render/assemble.ts +15 -11
  182. package/src/server/render/document.tsx +13 -2
  183. package/src/server/render/element.tsx +11 -6
  184. package/src/server/render/isr.ts +71 -33
  185. package/src/server/render/loaders.ts +328 -70
  186. package/src/server/render/mixed-cache.ts +327 -0
  187. package/src/server/render/not-found.ts +14 -11
  188. package/src/server/render/ppr-document.ts +47 -11
  189. package/src/server/render/ppr-route.ts +54 -20
  190. package/src/server/render/react-stream.ts +17 -0
  191. package/src/server/render/route-frame-transport.ts +3 -0
  192. package/src/server/render/ssg.ts +53 -19
  193. package/src/server/render/ssr.ts +105 -36
  194. package/src/server/render/static-params.ts +1 -1
  195. package/src/server/render/template.ts +23 -0
  196. package/src/server/router/defined-route.ts +3 -0
  197. package/src/server/router/discovery.ts +14 -0
  198. package/src/server/router/hmr.ts +109 -18
  199. package/src/server/router/patterns.ts +27 -0
  200. package/src/server/router/plugin.ts +94 -19
  201. package/src/server/router/source-version.ts +20 -2
  202. package/src/server/router/types.ts +4 -0
  203. package/src/server/security/csp.ts +44 -0
  204. package/src/server/sync/adapter.ts +41 -4
  205. package/src/server/sync/atomic.ts +303 -0
  206. package/src/server/sync/drizzle/index.ts +145 -0
  207. package/src/server/sync/execution-error.ts +1 -0
  208. package/src/server/sync/fingerprint.ts +2 -6
  209. package/src/server/sync/index.ts +6 -0
  210. package/src/server/sync/mutation-handler.ts +69 -0
  211. package/src/server/sync/plugin.ts +177 -60
  212. package/src/server/sync/postgres/execute.ts +20 -0
  213. package/src/server/sync/postgres/index.ts +60 -16
  214. package/src/server/sync/postgres/sql.ts +20 -0
  215. package/src/server/sync/prisma/index.ts +70 -0
  216. package/src/server/sync/queries.ts +75 -0
  217. package/src/server/sync/query-context.ts +85 -0
  218. package/src/server/sync/redis/index.ts +7 -3
  219. package/src/server/sync/redis/scripts.ts +1 -1
  220. package/src/server/sync/response.ts +21 -0
  221. package/src/server/sync/sqlite/index.ts +19 -8
  222. package/src/server/sync/stream.ts +14 -22
  223. package/src/server/sync/validation.ts +34 -0
  224. package/src/shared/defer.ts +48 -0
  225. package/src/shared/error.ts +2 -2
  226. package/src/shared/page-key.ts +36 -0
  227. package/src/shared/query-bindings.ts +138 -0
  228. package/src/shared/route-frame.ts +13 -1
  229. package/src/shared/route-map.ts +12 -2
  230. package/src/shared/sync-query.ts +138 -0
@@ -0,0 +1,303 @@
1
+ import { type Context, type Elysia, ElysiaStatus, StatusMap, Validator } from "elysia";
2
+ import {
3
+ appendPendingInvalidationHeader,
4
+ runInvalidationRules,
5
+ } from "../auto-invalidate/runtime.ts";
6
+ import type { InvalidationInput } from "../auto-invalidate/types.ts";
7
+ import { peekPendingInvalidations } from "../cache/invalidation.ts";
8
+ import { getLogger } from "../context-logger.ts";
9
+ import type {
10
+ AtomicMutationResult,
11
+ MutationLease,
12
+ SyncInvalidation,
13
+ TransactionalSyncAdapter,
14
+ } from "./adapter.ts";
15
+ import {
16
+ appendQueryInvalidations,
17
+ resolveSyncInvalidations,
18
+ type SyncInvalidationSelector,
19
+ } from "./queries.ts";
20
+ import {
21
+ mergeStoredResponseHeaders,
22
+ type StoreResponseResult,
23
+ storeResponse,
24
+ storeResponseSync,
25
+ } from "./response.ts";
26
+ import type { ResolvedSyncRuntime } from "./runtime.ts";
27
+
28
+ const TRAILING_SLASH_PATTERN = /\/$/;
29
+
30
+ class RejectedMutation {
31
+ readonly value: unknown;
32
+ constructor(value: unknown) {
33
+ this.value = value;
34
+ }
35
+ }
36
+
37
+ type CommittedMutation = Extract<AtomicMutationResult<unknown>, { kind: "committed" }>;
38
+ type ResponseSchemaMap = NonNullable<
39
+ NonNullable<Parameters<typeof Validator.response>[1]>["schemas"]
40
+ >[number];
41
+ interface Execution<Tx> {
42
+ adapter: TransactionalSyncAdapter<Tx, "async" | "sync">;
43
+ app: Elysia;
44
+ context: Context;
45
+ invalidate: SyncInvalidationSelector | undefined;
46
+ lease: MutationLease;
47
+ onCommit: (result: CommittedMutation) => void;
48
+ resolvedInvalidate?: InvalidationInput;
49
+ runtime: ResolvedSyncRuntime;
50
+ }
51
+
52
+ function responseStatus(context: Context, value: unknown): number {
53
+ if (value instanceof Response && value.status !== 200) {
54
+ return value.status;
55
+ }
56
+ if (value instanceof ElysiaStatus) {
57
+ return value.status;
58
+ }
59
+ if (typeof context.set.status === "string") {
60
+ return StatusMap[context.set.status];
61
+ }
62
+ return context.set.status ?? 200;
63
+ }
64
+
65
+ function withStatus(original: unknown, value: unknown): unknown {
66
+ return original instanceof ElysiaStatus
67
+ ? new ElysiaStatus(original.status, value, original.headers)
68
+ : value;
69
+ }
70
+
71
+ function validateResult<Tx>(execution: Execution<Tx>, value: unknown): unknown {
72
+ if (value instanceof Error) {
73
+ throw value;
74
+ }
75
+ if (value instanceof Response) {
76
+ return value;
77
+ }
78
+ const { app, context, adapter } = execution;
79
+ const registeredPath = context.route ?? context.path;
80
+ const strictPath = app["~config"]?.strictPath === true;
81
+ const [match] = app.routes
82
+ .toReversed()
83
+ .filter((entry) => entry.method === context.request.method || entry.method === "*")
84
+ .map((candidate) => {
85
+ const paths = [candidate.path, encodeURI(candidate.path)];
86
+ const exact = paths.includes(registeredPath);
87
+ const loose =
88
+ !strictPath &&
89
+ paths.some(
90
+ (path) =>
91
+ path.replace(TRAILING_SLASH_PATTERN, "") ===
92
+ registeredPath.replace(TRAILING_SLASH_PATTERN, "")
93
+ );
94
+ return { route: candidate, priority: exact ? 2 : Number(loose) };
95
+ })
96
+ .filter((entry) => entry.priority > 0)
97
+ .sort(
98
+ (left, right) =>
99
+ Number(right.route.method === context.request.method) -
100
+ Number(left.route.method === context.request.method) || right.priority - left.priority
101
+ );
102
+ if (!match) {
103
+ throw new Error(
104
+ "[furin] Could not resolve the effective mutation route for response validation."
105
+ );
106
+ }
107
+ const { route } = match;
108
+ const validators = Validator.response(route?.hooks.response, {
109
+ models: app["~ext"]?.models,
110
+ normalize: app["~config"]?.normalize,
111
+ sanitize: app["~config"]?.sanitize,
112
+ schemas: route?.hooks.schemas?.flatMap((schema: { response?: ResponseSchemaMap }) =>
113
+ schema.response ? [schema.response] : []
114
+ ),
115
+ });
116
+ const validator = validators?.[responseStatus(context, value)];
117
+ if (!validator) {
118
+ return value;
119
+ }
120
+ const body = value instanceof ElysiaStatus ? value.response : value;
121
+ const encoder = validator as Validator & {
122
+ EncodeFrom?: (body: unknown, type: string) => unknown;
123
+ };
124
+ const encoded = validator.mayReturnPromise
125
+ ? validator.From?.(body, "response", adapter.transactionMode !== "sync")
126
+ : encoder.EncodeFrom?.(body, "response");
127
+ if (!(encoded instanceof Promise)) {
128
+ return withStatus(value, encoded);
129
+ }
130
+ if (adapter.transactionMode === "sync") {
131
+ throw new Error("[furin] Bun SQLite mutations require synchronous response validation.");
132
+ }
133
+ return encoded.then((result) => withStatus(value, result));
134
+ }
135
+
136
+ function prepare<Tx>(execution: Execution<Tx>, value: unknown, original: unknown) {
137
+ const { context } = execution;
138
+ const status = responseStatus(context, value);
139
+ if (status < 200 || status >= 400) {
140
+ throw new RejectedMutation(original);
141
+ }
142
+ const invalidate = resolveSyncInvalidations(execution.invalidate, context, original);
143
+ execution.resolvedInvalidate = invalidate;
144
+ appendQueryInvalidations(invalidate, context);
145
+ const invalidations = [
146
+ ...normalizedInvalidations(invalidate),
147
+ ...pendingPathInvalidations(peekPendingInvalidations()),
148
+ ];
149
+ if (invalidations.length > 0) {
150
+ context.set.headers["x-furin-sync"] = "1";
151
+ }
152
+ const paths = invalidations
153
+ .filter((entry): entry is Extract<SyncInvalidation, { kind: "path" }> => entry.kind === "path")
154
+ .map((entry) => (entry.type === "layout" ? `${entry.path}:layout` : entry.path));
155
+ if (paths.length > 0) {
156
+ context.set.headers["x-furin-revalidate"] = paths.join(",");
157
+ }
158
+ const finish = (stored: StoreResponseResult) => {
159
+ if (stored.kind === "unreplayable") {
160
+ throw new Error(
161
+ "[furin] Atomic mutation responses must be bounded JSON, text or bodyless responses."
162
+ );
163
+ }
164
+ let { headers } = context.set;
165
+ if (value instanceof ElysiaStatus) {
166
+ headers = { ...headers, ...value.headers };
167
+ } else if (value instanceof Response) {
168
+ headers = { ...headers, ...Object.fromEntries(value.headers) };
169
+ }
170
+ return {
171
+ invalidations,
172
+ response: mergeStoredResponseHeaders({ ...stored.response, status }, headers),
173
+ value: original,
174
+ };
175
+ };
176
+ return execution.adapter.transactionMode === "sync"
177
+ ? finish(storeResponseSync(value, context.set))
178
+ : storeResponse(value, context.set).then(finish);
179
+ }
180
+
181
+ function assertSynchronous(mode: "async" | "sync", value: unknown): void {
182
+ if (
183
+ mode === "sync" &&
184
+ (value instanceof Promise || Object.prototype.toString.call(value) === "[object AsyncFunction]")
185
+ ) {
186
+ throw new Error("[furin] Bun SQLite mutation callbacks must be synchronous.");
187
+ }
188
+ }
189
+
190
+ function invoke<Tx>(execution: Execution<Tx>, callback: (tx: Tx) => unknown, tx: Tx) {
191
+ assertSynchronous(execution.adapter.transactionMode, callback);
192
+ const value = callback(tx);
193
+ assertSynchronous(execution.adapter.transactionMode, value);
194
+ if (value instanceof Promise) {
195
+ return value.then(async (original) =>
196
+ prepare(execution, await validateResult(execution, original), original)
197
+ );
198
+ }
199
+ const encoded = validateResult(execution, value);
200
+ return encoded instanceof Promise
201
+ ? encoded.then((result) => prepare(execution, result, value))
202
+ : prepare(execution, encoded, value);
203
+ }
204
+
205
+ async function afterCommit<Tx>(execution: Execution<Tx>, result: CommittedMutation): Promise<void> {
206
+ execution.onCommit(result);
207
+ if (execution.resolvedInvalidate) {
208
+ await runInvalidationRules(execution.resolvedInvalidate).catch(() =>
209
+ getLogger().warn(
210
+ "Sync cache invalidation failed after mutation; preserving the idempotent result"
211
+ )
212
+ );
213
+ appendPendingInvalidationHeader(execution.context.set);
214
+ }
215
+ const { notifier } = execution.runtime;
216
+ if (result.cursor !== undefined) {
217
+ notifier.publish(result.cursor).catch(() => undefined);
218
+ }
219
+ }
220
+
221
+ export async function executeAtomicMutation<Tx>(
222
+ execution: Execution<Tx>,
223
+ callback: (tx: Tx) => unknown
224
+ ): Promise<unknown> {
225
+ const { context } = execution;
226
+ const previousSyncHeader = context.set.headers["x-furin-sync"];
227
+ const previousPathHeader = context.set.headers["x-furin-revalidate"];
228
+ const previousQueryHeader = context.set.headers["x-furin-queries"];
229
+ let committed = false;
230
+ try {
231
+ const result = await execution.adapter.executeMutation(execution.lease, (tx) =>
232
+ invoke(execution, callback, tx)
233
+ );
234
+ committed = true;
235
+ await afterCommit(execution, result);
236
+ return result.value;
237
+ } catch (error) {
238
+ if (!committed) {
239
+ restoreHeader(context, "x-furin-sync", previousSyncHeader);
240
+ restoreHeader(context, "x-furin-revalidate", previousPathHeader);
241
+ restoreHeader(context, "x-furin-queries", previousQueryHeader);
242
+ }
243
+ if (error instanceof RejectedMutation) {
244
+ return error.value;
245
+ }
246
+ throw error;
247
+ }
248
+ }
249
+
250
+ function restoreHeader(
251
+ context: Context,
252
+ key: string,
253
+ value: Context["set"]["headers"][string] | undefined
254
+ ): void {
255
+ if (value === undefined) {
256
+ delete context.set.headers[key];
257
+ } else {
258
+ context.set.headers[key] = value;
259
+ }
260
+ }
261
+
262
+ export function conflictResponse(reason: "in-progress" | "payload-mismatch"): Response {
263
+ const inProgress = reason === "in-progress";
264
+ return Response.json(
265
+ {
266
+ code: inProgress ? "FURIN_MUTATION_IN_PROGRESS" : "FURIN_IDEMPOTENCY_MISMATCH",
267
+ message: inProgress
268
+ ? "A mutation with this Idempotency-Key is still running."
269
+ : "The Idempotency-Key was already used with a different request.",
270
+ },
271
+ {
272
+ headers: inProgress ? { "retry-after": "1" } : undefined,
273
+ status: 409,
274
+ }
275
+ );
276
+ }
277
+
278
+ export function normalizedInvalidations(input: InvalidationInput | undefined): SyncInvalidation[] {
279
+ if (!input) {
280
+ return [];
281
+ }
282
+ const rules = Array.isArray(input) ? input : [input];
283
+ const invalidations: SyncInvalidation[] = [];
284
+ for (const rule of rules) {
285
+ if ("path" in rule && rule.path) {
286
+ invalidations.push({ kind: "path", path: rule.path, type: rule.type });
287
+ }
288
+ if (rule.tags && rule.tags.length > 0) {
289
+ invalidations.push({ kind: "tags", tags: [...rule.tags] });
290
+ }
291
+ }
292
+ return invalidations;
293
+ }
294
+
295
+ export function pendingPathInvalidations(
296
+ entries: readonly string[]
297
+ ): Extract<SyncInvalidation, { kind: "path" }>[] {
298
+ return entries.map((entry) =>
299
+ entry.endsWith(":layout")
300
+ ? { kind: "path" as const, path: entry.slice(0, -":layout".length), type: "layout" }
301
+ : { kind: "path" as const, path: entry, type: "page" }
302
+ );
303
+ }
@@ -0,0 +1,145 @@
1
+ import { Database } from "bun:sqlite";
2
+ import { sql as drizzleSql } from "drizzle-orm";
3
+ import type { BunSQLDatabase } from "drizzle-orm/bun-sql";
4
+ import type { BunSQLiteDatabase } from "drizzle-orm/bun-sqlite";
5
+ import type {
6
+ AtomicMutationResult,
7
+ AtomicMutationValue,
8
+ MutationLease,
9
+ TransactionalSyncAdapter,
10
+ } from "../adapter.ts";
11
+ import { MutationLeaseLost } from "../execution-error.ts";
12
+ import { executePostgresMutation } from "../postgres/execute.ts";
13
+ import { PostgresSyncAdapter } from "../postgres/index.ts";
14
+ import { transactionSql } from "../postgres/sql.ts";
15
+ import { SqliteSyncAdapter } from "../sqlite/index.ts";
16
+
17
+ interface Schema {
18
+ [table: string]: unknown;
19
+ }
20
+ type Transaction<Db extends BunSQLiteDatabase<Schema> | BunSQLDatabase<Schema>> = Parameters<
21
+ Parameters<Db["transaction"]>[0]
22
+ >[0];
23
+
24
+ export class DrizzleSqliteSyncAdapter<Db extends BunSQLiteDatabase<Schema>>
25
+ extends SqliteSyncAdapter
26
+ implements TransactionalSyncAdapter<Transaction<Db>, "sync">
27
+ {
28
+ readonly transactionMode = "sync" as const;
29
+ private readonly db: Db;
30
+
31
+ constructor(options: { db: Db & { $client: import("bun:sqlite").Database }; namespace: string }) {
32
+ super({ database: options.db.$client, namespace: options.namespace });
33
+ this.db = options.db;
34
+ }
35
+
36
+ // biome-ignore lint/suspicious/useAwait: Bun SQLite commits synchronously before the returned promise resolves.
37
+ async executeMutation<T>(
38
+ lease: MutationLease,
39
+ callback: (tx: Transaction<Db>) => AtomicMutationValue<T> | Promise<AtomicMutationValue<T>>
40
+ ): Promise<AtomicMutationResult<T>> {
41
+ return this.db.transaction(
42
+ (tx) => {
43
+ if (!this.hasMutationLeaseSync(lease)) {
44
+ throw new MutationLeaseLost(
45
+ "[furin] Mutation lease lost; the transaction was rolled back."
46
+ );
47
+ }
48
+ const result = callback(tx as Transaction<Db>);
49
+ if (result instanceof Promise) {
50
+ throw new Error("[furin] Bun SQLite mutation callbacks must be synchronous.");
51
+ }
52
+ const completion = this.completeMutationSync({ ...result, lease });
53
+ if (completion.kind === "lost") {
54
+ throw new MutationLeaseLost(
55
+ "[furin] Mutation lease lost; the transaction was rolled back."
56
+ );
57
+ }
58
+ return { ...result, cursor: completion.cursor, kind: "committed" as const };
59
+ },
60
+ { behavior: "immediate" }
61
+ );
62
+ }
63
+ }
64
+
65
+ export class DrizzlePostgresSyncAdapter<Db extends BunSQLDatabase<Schema>>
66
+ extends PostgresSyncAdapter
67
+ implements TransactionalSyncAdapter<Transaction<Db>, "async">
68
+ {
69
+ readonly transactionMode = "async" as const;
70
+ private readonly db: Db;
71
+ private readonly syncNamespace: string;
72
+
73
+ constructor(options: { db: Db & { $client: import("bun").SQL }; namespace: string }) {
74
+ const sql = transactionSql(<Rows>(strings: TemplateStringsArray, values: unknown[]) =>
75
+ Promise.resolve(options.db.execute(drizzleSql(strings, ...values))).then(
76
+ (rows) => rows as unknown as Rows
77
+ )
78
+ );
79
+ sql.begin = (callback) =>
80
+ options.db.transaction((tx) =>
81
+ callback(
82
+ transactionSql(<Rows>(strings: TemplateStringsArray, values: unknown[]) =>
83
+ Promise.resolve(tx.execute(drizzleSql(strings, ...values))).then(
84
+ (rows) => rows as unknown as Rows
85
+ )
86
+ )
87
+ )
88
+ );
89
+ super({ namespace: options.namespace, sql, publishNotifications: false });
90
+ this.db = options.db;
91
+ this.syncNamespace = options.namespace;
92
+ }
93
+
94
+ executeMutation<T>(
95
+ lease: MutationLease,
96
+ callback: (tx: Transaction<Db>) => AtomicMutationValue<T> | Promise<AtomicMutationValue<T>>
97
+ ): Promise<AtomicMutationResult<T>> {
98
+ return this.db.transaction((tx) => {
99
+ const sql = transactionSql(<Rows>(strings: TemplateStringsArray, values: unknown[]) =>
100
+ Promise.resolve(tx.execute(drizzleSql(strings, ...values))).then(
101
+ (rows) => rows as unknown as Rows
102
+ )
103
+ );
104
+ return executePostgresMutation(
105
+ new PostgresSyncAdapter({
106
+ namespace: this.syncNamespace,
107
+ sql,
108
+ publishNotifications: false,
109
+ }),
110
+ lease,
111
+ tx as Transaction<Db>,
112
+ callback
113
+ );
114
+ });
115
+ }
116
+ }
117
+
118
+ export function drizzleSyncAdapter<Db extends BunSQLiteDatabase<Schema>>(options: {
119
+ db: Db & { $client: import("bun:sqlite").Database };
120
+ namespace: string;
121
+ }): DrizzleSqliteSyncAdapter<Db>;
122
+ export function drizzleSyncAdapter<Db extends BunSQLDatabase<Schema>>(options: {
123
+ db: Db & { $client: import("bun").SQL };
124
+ namespace: string;
125
+ }): DrizzlePostgresSyncAdapter<Db>;
126
+ export function drizzleSyncAdapter(options: {
127
+ db: (BunSQLiteDatabase<Schema> | BunSQLDatabase<Schema>) & {
128
+ $client: import("bun:sqlite").Database | import("bun").SQL;
129
+ };
130
+ namespace: string;
131
+ }):
132
+ | DrizzleSqliteSyncAdapter<BunSQLiteDatabase<Schema>>
133
+ | DrizzlePostgresSyncAdapter<BunSQLDatabase<Schema>> {
134
+ if (!(options.db.$client instanceof Database)) {
135
+ return new DrizzlePostgresSyncAdapter(
136
+ options as { db: BunSQLDatabase<Schema> & { $client: import("bun").SQL }; namespace: string }
137
+ );
138
+ }
139
+ return new DrizzleSqliteSyncAdapter(
140
+ options as {
141
+ db: BunSQLiteDatabase<Schema> & { $client: import("bun:sqlite").Database };
142
+ namespace: string;
143
+ }
144
+ );
145
+ }
@@ -0,0 +1 @@
1
+ export class MutationLeaseLost extends Error {}
@@ -32,12 +32,8 @@ export function sha256Hex(source: string): string {
32
32
 
33
33
  export function createMutationFingerprint(input: FingerprintInput): string {
34
34
  const url = new URL(input.request.url);
35
- const query = [...url.searchParams.entries()].sort(
36
- ([leftKey, leftValue], [rightKey, rightValue]) =>
37
- leftKey === rightKey
38
- ? compareCodePoints(leftValue, rightValue)
39
- : compareCodePoints(leftKey, rightKey)
40
- );
35
+ url.searchParams.sort();
36
+ const query = [...url.searchParams.entries()];
41
37
  const source = JSON.stringify({
42
38
  body: canonicalize(input.body) ?? null,
43
39
  contentType: input.request.headers.get("content-type") ?? "",
@@ -18,7 +18,10 @@ export const runWithSyncPath = runWithSyncPathImplementation;
18
18
 
19
19
  export type PollingSyncNotifier = PollingSyncNotifierImplementation;
20
20
 
21
+ export type { SyncInvalidationInput } from "../auto-invalidate/types.ts";
21
22
  export type {
23
+ AtomicMutationResult,
24
+ AtomicMutationValue,
22
25
  BeginMutationInput,
23
26
  BeginMutationResult,
24
27
  ChangePage,
@@ -30,9 +33,12 @@ export type {
30
33
  SyncAdapter,
31
34
  SyncChange,
32
35
  SyncInvalidation,
36
+ SyncMutation,
33
37
  SyncNotifier,
34
38
  SyncRuntimeOptions,
35
39
  SyncSubscription,
40
+ SyncTransaction,
41
+ TransactionalSyncAdapter,
36
42
  } from "./adapter.ts";
37
43
  export type { FurinSyncOption, FurinSyncOptions } from "./config.ts";
38
44
  export type { SyncInput, SyncRouteOption } from "./plugin.ts";
@@ -0,0 +1,69 @@
1
+ import type { Context, Elysia } from "elysia";
2
+ import { createContext } from "elysia/context";
3
+
4
+ const mutationBeginnings = new WeakMap<Request, () => Promise<Response | undefined>>();
5
+ const installedApplications = new WeakSet<Elysia>();
6
+ const installedContexts = new WeakSet<object>();
7
+
8
+ export function prepareMutationHandler(
9
+ context: Pick<Context, "request">,
10
+ begin: () => Promise<Response | undefined>
11
+ ): void {
12
+ if (!installedContexts.has(context.constructor)) {
13
+ throw new Error(
14
+ "[furin] Install furinSync on the final Elysia application, or mount furin({ sync }), before using mutation routes."
15
+ );
16
+ }
17
+ mutationBeginnings.set(context.request, begin);
18
+ }
19
+
20
+ /** Keep reservation and replay after authorization, including mounted route plugins. */
21
+ export function installMutationHandlers(app: Elysia): void {
22
+ if (installedApplications.has(app)) {
23
+ return;
24
+ }
25
+ installedApplications.add(app);
26
+ app.decorate("_furinMutationHandlers", true);
27
+ app.wrap((fetch) => {
28
+ installedContexts.add(createContext(app));
29
+ return fetch;
30
+ });
31
+ const compileHandler = app.handler.bind(app);
32
+ app.handler = (index, immediate, route, aliases, table) => {
33
+ // Passing the complete tuple also preserves the wrapper in Elysia's JIT path.
34
+ const nativeRoute =
35
+ route ??
36
+ (table
37
+ ? ([
38
+ table.method[index],
39
+ table.path[index],
40
+ table.handler[index],
41
+ table.owner[index],
42
+ table.localHook[index],
43
+ table.appHook[index],
44
+ table.inheritedChain[index],
45
+ table.macroScope?.get(index),
46
+ ] as NonNullable<typeof route>)
47
+ : app["~routes"][index]);
48
+ if (!nativeRoute || ["GET", "HEAD", "OPTIONS", "WS"].includes(nativeRoute[0])) {
49
+ return compileHandler(index, immediate, route, aliases, table);
50
+ }
51
+ const [method, path, handle, owner, hooks, chain, inherited, macroScope] = nativeRoute;
52
+ const wrapped = async (context: Context) => {
53
+ const begin = mutationBeginnings.get(context.request);
54
+ mutationBeginnings.delete(context.request);
55
+ const response = await begin?.();
56
+ if (response !== undefined) {
57
+ return response;
58
+ }
59
+ return typeof handle === "function" ? handle(context) : handle;
60
+ };
61
+ return compileHandler(
62
+ index,
63
+ immediate,
64
+ [method, path, wrapped, owner, hooks, chain, inherited, macroScope],
65
+ aliases,
66
+ table
67
+ );
68
+ };
69
+ }