Socket
Socket
Sign inDemoInstall

@ibm-cloud/cloudant

Package Overview
Dependencies
Maintainers
2
Versions
53
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@ibm-cloud/cloudant - npm Package Compare versions

Comparing version 0.8.2 to 0.8.3

72

auth/couchdbSessionAuthenticator.js

@@ -17,32 +17,6 @@ "use strict";

*/
var __extends = (this && this.__extends) || (function () {
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
if (typeof b !== "function" && b !== null)
throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
var __assign = (this && this.__assign) || function () {
__assign = Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.CouchdbSessionAuthenticator = void 0;
var ibm_cloud_sdk_core_1 = require("ibm-cloud-sdk-core");
var sessionTokenManager_1 = require("./sessionTokenManager");
const ibm_cloud_sdk_core_1 = require("ibm-cloud-sdk-core");
const sessionTokenManager_1 = require("./sessionTokenManager");
/**

@@ -60,4 +34,7 @@ * The CouchdbSessionAuthenticator is used to get CouchDB session authentication information to

*/
var CouchdbSessionAuthenticator = /** @class */ (function (_super) {
__extends(CouchdbSessionAuthenticator, _super);
class CouchdbSessionAuthenticator extends ibm_cloud_sdk_core_1.Authenticator {
tokenManager;
requiredOptions;
tokenOptions;
static AUTHTYPE_COUCHDB_SESSION = 'COUCHDB_SESSION';
/**

@@ -71,7 +48,6 @@ * Create a new CouchdbSessionAuthenticator instance.

*/
function CouchdbSessionAuthenticator(options) {
var _this = _super.call(this) || this;
(0, ibm_cloud_sdk_core_1.validateInput)(options, _this.requiredOptions);
_this.tokenOptions = __assign({}, options);
return _this;
constructor(options) {
super();
(0, ibm_cloud_sdk_core_1.validateInput)(options, this.requiredOptions);
this.tokenOptions = { ...options };
}

@@ -87,5 +63,5 @@ /**

*/
CouchdbSessionAuthenticator.prototype.authenticate = function (requestOptions) {
authenticate(requestOptions) {
return this.tokenManager.getToken();
};
}
/**

@@ -97,3 +73,3 @@ * Configure the TokenManager to use all the `request` settings

*/
CouchdbSessionAuthenticator.prototype.configure = function (userOptions) {
configure(userOptions) {
// Merge the options

@@ -103,3 +79,3 @@ Object.assign(this.tokenOptions, userOptions);

// Check if we've already patched the jar
var cookieJar = this.tokenOptions.jar;
const cookieJar = this.tokenOptions.jar;
if (cookieJar && !cookieJar.cloudantPatch) {

@@ -109,3 +85,3 @@ // Set the patching flag

// Replace the store's updateCookie function with one that applies a patch to newCookie
var originalUpdateCookieFn_1 = cookieJar.store.updateCookie;
const originalUpdateCookieFn = cookieJar.store.updateCookie;
cookieJar.store.updateCookie = function updateCookie(oldCookie, newCookie, cb) {

@@ -116,3 +92,3 @@ // Add current time as an update timestamp to the newCookie

// in place of creation time to check the expiry.
var originalExpiryTimeFn = newCookie.expiryTime;
const originalExpiryTimeFn = newCookie.expiryTime;
newCookie.expiryTime = function expiryTime(now) {

@@ -130,4 +106,4 @@ // The original expiryTime check is relative to a time in this order:

// patch we need to also provide that fallback.
if (originalUpdateCookieFn_1) {
originalUpdateCookieFn_1.call(cookieJar.store, oldCookie, newCookie, cb);
if (originalUpdateCookieFn) {
originalUpdateCookieFn.call(cookieJar.store, oldCookie, newCookie, cb);
}

@@ -142,3 +118,3 @@ else {

this.tokenManager = new sessionTokenManager_1.SessionTokenManager(this.tokenOptions);
};
}
/**

@@ -150,9 +126,7 @@ * Returns the authenticator's type ('COUCHDB_SESSION').

// eslint-disable-next-line class-methods-use-this
CouchdbSessionAuthenticator.prototype.authenticationType = function () {
authenticationType() {
return CouchdbSessionAuthenticator.AUTHTYPE_COUCHDB_SESSION;
};
CouchdbSessionAuthenticator.AUTHTYPE_COUCHDB_SESSION = 'COUCHDB_SESSION';
return CouchdbSessionAuthenticator;
}(ibm_cloud_sdk_core_1.Authenticator));
}
}
exports.CouchdbSessionAuthenticator = CouchdbSessionAuthenticator;
//# sourceMappingURL=couchdbSessionAuthenticator.js.map

@@ -17,3 +17,3 @@ /**

export { NoAuthAuthenticator, BasicAuthenticator, IamAuthenticator, IamTokenManager, getAuthenticatorFromEnvironment, } from 'ibm-cloud-sdk-core';
export { CouchdbSessionAuthenticator } from './couchdbSessionAuthenticator';
export { CouchdbSessionAuthenticator, CouchdbSessionAuthenticatorOptions, } from './couchdbSessionAuthenticator';
export { SessionTokenManager } from './sessionTokenManager';

@@ -17,20 +17,5 @@ "use strict";

*/
var __extends = (this && this.__extends) || (function () {
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
if (typeof b !== "function" && b !== null)
throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.SessionTokenManager = void 0;
var ibm_cloud_sdk_core_1 = require("ibm-cloud-sdk-core");
const ibm_cloud_sdk_core_1 = require("ibm-cloud-sdk-core");
/**

@@ -42,4 +27,11 @@ * Token Manager of CouchDB session token.

*/
var SessionTokenManager = /** @class */ (function (_super) {
__extends(SessionTokenManager, _super);
class SessionTokenManager extends ibm_cloud_sdk_core_1.TokenManager {
requiredOptions = [
'username',
'password',
'serviceUrl',
'jar',
];
tokenName;
options;
/**

@@ -61,14 +53,7 @@ * Create a new [[SessionTokenManager]] instance. For internal use by

*/
function SessionTokenManager(options) {
var _this = _super.call(this, options) || this;
_this.requiredOptions = [
'username',
'password',
'serviceUrl',
'jar',
];
(0, ibm_cloud_sdk_core_1.validateInput)(options, _this.requiredOptions);
_this.options = options;
_this.tokenName = 'AuthSession';
return _this;
constructor(options) {
super(options);
(0, ibm_cloud_sdk_core_1.validateInput)(options, this.requiredOptions);
this.options = options;
this.tokenName = 'AuthSession';
}

@@ -82,6 +67,6 @@ /**

// eslint-disable-next-line class-methods-use-this
SessionTokenManager.prototype.setHeaders = function (headers) {
var errMsg = 'During CouchDB Session Authentication only `request` service headers are in use';
setHeaders(headers) {
const errMsg = 'During CouchDB Session Authentication only `request` service headers are in use';
throw new Error(errMsg);
};
}
/**

@@ -92,3 +77,3 @@ * Request a session token using basic credentials.

*/
SessionTokenManager.prototype.requestToken = function () {
requestToken() {
if (!this.options.headers) {

@@ -98,6 +83,6 @@ this.options.headers = {};

// these cannot be overwritten
var parameters = {
const parameters = {
options: {
headers: this.options.headers,
url: "".concat(this.options.serviceUrl, "/_session"),
url: `${this.options.serviceUrl}/_session`,
method: 'POST',

@@ -111,3 +96,3 @@ body: {

return this.requestWrapperInstance.sendRequest(parameters);
};
}
/**

@@ -122,12 +107,12 @@ * From the response parse and save session token into field `accessToken`.

*/
SessionTokenManager.prototype.saveTokenInfo = function (tokenResponse) {
var sessionCookie = tokenResponse.headers['set-cookie'];
saveTokenInfo(tokenResponse) {
const sessionCookie = tokenResponse.headers['set-cookie'];
if (!Array.isArray(sessionCookie)) {
var err = 'Set-Cookie header not present in response';
const err = 'Set-Cookie header not present in response';
throw new Error(err);
}
var sessionToken = null;
var expireTime = null;
var refreshTime = null;
for (var i = 0; i < sessionCookie.length && sessionToken == null; i += 1) {
let sessionToken = null;
let expireTime = null;
let refreshTime = null;
for (let i = 0; i < sessionCookie.length && sessionToken == null; i += 1) {
sessionToken = new RegExp('AuthSession=([^;]*);').exec(sessionCookie[i]);

@@ -140,7 +125,7 @@ if (sessionToken != null) {

if (sessionToken == null) {
var err = 'Session token not present in response';
const err = 'Session token not present in response';
throw new Error(err);
}
this.accessToken = sessionToken[1];
var fractionOfTtl = 0.8;
[, this.accessToken] = sessionToken;
const fractionOfTtl = 0.8;
if (expireTime == null) {

@@ -161,9 +146,8 @@ if (refreshTime == null) {

// Set refresh time from the expire time
var timeToLive = this.expireTime - (0, ibm_cloud_sdk_core_1.getCurrentTime)();
const timeToLive = this.expireTime - (0, ibm_cloud_sdk_core_1.getCurrentTime)();
this.refreshTime = this.expireTime - timeToLive * (1.0 - fractionOfTtl);
}
};
return SessionTokenManager;
}(ibm_cloud_sdk_core_1.TokenManager));
}
}
exports.SessionTokenManager = SessionTokenManager;
//# sourceMappingURL=sessionTokenManager.js.map

@@ -18,6 +18,5 @@ /**

import { Stream } from './stream';
import { ChangesResultIterableIterator } from './changesResultIterator';
import CloudantV1 = require('../v1');
/** @internal */
export declare enum Mode {
/** @internal */
FINITE = 0,

@@ -30,5 +29,5 @@ LISTEN = 1

* There are two modes of operation:
* * {@link #startOneOff()} to fetch the changes from the supplied since sequence
* * {@link startOneOff} to fetch the changes from the supplied since sequence
* until there are no further pending changes.
* * {@link #start()} to fetch the changes from the supplied since sequence and
* * {@link start} to fetch the changes from the supplied since sequence and
* then continuing to listen indefinitely for further new changes.

@@ -38,7 +37,7 @@ *

* {@link CloudantV1.PostChangesParams.since}. By default when using:
* * {@link #startOneOff()} the feed will start from the beginning.
* * {@link #start()} the feed will start from "now".
* * {@link startOneOff} the feed will start from the beginning.
* * {@link start} the feed will start from "now".
*
* In either mode the {@link Stream} of changes can be terminated early by calling
* {@link #stop()}.
* {@link stop}.
*

@@ -83,2 +82,3 @@ * By default {@link ChangesFollower} will suppress transient errors indefinitely and

export declare class ChangesFollower {
/** @internal */
static BATCH_SIZE: number;

@@ -89,3 +89,3 @@ private readonly client;

private limit;
changesResultIterator: ChangesResultIterableIterator;
private changesResultIterator;
/**

@@ -111,3 +111,3 @@ * Create a new {@link ChangesFollower} using the supplied client and params that

* * the number of changes received reaches the limit specified in the {@link CloudantV1.PostChangesParams} used to instantiate this {@link ChangesFollower}.
* * {@link ChangesFollower#stop()} is called.
* * {@link stop} is called.
*

@@ -118,3 +118,3 @@ * The same change may be received more than once.

* @throws {Error} if:
* * {@link ChangesFollower#start} or {@link ChangesFollower#startOneOff} was already called.
* * {@link start} or {@link startOneOff} was already called.
* * a terminal error or unsuppressed transient error is received from the service when fetching changes.

@@ -131,3 +131,3 @@ */

* * the number of changes received reaches the limit specified in the {@link CloudantV1.PostChangesParams} used to instantiate this {@link ChangesFollower}.
* * {@link ChangesFollower#stop} is called.
* * {@link stop} is called.
*

@@ -138,3 +138,3 @@ * The same change may be received more than once.

* @throws {Error} if:
* * {@link ChangesFollower#start} or {@link ChangesFollower#startOneOff} was already called.
* * {@link start} or {@link startOneOff} was already called.
* * a terminal error or unsuppressed transient error is received from the service when fetching changes.

@@ -146,4 +146,4 @@ */

*
* @throws {Error} if {@link ChangesFollower#start}
* or {@link ChangesFollower#startOneOff} was not called first
* @throws {Error} if {@link start}
* or {@link startOneOff} was not called first
*/

@@ -150,0 +150,0 @@ stop(): void;

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ChangesFollower = exports.Mode = void 0;
var changesParamsHelper_1 = require("./changesParamsHelper");
var changesResultItemStream_1 = require("./changesResultItemStream");
var stream_1 = require("stream");
var changesResultIterator_1 = require("./changesResultIterator");
const changesParamsHelper_1 = require("./changesParamsHelper");
const changesResultItemStream_1 = require("./changesResultItemStream");
const stream_1 = require("stream");
const changesResultIterator_1 = require("./changesResultIterator");
/** @internal */
var Mode;
(function (Mode) {
/** @internal */
Mode[Mode["FINITE"] = 0] = "FINITE";

@@ -18,5 +18,5 @@ Mode[Mode["LISTEN"] = 1] = "LISTEN";

* There are two modes of operation:
* * {@link #startOneOff()} to fetch the changes from the supplied since sequence
* * {@link startOneOff} to fetch the changes from the supplied since sequence
* until there are no further pending changes.
* * {@link #start()} to fetch the changes from the supplied since sequence and
* * {@link start} to fetch the changes from the supplied since sequence and
* then continuing to listen indefinitely for further new changes.

@@ -26,7 +26,7 @@ *

* {@link CloudantV1.PostChangesParams.since}. By default when using:
* * {@link #startOneOff()} the feed will start from the beginning.
* * {@link #start()} the feed will start from "now".
* * {@link startOneOff} the feed will start from the beginning.
* * {@link start} the feed will start from "now".
*
* In either mode the {@link Stream} of changes can be terminated early by calling
* {@link #stop()}.
* {@link stop}.
*

@@ -70,3 +70,11 @@ * By default {@link ChangesFollower} will suppress transient errors indefinitely and

*/
var ChangesFollower = /** @class */ (function () {
class ChangesFollower {
/** @internal */
static BATCH_SIZE = 10000;
// Initialization fields
client;
params;
errorTolerance;
limit;
changesResultIterator;
/**

@@ -84,3 +92,3 @@ * Create a new {@link ChangesFollower} using the supplied client and params that

*/
function ChangesFollower(client, params, errorTolerance) {
constructor(client, params, errorTolerance) {
// Validate supplied params

@@ -103,6 +111,6 @@ changesParamsHelper_1.ChangesParamsHelper.validateParams(params);

// Check the timeout is suitable
var readTimeout = this.client.getTimeout();
const readTimeout = this.client.getTimeout();
if (readTimeout > 0 &&
readTimeout < changesParamsHelper_1.ChangesParamsHelper.MIN_CLIENT_TIMEOUT) {
throw new Error("To use ChangesFollower the client read timeout must be at least ".concat(changesParamsHelper_1.ChangesParamsHelper.MIN_CLIENT_TIMEOUT, " ms. The client read timeout is ").concat(readTimeout, " ms."));
throw new Error(`To use ChangesFollower the client read timeout must be at least ${changesParamsHelper_1.ChangesParamsHelper.MIN_CLIENT_TIMEOUT} ms. The client read timeout is ${readTimeout} ms.`);
}

@@ -117,3 +125,3 @@ }

* * the number of changes received reaches the limit specified in the {@link CloudantV1.PostChangesParams} used to instantiate this {@link ChangesFollower}.
* * {@link ChangesFollower#stop()} is called.
* * {@link stop} is called.
*

@@ -124,8 +132,8 @@ * The same change may be received more than once.

* @throws {Error} if:
* * {@link ChangesFollower#start} or {@link ChangesFollower#startOneOff} was already called.
* * {@link start} or {@link startOneOff} was already called.
* * a terminal error or unsuppressed transient error is received from the service when fetching changes.
*/
ChangesFollower.prototype.start = function () {
start() {
return this.run(Mode.LISTEN);
};
}
/**

@@ -139,3 +147,3 @@ * Return all available changes until there are no further changes pending or

* * the number of changes received reaches the limit specified in the {@link CloudantV1.PostChangesParams} used to instantiate this {@link ChangesFollower}.
* * {@link ChangesFollower#stop} is called.
* * {@link stop} is called.
*

@@ -146,15 +154,15 @@ * The same change may be received more than once.

* @throws {Error} if:
* * {@link ChangesFollower#start} or {@link ChangesFollower#startOneOff} was already called.
* * {@link start} or {@link startOneOff} was already called.
* * a terminal error or unsuppressed transient error is received from the service when fetching changes.
*/
ChangesFollower.prototype.startOneOff = function () {
startOneOff() {
return this.run(Mode.FINITE);
};
}
/**
* Stop this {@link ChangesFollower}.
*
* @throws {Error} if {@link ChangesFollower#start}
* or {@link ChangesFollower#startOneOff} was not called first
* @throws {Error} if {@link start}
* or {@link startOneOff} was not called first
*/
ChangesFollower.prototype.stop = function () {
stop() {
if (this.changesResultIterator) {

@@ -166,3 +174,3 @@ this.changesResultIterator.return();

}
};
}
/**

@@ -173,3 +181,3 @@ *

*/
ChangesFollower.prototype.run = function (mode) {
run(mode) {
if (!this.changesResultIterator) {

@@ -181,11 +189,9 @@ return this.createChangesResultItemsStream(mode);

}
};
ChangesFollower.prototype.createChangesResultItemsStream = function (mode) {
}
createChangesResultItemsStream(mode) {
this.changesResultIterator = new changesResultIterator_1.ChangesResultIterableIterator(this.client, changesParamsHelper_1.ChangesParamsHelper.cloneParams(this.params), mode, this.errorTolerance);
return (0, stream_1.pipeline)(stream_1.Readable.from(this.changesResultIterator), new changesResultItemStream_1.ChangesResultItemStream(), function () { });
};
ChangesFollower.BATCH_SIZE = 10000;
return ChangesFollower;
}());
return (0, stream_1.pipeline)(stream_1.Readable.from(this.changesResultIterator), new changesResultItemStream_1.ChangesResultItemStream(), () => { });
}
}
exports.ChangesFollower = ChangesFollower;
//# sourceMappingURL=changesFollower.js.map

@@ -19,7 +19,17 @@ "use strict";

exports.ChangesParamsHelper = void 0;
var v1_1 = require("../v1");
var ChangesParamsHelper = /** @class */ (function () {
function ChangesParamsHelper() {
}
ChangesParamsHelper.cloneParams = function (params, since, limit) {
const v1_1 = require("../v1");
class ChangesParamsHelper {
/**
* Set minimum client timeout to 1 minute (= 60 000 ms).
* 1 minute is the sort of number that very likely to be used as a client timeout,
* so it makes sense to set as our minimum client timeout.
*/
static MIN_CLIENT_TIMEOUT = 60000;
/**
* Set longpoll timeout to {@link MIN_CLIENT_TIMEOUT} - 3 second (= 3000 ms).
* To give the changes request a chance to be answered before the client timeout
* it is set to 3 seconds less.
*/
static LONGPOLL_TIMEOUT = this.MIN_CLIENT_TIMEOUT - 3000;
static cloneParams(params, since, limit) {
return {

@@ -46,4 +56,4 @@ db: params.db,

};
};
ChangesParamsHelper.validateParams = function (params) {
}
static validateParams(params) {
if (!params) {

@@ -55,4 +65,4 @@ throw new Error('PostChangesParams configuration is required.');

}
var invalidParams = [];
var paramsShouldBeUndefined = [
let invalidParams = [];
let paramsShouldBeUndefined = [
'descending',

@@ -64,17 +74,16 @@ 'feed',

];
for (var _i = 0, paramsShouldBeUndefined_1 = paramsShouldBeUndefined; _i < paramsShouldBeUndefined_1.length; _i++) {
var paramName = paramsShouldBeUndefined_1[_i];
for (let paramName of paramsShouldBeUndefined) {
if (paramName in params) {
invalidParams.push("'".concat(paramName, "'"));
invalidParams.push(`'${paramName}'`);
}
}
if ('filter' in params && params.filter !== '_selector') {
invalidParams.push("'filter=".concat(params.filter, "'"));
invalidParams.push(`'filter=${params.filter}'`);
}
var errorMsg = '';
let errorMsg = '';
if (invalidParams.length > 0) {
var invalidParamsAsText = invalidParams.join(', ');
errorMsg = "The params ".concat(invalidParamsAsText, " are invalid when using ChangesFollower.");
const invalidParamsAsText = invalidParams.join(', ');
errorMsg = `The params ${invalidParamsAsText} are invalid when using ChangesFollower.`;
if (invalidParams.length === 1) {
errorMsg = "The param ".concat(invalidParamsAsText, " is invalid when using ChangesFollower.");
errorMsg = `The param ${invalidParamsAsText} is invalid when using ChangesFollower.`;
}

@@ -85,20 +94,5 @@ }

}
};
var _a;
_a = ChangesParamsHelper;
/**
* Set minimum client timeout to 1 minute (= 60 000 ms).
* 1 minute is the sort of number that very likely to be used as a client timeout,
* so it makes sense to set as our minimum client timeout.
*/
ChangesParamsHelper.MIN_CLIENT_TIMEOUT = 60000;
/**
* Set longpoll timeout to {@link MIN_CLIENT_TIMEOUT} - 3 second (= 3000 ms).
* To give the changes request a chance to be answered before the client timeout
* it is set to 3 seconds less.
*/
ChangesParamsHelper.LONGPOLL_TIMEOUT = _a.MIN_CLIENT_TIMEOUT - 3000;
return ChangesParamsHelper;
}());
}
}
exports.ChangesParamsHelper = ChangesParamsHelper;
//# sourceMappingURL=changesParamsHelper.js.map

@@ -17,28 +17,9 @@ "use strict";

*/
var __extends = (this && this.__extends) || (function () {
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
if (typeof b !== "function" && b !== null)
throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.ChangesResultItemStream = void 0;
var stream_1 = require("./stream");
var ibm_cloud_sdk_core_1 = require("ibm-cloud-sdk-core");
var ChangesResultItemStream = /** @class */ (function (_super) {
__extends(ChangesResultItemStream, _super);
function ChangesResultItemStream() {
return _super !== null && _super.apply(this, arguments) || this;
}
ChangesResultItemStream.prototype._transform = function (chunk, encoding, callback) {
var validationError = this.getValidationError(chunk);
const stream_1 = require("./stream");
const ibm_cloud_sdk_core_1 = require("ibm-cloud-sdk-core");
class ChangesResultItemStream extends stream_1.Stream {
_transform(chunk, encoding, callback) {
const validationError = this.getValidationError(chunk);
if (validationError !== null) {

@@ -48,4 +29,3 @@ this.destroy(validationError);

else {
for (var _i = 0, _a = chunk.results; _i < _a.length; _i++) {
var result = _a[_i];
for (let result of chunk.results) {
this.push(result);

@@ -55,10 +35,9 @@ }

callback();
};
ChangesResultItemStream.prototype.getValidationError = function (params) {
var requiredParams = ['last_seq', 'pending', 'results'];
}
getValidationError(params) {
const requiredParams = ['last_seq', 'pending', 'results'];
return (0, ibm_cloud_sdk_core_1.validateParams)(params, requiredParams, requiredParams);
};
return ChangesResultItemStream;
}(stream_1.Stream));
}
}
exports.ChangesResultItemStream = ChangesResultItemStream;
//# sourceMappingURL=changesResultItemStream.js.map

@@ -17,47 +17,10 @@ "use strict";

*/
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (g && (g = 0, op[0] && (_ = 0)), _) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.ChangesResultIterableIterator = void 0;
var changesParamsHelper_1 = require("./changesParamsHelper");
var changesFollower_1 = require("./changesFollower");
var ibm_cloud_sdk_core_1 = require("ibm-cloud-sdk-core");
var util_1 = require("util");
const changesParamsHelper_1 = require("./changesParamsHelper");
const changesFollower_1 = require("./changesFollower");
const ibm_cloud_sdk_core_1 = require("ibm-cloud-sdk-core");
const util_1 = require("util");
var TransientErrorSuppression;
(function (TransientErrorSuppression) {
/** @internal */
TransientErrorSuppression[TransientErrorSuppression["ALWAYS"] = 0] = "ALWAYS";

@@ -67,18 +30,28 @@ TransientErrorSuppression[TransientErrorSuppression["NEVER"] = 1] = "NEVER";

})(TransientErrorSuppression || (TransientErrorSuppression = {}));
var ChangesResultIterableIterator = /** @class */ (function () {
function ChangesResultIterableIterator(client, params, mode, errorTolerance) {
this.timeoutPromise = (0, util_1.promisify)(setTimeout);
this.cancelToken = 'CloudantChangesIteratorCancel';
this.doneResult = {
done: true,
value: undefined,
};
this.logger = (0, ibm_cloud_sdk_core_1.getNewLogger)('cloudant-node-sdk');
this.baseDelay = 100;
this.expRetryGate = Math.floor(Math.log2(changesParamsHelper_1.ChangesParamsHelper.LONGPOLL_TIMEOUT / this.baseDelay));
this.inflight = null;
// Default to "infinite"
this.pending = Number.MAX_VALUE;
this.stopped = false;
this.retry = 0;
class ChangesResultIterableIterator {
timeoutPromise = (0, util_1.promisify)(setTimeout);
cancelToken = 'CloudantChangesIteratorCancel';
client;
doneResult = {
done: true,
value: undefined,
};
errorTolerance;
logger = (0, ibm_cloud_sdk_core_1.getNewLogger)('cloudant-node-sdk');
mode;
promisedConfig;
transientErrorSuppression;
baseDelay = 100;
expRetryGate = Math.floor(Math.log2(changesParamsHelper_1.ChangesParamsHelper.LONGPOLL_TIMEOUT / this.baseDelay));
cancel;
countDown;
inflight = null;
params;
// Default to "infinite"
pending = Number.MAX_VALUE;
since;
stopped = false;
successTimestamp;
retry = 0;
constructor(client, params, mode, errorTolerance) {
this.client = client;

@@ -89,3 +62,3 @@ this.params = params;

if (this.params.limit !== undefined) {
this.logger.debug("Applying changes limit ".concat(this.params.limit));
this.logger.debug(`Applying changes limit ${this.params.limit}`);
this.countDown = this.params.limit;

@@ -103,3 +76,3 @@ }

this.transientErrorSuppression = TransientErrorSuppression.TIMER;
this.logger.debug("Suppress errors for ".concat(this.errorTolerance, " ms."));
this.logger.debug(`Suppress errors for ${this.errorTolerance} ms.`);
}

@@ -115,190 +88,167 @@ if (this.params.since === undefined) {

}
ChangesResultIterableIterator.prototype.configure = function () {
return __awaiter(this, void 0, void 0, function () {
var _this = this;
return __generator(this, function (_a) {
if (this.params.includeDocs) {
return [2 /*return*/, this.client
.getDatabaseInformation({
db: this.params.db,
})
.then(function (info) {
if (info.result &&
'doc_count' in info.result &&
info.result.doc_count > 0 &&
'sizes' in info.result &&
'external' in info.result.sizes &&
info.result.sizes.external > 0) {
// Calculate an average doc size + typical change content size
// and try to keep each batch to be about 5 MB
_this.params.limit =
Math.floor((5 * 1024 * 1024) /
(info.result.sizes.external / info.result.doc_count + 500)) || 1;
}
})];
async configure() {
if (this.params.includeDocs) {
return this.client
.getDatabaseInformation({
db: this.params.db,
})
.then((info) => {
if (info.result &&
'doc_count' in info.result &&
info.result.doc_count > 0 &&
'sizes' in info.result &&
'external' in info.result.sizes &&
info.result.sizes.external > 0) {
// Calculate an average doc size + typical change content size
// and try to keep each batch to be about 5 MB
this.params.limit =
Math.floor((5 * 1024 * 1024) /
(info.result.sizes.external / info.result.doc_count + 500)) || 1;
}
else {
this.params.limit = changesFollower_1.ChangesFollower.BATCH_SIZE;
return [2 /*return*/, Promise.resolve()];
}
return [2 /*return*/];
});
}
else {
this.params.limit = changesFollower_1.ChangesFollower.BATCH_SIZE;
return Promise.resolve();
}
}
[Symbol.asyncIterator]() {
return this;
}
async return(value) {
this.logger.debug('Iterator return entry.');
if (!this.stopped) {
this.logger.debug('Setting stopped flag.');
this.stopped = true;
if (this.cancel) {
this.logger.debug('Cancelling inflight requests.');
this.cancel(new Error(this.cancelToken));
}
}
this.logger.debug('Iterator return exiting done.');
return this.doneResult;
}
async next(value) {
this.logger.debug('Iterator next entry.');
// Stop the iterator if stopped is set to true.
if (this.stopped) {
this.logger.debug('Already stopped, iterator next exiting done.');
return this.doneResult;
}
// Await the async config and also
// yield to the event loop so our long-running requests don't enqueue
// more long-running requests on the same microtask queue and
// end up blocking I/O.
await Promise.all([
this.promisedConfig,
new Promise((resolve) => setImmediate(resolve)),
]);
this.logger.debug('Making next request.');
// Make a new cancellable promise that can race with the request
// in case the follower is stopped.
let resolveCancellable;
const cancellable = new Promise((resolve, reject) => {
resolveCancellable = resolve;
this.cancel = reject;
});
};
ChangesResultIterableIterator.prototype[Symbol.asyncIterator] = function () {
return this;
};
ChangesResultIterableIterator.prototype.return = function (value) {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
this.logger.debug('Iterator return entry.');
if (!this.stopped) {
this.logger.debug('Setting stopped flag.');
return Promise.race([
cancellable,
this.client.postChanges(changesParamsHelper_1.ChangesParamsHelper.cloneParams(this.params, this.since, this.countDown && this.countDown < this.params.limit
? this.countDown
: undefined)),
])
.then((response) => {
this.logger.debug('Got next response.');
// Reset the retry counter
this.retry = 0;
if (this.transientErrorSuppression === TransientErrorSuppression.TIMER) {
this.logger.debug('Setting new timestamp for timer suppression');
this.successTimestamp = Date.now();
}
this.since = response.result.last_seq;
this.pending = response.result.pending;
if (this.mode === changesFollower_1.Mode.FINITE && this.pending === 0) {
this.logger.debug('No more changes pending, setting stopped flag.');
this.stopped = true;
}
if (this.countDown !== undefined) {
this.logger.debug('Decrementing limit.');
this.countDown -= response.result.results.length;
if (this.countDown <= 0) {
this.logger.debug('Limit reached, setting stopped flag.');
this.stopped = true;
if (this.cancel) {
this.logger.debug('Cancelling inflight requests.');
this.cancel(new Error(this.cancelToken));
}
}
this.logger.debug('Iterator next exiting with result.');
return { done: false, value: response.result };
})
.catch((err) => {
this.logger.debug(`Caught error ${err.message}`);
if (err.message === this.cancelToken) {
this.logger.debug('Iterator next exiting cancelled.');
return this.doneResult;
}
switch (this.transientErrorSuppression) {
case TransientErrorSuppression.ALWAYS:
break;
case TransientErrorSuppression.TIMER:
if (Date.now() < this.successTimestamp + this.errorTolerance) {
break;
}
}
this.logger.debug('Iterator return exiting done.');
return [2 /*return*/, this.doneResult];
});
this.logger.debug('Error tolerance deadline exceeded.');
// In the case the timer has been exceeded we want to throw so
// fall through
case TransientErrorSuppression.NEVER:
this.logger.verbose(`ChangesResultStream stream: ${err.message}`);
throw err;
}
switch (err.code) {
case 400:
case 401:
case 403:
case 404:
// Terminal error, stop running
this.logger.debug('Terminal error');
this.logger.verbose(`ChangesResultStream stream: ${err.message}`);
throw err;
default:
// Note this includes Errors
// which handles cases like disconnections and incomplete
// bodies where we may have received a successful response
// code, but couldn't e.g. parse the body
this.logger.verbose(`Suppressing transient error ${err.message}.`);
const emptyChangesResultPromise = {
done: false,
value: {
last_seq: this.since,
pending: this.pending,
results: [],
},
};
let expDelay;
if (this.retry > this.expRetryGate) {
// If we've exceeded the cap, use the timeout value
expDelay = changesParamsHelper_1.ChangesParamsHelper.LONGPOLL_TIMEOUT;
}
else {
expDelay = Math.pow(2, this.retry) * this.baseDelay;
}
const delay = Math.round(Math.random() * expDelay) + 1;
this.logger.debug(`Backing off for ${delay} ms.`);
this.retry++;
return this.timeoutPromise(delay).then(() => {
this.logger.debug(`Iterator next exiting with empty result.`);
return emptyChangesResultPromise;
});
}
})
.finally(() => {
this.logger.debug('Cleaning up cancellable.');
this.cancel = null;
// Resolve the cancellable to ensure clean up can happen
resolveCancellable();
});
};
ChangesResultIterableIterator.prototype.next = function (value) {
return __awaiter(this, void 0, void 0, function () {
var resolveCancellable, cancellable;
var _this = this;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
this.logger.debug('Iterator next entry.');
// Stop the iterator if stopped is set to true.
if (this.stopped) {
this.logger.debug('Already stopped, iterator next exiting done.');
return [2 /*return*/, this.doneResult];
}
// Await the async config and also
// yield to the event loop so our long-running requests don't enqueue
// more long-running requests on the same microtask queue and
// end up blocking I/O.
return [4 /*yield*/, Promise.all([
this.promisedConfig,
new Promise(function (resolve) { return setImmediate(resolve); }),
])];
case 1:
// Await the async config and also
// yield to the event loop so our long-running requests don't enqueue
// more long-running requests on the same microtask queue and
// end up blocking I/O.
_a.sent();
this.logger.debug('Making next request.');
cancellable = new Promise(function (resolve, reject) {
resolveCancellable = resolve;
_this.cancel = reject;
});
return [2 /*return*/, Promise.race([
cancellable,
this.client.postChanges(changesParamsHelper_1.ChangesParamsHelper.cloneParams(this.params, this.since, this.countDown && this.countDown < this.params.limit
? this.countDown
: undefined)),
])
.then(function (response) {
_this.logger.debug('Got next response.');
// Reset the retry counter
_this.retry = 0;
if (_this.transientErrorSuppression === TransientErrorSuppression.TIMER) {
_this.logger.debug('Setting new timestamp for timer suppression');
_this.successTimestamp = Date.now();
}
_this.since = response.result.last_seq;
_this.pending = response.result.pending;
if (_this.mode === changesFollower_1.Mode.FINITE && _this.pending === 0) {
_this.logger.debug('No more changes pending, setting stopped flag.');
_this.stopped = true;
}
if (_this.countDown !== undefined) {
_this.logger.debug('Decrementing limit.');
_this.countDown -= response.result.results.length;
if (_this.countDown <= 0) {
_this.logger.debug('Limit reached, setting stopped flag.');
_this.stopped = true;
}
}
_this.logger.debug('Iterator next exiting with result.');
return { done: false, value: response.result };
})
.catch(function (err) {
_this.logger.debug("Caught error ".concat(err.message));
if (err.message === _this.cancelToken) {
_this.logger.debug('Iterator next exiting cancelled.');
return _this.doneResult;
}
switch (_this.transientErrorSuppression) {
case TransientErrorSuppression.ALWAYS:
break;
case TransientErrorSuppression.TIMER:
if (Date.now() < _this.successTimestamp + _this.errorTolerance) {
break;
}
_this.logger.debug('Error tolerance deadline exceeded.');
// In the case the timer has been exceeded we want to throw so
// fall through
case TransientErrorSuppression.NEVER:
_this.logger.verbose("ChangesResultStream stream: ".concat(err.message));
throw err;
}
switch (err.code) {
case 400:
case 401:
case 403:
case 404:
// Terminal error, stop running
_this.logger.debug('Terminal error');
_this.logger.verbose("ChangesResultStream stream: ".concat(err.message));
throw err;
default:
// Note this includes Errors
// which handles cases like disconnections and incomplete
// bodies where we may have received a successful response
// code, but couldn't e.g. parse the body
_this.logger.verbose("Suppressing transient error ".concat(err.message, "."));
var emptyChangesResultPromise_1 = {
done: false,
value: {
last_seq: _this.since,
pending: _this.pending,
results: [],
},
};
var expDelay = void 0;
if (_this.retry > _this.expRetryGate) {
// If we've exceeded the cap, use the timeout value
expDelay = changesParamsHelper_1.ChangesParamsHelper.LONGPOLL_TIMEOUT;
}
else {
expDelay = Math.pow(2, _this.retry) * _this.baseDelay;
}
var delay = Math.round(Math.random() * expDelay) + 1;
_this.logger.debug("Backing off for ".concat(delay, " ms."));
_this.retry++;
return _this.timeoutPromise(delay).then(function () {
_this.logger.debug("Iterator next exiting with empty result.");
return emptyChangesResultPromise_1;
});
}
})
.finally(function () {
_this.logger.debug('Cleaning up cancellable.');
_this.cancel = null;
// Resolve the cancellable to ensure clean up can happen
resolveCancellable();
})];
}
});
});
};
return ChangesResultIterableIterator;
}());
}
}
exports.ChangesResultIterableIterator = ChangesResultIterableIterator;
//# sourceMappingURL=changesResultIterator.js.map

@@ -17,45 +17,21 @@ "use strict";

*/
var __extends = (this && this.__extends) || (function () {
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
if (typeof b !== "function" && b !== null)
throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
var __assign = (this && this.__assign) || function () {
__assign = Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.Stream = void 0;
var stream_1 = require("stream");
var Stream = /** @class */ (function (_super) {
__extends(Stream, _super);
function Stream(opts) {
return _super.call(this, __assign(__assign({}, opts), { objectMode: true, highWaterMark: 1 })) || this;
const stream_1 = require("stream");
class Stream extends stream_1.Transform {
constructor(opts) {
super({
...opts,
objectMode: true, // sets readableObjectMode and writableObjectMode to true
highWaterMark: 1,
});
}
Stream.prototype.push = function (chunk, encoding) {
return _super.prototype.push.call(this, chunk);
};
Stream.prototype.read = function (size) {
return _super.prototype.read.call(this, size);
};
return Stream;
}(stream_1.Transform));
push(chunk, encoding) {
return super.push(chunk);
}
read(size) {
return super.read(size);
}
}
exports.Stream = Stream;
//# sourceMappingURL=stream.js.map

@@ -20,4 +20,4 @@ /**

export import CloudantV1 = require('./cloudant/v1');
export { BasicAuthenticator, IamAuthenticator, CouchdbSessionAuthenticator, } from './auth';
export { BasicAuthenticator, IamAuthenticator, CouchdbSessionAuthenticator, CouchdbSessionAuthenticatorOptions, } from './auth';
export { ChangesFollower } from './cloudant/features/changesFollower';
export { Stream } from './cloudant/features/stream';

@@ -17,33 +17,18 @@ "use strict";

*/
var __extends = (this && this.__extends) || (function () {
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
if (typeof b !== "function" && b !== null)
throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
Object.defineProperty(exports, "__esModule", { value: true });
// eslint-disable-next-line max-classes-per-file
var ibm_cloud_sdk_core_1 = require("ibm-cloud-sdk-core");
var tough_cookie_1 = require("tough-cookie");
var auth_1 = require("../auth");
var common_1 = require("./common");
var https_1 = require("https");
var http_1 = require("http");
const ibm_cloud_sdk_core_1 = require("ibm-cloud-sdk-core");
const tough_cookie_1 = require("tough-cookie");
const auth_1 = require("../auth");
const common_1 = require("./common");
const https_1 = require("https");
const http_1 = require("http");
/**
* Set default timeout to 2.5 minutes (= 150 000 ms)
*/
var READ_TIMEOUT = 150000;
const READ_TIMEOUT = 150000;
/**
* Set Validation rules
*/
var DocumentOperations = [
const DocumentOperations = [
'deleteDocument',

@@ -61,3 +46,3 @@ 'getDocument',

];
var AttachmentOperations = [
const AttachmentOperations = [
'deleteAttachment',

@@ -68,3 +53,3 @@ 'getAttachment',

];
var docIdRule = {
const docIdRule = {
pathSegment: 'doc_id',

@@ -74,3 +59,3 @@ errorParameterName: 'Document ID',

};
var attIdRule = {
const attIdRule = {
pathSegment: 'attachment_name',

@@ -80,6 +65,6 @@ errorParameterName: 'Attachment name',

};
var validationRules = [docIdRule, attIdRule];
var rulesByOperation = {};
validationRules.forEach(function (rule) {
rule.operationIds.forEach(function (operationId) {
const validationRules = [docIdRule, attIdRule];
const rulesByOperation = {};
validationRules.forEach((rule) => {
rule.operationIds.forEach((operationId) => {
if (!(operationId in rulesByOperation)) {

@@ -98,9 +83,5 @@ rulesByOperation[operationId] = [];

*/
var InvalidArgumentValueError = /** @class */ (function (_super) {
__extends(InvalidArgumentValueError, _super);
function InvalidArgumentValueError() {
return _super !== null && _super.apply(this, arguments) || this;
}
return InvalidArgumentValueError;
}(Error));
class InvalidArgumentValueError extends Error {
code;
}
/**

@@ -112,4 +93,4 @@ * Cloudant specific service that extends the base service functions.

*/
var CloudantBaseService = /** @class */ (function (_super) {
__extends(CloudantBaseService, _super);
class CloudantBaseService extends ibm_cloud_sdk_core_1.BaseService {
timeout;
/**

@@ -121,4 +102,3 @@ * Configuration values to use Cloudant service.

*/
function CloudantBaseService(userOptions) {
var _this = this;
constructor(userOptions) {
userOptions.jar = userOptions.jar || new tough_cookie_1.CookieJar();

@@ -129,10 +109,9 @@ if (!('timeout' in userOptions)) {

CloudantBaseService.setDefaultAgentsIfUnset(userOptions);
_this = _super.call(this, userOptions) || this;
_this.timeout = userOptions.timeout;
_this.configureSessionAuthenticator();
return _this;
super(userOptions);
this.timeout = userOptions.timeout;
this.configureSessionAuthenticator();
}
CloudantBaseService.prototype.getTimeout = function () {
getTimeout() {
return this.timeout;
};
}
/**

@@ -145,6 +124,6 @@ * Set the service URL to send requests to and

*/
CloudantBaseService.prototype.setServiceUrl = function (url) {
_super.prototype.setServiceUrl.call(this, url);
setServiceUrl(url) {
super.setServiceUrl(url);
this.configureSessionAuthenticator();
};
}
/**

@@ -158,7 +137,7 @@ * Configure the service using external configuration

*/
CloudantBaseService.prototype.configureService = function (serviceName) {
configureService(serviceName) {
// Read external configuration and set as request defaults.
_super.prototype.configureService.call(this, serviceName);
super.configureService(serviceName);
this.configureSessionAuthenticator();
};
}
/**

@@ -171,7 +150,7 @@ * Turn request body compression on or off.

*/
CloudantBaseService.prototype.setEnableGzipCompression = function (setting) {
setEnableGzipCompression(setting) {
// Read external configuration and set as request defaults.
_super.prototype.setEnableGzipCompression.call(this, setting);
super.setEnableGzipCompression(setting);
this.configureSessionAuthenticator();
};
}
/**

@@ -181,7 +160,7 @@ * In case of CouchdbSessionAuthenticator

*/
CloudantBaseService.prototype.configureSessionAuthenticator = function () {
var auth = this.getAuthenticator();
configureSessionAuthenticator() {
const auth = this.getAuthenticator();
if (auth instanceof auth_1.CouchdbSessionAuthenticator) {
var serviceClass = this.constructor;
var newHeaders = (0, common_1.getSdkHeaders)(serviceClass.DEFAULT_SERVICE_NAME, 'v1', 'authenticatorPostSession');
const serviceClass = this.constructor;
const newHeaders = (0, common_1.getSdkHeaders)(serviceClass.DEFAULT_SERVICE_NAME, 'v1', 'authenticatorPostSession');
if (this.baseOptions.headers === undefined) {

@@ -195,24 +174,23 @@ Object.assign(this.baseOptions, { 'headers': newHeaders });

}
};
}
/**
* Extend createRequest to handle document and attachment validation.
*/
CloudantBaseService.prototype.createRequest = function (parameters) {
var _a;
var operationId = null;
createRequest(parameters) {
let operationId = null;
if ('X-IBMCloud-SDK-Analytics' in parameters.defaultOptions.headers) {
// Extract operation id
var analyticsHeader = parameters.defaultOptions.headers['X-IBMCloud-SDK-Analytics'];
_a = analyticsHeader
const analyticsHeader = parameters.defaultOptions.headers['X-IBMCloud-SDK-Analytics'];
[, operationId] = analyticsHeader
.split(';')
.find(function (element) { return element.startsWith('operation_id'); })
.split('='), operationId = _a[1];
.find((element) => element.startsWith('operation_id'))
.split('=');
// Check if operation id exists in rulesByOperation object
if (operationId != null &&
Object.keys(rulesByOperation).includes(operationId)) {
var violatedRules = rulesByOperation[operationId].filter(function (rule) {
const violatedRules = rulesByOperation[operationId].filter((rule) => {
// get the path segment e.g. doc_id from the response's path object
if ('path' in parameters.options &&
rule.pathSegment in parameters.options.path) {
var segmentToValidate = parameters.options.path[rule.pathSegment];
const segmentToValidate = parameters.options.path[rule.pathSegment];
return segmentToValidate.startsWith('_');

@@ -223,3 +201,3 @@ }

if (violatedRules.length > 0) {
var err = new InvalidArgumentValueError("".concat(violatedRules[0].errorParameterName, " ").concat(parameters.options.path[violatedRules[0].pathSegment], " starts with the invalid _ character."));
const err = new InvalidArgumentValueError(`${violatedRules[0].errorParameterName} ${parameters.options.path[violatedRules[0].pathSegment]} starts with the invalid _ character.`);
err.code = 'ERR_INVALID_ARG_VALUE';

@@ -230,6 +208,6 @@ return Promise.reject(err);

}
return _super.prototype.createRequest.call(this, parameters);
};
CloudantBaseService.setDefaultAgentsIfUnset = function (options) {
var cloudantDefaultAgentOptions = {
return super.createRequest(parameters);
}
static setDefaultAgentsIfUnset(options) {
const cloudantDefaultAgentOptions = {
keepAlive: true,

@@ -243,6 +221,5 @@ };

}
};
return CloudantBaseService;
}(ibm_cloud_sdk_core_1.BaseService));
}
}
exports.default = CloudantBaseService;
//# sourceMappingURL=cloudantBaseService.js.map

@@ -17,7 +17,30 @@ "use strict";

*/
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.getSdkHeaders = void 0;
var os = require("os");
const os = __importStar(require("os"));
// tslint:disable-next-line:no-var-requires
var pkg = require('../package.json');
const pkg = require('../package.json');
/**

@@ -27,11 +50,11 @@ * Get the request headers to be sent in requests by the SDK.

function getSdkHeaders(serviceName, serviceVersion, operationId) {
var sdkName = 'cloudant-node-sdk';
var sdkVersion = pkg.version;
var osName = os.platform();
var osVersion = os.release();
var osArch = os.arch();
var nodeVersion = process.version;
var headers = {
'User-Agent': "".concat(sdkName, "/").concat(sdkVersion, " (node.version=").concat(nodeVersion, "; os.name=").concat(osName, "; os.version=").concat(osVersion, "; os.arch=").concat(osArch, "; lang=Node.js;)"),
'X-IBMCloud-SDK-Analytics': "service_name=".concat(serviceName, ";service_version=").concat(serviceVersion, ";operation_id=").concat(operationId),
const sdkName = 'cloudant-node-sdk';
const sdkVersion = pkg.version;
const osName = os.platform();
const osVersion = os.release();
const osArch = os.arch();
const nodeVersion = process.version;
const headers = {
'User-Agent': `${sdkName}/${sdkVersion} (node.version=${nodeVersion}; os.name=${osName}; os.version=${osVersion}; os.arch=${osArch}; lang=Node.js;)`,
'X-IBMCloud-SDK-Analytics': `service_name=${serviceName};service_version=${serviceVersion};operation_id=${operationId}`,
};

@@ -38,0 +61,0 @@ return headers;

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

Object.defineProperty(exports, "__esModule", { value: true });
var ibm_cloud_sdk_core_1 = require("ibm-cloud-sdk-core");
var auth_1 = require("../auth");
var COUCHDB_SESSION_AUTH_TYPE = 'couchdb_session';
const ibm_cloud_sdk_core_1 = require("ibm-cloud-sdk-core");
const auth_1 = require("../auth");
const COUCHDB_SESSION_AUTH_TYPE = 'couchdb_session';
/**

@@ -30,5 +30,5 @@ * Extend the creating Authenticator from external configuration function with

function getAuthenticatorFromEnvCloudantExtension(serviceName) {
var auth;
var credentials = (0, ibm_cloud_sdk_core_1.readExternalSources)(serviceName);
var authType = credentials.authType;
let auth;
const credentials = (0, ibm_cloud_sdk_core_1.readExternalSources)(serviceName);
let { authType } = credentials;
if (!authType) {

@@ -35,0 +35,0 @@ // this is the alternative "AUTHTYPE" config property

{
"name": "@ibm-cloud/cloudant",
"version": "0.8.2",
"version": "0.8.3",
"description": "IBM Cloudant Node.js SDK",

@@ -32,3 +32,3 @@ "main": "index.js",

"test-integration-ci": "jest --runInBand --no-colors --testNamePattern='^((?!@slow).)*$' --json test/integration > test-output.log",
"typedoc": "typedoc --theme default --entryPointStrategy expand --excludeExternals --tsconfig tsconfig.json --out apidocs auth cloudant --includeVersion"
"typedoc": "typedoc"
},

@@ -40,10 +40,11 @@ "license": "Apache-2.0",

"dependencies": {
"@types/node": "18.19.4",
"ibm-cloud-sdk-core": "4.2.2"
"@types/node": "18.19.15",
"ibm-cloud-sdk-core": "4.2.3"
},
"devDependencies": {
"@types/jest": "29.5.11",
"@typescript-eslint/eslint-plugin": "6.17.0",
"@typescript-eslint/parser": "6.17.0",
"dotenv": "16.3.1",
"@types/extend": "3.0.4",
"@types/jest": "29.5.12",
"@typescript-eslint/eslint-plugin": "6.21.0",
"@typescript-eslint/parser": "6.21.0",
"dotenv": "16.4.3",
"eslint": "8.56.0",

@@ -62,6 +63,6 @@ "eslint-config-airbnb-base": "15.0.0",

"jest-junit": "16.0.0",
"prettier": "3.1.1",
"prettier": "3.2.5",
"sinon": "17.0.1",
"ts-jest": "29.1.1",
"typedoc": "0.25.6",
"ts-jest": "29.1.2",
"typedoc": "0.25.8",
"typescript": "5.3.3"

@@ -68,0 +69,0 @@ },

@@ -5,3 +5,3 @@ [![Build Status](https://github.com/IBM/cloudant-node-sdk/actions/workflows/test.yml/badge.svg?branch=main&event=push)](https://github.com/IBM/cloudant-node-sdk/actions/workflows/test.yml)

# IBM Cloudant Node.js SDK Version 0.8.2
# IBM Cloudant Node.js SDK Version 0.8.3

@@ -300,3 +300,3 @@ IBM Cloudant Node.js SDK is a client library that interacts with the

```ts
import { CloudantV1 } from "@ibm-cloud/cloudant";
import { CloudantV1 } from '@ibm-cloud/cloudant';
```

@@ -381,3 +381,3 @@ [embedmd]:# (test/examples/src/ts/CreateDbAndDoc.ts /interface/ $)

```js
const { CloudantV1 } = require('@ibm-cloud/cloudant');
import { CloudantV1 } from '@ibm-cloud/cloudant';
```

@@ -483,3 +483,3 @@ [embedmd]:# (test/examples/src/js/CreateDbAndDoc.js /const createDbAndDoc/ /createDbAndDoc\(\);\n\}/)

```ts
import { CloudantV1 } from "@ibm-cloud/cloudant";
import { CloudantV1 } from '@ibm-cloud/cloudant';
```

@@ -533,3 +533,3 @@ [embedmd]:# (test/examples/src/ts/GetInfoFromExistingDatabase.ts /\/\/ 1./ $)

```js
const { CloudantV1 } = require('@ibm-cloud/cloudant');
import { CloudantV1 } from '@ibm-cloud/cloudant';
```

@@ -613,3 +613,3 @@ [embedmd]:# (test/examples/src/js/GetInfoFromExistingDatabase.js /const getInfoFromExistingDatabase/ /getInfoFromExistingDatabase\(\);\n\}/)

```ts
import { CloudantV1 } from "@ibm-cloud/cloudant";
import { CloudantV1 } from '@ibm-cloud/cloudant';
```

@@ -709,3 +709,3 @@ [embedmd]:# (test/examples/src/ts/UpdateDoc.ts /interface/ $)

```js
const { CloudantV1 } = require('@ibm-cloud/cloudant');
import { CloudantV1 } from '@ibm-cloud/cloudant';
```

@@ -834,3 +834,3 @@ [embedmd]:# (test/examples/src/js/UpdateDoc.js /const updateDoc/ /updateDoc\(\);\n\}/)

```ts
import { CloudantV1 } from "@ibm-cloud/cloudant";
import { CloudantV1 } from '@ibm-cloud/cloudant';
```

@@ -891,3 +891,3 @@ [embedmd]:# (test/examples/src/ts/DeleteDoc.ts /interface/ $)

```js
const { CloudantV1 } = require('@ibm-cloud/cloudant');
import { CloudantV1 } from '@ibm-cloud/cloudant';
```

@@ -947,3 +947,3 @@ [embedmd]:# (test/examples/src/js/DeleteDoc.js /const deleteDoc/ /deleteDoc\(\);\n\}/)

For a complete list of code examples, see the [examples directory](https://github.com/IBM/cloudant-node-sdk/tree/v0.8.2/examples#examples-for-node).
For a complete list of code examples, see the [examples directory](https://github.com/IBM/cloudant-node-sdk/tree/v0.8.3/examples#examples-for-node).

@@ -1046,3 +1046,3 @@ ### Error handling

For use-cases where these configuration limitations are deemed too restrictive then it is recommended to
write code to use the SDK's [POST `_changes` API](https://github.com/IBM/cloudant-node-sdk/tree/v0.8.2/examples#postchanges) instead of the follower.
write code to use the SDK's [POST `_changes` API](https://github.com/IBM/cloudant-node-sdk/tree/v0.8.3/examples#postchanges) instead of the follower.

@@ -1082,3 +1082,3 @@ #### Error suppression

In these cases use-case specific control over the number of change requests made and the content size of the responses
may be achieved by using the SDK's [POST `_changes` API](https://github.com/IBM/cloudant-node-sdk/tree/v0.8.2/examples#postchanges).
may be achieved by using the SDK's [POST `_changes` API](https://github.com/IBM/cloudant-node-sdk/tree/v0.8.3/examples#postchanges).

@@ -1139,3 +1139,3 @@ #### Checkpointing

```js
const { ChangesFollower, CloudantV1 } = require('@ibm-cloud/cloudant');
import { ChangesFollower, CloudantV1 } from '@ibm-cloud/cloudant';
```

@@ -1186,3 +1186,3 @@ [embedmd]:# (test/examples/src/features/js/initialize.js /const client/ $)

```js
const { ChangesFollower, CloudantV1 } = require('@ibm-cloud/cloudant');
import { ChangesFollower, CloudantV1 } from '@ibm-cloud/cloudant';
```

@@ -1228,3 +1228,3 @@ [embedmd]:# (test/examples/src/features/js/start.js /const client/ $)

```js
const { ChangesFollower, CloudantV1 } = require('@ibm-cloud/cloudant');
import { ChangesFollower, CloudantV1 } from '@ibm-cloud/cloudant';
```

@@ -1302,5 +1302,5 @@ [embedmd]:# (test/examples/src/features/js/startOneOff.js /const client/ $)

```js
const { ChangesFollower, CloudantV1 } = require('@ibm-cloud/cloudant');
const { Writable } = require('node:stream');
const { pipeline } = require('node:stream/promises');
import { ChangesFollower, CloudantV1 } from '@ibm-cloud/cloudant';
import { Writable } from 'node:stream';
import { pipeline } from 'node:stream/promises';
```

@@ -1422,5 +1422,5 @@ [embedmd]:# (test/examples/src/features/js/startAndProcess.js /const client/ $)

```js
const { ChangesFollower, CloudantV1 } = require('@ibm-cloud/cloudant');
const { Writable } = require('node:stream');
const { pipeline } = require('node:stream/promises');
import { ChangesFollower, CloudantV1 } from '@ibm-cloud/cloudant';
import { Writable } from 'node:stream';
import { pipeline } from 'node:stream/promises';
```

@@ -1541,5 +1541,5 @@ [embedmd]:# (test/examples/src/features/js/startOneOffAndProcess.js /const client/ $)

```js
const { ChangesFollower, CloudantV1 } = require('@ibm-cloud/cloudant');
const { Writable } = require('node:stream');
const { pipeline } = require('node:stream/promises');
import { ChangesFollower, CloudantV1 } from '@ibm-cloud/cloudant';
import { Writable } from 'node:stream';
import { pipeline } from 'node:stream/promises';
```

@@ -1600,3 +1600,3 @@ [embedmd]:# (test/examples/src/features/js/stop.js /const client/ $)

[similar issues](https://github.com/IBM/cloudant-node-sdk/issues?q=is%3Aissue) and review the
[KNOWN_ISSUES file](https://github.com/IBM/cloudant-node-sdk/tree/v0.8.2/KNOWN_ISSUES.md) to verify that your issue hasn't been reported yet.
[KNOWN_ISSUES file](https://github.com/IBM/cloudant-node-sdk/tree/v0.8.3/KNOWN_ISSUES.md) to verify that your issue hasn't been reported yet.

@@ -1631,6 +1631,6 @@ Please consult the [security policy](https://github.com/IBM/cloudant-node-sdk/security/policy) before opening security related issues.

For more information, see [CONTRIBUTING](https://github.com/IBM/cloudant-node-sdk/tree/v0.8.2/CONTRIBUTING.md).
For more information, see [CONTRIBUTING](https://github.com/IBM/cloudant-node-sdk/tree/v0.8.3/CONTRIBUTING.md).
## License
This SDK is released under the Apache 2.0 license. To read the full text of the license, see [LICENSE](https://github.com/IBM/cloudant-node-sdk/tree/v0.8.2/LICENSE).
This SDK is released under the Apache 2.0 license. To read the full text of the license, see [LICENSE](https://github.com/IBM/cloudant-node-sdk/tree/v0.8.3/LICENSE).

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 too big to display

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

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