@ivogt/rsc-router 0.0.0-experimental.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 (123) hide show
  1. package/README.md +19 -0
  2. package/package.json +131 -0
  3. package/src/__mocks__/version.ts +6 -0
  4. package/src/__tests__/route-definition.test.ts +63 -0
  5. package/src/browser/event-controller.ts +876 -0
  6. package/src/browser/index.ts +18 -0
  7. package/src/browser/link-interceptor.ts +121 -0
  8. package/src/browser/lru-cache.ts +69 -0
  9. package/src/browser/merge-segment-loaders.ts +126 -0
  10. package/src/browser/navigation-bridge.ts +891 -0
  11. package/src/browser/navigation-client.ts +155 -0
  12. package/src/browser/navigation-store.ts +823 -0
  13. package/src/browser/partial-update.ts +545 -0
  14. package/src/browser/react/Link.tsx +248 -0
  15. package/src/browser/react/NavigationProvider.tsx +228 -0
  16. package/src/browser/react/ScrollRestoration.tsx +94 -0
  17. package/src/browser/react/context.ts +53 -0
  18. package/src/browser/react/index.ts +52 -0
  19. package/src/browser/react/location-state-shared.ts +120 -0
  20. package/src/browser/react/location-state.ts +62 -0
  21. package/src/browser/react/use-action.ts +240 -0
  22. package/src/browser/react/use-client-cache.ts +56 -0
  23. package/src/browser/react/use-handle.ts +178 -0
  24. package/src/browser/react/use-link-status.ts +134 -0
  25. package/src/browser/react/use-navigation.ts +150 -0
  26. package/src/browser/react/use-segments.ts +188 -0
  27. package/src/browser/request-controller.ts +149 -0
  28. package/src/browser/rsc-router.tsx +310 -0
  29. package/src/browser/scroll-restoration.ts +324 -0
  30. package/src/browser/server-action-bridge.ts +747 -0
  31. package/src/browser/shallow.ts +35 -0
  32. package/src/browser/types.ts +443 -0
  33. package/src/cache/__tests__/memory-segment-store.test.ts +487 -0
  34. package/src/cache/__tests__/memory-store.test.ts +484 -0
  35. package/src/cache/cache-scope.ts +565 -0
  36. package/src/cache/cf/__tests__/cf-cache-store.test.ts +361 -0
  37. package/src/cache/cf/cf-cache-store.ts +274 -0
  38. package/src/cache/cf/index.ts +19 -0
  39. package/src/cache/index.ts +52 -0
  40. package/src/cache/memory-segment-store.ts +150 -0
  41. package/src/cache/memory-store.ts +253 -0
  42. package/src/cache/types.ts +366 -0
  43. package/src/client.rsc.tsx +88 -0
  44. package/src/client.tsx +609 -0
  45. package/src/components/DefaultDocument.tsx +20 -0
  46. package/src/default-error-boundary.tsx +88 -0
  47. package/src/deps/browser.ts +8 -0
  48. package/src/deps/html-stream-client.ts +2 -0
  49. package/src/deps/html-stream-server.ts +2 -0
  50. package/src/deps/rsc.ts +10 -0
  51. package/src/deps/ssr.ts +2 -0
  52. package/src/errors.ts +259 -0
  53. package/src/handle.ts +120 -0
  54. package/src/handles/MetaTags.tsx +178 -0
  55. package/src/handles/index.ts +6 -0
  56. package/src/handles/meta.ts +247 -0
  57. package/src/href-client.ts +128 -0
  58. package/src/href.ts +139 -0
  59. package/src/index.rsc.ts +69 -0
  60. package/src/index.ts +84 -0
  61. package/src/loader.rsc.ts +204 -0
  62. package/src/loader.ts +47 -0
  63. package/src/network-error-thrower.tsx +21 -0
  64. package/src/outlet-context.ts +15 -0
  65. package/src/root-error-boundary.tsx +277 -0
  66. package/src/route-content-wrapper.tsx +198 -0
  67. package/src/route-definition.ts +1333 -0
  68. package/src/route-map-builder.ts +140 -0
  69. package/src/route-types.ts +148 -0
  70. package/src/route-utils.ts +89 -0
  71. package/src/router/__tests__/match-context.test.ts +104 -0
  72. package/src/router/__tests__/match-pipelines.test.ts +537 -0
  73. package/src/router/__tests__/match-result.test.ts +566 -0
  74. package/src/router/__tests__/on-error.test.ts +935 -0
  75. package/src/router/__tests__/pattern-matching.test.ts +577 -0
  76. package/src/router/error-handling.ts +287 -0
  77. package/src/router/handler-context.ts +60 -0
  78. package/src/router/loader-resolution.ts +326 -0
  79. package/src/router/manifest.ts +116 -0
  80. package/src/router/match-context.ts +261 -0
  81. package/src/router/match-middleware/background-revalidation.ts +236 -0
  82. package/src/router/match-middleware/cache-lookup.ts +261 -0
  83. package/src/router/match-middleware/cache-store.ts +250 -0
  84. package/src/router/match-middleware/index.ts +81 -0
  85. package/src/router/match-middleware/intercept-resolution.ts +268 -0
  86. package/src/router/match-middleware/segment-resolution.ts +174 -0
  87. package/src/router/match-pipelines.ts +214 -0
  88. package/src/router/match-result.ts +212 -0
  89. package/src/router/metrics.ts +62 -0
  90. package/src/router/middleware.test.ts +1355 -0
  91. package/src/router/middleware.ts +748 -0
  92. package/src/router/pattern-matching.ts +271 -0
  93. package/src/router/revalidation.ts +190 -0
  94. package/src/router/router-context.ts +299 -0
  95. package/src/router/types.ts +96 -0
  96. package/src/router.ts +3484 -0
  97. package/src/rsc/__tests__/helpers.test.ts +175 -0
  98. package/src/rsc/handler.ts +942 -0
  99. package/src/rsc/helpers.ts +64 -0
  100. package/src/rsc/index.ts +56 -0
  101. package/src/rsc/nonce.ts +18 -0
  102. package/src/rsc/types.ts +225 -0
  103. package/src/segment-system.tsx +405 -0
  104. package/src/server/__tests__/request-context.test.ts +171 -0
  105. package/src/server/context.ts +340 -0
  106. package/src/server/handle-store.ts +230 -0
  107. package/src/server/loader-registry.ts +174 -0
  108. package/src/server/request-context.ts +470 -0
  109. package/src/server/root-layout.tsx +10 -0
  110. package/src/server/tsconfig.json +14 -0
  111. package/src/server.ts +126 -0
  112. package/src/ssr/__tests__/ssr-handler.test.tsx +188 -0
  113. package/src/ssr/index.tsx +215 -0
  114. package/src/types.ts +1473 -0
  115. package/src/use-loader.tsx +346 -0
  116. package/src/vite/__tests__/expose-loader-id.test.ts +117 -0
  117. package/src/vite/expose-action-id.ts +344 -0
  118. package/src/vite/expose-handle-id.ts +209 -0
  119. package/src/vite/expose-loader-id.ts +357 -0
  120. package/src/vite/expose-location-state-id.ts +177 -0
  121. package/src/vite/index.ts +608 -0
  122. package/src/vite/version.d.ts +12 -0
  123. package/src/vite/virtual-entries.ts +109 -0
@@ -0,0 +1,1355 @@
1
+ import { describe, it, expect, vi } from "vitest";
2
+ import {
3
+ parsePattern,
4
+ extractParams,
5
+ parseCookies,
6
+ serializeCookie,
7
+ matchMiddleware,
8
+ executeMiddleware,
9
+ executeInterceptMiddleware,
10
+ executeServerActionMiddleware,
11
+ executeLoaderMiddleware,
12
+ collectRouteMiddleware,
13
+ type MiddlewareFn,
14
+ type MiddlewareEntry,
15
+ type MiddlewareCollectableEntry,
16
+ } from "./middleware";
17
+
18
+ describe("middleware", () => {
19
+ describe("parsePattern", () => {
20
+ it("should match all routes with *", () => {
21
+ const { regex } = parsePattern("*");
22
+ expect(regex.test("/")).toBe(true);
23
+ expect(regex.test("/foo")).toBe(true);
24
+ expect(regex.test("/foo/bar/baz")).toBe(true);
25
+ });
26
+
27
+ it("should match exact path", () => {
28
+ const { regex } = parsePattern("/admin");
29
+ expect(regex.test("/admin")).toBe(true);
30
+ expect(regex.test("/admin/")).toBe(true);
31
+ expect(regex.test("/admin/users")).toBe(false);
32
+ expect(regex.test("/administrator")).toBe(false);
33
+ });
34
+
35
+ it("should match prefix with wildcard", () => {
36
+ const { regex } = parsePattern("/admin/*");
37
+ expect(regex.test("/admin")).toBe(true);
38
+ expect(regex.test("/admin/")).toBe(true);
39
+ expect(regex.test("/admin/users")).toBe(true);
40
+ expect(regex.test("/admin/users/123")).toBe(true);
41
+ expect(regex.test("/administrator")).toBe(false);
42
+ });
43
+
44
+ it("should extract params from pattern", () => {
45
+ const { regex, paramNames } = parsePattern("/users/:id");
46
+ expect(paramNames).toEqual(["id"]);
47
+ expect(regex.test("/users/123")).toBe(true);
48
+ expect(regex.test("/users/abc")).toBe(true);
49
+ expect(regex.test("/users/")).toBe(false);
50
+ });
51
+
52
+ it("should extract multiple params", () => {
53
+ const { regex, paramNames } = parsePattern("/users/:userId/posts/:postId");
54
+ expect(paramNames).toEqual(["userId", "postId"]);
55
+ expect(regex.test("/users/123/posts/456")).toBe(true);
56
+ });
57
+
58
+ it("should handle param with wildcard", () => {
59
+ const { regex, paramNames } = parsePattern("/api/:version/*");
60
+ expect(paramNames).toEqual(["version"]);
61
+ expect(regex.test("/api/v1/users")).toBe(true);
62
+ expect(regex.test("/api/v2/users/123")).toBe(true);
63
+ });
64
+ });
65
+
66
+ describe("extractParams", () => {
67
+ it("should extract single param", () => {
68
+ const { regex, paramNames } = parsePattern("/users/:id");
69
+ const params = extractParams("/users/123", regex, paramNames);
70
+ expect(params).toEqual({ id: "123" });
71
+ });
72
+
73
+ it("should extract multiple params", () => {
74
+ const { regex, paramNames } = parsePattern("/users/:userId/posts/:postId");
75
+ const params = extractParams("/users/abc/posts/xyz", regex, paramNames);
76
+ expect(params).toEqual({ userId: "abc", postId: "xyz" });
77
+ });
78
+
79
+ it("should return empty object for no match", () => {
80
+ const { regex, paramNames } = parsePattern("/users/:id");
81
+ const params = extractParams("/posts/123", regex, paramNames);
82
+ expect(params).toEqual({});
83
+ });
84
+ });
85
+
86
+ describe("parseCookies", () => {
87
+ it("should parse single cookie", () => {
88
+ const cookies = parseCookies("session=abc123");
89
+ expect(cookies).toEqual({ session: "abc123" });
90
+ });
91
+
92
+ it("should parse multiple cookies", () => {
93
+ const cookies = parseCookies("session=abc123; user=john; theme=dark");
94
+ expect(cookies).toEqual({
95
+ session: "abc123",
96
+ user: "john",
97
+ theme: "dark",
98
+ });
99
+ });
100
+
101
+ it("should handle encoded values", () => {
102
+ const cookies = parseCookies("data=hello%20world");
103
+ expect(cookies).toEqual({ data: "hello world" });
104
+ });
105
+
106
+ it("should return empty object for null", () => {
107
+ const cookies = parseCookies(null);
108
+ expect(cookies).toEqual({});
109
+ });
110
+ });
111
+
112
+ describe("serializeCookie", () => {
113
+ it("should serialize basic cookie", () => {
114
+ const cookie = serializeCookie("session", "abc123");
115
+ expect(cookie).toBe("session=abc123");
116
+ });
117
+
118
+ it("should include all options", () => {
119
+ const cookie = serializeCookie("session", "abc123", {
120
+ domain: "example.com",
121
+ path: "/",
122
+ maxAge: 3600,
123
+ httpOnly: true,
124
+ secure: true,
125
+ sameSite: "lax",
126
+ });
127
+ expect(cookie).toContain("session=abc123");
128
+ expect(cookie).toContain("Domain=example.com");
129
+ expect(cookie).toContain("Path=/");
130
+ expect(cookie).toContain("Max-Age=3600");
131
+ expect(cookie).toContain("HttpOnly");
132
+ expect(cookie).toContain("Secure");
133
+ expect(cookie).toContain("SameSite=lax");
134
+ });
135
+
136
+ it("should handle expires date", () => {
137
+ const expires = new Date("2025-01-01T00:00:00Z");
138
+ const cookie = serializeCookie("session", "abc123", { expires });
139
+ expect(cookie).toContain("Expires=Wed, 01 Jan 2025 00:00:00 GMT");
140
+ });
141
+ });
142
+
143
+ describe("matchMiddleware", () => {
144
+ it("should match global middleware (no pattern)", () => {
145
+ const entries: MiddlewareEntry<unknown>[] = [
146
+ {
147
+ pattern: null,
148
+ regex: null,
149
+ paramNames: [],
150
+ handler: vi.fn(),
151
+ mountPrefix: null,
152
+ },
153
+ ];
154
+ const matches = matchMiddleware("/any/path", entries);
155
+ expect(matches).toHaveLength(1);
156
+ });
157
+
158
+ it("should match pattern-based middleware", () => {
159
+ const { regex, paramNames } = parsePattern("/admin/*");
160
+ const entries: MiddlewareEntry<unknown>[] = [
161
+ {
162
+ pattern: "/admin/*",
163
+ regex,
164
+ paramNames,
165
+ handler: vi.fn(),
166
+ mountPrefix: null,
167
+ },
168
+ ];
169
+
170
+ expect(matchMiddleware("/admin/users", entries)).toHaveLength(1);
171
+ expect(matchMiddleware("/public", entries)).toHaveLength(0);
172
+ });
173
+
174
+ it("should extract params when matching", () => {
175
+ const { regex, paramNames } = parsePattern("/users/:id/*");
176
+ const entries: MiddlewareEntry<unknown>[] = [
177
+ {
178
+ pattern: "/users/:id/*",
179
+ regex,
180
+ paramNames,
181
+ handler: vi.fn(),
182
+ mountPrefix: null,
183
+ },
184
+ ];
185
+
186
+ const matches = matchMiddleware("/users/123/posts", entries);
187
+ expect(matches).toHaveLength(1);
188
+ expect(matches[0].params).toEqual({ id: "123" });
189
+ });
190
+
191
+ it("should return multiple matches in order", () => {
192
+ const entries: MiddlewareEntry<unknown>[] = [
193
+ {
194
+ pattern: null,
195
+ regex: null,
196
+ paramNames: [],
197
+ handler: vi.fn(),
198
+ mountPrefix: null,
199
+ },
200
+ {
201
+ pattern: "/admin/*",
202
+ ...parsePattern("/admin/*"),
203
+ handler: vi.fn(),
204
+ mountPrefix: null,
205
+ },
206
+ ];
207
+
208
+ const matches = matchMiddleware("/admin/users", entries);
209
+ expect(matches).toHaveLength(2);
210
+ });
211
+ });
212
+
213
+ describe("executeMiddleware", () => {
214
+ const createMockEntry = (
215
+ handler: MiddlewareFn<unknown>
216
+ ): { entry: MiddlewareEntry<unknown>; params: Record<string, string> } => ({
217
+ entry: {
218
+ pattern: null,
219
+ regex: null,
220
+ paramNames: [],
221
+ handler,
222
+ mountPrefix: null,
223
+ },
224
+ params: {},
225
+ });
226
+
227
+ it("should execute single middleware and return response", async () => {
228
+ const middleware: MiddlewareFn<unknown> = async (ctx, next) => {
229
+ const response = await next();
230
+ response.headers.set("X-Test", "value");
231
+ return response;
232
+ };
233
+
234
+ const response = await executeMiddleware(
235
+ [createMockEntry(middleware)],
236
+ new Request("http://localhost/test"),
237
+ {},
238
+ {},
239
+ async () => new Response("OK")
240
+ );
241
+
242
+ expect(response.headers.get("X-Test")).toBe("value");
243
+ expect(await response.text()).toBe("OK");
244
+ });
245
+
246
+ it("should execute middleware in order", async () => {
247
+ const order: number[] = [];
248
+
249
+ const mw1: MiddlewareFn<unknown> = async (ctx, next) => {
250
+ order.push(1);
251
+ await next();
252
+ order.push(4);
253
+ };
254
+
255
+ const mw2: MiddlewareFn<unknown> = async (ctx, next) => {
256
+ order.push(2);
257
+ await next();
258
+ order.push(3);
259
+ };
260
+
261
+ await executeMiddleware(
262
+ [createMockEntry(mw1), createMockEntry(mw2)],
263
+ new Request("http://localhost/test"),
264
+ {},
265
+ {},
266
+ async () => new Response("OK")
267
+ );
268
+
269
+ expect(order).toEqual([1, 2, 3, 4]);
270
+ });
271
+
272
+ it("should allow ctx.res access after next()", async () => {
273
+ const middleware: MiddlewareFn<unknown> = async (ctx, next) => {
274
+ await next();
275
+ ctx.res.headers.set("X-Via-Ctx", "yes");
276
+ // No return - forgiving API
277
+ };
278
+
279
+ const response = await executeMiddleware(
280
+ [createMockEntry(middleware)],
281
+ new Request("http://localhost/test"),
282
+ {},
283
+ {},
284
+ async () => new Response("OK")
285
+ );
286
+
287
+ expect(response.headers.get("X-Via-Ctx")).toBe("yes");
288
+ });
289
+
290
+ it("should allow ctx.header() shorthand", async () => {
291
+ const middleware: MiddlewareFn<unknown> = async (ctx, next) => {
292
+ await next();
293
+ ctx.header("X-Shorthand", "works");
294
+ };
295
+
296
+ const response = await executeMiddleware(
297
+ [createMockEntry(middleware)],
298
+ new Request("http://localhost/test"),
299
+ {},
300
+ {},
301
+ async () => new Response("OK")
302
+ );
303
+
304
+ expect(response.headers.get("X-Shorthand")).toBe("works");
305
+ });
306
+
307
+ it("should short-circuit on early Response return", async () => {
308
+ const handler = vi.fn();
309
+
310
+ const middleware: MiddlewareFn<unknown> = async () => {
311
+ return new Response("Blocked", { status: 403 });
312
+ };
313
+
314
+ const response = await executeMiddleware(
315
+ [createMockEntry(middleware)],
316
+ new Request("http://localhost/test"),
317
+ {},
318
+ {},
319
+ async () => {
320
+ handler();
321
+ return new Response("OK");
322
+ }
323
+ );
324
+
325
+ expect(response.status).toBe(403);
326
+ expect(await response.text()).toBe("Blocked");
327
+ expect(handler).not.toHaveBeenCalled();
328
+ });
329
+
330
+ it("should catch errors from handler", async () => {
331
+ const middleware: MiddlewareFn<unknown> = async (ctx, next) => {
332
+ try {
333
+ return await next();
334
+ } catch (error) {
335
+ return new Response("Error caught", { status: 500 });
336
+ }
337
+ };
338
+
339
+ const response = await executeMiddleware(
340
+ [createMockEntry(middleware)],
341
+ new Request("http://localhost/test"),
342
+ {},
343
+ {},
344
+ async () => {
345
+ throw new Error("Handler error");
346
+ }
347
+ );
348
+
349
+ expect(response.status).toBe(500);
350
+ expect(await response.text()).toBe("Error caught");
351
+ });
352
+
353
+ it("should share variables with handler via ctx.set/get", async () => {
354
+ const variables: Record<string, any> = {};
355
+
356
+ const middleware: MiddlewareFn<unknown> = async (ctx, next) => {
357
+ ctx.set("user", { id: "123", name: "John" });
358
+ await next();
359
+ };
360
+
361
+ await executeMiddleware(
362
+ [createMockEntry(middleware)],
363
+ new Request("http://localhost/test"),
364
+ {},
365
+ variables,
366
+ async () => new Response("OK")
367
+ );
368
+
369
+ expect(variables).toEqual({ user: { id: "123", name: "John" } });
370
+ });
371
+
372
+ it("should read cookies from request", async () => {
373
+ let sessionValue: string | undefined;
374
+
375
+ const middleware: MiddlewareFn<unknown> = async (ctx, next) => {
376
+ sessionValue = ctx.cookie("session");
377
+ await next();
378
+ };
379
+
380
+ const request = new Request("http://localhost/test", {
381
+ headers: { Cookie: "session=abc123" },
382
+ });
383
+
384
+ await executeMiddleware(
385
+ [createMockEntry(middleware)],
386
+ request,
387
+ {},
388
+ {},
389
+ async () => new Response("OK")
390
+ );
391
+
392
+ expect(sessionValue).toBe("abc123");
393
+ });
394
+
395
+ it("should set cookies on response", async () => {
396
+ const middleware: MiddlewareFn<unknown> = async (ctx, next) => {
397
+ ctx.setCookie("session", "xyz789", { httpOnly: true });
398
+ await next();
399
+ };
400
+
401
+ const response = await executeMiddleware(
402
+ [createMockEntry(middleware)],
403
+ new Request("http://localhost/test"),
404
+ {},
405
+ {},
406
+ async () => new Response("OK")
407
+ );
408
+
409
+ const setCookie = response.headers.get("Set-Cookie");
410
+ expect(setCookie).toContain("session=xyz789");
411
+ expect(setCookie).toContain("HttpOnly");
412
+ });
413
+
414
+ it("should delete cookies", async () => {
415
+ const middleware: MiddlewareFn<unknown> = async (ctx, next) => {
416
+ ctx.deleteCookie("session");
417
+ await next();
418
+ };
419
+
420
+ const response = await executeMiddleware(
421
+ [createMockEntry(middleware)],
422
+ new Request("http://localhost/test"),
423
+ {},
424
+ {},
425
+ async () => new Response("OK")
426
+ );
427
+
428
+ const setCookie = response.headers.get("Set-Cookie");
429
+ expect(setCookie).toContain("session=");
430
+ expect(setCookie).toContain("Max-Age=0");
431
+ });
432
+
433
+ it("should throw if middleware doesn't call next() or return", async () => {
434
+ const middleware: MiddlewareFn<unknown> = async () => {
435
+ // Does nothing
436
+ };
437
+
438
+ await expect(
439
+ executeMiddleware(
440
+ [createMockEntry(middleware)],
441
+ new Request("http://localhost/test"),
442
+ {},
443
+ {},
444
+ async () => new Response("OK")
445
+ )
446
+ ).rejects.toThrow("Middleware must call next()");
447
+ });
448
+
449
+ it("should allow setting headers before next() via ctx.res", async () => {
450
+ const middleware: MiddlewareFn<unknown> = async (ctx, next) => {
451
+ // Set header before next() using stub response
452
+ ctx.res.headers.set("X-Before-Next", "works");
453
+ await next();
454
+ // Set header after next() as well
455
+ ctx.res.headers.set("X-After-Next", "also-works");
456
+ };
457
+
458
+ const response = await executeMiddleware(
459
+ [createMockEntry(middleware)],
460
+ new Request("http://localhost/test"),
461
+ {},
462
+ {},
463
+ async () => new Response("OK", { headers: { "X-Handler": "original" } })
464
+ );
465
+
466
+ // Both headers should be present
467
+ expect(response.headers.get("X-Before-Next")).toBe("works");
468
+ expect(response.headers.get("X-After-Next")).toBe("also-works");
469
+ expect(response.headers.get("X-Handler")).toBe("original");
470
+ });
471
+
472
+ it("should allow setting headers before next() via ctx.header()", async () => {
473
+ const middleware: MiddlewareFn<unknown> = async (ctx, next) => {
474
+ // Set header before next() using shorthand
475
+ ctx.header("X-Request-Id", "12345");
476
+ await next();
477
+ };
478
+
479
+ const response = await executeMiddleware(
480
+ [createMockEntry(middleware)],
481
+ new Request("http://localhost/test"),
482
+ {},
483
+ {},
484
+ async () => new Response("OK")
485
+ );
486
+
487
+ expect(response.headers.get("X-Request-Id")).toBe("12345");
488
+ });
489
+
490
+ it("should pass params to middleware context", async () => {
491
+ let receivedParams: Record<string, string> = {};
492
+
493
+ const middleware: MiddlewareFn<unknown> = async (ctx, next) => {
494
+ receivedParams = ctx.params;
495
+ await next();
496
+ };
497
+
498
+ await executeMiddleware(
499
+ [
500
+ {
501
+ entry: {
502
+ pattern: "/users/:id/*",
503
+ ...parsePattern("/users/:id/*"),
504
+ handler: middleware,
505
+ mountPrefix: null,
506
+ },
507
+ params: { id: "123" },
508
+ },
509
+ ],
510
+ new Request("http://localhost/users/123/profile"),
511
+ {},
512
+ {},
513
+ async () => new Response("OK")
514
+ );
515
+
516
+ expect(receivedParams).toEqual({ id: "123" });
517
+ });
518
+
519
+ it("should allow middleware to replace response via ctx.res setter", async () => {
520
+ const middleware: MiddlewareFn<unknown> = async (ctx, next) => {
521
+ await next();
522
+ ctx.res = new Response("Replaced", { status: 201 });
523
+ };
524
+
525
+ const response = await executeMiddleware(
526
+ [createMockEntry(middleware)],
527
+ new Request("http://localhost/test"),
528
+ {},
529
+ {},
530
+ async () => new Response("Original")
531
+ );
532
+
533
+ expect(response.status).toBe(201);
534
+ expect(await response.text()).toBe("Replaced");
535
+ });
536
+
537
+ it("should warn when middleware returns non-Response value", async () => {
538
+ const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => {});
539
+
540
+ const middleware: MiddlewareFn<unknown> = async (ctx, next) => {
541
+ await next();
542
+ return "some string" as any; // Incorrect return type
543
+ };
544
+
545
+ await executeMiddleware(
546
+ [createMockEntry(middleware)],
547
+ new Request("http://localhost/test"),
548
+ {},
549
+ {},
550
+ async () => new Response("OK")
551
+ );
552
+
553
+ expect(warnSpy).toHaveBeenCalledWith(
554
+ expect.stringContaining('returned string instead of Response or undefined')
555
+ );
556
+
557
+ warnSpy.mockRestore();
558
+ });
559
+
560
+ it("should warn about object return values", async () => {
561
+ const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => {});
562
+
563
+ const middleware: MiddlewareFn<unknown> = async (ctx, next) => {
564
+ await next();
565
+ return { data: "test" } as any; // Incorrect return type
566
+ };
567
+
568
+ await executeMiddleware(
569
+ [createMockEntry(middleware)],
570
+ new Request("http://localhost/test"),
571
+ {},
572
+ {},
573
+ async () => new Response("OK")
574
+ );
575
+
576
+ expect(warnSpy).toHaveBeenCalledWith(
577
+ expect.stringContaining('returned object instead of Response or undefined')
578
+ );
579
+
580
+ warnSpy.mockRestore();
581
+ });
582
+ });
583
+
584
+ describe("collectRouteMiddleware", () => {
585
+ const mw1: MiddlewareFn<unknown> = async (ctx, next) => { await next(); };
586
+ const mw2: MiddlewareFn<unknown> = async (ctx, next) => { await next(); };
587
+ const mw3: MiddlewareFn<unknown> = async (ctx, next) => { await next(); };
588
+ const mw4: MiddlewareFn<unknown> = async (ctx, next) => { await next(); };
589
+
590
+ it("should return empty array for empty entries", () => {
591
+ const result = collectRouteMiddleware([], { id: "123" });
592
+ expect(result).toEqual([]);
593
+ });
594
+
595
+ it("should return empty array for entries with no middleware", () => {
596
+ const entries: MiddlewareCollectableEntry[] = [
597
+ { middleware: [], layout: [] },
598
+ { middleware: undefined, layout: undefined },
599
+ ];
600
+ const result = collectRouteMiddleware(entries, { id: "123" });
601
+ expect(result).toEqual([]);
602
+ });
603
+
604
+ it("should collect middleware from a single entry", () => {
605
+ const entries: MiddlewareCollectableEntry[] = [
606
+ { middleware: [mw1, mw2] },
607
+ ];
608
+ const params = { id: "123" };
609
+
610
+ const result = collectRouteMiddleware(entries, params);
611
+
612
+ expect(result).toHaveLength(2);
613
+ expect(result[0].handler).toBe(mw1);
614
+ expect(result[0].params).toBe(params);
615
+ expect(result[1].handler).toBe(mw2);
616
+ expect(result[1].params).toBe(params);
617
+ });
618
+
619
+ it("should collect middleware from multiple entries in order", () => {
620
+ const entries: MiddlewareCollectableEntry[] = [
621
+ { middleware: [mw1] },
622
+ { middleware: [mw2, mw3] },
623
+ ];
624
+ const params = { slug: "test" };
625
+
626
+ const result = collectRouteMiddleware(entries, params);
627
+
628
+ expect(result).toHaveLength(3);
629
+ expect(result[0].handler).toBe(mw1);
630
+ expect(result[1].handler).toBe(mw2);
631
+ expect(result[2].handler).toBe(mw3);
632
+ // All should share the same params reference
633
+ expect(result.every(r => r.params === params)).toBe(true);
634
+ });
635
+
636
+ it("should collect middleware from orphan layouts (recursive)", () => {
637
+ const orphan1: MiddlewareCollectableEntry = { middleware: [mw3] };
638
+ const orphan2: MiddlewareCollectableEntry = { middleware: [mw4] };
639
+ const entries: MiddlewareCollectableEntry[] = [
640
+ { middleware: [mw1, mw2], layout: [orphan1, orphan2] },
641
+ ];
642
+ const params = { id: "456" };
643
+
644
+ const result = collectRouteMiddleware(entries, params);
645
+
646
+ expect(result).toHaveLength(4);
647
+ expect(result[0].handler).toBe(mw1);
648
+ expect(result[1].handler).toBe(mw2);
649
+ expect(result[2].handler).toBe(mw3);
650
+ expect(result[3].handler).toBe(mw4);
651
+ });
652
+
653
+ it("should collect middleware from deeply nested orphan layouts", () => {
654
+ const deepOrphan: MiddlewareCollectableEntry = { middleware: [mw4] };
655
+ const orphan: MiddlewareCollectableEntry = {
656
+ middleware: [mw3],
657
+ layout: [deepOrphan]
658
+ };
659
+ const entries: MiddlewareCollectableEntry[] = [
660
+ { middleware: [mw1], layout: [orphan] },
661
+ ];
662
+ const params = {};
663
+
664
+ const result = collectRouteMiddleware(entries, params);
665
+
666
+ expect(result).toHaveLength(3);
667
+ expect(result[0].handler).toBe(mw1);
668
+ expect(result[1].handler).toBe(mw3);
669
+ expect(result[2].handler).toBe(mw4);
670
+ });
671
+
672
+ it("should handle entries with only orphan layouts (no direct middleware)", () => {
673
+ const orphan: MiddlewareCollectableEntry = { middleware: [mw1, mw2] };
674
+ const entries: MiddlewareCollectableEntry[] = [
675
+ { layout: [orphan] },
676
+ ];
677
+ const params = { page: "1" };
678
+
679
+ const result = collectRouteMiddleware(entries, params);
680
+
681
+ expect(result).toHaveLength(2);
682
+ expect(result[0].handler).toBe(mw1);
683
+ expect(result[1].handler).toBe(mw2);
684
+ });
685
+
686
+ it("should work with iterable (generator) input", () => {
687
+ function* generateEntries(): Generator<MiddlewareCollectableEntry> {
688
+ yield { middleware: [mw1] };
689
+ yield { middleware: [mw2] };
690
+ }
691
+
692
+ const result = collectRouteMiddleware(generateEntries(), { id: "gen" });
693
+
694
+ expect(result).toHaveLength(2);
695
+ expect(result[0].handler).toBe(mw1);
696
+ expect(result[1].handler).toBe(mw2);
697
+ });
698
+
699
+ it("should preserve params reference across all collected middleware", () => {
700
+ const orphan: MiddlewareCollectableEntry = { middleware: [mw3] };
701
+ const entries: MiddlewareCollectableEntry[] = [
702
+ { middleware: [mw1], layout: [orphan] },
703
+ { middleware: [mw2] },
704
+ ];
705
+ const params = { shared: "value" };
706
+
707
+ const result = collectRouteMiddleware(entries, params);
708
+
709
+ // All middleware entries should have the exact same params object
710
+ expect(result).toHaveLength(3);
711
+ result.forEach(r => {
712
+ expect(r.params).toBe(params);
713
+ });
714
+ });
715
+ });
716
+
717
+ describe("executeInterceptMiddleware", () => {
718
+ it("should return null for empty middleware array", async () => {
719
+ const stubResponse = new Response(null, { status: 200 });
720
+ const result = await executeInterceptMiddleware(
721
+ [],
722
+ new Request("http://localhost/test"),
723
+ {},
724
+ {},
725
+ {},
726
+ stubResponse
727
+ );
728
+ expect(result).toBeNull();
729
+ });
730
+
731
+ it("should return null when middleware calls next() without returning Response", async () => {
732
+ const stubResponse = new Response(null, { status: 200 });
733
+ const middleware: MiddlewareFn<unknown> = async (ctx, next) => {
734
+ await next();
735
+ };
736
+
737
+ const result = await executeInterceptMiddleware(
738
+ [middleware],
739
+ new Request("http://localhost/test"),
740
+ {},
741
+ { id: "123" },
742
+ {},
743
+ stubResponse
744
+ );
745
+
746
+ expect(result).toBeNull();
747
+ });
748
+
749
+ it("should return Response when middleware short-circuits", async () => {
750
+ const stubResponse = new Response(null, { status: 200 });
751
+ const middleware: MiddlewareFn<unknown> = async (ctx, next) => {
752
+ return new Response("Blocked", { status: 403 });
753
+ };
754
+
755
+ const result = await executeInterceptMiddleware(
756
+ [middleware],
757
+ new Request("http://localhost/test"),
758
+ {},
759
+ {},
760
+ {},
761
+ stubResponse
762
+ );
763
+
764
+ expect(result).toBeInstanceOf(Response);
765
+ expect(result!.status).toBe(403);
766
+ expect(await result!.text()).toBe("Blocked");
767
+ });
768
+
769
+ it("should apply cookies to short-circuit Response", async () => {
770
+ const stubResponse = new Response(null, { status: 200 });
771
+ const middleware: MiddlewareFn<unknown> = async (ctx, next) => {
772
+ ctx.setCookie("session", "abc123", { path: "/" });
773
+ return new Response("Redirecting", { status: 302 });
774
+ };
775
+
776
+ const result = await executeInterceptMiddleware(
777
+ [middleware],
778
+ new Request("http://localhost/test"),
779
+ {},
780
+ {},
781
+ {},
782
+ stubResponse
783
+ );
784
+
785
+ expect(result).toBeInstanceOf(Response);
786
+ const cookies = result!.headers.get("set-cookie");
787
+ expect(cookies).toContain("session=abc123");
788
+ expect(cookies).toContain("Path=/");
789
+ });
790
+
791
+ it("should apply multiple cookies to short-circuit Response", async () => {
792
+ const stubResponse = new Response(null, { status: 200 });
793
+ const middleware: MiddlewareFn<unknown> = async (ctx, next) => {
794
+ ctx.setCookie("token", "xyz", { httpOnly: true });
795
+ ctx.setCookie("preference", "dark");
796
+ return new Response(null, { status: 302, headers: { Location: "/login" } });
797
+ };
798
+
799
+ const result = await executeInterceptMiddleware(
800
+ [middleware],
801
+ new Request("http://localhost/test"),
802
+ {},
803
+ {},
804
+ {},
805
+ stubResponse
806
+ );
807
+
808
+ expect(result).toBeInstanceOf(Response);
809
+ const cookies = result!.headers.getSetCookie();
810
+ expect(cookies).toHaveLength(2);
811
+ expect(cookies.some(c => c.includes("token=xyz"))).toBe(true);
812
+ expect(cookies.some(c => c.includes("preference=dark"))).toBe(true);
813
+ });
814
+
815
+ it("should share variables between middleware and allow setting new ones", async () => {
816
+ const stubResponse = new Response(null, { status: 200 });
817
+ const variables: Record<string, any> = { existing: "value" };
818
+ let capturedVars: Record<string, any> = {};
819
+
820
+ const middleware: MiddlewareFn<unknown> = async (ctx, next) => {
821
+ capturedVars.existing = ctx.get("existing");
822
+ ctx.set("newVar", "newValue");
823
+ capturedVars.newVar = ctx.get("newVar");
824
+ await next();
825
+ };
826
+
827
+ await executeInterceptMiddleware(
828
+ [middleware],
829
+ new Request("http://localhost/test"),
830
+ {},
831
+ {},
832
+ variables,
833
+ stubResponse
834
+ );
835
+
836
+ expect(capturedVars.existing).toBe("value");
837
+ expect(capturedVars.newVar).toBe("newValue");
838
+ expect(variables.newVar).toBe("newValue");
839
+ });
840
+
841
+ it("should provide params to middleware context", async () => {
842
+ const stubResponse = new Response(null, { status: 200 });
843
+ let capturedParams: Record<string, string> = {};
844
+
845
+ const middleware: MiddlewareFn<unknown> = async (ctx, next) => {
846
+ capturedParams = ctx.params;
847
+ await next();
848
+ };
849
+
850
+ await executeInterceptMiddleware(
851
+ [middleware],
852
+ new Request("http://localhost/test"),
853
+ {},
854
+ { id: "456", slug: "test-slug" },
855
+ {},
856
+ stubResponse
857
+ );
858
+
859
+ expect(capturedParams).toEqual({ id: "456", slug: "test-slug" });
860
+ });
861
+
862
+ it("should execute multiple middleware in order", async () => {
863
+ const stubResponse = new Response(null, { status: 200 });
864
+ const order: number[] = [];
865
+
866
+ const mw1: MiddlewareFn<unknown> = async (ctx, next) => {
867
+ order.push(1);
868
+ await next();
869
+ order.push(4);
870
+ };
871
+
872
+ const mw2: MiddlewareFn<unknown> = async (ctx, next) => {
873
+ order.push(2);
874
+ await next();
875
+ order.push(3);
876
+ };
877
+
878
+ await executeInterceptMiddleware(
879
+ [mw1, mw2],
880
+ new Request("http://localhost/test"),
881
+ {},
882
+ {},
883
+ {},
884
+ stubResponse
885
+ );
886
+
887
+ expect(order).toEqual([1, 2, 3, 4]);
888
+ });
889
+
890
+ it("should stop execution when middleware returns Response", async () => {
891
+ const stubResponse = new Response(null, { status: 200 });
892
+ const order: number[] = [];
893
+
894
+ const mw1: MiddlewareFn<unknown> = async (ctx, next) => {
895
+ order.push(1);
896
+ return new Response("Stopped at mw1", { status: 401 });
897
+ };
898
+
899
+ const mw2: MiddlewareFn<unknown> = async (ctx, next) => {
900
+ order.push(2);
901
+ await next();
902
+ };
903
+
904
+ const result = await executeInterceptMiddleware(
905
+ [mw1, mw2],
906
+ new Request("http://localhost/test"),
907
+ {},
908
+ {},
909
+ {},
910
+ stubResponse
911
+ );
912
+
913
+ expect(order).toEqual([1]);
914
+ expect(result!.status).toBe(401);
915
+ });
916
+
917
+ it("should allow ctx.res access after next() without throwing", async () => {
918
+ const stubResponse = new Response(null, { status: 200 });
919
+ let resStatus: number | undefined;
920
+
921
+ const middleware: MiddlewareFn<unknown> = async (ctx, next) => {
922
+ await next();
923
+ // This should not throw - ctx.res should be accessible
924
+ resStatus = ctx.res.status;
925
+ };
926
+
927
+ const result = await executeInterceptMiddleware(
928
+ [middleware],
929
+ new Request("http://localhost/test"),
930
+ {},
931
+ {},
932
+ {},
933
+ stubResponse
934
+ );
935
+
936
+ expect(resStatus).toBe(200);
937
+ expect(result).toBeNull(); // No short-circuit, no modifications
938
+ });
939
+
940
+ it("should NOT short-circuit when middleware uses ctx.header() after next() - headers go on stubResponse", async () => {
941
+ const stubResponse = new Response(null, { status: 200 });
942
+ const middleware: MiddlewareFn<unknown> = async (ctx, next) => {
943
+ await next();
944
+ ctx.header("X-Custom-Header", "custom-value");
945
+ };
946
+
947
+ const result = await executeInterceptMiddleware(
948
+ [middleware],
949
+ new Request("http://localhost/test"),
950
+ {},
951
+ {},
952
+ {},
953
+ stubResponse
954
+ );
955
+
956
+ // Should return null (no short-circuit) - headers are on stubResponse for caller to merge
957
+ expect(result).toBeNull();
958
+ expect(stubResponse.headers.get("X-Custom-Header")).toBe("custom-value");
959
+ });
960
+
961
+ it("should short-circuit when middleware replaces ctx.res after next()", async () => {
962
+ const stubResponse = new Response(null, { status: 200 });
963
+ const middleware: MiddlewareFn<unknown> = async (ctx, next) => {
964
+ await next();
965
+ ctx.res = new Response("Custom body", { status: 201 });
966
+ };
967
+
968
+ const result = await executeInterceptMiddleware(
969
+ [middleware],
970
+ new Request("http://localhost/test"),
971
+ {},
972
+ {},
973
+ {},
974
+ stubResponse
975
+ );
976
+
977
+ expect(result).toBeInstanceOf(Response);
978
+ expect(result!.status).toBe(201);
979
+ expect(await result!.text()).toBe("Custom body");
980
+ });
981
+
982
+ it("should NOT short-circuit when cookies set after next() - cookies go on stubResponse", async () => {
983
+ const stubResponse = new Response(null, { status: 200 });
984
+ const middleware: MiddlewareFn<unknown> = async (ctx, next) => {
985
+ await next();
986
+ ctx.header("X-Modified", "true");
987
+ ctx.setCookie("after-next", "cookie-value");
988
+ };
989
+
990
+ const result = await executeInterceptMiddleware(
991
+ [middleware],
992
+ new Request("http://localhost/test"),
993
+ {},
994
+ {},
995
+ {},
996
+ stubResponse
997
+ );
998
+
999
+ // Should return null (no short-circuit) - headers/cookies are on stubResponse
1000
+ expect(result).toBeNull();
1001
+ expect(stubResponse.headers.get("X-Modified")).toBe("true");
1002
+ const cookies = stubResponse.headers.get("set-cookie");
1003
+ expect(cookies).toContain("after-next=cookie-value");
1004
+ });
1005
+
1006
+ it("should set cookies on stubResponse when only cookies are set after next()", async () => {
1007
+ const stubResponse = new Response(null, { status: 200 });
1008
+ const middleware: MiddlewareFn<unknown> = async (ctx, next) => {
1009
+ await next();
1010
+ ctx.setCookie("only-cookie", "value123");
1011
+ };
1012
+
1013
+ const result = await executeInterceptMiddleware(
1014
+ [middleware],
1015
+ new Request("http://localhost/test"),
1016
+ {},
1017
+ {},
1018
+ {},
1019
+ stubResponse
1020
+ );
1021
+
1022
+ // Should return null (no short-circuit) - cookie is on stubResponse
1023
+ expect(result).toBeNull();
1024
+ const cookies = stubResponse.headers.get("set-cookie");
1025
+ expect(cookies).toContain("only-cookie=value123");
1026
+ });
1027
+ });
1028
+
1029
+ describe("executeServerActionMiddleware", () => {
1030
+ it("should do nothing for empty middleware array", async () => {
1031
+ const stubResponse = new Response(null, { status: 200 });
1032
+ await expect(
1033
+ executeServerActionMiddleware(
1034
+ [],
1035
+ new Request("http://localhost/test"),
1036
+ {},
1037
+ {},
1038
+ {},
1039
+ stubResponse
1040
+ )
1041
+ ).resolves.toBeUndefined();
1042
+ });
1043
+
1044
+ it("should execute middleware and call next()", async () => {
1045
+ const order: number[] = [];
1046
+ const stubResponse = new Response(null, { status: 200 });
1047
+
1048
+ const mw1: MiddlewareFn<unknown> = async (ctx, next) => {
1049
+ order.push(1);
1050
+ await next();
1051
+ order.push(4);
1052
+ };
1053
+
1054
+ const mw2: MiddlewareFn<unknown> = async (ctx, next) => {
1055
+ order.push(2);
1056
+ await next();
1057
+ order.push(3);
1058
+ };
1059
+
1060
+ await executeServerActionMiddleware(
1061
+ [mw1, mw2],
1062
+ new Request("http://localhost/test"),
1063
+ {},
1064
+ {},
1065
+ {},
1066
+ stubResponse
1067
+ );
1068
+
1069
+ expect(order).toEqual([1, 2, 3, 4]);
1070
+ });
1071
+
1072
+ it("should share variables between middleware", async () => {
1073
+ const variables: Record<string, any> = { existing: "value" };
1074
+ let capturedVars: Record<string, any> = {};
1075
+ const stubResponse = new Response(null, { status: 200 });
1076
+
1077
+ const mw1: MiddlewareFn<unknown> = async (ctx, next) => {
1078
+ ctx.set("fromMw1", "hello");
1079
+ await next();
1080
+ };
1081
+
1082
+ const mw2: MiddlewareFn<unknown> = async (ctx, next) => {
1083
+ capturedVars.existing = ctx.get("existing");
1084
+ capturedVars.fromMw1 = ctx.get("fromMw1");
1085
+ await next();
1086
+ };
1087
+
1088
+ await executeServerActionMiddleware(
1089
+ [mw1, mw2],
1090
+ new Request("http://localhost/test"),
1091
+ {},
1092
+ {},
1093
+ variables,
1094
+ stubResponse
1095
+ );
1096
+
1097
+ expect(capturedVars.existing).toBe("value");
1098
+ expect(capturedVars.fromMw1).toBe("hello");
1099
+ expect(variables.fromMw1).toBe("hello");
1100
+ });
1101
+
1102
+ it("should provide params to middleware context", async () => {
1103
+ let capturedParams: Record<string, string> = {};
1104
+ const stubResponse = new Response(null, { status: 200 });
1105
+
1106
+ const middleware: MiddlewareFn<unknown> = async (ctx, next) => {
1107
+ capturedParams = ctx.params;
1108
+ await next();
1109
+ };
1110
+
1111
+ await executeServerActionMiddleware(
1112
+ [middleware],
1113
+ new Request("http://localhost/test"),
1114
+ {},
1115
+ { id: "789", action: "submit" },
1116
+ {},
1117
+ stubResponse
1118
+ );
1119
+
1120
+ expect(capturedParams).toEqual({ id: "789", action: "submit" });
1121
+ });
1122
+
1123
+ it("should throw error if middleware returns Response", async () => {
1124
+ const stubResponse = new Response(null, { status: 200 });
1125
+ const middleware: MiddlewareFn<unknown> = async (ctx, next) => {
1126
+ return new Response("Redirect", { status: 302 });
1127
+ };
1128
+
1129
+ await expect(
1130
+ executeServerActionMiddleware(
1131
+ [middleware],
1132
+ new Request("http://localhost/test"),
1133
+ {},
1134
+ {},
1135
+ {},
1136
+ stubResponse
1137
+ )
1138
+ ).rejects.toThrow("Server actions cannot return Response");
1139
+ });
1140
+
1141
+ it("should set cookies on stub response", async () => {
1142
+ const stubResponse = new Response(null, { status: 200 });
1143
+ const middleware: MiddlewareFn<unknown> = async (ctx, next) => {
1144
+ ctx.setCookie("session", "abc123");
1145
+ await next();
1146
+ };
1147
+
1148
+ await executeServerActionMiddleware(
1149
+ [middleware],
1150
+ new Request("http://localhost/test"),
1151
+ {},
1152
+ {},
1153
+ {},
1154
+ stubResponse
1155
+ );
1156
+
1157
+ // Cookies are set on the stub response for later merging
1158
+ expect(stubResponse.headers.get("Set-Cookie")).toContain("session=abc123");
1159
+ });
1160
+
1161
+ it("should set multiple cookies on stub response", async () => {
1162
+ const stubResponse = new Response(null, { status: 200 });
1163
+ const middleware: MiddlewareFn<unknown> = async (ctx, next) => {
1164
+ ctx.setCookie("token", "xyz");
1165
+ ctx.setCookie("preference", "dark");
1166
+ await next();
1167
+ };
1168
+
1169
+ await executeServerActionMiddleware(
1170
+ [middleware],
1171
+ new Request("http://localhost/test"),
1172
+ {},
1173
+ {},
1174
+ {},
1175
+ stubResponse
1176
+ );
1177
+
1178
+ // Multiple cookies are appended to stub response
1179
+ const cookies = stubResponse.headers.getSetCookie();
1180
+ expect(cookies).toContain("token=xyz");
1181
+ expect(cookies).toContain("preference=dark");
1182
+ });
1183
+
1184
+ it("should allow reading cookies without error", async () => {
1185
+ let readCookie: string | undefined;
1186
+ const stubResponse = new Response(null, { status: 200 });
1187
+
1188
+ const middleware: MiddlewareFn<unknown> = async (ctx, next) => {
1189
+ readCookie = ctx.cookie("session");
1190
+ await next();
1191
+ };
1192
+
1193
+ await executeServerActionMiddleware(
1194
+ [middleware],
1195
+ new Request("http://localhost/test", {
1196
+ headers: { Cookie: "session=abc123" },
1197
+ }),
1198
+ {},
1199
+ {},
1200
+ {},
1201
+ stubResponse
1202
+ );
1203
+
1204
+ expect(readCookie).toBe("abc123");
1205
+ });
1206
+ });
1207
+
1208
+ describe("executeLoaderMiddleware", () => {
1209
+ it("should call finalHandler directly when no middleware", async () => {
1210
+ const finalHandler = vi.fn().mockResolvedValue(new Response("Data"));
1211
+
1212
+ const result = await executeLoaderMiddleware(
1213
+ [],
1214
+ new Request("http://localhost/test"),
1215
+ {},
1216
+ {},
1217
+ {},
1218
+ finalHandler
1219
+ );
1220
+
1221
+ expect(finalHandler).toHaveBeenCalled();
1222
+ expect(await result.text()).toBe("Data");
1223
+ });
1224
+
1225
+ it("should execute middleware before finalHandler", async () => {
1226
+ const order: string[] = [];
1227
+
1228
+ const middleware: MiddlewareFn<unknown> = async (ctx, next) => {
1229
+ order.push("middleware-before");
1230
+ await next();
1231
+ order.push("middleware-after");
1232
+ };
1233
+
1234
+ const finalHandler = async () => {
1235
+ order.push("handler");
1236
+ return new Response("OK");
1237
+ };
1238
+
1239
+ await executeLoaderMiddleware(
1240
+ [middleware],
1241
+ new Request("http://localhost/test"),
1242
+ {},
1243
+ {},
1244
+ {},
1245
+ finalHandler
1246
+ );
1247
+
1248
+ expect(order).toEqual(["middleware-before", "handler", "middleware-after"]);
1249
+ });
1250
+
1251
+ it("should share variables with finalHandler", async () => {
1252
+ const variables: Record<string, any> = {};
1253
+ let capturedVar: any;
1254
+
1255
+ const middleware: MiddlewareFn<unknown> = async (ctx, next) => {
1256
+ ctx.set("userId", "user-123");
1257
+ await next();
1258
+ };
1259
+
1260
+ const finalHandler = async () => {
1261
+ capturedVar = variables.userId;
1262
+ return new Response("OK");
1263
+ };
1264
+
1265
+ await executeLoaderMiddleware(
1266
+ [middleware],
1267
+ new Request("http://localhost/test"),
1268
+ {},
1269
+ {},
1270
+ variables,
1271
+ finalHandler
1272
+ );
1273
+
1274
+ expect(capturedVar).toBe("user-123");
1275
+ });
1276
+
1277
+ it("should provide params to middleware context", async () => {
1278
+ let capturedParams: Record<string, string> = {};
1279
+
1280
+ const middleware: MiddlewareFn<unknown> = async (ctx, next) => {
1281
+ capturedParams = ctx.params;
1282
+ await next();
1283
+ };
1284
+
1285
+ await executeLoaderMiddleware(
1286
+ [middleware],
1287
+ new Request("http://localhost/test"),
1288
+ {},
1289
+ { loaderId: "cart", userId: "456" },
1290
+ {},
1291
+ async () => new Response("OK")
1292
+ );
1293
+
1294
+ expect(capturedParams).toEqual({ loaderId: "cart", userId: "456" });
1295
+ });
1296
+
1297
+ it("should allow middleware to short-circuit with Response", async () => {
1298
+ const finalHandler = vi.fn().mockResolvedValue(new Response("Data"));
1299
+
1300
+ const middleware: MiddlewareFn<unknown> = async (ctx, next) => {
1301
+ return new Response("Unauthorized", { status: 401 });
1302
+ };
1303
+
1304
+ const result = await executeLoaderMiddleware(
1305
+ [middleware],
1306
+ new Request("http://localhost/test"),
1307
+ {},
1308
+ {},
1309
+ {},
1310
+ finalHandler
1311
+ );
1312
+
1313
+ expect(finalHandler).not.toHaveBeenCalled();
1314
+ expect(result.status).toBe(401);
1315
+ expect(await result.text()).toBe("Unauthorized");
1316
+ });
1317
+
1318
+ it("should apply cookies set by middleware", async () => {
1319
+ const middleware: MiddlewareFn<unknown> = async (ctx, next) => {
1320
+ ctx.setCookie("session", "new-session-id");
1321
+ await next();
1322
+ };
1323
+
1324
+ const result = await executeLoaderMiddleware(
1325
+ [middleware],
1326
+ new Request("http://localhost/test"),
1327
+ {},
1328
+ {},
1329
+ {},
1330
+ async () => new Response("OK")
1331
+ );
1332
+
1333
+ const cookies = result.headers.get("set-cookie");
1334
+ expect(cookies).toContain("session=new-session-id");
1335
+ });
1336
+
1337
+ it("should allow middleware to modify response headers", async () => {
1338
+ const middleware: MiddlewareFn<unknown> = async (ctx, next) => {
1339
+ await next();
1340
+ ctx.header("X-Loader-Cache", "HIT");
1341
+ };
1342
+
1343
+ const result = await executeLoaderMiddleware(
1344
+ [middleware],
1345
+ new Request("http://localhost/test"),
1346
+ {},
1347
+ {},
1348
+ {},
1349
+ async () => new Response("OK")
1350
+ );
1351
+
1352
+ expect(result.headers.get("X-Loader-Cache")).toBe("HIT");
1353
+ });
1354
+ });
1355
+ });