Debian Codegraph @

dist/ext/hx-ws.js

raw symbols SCIP
1 (() => {
2 let api;
3
4 // Build a CSS selector for querySelectorAll, respecting prefix + metaCharacter
5 function wsSelector(suffix) {
6 let mc = htmx.config.metaCharacter || ':';
7 let sel = `[${CSS.escape('hx-ws' + mc + suffix)}]`;
8 if (htmx.config.prefix) sel += `,[${CSS.escape(htmx.config.prefix + 'ws' + mc + suffix)}]`;
9 return sel;
10 }
11
12
13 // ========================================
14 // CONFIGURATION
15 // ========================================
16
17 function getConfig(element) {
18 const defaults = {
19 reconnect: true,
20 reconnectDelay: 500,
21 reconnectMaxDelay: 60000,
22 reconnectMaxAttempts: Infinity,
23 reconnectJitter: 0.3,
24 pauseOnBackground: true,
25 pendingRequestTTL: 30000
26 };
27 let global = htmx.config.ws || {};
28 let perElement = {};
29 if (element) {
30 let ctx = api.createRequestContext(element, new CustomEvent('_'));
31 perElement = ctx.request.ws || {};
32 }
33 let merged = { ...defaults, ...global, ...perElement };
34
35 // Backwards compat: boolean reconnectJitter (old API used true/false)
36 if (typeof merged.reconnectJitter === 'boolean') {
37 merged.reconnectJitter = merged.reconnectJitter ? 0.3 : 0;
38 }
39
40 return merged;
41 }
42
43 // ========================================
44 // URL NORMALIZATION
45 // ========================================
46
47 function normalizeWebSocketUrl(url) {
48 // Already a WebSocket URL
49 if (url.startsWith('ws://') || url.startsWith('wss://')) {
50 return url;
51 }
52
53 // Convert http(s):// to ws(s)://
54 if (url.startsWith('http://')) {
55 return 'ws://' + url.slice(7);
56 }
57 if (url.startsWith('https://')) {
58 return 'wss://' + url.slice(8);
59 }
60
61 // Relative URL - build absolute ws(s):// URL
62 let protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
63 let host = window.location.host;
64
65 if (url.startsWith('//')) {
66 // Protocol-relative URL
67 return protocol + url;
68 }
69
70 if (url.startsWith('/')) {
71 // Absolute path
72 return protocol + '//' + host + url;
73 }
74
75 // Relative path - resolve against current location
76 let basePath = window.location.pathname.substring(0, window.location.pathname.lastIndexOf('/') + 1);
77 return protocol + '//' + host + basePath + url;
78 }
79
80 // ========================================
81 // CONNECTIONS
82 // ========================================
83
84 const connections = new Map();
85
86 function getOrCreateConnection(url, element) {
87 let normalizedUrl = normalizeWebSocketUrl(url);
88
89 if (connections.has(normalizedUrl)) {
90 return connections.get(normalizedUrl);
91 }
92
93 let connection = {
94 url: normalizedUrl,
95 config: getConfig(element),
96 socket: null,
97 attempt: 0,
98 timer: null,
99 pendingRequests: new Map(), // abortController: null,
100 visibilityHandler: null,
101 cancelled: false
102 };
103
104 if (!api.triggerHtmxEvent(element, 'htmx:before:ws:connection', {connection}) || connection.cancelled) {
105 api.triggerHtmxEvent(element, 'htmx:ws:close', {
106 connection, reason: 'cancelled', code: null
107 });
108 return null;
109 }
110
111 // Event passed - now store in registry and create socket
112 connections.set(normalizedUrl, connection);
113 createWebSocket(normalizedUrl, connection);
114
115 let config = connection.config;
116 if (config.pauseOnBackground) {
117 connection.visibilityHandler = () => {
118 if (document.hidden) {
119 if (connection.socket && connection.socket.readyState === WebSocket.OPEN) {
120 connection.socket.close();
121 }
122 } else if (!connection.socket || connection.socket.readyState === WebSocket.CLOSED) {
123 connection.attempt = 0;
124 createWebSocket(normalizedUrl, connection);
125 }
126 };
127 document.addEventListener('visibilitychange', connection.visibilityHandler);
128 }
129
130 return connection;
131 }
132
133 function findConnectedElement(url) {
134 let sel = wsSelector('connect') + ',' + wsSelector('send');
135 for (let el of document.querySelectorAll(sel)) {
136 if (el._htmx?.ws?.url === url) return el;
137 }
138 return null;
139 }
140
141 // Close and fully clean up an orphaned connection (no owning element in DOM)
142 function cleanupOrphanedConnection(url, connection) {
143 if (connection.timer) clearTimeout(connection.timer);
144 if (connection.visibilityHandler) {
145 document.removeEventListener('visibilitychange', connection.visibilityHandler);
146 }
147 if (connection.abortController) {
148 connection.abortController.abort();
149 }
150 connection.pendingRequests.clear();
151 if (connection.socket) {
152 try {
153 if (connection.socket.readyState === WebSocket.OPEN || connection.socket.readyState === WebSocket.CONNECTING) {
154 connection.socket.close();
155 }
156 } catch (e) {
157 // Socket may already be in an invalid state
158 }
159 }
160 connections.delete(url);
161 }
162
163 function createWebSocket(url, connection) {
164 // Abort old socket's listeners and close it
165 if (connection.abortController) {
166 connection.abortController.abort();
167 }
168 if (connection.socket) {
169 let oldSocket = connection.socket;
170 connection.socket = null;
171 try {
172 if (oldSocket.readyState === WebSocket.OPEN || oldSocket.readyState === WebSocket.CONNECTING) {
173 oldSocket.close();
174 }
175 } catch (e) {
176 // Socket may already be in an invalid state
177 }
178 }
179
180 try {
181 connection.socket = new WebSocket(url);
182 let ac = new AbortController();
183 connection.abortController = ac;
184 let opts = { signal: ac.signal };
185
186 connection.socket.addEventListener('open', () => {
187 let elt = findConnectedElement(url);
188 if (elt) {
189 api.triggerHtmxEvent(elt, 'htmx:after:ws:connection', {connection});
190 } else {
191 // Element was removed while connecting — orphaned socket
192 cleanupOrphanedConnection(url, connection);
193 return;
194 }
195 connection.attempt = 0;
196 }, opts);
197
198 connection.socket.addEventListener('message', (event) => {
199 handleMessage(connection, event);
200 }, opts);
201
202 connection.socket.addEventListener('close', (event) => {
203 if (event.target !== connection.socket) return;
204
205 let elt = findConnectedElement(url);
206 if (elt) api.triggerHtmxEvent(elt, 'htmx:ws:close', {
207 connection, reason: 'closed', code: event.code
208 });
209
210 if (!connections.has(url)) return;
211
212 let config = connection.config;
213 if (config.pauseOnBackground && document.hidden) return;
214
215 if (config.reconnect && findConnectedElement(url)) {
216 scheduleReconnect(url, connection);
217 } else {
218 // No element or reconnect disabled — full cleanup
219 cleanupOrphanedConnection(url, connection);
220 }
221 }, opts);
222
223 connection.socket.addEventListener('error', (error) => {
224 let elt = findConnectedElement(url);
225 if (elt) api.triggerHtmxEvent(elt, 'htmx:ws:error', { url, error });
226 }, opts);
227
228 } catch (error) {
229 let elt = findConnectedElement(url);
230 if (elt) api.triggerHtmxEvent(elt, 'htmx:ws:error', { url, error });
231 }
232 }
233
234 function scheduleReconnect(url, connection) {
235 let config = connection.config;
236
237 connection.attempt++;
238 let attempt = connection.attempt;
239
240 if (!config.reconnect || attempt > config.reconnectMaxAttempts) {
241 cleanupOrphanedConnection(url, connection);
242 return;
243 }
244
245 let baseDelay = htmx.parseInterval(config.reconnectDelay) ?? config.reconnectDelay;
246 let maxDelay = htmx.parseInterval(config.reconnectMaxDelay) ?? config.reconnectMaxDelay;
247
248 let delay = Math.min(
249 baseDelay * Math.pow(2, attempt - 1),
250 maxDelay
251 );
252
253 if (config.reconnectJitter > 0) {
254 let jitterRange = delay * config.reconnectJitter;
255 delay = Math.max(0, delay + (Math.random() * 2 - 1) * jitterRange);
256 }
257
258 let elt = findConnectedElement(url);
259 if (elt) {
260 connection.cancelled = false;
261 if (!api.triggerHtmxEvent(elt, 'htmx:before:ws:connection', {connection}) || connection.cancelled) {
262 api.triggerHtmxEvent(elt, 'htmx:ws:close', {
263 connection, reason: 'cancelled', code: null
264 });
265 cleanupOrphanedConnection(url, connection);
266 return;
267 }
268 } else {
269 // Element gone — no point scheduling reconnect
270 cleanupOrphanedConnection(url, connection);
271 return;
272 }
273
274 connection.timer = setTimeout(() => {
275 if (findConnectedElement(url)) {
276 createWebSocket(url, connection);
277 } else {
278 cleanupOrphanedConnection(url, connection);
279 }
280 }, delay);
281 }
282
283 function closeConnection(url, element) {
284 let connection = connections.get(url);
285 if (!connection) return;
286
287 if (connection.timer) clearTimeout(connection.timer);
288 if (connection.visibilityHandler) {
289 document.removeEventListener('visibilitychange', connection.visibilityHandler);
290 }
291 if (connection.abortController) {
292 connection.abortController.abort();
293 }
294 connection.pendingRequests.clear();
295 api.triggerHtmxEvent(element, 'htmx:ws:close', {
296 connection, reason: 'removed', code: null
297 });
298 if (connection.socket && connection.socket.readyState === WebSocket.OPEN) {
299 connection.socket.close();
300 }
301 connections.delete(url);
302 }
303
304 // ========================================
305 // PENDING REQUEST MANAGEMENT // ========================================
306
307 function cleanupExpiredRequests(connection) {
308 let config = connection.config;
309 let now = Date.now();
310 let timeout = config.pendingRequestTTL || 30000;
311
312 for (let [requestId, pending] of connection.pendingRequests) {
313 if (now - pending.timestamp > timeout) {
314 connection.pendingRequests.delete(requestId);
315 }
316 }
317 }
318
319 // ========================================
320 // REQUESTS
321 // ========================================
322
323 async function sendRequest(element, event) {
324 // hx-ws:send="/url" creates its own connection; hx-ws:send (no value) uses ancestor's
325 let sendAttr = api.attributeValue(element, 'hx-ws:send');
326 let url = (sendAttr && sendAttr !== 'true') ? sendAttr : null;
327 if (!url) {
328 let ancestor = element.closest(wsSelector('connect'));
329 if (ancestor) {
330 url = api.attributeValue(ancestor, 'hx-ws:connect');
331 }
332 }
333
334 if (!url) {
335 api.triggerHtmxEvent(element, 'htmx:ws:error', {
336 url: null, error: 'No WebSocket connection found for element'
337 });
338 return;
339 }
340
341 let normalizedUrl = normalizeWebSocketUrl(url);
342 let connection = connections.get(normalizedUrl);
343
344 // Wait for socket to open if still connecting
345 if (connection && connection.socket && connection.socket.readyState === WebSocket.CONNECTING) {
346 await new Promise(resolve => {
347 connection.socket.addEventListener('open', resolve, { once: true });
348 connection.socket.addEventListener('close', resolve, { once: true });
349 connection.socket.addEventListener('error', resolve, { once: true });
350 });
351 }
352
353 if (!connection || !connection.socket || connection.socket.readyState !== WebSocket.OPEN) {
354 api.triggerHtmxEvent(element, 'htmx:ws:error', { url: normalizedUrl, error: 'Connection not open' });
355 return;
356 }
357
358 // [Correlation] Cleanup expired pending requests periodically
359 cleanupExpiredRequests(connection);
360
361 // Build headers using core's request context (same as HTTP requests)
362 let ctx = api.createRequestContext(element, event);
363 let headers = {...ctx.request.headers};
364 delete headers['Accept'];
365
366 // [Correlation] Add request ID as a header
367 let requestId = crypto.randomUUID();
368 headers['HX-Request-ID'] = requestId;
369
370 // Build body from form data
371 let form = element.form || element.closest('form');
372 let formData = api.collectFormData(element, form, event.submitter);
373
374 // Preserve multi-value form fields (checkboxes, multi-selects)
375 let body = {};
376 for (let [key, value] of formData) {
377 if (key in body) {
378 body[key] = [].concat(body[key], value);
379 } else {
380 body[key] = value;
381 }
382 }
383
384 // Merge hx-vals after serialization to preserve JS types (numbers, booleans)
385 let valsResult = api.getAttributeObject(element, 'hx-vals', obj => Object.assign(body, obj));
386 if (valsResult) await valsResult;
387
388 let detail = { headers, body };
389 if (!api.triggerHtmxEvent(element, 'htmx:before:ws:request', detail)) {
390 return;
391 }
392
393 try {
394 connection.socket.send(JSON.stringify(detail));
395
396 // [Correlation] Store pending request for response matching
397 connection.pendingRequests.set(requestId, { element, timestamp: Date.now() });
398
399 api.triggerHtmxEvent(element, 'htmx:after:ws:request', detail);
400 } catch (error) {
401 api.triggerHtmxEvent(element, 'htmx:ws:error', { url: normalizedUrl, error });
402 }
403 }
404
405 // ========================================
406 // MESSAGE RECEIVING & ROUTING
407 // ========================================
408
409 function handleMessage(connection, event) {
410 let json = null;
411 try {
412 json = JSON.parse(event.data);
413 } catch (e) {
414 // Not JSON - will be treated as raw HTML below
415 }
416
417 // [Correlation] Cleanup expired pending requests on every message
418 cleanupExpiredRequests(connection);
419
420 // [Correlation] Match response to originating element, or fall back to first subscriber
421 let connectionElement = null;
422 let requestId = json?.['HX-Request-ID'] || json?.request_id;
423 if (requestId && connection.pendingRequests.has(requestId)) {
424 connectionElement = connection.pendingRequests.get(requestId).element;
425 connection.pendingRequests.delete(requestId);
426 // If the correlated element has been removed from the DOM, fall back
427 if (!connectionElement.isConnected) {
428 connectionElement = findConnectedElement(connection.url);
429 }
430 } else {
431 connectionElement = findConnectedElement(connection.url);
432 }
433
434 if (!connectionElement) {
435 // No element in DOM for this connection — orphan cleanup
436 cleanupOrphanedConnection(connection.url, connection);
437 return;
438 }
439
440 let detail = {
441 message: { text: event.data, json, cancelled: false }
442 };
443
444 if (!api.triggerHtmxEvent(connectionElement, 'htmx:before:ws:message', detail) || detail.message.cancelled) {
445 return;
446 }
447
448 // JSON with 'content' or 'payload' field: swap the HTML
449 // Raw (non-JSON) string: swap the entire string as HTML
450 // JSON without 'content'/'payload': data-only message, no swap (handle via events)
451 let html;
452 if (detail.message.json) {
453 if (detail.message.json.content !== undefined) {
454 html = detail.message.json.content;
455 } else if (detail.message.json.payload !== undefined) {
456 html = detail.message.json.payload; // backwards compat
457 // Warn once per connection (not on every message)
458 if (!connection._payloadWarnFired) {
459 console.warn('htmx: [hx-ws] json.payload is deprecated; use json.content instead');
460 connection._payloadWarnFired = true;
461 }
462 }
463 } else {
464 html = detail.message.text;
465 }
466 if (html != null) {
467 let target = detail.message.json?.target || api.attributeValue(connectionElement, 'hx-target');
468 let swap = detail.message.json?.swap || api.attributeValue(connectionElement, 'hx-swap');
469
470 htmx.swap({
471 sourceElement: connectionElement,
472 target: target || connectionElement,
473 swap: swap || (target ? htmx.config.defaultSwap : 'none'),
474 text: html,
475 transition: false
476 });
477 }
478
479 delete detail.message.cancelled;
480 api.triggerHtmxEvent(connectionElement, 'htmx:after:ws:message', detail);
481 }
482
483 // ========================================
484 // ELEMENT LIFECYCLE
485 // ========================================
486
487 function initializeElement(element) {
488 api.htmxProp(element).ws ??= {};
489 if (element._htmx.ws.initialized) return;
490
491 let connectUrl = api.attributeValue(element, 'hx-ws:connect');
492 if (!connectUrl) return;
493
494 let specString = api.attributeValue(element, 'hx-trigger') || 'load';
495 api.onTrigger(element, specString, () => {
496 if (element._htmx?.ws?.url) return;
497 let connection = getOrCreateConnection(connectUrl, element);
498 if (connection) {
499 element._htmx.ws.url = connection.url;
500 }
501 });
502 element._htmx.ws.initialized = true;
503 }
504
505 function initializeSendElement(element) {
506 api.htmxProp(element).ws ??= {};
507 if (element._htmx.ws.sendInitialized) return;
508
509 let sendAttr = api.attributeValue(element, 'hx-ws:send');
510 let sendUrl = (sendAttr && sendAttr !== 'true') ? sendAttr : null;
511 let specString = api.attributeValue(element, 'hx-trigger');
512 if (!specString) {
513 specString = element.matches('form') ? 'submit' :
514 element.matches('input:not([type=button]),select,textarea') ? 'change' :
515 'click';
516 }
517
518 api.onTrigger(element, specString, async (evt) => {
519 if (element.matches('form') && evt.type === 'submit') {
520 evt.preventDefault();
521 }
522 if (sendUrl && !element._htmx?.ws?.url) {
523 let connection = getOrCreateConnection(sendUrl, element);
524 if (connection) {
525 element._htmx.ws.url = connection.url;
526 }
527 }
528 await sendRequest(element, evt);
529 });
530 element._htmx.ws.sendInitialized = true;
531 }
532
533 function cleanupElement(element) {
534 let url = element._htmx?.ws?.url;
535 if (!url || !connections.has(url)) return;
536 element._htmx.ws.url = null;
537 if (!findConnectedElement(url)) {
538 closeConnection(url, element);
539 }
540 }
541
542 // ========================================
543 // BACKWARD COMPATIBILITY
544 // ========================================
545
546 function checkLegacyAttributes(element) {
547 if (element.hasAttribute('ws-connect') || element.hasAttribute('ws-send')) {
548 console.warn('htmx: [hx-ws] legacy attributes ws-connect and ws-send are deprecated; use hx-ws:connect and hx-ws:send instead');
549
550 if (element.hasAttribute('ws-connect')) {
551 let url = element.getAttribute('ws-connect');
552 let mc = htmx.config.metaCharacter || ':';
553 let attr = (htmx.config.prefix || 'hx-') + 'ws' + mc + 'connect';
554 if (!element.hasAttribute(attr)) {
555 element.setAttribute(attr, url);
556 }
557 }
558
559 if (element.hasAttribute('ws-send')) {
560 let mc = htmx.config.metaCharacter || ':';
561 let attr = (htmx.config.prefix || 'hx-') + 'ws' + mc + 'send';
562 if (!element.hasAttribute(attr)) {
563 element.setAttribute(attr, '');
564 }
565 }
566 }
567 }
568
569 // ========================================
570 // EXTENSION REGISTRATION
571 // ========================================
572
573 htmx.registerExtension('ws', {
574 init: (internalAPI) => {
575 api = internalAPI;
576
577 // Initialize default config if not set
578 if (!htmx.config.ws) {
579 htmx.config.ws = {};
580 }
581 },
582
583 htmx_after_process: (element) => {
584 const processNode = (node) => {
585 checkLegacyAttributes(node);
586
587 if (api.attributeValue(node, 'hx-ws:connect') != null) {
588 initializeElement(node);
589 }
590
591 if (api.attributeValue(node, 'hx-ws:send') != null) {
592 initializeSendElement(node);
593 }
594 };
595
596 processNode(element);
597
598 let sel = wsSelector('connect') + ',' + wsSelector('send') + ',[ws-connect],[ws-send]';
599 element.querySelectorAll(sel).forEach(processNode);
600 },
601
602 htmx_before_cleanup: (element) => {
603 cleanupElement(element);
604 }
605 });
606
607 // Expose connections for testing
608 if (typeof window !== 'undefined' && window.htmx) {
609 // Clean up all WS connections on page navigation to prevent browser errors
610 window.addEventListener('pagehide', () => {
611 connections.forEach((connection) => {
612 if (connection.socket) {
613 connection.socket.close(1001, 'page navigating away');
614 }
615 });
616 });
617
618 window.htmx.ext = window.htmx.ext || {};
619 window.htmx.ext.ws = {
620 getRegistry: () => ({
621 clear: () => {
622 let activeConnections = Array.from(connections.values());
623 connections.clear(); // Clear first to prevent reconnects
624
625 activeConnections.forEach(connection => {
626 if (connection.timer) {
627 clearTimeout(connection.timer);
628 }
629 if (connection.visibilityHandler) {
630 document.removeEventListener('visibilitychange', connection.visibilityHandler);
631 }
632 if (connection.abortController) {
633 connection.abortController.abort();
634 }
635 if (connection.socket) {
636 connection.socket.close();
637 }
638 connection.pendingRequests.clear();
639 });
640 },
641 get: (key) => connections.get(normalizeWebSocketUrl(key)),
642 has: (key) => connections.has(normalizeWebSocketUrl(key)),
643 get size() { return connections.size; }
644 })
645 };
646 }
647 })();