@@ -26,6 +26,18 @@ export interface Toastr {
2626 error : ( message : string ) => void ;
2727}
2828
29+ interface ChatEvent {
30+ event_type : number ;
31+ content ?: string ;
32+ user_id : number ;
33+ }
34+
35+ interface ChatEvents {
36+ events : ChatEvent [ ] ;
37+ time : number ;
38+ sync : number ;
39+ }
40+
2941declare const CHAT : ChatObject ;
3042declare const toastr : Toastr ;
3143declare const fire : {
@@ -422,17 +434,53 @@ void (async function(): Promise<void> {
422434 await new Promise ( resolve => setTimeout ( resolve , 0 ) ) ;
423435 await Domains . fetchAllDomainInformation ( ) ;
424436
437+ const domParser = new DOMParser ( ) ;
438+
425439 CHAT . addEventHandlerHook ( event => {
426440 const eventToPass = Object . assign ( {
427441 ...event ,
428442 // because we can't use DOMParser with tests,
429443 // newChatEventOccurred has to accept a Document argument for content
430- content : new DOMParser ( ) . parseFromString ( event . content , 'text/html' )
444+ content : domParser . parseFromString ( event . content , 'text/html' )
431445 } ) as ChatParsedEvent ;
432446
433447 newChatEventOccurred ( eventToPass ) ;
434448 } ) ;
435449
450+ // to fix caching issues, fetch the most recent 100 messages
451+ // and run newChatEventOccurred on them
452+ try {
453+ const fkey = document . querySelector < HTMLInputElement > ( '#fkey' ) ?. value ;
454+ const formData = new FormData ( ) ;
455+ formData . append ( 'since' , '0' ) ;
456+ formData . append ( 'mode' , 'Messages' ) ;
457+ formData . append ( 'msgCount' , '100' ) ;
458+ formData . append ( 'fkey' , fkey || '' ) ;
459+
460+ const request = await fetch (
461+ 'https://chat.stackexchange.com/chats/11540/events' ,
462+ {
463+ method : 'POST' ,
464+ body : formData
465+ }
466+ ) ;
467+ const response = await request . json ( ) as ChatEvents ;
468+
469+ response . events
470+ . filter ( ( { event_type, content } ) => event_type === 1 && content )
471+ . forEach ( event => {
472+ const parsed = Object . assign ( {
473+ ...event ,
474+ content : domParser . parseFromString ( event . content as string , 'text/html' )
475+ } ) as ChatParsedEvent ;
476+
477+ // do NOT fetch PR info from the GitHub API
478+ newChatEventOccurred ( parsed , false ) ;
479+ } ) ;
480+ } catch ( error ) {
481+ console . error ( error ) ;
482+ }
483+
436484 window . addEventListener ( 'fire-popup-open' , ( ) => {
437485 void addHtmlToFirePopup ( ) ;
438486 } ) ;
0 commit comments