@sveltejs/kit 1.0.0-next.210 → 1.0.0-next.211

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,29 +1,28 @@
1
- import require$$0$2, { EventEmitter } from 'events';
2
- import fs__default from 'fs';
3
1
  import path__default from 'path';
4
- import { URL } from 'url';
5
2
  import { svelte } from '@sveltejs/vite-plugin-svelte';
6
3
  import require$$0$1 from 'util';
7
4
  import require$$0 from 'os';
5
+ import fs__default from 'fs';
8
6
  import require$$2 from 'http';
9
7
  import require$$3 from 'https';
8
+ import require$$0$2 from 'events';
10
9
  import require$$1 from 'child_process';
11
10
  import require$$0$3 from 'domain';
12
11
  import 'querystring';
12
+ import { URL } from 'url';
13
13
  import require$$10 from 'vm';
14
- import CheapWatch from 'cheap-watch';
15
- import { r as rimraf, c as copy_assets, p as print_config_conflicts, g as get_mime_lookup, a as resolve_entry, $ } from '../cli.js';
16
14
  import vite from 'vite';
15
+ import { r as resolve_entry, $, g as get_mime_lookup, a as rimraf, c as copy_assets, p as print_config_conflicts } from '../cli.js';
16
+ import { c as create_manifest_data, a as create_app, d as deep_merge } from './index2.js';
17
+ import { S as SVELTE_KIT, a as SVELTE_KIT_ASSETS } from './constants.js';
17
18
  import { respond } from '../ssr.js';
18
- import { d as deep_merge, c as create_manifest_data, a as create_app } from './index2.js';
19
19
  import { __fetch_polyfill } from '../install-fetch.js';
20
20
  import { getRawBody } from '../node.js';
21
- import { S as SVELTE_KIT, a as SVELTE_KIT_ASSETS } from './constants.js';
22
21
  import { c as coalesce_to_error } from './error.js';
23
22
  import 'sade';
24
23
  import 'net';
25
- import './url.js';
26
24
  import './misc.js';
25
+ import './url.js';
27
26
  import 'node:http';
28
27
  import 'node:https';
29
28
  import 'node:zlib';
@@ -4201,429 +4200,229 @@ function main() {
4201
4200
 
4202
4201
  amphtmlValidator.main = main;
4203
4202
 
4204
- /** @typedef {{ cwd?: string, port: number, host?: string, https: boolean, config: import('types/config').ValidatedConfig }} Options */
4205
- /** @typedef {import('types/internal').SSRComponent} SSRComponent */
4206
-
4207
- /** @param {Options} opts */
4208
- function dev(opts) {
4209
- __fetch_polyfill();
4210
-
4211
- return new Watcher(opts).init();
4212
- }
4213
-
4214
- class Watcher extends EventEmitter {
4215
- /** @param {Options} opts */
4216
- constructor({ cwd = process.cwd(), port, host, https, config }) {
4217
- super();
4218
-
4219
- /** @type {string} */
4220
- this.cwd = cwd;
4221
-
4222
- /** @type {string} */
4223
- this.dir = path__default.resolve(cwd, `${SVELTE_KIT}/dev`);
4224
-
4225
- this.port = port;
4226
- this.host = host;
4227
- this.https = https;
4228
-
4229
- /** @type {import('types/config').ValidatedConfig} */
4230
- this.config = config;
4231
-
4232
- /**
4233
- * @type {vite.ViteDevServer | undefined}
4234
- */
4235
- this.vite;
4236
-
4237
- process.on('exit', () => {
4238
- this.close();
4239
- });
4240
- }
4241
-
4242
- async init() {
4243
- rimraf(this.dir);
4244
- copy_assets(this.dir);
4245
- process.env.VITE_SVELTEKIT_AMP = this.config.kit.amp ? 'true' : '';
4246
-
4247
- await this.init_filewatcher();
4248
- this.update();
4249
-
4250
- await this.init_server();
4251
-
4252
- return this;
4253
- }
4254
-
4255
- async init_filewatcher() {
4256
- this.cheapwatch = new CheapWatch({
4257
- dir: this.config.kit.files.routes,
4258
- /** @type {({ path }: { path: string }) => boolean} */
4259
- filter: ({ path }) => path.split('/').every((part) => part[0] !== '_' || part[1] === '_')
4260
- });
4261
-
4262
- await this.cheapwatch.init();
4263
-
4264
- // not sure why TS doesn't understand that CheapWatch extends EventEmitter
4265
- this.cheapwatch.on('+', ({ isNew }) => {
4266
- if (isNew) this.update();
4267
- });
4268
-
4269
- this.cheapwatch.on('-', () => {
4270
- this.update();
4271
- });
4272
- }
4273
-
4274
- allowed_directories() {
4275
- return [
4276
- ...new Set([
4277
- this.config.kit.files.assets,
4278
- this.config.kit.files.lib,
4279
- this.config.kit.files.routes,
4280
- path__default.resolve(this.cwd, 'src'),
4281
- path__default.resolve(this.cwd, SVELTE_KIT),
4282
- path__default.resolve(this.cwd, 'node_modules'),
4283
- path__default.resolve(vite.searchForWorkspaceRoot(this.cwd), 'node_modules')
4284
- ])
4285
- ];
4286
- }
4287
-
4288
- async init_server() {
4289
- if (!this.manifest) throw new Error('Must call init() before init_server()');
4290
-
4291
- /** @type {import('vite').UserConfig} */
4292
- const vite_config = (this.config.kit.vite && this.config.kit.vite()) || {};
4293
-
4294
- const default_config = {
4295
- server: {
4296
- fs: {
4297
- allow: this.allowed_directories()
4298
- },
4299
- strictPort: true
4300
- }
4301
- };
4302
-
4303
- // don't warn on overriding defaults
4304
- const [modified_vite_config] = deep_merge(default_config, vite_config);
4305
-
4306
- const kit_plugin = await create_plugin(this.config, this.dir, this.https, () => {
4307
- if (!this.manifest) {
4308
- throw new Error('Manifest is not available');
4309
- }
4310
-
4311
- return this.manifest;
4312
- });
4313
-
4314
- /** @type {[any, string[]]} */
4315
- const [merged_config, conflicts] = deep_merge(modified_vite_config, {
4316
- configFile: false,
4317
- root: this.cwd,
4318
- resolve: {
4319
- alias: {
4320
- $app: path__default.resolve(`${this.dir}/runtime/app`),
4321
- $lib: this.config.kit.files.lib
4322
- }
4323
- },
4324
- build: {
4325
- rollupOptions: {
4326
- // Vite dependency crawler needs an explicit JS entry point
4327
- // eventhough server otherwise works without it
4328
- input: path__default.resolve(`${this.dir}/runtime/internal/start.js`)
4329
- }
4330
- },
4331
- plugins: [
4332
- svelte({
4333
- extensions: this.config.extensions,
4334
- emitCss: !this.config.kit.amp,
4335
- compilerOptions: {
4336
- hydratable: !!this.config.kit.hydrate
4337
- }
4338
- }),
4339
- kit_plugin
4340
- ],
4341
- publicDir: this.config.kit.files.assets,
4342
- base: this.config.kit.paths.assets.startsWith('/') ? `${this.config.kit.paths.assets}/` : '/'
4343
- });
4344
-
4345
- print_config_conflicts(conflicts, 'kit.vite.');
4203
+ /**
4204
+ * @param {import('types/config').ValidatedConfig} config
4205
+ * @param {string} output
4206
+ * @param {string} cwd
4207
+ * @param {import('amphtml-validator').Validator | false} amp
4208
+ * @returns {import('vite').Plugin}
4209
+ */
4210
+ function create_plugin(config, output, cwd, amp) {
4211
+ return {
4212
+ name: 'vite-plugin-svelte-kit',
4346
4213
 
4347
- // optional config from command-line flags
4348
- // these should take precedence, but not print conflict warnings
4349
- if (this.host) {
4350
- merged_config.server.host = this.host;
4351
- }
4352
- // https is already enabled then do nothing. it could be an object and we
4353
- // don't want to overwrite with a boolean
4354
- if (this.https && !merged_config.server.https) {
4355
- merged_config.server.https = this.https;
4356
- }
4357
- if (this.port) {
4358
- merged_config.server.port = this.port;
4359
- }
4214
+ configureServer(vite) {
4215
+ __fetch_polyfill();
4360
4216
 
4361
- this.vite = await vite.createServer(merged_config);
4362
- await this.vite.listen(this.port);
4363
- }
4217
+ /** @type {import('types/app').SSRManifest} */
4218
+ let manifest;
4364
4219
 
4365
- update() {
4366
- const manifest_data = create_manifest_data({
4367
- config: this.config,
4368
- output: this.dir,
4369
- cwd: this.cwd
4370
- });
4220
+ function update_manifest() {
4221
+ const manifest_data = create_manifest_data({ config, output, cwd });
4371
4222
 
4372
- create_app({
4373
- manifest_data,
4374
- output: this.dir,
4375
- cwd: this.cwd
4376
- });
4223
+ create_app({ manifest_data, output, cwd });
4377
4224
 
4378
- /** @type {import('types/app').SSRManifest} */
4379
- this.manifest = {
4380
- appDir: this.config.kit.appDir,
4381
- assets: new Set(manifest_data.assets.map((asset) => asset.file)),
4382
- _: {
4383
- mime: get_mime_lookup(manifest_data),
4384
- entry: {
4385
- file: `/${SVELTE_KIT}/dev/runtime/internal/start.js`,
4386
- css: [],
4387
- js: []
4388
- },
4389
- nodes: manifest_data.components.map((id) => {
4390
- return async () => {
4391
- const url = `/${id}`;
4392
-
4393
- if (!this.vite) throw new Error('Vite server has not been initialized');
4394
-
4395
- const module = /** @type {SSRComponent} */ (await this.vite.ssrLoadModule(url));
4396
- const node = await this.vite.moduleGraph.getModuleByUrl(url);
4397
-
4398
- if (!node) throw new Error(`Could not find node for ${url}`);
4399
-
4400
- const deps = new Set();
4401
- find_deps(node, deps);
4402
-
4403
- const styles = new Set();
4404
-
4405
- for (const dep of deps) {
4406
- const parsed = new URL(dep.url, 'http://localhost/');
4407
- const query = parsed.searchParams;
4408
-
4409
- // TODO what about .scss files, etc?
4410
- if (
4411
- dep.file.endsWith('.css') ||
4412
- (query.has('svelte') && query.get('type') === 'style')
4413
- ) {
4414
- try {
4415
- const mod = await this.vite.ssrLoadModule(dep.url);
4416
- styles.add(mod.default);
4417
- } catch {
4418
- // this can happen with dynamically imported modules, I think
4419
- // because the Vite module graph doesn't distinguish between
4420
- // static and dynamic imports? TODO investigate, submit fix
4225
+ manifest = {
4226
+ appDir: config.kit.appDir,
4227
+ assets: new Set(manifest_data.assets.map((asset) => asset.file)),
4228
+ _: {
4229
+ mime: get_mime_lookup(manifest_data),
4230
+ entry: {
4231
+ file: `/${SVELTE_KIT}/dev/runtime/internal/start.js`,
4232
+ css: [],
4233
+ js: []
4234
+ },
4235
+ nodes: manifest_data.components.map((id) => {
4236
+ return async () => {
4237
+ const url = `/${id}`;
4238
+
4239
+ const module = /** @type {import('types/internal').SSRComponent} */ (
4240
+ await vite.ssrLoadModule(url)
4241
+ );
4242
+ const node = await vite.moduleGraph.getModuleByUrl(url);
4243
+
4244
+ if (!node) throw new Error(`Could not find node for ${url}`);
4245
+
4246
+ const deps = new Set();
4247
+ find_deps(node, deps);
4248
+
4249
+ const styles = new Set();
4250
+
4251
+ for (const dep of deps) {
4252
+ const parsed = new URL(dep.url, 'http://localhost/');
4253
+ const query = parsed.searchParams;
4254
+
4255
+ // TODO what about .scss files, etc?
4256
+ if (
4257
+ dep.file.endsWith('.css') ||
4258
+ (query.has('svelte') && query.get('type') === 'style')
4259
+ ) {
4260
+ try {
4261
+ const mod = await vite.ssrLoadModule(dep.url);
4262
+ styles.add(mod.default);
4263
+ } catch {
4264
+ // this can happen with dynamically imported modules, I think
4265
+ // because the Vite module graph doesn't distinguish between
4266
+ // static and dynamic imports? TODO investigate, submit fix
4267
+ }
4268
+ }
4421
4269
  }
4270
+
4271
+ return {
4272
+ module,
4273
+ entry: url.endsWith('.svelte') ? url : url + '?import',
4274
+ css: [],
4275
+ js: [],
4276
+ styles: Array.from(styles)
4277
+ };
4278
+ };
4279
+ }),
4280
+ routes: manifest_data.routes.map((route) => {
4281
+ if (route.type === 'page') {
4282
+ return {
4283
+ type: 'page',
4284
+ pattern: route.pattern,
4285
+ params: get_params(route.params),
4286
+ a: route.a.map((id) => manifest_data.components.indexOf(id)),
4287
+ b: route.b.map((id) => manifest_data.components.indexOf(id))
4288
+ };
4422
4289
  }
4423
- }
4424
4290
 
4425
- return {
4426
- module,
4427
- entry: url.endsWith('.svelte') ? url : url + '?import',
4428
- css: [],
4429
- js: [],
4430
- styles: Array.from(styles)
4431
- };
4432
- };
4433
- }),
4434
- routes: manifest_data.routes.map((route) => {
4435
- if (route.type === 'page') {
4436
- return {
4437
- type: 'page',
4438
- pattern: route.pattern,
4439
- params: get_params(route.params),
4440
- a: route.a.map((id) => manifest_data.components.indexOf(id)),
4441
- b: route.b.map((id) => manifest_data.components.indexOf(id))
4442
- };
4291
+ return {
4292
+ type: 'endpoint',
4293
+ pattern: route.pattern,
4294
+ params: get_params(route.params),
4295
+ load: async () => {
4296
+ const url = path__default.resolve(cwd, route.file);
4297
+ return await vite.ssrLoadModule(url);
4298
+ }
4299
+ };
4300
+ })
4443
4301
  }
4444
-
4445
- return {
4446
- type: 'endpoint',
4447
- pattern: route.pattern,
4448
- params: get_params(route.params),
4449
- load: async () => {
4450
- if (!this.vite) throw new Error('Vite server has not been initialized');
4451
- const url = path__default.resolve(this.cwd, route.file);
4452
- return await this.vite.ssrLoadModule(url);
4453
- }
4454
- };
4455
- })
4302
+ };
4456
4303
  }
4457
- };
4458
- }
4459
-
4460
- close() {
4461
- if (!this.vite || !this.cheapwatch) {
4462
- throw new Error('Cannot close server before it is initialized');
4463
- }
4464
-
4465
- if (this.closed) return;
4466
- this.closed = true;
4467
4304
 
4468
- this.vite.close();
4469
- this.cheapwatch.close();
4470
- }
4471
- }
4305
+ update_manifest();
4472
4306
 
4473
- /** @param {string[]} array */
4474
- function get_params(array) {
4475
- // given an array of params like `['x', 'y', 'z']` for
4476
- // src/routes/[x]/[y]/[z]/svelte, create a function
4477
- // that turns a RegExpExecArray into ({ x, y, z })
4307
+ vite.watcher.on('add', update_manifest);
4308
+ vite.watcher.on('remove', update_manifest);
4478
4309
 
4479
- /** @param {RegExpExecArray} match */
4480
- const fn = (match) => {
4481
- /** @type {Record<string, string>} */
4482
- const params = {};
4483
- array.forEach((key, i) => {
4484
- if (key.startsWith('...')) {
4485
- params[key.slice(3)] = match[i + 1] || '';
4486
- } else {
4487
- params[key] = match[i + 1];
4488
- }
4489
- });
4490
- return params;
4491
- };
4492
-
4493
- return fn;
4494
- }
4310
+ return () => {
4311
+ remove_html_middlewares(vite.middlewares);
4495
4312
 
4496
- /**
4497
- * @param {import('types/config').ValidatedConfig} config
4498
- * @param {string} dir
4499
- * @param {boolean} https
4500
- * @param {() => import('types/app').SSRManifest} get_manifest
4501
- */
4502
- async function create_plugin(config, dir, https, get_manifest) {
4503
- /**
4504
- * @type {amp_validator.Validator?}
4505
- */
4506
- const validator = config.kit.amp ? await amphtmlValidator.getInstance() : null;
4507
-
4508
- /**
4509
- * @param {vite.ViteDevServer} vite
4510
- */
4511
- function create_kit_middleware(vite) {
4512
- /**
4513
- * Use a named function for debugging
4514
- * @type {import('connect').NextHandleFunction}
4515
- */
4516
- return async function svelteKitMiddleware(req, res) {
4517
- try {
4518
- if (!req.url || !req.method) throw new Error('Incomplete request');
4519
- if (req.url === '/favicon.ico') return not_found(res);
4520
-
4521
- const parsed = new URL(req.url, 'http://localhost/');
4522
- if (!parsed.pathname.startsWith(config.kit.paths.base)) return not_found(res);
4523
-
4524
- /** @type {Partial<import('types/internal').Hooks>} */
4525
- const user_hooks = resolve_entry(config.kit.files.hooks)
4526
- ? await vite.ssrLoadModule(`/${config.kit.files.hooks}`)
4527
- : {};
4528
-
4529
- /** @type {import('types/internal').Hooks} */
4530
- const hooks = {
4531
- getSession: user_hooks.getSession || (() => ({})),
4532
- handle: user_hooks.handle || (({ request, resolve }) => resolve(request)),
4533
- handleError:
4534
- user_hooks.handleError ||
4535
- (({ /** @type {Error & { frame?: string }} */ error }) => {
4536
- console.error($.bold().red(error.message));
4537
- if (error.frame) {
4538
- console.error($.gray(error.frame));
4539
- }
4540
- if (error.stack) {
4541
- console.error($.gray(error.stack));
4542
- }
4543
- }),
4544
- externalFetch: user_hooks.externalFetch || fetch
4545
- };
4313
+ vite.middlewares.use(async (req, res) => {
4314
+ try {
4315
+ if (!req.url || !req.method) throw new Error('Incomplete request');
4316
+ if (req.url === '/favicon.ico') return not_found(res);
4317
+
4318
+ const parsed = new URL(req.url, 'http://localhost/');
4319
+ if (!parsed.pathname.startsWith(config.kit.paths.base)) return not_found(res);
4320
+
4321
+ /** @type {Partial<import('types/internal').Hooks>} */
4322
+ const user_hooks = resolve_entry(config.kit.files.hooks)
4323
+ ? await vite.ssrLoadModule(`/${config.kit.files.hooks}`)
4324
+ : {};
4325
+
4326
+ /** @type {import('types/internal').Hooks} */
4327
+ const hooks = {
4328
+ getSession: user_hooks.getSession || (() => ({})),
4329
+ handle: user_hooks.handle || (({ request, resolve }) => resolve(request)),
4330
+ handleError:
4331
+ user_hooks.handleError ||
4332
+ (({ /** @type {Error & { frame?: string }} */ error }) => {
4333
+ console.error($.bold().red(error.message));
4334
+ if (error.frame) {
4335
+ console.error($.gray(error.frame));
4336
+ }
4337
+ if (error.stack) {
4338
+ console.error($.gray(error.stack));
4339
+ }
4340
+ }),
4341
+ externalFetch: user_hooks.externalFetch || fetch
4342
+ };
4546
4343
 
4547
- if (/** @type {any} */ (hooks).getContext) {
4548
- // TODO remove this for 1.0
4549
- throw new Error(
4550
- 'The getContext hook has been removed. See https://kit.svelte.dev/docs#hooks'
4551
- );
4552
- }
4344
+ if (/** @type {any} */ (hooks).getContext) {
4345
+ // TODO remove this for 1.0
4346
+ throw new Error(
4347
+ 'The getContext hook has been removed. See https://kit.svelte.dev/docs#hooks'
4348
+ );
4349
+ }
4553
4350
 
4554
- if (/** @type {any} */ (hooks).serverFetch) {
4555
- // TODO remove this for 1.0
4556
- throw new Error('The serverFetch hook has been renamed to externalFetch.');
4557
- }
4351
+ if (/** @type {any} */ (hooks).serverFetch) {
4352
+ // TODO remove this for 1.0
4353
+ throw new Error('The serverFetch hook has been renamed to externalFetch.');
4354
+ }
4558
4355
 
4559
- const root = (await vite.ssrLoadModule(`/${dir}/generated/root.svelte`)).default;
4356
+ const root = (await vite.ssrLoadModule(`/${output}/generated/root.svelte`)).default;
4560
4357
 
4561
- const paths = await vite.ssrLoadModule(`/${SVELTE_KIT}/dev/runtime/paths.js`);
4358
+ const paths = await vite.ssrLoadModule(`/${SVELTE_KIT}/dev/runtime/paths.js`);
4562
4359
 
4563
- paths.set_paths({
4564
- base: config.kit.paths.base,
4565
- assets: config.kit.paths.assets ? SVELTE_KIT_ASSETS : config.kit.paths.base
4566
- });
4360
+ paths.set_paths({
4361
+ base: config.kit.paths.base,
4362
+ assets: config.kit.paths.assets ? SVELTE_KIT_ASSETS : config.kit.paths.base
4363
+ });
4567
4364
 
4568
- let body;
4365
+ let body;
4569
4366
 
4570
- try {
4571
- body = await getRawBody(req);
4572
- } catch (/** @type {any} */ err) {
4573
- res.statusCode = err.status || 400;
4574
- return res.end(err.reason || 'Invalid request body');
4575
- }
4367
+ try {
4368
+ body = await getRawBody(req);
4369
+ } catch (/** @type {any} */ err) {
4370
+ res.statusCode = err.status || 400;
4371
+ return res.end(err.reason || 'Invalid request body');
4372
+ }
4576
4373
 
4577
- const rendered = await respond(
4578
- {
4579
- url: new URL(`${https ? 'https' : 'http'}://${req.headers.host}${req.url}`),
4580
- headers: /** @type {import('types/helper').RequestHeaders} */ (req.headers),
4581
- method: req.method,
4582
- rawBody: body
4583
- },
4584
- {
4585
- amp: config.kit.amp,
4586
- dev: true,
4587
- floc: config.kit.floc,
4588
- get_stack: (error) => {
4589
- vite.ssrFixStacktrace(error);
4590
- return error.stack;
4591
- },
4592
- handle_error: (error, request) => {
4593
- vite.ssrFixStacktrace(error);
4594
- hooks.handleError({ error, request });
4595
- },
4596
- hooks,
4597
- hydrate: config.kit.hydrate,
4598
- manifest: get_manifest(),
4599
- paths: {
4600
- base: config.kit.paths.base,
4601
- assets: config.kit.paths.assets ? SVELTE_KIT_ASSETS : config.kit.paths.base
4602
- },
4603
- prefix: '',
4604
- prerender: config.kit.prerender.enabled,
4605
- read: (file) => fs__default.readFileSync(path__default.join(config.kit.files.assets, file)),
4606
- root,
4607
- router: config.kit.router,
4608
- ssr: config.kit.ssr,
4609
- target: config.kit.target,
4610
- template: ({ head, body }) => {
4611
- let rendered = fs__default
4612
- .readFileSync(config.kit.files.template, 'utf8')
4613
- .replace('%svelte.head%', () => head)
4614
- .replace('%svelte.body%', () => body);
4615
-
4616
- if (config.kit.amp && validator) {
4617
- const result = validator.validateString(rendered);
4618
-
4619
- if (result.status !== 'PASS') {
4620
- const lines = rendered.split('\n');
4621
-
4622
- /** @param {string} str */
4623
- const escape = (str) =>
4624
- str.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
4625
-
4626
- rendered = `<!doctype html>
4374
+ const rendered = await respond(
4375
+ {
4376
+ url: new URL(
4377
+ `${vite.config.server.https ? 'https' : 'http'}://${req.headers.host}${req.url}`
4378
+ ),
4379
+ headers: /** @type {import('types/helper').RequestHeaders} */ (req.headers),
4380
+ method: req.method,
4381
+ rawBody: body
4382
+ },
4383
+ {
4384
+ amp: config.kit.amp,
4385
+ dev: true,
4386
+ floc: config.kit.floc,
4387
+ get_stack: (error) => {
4388
+ vite.ssrFixStacktrace(error);
4389
+ return error.stack;
4390
+ },
4391
+ handle_error: (error, request) => {
4392
+ vite.ssrFixStacktrace(error);
4393
+ hooks.handleError({ error, request });
4394
+ },
4395
+ hooks,
4396
+ hydrate: config.kit.hydrate,
4397
+ manifest,
4398
+ paths: {
4399
+ base: config.kit.paths.base,
4400
+ assets: config.kit.paths.assets ? SVELTE_KIT_ASSETS : config.kit.paths.base
4401
+ },
4402
+ prefix: '',
4403
+ prerender: config.kit.prerender.enabled,
4404
+ read: (file) => fs__default.readFileSync(path__default.join(config.kit.files.assets, file)),
4405
+ root,
4406
+ router: config.kit.router,
4407
+ ssr: config.kit.ssr,
4408
+ target: config.kit.target,
4409
+ template: ({ head, body }) => {
4410
+ let rendered = fs__default
4411
+ .readFileSync(config.kit.files.template, 'utf8')
4412
+ .replace('%svelte.head%', () => head)
4413
+ .replace('%svelte.body%', () => body);
4414
+
4415
+ if (amp) {
4416
+ const result = amp.validateString(rendered);
4417
+
4418
+ if (result.status !== 'PASS') {
4419
+ const lines = rendered.split('\n');
4420
+
4421
+ /** @param {string} str */
4422
+ const escape = (str) =>
4423
+ str.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
4424
+
4425
+ rendered = `<!doctype html>
4627
4426
  <head>
4628
4427
  <meta charset="utf-8" />
4629
4428
  <meta name="viewport" content="width=device-width, initial-scale=1" />
@@ -4654,45 +4453,57 @@ async function create_plugin(config, dir, https, get_manifest) {
4654
4453
  )
4655
4454
  .join('\n\n')}
4656
4455
  `;
4657
- }
4658
- }
4456
+ }
4457
+ }
4659
4458
 
4660
- return rendered;
4661
- },
4662
- trailing_slash: config.kit.trailingSlash
4459
+ return rendered;
4460
+ },
4461
+ trailing_slash: config.kit.trailingSlash
4462
+ }
4463
+ );
4464
+
4465
+ if (rendered) {
4466
+ res.writeHead(rendered.status, rendered.headers);
4467
+ if (rendered.body) res.write(rendered.body);
4468
+ res.end();
4469
+ } else {
4470
+ not_found(res);
4471
+ }
4472
+ } catch (e) {
4473
+ const error = coalesce_to_error(e);
4474
+ vite.ssrFixStacktrace(error);
4475
+ res.statusCode = 500;
4476
+ res.end(error.stack);
4663
4477
  }
4664
- );
4665
-
4666
- if (rendered) {
4667
- res.writeHead(rendered.status, rendered.headers);
4668
- if (rendered.body) res.write(rendered.body);
4669
- res.end();
4670
- } else {
4671
- not_found(res);
4672
- }
4673
- } catch (e) {
4674
- const error = coalesce_to_error(e);
4675
- vite.ssrFixStacktrace(error);
4676
- res.statusCode = 500;
4677
- res.end(error.stack);
4678
- }
4679
- };
4680
- }
4681
-
4682
- return {
4683
- name: 'vite-plugin-svelte-kit',
4684
- /**
4685
- * @param {import('vite').ViteDevServer} vite
4686
- */
4687
- configureServer(vite) {
4688
- return () => {
4689
- remove_html_middlewares(vite.middlewares);
4690
- vite.middlewares.use(create_kit_middleware(vite));
4478
+ });
4691
4479
  };
4692
4480
  }
4693
4481
  };
4694
4482
  }
4695
4483
 
4484
+ /** @param {string[]} array */
4485
+ function get_params(array) {
4486
+ // given an array of params like `['x', 'y', 'z']` for
4487
+ // src/routes/[x]/[y]/[z]/svelte, create a function
4488
+ // that turns a RegExpExecArray into ({ x, y, z })
4489
+
4490
+ /** @param {RegExpExecArray} match */
4491
+ const fn = (match) => {
4492
+ /** @type {Record<string, string>} */
4493
+ const params = {};
4494
+ array.forEach((key, i) => {
4495
+ if (key.startsWith('...')) {
4496
+ params[key.slice(3)] = match[i + 1] || '';
4497
+ } else {
4498
+ params[key] = match[i + 1];
4499
+ }
4500
+ });
4501
+ return params;
4502
+ };
4503
+
4504
+ return fn;
4505
+ }
4506
+
4696
4507
  /** @param {import('http').ServerResponse} res */
4697
4508
  function not_found(res) {
4698
4509
  res.statusCode = 404;
@@ -4729,4 +4540,100 @@ function find_deps(node, deps) {
4729
4540
  }
4730
4541
  }
4731
4542
 
4543
+ /** @typedef {{
4544
+ * cwd: string,
4545
+ * port: number,
4546
+ * host?: string,
4547
+ * https: boolean,
4548
+ * config: import('types/config').ValidatedConfig
4549
+ * }} Options */
4550
+ /** @typedef {import('types/internal').SSRComponent} SSRComponent */
4551
+
4552
+ /** @param {Options} opts */
4553
+ async function dev({ cwd, port, host, https, config }) {
4554
+ const output = path__default.resolve(cwd, `${SVELTE_KIT}/dev`);
4555
+
4556
+ rimraf(output);
4557
+ copy_assets(output);
4558
+
4559
+ process.env.VITE_SVELTEKIT_AMP = config.kit.amp ? 'true' : '';
4560
+
4561
+ const [vite_config] = deep_merge(
4562
+ {
4563
+ server: {
4564
+ fs: {
4565
+ allow: [
4566
+ ...new Set([
4567
+ config.kit.files.assets,
4568
+ config.kit.files.lib,
4569
+ config.kit.files.routes,
4570
+ path__default.resolve(cwd, 'src'),
4571
+ path__default.resolve(cwd, SVELTE_KIT),
4572
+ path__default.resolve(cwd, 'node_modules'),
4573
+ path__default.resolve(vite.searchForWorkspaceRoot(cwd), 'node_modules')
4574
+ ])
4575
+ ]
4576
+ },
4577
+ strictPort: true
4578
+ }
4579
+ },
4580
+ config.kit.vite()
4581
+ );
4582
+
4583
+ /** @type {[any, string[]]} */
4584
+ const [merged_config, conflicts] = deep_merge(vite_config, {
4585
+ configFile: false,
4586
+ root: cwd,
4587
+ resolve: {
4588
+ alias: {
4589
+ $app: path__default.resolve(`${output}/runtime/app`),
4590
+ $lib: config.kit.files.lib
4591
+ }
4592
+ },
4593
+ plugins: [
4594
+ svelte({
4595
+ extensions: config.extensions,
4596
+ emitCss: !config.kit.amp,
4597
+ compilerOptions: {
4598
+ hydratable: !!config.kit.hydrate
4599
+ }
4600
+ }),
4601
+ create_plugin(config, output, cwd, config.kit.amp && (await amphtmlValidator.getInstance()))
4602
+ ],
4603
+ publicDir: config.kit.files.assets,
4604
+ base: '/'
4605
+ });
4606
+
4607
+ print_config_conflicts(conflicts, 'kit.vite.');
4608
+
4609
+ // optional config from command-line flags
4610
+ // these should take precedence, but not print conflict warnings
4611
+ if (host) {
4612
+ merged_config.server.host = host;
4613
+ }
4614
+
4615
+ // if https is already enabled then do nothing. it could be an object and we
4616
+ // don't want to overwrite with a boolean
4617
+ if (https && !merged_config.server.https) {
4618
+ merged_config.server.https = https;
4619
+ }
4620
+
4621
+ if (port) {
4622
+ merged_config.server.port = port;
4623
+ }
4624
+
4625
+ const server = await vite.createServer(merged_config);
4626
+ await server.listen(port);
4627
+
4628
+ const address_info = /** @type {import('net').AddressInfo} */ (
4629
+ /** @type {import('http').Server} */ (server.httpServer).address()
4630
+ );
4631
+
4632
+ return {
4633
+ address_info,
4634
+ server_config: vite_config.server,
4635
+ close: () => server.close()
4636
+ };
4637
+ }
4638
+
4732
4639
  export { dev };
@@ -1,6 +1,6 @@
1
1
  import fs__default, { writeFileSync } from 'fs';
2
2
  import path__default from 'path';
3
- import { p as print_config_conflicts, c as copy_assets, b as posixify, a as resolve_entry, r as rimraf, m as mkdirp } from '../cli.js';
3
+ import { p as print_config_conflicts, c as copy_assets, b as posixify, r as resolve_entry, a as rimraf, m as mkdirp } from '../cli.js';
4
4
  import { d as deep_merge, a as create_app, c as create_manifest_data } from './index2.js';
5
5
  import { S as SVELTE_KIT } from './constants.js';
6
6
  import { g as generate_manifest } from './index4.js';
@@ -1,4 +1,4 @@
1
- import { m as mkdirp, r as rimraf, d as copy, $, l as logger } from '../cli.js';
1
+ import { m as mkdirp, a as rimraf, d as copy, $, l as logger } from '../cli.js';
2
2
  import { S as SVELTE_KIT } from './constants.js';
3
3
  import { readFileSync, writeFileSync } from 'fs';
4
4
  import { resolve, join, dirname } from 'path';
@@ -1,7 +1,7 @@
1
1
  import * as fs from 'fs';
2
2
  import * as path from 'path';
3
3
  import { createRequire } from 'module';
4
- import { r as rimraf, w as walk$1, $, m as mkdirp } from '../cli.js';
4
+ import { a as rimraf, w as walk$1, $, m as mkdirp } from '../cli.js';
5
5
  import 'sade';
6
6
  import 'child_process';
7
7
  import 'net';
package/dist/cli.js CHANGED
@@ -887,7 +887,7 @@ async function launch(port, https) {
887
887
  exec(`${cmd} ${https ? 'https' : 'http'}://localhost:${port}`);
888
888
  }
889
889
 
890
- const prog = sade('svelte-kit').version('1.0.0-next.210');
890
+ const prog = sade('svelte-kit').version('1.0.0-next.211');
891
891
 
892
892
  prog
893
893
  .command('dev')
@@ -903,37 +903,24 @@ prog
903
903
  const { dev } = await import('./chunks/index.js');
904
904
 
905
905
  try {
906
- const watcher = await dev({ port, host, https, config });
906
+ const cwd = process.cwd();
907
907
 
908
- watcher.on('stdout', (data) => {
909
- process.stdout.write(data);
910
- });
911
-
912
- watcher.on('stderr', (data) => {
913
- process.stderr.write(data);
908
+ const { address_info, server_config } = await dev({
909
+ cwd,
910
+ port,
911
+ host,
912
+ https,
913
+ config
914
914
  });
915
915
 
916
- if (!watcher.vite || !watcher.vite.httpServer) {
917
- throw Error('Could not find server');
918
- }
919
- // we never start the server on a socket path, so address will be of type AddressInfo
920
- const address_info = /** @type {import('net').AddressInfo} */ (
921
- watcher.vite.httpServer.address()
922
- );
923
-
924
- const vite_config = config.kit.vite();
925
-
926
- https = https || !!vite_config.server?.https;
927
- open = open || !!vite_config.server?.open;
928
-
929
916
  welcome({
930
917
  port: address_info.port,
931
918
  host: address_info.address,
932
- https,
933
- open,
934
- loose: vite_config.server?.fs?.strict === false,
935
- allow: watcher.allowed_directories(),
936
- cwd: watcher.cwd
919
+ https: !!(https || server_config.https),
920
+ open: open || !!server_config.open,
921
+ loose: server_config.fs.strict === false,
922
+ allow: server_config.fs.allow,
923
+ cwd
937
924
  });
938
925
  } catch (error) {
939
926
  handle_error(error);
@@ -1052,7 +1039,7 @@ async function check_port(port) {
1052
1039
  function welcome({ port, host, https, open, loose, allow, cwd }) {
1053
1040
  if (open) launch(port, https);
1054
1041
 
1055
- console.log($.bold().cyan(`\n SvelteKit v${'1.0.0-next.210'}\n`));
1042
+ console.log($.bold().cyan(`\n SvelteKit v${'1.0.0-next.211'}\n`));
1056
1043
 
1057
1044
  const protocol = https ? 'https:' : 'http:';
1058
1045
  const exposed = typeof host !== 'undefined' && host !== 'localhost' && host !== '127.0.0.1';
@@ -1089,4 +1076,4 @@ function welcome({ port, host, https, open, loose, allow, cwd }) {
1089
1076
  console.log('\n');
1090
1077
  }
1091
1078
 
1092
- export { $, resolve_entry as a, posixify as b, copy_assets as c, copy as d, get_mime_lookup as g, logger as l, mkdirp as m, print_config_conflicts as p, rimraf as r, walk as w };
1079
+ export { $, rimraf as a, posixify as b, copy_assets as c, copy as d, get_mime_lookup as g, logger as l, mkdirp as m, print_config_conflicts as p, resolve_entry as r, walk as w };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sveltejs/kit",
3
- "version": "1.0.0-next.210",
3
+ "version": "1.0.0-next.211",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "https://github.com/sveltejs/kit",
@@ -11,7 +11,6 @@
11
11
  "type": "module",
12
12
  "dependencies": {
13
13
  "@sveltejs/vite-plugin-svelte": "^1.0.0-next.32",
14
- "cheap-watch": "^1.0.4",
15
14
  "sade": "^1.7.4",
16
15
  "vite": "^2.7.2"
17
16
  },