-
Notifications
You must be signed in to change notification settings - Fork 0
/
nats.js
8349 lines (8349 loc) · 226 KB
/
nats.js
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
const Empty = new Uint8Array(0);
var Events;
(function(Events1) {
Events1["Disconnect"] = "disconnect";
Events1["Reconnect"] = "reconnect";
Events1["Update"] = "update";
Events1["LDM"] = "ldm";
Events1["Error"] = "error";
})(Events || (Events = {}));
var DebugEvents;
(function(DebugEvents1) {
DebugEvents1["Reconnecting"] = "reconnecting";
DebugEvents1["PingTimer"] = "pingTimer";
DebugEvents1["StaleConnection"] = "staleConnection";
})(DebugEvents || (DebugEvents = {}));
const DEFAULT_HOST = "127.0.0.1";
const DEFAULT_RECONNECT_TIME_WAIT = 2 * 1000;
const DEFAULT_PING_INTERVAL = 2 * 60 * 1000;
const DEFAULT_MAX_PING_OUT = 2;
var AdvisoryKind;
(function(AdvisoryKind1) {
AdvisoryKind1["API"] = "api_audit";
AdvisoryKind1["StreamAction"] = "stream_action";
AdvisoryKind1["ConsumerAction"] = "consumer_action";
AdvisoryKind1["SnapshotCreate"] = "snapshot_create";
AdvisoryKind1["SnapshotComplete"] = "snapshot_complete";
AdvisoryKind1["RestoreCreate"] = "restore_create";
AdvisoryKind1["RestoreComplete"] = "restore_complete";
AdvisoryKind1["MaxDeliver"] = "max_deliver";
AdvisoryKind1["Terminated"] = "terminated";
AdvisoryKind1["Ack"] = "consumer_ack";
AdvisoryKind1["StreamLeaderElected"] = "stream_leader_elected";
AdvisoryKind1["StreamQuorumLost"] = "stream_quorum_lost";
AdvisoryKind1["ConsumerLeaderElected"] = "consumer_leader_elected";
AdvisoryKind1["ConsumerQuorumLost"] = "consumer_quorum_lost";
})(AdvisoryKind || (AdvisoryKind = {}));
var RetentionPolicy;
(function(RetentionPolicy1) {
RetentionPolicy1["Limits"] = "limits";
RetentionPolicy1["Interest"] = "interest";
RetentionPolicy1["Workqueue"] = "workqueue";
})(RetentionPolicy || (RetentionPolicy = {}));
var DiscardPolicy;
(function(DiscardPolicy1) {
DiscardPolicy1["Old"] = "old";
DiscardPolicy1["New"] = "new";
})(DiscardPolicy || (DiscardPolicy = {}));
var StorageType;
(function(StorageType1) {
StorageType1["File"] = "file";
StorageType1["Memory"] = "memory";
})(StorageType || (StorageType = {}));
var DeliverPolicy;
(function(DeliverPolicy1) {
DeliverPolicy1["All"] = "all";
DeliverPolicy1["Last"] = "last";
DeliverPolicy1["New"] = "new";
DeliverPolicy1["StartSequence"] = "by_start_sequence";
DeliverPolicy1["StartTime"] = "by_start_time";
DeliverPolicy1["LastPerSubject"] = "last_per_subject";
})(DeliverPolicy || (DeliverPolicy = {}));
var AckPolicy;
(function(AckPolicy1) {
AckPolicy1["None"] = "none";
AckPolicy1["All"] = "all";
AckPolicy1["Explicit"] = "explicit";
AckPolicy1["NotSet"] = "";
})(AckPolicy || (AckPolicy = {}));
var ReplayPolicy;
(function(ReplayPolicy1) {
ReplayPolicy1["Instant"] = "instant";
ReplayPolicy1["Original"] = "original";
})(ReplayPolicy || (ReplayPolicy = {}));
var JsHeaders;
(function(JsHeaders1) {
JsHeaders1["StreamSourceHdr"] = "Nats-Stream-Source";
JsHeaders1["LastConsumerSeqHdr"] = "Nats-Last-Consumer";
JsHeaders1["LastStreamSeqHdr"] = "Nats-Last-Stream";
JsHeaders1["ConsumerStalledHdr"] = "Nats-Consumer-Stalled";
JsHeaders1["MessageSizeHdr"] = "Nats-Msg-Size";
JsHeaders1["RollupHdr"] = "Nats-Rollup";
JsHeaders1["RollupValueSubject"] = "sub";
JsHeaders1["RollupValueAll"] = "all";
})(JsHeaders || (JsHeaders = {}));
var ErrorCode;
(function(ErrorCode1) {
ErrorCode1["ApiError"] = "BAD API";
ErrorCode1["BadAuthentication"] = "BAD_AUTHENTICATION";
ErrorCode1["BadCreds"] = "BAD_CREDS";
ErrorCode1["BadHeader"] = "BAD_HEADER";
ErrorCode1["BadJson"] = "BAD_JSON";
ErrorCode1["BadPayload"] = "BAD_PAYLOAD";
ErrorCode1["BadSubject"] = "BAD_SUBJECT";
ErrorCode1["Cancelled"] = "CANCELLED";
ErrorCode1["ConnectionClosed"] = "CONNECTION_CLOSED";
ErrorCode1["ConnectionDraining"] = "CONNECTION_DRAINING";
ErrorCode1["ConnectionRefused"] = "CONNECTION_REFUSED";
ErrorCode1["ConnectionTimeout"] = "CONNECTION_TIMEOUT";
ErrorCode1["Disconnect"] = "DISCONNECT";
ErrorCode1["InvalidOption"] = "INVALID_OPTION";
ErrorCode1["InvalidPayload"] = "INVALID_PAYLOAD";
ErrorCode1["MaxPayloadExceeded"] = "MAX_PAYLOAD_EXCEEDED";
ErrorCode1["NoResponders"] = "503";
ErrorCode1["NotFunction"] = "NOT_FUNC";
ErrorCode1["RequestError"] = "REQUEST_ERROR";
ErrorCode1["ServerOptionNotAvailable"] = "SERVER_OPT_NA";
ErrorCode1["SubClosed"] = "SUB_CLOSED";
ErrorCode1["SubDraining"] = "SUB_DRAINING";
ErrorCode1["Timeout"] = "TIMEOUT";
ErrorCode1["Tls"] = "TLS";
ErrorCode1["Unknown"] = "UNKNOWN_ERROR";
ErrorCode1["WssRequired"] = "WSS_REQUIRED";
ErrorCode1["JetStreamInvalidAck"] = "JESTREAM_INVALID_ACK";
ErrorCode1["JetStream404NoMessages"] = "404";
ErrorCode1["JetStream408RequestTimeout"] = "408";
ErrorCode1["JetStream409MaxAckPendingExceeded"] = "409";
ErrorCode1["JetStreamNotEnabled"] = "503";
ErrorCode1["AuthorizationViolation"] = "AUTHORIZATION_VIOLATION";
ErrorCode1["AuthenticationExpired"] = "AUTHENTICATION_EXPIRED";
ErrorCode1["ProtocolError"] = "NATS_PROTOCOL_ERR";
ErrorCode1["PermissionsViolation"] = "PERMISSIONS_VIOLATION";
})(ErrorCode || (ErrorCode = {}));
class Messages {
messages;
constructor(){
this.messages = new Map();
this.messages.set(ErrorCode.InvalidPayload, "Invalid payload type - payloads can be 'binary', 'string', or 'json'");
this.messages.set(ErrorCode.BadJson, "Bad JSON");
this.messages.set(ErrorCode.WssRequired, "TLS is required, therefore a secure websocket connection is also required");
}
static getMessage(s) {
return messages.getMessage(s);
}
getMessage(s) {
return this.messages.get(s) || s;
}
}
const messages = new Messages();
function isNatsError(err) {
return typeof err.code === "string";
}
class NatsError extends Error {
name;
message;
code;
chainedError;
api_error;
constructor(message, code1, chainedError){
super(message);
this.name = "NatsError";
this.message = message;
this.code = code1;
this.chainedError = chainedError;
}
static errorForCode(code2, chainedError) {
const m = Messages.getMessage(code2);
return new NatsError(m, code2, chainedError);
}
isAuthError() {
return this.code === ErrorCode.AuthenticationExpired || this.code === ErrorCode.AuthorizationViolation;
}
isPermissionError() {
return this.code === ErrorCode.PermissionsViolation;
}
isProtocolError() {
return this.code === ErrorCode.ProtocolError;
}
isJetStreamError() {
return this.api_error !== undefined;
}
jsError() {
return this.api_error ? this.api_error : null;
}
}
function validateDurableName(name) {
return validateName("durable", name);
}
function validateStreamName(name) {
return validateName("stream", name);
}
function validateName(context, name = "") {
if (name === "") {
throw Error(`${context} name required`);
}
const bad = [
".",
"*",
">"
];
bad.forEach((v)=>{
if (name.indexOf(v) !== -1) {
throw Error(`invalid ${context} name - ${context} name cannot contain '${v}'`);
}
});
}
function defaultConsumer(name, opts = {}) {
return Object.assign({
name: name,
deliver_policy: DeliverPolicy.All,
ack_policy: AckPolicy.Explicit,
ack_wait: nanos(30 * 1000),
replay_policy: ReplayPolicy.Instant
}, opts);
}
function nanos(millis1) {
return millis1 * 1000000;
}
function millis(ns) {
return ns / 1000000;
}
function isFlowControlMsg(msg) {
const h = msg.headers;
if (!h) {
return false;
}
return h.code >= 100 && h.code < 200;
}
function isHeartbeatMsg(msg) {
return isFlowControlMsg(msg) && msg.headers?.description === "Idle Heartbeat";
}
function checkJsError(msg) {
const h = msg.headers;
if (!h) {
return null;
}
return checkJsErrorCode(h.code, h.status);
}
function checkJsErrorCode(code3, description = "") {
if (code3 < 300) {
return null;
}
description = description.toLowerCase();
switch(code3){
case 408:
return NatsError.errorForCode(ErrorCode.JetStream408RequestTimeout, new Error(description));
case 503:
return NatsError.errorForCode(ErrorCode.JetStreamNotEnabled, new Error(description));
default:
if (description === "") {
description = ErrorCode.Unknown;
}
return new NatsError(description, `${code3}`);
}
}
const TE = new TextEncoder();
const TD = new TextDecoder();
function concat(...bufs) {
let max = 0;
for(let i2 = 0; i2 < bufs.length; i2++){
max += bufs[i2].length;
}
const out = new Uint8Array(max);
let index = 0;
for(let i1 = 0; i1 < bufs.length; i1++){
out.set(bufs[i1], index);
index += bufs[i1].length;
}
return out;
}
function encode(...a) {
const bufs = [];
for(let i3 = 0; i3 < a.length; i3++){
bufs.push(TE.encode(a[i3]));
}
if (bufs.length === 0) {
return Empty;
}
if (bufs.length === 1) {
return bufs[0];
}
return concat(...bufs);
}
function decode(a) {
if (!a || a.length === 0) {
return "";
}
return TD.decode(a);
}
class DataBuffer {
buffers;
byteLength;
constructor(){
this.buffers = [];
this.byteLength = 0;
}
static concat(...bufs) {
let max = 0;
for(let i4 = 0; i4 < bufs.length; i4++){
max += bufs[i4].length;
}
const out = new Uint8Array(max);
let index = 0;
for(let i1 = 0; i1 < bufs.length; i1++){
out.set(bufs[i1], index);
index += bufs[i1].length;
}
return out;
}
static fromAscii(m) {
if (!m) {
m = "";
}
return TE.encode(m);
}
static toAscii(a) {
return TD.decode(a);
}
reset() {
this.buffers.length = 0;
this.byteLength = 0;
}
pack() {
if (this.buffers.length > 1) {
const v = new Uint8Array(this.byteLength);
let index = 0;
for(let i5 = 0; i5 < this.buffers.length; i5++){
v.set(this.buffers[i5], index);
index += this.buffers[i5].length;
}
this.buffers.length = 0;
this.buffers.push(v);
}
}
drain(n) {
if (this.buffers.length) {
this.pack();
const v = this.buffers.pop();
if (v) {
const max = this.byteLength;
if (n === undefined || n > max) {
n = max;
}
const d = v.subarray(0, n);
if (max > n) {
this.buffers.push(v.subarray(n));
}
this.byteLength = max - n;
return d;
}
}
return new Uint8Array(0);
}
fill(a, ...bufs) {
if (a) {
this.buffers.push(a);
this.byteLength += a.length;
}
for(let i6 = 0; i6 < bufs.length; i6++){
if (bufs[i6] && bufs[i6].length) {
this.buffers.push(bufs[i6]);
this.byteLength += bufs[i6].length;
}
}
}
peek() {
if (this.buffers.length) {
this.pack();
return this.buffers[0];
}
return new Uint8Array(0);
}
size() {
return this.byteLength;
}
length() {
return this.buffers.length;
}
}
const CR_LF = "\r\n";
CR_LF.length;
const CRLF = DataBuffer.fromAscii(CR_LF);
const CR = new Uint8Array(CRLF)[0];
const LF = new Uint8Array(CRLF)[1];
function isUint8Array(a) {
return a instanceof Uint8Array;
}
function protoLen(ba) {
for(let i7 = 0; i7 < ba.length; i7++){
const n = i7 + 1;
if (ba.byteLength > n && ba[i7] === CR && ba[n] === LF) {
return n + 1;
}
}
return 0;
}
function extractProtocolMessage(a) {
const len = protoLen(a);
if (len > 0) {
const ba = new Uint8Array(a);
const out = ba.slice(0, len);
return TD.decode(out);
}
return "";
}
function extend(a, ...b) {
for(let i8 = 0; i8 < b.length; i8++){
const o = b[i8];
Object.keys(o).forEach(function(k) {
a[k] = o[k];
});
}
return a;
}
function render(frame) {
const cr = "␍";
const lf = "␊";
return TD.decode(frame).replace(/\n/g, lf).replace(/\r/g, cr);
}
function timeout(ms) {
const err = NatsError.errorForCode(ErrorCode.Timeout);
let methods;
let timer;
const p = new Promise((_resolve, reject)=>{
const cancel = ()=>{
if (timer) {
clearTimeout(timer);
}
};
methods = {
cancel
};
timer = setTimeout(()=>{
reject(err);
}, ms);
});
return Object.assign(p, methods);
}
function delay(ms = 0) {
return new Promise((resolve)=>{
setTimeout(()=>{
resolve();
}, ms);
});
}
function deferred() {
let methods = {};
const p = new Promise((resolve, reject)=>{
methods = {
resolve,
reject
};
});
return Object.assign(p, methods);
}
function shuffle(a) {
for(let i9 = a.length - 1; i9 > 0; i9--){
const j = Math.floor(Math.random() * (i9 + 1));
[a[i9], a[j]] = [
a[j],
a[i9]
];
}
return a;
}
class Perf {
timers;
measures;
constructor(){
this.timers = new Map();
this.measures = new Map();
}
mark(key) {
this.timers.set(key, Date.now());
}
measure(key, startKey, endKey) {
const s = this.timers.get(startKey);
if (s === undefined) {
throw new Error(`${startKey} is not defined`);
}
const e = this.timers.get(endKey);
if (e === undefined) {
throw new Error(`${endKey} is not defined`);
}
this.measures.set(key, e - s);
}
getEntries() {
const values = [];
this.measures.forEach((v, k)=>{
values.push({
name: k,
duration: v
});
});
return values;
}
}
class QueuedIteratorImpl {
inflight;
processed;
received;
noIterator;
iterClosed;
done;
signal;
yields;
filtered;
pendingFiltered;
ingestionFilterFn;
protocolFilterFn;
dispatchedFn;
ctx;
_data;
err;
constructor(){
this.inflight = 0;
this.filtered = 0;
this.pendingFiltered = 0;
this.processed = 0;
this.received = 0;
this.noIterator = false;
this.done = false;
this.signal = deferred();
this.yields = [];
this.iterClosed = deferred();
}
[Symbol.asyncIterator]() {
return this.iterate();
}
push(v) {
if (this.done) {
return;
}
const { ingest , protocol } = this.ingestionFilterFn ? this.ingestionFilterFn(v, this.ctx || this) : {
ingest: true,
protocol: false
};
if (ingest) {
if (protocol) {
this.filtered++;
this.pendingFiltered++;
}
this.yields.push(v);
this.signal.resolve();
}
}
async *iterate() {
if (this.noIterator) {
throw new NatsError("unsupported iterator", ErrorCode.ApiError);
}
try {
while(true){
if (this.yields.length === 0) {
await this.signal;
}
if (this.err) {
throw this.err;
}
const yields = this.yields;
this.inflight = yields.length;
this.yields = [];
for(let i10 = 0; i10 < yields.length; i10++){
const ok = this.protocolFilterFn ? this.protocolFilterFn(yields[i10]) : true;
if (ok) {
this.processed++;
yield yields[i10];
if (this.dispatchedFn && yields[i10]) {
this.dispatchedFn(yields[i10]);
}
} else {
this.pendingFiltered--;
}
this.inflight--;
}
if (this.done) {
break;
} else if (this.yields.length === 0) {
yields.length = 0;
this.yields = yields;
this.signal = deferred();
}
}
} finally{
this.stop();
}
}
stop(err) {
if (this.done) {
return;
}
this.err = err;
this.done = true;
this.signal.resolve();
this.iterClosed.resolve();
}
getProcessed() {
return this.noIterator ? this.received : this.processed;
}
getPending() {
return this.yields.length + this.inflight - this.pendingFiltered;
}
getReceived() {
return this.received - this.filtered;
}
}
function canonicalMIMEHeaderKey(k) {
const dash = 45;
const toLower = 97 - 65;
let upper = true;
const buf = new Array(k.length);
for(let i11 = 0; i11 < k.length; i11++){
let c = k.charCodeAt(i11);
if (c === 58 || c < 33 || c > 126) {
throw new NatsError(`'${k[i11]}' is not a valid character for a header key`, ErrorCode.BadHeader);
}
if (upper && 97 <= c && c <= 122) {
c -= toLower;
} else if (!upper && 65 <= c && c <= 90) {
c += toLower;
}
buf[i11] = c;
upper = c == dash;
}
return String.fromCharCode(...buf);
}
function headers() {
return new MsgHdrsImpl();
}
const HEADER = "NATS/1.0";
var Match;
(function(Match1) {
Match1[Match1["Exact"] = 0] = "Exact";
Match1[Match1["CanonicalMIME"] = 1] = "CanonicalMIME";
Match1[Match1["IgnoreCase"] = 2] = "IgnoreCase";
})(Match || (Match = {}));
class MsgHdrsImpl {
code;
headers;
description;
constructor(){
this.code = 0;
this.headers = new Map();
this.description = "";
}
[Symbol.iterator]() {
return this.headers.entries();
}
size() {
return this.headers.size;
}
equals(mh) {
if (mh && this.headers.size === mh.headers.size && this.code === mh.code) {
for (const [k, v] of this.headers){
const a = mh.values(k);
if (v.length !== a.length) {
return false;
}
const vv = [
...v
].sort();
const aa = [
...a
].sort();
for(let i12 = 0; i12 < vv.length; i12++){
if (vv[i12] !== aa[i12]) {
return false;
}
}
}
return true;
}
return false;
}
static decode(a) {
const mh = new MsgHdrsImpl();
const s1 = TD.decode(a);
const lines = s1.split("\r\n");
const h = lines[0];
if (h !== HEADER) {
let str = h.replace(HEADER, "");
mh.code = parseInt(str, 10);
const scode = mh.code.toString();
str = str.replace(scode, "");
mh.description = str.trim();
}
if (lines.length >= 1) {
lines.slice(1).map((s)=>{
if (s) {
const idx = s.indexOf(":");
if (idx > -1) {
const k = s.slice(0, idx);
const v = s.slice(idx + 1).trim();
mh.append(k, v);
}
}
});
}
return mh;
}
toString() {
if (this.headers.size === 0) {
return "";
}
let s = HEADER;
for (const [k, v] of this.headers){
for(let i13 = 0; i13 < v.length; i13++){
s = `${s}\r\n${k}: ${v[i13]}`;
}
}
return `${s}\r\n\r\n`;
}
encode() {
return TE.encode(this.toString());
}
static validHeaderValue(k) {
const inv = /[\r\n]/;
if (inv.test(k)) {
throw new NatsError("invalid header value - \\r and \\n are not allowed.", ErrorCode.BadHeader);
}
return k.trim();
}
keys() {
const keys = [];
for (const sk of this.headers.keys()){
keys.push(sk);
}
return keys;
}
findKeys(k, match = Match.Exact) {
const keys = this.keys();
switch(match){
case Match.Exact:
return keys.filter((v)=>{
return v === k;
});
case Match.CanonicalMIME:
k = canonicalMIMEHeaderKey(k);
return keys.filter((v)=>{
return v === k;
});
default:
{
const lci = k.toLowerCase();
return keys.filter((v)=>{
return lci === v.toLowerCase();
});
}
}
}
get(k, match = Match.Exact) {
const keys = this.findKeys(k, match);
if (keys.length) {
const v = this.headers.get(keys[0]);
if (v) {
return Array.isArray(v) ? v[0] : v;
}
}
return "";
}
has(k, match = Match.Exact) {
return this.findKeys(k, match).length > 0;
}
set(k, v, match = Match.Exact) {
this.delete(k, match);
this.append(k, v, match);
}
append(k, v, match = Match.Exact) {
const ck = canonicalMIMEHeaderKey(k);
if (match === Match.CanonicalMIME) {
k = ck;
}
const keys = this.findKeys(k, match);
k = keys.length > 0 ? keys[0] : k;
const value = MsgHdrsImpl.validHeaderValue(v);
let a = this.headers.get(k);
if (!a) {
a = [];
this.headers.set(k, a);
}
a.push(value);
}
values(k, match = Match.Exact) {
const buf = [];
const keys = this.findKeys(k, match);
keys.forEach((v)=>{
const values = this.headers.get(v);
if (values) {
buf.push(...values);
}
});
return buf;
}
delete(k, match = Match.Exact) {
const keys = this.findKeys(k, match);
keys.forEach((v)=>{
this.headers.delete(v);
});
}
get hasError() {
return this.code >= 300;
}
get status() {
return `${this.code} ${this.description}`.trim();
}
}
function StringCodec() {
return {
encode (d) {
return TE.encode(d);
},
decode (a) {
return TD.decode(a);
}
};
}
function JSONCodec(reviver) {
return {
encode (d) {
try {
if (d === undefined) {
d = null;
}
return TE.encode(JSON.stringify(d));
} catch (err) {
throw NatsError.errorForCode(ErrorCode.BadJson, err);
}
},
decode (a) {
try {
return JSON.parse(TD.decode(a), reviver);
} catch (err) {
throw NatsError.errorForCode(ErrorCode.BadJson, err);
}
}
};
}
const defaultPrefix = "$JS.API";
function defaultJsOptions(opts) {
opts = opts || {};
if (opts.domain) {
opts.apiPrefix = `$JS.${opts.domain}.API`;
delete opts.domain;
}
return extend({
apiPrefix: defaultPrefix,
timeout: 5000
}, opts);
}
class BaseApiClient {
nc;
opts;
prefix;
timeout;
jc;
constructor(nc, opts){
this.nc = nc;
this.opts = defaultJsOptions(opts);
this._parseOpts();
this.prefix = this.opts.apiPrefix;
this.timeout = this.opts.timeout;
this.jc = JSONCodec();
}
_parseOpts() {
let prefix = this.opts.apiPrefix;
if (!prefix || prefix.length === 0) {
throw new Error("invalid empty prefix");
}
const c = prefix[prefix.length - 1];
if (c === ".") {
prefix = prefix.substr(0, prefix.length - 1);
}
this.opts.apiPrefix = prefix;
}
async _request(subj, data = null, opts) {
opts = opts || {};
opts.timeout = this.timeout;
let a = Empty;
if (data) {
a = this.jc.encode(data);
}
const m = await this.nc.request(subj, a, opts);
return this.parseJsResponse(m);
}
async findStream(subject) {
const q = {
subject
};
const r = await this._request(`${this.prefix}.STREAM.NAMES`, q);
const names = r;
if (!names.streams || names.streams.length !== 1) {
throw new Error("no stream matches subject");
}
return names.streams[0];
}
parseJsResponse(m) {
const v = this.jc.decode(m.data);
const r = v;
if (r.error) {
const err = checkJsErrorCode(r.error.code, r.error.description);
if (err !== null) {
err.api_error = r.error;
throw err;
}
}
return v;
}
}
class ListerImpl {
err;
offset;
pageInfo;
subject;
jsm;
filter;
constructor(subject, filter, jsm){
if (!subject) {
throw new Error("subject is required");
}
this.subject = subject;
this.jsm = jsm;
this.offset = 0;
this.pageInfo = {};
this.filter = filter;
}
async next() {
if (this.err) {
return [];
}
if (this.pageInfo && this.offset >= this.pageInfo.total) {
return [];
}
const offset = {
offset: this.offset
};
try {
const r = await this.jsm._request(this.subject, offset, {
timeout: this.jsm.timeout
});
this.pageInfo = r;
const a = this.filter(r);
this.offset += a.length;
return a;
} catch (err) {
this.err = err;
throw err;
}
}
async *[Symbol.asyncIterator]() {
let page = await this.next();
while(page.length > 0){
for (const item of page){
yield item;
}
page = await this.next();
}
}
}
class ConsumerAPIImpl extends BaseApiClient {
constructor(nc, opts){
super(nc, opts);
}
async add(stream, cfg) {
validateStreamName(stream);
if (cfg.deliver_group && cfg.flow_control) {
throw new Error("jetstream flow control is not supported with queue groups");
}
if (cfg.deliver_group && cfg.idle_heartbeat) {
throw new Error("jetstream idle heartbeat is not supported with queue groups");
}
const cr = {};
cr.config = cfg;
cr.stream_name = stream;
if (cr.config.durable_name) {
validateDurableName(cr.config.durable_name);
}
const subj = cfg.durable_name ? `${this.prefix}.CONSUMER.DURABLE.CREATE.${stream}.${cfg.durable_name}` : `${this.prefix}.CONSUMER.CREATE.${stream}`;
const r = await this._request(subj, cr);
return r;
}
async update(stream, durable, cfg) {
const ci = await this.info(stream, durable);
const changable = cfg;
return this.add(stream, Object.assign(ci.config, changable));
}
async info(stream, name) {
validateStreamName(stream);
validateDurableName(name);
const r = await this._request(`${this.prefix}.CONSUMER.INFO.${stream}.${name}`);
return r;
}
async delete(stream, name) {
validateStreamName(stream);
validateDurableName(name);
const r = await this._request(`${this.prefix}.CONSUMER.DELETE.${stream}.${name}`);
const cr = r;
return cr.success;
}
list(stream) {
validateStreamName(stream);
const filter = (v)=>{
const clr = v;
return clr.consumers;
};
const subj = `${this.prefix}.CONSUMER.LIST.${stream}`;
return new ListerImpl(subj, filter, this);
}
}
"use strict";
const digits = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
const base = 36;
const maxSeq = 3656158440062976;