### Build and Host Matrix JS SDK Example Source: https://github.com/matrix-org/matrix-js-sdk/blob/develop/examples/voip/README.md This snippet shows the commands to first build the SDK using npm, then navigate to the VoIP example directory, and finally start a simple Python HTTP server to host the example locally. ```bash $ npm run build $ cd examples/voip $ python -m SimpleHTTPServer 8003 ``` -------------------------------- ### Install matrix-js-sdk Source: https://github.com/matrix-org/matrix-js-sdk/blob/develop/README.md Install the matrix-js-sdk using pnpm. Using pnpm is recommended. ```bash pnpm add matrix-js-sdk ``` -------------------------------- ### Install Development Dependencies Source: https://github.com/matrix-org/matrix-js-sdk/blob/develop/README.md Install the necessary build tools for SDK development. ```bash $ pnpm install ``` -------------------------------- ### Start the Matrix Client Source: https://github.com/matrix-org/matrix-js-sdk/blob/develop/README.md Start the Matrix client to begin receiving updates. The initialSyncLimit can be set to control the amount of initial data fetched. ```javascript await client.startClient({ initialSyncLimit: 10 }); ``` -------------------------------- ### Handle Client Synchronization Source: https://github.com/matrix-org/matrix-js-sdk/blob/develop/README.md Listen for the 'PREPARED' state during client synchronization. This event indicates that the client has finished its initial setup. ```javascript client.once(ClientEvent.sync, function (state, prevState, res) { if (state === "PREPARED") { console.log("prepared"); } else { console.log(state); process.exit(1); } }); ``` -------------------------------- ### Install and Run Terminal App Source: https://github.com/matrix-org/matrix-js-sdk/blob/develop/examples/node/README.md Commands to install dependencies and execute the terminal application. ```bash $ npm install $ node app ``` -------------------------------- ### Terminal Application Output Source: https://github.com/matrix-org/matrix-js-sdk/blob/develop/examples/node/README.md Example output showing the room list, command help, and room interaction logs. ```text Room List: [0] Room Invite (0 members) [1] Room Invite (0 members) [2] My New Room (2 members) [3] @megan:localhost (1 members) [4] True Stuff (7 members) Global commands: '/help' : Show this help. Room list index commands: '/enter ' Enter a room, e.g. '/enter 5' Room commands: '/exit' Return to the room list index. '/members' Show the room member list. $ /enter 2 [2015-06-12 15:14:54] Megan2 <<< herro [2015-06-12 15:22:58] Me >>> hey [2015-06-12 15:23:00] Me >>> whats up? [2015-06-12 15:25:40] Megan2 <<< not a lot [2015-06-12 15:25:47] Megan2 --- [State: m.room.topic updated to: {"topic":"xXx_topic_goes_here_xXx"}] [2015-06-12 15:25:55] Megan2 --- [State: m.room.name updated to: {"name":"My Newer Room"}] ``` -------------------------------- ### Room Membership List Output Source: https://github.com/matrix-org/matrix-js-sdk/blob/develop/examples/node/README.md Example output displayed after executing the /members command. ```text $ /members Membership list for room "My Newer Room" ---------------------------------------- join :: @example:localhost (Me) leave :: @fred:localhost (@fred:localhost) invite :: @earl:localhost (@earl:localhost) join :: Megan2 (@megan:localhost) invite :: @toejam:localhost (@toejam:localhost) ``` -------------------------------- ### Automatically Join Rooms on Invite Source: https://github.com/matrix-org/matrix-js-sdk/blob/develop/README.md Listens for new invitations and automatically joins the room. Ensure the client is started after setting up the listener. ```javascript matrixClient.on(RoomEvent.MyMembership, function (room, membership, prevMembership) { if (membership === KnownMembership.Invite) { matrixClient.joinRoom(room.roomId).then(function () { console.log("Auto-joined %s", room.roomId); }); } }); matrixClient.startClient(); ``` -------------------------------- ### Object Key Naming Conventions (TypeScript/JavaScript) Source: https://github.com/matrix-org/matrix-js-sdk/blob/develop/code_style.md Provides examples of object key naming, preferring non-string keys (like computed property names) over string literals when possible, especially for event types. ```typescript { property: "value", "m.unavoidable": true, [EventType.RoomMessage]: true, } ``` -------------------------------- ### Specify changelog for downstream projects Source: https://github.com/matrix-org/matrix-js-sdk/blob/develop/CONTRIBUTING.md When fixing bugs in downstream projects, specify the project name followed by the changelog entry. This example targets 'element-web'. ```markdown Notes: Fix a bug where the `herd()` function would only work on Tuesdays element-web notes: Fix a bug where the 'Herd' button only worked on Tuesdays ``` -------------------------------- ### Initialize Matrix Client Source: https://github.com/matrix-org/matrix-js-sdk/blob/develop/README.md Sets up the basic configuration for a Matrix client with base URL, access token, and user ID. ```javascript import * as sdk from "matrix-js-sdk"; const myUserId = "@example:localhost"; const myAccessToken = "QGV4YW1wbGU6bG9jYWxob3N0.qPEvLuYfNBjxikiCjP"; const matrixClient = sdk.createClient({ baseUrl: "http://localhost:8008", accessToken: myAccessToken, userId: myUserId, }); ``` -------------------------------- ### Build Browser Version Source: https://github.com/matrix-org/matrix-js-sdk/blob/develop/README.md Build a browser version of the SDK from scratch during development. ```bash $ pnpm build ``` -------------------------------- ### Run Linting Source: https://github.com/matrix-org/matrix-js-sdk/blob/develop/README.md Perform linting on the SDK code. ```bash $ pnpm lint ``` -------------------------------- ### Run Tests Source: https://github.com/matrix-org/matrix-js-sdk/blob/develop/README.md Execute the SDK's test suite. ```bash $ pnpm test ``` -------------------------------- ### Create a Matrix Client Source: https://github.com/matrix-org/matrix-js-sdk/blob/develop/README.md Create a new Matrix client instance and fetch public rooms. The client requires a base URL for the Matrix homeserver. ```javascript import * as sdk from "matrix-js-sdk"; const client = sdk.createClient({ baseUrl: "https://matrix.org" }); client.publicRooms(function (err, data) { console.log("Public Rooms: %s", JSON.stringify(data)); }); ``` -------------------------------- ### Generate API Documentation Source: https://github.com/matrix-org/matrix-js-sdk/blob/develop/README.md Commands to generate and serve the API documentation locally using pnpm and Python's http.server. ```bash $ pnpm gendoc $ cd docs $ python -m http.server 8005 ``` -------------------------------- ### Initialize Secret Storage with Callbacks Source: https://github.com/matrix-org/matrix-js-sdk/blob/develop/README.md Set up secret storage for end-to-end encryption by providing callbacks for retrieving and creating secret storage keys. This ensures secure storage of encryption keys. ```javascript const matrixClient = sdk.createClient({ ..., cryptoCallbacks: { getSecretStorageKey: async (keys) => { // This function should prompt the user to enter their secret storage key. return mySecretStorageKeys; }, }, }); matrixClient.getCrypto().bootstrapSecretStorage({ // This function will be called if a new secret storage key (aka recovery key) is needed. // You should prompt the user to save the key somewhere, because they will need it to unlock secret storage in future. createSecretStorageKey: async () => { return mySecretStorageKey; }, }); ``` -------------------------------- ### Bootstrap Cross-Signing Source: https://github.com/matrix-org/matrix-js-sdk/blob/develop/README.md Initialize cross-signing to enable device verification and user verification. This requires a callback to authenticate the upload of new public cross-signing keys to the server. ```javascript matrixClient.getCrypto().bootstrapCrossSigning({ authUploadDeviceSigningKeys: async (makeRequest) => { return makeRequest(authDict); }, }); ``` -------------------------------- ### Initialize Matrix Client with Rust Crypto Source: https://github.com/matrix-org/matrix-js-sdk/blob/develop/README.md Create a new matrix client and initialize its end-to-end encryption support using the Rust-based crypto implementation. This is the first step for enabling E2EE. ```javascript const matrixClient = sdk.createClient({ baseUrl: "http://localhost:8008", accessToken: myAccessToken, userId: myUserId, }); // Initialize to enable end-to-end encryption support. await matrixClient.initRustCrypto(); ``` -------------------------------- ### Listen for Legacy Crypto Store Migration Progress Source: https://github.com/matrix-org/matrix-js-sdk/blob/develop/README.md Listen to the CryptoEvent.LegacyCryptoStoreMigrationProgress event to follow migration progress. When progress equals total and both are -1, the migration is finished. ```javascript // When progress === total === -1, the migration is finished. matrixClient.on(CryptoEvent.LegacyCryptoStoreMigrationProgress, (progress, total) => { ... }); ``` -------------------------------- ### Migrate Legacy Crypto to Rust Crypto Source: https://github.com/matrix-org/matrix-js-sdk/blob/develop/README.md Provide legacy crypto store and pickle key to createClient to migrate data. The migration is automatic when calling initRustCrypto. ```javascript // You should provide the legacy crypto store and the pickle key to the matrix client in order to migrate the data. const matrixClient = sdk.createClient({ cryptoStore: myCryptoStore, pickleKey: myPickleKey, baseUrl: "http://localhost:8008", accessToken: myAccessToken, userId: myUserId, }); // The migration will be done automatically when you call `initRustCrypto`. await matrixClient.initRustCrypto(); ``` -------------------------------- ### Listen for Matrix Events Source: https://github.com/matrix-org/matrix-js-sdk/blob/develop/README.md This snippet demonstrates how to listen for various events emitted by the MatrixClient. It shows how to subscribe to low-level MatrixEvents and specific RoomMemberEvent.Typing events. ```javascript // Listen for low-level MatrixEvents client.on(ClientEvent.Event, function (event) { console.log(event.getType()); }); // Listen for typing changes client.on(RoomMemberEvent.Typing, function (event, member) { if (member.typing) { console.log(member.name + " is typing..."); } else { console.log(member.name + " stopped typing."); } }); // start the client to setup the connection to the server client.startClient(); ``` -------------------------------- ### Print Membership Lists on Change Source: https://github.com/matrix-org/matrix-js-sdk/blob/develop/README.md Logs the current membership list for a room whenever it changes. It displays the room name followed by a list of members and their membership status. ```javascript matrixClient.on(RoomStateEvent.Members, function (event, state, member) { const room = matrixClient.getRoom(state.roomId); if (!room) { return; } const memberList = state.getMembers(); console.log(room.name); console.log(Array(room.name.length + 1).join("=")); // underline for (var i = 0; i < memberList.length; i++) { console.log("(%s) %s", memberList[i].membership, memberList[i].name); } }); matrixClient.startClient(); ``` -------------------------------- ### Add detailed changelog entry Source: https://github.com/matrix-org/matrix-js-sdk/blob/develop/CONTRIBUTING.md Use the 'Notes:' annotation in the pull request description to provide a detailed changelog entry. Include a URL to the relevant issue if applicable. ```markdown Notes: Fix a bug (https://github.com/matrix-org/notaproject/issues/123) where the 'Herd' button would not herd more than 8 Llamas if the moon was in the waxing gibbous phase ``` -------------------------------- ### Download Authenticated Media in NodeJS Source: https://github.com/matrix-org/matrix-js-sdk/blob/develop/README.md This snippet shows how to download or thumbnail media from a Matrix server that requires authentication. It constructs the download URL and fetches the media using the client's access token. ```javascript const downloadUrl = client.mxcUrlToHttp( /*mxcUrl=*/ "mxc://example.org/abc123", // the MXC URI to download/thumbnail, typically from an event or profile /*width=*/ undefined, // part of the thumbnail API. Use as required. /*height=*/ undefined, // part of the thumbnail API. Use as required. /*resizeMethod=*/ undefined, // part of the thumbnail API. Use as required. /*allowDirectLinks=*/ false, // should generally be left `false`. /*allowRedirects=*/ true, // implied supported with authentication /*useAuthentication=*/ true, // the flag we're after in this example ); const img = await fetch(downloadUrl, { headers: { Authorization: `Bearer ${client.getAccessToken()}`, }, }); // Do something with `img`. ``` -------------------------------- ### Interface and Type Definitions (TypeScript) Source: https://github.com/matrix-org/matrix-js-sdk/blob/develop/code_style.md Demonstrates the preferred way to define object structures using interfaces and parameter-value types using type aliases. It also shows the correct syntax for callback function types within interfaces. ```typescript interface MyObject { hasString: boolean; } type Options = MyObject | string; function doThing(arg: Options) { // ... } ``` ```typescript interface Test { myCallback: (arg: string) => Promise; } ``` -------------------------------- ### Configure VoIP Test Constants Source: https://github.com/matrix-org/matrix-js-sdk/blob/develop/examples/voip/index.html The browserTest.js file requires configuration of specific constants to enable VoIP functionality. Users must update these values to match their environment before initiating calls. ```javascript // Edit these constants in browserTest.js const VOIP_CONFIG = { homeserver: "https://matrix.org", userId: "@user:example.com", accessToken: "YOUR_ACCESS_TOKEN" }; ``` -------------------------------- ### Check and Reset Key Backup Source: https://github.com/matrix-org/matrix-js-sdk/blob/develop/README.md Check if a server-side key backup exists and create a new one if it does not. This is essential for recovering encryption keys. ```javascript // Check if we have a key backup. // If checkKeyBackupAndEnable returns null, there is no key backup. const hasKeyBackup = (await matrixClient.getCrypto().checkKeyBackupAndEnable()) !== null; // Create the key backup await matrixClient.getCrypto().resetKeyBackup(); ``` -------------------------------- ### Async/Await Usage in TypeScript Source: https://github.com/matrix-org/matrix-js-sdk/blob/develop/code_style.md Illustrates the preferred use of async-await syntax over traditional promise chaining for handling asynchronous operations. This improves code clarity and maintainability. ```typescript async function () { const result = await anotherAsyncFunction(); // ... } ``` -------------------------------- ### Iterate Through Stored Room Timelines Source: https://github.com/matrix-org/matrix-js-sdk/blob/develop/README.md Iterate through all stored rooms and their timelines using the client's memory store. This logs the event content for each timeline entry. ```javascript Object.keys(client.store.rooms).forEach((roomId) => { client.getRoom(roomId).timeline.forEach((t) => { console.log(t.event); }); }); ``` -------------------------------- ### TypeScript Test Structure with Describe Blocks Source: https://github.com/matrix-org/matrix-js-sdk/blob/develop/code_style.md Provides a template for structuring tests in TypeScript using 'describe' blocks for organizing tests by component or utility function. It includes standard hooks like 'beforeEach' and 'afterEach'. ```typescript // Describe the class, component, or file name. describe("FooComponent", () => { // all test inspecific variables go here beforeEach(() => { // exclude if not used. }); afterEach(() => { // exclude if not used. }); // Use "it should..." terminology it("should call the correct API", async () => { // test-specific variables go here // function calls/state changes go here // expectations go here }); }); // If the file being tested is a utility class: describe("foo-utils", () => { describe("firstUtilFunction", () => { it("should...", async () => { // ... }); }); describe("secondUtilFunction", () => { it("should...", async () => { // ... }); }); }); ``` -------------------------------- ### Document breaking changes Source: https://github.com/matrix-org/matrix-js-sdk/blob/develop/CONTRIBUTING.md For breaking changes, use the 'Notes:' section to explain migration steps. The 'X-Breaking-Change' label will automatically indicate a major version bump. ```markdown Notes: Remove legacy `Camelopard` class. `Giraffe` should be used instead. ``` -------------------------------- ### Object Shorthand Declarations (TypeScript/JavaScript) Source: https://github.com/matrix-org/matrix-js-sdk/blob/develop/code_style.md Shows the use of shorthand syntax for object property declarations when the property name matches the variable name, allowing for concise object creation. ```typescript { room, prop: this.prop, } ``` ```typescript { room, prop: this.prop } ``` -------------------------------- ### VoIP Video Element Styling Source: https://github.com/matrix-org/matrix-js-sdk/blob/develop/examples/voip/index.html CSS styles used to define the dimensions and layout of the video background and video elements during a call session. ```css .video-background { height: 500px; margin: 10px; } .video-element { height: 100%; } ``` -------------------------------- ### Developer Certificate of Origin (DCO) Text Source: https://github.com/matrix-org/matrix-js-sdk/blob/develop/CONTRIBUTING.md The full text of the Developer Certificate of Origin, Version 1.1. This must be agreed to for contributions. ```text Developer Certificate of Origin Version 1.1 Copyright (C) 2004, 2006 The Linux Foundation and its contributors. 660 York Street, Suite 102, San Francisco, CA 94110 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Developer's Certificate of Origin 1.1 By making a contribution to this project, I certify that: (a) The contribution was created in whole or in part by me and I have the right to submit it under the open source license indicated in the file; or (b) The contribution is based upon previous work that, to the best of my knowledge, is covered under an appropriate open source license and I have the right under that license to submit that work with modifications, whether created in whole or in part by me, under the same open source license (unless I am permitted to submit under a different license), as indicated in the file; or (c) The contribution was provided directly to me by some other person who certified (a), (b) or (c) and I have not modified it. (d) I understand and agree that this project and the contribution are public and that a record of the contribution (including all personal information I submit with it, including my sign-off) is maintained indefinitely and may be redistributed consistent with this project or the open source license(s) involved. ``` -------------------------------- ### Export IndexedDB content to JSON Source: https://github.com/matrix-org/matrix-js-sdk/blob/develop/spec/test-utils/test_indexeddb_cryptostore_dump/README.md This script iterates through all object stores in a specified IndexedDB database, serializes the data into a JSON object, and triggers a browser download. It requires the 'saveAs' utility to be available in the global scope. ```javascript async function exportIndexedDb(name) { const db = await new Promise((resolve, reject) => { const dbReq = indexedDB.open(name); dbReq.onerror = reject; dbReq.onsuccess = () => resolve(dbReq.result); }); const storeNames = db.objectStoreNames; const exports = {}; for (const store of storeNames) { exports[store] = []; const txn = db.transaction(store, "readonly"); const objectStore = txn.objectStore(store); await new Promise((resolve, reject) => { const cursorReq = objectStore.openCursor(); cursorReq.onerror = reject; cursorReq.onsuccess = (event) => { const cursor = event.target.result; if (cursor) { const entry = { value: cursor.value }; if (!objectStore.keyPath) { entry.key = cursor.key; } exports[store].push(entry); cursor.continue(); } else { resolve(); } }; }); } return exports; } window.saveAs( new Blob([JSON.stringify(await exportIndexedDb("matrix-js-sdk:crypto"), null, 2)], { type: "application/json;charset=utf-8", }), "dump.json", ); ``` -------------------------------- ### Optional vs. Nullable Parameters (TypeScript) Source: https://github.com/matrix-org/matrix-js-sdk/blob/develop/code_style.md Illustrates the preference for using `T | null` over optional parameters (`T?`) for function arguments, especially when the absence of a value needs explicit acknowledgment. This promotes clarity about whether the caller intentionally omitted the value. ```typescript function doThingWithRoom( thing: string, room: string | null, // require the caller to specify ) { // ... } ``` -------------------------------- ### Variable Declaration with Type Annotation (TypeScript) Source: https://github.com/matrix-org/matrix-js-sdk/blob/develop/code_style.md Illustrates how to declare a variable without an initial value in TypeScript, requiring an explicit type annotation. ```typescript let errorMessage: string; ``` -------------------------------- ### Print Room Messages Source: https://github.com/matrix-org/matrix-js-sdk/blob/develop/README.md Logs messages from all rooms to the console, filtering for 'm.room.message' events. It avoids printing paginated results. ```javascript matrixClient.on(RoomEvent.Timeline, function (event, room, toStartOfTimeline) { if (toStartOfTimeline) { return; // don't print paginated results } if (event.getType() !== "m.room.message") { return; // only print messages } console.log( // the room name will update with m.room.name events automatically "(%s) %s :: %s", room.name, event.getSender(), event.getContent().body, ); }); matrixClient.startClient(); ``` -------------------------------- ### Mass Sign-off using Git Rebase Source: https://github.com/matrix-org/matrix-js-sdk/blob/develop/CONTRIBUTING.md Command to mass sign off commits if you forgot to do so before creating a pull request, for Git 2.17+. ```git git rebase --signoff origin/develop ``` -------------------------------- ### Conditional Statement Formatting (TypeScript/JavaScript) Source: https://github.com/matrix-org/matrix-js-sdk/blob/develop/code_style.md Demonstrates the preferred formatting for conditional statements in TypeScript/JavaScript. Single-line bodies should not use curly braces, while multi-line blocks require them and should have spaces around the condition. ```typescript if (x) doThing(); ``` ```typescript if (x) { doThing(); } ``` -------------------------------- ### String Literal Quoting in TypeScript Source: https://github.com/matrix-org/matrix-js-sdk/blob/develop/code_style.md Demonstrates the use of double quotes for strings, with a fallback to single quotes when the string itself contains double quotes. This ensures consistency and readability. ```typescript const example1 = "simple string"; const example2 = 'string containing "double quotes"'; ``` -------------------------------- ### Listen for Room Timeline Events Source: https://github.com/matrix-org/matrix-js-sdk/blob/develop/README.md Listen for new message events in a room's timeline. This snippet filters for 'm.room.message' types and logs the message body. ```javascript client.on(RoomEvent.Timeline, function (event, room, toStartOfTimeline) { if (event.getType() !== "m.room.message") { return; // only use messages } console.log(event.event.content.body); }); ``` -------------------------------- ### Suppress changelog entry Source: https://github.com/matrix-org/matrix-js-sdk/blob/develop/CONTRIBUTING.md To prevent a changelog entry for a pull request, use 'Notes: none'. This is the default for PRs labeled with 'T-Task'. ```markdown Notes: none ``` -------------------------------- ### Send a Message in a Room Source: https://github.com/matrix-org/matrix-js-sdk/blob/develop/README.md Send a text message to a specified room. The message content includes the body and message type. ```javascript const content = { body: "message text", msgtype: "m.text", }; client.sendEvent("roomId", "m.room.message", content, "", (err, res) => { console.log(err); }); ``` -------------------------------- ### Boolean Type Enforcement (TypeScript/JavaScript) Source: https://github.com/matrix-org/matrix-js-sdk/blob/develop/code_style.md Explains the importance of ensuring boolean variables are truly boolean. It shows correct and incorrect ways to derive boolean values, emphasizing the use of `!!` or `Boolean()` for explicit conversion and avoiding assignment of non-boolean types to boolean variables. ```typescript const isRealUser = !!userId && ...; // good ``` ```typescript const isRealUser = Boolean(userId) && Boolean(userName); // also good ``` ```typescript const isRealUser = Boolean(userId) && isReal; // also good (where isReal is another boolean variable) ``` ```typescript const isRealUser = Boolean(userId && userName); // also fine ``` ```typescript const isRealUser = Boolean(userId || userName); // good: same as && ``` ```typescript const isRealUser = userId && ...; // bad: isRealUser is userId's type, not a boolean ``` ```typescript if (userId) // fine: userId is evaluated for truthiness, not stored as a boolean ``` -------------------------------- ### Sign-off Line for Commits Source: https://github.com/matrix-org/matrix-js-sdk/blob/develop/CONTRIBUTING.md The required line to include in your commit or pull request comment to signify agreement with the DCO. ```git Signed-off-by: Your Name ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.