forked from CopilotKit/CopilotKit
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmiddleware.test.ts
More file actions
1574 lines (1456 loc) · 68.9 KB
/
Copy pathmiddleware.test.ts
File metadata and controls
1574 lines (1456 loc) · 68.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import {
parse as parseMatcherPath,
tokensToRegexp,
} from "next/dist/compiled/path-to-regexp";
import { NextRequest } from "next/server";
import type { NextFetchEvent } from "next/server";
// The statically-imported middleware module emits its table-validation
// warns (duplicate exact sources / duplicate wildcard prefixes) at
// IMPORT time — before any beforeEach spy exists — so they printed raw
// on every run (SU4-A7). vi.hoisted executes before the static imports
// below, swallowing them; the file-level beforeEach re-spies per test
// and afterEach's restoreAllMocks puts the real console.warn back.
vi.hoisted(() => {
vi.spyOn(console, "warn").mockImplementation(() => {});
});
import {
buildRedirectLookup,
config,
DELIBERATE_COLLAPSE_WILDCARD_IDS,
middleware,
normalizePosthogHost,
REGISTRY_FRAMEWORK_SLUGS,
substituteWildcardTemplate,
warnIfNoFrameworkSlugs,
} from "./middleware";
const DOCS_HOST = "https://docs.example.test";
const SHELL_ORIGIN = "https://shell.example.test";
function makeEvent(): NextFetchEvent {
return { waitUntil: vi.fn() } as unknown as NextFetchEvent;
}
function run(pathAndQuery: string, event: NextFetchEvent = makeEvent()) {
return middleware(new NextRequest(`${SHELL_ORIGIN}${pathAndQuery}`), event);
}
function location(res: Response): URL {
const loc = res.headers.get("location");
expect(loc).not.toBeNull();
return new URL(loc as string);
}
beforeEach(() => {
vi.stubEnv("DOCS_HOST", DOCS_HOST);
// An ambient POSTHOG_KEY (developer shell, CI secrets) would make every
// SEO-redirect test fire a REAL fetch to PostHog — global fetch is only
// stubbed inside the PostHog describe. Force tracking off by default;
// tests that exercise tracking stub their own key (and fetch).
vi.stubEnv("POSTHOG_KEY", "");
vi.stubEnv("POSTHOG_HOST", "");
// ALSO stub the NEXT_PUBLIC_ alternates (SU4-A7): readEnvPair treats
// an empty-string primary as unset and falls through to the alt name,
// so an ambient NEXT_PUBLIC_POSTHOG_KEY (developer shell, CI secrets)
// would re-enable REAL PostHog POSTs straight through the
// empty-string primary stubs above.
vi.stubEnv("NEXT_PUBLIC_POSTHOG_KEY", "");
vi.stubEnv("NEXT_PUBLIC_POSTHOG_HOST", "");
// Pin BASE_URL explicitly: runtime-config console.warns once per
// isolate when it is unset, and the warn-count assertions below only
// passed because Vitest happens to mirror Vite's BASE_URL="/" into
// process.env — an implementation detail, not a contract. Without
// this stub, fresh-imported middleware instances (resetModules
// re-runs runtime-config's warn-once latches too) would emit an
// unrelated warn into those counts.
vi.stubEnv("BASE_URL", "http://localhost:3000");
// With tracking forced off, the first redirect test trips the
// statically-imported module's warn-once latch — spy at file level so
// no real console.warn escapes (restoreAllMocks in afterEach resets it).
vi.spyOn(console, "warn").mockImplementation(() => {});
// mockClear is load-bearing (SU5-A6): when console.warn is ALREADY a
// mock (the vi.hoisted spy, before the first afterEach restores it),
// spyOn returns that same mock WITHOUT clearing its history — under
// .only/-t/--shuffle the module-load table warns would poison
// bare-count assertions (toHaveBeenCalledOnce) in whichever test runs
// first.
vi.mocked(console.warn).mockClear();
});
afterEach(() => {
vi.unstubAllEnvs();
vi.unstubAllGlobals();
vi.restoreAllMocks();
});
describe("middleware SEO redirects resolve against the docs host (SU-17)", () => {
it("redirects /faq to the docs host, never to itself on the shell origin", () => {
const res = run("/faq");
const dest = location(res);
// The destination table targets the DOCS routing surface. Resolving
// against the shell origin makes /faq -> shell /faq, an infinite
// 301 loop (ERR_TOO_MANY_REDIRECTS in prod).
expect(dest.origin).toBe(DOCS_HOST);
expect(dest.pathname).toBe("/faq");
});
it("sends exact-match destinations to the docs host in one hop", () => {
const res = run("/coagents/quickstart");
const dest = location(res);
expect(dest.origin).toBe(DOCS_HOST);
expect(dest.pathname).toBe("/langgraph-python/quickstart");
});
it("sends wildcard-match destinations to the docs host in one hop", () => {
const res = run("/troubleshooting/common-issues");
const dest = location(res);
expect(dest.origin).toBe(DOCS_HOST);
expect(dest.pathname).toBe("/troubleshooting/common-issues");
});
});
describe("SEO redirects forward the query string (SU-16)", () => {
it("preserves the query string on exact-match redirects", () => {
const res = run("/faq?utm_source=newsletter");
const dest = location(res);
expect(dest.pathname).toBe("/faq");
expect(dest.search).toBe("?utm_source=newsletter");
});
it("preserves the query string on wildcard-match redirects", () => {
const res = run("/coagents/foo?utm_source=newsletter&x=1");
const dest = location(res);
expect(dest.pathname).toBe("/langgraph-python/foo");
expect(dest.search).toBe("?utm_source=newsletter&x=1");
});
});
describe("wildcard sources match the bare path with zero segments (SU-19)", () => {
// next.config `/x/:path*` semantics: :path* is ZERO or more segments,
// so the bare /x must redirect too (11 such sources regressed to 404).
it("redirects /backend (P12) like /backend/:path* with zero segments", () => {
const res = run("/backend");
const dest = location(res);
expect(res.status).toBe(301);
expect(dest.origin).toBe(DOCS_HOST);
expect(dest.pathname).toBe("/backend");
});
it("redirects /guides (P11) to /built-in-agent/guides without a trailing slash", () => {
const dest = location(run("/guides"));
expect(dest.pathname).toBe("/built-in-agent/guides");
});
it("redirects /learn (P3) to /concepts", () => {
const dest = location(run("/learn"));
expect(dest.pathname).toBe("/concepts");
});
});
describe("docs-host redirects at the middleware level (SU-11)", () => {
it("pins 'mastra' as a registry slug — slug-dependent tests rely on it (SU4-A7)", () => {
// Several tests in this file (and below) route /mastra/* through
// the docs-host step. If the registry ever drops or renames the
// mastra integration, fail HERE with a self-explanatory message
// instead of as a baffling 301-vs-308 mismatch downstream.
expect(REGISTRY_FRAMEWORK_SLUGS.has("mastra")).toBe(true);
});
it("redirects /docs/:path* to the docs host with the prefix stripped", () => {
const res = run("/docs/quickstart");
expect(res.status).toBe(308);
const dest = location(res);
expect(dest.origin).toBe(DOCS_HOST);
expect(dest.pathname).toBe("/quickstart");
});
it("forwards the query string on docs-host redirects", () => {
const dest = location(run("/docs/quickstart?utm_source=newsletter"));
expect(dest.pathname).toBe("/quickstart");
expect(dest.search).toBe("?utm_source=newsletter");
});
it("takes precedence over the SEO table (next.config-before-middleware parity)", () => {
// /docs/api is ALSO an SEO source (R2 -> /reference/v2); the
// docs-host step must win and strip the /docs prefix instead, like
// config redirects did.
const res = run("/docs/api");
expect(res.status).toBe(308);
expect(location(res).pathname).toBe("/api");
// A registry framework slug is docs-host-step territory even when
// the SEO table has wildcard entries that could match it.
const slugRes = run("/mastra/quickstart/mastra");
expect(slugRes.status).toBe(308);
expect(location(slugRes).pathname).toBe("/mastra/quickstart/mastra");
});
it("does not redirect shell-owned routes", () => {
const res = run("/integrations/mastra");
expect(res.headers.get("location")).toBeNull();
});
it("never lets the SEO table hijack the /integrations namespace (SU3-A1)", () => {
// /integrations/built-in-agent is a LIVE shell product page (a
// deployed registry integration, internally linked from
// search-modal.tsx and integration-explorer.tsx). R15/R17 used to
// 301 it (and every subpath) to the docs host, hijacking the live
// page. /integrations/* is a shell-owned namespace — the guard runs
// FIRST in middleware (SU4-A1), so no redirect step (docs-host OR
// SEO table) may ever match under it, structurally.
expect(
run("/integrations/built-in-agent").headers.get("location"),
).toBeNull();
expect(
run("/integrations/built-in-agent/agentic-chat").headers.get("location"),
).toBeNull();
expect(run("/integrations").headers.get("location")).toBeNull();
});
it("guards /integrations even if 'integrations' appears as a registry slug (SU4-A1)", () => {
// Before the hoist, the guard ran AFTER the docs-host redirect: the
// protection was data-dependent — a registry slug literally named
// "integrations" would have let step 1 308 live shell pages to the
// docs host before the guard executed. Stub the slug set to contain
// it and prove the guard is structural.
//
// Shared-state hygiene (SU5-A6): REGISTRY_FRAMEWORK_SLUGS is the
// live module-level Set every other test in this worker reads.
// Capture whether the slug pre-existed and only delete what THIS
// test added — an unconditional finally-delete would erase a real
// registry slug for the rest of the run if one ever appeared.
const had = REGISTRY_FRAMEWORK_SLUGS.has("integrations");
// Precondition: the stub below is only meaningful while the real
// registry does NOT claim the slug (if it ever does, the guard's
// structural claim needs re-proving with a different slug).
expect(had).toBe(false);
REGISTRY_FRAMEWORK_SLUGS.add("integrations");
try {
expect(
run("/integrations/built-in-agent").headers.get("location"),
).toBeNull();
expect(run("/integrations").headers.get("location")).toBeNull();
expect(run("/Integrations/anything").headers.get("location")).toBeNull();
} finally {
if (!had) REGISTRY_FRAMEWORK_SLUGS.delete("integrations");
}
});
});
describe("case-insensitive matching parity (SU3-A4)", () => {
// The next.config rules this layer replaced were compiled by
// path-to-regexp with sensitive:false — /FAQ and /Mastra/quickstart
// matched. The middleware port's Map/startsWith/Set lookups are
// case-sensitive and regressed those URLs to 404. Matching is now
// case-insensitive; the wildcard remainder keeps its ORIGINAL case
// (path-to-regexp preserves matched-param case in destinations).
it("redirects /FAQ exactly like /faq", () => {
const res = run("/FAQ");
expect(res.status).toBe(301);
const dest = location(res);
expect(dest.origin).toBe(DOCS_HOST);
expect(dest.pathname).toBe("/faq");
});
it("forwards /Mastra/Quickstart to the docs host with the original-case tail", () => {
const res = run("/Mastra/Quickstart");
expect(res.status).toBe(308);
const dest = location(res);
expect(dest.origin).toBe(DOCS_HOST);
// Slug literal is canonical lowercase; the matched remainder keeps
// its original case, exactly as a path-to-regexp :path* param did.
expect(dest.pathname).toBe("/mastra/Quickstart");
});
it("matches SEO wildcard prefixes case-insensitively, keeping the rest's case", () => {
const res = run("/Coagents/Foo");
expect(res.status).toBe(301);
expect(location(res).pathname).toBe("/langgraph-python/Foo");
});
it("matches kept docs prefixes (/AG-UI) and /DOCS case-insensitively", () => {
const agui = run("/AG-UI/Events");
expect(agui.status).toBe(308);
expect(location(agui).pathname).toBe("/ag-ui/Events");
const docs = run("/DOCS/Quickstart");
expect(docs.status).toBe(308);
expect(location(docs).pathname).toBe("/Quickstart");
});
it("still guards the /integrations namespace case-insensitively", () => {
expect(
run("/Integrations/built-in-agent").headers.get("location"),
).toBeNull();
});
});
describe("trailing-slash normalization for matching (SU3-A5)", () => {
it("redirects /faq/ via the exact entry in ONE hop (no 308 detour)", () => {
// A trailing slash missed the exact map, falling through to Next's
// own trailing-slash 308 — an extra hop for every such URL.
const res = run("/faq/");
expect(res.status).toBe(301);
const dest = location(res);
expect(dest.origin).toBe(DOCS_HOST);
expect(dest.pathname).toBe("/faq");
});
it("attributes /coagents/ to the exact entry L1, not the wildcard L12", () => {
vi.stubEnv("POSTHOG_KEY", "phc_test");
const fetchMock = vi.fn((_input: RequestInfo | URL, _init?: RequestInit) =>
Promise.resolve(new Response("ok")),
);
vi.stubGlobal("fetch", fetchMock);
const res = run("/coagents/");
expect(location(res).pathname).toBe("/langgraph-python");
expect(fetchMock).toHaveBeenCalledOnce();
const body = JSON.parse(fetchMock.mock.calls[0][1]?.body as string);
expect(body.properties.redirect_id).toBe("L1");
});
it("does not strip the root path", () => {
expect(run("/").headers.get("location")).toBeNull();
});
it("strips a WHOLE trailing-slash run, not just one slash (SU4-A3)", () => {
// slice(0, -1) only removed ONE slash: "/faq//" became "/faq/" and
// still missed the exact map.
const res = run("/faq//");
expect(res.status).toBe(301);
expect(location(res).pathname).toBe("/faq");
expect(location(run("/coagents///")).pathname).toBe("/langgraph-python");
});
});
describe("leading-slash runs are collapsed for matching (SU4-A3)", () => {
// "//docs/foo" and "//ag-ui/x" fell through the docs-host step's
// strict ===/startsWith branches (only the framework-slug regex
// tolerated runs) AND missed the SEO wildcard scan → 404. The run is
// collapsed once in middleware() for ALL matching steps.
it("redirects //docs/foo like /docs/foo (308, prefix stripped)", () => {
const res = run("//docs/foo");
expect(res.status).toBe(308);
const dest = location(res);
expect(dest.origin).toBe(DOCS_HOST);
expect(dest.pathname).toBe("/foo");
});
it("redirects //ag-ui/x like /ag-ui/x (prefix kept)", () => {
const res = run("//ag-ui/x");
expect(res.status).toBe(308);
expect(location(res).pathname).toBe("/ag-ui/x");
});
it("redirects ///coagents/foo through the SEO wildcard scan", () => {
const res = run("///coagents/foo");
expect(res.status).toBe(301);
expect(location(res).pathname).toBe("/langgraph-python/foo");
});
it("still guards the /integrations namespace behind a slash run", () => {
expect(run("//integrations/mastra").headers.get("location")).toBeNull();
});
it("collapses an all-slash path to root and passes it through", () => {
expect(run("///").headers.get("location")).toBeNull();
});
});
describe("table-entry pins (SU3-A6)", () => {
it("matches MG3's uppercase source against the lowercase live URL", () => {
// The table source is "/migration-guides/1.10.X" (uppercase X) but
// live URLs are lowercase — before case-insensitive matching (SU3-A4
// lowercases BOTH the table keys and the request path) this entry
// could never fire.
expect(location(run("/migration-guides/1.10.x")).pathname).toBe(
"/migrate/v2",
);
expect(location(run("/migration-guides/1.10.X")).pathname).toBe(
"/migrate/v2",
);
});
it("keeps the framework segment on F13 like every comparable rule", () => {
// F13 dropped the framework segment (→ /human-in-the-loop), unlike
// F11/F12, the S× renames and the P1×aws-strands catch-all, which
// all map onto the canonical slug (aws-strands → strands).
expect(location(run("/aws-strands/human-in-the-loop")).pathname).toBe(
"/strands/human-in-the-loop",
);
});
});
describe("redirect status codes (SU-2)", () => {
it("emits 308 for docs-host redirects, matching next.config permanent:true", () => {
// The removed next.config rules used `permanent: true`, which Next
// emits as 308 — a 1:1 port must keep the status code.
expect(run("/docs/quickstart").status).toBe(308);
expect(run("/ag-ui").status).toBe(308);
});
it("keeps 301 for SEO-table redirects (their original middleware status)", () => {
expect(run("/faq").status).toBe(301);
expect(run("/coagents/foo").status).toBe(301);
});
});
describe("matcher boundaries (SU-15)", () => {
// Compile the matcher EXACTLY as Next does (SU6-A6 — see
// tryToParsePath in next/dist/lib/try-to-parse-path.ts, which
// getMiddlewareMatchers uses at build): parse() + tokensToRegexp()
// with NO options, keeping only the regex SOURCE — the build manifest
// stores `.source` and the runtime re-hydrates it with
// `new RegExp(matcher.regexp)` (middleware-route-matcher.ts),
// DROPPING the `i` flag that tokensToRegexp's sensitive:false default
// implies. Runtime matcher matching is therefore case-SENSITIVE. The
// previous homemade option set ({ delimiter: "/", sensitive: false,
// strict: true }) was NOT what Next uses and diverged on exactly that
// class of input (a case-variant of an excluded prefix).
const matcherRe = new RegExp(
tokensToRegexp(parseMatcherPath(config.matcher[0])).source,
);
it("pins a single matcher entry — every boundary below compiles config.matcher[0] only (SU7-F3)", () => {
// A second matcher entry would be entirely untested by this
// describe (matcherRe compiles only the first); fail HERE with a
// self-explanatory message instead of silently green-lighting an
// unverified pattern.
expect(config.matcher).toHaveLength(1);
});
it("runs middleware on /api and /api-reference (SEO sources R1/R3)", () => {
expect(matcherRe.test("/api")).toBe(true);
expect(matcherRe.test("/api-reference")).toBe(true);
});
it("still excludes real API routes and internals", () => {
expect(matcherRe.test("/api/runtime")).toBe(false);
expect(matcherRe.test("/_next/static/chunk.js")).toBe(false);
expect(matcherRe.test("/_next/image")).toBe(false);
expect(matcherRe.test("/previews/foo")).toBe(false);
expect(matcherRe.test("/favicon.ico")).toBe(false);
});
it("excludes ALL _next/* internals wholesale (SU4-A6)", () => {
// The old `_next/static|_next/image` pair let /_next/data and every
// other /_next/* internal run the middleware for nothing — no table
// source or registry slug starts with `_next`.
expect(matcherRe.test("/_next/data/build-id/foo.json")).toBe(false);
expect(matcherRe.test("/_next/postponed/resume")).toBe(false);
// A lookalike OUTSIDE the _next/ prefix still runs the middleware.
expect(matcherRe.test("/_nextdoor")).toBe(true);
});
it("matches case-SENSITIVELY, like Next's runtime regexp (SU6-A6)", () => {
// The runtime rebuilds the matcher with `new RegExp(source)` — no
// `i` flag — so a case-variant of an excluded prefix still reaches
// the middleware (which then passes it through; no table source
// starts with /API or /_NEXT).
expect(matcherRe.test("/API/runtime")).toBe(true);
expect(matcherRe.test("/_NEXT/static/chunk.js")).toBe(true);
});
it("lets bare /api/ (trailing slash) reach middleware for the single-hop R1 redirect (SU5-A4)", () => {
// The blanket `api/` exclusion also swallowed the BARE "/api/":
// Next then 308'd it to /api (trailing-slash normalization) before
// R1 could 301 — a needless double hop. Narrowed to `api/.+`, the
// bare trailing-slash form reaches middleware and R1 redirects in
// ONE hop; real API routes (/api/<anything>) stay excluded.
expect(matcherRe.test("/api/")).toBe(true);
const res = run("/api/");
expect(res.status).toBe(301);
const dest = location(res);
expect(dest.origin).toBe(DOCS_HOST);
expect(dest.pathname).toBe("/reference/v2");
});
it("redirects /api and /api-reference to /reference/v2 on the docs host", () => {
const apiDest = location(run("/api"));
expect(apiDest.origin).toBe(DOCS_HOST);
expect(apiDest.pathname).toBe("/reference/v2");
const apiRefDest = location(run("/api-reference"));
expect(apiRefDest.pathname).toBe("/reference/v2");
});
});
describe("REGISTRY_FRAMEWORK_SLUGS lowercase-normalizes registry slugs (SU4-A4)", () => {
afterEach(() => {
vi.doUnmock("@/data/registry.json");
vi.resetModules();
});
it("matches a mixed-case registry slug after construction-time lowercasing", async () => {
// docs-redirects compares the LOWERCASED first segment against the
// set — a mixed-case slug stored verbatim would silently never
// match, disabling its docs-host redirect with no signal.
vi.resetModules();
vi.doMock("@/data/registry.json", () => ({
default: { integrations: [{ slug: "MiXedCase" }] },
}));
const fresh = await import("./middleware");
expect(fresh.REGISTRY_FRAMEWORK_SLUGS.has("mixedcase")).toBe(true);
const res = fresh.middleware(
new NextRequest(`${SHELL_ORIGIN}/MixedCase/quickstart`),
makeEvent(),
);
expect(res.status).toBe(308);
expect(location(res).pathname).toBe("/mixedcase/quickstart");
});
});
describe("REGISTRY_FRAMEWORK_SLUGS survives a malformed registry (SU5-A1)", () => {
// Module-load defensiveness: the slug-set construction used to do
// `i.slug.toLowerCase()` through a bare `as` cast — a registry that is
// null, has a non-array `integrations`, or contains entries with a
// missing/non-string slug would TypeError at MODULE LOAD: the exact
// 500-every-request failure warnIfNoFrameworkSlugs exists to prevent.
afterEach(() => {
vi.doUnmock("@/data/registry.json");
vi.resetModules();
});
async function importWithRegistry(registryShape: unknown) {
vi.resetModules();
vi.doMock("@/data/registry.json", () => ({ default: registryShape }));
return import("./middleware");
}
it("imports without throwing when the registry is null", async () => {
const fresh = await importWithRegistry(null);
expect(fresh.REGISTRY_FRAMEWORK_SLUGS.size).toBe(0);
});
it("imports without throwing when integrations is not an array", async () => {
const fresh = await importWithRegistry({ integrations: "corrupt" });
expect(fresh.REGISTRY_FRAMEWORK_SLUGS.size).toBe(0);
});
it("drops entries with a missing or non-string slug and warns, keeping valid ones", async () => {
const fresh = await importWithRegistry({
integrations: [
{ slug: "Good" },
{ name: "no-slug-key" },
{ slug: 42 },
null,
],
});
expect(fresh.REGISTRY_FRAMEWORK_SLUGS.has("good")).toBe(true);
expect(fresh.REGISTRY_FRAMEWORK_SLUGS.size).toBe(1);
// The drop is observable next to warnIfNoFrameworkSlugs's module-load
// guard — a silently-shrunken slug set disables docs-host redirects
// with no signal otherwise.
const dropWarns = vi
.mocked(console.warn)
.mock.calls.filter(([msg]) =>
String(msg).includes("dropped from the framework-slug set"),
);
expect(dropWarns).toHaveLength(1);
// Count-phrase match (SU6-A6): a bare toContain("3") would match a
// "3" anywhere in the message (ids, paths, "SU3-..."), not the
// dropped-entry count.
expect(String(dropWarns[0][0])).toContain("has 3 integration");
});
it("stays silent about drops for a fully well-formed registry", async () => {
await importWithRegistry({ integrations: [{ slug: "fine" }] });
const dropWarns = vi
.mocked(console.warn)
.mock.calls.filter(([msg]) =>
String(msg).includes("dropped from the framework-slug set"),
);
expect(dropWarns).toHaveLength(0);
});
});
describe("empty framework-slug set guard (SU-20)", () => {
it("console.errors in production when the slug set is empty", () => {
vi.stubEnv("NODE_ENV", "production");
const error = vi.spyOn(console, "error").mockImplementation(() => {});
warnIfNoFrameworkSlugs(new Set());
// Message-filtered count (SU6-A6, applied SU7-F3): a bare
// toHaveBeenCalledOnce() would absorb any unrelated error into this
// count — or mask a missing slug error when exactly one unrelated
// error fired.
const slugErrors = error.mock.calls.filter(([msg]) =>
String(msg).includes("ZERO framework slugs"),
);
expect(slugErrors).toHaveLength(1);
});
it("console.warns outside production when the slug set is empty", () => {
vi.stubEnv("NODE_ENV", "development");
const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
warnIfNoFrameworkSlugs(new Set());
// Message-filtered count (SU6-A6): a bare toHaveBeenCalledOnce()
// would absorb any unrelated warn into this count.
const slugWarns = warn.mock.calls.filter(([msg]) =>
String(msg).includes("ZERO framework slugs"),
);
expect(slugWarns).toHaveLength(1);
});
it("stays silent when slugs are present", () => {
const error = vi.spyOn(console, "error").mockImplementation(() => {});
const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
warnIfNoFrameworkSlugs(new Set(["mastra"]));
expect(error).not.toHaveBeenCalled();
expect(warn).not.toHaveBeenCalled();
});
});
describe("docs-redirects-disabled sentinel consumer (SU4-B2)", () => {
// middleware.ts keeps a module-level warn-once latch
// (docsRedirectsDisabledWarned) — reset modules and import a fresh
// middleware per test so this describe owns the latch (same pattern
// as the PostHog tracking-lifetime describe below).
let freshMiddleware: typeof middleware;
beforeEach(async () => {
// Shell deployed AT the default docs host with DOCS_HOST pointing
// there too: the configured value is rejected (self-host) AND the
// DEFAULT_DOCS_HOST fallback carries the identical defect, so
// runtime-config hands middleware the DOCS_REDIRECTS_DISABLED_HOST
// sentinel instead of a looping host.
vi.stubEnv("BASE_URL", "https://docs.showcase.copilotkit.ai");
vi.stubEnv("DOCS_HOST", "https://docs.showcase.copilotkit.ai");
// The FATAL-CONFIG console.error asserted below is the PROD posture
// — readDocsHost branches dev-vs-prod (dev logs a warn instead).
vi.stubEnv("NODE_ENV", "production");
vi.resetModules();
({ middleware: freshMiddleware } = await import("./middleware"));
// Fresh import re-runs module-load warnings into the file-level
// warn spy — clear them so the once-assertions below only count
// request-time warns.
vi.mocked(console.warn).mockClear();
});
it("skips the docs-host step (no 308 to the sentinel) and warns once", () => {
// runtime-config console.errors its FATAL-CONFIG diagnosis at
// request time (fresh latches after resetModules) — swallow it so
// nothing prints raw, and assert it fired.
const error = vi.spyOn(console, "error").mockImplementation(() => {});
const sentinelWarns = () =>
vi
.mocked(console.warn)
.mock.calls.filter((c) =>
String(c[0]).includes("docs redirects are DISABLED"),
);
const first = freshMiddleware(
new NextRequest(`${SHELL_ORIGIN}/docs/foo`),
makeEvent(),
);
// The redirect steps are skipped entirely: /docs/foo would normally
// 308 to the docs host (and the SEO DOCS-wild entry would otherwise
// 301 it to the same docsHost) — with the sentinel the request
// passes straight through to NextResponse.next(), never a redirect
// to the guaranteed-dead `.invalid` sentinel origin.
expect(first.headers.get("location")).toBeNull();
expect(first.status).toBe(200);
expect(sentinelWarns()).toHaveLength(1);
expect(
error.mock.calls.some((c) => String(c[0]).includes("FATAL-CONFIG")),
).toBe(true);
// Second request: still no redirect, and the warn-once latch holds.
const second = freshMiddleware(
new NextRequest(`${SHELL_ORIGIN}/docs/bar`),
makeEvent(),
);
expect(second.headers.get("location")).toBeNull();
expect(sentinelWarns()).toHaveLength(1);
});
});
describe("PostHog tracking lifetime (SU-14)", () => {
// middleware.ts keeps a module-level warn-once latch (posthogKeyWarned).
// On the statically-imported instance, whichever earlier test triggered
// the first no-key redirect already consumed it, which makes the warn
// path untestable here — reset modules and import a fresh middleware
// per test so this describe owns the latch.
let freshMiddleware: typeof middleware;
beforeEach(async () => {
vi.resetModules();
({ middleware: freshMiddleware } = await import("./middleware"));
// The fresh import re-runs module-load warnings (e.g. the duplicate
// exact-sources warn from SU2-A3) into the file-level warn spy —
// clear them so assertions below only count request-time warns.
vi.mocked(console.warn).mockClear();
});
function runFresh(pathAndQuery: string, event: NextFetchEvent) {
return freshMiddleware(
new NextRequest(`${SHELL_ORIGIN}${pathAndQuery}`),
event,
);
}
it("registers the tracking fetch with event.waitUntil", () => {
vi.stubEnv("POSTHOG_KEY", "phc_test");
const fetchMock = vi.fn(() => Promise.resolve(new Response("ok")));
vi.stubGlobal("fetch", fetchMock);
const event = makeEvent();
runFresh("/faq", event);
expect(fetchMock).toHaveBeenCalledOnce();
// Without waitUntil the Edge runtime may terminate right after the
// redirect response, dropping the in-flight capture.
expect(event.waitUntil).toHaveBeenCalledOnce();
});
it("warns exactly once and skips fetch/waitUntil when tracking is disabled (no POSTHOG_KEY)", () => {
// POSTHOG_KEY is already stubbed to "" by the file-level beforeEach.
const warn = vi.spyOn(console, "warn");
const fetchMock = vi.fn(() => Promise.resolve(new Response("ok")));
vi.stubGlobal("fetch", fetchMock);
const first = makeEvent();
const second = makeEvent();
runFresh("/faq", first);
runFresh("/learn", second);
expect(fetchMock).not.toHaveBeenCalled();
expect(first.waitUntil).not.toHaveBeenCalled();
expect(second.waitUntil).not.toHaveBeenCalled();
// The latch warns once per cold start, not once per request.
// Filter by message: a bare toHaveBeenCalledOnce() would absorb any
// unrelated warn (module-load table warns, runtime-config fallbacks)
// into this count and fail — or worse, mask a missing key warn when
// exactly one unrelated warn fired.
const keyWarns = warn.mock.calls.filter(([msg]) =>
String(msg).includes("POSTHOG_KEY"),
);
expect(keyWarns).toHaveLength(1);
});
it("console.errors (not warns) in production when POSTHOG_KEY is missing (SU4-A5)", () => {
// Mirrors warnIfNoFrameworkSlugs's NODE_ENV branching: on dev /
// preview deploys a missing key is legitimate, but in production it
// is a wiring bug that silently under-counts the decommission
// report — it must hit the error stream.
vi.stubEnv("NODE_ENV", "production");
const error = vi.spyOn(console, "error").mockImplementation(() => {});
const warn = vi.spyOn(console, "warn");
const event = makeEvent();
runFresh("/faq", event);
const keyErrors = error.mock.calls.filter(([msg]) =>
String(msg).includes("POSTHOG_KEY"),
);
expect(keyErrors).toHaveLength(1);
expect(String(keyErrors[0][0])).toContain("wiring bug");
const keyWarns = warn.mock.calls.filter(([msg]) =>
String(msg).includes("POSTHOG_KEY"),
);
expect(keyWarns).toHaveLength(0);
});
it("console.warns (not errors) outside production when POSTHOG_KEY is missing (SU4-A5)", () => {
vi.stubEnv("NODE_ENV", "development");
const error = vi.spyOn(console, "error").mockImplementation(() => {});
const warn = vi.spyOn(console, "warn");
const event = makeEvent();
runFresh("/faq", event);
const keyWarns = warn.mock.calls.filter(([msg]) =>
String(msg).includes("POSTHOG_KEY"),
);
expect(keyWarns).toHaveLength(1);
const keyErrors = error.mock.calls.filter(([msg]) =>
String(msg).includes("POSTHOG_KEY"),
);
expect(keyErrors).toHaveLength(0);
});
it("surfaces the missing-key wiring bug on the FIRST request, even when no redirect fires (SU6-A5)", () => {
// The check used to live inside trackRedirect, which only runs when
// a redirect MATCHES — a prod deploy whose traffic never hits a
// redirect source got ZERO signal that every seo_redirect would go
// uncaptured. It now runs at config-resolution time on every
// middleware invocation (latched once per isolate).
vi.stubEnv("NODE_ENV", "production");
const error = vi.spyOn(console, "error").mockImplementation(() => {});
const keyErrors = () =>
error.mock.calls.filter(([msg]) => String(msg).includes("POSTHOG_KEY"));
// A pass-through path: no redirect step matches it.
const res = runFresh("/integrations/built-in-agent", makeEvent());
expect(res.headers.get("location")).toBeNull();
expect(keyErrors()).toHaveLength(1);
// Second request: the once-latch holds.
runFresh("/integrations/built-in-agent", makeEvent());
expect(keyErrors()).toHaveLength(1);
});
it("does NOT capture PostHog events for docs-host redirects (parity pin)", () => {
// Deliberate parity choice (see the docs-host step): the next.config
// `redirects()` rules these replace were never tracked — only the
// SEO table calls trackRedirect. Pin it so a future refactor doesn't
// silently start double-counting docs traffic as seo_redirect events.
vi.stubEnv("POSTHOG_KEY", "phc_test");
const fetchMock = vi.fn(() => Promise.resolve(new Response("ok")));
vi.stubGlobal("fetch", fetchMock);
const event = makeEvent();
const res = runFresh("/docs/quickstart", event);
expect(res.status).toBe(308);
expect(fetchMock).not.toHaveBeenCalled();
expect(event.waitUntil).not.toHaveBeenCalled();
});
});
describe("duplicate exact sources: first match wins (SU2-A3)", () => {
it("attributes /unselected to SR-root×unselected, not the later P2× entry", () => {
// The table doc says "first match wins"; a Map last-write-wins build
// inverted that and skewed PostHog redirect_id attribution for the
// duplicate sources (P2×unselected overrode SR-root×unselected).
vi.stubEnv("POSTHOG_KEY", "phc_test");
const fetchMock = vi.fn((_input: RequestInfo | URL, _init?: RequestInit) =>
Promise.resolve(new Response("ok")),
);
vi.stubGlobal("fetch", fetchMock);
const res = run("/unselected");
expect(location(res).pathname).toBe("/built-in-agent");
expect(fetchMock).toHaveBeenCalledOnce();
const body = JSON.parse(fetchMock.mock.calls[0][1]?.body as string);
expect(body.properties.redirect_id).toBe("SR-root×unselected");
});
it("rejects wildcard sources whose prefix lacks a '/' boundary (SU2-A7v)", () => {
// Without the boundary, `startsWith(prefix)` would match prefix
// LOOKALIKES (e.g. "/x:path*" matching "/xylophone").
const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
const { wildcardEntries } = buildRedirectLookup([
{ id: "bad", source: "/x:path*", destination: "/y/:path*" },
{ id: "good", source: "/a/:path*", destination: "/b/:path*" },
]);
expect(wildcardEntries).toHaveLength(1);
expect(wildcardEntries[0].id).toBe("good");
// Message-filtered count (SU6-A6): a bare toHaveBeenCalledOnce()
// would absorb any unrelated warn into this count.
const malformedWarns = warn.mock.calls.filter(([msg]) =>
String(msg).includes("malformed wildcard"),
);
expect(malformedWarns).toHaveLength(1);
expect(String(malformedWarns[0][0])).toContain("/x:path*");
});
it("applies first-match-wins + warn to duplicate WILDCARD prefixes (SU3-A2)", () => {
// Exact sources got first-match-wins + a module-load warn in round 2;
// wildcard sources have the same shadowing problem (six SR-wild×
// prefixes duplicate the later P1× entries). Without dedup the
// shadowed ids silently get zero traffic attribution — and the
// decommission report then proposes deleting a LIVE redirect.
const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
const { wildcardEntries } = buildRedirectLookup([
{ id: "first-wild", source: "/x/:path*", destination: "/a/:path*" },
{ id: "second-wild", source: "/x/:path*", destination: "/b/:path*" },
{ id: "other", source: "/y/:path*", destination: "/c/:path*" },
]);
expect(wildcardEntries).toHaveLength(2);
expect(wildcardEntries[0].id).toBe("first-wild");
expect(wildcardEntries[1].id).toBe("other");
const dupWarns = warn.mock.calls.filter(([msg]) =>
String(msg).includes("duplicate wildcard"),
);
expect(dupWarns).toHaveLength(1);
expect(String(dupWarns[0][0])).toContain("second-wild");
expect(String(dupWarns[0][0])).toContain("first-wild");
});
it("attributes /langgraph/foo to SR-wild×langgraph, not the later P1× entry (SU3-A2)", () => {
vi.stubEnv("POSTHOG_KEY", "phc_test");
const fetchMock = vi.fn((_input: RequestInfo | URL, _init?: RequestInit) =>
Promise.resolve(new Response("ok")),
);
vi.stubGlobal("fetch", fetchMock);
const res = run("/langgraph/foo");
expect(location(res).pathname).toBe("/langgraph-python/foo");
expect(fetchMock).toHaveBeenCalledOnce();
const body = JSON.parse(fetchMock.mock.calls[0][1]?.body as string);
expect(body.properties.redirect_id).toBe("SR-wild×langgraph");
});
it("keeps the first entry and warns once, naming the duplicate keys", () => {
const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
const { exactMap } = buildRedirectLookup([
{ id: "first", source: "/dup", destination: "/x" },
{ id: "second", source: "/dup", destination: "/y" },
{ id: "only", source: "/solo", destination: "/z" },
]);
expect(exactMap.get("/dup")?.id).toBe("first");
expect(exactMap.get("/dup")?.destination).toBe("/x");
expect(exactMap.get("/solo")?.id).toBe("only");
// Message-filtered count (SU6-A6): a bare toHaveBeenCalledOnce()
// would absorb any unrelated warn into this count.
const dupWarns = warn.mock.calls.filter(([msg]) =>
String(msg).includes("duplicate exact sources"),
);
expect(dupWarns).toHaveLength(1);
expect(String(dupWarns[0][0])).toContain("/dup");
expect(String(dupWarns[0][0])).toContain("second");
});
});
describe("buildRedirectLookup rejects malformed entries (SU3-A3)", () => {
it("skips+warns wildcard sources with segments AFTER :path*", () => {
// "/x/:path*/y" silently truncated to prefix "/x/" — over-matching
// every /x/* path instead of only /x/*/y shapes.
const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
const { wildcardEntries } = buildRedirectLookup([
{ id: "trailing", source: "/x/:path*/y", destination: "/z/:path*" },
{ id: "good", source: "/a/:path*", destination: "/b/:path*" },
]);
expect(wildcardEntries).toHaveLength(1);
expect(wildcardEntries[0].id).toBe("good");
const warns = warn.mock.calls.filter(([msg]) =>
String(msg).includes("/x/:path*/y"),
);
expect(warns).toHaveLength(1);
});
it("rejects+warns a root wildcard source /:path* (would hijack the entire site)", () => {
const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
const { wildcardEntries } = buildRedirectLookup([
{ id: "root-wild", source: "/:path*", destination: "/y/:path*" },
]);
expect(wildcardEntries).toHaveLength(0);
const warns = warn.mock.calls.filter(([msg]) =>
String(msg).includes("root-wild"),
);
expect(warns).toHaveLength(1);
});
it("rejects+warns a root EXACT source '/' — it would hijack the homepage (SU7-F3)", () => {
// The twin of the root-wildcard guard: "/" passes every source
// check (starts with "/", no "//", no ?/#, length-1 so the
// trailing-slash guard skips it) and lands in the exact map, where
// it matches the HOMEPAGE — never a legitimate SEO entry.
const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
const { exactMap } = buildRedirectLookup([
{ id: "root-exact", source: "/", destination: "/y" },
{ id: "ok", source: "/ok", destination: "/fine" },
]);
expect(exactMap.has("/")).toBe(false);
expect(exactMap.size).toBe(1);
expect(exactMap.get("/ok")?.id).toBe("ok");
const warns = warn.mock.calls.filter(([msg]) =>
String(msg).includes("hijack the homepage"),
);
expect(warns).toHaveLength(1);
expect(String(warns[0][0])).toContain("root-exact");
expect(String(warns[0][0])).not.toContain("(ok)");
});
it("skips+warns destinations that are not root-relative or carry ?/#", () => {
const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
const { exactMap, wildcardEntries } = buildRedirectLookup([
// Absolute URL: would be mangled into a docs-host path
// ("https://<docsHost>https://evil.test/x").
{ id: "abs", source: "/abs", destination: "https://evil.test/x" },
// "?" query: silently wiped by the per-request search overwrite.
{ id: "query", source: "/query", destination: "/q?x=y" },
// "#" fragment: same overwrite/mangling class.
{ id: "frag", source: "/frag", destination: "/f#sec" },
{ id: "wild-q", source: "/wq/:path*", destination: "/w/:path*?x=y" },
// "//" run (SU6-A4): request-time normalizeRedirectPath WOULD
// collapse it (so it can never become a scheme-relative open
// redirect — SU-18), but an authored "//" is a presumed typo,
// same as in sources — reject it loudly instead of silently
// papering over it.
{ id: "dbl", source: "/dbl", destination: "/a//b" },
{ id: "wild-dbl", source: "/wd/:path*", destination: "//w/:path*" },
{ id: "ok", source: "/ok", destination: "/fine" },
]);
expect(exactMap.size).toBe(1);
expect(exactMap.get("/ok")?.id).toBe("ok");
expect(wildcardEntries).toHaveLength(0);
const warns = warn.mock.calls.filter(([msg]) =>
String(msg).includes("invalid destination"),
);
expect(warns).toHaveLength(1);
for (const id of ["abs", "query", "frag", "wild-q", "dbl", "wild-dbl"]) {
expect(String(warns[0][0])).toContain(id);
}
});
it("rejects+warns sources containing '//' — '//:path*' bypasses the root-wildcard guard (SU5-A2)", () => {
const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
const { exactMap, wildcardEntries } = buildRedirectLookup([
// "//:path*" passed every builder check (prefix "//" ends with
// "/", :path* terminates the source, prefix !== "/") — but the
// matcher derives bareSource = prefix minus one slash = "/", so
// the entry matched the HOMEPAGE: the exact hijack the
// root-wildcard guard exists to reject.
{ id: "root-bypass", source: "//:path*", destination: "/y/:path*" },
// A leading-"//" exact source is unreachable too — middleware
// collapses leading slash runs before any lookup — and previously
// sat in the table as a silent dead entry with no warn.
{ id: "dead-exact", source: "//x", destination: "/x" },
{ id: "ok", source: "/ok", destination: "/fine" },
]);
expect(wildcardEntries).toHaveLength(0);
expect(exactMap.size).toBe(1);
expect(exactMap.get("/ok")?.id).toBe("ok");
const warns = warn.mock.calls.filter(([msg]) =>
String(msg).includes("invalid source"),
);
expect(warns).toHaveLength(1);
expect(String(warns[0][0])).toContain("root-bypass");
expect(String(warns[0][0])).toContain("dead-exact");
});