-
Notifications
You must be signed in to change notification settings - Fork 2
/
api.ts
890 lines (811 loc) · 36.2 KB
/
api.ts
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
// NOTE: GENERATED by github.com/mjl-/sherpats, DO NOT MODIFY
namespace api {
export interface Overview {
Email: string // From User
UpdateInterval: Interval
MetaUnsubscribed: boolean
UpdatesUnsubscribed: boolean
Backoff: string
BackoffUntil: Date
SkipModulePaths?: string[] | null
Subscriptions?: Subscription[] | null
ModuleUpdates?: ModuleUpdateURLs[] | null
HookConfigs?: HookConfig[] | null
RecentHooks?: UpdateHook[] | null
UserLogs?: UserLog[] | null
}
// Subscription to a module. New versions will cause an Update to be registered and sent.
export interface Subscription {
ID: number
Module: string // Full path to subscribe to, e.g. github.com/mjl-. The transparency log can have entries for various upper/lower case variants. Easiest to care only about the canonical name.
BelowModule: boolean // If set, we also match module paths that are below the subscribed module.
OlderVersions: boolean // If set, we also send updates about added versions that are older than what seen previously. Can happen when multiple tags (versions) are pushed and old ones are fetched later.
Prerelease: boolean // No pre-release version, such as "v1.2.3-rc1", or "v1.2.3-0.20240214164601-39bfa4338a12".
Pseudo: boolean // No pseudo versions like "v0.0.0-20240214164601-39bfa4338a12".
Comment: string // Comment by user, to explain to future self why this is being monitored.
HookConfigID: number // If nonzero, don't deliver email message, but make a webhook call.
}
export interface ModuleUpdateURLs {
ID: number
UserID: number
SubscriptionID: number // No reference, subscriptions may be deleted.
LogRecordID: number // As found in transparency log.
Discovered: Date
Module: string
Version: string
MessageID: number // If 0, not yet sent. Only relevant when HookID is 0, otherwise this is a webhook call. We can suppress sending when recent messages have failed, or when our send rate has been too high. Index for enumerating updates that weren't notified about yet.
HookID: number // If nonzero, this is a webhook. The Hook record may have been cleaned up, but the ID remains, hence no ref.
HookConfigID: number
RepoURL: string
TagURL: string
DocURL: string
}
// HookConfig has the configured URL for deliveries by webhook.
export interface HookConfig {
ID: number
UserID: number
Name: string
URL: string // URL to POST JSON body to.
Headers?: (string[] | null)[] | null // Headers to send in request.
Disabled: boolean
}
export interface UpdateHook {
Update: ModuleUpdate
Hook: Hook
}
// ModuleUpdate is a registered update for a module for a subscription.
export interface ModuleUpdate {
ID: number
UserID: number
SubscriptionID: number // No reference, subscriptions may be deleted.
LogRecordID: number // As found in transparency log.
Discovered: Date
Module: string
Version: string
MessageID: number // If 0, not yet sent. Only relevant when HookID is 0, otherwise this is a webhook call. We can suppress sending when recent messages have failed, or when our send rate has been too high. Index for enumerating updates that weren't notified about yet.
HookID: number // If nonzero, this is a webhook. The Hook record may have been cleaned up, but the ID remains, hence no ref.
HookConfigID: number
}
// Hook represents the (scheduled) delivery of a module update.
export interface Hook {
ID: number
UserID: number // Index for listing recent hooks.
HookConfigID: number
URL: string // Copied from webhook config.
Queued: Date
LastResult: Date
Attempts: number // Start with 0. Increased each time, determines the next interval in case of errors.
NextAttempt: Date
Done: boolean // Index for quickly finding next work to do.
Results?: HookResult[] | null // From old attempts to recent.
}
// HookResult is the result of one attempt at a webhook delivery.
export interface HookResult {
StatusCode: number // Successful if 2xx.
Error: string
Response: string // Max 256 bytes, only if text/plain or application/json.
Start: Date
DurationMS: number
}
// UserLog is a line of history about a change to the user account.
export interface UserLog {
ID: number
UserID: number
Time: Date
Text: string
}
export interface SubscriptionImport {
GoMod: string
BelowModule: boolean
OlderVersions: boolean
Prerelease: boolean
Pseudo: boolean
Comment: string
HookConfigID: number
Indirect: boolean
}
export interface Home {
Version: string
GoVersion: string
GoOS: string
GoArch: string
ServiceName: string
AdminName: string
AdminEmail: string
Note: string
SignupNote: string
SkipModulePrefixes?: string[] | null
SignupEmailDisabled: boolean
SignupWebsiteDisabled: boolean
SignupAddress: string
Recents?: Recent[] | null
}
export interface Recent {
Module: string
Version: string
Discovered: Date
RepoURL: string
TagURL: string
DocURL: string
}
// How often a user wants to receive update notification email messages.
export enum Interval {
IntervalImmediate = "immediate",
IntervalHour = "hour",
IntervalDay = "day",
IntervalWeek = "week",
}
export const structTypes: {[typename: string]: boolean} = {"Home":true,"Hook":true,"HookConfig":true,"HookResult":true,"ModuleUpdate":true,"ModuleUpdateURLs":true,"Overview":true,"Recent":true,"Subscription":true,"SubscriptionImport":true,"UpdateHook":true,"UserLog":true}
export const stringsTypes: {[typename: string]: boolean} = {"Interval":true}
export const intsTypes: {[typename: string]: boolean} = {}
export const types: TypenameMap = {
"Overview": {"Name":"Overview","Docs":"","Fields":[{"Name":"Email","Docs":"","Typewords":["string"]},{"Name":"UpdateInterval","Docs":"","Typewords":["Interval"]},{"Name":"MetaUnsubscribed","Docs":"","Typewords":["bool"]},{"Name":"UpdatesUnsubscribed","Docs":"","Typewords":["bool"]},{"Name":"Backoff","Docs":"","Typewords":["string"]},{"Name":"BackoffUntil","Docs":"","Typewords":["timestamp"]},{"Name":"SkipModulePaths","Docs":"","Typewords":["[]","string"]},{"Name":"Subscriptions","Docs":"","Typewords":["[]","Subscription"]},{"Name":"ModuleUpdates","Docs":"","Typewords":["[]","ModuleUpdateURLs"]},{"Name":"HookConfigs","Docs":"","Typewords":["[]","HookConfig"]},{"Name":"RecentHooks","Docs":"","Typewords":["[]","UpdateHook"]},{"Name":"UserLogs","Docs":"","Typewords":["[]","UserLog"]}]},
"Subscription": {"Name":"Subscription","Docs":"","Fields":[{"Name":"ID","Docs":"","Typewords":["int64"]},{"Name":"Module","Docs":"","Typewords":["string"]},{"Name":"BelowModule","Docs":"","Typewords":["bool"]},{"Name":"OlderVersions","Docs":"","Typewords":["bool"]},{"Name":"Prerelease","Docs":"","Typewords":["bool"]},{"Name":"Pseudo","Docs":"","Typewords":["bool"]},{"Name":"Comment","Docs":"","Typewords":["string"]},{"Name":"HookConfigID","Docs":"","Typewords":["int64"]}]},
"ModuleUpdateURLs": {"Name":"ModuleUpdateURLs","Docs":"","Fields":[{"Name":"ID","Docs":"","Typewords":["int64"]},{"Name":"UserID","Docs":"","Typewords":["int64"]},{"Name":"SubscriptionID","Docs":"","Typewords":["int64"]},{"Name":"LogRecordID","Docs":"","Typewords":["int64"]},{"Name":"Discovered","Docs":"","Typewords":["timestamp"]},{"Name":"Module","Docs":"","Typewords":["string"]},{"Name":"Version","Docs":"","Typewords":["string"]},{"Name":"MessageID","Docs":"","Typewords":["int64"]},{"Name":"HookID","Docs":"","Typewords":["int64"]},{"Name":"HookConfigID","Docs":"","Typewords":["int64"]},{"Name":"RepoURL","Docs":"","Typewords":["string"]},{"Name":"TagURL","Docs":"","Typewords":["string"]},{"Name":"DocURL","Docs":"","Typewords":["string"]}]},
"HookConfig": {"Name":"HookConfig","Docs":"","Fields":[{"Name":"ID","Docs":"","Typewords":["int64"]},{"Name":"UserID","Docs":"","Typewords":["int64"]},{"Name":"Name","Docs":"","Typewords":["string"]},{"Name":"URL","Docs":"","Typewords":["string"]},{"Name":"Headers","Docs":"","Typewords":["[]","[]","string"]},{"Name":"Disabled","Docs":"","Typewords":["bool"]}]},
"UpdateHook": {"Name":"UpdateHook","Docs":"","Fields":[{"Name":"Update","Docs":"","Typewords":["ModuleUpdate"]},{"Name":"Hook","Docs":"","Typewords":["Hook"]}]},
"ModuleUpdate": {"Name":"ModuleUpdate","Docs":"","Fields":[{"Name":"ID","Docs":"","Typewords":["int64"]},{"Name":"UserID","Docs":"","Typewords":["int64"]},{"Name":"SubscriptionID","Docs":"","Typewords":["int64"]},{"Name":"LogRecordID","Docs":"","Typewords":["int64"]},{"Name":"Discovered","Docs":"","Typewords":["timestamp"]},{"Name":"Module","Docs":"","Typewords":["string"]},{"Name":"Version","Docs":"","Typewords":["string"]},{"Name":"MessageID","Docs":"","Typewords":["int64"]},{"Name":"HookID","Docs":"","Typewords":["int64"]},{"Name":"HookConfigID","Docs":"","Typewords":["int64"]}]},
"Hook": {"Name":"Hook","Docs":"","Fields":[{"Name":"ID","Docs":"","Typewords":["int64"]},{"Name":"UserID","Docs":"","Typewords":["int64"]},{"Name":"HookConfigID","Docs":"","Typewords":["int64"]},{"Name":"URL","Docs":"","Typewords":["string"]},{"Name":"Queued","Docs":"","Typewords":["timestamp"]},{"Name":"LastResult","Docs":"","Typewords":["timestamp"]},{"Name":"Attempts","Docs":"","Typewords":["int32"]},{"Name":"NextAttempt","Docs":"","Typewords":["timestamp"]},{"Name":"Done","Docs":"","Typewords":["bool"]},{"Name":"Results","Docs":"","Typewords":["[]","HookResult"]}]},
"HookResult": {"Name":"HookResult","Docs":"","Fields":[{"Name":"StatusCode","Docs":"","Typewords":["int32"]},{"Name":"Error","Docs":"","Typewords":["string"]},{"Name":"Response","Docs":"","Typewords":["string"]},{"Name":"Start","Docs":"","Typewords":["timestamp"]},{"Name":"DurationMS","Docs":"","Typewords":["int64"]}]},
"UserLog": {"Name":"UserLog","Docs":"","Fields":[{"Name":"ID","Docs":"","Typewords":["int64"]},{"Name":"UserID","Docs":"","Typewords":["int64"]},{"Name":"Time","Docs":"","Typewords":["timestamp"]},{"Name":"Text","Docs":"","Typewords":["string"]}]},
"SubscriptionImport": {"Name":"SubscriptionImport","Docs":"","Fields":[{"Name":"GoMod","Docs":"","Typewords":["string"]},{"Name":"BelowModule","Docs":"","Typewords":["bool"]},{"Name":"OlderVersions","Docs":"","Typewords":["bool"]},{"Name":"Prerelease","Docs":"","Typewords":["bool"]},{"Name":"Pseudo","Docs":"","Typewords":["bool"]},{"Name":"Comment","Docs":"","Typewords":["string"]},{"Name":"HookConfigID","Docs":"","Typewords":["int64"]},{"Name":"Indirect","Docs":"","Typewords":["bool"]}]},
"Home": {"Name":"Home","Docs":"","Fields":[{"Name":"Version","Docs":"","Typewords":["string"]},{"Name":"GoVersion","Docs":"","Typewords":["string"]},{"Name":"GoOS","Docs":"","Typewords":["string"]},{"Name":"GoArch","Docs":"","Typewords":["string"]},{"Name":"ServiceName","Docs":"","Typewords":["string"]},{"Name":"AdminName","Docs":"","Typewords":["string"]},{"Name":"AdminEmail","Docs":"","Typewords":["string"]},{"Name":"Note","Docs":"","Typewords":["string"]},{"Name":"SignupNote","Docs":"","Typewords":["string"]},{"Name":"SkipModulePrefixes","Docs":"","Typewords":["[]","string"]},{"Name":"SignupEmailDisabled","Docs":"","Typewords":["bool"]},{"Name":"SignupWebsiteDisabled","Docs":"","Typewords":["bool"]},{"Name":"SignupAddress","Docs":"","Typewords":["string"]},{"Name":"Recents","Docs":"","Typewords":["[]","Recent"]}]},
"Recent": {"Name":"Recent","Docs":"","Fields":[{"Name":"Module","Docs":"","Typewords":["string"]},{"Name":"Version","Docs":"","Typewords":["string"]},{"Name":"Discovered","Docs":"","Typewords":["timestamp"]},{"Name":"RepoURL","Docs":"","Typewords":["string"]},{"Name":"TagURL","Docs":"","Typewords":["string"]},{"Name":"DocURL","Docs":"","Typewords":["string"]}]},
"Interval": {"Name":"Interval","Docs":"","Values":[{"Name":"IntervalImmediate","Value":"immediate","Docs":""},{"Name":"IntervalHour","Value":"hour","Docs":""},{"Name":"IntervalDay","Value":"day","Docs":""},{"Name":"IntervalWeek","Value":"week","Docs":""}]},
}
export const parser = {
Overview: (v: any) => parse("Overview", v) as Overview,
Subscription: (v: any) => parse("Subscription", v) as Subscription,
ModuleUpdateURLs: (v: any) => parse("ModuleUpdateURLs", v) as ModuleUpdateURLs,
HookConfig: (v: any) => parse("HookConfig", v) as HookConfig,
UpdateHook: (v: any) => parse("UpdateHook", v) as UpdateHook,
ModuleUpdate: (v: any) => parse("ModuleUpdate", v) as ModuleUpdate,
Hook: (v: any) => parse("Hook", v) as Hook,
HookResult: (v: any) => parse("HookResult", v) as HookResult,
UserLog: (v: any) => parse("UserLog", v) as UserLog,
SubscriptionImport: (v: any) => parse("SubscriptionImport", v) as SubscriptionImport,
Home: (v: any) => parse("Home", v) as Home,
Recent: (v: any) => parse("Recent", v) as Recent,
Interval: (v: any) => parse("Interval", v) as Interval,
}
// API holds functions for the frontend.
let defaultOptions: ClientOptions = {slicesNullable: true, mapsNullable: true, nullableOptional: true}
export class Client {
private baseURL: string
public authState: AuthState
public options: ClientOptions
constructor() {
this.authState = {}
this.options = {...defaultOptions}
this.baseURL = this.options.baseURL || defaultBaseURL
}
withAuthToken(token: string): Client {
const c = new Client()
c.authState.token = token
c.options = this.options
return c
}
withOptions(options: ClientOptions): Client {
const c = new Client()
c.authState = this.authState
c.options = { ...this.options, ...options }
return c
}
// Signup registers a new account. We send an email for users to verify they
// control the email address. If we already have a verified account, we send a
// password reset instead.
async Signup(prepToken: string, email: string): Promise<void> {
const fn: string = "Signup"
const paramTypes: string[][] = [["string"],["string"]]
const returnTypes: string[][] = []
const params: any[] = [prepToken, email]
return await _sherpaCall(this.baseURL, this.authState, { ...this.options }, paramTypes, returnTypes, fn, params) as void
}
// SignupEmail returns the email address for a verify token. So we can show it, and
// the user can get prompted for saving full full login credentials by a password
// manager after verifying the signup.
async SignupEmail(prepToken: string, verifyToken: string): Promise<string> {
const fn: string = "SignupEmail"
const paramTypes: string[][] = [["string"],["string"]]
const returnTypes: string[][] = [["string"]]
const params: any[] = [prepToken, verifyToken]
return await _sherpaCall(this.baseURL, this.authState, { ...this.options }, paramTypes, returnTypes, fn, params) as string
}
// VerifySignup verifies a new account by checking the token. The token was in the
// URL in the signup email.
async VerifySignup(prepToken: string, verifyToken: string, email: string, password: string): Promise<string> {
const fn: string = "VerifySignup"
const paramTypes: string[][] = [["string"],["string"],["string"],["string"]]
const returnTypes: string[][] = [["string"]]
const params: any[] = [prepToken, verifyToken, email, password]
return await _sherpaCall(this.baseURL, this.authState, { ...this.options }, paramTypes, returnTypes, fn, params) as string
}
// UserRemove lets a user remove their account.
async UserRemove(): Promise<void> {
const fn: string = "UserRemove"
const paramTypes: string[][] = []
const returnTypes: string[][] = []
const params: any[] = []
return await _sherpaCall(this.baseURL, this.authState, { ...this.options }, paramTypes, returnTypes, fn, params) as void
}
// Redeem turns a login token, as used in login-links in notification emails, into
// a session by returning a csrf token and setting a session cookie.
async Redeem(prepToken: string, loginToken: string): Promise<string> {
const fn: string = "Redeem"
const paramTypes: string[][] = [["string"],["string"]]
const returnTypes: string[][] = [["string"]]
const params: any[] = [prepToken, loginToken]
return await _sherpaCall(this.baseURL, this.authState, { ...this.options }, paramTypes, returnTypes, fn, params) as string
}
// RequestPasswordReset requests a password reset. We send an email with a link
// with a password reset token.
async RequestPasswordReset(prepToken: string, email: string): Promise<void> {
const fn: string = "RequestPasswordReset"
const paramTypes: string[][] = [["string"],["string"]]
const returnTypes: string[][] = []
const params: any[] = [prepToken, email]
return await _sherpaCall(this.baseURL, this.authState, { ...this.options }, paramTypes, returnTypes, fn, params) as void
}
// ResetPassword resets a password for an account based on a token.
async ResetPassword(prepToken: string, email: string, password: string, resetToken: string): Promise<void> {
const fn: string = "ResetPassword"
const paramTypes: string[][] = [["string"],["string"],["string"],["string"]]
const returnTypes: string[][] = []
const params: any[] = [prepToken, email, password, resetToken]
return await _sherpaCall(this.baseURL, this.authState, { ...this.options }, paramTypes, returnTypes, fn, params) as void
}
// Prep helps prevent CSRF calls. It must be called before calling functions like
// Login, Subscribe. It returns a token, which it also sets as a samesite cookie.
// The subsequent call must pass in the token, and the request must have the cookie
// set.
async Prep(): Promise<string> {
const fn: string = "Prep"
const paramTypes: string[][] = []
const returnTypes: string[][] = [["string"]]
const params: any[] = []
return await _sherpaCall(this.baseURL, this.authState, { ...this.options }, paramTypes, returnTypes, fn, params) as string
}
// Login verifies the accounts password and creates a new session, returning a csrf
// token that must be present in an x-csrf header in subsequent calls. A same-site
// cookie is set too.
async Login(prepToken: string, email: string, password: string): Promise<string> {
const fn: string = "Login"
const paramTypes: string[][] = [["string"],["string"],["string"]]
const returnTypes: string[][] = [["string"]]
const params: any[] = [prepToken, email, password]
return await _sherpaCall(this.baseURL, this.authState, { ...this.options }, paramTypes, returnTypes, fn, params) as string
}
// Logout clears the session cookie. It does not invalidate the session.
async Logout(): Promise<void> {
const fn: string = "Logout"
const paramTypes: string[][] = []
const returnTypes: string[][] = []
const params: any[] = []
return await _sherpaCall(this.baseURL, this.authState, { ...this.options }, paramTypes, returnTypes, fn, params) as void
}
// Overview returns data needed for the overview page, after logging in.
async Overview(): Promise<Overview> {
const fn: string = "Overview"
const paramTypes: string[][] = []
const returnTypes: string[][] = [["Overview"]]
const params: any[] = []
return await _sherpaCall(this.baseURL, this.authState, { ...this.options }, paramTypes, returnTypes, fn, params) as Overview
}
// SubscribeSet changes either meta (service messages) or module updates
// subscriptions. If not subscribed, no messages are sent.
async SubscribeSet(meta: boolean, subscribed: boolean): Promise<void> {
const fn: string = "SubscribeSet"
const paramTypes: string[][] = [["bool"],["bool"]]
const returnTypes: string[][] = []
const params: any[] = [meta, subscribed]
return await _sherpaCall(this.baseURL, this.authState, { ...this.options }, paramTypes, returnTypes, fn, params) as void
}
// SetInterval sets a new minimum interval between update messages.
async IntervalSet(interval: Interval): Promise<void> {
const fn: string = "IntervalSet"
const paramTypes: string[][] = [["Interval"]]
const returnTypes: string[][] = []
const params: any[] = [interval]
return await _sherpaCall(this.baseURL, this.authState, { ...this.options }, paramTypes, returnTypes, fn, params) as void
}
// SubscriptionCreate adds a new subscription to a module.
async SubscriptionCreate(sub: Subscription): Promise<Subscription> {
const fn: string = "SubscriptionCreate"
const paramTypes: string[][] = [["Subscription"]]
const returnTypes: string[][] = [["Subscription"]]
const params: any[] = [sub]
return await _sherpaCall(this.baseURL, this.authState, { ...this.options }, paramTypes, returnTypes, fn, params) as Subscription
}
// SubscriptionImport parses a go.mod file and subscribes to all direct and
// optionally indirect dependencies.
async SubscriptionImport(imp: SubscriptionImport): Promise<Subscription[] | null> {
const fn: string = "SubscriptionImport"
const paramTypes: string[][] = [["SubscriptionImport"]]
const returnTypes: string[][] = [["[]","Subscription"]]
const params: any[] = [imp]
return await _sherpaCall(this.baseURL, this.authState, { ...this.options }, paramTypes, returnTypes, fn, params) as Subscription[] | null
}
// SubscriptionSave updates an existing subscription to a module.
async SubscriptionSave(sub: Subscription): Promise<void> {
const fn: string = "SubscriptionSave"
const paramTypes: string[][] = [["Subscription"]]
const returnTypes: string[][] = []
const params: any[] = [sub]
return await _sherpaCall(this.baseURL, this.authState, { ...this.options }, paramTypes, returnTypes, fn, params) as void
}
// SubscriptionRemove removes an existing subscription.
async SubscriptionRemove(subID: number): Promise<void> {
const fn: string = "SubscriptionRemove"
const paramTypes: string[][] = [["int64"]]
const returnTypes: string[][] = []
const params: any[] = [subID]
return await _sherpaCall(this.baseURL, this.authState, { ...this.options }, paramTypes, returnTypes, fn, params) as void
}
// Home returns data for the home page.
async Home(): Promise<Home> {
const fn: string = "Home"
const paramTypes: string[][] = []
const returnTypes: string[][] = [["Home"]]
const params: any[] = []
return await _sherpaCall(this.baseURL, this.authState, { ...this.options }, paramTypes, returnTypes, fn, params) as Home
}
// Recents returns more recent packages, currently 150.
async Recents(): Promise<Recent[] | null> {
const fn: string = "Recents"
const paramTypes: string[][] = []
const returnTypes: string[][] = [["[]","Recent"]]
const params: any[] = []
return await _sherpaCall(this.baseURL, this.authState, { ...this.options }, paramTypes, returnTypes, fn, params) as Recent[] | null
}
// Forward tries a bit harder to forward the transparency log. While we
// periodically fetch the /latest database tree state and forward the log, at
// least sum.golang.org only returns new values about once every 10 minutes.
// But we can look at the latest additions to index.golang.org and get the most
// recently added module from it, then look it up to get the associated tree
// state and forward based on that.
async Forward(): Promise<void> {
const fn: string = "Forward"
const paramTypes: string[][] = []
const returnTypes: string[][] = []
const params: any[] = []
return await _sherpaCall(this.baseURL, this.authState, { ...this.options }, paramTypes, returnTypes, fn, params) as void
}
async TestSend(secret: string, kind: string, email: string): Promise<void> {
const fn: string = "TestSend"
const paramTypes: string[][] = [["string"],["string"],["string"]]
const returnTypes: string[][] = []
const params: any[] = [secret, kind, email]
return await _sherpaCall(this.baseURL, this.authState, { ...this.options }, paramTypes, returnTypes, fn, params) as void
}
async HookConfigAdd(hc: HookConfig): Promise<HookConfig> {
const fn: string = "HookConfigAdd"
const paramTypes: string[][] = [["HookConfig"]]
const returnTypes: string[][] = [["HookConfig"]]
const params: any[] = [hc]
return await _sherpaCall(this.baseURL, this.authState, { ...this.options }, paramTypes, returnTypes, fn, params) as HookConfig
}
async HookConfigSave(hc: HookConfig): Promise<void> {
const fn: string = "HookConfigSave"
const paramTypes: string[][] = [["HookConfig"]]
const returnTypes: string[][] = []
const params: any[] = [hc]
return await _sherpaCall(this.baseURL, this.authState, { ...this.options }, paramTypes, returnTypes, fn, params) as void
}
async HookConfigRemove(hcID: number): Promise<void> {
const fn: string = "HookConfigRemove"
const paramTypes: string[][] = [["int64"]]
const returnTypes: string[][] = []
const params: any[] = [hcID]
return await _sherpaCall(this.baseURL, this.authState, { ...this.options }, paramTypes, returnTypes, fn, params) as void
}
async HookCancel(hID: number): Promise<Hook> {
const fn: string = "HookCancel"
const paramTypes: string[][] = [["int64"]]
const returnTypes: string[][] = [["Hook"]]
const params: any[] = [hID]
return await _sherpaCall(this.baseURL, this.authState, { ...this.options }, paramTypes, returnTypes, fn, params) as Hook
}
async HookKick(hID: number): Promise<Hook> {
const fn: string = "HookKick"
const paramTypes: string[][] = [["int64"]]
const returnTypes: string[][] = [["Hook"]]
const params: any[] = [hID]
return await _sherpaCall(this.baseURL, this.authState, { ...this.options }, paramTypes, returnTypes, fn, params) as Hook
}
}
export const defaultBaseURL = (function() {
let p = location.pathname
if (p && p[p.length - 1] !== '/') {
let l = location.pathname.split('/')
l = l.slice(0, l.length - 1)
p = '/' + l.join('/') + '/'
}
return location.protocol + '//' + location.host + p + 'api/'
})()
// NOTE: code below is shared between github.com/mjl-/sherpaweb and github.com/mjl-/sherpats.
// KEEP IN SYNC.
export const supportedSherpaVersion = 1
export interface Section {
Name: string
Docs: string
Functions: Function[]
Sections: Section[]
Structs: Struct[]
Ints: Ints[]
Strings: Strings[]
Version: string // only for top-level section
SherpaVersion: number // only for top-level section
SherpadocVersion: number // only for top-level section
}
export interface Function {
Name: string
Docs: string
Params: Arg[]
Returns: Arg[]
}
export interface Arg {
Name: string
Typewords: string[]
}
export interface Struct {
Name: string
Docs: string
Fields: Field[]
}
export interface Field {
Name: string
Docs: string
Typewords: string[]
}
export interface Ints {
Name: string
Docs: string
Values: {
Name: string
Value: number
Docs: string
}[] | null
}
export interface Strings {
Name: string
Docs: string
Values: {
Name: string
Value: string
Docs: string
}[] | null
}
export type NamedType = Struct | Strings | Ints
export type TypenameMap = { [k: string]: NamedType }
// verifyArg typechecks "v" against "typewords", returning a new (possibly modified) value for JSON-encoding.
// toJS indicate if the data is coming into JS. If so, timestamps are turned into JS Dates. Otherwise, JS Dates are turned into strings.
// allowUnknownKeys configures whether unknown keys in structs are allowed.
// types are the named types of the API.
export const verifyArg = (path: string, v: any, typewords: string[], toJS: boolean, allowUnknownKeys: boolean, types: TypenameMap, opts: ClientOptions): any => {
return new verifier(types, toJS, allowUnknownKeys, opts).verify(path, v, typewords)
}
export const parse = (name: string, v: any): any => verifyArg(name, v, [name], true, false, types, defaultOptions)
class verifier {
constructor(private types: TypenameMap, private toJS: boolean, private allowUnknownKeys: boolean, private opts: ClientOptions) {
}
verify(path: string, v: any, typewords: string[]): any {
typewords = typewords.slice(0)
const ww = typewords.shift()
const error = (msg: string) => {
if (path != '') {
msg = path + ': ' + msg
}
throw new Error(msg)
}
if (typeof ww !== 'string') {
error('bad typewords')
return // should not be necessary, typescript doesn't see error always throws an exception?
}
const w: string = ww
const ensure = (ok: boolean, expect: string): any => {
if (!ok) {
error('got ' + JSON.stringify(v) + ', expected ' + expect)
}
return v
}
switch (w) {
case 'nullable':
if (v === null || v === undefined && this.opts.nullableOptional) {
return v
}
return this.verify(path, v, typewords)
case '[]':
if (v === null && this.opts.slicesNullable || v === undefined && this.opts.slicesNullable && this.opts.nullableOptional) {
return v
}
ensure(Array.isArray(v), "array")
return v.map((e: any, i: number) => this.verify(path + '[' + i + ']', e, typewords))
case '{}':
if (v === null && this.opts.mapsNullable || v === undefined && this.opts.mapsNullable && this.opts.nullableOptional) {
return v
}
ensure(v !== null || typeof v === 'object', "object")
const r: any = {}
for (const k in v) {
r[k] = this.verify(path + '.' + k, v[k], typewords)
}
return r
}
ensure(typewords.length == 0, "empty typewords")
const t = typeof v
switch (w) {
case 'any':
return v
case 'bool':
ensure(t === 'boolean', 'bool')
return v
case 'int8':
case 'uint8':
case 'int16':
case 'uint16':
case 'int32':
case 'uint32':
case 'int64':
case 'uint64':
ensure(t === 'number' && Number.isInteger(v), 'integer')
return v
case 'float32':
case 'float64':
ensure(t === 'number', 'float')
return v
case 'int64s':
case 'uint64s':
ensure(t === 'number' && Number.isInteger(v) || t === 'string', 'integer fitting in float without precision loss, or string')
return '' + v
case 'string':
ensure(t === 'string', 'string')
return v
case 'timestamp':
if (this.toJS) {
ensure(t === 'string', 'string, with timestamp')
const d = new Date(v)
if (d instanceof Date && !isNaN(d.getTime())) {
return d
}
error('invalid date ' + v)
} else {
ensure(t === 'object' && v !== null, 'non-null object')
ensure(v.__proto__ === Date.prototype, 'Date')
return v.toISOString()
}
}
// We're left with named types.
const nt = this.types[w]
if (!nt) {
error('unknown type ' + w)
}
if (v === null) {
error('bad value ' + v + ' for named type ' + w)
}
if (structTypes[nt.Name]) {
const t = nt as Struct
if (typeof v !== 'object') {
error('bad value ' + v + ' for struct ' + w)
}
const r: any = {}
for (const f of t.Fields) {
r[f.Name] = this.verify(path + '.' + f.Name, v[f.Name], f.Typewords)
}
// If going to JSON also verify no unknown fields are present.
if (!this.allowUnknownKeys) {
const known: { [key: string]: boolean } = {}
for (const f of t.Fields) {
known[f.Name] = true
}
Object.keys(v).forEach((k) => {
if (!known[k]) {
error('unknown key ' + k + ' for struct ' + w)
}
})
}
return r
} else if (stringsTypes[nt.Name]) {
const t = nt as Strings
if (typeof v !== 'string') {
error('mistyped value ' + v + ' for named strings ' + t.Name)
}
if (!t.Values || t.Values.length === 0) {
return v
}
for (const sv of t.Values) {
if (sv.Value === v) {
return v
}
}
error('unknown value ' + v + ' for named strings ' + t.Name)
} else if (intsTypes[nt.Name]) {
const t = nt as Ints
if (typeof v !== 'number' || !Number.isInteger(v)) {
error('mistyped value ' + v + ' for named ints ' + t.Name)
}
if (!t.Values || t.Values.length === 0) {
return v
}
for (const sv of t.Values) {
if (sv.Value === v) {
return v
}
}
error('unknown value ' + v + ' for named ints ' + t.Name)
} else {
throw new Error('unexpected named type ' + nt)
}
}
}
export interface ClientOptions {
baseURL?: string
aborter?: {abort?: () => void}
timeoutMsec?: number
skipParamCheck?: boolean
skipReturnCheck?: boolean
slicesNullable?: boolean
mapsNullable?: boolean
nullableOptional?: boolean
csrfHeader?: string
login?: (reason: string) => Promise<string>
}
export interface AuthState {
token?: string // For csrf request header.
loginPromise?: Promise<void> // To let multiple API calls wait for a single login attempt, not each opening a login popup.
}
const _sherpaCall = async (baseURL: string, authState: AuthState, options: ClientOptions, paramTypes: string[][], returnTypes: string[][], name: string, params: any[]): Promise<any> => {
if (!options.skipParamCheck) {
if (params.length !== paramTypes.length) {
return Promise.reject({ message: 'wrong number of parameters in sherpa call, saw ' + params.length + ' != expected ' + paramTypes.length })
}
params = params.map((v: any, index: number) => verifyArg('params[' + index + ']', v, paramTypes[index], false, false, types, options))
}
const simulate = async (json: string) => {
const config = JSON.parse(json || 'null') || {}
const waitMinMsec = config.waitMinMsec || 0
const waitMaxMsec = config.waitMaxMsec || 0
const wait = Math.random() * (waitMaxMsec - waitMinMsec)
const failRate = config.failRate || 0
return new Promise<void>((resolve, reject) => {
if (options.aborter) {
options.aborter.abort = () => {
reject({ message: 'call to ' + name + ' aborted by user', code: 'sherpa:aborted' })
reject = resolve = () => { }
}
}
setTimeout(() => {
const r = Math.random()
if (r < failRate) {
reject({ message: 'injected failure on ' + name, code: 'server:injected' })
} else {
resolve()
}
reject = resolve = () => { }
}, waitMinMsec + wait)
})
}
// Only simulate when there is a debug string. Otherwise it would always interfere
// with setting options.aborter.
let json: string = ''
try {
json = window.localStorage.getItem('sherpats-debug') || ''
} catch (err) {}
if (json) {
await simulate(json)
}
const fn = (resolve: (v: any) => void, reject: (v: any) => void) => {
let resolve1 = (v: any) => {
resolve(v)
resolve1 = () => { }
reject1 = () => { }
}
let reject1 = (v: { code: string, message: string }) => {
if ((v.code === 'user:noAuth' || v.code === 'user:badAuth') && options.login) {
const login = options.login
if (!authState.loginPromise) {
authState.loginPromise = new Promise((aresolve, areject) => {
login(v.code === 'user:badAuth' ? (v.message || '') : '')
.then((token) => {
authState.token = token
authState.loginPromise = undefined
aresolve()
}, (err: any) => {
authState.loginPromise = undefined
areject(err)
})
})
}
authState.loginPromise
.then(() => {
fn(resolve, reject)
}, (err: any) => {
reject(err)
})
return
}
reject(v)
resolve1 = () => { }
reject1 = () => { }
}
const url = baseURL + name
const req = new window.XMLHttpRequest()
if (options.aborter) {
options.aborter.abort = () => {
req.abort()
reject1({ code: 'sherpa:aborted', message: 'request aborted' })
}
}
req.open('POST', url, true)
if (options.csrfHeader && authState.token) {
req.setRequestHeader(options.csrfHeader, authState.token)
}
if (options.timeoutMsec) {
req.timeout = options.timeoutMsec
}
req.onload = () => {
if (req.status !== 200) {
if (req.status === 404) {
reject1({ code: 'sherpa:badFunction', message: 'function does not exist' })
} else {
reject1({ code: 'sherpa:http', message: 'error calling function, HTTP status: ' + req.status })
}
return
}
let resp: any
try {
resp = JSON.parse(req.responseText)
} catch (err) {
reject1({ code: 'sherpa:badResponse', message: 'bad JSON from server' })
return
}
if (resp && resp.error) {
const err = resp.error
reject1({ code: err.code, message: err.message })
return
} else if (!resp || !resp.hasOwnProperty('result')) {
reject1({ code: 'sherpa:badResponse', message: "invalid sherpa response object, missing 'result'" })
return
}
if (options.skipReturnCheck) {
resolve1(resp.result)
return
}
let result = resp.result
try {
if (returnTypes.length === 0) {
if (result) {
throw new Error('function ' + name + ' returned a value while prototype says it returns "void"')
}
} else if (returnTypes.length === 1) {
result = verifyArg('result', result, returnTypes[0], true, true, types, options)
} else {
if (result.length != returnTypes.length) {
throw new Error('wrong number of values returned by ' + name + ', saw ' + result.length + ' != expected ' + returnTypes.length)
}
result = result.map((v: any, index: number) => verifyArg('result[' + index + ']', v, returnTypes[index], true, true, types, options))
}
} catch (err) {
let errmsg = 'bad types'
if (err instanceof Error) {
errmsg = err.message
}
reject1({ code: 'sherpa:badTypes', message: errmsg })
}
resolve1(result)
}
req.onerror = () => {
reject1({ code: 'sherpa:connection', message: 'connection failed' })
}
req.ontimeout = () => {
reject1({ code: 'sherpa:timeout', message: 'request timeout' })
}
req.setRequestHeader('Content-Type', 'application/json')
try {
req.send(JSON.stringify({ params: params }))
} catch (err) {
reject1({ code: 'sherpa:badData', message: 'cannot marshal to JSON' })
}
}
return await new Promise(fn)
}
}