-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathindex.test.ts
More file actions
1300 lines (1121 loc) · 46.6 KB
/
index.test.ts
File metadata and controls
1300 lines (1121 loc) · 46.6 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 { test, expect, describe, beforeEach, afterEach, mock, spyOn } from "bun:test";
import {
captureLog,
configStubs,
credentialStoreStubs,
autolinkStubs,
gitStubs,
promptsStubs,
listageStubs,
} from "../../test/lib/stubs.ts";
import { PlapiError } from "../../lib/errors.ts";
const mockIsAgent = mock();
let _modeOverride: string | undefined;
mock.module("../../mode.ts", () => ({
isAgent: (...args: unknown[]) =>
_modeOverride !== undefined ? _modeOverride === "agent" : mockIsAgent(...args),
isHuman: (...args: unknown[]) =>
_modeOverride !== undefined ? _modeOverride !== "agent" : !mockIsAgent(...args),
setMode: (m: string) => {
_modeOverride = m;
},
getMode: () => _modeOverride ?? "human",
}));
const mockGetToken = mock();
mock.module("../../lib/credential-store.ts", () => ({
...credentialStoreStubs,
getToken: (...args: unknown[]) => mockGetToken(...args),
}));
const mockLogin = mock();
mock.module("../auth/login.ts", () => ({
login: (...args: unknown[]) => mockLogin(...args),
}));
const mockListApplications = mock();
const mockFetchApplication = mock();
const mockCreateApplication = mock();
mock.module("../../lib/plapi.ts", () => ({
listApplications: (...args: unknown[]) => mockListApplications(...args),
fetchApplication: (...args: unknown[]) => mockFetchApplication(...args),
createApplication: (...args: unknown[]) => mockCreateApplication(...args),
PlapiError: class PlapiError extends Error {},
fetchInstanceConfig: async () => ({}),
putInstanceConfig: async () => ({}),
patchInstanceConfig: async () => ({}),
}));
const mockSetProfile = mock();
const mockResolveProfile = mock();
const mockMoveProfile = mock();
mock.module("../../lib/config.ts", () => ({
...configStubs,
setProfile: (...args: unknown[]) => mockSetProfile(...args),
resolveProfile: (...args: unknown[]) => mockResolveProfile(...args),
moveProfile: (...args: unknown[]) => mockMoveProfile(...args),
}));
const mockAutolink = mock();
const mockFindClerkKeys = mock();
const mockMatchKeyToApp = mock();
mock.module("../../lib/autolink.ts", () => ({
...autolinkStubs,
autolink: (...args: unknown[]) => mockAutolink(...args),
findClerkKeys: (...args: unknown[]) => mockFindClerkKeys(...args),
matchKeyToApp: (...args: unknown[]) => mockMatchKeyToApp(...args),
}));
const mockGetGitRepoIdentifier = mock();
const mockGetGitRepoRoot = mock();
const mockGetGitNormalizedRemote = mock();
mock.module("../../lib/git.ts", () => ({
...gitStubs,
getGitRepoIdentifier: (...args: unknown[]) => mockGetGitRepoIdentifier(...args),
getGitRepoRoot: (...args: unknown[]) => mockGetGitRepoRoot(...args),
getGitNormalizedRemote: (...args: unknown[]) => mockGetGitNormalizedRemote(...args),
}));
const mockSearch = mock();
const mockConfirm = mock();
const mockInput = mock();
mock.module("@inquirer/prompts", () => ({
...promptsStubs,
search: (...args: unknown[]) => mockSearch(...args),
confirm: (...args: unknown[]) => mockConfirm(...args),
input: (...args: unknown[]) => mockInput(...args),
}));
mock.module("../../lib/prompts.ts", () => ({
confirm: (...args: unknown[]) => mockConfirm(...args),
}));
mock.module("../../lib/listage.ts", () => ({
...listageStubs,
search: (...args: unknown[]) => mockSearch(...args),
}));
mock.module("../../lib/spinner.ts", () => ({
intro: () => {},
outro: () => {},
bar: () => {},
withSpinner: async (_msg: string, fn: () => Promise<unknown>) => fn(),
}));
const { link } = await import("./index.ts");
const mockApp = {
application_id: "app_123",
instances: [
{
instance_id: "ins_dev",
environment_type: "development",
secret_key: "sk_test",
publishable_key: "pk_test",
},
{
instance_id: "ins_prod",
environment_type: "production",
secret_key: "sk_live",
publishable_key: "pk_live",
},
],
};
describe("link", () => {
let consoleSpy: ReturnType<typeof spyOn>;
let captured: ReturnType<typeof captureLog>;
beforeEach(() => {
captured = captureLog();
});
afterEach(() => {
captured.teardown();
_modeOverride = undefined;
mockIsAgent.mockReset();
mockGetToken.mockReset();
mockLogin.mockReset();
mockListApplications.mockReset();
mockFetchApplication.mockReset();
mockCreateApplication.mockReset();
mockSetProfile.mockReset();
mockResolveProfile.mockReset();
mockResolveProfile.mockResolvedValue(undefined);
mockAutolink.mockReset();
mockAutolink.mockResolvedValue(undefined);
mockFindClerkKeys.mockReset();
mockFindClerkKeys.mockResolvedValue([]);
mockMatchKeyToApp.mockReset();
mockMatchKeyToApp.mockReturnValue(undefined);
mockMoveProfile.mockReset();
mockGetGitRepoIdentifier.mockReset();
mockGetGitRepoIdentifier.mockResolvedValue("/repo/.git");
mockGetGitRepoRoot.mockReset();
mockGetGitRepoRoot.mockResolvedValue("/repo");
mockGetGitNormalizedRemote.mockReset();
mockGetGitNormalizedRemote.mockResolvedValue("github.com/org/repo");
mockSearch.mockReset();
mockConfirm.mockReset();
mockInput.mockReset();
consoleSpy?.mockRestore();
});
function runLink(options?: Parameters<typeof link>[0]) {
return captured.run(() => link(options));
}
describe("agent mode", () => {
test("links directly with --app", async () => {
mockIsAgent.mockReturnValue(true);
mockGetToken.mockResolvedValue("token");
mockFetchApplication.mockResolvedValue(mockApp);
consoleSpy = spyOn(console, "log").mockImplementation(() => {});
await runLink({ app: "app_123" });
expect(mockFetchApplication).toHaveBeenCalledWith("app_123");
expect(mockSetProfile).toHaveBeenCalledWith(
expect.any(String),
expect.objectContaining({
appId: "app_123",
instances: expect.objectContaining({ development: "ins_dev", production: "ins_prod" }),
}),
);
});
test("auto-links without prompts when a key match is available", async () => {
mockIsAgent.mockReturnValue(true);
mockAutolink.mockResolvedValue({
path: "github.com/org/repo",
profile: { workspaceId: "", appId: "app_auto", instances: { development: "ins_dev" } },
});
consoleSpy = spyOn(console, "log").mockImplementation(() => {});
await runLink();
expect(mockSearch).not.toHaveBeenCalled();
expect(mockGetToken).not.toHaveBeenCalled();
expect(mockListApplications).not.toHaveBeenCalled();
});
test("returns current link status when already linked and no app is provided", async () => {
mockIsAgent.mockReturnValue(true);
mockResolveProfile.mockResolvedValue({
path: "/repo/.git",
profile: { workspaceId: "", appId: "app_existing", instances: { development: "ins_1" } },
});
consoleSpy = spyOn(console, "log").mockImplementation(() => {});
await runLink();
expect(captured.err).toContain("Already linked");
expect(mockConfirm).not.toHaveBeenCalled();
expect(mockFetchApplication).not.toHaveBeenCalled();
expect(mockSetProfile).not.toHaveBeenCalled();
});
test("re-links directly when already linked and --app differs", async () => {
mockIsAgent.mockReturnValue(true);
mockGetToken.mockResolvedValue("token");
mockResolveProfile.mockResolvedValue({
path: "/repo/.git",
profile: { workspaceId: "", appId: "app_existing", instances: { development: "ins_1" } },
});
mockFetchApplication.mockResolvedValue(mockApp);
consoleSpy = spyOn(console, "log").mockImplementation(() => {});
await runLink({ app: "app_123" });
expect(mockConfirm).not.toHaveBeenCalled();
expect(mockFetchApplication).toHaveBeenCalledWith("app_123");
expect(mockSetProfile).toHaveBeenCalled();
});
test("errors when no deterministic app selection is available", async () => {
mockIsAgent.mockReturnValue(true);
consoleSpy = spyOn(console, "log").mockImplementation(() => {});
await expect(runLink()).rejects.toThrow(
"Cannot select an application in agent mode. Pass --app <id>",
);
expect(mockSearch).not.toHaveBeenCalled();
expect(mockListApplications).not.toHaveBeenCalled();
});
test("creates and links a new app when createIfMissing is provided", async () => {
mockIsAgent.mockReturnValue(true);
mockGetToken.mockResolvedValue("token");
mockCreateApplication.mockResolvedValue({ ...mockApp, application_id: "app_new" });
consoleSpy = spyOn(console, "log").mockImplementation(() => {});
await runLink({ createIfMissing: "my-project" });
expect(mockCreateApplication).toHaveBeenCalledWith("my-project");
expect(mockFetchApplication).not.toHaveBeenCalled();
expect(mockSearch).not.toHaveBeenCalled();
expect(mockListApplications).not.toHaveBeenCalled();
expect(mockSetProfile).toHaveBeenCalled();
});
test("autolink takes precedence over createIfMissing when keys match", async () => {
mockIsAgent.mockReturnValue(true);
mockAutolink.mockResolvedValue({
path: "github.com/org/repo",
profile: { workspaceId: "", appId: "app_existing", instances: { development: "ins_1" } },
});
consoleSpy = spyOn(console, "log").mockImplementation(() => {});
await runLink({ createIfMissing: "my-project" });
expect(mockAutolink).toHaveBeenCalled();
expect(mockCreateApplication).not.toHaveBeenCalled();
});
});
describe("already linked", () => {
test("notifies and returns when user declines re-link", async () => {
mockIsAgent.mockReturnValue(false);
mockResolveProfile.mockResolvedValue({
path: "/repo/.git",
profile: { workspaceId: "", appId: "app_existing", instances: { development: "ins_1" } },
});
mockConfirm.mockResolvedValue(false);
consoleSpy = spyOn(console, "log").mockImplementation(() => {});
await runLink();
const output = captured.err;
expect(output).toContain("Already linked");
expect(output).toContain("app_existing");
expect(mockConfirm).toHaveBeenCalled();
expect(mockGetToken).not.toHaveBeenCalled();
expect(mockListApplications).not.toHaveBeenCalled();
});
test("proceeds with re-link when user confirms", async () => {
mockIsAgent.mockReturnValue(false);
mockResolveProfile.mockResolvedValue({
path: "/repo/.git",
profile: { workspaceId: "", appId: "app_existing", instances: { development: "ins_1" } },
});
mockConfirm.mockResolvedValue(true);
mockGetToken.mockResolvedValue("token");
mockFetchApplication.mockResolvedValue(mockApp);
consoleSpy = spyOn(console, "log").mockImplementation(() => {});
await runLink({ app: "app_123" });
expect(mockConfirm).toHaveBeenCalled();
expect(mockSetProfile).toHaveBeenCalled();
});
});
describe("skipIfLinked", () => {
test("returns early when linked and no --app given", async () => {
mockIsAgent.mockReturnValue(false);
mockResolveProfile.mockResolvedValue({
path: "/repo/.git",
profile: { workspaceId: "", appId: "app_existing", instances: { development: "ins_1" } },
});
consoleSpy = spyOn(console, "log").mockImplementation(() => {});
await runLink({ skipIfLinked: true });
expect(captured.err).toContain("Already linked");
expect(mockConfirm).not.toHaveBeenCalled();
expect(mockFetchApplication).not.toHaveBeenCalled();
expect(mockSetProfile).not.toHaveBeenCalled();
});
test("returns early when linked to the same app as --app", async () => {
mockIsAgent.mockReturnValue(false);
mockResolveProfile.mockResolvedValue({
path: "/repo/.git",
profile: { workspaceId: "", appId: "app_123", instances: { development: "ins_1" } },
});
consoleSpy = spyOn(console, "log").mockImplementation(() => {});
await runLink({ skipIfLinked: true, app: "app_123" });
expect(captured.err).toContain("Already linked");
expect(mockConfirm).not.toHaveBeenCalled();
expect(mockFetchApplication).not.toHaveBeenCalled();
expect(mockSetProfile).not.toHaveBeenCalled();
});
test("falls through to re-link prompt when --app differs from existing link", async () => {
mockIsAgent.mockReturnValue(false);
mockResolveProfile.mockResolvedValue({
path: "/repo/.git",
profile: { workspaceId: "", appId: "app_existing", instances: { development: "ins_1" } },
});
mockGetToken.mockResolvedValue("token");
mockFetchApplication.mockResolvedValue(mockApp);
mockConfirm.mockResolvedValue(true);
consoleSpy = spyOn(console, "log").mockImplementation(() => {});
await runLink({ skipIfLinked: true, app: "app_123" });
expect(mockConfirm).toHaveBeenCalled();
expect(mockFetchApplication).toHaveBeenCalledWith("app_123");
expect(mockSetProfile).toHaveBeenCalled();
});
});
describe("authentication", () => {
test("calls login when no token exists", async () => {
mockIsAgent.mockReturnValue(false);
mockGetToken.mockResolvedValue(null);
mockLogin.mockResolvedValue({ userId: "user_1", email: "test@test.com" });
mockFetchApplication.mockResolvedValue(mockApp);
consoleSpy = spyOn(console, "log").mockImplementation(() => {});
await runLink({ app: "app_123" });
expect(mockLogin).toHaveBeenCalled();
});
test("skips login when token exists", async () => {
mockIsAgent.mockReturnValue(false);
mockGetToken.mockResolvedValue("oauth_token_123");
mockFetchApplication.mockResolvedValue(mockApp);
consoleSpy = spyOn(console, "log").mockImplementation(() => {});
await runLink({ app: "app_123" });
expect(mockLogin).not.toHaveBeenCalled();
});
test("suppresses auth next-steps when login runs during link", async () => {
mockIsAgent.mockReturnValue(false);
mockGetToken.mockResolvedValue(null);
mockLogin.mockResolvedValue({ userId: "user_1", email: "test@test.com" });
mockFetchApplication.mockResolvedValue(mockApp);
consoleSpy = spyOn(console, "log").mockImplementation(() => {});
await runLink({ app: "app_123" });
expect(mockLogin).toHaveBeenCalledWith({ showNextSteps: false });
});
});
describe("app selection", () => {
test("uses --app flag to skip picker", async () => {
mockIsAgent.mockReturnValue(false);
mockGetToken.mockResolvedValue("token");
mockFetchApplication.mockResolvedValue(mockApp);
consoleSpy = spyOn(console, "log").mockImplementation(() => {});
await runLink({ app: "app_123" });
expect(mockListApplications).not.toHaveBeenCalled();
expect(mockSearch).not.toHaveBeenCalled();
expect(mockFetchApplication).toHaveBeenCalledWith("app_123");
});
test("shows interactive picker when no --app flag", async () => {
mockIsAgent.mockReturnValue(false);
mockGetToken.mockResolvedValue("token");
mockListApplications.mockResolvedValue([
{
application_id: "app_a",
instances: [
{ instance_id: "ins_1", environment_type: "development", publishable_key: "pk_test" },
],
},
{
application_id: "app_b",
instances: [
{ instance_id: "ins_2", environment_type: "development", publishable_key: "pk_test2" },
],
},
]);
mockSearch.mockResolvedValue("app_a");
consoleSpy = spyOn(console, "log").mockImplementation(() => {});
await runLink();
expect(mockListApplications).toHaveBeenCalled();
expect(mockSearch).toHaveBeenCalled();
expect(mockFetchApplication).not.toHaveBeenCalled();
});
test("source returns all choices plus create option when term is empty", async () => {
mockIsAgent.mockReturnValue(false);
mockGetToken.mockResolvedValue("token");
mockListApplications.mockResolvedValue([
{
name: "My App",
application_id: "app_a",
instances: [
{ instance_id: "ins_1", environment_type: "development", publishable_key: "pk_test" },
],
},
{
name: "Other App",
application_id: "app_b",
instances: [
{ instance_id: "ins_2", environment_type: "development", publishable_key: "pk_test2" },
],
},
]);
mockSearch.mockImplementation(
async (config: { source: (term: string | undefined) => unknown[] }) => {
const results = config.source(undefined);
expect(results).toHaveLength(3); // 2 apps + create option
return "app_a";
},
);
consoleSpy = spyOn(console, "log").mockImplementation(() => {});
await runLink();
});
test("source filters choices by name substring (case-insensitive), keeps create option", async () => {
mockIsAgent.mockReturnValue(false);
mockGetToken.mockResolvedValue("token");
mockListApplications.mockResolvedValue([
{
name: "My App",
application_id: "app_a",
instances: [
{ instance_id: "ins_1", environment_type: "development", publishable_key: "pk_test" },
],
},
{
name: "Other App",
application_id: "app_b",
instances: [
{ instance_id: "ins_2", environment_type: "development", publishable_key: "pk_test2" },
],
},
]);
mockSearch.mockImplementation(
async (config: {
source: (term: string | undefined) => { name: string; value: string }[];
}) => {
const results = config.source("my");
expect(results).toHaveLength(2); // 1 match + create option
expect(results[0]!.value).toBe("app_a");
expect(results[1]!.value).toBe("__create_new__");
const noMatch = config.source("zzz");
expect(noMatch).toHaveLength(1); // only create option
expect(noMatch[0]!.value).toBe("__create_new__");
return "app_a";
},
);
consoleSpy = spyOn(console, "log").mockImplementation(() => {});
await runLink();
});
test("source filters by app ID when name is absent", async () => {
mockIsAgent.mockReturnValue(false);
mockGetToken.mockResolvedValue("token");
mockListApplications.mockResolvedValue([
{
application_id: "app_abc",
instances: [
{ instance_id: "ins_1", environment_type: "development", publishable_key: "pk_test" },
],
},
{
name: "Named",
application_id: "app_xyz",
instances: [
{ instance_id: "ins_2", environment_type: "development", publishable_key: "pk_test2" },
],
},
]);
mockSearch.mockImplementation(
async (config: {
source: (term: string | undefined) => { name: string; value: string }[];
}) => {
const results = config.source("abc");
expect(results).toHaveLength(2); // 1 match + create option
expect(results[0]!.value).toBe("app_abc");
expect(results[1]!.value).toBe("__create_new__");
return "app_abc";
},
);
consoleSpy = spyOn(console, "log").mockImplementation(() => {});
await runLink();
});
test("shows picker with create option when no apps found", async () => {
mockIsAgent.mockReturnValue(false);
mockGetToken.mockResolvedValue("token");
mockListApplications.mockResolvedValue([]);
mockSearch.mockImplementation(
async (config: {
source: (term: string | undefined) => { name: string; value: string }[];
}) => {
const results = config.source(undefined);
expect(results).toHaveLength(1);
expect(results[0]!.value).toBe("__create_new__");
return "__create_new__";
},
);
mockInput.mockResolvedValue("New App");
mockCreateApplication.mockResolvedValue({
application_id: "app_created",
name: "New App",
instances: [],
});
mockFetchApplication.mockResolvedValue({
application_id: "app_created",
name: "New App",
instances: [
{ instance_id: "ins_dev", environment_type: "development", publishable_key: "pk_test" },
],
});
consoleSpy = spyOn(console, "log").mockImplementation(() => {});
await runLink();
expect(mockCreateApplication).toHaveBeenCalledWith("New App");
expect(mockFetchApplication).toHaveBeenCalledWith("app_created");
expect(mockSetProfile).toHaveBeenCalled();
});
test("shows picker with only create option when listApplications fails with 500", async () => {
mockIsAgent.mockReturnValue(false);
mockGetToken.mockResolvedValue("token");
mockListApplications.mockRejectedValue(PlapiError.fromBody(500, "Internal Server Error"));
mockSearch.mockImplementation(
async (config: {
source: (term: string | undefined) => { name: string; value: string }[];
}) => {
const results = config.source(undefined);
expect(results).toHaveLength(1);
expect(results[0]!.value).toBe("__create_new__");
return "__create_new__";
},
);
mockInput.mockResolvedValue("My App");
mockCreateApplication.mockResolvedValue({
application_id: "app_new",
name: "My App",
instances: [],
});
mockFetchApplication.mockResolvedValue({
application_id: "app_new",
name: "My App",
instances: [
{ instance_id: "ins_dev", environment_type: "development", publishable_key: "pk_test" },
],
});
consoleSpy = spyOn(console, "log").mockImplementation(() => {});
await runLink();
expect(mockCreateApplication).toHaveBeenCalledWith("My App");
expect(mockSetProfile).toHaveBeenCalled();
});
test("propagates listApplications errors that are not 5xx", async () => {
mockIsAgent.mockReturnValue(false);
mockGetToken.mockResolvedValue("token");
mockListApplications.mockRejectedValue(PlapiError.fromBody(401, "Unauthorized"));
await expect(runLink()).rejects.toBeInstanceOf(PlapiError);
});
});
describe("profile storage", () => {
test("stores profile keyed by normalized remote URL", async () => {
mockIsAgent.mockReturnValue(false);
mockGetToken.mockResolvedValue("token");
mockFetchApplication.mockResolvedValue(mockApp);
mockGetGitNormalizedRemote.mockResolvedValue("github.com/org/repo");
mockGetGitRepoIdentifier.mockResolvedValue("/repo/.git");
consoleSpy = spyOn(console, "log").mockImplementation(() => {});
await runLink({ app: "app_123" });
expect(mockSetProfile).toHaveBeenCalledWith("github.com/org/repo", {
workspaceId: "",
appId: "app_123",
instances: {
development: "ins_dev",
production: "ins_prod",
},
});
});
test("falls back to git repo identifier when no remote", async () => {
mockIsAgent.mockReturnValue(false);
mockGetToken.mockResolvedValue("token");
mockFetchApplication.mockResolvedValue(mockApp);
mockGetGitNormalizedRemote.mockResolvedValue(undefined);
mockGetGitRepoIdentifier.mockResolvedValue("/repo/.git");
consoleSpy = spyOn(console, "log").mockImplementation(() => {});
await runLink({ app: "app_123" });
expect(mockSetProfile).toHaveBeenCalledWith("/repo/.git", {
workspaceId: "",
appId: "app_123",
instances: {
development: "ins_dev",
production: "ins_prod",
},
});
});
test("falls back to cwd when not in a git repo", async () => {
mockIsAgent.mockReturnValue(false);
mockGetToken.mockResolvedValue("token");
mockFetchApplication.mockResolvedValue(mockApp);
mockGetGitNormalizedRemote.mockResolvedValue(undefined);
mockGetGitRepoIdentifier.mockResolvedValue(undefined);
mockGetGitRepoRoot.mockResolvedValue(undefined);
consoleSpy = spyOn(console, "log").mockImplementation(() => {});
await runLink({ app: "app_123" });
expect(mockSetProfile).toHaveBeenCalledWith(process.cwd(), {
workspaceId: "",
appId: "app_123",
instances: {
development: "ins_dev",
production: "ins_prod",
},
});
});
test("omits production when not available", async () => {
mockIsAgent.mockReturnValue(false);
mockGetToken.mockResolvedValue("token");
mockFetchApplication.mockResolvedValue({
application_id: "app_123",
instances: [
{
instance_id: "ins_dev",
environment_type: "development",
secret_key: "sk_test",
publishable_key: "pk_test",
},
],
});
consoleSpy = spyOn(console, "log").mockImplementation(() => {});
await runLink({ app: "app_123" });
const storedProfile = mockSetProfile.mock.calls[0]![1];
expect(storedProfile.instances.production).toBeUndefined();
});
test("exits when no development instance", async () => {
mockIsAgent.mockReturnValue(false);
mockGetToken.mockResolvedValue("token");
mockFetchApplication.mockResolvedValue({
application_id: "app_123",
instances: [
{
instance_id: "ins_prod",
environment_type: "production",
secret_key: "sk_live",
publishable_key: "pk_live",
},
],
});
await expect(runLink({ app: "app_123" })).rejects.toThrow(
"Application has no development instance",
);
});
test("logs confirmation message", async () => {
mockIsAgent.mockReturnValue(false);
mockGetToken.mockResolvedValue("token");
mockFetchApplication.mockResolvedValue(mockApp);
consoleSpy = spyOn(console, "log").mockImplementation(() => {});
await runLink({ app: "app_123" });
expect(captured.err).toContain("Linked to");
});
});
describe("auto-link via remote", () => {
test("prints auto-link notice when resolved via remote", async () => {
mockIsAgent.mockReturnValue(false);
mockGetGitNormalizedRemote.mockResolvedValue("github.com/org/repo");
mockResolveProfile.mockResolvedValue({
path: "github.com/org/repo",
profile: { workspaceId: "", appId: "app_existing", instances: { development: "ins_1" } },
resolvedVia: "remote",
});
mockConfirm.mockResolvedValue(false);
consoleSpy = spyOn(console, "log").mockImplementation(() => {});
await runLink();
const output = captured.err;
expect(output).toContain("Auto-linked via git remote");
expect(output).toContain("github.com/org/repo");
});
test("skips silently with skipIfLinked after printing auto-link notice", async () => {
mockIsAgent.mockReturnValue(false);
mockGetGitNormalizedRemote.mockResolvedValue("github.com/org/repo");
mockResolveProfile.mockResolvedValue({
path: "github.com/org/repo",
profile: { workspaceId: "", appId: "app_existing", instances: { development: "ins_1" } },
resolvedVia: "remote",
});
consoleSpy = spyOn(console, "log").mockImplementation(() => {});
await runLink({ skipIfLinked: true });
const output = captured.err;
expect(output).toContain("Auto-linked via git remote");
expect(mockConfirm).not.toHaveBeenCalled();
expect(mockGetToken).not.toHaveBeenCalled();
});
test("does not print auto-link notice when resolved via git-common-dir", async () => {
mockIsAgent.mockReturnValue(false);
mockResolveProfile.mockResolvedValue({
path: "/repo/.git",
profile: { workspaceId: "", appId: "app_existing", instances: { development: "ins_1" } },
resolvedVia: "git-common-dir",
});
mockConfirm.mockResolvedValue(false);
consoleSpy = spyOn(console, "log").mockImplementation(() => {});
await runLink();
const output = captured.err;
expect(output).not.toContain("Auto-linked via git remote");
expect(output).toContain("Already linked");
});
});
describe("profile upgrade to remote", () => {
const dirProfile = {
path: "/projects/myapp",
profile: { workspaceId: "", appId: "app_existing", instances: { development: "ins_1" } },
resolvedVia: "directory" as const,
availableRemote: "github.com/org/repo",
};
test("offers upgrade when directory-keyed profile has available remote", async () => {
mockIsAgent.mockReturnValue(false);
mockGetGitNormalizedRemote.mockResolvedValue("github.com/org/repo");
mockResolveProfile.mockResolvedValue(dirProfile);
mockConfirm.mockResolvedValueOnce(true); // accept upgrade
consoleSpy = spyOn(console, "log").mockImplementation(() => {});
await runLink();
const output = captured.err;
expect(output).toContain("git repository with remote");
expect(output).toContain("Link updated");
expect(mockMoveProfile).toHaveBeenCalledWith("/projects/myapp", "github.com/org/repo");
});
test("falls through to re-link when upgrade is declined", async () => {
mockIsAgent.mockReturnValue(false);
mockGetGitNormalizedRemote.mockResolvedValue("github.com/org/repo");
mockResolveProfile.mockResolvedValue(dirProfile);
mockConfirm
.mockResolvedValueOnce(false) // decline upgrade
.mockResolvedValueOnce(false); // decline re-link
consoleSpy = spyOn(console, "log").mockImplementation(() => {});
await runLink();
expect(mockMoveProfile).not.toHaveBeenCalled();
expect(mockGetToken).not.toHaveBeenCalled();
});
test("skips upgrade prompt with skipIfLinked", async () => {
mockIsAgent.mockReturnValue(false);
mockGetGitNormalizedRemote.mockResolvedValue("github.com/org/repo");
mockResolveProfile.mockResolvedValue(dirProfile);
consoleSpy = spyOn(console, "log").mockImplementation(() => {});
await runLink({ skipIfLinked: true });
expect(mockConfirm).not.toHaveBeenCalled();
expect(mockMoveProfile).not.toHaveBeenCalled();
});
test("offers upgrade for git-common-dir profile with available remote", async () => {
mockIsAgent.mockReturnValue(false);
mockGetGitNormalizedRemote.mockResolvedValue("github.com/org/repo");
mockResolveProfile.mockResolvedValue({
...dirProfile,
path: "/repo/.git",
resolvedVia: "git-common-dir",
availableRemote: "github.com/org/repo",
});
mockConfirm.mockResolvedValueOnce(true); // accept upgrade
consoleSpy = spyOn(console, "log").mockImplementation(() => {});
await runLink();
expect(mockMoveProfile).toHaveBeenCalledWith("/repo/.git", "github.com/org/repo");
});
});
describe("autolink from detected keys", () => {
test("suggests detected app and links when user confirms", async () => {
mockIsAgent.mockReturnValue(false);
mockGetToken.mockResolvedValue("token");
mockListApplications.mockResolvedValue([mockApp]);
mockFindClerkKeys.mockResolvedValue([
{ key: "pk_test", source: "CLERK_PUBLISHABLE_KEY env var" },
]);
mockMatchKeyToApp.mockReturnValue({
app: mockApp,
instance: mockApp.instances[0],
source: "CLERK_PUBLISHABLE_KEY env var",
});
mockConfirm.mockResolvedValue(true);
consoleSpy = spyOn(console, "log").mockImplementation(() => {});
await runLink();
expect(mockFindClerkKeys).toHaveBeenCalled();
expect(mockMatchKeyToApp).toHaveBeenCalled();
expect(mockConfirm).toHaveBeenCalled();
expect(mockSetProfile).toHaveBeenCalledWith("github.com/org/repo", {
workspaceId: "",
appId: "app_123",
instances: {
development: "ins_dev",
production: "ins_prod",
},
});
expect(mockSearch).not.toHaveBeenCalled();
});
test("shows picker when user declines suggested app", async () => {
mockIsAgent.mockReturnValue(false);
mockGetToken.mockResolvedValue("token");
const otherApp = {
application_id: "app_other",
name: "Other App",
instances: [
{
instance_id: "ins_dev_other",
environment_type: "development",
publishable_key: "pk_other",
},
],
};
mockListApplications.mockResolvedValue([mockApp, otherApp]);
mockFindClerkKeys.mockResolvedValue([
{ key: "pk_test", source: "CLERK_PUBLISHABLE_KEY env var" },
]);
mockMatchKeyToApp.mockReturnValue({
app: mockApp,
instance: mockApp.instances[0],
source: "CLERK_PUBLISHABLE_KEY env var",
});
mockConfirm.mockResolvedValue(false);
mockSearch.mockResolvedValue("app_other");
consoleSpy = spyOn(console, "log").mockImplementation(() => {});
await runLink();
expect(mockSearch).toHaveBeenCalled();
expect(mockSetProfile).toHaveBeenCalledWith(
"github.com/org/repo",
expect.objectContaining({ appId: "app_other" }),
);
});
test("skips key detection when --app flag is provided", async () => {
mockIsAgent.mockReturnValue(false);
mockGetToken.mockResolvedValue("token");
mockFetchApplication.mockResolvedValue(mockApp);
consoleSpy = spyOn(console, "log").mockImplementation(() => {});
await runLink({ app: "app_123" });
expect(mockFindClerkKeys).not.toHaveBeenCalled();
expect(mockMatchKeyToApp).not.toHaveBeenCalled();
});
test("returns silently with skipIfLinked when autolink succeeds", async () => {
mockIsAgent.mockReturnValue(false);
mockAutolink.mockResolvedValue({
path: "github.com/org/repo",
profile: { workspaceId: "", appId: "app_detected", instances: { development: "ins_1" } },
});
consoleSpy = spyOn(console, "log").mockImplementation(() => {});
spyOn(console, "error").mockImplementation(() => {});
await runLink({ skipIfLinked: true });
expect(mockAutolink).toHaveBeenCalled();
expect(mockConfirm).not.toHaveBeenCalled();
expect(mockGetToken).not.toHaveBeenCalled();
});
test("falls through to picker when no keys detected", async () => {
mockIsAgent.mockReturnValue(false);
mockGetToken.mockResolvedValue("token");
mockListApplications.mockResolvedValue([mockApp]);
mockFindClerkKeys.mockResolvedValue([]);
mockSearch.mockResolvedValue("app_123");
consoleSpy = spyOn(console, "log").mockImplementation(() => {});
await runLink();
expect(mockFindClerkKeys).toHaveBeenCalled();
expect(mockMatchKeyToApp).not.toHaveBeenCalled();
expect(mockSearch).toHaveBeenCalled();
});
test("falls through to picker when keys don't match any app", async () => {
mockIsAgent.mockReturnValue(false);
mockGetToken.mockResolvedValue("token");
mockListApplications.mockResolvedValue([mockApp]);
mockFindClerkKeys.mockResolvedValue([{ key: "sk_unknown", source: ".env" }]);
mockMatchKeyToApp.mockReturnValue(undefined);
mockSearch.mockResolvedValue("app_123");
consoleSpy = spyOn(console, "log").mockImplementation(() => {});
await runLink();
expect(mockMatchKeyToApp).toHaveBeenCalled();
expect(mockConfirm).not.toHaveBeenCalled();
expect(mockSearch).toHaveBeenCalled();
});
});
describe("re-link skips key detection", () => {
test("skips key suggestion and shows picker when re-linking", async () => {
mockIsAgent.mockReturnValue(false);