chore(dep): update and modernize dependencies

This commit is contained in:
Connor Peet 2019-07-03 12:22:56 -07:00
Родитель 291b41f412
Коммит 7691f9bf22
21 изменённых файлов: 108 добавлений и 150 удалений

Просмотреть файл

@ -4,6 +4,7 @@
- **feat**: allow retrieving lock lease IDs (see [#75](https://github.com/mixer/etcd3/issues/75))
- **bug**: fixed using `lease.put` in transactions not applying the lease to the target key (see [#92](https://github.com/mixer/etcd3/issues/92))
- **bug**: call `markFailed` on the mock instance, rather than the real connection pool, whilst mocking (see [#94](https://github.com/mixer/etcd3/issues/94))
- **chore**: update dependencies, including grpc and Typescript versions
## 0.2.12 2019-07-03

Просмотреть файл

@ -51,35 +51,34 @@
},
"homepage": "https://github.com/mixer/etcd3#readme",
"devDependencies": {
"@types/bignumber.js": "^4.0.3",
"@types/chai": "^3.4.35",
"@types/chai": "^4.1.7",
"@types/chai-as-promised": "^7.1.0",
"@types/chai-subset": "^1.3.0",
"@types/mocha": "^2.2.40",
"@types/chai-subset": "^1.3.2",
"@types/mocha": "^5.2.7",
"@types/node": "^7.0.12",
"@types/sinon": "^2.1.2",
"chai": "^3.5.0",
"@types/sinon": "^7.0.13",
"chai": "^4.2.0",
"chai-as-promised": "^7.1.1",
"chai-subset": "^1.5.0",
"change-case": "^3.0.1",
"lodash": "^4.17.4",
"mocha": "^3.2.0",
"node-fetch": "^1.6.3",
"npm-run-all": "^4.0.2",
"nyc": "^11.2.1",
"prettier": "^1.4.4",
"protobufjs": "^6.8.6",
"sinon": "^2.1.0",
"ts-node": "^3.3.0",
"tslint": "^5.7.0",
"tslint-microsoft-contrib": "5.0.1",
"typedoc": "^0.7.1",
"typescript": "^2.7.1"
"change-case": "^3.1.0",
"lodash": "^4.17.11",
"mocha": "^6.1.4",
"node-fetch": "^2.6.0",
"npm-run-all": "^4.1.5",
"nyc": "^14.1.1",
"prettier": "^1.18.2",
"protobufjs": "^6.8.8",
"sinon": "^7.3.2",
"ts-node": "^8.3.0",
"tslint": "^5.18.0",
"tslint-config-prettier": "^1.18.0",
"typedoc": "^0.14.2",
"typescript": "^3.5.2"
},
"dependencies": {
"@grpc/proto-loader": "^0.4.0",
"bignumber.js": "^4.1.0",
"grpc": "^1.19.0"
"@grpc/proto-loader": "^0.5.1",
"bignumber.js": "^5.0.0",
"grpc": "^1.21.1"
},
"prettier": {
"singleQuote": true,

Просмотреть файл

@ -14,10 +14,10 @@ export type IPermissionRequest =
function getRange(req: IPermissionRequest): Range {
if (req.hasOwnProperty('key')) {
return new Range(toBuffer((<{ key: Buffer | string }>req).key));
return new Range(toBuffer((req as { key: Buffer | string }).key));
}
return (<{ range: Range }>req).range;
return (req as { range: Range }).range;
}
/**

Просмотреть файл

@ -149,8 +149,8 @@ export class SingleRangeBuilder extends RangeBuilder<string | null> {
* string, or `null` if it isn't found.
*/
public string(encoding: string = 'utf8'): Promise<string | null> {
return this.exec().then(
res => (res.kvs.length === 0 ? null : res.kvs[0].value.toString(encoding)),
return this.exec().then(res =>
res.kvs.length === 0 ? null : res.kvs[0].value.toString(encoding),
);
}
@ -304,8 +304,8 @@ export class MultiRangeBuilder extends RangeBuilder<{ [key: string]: string }> {
return this.kv
.range(this.namespace.applyToRequest(this.request), this.callOptions)
.then(res => {
for (let i = 0; i < res.kvs.length; i++) {
res.kvs[i].key = this.namespace.unprefix(res.kvs[i].key);
for (const kv of res.kvs) {
kv.key = this.namespace.unprefix(kv.key);
}
return res;
@ -326,8 +326,8 @@ export class MultiRangeBuilder extends RangeBuilder<{ [key: string]: string }> {
private mapValues<T>(iterator: (buf: Buffer) => T): Promise<{ [key: string]: T }> {
return this.exec().then(res => {
const output: { [key: string]: T } = {};
for (let i = 0; i < res.kvs.length; i++) {
output[res.kvs[i].key.toString()] = iterator(res.kvs[i].value);
for (const kv of res.kvs) {
output[kv.key.toString()] = iterator(kv.value);
}
return output;
@ -560,9 +560,9 @@ export class PutBuilder extends PromiseWrap<RPC.IPutResponse> {
*/
export class ComparatorBuilder {
private request: {
compare: Promise<RPC.ICompare>[];
success: Promise<RPC.IRequestOp>[];
failure: Promise<RPC.IRequestOp>[];
compare: Array<Promise<RPC.ICompare>>;
success: Array<Promise<RPC.IRequestOp>>;
failure: Array<Promise<RPC.IRequestOp>>;
} = { compare: [], success: [], failure: [] };
private callOptions: grpc.CallOptions | undefined;
@ -589,7 +589,7 @@ export class ComparatorBuilder {
assertWithin(comparator, cmp, 'comparator in client.and(...)');
if (column === 'Value') {
value = toBuffer(<string | Buffer>value);
value = toBuffer(value as string | Buffer);
}
this.request.compare.push(
@ -607,7 +607,7 @@ export class ComparatorBuilder {
* Adds one or more consequent clauses to be executed if the comparison
* is truthy.
*/
public then(...clauses: (RPC.IRequestOp | IOperation)[]): this {
public then(...clauses: Array<RPC.IRequestOp | IOperation>): this {
this.request.success = this.mapOperations(clauses);
return this;
}
@ -616,7 +616,7 @@ export class ComparatorBuilder {
* Adds one or more consequent clauses to be executed if the comparison
* is falsey.
*/
public else(...clauses: (RPC.IRequestOp | IOperation)[]): this {
public else(...clauses: Array<RPC.IRequestOp | IOperation>): this {
this.request.failure = this.mapOperations(clauses);
return this;
}
@ -638,13 +638,13 @@ export class ComparatorBuilder {
/**
* Low-level method to add
*/
public mapOperations(ops: (RPC.IRequestOp | IOperation)[]) {
public mapOperations(ops: Array<RPC.IRequestOp | IOperation>) {
return ops.map(op => {
if (typeof (<IOperation>op).op === 'function') {
return (<IOperation>op).op();
if (typeof (op as IOperation).op === 'function') {
return (op as IOperation).op();
}
return Promise.resolve(<RPC.IRequestOp>op);
return Promise.resolve(op as RPC.IRequestOp);
});
}
}

Просмотреть файл

@ -45,7 +45,7 @@ function runServiceCall(
payload: object,
): Promise<any> {
return new Promise((resolve, reject) => {
(<any>client)[method](payload, metadata, options, (err: Error | null, res: any) => {
(client as any)[method](payload, metadata, options, (err: Error | null, res: any) => {
if (err) {
reject(castGrpcError(err));
} else {
@ -254,7 +254,7 @@ export class ConnectionPool implements ICallable<Host> {
service: keyof typeof Services,
): Promise<{ resource: Host; client: grpc.Client; metadata: grpc.Metadata }> {
if (this.mockImpl) {
return Promise.resolve(<any>this.mockImpl.getConnection(service)).then(connection => ({
return Promise.resolve(this.mockImpl.getConnection(service) as any).then(connection => ({
metadata: new grpc.Metadata(),
...connection,
}));

Просмотреть файл

@ -202,9 +202,7 @@ export class STMConflictError extends Error {
}
}
interface IErrorCtor {
new (message: string): Error;
}
type IErrorCtor = new (message: string) => Error;
/**
* Mapping of GRPC error messages to typed error. GRPC errors are untyped
@ -213,6 +211,7 @@ interface IErrorCtor {
const grpcMessageToError = new Map<string, IErrorCtor>([
['Connect Failed', GRPCConnectFailedError],
['Channel Disconnected', GRPCConnectFailedError],
['failed to connect to all addresses', GRPCConnectFailedError],
['Endpoint read failed', GRPCProtocolError],
['Got config after disconnection', GRPCProtocolError],
['Failed to create subchannel', GRPCProtocolError],
@ -272,7 +271,7 @@ export function castGrpcErrorMessage(message: string): Error {
* consume. Yes, this method is abhorrent.
*/
export function castGrpcError(err: Error): Error {
if ((<any>err).constructor !== Error) {
if ((err as any).constructor !== Error) {
return err; // it looks like it's already some kind of typed error
}

Просмотреть файл

@ -96,7 +96,7 @@ export class Etcd3 extends Namespace {
* ```
*/
public mock<T extends Partial<RPC.ICallable<any>>>(callable: T): T {
this.pool.mock(<any>callable);
this.pool.mock(callable as any);
return callable;
}

Просмотреть файл

@ -163,7 +163,7 @@ export class Lease extends EventEmitter {
*/
public put(key: string | Buffer): PutBuilder {
return new PutBuilder(
new RPC.KVClient(new LeaseClientWrapper(this.pool, <any>this)),
new RPC.KVClient(new LeaseClientWrapper(this.pool, this as any)),
this.namespace,
key,
).lease(this.grant());
@ -241,7 +241,7 @@ export class Lease extends EventEmitter {
/**
* Implements EventEmitter.on(...).
*/
public on(event: string, handler: Function): this {
public on(event: string, handler: (...args: any[]) => void): this {
// tslint:disable-line
return super.on(event, handler);
}
@ -290,7 +290,7 @@ export class Lease extends EventEmitter {
return stream.end();
}
const keepaliveTimer = setInterval(() => this.fireKeepAlive(stream), 1000 * this.ttl / 3);
const keepaliveTimer = setInterval(() => this.fireKeepAlive(stream), (1000 * this.ttl) / 3);
this.teardown = () => {
this.teardown = () => undefined;
@ -298,14 +298,16 @@ export class Lease extends EventEmitter {
stream.end();
};
stream.on('error', err => this.handleKeepaliveError(err)).on('data', res => {
if (leaseExpired(res)) {
return this.handleKeepaliveError(new EtcdLeaseInvalidError(res.ID));
}
stream
.on('error', err => this.handleKeepaliveError(err))
.on('data', res => {
if (leaseExpired(res)) {
return this.handleKeepaliveError(new EtcdLeaseInvalidError(res.ID));
}
this.lastKeepAlive = Date.now();
this.emit('keepaliveSucceeded', res);
});
this.lastKeepAlive = Date.now();
this.emit('keepaliveSucceeded', res);
});
this.emit('keepaliveEstablished');
return this.fireKeepAlive(stream);

Просмотреть файл

@ -29,14 +29,6 @@ function rangableIsPrefix(r: Rangable): r is { prefix: string | Buffer } {
* https://github.com/coreos/etcd/blob/c4a45c57135bf49ae701352c9151dc1be433d1dd/pkg/adt/interval_tree.go
*/
export class Range {
public readonly start: Buffer;
public readonly end: Buffer;
constructor(start: Buffer | string, end: Buffer | string = emptyKey) {
this.start = toBuffer(start);
this.end = toBuffer(end);
}
/**
* Prefix returns a Range that maps to all keys
* prefixed with the provided string.
@ -67,6 +59,13 @@ export class Range {
return new Range(v.start, v.end);
}
public readonly start: Buffer;
public readonly end: Buffer;
constructor(start: Buffer | string, end: Buffer | string = emptyKey) {
this.start = toBuffer(start);
this.end = toBuffer(end);
}
/**
* Returns whether the byte range includes the provided value.

Просмотреть файл

@ -23,7 +23,7 @@ export class SharedPool<T> {
// tests simpler.
private static deterministicInsertion: false;
private resources: IResourceRecord<T>[] = [];
private resources: Array<IResourceRecord<T>> = [];
private contentionCount = 0;
public constructor(private strategy: IBackoffStrategy) {}

Просмотреть файл

@ -71,10 +71,10 @@ function keyValueToResponse(key: string | Buffer, value?: Buffer): RPC.IRangeRes
key = toBuffer(key);
if (!value) {
return <any>{ kvs: [], more: false, count: '0' };
return { kvs: [], more: false, count: '0' } as any;
}
return <any>{
return {
kvs: [
{
key: Buffer.from(key),
@ -83,7 +83,7 @@ function keyValueToResponse(key: string | Buffer, value?: Buffer): RPC.IRangeRes
],
more: false,
count: '1',
};
} as any;
}
/**
@ -91,7 +91,7 @@ function keyValueToResponse(key: string | Buffer, value?: Buffer): RPC.IRangeRes
*/
class ReadSet {
private readonly reads: { [key: string]: Promise<RPC.IRangeResponse> } = Object.create(null);
private readonly completedReads: { key: Buffer; res: RPC.IRangeResponse }[] = [];
private readonly completedReads: Array<{ key: Buffer; res: RPC.IRangeResponse }> = [];
private earliestMod = new BigNumber(Infinity);
/**
@ -302,7 +302,7 @@ class BasicTransaction {
public put(req: RPC.IPutRequest): Promise<RPC.IPutResponse> {
this.assertNoOption('put', req, ['lease', 'prev_kv']);
this.writeSet.addPut(req);
return Promise.resolve(<any>{});
return Promise.resolve({} as any);
}
/**
@ -312,7 +312,7 @@ class BasicTransaction {
this.assertNoOption('delete', req, ['prev_kv']);
this.writeSet.addDeletion(req);
return Promise.resolve({
header: <any>undefined,
header: undefined as any,
deleted: '1',
prev_kvs: [],
});
@ -329,7 +329,7 @@ class BasicTransaction {
]);
}
protected assertNoOption<T>(req: string, obj: T, keys: (keyof T)[]) {
protected assertNoOption<T>(req: string, obj: T, keys: Array<keyof T>) {
keys.forEach(key => {
if (obj[key] !== undefined) {
throw new Error(`"${key}" is not supported in ${req} requests within STM transactions`);
@ -430,7 +430,7 @@ export class SoftwareTransaction {
case 'deleteRange':
return (req: RPC.IDeleteRangeRequest) => this.tx.deleteRange(req);
default:
throw new ClientRuntimeError(`Unexpected kv operation in STM: ${key}`);
throw new ClientRuntimeError(`Unexpected kv operation in STM: ${key.toString()}`);
}
},
});

Просмотреть файл

@ -155,9 +155,9 @@ export function forOwn<T>(
obj: T,
iterator: <K extends keyof T>(value: T[K], key: K) => void,
): void {
const keys = <(keyof T)[]>Object.keys(obj);
for (let i = 0; i < keys.length; i++) {
iterator(obj[keys[i]], keys[i]);
const keys = Object.keys(obj) as Array<keyof T>;
for (const key of keys) {
iterator(obj[key], key);
}
}
@ -167,7 +167,7 @@ export function forOwn<T>(
*/
export function onceEvent(emitter: EventEmitter, ...events: string[]): Promise<any> {
return new Promise((resolve, reject) => {
const teardown: (() => void)[] = [];
const teardown: Array<() => void> = [];
const handler = (data: any, event: string) => {
teardown.forEach(t => t());
@ -198,7 +198,7 @@ export abstract class PromiseWrap<T> implements PromiseLike<T> {
onFulfilled: (value: T) => R | Promise<R>,
onRejected?: (err: any) => V | Promise<V>,
): Promise<R | V> {
return this.createPromise().then(onFulfilled, <any>onRejected);
return this.createPromise().then(onFulfilled, onRejected as any);
}
/**

Просмотреть файл

@ -64,7 +64,7 @@ class AttachQueue {
throw new ClientRuntimeError('Could not find watcher corresponding to create response');
}
(<{ id: string }>watcher).id = res.watch_id;
(watcher as { id: string }).id = res.watch_id;
watcher.emit('connected', res);
this.readQueue();
}
@ -262,7 +262,7 @@ export class WatchManager {
this.watchers.forEach(watcher => {
watcher.emit('disconnected', err);
(<{ id: null }>watcher).id = null;
(watcher as { id: null }).id = null;
});
setTimeout(() => {
@ -381,7 +381,7 @@ export class WatchBuilder {
/**
* ignore omits certain operation kinds from the watch stream.
*/
public ignore(...operations: (keyof typeof operationNames)[]): this {
public ignore(...operations: Array<keyof typeof operationNames>): this {
this.request.filters = operations.map(op => operationNames[op]);
return this;
}
@ -506,7 +506,7 @@ export class Watcher extends EventEmitter {
/**
* Implements EventEmitter.on(...).
*/
public on(event: string, handler: Function): this {
public on(event: string, handler: (...args: any[]) => void): this {
// tslint:disable-line
return super.on(event, handler);
}
@ -517,7 +517,7 @@ export class Watcher extends EventEmitter {
* connected.
*/
public lastRevision(): number | null {
return <number>this.request.start_revision;
return this.request.start_revision as number;
}
/**

Просмотреть файл

@ -5,4 +5,4 @@ import { SharedPool } from '../src/shared-pool';
chai.use(require('chai-subset')); // tslint:disable-line
chai.use(require('chai-as-promised')); // tslint:disable-line
(<any>SharedPool).deterministicInsertion = true;
(SharedPool as any).deterministicInsertion = true;

Просмотреть файл

@ -30,7 +30,7 @@ describe('lease()', () => {
it('throws if trying to use too short of a ttl, or an undefined ttl', () => {
expect(() => client.lease(0)).to.throw(/must be at least 1 second/);
expect(() => (<any>client.lease)()).to.throw(/must be at least 1 second/);
expect(() => (client.lease as any)()).to.throw(/must be at least 1 second/);
});
it('reports a loss and errors if the client is invalid', async () => {
@ -101,7 +101,7 @@ describe('lease()', () => {
lease = proxiedClient.lease(1);
await lease.grant();
proxy.pause();
(<any>lease).lastKeepAlive = Date.now() - 2000; // speed things up a little
(lease as any).lastKeepAlive = Date.now() - 2000; // speed things up a little
const err = await onceEvent(lease, 'lost');
expect(err.message).to.match(/our lease has expired/);
proxiedClient.close();
@ -132,7 +132,7 @@ describe('lease()', () => {
});
it('emits a loss if the touched key is lost', async () => {
(<any>lease).leaseID = Promise.resolve('123456789');
(lease as any).leaseID = Promise.resolve('123456789');
const lost = onceEvent(lease, 'lost');
try {

Просмотреть файл

@ -1,4 +1,8 @@
--compilers ts:ts-node/register
--timeout 20000
--watch-extensions ts
--require source-map-support/register
--require ts-node/register
--require test/_setup.ts
test/*.test.ts
--timeout 20000
--recursive
--exit
test/**/*.test.ts

Просмотреть файл

@ -14,7 +14,7 @@ import {
} from '../src';
import { createTestClientAndKeys, expectReject, getOptions, tearDownTestClient } from './util';
function wipeAll(things: Promise<{ delete(): any }[]>) {
function wipeAll(things: Promise<Array<{ delete(): any }>>) {
return things.then(items => Promise.all(items.map(item => item.delete())));
}
@ -227,7 +227,7 @@ describe('roles and auth', () => {
},
}),
);
const auth = (<any>authedClient).pool.authenticator;
const auth = (authedClient as any).pool.authenticator;
const badMeta = new grpc.Metadata();
badMeta.add('token', 'lol');
auth.awaitingMetadata = Promise.resolve(badMeta);

Просмотреть файл

@ -69,7 +69,7 @@ describe('shared pool', () => {
});
it('should not back off multiple times if multiple callers fail', async () => {
const getFirstBackoff = (): number => (<any>pool).resources[0].availableAfter;
const getFirstBackoff = (): number => (pool as any).resources[0].availableAfter;
const cnx = await pool.pull();
pool.fail(cnx);
expect(getFirstBackoff()).to.equal(Date.now() + 500);

Просмотреть файл

@ -17,7 +17,7 @@ const [etcdSourceHost, etcdSourcePort] = etcdSourceAddress.split(':');
*/
export class Proxy {
public isActive = false;
public connections: { end(): void }[] = [];
public connections: Array<{ end(): void }> = [];
private server: tls.Server;
private host: string;
private port: number;
@ -159,13 +159,14 @@ export function getOptions(defaults: Partial<IOptions> = {}): IOptions {
* Returns a promise that throws if the promise is resolved or rejected with
* something other than the provided constructor
*/
export function expectReject(promise: Promise<any>, err: { new (message: string): Error }) {
export function expectReject(promise: Promise<any>, err: new (message: string) => Error) {
return promise
.then(() => {
throw new Error('expected to reject');
})
.catch(actualErr => {
if (!(actualErr instanceof err)) {
// tslint:disable-next-line
console.error(actualErr.stack);
expect(actualErr).to.be.an.instanceof(err);
}

Просмотреть файл

@ -19,7 +19,7 @@ describe('watch()', () => {
* Returns the list of watchers currently attached and listening.
*/
function getWatchers(): Watcher[] {
return (<any>client).watchManager.watchers;
return (client as any).watchManager.watchers;
}
/**

Просмотреть файл

@ -1,57 +1,10 @@
{
"extends": "tslint-microsoft-contrib",
"rulesDirectory": [
"node_modules/tslint-microsoft-contrib"
],
"$schema": "http://json.schemastore.org/tslint",
"extends": ["tslint:recommended", "tslint-config-prettier"],
"rules": {
// Basic
"no-multiline-string": false,
"jsdoc-format": true,
"cyclomatic-complexity": [true, 20],
"no-default-export": false,
"typedef": false,
"no-unsafe-any": false,
"no-parameter-properties": false,
"max-classes-per-file": false,
"strict-boolean-expressions": false,
"no-require-imports": false,
"no-var-requires": false,
"newline-before-return": false,
"match-default-export-name": false,
"prefer-for-of": false,
"no-non-null-assertion": false,
"promise-function-async": false,
"no-void-expression": false,
"no-use-before-declare": false,
"object-literal-sort-keys": false,
"unified-signatures": false,
"max-func-body-length": false,
// Prettier-incompatible or prettier-handled rules
"align": false,
"no-single-line-block-comment": false,
"semicolon": false,
"trailing-comma": false,
"space-before-function-paren": false,
"quotemark": false,
// Microsoft
"no-relative-imports": false,
"missing-jsdoc": false,
"chai-vague-errors": false,
"import-name": false,
"export-name": false,
"no-reserved-keywords": false,
"no-any": false,
"no-increment-decrement": false,
"no-backbone-get-set-outside-model": false,
"function-name": [true, {
"method-regex": "^[a-z][\\w\\d]+$",
"private-method-regex": "^[a-z][\\w\\d]+$",
"static-method-regex": "^[a-z][\\w\\d]+$",
"function-regex": "^[a-zA-Z][\\w\\d]+$"
}],
"insecure-random": false,
"variable-name": [true, "ban-keywords", "check-format", "allow-leading-underscore"], // for unused params
"no-string-based-set-timeout": false
"max-classes-per-file": false,
"variable-name": false
}
}