| 1 |
(() => { |
| 2 |
let api; |
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
function getConfig(ctx) { |
| 9 |
let isConnect = api.attributeValue(ctx.sourceElement, 'hx-sse:connect') != null; |
| 10 |
let defaults = { |
| 11 |
reconnect: isConnect, |
| 12 |
reconnectDelay: 500, |
| 13 |
reconnectMaxDelay: 60000, |
| 14 |
reconnectMaxAttempts: Infinity, |
| 15 |
reconnectJitter: 0.3, |
| 16 |
pauseOnBackground: isConnect |
| 17 |
}; |
| 18 |
let global = htmx.config.sse || {}; |
| 19 |
|
| 20 |
|
| 21 |
let perElement = ctx.request.sse || {}; |
| 22 |
return {...defaults, ...global, ...perElement}; |
| 23 |
} |
| 24 |
|
| 25 |
|
| 26 |
|
| 27 |
|
| 28 |
|
| 29 |
async function* parseSSE(reader) { |
| 30 |
let decoder = new TextDecoder(); |
| 31 |
let buffer = ''; |
| 32 |
let hasData = false; |
| 33 |
let message = {data: '', event: '', id: '', retry: null}; |
| 34 |
let firstChunk = true; |
| 35 |
|
| 36 |
try { |
| 37 |
while (true) { |
| 38 |
let {done, value} = await reader.read(); |
| 39 |
if (done) break; |
| 40 |
|
| 41 |
let chunk = decoder.decode(value, {stream: true}); |
| 42 |
|
| 43 |
if (firstChunk) { |
| 44 |
if (chunk.charCodeAt(0) === 0xFEFF) chunk = chunk.slice(1); |
| 45 |
firstChunk = false; |
| 46 |
} |
| 47 |
buffer += chunk; |
| 48 |
|
| 49 |
|
| 50 |
let lines = buffer.split(/\r\n|\r|\n/); |
| 51 |
buffer = lines.pop() || ''; |
| 52 |
|
| 53 |
for (let line of lines) { |
| 54 |
if (!line) { |
| 55 |
if (hasData) { |
| 56 |
yield message; |
| 57 |
hasData = false; |
| 58 |
message = {data: '', event: '', id: '', retry: null}; |
| 59 |
} |
| 60 |
continue; |
| 61 |
} |
| 62 |
|
| 63 |
let colonIndex = line.indexOf(':'); |
| 64 |
if (colonIndex === 0) continue; |
| 65 |
|
| 66 |
let field, value; |
| 67 |
if (colonIndex < 0) { |
| 68 |
|
| 69 |
field = line; |
| 70 |
value = ''; |
| 71 |
} else { |
| 72 |
field = line.slice(0, colonIndex); |
| 73 |
value = line.slice(colonIndex + 1); |
| 74 |
if (value[0] === ' ') value = value.slice(1); |
| 75 |
} |
| 76 |
|
| 77 |
if (field === 'data') { |
| 78 |
message.data += (hasData ? '\n' : '') + value; |
| 79 |
hasData = true; |
| 80 |
} else if (field === 'event') { |
| 81 |
message.event = value; |
| 82 |
} else if (field === 'id') { |
| 83 |
if (!value.includes('\0')) message.id = value; |
| 84 |
} else if (field === 'retry') { |
| 85 |
let retryValue = parseInt(value, 10); |
| 86 |
if (!isNaN(retryValue)) message.retry = retryValue; |
| 87 |
} |
| 88 |
} |
| 89 |
} |
| 90 |
} finally { |
| 91 |
reader.releaseLock(); |
| 92 |
} |
| 93 |
} |
| 94 |
|
| 95 |
|
| 96 |
|
| 97 |
|
| 98 |
|
| 99 |
|
| 100 |
|
| 101 |
async function handleSSEResponse(ctx) { |
| 102 |
let element = ctx.sourceElement; |
| 103 |
let config = getConfig(ctx); |
| 104 |
let reconnectRequested = false; |
| 105 |
|
| 106 |
let connection = { |
| 107 |
url: ctx.request.action, |
| 108 |
config: config, |
| 109 |
abortController: null, |
| 110 |
reader: null, |
| 111 |
lastEventId: null, |
| 112 |
delayCanceller: null, |
| 113 |
visibilityHandler: null, |
| 114 |
attempt: 0, |
| 115 |
cancelled: false, |
| 116 |
status: null |
| 117 |
}; |
| 118 |
api.htmxProp(element).sse = connection; |
| 119 |
|
| 120 |
let reconnect = () => { |
| 121 |
if (!element.isConnected || reconnectRequested) return; |
| 122 |
reconnectRequested = true; |
| 123 |
if (connection.delayCanceller) connection.delayCanceller(); |
| 124 |
connection.reader?.cancel(); |
| 125 |
}; |
| 126 |
|
| 127 |
let paused = false; |
| 128 |
let unpauseResolver = null; |
| 129 |
|
| 130 |
if (config.pauseOnBackground) { |
| 131 |
let visibilityHandler = () => { |
| 132 |
if (document.hidden) { |
| 133 |
paused = true; |
| 134 |
connection.reader?.cancel(); |
| 135 |
} else if (paused) { |
| 136 |
paused = false; |
| 137 |
if (unpauseResolver) unpauseResolver(); |
| 138 |
} |
| 139 |
}; |
| 140 |
document.addEventListener('visibilitychange', visibilityHandler); |
| 141 |
connection.visibilityHandler = visibilityHandler; |
| 142 |
} |
| 143 |
|
| 144 |
connection.cancelled = false; |
| 145 |
if (!api.triggerHtmxEvent(element, 'htmx:before:sse:connection', {connection}) || connection.cancelled) { |
| 146 |
cleanup(element, 'cancelled'); |
| 147 |
return; |
| 148 |
} |
| 149 |
|
| 150 |
connection.status = ctx.response.status; |
| 151 |
api.triggerHtmxEvent(element, 'htmx:after:sse:connection', {connection}); |
| 152 |
|
| 153 |
let currentResponse = ctx.response.raw; |
| 154 |
|
| 155 |
try { |
| 156 |
while (element.isConnected) { |
| 157 |
e) |
| 158 |
if (connection.attempt > 0) { |
| 159 |
|
| 160 |
if (paused) { |
| 161 |
await new Promise(r => { unpauseResolver = r; }); |
| 162 |
unpauseResolver = null; |
| 163 |
if (!element.isConnected) break; |
| 164 |
connection.attempt = 1; |
| 165 |
reconnectRequested = true; |
| 166 |
} |
| 167 |
|
| 168 |
if (!reconnectRequested) { |
| 169 |
if (!config.reconnect || connection.attempt > config.reconnectMaxAttempts) break; |
| 170 |
} |
| 171 |
|
| 172 |
let baseDelay = htmx.parseInterval(config.reconnectDelay) ?? config.reconnectDelay; |
| 173 |
let maxDelay = htmx.parseInterval(config.reconnectMaxDelay) ?? config.reconnectMaxDelay; |
| 174 |
let delay = Math.min( |
| 175 |
baseDelay * Math.pow(2, connection.attempt - 1), |
| 176 |
maxDelay |
| 177 |
); |
| 178 |
if (config.reconnectJitter > 0) { |
| 179 |
let jitterRange = delay * config.reconnectJitter; |
| 180 |
delay = Math.max(0, delay + (Math.random() * 2 - 1) * jitterRange); |
| 181 |
} |
| 182 |
|
| 183 |
connection.cancelled = false; |
| 184 |
if (!api.triggerHtmxEvent(element, 'htmx:before:sse:connection', {connection}) || connection.cancelled) break; |
| 185 |
|
| 186 |
await new Promise(r => { |
| 187 |
connection.delayCanceller = r; |
| 188 |
setTimeout(r, delay); |
| 189 |
}); |
| 190 |
connection.delayCanceller = null; |
| 191 |
if (!element.isConnected) break; |
| 192 |
|
| 193 |
|
| 194 |
let ac = new AbortController(); |
| 195 |
connection.abortController = ac; |
| 196 |
try { |
| 197 |
if (connection.lastEventId) ctx.request.headers['Last-Event-ID'] = connection.lastEventId; |
| 198 |
currentResponse = await fetch(ctx.request.action, { |
| 199 |
...ctx.request, |
| 200 |
signal: ac.signal |
| 201 |
}); |
| 202 |
} catch (e) { |
| 203 |
if (ac.signal.aborted) break; |
| 204 |
api.triggerHtmxEvent(element, 'htmx:sse:error', {error: e, url: ctx.request.action}); |
| 205 |
reconnectRequested = false; |
| 206 |
connection.attempt++; |
| 207 |
continue; |
| 208 |
} |
| 209 |
|
| 210 |
if (!currentResponse.ok) { |
| 211 |
api.triggerHtmxEvent(element, 'htmx:sse:error', { |
| 212 |
error: new Error(`SSE reconnect failed with status ${currentResponse.status}`), |
| 213 |
status: currentResponse.status, |
| 214 |
url: ctx.request.action |
| 215 |
}); |
| 216 |
reconnectRequested = false; |
| 217 |
connection.attempt++; |
| 218 |
continue; |
| 219 |
} |
| 220 |
|
| 221 |
connection.status = currentResponse.status; |
| 222 |
api.triggerHtmxEvent(element, 'htmx:after:sse:connection', {connection}); |
| 223 |
connection.attempt = 0; |
| 224 |
} |
| 225 |
|
| 226 |
|
| 227 |
reconnectRequested = false; |
| 228 |
|
| 229 |
try { |
| 230 |
connection.reader = currentResponse.body.getReader(); |
| 231 |
|
| 232 |
for await (let msg of parseSSE(connection.reader)) { |
| 233 |
if (!element.isConnected || reconnectRequested) break; |
| 234 |
|
| 235 |
let detail = { |
| 236 |
message: {data: msg.data, event: msg.event, id: msg.id, cancelled: false} |
| 237 |
}; |
| 238 |
if (!api.triggerHtmxEvent(element, 'htmx:before:sse:message', detail) || detail.message.cancelled) continue; |
| 239 |
|
| 240 |
if (msg.id) { |
| 241 |
connection.lastEventId = msg.id; |
| 242 |
} |
| 243 |
if (msg.retry != null) config.reconnectDelay = msg.retry; |
| 244 |
|
| 245 |
if (detail.message.event) { |
| 246 |
htmx.trigger(element, detail.message.event, {data: detail.message.data, id: detail.message.id}); |
| 247 |
delete detail.message.cancelled; |
| 248 |
api.triggerHtmxEvent(element, 'htmx:after:sse:message', detail); |
| 249 |
|
| 250 |
nt |
| 251 |
let closeEvent = api.attributeValue(element, 'hx-sse:close'); |
| 252 |
if (closeEvent && detail.message.event === closeEvent) { |
| 253 |
cleanup(element, 'message'); |
| 254 |
return; |
| 255 |
} |
| 256 |
continue; |
| 257 |
} |
| 258 |
|
| 259 |
|
| 260 |
ctx.text = detail.message.data; |
| 261 |
if (!ctx.swap.includes('swapEmpty')) ctx.swap += ' swapEmpty:false'; |
| 262 |
await htmx.swap(ctx); |
| 263 |
delete detail.message.cancelled; |
| 264 |
api.triggerHtmxEvent(element, 'htmx:after:sse:message', detail); |
| 265 |
} |
| 266 |
} catch (e) { |
| 267 |
if (!connection.abortController?.signal?.aborted) { |
| 268 |
api.triggerHtmxEvent(element, 'htmx:sse:error', {error: e, url: ctx.request.action}); |
| 269 |
} |
| 270 |
} |
| 271 |
|
| 272 |
connection.reader = null; |
| 273 |
if (!element.isConnected) break; |
| 274 |
|
| 275 |
connection.attempt++; |
| 276 |
} |
| 277 |
} finally { |
| 278 |
cleanup(element, element.isConnected ? 'ended' : 'removed'); |
| 279 |
} |
| 280 |
} |
| 281 |
|
| 282 |
|
| 283 |
|
| 284 |
|
| 285 |
|
| 286 |
function processElement(element) { |
| 287 |
let connectUrl = api.attributeValue(element, 'hx-sse:connect'); |
| 288 |
if (!connectUrl) return; |
| 289 |
if (element._htmx?.sse) return; |
| 290 |
|
| 291 |
let specString = api.attributeValue(element, 'hx-trigger') || 'load'; |
| 292 |
api.onTrigger(element, specString, () => { |
| 293 |
if (element._htmx?.sse) return; |
| 294 |
htmx.ajax('GET', connectUrl, {source: element}); |
| 295 |
}); |
| 296 |
} |
| 297 |
|
| 298 |
|
| 299 |
|
| 300 |
|
| 301 |
|
| 302 |
function cleanup(element, reason) { |
| 303 |
let connection = element?._htmx?.sse; |
| 304 |
if (!connection) return; |
| 305 |
|
| 306 |
connection.abortController?.abort(); |
| 307 |
connection.reader?.cancel?.(); |
| 308 |
if (connection.delayCanceller) connection.delayCanceller(); |
| 309 |
if (connection.visibilityHandler) { |
| 310 |
document.removeEventListener('visibilitychange', connection.visibilityHandler); |
| 311 |
} |
| 312 |
api.triggerHtmxEvent(element, 'htmx:sse:close', {connection, reason: reason || 'cleanup'}); |
| 313 |
delete element._htmx.sse; |
| 314 |
} |
| 315 |
|
| 316 |
|
| 317 |
|
| 318 |
|
| 319 |
|
| 320 |
function checkLegacyAttributes(element) { |
| 321 |
if (element.hasAttribute('sse-connect')) { |
| 322 |
console.warn('htmx: [hx-sse] legacy attribute sse-connect is deprecated; use hx-sse:connect instead'); |
| 323 |
|
| 324 |
let url = element.getAttribute('sse-connect'); |
| 325 |
let attr = (htmx.config.prefix || 'hx-') + 'sse' + (htmx.config.metaCharacter || ':') + 'connect'; |
| 326 |
if (!element.hasAttribute(attr)) { |
| 327 |
element.setAttribute(attr, url); |
| 328 |
} |
| 329 |
} |
| 330 |
if (element.hasAttribute('sse-swap')) { |
| 331 |
console.warn('htmx: [hx-sse] sse-swap is removed in htmx 4. Unnamed SSE messages are swapped automatically. Named events are dispatched as DOM events.'); |
| 332 |
} |
| 333 |
} |
| 334 |
|
| 335 |
|
| 336 |
|
| 337 |
|
| 338 |
|
| 339 |
htmx.registerExtension('sse', { |
| 340 |
init: (internalAPI) => { |
| 341 |
api = internalAPI; |
| 342 |
}, |
| 343 |
|
| 344 |
htmx_config_request: (element, detail) => { |
| 345 |
detail.ctx.request.headers['Accept'] = 'text/html, text/event-stream'; |
| 346 |
}, |
| 347 |
|
| 348 |
|
| 349 |
htmx_before_response: (element, detail) => { |
| 350 |
let ctx = detail.ctx; |
| 351 |
let contentType = ctx.response.raw.headers.get('Content-Type'); |
| 352 |
if (!contentType?.includes('text/event-stream')) return; |
| 353 |
|
| 354 |
() |
| 355 |
handleSSEResponse(ctx).catch(e => { |
| 356 |
api.triggerHtmxEvent(element, 'htmx:sse:error', {error: e, url: ctx.request.action}); |
| 357 |
cleanup(element); |
| 358 |
}); |
| 359 |
return false; |
| 360 |
}, |
| 361 |
|
| 362 |
htmx_after_process: (element) => { |
| 363 |
checkLegacyAttributes(element); |
| 364 |
processElement(element); |
| 365 |
let mc = htmx.config.metaCharacter || ':'; |
| 366 |
let sseAttr = CSS.escape('hx-sse' + mc + 'connect'); |
| 367 |
let sseSelector = `[${sseAttr}]`; |
| 368 |
if (htmx.config.prefix) sseSelector += `,[${CSS.escape(htmx.config.prefix + 'sse' + mc + 'connect')}]`; |
| 369 |
element.querySelectorAll(`${sseSelector},[sse-connect]`).forEach((el) => { |
| 370 |
checkLegacyAttributes(el); |
| 371 |
processElement(el); |
| 372 |
}); |
| 373 |
}, |
| 374 |
|
| 375 |
htmx_before_cleanup: (element) => { |
| 376 |
cleanup(element); |
| 377 |
} |
| 378 |
}); |
| 379 |
})(); |