From 2f09909babea728bab6268a5d987187077fc3a4f Mon Sep 17 00:00:00 2001 From: Ben McCann <322311+benmccann@users.noreply.github.com> Date: Tue, 7 Sep 2021 16:35:51 -0700 Subject: [PATCH 1/3] [feat] use the Vite server options in dev mode --- .changeset/spotty-ties-love.md | 5 ++ packages/kit/src/core/dev/index.js | 76 ++++++++++++++++++------------ 2 files changed, 52 insertions(+), 29 deletions(-) create mode 100644 .changeset/spotty-ties-love.md diff --git a/.changeset/spotty-ties-love.md b/.changeset/spotty-ties-love.md new file mode 100644 index 000000000000..32e1e21e996b --- /dev/null +++ b/.changeset/spotty-ties-love.md @@ -0,0 +1,5 @@ +--- +'@sveltejs/kit': patch +--- + +[feat] use the Vite server options in dev mode diff --git a/packages/kit/src/core/dev/index.js b/packages/kit/src/core/dev/index.js index 06253e6919e4..31259df1f9c5 100644 --- a/packages/kit/src/core/dev/index.js +++ b/packages/kit/src/core/dev/index.js @@ -18,7 +18,6 @@ import { print_config_conflicts } from '../config/index.js'; import { create_app } from '../create_app/index.js'; import create_manifest_data from '../create_manifest_data/index.js'; import { getRawBody } from '../node/index.js'; -import { get_server } from '../server/index.js'; import { SVELTE_KIT, SVELTE_KIT_ASSETS } from '../constants.js'; import { copy_assets, resolve_entry } from '../utils.js'; @@ -106,14 +105,17 @@ class Watcher extends EventEmitter { } }; - /** @type {(req: import("http").IncomingMessage, res: import("http").ServerResponse) => void} */ - let handler = (req, res) => {}; - - this.server = await get_server(this.https, vite_config, (req, res) => handler(req, res)); - // don't warn on overriding defaults const [modified_vite_config] = deep_merge(default_config, vite_config); + const kit_plugin = await create_plugin(this.config, this.dir, this.cwd, () => { + if (!this.manifest) { + throw new Error('Manifest is not available'); + } + + return this.manifest; + }); + /** @type {[any, string[]]} */ const [merged_config, conflicts] = deep_merge(modified_vite_config, { configFile: false, @@ -138,14 +140,13 @@ class Watcher extends EventEmitter { compilerOptions: { hydratable: !!this.config.kit.hydrate } - }) + }), + kit_plugin ], publicDir: this.config.kit.files.assets, server: { - middlewareMode: true, - hmr: { - ...(this.https ? { server: this.server, port: this.port } : {}) - } + host: this.host, + https: this.https }, base: this.config.kit.paths.assets.startsWith('/') ? `${this.config.kit.paths.assets}/` : '/' }); @@ -154,17 +155,21 @@ class Watcher extends EventEmitter { this.vite = await vite.createServer(merged_config); - const get_manifest = () => { - if (!this.manifest) { - throw new Error('Manifest is not available'); + /** + * @type {import('connect').Server} + */ + const connect_server = this.vite.middlewares; + // TODO: replace index with name after https://github.com/vitejs/vite/pull/4908 is merged and released + const spa_fallback_index = 7; + const html_middlewares = ['viteIndexHtmlMiddleware', 'vite404Middleware']; + for (let i = connect_server.stack.length - 1; i > 0; i--) { + // @ts-expect-error using internals until https://github.com/vitejs/vite/pull/4640 is merged + if (html_middlewares.includes(connect_server.stack[i].name) || i === spa_fallback_index) { + connect_server.stack.splice(i, 1); } + } - return this.manifest; - }; - - handler = await create_handler(this.vite, this.config, this.dir, this.cwd, get_manifest); - - this.server.listen(this.port, this.host || '0.0.0.0'); + await this.vite.listen(this.port); } update() { @@ -211,7 +216,7 @@ class Watcher extends EventEmitter { } close() { - if (!this.vite || !this.server || !this.cheapwatch) { + if (!this.vite || !this.cheapwatch) { throw new Error('Cannot close server before it is initialized'); } @@ -219,7 +224,6 @@ class Watcher extends EventEmitter { this.closed = true; this.vite.close(); - this.server.close(); this.cheapwatch.close(); } } @@ -248,13 +252,12 @@ function get_params(array) { } /** - * @param {vite.ViteDevServer} vite * @param {import('types/config').ValidatedConfig} config * @param {string} dir * @param {string} cwd * @param {() => import('types/internal').SSRManifest} get_manifest */ -async function create_handler(vite, config, dir, cwd, get_manifest) { +async function create_plugin(config, dir, cwd, get_manifest) { /** * @type {amp_validator.Validator?} */ @@ -274,11 +277,14 @@ async function create_handler(vite, config, dir, cwd, get_manifest) { }; /** - * @param {import('http').IncomingMessage} req - * @param {import('http').ServerResponse} res + * @param {vite.ViteDevServer} vite */ - return (req, res) => { - vite.middlewares(req, res, async () => { + function create_kit_middleware(vite) { + /** + * Use a named function for debugging + * @type {import('connect').NextHandleFunction} + */ + return async function svelteKitMiddleware(req, res) { try { if (!req.url || !req.method) throw new Error('Incomplete request'); if (req.url === '/favicon.ico') return not_found(res); @@ -490,7 +496,19 @@ async function create_handler(vite, config, dir, cwd, get_manifest) { res.statusCode = 500; res.end(e.stack); } - }); + }; + } + + return { + name: 'vite-plugin-svelte-kit', + /** + * @param {import('vite').ViteDevServer} vite + */ + configureServer(vite) { + return () => { + vite.middlewares.use(create_kit_middleware(vite)); + }; + } }; } From 7486720e7dc11a3770970b464b2af1c401dc0fb2 Mon Sep 17 00:00:00 2001 From: Ben McCann <322311+benmccann@users.noreply.github.com> Date: Sun, 12 Sep 2021 22:03:59 -0700 Subject: [PATCH 2/3] move server code into preview directory --- .../kit/src/core/{server => preview}/cert.js | 0 packages/kit/src/core/preview/index.js | 37 +++++++++++++++++-- packages/kit/src/core/server/index.js | 32 ---------------- 3 files changed, 34 insertions(+), 35 deletions(-) rename packages/kit/src/core/{server => preview}/cert.js (100%) delete mode 100644 packages/kit/src/core/server/index.js diff --git a/packages/kit/src/core/server/cert.js b/packages/kit/src/core/preview/cert.js similarity index 100% rename from packages/kit/src/core/server/cert.js rename to packages/kit/src/core/preview/cert.js diff --git a/packages/kit/src/core/preview/index.js b/packages/kit/src/core/preview/index.js index a859ba209700..de89bf9404b9 100644 --- a/packages/kit/src/core/preview/index.js +++ b/packages/kit/src/core/preview/index.js @@ -1,9 +1,10 @@ import fs from 'fs'; -import { pathToFileURL } from 'url'; +import http from 'http'; +import https from 'https'; +import { join, resolve } from 'path'; import sirv from 'sirv'; +import { pathToFileURL } from 'url'; import { getRawBody } from '../node/index.js'; -import { join, resolve } from 'path'; -import { get_server } from '../server/index.js'; import { __fetch_polyfill } from '../../install-fetch.js'; import { SVELTE_KIT, SVELTE_KIT_ASSETS } from '../constants.js'; @@ -128,3 +129,33 @@ export async function preview({ return Promise.resolve(server); } + +/** + * @param {boolean} use_https + * @param {import('vite').UserConfig} user_config + * @param {(req: http.IncomingMessage, res: http.ServerResponse) => void} handler + * @returns {Promise} + */ +async function get_server(use_https, user_config, handler) { + /** @type {https.ServerOptions} */ + const https_options = {}; + + if (use_https) { + const secure_opts = user_config.server + ? /** @type {import('tls').SecureContextOptions} */ (user_config.server.https) + : {}; + + if (secure_opts.key && secure_opts.cert) { + https_options.key = secure_opts.key.toString(); + https_options.cert = secure_opts.cert.toString(); + } else { + https_options.key = https_options.cert = (await import('./cert')).createCertificate(); + } + } + + return Promise.resolve( + use_https + ? https.createServer(/** @type {https.ServerOptions} */ (https_options), handler) + : http.createServer(handler) + ); +} diff --git a/packages/kit/src/core/server/index.js b/packages/kit/src/core/server/index.js deleted file mode 100644 index d5f11683f418..000000000000 --- a/packages/kit/src/core/server/index.js +++ /dev/null @@ -1,32 +0,0 @@ -import http from 'http'; -import https from 'https'; - -/** - * @param {boolean} use_https - * @param {import('vite').UserConfig} user_config - * @param {(req: http.IncomingMessage, res: http.ServerResponse) => void} handler - * @returns {Promise} - */ -export async function get_server(use_https, user_config, handler) { - /** @type {https.ServerOptions} */ - const https_options = {}; - - if (use_https) { - const secure_opts = user_config.server - ? /** @type {import('tls').SecureContextOptions} */ (user_config.server.https) - : {}; - - if (secure_opts.key && secure_opts.cert) { - https_options.key = secure_opts.key.toString(); - https_options.cert = secure_opts.cert.toString(); - } else { - https_options.key = https_options.cert = (await import('./cert')).createCertificate(); - } - } - - return Promise.resolve( - use_https - ? https.createServer(/** @type {https.ServerOptions} */ (https_options), handler) - : http.createServer(handler) - ); -} From 989965931161aef9cb715750af369a293e7fc139 Mon Sep 17 00:00:00 2001 From: Ben McCann <322311+benmccann@users.noreply.github.com> Date: Sun, 12 Sep 2021 22:51:45 -0700 Subject: [PATCH 3/3] refactor out a separate method and fix todo --- packages/kit/src/core/dev/index.js | 33 ++++++++++++++++-------------- 1 file changed, 18 insertions(+), 15 deletions(-) diff --git a/packages/kit/src/core/dev/index.js b/packages/kit/src/core/dev/index.js index 31259df1f9c5..06a6a7192384 100644 --- a/packages/kit/src/core/dev/index.js +++ b/packages/kit/src/core/dev/index.js @@ -154,21 +154,7 @@ class Watcher extends EventEmitter { print_config_conflicts(conflicts, 'kit.vite.'); this.vite = await vite.createServer(merged_config); - - /** - * @type {import('connect').Server} - */ - const connect_server = this.vite.middlewares; - // TODO: replace index with name after https://github.com/vitejs/vite/pull/4908 is merged and released - const spa_fallback_index = 7; - const html_middlewares = ['viteIndexHtmlMiddleware', 'vite404Middleware']; - for (let i = connect_server.stack.length - 1; i > 0; i--) { - // @ts-expect-error using internals until https://github.com/vitejs/vite/pull/4640 is merged - if (html_middlewares.includes(connect_server.stack[i].name) || i === spa_fallback_index) { - connect_server.stack.splice(i, 1); - } - } - + remove_html_middlewares(this.vite.middlewares); await this.vite.listen(this.port); } @@ -517,3 +503,20 @@ function not_found(res) { res.statusCode = 404; res.end('Not found'); } + +/** + * @param {import('connect').Server} server + */ +function remove_html_middlewares(server) { + const html_middlewares = [ + 'viteIndexHtmlMiddleware', + 'vite404Middleware', + 'viteSpaFallbackMiddleware' + ]; + for (let i = server.stack.length - 1; i > 0; i--) { + // @ts-expect-error using internals until https://github.com/vitejs/vite/pull/4640 is merged + if (html_middlewares.includes(server.stack[i].handle.name)) { + server.stack.splice(i, 1); + } + } +}