-
-
Notifications
You must be signed in to change notification settings - Fork 2k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
feat: native support for Websockets #12973
Draft
LukeHagar
wants to merge
11
commits into
sveltejs:main
Choose a base branch
from
LukeHagar:crossws
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Draft
Changes from all commits
Commits
Show all changes
11 commits
Select commit
Hold shift + click to select a range
d0b7f09
example crossws implementation with `hooks.server.js` websocketHooks …
LukeHagar b69b2e0
Migrated from hooks to server.js export named socket, validated funct…
LukeHagar aa69e1c
Formatting and fix a test
LukeHagar 38c919c
removed global comment
LukeHagar 2a022b5
regenerated types
LukeHagar c3a0bf7
removed some log statements
LukeHagar c86e4e9
cleaning up previous implementation
LukeHagar 5858b49
Thoroughly tested handle implementation
LukeHagar 9d56c50
Cleaning
LukeHagar 46c8682
regenerated types and ran formatter
LukeHagar 7791759
generate types
eltigerchino File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,193 @@ | ||
import { BROWSER, DEV } from 'esm-env'; | ||
import { validate_server_exports } from '../../utils/exports.js'; | ||
import { exec } from '../../utils/routing.js'; | ||
import { decode_pathname, decode_params } from '../../utils/url.js'; | ||
import { base } from '__sveltekit/paths'; | ||
|
||
/** | ||
* @param {import('types').SSROptions} options | ||
* @param {import('@sveltejs/kit').SSRManifest} manifest | ||
* @param {import('types').SSRState} state | ||
* @returns {(info: Request | import('crossws').Peer) => import('types').MaybePromise<Partial<import('crossws').Hooks>>} | ||
*/ | ||
export function resolve(options, manifest, state) { | ||
return async (info) => { | ||
/** @type {Request} */ | ||
let request; | ||
|
||
// These types all need to be straightened out | ||
if (info.request) { | ||
request = info.request; | ||
} else { | ||
request = info; | ||
} | ||
|
||
/** URL but stripped from the potential `/__data.json` suffix and its search param */ | ||
const url = new URL(request.url); | ||
|
||
// reroute could alter the given URL, so we pass a copy | ||
let rerouted_path; | ||
try { | ||
rerouted_path = options.hooks.reroute({ url }) ?? url.pathname; | ||
} catch { | ||
return {}; | ||
} | ||
|
||
let decoded; | ||
try { | ||
decoded = decode_pathname(rerouted_path); | ||
} catch (e) { | ||
console.error(e); | ||
return {}; | ||
} | ||
|
||
if (base && decoded.startsWith(base)) { | ||
decoded = decoded.slice(base.length) || '/'; | ||
} | ||
|
||
/** @type {import('types').SSRRoute | null} */ | ||
let route = null; | ||
|
||
/** @type {Record<string, string>} */ | ||
let params = {}; | ||
|
||
try { | ||
// TODO this could theoretically break - should probably be inside a try-catch | ||
const matchers = await manifest._.matchers(); | ||
|
||
for (const candidate of manifest._.routes) { | ||
const match = candidate.pattern.exec(decoded); | ||
|
||
if (!match) continue; | ||
|
||
const matched = exec(match, candidate.params, matchers); | ||
if (matched) { | ||
route = candidate; | ||
params = decode_params(matched); | ||
break; | ||
} | ||
} | ||
} catch (e) { | ||
console.error(e); | ||
return {}; | ||
} | ||
|
||
/** @type {Record<string, string>} */ | ||
const headers = {}; | ||
|
||
try { | ||
// determine whether we need to redirect to add/remove a trailing slash | ||
if (route && route.endpoint) { | ||
// if `paths.base === '/a/b/c`, then the root route is `/a/b/c/`, | ||
// regardless of the `trailingSlash` route option | ||
|
||
const node = await route.endpoint(); | ||
|
||
if (DEV) { | ||
validate_server_exports(node, /** @type {string} */ (route.endpoint_id)); | ||
} | ||
|
||
return { | ||
...node.socket, | ||
upgrade: async (req) => { | ||
/** @type {import('@sveltejs/kit').RequestEvent} */ | ||
const event = { | ||
// @ts-expect-error `cookies` and `fetch` need to be created after the `event` itself | ||
cookies: null, | ||
// @ts-expect-error | ||
fetch: null, | ||
getClientAddress: | ||
state.getClientAddress || | ||
(() => { | ||
throw new Error( | ||
`${__SVELTEKIT_ADAPTER_NAME__} does not specify getClientAddress. Please raise an issue` | ||
); | ||
}), | ||
locals: {}, | ||
params, | ||
platform: state.platform, | ||
request: req, | ||
socket: { | ||
/** | ||
* Accept a WebSocket Upgrade request | ||
* @param {RequestInit} init | ||
* @returns {RequestInit} | ||
*/ | ||
accept: (init) => { | ||
return { ...init }; | ||
}, | ||
/** | ||
* Reject a WebSocket Upgrade request | ||
* @param {number} status The [HTTP status code](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status#client_error_responses). Must be in the range 400-599. | ||
* @param {{ message: string } extends App.Error ? App.Error | string | undefined : never} body An object that conforms to the App.Error type. If a string is passed, it will be used as the message property. | ||
* @return {Response} A Response object | ||
* @throws {Error} If the provided status is invalid (not between 400 and 599). | ||
*/ | ||
reject: (status, body) => { | ||
if ((!BROWSER || DEV) && (isNaN(status) || status < 400 || status > 599)) { | ||
throw new Error( | ||
`HTTP error status codes must be between 400 and 599 — ${status} is invalid` | ||
); | ||
} | ||
|
||
try { | ||
const jsonBody = JSON.stringify(body); | ||
return new Response(jsonBody, { | ||
status, | ||
headers: { | ||
'content-type': 'application/json' | ||
} | ||
}); | ||
} catch (e) { | ||
console.error(e); | ||
throw new Error('Failed to serialize error body'); | ||
} | ||
} | ||
}, | ||
route: { id: route?.id ?? null }, | ||
setHeaders: (new_headers) => { | ||
for (const key in new_headers) { | ||
const lower = key.toLowerCase(); | ||
const value = new_headers[key]; | ||
|
||
if (lower === 'set-cookie') { | ||
throw new Error( | ||
'Use `event.cookies.set(name, value, options)` instead of `event.setHeaders` to set cookies' | ||
); | ||
} else if (lower in headers) { | ||
throw new Error(`"${key}" header is already set`); | ||
} else { | ||
headers[lower] = value; | ||
|
||
if (state.prerendering && lower === 'cache-control') { | ||
state.prerendering.cache = /** @type {string} */ (value); | ||
} | ||
} | ||
} | ||
}, | ||
url, | ||
isDataRequest: false, | ||
isSubRequest: state.depth > 0 | ||
}; | ||
|
||
const response = await options.hooks.handle({ | ||
event, | ||
resolve: async (event) => { | ||
if (node.socket && node.socket.upgrade) { | ||
return await node.socket.upgrade(event.request); | ||
} else { | ||
return new Response('Not Implemented', { status: 501 }); | ||
} | ||
} | ||
}); | ||
|
||
return response ?? new Response('Not Implemented', { status: 501 }); | ||
} | ||
}; | ||
} | ||
} catch (e) { | ||
console.error(e); | ||
return {}; | ||
} | ||
}; | ||
} |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Is returning
void
or aResponseInit
important to cancel the websocket connection? This would be a breaking change.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Its as I mentioned on Discord, returning a
Response
aborts the Websocket upgrade, and returning aheaders
object (or maybe more?) accepts the upgrade request, I'm not certain on thevoid
bit here but that was their typing.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I do think there is a path to improving the dev experience here, we have an issue logged on the crossws repo to discuss further.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Related to unjs/crossws#88
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Same, would love to keep this as is
unjs/crossws#90