forked from CopilotKit/CopilotKit
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathruntime-config.test.ts
More file actions
1409 lines (1340 loc) · 58.9 KB
/
Copy pathruntime-config.test.ts
File metadata and controls
1409 lines (1340 loc) · 58.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";
// Stub next/cache.unstable_noStore — vitest runs outside Next's runtime
// so the real implementation throws ("called outside a Server
// Component"). The function is a no-op for our purposes (it tells Next
// not to cache; in a unit test there is no cache to opt out of).
vi.mock("next/cache", () => ({
unstable_noStore: () => {},
}));
import { getRuntimeConfig } from "./runtime-config";
describe("server getRuntimeConfig (shell)", () => {
const ORIGINAL_ENV = { ...process.env };
beforeEach(() => {
for (const k of [
"BASE_URL",
"POSTHOG_HOST",
"POSTHOG_KEY",
"DOCS_HOST",
"SHOWCASE_BACKEND_HOST_PATTERN",
"NEXT_PUBLIC_BASE_URL",
"NEXT_PUBLIC_POSTHOG_HOST",
"NEXT_PUBLIC_POSTHOG_KEY",
"NEXT_PUBLIC_DOCS_HOST",
"NEXT_PUBLIC_SHOWCASE_BACKEND_HOST_PATTERN",
"NODE_ENV",
]) {
delete (process.env as Record<string, string | undefined>)[k];
}
});
afterEach(() => {
// Full restore, not just value restore: Object.assign alone cannot
// DELETE keys a test added (e.g. DOCS_HOST set by a test but absent
// from the snapshot), which poisons other test FILES under vitest
// worker reuse. Drop added keys first, then restore values.
for (const key of Object.keys(process.env)) {
if (!(key in ORIGINAL_ENV)) {
delete (process.env as Record<string, string | undefined>)[key];
}
}
Object.assign(process.env, ORIGINAL_ENV);
});
it("returns env values when all are set (production)", () => {
// ALL five env values actually set — the test name promises it, and
// the exact-shape toEqual pins the full config (including posthogKey
// PRESENCE; a regression dropping the field from the return object
// would otherwise pass against an undefined-tolerant comparison).
(process.env as Record<string, string>).NODE_ENV = "production";
process.env.BASE_URL = "https://showcase.copilotkit.ai";
process.env.POSTHOG_HOST = "https://eu.i.posthog.com";
process.env.POSTHOG_KEY = "phc_test_key";
process.env.DOCS_HOST = "https://docs-staging.example.com";
process.env.SHOWCASE_BACKEND_HOST_PATTERN =
"showcase-{slug}-staging.up.railway.app";
const cfg = getRuntimeConfig();
expect(cfg).toEqual({
baseUrl: "https://showcase.copilotkit.ai",
posthogHost: "https://eu.i.posthog.com",
posthogKey: "phc_test_key",
backendHostPattern: "showcase-{slug}-staging.up.railway.app",
docsHost: "https://docs-staging.example.com",
});
// toEqual treats a missing key and an undefined value as equal —
// pin posthogKey presence explicitly.
expect(cfg.posthogKey).toBe("phc_test_key");
});
it("backendHostPattern/docsHost default to prod values when unset (both envs, no FATAL log)", async () => {
for (const nodeEnv of ["production", "development"]) {
(process.env as Record<string, string>).NODE_ENV = nodeEnv;
process.env.BASE_URL = "https://showcase.copilotkit.ai";
// The no-FATAL assertions below are about ABSENCE — on the static
// module instance they can pass vacuously when a prior test
// already consumed the once-guard for these keys. Fresh module so
// a log would actually fire if the code were wrong.
vi.resetModules();
const { getRuntimeConfig: freshGet } = await import("./runtime-config");
const errs: string[] = [];
const spy = vi
.spyOn(console, "error")
.mockImplementation(
(...args: unknown[]) => void errs.push(args.map(String).join(" ")),
);
// try/finally so a failing assertion can't leak the spy into
// other tests (matches every other spy in this file).
let cfg: ReturnType<typeof freshGet>;
try {
cfg = freshGet();
} finally {
spy.mockRestore();
}
expect(cfg.backendHostPattern).toBe(
"showcase-{slug}-production.up.railway.app",
);
expect(cfg.docsHost).toBe("https://docs.showcase.copilotkit.ai");
// These have legitimate prod defaults — never FATAL-CONFIG noise.
expect(errs.some((m) => m.includes("DOCS_HOST"))).toBe(false);
expect(
errs.some((m) => m.includes("SHOWCASE_BACKEND_HOST_PATTERN")),
).toBe(false);
}
});
it("honors SHOWCASE_BACKEND_HOST_PATTERN and DOCS_HOST at request time", () => {
(process.env as Record<string, string>).NODE_ENV = "production";
process.env.BASE_URL = "https://staging.example.com";
process.env.SHOWCASE_BACKEND_HOST_PATTERN =
"showcase-{slug}-staging.up.railway.app";
process.env.DOCS_HOST = "https://docs-staging.example.com/";
const cfg = getRuntimeConfig();
expect(cfg.backendHostPattern).toBe(
"showcase-{slug}-staging.up.railway.app",
);
// docsHost is a URL — trailing slash stripped like the others.
expect(cfg.docsHost).toBe("https://docs-staging.example.com");
// Live re-read on each call (no module-load freeze).
process.env.DOCS_HOST = "https://docs-staging2.example.com";
expect(getRuntimeConfig().docsHost).toBe(
"https://docs-staging2.example.com",
);
});
it("normalizes a scheme-bearing / slash-trailing SHOWCASE_BACKEND_HOST_PATTERN", () => {
// The consumer (backendUrlFromPattern) prepends `https://` and
// concatenates routes — a scheme-bearing value would yield
// `https://https://…` and a trailing slash would yield `//route`.
(process.env as Record<string, string>).NODE_ENV = "production";
process.env.BASE_URL = "https://showcase.copilotkit.ai";
process.env.SHOWCASE_BACKEND_HOST_PATTERN =
"https://showcase-{slug}-staging.up.railway.app/";
const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => {});
try {
expect(getRuntimeConfig().backendHostPattern).toBe(
"showcase-{slug}-staging.up.railway.app",
);
} finally {
warnSpy.mockRestore();
}
});
it("degenerate SHOWCASE_BACKEND_HOST_PATTERN falls back to the default pattern, never an empty string", async () => {
// Fix-round interaction bug: "https://" normalized to "" with NO
// fallback — server-side iframe srcs became literally "https://",
// and the injected "" failed the client reader's
// REQUIRED_CONFIG_FIELDS check, crashing EVERY client component
// with a message blaming the layout injection instead of the env
// var. The degenerate value must produce the default + one FATAL.
(process.env as Record<string, string>).NODE_ENV = "production";
process.env.BASE_URL = "https://showcase.copilotkit.ai";
for (const bad of ["https://", "/"]) {
process.env.SHOWCASE_BACKEND_HOST_PATTERN = bad;
vi.resetModules();
const { getRuntimeConfig: freshGet } = await import("./runtime-config");
const errs: string[] = [];
const errSpy = vi
.spyOn(console, "error")
.mockImplementation(
(...args: unknown[]) => void errs.push(args.map(String).join(" ")),
);
const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => {});
try {
const cfg = freshGet();
expect(cfg.backendHostPattern, `pattern ${JSON.stringify(bad)}`).toBe(
"showcase-{slug}-production.up.railway.app",
);
// The client reader requires a non-empty string — this is the
// exact invariant the round-3 check enforces.
expect(cfg.backendHostPattern.length).toBeGreaterThan(0);
expect(
errs.some(
(m) =>
m.includes("FATAL-CONFIG") &&
m.includes("SHOWCASE_BACKEND_HOST_PATTERN"),
),
).toBe(true);
} finally {
errSpy.mockRestore();
warnSpy.mockRestore();
}
}
});
it("prepends https:// when DOCS_HOST lacks a scheme (host-only misconfig)", () => {
// Middleware does `new URL(docsHost)` on every docs route. A
// host-only DOCS_HOST (the documented format of the sibling
// SHOWCASE_BACKEND_HOST_PATTERN var, an easy misconfig) must NOT
// produce an unparseable URL that 500s every docs request.
(process.env as Record<string, string>).NODE_ENV = "production";
process.env.BASE_URL = "https://showcase.copilotkit.ai";
process.env.DOCS_HOST = "docs-staging.example.com";
const cfg = getRuntimeConfig();
expect(cfg.docsHost).toBe("https://docs-staging.example.com");
expect(() => new URL(cfg.docsHost)).not.toThrow();
});
it("prepends http:// (not https://) to scheme-less LOOPBACK hosts", () => {
// The documented local-dev DOCS_HOST wiring is `localhost:3005` —
// an https:// prepend turns it into a TLS-failing destination with
// zero warn (nothing serves TLS on a local dev port). Loopback
// hosts (localhost, 127.0.0.1, [::1]) get http:// instead, across
// every ensureScheme consumer (BASE_URL, DOCS_HOST, POSTHOG_HOST).
(process.env as Record<string, string>).NODE_ENV = "development";
process.env.BASE_URL = "localhost:3000";
process.env.DOCS_HOST = "localhost:3005";
process.env.POSTHOG_HOST = "127.0.0.1:8010";
const cfg = getRuntimeConfig();
expect(cfg.baseUrl).toBe("http://localhost:3000");
expect(cfg.docsHost).toBe("http://localhost:3005");
expect(cfg.posthogHost).toBe("http://127.0.0.1:8010");
// IPv6 loopback too.
process.env.DOCS_HOST = "[::1]:3005";
expect(getRuntimeConfig().docsHost).toBe("http://[::1]:3005");
});
it("rejects a loopback BASE_URL in production with the sentinel + FATAL (no silent http:// prepend)", async () => {
// The loopback http:// prepend exists for frictionless DEV — in
// production it silently "fixed" BASE_URL=localhost:3000, so
// canonical hrefs, OG metadata, and the docs loop guard all ran
// against localhost with zero log. Prod loopback is always a
// misconfig: FATAL path, not the prepend.
(process.env as Record<string, string>).NODE_ENV = "production";
for (const bad of [
"localhost:3000",
"http://127.0.0.1:3000",
"[::1]:3000",
]) {
process.env.BASE_URL = bad;
vi.resetModules();
const { getRuntimeConfig: freshGet } = await import("./runtime-config");
const errs: string[] = [];
const spy = vi
.spyOn(console, "error")
.mockImplementation(
(...args: unknown[]) => void errs.push(args.map(String).join(" ")),
);
try {
expect(freshGet().baseUrl, `value ${JSON.stringify(bad)}`).toBe(
"https://shell-base-url-missing.invalid",
);
expect(
errs.some((m) => m.includes("BASE_URL") && m.includes("loopback")),
`value ${JSON.stringify(bad)} should log a loopback FATAL`,
).toBe(true);
} finally {
spy.mockRestore();
}
}
});
it("rejects a loopback DOCS_HOST in production with the default fallback + FATAL", async () => {
// Same class as the BASE_URL case: `DOCS_HOST=localhost:3005` is
// documented local-dev wiring — in production it would 308 every
// docs visitor to localhost, silently.
(process.env as Record<string, string>).NODE_ENV = "production";
process.env.BASE_URL = "https://showcase.copilotkit.ai";
for (const bad of ["localhost:3005", "http://localhost:3005"]) {
process.env.DOCS_HOST = bad;
vi.resetModules();
const { getRuntimeConfig: freshGet } = await import("./runtime-config");
const errs: string[] = [];
const spy = vi
.spyOn(console, "error")
.mockImplementation(
(...args: unknown[]) => void errs.push(args.map(String).join(" ")),
);
try {
expect(freshGet().docsHost, `value ${JSON.stringify(bad)}`).toBe(
"https://docs.showcase.copilotkit.ai",
);
expect(
errs.some((m) => m.includes("DOCS_HOST") && m.includes("loopback")),
`value ${JSON.stringify(bad)} should log a loopback FATAL`,
).toBe(true);
} finally {
spy.mockRestore();
}
}
});
it("preserves an explicit http:// scheme on DOCS_HOST", () => {
(process.env as Record<string, string>).NODE_ENV = "development";
process.env.BASE_URL = "http://localhost:3000";
process.env.DOCS_HOST = "http://localhost:3005";
expect(getRuntimeConfig().docsHost).toBe("http://localhost:3005");
});
it("falls back to the default docs host (with one loud log) when DOCS_HOST is unparseable", async () => {
(process.env as Record<string, string>).NODE_ENV = "production";
process.env.BASE_URL = "https://showcase.copilotkit.ai";
// Spaces make the host unparseable even after prepending https://.
process.env.DOCS_HOST = "not a parseable host";
// Warn-once module state — fresh module instance so the assertion
// is order-independent and retry-safe.
vi.resetModules();
const { getRuntimeConfig: freshGet } = await import("./runtime-config");
const errs: string[] = [];
const spy = vi
.spyOn(console, "error")
.mockImplementation(
(...args: unknown[]) => void errs.push(args.map(String).join(" ")),
);
try {
const cfg = freshGet();
expect(cfg.docsHost).toBe("https://docs.showcase.copilotkit.ai");
expect(() => new URL(cfg.docsHost)).not.toThrow();
expect(errs.some((m) => m.includes("DOCS_HOST"))).toBe(true);
// Loud log fires ONCE per bad value, not per request.
const before = errs.length;
freshGet();
expect(errs.length).toBe(before);
} finally {
spy.mockRestore();
}
});
it("rejects a degenerate DOCS_HOST of just a scheme (https://) with the loud fallback", async () => {
// `https://` strips to `https:`, the prepend yields
// `https://https:`, and that PARSES (hostname "https") — it used to
// slip through silently and break every docs redirect.
(process.env as Record<string, string>).NODE_ENV = "production";
process.env.BASE_URL = "https://showcase.copilotkit.ai";
process.env.DOCS_HOST = "https://";
vi.resetModules();
const { getRuntimeConfig: freshGet } = await import("./runtime-config");
const errs: string[] = [];
const spy = vi
.spyOn(console, "error")
.mockImplementation(
(...args: unknown[]) => void errs.push(args.map(String).join(" ")),
);
try {
const cfg = freshGet();
expect(cfg.docsHost).toBe("https://docs.showcase.copilotkit.ai");
expect(errs.some((m) => m.includes("DOCS_HOST"))).toBe(true);
} finally {
spy.mockRestore();
}
});
it("prepends https:// when BASE_URL lacks a scheme (host-only misconfig)", async () => {
// Consumers compose `new URL(path, baseUrl)` — a scheme-less value
// previously passed readUrl unvalidated and threw at every compose
// site: opaque 500s with NO log (the env var IS set, so the
// unset-fallback never fires).
(process.env as Record<string, string>).NODE_ENV = "production";
process.env.BASE_URL = "shell.copilotkit.ai";
// The no-FATAL assertion below is an ABSENCE assertion — vacuous on
// the static module instance if a prior test consumed the BASE_URL
// once-guard. Fresh module so a log would actually fire.
vi.resetModules();
const { getRuntimeConfig: freshGet } = await import("./runtime-config");
const errs: string[] = [];
const spy = vi
.spyOn(console, "error")
.mockImplementation(
(...args: unknown[]) => void errs.push(args.map(String).join(" ")),
);
try {
const cfg = freshGet();
expect(cfg.baseUrl).toBe("https://shell.copilotkit.ai");
expect(() => new URL("/some/path", cfg.baseUrl)).not.toThrow();
// The prepend FIXES the value — no FATAL noise for it.
expect(errs.some((m) => m.includes("BASE_URL"))).toBe(false);
} finally {
spy.mockRestore();
}
});
it("falls back to the sentinel (one loud log naming the value) for a degenerate BASE_URL of just a scheme", async () => {
// `https://` is reduced to `https:` by the trailing-slash strip,
// ensureScheme yields `https://https:` which PARSES (hostname
// "https") — it must be rejected, not silently returned.
(process.env as Record<string, string>).NODE_ENV = "production";
process.env.BASE_URL = "https://";
vi.resetModules();
const { getRuntimeConfig: freshGet } = await import("./runtime-config");
const errs: string[] = [];
const spy = vi
.spyOn(console, "error")
.mockImplementation(
(...args: unknown[]) => void errs.push(args.map(String).join(" ")),
);
try {
const cfg = freshGet();
expect(cfg.baseUrl).toBe("https://shell-base-url-missing.invalid");
expect(() => new URL("/some/path", cfg.baseUrl)).not.toThrow();
// The log must NAME the bad value so the operator can find it.
// (readUrl's trailing-slash strip runs first, so the named value
// is the post-strip "https:" — still unambiguous.)
expect(
errs.some((m) => m.includes("BASE_URL") && m.includes('"https:')),
).toBe(true);
// Once-guarded — not per request.
const before = errs.length;
freshGet();
expect(errs.length).toBe(before);
} finally {
spy.mockRestore();
}
});
it("rejects a non-http(s) BASE_URL scheme with the sentinel (ftp:// and the dot-scheme edge)", async () => {
// `ftp://shell.x` parses fine; `example.com://oops` matches
// SCHEME_RE (dot is a valid scheme char) so ensureScheme leaves it
// and it parses with protocol "example.com:" and hostname "oops".
// Neither can serve consumers composing http(s) URLs.
(process.env as Record<string, string>).NODE_ENV = "production";
for (const bad of ["ftp://shell.example.com", "example.com://oops"]) {
process.env.BASE_URL = bad;
vi.resetModules();
const { getRuntimeConfig: freshGet } = await import("./runtime-config");
const errs: string[] = [];
const spy = vi
.spyOn(console, "error")
.mockImplementation(
(...args: unknown[]) => void errs.push(args.map(String).join(" ")),
);
try {
const cfg = freshGet();
expect(cfg.baseUrl, `value ${JSON.stringify(bad)}`).toBe(
"https://shell-base-url-missing.invalid",
);
expect(
errs.some((m) => m.includes("BASE_URL") && m.includes("scheme")),
`value ${JSON.stringify(bad)} should log a scheme rejection`,
).toBe(true);
} finally {
spy.mockRestore();
}
}
});
it("rejects a mailto: BASE_URL (userinfo after the https:// prepend) with the sentinel", async () => {
// `mailto:ops@example.com` lacks `://` so SCHEME_RE misses it and
// the prepend yields `https://mailto:ops@example.com` — a URL with
// userinfo "mailto:ops" and host "example.com" that previously
// sailed through validation.
(process.env as Record<string, string>).NODE_ENV = "production";
process.env.BASE_URL = "mailto:ops@example.com";
vi.resetModules();
const { getRuntimeConfig: freshGet } = await import("./runtime-config");
const errs: string[] = [];
const spy = vi
.spyOn(console, "error")
.mockImplementation(
(...args: unknown[]) => void errs.push(args.map(String).join(" ")),
);
try {
expect(freshGet().baseUrl).toBe("https://shell-base-url-missing.invalid");
expect(errs.some((m) => m.includes("BASE_URL"))).toBe(true);
} finally {
spy.mockRestore();
}
});
it("origin-normalizes a BASE_URL carrying a path/query/fragment with one warn (subpath deploys unsupported)", async () => {
// Consumers compose `new URL(path, baseUrl)` — a path/query/fragment
// silently corrupts every composed URL (a base path is dropped by
// composition, a fragment swallows the path).
(process.env as Record<string, string>).NODE_ENV = "production";
for (const [bad, why] of [
["https://shell.example.com/sub", "path"],
["https://shell.example.com?a=b", "query"],
["https://shell.example.com#frag", "fragment"],
] as const) {
process.env.BASE_URL = bad;
vi.resetModules();
const { getRuntimeConfig: freshGet } = await import("./runtime-config");
const warns: string[] = [];
const spy = vi
.spyOn(console, "warn")
.mockImplementation(
(...args: unknown[]) => void warns.push(args.map(String).join(" ")),
);
try {
expect(freshGet().baseUrl, `${why} should normalize to origin`).toBe(
"https://shell.example.com",
);
expect(warns.some((m) => m.includes("BASE_URL"))).toBe(true);
// Once-guarded — not per request.
const before = warns.length;
freshGet();
expect(warns.length).toBe(before);
} finally {
spy.mockRestore();
}
}
});
it("dev-mode SET-but-malformed BASE_URL falls back to localhost with a dev warn, not the prod sentinel", async () => {
// The module's contract is frictionless dev: a malformed value in
// development previously fell to the PROD `.invalid` sentinel with
// Railway-flavored guidance — useless on a laptop.
(process.env as Record<string, string>).NODE_ENV = "development";
process.env.BASE_URL = "https://";
vi.resetModules();
const { getRuntimeConfig: freshGet } = await import("./runtime-config");
const warns: string[] = [];
const errs: string[] = [];
const warnSpy = vi
.spyOn(console, "warn")
.mockImplementation(
(...args: unknown[]) => void warns.push(args.map(String).join(" ")),
);
const errSpy = vi
.spyOn(console, "error")
.mockImplementation(
(...args: unknown[]) => void errs.push(args.map(String).join(" ")),
);
try {
const cfg = freshGet();
expect(cfg.baseUrl).toBe("http://localhost:3000");
expect(warns.some((m) => m.includes("BASE_URL"))).toBe(true);
// No FATAL noise and no Railway guidance in dev.
expect(errs.some((m) => m.includes("BASE_URL"))).toBe(false);
} finally {
warnSpy.mockRestore();
errSpy.mockRestore();
}
});
it("unset-BASE_URL FATAL names the post-strip sentinel (consistent with the returned value)", async () => {
// readUrl returns the trailing-slash-stripped fallback but printed
// the PRE-strip form — the log named a value that never appears.
(process.env as Record<string, string>).NODE_ENV = "production";
vi.resetModules();
const { getRuntimeConfig: freshGet } = await import("./runtime-config");
const errs: string[] = [];
const spy = vi
.spyOn(console, "error")
.mockImplementation(
(...args: unknown[]) => void errs.push(args.map(String).join(" ")),
);
try {
freshGet();
const fatal = errs.find((m) => m.includes("BASE_URL is unset"));
expect(fatal).toBeDefined();
expect(fatal).toContain("https://shell-base-url-missing.invalid");
expect(fatal).not.toContain("shell-base-url-missing.invalid/");
} finally {
spy.mockRestore();
}
});
it("falls back to the sentinel (one loud log) when BASE_URL is unparseable garbage", async () => {
(process.env as Record<string, string>).NODE_ENV = "production";
process.env.BASE_URL = "not a base url";
vi.resetModules();
const { getRuntimeConfig: freshGet } = await import("./runtime-config");
const errs: string[] = [];
const spy = vi
.spyOn(console, "error")
.mockImplementation(
(...args: unknown[]) => void errs.push(args.map(String).join(" ")),
);
try {
const cfg = freshGet();
expect(cfg.baseUrl).toBe("https://shell-base-url-missing.invalid");
expect(
errs.some(
(m) => m.includes("BASE_URL") && m.includes('"not a base url"'),
),
).toBe(true);
} finally {
spy.mockRestore();
}
});
it("normalizes a DOCS_HOST carrying a path/query/fragment to its origin (one warn)", async () => {
// docs-redirects composes destination paths against this value — a
// fragment swallows the path (`https://docs.x.ai#frag` + `/docs/y`
// lands on the docs ROOT), a query/path corrupts every destination.
(process.env as Record<string, string>).NODE_ENV = "production";
process.env.BASE_URL = "https://showcase.copilotkit.ai";
for (const [bad, why] of [
["https://docs.example.com/sub", "path"],
["https://docs.example.com?a=b", "query"],
["https://docs.example.com#frag", "fragment"],
] as const) {
process.env.DOCS_HOST = bad;
vi.resetModules();
const { getRuntimeConfig: freshGet } = await import("./runtime-config");
const warns: string[] = [];
const spy = vi
.spyOn(console, "warn")
.mockImplementation(
(...args: unknown[]) => void warns.push(args.map(String).join(" ")),
);
try {
const cfg = freshGet();
expect(cfg.docsHost, `${why} should normalize to origin`).toBe(
"https://docs.example.com",
);
expect(warns.some((m) => m.includes("DOCS_HOST"))).toBe(true);
// Once-guarded — not per request.
const before = warns.length;
freshGet();
expect(warns.length).toBe(before);
} finally {
spy.mockRestore();
}
}
});
it("rejects a non-http(s) DOCS_HOST scheme (ftp://) with the loud fallback", async () => {
// `ftp://docs.example.com` parses fine — but no middleware redirect
// destination can ever use it; it must not pass validation silently.
(process.env as Record<string, string>).NODE_ENV = "production";
process.env.BASE_URL = "https://showcase.copilotkit.ai";
process.env.DOCS_HOST = "ftp://docs.example.com";
vi.resetModules();
const { getRuntimeConfig: freshGet } = await import("./runtime-config");
const errs: string[] = [];
const spy = vi
.spyOn(console, "error")
.mockImplementation(
(...args: unknown[]) => void errs.push(args.map(String).join(" ")),
);
try {
const cfg = freshGet();
expect(cfg.docsHost).toBe("https://docs.showcase.copilotkit.ai");
// The reason must be the scheme — NOT the catch-all "not a
// parseable URL" mislabel (it parsed just fine).
expect(
errs.some(
(m) =>
m.includes("DOCS_HOST") &&
m.includes("scheme") &&
!m.includes("not a parseable URL"),
),
).toBe(true);
} finally {
spy.mockRestore();
}
});
it("rejects a credentialed DOCS_HOST (userinfo) with the loud fallback", async () => {
// A credentialed DOCS_HOST lands userinfo in every 308 Location —
// browsers strip or silently block credentialed redirect
// destinations, so docs redirects break with zero signal. Same
// rejection validateBaseUrl has.
(process.env as Record<string, string>).NODE_ENV = "production";
process.env.BASE_URL = "https://showcase.copilotkit.ai";
for (const bad of [
"https://user:pass@docs.example.com",
// Scheme-less form: the https:// prepend manufactures the
// userinfo (`user:pass@docs…` → `https://user:pass@docs…`).
"user:pass@docs.example.com",
]) {
process.env.DOCS_HOST = bad;
vi.resetModules();
const { getRuntimeConfig: freshGet } = await import("./runtime-config");
const errs: string[] = [];
const spy = vi
.spyOn(console, "error")
.mockImplementation(
(...args: unknown[]) => void errs.push(args.map(String).join(" ")),
);
try {
const cfg = freshGet();
expect(cfg.docsHost, `value ${JSON.stringify(bad)}`).toBe(
"https://docs.showcase.copilotkit.ai",
);
expect(
errs.some((m) => m.includes("DOCS_HOST") && m.includes("userinfo")),
`value ${JSON.stringify(bad)} should log a userinfo rejection`,
).toBe(true);
} finally {
spy.mockRestore();
}
}
});
it("labels the degenerate-host rejection as such, not as a parse failure", async () => {
// `https://` DID parse (hostname "https") — the operator-facing log
// must not send them hunting for a syntax error that isn't there.
(process.env as Record<string, string>).NODE_ENV = "production";
process.env.BASE_URL = "https://showcase.copilotkit.ai";
process.env.DOCS_HOST = "https://";
vi.resetModules();
const { getRuntimeConfig: freshGet } = await import("./runtime-config");
const errs: string[] = [];
const spy = vi
.spyOn(console, "error")
.mockImplementation(
(...args: unknown[]) => void errs.push(args.map(String).join(" ")),
);
try {
freshGet();
expect(
errs.some(
(m) => m.includes("DOCS_HOST") && !m.includes("not a parseable URL"),
),
).toBe(true);
} finally {
spy.mockRestore();
}
});
it("dev-mode SET-but-broken DOCS_HOST falls back with a dev warn, not FATAL-CONFIG / Railway guidance", async () => {
// Same dev-vs-prod branch validateBaseUrl has: the FATAL-CONFIG
// error and Railway guidance are useless on a laptop — the dev
// contract is frictionless iteration with a warn.
(process.env as Record<string, string>).NODE_ENV = "development";
process.env.BASE_URL = "http://localhost:3000";
process.env.DOCS_HOST = "https://";
vi.resetModules();
const { getRuntimeConfig: freshGet } = await import("./runtime-config");
const warns: string[] = [];
const errs: string[] = [];
const warnSpy = vi
.spyOn(console, "warn")
.mockImplementation(
(...args: unknown[]) => void warns.push(args.map(String).join(" ")),
);
const errSpy = vi
.spyOn(console, "error")
.mockImplementation(
(...args: unknown[]) => void errs.push(args.map(String).join(" ")),
);
try {
const cfg = freshGet();
// Same fallback VALUE as prod — only the log level/text branches.
expect(cfg.docsHost).toBe("https://docs.showcase.copilotkit.ai");
expect(warns.some((m) => m.includes("DOCS_HOST"))).toBe(true);
// No FATAL noise and no Railway guidance in dev.
expect(errs.some((m) => m.includes("DOCS_HOST"))).toBe(false);
expect(
warns.some((m) => m.includes("DOCS_HOST") && m.includes("Railway")),
).toBe(false);
} finally {
warnSpy.mockRestore();
errSpy.mockRestore();
}
});
it("falls back to the default docs host (one loud log) when DOCS_HOST points at the shell's own host", async () => {
// The redirect table has self-referential entries (/faq → /faq etc.)
// that terminate ONLY because the destination host differs. An
// operator pointing DOCS_HOST at the shell's own host turns ~15
// paths into ERR_TOO_MANY_REDIRECTS loops.
(process.env as Record<string, string>).NODE_ENV = "production";
process.env.BASE_URL = "https://shell.example.com";
process.env.DOCS_HOST = "https://shell.example.com";
vi.resetModules();
const { getRuntimeConfig: freshGet } = await import("./runtime-config");
const errs: string[] = [];
const spy = vi
.spyOn(console, "error")
.mockImplementation(
(...args: unknown[]) => void errs.push(args.map(String).join(" ")),
);
try {
const cfg = freshGet();
expect(cfg.docsHost).toBe("https://docs.showcase.copilotkit.ai");
expect(errs.some((m) => m.includes("DOCS_HOST"))).toBe(true);
// Once-guarded — not per request.
const before = errs.length;
freshGet();
expect(errs.length).toBe(before);
} finally {
spy.mockRestore();
}
});
it("disables docs redirects (sentinel) when the shell is deployed AT the default docs host with DOCS_HOST unset", async () => {
// The unconditional DEFAULT_DOCS_HOST fallback can carry the same
// defect it's escaping: shell deployed at the docs host with
// DOCS_HOST unset used to log a self-contradictory FATAL ("falling
// back to <the same looping value>") AND return the looping value.
(process.env as Record<string, string>).NODE_ENV = "production";
process.env.BASE_URL = "https://docs.showcase.copilotkit.ai";
// DOCS_HOST deliberately unset.
vi.resetModules();
const { getRuntimeConfig: freshGet, DOCS_REDIRECTS_DISABLED_HOST } =
await import("./runtime-config");
const errs: string[] = [];
const spy = vi
.spyOn(console, "error")
.mockImplementation(
(...args: unknown[]) => void errs.push(args.map(String).join(" ")),
);
try {
const cfg = freshGet();
expect(cfg.docsHost).toBe(DOCS_REDIRECTS_DISABLED_HOST);
// The sentinel must be parseable (incidental new URL consumers)
// and distinct from the looping default.
expect(() => new URL(cfg.docsHost)).not.toThrow();
expect(cfg.docsHost).not.toBe("https://docs.showcase.copilotkit.ai");
// Branched message: names the UNSET case and says redirects are
// disabled — never the self-contradictory "falling back to" the
// very value that loops.
const fatal = errs.find((m) => m.includes("DOCS_HOST"));
expect(fatal).toBeDefined();
expect(fatal).toContain("unset");
expect(fatal).toContain("disabled");
expect(fatal).not.toContain(
"falling back to https://docs.showcase.copilotkit.ai",
);
} finally {
spy.mockRestore();
}
});
it("disables docs redirects (sentinel) when DOCS_HOST is rejected AND the default fallback also collides", async () => {
// Shell deployed at the docs host with DOCS_HOST explicitly SET to
// that same host: the configured value is rejected (self-host) and
// the default fallback has the identical defect — return the
// disabled sentinel, not the looping default.
(process.env as Record<string, string>).NODE_ENV = "production";
process.env.BASE_URL = "https://docs.showcase.copilotkit.ai";
process.env.DOCS_HOST = "https://docs.showcase.copilotkit.ai";
vi.resetModules();
const { getRuntimeConfig: freshGet, DOCS_REDIRECTS_DISABLED_HOST } =
await import("./runtime-config");
const errs: string[] = [];
const spy = vi
.spyOn(console, "error")
.mockImplementation(
(...args: unknown[]) => void errs.push(args.map(String).join(" ")),
);
try {
const cfg = freshGet();
expect(cfg.docsHost).toBe(DOCS_REDIRECTS_DISABLED_HOST);
const fatal = errs.find((m) => m.includes("DOCS_HOST"));
expect(fatal).toBeDefined();
expect(fatal).toContain("disabled");
expect(fatal).not.toContain(
"falling back to https://docs.showcase.copilotkit.ai",
);
} finally {
spy.mockRestore();
}
});
it("re-logs the DOCS_HOST fallback when the shell host or mode changes the outcome (guard key covers both)", async () => {
// The fallback log's MESSAGE and OUTCOME (default vs disabled
// sentinel) depend on shellHost — a live BASE_URL re-read — and its
// LEVEL depends on the mode. A once-guard keyed on the raw value
// alone swallows a changed outcome: the deploy silently flips to
// redirects-disabled with zero log.
process.env.DOCS_HOST = "https://";
(process.env as Record<string, string>).NODE_ENV = "development";
process.env.BASE_URL = "https://shell.example.com";
vi.resetModules();
const { getRuntimeConfig: freshGet, DOCS_REDIRECTS_DISABLED_HOST } =
await import("./runtime-config");
const errs: string[] = [];
const warns: string[] = [];
const errSpy = vi
.spyOn(console, "error")
.mockImplementation(
(...args: unknown[]) => void errs.push(args.map(String).join(" ")),
);
const warnSpy = vi
.spyOn(console, "warn")
.mockImplementation(
(...args: unknown[]) => void warns.push(args.map(String).join(" ")),
);
try {
// Dev: warn-level fallback consumed the raw-value guard.
expect(freshGet().docsHost).toBe("https://docs.showcase.copilotkit.ai");
expect(warns.some((m) => m.includes("DOCS_HOST"))).toBe(true);
// Same raw value, PROD mode: the FATAL must still fire.
(process.env as Record<string, string>).NODE_ENV = "production";
expect(freshGet().docsHost).toBe("https://docs.showcase.copilotkit.ai");
expect(
errs.some((m) => m.includes("FATAL-CONFIG") && m.includes("DOCS_HOST")),
"prod FATAL must not be swallowed by the dev warn's guard entry",
).toBe(true);
// Same raw value, same mode, but BASE_URL moved to the default
// docs host: the OUTCOME flips to the disabled sentinel — that
// must be logged, not silently returned.
process.env.BASE_URL = "https://docs.showcase.copilotkit.ai";
const before = errs.length;
expect(freshGet().docsHost).toBe(DOCS_REDIRECTS_DISABLED_HOST);
expect(
errs.slice(before).some((m) => m.includes("disabled")),
"outcome change (fallback → disabled sentinel) must re-log",
).toBe(true);
// And the guard still holds per (mode, shellHost, value): an
// identical repeat call logs nothing new.
const after = errs.length;
freshGet();
expect(errs.length).toBe(after);
} finally {
errSpy.mockRestore();
warnSpy.mockRestore();
}
});
it("still falls back to the default docs host when only the CONFIGURED value collides", async () => {
// The fallback re-check must not over-trigger: a shell at its own
// (non-docs) host with a colliding DOCS_HOST keeps the working
// default — redirects stay enabled.
(process.env as Record<string, string>).NODE_ENV = "production";
process.env.BASE_URL = "https://shell.example.com";
process.env.DOCS_HOST = "https://shell.example.com";
vi.resetModules();
const { getRuntimeConfig: freshGet } = await import("./runtime-config");
const spy = vi.spyOn(console, "error").mockImplementation(() => {});
try {
expect(freshGet().docsHost).toBe("https://docs.showcase.copilotkit.ai");
} finally {
spy.mockRestore();
}
});
it("trips the self-host loop guard for a trailing-dot FQDN spelling (both compare sides)", async () => {
// `shell.example.com.` is the same authority as `shell.example.com`
// to DNS and browsers — the redirect table's self-referential paths
// loop just the same, but a literal host compare let the dotted
// spelling evade the guard.
(process.env as Record<string, string>).NODE_ENV = "production";
process.env.BASE_URL = "https://shell.example.com";
process.env.DOCS_HOST = "https://shell.example.com.";
vi.resetModules();
let { getRuntimeConfig: freshGet } = await import("./runtime-config");
const errs: string[] = [];
let spy = vi
.spyOn(console, "error")
.mockImplementation(
(...args: unknown[]) => void errs.push(args.map(String).join(" ")),
);
try {
expect(freshGet().docsHost).toBe("https://docs.showcase.copilotkit.ai");
expect(
errs.some((m) => m.includes("DOCS_HOST") && m.includes("own host")),
).toBe(true);
} finally {
spy.mockRestore();
}
// Dotted spelling on the SHELL side: the fallback collision
// re-check must normalize too, or a shell deployed at
// `docs.showcase.copilotkit.ai.` hands out the looping default.
process.env.BASE_URL = "https://docs.showcase.copilotkit.ai.";
delete process.env.DOCS_HOST;
vi.resetModules();
const fresh2 = await import("./runtime-config");
freshGet = fresh2.getRuntimeConfig;
spy = vi.spyOn(console, "error").mockImplementation(() => {});
try {
expect(freshGet().docsHost).toBe(fresh2.DOCS_REDIRECTS_DISABLED_HOST);
} finally {
spy.mockRestore();
}
});
it("does NOT trip the loop guard for same-hostname different-port docs (local dev)", () => {
// The loop predicate is the full authority (host:port), not the
// hostname: localhost:3000 (shell) → localhost:3005 (docs) is the
// documented dev wiring and terminates fine.
(process.env as Record<string, string>).NODE_ENV = "development";
process.env.BASE_URL = "http://localhost:3000";
process.env.DOCS_HOST = "http://localhost:3005";
expect(getRuntimeConfig().docsHost).toBe("http://localhost:3005");
});
it("returns the parsed-normalized form (host case, default port) for BASE_URL/DOCS_HOST/POSTHOG_HOST", () => {
// Validation already PARSES every value — returning the raw
// candidate string instead of the parsed form leaked un-normalized
// values (uppercase hosts, explicit default ports) to consumers,
// while the internal comparisons (e.g. the docs self-host guard)
// operate on parsed forms: the same authority could compare unequal
// to itself depending on which side was spelled canonically.
(process.env as Record<string, string>).NODE_ENV = "production";
process.env.BASE_URL = "https://Shell.Example.COM:443";
process.env.DOCS_HOST = "https://Docs.Example.COM:443";
process.env.POSTHOG_HOST = "https://Proxy.Example.COM:443/ingest";
const cfg = getRuntimeConfig();
expect(cfg.baseUrl).toBe("https://shell.example.com");
expect(cfg.docsHost).toBe("https://docs.example.com");
// Path preserved (reverse-proxy ingest), host normalized.
expect(cfg.posthogHost).toBe("https://proxy.example.com/ingest");
});
it("strips trailing slashes", () => {
(process.env as Record<string, string>).NODE_ENV = "production";
process.env.BASE_URL = "https://showcase.example.com/";
process.env.POSTHOG_HOST = "https://eu.i.posthog.com//";
const cfg = getRuntimeConfig();
expect(cfg.baseUrl).toBe("https://showcase.example.com");
expect(cfg.posthogHost).toBe("https://eu.i.posthog.com");
});
it("falls back to dev defaults when unset in non-production", () => {
(process.env as Record<string, string>).NODE_ENV = "development";
// Spy to keep the dev-fallback warning out of the test output.
const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => {});
try {
const cfg = getRuntimeConfig();
expect(cfg.baseUrl).toBe("http://localhost:3000");
expect(cfg.posthogHost).toBe("https://eu.i.posthog.com");