### Alternative Setup with GNU Make Source: https://github.com/conversejs/converse.js/blob/master/docs/src/content/docs/development/setup-dev-environment.md If GNU Make is installed, these commands provide an alternative way to start the development server and watcher. ```bash make serve_bg make watch ``` -------------------------------- ### Install Dependencies and Start Development Server Source: https://github.com/conversejs/converse.js/blob/master/CONTRIBUTING.md Run these commands to install project dependencies, start a background development server, and watch for file changes. ```bash npm install npm run serve & npm run watch ``` -------------------------------- ### Development Setup for @converse/log Source: https://github.com/conversejs/converse.js/blob/master/src/log/README.md Instructions for cloning the repository, navigating to the log directory, and installing dependencies for local development and testing. ```bash git clone https://github.com/conversejs/converse.js.git cd src/log npm install npm test ``` -------------------------------- ### Install and Build Converse.js Source: https://github.com/conversejs/converse.js/blob/master/README.md Clone the repository, install dependencies, build the project, and start a local development server. Access the application via http://localhost:8008/dev.html. ```bash git clone git@github.com:conversejs/converse.js.git cd converse.js git clone https://github.com/conversejs/media.git media; // To see images like sponsorship logos npm install npm run build npm run serve -- -p 8008 ``` -------------------------------- ### Install Dependencies Source: https://github.com/conversejs/converse.js/blob/master/docs/src/content/docs/documentation.md Navigate to the docs directory and install project dependencies using npm. ```bash cd docs npm install ``` -------------------------------- ### Install @converse/log Source: https://github.com/conversejs/converse.js/blob/master/src/log/README.md Install the package using npm. This is the first step before using the logging utility. ```bash npm install @converse/log ``` -------------------------------- ### Start Development Server with Live Reloading Source: https://github.com/conversejs/converse.js/blob/master/CONTRIBUTING.md Use this command to start a development server that provides live reloading when source files change. ```bash make devserver ``` -------------------------------- ### Run Development Server Source: https://github.com/conversejs/converse.js/blob/master/docs/src/content/docs/documentation.md Start a local development server with live-reloading to preview the documentation. Access it at http://localhost:4321. ```bash npm run dev ``` -------------------------------- ### Minimal Converse.js HTML Example Source: https://github.com/conversejs/converse.js/blob/master/docs/src/content/docs/quickstart.md A complete, minimal HTML file to get Converse.js running. Save this as `index.html` and open it in your browser to see the login screen. ```html My Chat ``` -------------------------------- ### Create Astro Project with Starlight Template Source: https://github.com/conversejs/converse.js/blob/master/docs/README.md Use this command to initialize a new Astro project with the Starlight template. Ensure you have Node.js installed. ```bash npm create astro@latest -- --template starlight ``` -------------------------------- ### Development Builds Source: https://github.com/conversejs/converse.js/blob/master/docs/src/content/docs/development/builds.md Commands for creating unminified development builds and starting the development server with live reloading. ```bash npm run dev ``` ```bash npm run watch ``` ```bash npm run devserver ``` -------------------------------- ### Development Server Command Source: https://github.com/conversejs/converse.js/blob/master/AGENTS.md Starts a development server with live reload functionality, typically on http://localhost:8080. ```bash # Dev server with live reload npm run devserver # Starts on http://localhost:8080 ``` -------------------------------- ### Initialize Converse with prebind authentication Source: https://github.com/conversejs/converse.js/blob/master/docs/src/content/docs/configuration.md This example shows how to initialize Converse using the 'prebind' authentication method, which attaches to an existing BOSH session. It requires `bosh_service_url`, `jid`, `prebind_url`, and `auto_login` to be set. ```javascript converse.initialize({ bosh_service_url: 'https://bind.example.com', jid: 'me@example.com', authentication: 'prebind', prebind_url: 'http://example.com/api/prebind', auto_login: true, allow_logout: false }); ``` -------------------------------- ### Start Development Server with Live Reloading Source: https://github.com/conversejs/converse.js/blob/master/docs/src/content/docs/development/setup-dev-environment.md Use this command to start the RSPack development server, which includes live reloading for a more seamless development experience. ```bash make devserver ``` ```bash npm run devserver ``` -------------------------------- ### Alternative Command for Live Reloading Source: https://github.com/conversejs/converse.js/blob/master/CONTRIBUTING.md An alternative npm script to start the development server with live reloading capabilities. ```bash npm run devserver ``` -------------------------------- ### Initialize Converse.js with Full HTML Setup Source: https://context7.com/conversejs/converse.js/llms.txt This snippet shows the complete HTML structure required to load Converse.js and initialize it with a comprehensive set of configuration options. It includes CDN links for CSS and JS, and demonstrates settings for connection, authentication, display mode, behavior, message archiving, and localization. ```html My Chat ``` -------------------------------- ### Initialize Converse.js with Fullscreen View Source: https://github.com/conversejs/converse.js/blob/master/fullscreen.html Configure Converse.js for a fullscreen chat experience. Ensure JavaScript is enabled in the browser. This example sets a 'dracula' theme, uses 'login' authentication, and specifies the BOSH service URL for testing. ```javascript converse.initialize({ theme: 'dracula', authentication: 'login', auto_away: 300, auto_reconnect: true, bosh_service_url: 'https://conversejs.org/http-bind/', // Please use this connection manager only for testing purposes message_archiving: 'always', view_mode: 'fullscreen', show_background: true, }); ``` -------------------------------- ### Anonymous Login for Converse.js Source: https://context7.com/conversejs/converse.js/llms.txt Configure Converse.js for anonymous login, allowing users to connect without an account. Ensure the XMPP server supports anonymous authentication. Combine with `auto_login: true` for immediate authentication on page load. This example also shows how to auto-join an embedded room for a read-only setup. ```javascript converse.initialize({ bosh_service_url: 'https://conversejs.org/http-bind/', authentication: 'anonymous', jid: 'conversejs.org', // Server domain (not a full JID) auto_login: true, allow_logout: false, // Auto-join an embedded room for a read-only or kiosk setup auto_join_rooms: ['support@conference.example.com'], view_mode: 'embedded', singleton: true, }); ``` -------------------------------- ### Initialize Converse.js with Options Source: https://github.com/conversejs/converse.js/blob/master/dev.html Demonstrates the initialization of Converse.js with a comprehensive set of configuration options. This includes language, theme, connection details, and plugin whitelisting. Ensure the BOSH service URL is appropriate for your environment. ```javascript converse.initialize({ i18n: 'af', theme: 'nordic', dark_theme: 'dracula', auto_away: 300, loglevel: 'debug', show_background: true, message_archiving: 'always', muc_show_logs_before_join: true, notify_all_room_messages: ['discuss@conference.conversejs.org'], fetch_url_headers: true, whitelisted_plugins: ['converse-debug'], bosh_service_url: 'https://conversejs.org/http-bind/', // Please use this connection manager only for testing purposes // view_mode: 'overlayed', show_controlbox_by_default: true, // websocket_url: 'wss://conversejs.org/xmpp-websocket', // websocket_url: 'ws://chat.example.org:5380/xmpp-websocket', // connection_options: { // worker: '/dist/shared-connection-worker.js' // } }); ``` -------------------------------- ### Configure auto_join_private_chats Source: https://github.com/conversejs/converse.js/blob/master/docs/src/content/docs/configuration.md Automatically start private chats with specified JIDs upon login. ```javascript [ 'tom@example.org', 'dick@example.org', 'harry@example.org' ] ``` -------------------------------- ### Basic Usage Source: https://github.com/conversejs/converse.js/blob/master/src/log/README.md Demonstrates how to import, configure, and use the logging methods provided by the utility. ```APIDOC ## Basic Usage ```javascript import log from '@converse/log'; // Configure log level (default: 'info') log.setLogLevel('debug'); // Log messages log.debug('Detailed debug information'); log.info('System status update'); log.warn('Potential issue detected'); log.error('Operation failed'); log.fatal('Critical system failure'); // Pass multiple arguments like console log.debug('User', username, 'logged in', { timestamp: Date.now() }); // Use %c for CSS styling in the browser console log.debug('%c%s', 'color: darkgoldenrod', xmlStanza.outerHTML); ``` ``` -------------------------------- ### Build HTML Documentation Source: https://github.com/conversejs/converse.js/blob/master/AGENTS.md Use `make doc` to build the HTML documentation. For a development server with live reload, use `npm run docs:dev`. Production builds are created with `npm run docs:build`. ```bash make doc # Build HTML documentation npm run docs:dev # Start dev server with live reload npm run docs:build # Build for production ``` -------------------------------- ### Build Distribution Files Source: https://github.com/conversejs/converse.js/blob/master/docs/src/content/docs/development/builds.md Run this command to generate all CSS and JavaScript bundles for distribution. The output is placed in the `./dist` directory. ```bash npm run build ``` -------------------------------- ### Test Pattern with mock.initConverse Source: https://github.com/conversejs/converse.js/blob/master/src/headless/AGENTS.md Example of initializing Converse for testing using mock.initConverse. Use u.waitUntil() for asynchronous assertions. ```javascript /* global converse */ import { mock, domain } from '../../tests/mock.js'; describe('My Plugin', function () { it('does something', mock.initConverse([], {}, async function (_converse) { // _converse is the private instance // Use u.waitUntil() for async assertions const { u } = window.converse.env; await u.waitUntil(() => _converse.state.chatboxes.length > 0); }) ); }); ``` -------------------------------- ### Create CDN Build Source: https://github.com/conversejs/converse.js/blob/master/docs/src/content/docs/development/builds.md Run this command to create a build optimized for Content Delivery Network (CDN) deployment, featuring absolute paths. ```bash npm run cdn ``` -------------------------------- ### Restrict SASL Authentication Mechanisms Source: https://github.com/conversejs/converse.js/blob/master/docs/src/content/docs/configuration.md Pass a map of configuration options to the Strophe.Connection constructor to restrict supported SASL authentication mechanisms. This example restricts to SASLMD5. ```javascript converse.initialize({ connection_options: { 'mechanisms': [ converse.env.Strophe.SASLMD5, ] } }); ``` -------------------------------- ### Nginx Reverse Proxy for Production WebSocket Setup Source: https://context7.com/conversejs/converse.js/llms.txt Configure Nginx to proxy WebSocket connections, enabling TLS termination and same-origin serving for production environments. ```nginx server { listen 80; server_name converse.example.com; location / { proxy_pass http://localhost:8080; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; # WebSocket support proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; } } ``` -------------------------------- ### Production Build Commands Source: https://github.com/conversejs/converse.js/blob/master/AGENTS.md Creates minified production-ready bundles for various formats (ESM, CJS) and CSS. Use for deployment. ```bash # Production build (minified) npm run build # Full build: headless + ESM + CJS + CSS npm run build:headless # Build headless package only npm run build:esm # Build ESM bundle npm run build:cjs # Build CommonJS bundle npm run build:website-css # Build website CSS npm run build:website-min-css # Build and minify website CSS ``` -------------------------------- ### Defining a Lit Component in Converse.js Source: https://github.com/conversejs/converse.js/blob/master/AGENTS.md Provides an example of how to define a custom element using Lit, extending `CustomElement` and utilizing `properties` and `state` for component behavior and rendering. ```javascript import { html } from 'lit'; import { CustomElement } from 'shared/components/element.js'; export default class MyComponent extends CustomElement { static get properties() { return { model: { type: Object }, some_state: { state: true }, // Internal state }; } async initialize() { await this.model.initialized; // Listen to model changes to trigger re-render this.listenTo(this.model, 'change', () => this.requestUpdate()); this.requestUpdate(); } render() { return html`
...
`; } } customElements.define('my-component', MyComponent); ``` -------------------------------- ### Initialize Converse.js with Credentials URL Source: https://context7.com/conversejs/converse.js/llms.txt Demonstrates how to initialize Converse.js and configure it to fetch login credentials from a specified URL, enabling auto-login. ```APIDOC ## Credentials URL — Auto-login with dynamic credentials Fetches login credentials (JID + password or token) from a backend endpoint. Enables automatic login and re-authentication without storing credentials in the page source. ```javascript converse.initialize({ websocket_url: 'wss://xmpp.example.com/ws', authentication: 'login', auto_login: true, auto_reconnect: true, // Server must return: {"jid": "alice@example.com/resource", "password": "token123"} credentials_url: '/api/xmpp-credentials', }); ``` ``` -------------------------------- ### Get Chat Model(s) Source: https://context7.com/conversejs/converse.js/llms.txt Explains how to use `api.chats.get` to retrieve ChatBox models for one-on-one chats without necessarily opening them in the UI. It can fetch a specific chat or all open private chats. ```APIDOC ## `api.chats.get(jids)` — Get Chat Model(s) Retrieves the ChatBox model(s) for one-on-one chats without opening them in the UI. ```javascript converse.plugins.add('chat-getter-example', { initialize() { const { api } = this._converse; api.listen.on('chatBoxesFetched', async () => { // Get a specific chat model const chat = await api.chats.get('alice@example.com'); if (chat) { console.log('Chat type:', chat.get('type')); console.log('Unread count:', chat.get('num_unread')); } // Get all open private chats const allChats = await api.chats.get(); allChats.forEach(c => console.log(c.get('jid'))); }); } }); ``` ``` -------------------------------- ### Initialize Converse.js with BOSH or WebSocket URL Source: https://github.com/conversejs/converse.js/blob/master/docs/src/content/docs/quickstart.md Add this script before your closing `` tag to initialize Converse.js. Replace the placeholder URL with your XMPP server's BOSH or WebSocket endpoint. ```html ``` -------------------------------- ### Core and Utility Imports in Converse.js Source: https://github.com/conversejs/converse.js/blob/master/AGENTS.md Illustrates the recommended import patterns for core modules, logging, the Lit framework, local files, and utility functions from `@converse/headless`. ```javascript // Headless core imports import { _converse, api, converse } from '@converse/headless'; // Logging import { log } from '@converse/log'; // Lit framework import { html, css } from 'lit'; // Relative imports for local files import ChatView from './chat.js'; import './styles/index.scss'; // Utilities import { u } from '@converse/headless'; // Utility functions const { dayjs, Strophe, sizzle } = converse.env; // Common libraries ``` -------------------------------- ### Programmatic Login and Logout with Converse.js API Source: https://context7.com/conversejs/converse.js/llms.txt Use `api.user.login` and `api.user.logout` for programmatic user authentication. `login` can be called without parameters if `credentials_url` or `prebind_url` is configured. Listen for the 'connected' event to get the current user's JID. ```javascript converse.plugins.add('auth-control', { initialize() { const { api } = this._converse; // Programmatic login (e.g., after your own auth form submits) document.getElementById('my-login-form').addEventListener('submit', async (e) => { e.preventDefault(); const jid = document.getElementById('jid').value; const password = document.getElementById('password').value; try { await api.user.login(jid, password); console.log('Logged in as:', api.user.jid()); } catch (err) { console.error('Login failed:', err); } }); // Programmatic logout document.getElementById('logout-btn').addEventListener('click', async () => { await api.user.logout(); console.log('User has been logged out'); }); // Get current user's full JID api.listen.on('connected', () => { console.log('Connected JID:', api.user.jid()); // e.g. "alice@example.com/browser" }); } }); ``` -------------------------------- ### Get MUC Room Models Source: https://context7.com/conversejs/converse.js/llms.txt Retrieve MUC room models using `api.rooms.get`. If called without arguments, it returns all open rooms. The method supports creating a room if it's not found by passing `true` as the third argument. ```javascript converse.plugins.add('rooms-getter', { initialize() { const { api } = this._converse; api.listen.on('roomsAutoJoined', async () => { // Get a specific room (create if not found) const room = await api.rooms.get( 'general@conference.example.com', { nick: 'me', password: 'secret' }, true // create if not found ); // Get all currently open MUC rooms const allRooms = await api.rooms.get(); allRooms.forEach(r => { console.log(`Room: ${r.get('jid')}, occupants: ${r.occupants.length}`); }); }); } }); ``` -------------------------------- ### converse.initialize(settings) Source: https://context7.com/conversejs/converse.js/llms.txt The main entry point for Converse.js. It initializes the library with a configuration object that controls its behavior, appearance, and connection settings. This function must be called once after the library is loaded and before any other Converse.js operations. ```APIDOC ## converse.initialize(settings) — Initialize Converse The entry point for all Converse usage. Must be called once after the library script is loaded, before anything else. Accepts a configuration object with dozens of options controlling authentication, display, features, and behavior. ### Parameters * **settings** (Object) - Configuration object for initializing Converse.js. * **websocket_url** (string) - URL for WebSocket connection. * **bosh_service_url** (string) - URL for BOSH service (alternative to WebSocket). * **authentication** (string) - Authentication method ('login', 'anonymous', 'prebind', 'external'). * **auto_login** (boolean) - Automatically log in on page load. * **view_mode** (string) - Display mode ('fullscreen', 'overlayed', 'embedded'). * **keepalive** (boolean) - Maintain login session across page reloads. * **auto_reconnect** (boolean) - Automatically reconnect if connection is dropped. * **play_sounds** (boolean) - Enable sound notifications. * **show_desktop_notifications** (boolean) - Show desktop notifications. * **auto_join_rooms** (Array) - Rooms to automatically join on login. Each object can specify 'jid' and 'nick', or it can be a room JID string. * **message_archiving** (string) - Message archiving strategy ('never', 'always', 'roster'). * **archived_messages_page_size** (number) - Number of archived messages to fetch per page. * **i18n** (string) - Language code to force for internationalization. * **whitelisted_plugins** (Array) - List of plugins to whitelist. ### Request Example ```html My Chat ``` ``` -------------------------------- ### XHR User Search URL with Query String Source: https://github.com/conversejs/converse.js/blob/master/docs/src/content/docs/configuration.md Specifies the URL for XHR GET requests to fetch user data. Converse appends 'q=' to this URL. Ensure proper query string delimiters like '?' or '&' are included. ```javascript xhr_user_search_url: 'https://some.url/some_path?', ``` ```javascript xhr_user_search_url: 'https://some.url/some_path?api_key=somekey&', ``` -------------------------------- ### Common API Usage Patterns in Converse.js Source: https://github.com/conversejs/converse.js/blob/master/AGENTS.md Covers essential API patterns including extending and getting settings, listening to and triggering events, using hooks for data interception, waiting for specific API states, and triggering user confirmations or alerts. ```javascript // Settings api.settings.extend({ 'my_setting': 'default' }); api.settings.get('my_setting'); // Events (fire-and-forget notifications) api.listen.on('connected', callback); api.trigger('customEvent', data); // Hooks (chainable async pipelines — each listener receives and can modify the data) // Use hooks when a caller needs plugins to intercept or transform data. const result = await api.hook('hookName', context, data); api.listen.on('hookName', (context, data) => { return { ...data, modified: true }; // Return modified data to pass along the chain }); // Promises await api.waitUntil('connected'); // User interaction const confirmed = await api.confirm('Are you sure?'); await api.alert('Something happened'); ``` -------------------------------- ### Nginx Reverse Proxy Configuration for WebSocket Source: https://github.com/conversejs/converse.js/blob/master/docs/src/content/docs/setup.md Configure Nginx to proxy WebSocket connections to your XMPP server. Ensure SSL is enabled and headers are correctly set for the upgrade request. This setup is suitable when your website is on HTTPS and the XMPP server runs on a different port. ```nginx http { server { listen 443 server_name mysite.com; ssl on; ssl_certificate /path/to/fullchain.pem; ssl_certificate_key /path/to/privkey.pem; location = / { root /path/to/converse.js/; index index.html; } location /xmpp-websocket { proxy_http_version 1.1; proxy_pass http://127.0.0.1:5280; proxy_buffering off; proxy_set_header Host $host; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; proxy_read_timeout 86400; } # CORS location ~ .(ttf|ttc|otf|eot|woff|woff2|font.css|css|js)$ { add_header Access-Control-Allow-Origin "*"; root /path/to/converse.js/; } } } ``` -------------------------------- ### Importing Core APIs from @converse/headless Source: https://github.com/conversejs/converse.js/blob/master/src/headless/AGENTS.md Demonstrates how to import essential APIs and utilities from the @converse/headless package. These are the fundamental building blocks for interacting with the headless library. ```javascript import { _converse, api, converse, log, u, constants, i18n, parsers, errors } from '@converse/headless'; import { Model, Collection, EventEmitter } from '@converse/headless'; import { BaseMessage, ModelWithMessages } from '@converse/headless'; ``` -------------------------------- ### Run Headless Development and Tests Source: https://github.com/conversejs/converse.js/blob/master/src/headless/AGENTS.md Commands to run the headless development build and execute tests. Always use '--single-run' when testing. ```bash npm run dev:headless && npm test -- --single-run # from workspace root cd src/headless && npm run dev && npm test -- --single-run # from workspace dir ``` -------------------------------- ### Converse Test Structure with Mock Initialization Source: https://github.com/conversejs/converse.js/blob/master/docs/src/content/docs/development/testing.md Illustrates the standard structure for Converse tests using `describe` and `it`, and the `mock.initConverse` helper for setting up the test environment and configuration. ```javascript /*global mock, converse */ const { api } = converse; const u = converse.env.utils; describe("My Feature", function () { it("does something", mock.initConverse(['chatBoxesFetched'], { view_mode: 'fullscreen' }, async function (_converse) { // Test implementation } )); }); ``` -------------------------------- ### Create New Language Translations File Source: https://github.com/conversejs/converse.js/blob/master/docs/src/content/docs/translations.md Use `msginit` to create a new PO file for a language not yet supported. Replace 'pl' with your target language code. Ensure the required attributes are added to the file header for Jed compatibility. ```bash mkdir -p ./src/i18n/locales/pl/LC_MESSAGES msginit -i ./src/i18n/converse.pot -o ./src/i18n/locales/pl/LC_MESSAGES/converse.po -l pl ``` ```po "domain: converse\n" "lang: pl\n" "Content-Type: text/plain; charset=UTF-8\n" "plural_forms: nplurals=2; plural=(n != 1); " ``` -------------------------------- ### Initialize Converse with Custom Theme Source: https://context7.com/conversejs/converse.js/llms.txt Load Converse's CSS and JavaScript, then initialize Converse by passing the desired theme name to the `converse.initialize` function. ```html ``` -------------------------------- ### Serve Static Files Command Source: https://github.com/conversejs/converse.js/blob/master/AGENTS.md Serves static files from the project directory, defaulting to http://localhost:8000. Supports custom ports and HTTPS. ```bash # Serve static files npm run serve # Serves on http://localhost:8000 (default) npm run serve -- -p 8008 # Serve on custom port npm run serve-tls # HTTPS server (requires certs/) ``` -------------------------------- ### Production Builds Source: https://github.com/conversejs/converse.js/blob/master/docs/src/content/docs/development/builds.md Commands for creating minified production builds, including options for building only the headless package, ESM bundle, or CommonJS bundle. ```bash npm run build ``` ```bash npm run build:headless ``` ```bash npm run build:esm ``` ```bash npm run build:cjs ``` -------------------------------- ### Initialize Converse with Custom Theme Source: https://github.com/conversejs/converse.js/blob/master/docs/src/content/docs/theming.md After loading your custom theme CSS, initialize Converse and set the 'theme' configuration option to the name of your custom theme. ```javascript converse.initialize({ theme: "ocean" // ... other configuration options }); ``` -------------------------------- ### Basic Usage of @converse/log Source: https://github.com/conversejs/converse.js/blob/master/src/log/README.md Demonstrates how to import, configure log level, and use various logging methods. Supports multiple arguments and CSS styling for browser console output. ```javascript import log from '@converse/log'; // Configure log level (default: 'info') log.setLogLevel('debug'); // Log messages log.debug('Detailed debug information'); log.info('System status update'); log.warn('Potential issue detected'); log.error('Operation failed'); log.fatal('Critical system failure'); // Pass multiple arguments like console log.debug('User', username, 'logged in', { timestamp: Date.now() }); // Use %c for CSS styling in the browser console log.debug('%c%s', 'color: darkgoldenrod', xmlStanza.outerHTML); ```