├── .github ├── FUNDING.yml └── ISSUE_TEMPLATE │ ├── bug_report.md │ ├── config.yml │ ├── feature_request.md │ └── question.md ├── .gitignore ├── .npmrc ├── .prettierignore ├── .prettierrc ├── LICENSE ├── README.md ├── bun.lock ├── e2e └── main.test.js ├── eslint.config.js ├── jsconfig.json ├── package.json ├── playwright.config.js ├── src ├── app.d.ts ├── app.html ├── lib │ ├── constants.js │ ├── consume.js │ ├── createRandomValue.js │ ├── delay.js │ ├── error.js │ ├── index.js │ ├── ok.js │ ├── playwright │ │ ├── getPlaywrightState.js │ │ └── playwright.js │ ├── produce.js │ ├── source.js │ ├── stores │ │ └── stats.js │ ├── types.external.js │ ├── types.internal.js │ └── uuid.js └── routes │ ├── +layout.svelte │ ├── +page.js │ ├── +page.server.js │ ├── +page.svelte │ ├── events │ └── +server.js │ ├── issue-43 │ ├── +page.svelte │ └── events │ │ └── +server.js │ ├── issue-48 │ ├── +page.svelte │ └── events │ │ └── +server.js │ ├── issue-55 │ ├── +page.svelte │ └── events │ │ └── +server.js │ ├── issue-58 │ ├── +page.svelte │ └── events │ │ └── +server.js │ ├── issue-65 │ ├── +page.svelte │ └── stats │ │ └── +server.js │ └── room │ ├── +page.js │ ├── +page.server.js │ ├── +page.svelte │ ├── +server.js │ ├── cat-name.js │ ├── mock-db.server.js │ ├── sse-utils.js │ ├── sse-utils.server.js │ └── waiting-lobby │ ├── +page.js │ ├── +page.server.js │ ├── +page.svelte │ └── +server.js ├── static └── favicon.png ├── svelte.config.js └── vite.config.js /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | # These are supported funding model platforms 2 | 3 | github: razshare 4 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/bug_report.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Bug report 3 | about: Create a bug report 4 | title: 'Bug: ' 5 | labels: bug 6 | assignees: '' 7 | 8 | --- 9 | 10 | **Describe the bug** 11 | A clear and concise description of what the bug is. 12 | 13 | **To Reproduce** 14 | Steps to reproduce the behavior: 15 | 1. Go to '...' 16 | 2. Click on '....' 17 | 3. Scroll down to '....' 18 | 4. See error 19 | 20 | **Expected behavior** 21 | A clear and concise description of what you expected to happen. 22 | 23 | **Screenshots** 24 | If applicable, add screenshots to help explain your problem. 25 | 26 | **Desktop (please complete the following information):** 27 | - OS: [e.g. iOS] 28 | - Browser [e.g. chrome, safari] 29 | - Version [e.g. 22] 30 | 31 | **Smartphone (please complete the following information):** 32 | - Device: [e.g. iPhone6] 33 | - OS: [e.g. iOS8.1] 34 | - Browser [e.g. stock browser, safari] 35 | - Version [e.g. 22] 36 | 37 | **Additional context** 38 | Add any other context about the problem here. 39 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/config.yml: -------------------------------------------------------------------------------- 1 | blank_issues_enabled: false 2 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/feature_request.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Feature request 3 | about: Suggest an idea for this project 4 | title: 'Feature: ' 5 | labels: feature request 6 | assignees: '' 7 | 8 | --- 9 | 10 | **Is your feature request related to a problem? Please describe.** 11 | A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] 12 | 13 | **Describe the solution you'd like** 14 | A clear and concise description of what you want to happen. 15 | 16 | **Describe alternatives you've considered** 17 | A clear and concise description of any alternative solutions or features you've considered. 18 | 19 | **Additional context** 20 | Add any other context or screenshots about the feature request here. 21 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/question.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Question 3 | about: Ask a question 4 | title: 'Question: ' 5 | labels: question 6 | assignees: '' 7 | 8 | --- 9 | 10 | 11 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | test-results 2 | node_modules 3 | 4 | # Output 5 | .output 6 | .vercel 7 | .netlify 8 | .wrangler 9 | /.svelte-kit 10 | /build 11 | /dist 12 | 13 | # OS 14 | .DS_Store 15 | Thumbs.db 16 | 17 | # Env 18 | .env 19 | .env.* 20 | !.env.example 21 | !.env.test 22 | 23 | # Vite 24 | vite.config.js.timestamp-* 25 | vite.config.ts.timestamp-* 26 | -------------------------------------------------------------------------------- /.npmrc: -------------------------------------------------------------------------------- 1 | engine-strict=true 2 | -------------------------------------------------------------------------------- /.prettierignore: -------------------------------------------------------------------------------- 1 | # Package Managers 2 | package-lock.json 3 | pnpm-lock.yaml 4 | yarn.lock 5 | -------------------------------------------------------------------------------- /.prettierrc: -------------------------------------------------------------------------------- 1 | { 2 | "arrowParens": "avoid", 3 | "singleQuote": true, 4 | "trailingComma": "all", 5 | "printWidth": 80, 6 | "plugins": ["prettier-plugin-svelte"], 7 | "semi": false, 8 | "svelteSortOrder": "options-styles-scripts-markup", 9 | "svelteStrictMode": false, 10 | "svelteBracketNewLine": true, 11 | "svelteIndentScriptAndStyle": true, 12 | "useTabs": false, 13 | "overrides": [{ "files": "*.svelte", "options": { "parser": "svelte" } }], 14 | "bracketSpacing": true, 15 | "quoteProps": "consistent" 16 | } 17 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2025 Razvan Tanase 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # SvelteKit SSE 2 | 3 | This library provides an easy way to produce and consume server sent events. 4 | 5 | Install with: 6 | 7 | ```sh 8 | npm i -D sveltekit-sse 9 | ``` 10 | 11 | Produce your server sent events with 12 | 13 | ```js 14 | // src/routes/custom-event/+server.js 15 | import { produce } from 'sveltekit-sse' 16 | 17 | /** 18 | * @param {number} milliseconds 19 | * @returns 20 | */ 21 | function delay(milliseconds) { 22 | return new Promise(function run(resolve) { 23 | setTimeout(resolve, milliseconds) 24 | }) 25 | } 26 | 27 | export function POST() { 28 | return produce(async function start({ emit }) { 29 | while (true) { 30 | const {error} = emit('message', `the time is ${Date.now()}`) 31 | if(error) { 32 | return 33 | } 34 | await delay(1000) 35 | } 36 | }) 37 | } 38 | ``` 39 | 40 | Consume them on your client with 41 | 42 | ```svelte 43 | 48 | 49 | {$value} 50 | ``` 51 | Your application will render something like this 52 | 53 | ![Peek 2024-05-28 03-03](https://github.com/razshare/sveltekit-sse/assets/6891346/215b0b26-fa21-4841-9b69-b28a4c1ec731) 54 | 55 | 56 | ## Locking 57 | 58 | All streams are locked server side by default, meaning the server will keep the connection alive indefinitely. 59 | 60 | The locking mechanism is achieved through a `Writable`, which you can access from the `start` function. 61 | 62 | ```js 63 | import { produce } from 'sveltekit-sse' 64 | export function POST() { 65 | return produce(function start({ emit, lock }) { 66 | emit('message', 'hello world') 67 | setTimeout(function unlock() { 68 | lock.set(false) 69 | }, 2000) 70 | }) 71 | } 72 | ``` 73 | 74 | The above code `emit`s the `hello world` string with the `message` event name and closes the stream after 2 seconds. 75 | 76 | You should not send any more messages after invoking `lock.set(false)` otherwise your `emit` function will return an error.\ 77 | The resulting error is wrapped in `Unsafe`, which you can manage using conditionals 78 | 79 | ```js 80 | lock.set(false) 81 | const { error } = emit('message', 'I have a bad feeling about this...') 82 | if (error) { 83 | console.error(error) 84 | return 85 | } 86 | ``` 87 | 88 | ## Stop 89 | 90 | You can stop a connection and run code when a connection is stopped 91 | - by returning a function from `start()` 92 | ```js 93 | import { produce } from 'sveltekit-sse' 94 | export function POST() { 95 | return produce(function start({ emit, lock }) { 96 | emit('message', 'hello') 97 | return function cancel() { 98 | console.log('Connection canceled.') 99 | } 100 | }) 101 | } 102 | ``` 103 | 104 | - or by setting `options::stop()` and calling `lock.set(false)` 105 | 106 | ```js 107 | import { produce } from 'sveltekit-sse' 108 | export function POST() { 109 | return produce( 110 | function start({ emit, lock }) { 111 | emit('message', 'hello') 112 | lock.set(false) 113 | }, 114 | { 115 | stop() { 116 | console.log('Connection stopped.') 117 | }, 118 | }, 119 | ) 120 | } 121 | ``` 122 | 123 | Both ways are valid. 124 | 125 | > [!NOTE] 126 | > In the second case, using `options::stop()`, your code will also 127 | > run if the client itself cancels the connections. 128 | 129 | ## Cleanup 130 | 131 | Whenever the client disconnects from the stream, the server will detect that event and trigger your [stop function](#stop).\ 132 | This behavior has a delay of 30 seconds by default.\ 133 | This is achieved through a ping mechanism, by periodically (_every 30 seconds by default_) sending a ping event to the client. 134 | 135 | You can customize that ping event's time interval 136 | 137 | ```js 138 | import { produce } from 'sveltekit-sse' 139 | export function POST() { 140 | return produce( 141 | function start() { 142 | // Your emitters go here 143 | }, 144 | { 145 | ping: 4000, // Custom ping interval 146 | stop(){ 147 | console.log("Client disconnected.") 148 | } 149 | }, 150 | ) 151 | } 152 | ``` 153 | 154 | You can also forcefully detect disconnected clients by simply emitting any event to that client, you will get back an error if the client has disconnected. 155 | 156 | When that happens, you should stop your producer 157 | 158 | ```js 159 | import { produce } from 'sveltekit-sse' 160 | export function POST() { 161 | return produce(async function start({ emit }) { 162 | await new Promise(function start(resolve){ 163 | someRemoteEvent("incoming-data", function run(data){ 164 | const {error} = emit("data", data) 165 | if(error){ 166 | resolve(error) 167 | } 168 | }) 169 | }) 170 | return function stop(){ 171 | // Do your cleanup here 172 | console.log("Client has disconnected.") 173 | } 174 | }) 175 | } 176 | ``` 177 | 178 | ## Reconnect 179 | 180 | You can reconnect to the stream whenever the stream closes 181 | 182 | ```html 183 | 199 | 200 | {$data} 201 | ``` 202 | 203 | ## Custom Headers 204 | 205 | You can apply custom headers to the request 206 | 207 | ```html 208 | 221 | 222 | {$data} 223 | ``` 224 | 225 | ## Transform 226 | 227 | You can transform the stream into any type of object you want by using `source::select::transform`. 228 | 229 | The `transform` method receives a `string`, which is the value of the store. 230 | 231 | Here's an example how to use it. 232 | 233 | ```html 234 | 246 | ``` 247 | 248 | ## Json 249 | 250 | You can parse incoming messages from the source as json using `source::select::json`. 251 | 252 | ```svelte 253 | 17 | 18 | 28 |
29 |
30 | 31 |
32 | 33 |
34 | 35 |

An International Cat Quote

36 | {$quote?.value}
37 | -------------------------------------------------------------------------------- /src/routes/events/+server.js: -------------------------------------------------------------------------------- 1 | import { delay } from '$lib/delay.js' 2 | import { produce } from '$lib/produce.js' 3 | 4 | /** 5 | * @typedef Quote 6 | * @property {string} id 7 | * @property {string} value 8 | */ 9 | 10 | /** 11 | * @type {Array} 12 | */ 13 | const CAT_QUOTES = [ 14 | '"Cats are connoisseurs of comfort." - James Herriot', 15 | '"Just watching my cats can make me happy." - Paula Cole', 16 | '"I\'m not sure why I like cats so much. I mean, they\'re really cute obviously. They are both wild and domestic at the same time." - Michael Showalter', 17 | '"You can not look at a sleeping cat and feel tense." - Jane Pauley', 18 | '"The phrase \'domestic cat\' is an oxymoron." - George Will', 19 | '"One cat just leads to another." - Ernest Hemingway', 20 | ] 21 | 22 | /** 23 | * @type {Array} 24 | */ 25 | const FRASI_GATTO = [ 26 | '"I gatti sono intenditori del comfort." - James Herriot', 27 | '"Guardare i miei gatti può farmi felice." - Paula Cole', 28 | '"Non sono sicuro del perché mi piacciano così tanto i gatti. Voglio dire, sono ovviamente molto carini. Sono sia selvatici che domestici allo stesso tempo." - Michael Showalter', 29 | '"Non puoi guardare un gatto che dorme e sentirti teso." - Jane Pauley', 30 | '"La frase \'gatto domestico\' è un ossimoro." - George Will', 31 | '"Un gatto porta ad un altro." - Ernest Hemingway', 32 | ] 33 | 34 | /** @type {Record } */ 35 | const LANGUAGE_MAP = { 36 | en: CAT_QUOTES, 37 | it: FRASI_GATTO, 38 | } 39 | 40 | /** 41 | * @param {string | null} [language] 42 | * @returns {Quote} 43 | */ 44 | function findCatQuote(language) { 45 | language = language || 'en' 46 | const quotes = LANGUAGE_MAP[language] || CAT_QUOTES 47 | const index = Math.floor(Math.random() * quotes.length) 48 | return { id: `item-${index}-${language}`, value: quotes[index] } 49 | } 50 | 51 | /** 52 | * Send some data to the client 53 | * @param {string} lang 54 | * @param {import('$lib/types.external.js').Connection} payload 55 | */ 56 | async function dumpData(lang, { emit, lock }) { 57 | for (let i = 0; i < 10; i++) { 58 | const catQuote = findCatQuote(lang) 59 | const stringifiedCatQuote = JSON.stringify(catQuote) 60 | 61 | const { error } = emit('cat-quote', i === 9 ? 'qw___' : stringifiedCatQuote) 62 | if (error) { 63 | lock.set(false) 64 | return function cancel() { 65 | console.error(error.message) 66 | } 67 | } 68 | await delay(1000) 69 | } 70 | lock.set(false) 71 | return function cancel() { 72 | console.log('Stream canceled.') 73 | } 74 | } 75 | 76 | export function POST({ url }) { 77 | return produce(function start(connection) { 78 | const lang = url.searchParams.get('lang') || 'en' 79 | return dumpData(lang, connection) 80 | }) 81 | } 82 | -------------------------------------------------------------------------------- /src/routes/issue-43/+page.svelte: -------------------------------------------------------------------------------- 1 | 2 | 46 | 47 |

{$message}

48 | 49 | 50 | 51 | -------------------------------------------------------------------------------- /src/routes/issue-43/events/+server.js: -------------------------------------------------------------------------------- 1 | import { produce } from '$lib' 2 | import { delay } from '$lib/delay.js' 3 | 4 | export async function POST() { 5 | return produce(async function start({ emit }) { 6 | // eslint-disable-next-line no-constant-condition 7 | while (true) { 8 | const { error } = emit('message', `${Date.now()}`) 9 | if (error) { 10 | return 11 | } 12 | await delay(1000) 13 | } 14 | }) 15 | } 16 | -------------------------------------------------------------------------------- /src/routes/issue-48/+page.svelte: -------------------------------------------------------------------------------- 1 | 59 | -------------------------------------------------------------------------------- /src/routes/issue-48/events/+server.js: -------------------------------------------------------------------------------- 1 | import { produce } from '$lib' 2 | 3 | export function POST() { 4 | return produce(function start({ emit }) { 5 | const data = { time: Date.now() } 6 | emit('event0', JSON.stringify(data)) 7 | }) 8 | } 9 | -------------------------------------------------------------------------------- /src/routes/issue-55/+page.svelte: -------------------------------------------------------------------------------- 1 | 2 | 13 | 14 |

{$message}

15 | -------------------------------------------------------------------------------- /src/routes/issue-55/events/+server.js: -------------------------------------------------------------------------------- 1 | import { produce } from '$lib' 2 | import { delay } from '$lib/delay.js' 3 | 4 | export async function GET() { 5 | return produce(async function start({ emit }) { 6 | // eslint-disable-next-line no-constant-condition 7 | while (true) { 8 | const { error } = emit('message', `${Date.now()}`) 9 | if (error) { 10 | return 11 | } 12 | await delay(1000) 13 | } 14 | }) 15 | } 16 | -------------------------------------------------------------------------------- /src/routes/issue-58/+page.svelte: -------------------------------------------------------------------------------- 1 | 2 | 13 | 14 |

{$message}

15 | -------------------------------------------------------------------------------- /src/routes/issue-58/events/+server.js: -------------------------------------------------------------------------------- 1 | import { produce } from '$lib' 2 | import { delay } from '$lib/delay.js' 3 | 4 | export async function GET() { 5 | return produce( 6 | async function start({ emit }) { 7 | // eslint-disable-next-line no-constant-condition 8 | while (true) { 9 | const { error } = emit('message', `${Date.now()}`) 10 | if (error) { 11 | return 12 | } 13 | await delay(1000) 14 | } 15 | }, 16 | { 17 | stop() { 18 | console.log('Client disconnected!!') 19 | }, 20 | }, 21 | ) 22 | } 23 | -------------------------------------------------------------------------------- /src/routes/issue-65/+page.svelte: -------------------------------------------------------------------------------- 1 | 4 | 5 |
6 |

Admin dashboard page

7 | 8 | {#if localStorage.getItem('showStats')} 9 | Cpu usage - {$stats.cpu_usage}
10 | Memory - {$stats.memory}
11 | Time - {$stats.time}
12 | {/if} 13 |
14 | -------------------------------------------------------------------------------- /src/routes/issue-65/stats/+server.js: -------------------------------------------------------------------------------- 1 | import { produce } from '$lib' 2 | import { delay } from '$lib/delay' 3 | 4 | export function POST() { 5 | return produce( 6 | async function start({ emit, lock }) { 7 | while (lock) { 8 | emit( 9 | 'message', 10 | JSON.stringify({ 11 | cpu_usage: '0.00%', 12 | memory: '200.67 MB', 13 | time: Date.now(), 14 | }), 15 | ) 16 | await delay(1000) 17 | } 18 | }, 19 | { 20 | stop() { 21 | console.info('SSE client disconnected.') 22 | }, 23 | }, 24 | ) 25 | } 26 | -------------------------------------------------------------------------------- /src/routes/room/+page.js: -------------------------------------------------------------------------------- 1 | import { catName } from './cat-name' 2 | import { orPrevious, reconnectingSource } from './sse-utils' 3 | 4 | export async function load() { 5 | const id = catName() 6 | 7 | const connection = reconnectingSource(`/room`, { 8 | options: { body: JSON.stringify({ id }) }, 9 | }) 10 | 11 | /** @type {import('svelte/store').Readable} */ 12 | const usersInRoom = connection.select('usersInRoom').json(orPrevious) 13 | 14 | /** @type {import('svelte/store').Readable} */ 15 | const usersInLobby = connection.select('usersInLobby').json(orPrevious) 16 | 17 | return { 18 | id, 19 | usersInRoom, 20 | usersInLobby, 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/routes/room/+page.server.js: -------------------------------------------------------------------------------- 1 | import { fail } from '@sveltejs/kit' 2 | import { lobby, updateStore } from './mock-db.server' 3 | 4 | export const actions = { 5 | async approve({ request }) { 6 | const data = await request.formData() 7 | const id = data.get('id') 8 | if (!id || typeof id !== 'string') return fail(400) 9 | 10 | updateStore(lobby, { id, approved: true }) 11 | }, 12 | async decline({ request }) { 13 | const data = await request.formData() 14 | const id = data.get('id') 15 | if (!id || typeof id !== 'string') return fail(400) 16 | 17 | updateStore(lobby, { id, approved: false }) 18 | }, 19 | } 20 | -------------------------------------------------------------------------------- /src/routes/room/+page.svelte: -------------------------------------------------------------------------------- 1 | 10 | 11 |

Inside

12 | 13 |
    14 | {#each $usersInRoom || [] as user (user.id)} 15 |
  • 16 | Participant {user.id} 17 | {data.id === user.id ? '(You)' : ''} 18 |
  • 19 | {:else} 20 |
  • 21 | (There are no participants inside the room... which is surprising, 23 | because you are reading this) 25 |
  • 26 | {/each} 27 |
28 | 29 |

Outside

30 | 31 |
    32 | {#each $usersInLobby || [] as guest (guest.id)} 33 |
  • 34 | Guest {guest.id} 35 |
    36 | 37 | 38 | 39 |
    40 |
  • 41 | {:else} 42 |
  • (There are no guests in the waiting lobby)
  • 43 | {/each} 44 |
45 | -------------------------------------------------------------------------------- /src/routes/room/+server.js: -------------------------------------------------------------------------------- 1 | import { produce } from '$lib' 2 | import { room, lobbyView, updateStore, removeFromStore } from './mock-db.server' 3 | import { eventStopper } from './sse-utils.server' 4 | 5 | export async function POST({ route, request }) { 6 | /** @type {string} */ 7 | let id 8 | 9 | if (request.body) { 10 | id = (await request.json()).id 11 | } 12 | 13 | return produce(function start({ emit, lock }) { 14 | const stopper = eventStopper(route.id, emit, lock) 15 | 16 | const unsubRoom = room.subscribe(function notify(value) { 17 | const { error } = emit('usersInRoom', JSON.stringify(value)) 18 | if (error) { 19 | console.error(error) 20 | lock.set(false) 21 | } 22 | }) 23 | stopper.push(unsubRoom) 24 | 25 | const unsubLobby = lobbyView.subscribe(function notify(value) { 26 | const { error } = emit('usersInLobby', JSON.stringify(value)) 27 | if (error) { 28 | console.error(error) 29 | lock.set(false) 30 | } 31 | }) 32 | stopper.push(unsubLobby) 33 | 34 | updateStore(room, { id }) 35 | stopper.push(function leaveRoom() { 36 | removeFromStore(room, id) 37 | }) 38 | 39 | return stopper.onStop 40 | }) 41 | } 42 | -------------------------------------------------------------------------------- /src/routes/room/cat-name.js: -------------------------------------------------------------------------------- 1 | import { browser } from '$app/environment' 2 | 3 | let cat = '' 4 | 5 | /** 6 | * Retrieves an existing cat name from session storage, or generate a new one 7 | * whenever a new tab is opened. 8 | */ 9 | export function catName() { 10 | if (cat || !browser) return cat 11 | 12 | cat = sessionStorage.getItem('catname') || '' 13 | sessionStorage.tabsopened++ // keep track of tab count to avoid duplicate names 14 | 15 | if (!cat || sessionStorage.tabsopened >= 1) { 16 | const adjective = adjectives[Math.floor(Math.random() * adjectives.length)] 17 | const name = names[Math.floor(Math.random() * names.length)] 18 | cat = `${adjective} ${name}` 19 | sessionStorage.setItem('catname', cat) 20 | sessionStorage.setItem('tabsopened', '0') 21 | } 22 | 23 | return cat 24 | } 25 | 26 | if (browser) { 27 | // decrement tab count, so name is persisted on refresh 28 | window.addEventListener('beforeunload', function countUnloads() { 29 | sessionStorage.tabsopened-- 30 | }) 31 | } 32 | 33 | const adjectives = [ 34 | 'Sleek', 35 | 'Elegant', 36 | 'Graceful', 37 | 'Majestic', 38 | 'Agile', 39 | 'Cuddly', 40 | 'Curious', 41 | 'Playful', 42 | 'Independent', 43 | 'Affectionate', 44 | 'Gentle', 45 | 'Mysterious', 46 | 'Adorable', 47 | 'Regal', 48 | 'Sociable', 49 | 'Furry', 50 | 'Mellow', 51 | 'Charming', 52 | 'Mischievous', 53 | 'Sphinxlike', 54 | 'Lithe', 55 | 'Fluffy', 56 | 'Agile', 57 | 'Alert', 58 | 'Quick', 59 | 'Proud', 60 | 'Inquisitive', 61 | 'Agile', 62 | 'Energetic', 63 | 'Nimble', 64 | 'Vivacious', 65 | 'Clever', 66 | 'Noble', 67 | 'Sophisticated', 68 | 'Soft', 69 | 'Agreeable', 70 | 'Feline', 71 | 'Sassy', 72 | 'Spry', 73 | 'Stealthy', 74 | 'Sly', 75 | 'Whiskered', 76 | 'Sly', 77 | 'Quiet', 78 | 'Sharp-eyed', 79 | 'Fuzzy', 80 | 'Slender', 81 | 'Lithe', 82 | ] 83 | 84 | const names = [ 85 | 'Whiskers', 86 | 'Mittens', 87 | 'Shadow', 88 | 'Luna', 89 | 'Simba', 90 | 'Tigger', 91 | 'Felix', 92 | 'Cleo', 93 | 'Smokey', 94 | 'Oreo', 95 | 'Gizmo', 96 | 'Milo', 97 | 'Bella', 98 | 'Leo', 99 | 'Oliver', 100 | 'Loki', 101 | 'Charlie', 102 | 'Chloe', 103 | 'Max', 104 | 'Lucy', 105 | 'Salem', 106 | 'Nala', 107 | 'Jasper', 108 | 'Coco', 109 | 'Misty', 110 | 'Socks', 111 | 'Toby', 112 | 'Princess', 113 | 'Garfield', 114 | 'Pumpkin', 115 | 'Shadow', 116 | 'Ziggy', 117 | 'Sapphire', 118 | 'Marbles', 119 | 'Muffin', 120 | 'Peanut', 121 | 'Tinkerbell', 122 | 'Midnight', 123 | 'Cinnamon', 124 | 'Socks', 125 | 'Snuggles', 126 | 'Fluffy', 127 | 'Angel', 128 | 'Ginger', 129 | 'Fuzzy', 130 | 'Boots', 131 | 'Socks', 132 | 'Snowball', 133 | ] 134 | -------------------------------------------------------------------------------- /src/routes/room/mock-db.server.js: -------------------------------------------------------------------------------- 1 | import { derived, writable } from 'svelte/store' 2 | 3 | /** 4 | * @typedef {{ id: string, approved?: boolean }} User 5 | */ 6 | 7 | /** 8 | * Users in the room. 9 | * @type {import('svelte/store').Writable<{ id: string }[]> } 10 | */ 11 | export const room = writable([]) 12 | 13 | /** 14 | * Users in the waiting lobby. 15 | * @type {import('svelte/store').Writable<{ id: string, approved?: boolean }[]> } 16 | */ 17 | export const lobby = writable([]) 18 | 19 | /** 20 | * Derived view of the waiting lobby. Only includes users in the lobby who are 21 | * waiting for approval. 22 | */ 23 | export const lobbyView = derived(lobby, function view($lobby) { 24 | const waitingForApproval = [] 25 | 26 | for (const user of $lobby) { 27 | if (user.approved == undefined) { 28 | waitingForApproval.push(user) 29 | } 30 | } 31 | 32 | return waitingForApproval 33 | }) 34 | 35 | /** 36 | * @param {User[]} users 37 | * @param {string} id 38 | */ 39 | export function findMatchingId(users, id) { 40 | return users.find(function same(user) { 41 | return user.id === id 42 | }) 43 | } 44 | 45 | /** 46 | * @template {{id: string}} T 47 | * @param {import('svelte/store').Writable} store 48 | * @param {T} update 49 | */ 50 | export function updateStore(store, update) { 51 | store.update(function upsert(objects) { 52 | const object = findMatchingId(objects, update.id) 53 | if (object) { 54 | Object.assign(object, update) 55 | } else { 56 | objects.push(update) 57 | } 58 | return objects 59 | }) 60 | } 61 | 62 | /** 63 | * @template {{id: string}} T 64 | * @param {import('svelte/store').Writable} store 65 | * @param {string} id 66 | */ 67 | export function removeFromStore(store, id) { 68 | store.update(function removeFrom(objects) { 69 | return objects.filter(function exceptWithId(object) { 70 | return object.id !== id 71 | }) 72 | }) 73 | } 74 | -------------------------------------------------------------------------------- /src/routes/room/sse-utils.js: -------------------------------------------------------------------------------- 1 | import { source } from '$lib' 2 | import { readonly, writable } from 'svelte/store' 3 | 4 | /** 5 | * Wrapper for the source function that reconnects on close or error. 6 | * 7 | * @param {string} url Path to the stream. 8 | * @param {import('$lib').SourceConfiguration} [opts] 9 | */ 10 | export function reconnectingSource(url, opts = {}) { 11 | /** @type {import('svelte/store').Writable<'connecting' | 'reconnecting' | 'connected' | 'closed' | 'errored' >} */ 12 | const status = writable('connecting') 13 | 14 | let stopped = false 15 | let _connect = function noop() {} 16 | 17 | function reconnect() { 18 | status.set('reconnecting') 19 | stopped = false 20 | _connect() 21 | listenToStopEvents() 22 | } 23 | 24 | const connection = source(url, { 25 | open({ connect }) { 26 | status.set('connected') 27 | _connect = connect 28 | }, 29 | 30 | close({ connect, isLocal }) { 31 | status.set('closed') 32 | _connect = connect 33 | 34 | if (isLocal) { 35 | stopped = true 36 | } else if (!stopped) { 37 | console.error( 38 | `Event stream ${url} closed unexpectedly, reconnecting...`, 39 | ) 40 | reconnect() 41 | } 42 | }, 43 | 44 | error({ connect, error, isLocal }) { 45 | status.set('errored') 46 | _connect = connect 47 | console.error(`Connection to ${url} errored:`, error) 48 | 49 | if (isLocal) { 50 | stopped = true 51 | } else if (!stopped) { 52 | console.error( 53 | `Event stream ${url} errored unexpectedly, reconnecting...`, 54 | ) 55 | reconnect() 56 | } 57 | }, 58 | ...opts, 59 | }) 60 | 61 | function listenToStopEvents() { 62 | let initial = true 63 | const unsub = connection.select('stop').subscribe(function listen(message) { 64 | if (initial) { 65 | initial = false // Svelte will call the first subscriber immediately, so we need to ignore 66 | return 67 | } 68 | 69 | // Discard prefix - timetamp followed by colon, space 70 | message = message.split(': ')[1] 71 | 72 | stopped = true 73 | connection.close() 74 | if (message) { 75 | console.warn(`Event stream ${url} stoppped by server:`, message.length) 76 | } else { 77 | console.log(`Event stream ${url} stoppped by server.`) 78 | } 79 | unsub() 80 | }) 81 | } 82 | 83 | listenToStopEvents() 84 | 85 | return { 86 | ...connection, 87 | reconnect, 88 | status: readonly(status), 89 | } 90 | } 91 | 92 | /** 93 | * Use this function with SvelteKit form actions to prevent submission from 94 | * invalidating load functions. 95 | * 96 | * @type {import('@sveltejs/kit').SubmitFunction} 97 | */ 98 | export function skipInvalidate() { 99 | return async function onResponse({ update }) { 100 | await update({ reset: false, invalidateAll: false }) 101 | } 102 | } 103 | 104 | /** 105 | * Default error handler for `.json()` transformer parsing errors. 106 | * 107 | * @type {import('$lib').JsonPredicate} 108 | */ 109 | export function orPrevious({ error, previous, raw }) { 110 | console.warn( 111 | `Could not parse "${raw}" as json, reverting back to ${previous}. ${error}`, 112 | ) 113 | return previous 114 | } 115 | -------------------------------------------------------------------------------- /src/routes/room/sse-utils.server.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Helper function to create a stopper object for SSE events. 3 | * 4 | * @param {string} route_id 5 | * @param {import('$lib').Connection['emit']} emit 6 | * @param {import('$lib').Connection['lock']} lock 7 | * 8 | * @example 9 | * export function POST({ route, request }) { 10 | * return events({ 11 | * request, 12 | * start({ emit, lock }) { 13 | * const stopper = eventStopper(route.id, emit, lock) 14 | * 15 | * const unsub = databaseListener.subscribe(function notify(event) { 16 | * if (event.type === 'new') { 17 | * const { error } = emit('event', JSON.stringify(event)) 18 | * if (error) { 19 | * return stopper.stop(error) 20 | * } 21 | * } else if (event.type === 'end') { 22 | * return stopper.stop() 23 | * } else { 24 | * return stopper.stop('Unexpected error') 25 | * } 26 | * }) 27 | * 28 | * stopper.push(unsub) 29 | * 30 | * return stopper.onStop 31 | * } 32 | * }) 33 | * } 34 | */ 35 | export function eventStopper(route_id, emit, lock) { 36 | /** @type {(() => void)[]} */ 37 | const stopFunctions = [] 38 | 39 | return { 40 | /** 41 | * Appends a callback to run when the stopper is stopped. 42 | * @param {() => void} func 43 | */ 44 | push(func) { 45 | stopFunctions.push(func) 46 | }, 47 | 48 | /** 49 | * Calls all functions in the stopper. Expected usage is that this will be\ 50 | * returned at the end of the `start` scope of the `events` function, 51 | * instead of being called directly. 52 | */ 53 | onStop() { 54 | for (const fn of stopFunctions) { 55 | try { 56 | console.debug('Stopping SSE @', route_id) 57 | fn() 58 | } catch (err) { 59 | console.error('Error stopping SSE @', route_id, err) 60 | } 61 | } 62 | }, 63 | 64 | /** 65 | * Emits a `stop` event to the client, then locks the connection. If a 66 | * message is provided, it will be pushed to the client as an error message. 67 | */ 68 | stop(message = '') { 69 | // Include timestamp with message to ensure Svelte reactivity 70 | const { error } = emit('stop', `${new Date().getTime()}: ${message}`) 71 | if (error && error.message !== 'Client disconnected from the stream.') { 72 | console.error('Error stopping SSE @', route_id, error) 73 | } 74 | lock.set(false) 75 | 76 | return this.onStop 77 | }, 78 | } 79 | } 80 | -------------------------------------------------------------------------------- /src/routes/room/waiting-lobby/+page.js: -------------------------------------------------------------------------------- 1 | import { catName } from '../cat-name' 2 | import { reconnectingSource, orPrevious } from '../sse-utils' 3 | 4 | export function load() { 5 | const id = catName() 6 | 7 | const connection = reconnectingSource(`/room/waiting-lobby`, { 8 | options: { body: JSON.stringify({ id }) }, 9 | }) 10 | 11 | /** @type {import('svelte/store').Readable} */ 12 | const waitingUser = connection.select('waitingUser').json(orPrevious) 13 | 14 | return { id, waitingUser, connection } 15 | } 16 | -------------------------------------------------------------------------------- /src/routes/room/waiting-lobby/+page.server.js: -------------------------------------------------------------------------------- 1 | import { fail } from '@sveltejs/kit' 2 | import { lobby, updateStore } from '../mock-db.server' 3 | 4 | export const actions = { 5 | async rejoin({ request }) { 6 | const form = await request.formData() 7 | 8 | const id = form.get('id') 9 | if (!id || typeof id !== 'string') return fail(400) 10 | 11 | updateStore(lobby, { id, approved: undefined }) 12 | }, 13 | } 14 | -------------------------------------------------------------------------------- /src/routes/room/waiting-lobby/+page.svelte: -------------------------------------------------------------------------------- 1 | 19 | 20 |

You are {data.id}, connection status {$status}

21 | 22 | {#if $status.includes('connecting')} 23 |

Connecting...

24 | {:else if $waitingUser?.approved === false} 25 |

You have been denied access to the room.

26 | {:else if $status === 'connected'} 27 |

Waiting to be let into the room...

28 | {:else} 29 |

Disconnected.

30 | {/if} 31 | 32 | {#if $status === 'closed'} 33 |
45 | 46 | 47 |
48 | {:else} 49 | 50 | {/if} 51 | -------------------------------------------------------------------------------- /src/routes/room/waiting-lobby/+server.js: -------------------------------------------------------------------------------- 1 | import { produce } from '$lib' 2 | import { 3 | findMatchingId, 4 | lobby, 5 | removeFromStore, 6 | updateStore, 7 | } from '../mock-db.server' 8 | import { eventStopper } from '../sse-utils.server' 9 | 10 | export async function POST({ route, request }) { 11 | /** @type {string} */ 12 | let id 13 | 14 | if (request.body) { 15 | id = (await request.json()).id 16 | } 17 | 18 | return produce(function start({ emit, lock }) { 19 | const stopper = eventStopper(route.id, emit, lock) 20 | 21 | updateStore(lobby, { id, approved: undefined }) 22 | stopper.push(function leaveLobby() { 23 | removeFromStore(lobby, id) 24 | }) 25 | 26 | const unsub = lobby.subscribe(function notify(guests) { 27 | const guest = findMatchingId(guests, id) 28 | 29 | if (!guest) { 30 | // already disconnected 31 | return lock.set(false) 32 | } 33 | 34 | const { error } = emit('waitingUser', JSON.stringify(guest)) 35 | if (error) { 36 | console.error(error) 37 | lock.set(false) 38 | } else if (guest.approved === true || guest.approved === false) { 39 | stopper.stop() 40 | } 41 | }) 42 | stopper.push(unsub) 43 | 44 | const { error } = emit('waitingUser', JSON.stringify({ id })) 45 | if (error) { 46 | console.error(error) 47 | lock.set(false) 48 | } 49 | 50 | return stopper.onStop 51 | }) 52 | } 53 | -------------------------------------------------------------------------------- /static/favicon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/razshare/sveltekit-sse/3218dce237e71b5130f5deac1dd59aa512573b6b/static/favicon.png -------------------------------------------------------------------------------- /svelte.config.js: -------------------------------------------------------------------------------- 1 | import adapter from '@sveltejs/adapter-auto' 2 | 3 | /** @type {import('@sveltejs/kit').Config} */ 4 | const config = { 5 | kit: { 6 | // adapter-auto only supports some environments, see https://svelte.dev/docs/kit/adapter-auto for a list. 7 | // If your environment is not supported, or you settled on a specific environment, switch out the adapter. 8 | // See https://svelte.dev/docs/kit/adapters for more information about adapters. 9 | adapter: adapter(), 10 | }, 11 | } 12 | 13 | export default config 14 | -------------------------------------------------------------------------------- /vite.config.js: -------------------------------------------------------------------------------- 1 | import { sveltekit } from '@sveltejs/kit/vite' 2 | import { defineConfig } from 'vite' 3 | export default defineConfig({ 4 | plugins: [sveltekit()], 5 | }) 6 | --------------------------------------------------------------------------------