Skip to content

Commit 8863e42

Browse files
authored
More typescript linting (#3310)
* More typescript linting * Improve types Signed-off-by: Michael Telatynski <[email protected]> * Discard changes to src/models/MSC3089TreeSpace.ts * Discard changes to src/realtime-callbacks.ts * Fix tests Signed-off-by: Michael Telatynski <[email protected]> * Improve coverage Signed-off-by: Michael Telatynski <[email protected]> --------- Signed-off-by: Michael Telatynski <[email protected]>
1 parent bc52469 commit 8863e42

17 files changed

+58
-47
lines changed

.eslintrc.cjs

+1
Original file line numberDiff line numberDiff line change
@@ -138,6 +138,7 @@ module.exports = {
138138
tryExtensions: [".ts"],
139139
},
140140
],
141+
"no-extra-boolean-cast": "error",
141142
},
142143
},
143144
{

spec/integ/matrix-client-methods.spec.ts

+22
Original file line numberDiff line numberDiff line change
@@ -1915,6 +1915,28 @@ describe("MatrixClient", function () {
19151915
return prom;
19161916
});
19171917
});
1918+
1919+
describe("getDomain", () => {
1920+
it("should return null if no userId is set", () => {
1921+
const client = new MatrixClient({ baseUrl: "http://localhost" });
1922+
expect(client.getDomain()).toBeNull();
1923+
});
1924+
1925+
it("should return the domain of the userId", () => {
1926+
expect(client.getDomain()).toBe("localhost");
1927+
});
1928+
});
1929+
1930+
describe("getUserIdLocalpart", () => {
1931+
it("should return null if no userId is set", () => {
1932+
const client = new MatrixClient({ baseUrl: "http://localhost" });
1933+
expect(client.getUserIdLocalpart()).toBeNull();
1934+
});
1935+
1936+
it("should return the localpart of the userId", () => {
1937+
expect(client.getUserIdLocalpart()).toBe("alice");
1938+
});
1939+
});
19181940
});
19191941

19201942
function withThreadId(event: MatrixEvent, newThreadId: string): MatrixEvent {

spec/test-utils/webrtc.ts

+3
Original file line numberDiff line numberDiff line change
@@ -481,6 +481,9 @@ export class MockCallMatrixClient extends TypedEventEmitter<EmittedEvents, Emitt
481481
public getUserId(): string {
482482
return this.userId;
483483
}
484+
public getSafeUserId(): string {
485+
return this.userId;
486+
}
484487

485488
public getDeviceId(): string {
486489
return this.deviceId;

spec/unit/webrtc/groupCall.spec.ts

+1-1
Original file line numberDiff line numberDiff line change
@@ -1430,7 +1430,7 @@ describe("Group Call", function () {
14301430
let client: MatrixClient;
14311431

14321432
beforeEach(() => {
1433-
client = new MatrixClient({ baseUrl: "base_url" });
1433+
client = new MatrixClient({ baseUrl: "base_url", userId: "my_user_id" });
14341434

14351435
jest.spyOn(client, "sendStateEvent").mockResolvedValue({} as any);
14361436
});

src/@types/global.d.ts

+1-1
Original file line numberDiff line numberDiff line change
@@ -65,6 +65,6 @@ declare global {
6565
interface Navigator {
6666
// We check for the webkit-prefixed getUserMedia to detect if we're
6767
// on webkit: we should check if we still need to do this
68-
webkitGetUserMedia: DummyInterfaceWeShouldntBeUsingThis;
68+
webkitGetUserMedia?: DummyInterfaceWeShouldntBeUsingThis;
6969
}
7070
}

src/autodiscovery.ts

+1-1
Original file line numberDiff line numberDiff line change
@@ -130,7 +130,7 @@ export class AutoDiscovery {
130130
* configuration, which may include error states. Rejects on unexpected
131131
* failure, not when verification fails.
132132
*/
133-
public static async fromDiscoveryConfig(wellknown: IClientWellKnown): Promise<ClientConfig> {
133+
public static async fromDiscoveryConfig(wellknown?: IClientWellKnown): Promise<ClientConfig> {
134134
// Step 1 is to get the config, which is provided to us here.
135135

136136
// We default to an error state to make the first few checks easier to

src/client.ts

+4-10
Original file line numberDiff line numberDiff line change
@@ -1832,10 +1832,7 @@ export class MatrixClient extends TypedEventEmitter<EmittedEvents, ClientEventHa
18321832
* @returns MXID for the logged-in user, or null if not logged in
18331833
*/
18341834
public getUserId(): string | null {
1835-
if (this.credentials && this.credentials.userId) {
1836-
return this.credentials.userId;
1837-
}
1838-
return null;
1835+
return this.credentials?.userId ?? null;
18391836
}
18401837

18411838
/**
@@ -1857,7 +1854,7 @@ export class MatrixClient extends TypedEventEmitter<EmittedEvents, ClientEventHa
18571854
* @returns Domain of this MXID
18581855
*/
18591856
public getDomain(): string | null {
1860-
if (this.credentials && this.credentials.userId) {
1857+
if (this.credentials?.userId) {
18611858
return this.credentials.userId.replace(/^.*?:/, "");
18621859
}
18631860
return null;
@@ -1868,10 +1865,7 @@ export class MatrixClient extends TypedEventEmitter<EmittedEvents, ClientEventHa
18681865
* @returns The user ID localpart or null.
18691866
*/
18701867
public getUserIdLocalpart(): string | null {
1871-
if (this.credentials && this.credentials.userId) {
1872-
return this.credentials.userId.split(":")[0].substring(1);
1873-
}
1874-
return null;
1868+
return this.credentials?.userId?.split(":")[0].substring(1) ?? null;
18751869
}
18761870

18771871
/**
@@ -4313,7 +4307,7 @@ export class MatrixClient extends TypedEventEmitter<EmittedEvents, ClientEventHa
43134307
*/
43144308
public getIgnoredUsers(): string[] {
43154309
const event = this.getAccountData("m.ignored_user_list");
4316-
if (!event || !event.getContent() || !event.getContent()["ignored_users"]) return [];
4310+
if (!event?.getContent()["ignored_users"]) return [];
43174311
return Object.keys(event.getContent()["ignored_users"]);
43184312
}
43194313

src/crypto/EncryptionSetup.ts

+1-1
Original file line numberDiff line numberDiff line change
@@ -106,7 +106,7 @@ export class EncryptionSetupBuilder {
106106
if (!this.keySignatures) {
107107
this.keySignatures = {};
108108
}
109-
const userSignatures = this.keySignatures[userId] || {};
109+
const userSignatures = this.keySignatures[userId] ?? {};
110110
this.keySignatures[userId] = userSignatures;
111111
userSignatures[deviceId] = signature;
112112
}

src/crypto/dehydration.ts

+3-3
Original file line numberDiff line numberDiff line change
@@ -27,8 +27,8 @@ import decryptAESSecretStorageItem from "../utils/decryptAESSecretStorageItem.ts
2727
import encryptAESSecretStorageItem from "../utils/encryptAESSecretStorageItem.ts";
2828

2929
export interface IDehydratedDevice {
30-
device_id: string; // eslint-disable-line camelcase
31-
device_data: SecretStorageKeyDescription & {
30+
device_id?: string; // eslint-disable-line camelcase
31+
device_data?: SecretStorageKeyDescription & {
3232
// eslint-disable-line camelcase
3333
algorithm: string;
3434
account: string; // pickle
@@ -90,7 +90,7 @@ export class DehydrationManager {
9090
}
9191

9292
public async setKey(
93-
key: Uint8Array,
93+
key?: Uint8Array,
9494
keyInfo: { [props: string]: any } = {},
9595
deviceDisplayName?: string,
9696
): Promise<boolean | undefined> {

src/crypto/store/localStorage-crypto-store.ts

+2-2
Original file line numberDiff line numberDiff line change
@@ -162,15 +162,15 @@ export class LocalStorageCryptoStore extends MemoryCryptoStore implements Crypto
162162
func: (session: ISessionInfo) => void,
163163
): void {
164164
const sessions = this._getEndToEndSessions(deviceKey);
165-
func(sessions[sessionId] || {});
165+
func(sessions[sessionId] ?? {});
166166
}
167167

168168
public getEndToEndSessions(
169169
deviceKey: string,
170170
txn: unknown,
171171
func: (sessions: { [sessionId: string]: ISessionInfo }) => void,
172172
): void {
173-
func(this._getEndToEndSessions(deviceKey) || {});
173+
func(this._getEndToEndSessions(deviceKey) ?? {});
174174
}
175175

176176
public getAllEndToEndSessions(txn: unknown, func: (session: ISessionInfo) => void): void {

src/models/event.ts

+4-4
Original file line numberDiff line numberDiff line change
@@ -559,9 +559,9 @@ export class MatrixEvent extends TypedEventEmitter<MatrixEventEmittedEvents, Mat
559559
return {} as T;
560560
}
561561
if (this.clearEvent) {
562-
return (this.clearEvent.content || {}) as T;
562+
return (this.clearEvent.content ?? {}) as T;
563563
}
564-
return (this.event.content || {}) as T;
564+
return (this.event.content ?? {}) as T;
565565
}
566566

567567
/**
@@ -575,7 +575,7 @@ export class MatrixEvent extends TypedEventEmitter<MatrixEventEmittedEvents, Mat
575575
if (this._localRedactionEvent) {
576576
return {} as T;
577577
} else if (this._replacingEvent) {
578-
return this._replacingEvent.getContent()["m.new_content"] || {};
578+
return this._replacingEvent.getContent()["m.new_content"] ?? {};
579579
} else {
580580
return this.getOriginalContent();
581581
}
@@ -1633,7 +1633,7 @@ export class MatrixEvent extends TypedEventEmitter<MatrixEventEmittedEvents, Mat
16331633
* @param otherEvent - The other event to check against.
16341634
* @returns True if the events are the same, false otherwise.
16351635
*/
1636-
public isEquivalentTo(otherEvent: MatrixEvent): boolean {
1636+
public isEquivalentTo(otherEvent?: MatrixEvent): boolean {
16371637
if (!otherEvent) return false;
16381638
if (otherEvent === this) return true;
16391639
const myProps = deepSortedObjectEntries(this.event);

src/sliding-sync.ts

+6-6
Original file line numberDiff line numberDiff line change
@@ -196,8 +196,8 @@ class SlidingList {
196196
* @param list - The new list parameters
197197
*/
198198
public replaceList(list: MSC3575List): void {
199-
list.filters = list.filters || {};
200-
list.ranges = list.ranges || [];
199+
list.filters = list.filters ?? {};
200+
list.ranges = list.ranges ?? [];
201201
this.list = JSON.parse(JSON.stringify(list));
202202
this.isModified = true;
203203

@@ -894,9 +894,9 @@ export class SlidingSync extends TypedEventEmitter<SlidingSyncEvent, SlidingSync
894894
l.setModified(false);
895895
});
896896
// set default empty values so we don't need to null check
897-
resp.lists = resp.lists || {};
898-
resp.rooms = resp.rooms || {};
899-
resp.extensions = resp.extensions || {};
897+
resp.lists = resp.lists ?? {};
898+
resp.rooms = resp.rooms ?? {};
899+
resp.extensions = resp.extensions ?? {};
900900
Object.keys(resp.lists).forEach((key: string) => {
901901
const list = this.lists.get(key);
902902
if (!list || !resp) {
@@ -934,7 +934,7 @@ export class SlidingSync extends TypedEventEmitter<SlidingSyncEvent, SlidingSync
934934
const listKeysWithUpdates: Set<string> = new Set();
935935
if (!doNotUpdateList) {
936936
for (const [key, list] of Object.entries(resp.lists)) {
937-
list.ops = list.ops || [];
937+
list.ops = list.ops ?? [];
938938
if (list.ops.length > 0) {
939939
listKeysWithUpdates.add(key);
940940
}

src/store/indexeddb.ts

+1-1
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,7 @@ const WRITE_DELAY_MS = 1000 * 60 * 5; // once every 5 minutes
4242

4343
interface IOpts extends IBaseOpts {
4444
/** The Indexed DB interface e.g. `window.indexedDB` */
45-
indexedDB: IDBFactory;
45+
indexedDB?: IDBFactory;
4646
/** Optional database name. The same name must be used to open the same database. */
4747
dbName?: string;
4848
/** Optional factory to spin up a Worker to execute the IDB transactions within. */

src/webrtc/call.ts

+3-3
Original file line numberDiff line numberDiff line change
@@ -3016,9 +3016,9 @@ export function supportsMatrixCall(): boolean {
30163016
// is that the browser throwing a SecurityError will brick the client creation process.
30173017
try {
30183018
const supported = Boolean(
3019-
window.RTCPeerConnection ||
3020-
window.RTCSessionDescription ||
3021-
window.RTCIceCandidate ||
3019+
window.RTCPeerConnection ??
3020+
window.RTCSessionDescription ??
3021+
window.RTCIceCandidate ??
30223022
navigator.mediaDevices,
30233023
);
30243024
if (!supported) {

src/webrtc/groupCall.ts

+1-1
Original file line numberDiff line numberDiff line change
@@ -1445,7 +1445,7 @@ export class GroupCall extends TypedEventEmitter<
14451445
* Recalculates and updates the participant map to match the room state.
14461446
*/
14471447
private updateParticipants(): void {
1448-
const localMember = this.room.getMember(this.client.getUserId()!)!;
1448+
const localMember = this.room.getMember(this.client.getSafeUserId());
14491449
if (!localMember) {
14501450
// The client hasn't fetched enough of the room state to get our own member
14511451
// event. This probably shouldn't happen, but sanity check & exit for now.

src/webrtc/stats/callFeedStatsReporter.ts

+2-5
Original file line numberDiff line numberDiff line change
@@ -49,8 +49,8 @@ export class CallFeedStatsReporter {
4949
return {
5050
id: track.id,
5151
kind: track.kind,
52-
settingDeviceId: settingDeviceId ? settingDeviceId : "unknown",
53-
constrainDeviceId: constrainDeviceId ? constrainDeviceId : "unknown",
52+
settingDeviceId: settingDeviceId ?? "unknown",
53+
constrainDeviceId: constrainDeviceId ?? "unknown",
5454
muted: track.muted,
5555
enabled: track.enabled,
5656
readyState: track.readyState,
@@ -63,9 +63,6 @@ export class CallFeedStatsReporter {
6363
callFeeds: CallFeed[],
6464
prefix = "unknown",
6565
): CallFeedReport {
66-
if (!report.callFeeds) {
67-
report.callFeeds = [];
68-
}
6966
callFeeds.forEach((feed) => {
7067
const audioTracks = feed.stream.getAudioTracks();
7168
const videoTracks = feed.stream.getVideoTracks();

src/webrtc/stats/media/mediaTrackHandler.ts

+2-8
Original file line numberDiff line numberDiff line change
@@ -49,18 +49,12 @@ export class MediaTrackHandler {
4949

5050
public getLocalTrackIdByMid(mid: string): string | undefined {
5151
const transceiver = this.pc.getTransceivers().find((t) => t.mid === mid);
52-
if (transceiver !== undefined && !!transceiver.sender && !!transceiver.sender.track) {
53-
return transceiver.sender.track.id;
54-
}
55-
return undefined;
52+
return transceiver?.sender?.track?.id;
5653
}
5754

5855
public getRemoteTrackIdByMid(mid: string): string | undefined {
5956
const transceiver = this.pc.getTransceivers().find((t) => t.mid === mid);
60-
if (transceiver !== undefined && !!transceiver.receiver && !!transceiver.receiver.track) {
61-
return transceiver.receiver.track.id;
62-
}
63-
return undefined;
57+
return transceiver?.receiver?.track?.id;
6458
}
6559

6660
public getActiveSimulcastStreams(): number {

0 commit comments

Comments
 (0)