Debian Codegraph @

test/tests/ext/hx-sse.js

raw symbols SCIP
1 describe('hx-sse SSE extension', function() {
2
3 let extBackup;
4 let docListeners = [];
5
6 function onDoc(event, handler) {
7 document.addEventListener(event, handler);
8 docListeners.push({event, handler});
9 }
10
11 before(async () => {
12 extBackup = backupExtensions();
13 clearExtensions();
14
15 htmx.config.extensions = 'sse';
16 htmx.__approvedExt = 'sse';
17
18 let script = document.createElement('script');
19 script.src = '../src/ext/hx-sse.js';
20 await new Promise(resolve => {
21 script.onload = resolve;
22 document.head.appendChild(script);
23 });
24
25 if (!htmx.__registeredExt.has('sse')) {
26 throw new Error('SSE extension failed to register - check approval');
27 }
28 });
29
30 after(() => {
31 restoreExtensions(extBackup);
32 });
33
34 afterEach(function() {
35 // Clean up document-level listeners added during tests
36 for (let l of docListeners) {
37 document.removeEventListener(l.event, l.handler);
38 }
39 docListeners = [];
40
41 // Restore document.hidden if overridden
42 Object.defineProperty(document, 'hidden', {value: false, configurable: true});
43
44 cleanupTest()
45 })
46
47 it('basic one-off SSE stream works', async function() {
48 const stream = mockStreamResponse('/stream');
49 createProcessedHTML('<button hx-get="/stream" hx-swap="innerHTML">Stream</button>');
50
51 find('button').click();
52 await htmx.timeout(1);
53
54 stream.send('message 1');
55 await waitForEvent('htmx:after:sse:message');
56 assertTextContentIs('button', 'message 1');
57
58 stream.send('message 2');
59 await waitForEvent('htmx:after:sse:message');
60 assertTextContentIs('button', 'message 2');
61
62 stream.close();
63 });
64
65 it('continuous stream reconnects with exponential backoff', async function() {
66 const stream = mockStreamResponse('/reconnect');
67 createProcessedHTML('<button hx-get="/reconnect" hx-config="sse.reconnect:true sse.reconnectDelay:50ms sse.reconnectMaxAttempts:3 sse.reconnectJitter:0" hx-swap="innerHTML">Connect</button>');
68
69 let reconnectAttempts = 0;
70
71 onDoc('htmx:before:sse:connection', (e) => {
72 if (e.detail.connection.attempt > 0) {
73 reconnectAttempts++;
74 }
75 });
76
77 find('button').click();
78 await htmx.timeout(1);
79
80 stream.send('first');
81 await waitForEvent('htmx:after:sse:message');
82 assertTextContentIs('button', 'first');
83
84 stream.close();
85 await waitForEvent('htmx:after:sse:connection');
86
87 assert.equal(reconnectAttempts, 1, 'Should attempt to reconnect');
88
89 stream.send('second');
90 await waitForEvent('htmx:after:sse:message');
91 assertTextContentIs('button', 'second');
92
93 stream.close();
94 });
95
96 it('Last-Event-ID header sent on reconnect', async function() {
97 this.timeout(5000);
98 const stream = mockStreamResponse('/with-id');
99 createProcessedHTML('<button hx-get="/with-id" hx-config="sse.reconnect:true sse.reconnectDelay:50ms sse.reconnectMaxAttempts:2" hx-swap="innerHTML">Connect</button>');
100
101 let lastEventIdSent = null;
102 onDoc('htmx:before:sse:connection', (e) => {
103 if (e.detail.connection.attempt > 0) {
104 lastEventIdSent = e.detail.connection.lastEventId;
105 }
106 });
107
108 find('button').click();
109 await htmx.timeout(1);
110
111 stream.send('first message', null, 'msg-123');
112 await waitForEvent('htmx:after:sse:message');
113 assertTextContentIs('button', 'first message');
114
115 await new Promise(r => setTimeout(r, 50));
116
117 stream.close();
118 await waitForEvent('htmx:after:sse:connection', 5000);
119
120 assert.equal(lastEventIdSent, 'msg-123', 'Should send last event ID on reconnect');
121
122 const lastCall = lastFetch();
123 assert.equal(lastCall.request.headers['Last-Event-ID'], 'msg-123', 'Last-Event-ID header should be set');
124
125 stream.close();
126 });
127
128 it('events fire correctly and can cancel operations', async function() {
129 const stream = mockStreamResponse('/cancelable');
130 createProcessedHTML('<button hx-get="/cancelable" hx-swap="innerHTML">Go</button>');
131
132 let beforeConnectFired = false;
133 let beforeMessageFired = false;
134 let afterMessageFired = false;
135
136 onDoc('htmx:before:sse:connection', () => { beforeConnectFired = true; });
137 onDoc('htmx:before:sse:message', () => { beforeMessageFired = true; });
138 onDoc('htmx:after:sse:message', () => { afterMessageFired = true; });
139
140 find('button').click();
141 await htmx.timeout(1);
142
143 assert.isTrue(beforeConnectFired, 'before:sse:connect should fire');
144
145 stream.send('test');
146 await waitForEvent('htmx:after:sse:message');
147
148 assert.isTrue(beforeMessageFired, 'before:sse:message should fire');
149 assert.isTrue(afterMessageFired, 'after:sse:message should fire');
150 assertTextContentIs('button', 'test');
151
152 stream.close();
153 });
154
155 it('element removal stops streaming and fires close event', async function() {
156 const stream = mockStreamResponse('/removable');
157 createProcessedHTML('<div id="container"><button hx-get="/removable" hx-config="sse.reconnect:true sse.reconnectDelay:50ms" hx-swap="innerHTML">Connect</button></div>');
158
159 find('button').click();
160 await htmx.timeout(1);
161
162 stream.send('message 1');
163 await waitForEvent('htmx:after:sse:message');
164 assertTextContentIs('button', 'message 1');
165
166 let closeFired = false;
167 let closeReason = null;
168 onDoc('htmx:sse:close', (e) => {
169 closeFired = true;
170 closeReason = e.detail.reason;
171 });
172
173 // Remove the element
174 find('#container').innerHTML = '';
175 await htmx.timeout(50);
176
177 // Verify no further messages are processed
178 let messageAfterRemoval = false;
179 onDoc('htmx:after:sse:message', () => { messageAfterRemoval = true; });
180 stream.send('message 2');
181 await htmx.timeout(50);
182
183 assert.isFalse(messageAfterRemoval, 'Should not process messages after element removal');
184 assert.isTrue(closeFired, 'htmx:sse:close should fire');
185 assert.equal(closeReason, 'removed', 'Close reason should be "removed"');
186
187 stream.close();
188 });
189
190 it('HTTP vs SSE differentiation', async function() {
191 mockResponse('GET', '/regular', 'HTTP response');
192 createProcessedHTML('<button id="http" hx-get="/regular" hx-swap="innerHTML">HTTP</button>');
193
194 find('#http').click()
195 await forRequest();
196 assertTextContentIs('#http', 'HTTP response');
197
198 const stream = mockStreamResponse('/sse');
199 createProcessedHTML('<button id="sse" hx-get="/sse" hx-swap="innerHTML">SSE</button>');
200
201 find('#sse').click();
202 await htmx.timeout(1);
203
204 stream.send('SSE response');
205 await waitForEvent('htmx:after:sse:message');
206
207 assertTextContentIs('#sse', 'SSE response');
208 stream.close();
209 });
210
211 it('SSE message parsing with id field', async function() {
212 const stream = mockStreamResponse('/parse');
213 createProcessedHTML('<div id="target"></div><button hx-get="/parse" hx-target="#target">Go</button>');
214
215 find('button').click();
216 await htmx.timeout(1);
217
218 // Send HTML with id field (no event field, so it swaps)
219 stream.send('<div id="msg1">message with id</div>', null, '42');
220 await waitForEvent('htmx:after:sse:message');
221
222 assertTextContentIs('#msg1', 'message with id');
223 stream.close();
224 });
225
226 it('reconnectMaxAttempts configuration works', async function() {
227 let fetchCount = 0;
228 fetchMock.mockResponse('GET', '/max-attempts', () => {
229 fetchCount++;
230 if (fetchCount === 1) {
231 let ctrl;
232 const body = new ReadableStream({ start(c) { ctrl = c; } });
233 const response = new MockResponse(body, {
234 headers: { 'Content-Type': 'text/event-stream' }
235 });
236 response.body = body;
237 setTimeout(() => ctrl.close(), 10);
238 return response;
239 }
240 throw new Error('Network error');
241 });
242
243 createProcessedHTML('<button hx-get="/max-attempts" hx-config="sse.reconnect:true sse.reconnectDelay:20ms sse.reconnectMaxAttempts:2" hx-swap="innerHTML">Connect</button>');
244
245 let reconnectAttempts = 0;
246 onDoc('htmx:before:sse:connection', (e) => {
247 if (e.detail.connection.attempt > 0) reconnectAttempts++;
248 });
249
250 find('button').click();
251 await waitForEvent('htmx:before:sse:connection');
252
253 await new Promise(r => setTimeout(r, 150));
254
255 assert.equal(reconnectAttempts, 2, 'Should attempt reconnecting 2 times');
256 assert.equal(fetchCount, 3, 'Should fetch 3 times total (initial + 2 retries)');
257 });
258
259 it('reconnectMaxDelay configuration caps backoff', async function() {
260 let fetchCount = 0;
261 fetchMock.mockResponse('GET', '/max-delay', () => {
262 fetchCount++;
263 if (fetchCount === 1) {
264 let ctrl;
265 const body = new ReadableStream({ start(c) { ctrl = c; } });
266 const response = new MockResponse(body, {
267 headers: { 'Content-Type': 'text/event-stream' }
268 });
269 response.body = body;
270 setTimeout(() => ctrl.close(), 10);
271 return response;
272 }
273 throw new Error('Network error');
274 });
275
276 createProcessedHTML('<button hx-get="/max-delay" hx-config="sse.reconnect:true sse.reconnectDelay:20ms sse.reconnectMaxDelay:60ms sse.reconnectJitter:0" hx-swap="innerHTML">Connect</button>');
277
278 let reconnectAttempts = [];
279 onDoc('htmx:before:sse:connection', (e) => {
280 if (e.detail.connection.attempt > 0) reconnectAttempts.push(e.detail.connection.attempt);
281 });
282
283 find('button').click();
284 await waitForEvent('htmx:before:sse:connection');
285
286 await new Promise(r => setTimeout(r, 350));
287
288 assert.isAtLeast(reconnectAttempts.length, 4, 'Should have at least 4 reconnect attempts');
289 });
290
291 it('reconnectJitter randomizes reconnect delays', async function() {
292 let fetchCount = 0;
293 fetchMock.mockResponse('GET', '/jitter-test', () => {
294 fetchCount++;
295 if (fetchCount === 1) {
296 let ctrl;
297 const body = new ReadableStream({ start(c) { ctrl = c; } });
298 const response = new MockResponse(body, {
299 headers: { 'Content-Type': 'text/event-stream' }
300 });
301 response.body = body;
302 setTimeout(() => ctrl.close(), 10);
303 return response;
304 }
305 throw new Error('Network error');
306 });
307
308 // Use a jitter of 0.5 (50%) and a reconnectDelay of 100ms
309 createProcessedHTML('<button hx-get="/jitter-test" hx-config="sse.reconnect:true, sse.reconnectDelay:100ms, sse.reconnectJitter:0.5, sse.reconnectMaxAttempts: 5" hx-swap="innerHTML">Connect</button>');
310
311 let reconnectAttempts = [];
312 onDoc('htmx:before:sse:connection', (e) => {
313 if (e.detail.connection.attempt > 0) reconnectAttempts.push(e.detail.connection.attempt);
314 });
315
316 find('button').click();
317 await waitForEvent('htmx:before:sse:connection');
318
319 // Wait for multiple reconnects
320 await new Promise(r => setTimeout(r, 800));
321
322 // Verify we have multiple reconnects (jitter affects timing but reconnects still happen)
323 assert.isAtLeast(reconnectAttempts.length, 3, 'Should have at least 3 reconnect attempts');
324 });
325
326 it('reconnectJitter of 0 disables jitter', async function() {
327 let fetchCount = 0;
328 fetchMock.mockResponse('GET', '/no-jitter', () => {
329 fetchCount++;
330 if (fetchCount === 1) {
331 let ctrl;
332 const body = new ReadableStream({ start(c) { ctrl = c; } });
333 const response = new MockResponse(body, {
334 headers: { 'Content-Type': 'text/event-stream' }
335 });
336 response.body = body;
337 setTimeout(() => ctrl.close(), 10);
338 return response;
339 }
340 throw new Error('Network error');
341 });
342
343 createProcessedHTML('<button hx-get="/no-jitter" hx-config="sse.reconnect:true, sse.reconnectDelay:100ms, sse.reconnectJitter:0, sse.reconnectMaxAttempts:3" hx-swap="innerHTML">Connect</button>');
344
345 let reconnectAttempts = [];
346 onDoc('htmx:before:sse:connection', (e) => {
347 if (e.detail.connection.attempt > 0) reconnectAttempts.push(e.detail.connection.attempt);
348 });
349
350 find('button').click();
351 await waitForEvent('htmx:before:sse:connection');
352
353 await new Promise(r => setTimeout(r, 450));
354
355 assert.isAtLeast(reconnectAttempts.length, 2, 'Should have at least 2 reconnect attempts');
356 });
357
358 it('pauseOnBackground stops reconnection while tab is hidden', async function() {
359 this.timeout(5000);
360 const stream = mockStreamResponse('/pause-test');
361 createProcessedHTML('<button hx-get="/pause-test" hx-config="sse.reconnect:true sse.pauseOnBackground:true sse.reconnectDelay:50ms sse.reconnectJitter:0" hx-swap="innerHTML">Connect</button>');
362
363 let connectionAttempts = 0;
364 onDoc('htmx:before:sse:connection', () => { connectionAttempts++; });
365
366 find('button').click();
367 await waitForEvent('htmx:after:sse:connection');
368 assert.equal(connectionAttempts, 1, 'Initial connection');
369
370 stream.send('hello');
371 await waitForEvent('htmx:after:sse:message');
372 assertTextContentIs('button', 'hello');
373
374 // Simulate tab going hidden
375 Object.defineProperty(document, 'hidden', {value: true, configurable: true});
376 document.dispatchEvent(new Event('visibilitychange'));
377
378 // Wait long enough that reconnection would have happened if not paused
379 await new Promise(r => setTimeout(r, 300));
380
381 assert.equal(connectionAttempts, 1, 'Should NOT reconnect while tab is hidden');
382
383 // Simulate tab becoming visible again
384 Object.defineProperty(document, 'hidden', {value: false, configurable: true});
385 document.dispatchEvent(new Event('visibilitychange'));
386
387 await waitForEvent('htmx:after:sse:connection', 3000);
388 assert.equal(connectionAttempts, 2, 'Should reconnect when tab becomes visible');
389
390 stream.send('world');
391 await waitForEvent('htmx:after:sse:message');
392 assertTextContentIs('button', 'world');
393
394 stream.close();
395 });
396
397 it('pauseOnBackground does not inflate attempt counter across pause cycles', async function() {
398 this.timeout(5000);
399 const stream = mockStreamResponse('/pause-counter');
400 createProcessedHTML('<button hx-get="/pause-counter" hx-config="sse.reconnect:true sse.pauseOnBackground:true sse.reconnectDelay:50ms sse.reconnectJitter:0" hx-swap="innerHTML">Connect</button>');
401
402 let attempts = [];
403 onDoc('htmx:before:sse:connection', (e) => {
404 if (e.detail.connection.attempt > 0) {
405 attempts.push(e.detail.connection.attempt);
406 }
407 });
408
409 find('button').click();
410 await waitForEvent('htmx:after:sse:connection');
411
412 stream.send('msg1');
413 await waitForEvent('htmx:after:sse:message');
414
415 // First pause/resume cycle
416 Object.defineProperty(document, 'hidden', {value: true, configurable: true});
417 document.dispatchEvent(new Event('visibilitychange'));
418 await new Promise(r => setTimeout(r, 50));
419 Object.defineProperty(document, 'hidden', {value: false, configurable: true});
420 document.dispatchEvent(new Event('visibilitychange'));
421 await waitForEvent('htmx:after:sse:connection', 3000);
422
423 stream.send('msg2');
424 await waitForEvent('htmx:after:sse:message');
425
426 // Second pause/resume cycle
427 Object.defineProperty(document, 'hidden', {value: true, configurable: true});
428 document.dispatchEvent(new Event('visibilitychange'));
429 await new Promise(r => setTimeout(r, 50));
430 Object.defineProperty(document, 'hidden', {value: false, configurable: true});
431 document.dispatchEvent(new Event('visibilitychange'));
432 await waitForEvent('htmx:after:sse:connection', 3000);
433
434 // Both attempts should be 1 (not escalating across pause cycles)
435 assert.equal(attempts.length, 2, 'Should have 2 reconnections');
436 assert.equal(attempts[0], 1, 'First attempt should be 1');
437 assert.equal(attempts[1], 1, 'Second attempt should also be 1 (not escalating)');
438
439 stream.close();
440 });
441
442 it('custom events trigger on element and bubble', async function() {
443 const stream = mockStreamResponse('/custom-events');
444 createProcessedHTML('<button hx-get="/custom-events" hx-swap="innerHTML">Connect</button>');
445
446 let customEventFired = false;
447 let customEventData = null;
448 let customEventId = null;
449
450 // Listen for custom event on the button
451 find('button').addEventListener('update', (e) => {
452 customEventFired = true;
453 customEventData = e.detail.data;
454 customEventId = e.detail.id;
455 });
456
457 find('button').click();
458 await htmx.timeout(1);
459
460 stream.send('some data', 'update', 'event-123');
461 await htmx.timeout(1);
462
463 assert.isTrue(customEventFired, 'Custom event should be triggered');
464 assert.equal(customEventData, 'some data', 'Event should include data');
465 assert.equal(customEventId, 'event-123', 'Event should include id');
466
467 stream.close();
468 });
469
470 it('custom events bubble to document', async function() {
471 const stream = mockStreamResponse('/bubble-test');
472 createProcessedHTML('<button hx-get="/bubble-test" hx-swap="innerHTML">Connect</button>');
473
474 let documentEventFired = false;
475 let eventTarget = null;
476
477 // Listen for custom event on document
478 onDoc('notification', (e) => {
479 documentEventFired = true;
480 eventTarget = e.target;
481 });
482
483 find('button').click();
484 await htmx.timeout(1);
485
486 stream.send('notification message', 'notification');
487 await htmx.timeout(1);
488
489 assert.isTrue(documentEventFired, 'Event should bubble to document');
490 assert.equal(eventTarget, find('button'), 'Event target should be the button');
491
492 stream.close();
493 });
494
495 it('custom events work with hx-on attribute', async function() {
496 const stream = mockStreamResponse('/hx-on-test');
497 createProcessedHTML('<button hx-get="/hx-on-test" hx-swap="innerHTML" hx-on:progress="this.setAttribute(\'data-progress\', event.detail.data)">Connect</button>');
498
499 find('button').click();
500 await htmx.timeout(1);
501
502 stream.send('50%', 'progress');
503 await waitForEvent('htmx:after:sse:message');
504
505 assert.equal(find('button').getAttribute('data-progress'), '50%', 'hx-on should handle custom event');
506
507 stream.send('100%', 'progress');
508 await waitForEvent('htmx:after:sse:message');
509
510 assert.equal(find('button').getAttribute('data-progress'), '100%', 'hx-on should handle multiple custom events');
511
512 stream.close();
513 });
514
515 it('custom events and HTML swaps can coexist', async function() {
516 const stream = mockStreamResponse('/mixed-test');
517 createProcessedHTML('<button hx-get="/mixed-test" hx-swap="innerHTML">Connect</button>');
518
519 let statusEventFired = false;
520
521 find('button').addEventListener('status', (e) => {
522 statusEventFired = true;
523 });
524
525 find('button').click();
526 await htmx.timeout(1);
527
528 // Send a custom event (should NOT swap)
529 stream.send('processing', 'status');
530 await waitForEvent('htmx:after:sse:message');
531 assert.isTrue(statusEventFired, 'Custom event should fire');
532 assertTextContentIs('button', 'Connect', 'Content should NOT be swapped for custom events');
533
534 // Send HTML content (no event field, so it swaps normally)
535 stream.send('<div>Result</div>');
536 await waitForEvent('htmx:after:sse:message');
537 assertTextContentIs('button', 'Result');
538
539 stream.close();
540 });
541
542 it('custom events do not swap content', async function() {
543 const stream = mockStreamResponse('/event-only');
544 createProcessedHTML('<button hx-get="/event-only" hx-swap="innerHTML">Connect</button>');
545
546 let notifyFired = false;
547 let notifyData = null;
548
549 find('button').addEventListener('notify', (e) => {
550 notifyFired = true;
551 notifyData = e.detail.data;
552 });
553
554 find('button').click();
555 await htmx.timeout(1);
556
557 // Send event - should trigger event but NOT swap
558 stream.send('notification data', 'notify');
559 await waitForEvent('htmx:after:sse:message');
560
561 assert.isTrue(notifyFired, 'Custom event should fire');
562 assert.equal(notifyData, 'notification data', 'Event should have data');
563 assertTextContentIs('button', 'Connect', 'Content should NOT be swapped');
564
565 stream.close();
566 });
567
568 it('only trims single space after colon', async function() {
569 const stream = mockStreamResponse('/sse-whitespace');
570 createProcessedHTML('<button id="ws-btn" hx-get="/sse-whitespace" hx-swap="innerHTML">Whitespace</button>');
571
572 find('#ws-btn').click();
573 await htmx.timeout(1);
574
575 stream.send(' \ttext-with-two-leading-spaces');
576 await waitForEvent('htmx:after:sse:message');
577 assertTextContentIs('#ws-btn', ' \ttext-with-two-leading-spaces');
578
579 stream.send('NoTrim');
580 await waitForEvent('htmx:after:sse:message');
581 assertTextContentIs('#ws-btn', 'NoTrim');
582
583 stream.close();
584 });
585
586 it('hx-sse:connect auto-connects on load and streams', async function() {
587 const stream = mockStreamResponse('/connect-test');
588 createProcessedHTML('<div hx-sse:connect="/connect-test" hx-swap="innerHTML">Waiting</div>');
589
590 await htmx.timeout(1);
591
592 stream.send('connected!');
593 await waitForEvent('htmx:after:sse:message');
594 assertTextContentIs('div', 'connected!');
595
596 stream.close();
597 });
598
599 it('hx-sse:connect enables reconnect by default', async function() {
600 const stream = mockStreamResponse('/connect-reconnect');
601 createProcessedHTML('<div hx-sse:connect="/connect-reconnect" hx-swap="innerHTML">Waiting</div>');
602
603 await htmx.timeout(1);
604
605 stream.send('first');
606 await waitForEvent('htmx:after:sse:message');
607 assertTextContentIs('div', 'first');
608
609 let reconnectFired = false;
610 onDoc('htmx:before:sse:connection', (e) => {
611 if (e.detail.connection.attempt > 0) reconnectFired = true;
612 });
613
614 stream.close();
615 await waitForEvent('htmx:after:sse:connection');
616
617 assert.isTrue(reconnectFired, 'connect should reconnect by default');
618 });
619
620 it('hx-sse:connect with hx-trigger="load delay:100ms" delays connection', async function() {
621 const stream = mockStreamResponse('/delayed');
622 createProcessedHTML('<div hx-sse:connect="/delayed" hx-trigger="load delay:100ms" hx-swap="innerHTML">Waiting</div>');
623
624 // Should NOT have connected yet
625 await htmx.timeout(10);
626 stream.send('too early');
627 await htmx.timeout(10);
628 assertTextContentIs('div', 'Waiting');
629
630 // Wait for delay to elapse + connection
631 await htmx.timeout(150);
632
633 stream.send('delayed!');
634 await waitForEvent('htmx:after:sse:message');
635 assertTextContentIs('div', 'delayed!');
636
637 stream.close();
638 });
639
640 it('hx-sse:connect with hx-trigger="click" connects on click', async function() {
641 const stream = mockStreamResponse('/on-click');
642 createProcessedHTML('<button hx-sse:connect="/on-click" hx-trigger="click" hx-swap="innerHTML">Click me</button>');
643
644 // Should NOT have connected yet
645 await htmx.timeout(10);
646 assertTextContentIs('button', 'Click me');
647
648 find('button').click();
649 await htmx.timeout(1);
650
651 stream.send('clicked!');
652 await waitForEvent('htmx:after:sse:message');
653 assertTextContentIs('button', 'clicked!');
654
655 stream.close();
656 });
657
658 it('hx-sse:connect with hx-trigger="click once" only connects once', async function() {
659 let fetchCount = 0;
660 fetchMock.mockResponse('GET', '/once-test', () => {
661 fetchCount++;
662 let ctrl;
663 const body = new ReadableStream({ start(c) { ctrl = c; } });
664 const response = new MockResponse(body, {
665 headers: { 'Content-Type': 'text/event-stream' }
666 });
667 response.body = body;
668 return response;
669 });
670
671 createProcessedHTML('<button hx-sse:connect="/once-test" hx-trigger="click once" hx-swap="innerHTML">Click</button>');
672
673 find('button').click();
674 await htmx.timeout(10);
675 assert.equal(fetchCount, 1, 'First click should connect');
676
677 find('button').click();
678 await htmx.timeout(10);
679 assert.equal(fetchCount, 1, 'Second click should be ignored (once modifier)');
680 });
681
682 it('hx-sse:connect with hx-target swaps into correct target', async function() {
683 const stream = mockStreamResponse('/targeted');
684 createProcessedHTML('<div><button hx-sse:connect="/targeted" hx-target="#output">Go</button><span id="output">empty</span></div>');
685
686 await htmx.timeout(1);
687
688 stream.send('targeted!');
689 await waitForEvent('htmx:after:sse:message');
690 assertTextContentIs('#output', 'targeted!');
691
692 stream.close();
693 });
694
695 it('hx-sse:connect respects hx-swap style', async function() {
696 const stream = mockStreamResponse('/append-test');
697 createProcessedHTML('<div hx-sse:connect="/append-test" hx-swap="beforeend">start</div>');
698
699 await htmx.timeout(1);
700
701 stream.send('<span>1</span>');
702 await waitForEvent('htmx:after:sse:message');
703 stream.send('<span>2</span>');
704 await waitForEvent('htmx:after:sse:message');
705
706 assertTextContentIs('div', 'start12');
707
708 stream.close();
709 });
710
711 it('named SSE event on parent does NOT trigger child hx-trigger without from:', async function() {
712 const stream = mockStreamResponse('/bubble-down');
713 mockResponse('GET', '/child-refresh', 'Refreshed!');
714 createProcessedHTML('<div hx-sse:connect="/bubble-down"><div id="child" hx-get="/child-refresh" hx-trigger="update" hx-swap="innerHTML">Original</div></div>');
715
716 await htmx.timeout(1);
717
718 stream.send('payload', 'update');
719 await waitForEvent('htmx:after:sse:message');
720 await htmx.timeout(50);
721
722 // Event dispatches on parent, bubbles UP — child doesn't see it
723 assertTextContentIs('#child', 'Original');
724
725 stream.close();
726 });
727
728 it('named SSE event triggers child with hx-trigger="... from:body"', async function() {
729 const stream = mockStreamResponse('/bubble-from');
730 mockResponse('GET', '/child-action', 'Updated!');
731 createProcessedHTML('<div hx-sse:connect="/bubble-from"><div id="child" hx-get="/child-action" hx-trigger="update from:body" hx-swap="innerHTML">Original</div></div>');
732
733 await htmx.timeout(1);
734
735 stream.send('payload', 'update');
736 await waitForEvent('htmx:after:sse:message');
737 await forRequest();
738
739 assertTextContentIs('#child', 'Updated!');
740
741 stream.close();
742 });
743
744 // --- New tests ---
745
746 it('htmx:sse:error fires on stream errors', async function() {
747 let fetchCount = 0;
748 fetchMock.mockResponse('GET', '/error-test', () => {
749 fetchCount++;
750 if (fetchCount === 1) {
751 let ctrl;
752 const body = new ReadableStream({
753 start(c) { ctrl = c; },
754 });
755 const response = new MockResponse(body, {
756 headers: { 'Content-Type': 'text/event-stream' }
757 });
758 response.body = body;
759 // Trigger an error on the stream
760 setTimeout(() => ctrl.error(new Error('stream broken')), 20);
761 return response;
762 }
763 throw new Error('Network error');
764 });
765
766 createProcessedHTML('<button hx-get="/error-test" hx-swap="innerHTML">Go</button>');
767
768 let errorFired = false;
769 let errorDetail = null;
770 onDoc('htmx:sse:error', (e) => {
771 errorFired = true;
772 errorDetail = e.detail;
773 });
774
775 find('button').click();
776 await new Promise(r => setTimeout(r, 100));
777
778 assert.isTrue(errorFired, 'htmx:sse:error should fire on stream error');
779 assert.isNotNull(errorDetail.error, 'Error detail should contain error object');
780 });
781
782 it('htmx:sse:error fires on non-2xx reconnect response', async function() {
783 this.timeout(5000);
784 let fetchCount = 0;
785 fetchMock.mockResponse('GET', '/status-error', () => {
786 fetchCount++;
787 if (fetchCount === 1) {
788 let ctrl;
789 const body = new ReadableStream({ start(c) { ctrl = c; } });
790 const response = new MockResponse(body, {
791 headers: { 'Content-Type': 'text/event-stream' }
792 });
793 response.body = body;
794 setTimeout(() => ctrl.close(), 10);
795 return response;
796 }
797 // Return a 500 on reconnect
798 const body = new ReadableStream({ start(c) { c.close(); } });
799 const response = new MockResponse(body, {
800 status: 500,
801 headers: { 'Content-Type': 'text/event-stream' }
802 });
803 response.body = body;
804 response.ok = false;
805 return response;
806 });
807
808 createProcessedHTML('<button hx-get="/status-error" hx-config="sse.reconnect:true sse.reconnectDelay:20ms sse.reconnectMaxAttempts:1" hx-swap="innerHTML">Go</button>');
809
810 let errorFired = false;
811 let errorStatus = null;
812 onDoc('htmx:sse:error', (e) => {
813 errorFired = true;
814 errorStatus = e.detail.status;
815 });
816
817 find('button').click();
818 await new Promise(r => setTimeout(r, 200));
819
820 assert.isTrue(errorFired, 'htmx:sse:error should fire for non-2xx reconnect');
821 assert.equal(errorStatus, 500, 'Error detail should include status code');
822 });
823
824 it('htmx:before:sse:message cancellation prevents swap', async function() {
825 const stream = mockStreamResponse('/cancel-msg');
826 createProcessedHTML('<button hx-get="/cancel-msg" hx-swap="innerHTML">Original</button>');
827
828 onDoc('htmx:before:sse:message', (e) => {
829 if (e.detail.message.data === 'skip me') {
830 e.detail.message.cancelled = true;
831 }
832 });
833
834 find('button').click();
835 await htmx.timeout(1);
836
837 stream.send('skip me');
838 await htmx.timeout(50);
839 assertTextContentIs('button', 'Original', 'Cancelled message should not swap');
840
841 stream.send('keep me');
842 await waitForEvent('htmx:after:sse:message');
843 assertTextContentIs('button', 'keep me', 'Non-cancelled message should swap');
844
845 stream.close();
846 });
847
848 it('htmx:before:sse:message cancellation via preventDefault', async function() {
849 const stream = mockStreamResponse('/cancel-prevent');
850 createProcessedHTML('<button hx-get="/cancel-prevent" hx-swap="innerHTML">Original</button>');
851
852 onDoc('htmx:before:sse:message', (e) => {
853 if (e.detail.message.data === 'blocked') {
854 e.preventDefault();
855 }
856 });
857
858 find('button').click();
859 await htmx.timeout(1);
860
861 stream.send('blocked');
862 await htmx.timeout(50);
863 assertTextContentIs('button', 'Original', 'preventDefault should skip message');
864
865 stream.send('allowed');
866 await waitForEvent('htmx:after:sse:message');
867 assertTextContentIs('button', 'allowed');
868
869 stream.close();
870 });
871
872 it('hx-sse:close closes connection on matching event', async function() {
873 const stream = mockStreamResponse('/close-test');
874 createProcessedHTML('<div hx-sse:connect="/close-test" hx-sse:close="done" hx-swap="innerHTML">Waiting</div>');
875
876 await htmx.timeout(1);
877
878 stream.send('message 1');
879 await waitForEvent('htmx:after:sse:message');
880 assertTextContentIs('div', 'message 1');
881
882 let closeFired = false;
883 let closeReason = null;
884 onDoc('htmx:sse:close', (e) => {
885 closeFired = true;
886 closeReason = e.detail.reason;
887 });
888
889 // Send the close event
890 stream.send('goodbye', 'done');
891 await waitForEvent('htmx:sse:close');
892
893 assert.isTrue(closeFired, 'htmx:sse:close should fire');
894 assert.equal(closeReason, 'message', 'Close reason should be "message"');
895
896 // Verify no reconnection occurs
897 let reconnectFired = false;
898 onDoc('htmx:before:sse:connection', (e) => {
899 if (e.detail.connection.attempt > 0) reconnectFired = true;
900 });
901
902 await htmx.timeout(100);
903 assert.isFalse(reconnectFired, 'Should NOT attempt reconnect after hx-sse:close');
904 });
905
906 it('hx-sse:close does not close on non-matching events', async function() {
907 const stream = mockStreamResponse('/close-nomatch');
908 createProcessedHTML('<div hx-sse:connect="/close-nomatch" hx-sse:close="done" hx-swap="innerHTML">Waiting</div>');
909
910 await htmx.timeout(1);
911
912 let closeFired = false;
913 onDoc('htmx:sse:close', () => { closeFired = true; });
914
915 // Send a different named event — should NOT close
916 stream.send('status update', 'status');
917 await waitForEvent('htmx:after:sse:message');
918
919 assert.isFalse(closeFired, 'Should NOT close on non-matching event');
920
921 // Regular messages should still swap
922 stream.send('content');
923 await waitForEvent('htmx:after:sse:message');
924 assertTextContentIs('div', 'content');
925
926 stream.close();
927 });
928
929 it('htmx:sse:close fires with "ended" reason when stream ends naturally', async function() {
930 let ctrl;
931 fetchMock.mockResponse('GET', '/end-test', () => {
932 const body = new ReadableStream({ start(c) { ctrl = c; } });
933 const response = new MockResponse(body, {
934 headers: { 'Content-Type': 'text/event-stream' }
935 });
936 response.body = body;
937 return response;
938 });
939
940 createProcessedHTML('<button hx-get="/end-test" hx-swap="innerHTML">Go</button>');
941
942 let closeReason = null;
943 onDoc('htmx:sse:close', (e) => { closeReason = e.detail.reason; });
944
945 find('button').click();
946 await htmx.timeout(1);
947
948 // Close the stream (no reconnect configured)
949 ctrl.close();
950 await waitForEvent('htmx:sse:close');
951
952 assert.equal(closeReason, 'ended', 'Close reason should be "ended"');
953 });
954
955 it('pauseOnBackground reconnect sends Last-Event-ID for message replay', async function() {
956 this.timeout(5000);
957 const enc = new TextEncoder();
958 const controllers = [];
959
960 // All notifications the "server" knows about
961 const allMessages = [
962 {id: 'n-1', data: '<p>Notification 1</p>'},
963 {id: 'n-2', data: '<p>Notification 2</p>'},
964 {id: 'n-3', data: '<p>Notification 3</p>'}
965 ];
966
967 // Simulate a server that replays missed messages using Last-Event-ID
968 fetchMock.mockResponse('GET', '/notifications', () => {
969 let ctrl;
970 const body = new ReadableStream({ start(c) { ctrl = c; controllers.push(c); } });
971 const response = new MockResponse(body, {
972 headers: { 'Content-Type': 'text/event-stream' }
973 });
974 response.body = body;
975
976 // On reconnect, check Last-Event-ID and replay missed messages
977 if (controllers.length > 1) {
978 const calls = fetchMock.getCalls();
979 const lastId = calls[calls.length - 1].request.headers?.['Last-Event-ID'];
980 if (lastId) {
981 let start = allMessages.findIndex(m => m.id === lastId) + 1;
982 for (let i = start; i < allMessages.length; i++) {
983 ctrl.enqueue(enc.encode(`id: ${allMessages[i].id}\ndata: ${allMessages[i].data}\n\n`));
984 }
985 }
986 }
987 return response;
988 });
989
990 createProcessedHTML('<button hx-get="/notifications" hx-target="#output" hx-config="sse.reconnect:true sse.pauseOnBackground:true sse.reconnectDelay:50ms sse.reconnectJitter:0" hx-swap="beforeend">Connect</button><div id="output"></div>');
991
992 find('button').click();
993 await waitForEvent('htmx:after:sse:connection');
994
995 // Server sends first 2 notifications
996 controllers[0].enqueue(enc.encode('id: n-1\ndata: <p>Notification 1</p>\n\n'));
997 await waitForEvent('htmx:after:sse:message');
998 controllers[0].enqueue(enc.encode('id: n-2\ndata: <p>Notification 2</p>\n\n'));
999 await waitForEvent('htmx:after:sse:message');
1000
1001 assert.include(find('#output').innerHTML, 'Notification 1');
1002 assert.include(find('#output').innerHTML, 'Notification 2');
1003
1004 // Tab goes to background (n-3 exists on the server but client never received it)
1005 Object.defineProperty(document, 'hidden', {value: true, configurable: true});
1006 document.dispatchEvent(new Event('visibilitychange'));
1007 await new Promise(r => setTimeout(r, 50));
1008
1009 // Tab comes back — extension reconnects with Last-Event-ID: n-2
1010 Object.defineProperty(document, 'hidden', {value: false, configurable: true});
1011 document.dispatchEvent(new Event('visibilitychange'));
1012 await waitForEvent('htmx:after:sse:connection', 3000);
1013
1014 // Verify Last-Event-ID header was sent
1015 const reconnectCall = fetchMock.getCalls()[fetchMock.getCalls().length - 1];
1016 assert.equal(reconnectCall.request.headers['Last-Event-ID'], 'n-2', 'Should send Last-Event-ID of last received message');
1017
1018 // Server replayed n-3 on reconnect — verify it was swapped in
1019 await waitForEvent('htmx:after:sse:message', 1000);
1020 assert.include(find('#output').innerHTML, 'Notification 3', 'Missed notification should be replayed on reconnect');
1021
1022 controllers[controllers.length - 1].close();
1023 });
1024
1025 it('server retry field updates reconnect delay', async function() {
1026 this.timeout(5000);
1027 const stream = mockStreamResponse('/retry-test');
1028 createProcessedHTML('<button hx-get="/retry-test" hx-config="sse.reconnect:true sse.reconnectDelay:50ms sse.reconnectMaxAttempts:2 sse.reconnectJitter:0" hx-swap="innerHTML">Go</button>');
1029
1030 let reconnected = false;
1031 onDoc('htmx:before:sse:connection', (e) => {
1032 if (e.detail.connection.attempt > 0) reconnected = true;
1033 });
1034
1035 find('button').click();
1036 await htmx.timeout(1);
1037
1038 // Send a message with retry field set to 200ms
1039 stream.sendRaw('retry: 200\ndata: hello\n\n');
1040 await waitForEvent('htmx:after:sse:message');
1041
1042 stream.close();
1043 await waitForEvent('htmx:after:sse:connection', 5000);
1044
1045 // Server retry field should be respected (reconnection happens)
1046 assert.isTrue(reconnected, 'Should reconnect using server-provided retry delay');
1047
1048 stream.close();
1049 });
1050
1051 it('sends Accept: text/html, text/event-stream header on every request', async function() {
1052 const stream = mockStreamResponse('/accept-header-test');
1053 createProcessedHTML('<button hx-get="/accept-header-test" hx-swap="innerHTML">Go</button>');
1054
1055 find('button').click();
1056 await htmx.timeout(1);
1057
1058 assert.equal(fetchMock.getLastCall().request.headers['Accept'], 'text/html, text/event-stream');
1059
1060 stream.close();
1061 });
1062
1063 it('oob-only SSE message does not blank main target by default', async function() {
1064 const stream = mockStreamResponse('/oob-only');
1065 createProcessedHTML('<div id="target" hx-sse:connect="/oob-only" hx-swap="innerHTML">Original</div><div id="oob">OOB</div>');
1066
1067 await htmx.timeout(1);
1068
1069 stream.send('<div id="oob" hx-swap-oob="true">Updated</div>');
1070 await waitForEvent('htmx:after:sse:message');
1071
1072 assertTextContentIs('#target', 'Original');
1073 assertTextContentIs('#oob', 'Updated');
1074
1075 stream.close();
1076 });
1077
1078 it('oob-only SSE message blanks main target when swapEmpty:true explicitly set', async function() {
1079 const stream = mockStreamResponse('/oob-empty-true');
1080 createProcessedHTML('<div id="target" hx-sse:connect="/oob-empty-true" hx-swap="innerHTML swapEmpty:true">Original</div><div id="oob">OOB</div>');
1081
1082 await htmx.timeout(1);
1083
1084 stream.send('<div id="oob" hx-swap-oob="true">Updated</div>');
1085 await waitForEvent('htmx:after:sse:message');
1086
1087 assertTextContentIs('#target', '');
1088 assertTextContentIs('#oob', 'Updated');
1089
1090 stream.close();
1091 });
1092
1093 it('SSE message with real content alongside oob still swaps main target', async function() {
1094 const stream = mockStreamResponse('/oob-with-content');
1095 createProcessedHTML('<div id="target" hx-sse:connect="/oob-with-content" hx-swap="innerHTML">Original</div><div id="oob">OOB</div>');
1096
1097 await htmx.timeout(1);
1098
1099 stream.send('<div>New Content</div><div id="oob" hx-swap-oob="true">Updated</div>');
1100 await waitForEvent('htmx:after:sse:message');
1101
1102 assertTextContentIs('#oob', 'Updated');
1103 find('#target').innerText.trim().should.equal('New Content');
1104
1105 stream.close();
1106 });
1107
1108 it('supports legacy sse-connect attribute with deprecation warning', async function() {
1109 let warnCalled = false;
1110 let originalWarn = console.warn;
1111 console.warn = () => { warnCalled = true; };
1112
1113 const stream = mockStreamResponse('/legacy-test');
1114 createProcessedHTML('<div sse-connect="/legacy-test" hx-swap="innerHTML">Waiting</div>');
1115
1116 await htmx.timeout(1);
1117
1118 console.warn = originalWarn;
1119
1120 stream.send('legacy works');
1121 await waitForEvent('htmx:after:sse:message');
1122 assertTextContentIs('div', 'legacy works');
1123
1124 assert.isTrue(warnCalled, 'Should emit deprecation warning');
1125
1126 stream.close();
1127 });
1128 });