From f6a169b5a5f3e5d43380cf78eadc9c01b0809112 Mon Sep 17 00:00:00 2001 From: Will Hunt Date: Fri, 1 Nov 2024 09:15:21 +0000 Subject: [PATCH] Replace usages of `global` with `globalThis` (#4489) * Update src with globalThis * Update spec with globalThis * Replace in more spec/ places * More changes to src/ * Add a linter rule for global * Prettify * lint --- .eslintrc.cjs | 4 ++ spec/TestClient.ts | 2 +- spec/integ/crypto/crypto.spec.ts | 14 +++---- spec/integ/crypto/olm-utils.ts | 8 ++-- spec/integ/crypto/verification.spec.ts | 6 +-- spec/integ/devicelist-integ.spec.ts | 2 +- spec/integ/matrix-client-opts.spec.ts | 4 +- spec/integ/matrix-client-syncing.spec.ts | 6 +-- .../rendezvous/MSC4108SignInWithQR.spec.ts | 4 +- spec/test-utils/test-utils.ts | 2 +- spec/test-utils/webrtc.ts | 12 +++--- spec/unit/autodiscovery.spec.ts | 4 +- spec/unit/base64.spec.ts | 8 ++-- spec/unit/content-helpers.spec.ts | 4 +- spec/unit/crypto.spec.ts | 2 +- spec/unit/crypto/CrossSigningInfo.spec.ts | 8 ++-- spec/unit/crypto/algorithms/megolm.spec.ts | 6 +-- spec/unit/crypto/algorithms/olm.spec.ts | 4 +- spec/unit/crypto/backup.spec.ts | 10 ++--- spec/unit/crypto/cross-signing.spec.ts | 38 +++++++++---------- spec/unit/crypto/crypto-utils.ts | 2 +- spec/unit/crypto/dehydration.spec.ts | 6 +-- .../crypto/outgoing-room-key-requests.spec.ts | 2 +- spec/unit/crypto/secrets.spec.ts | 8 ++-- spec/unit/crypto/store/CryptoStore.spec.ts | 2 +- .../crypto/store/IndexedDBCryptoStore.spec.ts | 14 +++---- spec/unit/crypto/verification/qr_code.spec.ts | 4 +- spec/unit/crypto/verification/request.spec.ts | 4 +- spec/unit/crypto/verification/sas.spec.ts | 4 +- .../verification/secret_request.spec.ts | 2 +- spec/unit/digest.spec.ts | 6 +-- spec/unit/http-api/errors.spec.ts | 2 +- spec/unit/http-api/fetch.spec.ts | 6 +-- spec/unit/http-api/index.spec.ts | 6 +-- spec/unit/models/beacon.spec.ts | 6 +-- spec/unit/oidc/authorize.spec.ts | 2 +- spec/unit/pusher.spec.ts | 2 +- spec/unit/queueToDevice.spec.ts | 4 +- spec/unit/read-receipt.spec.ts | 2 +- spec/unit/realtime-callbacks.spec.ts | 4 +- .../OutgoingRequestProcessor.spec.ts | 2 +- spec/unit/sync-accumulator.spec.ts | 6 +-- spec/unit/webrtc/call.spec.ts | 36 +++++++++--------- spec/unit/webrtc/mediaHandler.spec.ts | 2 +- spec/unit/webrtc/stats/groupCallStats.spec.ts | 8 ++-- src/@types/global.d.ts | 4 +- src/autodiscovery.ts | 8 ++-- src/client.ts | 16 ++++---- src/crypto/CrossSigning.ts | 8 ++-- src/crypto/OlmDevice.ts | 22 +++++------ src/crypto/backup.ts | 10 ++--- src/crypto/dehydration.ts | 12 +++--- src/crypto/index.ts | 8 ++-- src/crypto/olmlib.ts | 4 +- src/crypto/store/indexeddb-crypto-store.ts | 2 +- src/crypto/verification/SAS.ts | 8 ++-- src/http-api/fetch.ts | 4 +- src/http-api/index.ts | 6 +-- src/http-api/interface.ts | 2 +- src/index.ts | 4 +- src/matrix.ts | 2 +- src/realtime-callbacks.ts | 10 ++--- .../transports/MSC4108RendezvousSession.ts | 12 +++--- src/sync.ts | 10 ++--- 64 files changed, 224 insertions(+), 218 deletions(-) diff --git a/.eslintrc.cjs b/.eslintrc.cjs index 036f51f757b..50ca8d622e7 100644 --- a/.eslintrc.cjs +++ b/.eslintrc.cjs @@ -63,6 +63,10 @@ module.exports = { name: "setImmediate", message: "Use setTimeout instead.", }, + { + name: "global", + message: "Use globalThis instead.", + }, ], "import/no-restricted-paths": [ diff --git a/spec/TestClient.ts b/spec/TestClient.ts index 7d23cadfffa..66c63064e4d 100644 --- a/spec/TestClient.ts +++ b/spec/TestClient.ts @@ -66,7 +66,7 @@ export class TestClient implements IE2EKeyReceiver, ISyncResponder { userId: userId, accessToken: accessToken, deviceId: deviceId, - fetchFn: this.httpBackend.fetchFn as typeof global.fetch, + fetchFn: this.httpBackend.fetchFn as typeof globalThis.fetch, ...options, }; if (!fullOptions.cryptoStore) { diff --git a/spec/integ/crypto/crypto.spec.ts b/spec/integ/crypto/crypto.spec.ts index 3d62413c33f..613769e4968 100644 --- a/spec/integ/crypto/crypto.spec.ts +++ b/spec/integ/crypto/crypto.spec.ts @@ -136,7 +136,7 @@ async function expectSendRoomKey( recipientOlmAccount: Olm.Account, recipientOlmSession: Olm.Session | null = null, ): Promise { - const Olm = global.Olm; + const Olm = globalThis.Olm; const testRecipientKey = JSON.parse(recipientOlmAccount.identity_keys())["curve25519"]; function onSendRoomKey(content: any): Olm.InboundGroupSession { @@ -219,7 +219,7 @@ async function expectSendMegolmMessage( } describe.each(Object.entries(CRYPTO_BACKENDS))("crypto (%s)", (backend: string, initCrypto: InitCrypto) => { - if (!global.Olm) { + if (!globalThis.Olm) { // currently we use libolm to implement the crypto in the tests, so need it to be present. logger.warn("not running megolm tests: Olm not present"); return; @@ -230,7 +230,7 @@ describe.each(Object.entries(CRYPTO_BACKENDS))("crypto (%s)", (backend: string, const oldBackendOnly = backend === "rust-sdk" ? test.skip : test; const newBackendOnly = backend !== "rust-sdk" ? test.skip : test; - const Olm = global.Olm; + const Olm = globalThis.Olm; let testOlmAccount = {} as unknown as Olm.Account; let testSenderKey = ""; @@ -1897,13 +1897,13 @@ describe.each(Object.entries(CRYPTO_BACKENDS))("crypto (%s)", (backend: string, const aliceOtks = await keyReceiver.awaitOneTimeKeyUpload(); const aliceOtkId = Object.keys(aliceOtks)[0]; const aliceOtk = aliceOtks[aliceOtkId]; - const p2pSession = new global.Olm.Session(); + const p2pSession = new globalThis.Olm.Session(); await beccaTestClient.client.crypto!.cryptoStore.doTxn( "readonly", [IndexedDBCryptoStore.STORE_ACCOUNT], (txn) => { beccaTestClient.client.crypto!.cryptoStore.getAccount(txn, (pickledAccount: string | null) => { - const account = new global.Olm.Account(); + const account = new globalThis.Olm.Account(); try { account.unpickle(beccaTestClient.client.crypto!.olmDevice.pickleKey, pickledAccount!); p2pSession.create_outbound(account, keyReceiver.getDeviceKey(), aliceOtk.key); @@ -2045,13 +2045,13 @@ describe.each(Object.entries(CRYPTO_BACKENDS))("crypto (%s)", (backend: string, const aliceOtks = await keyReceiver.awaitOneTimeKeyUpload(); const aliceOtkId = Object.keys(aliceOtks)[0]; const aliceOtk = aliceOtks[aliceOtkId]; - const p2pSession = new global.Olm.Session(); + const p2pSession = new globalThis.Olm.Session(); await beccaTestClient.client.crypto!.cryptoStore.doTxn( "readonly", [IndexedDBCryptoStore.STORE_ACCOUNT], (txn) => { beccaTestClient.client.crypto!.cryptoStore.getAccount(txn, (pickledAccount: string | null) => { - const account = new global.Olm.Account(); + const account = new globalThis.Olm.Account(); try { account.unpickle(beccaTestClient.client.crypto!.olmDevice.pickleKey, pickledAccount!); p2pSession.create_outbound(account, keyReceiver.getDeviceKey(), aliceOtk.key); diff --git a/spec/integ/crypto/olm-utils.ts b/spec/integ/crypto/olm-utils.ts index 3f8144fff5f..a257ea7c985 100644 --- a/spec/integ/crypto/olm-utils.ts +++ b/spec/integ/crypto/olm-utils.ts @@ -85,15 +85,15 @@ export function bootstrapCrossSigningTestOlmAccount( deviceId: string, keyBackupInfo: KeyBackupInfo[] = [], ): Partial { - const olmAliceMSK = new global.Olm.PkSigning(); + const olmAliceMSK = new globalThis.Olm.PkSigning(); const masterPrivkey = olmAliceMSK.generate_seed(); const masterPubkey = olmAliceMSK.init_with_seed(masterPrivkey); - const olmAliceUSK = new global.Olm.PkSigning(); + const olmAliceUSK = new globalThis.Olm.PkSigning(); const userPrivkey = olmAliceUSK.generate_seed(); const userPubkey = olmAliceUSK.init_with_seed(userPrivkey); - const olmAliceSSK = new global.Olm.PkSigning(); + const olmAliceSSK = new globalThis.Olm.PkSigning(); const sskPrivkey = olmAliceSSK.generate_seed(); const sskPubkey = olmAliceSSK.init_with_seed(sskPrivkey); @@ -181,7 +181,7 @@ export async function createOlmSession( const otkId = Object.keys(keys)[0]; const otk = keys[otkId]; - const session = new global.Olm.Session(); + const session = new globalThis.Olm.Session(); session.create_outbound(olmAccount, recipientTestClient.getDeviceKey(), otk.key); return session; } diff --git a/spec/integ/crypto/verification.spec.ts b/spec/integ/crypto/verification.spec.ts index 763de044ad6..a9f9ba522e7 100644 --- a/spec/integ/crypto/verification.spec.ts +++ b/spec/integ/crypto/verification.spec.ts @@ -90,7 +90,7 @@ jest.useFakeTimers({ doNotFake: ["queueMicrotask"] }); beforeAll(async () => { // we use the libolm primitives in the test, so init the Olm library - await global.Olm.init(); + await globalThis.Olm.init(); }); // load the rust library. This can take a few seconds on a slow GH worker. @@ -264,7 +264,7 @@ describe.each(Object.entries(CRYPTO_BACKENDS))("verification (%s)", (backend: st // The dummy device makes up a curve25519 keypair and sends the public bit back in an `m.key.verification.key' // We use the Curve25519, HMAC and HKDF implementations in libolm, for now - const olmSAS = new global.Olm.SAS(); + const olmSAS = new globalThis.Olm.SAS(); returnToDeviceMessageFromSync(buildSasKeyMessage(transactionId, olmSAS.get_pubkey())); // alice responds with a 'key' ... @@ -358,7 +358,7 @@ describe.each(Object.entries(CRYPTO_BACKENDS))("verification (%s)", (backend: st // The dummy device makes up a curve25519 keypair and uses the hash in an 'm.key.verification.accept' // We use the Curve25519, HMAC and HKDF implementations in libolm, for now - const olmSAS = new global.Olm.SAS(); + const olmSAS = new globalThis.Olm.SAS(); const commitmentStr = olmSAS.get_pubkey() + anotherjson.stringify(toDeviceMessage); sendToDevicePromise = expectSendToDeviceMessage("m.key.verification.key"); diff --git a/spec/integ/devicelist-integ.spec.ts b/spec/integ/devicelist-integ.spec.ts index bf29242dd24..88388fdf9f7 100644 --- a/spec/integ/devicelist-integ.spec.ts +++ b/spec/integ/devicelist-integ.spec.ts @@ -67,7 +67,7 @@ function getSyncResponse(roomMembers: string[]) { } describe("DeviceList management:", function () { - if (!global.Olm) { + if (!globalThis.Olm) { logger.warn("not running deviceList tests: Olm not present"); return; } diff --git a/spec/integ/matrix-client-opts.spec.ts b/spec/integ/matrix-client-opts.spec.ts index 75edf1c50eb..cb5b1b9068e 100644 --- a/spec/integ/matrix-client-opts.spec.ts +++ b/spec/integ/matrix-client-opts.spec.ts @@ -80,7 +80,7 @@ describe("MatrixClient opts", function () { let client: MatrixClient; beforeEach(function () { client = new MatrixClient({ - fetchFn: httpBackend.fetchFn as typeof global.fetch, + fetchFn: httpBackend.fetchFn as typeof globalThis.fetch, store: undefined, baseUrl: baseUrl, userId: userId, @@ -135,7 +135,7 @@ describe("MatrixClient opts", function () { let client: MatrixClient; beforeEach(function () { client = new MatrixClient({ - fetchFn: httpBackend.fetchFn as typeof global.fetch, + fetchFn: httpBackend.fetchFn as typeof globalThis.fetch, store: new MemoryStore() as IStore, baseUrl: baseUrl, userId: userId, diff --git a/spec/integ/matrix-client-syncing.spec.ts b/spec/integ/matrix-client-syncing.spec.ts index e2d7fe3f263..673532ddf83 100644 --- a/spec/integ/matrix-client-syncing.spec.ts +++ b/spec/integ/matrix-client-syncing.spec.ts @@ -2406,7 +2406,7 @@ describe("MatrixClient syncing (IndexedDB version)", () => { it("should emit ClientEvent.Room when invited while using indexeddb crypto store", async () => { const idbTestClient = new TestClient(selfUserId, "DEVICE", selfAccessToken, undefined, { - cryptoStore: new IndexedDBCryptoStore(global.indexedDB, "tests"), + cryptoStore: new IndexedDBCryptoStore(globalThis.indexedDB, "tests"), }); const idbHttpBackend = idbTestClient.httpBackend; const idbClient = idbTestClient.client; @@ -2486,7 +2486,7 @@ describe("MatrixClient syncing (IndexedDB version)", () => { let idbTestClient = new TestClient(selfUserId, "DEVICE", selfAccessToken, undefined, { store: new IndexedDBStore({ - indexedDB: global.indexedDB, + indexedDB: globalThis.indexedDB, dbName: "test", }), }); @@ -2558,7 +2558,7 @@ describe("MatrixClient syncing (IndexedDB version)", () => { idbTestClient = new TestClient(selfUserId, "DEVICE", selfAccessToken, undefined, { store: new IndexedDBStore({ - indexedDB: global.indexedDB, + indexedDB: globalThis.indexedDB, dbName: "test", }), }); diff --git a/spec/integ/rendezvous/MSC4108SignInWithQR.spec.ts b/spec/integ/rendezvous/MSC4108SignInWithQR.spec.ts index b564155fe03..82818e229a3 100644 --- a/spec/integ/rendezvous/MSC4108SignInWithQR.spec.ts +++ b/spec/integ/rendezvous/MSC4108SignInWithQR.spec.ts @@ -266,7 +266,7 @@ describe("MSC4108SignInWithQR", () => { }); it("should abort if device doesn't come up by timeout", async () => { - jest.spyOn(global, "setTimeout").mockImplementation((fn) => { + jest.spyOn(globalThis, "setTimeout").mockImplementation((fn) => { fn(); // TODO: mock timers properly return -1 as any; @@ -319,7 +319,7 @@ describe("MSC4108SignInWithQR", () => { }); it("should not send secrets if user cancels", async () => { - jest.spyOn(global, "setTimeout").mockImplementation((fn) => { + jest.spyOn(globalThis, "setTimeout").mockImplementation((fn) => { fn(); // TODO: mock timers properly return -1 as any; diff --git a/spec/test-utils/test-utils.ts b/spec/test-utils/test-utils.ts index 15c7c9efd22..08a2f9f779e 100644 --- a/spec/test-utils/test-utils.ts +++ b/spec/test-utils/test-utils.ts @@ -560,7 +560,7 @@ export const CRYPTO_BACKENDS: Record = {}; export type InitCrypto = (_: MatrixClient) => Promise; CRYPTO_BACKENDS["rust-sdk"] = (client: MatrixClient) => client.initRustCrypto(); -if (global.Olm) { +if (globalThis.Olm) { CRYPTO_BACKENDS["libolm"] = (client: MatrixClient) => client.initCrypto(); } diff --git a/spec/test-utils/webrtc.ts b/spec/test-utils/webrtc.ts index 519701bdaa9..fbc6d93be26 100644 --- a/spec/test-utils/webrtc.ts +++ b/spec/test-utils/webrtc.ts @@ -582,11 +582,11 @@ export class MockCallFeed { } export function installWebRTCMocks() { - global.navigator = { + globalThis.navigator = { mediaDevices: new MockMediaDevices().typed(), } as unknown as Navigator; - global.window = { + globalThis.window = { // @ts-ignore Mock RTCPeerConnection: MockRTCPeerConnection, // @ts-ignore Mock @@ -596,13 +596,13 @@ export function installWebRTCMocks() { getUserMedia: () => new MockMediaStream("local_stream"), }; // @ts-ignore Mock - global.document = {}; + globalThis.document = {}; // @ts-ignore Mock - global.AudioContext = MockAudioContext; + globalThis.AudioContext = MockAudioContext; // @ts-ignore Mock - global.RTCRtpReceiver = { + globalThis.RTCRtpReceiver = { getCapabilities: jest.fn().mockReturnValue({ codecs: [], headerExtensions: [], @@ -610,7 +610,7 @@ export function installWebRTCMocks() { }; // @ts-ignore Mock - global.RTCRtpSender = { + globalThis.RTCRtpSender = { getCapabilities: jest.fn().mockReturnValue({ codecs: [], headerExtensions: [], diff --git a/spec/unit/autodiscovery.spec.ts b/spec/unit/autodiscovery.spec.ts index e4c7c98b293..282d2f57c1a 100644 --- a/spec/unit/autodiscovery.spec.ts +++ b/spec/unit/autodiscovery.spec.ts @@ -22,12 +22,12 @@ import { AutoDiscovery } from "../../src/autodiscovery"; // keep to reset the fetch function after using MockHttpBackend // @ts-ignore private property -const realAutoDiscoveryFetch: typeof global.fetch = AutoDiscovery.fetchFn; +const realAutoDiscoveryFetch: typeof globalThis.fetch = AutoDiscovery.fetchFn; describe("AutoDiscovery", function () { const getHttpBackend = (): MockHttpBackend => { const httpBackend = new MockHttpBackend(); - AutoDiscovery.setFetchFn(httpBackend.fetchFn as typeof global.fetch); + AutoDiscovery.setFetchFn(httpBackend.fetchFn as typeof globalThis.fetch); return httpBackend; }; diff --git a/spec/unit/base64.spec.ts b/spec/unit/base64.spec.ts index 3ef495134a1..cba73bec9f3 100644 --- a/spec/unit/base64.spec.ts +++ b/spec/unit/base64.spec.ts @@ -29,8 +29,8 @@ describe.each(["browser", "node"])("Base64 encoding (%s)", (env) => { // eslint-disable-next-line no-global-assign Buffer = undefined; - global.atob = NodeBuffer.atob; - global.btoa = NodeBuffer.btoa; + globalThis.atob = NodeBuffer.atob; + globalThis.btoa = NodeBuffer.btoa; } }); @@ -38,9 +38,9 @@ describe.each(["browser", "node"])("Base64 encoding (%s)", (env) => { // eslint-disable-next-line no-global-assign Buffer = origBuffer; // @ts-ignore - global.atob = undefined; + globalThis.atob = undefined; // @ts-ignore - global.btoa = undefined; + globalThis.btoa = undefined; }); it("Should decode properly encoded data", () => { diff --git a/spec/unit/content-helpers.spec.ts b/spec/unit/content-helpers.spec.ts index 2188cbcca2c..afb465f5382 100644 --- a/spec/unit/content-helpers.spec.ts +++ b/spec/unit/content-helpers.spec.ts @@ -29,10 +29,10 @@ describe("Beacon content helpers", () => { describe("makeBeaconInfoContent()", () => { const mockDateNow = 123456789; beforeEach(() => { - jest.spyOn(global.Date, "now").mockReturnValue(mockDateNow); + jest.spyOn(globalThis.Date, "now").mockReturnValue(mockDateNow); }); afterAll(() => { - jest.spyOn(global.Date, "now").mockRestore(); + jest.spyOn(globalThis.Date, "now").mockRestore(); }); it("create fully defined event content", () => { expect(makeBeaconInfoContent(1234, true, "nice beacon_info", LocationAssetType.Pin)).toEqual({ diff --git a/spec/unit/crypto.spec.ts b/spec/unit/crypto.spec.ts index 616c8f95255..ce2d2389212 100644 --- a/spec/unit/crypto.spec.ts +++ b/spec/unit/crypto.spec.ts @@ -28,7 +28,7 @@ import * as testData from "../test-utils/test-data"; import { KnownMembership } from "../../src/@types/membership"; import type { DeviceInfoMap } from "../../src/crypto/DeviceList"; -const Olm = global.Olm; +const Olm = globalThis.Olm; function awaitEvent(emitter: EventEmitter, event: string): Promise { return new Promise((resolve) => { diff --git a/spec/unit/crypto/CrossSigningInfo.spec.ts b/spec/unit/crypto/CrossSigningInfo.spec.ts index b343aef1cf8..e99ceb2739b 100644 --- a/spec/unit/crypto/CrossSigningInfo.spec.ts +++ b/spec/unit/crypto/CrossSigningInfo.spec.ts @@ -44,13 +44,13 @@ badKey[0] ^= 1; const masterKeyPub = "nqOvzeuGWT/sRx3h7+MHoInYj3Uk2LD/unI9kDYcHwk"; describe("CrossSigningInfo.getCrossSigningKey", function () { - if (!global.Olm) { + if (!globalThis.Olm) { logger.warn("Not running megolm backup unit tests: libolm not present"); return; } beforeAll(function () { - return global.Olm.init(); + return globalThis.Olm.init(); }); it("should throw if no callback is provided", async () => { @@ -80,7 +80,7 @@ describe("CrossSigningInfo.getCrossSigningKey", function () { expect(pubKey).toEqual(masterKeyPub); // check that the pkSigning object corresponds to the pubKey const signature = pkSigning.sign("message"); - const util = new global.Olm.Utility(); + const util = new globalThis.Olm.Utility(); try { util.ed25519_verify(pubKey, "message", signature); } finally { @@ -199,7 +199,7 @@ describe("CrossSigningInfo.getCrossSigningKey", function () { * it's not possible to get one in normal execution unless you hack as we do here. */ describe.each([ - ["IndexedDBCryptoStore", () => new IndexedDBCryptoStore(global.indexedDB, "tests")], + ["IndexedDBCryptoStore", () => new IndexedDBCryptoStore(globalThis.indexedDB, "tests")], ["LocalStorageCryptoStore", () => new IndexedDBCryptoStore(undefined!, "tests")], [ "MemoryCryptoStore", diff --git a/spec/unit/crypto/algorithms/megolm.spec.ts b/spec/unit/crypto/algorithms/megolm.spec.ts index b27e59d4934..d2a1fbf3372 100644 --- a/spec/unit/crypto/algorithms/megolm.spec.ts +++ b/spec/unit/crypto/algorithms/megolm.spec.ts @@ -43,10 +43,10 @@ const MegolmEncryption = algorithms.ENCRYPTION_CLASSES.get("m.megolm.v1.aes-sha2 const ROOM_ID = "!ROOM:ID"; -const Olm = global.Olm; +const Olm = globalThis.Olm; describe("MegolmDecryption", function () { - if (!global.Olm) { + if (!globalThis.Olm) { logger.warn("Not running megolm unit tests: libolm not present"); return; } @@ -101,7 +101,7 @@ describe("MegolmDecryption", function () { describe("receives some keys:", function () { let groupSession: OutboundGroupSession; beforeEach(async function () { - groupSession = new global.Olm.OutboundGroupSession(); + groupSession = new globalThis.Olm.OutboundGroupSession(); groupSession.create(); // construct a fake decrypted key event via the use of a mocked diff --git a/spec/unit/crypto/algorithms/olm.spec.ts b/spec/unit/crypto/algorithms/olm.spec.ts index 644bb96e391..6c50f09635e 100644 --- a/spec/unit/crypto/algorithms/olm.spec.ts +++ b/spec/unit/crypto/algorithms/olm.spec.ts @@ -47,13 +47,13 @@ function alwaysSucceed(promise: Promise): Promise { } describe("OlmDevice", function () { - if (!global.Olm) { + if (!globalThis.Olm) { logger.warn("Not running megolm unit tests: libolm not present"); return; } beforeAll(function () { - return global.Olm.init(); + return globalThis.Olm.init(); }); let aliceOlmDevice: OlmDevice; diff --git a/spec/unit/crypto/backup.spec.ts b/spec/unit/crypto/backup.spec.ts index 427a9f318ce..2d655a90117 100644 --- a/spec/unit/crypto/backup.spec.ts +++ b/spec/unit/crypto/backup.spec.ts @@ -33,7 +33,7 @@ import { CryptoStore } from "../../../src/crypto/store/base"; import { MegolmDecryption as MegolmDecryptionClass } from "../../../src/crypto/algorithms/megolm"; import { IKeyBackupInfo } from "../../../src/crypto/keybackup"; -const Olm = global.Olm; +const Olm = globalThis.Olm; const MegolmDecryption = algorithms.DECRYPTION_CLASSES.get("m.megolm.v1.aes-sha2")!; @@ -155,7 +155,7 @@ function makeTestClient(cryptoStore: CryptoStore) { } describe("MegolmBackup", function () { - if (!global.Olm) { + if (!globalThis.Olm) { logger.warn("Not running megolm backup unit tests: libolm not present"); return; } @@ -205,14 +205,14 @@ describe("MegolmBackup", function () { // clobber the setTimeout function to run 100x faster. // ideally we would use lolex, but we have no oportunity // to tick the clock between the first try and the retry. - const realSetTimeout = global.setTimeout; - jest.spyOn(global, "setTimeout").mockImplementation(function (f, n) { + const realSetTimeout = globalThis.setTimeout; + jest.spyOn(globalThis, "setTimeout").mockImplementation(function (f, n) { return realSetTimeout(f!, n! / 100); }); }); afterEach(function () { - jest.spyOn(global, "setTimeout").mockRestore(); + jest.spyOn(globalThis, "setTimeout").mockRestore(); }); test("fail if crypto not enabled", async () => { diff --git a/spec/unit/crypto/cross-signing.spec.ts b/spec/unit/crypto/cross-signing.spec.ts index ad347dd3296..967c86ca69a 100644 --- a/spec/unit/crypto/cross-signing.spec.ts +++ b/spec/unit/crypto/cross-signing.spec.ts @@ -84,13 +84,13 @@ async function makeTestClient( } describe("Cross Signing", function () { - if (!global.Olm) { + if (!globalThis.Olm) { logger.warn("Not running megolm backup unit tests: libolm not present"); return; } beforeAll(function () { - return global.Olm.init(); + return globalThis.Olm.init(); }); it("should sign the master key with the device key", async function () { @@ -369,10 +369,10 @@ describe("Cross Signing", function () { // set Alice's cross-signing key await resetCrossSigningKeys(alice); // Alice downloads Bob's ssk and device key - const bobMasterSigning = new global.Olm.PkSigning(); + const bobMasterSigning = new globalThis.Olm.PkSigning(); const bobMasterPrivkey = bobMasterSigning.generate_seed(); const bobMasterPubkey = bobMasterSigning.init_with_seed(bobMasterPrivkey); - const bobSigning = new global.Olm.PkSigning(); + const bobSigning = new globalThis.Olm.PkSigning(); const bobPrivkey = bobSigning.generate_seed(); const bobPubkey = bobSigning.init_with_seed(bobPrivkey); const bobSSK: CrossSigningKeyInfo = { @@ -488,7 +488,7 @@ describe("Cross Signing", function () { }; await alice.crypto!.signObject(aliceDevice); - const bobOlmAccount = new global.Olm.Account(); + const bobOlmAccount = new globalThis.Olm.Account(); bobOlmAccount.create(); const bobKeys = JSON.parse(bobOlmAccount.identity_keys()); const bobDeviceUnsigned = { @@ -622,10 +622,10 @@ describe("Cross Signing", function () { await resetCrossSigningKeys(alice); // Alice downloads Bob's ssk and device key // (NOTE: device key is not signed by ssk) - const bobMasterSigning = new global.Olm.PkSigning(); + const bobMasterSigning = new globalThis.Olm.PkSigning(); const bobMasterPrivkey = bobMasterSigning.generate_seed(); const bobMasterPubkey = bobMasterSigning.init_with_seed(bobMasterPrivkey); - const bobSigning = new global.Olm.PkSigning(); + const bobSigning = new globalThis.Olm.PkSigning(); const bobPrivkey = bobSigning.generate_seed(); const bobPubkey = bobSigning.init_with_seed(bobPrivkey); const bobSSK: CrossSigningKeyInfo = { @@ -688,10 +688,10 @@ describe("Cross Signing", function () { alice.uploadKeySignatures = async () => ({ failures: {} }); await resetCrossSigningKeys(alice); // Alice downloads Bob's keys - const bobMasterSigning = new global.Olm.PkSigning(); + const bobMasterSigning = new globalThis.Olm.PkSigning(); const bobMasterPrivkey = bobMasterSigning.generate_seed(); const bobMasterPubkey = bobMasterSigning.init_with_seed(bobMasterPrivkey); - const bobSigning = new global.Olm.PkSigning(); + const bobSigning = new globalThis.Olm.PkSigning(); const bobPrivkey = bobSigning.generate_seed(); const bobPubkey = bobSigning.init_with_seed(bobPrivkey); const bobSSK: CrossSigningKeyInfo = { @@ -755,10 +755,10 @@ describe("Cross Signing", function () { expect(bobDeviceTrust.isTofu()).toBeTruthy(); // Alice downloads new SSK for Bob - const bobMasterSigning2 = new global.Olm.PkSigning(); + const bobMasterSigning2 = new globalThis.Olm.PkSigning(); const bobMasterPrivkey2 = bobMasterSigning2.generate_seed(); const bobMasterPubkey2 = bobMasterSigning2.init_with_seed(bobMasterPrivkey2); - const bobSigning2 = new global.Olm.PkSigning(); + const bobSigning2 = new globalThis.Olm.PkSigning(); const bobPrivkey2 = bobSigning2.generate_seed(); const bobPubkey2 = bobSigning2.init_with_seed(bobPrivkey2); const bobSSK2: CrossSigningKeyInfo = { @@ -905,10 +905,10 @@ describe("Cross Signing", function () { alice.uploadKeySignatures = async () => ({ failures: {} }); // Generate Alice's SSK etc - const aliceMasterSigning = new global.Olm.PkSigning(); + const aliceMasterSigning = new globalThis.Olm.PkSigning(); const aliceMasterPrivkey = aliceMasterSigning.generate_seed(); const aliceMasterPubkey = aliceMasterSigning.init_with_seed(aliceMasterPrivkey); - const aliceSigning = new global.Olm.PkSigning(); + const aliceSigning = new globalThis.Olm.PkSigning(); const alicePrivkey = aliceSigning.generate_seed(); const alicePubkey = aliceSigning.init_with_seed(alicePrivkey); const aliceSSK: CrossSigningKeyInfo = { @@ -980,10 +980,10 @@ describe("Cross Signing", function () { alice.uploadKeySignatures = async () => ({ failures: {} }); // Generate Alice's SSK etc - const aliceMasterSigning = new global.Olm.PkSigning(); + const aliceMasterSigning = new globalThis.Olm.PkSigning(); const aliceMasterPrivkey = aliceMasterSigning.generate_seed(); const aliceMasterPubkey = aliceMasterSigning.init_with_seed(aliceMasterPrivkey); - const aliceSigning = new global.Olm.PkSigning(); + const aliceSigning = new globalThis.Olm.PkSigning(); const alicePrivkey = aliceSigning.generate_seed(); const alicePubkey = aliceSigning.init_with_seed(alicePrivkey); const aliceSSK: CrossSigningKeyInfo = { @@ -1040,10 +1040,10 @@ describe("Cross Signing", function () { alice.uploadKeySignatures = async () => ({ failures: {} }); // Generate Alice's SSK etc - const aliceMasterSigning = new global.Olm.PkSigning(); + const aliceMasterSigning = new globalThis.Olm.PkSigning(); const aliceMasterPrivkey = aliceMasterSigning.generate_seed(); const aliceMasterPubkey = aliceMasterSigning.init_with_seed(aliceMasterPrivkey); - const aliceSigning = new global.Olm.PkSigning(); + const aliceSigning = new globalThis.Olm.PkSigning(); const alicePrivkey = aliceSigning.generate_seed(); const alicePubkey = aliceSigning.init_with_seed(alicePrivkey); const aliceSSK: CrossSigningKeyInfo = { @@ -1088,12 +1088,12 @@ describe("Cross Signing", function () { }); describe("userHasCrossSigningKeys", function () { - if (!global.Olm) { + if (!globalThis.Olm) { return; } beforeAll(() => { - return global.Olm.init(); + return globalThis.Olm.init(); }); let aliceClient: MatrixClient; diff --git a/spec/unit/crypto/crypto-utils.ts b/spec/unit/crypto/crypto-utils.ts index 39a53562aea..e6263a6dc22 100644 --- a/spec/unit/crypto/crypto-utils.ts +++ b/spec/unit/crypto/crypto-utils.ts @@ -32,7 +32,7 @@ export async function resetCrossSigningKeys( } export async function createSecretStorageKey(): Promise { - const decryption = new global.Olm.PkDecryption(); + const decryption = new globalThis.Olm.PkDecryption(); decryption.generate_key(); const storagePrivateKey = decryption.get_private_key(); decryption.free(); diff --git a/spec/unit/crypto/dehydration.spec.ts b/spec/unit/crypto/dehydration.spec.ts index 18b4b382806..37893230a46 100644 --- a/spec/unit/crypto/dehydration.spec.ts +++ b/spec/unit/crypto/dehydration.spec.ts @@ -19,16 +19,16 @@ import { TestClient } from "../../TestClient"; import { logger } from "../../../src/logger"; import { DEHYDRATION_ALGORITHM } from "../../../src/crypto/dehydration"; -const Olm = global.Olm; +const Olm = globalThis.Olm; describe("Dehydration", () => { - if (!global.Olm) { + if (!globalThis.Olm) { logger.warn("Not running dehydration unit tests: libolm not present"); return; } beforeAll(function () { - return global.Olm.init(); + return globalThis.Olm.init(); }); it("should rehydrate a dehydrated device", async () => { diff --git a/spec/unit/crypto/outgoing-room-key-requests.spec.ts b/spec/unit/crypto/outgoing-room-key-requests.spec.ts index f160efc0c9f..f7d5160610a 100644 --- a/spec/unit/crypto/outgoing-room-key-requests.spec.ts +++ b/spec/unit/crypto/outgoing-room-key-requests.spec.ts @@ -51,7 +51,7 @@ const requests = [ ]; describe.each([ - ["IndexedDBCryptoStore", () => new IndexedDBCryptoStore(global.indexedDB, "tests")], + ["IndexedDBCryptoStore", () => new IndexedDBCryptoStore(globalThis.indexedDB, "tests")], ["LocalStorageCryptoStore", () => new LocalStorageCryptoStore(localStorage)], ["MemoryCryptoStore", () => new MemoryCryptoStore()], ])("Outgoing room key requests [%s]", function (name, dbFactory) { diff --git a/spec/unit/crypto/secrets.spec.ts b/spec/unit/crypto/secrets.spec.ts index f09657c88b1..d7c7516a98b 100644 --- a/spec/unit/crypto/secrets.spec.ts +++ b/spec/unit/crypto/secrets.spec.ts @@ -69,20 +69,20 @@ function sign( } describe("Secrets", function () { - if (!global.Olm) { + if (!globalThis.Olm) { logger.warn("Not running megolm backup unit tests: libolm not present"); return; } beforeAll(function () { - return global.Olm.init(); + return globalThis.Olm.init(); }); it("should store and retrieve a secret", async function () { const key = new Uint8Array(16); for (let i = 0; i < 16; i++) key[i] = i; - const signing = new global.Olm.PkSigning(); + const signing = new globalThis.Olm.PkSigning(); const signingKey = signing.generate_seed(); const signingPubKey = signing.init_with_seed(signingKey); @@ -332,7 +332,7 @@ describe("Secrets", function () { }); it("bootstraps when cross-signing keys in secret storage", async function () { - const decryption = new global.Olm.PkDecryption(); + const decryption = new globalThis.Olm.PkDecryption(); const storagePrivateKey = decryption.get_private_key(); const bob: MatrixClient = await makeTestClient( diff --git a/spec/unit/crypto/store/CryptoStore.spec.ts b/spec/unit/crypto/store/CryptoStore.spec.ts index 9070c2a5c44..f62c17dacb1 100644 --- a/spec/unit/crypto/store/CryptoStore.spec.ts +++ b/spec/unit/crypto/store/CryptoStore.spec.ts @@ -20,7 +20,7 @@ import { IndexedDBCryptoStore, LocalStorageCryptoStore, MemoryCryptoStore } from import { CryptoStore, MigrationState, SESSION_BATCH_SIZE } from "../../../../src/crypto/store/base"; describe.each([ - ["IndexedDBCryptoStore", () => new IndexedDBCryptoStore(global.indexedDB, "tests")], + ["IndexedDBCryptoStore", () => new IndexedDBCryptoStore(globalThis.indexedDB, "tests")], ["LocalStorageCryptoStore", () => new LocalStorageCryptoStore(localStorage)], ["MemoryCryptoStore", () => new MemoryCryptoStore()], ])("CryptoStore tests for %s", function (name, dbFactory) { diff --git a/spec/unit/crypto/store/IndexedDBCryptoStore.spec.ts b/spec/unit/crypto/store/IndexedDBCryptoStore.spec.ts index 52fd574ba14..21523c9107a 100644 --- a/spec/unit/crypto/store/IndexedDBCryptoStore.spec.ts +++ b/spec/unit/crypto/store/IndexedDBCryptoStore.spec.ts @@ -27,21 +27,21 @@ describe("IndexedDBCryptoStore", () => { it("Should be true if there is a legacy database", async () => { // should detect a store that is not migrated - const store = new IndexedDBCryptoStore(global.indexedDB, "tests"); + const store = new IndexedDBCryptoStore(globalThis.indexedDB, "tests"); await store.startup(); - const result = await IndexedDBCryptoStore.existsAndIsNotMigrated(global.indexedDB, "tests"); + const result = await IndexedDBCryptoStore.existsAndIsNotMigrated(globalThis.indexedDB, "tests"); expect(result).toBe(true); }); it("Should be true if there is a legacy database in non migrated state", async () => { // should detect a store that is not migrated - const store = new IndexedDBCryptoStore(global.indexedDB, "tests"); + const store = new IndexedDBCryptoStore(globalThis.indexedDB, "tests"); await store.startup(); await store.setMigrationState(MigrationState.NOT_STARTED); - const result = await IndexedDBCryptoStore.existsAndIsNotMigrated(global.indexedDB, "tests"); + const result = await IndexedDBCryptoStore.existsAndIsNotMigrated(globalThis.indexedDB, "tests"); expect(result).toBe(true); }); @@ -54,18 +54,18 @@ describe("IndexedDBCryptoStore", () => { ])("Exists and Migration state is %s", (migrationState) => { it("Should be false if migration has started", async () => { // should detect a store that is not migrated - const store = new IndexedDBCryptoStore(global.indexedDB, "tests"); + const store = new IndexedDBCryptoStore(globalThis.indexedDB, "tests"); await store.startup(); await store.setMigrationState(migrationState); - const result = await IndexedDBCryptoStore.existsAndIsNotMigrated(global.indexedDB, "tests"); + const result = await IndexedDBCryptoStore.existsAndIsNotMigrated(globalThis.indexedDB, "tests"); expect(result).toBe(false); }); }); it("Should be false if there is no legacy database", async () => { - const result = await IndexedDBCryptoStore.existsAndIsNotMigrated(global.indexedDB, "tests"); + const result = await IndexedDBCryptoStore.existsAndIsNotMigrated(globalThis.indexedDB, "tests"); expect(result).toBe(false); }); diff --git a/spec/unit/crypto/verification/qr_code.spec.ts b/spec/unit/crypto/verification/qr_code.spec.ts index 7d2fc9171d1..0f8fdcba591 100644 --- a/spec/unit/crypto/verification/qr_code.spec.ts +++ b/spec/unit/crypto/verification/qr_code.spec.ts @@ -17,10 +17,10 @@ limitations under the License. import "../../../olm-loader"; import { logger } from "../../../../src/logger"; -const Olm = global.Olm; +const Olm = globalThis.Olm; describe("QR code verification", function () { - if (!global.Olm) { + if (!globalThis.Olm) { logger.warn("Not running device verification tests: libolm not present"); return; } diff --git a/spec/unit/crypto/verification/request.spec.ts b/spec/unit/crypto/verification/request.spec.ts index 63989c77c40..c3b45b7b813 100644 --- a/spec/unit/crypto/verification/request.spec.ts +++ b/spec/unit/crypto/verification/request.spec.ts @@ -20,12 +20,12 @@ import { logger } from "../../../../src/logger"; import { SAS } from "../../../../src/crypto/verification/SAS"; import { makeTestClients } from "./util"; -const Olm = global.Olm; +const Olm = globalThis.Olm; jest.useFakeTimers(); describe("verification request integration tests with crypto layer", function () { - if (!global.Olm) { + if (!globalThis.Olm) { logger.warn("Not running device verification unit tests: libolm not present"); return; } diff --git a/spec/unit/crypto/verification/sas.spec.ts b/spec/unit/crypto/verification/sas.spec.ts index 7a4f65d05c6..939dc3b7789 100644 --- a/spec/unit/crypto/verification/sas.spec.ts +++ b/spec/unit/crypto/verification/sas.spec.ts @@ -29,13 +29,13 @@ import { MatrixClient } from "../../../../src"; import { VerificationRequest } from "../../../../src/crypto/verification/request/VerificationRequest"; import { TestClient } from "../../../TestClient"; -const Olm = global.Olm; +const Olm = globalThis.Olm; let ALICE_DEVICES: Record; let BOB_DEVICES: Record; describe("SAS verification", function () { - if (!global.Olm) { + if (!globalThis.Olm) { logger.warn("Not running device verification unit tests: libolm not present"); return; } diff --git a/spec/unit/crypto/verification/secret_request.spec.ts b/spec/unit/crypto/verification/secret_request.spec.ts index 06ff0393ef1..acc00abf120 100644 --- a/spec/unit/crypto/verification/secret_request.spec.ts +++ b/spec/unit/crypto/verification/secret_request.spec.ts @@ -34,7 +34,7 @@ const testKeyPub = "nqOvzeuGWT/sRx3h7+MHoInYj3Uk2LD/unI9kDYcHwk"; describe("self-verifications", () => { beforeAll(function () { - return global.Olm.init(); + return globalThis.Olm.init(); }); it("triggers a request for key sharing upon completion", async () => { diff --git a/spec/unit/digest.spec.ts b/spec/unit/digest.spec.ts index e129cf85070..4d33564f73e 100644 --- a/spec/unit/digest.spec.ts +++ b/spec/unit/digest.spec.ts @@ -29,12 +29,12 @@ describe("sha256", () => { }); it("throws if webcrypto is not available", async () => { - const oldCrypto = global.crypto; + const oldCrypto = globalThis.crypto; try { - global.crypto = {} as any; + globalThis.crypto = {} as any; await expect(sha256("test")).rejects.toThrow(); } finally { - global.crypto = oldCrypto; + globalThis.crypto = oldCrypto; } }); }); diff --git a/spec/unit/http-api/errors.spec.ts b/spec/unit/http-api/errors.spec.ts index 426d23ee0c1..6054aad4bb9 100644 --- a/spec/unit/http-api/errors.spec.ts +++ b/spec/unit/http-api/errors.spec.ts @@ -57,7 +57,7 @@ describe("MatrixError", () => { it("should retrieve Date Retry-After header from rate-limit error", () => { headers.set("Retry-After", `${new Date(160000).toUTCString()}`); - jest.spyOn(global.Date, "now").mockImplementationOnce(() => 100000); + jest.spyOn(globalThis.Date, "now").mockImplementationOnce(() => 100000); const err = makeMatrixError(429, { errcode: "M_LIMIT_EXCEEDED", retry_after_ms: 150000 }); expect(err.isRateLimitError()).toBe(true); // prefer Retry-After header over retry_after_ms diff --git a/spec/unit/http-api/fetch.spec.ts b/spec/unit/http-api/fetch.spec.ts index 2a48f03b6dc..294ec8df004 100644 --- a/spec/unit/http-api/fetch.spec.ts +++ b/spec/unit/http-api/fetch.spec.ts @@ -60,11 +60,11 @@ describe("FetchHttpApi", () => { }); it("should fall back to global fetch if fetchFn not provided", () => { - global.fetch = jest.fn(); - expect(global.fetch).not.toHaveBeenCalled(); + globalThis.fetch = jest.fn(); + expect(globalThis.fetch).not.toHaveBeenCalled(); const api = new FetchHttpApi(new TypedEventEmitter(), { baseUrl, prefix }); api.fetch("test"); - expect(global.fetch).toHaveBeenCalled(); + expect(globalThis.fetch).toHaveBeenCalled(); }); it("should update identity server base url", () => { diff --git a/spec/unit/http-api/index.spec.ts b/spec/unit/http-api/index.spec.ts index ca20bee4561..5435c4bdcae 100644 --- a/spec/unit/http-api/index.spec.ts +++ b/spec/unit/http-api/index.spec.ts @@ -45,9 +45,9 @@ describe("MatrixHttpApi", () => { } as unknown as XMLHttpRequest; // We stub out XHR here as it is not available in JSDOM // @ts-ignore - global.XMLHttpRequest = jest.fn().mockReturnValue(xhr); + globalThis.XMLHttpRequest = jest.fn().mockReturnValue(xhr); // @ts-ignore - global.XMLHttpRequest.DONE = DONE; + globalThis.XMLHttpRequest.DONE = DONE; }); afterEach(() => { @@ -60,7 +60,7 @@ describe("MatrixHttpApi", () => { }); it("should fall back to `fetch` where xhr is unavailable", () => { - global.XMLHttpRequest = undefined!; + globalThis.XMLHttpRequest = undefined!; const fetchFn = jest.fn().mockResolvedValue({ ok: true, json: jest.fn().mockResolvedValue({}) }); const api = new MatrixHttpApi(new TypedEventEmitter(), { baseUrl, prefix, fetchFn }); upload = api.uploadContent({} as File); diff --git a/spec/unit/models/beacon.spec.ts b/spec/unit/models/beacon.spec.ts index b3042cd6a31..8c35268d81e 100644 --- a/spec/unit/models/beacon.spec.ts +++ b/spec/unit/models/beacon.spec.ts @@ -70,7 +70,7 @@ describe("Beacon", () => { const advanceDateAndTime = (ms: number) => { // bc liveness check uses Date.now we have to advance this mock - jest.spyOn(global.Date, "now").mockReturnValue(Date.now() + ms); + jest.spyOn(globalThis.Date, "now").mockReturnValue(Date.now() + ms); // then advance time for the interval by the same amount jest.advanceTimersByTime(ms); }; @@ -108,11 +108,11 @@ describe("Beacon", () => { ); // back to 'now' - jest.spyOn(global.Date, "now").mockReturnValue(now); + jest.spyOn(globalThis.Date, "now").mockReturnValue(now); }); afterAll(() => { - jest.spyOn(global.Date, "now").mockRestore(); + jest.spyOn(globalThis.Date, "now").mockRestore(); }); it("creates beacon from event", () => { diff --git a/spec/unit/oidc/authorize.spec.ts b/spec/unit/oidc/authorize.spec.ts index e786b8fb56c..9fcf899d537 100644 --- a/spec/unit/oidc/authorize.spec.ts +++ b/spec/unit/oidc/authorize.spec.ts @@ -56,7 +56,7 @@ describe("oidc authorization", () => { delegatedAuthConfig.metadata.issuer + ".well-known/openid-configuration", mockOpenIdConfiguration(), ); - global.TextEncoder = TextEncoder; + globalThis.TextEncoder = TextEncoder; }); beforeEach(() => { diff --git a/spec/unit/pusher.spec.ts b/spec/unit/pusher.spec.ts index 994ef767587..75d08a270f6 100644 --- a/spec/unit/pusher.spec.ts +++ b/spec/unit/pusher.spec.ts @@ -35,7 +35,7 @@ describe("Pushers", () => { client = new MatrixClient({ baseUrl: "https://my.home.server", accessToken: "my.access.token", - fetchFn: httpBackend.fetchFn as typeof global.fetch, + fetchFn: httpBackend.fetchFn as typeof globalThis.fetch, }); }); diff --git a/spec/unit/queueToDevice.spec.ts b/spec/unit/queueToDevice.spec.ts index 362d410af1a..e4716755cc1 100644 --- a/spec/unit/queueToDevice.spec.ts +++ b/spec/unit/queueToDevice.spec.ts @@ -82,7 +82,7 @@ describe.each([[StoreType.Memory], [StoreType.IndexedDB]])("queueToDevice (%s st client = new MatrixClient({ baseUrl: "https://my.home.server", accessToken: "my.access.token", - fetchFn: httpBackend.fetchFn as typeof global.fetch, + fetchFn: httpBackend.fetchFn as typeof globalThis.fetch, store, }); }); @@ -256,7 +256,7 @@ describe.each([[StoreType.Memory], [StoreType.IndexedDB]])("queueToDevice (%s st client = new MatrixClient({ baseUrl: "https://my.home.server", accessToken: "my.access.token", - fetchFn: httpBackend.fetchFn as typeof global.fetch, + fetchFn: httpBackend.fetchFn as typeof globalThis.fetch, store, }); }); diff --git a/spec/unit/read-receipt.spec.ts b/spec/unit/read-receipt.spec.ts index 1fe7d4dc3f4..017a0aa3f96 100644 --- a/spec/unit/read-receipt.spec.ts +++ b/spec/unit/read-receipt.spec.ts @@ -54,7 +54,7 @@ describe("Read receipt", () => { userId: "@user:server", baseUrl: "https://my.home.server", accessToken: "my.access.token", - fetchFn: httpBackend.fetchFn as typeof global.fetch, + fetchFn: httpBackend.fetchFn as typeof globalThis.fetch, }); client.isGuest = () => false; client.supportsThreads = () => true; diff --git a/spec/unit/realtime-callbacks.spec.ts b/spec/unit/realtime-callbacks.spec.ts index 7cb1806a39c..7f9b83a8bca 100644 --- a/spec/unit/realtime-callbacks.spec.ts +++ b/spec/unit/realtime-callbacks.spec.ts @@ -53,8 +53,8 @@ describe("realtime-callbacks", function () { it("should set 'this' to the global object", function () { let passed = false; - const callback = function (this: typeof global) { - expect(this).toBe(global); // eslint-disable-line @typescript-eslint/no-invalid-this + const callback = function (this: typeof globalThis) { + expect(this).toBe(globalThis); // eslint-disable-line @typescript-eslint/no-invalid-this expect(this.console).toBeTruthy(); // eslint-disable-line @typescript-eslint/no-invalid-this passed = true; }; diff --git a/spec/unit/rust-crypto/OutgoingRequestProcessor.spec.ts b/spec/unit/rust-crypto/OutgoingRequestProcessor.spec.ts index 3f2199a09f0..959917b131f 100644 --- a/spec/unit/rust-crypto/OutgoingRequestProcessor.spec.ts +++ b/spec/unit/rust-crypto/OutgoingRequestProcessor.spec.ts @@ -61,7 +61,7 @@ describe("OutgoingRequestProcessor", () => { const httpApi = new MatrixHttpApi(dummyEventEmitter, { baseUrl: "https://example.com", prefix: "/_matrix", - fetchFn: httpBackend.fetchFn as typeof global.fetch, + fetchFn: httpBackend.fetchFn as typeof globalThis.fetch, onlyData: true, }); diff --git a/spec/unit/sync-accumulator.spec.ts b/spec/unit/sync-accumulator.spec.ts index c68de970a85..5769b50fb8a 100644 --- a/spec/unit/sync-accumulator.spec.ts +++ b/spec/unit/sync-accumulator.spec.ts @@ -794,7 +794,7 @@ describe("SyncAccumulator", function () { } afterEach(() => { - jest.spyOn(global.Date, "now").mockRestore(); + jest.spyOn(globalThis.Date, "now").mockRestore(); }); it("should copy summary properties", function () { @@ -851,11 +851,11 @@ describe("SyncAccumulator", function () { const delta = 1000; const startingTs = 1000; - jest.spyOn(global.Date, "now").mockReturnValue(startingTs); + jest.spyOn(globalThis.Date, "now").mockReturnValue(startingTs); sa.accumulate(RES_WITH_AGE); - jest.spyOn(global.Date, "now").mockReturnValue(startingTs + delta); + jest.spyOn(globalThis.Date, "now").mockReturnValue(startingTs + delta); const output = sa.getJSON(); expect(output.roomsData.join["!foo:bar"].timeline.events[0].unsigned?.age).toEqual( diff --git a/spec/unit/webrtc/call.spec.ts b/spec/unit/webrtc/call.spec.ts index f8fc35a6661..922d63bd738 100644 --- a/spec/unit/webrtc/call.spec.ts +++ b/spec/unit/webrtc/call.spec.ts @@ -119,9 +119,9 @@ describe("Call", function () { const errorListener = () => {}; beforeEach(function () { - prevNavigator = global.navigator; - prevDocument = global.document; - prevWindow = global.window; + prevNavigator = globalThis.navigator; + prevDocument = globalThis.document; + prevWindow = globalThis.window; installWebRTCMocks(); @@ -159,9 +159,9 @@ describe("Call", function () { call.hangup(CallErrorCode.UserHangup, true); client.stop(); - global.navigator = prevNavigator; - global.window = prevWindow; - global.document = prevDocument; + globalThis.navigator = prevNavigator; + globalThis.window = prevWindow; + globalThis.document = prevDocument; jest.useRealTimers(); }); @@ -788,17 +788,17 @@ describe("Call", function () { }); it("should return false if window or document are undefined", () => { - global.window = undefined!; + globalThis.window = undefined!; expect(supportsMatrixCall()).toBe(false); - global.window = prevWindow; - global.document = undefined!; + globalThis.window = prevWindow; + globalThis.document = undefined!; expect(supportsMatrixCall()).toBe(false); }); it("should return false if RTCPeerConnection throws", () => { // @ts-ignore - writing to window as we are simulating browser edge-cases - global.window = {}; - Object.defineProperty(global.window, "RTCPeerConnection", { + globalThis.window = {}; + Object.defineProperty(globalThis.window, "RTCPeerConnection", { get: () => { throw Error("Secure mode, naaah!"); }, @@ -810,11 +810,11 @@ describe("Call", function () { "should return false if RTCPeerConnection & RTCSessionDescription " + "& RTCIceCandidate & mediaDevices are unavailable", () => { - global.window.RTCPeerConnection = undefined!; - global.window.RTCSessionDescription = undefined!; - global.window.RTCIceCandidate = undefined!; + globalThis.window.RTCPeerConnection = undefined!; + globalThis.window.RTCSessionDescription = undefined!; + globalThis.window.RTCIceCandidate = undefined!; // @ts-ignore - writing to a read-only property as we are simulating faulty browsers - global.navigator.mediaDevices = undefined; + globalThis.navigator.mediaDevices = undefined; expect(supportsMatrixCall()).toBe(false); }, ); @@ -1305,7 +1305,7 @@ describe("Call", function () { }); it("removes RTX codec from screen sharing transcievers", async () => { - mocked(global.RTCRtpSender.getCapabilities).mockReturnValue({ + mocked(globalThis.RTCRtpSender.getCapabilities).mockReturnValue({ codecs: [ { mimeType: "video/rtx", clockRate: 90000 }, { mimeType: "video/somethingelse", clockRate: 90000 }, @@ -1816,8 +1816,8 @@ describe("Call", function () { it("should emit IceFailed error on the successor call if RTCPeerConnection throws", async () => { // @ts-ignore - writing to window as we are simulating browser edge-cases - global.window = {}; - Object.defineProperty(global.window, "RTCPeerConnection", { + globalThis.window = {}; + Object.defineProperty(globalThis.window, "RTCPeerConnection", { get: () => { throw Error("Secure mode, naaah!"); }, diff --git a/spec/unit/webrtc/mediaHandler.spec.ts b/spec/unit/webrtc/mediaHandler.spec.ts index f50baec1f06..4d23ead5f21 100644 --- a/spec/unit/webrtc/mediaHandler.spec.ts +++ b/spec/unit/webrtc/mediaHandler.spec.ts @@ -31,7 +31,7 @@ describe("Media Handler", function () { beforeEach(() => { mockMediaDevices = new MockMediaDevices(); - global.navigator = { + globalThis.navigator = { mediaDevices: mockMediaDevices.typed(), } as unknown as Navigator; diff --git a/spec/unit/webrtc/stats/groupCallStats.spec.ts b/spec/unit/webrtc/stats/groupCallStats.spec.ts index 6aa45f307f9..ae97148764f 100644 --- a/spec/unit/webrtc/stats/groupCallStats.spec.ts +++ b/spec/unit/webrtc/stats/groupCallStats.spec.ts @@ -126,7 +126,7 @@ describe("GroupCallStats", () => { it("doing nothing if process already running", async () => { // @ts-ignore - jest.spyOn(global, "setInterval").mockReturnValue(22); + jest.spyOn(globalThis, "setInterval").mockReturnValue(22); stats.start(); expect(setInterval).toHaveBeenCalledTimes(1); stats.start(); @@ -146,8 +146,8 @@ describe("GroupCallStats", () => { }); it("finish stats process if was started", async () => { // @ts-ignore - jest.spyOn(global, "setInterval").mockReturnValue(22); - jest.spyOn(global, "clearInterval"); + jest.spyOn(globalThis, "setInterval").mockReturnValue(22); + jest.spyOn(globalThis, "clearInterval"); stats.start(); expect(setInterval).toHaveBeenCalledTimes(1); stats.stop(); @@ -155,7 +155,7 @@ describe("GroupCallStats", () => { }); it("do nothing if stats process was not started", async () => { - jest.spyOn(global, "clearInterval"); + jest.spyOn(globalThis, "clearInterval"); stats.stop(); expect(clearInterval).not.toHaveBeenCalled(); }); diff --git a/src/@types/global.d.ts b/src/@types/global.d.ts index d7e7c76ac2d..0b51c2b229a 100644 --- a/src/@types/global.d.ts +++ b/src/@types/global.d.ts @@ -14,13 +14,13 @@ See the License for the specific language governing permissions and limitations under the License. */ -// this is needed to tell TS about global.Olm +// this is needed to tell TS about globalThis.Olm import "@matrix-org/olm"; export {}; declare global { - // use `number` as the return type in all cases for global.set{Interval,Timeout}, + // use `number` as the return type in all cases for globalThis.set{Interval,Timeout}, // so we don't accidentally use the methods on NodeJS.Timeout - they only exist in a subset of environments. // The overload for clear{Interval,Timeout} is resolved as expected. // We use `ReturnType` in the code to be agnostic of if this definition gets loaded. diff --git a/src/autodiscovery.ts b/src/autodiscovery.ts index 3733e533022..b321dcddccb 100644 --- a/src/autodiscovery.ts +++ b/src/autodiscovery.ts @@ -414,16 +414,16 @@ export class AutoDiscovery { } } - private static fetch(resource: URL | string, options?: RequestInit): ReturnType { + private static fetch(resource: URL | string, options?: RequestInit): ReturnType { if (this.fetchFn) { return this.fetchFn(resource, options); } - return global.fetch(resource, options); + return globalThis.fetch(resource, options); } - private static fetchFn?: typeof global.fetch; + private static fetchFn?: typeof globalThis.fetch; - public static setFetchFn(fetchFn: typeof global.fetch): void { + public static setFetchFn(fetchFn: typeof globalThis.fetch): void { AutoDiscovery.fetchFn = fetchFn; } diff --git a/src/client.ts b/src/client.ts index 023231532e1..82fd049273c 100644 --- a/src/client.ts +++ b/src/client.ts @@ -307,7 +307,7 @@ export interface ICreateClientOpts { * The function to invoke for HTTP requests. * Most supported environments have a global `fetch` registered to which this will fall back. */ - fetchFn?: typeof global.fetch; + fetchFn?: typeof globalThis.fetch; userId?: string; @@ -1581,11 +1581,11 @@ export class MatrixClient extends TypedEventEmitter => { let indexedDB: IDBFactory; try { - indexedDB = global.indexedDB; + indexedDB = globalThis.indexedDB; if (!indexedDB) return; // No indexedDB support } catch { // No indexedDB support @@ -1799,7 +1799,7 @@ export class MatrixClient extends TypedEventEmitter { - // In private browsing, Firefox has a global.indexedDB, but attempts to delete an indexeddb + // In private browsing, Firefox has a globalThis.indexedDB, but attempts to delete an indexeddb // (even a non-existent one) fail with "DOMException: A mutation operation was attempted on a // database that did not allow mutations." // @@ -7548,7 +7548,9 @@ export class MatrixClient extends TypedEventEmittererr).httpStatus === 403) { // We got a 403, so there's no point in looping forever. this.logger.info("TURN access unavailable for this account: stopping credentials checks"); - if (this.checkTurnServersIntervalID !== null) global.clearInterval(this.checkTurnServersIntervalID); + if (this.checkTurnServersIntervalID !== null) { + globalThis.clearInterval(this.checkTurnServersIntervalID); + } this.checkTurnServersIntervalID = undefined; this.emit(ClientEvent.TurnServersError, err, true); // fatal } else { diff --git a/src/crypto/CrossSigning.ts b/src/crypto/CrossSigning.ts index ab1c9bcf2ab..77abb6b2545 100644 --- a/src/crypto/CrossSigning.ts +++ b/src/crypto/CrossSigning.ts @@ -125,7 +125,7 @@ export class CrossSigningInfo { function validateKey(key: Uint8Array | null): [string, PkSigning] | undefined { if (!key) return; - const signing = new global.Olm.PkSigning(); + const signing = new globalThis.Olm.PkSigning(); const gotPubkey = signing.init_with_seed(key); if (gotPubkey === expectedPubkey) { return [gotPubkey, signing]; @@ -307,7 +307,7 @@ export class CrossSigningInfo { try { if (level & CrossSigningLevel.MASTER) { - masterSigning = new global.Olm.PkSigning(); + masterSigning = new globalThis.Olm.PkSigning(); privateKeys.master = masterSigning.generate_seed(); masterPub = masterSigning.init_with_seed(privateKeys.master); keys.master = { @@ -322,7 +322,7 @@ export class CrossSigningInfo { } if (level & CrossSigningLevel.SELF_SIGNING) { - const sskSigning = new global.Olm.PkSigning(); + const sskSigning = new globalThis.Olm.PkSigning(); try { privateKeys.self_signing = sskSigning.generate_seed(); const sskPub = sskSigning.init_with_seed(privateKeys.self_signing); @@ -340,7 +340,7 @@ export class CrossSigningInfo { } if (level & CrossSigningLevel.USER_SIGNING) { - const uskSigning = new global.Olm.PkSigning(); + const uskSigning = new globalThis.Olm.PkSigning(); try { privateKeys.user_signing = uskSigning.generate_seed(); const uskPub = uskSigning.init_with_seed(privateKeys.user_signing); diff --git a/src/crypto/OlmDevice.ts b/src/crypto/OlmDevice.ts index 181acb9f141..6cedd49097e 100644 --- a/src/crypto/OlmDevice.ts +++ b/src/crypto/OlmDevice.ts @@ -167,7 +167,7 @@ export class OlmDevice { * @returns The version of Olm. */ public static getOlmVersion(): [number, number, number] { - return global.Olm.get_library_version(); + return globalThis.Olm.get_library_version(); } /** @@ -186,7 +186,7 @@ export class OlmDevice { */ public async init({ pickleKey, fromExportedDevice }: IInitOpts = {}): Promise { let e2eKeys; - const account = new global.Olm.Account(); + const account = new globalThis.Olm.Account(); try { if (fromExportedDevice) { @@ -268,7 +268,7 @@ export class OlmDevice { */ private getAccount(txn: unknown, func: (account: Account) => void): void { this.cryptoStore.getAccount(txn, (pickledAccount: string | null) => { - const account = new global.Olm.Account(); + const account = new globalThis.Olm.Account(); try { account.unpickle(this.pickleKey, pickledAccount!); func(account); @@ -352,7 +352,7 @@ export class OlmDevice { sessionInfo: ISessionInfo, func: (unpickledSessionInfo: IUnpickledSessionInfo) => void, ): void { - const session = new global.Olm.Session(); + const session = new globalThis.Olm.Session(); try { session.unpickle(this.pickleKey, sessionInfo.session!); const unpickledSessInfo: IUnpickledSessionInfo = Object.assign({}, sessionInfo, { session }); @@ -390,7 +390,7 @@ export class OlmDevice { * @internal */ private getUtility(func: (utility: Utility) => T): T { - const utility = new global.Olm.Utility(); + const utility = new globalThis.Olm.Utility(); try { return func(utility); } finally { @@ -517,7 +517,7 @@ export class OlmDevice { [IndexedDBCryptoStore.STORE_ACCOUNT, IndexedDBCryptoStore.STORE_SESSIONS], (txn) => { this.getAccount(txn, (account: Account) => { - const session = new global.Olm.Session(); + const session = new globalThis.Olm.Session(); try { session.create_outbound(account, theirIdentityKey, theirOneTimeKey); newSessionId = session.session_id(); @@ -567,7 +567,7 @@ export class OlmDevice { [IndexedDBCryptoStore.STORE_ACCOUNT, IndexedDBCryptoStore.STORE_SESSIONS], (txn) => { this.getAccount(txn, (account: Account) => { - const session = new global.Olm.Session(); + const session = new globalThis.Olm.Session(); try { session.create_inbound_from(account, theirDeviceIdentityKey, ciphertext); account.remove_one_time_keys(session); @@ -889,7 +889,7 @@ export class OlmDevice { throw new Error("Unknown outbound group session " + sessionId); } - const session = new global.Olm.OutboundGroupSession(); + const session = new globalThis.Olm.OutboundGroupSession(); try { session.unpickle(this.pickleKey, pickled); return func(session); @@ -904,7 +904,7 @@ export class OlmDevice { * @returns sessionId for the outbound session. */ public createOutboundGroupSession(): string { - const session = new global.Olm.OutboundGroupSession(); + const session = new globalThis.Olm.OutboundGroupSession(); try { session.create(); this.saveOutboundGroupSession(session); @@ -966,7 +966,7 @@ export class OlmDevice { sessionData: InboundGroupSessionData, func: (session: InboundGroupSession) => T, ): T { - const session = new global.Olm.InboundGroupSession(); + const session = new globalThis.Olm.InboundGroupSession(); try { session.unpickle(this.pickleKey, sessionData.session); return func(session); @@ -1068,7 +1068,7 @@ export class OlmDevice { existingSessionData: InboundGroupSessionData | null, ) => { // new session. - const session = new global.Olm.InboundGroupSession(); + const session = new globalThis.Olm.InboundGroupSession(); try { if (exportFormat) { session.import_session(sessionKey); diff --git a/src/crypto/backup.ts b/src/crypto/backup.ts index 39bcaae6126..42233385f16 100644 --- a/src/crypto/backup.ts +++ b/src/crypto/backup.ts @@ -666,13 +666,13 @@ export class Curve25519 implements BackupAlgorithm { if (!authData || !("public_key" in authData)) { throw new Error("auth_data missing required information"); } - const publicKey = new global.Olm.PkEncryption(); + const publicKey = new globalThis.Olm.PkEncryption(); publicKey.set_recipient_key(authData.public_key); return new Curve25519(authData as ICurve25519AuthData, publicKey, getKey); } public static async prepare(key?: string | Uint8Array | null): Promise<[Uint8Array, AuthData]> { - const decryption = new global.Olm.PkDecryption(); + const decryption = new globalThis.Olm.PkDecryption(); try { const authData: Partial = {}; if (!key) { @@ -685,7 +685,7 @@ export class Curve25519 implements BackupAlgorithm { authData.private_key_iterations = derivation.iterations; authData.public_key = decryption.init_with_private_key(derivation.key); } - const publicKey = new global.Olm.PkEncryption(); + const publicKey = new globalThis.Olm.PkEncryption(); publicKey.set_recipient_key(authData.public_key); return [decryption.get_private_key(), authData as AuthData]; @@ -716,7 +716,7 @@ export class Curve25519 implements BackupAlgorithm { sessions: Record>, ): Promise { const privKey = await this.getKey(); - const decryption = new global.Olm.PkDecryption(); + const decryption = new globalThis.Olm.PkDecryption(); try { const backupPubKey = decryption.init_with_private_key(privKey); @@ -748,7 +748,7 @@ export class Curve25519 implements BackupAlgorithm { } public async keyMatches(key: Uint8Array): Promise { - const decryption = new global.Olm.PkDecryption(); + const decryption = new globalThis.Olm.PkDecryption(); let pubKey: string; try { pubKey = decryption.init_with_private_key(key); diff --git a/src/crypto/dehydration.ts b/src/crypto/dehydration.ts index 4cfc1193a0b..cb72691f193 100644 --- a/src/crypto/dehydration.ts +++ b/src/crypto/dehydration.ts @@ -68,7 +68,7 @@ export class DehydrationManager { this.deviceDisplayName = deviceDisplayName; const now = Date.now(); const delay = Math.max(1, time + oneweek - now); - this.timeoutId = global.setTimeout(this.dehydrateDevice.bind(this), delay); + this.timeoutId = globalThis.setTimeout(this.dehydrateDevice.bind(this), delay); } }, "dehydration", @@ -97,7 +97,7 @@ export class DehydrationManager { if (!key) { // unsetting the key -- cancel any pending dehydration task if (this.timeoutId) { - global.clearTimeout(this.timeoutId); + globalThis.clearTimeout(this.timeoutId); this.timeoutId = undefined; } // clear storage @@ -135,7 +135,7 @@ export class DehydrationManager { } this.inProgress = true; if (this.timeoutId) { - global.clearTimeout(this.timeoutId); + globalThis.clearTimeout(this.timeoutId); this.timeoutId = undefined; } try { @@ -155,7 +155,7 @@ export class DehydrationManager { logger.log("Creating account"); // create the account and all the necessary keys - const account = new global.Olm.Account(); + const account = new globalThis.Olm.Account(); account.create(); const e2eKeys = JSON.parse(account.identity_keys()); @@ -255,7 +255,7 @@ export class DehydrationManager { logger.log("Done dehydrating"); // dehydrate again in a week - this.timeoutId = global.setTimeout(this.dehydrateDevice.bind(this), oneweek); + this.timeoutId = globalThis.setTimeout(this.dehydrateDevice.bind(this), oneweek); return deviceId; } finally { @@ -265,7 +265,7 @@ export class DehydrationManager { public stop(): void { if (this.timeoutId) { - global.clearTimeout(this.timeoutId); + globalThis.clearTimeout(this.timeoutId); this.timeoutId = undefined; } } diff --git a/src/crypto/index.ts b/src/crypto/index.ts index c252ba15a4b..2e3bef6eecc 100644 --- a/src/crypto/index.ts +++ b/src/crypto/index.ts @@ -537,7 +537,7 @@ export class Crypto extends TypedEventEmitter { logger.log("Crypto: initialising Olm..."); - await global.Olm.init(); + await globalThis.Olm.init(); logger.log( exportedOlmDevice ? "Crypto: initialising Olm device from exported device..." @@ -668,7 +668,7 @@ export class Crypto extends TypedEventEmitter { - const decryption = new global.Olm.PkDecryption(); + const decryption = new globalThis.Olm.PkDecryption(); try { if (password) { const derivation = await keyFromPassphrase(password); @@ -1252,7 +1252,7 @@ export class Crypto extends TypedEventEmitter => { - await global.Olm.init(); - olmutil = olmutil || new global.Olm.Utility(); + await globalThis.Olm.init(); + olmutil = olmutil || new globalThis.Olm.Utility(); // make sure user's keys are downloaded await this.baseApis.downloadKeys([this.userId]); @@ -369,7 +369,7 @@ export class SAS extends Base { const keyAgreement = content.key_agreement_protocol; const macMethod = content.message_authentication_code; const hashCommitment = content.commitment; - const olmSAS = new global.Olm.SAS(); + const olmSAS = new globalThis.Olm.SAS(); try { this.ourSASPubKey = olmSAS.get_pubkey(); await this.send(EventType.KeyVerificationKey, { @@ -411,7 +411,7 @@ export class SAS extends Base { throw newUnknownMethodError(); } - const olmSAS = new global.Olm.SAS(); + const olmSAS = new globalThis.Olm.SAS(); try { const commitmentStr = olmSAS.get_pubkey() + anotherjson.stringify(content); await this.send(EventType.KeyVerificationAccept, { diff --git a/src/http-api/fetch.ts b/src/http-api/fetch.ts index 6ada49ab7a1..bdf9cb15325 100644 --- a/src/http-api/fetch.ts +++ b/src/http-api/fetch.ts @@ -53,11 +53,11 @@ export class FetchHttpApi { this.abortController = new AbortController(); } - public fetch(resource: URL | string, options?: RequestInit): ReturnType { + public fetch(resource: URL | string, options?: RequestInit): ReturnType { if (this.opts.fetchFn) { return this.opts.fetchFn(resource, options); } - return global.fetch(resource, options); + return globalThis.fetch(resource, options); } /** diff --git a/src/http-api/index.ts b/src/http-api/index.ts index abc7391da16..bb1efa41ffc 100644 --- a/src/http-api/index.ts +++ b/src/http-api/index.ts @@ -60,8 +60,8 @@ export class MatrixHttpApi extends FetchHttpApi { } as Upload; const deferred = defer(); - if (global.XMLHttpRequest) { - const xhr = new global.XMLHttpRequest(); + if (globalThis.XMLHttpRequest) { + const xhr = new globalThis.XMLHttpRequest(); const timeoutFn = function (): void { xhr.abort(); @@ -73,7 +73,7 @@ export class MatrixHttpApi extends FetchHttpApi { xhr.onreadystatechange = function (): void { switch (xhr.readyState) { - case global.XMLHttpRequest.DONE: + case globalThis.XMLHttpRequest.DONE: callbacks.clearTimeout(timeoutTimer); try { if (xhr.status === 0) { diff --git a/src/http-api/interface.ts b/src/http-api/interface.ts index c06b850f311..57e8e6b0995 100644 --- a/src/http-api/interface.ts +++ b/src/http-api/interface.ts @@ -36,7 +36,7 @@ export type AccessTokens = { */ export type TokenRefreshFunction = (refreshToken: string) => Promise; export interface IHttpOpts { - fetchFn?: typeof global.fetch; + fetchFn?: typeof globalThis.fetch; baseUrl: string; idBaseUrl?: string; diff --git a/src/index.ts b/src/index.ts index 65e798c870f..a63d9f45a7d 100644 --- a/src/index.ts +++ b/src/index.ts @@ -16,10 +16,10 @@ limitations under the License. import * as matrixcs from "./matrix.ts"; -if (global.__js_sdk_entrypoint) { +if (globalThis.__js_sdk_entrypoint) { throw new Error("Multiple matrix-js-sdk entrypoints detected!"); } -global.__js_sdk_entrypoint = true; +globalThis.__js_sdk_entrypoint = true; export * from "./matrix.ts"; export default matrixcs; diff --git a/src/matrix.ts b/src/matrix.ts index 1a79e8b04c3..638a238d9c6 100644 --- a/src/matrix.ts +++ b/src/matrix.ts @@ -130,7 +130,7 @@ function amendClientOpts(opts: ICreateClientOpts): ICreateClientOpts { opts.store = opts.store ?? new MemoryStore({ - localStorage: global.localStorage, + localStorage: globalThis.localStorage, }); opts.scheduler = opts.scheduler ?? new MatrixScheduler(); opts.cryptoStore = opts.cryptoStore ?? cryptoStoreFactory(); diff --git a/src/realtime-callbacks.ts b/src/realtime-callbacks.ts index b59d145344a..8ca0c5d9c28 100644 --- a/src/realtime-callbacks.ts +++ b/src/realtime-callbacks.ts @@ -33,7 +33,7 @@ const TIMER_CHECK_PERIOD_MS = 1000; // counter, for making up ids to return from setTimeout let count = 0; -// the key for our callback with the real global.setTimeout +// the key for our callback with the real globalThis.setTimeout let realCallbackKey: NodeJS.Timeout | number; type Callback = { @@ -114,10 +114,10 @@ export function clearTimeout(key: number): void { } } -// use the real global.setTimeout to schedule a callback to runCallbacks. +// use the real globalThis.setTimeout to schedule a callback to runCallbacks. function scheduleRealCallback(): void { if (realCallbackKey) { - global.clearTimeout(realCallbackKey as NodeJS.Timeout); + globalThis.clearTimeout(realCallbackKey as NodeJS.Timeout); } const first = callbackList[0]; @@ -131,7 +131,7 @@ function scheduleRealCallback(): void { const delayMs = Math.min(first.runAt - timestamp, TIMER_CHECK_PERIOD_MS); debuglog("scheduleRealCallback: now:", timestamp, "delay:", delayMs); - realCallbackKey = global.setTimeout(runCallbacks, delayMs); + realCallbackKey = globalThis.setTimeout(runCallbacks, delayMs); } function runCallbacks(): void { @@ -158,7 +158,7 @@ function runCallbacks(): void { for (const cb of callbacksToRun) { try { - cb.func.apply(global, cb.params); + cb.func.apply(globalThis, cb.params); } catch (e) { logger.error("Uncaught exception in callback function", e); } diff --git a/src/rendezvous/transports/MSC4108RendezvousSession.ts b/src/rendezvous/transports/MSC4108RendezvousSession.ts index 98091471fae..ae7719bc24f 100644 --- a/src/rendezvous/transports/MSC4108RendezvousSession.ts +++ b/src/rendezvous/transports/MSC4108RendezvousSession.ts @@ -29,7 +29,7 @@ export class MSC4108RendezvousSession { public url?: string; private readonly client?: MatrixClient; private readonly fallbackRzServer?: string; - private readonly fetchFn?: typeof global.fetch; + private readonly fetchFn?: typeof globalThis.fetch; private readonly onFailure?: RendezvousFailureListener; private etag?: string; private expiresAt?: Date; @@ -42,7 +42,7 @@ export class MSC4108RendezvousSession { url, fetchFn, }: { - fetchFn?: typeof global.fetch; + fetchFn?: typeof globalThis.fetch; onFailure?: RendezvousFailureListener; url: string; }); @@ -52,7 +52,7 @@ export class MSC4108RendezvousSession { fallbackRzServer, fetchFn, }: { - fetchFn?: typeof global.fetch; + fetchFn?: typeof globalThis.fetch; onFailure?: RendezvousFailureListener; client?: MatrixClient; fallbackRzServer?: string; @@ -64,7 +64,7 @@ export class MSC4108RendezvousSession { client, fallbackRzServer, }: { - fetchFn?: typeof global.fetch; + fetchFn?: typeof globalThis.fetch; onFailure?: RendezvousFailureListener; url?: string; client?: MatrixClient; @@ -91,11 +91,11 @@ export class MSC4108RendezvousSession { return this._cancelled; } - private fetch(resource: URL | string, options?: RequestInit): ReturnType { + private fetch(resource: URL | string, options?: RequestInit): ReturnType { if (this.fetchFn) { return this.fetchFn(resource, options); } - return global.fetch(resource, options); + return globalThis.fetch(resource, options); } private async getPostEndpoint(): Promise { diff --git a/src/sync.ts b/src/sync.ts index 47be1ebc89a..2652a89a517 100644 --- a/src/sync.ts +++ b/src/sync.ts @@ -694,7 +694,7 @@ export class SyncApi { this.running = true; this.abortController = new AbortController(); - global.window?.addEventListener?.("online", this.onOnline, false); + globalThis.window?.addEventListener?.("online", this.onOnline, false); if (this.client.isGuest()) { // no push rules for guests, no access to POST filter for guests. @@ -779,10 +779,10 @@ export class SyncApi { public stop(): void { debuglog("SyncApi.stop"); // It is necessary to check for the existance of - // global.window AND global.window.removeEventListener. - // Some platforms (e.g. React Native) register global.window, - // but do not have global.window.removeEventListener. - global.window?.removeEventListener?.("online", this.onOnline, false); + // globalThis.window AND globalThis.window.removeEventListener. + // Some platforms (e.g. React Native) register globalThis.window, + // but do not have globalThis.window.removeEventListener. + globalThis.window?.removeEventListener?.("online", this.onOnline, false); this.running = false; this.abortController?.abort(); if (this.keepAliveTimer) {