Debian Codegraph @

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