From 3afd1b06909e0c707b1be6488a666a6ab13e7230 Mon Sep 17 00:00:00 2001 From: Teo Gebhard Date: Thu, 11 Mar 2021 19:10:31 +0200 Subject: [PATCH 1/7] StreamrClient properties/methods --- src/Session.ts | 10 +++++----- src/StreamrClient.ts | 35 +++++++++++++++++++++++++---------- 2 files changed, 30 insertions(+), 15 deletions(-) diff --git a/src/Session.ts b/src/Session.ts index ef349071b..8845dfda8 100644 --- a/src/Session.ts +++ b/src/Session.ts @@ -47,21 +47,21 @@ export default class Session extends EventEmitter { if (typeof this.options.privateKey !== 'undefined') { const wallet = new Wallet(this.options.privateKey) this.loginFunction = async () => ( - this._client.loginEndpoints.loginWithChallengeResponse((d: string) => wallet.signMessage(d), wallet.address) + this._client.loginWithChallengeResponse((d: string) => wallet.signMessage(d), wallet.address) ) } else if (typeof this.options.ethereum !== 'undefined') { const provider = new Web3Provider(this.options.ethereum) const signer = provider.getSigner() this.loginFunction = async () => ( - this._client.loginEndpoints.loginWithChallengeResponse((d: string) => signer.signMessage(d), await signer.getAddress()) + this._client.loginWithChallengeResponse((d: string) => signer.signMessage(d), await signer.getAddress()) ) } else if (typeof this.options.apiKey !== 'undefined') { this.loginFunction = async () => ( - this._client.loginEndpoints.loginWithApiKey(this.options.apiKey!) + this._client.loginWithApiKey(this.options.apiKey!) ) } else if (typeof this.options.username !== 'undefined' && typeof this.options.password !== 'undefined') { this.loginFunction = async () => ( - this._client.loginEndpoints.loginWithUsernamePassword(this.options.username!, this.options.password!) + this._client.loginWithUsernamePassword(this.options.username!, this.options.password!) ) } else { if (!this.options.sessionToken) { @@ -128,7 +128,7 @@ export default class Session extends EventEmitter { } this.updateState(State.LOGGING_OUT) - await this._client.loginEndpoints.logoutEndpoint() + await this._client.logoutEndpoint() this.options.sessionToken = undefined this.updateState(State.LOGGED_OUT) } diff --git a/src/StreamrClient.ts b/src/StreamrClient.ts index bcd105fcf..687614d94 100644 --- a/src/StreamrClient.ts +++ b/src/StreamrClient.ts @@ -9,7 +9,7 @@ import StreamrEthereum from './Ethereum' import Session from './Session' import Connection, { ConnectionError } from './Connection' import Publisher from './publish' -import { Subscriber } from './subscribe' +import { Subscriber, Subscription } from './subscribe' import { getUserId } from './user' import { Todo, MaybeAsync, EthereumAddress } from './types' import { StreamEndpoints } from './rest/StreamEndpoints' @@ -141,18 +141,24 @@ export interface StreamrClient extends StreamEndpoints, LoginEndpoints {} // eslint-disable-next-line no-redeclare export class StreamrClient extends EventEmitter { + /** @internal */ id: string + /** @internal */ debug: Debug.Debugger + /** @internal */ options: StrictStreamrClientOptions /** @internal */ session: Session + /** @internal */ connection: StreamrConnection + /** @internal */ publisher: Todo + /** @internal */ subscriber: Subscriber + /** @internal */ cached: StreamrCached + /** @internal */ ethereum: StreamrEthereum - streamEndpoints: StreamEndpoints - loginEndpoints: LoginEndpoints constructor(options: StreamrClientOptions = {}, connection?: StreamrConnection) { super() @@ -189,25 +195,29 @@ export class StreamrClient extends EventEmitter { this.subscriber = new Subscriber(this) this.ethereum = new StreamrEthereum(this) - this.streamEndpoints = Plugin(this, new StreamEndpoints(this)) - this.loginEndpoints = Plugin(this, new LoginEndpoints(this)) + Plugin(this, new StreamEndpoints(this)) + Plugin(this, new LoginEndpoints(this)) this.cached = new StreamrCached(this) } + /** @internal */ async onConnectionConnected() { this.debug('Connected!') this.emit('connected') } + /** @internal */ async onConnectionDisconnected() { this.debug('Disconnected.') this.emit('disconnected') } + /** @internal */ onConnectionError(err: Todo) { this.emit('error', new ConnectionError(err)) } + /** @internal */ getErrorEmitter(source: Todo) { return (err: Todo) => { if (!(err instanceof ConnectionError || err.reason instanceof ConnectionError)) { @@ -219,19 +229,20 @@ export class StreamrClient extends EventEmitter { } } + /** @internal */ _onError(err: Todo, ...args: Todo) { // @ts-expect-error this.onError(err, ...args) } + /** @internal */ async send(request: Todo) { return this.connection.send(request) } /** * Override to control output - */ - + * @internal */ onError(error: Todo) { // eslint-disable-line class-methods-use-this console.error(error) } @@ -256,6 +267,7 @@ export class StreamrClient extends EventEmitter { return this.connection.connect() } + /** @internal */ async nextConnection() { return this.connection.nextConnection() } @@ -297,10 +309,12 @@ export class StreamrClient extends EventEmitter { return getUserId(this) } + /** @internal */ setNextGroupKey(...args: Todo) { return this.publisher.setNextGroupKey(...args) } + /** @internal */ rotateGroupKey(...args: Todo) { return this.publisher.rotateGroupKey(...args) } @@ -340,7 +354,7 @@ export class StreamrClient extends EventEmitter { await this.subscriber.unsubscribe(opts) } - async resend(opts: Todo, onMessage?: OnMessageCallback) { + async resend(opts: Todo, onMessage?: OnMessageCallback): Promise { const task = this.subscriber.resend(opts) if (typeof onMessage !== 'function') { return task @@ -367,11 +381,11 @@ export class StreamrClient extends EventEmitter { return this.connection.enableAutoDisconnect(...args) } - getAddress() { + getAddress(): EthereumAddress { return this.ethereum.getAddress() } - async getPublisherId() { + async getPublisherId(): Promise { return this.getAddress() } @@ -406,6 +420,7 @@ export class StreamrClient extends EventEmitter { return DataUnion._deploy(options, this) // eslint-disable-line no-underscore-dangle } + /** @internal */ _getDataUnionFromName({ dataUnionName, deployerAddress }: { dataUnionName: string, deployerAddress: EthereumAddress}) { return DataUnion._fromName({ // eslint-disable-line no-underscore-dangle dataUnionName, From 8e7e3f1b65da27403bcd9919175e23092b08eef7 Mon Sep 17 00:00:00 2001 From: Teo Gebhard Date: Thu, 11 Mar 2021 19:41:40 +0200 Subject: [PATCH 2/7] DataUnion properties/methods --- src/dataunion/DataUnion.ts | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/src/dataunion/DataUnion.ts b/src/dataunion/DataUnion.ts index 2c92d2b77..6ba6ab0ed 100644 --- a/src/dataunion/DataUnion.ts +++ b/src/dataunion/DataUnion.ts @@ -68,10 +68,11 @@ const log = debug('StreamrClient::DataUnion') export class DataUnion { - contractAddress: EthereumAddress - sidechainAddress: EthereumAddress - client: StreamrClient + private contractAddress: EthereumAddress + private sidechainAddress: EthereumAddress + private client: StreamrClient + /** @internal */ constructor(contractAddress: EthereumAddress, sidechainAddress: EthereumAddress, client: StreamrClient) { // validate and convert to checksum case this.contractAddress = getAddress(contractAddress) @@ -460,6 +461,7 @@ export class DataUnion { * Create a new DataUnionMainnet contract to mainnet with DataUnionFactoryMainnet * This triggers DataUnionSidechain contract creation in sidechain, over the bridge (AMB) * @return that resolves when the new DU is deployed over the bridge to side-chain + * @internal */ static async _deploy(options: DataUnionDeployOptions = {}, client: StreamrClient): Promise { const deployerAddress = client.getAddress() @@ -513,18 +515,21 @@ export class DataUnion { // Internal functions + /** @internal */ static _fromContractAddress(contractAddress: string, client: StreamrClient) { const contracts = new Contracts(client) const sidechainAddress = contracts.getDataUnionSidechainAddress(getAddress(contractAddress)) // throws if bad address return new DataUnion(contractAddress, sidechainAddress, client) } + /** @internal */ static _fromName({ dataUnionName, deployerAddress }: { dataUnionName: string, deployerAddress: string}, client: StreamrClient) { const contracts = new Contracts(client) const contractAddress = contracts.getDataUnionMainnetAddress(dataUnionName, getAddress(deployerAddress)) // throws if bad address return DataUnion._fromContractAddress(contractAddress, client) // eslint-disable-line no-underscore-dangle } + /** @internal */ async _getContract() { const ret = this.getContracts().getMainnetContract(this.contractAddress) // @ts-expect-error From 2ebf37d9ef053fdce45c405956b5ef647345ffc1 Mon Sep 17 00:00:00 2001 From: Teo Gebhard Date: Thu, 11 Mar 2021 20:03:38 +0200 Subject: [PATCH 3/7] Subscription classes to TypeScript --- src/subscribe/{index.js => index.ts} | 133 ++++++++++++++++++--------- 1 file changed, 90 insertions(+), 43 deletions(-) rename src/subscribe/{index.js => index.ts} (85%) diff --git a/src/subscribe/index.js b/src/subscribe/index.ts similarity index 85% rename from src/subscribe/index.js rename to src/subscribe/index.ts index 591e51c32..67f5571c9 100644 --- a/src/subscribe/index.js +++ b/src/subscribe/index.ts @@ -10,9 +10,33 @@ import MessagePipeline from './pipeline' import Validator from './Validator' import messageStream from './messageStream' import resendStream from './resendStream' +import { Todo } from '../types' +import StreamrClient from '..' export class Subscription extends Emitter { - constructor(client, opts, onFinally = () => {}) { + + streamId: string + streamPartition: number + /** @internal */ + client: StreamrClient + /** @internal */ + options: Todo + /** @internal */ + key: Todo + /** @internal */ + id: Todo + /** @internal */ + _onDone: Todo + /** @internal */ + _onFinally: Todo + /** @internal */ + pipeline: Todo + /** @internal */ + msgStream: Todo + /** @internal */ + iterated?: Todo + + constructor(client: StreamrClient, opts: Todo, onFinally = () => {}) { super() this.client = client this.options = validateOptions(opts) @@ -30,9 +54,10 @@ export class Subscription extends Emitter { this.pipeline = opts.pipeline || MessagePipeline(client, { ...this.options, validate, - onError: (err) => { + onError: (err: Todo) => { this.emit('error', err) }, + // @ts-expect-error }, this.onPipelineEnd) this.msgStream = this.pipeline.msgStream @@ -42,7 +67,7 @@ export class Subscription extends Emitter { * Expose cleanup */ - async onPipelineEnd(err) { + async onPipelineEnd(err: Todo) { try { await this._onFinally(err) } finally { @@ -58,8 +83,7 @@ export class Subscription extends Emitter { * Collect all messages into an array. * Returns array when subscription is ended. */ - - async collect(n) { + async collect(n?: Todo) { const msgs = [] for await (const msg of this) { if (n === 0) { @@ -85,19 +109,19 @@ export class Subscription extends Emitter { return this.pipeline } - async cancel(...args) { + async cancel(...args: Todo[]) { return this.pipeline.cancel(...args) } - async return(...args) { + async return(...args: Todo[]) { return this.pipeline.return(...args) } - async throw(...args) { + async throw(...args: Todo[]) { return this.pipeline.throw(...args) } - async unsubscribe(...args) { + async unsubscribe(...args: Todo[]) { return this.cancel(...args) } } @@ -107,9 +131,9 @@ export class Subscription extends Emitter { * Aggregates errors rather than throwing on first. */ -function multiEmit(emitters, ...args) { - let error - emitters.forEach((s) => { +function multiEmit(emitters: Todo, ...args: Todo[]) { + let error: Todo + emitters.forEach((s: Todo) => { try { s.emit(...args) } catch (err) { @@ -128,7 +152,15 @@ function multiEmit(emitters, ...args) { */ class SubscriptionSession extends Emitter { - constructor(client, options) { + + client: StreamrClient + options: Todo + validate: Todo + subscriptions: Set + deletedSubscriptions: Set + step?: Todo + + constructor(client: StreamrClient, options: Todo) { super() this.client = client this.options = validateOptions(options) @@ -229,6 +261,7 @@ class SubscriptionSession extends Emitter { await unsubscribe(this.client, this.options) } } + // @ts-expect-error ], check, { onError(err) { if (err instanceof ConnectionError && !check()) { @@ -241,7 +274,7 @@ class SubscriptionSession extends Emitter { }) } - has(sub) { + has(sub: Todo) { return this.subscriptions.has(sub) } @@ -250,14 +283,14 @@ class SubscriptionSession extends Emitter { * then on self. */ - emit(...args) { + emit(...args: Todo[]) { const subs = this._getSubs() try { multiEmit(subs, ...args) } catch (error) { return super.emit('error', error) } - + // @ts-expect-error return super.emit(...args) } @@ -273,7 +306,7 @@ class SubscriptionSession extends Emitter { * Add subscription & appropriate connection handle. */ - async add(sub) { + async add(sub: Todo) { this.subscriptions.add(sub) const { connection } = this.client await connection.addHandle(`adding${sub.id}`) @@ -289,7 +322,7 @@ class SubscriptionSession extends Emitter { * Remove subscription & appropriate connection handle. */ - async remove(sub) { + async remove(sub: Todo) { this.subscriptions.delete(sub) if (this.deletedSubscriptions.has(sub)) { @@ -328,12 +361,16 @@ class SubscriptionSession extends Emitter { */ class Subscriptions { - constructor(client) { + + client: StreamrClient + subSessions: Map + + constructor(client: StreamrClient) { this.client = client this.subSessions = new Map() } - async add(opts, onFinally = async () => {}) { + async add(opts: Todo, onFinally: Todo = async () => {}) { const options = validateOptions(opts) const { key } = options @@ -345,7 +382,8 @@ class Subscriptions { const sub = new Subscription(this.client, { ...options, validate: subSession.validate, - }, async (err) => { + // @ts-expect-error + }, async (err: Todo) => { try { await this.remove(sub) } finally { @@ -353,6 +391,7 @@ class Subscriptions { } }) + // @ts-expect-error sub.count = () => { // sub.count() gives number of subs on same stream+partition return this.count(sub.options) @@ -375,7 +414,7 @@ class Subscriptions { return sub } - async remove(sub) { + async remove(sub: Todo) { const { key } = sub let cancelTask try { @@ -397,10 +436,9 @@ class Subscriptions { /** * Remove all subscriptions, optionally only those matching options. */ - - async removeAll(options) { + async removeAll(options?: Todo) { const subs = this.get(options) - return allSettledValues(subs.map((sub) => ( + return allSettledValues(subs.map((sub: Todo) => ( this.remove(sub) ))) } @@ -421,7 +459,7 @@ class Subscriptions { * Count all matching subscriptions. */ - count(options) { + count(options: Todo) { if (options === undefined) { return this.countAll() } return this.get(options).length } @@ -441,7 +479,7 @@ class Subscriptions { * Get subscription session for matching sub options. */ - getSubscriptionSession(options) { + getSubscriptionSession(options: Todo) { const { key } = validateOptions(options) return this.subSessions.get(key) } @@ -450,7 +488,7 @@ class Subscriptions { * Get all subscriptions matching options. */ - get(options) { + get(options: Todo) { if (options === undefined) { return this.getAll() } const { key } = validateOptions(options) @@ -465,28 +503,35 @@ class Subscriptions { * Top-level user-facing interface for creating/destroying subscriptions. */ export class Subscriber { - constructor(client) { + + client: StreamrClient + subscriptions: Subscriptions + + constructor(client: StreamrClient) { this.client = client this.subscriptions = new Subscriptions(client) } - getSubscriptionSession(...args) { + getSubscriptionSession(...args: Todo[]) { + // @ts-expect-error return this.subscriptions.getSubscriptionSession(...args) } - getAll(...args) { + getAll(...args: Todo[]) { + // @ts-expect-error return this.subscriptions.getAll(...args) } - count(options) { + count(options: Todo[]) { return this.subscriptions.count(options) } - async subscribe(...args) { + async subscribe(...args: Todo[]) { + // @ts-expect-error return this.subscriptions.add(...args) } - async unsubscribe(options) { + async unsubscribe(options: Todo): Promise { if (options instanceof Subscription) { const sub = options return sub.cancel() @@ -499,7 +544,7 @@ export class Subscriber { return this.subscriptions.removeAll(options) } - async resend(opts) { + async resend(opts: Todo) { const resendMsgStream = resendStream(this.client, opts) const sub = new Subscription(this.client, { @@ -514,7 +559,7 @@ export class Subscriber { return sub } - async resendSubscribe(opts, onMessage) { + async resendSubscribe(opts: Todo, onMessage: Todo) { // This works by passing a custom message stream to a subscription // the custom message stream iterates resends, then iterates realtime const options = validateOptions(opts) @@ -523,7 +568,7 @@ export class Subscriber { const realtimeMessageStream = messageStream(this.client.connection, options) // cancel both streams on end - async function end(optionalErr) { + async function end(optionalErr: Todo) { await Promise.all([ resendMessageStream.cancel(optionalErr), realtimeMessageStream.cancel(optionalErr), @@ -534,15 +579,15 @@ export class Subscriber { } } - let resendSubscribeSub + let resendSubscribeSub: Todo - let lastResentMsgId - let lastProcessedMsgId + let lastResentMsgId: Todo + let lastProcessedMsgId: Todo const resendDone = Defer() let isResendDone = false let resentEmitted = false - function messageIDString(msg) { + function messageIDString(msg: Todo) { return msg.getMessageID().serialize() } @@ -579,14 +624,16 @@ export class Subscriber { } finally { isResendDone = true maybeEmitResend() + // @ts-expect-error resendDone.resolve() } }, - async function* ResendThenRealtime(src) { + async function* ResendThenRealtime(src: Todo) { yield* src await resendDone // ensure realtime doesn't start until resend ends yield* resendSubscribeSub.realtime }, + // @ts-expect-error ], end) const resendTask = resendMessageStream.subscribe() @@ -594,7 +641,7 @@ export class Subscriber { ...options, msgStream: it, afterSteps: [ - async function* detectEndOfResend(src) { + async function* detectEndOfResend(src: Todo) { for await (const msg of src) { const id = messageIDString(msg) try { From b583e69fd9e50e0e030c2fc5d51e8fc0e4af056a Mon Sep 17 00:00:00 2001 From: Teo Gebhard Date: Thu, 11 Mar 2021 20:09:33 +0200 Subject: [PATCH 4/7] Subscription methods --- src/subscribe/index.ts | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/src/subscribe/index.ts b/src/subscribe/index.ts index 67f5571c9..b7ce2e205 100644 --- a/src/subscribe/index.ts +++ b/src/subscribe/index.ts @@ -65,8 +65,8 @@ export class Subscription extends Emitter { /** * Expose cleanup + * @internal */ - async onPipelineEnd(err: Todo) { try { await this._onFinally(err) @@ -75,6 +75,7 @@ export class Subscription extends Emitter { } } + /** @internal */ async onDone() { return this._onDone } @@ -99,6 +100,7 @@ export class Subscription extends Emitter { return msgs } + /** @internal */ [Symbol.asyncIterator]() { // only iterate sub once if (this.iterated) { @@ -109,14 +111,17 @@ export class Subscription extends Emitter { return this.pipeline } + /** @internal */ async cancel(...args: Todo[]) { return this.pipeline.cancel(...args) } + /** @internal */ async return(...args: Todo[]) { return this.pipeline.return(...args) } + /** @internal */ async throw(...args: Todo[]) { return this.pipeline.throw(...args) } From 2a49d436a35f47ba38b3a5e9638e74bf01ee94dd Mon Sep 17 00:00:00 2001 From: Teo Gebhard Date: Thu, 11 Mar 2021 20:15:26 +0200 Subject: [PATCH 5/7] LoginEndpoints and StreamEndpoints --- src/rest/LoginEndpoints.ts | 7 +++++++ src/rest/StreamEndpoints.ts | 5 +++-- 2 files changed, 10 insertions(+), 2 deletions(-) diff --git a/src/rest/LoginEndpoints.ts b/src/rest/LoginEndpoints.ts index 56e38f89d..f67ec19e3 100644 --- a/src/rest/LoginEndpoints.ts +++ b/src/rest/LoginEndpoints.ts @@ -28,12 +28,14 @@ async function getSessionToken(url: string, props: any) { /** TODO the class should be annotated with at-internal, but adding the annotation hides the methods */ export class LoginEndpoints { + /** @internal */ client: StreamrClient constructor(client: StreamrClient) { this.client = client } + /** @internal */ async getChallenge(address: string) { this.client.debug('getChallenge %o', { address, @@ -48,6 +50,7 @@ export class LoginEndpoints { ) } + /** @internal */ async sendChallengeResponse(challenge: { challenge: string }, signature: string, address: string) { this.client.debug('sendChallengeResponse %o', { challenge, @@ -63,6 +66,7 @@ export class LoginEndpoints { return getSessionToken(url, props) } + /** @internal */ async loginWithChallengeResponse(signingFunction: (challenge: string) => Promise, address: string) { this.client.debug('loginWithChallengeResponse %o', { address, @@ -72,6 +76,7 @@ export class LoginEndpoints { return this.sendChallengeResponse(challenge, signature, address) } + /** @internal */ async loginWithApiKey(apiKey: string) { this.client.debug('loginWithApiKey %o', { apiKey, @@ -83,6 +88,7 @@ export class LoginEndpoints { return getSessionToken(url, props) } + /** @internal */ async loginWithUsernamePassword(username: string, password: string) { this.client.debug('loginWithUsernamePassword %o', { username, @@ -110,6 +116,7 @@ export class LoginEndpoints { return authFetch(`${this.client.options.restUrl}/users/me`, this.client.session) } + /** @internal */ async logoutEndpoint(): Promise { this.client.debug('logoutEndpoint') await authFetch(`${this.client.options.restUrl}/logout`, this.client.session, { diff --git a/src/rest/StreamEndpoints.ts b/src/rest/StreamEndpoints.ts index a1b9426f3..7005f47f5 100644 --- a/src/rest/StreamEndpoints.ts +++ b/src/rest/StreamEndpoints.ts @@ -79,6 +79,7 @@ function getKeepAliveAgentForUrl(url: string) { /** TODO the class should be annotated with at-internal, but adding the annotation hides the methods */ export class StreamEndpoints { + /** @internal */ client: StreamrClient constructor(client: StreamrClient) { @@ -171,7 +172,7 @@ export class StreamEndpoints { return json.addresses.map((a: string) => a.toLowerCase()) } - async isStreamPublisher(streamId: string, ethAddress: string) { + async isStreamPublisher(streamId: string, ethAddress: EthereumAddress) { this.client.debug('isStreamPublisher %o', { streamId, ethAddress, @@ -198,7 +199,7 @@ export class StreamEndpoints { return json.addresses.map((a: string) => a.toLowerCase()) } - async isStreamSubscriber(streamId: string, ethAddress: string) { + async isStreamSubscriber(streamId: string, ethAddress: EthereumAddress) { this.client.debug('isStreamSubscriber %o', { streamId, ethAddress, From da355fdafe5efb4fb1aa59442e6b0c9cfbd274c2 Mon Sep 17 00:00:00 2001 From: Teo Gebhard Date: Thu, 11 Mar 2021 20:23:10 +0200 Subject: [PATCH 6/7] Stream and StorageNode --- src/stream/StorageNode.ts | 4 +++- src/stream/index.ts | 7 ++++++- 2 files changed, 9 insertions(+), 2 deletions(-) diff --git a/src/stream/StorageNode.ts b/src/stream/StorageNode.ts index 2e18d5767..ccb89b630 100644 --- a/src/stream/StorageNode.ts +++ b/src/stream/StorageNode.ts @@ -1,7 +1,9 @@ import { EthereumAddress } from '../types' export default class StorageNode { - _address: EthereumAddress + + private _address: EthereumAddress + constructor(address: EthereumAddress) { this._address = address } diff --git a/src/stream/index.ts b/src/stream/index.ts index 9a7496a6c..45c45465c 100644 --- a/src/stream/index.ts +++ b/src/stream/index.ts @@ -70,17 +70,21 @@ function getFieldType(value: any): (Field['type'] | undefined) { } export class Stream { - // TODO add field definitions for all fields // @ts-expect-error id: string // @ts-expect-error name: string + description?: string config: { fields: Field[]; } = { fields: [] } + partitions?: number + /** @internal */ _client: StreamrClient requireEncryptedData?: boolean requireSignedData?: boolean + storageDays?: number + inactivityThresholdHours?: number constructor(client: StreamrClient, props: StreamProperties) { this._client = client @@ -99,6 +103,7 @@ export class Stream { return json ? new Stream(this._client, json) : undefined } + /** @internal */ toObject() { const result = {} Object.keys(this).forEach((key) => { From 07bb14f5ec37a9be2e83c214e5e54a442f90dacc Mon Sep 17 00:00:00 2001 From: Teo Gebhard Date: Thu, 11 Mar 2021 20:32:07 +0200 Subject: [PATCH 7/7] Update tests --- test/integration/LoginEndpoints.test.js | 18 +++++++++--------- test/unit/Session.test.js | 8 +++----- 2 files changed, 12 insertions(+), 14 deletions(-) diff --git a/test/integration/LoginEndpoints.test.js b/test/integration/LoginEndpoints.test.js index 5c1b35c93..ce4f94610 100644 --- a/test/integration/LoginEndpoints.test.js +++ b/test/integration/LoginEndpoints.test.js @@ -27,7 +27,7 @@ describe('LoginEndpoints', () => { describe('Challenge generation', () => { it('should retrieve a challenge', async () => { - const challenge = await client.loginEndpoints.getChallenge('some-address') + const challenge = await client.getChallenge('some-address') assert(challenge) assert(challenge.id) assert(challenge.challenge) @@ -38,7 +38,7 @@ describe('LoginEndpoints', () => { describe('Challenge response', () => { it('should fail to get a session token', async () => { await expect(async () => { - await client.loginEndpoints.sendChallengeResponse({ + await client.sendChallengeResponse({ id: 'some-id', challenge: 'some-challenge', }, 'some-sig', 'some-address') @@ -47,10 +47,10 @@ describe('LoginEndpoints', () => { it('should get a session token', async () => { const wallet = ethers.Wallet.createRandom() - const challenge = await client.loginEndpoints.getChallenge(wallet.address) + const challenge = await client.getChallenge(wallet.address) assert(challenge.challenge) const signature = await wallet.signMessage(challenge.challenge) - const sessionToken = await client.loginEndpoints.sendChallengeResponse(challenge, signature, wallet.address) + const sessionToken = await client.sendChallengeResponse(challenge, signature, wallet.address) assert(sessionToken) assert(sessionToken.token) assert(sessionToken.expires) @@ -58,7 +58,7 @@ describe('LoginEndpoints', () => { it('should get a session token with combined function', async () => { const wallet = ethers.Wallet.createRandom() - const sessionToken = await client.loginEndpoints.loginWithChallengeResponse((d) => wallet.signMessage(d), wallet.address) + const sessionToken = await client.loginWithChallengeResponse((d) => wallet.signMessage(d), wallet.address) assert(sessionToken) assert(sessionToken.token) assert(sessionToken.expires) @@ -73,7 +73,7 @@ describe('LoginEndpoints', () => { }) it('should get a session token', async () => { - const sessionToken = await client.loginEndpoints.loginWithApiKey('tester1-api-key') + const sessionToken = await client.loginWithApiKey('tester1-api-key') assert(sessionToken) assert(sessionToken.token) assert(sessionToken.expires) @@ -83,14 +83,14 @@ describe('LoginEndpoints', () => { describe('Username/password login', () => { it('should fail', async () => { await expect(async () => { - await client.loginEndpoints.loginWithUsernamePassword('username', 'password') + await client.loginWithUsernamePassword('username', 'password') }).rejects.toThrow('no longer supported') }) }) describe('UserInfo', () => { it('should get user info', async () => { - const userInfo = await client.loginEndpoints.getUserInfo() + const userInfo = await client.getUserInfo() assert(userInfo.name) assert(userInfo.username) }) @@ -100,7 +100,7 @@ describe('LoginEndpoints', () => { it('should not be able to use the same session token after logout', async () => { await client.getUserInfo() // first fetches the session token, then requests the endpoint const sessionToken1 = client.session.options.sessionToken - await client.loginEndpoints.logoutEndpoint() // invalidates the session token in engine-and-editor + await client.logoutEndpoint() // invalidates the session token in engine-and-editor await client.getUserInfo() // requests the endpoint with sessionToken1, receives 401, fetches a new session token const sessionToken2 = client.session.options.sessionToken assert.notDeepStrictEqual(sessionToken1, sessionToken2) diff --git a/test/unit/Session.test.js b/test/unit/Session.test.js index b273b79ec..a31a7d40a 100644 --- a/test/unit/Session.test.js +++ b/test/unit/Session.test.js @@ -23,9 +23,7 @@ describe('Session', () => { sessionToken: 'session-token', }, }) - clientSessionToken.loginEndpoints = { - logoutEndpoint: sinon.stub().resolves() - } + clientSessionToken.logoutEndpoint = sinon.stub().resolves() session = new Session(clientSessionToken) session.options.unauthenticated = false @@ -162,7 +160,7 @@ describe('Session', () => { it('should call the logout endpoint', async () => { await session.getSessionToken() await session.logout() - expect(clientSessionToken.loginEndpoints.logoutEndpoint.calledOnce).toBeTruthy() + expect(clientSessionToken.logoutEndpoint.calledOnce).toBeTruthy() }) it('should call the logout endpoint again', async () => { @@ -171,7 +169,7 @@ describe('Session', () => { await session.logout() await session.getSessionToken() await session.logout() - expect(clientSessionToken.loginEndpoints.logoutEndpoint.calledTwice).toBeTruthy() + expect(clientSessionToken.logoutEndpoint.calledTwice).toBeTruthy() }) it('should throw if already logging out', async () => {