Skip to content

Commit

Permalink
Enable Typescript strict mode (#80)
Browse files Browse the repository at this point in the history
  • Loading branch information
t3chguy authored Mar 7, 2023
1 parent 1f378c7 commit a8fc2b9
Show file tree
Hide file tree
Showing 10 changed files with 44 additions and 44 deletions.
20 changes: 10 additions & 10 deletions src/ClientWidgetApi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -158,7 +158,7 @@ export class ClientWidgetApi extends EventEmitter {
|| this.hasCapability(`org.matrix.msc2762.timeline:${roomId}`);
}

public canSendRoomEvent(eventType: string, msgtype: string = null): boolean {
public canSendRoomEvent(eventType: string, msgtype: string | null = null): boolean {
return this.allowedEvents.some(e => e.matchesAsRoomEvent(EventDirection.Send, eventType, msgtype));
}

Expand All @@ -170,7 +170,7 @@ export class ClientWidgetApi extends EventEmitter {
return this.allowedEvents.some(e => e.matchesAsToDeviceEvent(EventDirection.Send, eventType));
}

public canReceiveRoomEvent(eventType: string, msgtype: string = null): boolean {
public canReceiveRoomEvent(eventType: string, msgtype: string | null = null): boolean {
return this.allowedEvents.some(e => e.matchesAsRoomEvent(EventDirection.Receive, eventType, msgtype));
}

Expand Down Expand Up @@ -288,7 +288,7 @@ export class ClientWidgetApi extends EventEmitter {
});
}

const onErr = (e) => {
const onErr = (e: any) => {
console.error("[ClientWidgetApi] Failed to handle navigation: ", e);
return this.transport.reply<IWidgetApiErrorResponseData>(request, {
error: {message: "Error handling navigation"},
Expand Down Expand Up @@ -355,7 +355,7 @@ export class ClientWidgetApi extends EventEmitter {
return replyError("client provided invalid OIDC token for an allowed request");
}
if (update.state === OpenIDRequestState.Blocked) {
update.token = null; // just in case the client did something weird
update.token = undefined; // just in case the client did something weird
}

observer.close();
Expand All @@ -377,7 +377,7 @@ export class ClientWidgetApi extends EventEmitter {
});
}

let askRoomIds: string[] = null; // null denotes current room only
let askRoomIds: string[] | null = null; // null denotes current room only
if (request.data.room_ids) {
askRoomIds = request.data.room_ids as string[];
if (!Array.isArray(askRoomIds)) {
Expand All @@ -397,7 +397,7 @@ export class ClientWidgetApi extends EventEmitter {
let events: Promise<IRoomEvent[]> = Promise.resolve([]);
if (request.data.state_key !== undefined) {
const stateKey = request.data.state_key === true ? undefined : request.data.state_key.toString();
if (!this.canReceiveStateEvent(request.data.type, stateKey)) {
if (!stateKey || !this.canReceiveStateEvent(request.data.type, stateKey)) {
return this.transport.reply<IWidgetApiErrorResponseData>(request, {
error: {message: "Cannot read state events of this type"},
});
Expand Down Expand Up @@ -431,7 +431,7 @@ export class ClientWidgetApi extends EventEmitter {
const isState = request.data.state_key !== null && request.data.state_key !== undefined;
let sendEventPromise: Promise<ISendEventDetails>;
if (isState) {
if (!this.canSendStateEvent(request.data.type, request.data.state_key)) {
if (!this.canSendStateEvent(request.data.type, request.data.state_key!)) {
return this.transport.reply<IWidgetApiErrorResponseData>(request, {
error: {message: "Cannot send state events of this type"},
});
Expand All @@ -444,7 +444,7 @@ export class ClientWidgetApi extends EventEmitter {
request.data.room_id,
);
} else {
const content = request.data.content || {};
const content = request.data.content as { msgtype?: string } || {};
const msgtype = content['msgtype'];
if (!this.canSendRoomEvent(request.data.type, msgtype)) {
return this.transport.reply<IWidgetApiErrorResponseData>(request, {
Expand Down Expand Up @@ -599,7 +599,7 @@ export class ClientWidgetApi extends EventEmitter {
if (e.state_key !== undefined) {
return this.canReceiveStateEvent(e.type, e.state_key);
} else {
return this.canReceiveRoomEvent(e.type, e.content['msgtype']);
return this.canReceiveRoomEvent(e.type, (e.content as { msgtype?: string })['msgtype']);
}
});

Expand Down Expand Up @@ -717,7 +717,7 @@ export class ClientWidgetApi extends EventEmitter {
}
} else {
// message event
if (!this.canReceiveRoomEvent(rawEvent.type, rawEvent.content?.["msgtype"])) {
if (!this.canReceiveRoomEvent(rawEvent.type, (rawEvent.content as { msgtype?: string })?.["msgtype"])) {
return; // no-op
}
}
Expand Down
6 changes: 3 additions & 3 deletions src/WidgetApi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -92,8 +92,8 @@ export class WidgetApi extends EventEmitter {
private capabilitiesFinished = false;
private supportsMSC2974Renegotiate = false;
private requestedCapabilities: Capability[] = [];
private approvedCapabilities: Capability[];
private cachedClientVersions: ApiVersion[];
private approvedCapabilities?: Capability[];
private cachedClientVersions?: ApiVersion[];
private turnServerWatchers = 0;

/**
Expand All @@ -102,7 +102,7 @@ export class WidgetApi extends EventEmitter {
* the API will use the widget ID from the first valid request it receives.
* @param {string} clientOrigin The origin of the client, or null if not known.
*/
public constructor(widgetId: string = null, private clientOrigin: string = null) {
public constructor(widgetId: string | null = null, private clientOrigin: string | null = null) {
super();
if (!window.parent) {
throw new Error("No parent window. This widget doesn't appear to be embedded properly.");
Expand Down
8 changes: 4 additions & 4 deletions src/driver/WidgetDriver.ts
Original file line number Diff line number Diff line change
Expand Up @@ -75,8 +75,8 @@ export abstract class WidgetDriver {
public sendEvent(
eventType: string,
content: unknown,
stateKey: string = null,
roomId: string = null,
stateKey: string | null = null,
roomId: string | null = null,
): Promise<ISendEventDetails> {
return Promise.reject(new Error("Failed to override function"));
}
Expand Down Expand Up @@ -117,7 +117,7 @@ export abstract class WidgetDriver {
eventType: string,
msgtype: string | undefined,
limit: number,
roomIds: string[] = null,
roomIds: string[] | null = null,
): Promise<IRoomEvent[]> {
return Promise.resolve([]);
}
Expand All @@ -141,7 +141,7 @@ export abstract class WidgetDriver {
eventType: string,
stateKey: string | undefined,
limit: number,
roomIds: string[] = null,
roomIds: string[] | null = null,
): Promise<IRoomEvent[]> {
return Promise.resolve([]);
}
Expand Down
3 changes: 3 additions & 0 deletions src/interfaces/IWidgetApiRequest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,4 +31,7 @@ export interface IWidgetApiRequest {
action: WidgetApiAction;
widgetId: string;
data: IWidgetApiRequestData;
// XXX: This is for Scalar support
// TODO: Fix scalar
visible?: any;
}
12 changes: 6 additions & 6 deletions src/models/WidgetEventCapability.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ export class WidgetEventCapability {
return true;
}

public matchesAsRoomEvent(direction: EventDirection, eventType: string, msgtype: string = null): boolean {
public matchesAsRoomEvent(direction: EventDirection, eventType: string, msgtype: string | null = null): boolean {
if (this.kind !== EventKind.Event) return false; // not a room event
if (this.direction !== direction) return false; // direction mismatch
if (this.eventType !== eventType) return false; // event type mismatch
Expand Down Expand Up @@ -124,9 +124,9 @@ export class WidgetEventCapability {
public static findEventCapabilities(capabilities: Iterable<Capability>): WidgetEventCapability[] {
const parsed: WidgetEventCapability[] = [];
for (const cap of capabilities) {
let direction: EventDirection = null;
let eventSegment: string;
let kind: EventKind = null;
let direction: EventDirection | null = null;
let eventSegment: string | undefined;
let kind: EventKind | null = null;

// TODO: Enable support for m.* namespace once the MSCs land.
// https://github.com/matrix-org/matrix-widget-api/issues/22
Expand Down Expand Up @@ -158,14 +158,14 @@ export class WidgetEventCapability {
eventSegment = cap.substring("org.matrix.msc3819.receive.to_device:".length);
}

if (direction === null || kind === null) continue;
if (direction === null || kind === null || eventSegment === undefined) continue;

// The capability uses `#` as a separator between event type and state key/msgtype,
// so we split on that. However, a # is also valid in either one of those so we
// join accordingly.
// Eg: `m.room.message##m.text` is "m.room.message" event with msgtype "#m.text".
const expectingKeyStr = eventSegment.startsWith("m.room.message#") || kind === EventKind.State;
let keyStr: string = null;
let keyStr: string | null = null;
if (eventSegment.includes('#') && expectingKeyStr) {
// Dev note: regex is difficult to write, so instead the rules are manually written
// out. This is probably just as understandable as a boring regex though, so win-win?
Expand Down
2 changes: 1 addition & 1 deletion src/models/WidgetParser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -116,7 +116,7 @@ export class WidgetParser {
// is done against the requirements of the interface because not everyone
// will have an interface to validate against.

const content = stateEvent.content || {};
const content = stateEvent.content as IWidget || {};

// Form our best approximation of a widget with the information we have
const estimatedWidget: IWidget = {
Expand Down
4 changes: 2 additions & 2 deletions src/templating/url-template.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ export function runTemplate(url: string, widget: IWidget, params: ITemplateParam
const pattern = `$${key}`.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string
const rexp = new RegExp(pattern, 'g');

// This is technically not what we're supposed to do for a couple reasons:
// This is technically not what we're supposed to do for a couple of reasons:
// 1. We are assuming that there won't later be a $key match after we replace a variable.
// 2. We are assuming that the variable is in a place where it can be escaped (eg: path or query string).
result = result.replace(rexp, encodeURIComponent(toString(variables[key])));
Expand All @@ -58,5 +58,5 @@ export function toString(a: unknown): string {
if (a === null || a === undefined) {
return `${a}`;
}
return a.toString();
return String(a);
}
10 changes: 5 additions & 5 deletions src/transport/ITransport.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ export interface ITransport extends EventEmitter {
/**
* The widget ID, if known. If not known, null.
*/
readonly widgetId: string;
readonly widgetId: string | null;

/**
* If true, the transport will refuse requests from origins other than the
Expand All @@ -51,7 +51,7 @@ export interface ITransport extends EventEmitter {
* The origin the transport should be replying/sending to. If not known, leave
* null.
*/
targetOrigin: string;
targetOrigin: string | null;

/**
* The number of seconds an outbound request is allowed to take before it
Expand All @@ -62,12 +62,12 @@ export interface ITransport extends EventEmitter {
/**
* Starts the transport for listening
*/
start();
start(): void;

/**
* Stops the transport. It cannot be re-started.
*/
stop();
stop(): void;

/**
* Sends a request to the remote end.
Expand Down Expand Up @@ -100,5 +100,5 @@ export interface ITransport extends EventEmitter {
* @param {IWidgetApiRequest} request The request to reply to.
* @param {IWidgetApiResponseData} responseData The response data to reply with.
*/
reply<T extends IWidgetApiResponseData>(request: IWidgetApiRequest, responseData: T);
reply<T extends IWidgetApiResponseData>(request: IWidgetApiRequest, responseData: T): void;
}
19 changes: 8 additions & 11 deletions src/transport/PostmessageTransport.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,26 +39,26 @@ interface IOutboundRequest {
* Transport for the Widget API over postMessage.
*/
export class PostmessageTransport extends EventEmitter implements ITransport {
public strictOriginCheck: boolean;
public targetOrigin: string;
public strictOriginCheck = false;
public targetOrigin = "*";
public timeoutSeconds = 10;

private _ready = false;
private _widgetId = null;
private outboundRequests = new Map<string, IOutboundRequest>();
private _widgetId: string | null = null;
private outboundRequests = new Map<string, IOutboundRequest | null>();
private stopController = new AbortController();

public get ready(): boolean {
return this._ready;
}

public get widgetId(): string {
public get widgetId(): string | null {
return this._widgetId || null;
}

public constructor(
private sendDirection: WidgetApiDirection,
private initialWidgetId: string,
private initialWidgetId: string | null,
private transportWindow: Window,
private inboundWindow: Window,
) {
Expand All @@ -81,9 +81,8 @@ export class PostmessageTransport extends EventEmitter implements ITransport {
}

private sendInternal(message: IWidgetApiRequest | IWidgetApiResponse) {
const targetOrigin = this.targetOrigin || '*';
console.log(`[PostmessageTransport] Sending object to ${targetOrigin}: `, message);
this.transportWindow.postMessage(message, targetOrigin);
console.log(`[PostmessageTransport] Sending object to ${this.targetOrigin}: `, message);
this.transportWindow.postMessage(message, this.targetOrigin);
}

public reply<T extends IWidgetApiResponseData>(request: IWidgetApiRequest, responseData: T) {
Expand Down Expand Up @@ -113,8 +112,6 @@ export class PostmessageTransport extends EventEmitter implements ITransport {
data: data,
};
if (action === WidgetApiToWidgetAction.UpdateVisibility) {
// XXX: This is for Scalar support
// TODO: Fix scalar
request['visible'] = data['visible'];
}
return new Promise<R>((prResolve, prReject) => {
Expand Down
4 changes: 2 additions & 2 deletions tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,15 +6,15 @@
"module": "commonjs",
"moduleResolution": "node",
"target": "es2016",
"noImplicitAny": false,
"sourceMap": true,
"outDir": "./lib",
"declaration": true,
"types": ["jest"],
"lib": [
"es2020",
"dom"
]
],
"strict": true
},
"include": [
"./src/**/*.ts"
Expand Down

0 comments on commit a8fc2b9

Please sign in to comment.