Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

nats

Package Overview
Dependencies
Maintainers
3
Versions
195
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

nats - npm Package Compare versions

Comparing version 2.8.0 to 2.8.1-0

lib/nats-base-client/base64.d.ts

1

lib/nats-base-client/error.d.ts

@@ -35,2 +35,3 @@ import { ApiError } from "./types";

JetStreamNotEnabled = "503",
JetStreamIdleHeartBeat = "IDLE_HEARTBEAT",
AuthorizationViolation = "AUTHORIZATION_VIOLATION",

@@ -37,0 +38,0 @@ AuthenticationExpired = "AUTHENTICATION_EXPIRED",

@@ -55,2 +55,3 @@ "use strict";

ErrorCode["JetStreamNotEnabled"] = "503";
ErrorCode["JetStreamIdleHeartBeat"] = "IDLE_HEARTBEAT";
// emitted by the server

@@ -57,0 +58,0 @@ ErrorCode["AuthorizationViolation"] = "AUTHORIZATION_VIOLATION";

10

lib/nats-base-client/headers.d.ts

@@ -15,3 +15,3 @@ export interface MsgHdrs extends Iterable<[string, string[]]> {

export declare function canonicalMIMEHeaderKey(k: string): string;
export declare function headers(): MsgHdrs;
export declare function headers(code?: number, description?: string): MsgHdrs;
export declare enum Match {

@@ -23,6 +23,6 @@ Exact = 0,

export declare class MsgHdrsImpl implements MsgHdrs {
code: number;
_code: number;
headers: Map<string, string[]>;
description: string;
constructor();
_description: string;
constructor(code?: number, description?: string);
[Symbol.iterator](): IterableIterator<[string, string[]]>;

@@ -46,3 +46,5 @@ size(): number;

toRecord(): Record<string, string[]>;
get code(): number;
get description(): string;
static fromRecord(r: Record<string, string[]>): MsgHdrs;
}
"use strict";
/*
* Copyright 2020-2021 The NATS Authors
* Copyright 2020-2022 The NATS Authors
* Licensed under the Apache License, Version 2.0 (the "License");

@@ -62,4 +62,7 @@ * you may not use this file except in compliance with the License.

exports.canonicalMIMEHeaderKey = canonicalMIMEHeaderKey;
function headers() {
return new MsgHdrsImpl();
function headers(code = 0, description = "") {
if ((code === 0 && description !== "") || (code > 0 && description === "")) {
throw new Error("setting status requires both code and description");
}
return new MsgHdrsImpl(code, description);
}

@@ -78,6 +81,6 @@ exports.headers = headers;

class MsgHdrsImpl {
constructor() {
this.code = 0;
constructor(code = 0, description = "") {
this._code = code;
this._description = description;
this.headers = new Map();
this.description = "";
}

@@ -92,3 +95,3 @@ [Symbol.iterator]() {

if (mh && this.headers.size === mh.headers.size &&
this.code === mh.code) {
this._code === mh._code) {
for (const [k, v] of this.headers) {

@@ -118,6 +121,6 @@ const a = mh.values(k);

let str = h.replace(HEADER, "");
mh.code = parseInt(str, 10);
const scode = mh.code.toString();
mh._code = parseInt(str, 10);
const scode = mh._code.toString();
str = str.replace(scode, "");
mh.description = str.trim();
mh._description = str.trim();
}

@@ -139,6 +142,9 @@ if (lines.length >= 1) {

toString() {
if (this.headers.size === 0) {
if (this.headers.size === 0 && this._code === 0) {
return "";
}
let s = HEADER;
if (this._code > 0 && this._description !== "") {
s += ` ${this._code} ${this._description}`;
}
for (const [k, v] of this.headers) {

@@ -241,6 +247,6 @@ for (let i = 0; i < v.length; i++) {

get hasError() {
return this.code >= 300;
return this._code >= 300;
}
get status() {
return `${this.code} ${this.description}`.trim();
return `${this._code} ${this._description}`.trim();
}

@@ -254,2 +260,8 @@ toRecord() {

}
get code() {
return this._code;
}
get description() {
return this._description;
}
static fromRecord(r) {

@@ -256,0 +268,0 @@ const h = new MsgHdrsImpl();

export { NatsConnectionImpl } from "./nats";
export { Nuid, nuid } from "./nuid";
export { ErrorCode, isNatsError, NatsError } from "./error";
export type { AccountLimits, ClusterInfo, ConnectionOptions, Consumer, ConsumerConfig, ConsumerInfo, ConsumerOpts, ConsumerOptsBuilder, DeliveryInfo, JetStreamAccountStats, JetStreamApiStats, JetStreamClient, JetStreamManager, JetStreamOptions, JetStreamPublishOptions, JetStreamPullSubscription, JetStreamSubscription, JetStreamSubscriptionOptions, JsMsg, JsMsgCallback, KV, KvCodec, KvCodecs, KvEntry, KvOptions, KvPutOptions, KvRemove, KvStatus, LastForMsgRequest, Lister, LostStreamData, Msg, MsgDeleteRequest, MsgRequest, Nanos, NatsConnection, PeerInfo, Placement, PubAck, PublishOptions, PullOptions, PurgeOpts, PurgeResponse, RequestOptions, SeqMsgRequest, SequenceInfo, Server, ServerInfo, ServersChanged, Stats, Status, StoredMsg, StreamConfig, StreamInfo, StreamNames, StreamSource, StreamSourceInfo, StreamState, Sub, SubOpts, Subscription, SubscriptionOptions, } from "./types";
export { AckPolicy, AdvisoryKind, DeliverPolicy, DiscardPolicy, ReplayPolicy, RetentionPolicy, StorageType, } from "./types";
export type { AccountLimits, Advisory, ApiError, ApiPagedRequest, callbackFn, Closed, ClusterInfo, ConnectionOptions, Consumer, ConsumerAPI, ConsumerConfig, ConsumerInfo, ConsumerInfoable, ConsumerOpts, ConsumerOptsBuilder, ConsumerUpdateConfig, DeliveryInfo, Destroyable, JetStreamAccountStats, JetStreamApiStats, JetStreamClient, JetStreamManager, JetStreamOptions, JetStreamPublishOptions, JetStreamPullSubscription, JetStreamSubscription, JetStreamSubscriptionOptions, JetStreamUsageAccountLimits, JsMsg, JsMsgCallback, KV, KvCodec, KvCodecs, KvEntry, KvLimits, KvOptions, KvPutOptions, KvRemove, KvStatus, KvWatchOptions, LastForMsgRequest, Lister, LostStreamData, Msg, MsgDeleteRequest, MsgRequest, Nanos, NatsConnection, ObjectInfo, ObjectResult, ObjectStore, ObjectStoreLink, ObjectStoreMeta, ObjectStoreMetaOptions, ObjectStoreOptions, ObjectStoreStatus, PeerInfo, Placement, PubAck, PublishOptions, Pullable, PullOptions, PurgeBySeq, PurgeBySubject, PurgeOpts, PurgeResponse, PurgeTrimOpts, Republish, RequestOptions, RoKV, SeqMsgRequest, SequenceInfo, Server, ServerInfo, ServersChanged, Stats, Status, StoredMsg, StreamAlternate, StreamAPI, StreamConfig, StreamInfo, StreamInfoRequestOptions, StreamNames, StreamSource, StreamSourceInfo, StreamState, StreamUpdateConfig, Sub, SubOpts, Subscription, SubscriptionOptions, TlsOptions, TypedSubscriptionOptions, Views, } from "./types";
export { AckPolicy, AdvisoryKind, DeliverPolicy, DirectMsgHeaders, DiscardPolicy, ReplayPolicy, RepublishHeaders, RetentionPolicy, StorageType, } from "./types";
export { consumerOpts } from "./jsconsumeropts";

@@ -16,3 +16,3 @@ export { toJsMsg } from "./jsmsg";

export { Connect, createInbox, INFO, ProtocolHandler } from "./protocol";
export type { Deferred, Timeout } from "./util";
export type { Deferred, Perf, Timeout } from "./util";
export { collect, deferred, delay, extend, extractProtocolMessage, render, timeout, } from "./util";

@@ -35,3 +35,3 @@ export type { MsgHdrs } from "./headers";

export { QueuedIteratorImpl } from "./queued_iterator";
export type { QueuedIterator } from "./queued_iterator";
export type { IngestionFilterFn, IngestionFilterFnResult, ProtocolFilterFn, QueuedIterator, } from "./queued_iterator";
export type { ParserEvent } from "./parser";

@@ -45,3 +45,3 @@ export { Kind, Parser, State } from "./parser";

export { TypedSubscription } from "./typedsub";
export type { TypedSubscriptionOptions } from "./typedsub";
export type { MsgAdapter, TypedCallback } from "./typedsub";
export { checkJsError, isFlowControlMsg, isHeartbeatMsg, millis, nanos, } from "./jsutil";

@@ -48,0 +48,0 @@ export { Base64KeyCodec, Bucket, defaultBucketOpts, NoopKvCodecs, } from "./kv";

@@ -17,4 +17,4 @@ "use strict";

Object.defineProperty(exports, "__esModule", { value: true });
exports.JSONCodec = exports.usernamePasswordAuthenticator = exports.tokenAuthenticator = exports.nkeyAuthenticator = exports.jwtAuthenticator = exports.credsAuthenticator = exports.RequestOne = exports.checkUnsupportedOption = exports.checkOptions = exports.DataBuffer = exports.MuxSubscription = exports.Heartbeat = exports.MsgHdrsImpl = exports.Match = exports.headers = exports.canonicalMIMEHeaderKey = exports.timeout = exports.render = exports.extractProtocolMessage = exports.extend = exports.delay = exports.deferred = exports.collect = exports.ProtocolHandler = exports.INFO = exports.createInbox = exports.Connect = exports.setTransportFactory = exports.Subscriptions = exports.SubscriptionImpl = exports.MsgImpl = exports.JsHeaders = exports.Events = exports.Empty = exports.DebugEvents = exports.toJsMsg = exports.consumerOpts = exports.StorageType = exports.RetentionPolicy = exports.ReplayPolicy = exports.DiscardPolicy = exports.DeliverPolicy = exports.AdvisoryKind = exports.AckPolicy = exports.NatsError = exports.isNatsError = exports.ErrorCode = exports.nuid = exports.Nuid = exports.NatsConnectionImpl = void 0;
exports.parseSemVer = exports.compare = exports.NoopKvCodecs = exports.defaultBucketOpts = exports.Bucket = exports.Base64KeyCodec = exports.nanos = exports.millis = exports.isHeartbeatMsg = exports.isFlowControlMsg = exports.checkJsError = exports.TypedSubscription = exports.parseIP = exports.isIP = exports.TE = exports.TD = exports.Metric = exports.Bench = exports.writeAll = exports.readAll = exports.MAX_SIZE = exports.DenoBuffer = exports.State = exports.Parser = exports.Kind = exports.QueuedIteratorImpl = exports.StringCodec = void 0;
exports.tokenAuthenticator = exports.nkeyAuthenticator = exports.jwtAuthenticator = exports.credsAuthenticator = exports.RequestOne = exports.checkUnsupportedOption = exports.checkOptions = exports.DataBuffer = exports.MuxSubscription = exports.Heartbeat = exports.MsgHdrsImpl = exports.Match = exports.headers = exports.canonicalMIMEHeaderKey = exports.timeout = exports.render = exports.extractProtocolMessage = exports.extend = exports.delay = exports.deferred = exports.collect = exports.ProtocolHandler = exports.INFO = exports.createInbox = exports.Connect = exports.setTransportFactory = exports.Subscriptions = exports.SubscriptionImpl = exports.MsgImpl = exports.JsHeaders = exports.Events = exports.Empty = exports.DebugEvents = exports.toJsMsg = exports.consumerOpts = exports.StorageType = exports.RetentionPolicy = exports.RepublishHeaders = exports.ReplayPolicy = exports.DiscardPolicy = exports.DirectMsgHeaders = exports.DeliverPolicy = exports.AdvisoryKind = exports.AckPolicy = exports.NatsError = exports.isNatsError = exports.ErrorCode = exports.nuid = exports.Nuid = exports.NatsConnectionImpl = void 0;
exports.parseSemVer = exports.compare = exports.NoopKvCodecs = exports.defaultBucketOpts = exports.Bucket = exports.Base64KeyCodec = exports.nanos = exports.millis = exports.isHeartbeatMsg = exports.isFlowControlMsg = exports.checkJsError = exports.TypedSubscription = exports.parseIP = exports.isIP = exports.TE = exports.TD = exports.Metric = exports.Bench = exports.writeAll = exports.readAll = exports.MAX_SIZE = exports.DenoBuffer = exports.State = exports.Parser = exports.Kind = exports.QueuedIteratorImpl = exports.StringCodec = exports.JSONCodec = exports.usernamePasswordAuthenticator = void 0;
var nats_1 = require("./nats");

@@ -33,4 +33,6 @@ Object.defineProperty(exports, "NatsConnectionImpl", { enumerable: true, get: function () { return nats_1.NatsConnectionImpl; } });

Object.defineProperty(exports, "DeliverPolicy", { enumerable: true, get: function () { return types_1.DeliverPolicy; } });
Object.defineProperty(exports, "DirectMsgHeaders", { enumerable: true, get: function () { return types_1.DirectMsgHeaders; } });
Object.defineProperty(exports, "DiscardPolicy", { enumerable: true, get: function () { return types_1.DiscardPolicy; } });
Object.defineProperty(exports, "ReplayPolicy", { enumerable: true, get: function () { return types_1.ReplayPolicy; } });
Object.defineProperty(exports, "RepublishHeaders", { enumerable: true, get: function () { return types_1.RepublishHeaders; } });
Object.defineProperty(exports, "RetentionPolicy", { enumerable: true, get: function () { return types_1.RetentionPolicy; } });

@@ -37,0 +39,0 @@ Object.defineProperty(exports, "StorageType", { enumerable: true, get: function () { return types_1.StorageType; } });

import type { ConsumerOptsBuilder, Views } from "./types";
import { ConsumerAPI, ConsumerInfo, ConsumerOpts, JetStreamClient, JetStreamOptions, JetStreamPublishOptions, JetStreamPullSubscription, JetStreamSubscription, JsMsg, NatsConnection, PubAck, PullOptions } from "./types";
import { ConsumerAPI, ConsumerInfo, ConsumerInfoable, ConsumerOpts, Destroyable, JetStreamClient, JetStreamOptions, JetStreamPublishOptions, JetStreamPullSubscription, JetStreamSubscription, JetStreamSubscriptionOptions, JsMsg, Msg, NatsConnection, PubAck, PullOptions } from "./types";
import { BaseApiClient } from "./jsbaseclient_api";
import { TypedSubscriptionOptions } from "./typedsub";
import { TypedSubscription, TypedSubscriptionOptions } from "./typedsub";
import { IngestionFilterFn, QueuedIterator } from "./queued_iterator";
import { IdleHeartbeat } from "./idleheartbeat";
export interface JetStreamSubscriptionInfoable {

@@ -23,2 +24,16 @@ info: JetStreamSubscriptionInfo | null;

}
export declare class JetStreamSubscriptionImpl extends TypedSubscription<JsMsg> implements JetStreamSubscriptionInfoable, Destroyable, ConsumerInfoable {
js: BaseApiClient;
monitor: IdleHeartbeat | null;
constructor(js: BaseApiClient, subject: string, opts: JetStreamSubscriptionOptions);
set info(info: JetStreamSubscriptionInfo | null);
get info(): JetStreamSubscriptionInfo | null;
_resetOrderedConsumer(sseq: number): void;
_maybeSetupHbMonitoring(): void;
_setupHbMonitoring(millis: number, cancelAfter?: number): void;
_checkHbOrderConsumer(msg: Msg): boolean;
_checkOrderedConsumer(jm: JsMsg): boolean;
destroy(): Promise<void>;
consumerInfo(): Promise<ConsumerInfo>;
}
interface JetStreamSubscriptionInfo extends ConsumerOpts {

@@ -25,0 +40,0 @@ api: BaseApiClient;

@@ -26,3 +26,3 @@ "use strict";

Object.defineProperty(exports, "__esModule", { value: true });
exports.JetStreamClientImpl = void 0;
exports.JetStreamSubscriptionImpl = exports.JetStreamClientImpl = void 0;
const types_1 = require("./types");

@@ -43,2 +43,3 @@ const jsbaseclient_api_1 = require("./jsbaseclient_api");

const objectstore_1 = require("./objectstore");
const idleheartbeat_1 = require("./idleheartbeat");
var PubHeaders;

@@ -172,6 +173,7 @@ (function (PubHeaders) {

const max_bytes = trackBytes ? opts.max_bytes : 0;
let monitor = null;
const args = {};
args.batch = opts.batch || 1;
if (max_bytes) {
const fv = this.nc.protocol.features.get(semver_1.Feature.JS_PULL_MAX_BYTES);
const fv = this.nc.features.get(semver_1.Feature.JS_PULL_MAX_BYTES);
if (!fv.ok) {

@@ -193,5 +195,22 @@ throw new Error(`max_bytes is only supported on servers ${fv.min} or better`);

}
const hb = opts.idle_heartbeat || 0;
if (hb) {
args.idle_heartbeat = (0, jsutil_1.nanos)(hb);
//@ts-ignore: for testing
if (opts.delay_heartbeat === true) {
//@ts-ignore: test option
args.idle_heartbeat = (0, jsutil_1.nanos)(hb * 4);
}
}
const qi = new queued_iterator_1.QueuedIteratorImpl();
const wants = args.batch;
let received = 0;
qi.protocolFilterFn = (jm, _ingest = false) => {
const jsmi = jm;
if ((0, jsutil_1.isHeartbeatMsg)(jsmi.msg)) {
monitor === null || monitor === void 0 ? void 0 : monitor.work();
return false;
}
return true;
};
// FIXME: this looks weird, we want to stop the iterator

@@ -237,2 +256,4 @@ // but doing it from a dispatchedFn...

else {
// if we are doing heartbeats, message resets
monitor === null || monitor === void 0 ? void 0 : monitor.work();
qi.received++;

@@ -253,5 +274,23 @@ qi.push((0, jsmsg_1.toJsMsg)(msg));

}
if (monitor) {
monitor.cancel();
}
});
}
(() => __awaiter(this, void 0, void 0, function* () {
try {
if (hb) {
monitor = new idleheartbeat_1.IdleHeartbeat(hb, (v) => {
//@ts-ignore: pushing a fn
qi.push(() => {
// this will terminate the iterator
qi.err = new error_1.NatsError(`${jsutil_1.Js409Errors.IdleHeartbeatMissed}: ${v}`, error_1.ErrorCode.JetStreamIdleHeartBeat);
});
return true;
});
}
}
catch (_err) {
// ignore it
}
// close the iterator if the connection or subscription closes unexpectedly

@@ -263,2 +302,5 @@ yield sub.closed;

}
if (monitor) {
monitor.cancel();
}
qi.stop();

@@ -316,2 +358,3 @@ }))().catch();

}
sub._maybeSetupHbMonitoring();
return sub;

@@ -356,2 +399,4 @@ });

jsi.config.ack_wait = (0, jsutil_1.nanos)(22 * 60 * 60 * 1000);
jsi.config.mem_storage = true;
jsi.config.num_replicas = 1;
}

@@ -457,2 +502,3 @@ if (jsi.config.ack_policy === types_1.AckPolicy.NotSet) {

return (jm, ctx) => {
var _a;
// ctx is expected to be the iterator (the JetstreamSubscriptionImpl)

@@ -464,2 +510,5 @@ const jsub = ctx;

const jmi = jm;
if (!(0, jsutil_1.checkJsError)(jmi.msg)) {
(_a = jsub.monitor) === null || _a === void 0 ? void 0 : _a.work();
}
if ((0, jsutil_1.isHeartbeatMsg)(jmi.msg)) {

@@ -486,2 +535,8 @@ const ingest = ordered ? jsub._checkHbOrderConsumer(jmi.msg) : true;

this.js = js;
this.monitor = null;
this.sub.closed.then(() => {
if (this.monitor) {
this.monitor.cancel();
}
});
}

@@ -510,4 +565,13 @@ set info(info) {

info.config.opt_start_seq = sseq;
// put the stream name
const req = {};
req.stream_name = this.info.stream;
req.config = info.config;
const subj = `${info.api.prefix}.CONSUMER.CREATE.${info.stream}`;
this.js._request(subj, this.info.config)
this.js._request(subj, req)
.then((v) => {
const ci = v;
this.info.config = ci.config;
this.info.name = ci.name;
})
.catch((err) => {

@@ -520,2 +584,45 @@ // to inform the subscription we inject an error this will

}
// this is called by push subscriptions, to initialize the monitoring
// if configured on the consumer
_maybeSetupHbMonitoring() {
var _a, _b;
const ns = ((_b = (_a = this.info) === null || _a === void 0 ? void 0 : _a.config) === null || _b === void 0 ? void 0 : _b.idle_heartbeat) || 0;
if (ns) {
this._setupHbMonitoring((0, jsutil_1.millis)(ns));
}
}
_setupHbMonitoring(millis, cancelAfter = 0) {
const opts = { cancelAfter: 0, maxOut: 2 };
if (cancelAfter) {
opts.cancelAfter = cancelAfter;
}
const sub = this.sub;
const handler = (v) => {
var _a, _b, _c;
const msg = (0, jsutil_1.newJsErrorMsg)(409, `${jsutil_1.Js409Errors.IdleHeartbeatMissed}: ${v}`, this.sub.subject);
const ordered = (_a = this.info) === null || _a === void 0 ? void 0 : _a.ordered;
// non-ordered consumers are always notified of the condition
// as they need to try and recover
if (!ordered) {
this.sub.callback(null, msg);
}
else {
if (!this.js.nc.protocol.connected) {
// we are not connected don't do anything
return false;
}
// reset the consumer
const seq = ((_c = (_b = this.info) === null || _b === void 0 ? void 0 : _b.ordered_consumer_sequence) === null || _c === void 0 ? void 0 : _c.stream_seq) || 0;
this._resetOrderedConsumer(seq + 1);
// if we are ordered, we will reset the consumer and keep
// feeding the iterator or callback - we are not stopping
return false;
}
// let the hb monitor know if we are stopping for callbacks
// we don't as we deliver the errors via the cb.
return !sub.noIterator;
};
// this only applies for push subscriptions
this.monitor = new idleheartbeat_1.IdleHeartbeat(millis, handler, opts);
}
_checkHbOrderConsumer(msg) {

@@ -569,2 +676,3 @@ const rm = msg.headers.get(types_1.JsHeaders.ConsumerStalledHdr);

}
exports.JetStreamSubscriptionImpl = JetStreamSubscriptionImpl;
class JetStreamPullSubscriptionImpl extends JetStreamSubscriptionImpl {

@@ -582,3 +690,3 @@ constructor(js, subject, opts) {

if (((_b = opts.max_bytes) !== null && _b !== void 0 ? _b : 0) > 0) {
const fv = this.js.nc.protocol.features.get(semver_1.Feature.JS_PULL_MAX_BYTES);
const fv = this.js.nc.features.get(semver_1.Feature.JS_PULL_MAX_BYTES);
if (!fv.ok) {

@@ -589,6 +697,30 @@ throw new Error(`max_bytes is only supported on servers ${fv.min} or better`);

}
let expires = 0;
if (opts.expires && opts.expires > 0) {
args.expires = (0, jsutil_1.nanos)(opts.expires);
expires = opts.expires;
args.expires = (0, jsutil_1.nanos)(expires);
}
let hb = 0;
if (opts.idle_heartbeat && opts.idle_heartbeat > 0) {
hb = opts.idle_heartbeat;
args.idle_heartbeat = (0, jsutil_1.nanos)(hb);
}
if (hb && expires === 0) {
throw new Error("idle_heartbeat requires expires");
}
if (hb > expires) {
throw new Error("expires must be greater than idle_heartbeat");
}
if (this.info) {
if (this.monitor) {
this.monitor.cancel();
}
if (expires && hb) {
if (!this.monitor) {
this._setupHbMonitoring(hb, expires);
}
else {
this.monitor._change(hb, expires);
}
}
const api = this.info.api;

@@ -595,0 +727,0 @@ const subj = `${api.prefix}.CONSUMER.MSG.NEXT.${stream}.${consumer}`;

@@ -11,5 +11,6 @@ import { ApiPaged, Lister } from "./types";

filter: ListerFieldFilter<T>;
constructor(subject: string, filter: ListerFieldFilter<T>, jsm: BaseApiClient);
payload: unknown;
constructor(subject: string, filter: ListerFieldFilter<T>, jsm: BaseApiClient, payload?: unknown);
next(): Promise<T[]>;
[Symbol.asyncIterator](): AsyncGenerator<Awaited<T>, void, unknown>;
}

@@ -26,3 +26,3 @@ "use strict";

class ListerImpl {
constructor(subject, filter, jsm) {
constructor(subject, filter, jsm, payload) {
if (!subject) {

@@ -36,2 +36,3 @@ throw new Error("subject is required");

this.filter = filter;
this.payload = payload || {};
}

@@ -47,2 +48,5 @@ next() {

const offset = { offset: this.offset };
if (this.payload) {
Object.assign(offset, this.payload);
}
try {

@@ -49,0 +53,0 @@ const r = yield this.jsm._request(this.subject, offset, { timeout: this.jsm.timeout });

@@ -16,2 +16,3 @@ "use strict";

const jsutil_1 = require("./jsutil");
const semver_1 = require("./semver");
class ConsumerAPIImpl extends jsbaseclient_api_1.BaseApiClient {

@@ -22,2 +23,3 @@ constructor(nc, opts) {

add(stream, cfg) {
var _a, _b, _c;
return __awaiter(this, void 0, void 0, function* () {

@@ -37,5 +39,33 @@ (0, jsutil_1.validateStreamName)(stream);

}
const subj = cfg.durable_name
? `${this.prefix}.CONSUMER.DURABLE.CREATE.${stream}.${cfg.durable_name}`
: `${this.prefix}.CONSUMER.CREATE.${stream}`;
const nci = this.nc;
const { min, ok: newAPI } = nci.features.get(semver_1.Feature.JS_NEW_CONSUMER_CREATE_API);
const name = cfg.name === "" ? undefined : cfg.name;
if (name && !newAPI) {
throw new Error(`consumer 'name' requires server ${min}`);
}
if (name) {
const m = (0, jsutil_1.validName)(name);
if (m.length) {
throw new Error(`consumer 'name' ${m}`);
}
}
let subj;
let consumerName = "";
if (newAPI) {
consumerName = (_b = (_a = cfg.name) !== null && _a !== void 0 ? _a : cfg.durable_name) !== null && _b !== void 0 ? _b : "";
}
if (consumerName !== "") {
let fs = (_c = cfg.filter_subject) !== null && _c !== void 0 ? _c : undefined;
if (fs === ">") {
fs = undefined;
}
subj = fs !== undefined
? `${this.prefix}.CONSUMER.CREATE.${stream}.${consumerName}.${fs}`
: `${this.prefix}.CONSUMER.CREATE.${stream}.${consumerName}`;
}
else {
subj = cfg.durable_name
? `${this.prefix}.CONSUMER.DURABLE.CREATE.${stream}.${cfg.durable_name}`
: `${this.prefix}.CONSUMER.CREATE.${stream}`;
}
const r = yield this._request(subj, cr);

@@ -42,0 +72,0 @@ return r;

@@ -1,2 +0,2 @@

import { JetStreamOptions, Lister, MsgRequest, NatsConnection, PurgeOpts, PurgeResponse, StoredMsg, StreamAPI, StreamConfig, StreamInfo, StreamInfoRequestOptions, StreamMsgResponse, StreamUpdateConfig } from "./types";
import { JetStreamOptions, KvStatus, Lister, MsgRequest, NatsConnection, ObjectStoreStatus, PurgeOpts, PurgeResponse, StoredMsg, StreamAPI, StreamConfig, StreamInfo, StreamInfoRequestOptions, StreamMsgResponse, StreamUpdateConfig } from "./types";
import { BaseApiClient } from "./jsbaseclient_api";

@@ -10,3 +10,3 @@ import { MsgHdrs } from "./headers";

info(name: string, data?: Partial<StreamInfoRequestOptions>): Promise<StreamInfo>;
list(): Lister<StreamInfo>;
list(subject?: string): Lister<StreamInfo>;
_fixInfo(si: StreamInfo): void;

@@ -17,2 +17,5 @@ purge(name: string, opts?: PurgeOpts): Promise<PurgeResponse>;

find(subject: string): Promise<string>;
listKvs(): Lister<KvStatus>;
listObjectStores(): Lister<ObjectStoreStatus>;
names(subject?: string): Lister<string>;
}

@@ -19,0 +22,0 @@ export declare class StoredMsgImpl implements StoredMsg {

@@ -32,2 +32,4 @@ "use strict";

const headers_1 = require("./headers");
const kv_1 = require("./kv");
const objectstore_1 = require("./objectstore");
class StreamAPIImpl extends jsbaseclient_api_1.BaseApiClient {

@@ -74,4 +76,47 @@ constructor(nc, opts) {

(0, jsutil_1.validateStreamName)(name);
const r = yield this._request(`${this.prefix}.STREAM.INFO.${name}`, data);
const si = r;
const subj = `${this.prefix}.STREAM.INFO.${name}`;
const r = yield this._request(subj, data);
let si = r;
let { total, limit } = si;
// check how many subjects we got in the first request
let have = si.state.subjects
? Object.getOwnPropertyNames(si.state.subjects).length
: 1;
// if the response is paged, we have a large list of subjects
// handle the paging and return a StreamInfo with all of it
if (total && total > have) {
const infos = [si];
const paged = data || {};
let i = 0;
// total could change, so it is possible to have collected
// more that the total
while (total > have) {
i++;
paged.offset = limit * i;
const r = yield this._request(subj, paged);
// update it in case it changed
total = r.total;
infos.push(r);
const count = Object.getOwnPropertyNames(r.state.subjects).length;
have += count;
// if request returns less than limit it is done
if (count < limit) {
// done
break;
}
}
// collect all the subjects
let subjects = {};
for (let i = 0; i < infos.length; i++) {
si = infos[i];
if (si.state.subjects) {
subjects = Object.assign(subjects, si.state.subjects);
}
}
// don't give the impression we paged
si.offset = 0;
si.total = 0;
si.limit = 0;
si.state.subjects = subjects;
}
this._fixInfo(si);

@@ -81,4 +126,5 @@ return si;

}
list() {
const filter = (v) => {
list(subject = "") {
const payload = (subject === null || subject === void 0 ? void 0 : subject.length) ? { subject } : {};
const listerFilter = (v) => {
const slr = v;

@@ -91,3 +137,3 @@ slr.streams.forEach((si) => {

const subj = `${this.prefix}.STREAM.LIST`;
return new jslister_1.ListerImpl(subj, filter, this);
return new jslister_1.ListerImpl(subj, listerFilter, this, payload);
}

@@ -138,2 +184,50 @@ // FIXME: init of sealed, deny_delete, deny_purge shouldn't be necessary

}
listKvs() {
const filter = (v) => {
var _a, _b;
const slr = v;
const kvStreams = slr.streams.filter((v) => {
return v.config.name.startsWith(kv_1.kvPrefix);
});
kvStreams.forEach((si) => {
this._fixInfo(si);
});
let cluster = "";
if (kvStreams.length) {
cluster = (_b = (_a = this.nc.info) === null || _a === void 0 ? void 0 : _a.cluster) !== null && _b !== void 0 ? _b : "";
}
const status = kvStreams.map((si) => {
return new kv_1.KvStatusImpl(si, cluster);
});
return status;
};
const subj = `${this.prefix}.STREAM.LIST`;
return new jslister_1.ListerImpl(subj, filter, this);
}
listObjectStores() {
const filter = (v) => {
const slr = v;
const objStreams = slr.streams.filter((v) => {
return v.config.name.startsWith(objectstore_1.osPrefix);
});
objStreams.forEach((si) => {
this._fixInfo(si);
});
const status = objStreams.map((si) => {
return new objectstore_1.ObjectStoreStatusImpl(si);
});
return status;
};
const subj = `${this.prefix}.STREAM.LIST`;
return new jslister_1.ListerImpl(subj, filter, this);
}
names(subject = "") {
const payload = (subject === null || subject === void 0 ? void 0 : subject.length) ? { subject } : {};
const listerFilter = (v) => {
const slr = v;
return slr.streams;
};
const subj = `${this.prefix}.STREAM.NAMES`;
return new jslister_1.ListerImpl(subj, listerFilter, this, payload);
}
}

@@ -140,0 +234,0 @@ exports.StreamAPIImpl = StreamAPIImpl;

@@ -6,2 +6,3 @@ import { ConsumerConfig, Msg, Nanos } from "./types";

export declare function validateName(context: string, name?: string): void;
export declare function validName(name?: string): string;
export declare function defaultConsumer(name: string, opts?: Partial<ConsumerConfig>): ConsumerConfig;

@@ -28,2 +29,3 @@ /**

export declare function isHeartbeatMsg(msg: Msg): boolean;
export declare function newJsErrorMsg(code: number, description: string, subject: string): Msg;
export declare function checkJsError(msg: Msg): NatsError | null;

@@ -36,3 +38,4 @@ export declare enum Js409Errors {

PushConsumer = "consumer is push based",
MaxWaitingExceeded = "exceeded maxwaiting"
MaxWaitingExceeded = "exceeded maxwaiting",
IdleHeartbeatMissed = "`idle heartbeats missed`"
}

@@ -39,0 +42,0 @@ export declare function setMaxWaitingToFail(tf: boolean): void;

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.checkJsErrorCode = exports.isTerminal409 = exports.setMaxWaitingToFail = exports.Js409Errors = exports.checkJsError = exports.isHeartbeatMsg = exports.isFlowControlMsg = exports.millis = exports.nanos = exports.defaultConsumer = exports.validateName = exports.validateStreamName = exports.validateDurableName = void 0;
exports.checkJsErrorCode = exports.isTerminal409 = exports.setMaxWaitingToFail = exports.Js409Errors = exports.checkJsError = exports.newJsErrorMsg = exports.isHeartbeatMsg = exports.isFlowControlMsg = exports.millis = exports.nanos = exports.defaultConsumer = exports.validName = exports.validateName = exports.validateStreamName = exports.validateDurableName = void 0;
/*
* Copyright 2021 The NATS Authors
* Copyright 2021-2022 The NATS Authors
* Licensed under the Apache License, Version 2.0 (the "License");

@@ -20,2 +20,4 @@ * you may not use this file except in compliance with the License.

const error_1 = require("./error");
const headers_1 = require("./headers");
const msg_1 = require("./msg");
function validateDurableName(name) {

@@ -33,10 +35,22 @@ return validateName("durable", name);

}
const m = validName(name);
if (m.length) {
throw new Error(`invalid ${context} name - ${context} name ${m}`);
}
}
exports.validateName = validateName;
function validName(name = "") {
if (name === "") {
throw Error(`name required`);
}
const bad = [".", "*", ">"];
bad.forEach((v) => {
for (let i = 0; i < bad.length; i++) {
const v = bad[i];
if (name.indexOf(v) !== -1) {
throw Error(`invalid ${context} name - ${context} name cannot contain '${v}'`);
return `cannot contain '${v}'`;
}
});
}
return "";
}
exports.validateName = validateName;
exports.validName = validName;
function defaultConsumer(name, opts = {}) {

@@ -92,2 +106,11 @@ return Object.assign({

exports.isHeartbeatMsg = isHeartbeatMsg;
function newJsErrorMsg(code, description, subject) {
const h = (0, headers_1.headers)(code, description);
const arg = { hdr: 1, sid: 0, size: 0 };
const msg = new msg_1.MsgImpl(arg, types_1.Empty, {});
msg._headers = h;
msg._subject = subject;
return msg;
}
exports.newJsErrorMsg = newJsErrorMsg;
function checkJsError(msg) {

@@ -113,2 +136,3 @@ // JS error only if no payload - otherwise assume it is application data

Js409Errors["MaxWaitingExceeded"] = "exceeded maxwaiting";
Js409Errors["IdleHeartbeatMissed"] = "`idle heartbeats missed`";
})(Js409Errors = exports.Js409Errors || (exports.Js409Errors = {}));

@@ -130,2 +154,3 @@ let MAX_WAITING_FAIL = false;

Js409Errors.PushConsumer,
Js409Errors.IdleHeartbeatMissed,
];

@@ -152,7 +177,11 @@ if (MAX_WAITING_FAIL) {

return new error_1.NatsError(description, error_1.ErrorCode.JetStream408RequestTimeout);
case 409:
case 409: {
// the description can be exceeded max waiting or max ack pending, which are
// recoverable, but can also be terminal errors where the request exceeds
// some value in the consumer configuration
return new error_1.NatsError(description, error_1.ErrorCode.JetStream409);
const ec = description.startsWith(Js409Errors.IdleHeartbeatMissed)
? error_1.ErrorCode.JetStreamIdleHeartBeat
: error_1.ErrorCode.JetStream409;
return new error_1.NatsError(description, ec);
}
case 503:

@@ -159,0 +188,0 @@ return error_1.NatsError.errorForCode(error_1.ErrorCode.JetStreamNotEnabled, new Error(description));

@@ -1,2 +0,2 @@

import { callbackFn, ConsumerConfig, JetStreamClient, JetStreamManager, JsMsg, KV, KvCodec, KvCodecs, KvEntry, KvOptions, KvPutOptions, KvRemove, KvStatus, PurgeOpts, PurgeResponse, StoredMsg } from "./types";
import { callbackFn, ConsumerConfig, JetStreamClient, JetStreamManager, JsMsg, KV, KvCodec, KvCodecs, KvEntry, KvOptions, KvPutOptions, KvRemove, KvStatus, Placement, PurgeOpts, PurgeResponse, Republish, StorageType, StoredMsg, StreamInfo } from "./types";
import { QueuedIterator } from "./queued_iterator";

@@ -8,2 +8,3 @@ import { MsgHdrs } from "./headers";

export declare const kvOperationHdr = "KV-Operation";
export declare const kvPrefix = "KV_";
export declare function validateKey(k: string): void;

@@ -69,1 +70,23 @@ export declare function validateSearchKey(k: string): void;

}
export declare class KvStatusImpl implements KvStatus {
si: StreamInfo;
cluster: string;
constructor(si: StreamInfo, cluster?: string);
get bucket(): string;
get values(): number;
get history(): number;
get ttl(): number;
get bucket_location(): string;
get backingStore(): StorageType;
get storage(): StorageType;
get replicas(): number;
get description(): string;
get maxBucketSize(): number;
get maxValueSize(): number;
get max_bytes(): number;
get placement(): Placement;
get placementCluster(): string;
get republish(): Republish;
get streamInfo(): StreamInfo;
get size(): number;
}

@@ -33,3 +33,3 @@ "use strict";

Object.defineProperty(exports, "__esModule", { value: true });
exports.Bucket = exports.validateBucket = exports.hasWildcards = exports.validateSearchKey = exports.validateKey = exports.kvOperationHdr = exports.defaultBucketOpts = exports.NoopKvCodecs = exports.Base64KeyCodec = void 0;
exports.KvStatusImpl = exports.Bucket = exports.validateBucket = exports.hasWildcards = exports.validateSearchKey = exports.validateKey = exports.kvPrefix = exports.kvOperationHdr = exports.defaultBucketOpts = exports.NoopKvCodecs = exports.Base64KeyCodec = void 0;
const types_1 = require("./types");

@@ -86,3 +86,3 @@ const jsutil_1 = require("./jsutil");

exports.kvOperationHdr = "KV-Operation";
const kvPrefix = "KV_";
exports.kvPrefix = "KV_";
const kvSubjectPrefix = "$KV";

@@ -155,5 +155,9 @@ const validKeyRe = /^[-/=.\w]+$/;

return __awaiter(this, void 0, void 0, function* () {
const jsi = js;
const { ok, min } = jsi.nc.features.get(semver_1.Feature.JS_KV);
if (!ok) {
return Promise.reject(new Error(`kv is only supported on servers ${min} or better`));
}
validateBucket(name);
const to = opts.timeout || 2000;
const jsi = js;
let jsopts = jsi.opts || {};

@@ -172,3 +176,3 @@ jsopts = Object.assign(jsopts, { timeout: to });

const jsm = yield jsi.nc.jetstreamManager();
const info = yield jsm.streams.info(`${kvPrefix}${name}`);
const info = yield jsm.streams.info(`${exports.kvPrefix}${name}`);
validateBucket(info.config.name);

@@ -219,4 +223,17 @@ const bucket = new Bucket(name, jsm, js);

sc.discard = discardNew ? types_1.DiscardPolicy.New : types_1.DiscardPolicy.Old;
const direct = have ? (0, semver_1.compare)(have, (0, semver_1.parseSemVer)("2.8.5")) >= 0 : false;
sc.allow_direct = opts.allow_direct ? direct : false;
const { ok: direct, min } = nci.features.get(semver_1.Feature.JS_ALLOW_DIRECT);
if (!direct && opts.allow_direct === true) {
const v = have
? `${have.major}.${have.minor}.${have.micro}`
: "unknown";
return Promise.reject(new Error(`allow_direct is not available on server version ${v} - requires ${min}`));
}
// if we are given allow_direct we use it, otherwise what
// the server supports - in creation this will always rule,
// but allows the client to opt-in even if it is already
// available on the stream
opts.allow_direct = typeof opts.allow_direct === "boolean"
? opts.allow_direct
: direct;
sc.allow_direct = opts.allow_direct;
this.direct = sc.allow_direct;

@@ -229,3 +246,6 @@ sc.num_replicas = bo.replicas;

try {
yield this.jsm.streams.info(sc.name);
const info = yield this.jsm.streams.info(sc.name);
if (!info.config.allow_direct && this.direct === true) {
this.direct = false;
}
}

@@ -241,3 +261,3 @@ catch (err) {

var _a;
return (_a = this.stream) !== null && _a !== void 0 ? _a : `${kvPrefix}${this.bucket}`;
return (_a = this.stream) !== null && _a !== void 0 ? _a : `${exports.kvPrefix}${this.bucket}`;
}

@@ -335,2 +355,3 @@ subjectForBucket() {

put(k, data, opts = {}) {
var _a, _b;
return __awaiter(this, void 0, void 0, function* () {

@@ -345,4 +366,15 @@ const ek = this.encodeKey(k);

}
const pa = yield this.js.publish(this.subjectForKey(ek), data, o);
return pa.seq;
try {
const pa = yield this.js.publish(this.subjectForKey(ek), data, o);
return pa.seq;
}
catch (err) {
const ne = err;
if (ne.isJetStreamError()) {
ne.message = (_a = ne.api_error) === null || _a === void 0 ? void 0 : _a.description;
ne.code = `${(_b = ne.api_error) === null || _b === void 0 ? void 0 : _b.code}`;
return Promise.reject(ne);
}
return Promise.reject(err);
}
});

@@ -692,13 +724,5 @@ }

const cluster = (_b = (_a = ji.nc.info) === null || _a === void 0 ? void 0 : _a.cluster) !== null && _b !== void 0 ? _b : "";
const si = yield this.jsm.streams.info(this.bucketName());
return {
bucket: this.bucketName(),
values: si.state.messages,
history: si.config.max_msgs_per_subject,
ttl: (0, jsutil_1.millis)(si.config.max_age),
bucket_location: cluster,
backingStore: si.config.storage,
storage: si.config.storage,
replicas: si.config.num_replicas,
};
const bn = this.bucketName();
const si = yield this.jsm.streams.info(bn);
return new KvStatusImpl(si, cluster);
});

@@ -708,2 +732,65 @@ }

exports.Bucket = Bucket;
class KvStatusImpl {
constructor(si, cluster = "") {
this.si = si;
this.cluster = cluster;
}
get bucket() {
return this.si.config.name.startsWith(exports.kvPrefix)
? this.si.config.name.substring(exports.kvPrefix.length)
: this.si.config.name;
}
get values() {
return this.si.state.messages;
}
get history() {
return this.si.config.max_msgs_per_subject;
}
get ttl() {
return (0, jsutil_1.millis)(this.si.config.max_age);
}
get bucket_location() {
return this.cluster;
}
get backingStore() {
return this.si.config.storage;
}
get storage() {
return this.si.config.storage;
}
get replicas() {
return this.si.config.num_replicas;
}
get description() {
var _a;
return (_a = this.si.config.description) !== null && _a !== void 0 ? _a : "";
}
get maxBucketSize() {
return this.si.config.max_bytes;
}
get maxValueSize() {
return this.si.config.max_msg_size;
}
get max_bytes() {
return this.si.config.max_bytes;
}
get placement() {
return this.si.config.placement || { cluster: "", tags: [] };
}
get placementCluster() {
var _a, _b;
return (_b = (_a = this.si.config.placement) === null || _a === void 0 ? void 0 : _a.cluster) !== null && _b !== void 0 ? _b : "";
}
get republish() {
var _a;
return (_a = this.si.config.republish) !== null && _a !== void 0 ? _a : { src: "", dest: "" };
}
get streamInfo() {
return this.si;
}
get size() {
return this.si.state.bytes;
}
}
exports.KvStatusImpl = KvStatusImpl;
//# sourceMappingURL=kv.js.map
export { AckPolicy, AdvisoryKind, Bench, canonicalMIMEHeaderKey, checkJsError, consumerOpts, createInbox, credsAuthenticator, DebugEvents, deferred, DeliverPolicy, DiscardPolicy, Empty, ErrorCode, Events, headers, isFlowControlMsg, isHeartbeatMsg, JsHeaders, JSONCodec, jwtAuthenticator, Match, Metric, millis, MsgHdrsImpl, nanos, NatsError, nkeyAuthenticator, Nuid, nuid, ReplayPolicy, RetentionPolicy, StorageType, StringCodec, toJsMsg, tokenAuthenticator, usernamePasswordAuthenticator, } from "./internal_mod";
export type { AccountLimits, Auth, Authenticator, ClusterInfo, Codec, ConnectionOptions, Consumer, ConsumerConfig, ConsumerInfo, ConsumerOpts, ConsumerOptsBuilder, Deferred, DeliveryInfo, JetStreamAccountStats, JetStreamApiStats, JetStreamClient, JetStreamManager, JetStreamOptions, JetStreamPublishOptions, JetStreamPullSubscription, JetStreamSubscription, JetStreamSubscriptionOptions, JsMsg, JsMsgCallback, JwtAuth, LastForMsgRequest, Lister, LostStreamData, Msg, MsgDeleteRequest, MsgHdrs, MsgRequest, Nanos, NatsConnection, NKeyAuth, NoAuth, PeerInfo, Placement, PubAck, PublishOptions, PullOptions, RequestOptions, SeqMsgRequest, SequenceInfo, ServerInfo, ServersChanged, Stats, Status, StoredMsg, StreamConfig, StreamInfo, StreamNames, StreamSource, StreamSourceInfo, StreamState, Sub, SubOpts, Subscription, SubscriptionOptions, TokenAuth, UserPass, } from "./internal_mod";
export type { AccountLimits, Advisory, ApiError, ApiPagedRequest, Auth, Authenticator, BenchOpts, callbackFn, Closed, ClusterInfo, Codec, ConnectionOptions, Consumer, ConsumerAPI, ConsumerConfig, ConsumerInfo, ConsumerInfoable, ConsumerOpts, ConsumerOptsBuilder, ConsumerUpdateConfig, Deferred, DeliveryInfo, Destroyable, DirectMsgHeaders, DispatchedFn, IngestionFilterFn, IngestionFilterFnResult, JetStreamAccountStats, JetStreamApiStats, JetStreamClient, JetStreamManager, JetStreamOptions, JetStreamPublishOptions, JetStreamPullSubscription, JetStreamSubscription, JetStreamSubscriptionOptions, JetStreamUsageAccountLimits, JsMsg, JsMsgCallback, JwtAuth, KV, KvCodec, KvCodecs, KvEntry, KvLimits, KvOptions, KvPutOptions, KvStatus, KvWatchOptions, LastForMsgRequest, Lister, LostStreamData, Msg, MsgAdapter, MsgDeleteRequest, MsgHdrs, MsgRequest, Nanos, NatsConnection, NKeyAuth, NoAuth, ObjectInfo, ObjectResult, ObjectStore, ObjectStoreLink, ObjectStoreMeta, ObjectStoreMetaOptions, ObjectStoreOptions, ObjectStoreStatus, PeerInfo, Perf, Placement, ProtocolFilterFn, PubAck, PublishOptions, Pullable, PullOptions, PurgeBySeq, PurgeBySubject, PurgeOpts, PurgeResponse, PurgeTrimOpts, QueuedIterator, Republish, RepublishHeaders, RequestOptions, RoKV, SeqMsgRequest, SequenceInfo, ServerInfo, ServersChanged, Stats, Status, StoredMsg, StreamAlternate, StreamAPI, StreamConfig, StreamInfo, StreamInfoRequestOptions, StreamNames, StreamSource, StreamSourceInfo, StreamState, StreamUpdateConfig, Sub, SubOpts, Subscription, SubscriptionOptions, TlsOptions, TokenAuth, TypedCallback, TypedSubscriptionOptions, UserPass, Views, } from "./internal_mod";

@@ -24,2 +24,3 @@ import { Msg } from "./types";

}): boolean;
size(): number;
}

@@ -5,3 +5,3 @@ "use strict";

/*
* Copyright 2020 The NATS Authors
* Copyright 2020-2022 The NATS Authors
* Licensed under the Apache License, Version 2.0 (the "License");

@@ -24,11 +24,8 @@ * you may not use this file except in compliance with the License.

function isRequestError(msg) {
// to consider an error from the server we expect no payload
if (msg && msg.data.length === 0 && msg.headers) {
const headers = msg.headers;
if (headers.hasError) {
// only 503s are expected from core NATS (404/408/409s are JetStream)
if (headers.code === 503) {
return error_1.NatsError.errorForCode(error_1.ErrorCode.NoResponders);
}
}
var _a;
// NATS core only considers errors 503s on messages that have no payload
// everything else simply forwarded as part of the message and is considered
// application level information
if (msg && msg.data.length === 0 && ((_a = msg.headers) === null || _a === void 0 ? void 0 : _a.code) === 503) {
return error_1.NatsError.errorForCode(error_1.ErrorCode.NoResponders);
}

@@ -84,4 +81,11 @@ return null;

}
size() {
var _a;
const subj = this._msg.subject.length;
const reply = ((_a = this._msg.reply) === null || _a === void 0 ? void 0 : _a.length) || 0;
const payloadAndHeaders = this._msg.size === -1 ? 0 : this._msg.size;
return subj + reply + payloadAndHeaders;
}
}
exports.MsgImpl = MsgImpl;
//# sourceMappingURL=msg.js.map
import { ProtocolHandler } from "./protocol";
import { ConnectionOptions, JetStreamClient, JetStreamManager, JetStreamOptions, Msg, NatsConnection, PublishOptions, RequestManyOptions, RequestOptions, ServerInfo, Stats, Status, Subscription, SubscriptionOptions } from "./types";
import type { SemVer } from "./semver";
import { Features } from "./semver";
import { QueuedIterator } from "./queued_iterator";

@@ -36,2 +37,3 @@ export declare class NatsConnectionImpl implements NatsConnection {

rtt(): Promise<number>;
get features(): Features;
}

@@ -442,4 +442,7 @@ "use strict";

}
get features() {
return this.protocol.features;
}
}
exports.NatsConnectionImpl = NatsConnectionImpl;
//# sourceMappingURL=nats.js.map

@@ -1,6 +0,8 @@

import { JetStreamClient, JetStreamManager, ObjectInfo, ObjectResult, ObjectStore, ObjectStoreInfo, ObjectStoreMeta, ObjectStoreMetaOptions, ObjectStoreOptions, PubAck, PurgeResponse, StorageType, StreamInfo, StreamInfoRequestOptions } from "./types";
import { JetStreamClient, JetStreamManager, ObjectInfo, ObjectResult, ObjectStore, ObjectStoreMeta, ObjectStoreMetaOptions, ObjectStoreOptions, ObjectStoreStatus, PubAck, PurgeResponse, StorageType, StreamInfo, StreamInfoRequestOptions } from "./types";
import { QueuedIterator } from "./queued_iterator";
export declare const osPrefix = "OBJ_";
export declare const digestType = "SHA-256=";
export declare function objectStoreStreamName(bucket: string): string;
export declare function objectStoreBucketName(stream: string): string;
export declare class ObjectStoreInfoImpl implements ObjectStoreInfo {
export declare class ObjectStoreStatusImpl implements ObjectStoreStatus {
si: StreamInfo;

@@ -46,5 +48,7 @@ backingStore: string;

rawInfo(name: string): Promise<ServerObjectInfo | null>;
seal(): Promise<ObjectStoreInfo>;
status(opts?: Partial<StreamInfoRequestOptions>): Promise<ObjectStoreInfo>;
_si(opts?: Partial<StreamInfoRequestOptions>): Promise<StreamInfo | null>;
seal(): Promise<ObjectStoreStatus>;
status(opts?: Partial<StreamInfoRequestOptions>): Promise<ObjectStoreStatus>;
destroy(): Promise<boolean>;
_put(meta: ObjectStoreMeta, rs: ReadableStream<Uint8Array> | null): Promise<ObjectInfo>;
put(meta: ObjectStoreMeta, rs: ReadableStream<Uint8Array> | null): Promise<ObjectInfo>;

@@ -51,0 +55,0 @@ get(name: string): Promise<ObjectResult | null>;

@@ -33,5 +33,6 @@ "use strict";

Object.defineProperty(exports, "__esModule", { value: true });
exports.ObjectStoreImpl = exports.ObjectStoreInfoImpl = exports.objectStoreBucketName = exports.objectStoreStreamName = void 0;
exports.ObjectStoreImpl = exports.ObjectStoreStatusImpl = exports.objectStoreBucketName = exports.objectStoreStreamName = exports.digestType = exports.osPrefix = void 0;
const types_1 = require("./types");
const kv_1 = require("./kv");
const base64_1 = require("./base64");
const codec_1 = require("./codec");

@@ -45,9 +46,12 @@ const nuid_1 = require("./nuid");

const sha256_1 = require("./sha256");
const semver_1 = require("./semver");
exports.osPrefix = "OBJ_";
exports.digestType = "SHA-256=";
function objectStoreStreamName(bucket) {
(0, kv_1.validateBucket)(bucket);
return `OBJ_${bucket}`;
return `${exports.osPrefix}${bucket}`;
}
exports.objectStoreStreamName = objectStoreStreamName;
function objectStoreBucketName(stream) {
if (stream.startsWith("OBJ_")) {
if (stream.startsWith(exports.osPrefix)) {
return stream.substring(4);

@@ -58,3 +62,3 @@ }

exports.objectStoreBucketName = objectStoreBucketName;
class ObjectStoreInfoImpl {
class ObjectStoreStatusImpl {
constructor(si) {

@@ -90,3 +94,3 @@ this.si = si;

}
exports.ObjectStoreInfoImpl = ObjectStoreInfoImpl;
exports.ObjectStoreStatusImpl = ObjectStoreStatusImpl;
class ObjectInfoImpl {

@@ -177,3 +181,3 @@ constructor(oi) {

// name = name.replaceAll(" ", "_");
name = name.replace(/[\. ]/g, "_");
name = name.replace(/[. ]/g, "_");
let error = undefined;

@@ -229,3 +233,3 @@ try {

}
const meta = `$O.${this.name}.M.${obj}`;
const meta = this._metaSubject(obj);
try {

@@ -236,4 +240,3 @@ const m = yield this.jsm.streams.getMessage(this.stream, {

const jc = (0, codec_1.JSONCodec)();
const info = jc.decode(m.data);
return info;
return jc.decode(m.data);
}

@@ -248,5 +251,19 @@ catch (err) {

}
_si(opts) {
return __awaiter(this, void 0, void 0, function* () {
try {
return yield this.jsm.streams.info(this.stream, opts);
}
catch (err) {
const nerr = err;
if (nerr.code === "404") {
return null;
}
return Promise.reject(err);
}
});
}
seal() {
return __awaiter(this, void 0, void 0, function* () {
let info = yield this.jsm.streams.info(this.stream);
let info = yield this._si();
if (info === null) {

@@ -257,3 +274,3 @@ return Promise.reject(new Error("object store not found"));

info = yield this.jsm.streams.update(this.stream, info.config);
return Promise.resolve(new ObjectStoreInfoImpl(info));
return Promise.resolve(new ObjectStoreStatusImpl(info));
});

@@ -263,7 +280,7 @@ }

return __awaiter(this, void 0, void 0, function* () {
const info = yield this.jsm.streams.info(this.stream, opts);
const info = yield this._si(opts);
if (info === null) {
return Promise.reject(new Error("object store not found"));
}
return Promise.resolve(new ObjectStoreInfoImpl(info));
return Promise.resolve(new ObjectStoreStatusImpl(info));
});

@@ -274,3 +291,3 @@ }

}
put(meta, rs) {
_put(meta, rs) {
var _a, _b;

@@ -316,10 +333,10 @@ return __awaiter(this, void 0, void 0, function* () {

info.size += payload.length;
info.mtime = new Date().toISOString();
const digest = sha.digest("base64");
const pad = digest.length % 3;
const padding = pad > 0 ? "=".repeat(pad) : "";
info.digest = `sha-256=${digest}${padding}`;
info.deleted = false;
proms.push(this.js.publish(chunkSubj, payload));
}
info.mtime = new Date().toISOString();
const digest = sha.digest("base64");
const pad = digest.length % 3;
const padding = pad > 0 ? "=".repeat(pad) : "";
info.digest = `${exports.digestType}${digest}${padding}`;
info.deleted = false;
// trailing md for the object

@@ -361,2 +378,9 @@ const h = (0, headers_1.headers)();

}
put(meta, rs) {
var _a;
if ((_a = meta === null || meta === void 0 ? void 0 : meta.options) === null || _a === void 0 ? void 0 : _a.link) {
return Promise.reject(new Error("link cannot be set when putting the object in bucket"));
}
return this._put(meta, rs);
}
get(name) {

@@ -368,2 +392,5 @@ return __awaiter(this, void 0, void 0, function* () {

}
if (info.deleted) {
return Promise.resolve(null);
}
if (info.options && info.options.link) {

@@ -407,3 +434,3 @@ const ln = info.options.link.name || "";

const padding = pad > 0 ? "=".repeat(pad) : "";
const digest = `sha-256=${hash}${padding}`;
const digest = `${exports.digestType}${hash}${padding}`;
if (digest !== info.digest) {

@@ -458,3 +485,3 @@ controller.error(new Error(`received a corrupt object, digests do not match received: ${info.digest} calculated ${digest}`));

};
return this.put(meta, null);
return this._put(meta, null);
}

@@ -488,3 +515,3 @@ link(name, info) {

};
return this.put(mm, null);
return this._put(mm, null);
});

@@ -520,2 +547,5 @@ }

}
if (info.deleted) {
return Promise.reject(new Error("cannot update meta for a deleted object"));
}
// FIXME: Go's implementation doesn't seem correct - it possibly adds a new meta entry

@@ -529,2 +559,8 @@ // effectively making the object available under 2 names, but it doesn't remove the

}
if (name !== meta.name) {
const i = yield this.info(meta.name);
if (i && !i.deleted) {
return Promise.reject(new Error("an object already exists with that name"));
}
}
meta.name = n;

@@ -605,3 +641,3 @@ const ii = Object.assign({}, info, toServerObjectStoreMeta(meta));

_metaSubject(n) {
return `$O.${this.name}.M.${n}`;
return `$O.${this.name}.M.${base64_1.Base64UrlCodec.encode(n)}`;
}

@@ -645,2 +681,6 @@ _metaSubjectAll() {

const jsi = js;
const { ok, min } = jsi.nc.features.get(semver_1.Feature.JS_OBJECTSTORE);
if (!ok) {
return Promise.reject(new Error(`objectstore is only supported on servers ${min} or better`));
}
let jsopts = jsi.opts || {};

@@ -657,41 +697,2 @@ const to = jsopts.timeout || 2000;

exports.ObjectStoreImpl = ObjectStoreImpl;
class Base64Codec {
static encode(bytes) {
if (typeof bytes === "string") {
return btoa(bytes);
}
const a = Array.from(bytes);
return btoa(String.fromCharCode(...a));
}
static decode(s, binary = false) {
const bin = atob(s);
if (!binary) {
return bin;
}
const bytes = new Uint8Array(bin.length);
for (let i = 0; i < bin.length; i++) {
bytes[i] = bin.charCodeAt(i);
}
return bytes;
}
}
class Base64UrlCodec {
static encode(bytes) {
return Base64UrlCodec.toB64URLEncoding(Base64Codec.encode(bytes));
}
static decode(s, binary = false) {
return Base64Codec.decode(Base64UrlCodec.fromB64URLEncoding(s), binary);
}
static toB64URLEncoding(b64str) {
b64str = b64str.replace(/=/g, "");
b64str = b64str.replace(/\+/g, "-");
return b64str.replace(/\//g, "_");
}
static fromB64URLEncoding(b64str) {
// pads are % 4, but not necessary on decoding
b64str = b64str.replace(/_/g, "/");
b64str = b64str.replace(/-/g, "+");
return b64str;
}
}
//# sourceMappingURL=objectstore.js.map

@@ -413,3 +413,3 @@ "use strict";

if (!this.infoReceived) {
this.features = new semver_1.Features((0, semver_1.parseSemVer)(info.version));
this.features.update((0, semver_1.parseSemVer)(info.version));
this.infoReceived = true;

@@ -416,0 +416,0 @@ if (this.transport.isEncrypted()) {

@@ -46,3 +46,3 @@ import { Deferred } from "./util";

received: number;
protected noIterator: boolean;
noIterator: boolean;
iterClosed: Deferred<void>;

@@ -59,3 +59,3 @@ protected done: boolean;

_data?: unknown;
private err?;
err?: Error;
constructor();

@@ -62,0 +62,0 @@ [Symbol.asyncIterator](): AsyncIterableIterator<T>;

@@ -86,3 +86,2 @@ "use strict";

for (let i = 0; i < yields.length; i++) {
// some iterators could inject a callback
if (typeof yields[i] === "function") {

@@ -89,0 +88,0 @@ const fn = yields[i];

@@ -9,3 +9,7 @@ export declare type SemVer = {

export declare enum Feature {
JS_PULL_MAX_BYTES = "js_pull_max_bytes"
JS_KV = "js_kv",
JS_OBJECTSTORE = "js_objectstore",
JS_PULL_MAX_BYTES = "js_pull_max_bytes",
JS_NEW_CONSUMER_CREATE_API = "js_new_consumer_create",
JS_ALLOW_DIRECT = "js_allow_direct"
}

@@ -19,8 +23,38 @@ declare type FeatureVersion = {

features: Map<Feature, FeatureVersion>;
disabled: Feature[];
constructor(v: SemVer);
/**
* Removes all disabled entries
*/
resetDisabled(): void;
/**
* Disables a particular feature.
* @param f
*/
disable(f: Feature): void;
isDisabled(f: Feature): boolean;
update(v: SemVer | string): void;
/**
* Register a feature that requires a particular server version.
* @param f
* @param requires
*/
set(f: Feature, requires: string): void;
/**
* Returns whether the feature is available and the min server
* version that supports it.
* @param f
*/
get(f: Feature): FeatureVersion;
/**
* Returns true if the feature is supported
* @param f
*/
supports(f: Feature): boolean;
/**
* Returns true if the server is at least the specified version
* @param v
*/
require(v: SemVer | string): boolean;
}
export {};

@@ -34,3 +34,7 @@ "use strict";

(function (Feature) {
Feature["JS_KV"] = "js_kv";
Feature["JS_OBJECTSTORE"] = "js_objectstore";
Feature["JS_PULL_MAX_BYTES"] = "js_pull_max_bytes";
Feature["JS_NEW_CONSUMER_CREATE_API"] = "js_new_consumer_create";
Feature["JS_ALLOW_DIRECT"] = "js_allow_direct";
})(Feature = exports.Feature || (exports.Feature = {}));

@@ -40,5 +44,42 @@ class Features {

this.features = new Map();
this.disabled = [];
this.update(v);
}
/**
* Removes all disabled entries
*/
resetDisabled() {
this.disabled.length = 0;
this.update(this.server);
}
/**
* Disables a particular feature.
* @param f
*/
disable(f) {
this.disabled.push(f);
this.update(this.server);
}
isDisabled(f) {
return this.disabled.indexOf(f) !== -1;
}
update(v) {
if (typeof v === "string") {
v = parseSemVer(v);
}
this.server = v;
this.set(Feature.JS_KV, "2.6.2");
this.set(Feature.JS_OBJECTSTORE, "2.6.3");
this.set(Feature.JS_PULL_MAX_BYTES, "2.8.3");
this.set(Feature.JS_NEW_CONSUMER_CREATE_API, "2.9.0");
this.set(Feature.JS_ALLOW_DIRECT, "2.9.0");
this.disabled.forEach((f) => {
this.features.delete(f);
});
}
/**
* Register a feature that requires a particular server version.
* @param f
* @param requires
*/
set(f, requires) {

@@ -50,8 +91,22 @@ this.features.set(f, {

}
/**
* Returns whether the feature is available and the min server
* version that supports it.
* @param f
*/
get(f) {
return this.features.get(f) || { min: "unknown", ok: false };
}
/**
* Returns true if the feature is supported
* @param f
*/
supports(f) {
return this.get(f).ok;
var _a;
return ((_a = this.get(f)) === null || _a === void 0 ? void 0 : _a.ok) || false;
}
/**
* Returns true if the server is at least the specified version
* @param v
*/
require(v) {

@@ -58,0 +113,0 @@ if (typeof v === "string") {

@@ -89,12 +89,21 @@ "use strict";

this.cancelTimeout();
this.stop();
if (this.cleanupFn) {
try {
this.cleanupFn(this, this.info);
const fn = () => {
this.stop();
if (this.cleanupFn) {
try {
this.cleanupFn(this, this.info);
}
catch (_err) {
// ignoring
}
}
catch (_err) {
// ignoring
}
this.closed.resolve();
};
if (this.noIterator) {
fn();
}
this.closed.resolve();
else {
//@ts-ignore: schedule the close once all messages are processed
this.push(fn);
}
}

@@ -101,0 +110,0 @@ }

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.RepublishHeaders = exports.DirectMsgHeaders = exports.JsHeaders = exports.ReplayPolicy = exports.AckPolicy = exports.DeliverPolicy = exports.StorageType = exports.DiscardPolicy = exports.RetentionPolicy = exports.AdvisoryKind = exports.RequestStrategy = exports.DEFAULT_MAX_PING_OUT = exports.DEFAULT_PING_INTERVAL = exports.DEFAULT_JITTER_TLS = exports.DEFAULT_JITTER = exports.DEFAULT_MAX_RECONNECT_ATTEMPTS = exports.DEFAULT_RECONNECT_TIME_WAIT = exports.DEFAULT_HOST = exports.DEFAULT_PORT = exports.DebugEvents = exports.Events = exports.Empty = void 0;
exports.RepublishHeaders = exports.DirectMsgHeaders = exports.JsHeaders = exports.ReplayPolicy = exports.AckPolicy = exports.DeliverPolicy = exports.StorageType = exports.DiscardPolicy = exports.RetentionPolicy = exports.AdvisoryKind = exports.RequestStrategy = exports.DEFAULT_MAX_PING_OUT = exports.DEFAULT_PING_INTERVAL = exports.DEFAULT_JITTER_TLS = exports.DEFAULT_JITTER = exports.DEFAULT_MAX_RECONNECT_ATTEMPTS = exports.DEFAULT_RECONNECT_TIME_WAIT = exports.DEFAULT_HOST = exports.DEFAULT_PORT = exports.DebugEvents = exports.Events = exports.Empty = exports.NatsError = void 0;
var error_1 = require("./error");
Object.defineProperty(exports, "NatsError", { enumerable: true, get: function () { return error_1.NatsError; } });
exports.Empty = new Uint8Array(0);
/**
* Events reported by the {@link NatsConnection.status} iterator.
* Events reported by the {@link NatsConnection#status} iterator.
*/

@@ -22,3 +24,3 @@ var Events;

/**
* Other events that can be reported by the {@link NatsConnection.status} iterator.
* Other events that can be reported by the {@link NatsConnection#status} iterator.
* These can usually be safely ignored, as higher-order functionality of the client

@@ -219,3 +221,3 @@ * will handle them.

/**
* The size in bytes of the message's body - Only if {@link Republish.headers_only} is set.
* The size in bytes of the message's body - Only if {@link Republish#headers_only} is set.
*/

@@ -222,0 +224,0 @@ RepublishHeaders["Size"] = "Nats-Msg-Size";

@@ -46,3 +46,3 @@ "use strict";

const dns = require("dns");
const VERSION = "2.8.0";
const VERSION = "2.8.1-0";
const LANG = "nats.js";

@@ -279,4 +279,4 @@ class NodeTransport {

this.socket.on("close", () => {
this._closed(connError, false);
this.socket = undefined;
this._closed(connError, false);
});

@@ -323,3 +323,3 @@ }

_send(frame) {
if (this.isClosed) {
if (this.isClosed || this.socket === undefined) {
return Promise.resolve();

@@ -326,0 +326,0 @@ }

{
"name": "nats",
"version": "2.8.0",
"version": "2.8.1-0",
"description": "Node.js client for NATS, a lightweight, high-performance cloud native messaging system",

@@ -43,3 +43,3 @@ "keywords": [

"clean": "shx rm -Rf ./lib/* ./nats-base-client ./.deps",
"clone-nbc": "shx mkdir -p ./.deps && cd ./.deps && git clone --branch v1.8.0 https://github.com/nats-io/nats.deno.git",
"clone-nbc": "shx mkdir -p ./.deps && cd ./.deps && git clone --branch main https://github.com/nats-io/nats.deno.git",
"fmt": "deno fmt ./src/ ./examples/ ./test/",

@@ -58,3 +58,3 @@ "prepack": "npm run clone-nbc && npm run cjs && npm run check-package && npm run build",

"engines": {
"node": ">= 10.0.0"
"node": ">= 14.0.0"
},

@@ -61,0 +61,0 @@ "dependencies": {

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc