@sveltejs/kit 1.0.0-next.20 → 1.0.0-next.200

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.
Files changed (77) hide show
  1. package/README.md +12 -9
  2. package/assets/components/error.svelte +19 -3
  3. package/assets/runtime/app/env.js +20 -0
  4. package/assets/runtime/app/navigation.js +45 -13
  5. package/assets/runtime/app/paths.js +1 -2
  6. package/assets/runtime/app/stores.js +15 -9
  7. package/assets/runtime/chunks/utils.js +13 -0
  8. package/assets/runtime/env.js +8 -0
  9. package/assets/runtime/internal/singletons.js +5 -11
  10. package/assets/runtime/internal/start.js +979 -351
  11. package/assets/runtime/paths.js +13 -0
  12. package/dist/chunks/cert.js +29254 -0
  13. package/dist/chunks/constants.js +8 -0
  14. package/dist/chunks/error.js +21 -0
  15. package/dist/chunks/index.js +4745 -0
  16. package/dist/chunks/index2.js +700 -0
  17. package/dist/chunks/index3.js +1060 -0
  18. package/dist/chunks/index4.js +398 -0
  19. package/dist/chunks/index5.js +413 -0
  20. package/dist/chunks/index6.js +15574 -0
  21. package/dist/{standard.js → chunks/standard.js} +16 -18
  22. package/dist/chunks/url.js +59 -0
  23. package/dist/cli.js +947 -67
  24. package/dist/hooks.js +28 -0
  25. package/dist/install-fetch.js +6070 -0
  26. package/dist/node.js +51 -0
  27. package/dist/ssr.js +1771 -0
  28. package/package.json +89 -54
  29. package/svelte-kit.js +2 -0
  30. package/types/ambient-modules.d.ts +173 -0
  31. package/types/app.d.ts +21 -0
  32. package/types/config.d.ts +96 -0
  33. package/types/endpoint.d.ts +18 -0
  34. package/types/helper.d.ts +41 -0
  35. package/types/hooks.d.ts +36 -0
  36. package/types/index.d.ts +17 -0
  37. package/types/internal.d.ts +219 -0
  38. package/types/page.d.ts +77 -0
  39. package/CHANGELOG.md +0 -276
  40. package/assets/runtime/app/navigation.js.map +0 -1
  41. package/assets/runtime/app/paths.js.map +0 -1
  42. package/assets/runtime/app/stores.js.map +0 -1
  43. package/assets/runtime/internal/singletons.js.map +0 -1
  44. package/assets/runtime/internal/start.js.map +0 -1
  45. package/assets/runtime/utils-85ebcc60.js +0 -18
  46. package/assets/runtime/utils-85ebcc60.js.map +0 -1
  47. package/dist/api.js +0 -44
  48. package/dist/api.js.map +0 -1
  49. package/dist/build.js +0 -246
  50. package/dist/build.js.map +0 -1
  51. package/dist/cli.js.map +0 -1
  52. package/dist/colors.js +0 -37
  53. package/dist/colors.js.map +0 -1
  54. package/dist/create_app.js +0 -578
  55. package/dist/create_app.js.map +0 -1
  56. package/dist/index.js +0 -12042
  57. package/dist/index.js.map +0 -1
  58. package/dist/index2.js +0 -544
  59. package/dist/index2.js.map +0 -1
  60. package/dist/index3.js +0 -71
  61. package/dist/index3.js.map +0 -1
  62. package/dist/index4.js +0 -466
  63. package/dist/index4.js.map +0 -1
  64. package/dist/index5.js +0 -725
  65. package/dist/index5.js.map +0 -1
  66. package/dist/index6.js +0 -713
  67. package/dist/index6.js.map +0 -1
  68. package/dist/logging.js +0 -43
  69. package/dist/logging.js.map +0 -1
  70. package/dist/package.js +0 -432
  71. package/dist/package.js.map +0 -1
  72. package/dist/renderer.js +0 -2391
  73. package/dist/renderer.js.map +0 -1
  74. package/dist/standard.js.map +0 -1
  75. package/dist/utils.js +0 -54
  76. package/dist/utils.js.map +0 -1
  77. package/svelte-kit +0 -3
package/dist/cli.js CHANGED
@@ -1,79 +1,844 @@
1
- 'use strict';
2
-
3
- var sade = require('sade');
4
- var _package = require('./package.js');
5
- require('path');
6
- require('module');
7
- require('url');
8
-
9
- function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
10
-
11
- function _interopNamespace(e) {
12
- if (e && e.__esModule) return e;
13
- var n = Object.create(null);
14
- if (e) {
15
- Object.keys(e).forEach(function (k) {
16
- if (k !== 'default') {
17
- var d = Object.getOwnPropertyDescriptor(e, k);
18
- Object.defineProperty(n, k, d.get ? d : {
19
- enumerable: true,
20
- get: function () {
21
- return e[k];
22
- }
1
+ import fs__default, { existsSync } from 'fs';
2
+ import sade from 'sade';
3
+ import path__default, { relative } from 'path';
4
+ import { exec as exec$1 } from 'child_process';
5
+ import { createConnection, createServer } from 'net';
6
+ import * as url from 'url';
7
+ import { fileURLToPath } from 'url';
8
+ import { networkInterfaces, release } from 'os';
9
+ import { c as coalesce_to_error, h as has_error_code } from './chunks/error.js';
10
+
11
+ let FORCE_COLOR, NODE_DISABLE_COLORS, NO_COLOR, TERM, isTTY=true;
12
+ if (typeof process !== 'undefined') {
13
+ ({ FORCE_COLOR, NODE_DISABLE_COLORS, NO_COLOR, TERM } = process.env);
14
+ isTTY = process.stdout && process.stdout.isTTY;
15
+ }
16
+
17
+ const $ = {
18
+ enabled: !NODE_DISABLE_COLORS && NO_COLOR == null && TERM !== 'dumb' && (
19
+ FORCE_COLOR != null && FORCE_COLOR !== '0' || isTTY
20
+ ),
21
+
22
+ // modifiers
23
+ reset: init(0, 0),
24
+ bold: init(1, 22),
25
+ dim: init(2, 22),
26
+ italic: init(3, 23),
27
+ underline: init(4, 24),
28
+ inverse: init(7, 27),
29
+ hidden: init(8, 28),
30
+ strikethrough: init(9, 29),
31
+
32
+ // colors
33
+ black: init(30, 39),
34
+ red: init(31, 39),
35
+ green: init(32, 39),
36
+ yellow: init(33, 39),
37
+ blue: init(34, 39),
38
+ magenta: init(35, 39),
39
+ cyan: init(36, 39),
40
+ white: init(37, 39),
41
+ gray: init(90, 39),
42
+ grey: init(90, 39),
43
+
44
+ // background colors
45
+ bgBlack: init(40, 49),
46
+ bgRed: init(41, 49),
47
+ bgGreen: init(42, 49),
48
+ bgYellow: init(43, 49),
49
+ bgBlue: init(44, 49),
50
+ bgMagenta: init(45, 49),
51
+ bgCyan: init(46, 49),
52
+ bgWhite: init(47, 49)
53
+ };
54
+
55
+ function run(arr, str) {
56
+ let i=0, tmp, beg='', end='';
57
+ for (; i < arr.length; i++) {
58
+ tmp = arr[i];
59
+ beg += tmp.open;
60
+ end += tmp.close;
61
+ if (!!~str.indexOf(tmp.close)) {
62
+ str = str.replace(tmp.rgx, tmp.close + tmp.open);
63
+ }
64
+ }
65
+ return beg + str + end;
66
+ }
67
+
68
+ function chain(has, keys) {
69
+ let ctx = { has, keys };
70
+
71
+ ctx.reset = $.reset.bind(ctx);
72
+ ctx.bold = $.bold.bind(ctx);
73
+ ctx.dim = $.dim.bind(ctx);
74
+ ctx.italic = $.italic.bind(ctx);
75
+ ctx.underline = $.underline.bind(ctx);
76
+ ctx.inverse = $.inverse.bind(ctx);
77
+ ctx.hidden = $.hidden.bind(ctx);
78
+ ctx.strikethrough = $.strikethrough.bind(ctx);
79
+
80
+ ctx.black = $.black.bind(ctx);
81
+ ctx.red = $.red.bind(ctx);
82
+ ctx.green = $.green.bind(ctx);
83
+ ctx.yellow = $.yellow.bind(ctx);
84
+ ctx.blue = $.blue.bind(ctx);
85
+ ctx.magenta = $.magenta.bind(ctx);
86
+ ctx.cyan = $.cyan.bind(ctx);
87
+ ctx.white = $.white.bind(ctx);
88
+ ctx.gray = $.gray.bind(ctx);
89
+ ctx.grey = $.grey.bind(ctx);
90
+
91
+ ctx.bgBlack = $.bgBlack.bind(ctx);
92
+ ctx.bgRed = $.bgRed.bind(ctx);
93
+ ctx.bgGreen = $.bgGreen.bind(ctx);
94
+ ctx.bgYellow = $.bgYellow.bind(ctx);
95
+ ctx.bgBlue = $.bgBlue.bind(ctx);
96
+ ctx.bgMagenta = $.bgMagenta.bind(ctx);
97
+ ctx.bgCyan = $.bgCyan.bind(ctx);
98
+ ctx.bgWhite = $.bgWhite.bind(ctx);
99
+
100
+ return ctx;
101
+ }
102
+
103
+ function init(open, close) {
104
+ let blk = {
105
+ open: `\x1b[${open}m`,
106
+ close: `\x1b[${close}m`,
107
+ rgx: new RegExp(`\\x1b\\[${close}m`, 'g')
108
+ };
109
+ return function (txt) {
110
+ if (this !== void 0 && this.has !== void 0) {
111
+ !!~this.has.indexOf(open) || (this.has.push(open),this.keys.push(blk));
112
+ return txt === void 0 ? this : $.enabled ? run(this.keys, txt+'') : txt+'';
113
+ }
114
+ return txt === void 0 ? chain([open], [blk]) : $.enabled ? run([blk], txt+'') : txt+'';
115
+ };
116
+ }
117
+
118
+ function exec(cmd) {
119
+ return new Promise((fulfil, reject) => {
120
+ exec$1(cmd, (error, stdout, stderr) => {
121
+ if (error) return reject(error);
122
+ fulfil({ stdout, stderr });
123
+ });
124
+ });
125
+ }
126
+
127
+ async function blame(port) {
128
+ try {
129
+ const { stdout } = await exec(`lsof -i :${port} -sTCP:LISTEN -Fp`);
130
+
131
+ if (!stdout) return null;
132
+ const pid = parseInt(stdout.slice(1), 10);
133
+ if (isNaN(pid)) throw new Error(`Invalid stdout ${stdout}`);
134
+
135
+ return pid;
136
+ } catch (error) {
137
+ return null;
138
+ }
139
+ }
140
+
141
+ let promise;
142
+
143
+ function weird() {
144
+ if (!promise) {
145
+ promise = get_weird(9000);
146
+ }
147
+ return promise;
148
+ }
149
+
150
+ function get_weird(port) {
151
+ return new Promise(fulfil => {
152
+ const server = createServer();
153
+
154
+ server.unref();
155
+
156
+ server.on('error', () => {
157
+ fulfil(get_weird(port + 1));
158
+ });
159
+
160
+ server.listen({ port }, () => {
161
+ const server2 = createServer();
162
+
163
+ server2.unref();
164
+
165
+ server2.on('error', () => {
166
+ server.close(() => {
167
+ fulfil(false);
168
+ });
169
+ });
170
+
171
+ server2.listen({ port }, () => {
172
+ server2.close(() => {
173
+ server.close(() => {
174
+ fulfil(true);
175
+ });
176
+ });
177
+ });
178
+ });
179
+ });
180
+ }
181
+
182
+ function check(port) {
183
+ return weird().then(weird => {
184
+ if (weird) {
185
+ return check_weird(port);
186
+ }
187
+
188
+ return new Promise(fulfil => {
189
+ const server = createServer();
190
+
191
+ server.unref();
192
+
193
+ server.on('error', () => {
194
+ fulfil(false);
195
+ });
196
+
197
+ server.listen({ port }, () => {
198
+ server.close(() => {
199
+ fulfil(true);
23
200
  });
201
+ });
202
+ });
203
+ });
204
+ }
205
+
206
+ function check_weird(port) {
207
+ return new Promise(fulfil => {
208
+ const client = createConnection({ port }, () => {
209
+ client.end();
210
+ fulfil(false);
211
+ })
212
+ .on('error', () => {
213
+ fulfil(true);
214
+ });
215
+ });
216
+ }
217
+
218
+ /** @param {string} dir */
219
+ function mkdirp(dir) {
220
+ try {
221
+ fs__default.mkdirSync(dir, { recursive: true });
222
+ } catch (/** @type {any} */ e) {
223
+ if (e.code === 'EEXIST') return;
224
+ throw e;
225
+ }
226
+ }
227
+
228
+ /** @param {string} path */
229
+ function rimraf(path) {
230
+ (fs__default.rmSync || fs__default.rmdirSync)(path, { recursive: true, force: true });
231
+ }
232
+
233
+ /**
234
+ * @param {string} from
235
+ * @param {string} to
236
+ * @param {(basename: string) => boolean} filter
237
+ */
238
+ function copy(from, to, filter = () => true) {
239
+ if (!fs__default.existsSync(from)) return [];
240
+ if (!filter(path__default.basename(from))) return [];
241
+
242
+ const files = [];
243
+ const stats = fs__default.statSync(from);
244
+
245
+ if (stats.isDirectory()) {
246
+ fs__default.readdirSync(from).forEach((file) => {
247
+ files.push(...copy(path__default.join(from, file), path__default.join(to, file)));
248
+ });
249
+ } else {
250
+ mkdirp(path__default.dirname(to));
251
+ fs__default.copyFileSync(from, to);
252
+ files.push(to);
253
+ }
254
+
255
+ return files;
256
+ }
257
+
258
+ /**
259
+ * Get a list of all files in a directory
260
+ * @param {string} cwd - the directory to walk
261
+ * @param {boolean} [dirs] - whether to include directories in the result
262
+ */
263
+ function walk(cwd, dirs = false) {
264
+ /** @type {string[]} */
265
+ const all_files = [];
266
+
267
+ /** @param {string} dir */
268
+ function walk_dir(dir) {
269
+ const files = fs__default.readdirSync(path__default.join(cwd, dir));
270
+
271
+ for (const file of files) {
272
+ const joined = path__default.join(dir, file);
273
+ const stats = fs__default.statSync(path__default.join(cwd, joined));
274
+ if (stats.isDirectory()) {
275
+ if (dirs) all_files.push(joined);
276
+ walk_dir(joined);
277
+ } else {
278
+ all_files.push(joined);
279
+ }
280
+ }
281
+ }
282
+
283
+ return walk_dir(''), all_files;
284
+ }
285
+
286
+ const __filename = fileURLToPath(import.meta.url);
287
+ const __dirname = path__default.dirname(__filename);
288
+
289
+ /** @param {string} dest */
290
+ function copy_assets(dest) {
291
+ let prefix = '..';
292
+ do {
293
+ // we jump through these hoops so that this function
294
+ // works whether or not it's been bundled
295
+ const resolved = path__default.resolve(__dirname, `${prefix}/assets`);
296
+
297
+ if (fs__default.existsSync(resolved)) {
298
+ copy(resolved, dest);
299
+ return;
300
+ }
301
+
302
+ prefix = `../${prefix}`;
303
+ } while (true); // eslint-disable-line
304
+ }
305
+
306
+ function noop() {}
307
+
308
+ /** @param {{ verbose: boolean }} opts */
309
+ function logger({ verbose }) {
310
+ /** @type {import('types/internal').Logger} */
311
+ const log = (msg) => console.log(msg.replace(/^/gm, ' '));
312
+
313
+ log.success = (msg) => log($.green(`✔ ${msg}`));
314
+ log.error = (msg) => log($.bold().red(msg));
315
+ log.warn = (msg) => log($.bold().yellow(msg));
316
+
317
+ log.minor = verbose ? (msg) => log($.grey(msg)) : noop;
318
+ log.info = verbose ? log : noop;
319
+
320
+ return log;
321
+ }
322
+
323
+ /**
324
+ * Given an entry point like [cwd]/src/hooks, returns a filename like [cwd]/src/hooks.js or [cwd]/src/hooks/index.js
325
+ * @param {string} entry
326
+ * @returns {string|null}
327
+ */
328
+ function resolve_entry(entry) {
329
+ if (fs__default.existsSync(entry)) {
330
+ const stats = fs__default.statSync(entry);
331
+ if (stats.isDirectory()) {
332
+ return resolve_entry(path__default.join(entry, 'index'));
333
+ }
334
+
335
+ return entry;
336
+ } else {
337
+ const dir = path__default.dirname(entry);
338
+
339
+ if (fs__default.existsSync(dir)) {
340
+ const base = path__default.basename(entry);
341
+ const files = fs__default.readdirSync(dir);
342
+
343
+ const found = files.find((file) => file.replace(/\.[^.]+$/, '') === base);
344
+
345
+ if (found) return path__default.join(dir, found);
346
+ }
347
+ }
348
+
349
+ return null;
350
+ }
351
+
352
+ /** @param {string} str */
353
+ function posixify(str) {
354
+ return str.replace(/\\/g, '/');
355
+ }
356
+
357
+ /** @typedef {import('./types').ConfigDefinition} ConfigDefinition */
358
+ /** @typedef {import('./types').Validator} Validator */
359
+
360
+ /** @type {Validator} */
361
+ const options = object(
362
+ {
363
+ extensions: validate(['.svelte'], (input, keypath) => {
364
+ if (!Array.isArray(input) || !input.every((page) => typeof page === 'string')) {
365
+ throw new Error(`${keypath} must be an array of strings`);
366
+ }
367
+
368
+ input.forEach((extension) => {
369
+ if (extension[0] !== '.') {
370
+ throw new Error(`Each member of ${keypath} must start with '.' — saw '${extension}'`);
371
+ }
372
+
373
+ if (!/^(\.[a-z0-9]+)+$/i.test(extension)) {
374
+ throw new Error(`File extensions must be alphanumeric — saw '${extension}'`);
375
+ }
376
+ });
377
+
378
+ return input;
379
+ }),
380
+
381
+ kit: object({
382
+ adapter: validate(null, (input, keypath) => {
383
+ if (typeof input !== 'object' || !input.adapt) {
384
+ let message = `${keypath} should be an object with an "adapt" method`;
385
+
386
+ if (Array.isArray(input) || typeof input === 'string') {
387
+ // for the early adapter adopters
388
+ message += ', rather than the name of an adapter';
389
+ }
390
+
391
+ throw new Error(`${message}. See https://kit.svelte.dev/docs#adapters`);
392
+ }
393
+
394
+ return input;
395
+ }),
396
+
397
+ amp: boolean(false),
398
+
399
+ appDir: validate('_app', (input, keypath) => {
400
+ assert_string(input, keypath);
401
+
402
+ if (input) {
403
+ if (input.startsWith('/') || input.endsWith('/')) {
404
+ throw new Error(
405
+ "config.kit.appDir cannot start or end with '/'. See https://kit.svelte.dev/docs#configuration"
406
+ );
407
+ }
408
+ } else {
409
+ throw new Error(`${keypath} cannot be empty`);
410
+ }
411
+
412
+ return input;
413
+ }),
414
+
415
+ files: object({
416
+ assets: string('static'),
417
+ hooks: string('src/hooks'),
418
+ lib: string('src/lib'),
419
+ routes: string('src/routes'),
420
+ serviceWorker: string('src/service-worker'),
421
+ template: string('src/app.html')
422
+ }),
423
+
424
+ floc: boolean(false),
425
+
426
+ host: string(null),
427
+
428
+ hostHeader: string(null),
429
+
430
+ hydrate: boolean(true),
431
+
432
+ package: object({
433
+ dir: string('package'),
434
+ // excludes all .d.ts and filename starting with _
435
+ exports: fun((filepath) => !/^_|\/_|\.d\.ts$/.test(filepath)),
436
+ files: fun(() => true),
437
+ emitTypes: boolean(true)
438
+ }),
439
+
440
+ paths: object({
441
+ base: validate('', (input, keypath) => {
442
+ assert_string(input, keypath);
443
+
444
+ if (input !== '' && (input.endsWith('/') || !input.startsWith('/'))) {
445
+ throw new Error(
446
+ `${keypath} option must be a root-relative path that starts but doesn't end with '/'. See https://kit.svelte.dev/docs#configuration-paths`
447
+ );
448
+ }
449
+
450
+ return input;
451
+ }),
452
+ assets: validate('', (input, keypath) => {
453
+ assert_string(input, keypath);
454
+
455
+ if (input) {
456
+ if (!/^[a-z]+:\/\//.test(input)) {
457
+ throw new Error(
458
+ `${keypath} option must be an absolute path, if specified. See https://kit.svelte.dev/docs#configuration-paths`
459
+ );
460
+ }
461
+
462
+ if (input.endsWith('/')) {
463
+ throw new Error(
464
+ `${keypath} option must not end with '/'. See https://kit.svelte.dev/docs#configuration-paths`
465
+ );
466
+ }
467
+ }
468
+
469
+ return input;
470
+ })
471
+ }),
472
+
473
+ prerender: object({
474
+ crawl: boolean(true),
475
+ enabled: boolean(true),
476
+ entries: validate(['*'], (input, keypath) => {
477
+ if (!Array.isArray(input) || !input.every((page) => typeof page === 'string')) {
478
+ throw new Error(`${keypath} must be an array of strings`);
479
+ }
480
+
481
+ input.forEach((page) => {
482
+ if (page !== '*' && page[0] !== '/') {
483
+ throw new Error(
484
+ `Each member of ${keypath} must be either '*' or an absolute path beginning with '/' — saw '${page}'`
485
+ );
486
+ }
487
+ });
488
+
489
+ return input;
490
+ }),
491
+ // TODO: remove this for the 1.0 release
492
+ force: validate(undefined, (input, keypath) => {
493
+ if (typeof input !== undefined) {
494
+ const newSetting = input ? 'continue' : 'fail';
495
+ const needsSetting = newSetting === 'continue';
496
+ throw new Error(
497
+ `${keypath} has been removed in favor of \`onError\`. In your case, set \`onError\` to "${newSetting}"${
498
+ needsSetting ? '' : ' (or leave it undefined)'
499
+ } to get the same behavior as you would with \`force: ${JSON.stringify(input)}\``
500
+ );
501
+ }
502
+ }),
503
+ onError: validate('fail', (input, keypath) => {
504
+ if (typeof input === 'function') return input;
505
+ if (['continue', 'fail'].includes(input)) return input;
506
+ throw new Error(
507
+ `${keypath} should be either a custom function or one of "continue" or "fail"`
508
+ );
509
+ }),
510
+ // TODO: remove this for the 1.0 release
511
+ pages: validate(undefined, (input, keypath) => {
512
+ if (typeof input !== undefined) {
513
+ throw new Error(`${keypath} has been renamed to \`entries\`.`);
514
+ }
515
+ })
516
+ }),
517
+
518
+ router: boolean(true),
519
+
520
+ serviceWorker: object({
521
+ files: fun((filename) => !/\.DS_STORE/.test(filename))
522
+ }),
523
+
524
+ ssr: boolean(true),
525
+
526
+ target: string(null),
527
+
528
+ trailingSlash: list(['never', 'always', 'ignore']),
529
+
530
+ vite: validate(
531
+ () => ({}),
532
+ (input, keypath) => {
533
+ if (typeof input === 'object') {
534
+ const config = input;
535
+ input = () => config;
536
+ }
537
+
538
+ if (typeof input !== 'function') {
539
+ throw new Error(
540
+ `${keypath} must be a Vite config object (https://vitejs.dev/config) or a function that returns one`
541
+ );
542
+ }
543
+
544
+ return input;
545
+ }
546
+ )
547
+ })
548
+ },
549
+ true
550
+ );
551
+
552
+ /**
553
+ * @param {Record<string, Validator>} children
554
+ * @param {boolean} [allow_unknown]
555
+ * @returns {Validator}
556
+ */
557
+ function object(children, allow_unknown = false) {
558
+ return (input, keypath) => {
559
+ /** @type {Record<string, any>} */
560
+ const output = {};
561
+
562
+ if ((input && typeof input !== 'object') || Array.isArray(input)) {
563
+ throw new Error(`${keypath} should be an object`);
564
+ }
565
+
566
+ for (const key in input) {
567
+ if (!(key in children)) {
568
+ if (allow_unknown) {
569
+ output[key] = input[key];
570
+ } else {
571
+ let message = `Unexpected option ${keypath}.${key}`;
572
+
573
+ // special case
574
+ if (keypath === 'config.kit' && key in options) {
575
+ message += ` (did you mean config.${key}?)`;
576
+ }
577
+
578
+ throw new Error(message);
579
+ }
580
+ }
581
+ }
582
+
583
+ for (const key in children) {
584
+ const validator = children[key];
585
+ output[key] = validator(input && input[key], `${keypath}.${key}`);
586
+ }
587
+
588
+ return output;
589
+ };
590
+ }
591
+
592
+ /**
593
+ * @param {any} fallback
594
+ * @param {(value: any, keypath: string) => any} fn
595
+ * @returns {Validator}
596
+ */
597
+ function validate(fallback, fn) {
598
+ return (input, keypath) => {
599
+ return input === undefined ? fallback : fn(input, keypath);
600
+ };
601
+ }
602
+
603
+ /**
604
+ * @param {string | null} fallback
605
+ * @param {boolean} allow_empty
606
+ * @returns {Validator}
607
+ */
608
+ function string(fallback, allow_empty = true) {
609
+ return validate(fallback, (input, keypath) => {
610
+ assert_string(input, keypath);
611
+
612
+ if (!allow_empty && input === '') {
613
+ throw new Error(`${keypath} cannot be empty`);
614
+ }
615
+
616
+ return input;
617
+ });
618
+ }
619
+
620
+ /**
621
+ * @param {boolean} fallback
622
+ * @returns {Validator}
623
+ */
624
+ function boolean(fallback) {
625
+ return validate(fallback, (input, keypath) => {
626
+ if (typeof input !== 'boolean') {
627
+ throw new Error(`${keypath} should be true or false, if specified`);
628
+ }
629
+ return input;
630
+ });
631
+ }
632
+
633
+ /**
634
+ * @param {string[]} options
635
+ * @returns {Validator}
636
+ */
637
+ function list(options, fallback = options[0]) {
638
+ return validate(fallback, (input, keypath) => {
639
+ if (!options.includes(input)) {
640
+ // prettier-ignore
641
+ const msg = options.length > 2
642
+ ? `${keypath} should be one of ${options.slice(0, -1).map(input => `"${input}"`).join(', ')} or "${options[options.length - 1]}"`
643
+ : `${keypath} should be either "${options[0]}" or "${options[1]}"`;
644
+
645
+ throw new Error(msg);
646
+ }
647
+ return input;
648
+ });
649
+ }
650
+
651
+ /**
652
+ * @param {(filename: string) => boolean} fallback
653
+ * @returns {Validator}
654
+ */
655
+ function fun(fallback) {
656
+ return validate(fallback, (input, keypath) => {
657
+ if (typeof input !== 'function') {
658
+ throw new Error(`${keypath} should be a function, if specified`);
659
+ }
660
+ return input;
661
+ });
662
+ }
663
+
664
+ /**
665
+ * @param {string} input
666
+ * @param {string} keypath
667
+ */
668
+ function assert_string(input, keypath) {
669
+ if (typeof input !== 'string') {
670
+ throw new Error(`${keypath} should be a string, if specified`);
671
+ }
672
+ }
673
+
674
+ /** @typedef {import('./types').ConfigDefinition} ConfigDefinition */
675
+
676
+ /**
677
+ * @param {string} cwd
678
+ * @param {import('types/config').ValidatedConfig} validated
679
+ */
680
+ function validate_template(cwd, validated) {
681
+ const { template } = validated.kit.files;
682
+ const relative = path__default.relative(cwd, template);
683
+
684
+ if (fs__default.existsSync(template)) {
685
+ const contents = fs__default.readFileSync(template, 'utf8');
686
+ const expected_tags = ['%svelte.head%', '%svelte.body%'];
687
+ expected_tags.forEach((tag) => {
688
+ if (contents.indexOf(tag) === -1) {
689
+ throw new Error(`${relative} is missing ${tag}`);
24
690
  }
25
691
  });
692
+ } else {
693
+ throw new Error(`${relative} does not exist`);
694
+ }
695
+ }
696
+
697
+ async function load_config({ cwd = process.cwd() } = {}) {
698
+ const config_file_esm = path__default.join(cwd, 'svelte.config.js');
699
+ const config_file = fs__default.existsSync(config_file_esm)
700
+ ? config_file_esm
701
+ : path__default.join(cwd, 'svelte.config.cjs');
702
+ const config = await import(url.pathToFileURL(config_file).href);
703
+
704
+ const validated = validate_config(config.default);
705
+
706
+ validated.kit.files.assets = path__default.resolve(cwd, validated.kit.files.assets);
707
+ validated.kit.files.hooks = path__default.resolve(cwd, validated.kit.files.hooks);
708
+ validated.kit.files.lib = path__default.resolve(cwd, validated.kit.files.lib);
709
+ validated.kit.files.routes = path__default.resolve(cwd, validated.kit.files.routes);
710
+ validated.kit.files.serviceWorker = path__default.resolve(cwd, validated.kit.files.serviceWorker);
711
+ validated.kit.files.template = path__default.resolve(cwd, validated.kit.files.template);
712
+
713
+ validate_template(cwd, validated);
714
+
715
+ // TODO check all the `files` exist when the config is loaded?
716
+
717
+ return validated;
718
+ }
719
+
720
+ /**
721
+ * @param {import('types/config').Config} config
722
+ * @returns {import('types/config').ValidatedConfig}
723
+ */
724
+ function validate_config(config) {
725
+ const type = typeof config;
726
+
727
+ if (type === 'undefined') {
728
+ throw new Error(
729
+ 'Your config is missing default exports. Make sure to include "export default config;"'
730
+ );
731
+ }
732
+
733
+ if (type !== 'object') {
734
+ throw new Error(
735
+ `Unexpected config type "${type}", make sure your default export is an object.`
736
+ );
26
737
  }
27
- n['default'] = e;
28
- return Object.freeze(n);
738
+
739
+ return options(config, 'config');
740
+ }
741
+
742
+ /**
743
+ * @param {string[]} conflicts - array of conflicts in dotted notation
744
+ * @param {string=} pathPrefix - prepended in front of the path
745
+ * @param {string=} scope - used to prefix the whole error message
746
+ */
747
+ function print_config_conflicts(conflicts, pathPrefix = '', scope) {
748
+ const prefix = scope ? scope + ': ' : '';
749
+ const log = logger({ verbose: false });
750
+ conflicts.forEach((conflict) => {
751
+ log.error(
752
+ `${prefix}The value for ${pathPrefix}${conflict} specified in svelte.config.js has been ignored. This option is controlled by SvelteKit.`
753
+ );
754
+ });
29
755
  }
30
756
 
31
- var sade__default = /*#__PURE__*/_interopDefaultLegacy(sade);
757
+ async function get_config() {
758
+ // TODO this is temporary, for the benefit of early adopters
759
+ if (existsSync('svelte.config.cjs')) {
760
+ // prettier-ignore
761
+ console.error($.bold().red(
762
+ 'svelte.config.cjs should be renamed to svelte.config.js and converted to an ES module. See https://kit.svelte.dev/docs#configuration for an example'
763
+ ));
764
+ }
765
+
766
+ if (existsSync('vite.config.js')) {
767
+ // prettier-ignore
768
+ console.error($.bold().red(
769
+ 'Please remove vite.config.js and put Vite config in svelte.config.js: https://kit.svelte.dev/docs#configuration-vite'
770
+ ));
771
+ }
32
772
 
33
- function get_config() {
34
773
  try {
35
- return _package.load_config();
36
- } catch (error) {
774
+ return await load_config();
775
+ } catch (err) {
776
+ const error = coalesce_to_error(err);
37
777
  let message = error.message;
38
778
 
39
- if (error.code === 'ENOENT') {
779
+ if (
780
+ has_error_code(error, 'MODULE_NOT_FOUND') &&
781
+ /Cannot find module svelte\.config\./.test(error.message)
782
+ ) {
40
783
  message = 'Missing svelte.config.js';
41
784
  } else if (error.name === 'SyntaxError') {
42
785
  message = 'Malformed svelte.config.js';
43
786
  }
44
787
 
45
- console.error(_package.$.bold().red(message));
46
- console.error(_package.$.grey(error.stack));
788
+ console.error($.bold().red(message));
789
+ if (error.stack) {
790
+ console.error($.grey(error.stack));
791
+ }
47
792
  process.exit(1);
48
793
  }
49
794
  }
50
795
 
796
+ /** @param {unknown} error */
51
797
  function handle_error(error) {
52
- console.log(_package.$.bold().red(`> ${error.message}`));
53
- console.log(_package.$.gray(error.stack));
798
+ const err = coalesce_to_error(error);
799
+ console.log($.bold().red(`> ${err.message}`));
800
+ if (err.stack) {
801
+ console.log($.gray(err.stack));
802
+ }
54
803
  process.exit(1);
55
804
  }
56
805
 
57
- async function launch(port) {
58
- const { exec } = await Promise.resolve().then(function () { return /*#__PURE__*/_interopNamespace(require('child_process')); });
59
- exec(`${process.platform == 'win32' ? 'start' : 'open'} http://localhost:${port}`);
806
+ /**
807
+ * @param {number} port
808
+ * @param {boolean} https
809
+ */
810
+ async function launch(port, https) {
811
+ const { exec } = await import('child_process');
812
+ let cmd = 'open';
813
+ if (process.platform == 'win32') {
814
+ cmd = 'start';
815
+ } else if (process.platform == 'linux') {
816
+ if (/microsoft/i.test(release())) {
817
+ cmd = 'cmd.exe /c start';
818
+ } else {
819
+ cmd = 'xdg-open';
820
+ }
821
+ }
822
+ exec(`${cmd} ${https ? 'https' : 'http'}://localhost:${port}`);
60
823
  }
61
824
 
62
- const prog = sade__default['default']('svelte').version(_package.version);
825
+ const prog = sade('svelte-kit').version('1.0.0-next.200');
63
826
 
64
827
  prog
65
828
  .command('dev')
66
829
  .describe('Start a development server')
67
- .option('-p, --port', 'Port', 3000)
68
- .option('-o, --open', 'Open a browser tab', false)
69
- .action(async ({ port, open }) => {
70
- process.env.NODE_ENV = 'development';
71
- const config = get_config();
830
+ .option('-p, --port', 'Port')
831
+ .option('-h, --host', 'Host (only use this on trusted networks)')
832
+ .option('-H, --https', 'Use self-signed HTTPS certificate')
833
+ .option('-o, --open', 'Open a browser tab')
834
+ .action(async ({ port, host, https, open }) => {
835
+ process.env.NODE_ENV = process.env.NODE_ENV || 'development';
836
+ const config = await get_config();
72
837
 
73
- const { dev } = await Promise.resolve().then(function () { return require('./index.js'); });
838
+ const { dev } = await import('./chunks/index.js');
74
839
 
75
840
  try {
76
- const watcher = await dev({ port, config });
841
+ const watcher = await dev({ port, host, https, config });
77
842
 
78
843
  watcher.on('stdout', (data) => {
79
844
  process.stdout.write(data);
@@ -83,8 +848,28 @@ prog
83
848
  process.stderr.write(data);
84
849
  });
85
850
 
86
- console.log(_package.$.bold().cyan(`> Listening on http://localhost:${watcher.port}`));
87
- if (open) launch(watcher.port);
851
+ if (!watcher.vite || !watcher.vite.httpServer) {
852
+ throw Error('Could not find server');
853
+ }
854
+ // we never start the server on a socket path, so address will be of type AddressInfo
855
+ const address_info = /** @type {import('net').AddressInfo} */ (
856
+ watcher.vite.httpServer.address()
857
+ );
858
+
859
+ const vite_config = config.kit.vite();
860
+
861
+ https = https || !!vite_config.server?.https;
862
+ open = open || !!vite_config.server?.open;
863
+
864
+ welcome({
865
+ port: address_info.port,
866
+ host: address_info.address,
867
+ https,
868
+ open,
869
+ loose: vite_config.server?.fs?.strict === false,
870
+ allow: watcher.allowed_directories(),
871
+ cwd: watcher.cwd
872
+ });
88
873
  } catch (error) {
89
874
  handle_error(error);
90
875
  }
@@ -93,55 +878,150 @@ prog
93
878
  prog
94
879
  .command('build')
95
880
  .describe('Create a production build of your app')
96
- .action(async () => {
97
- process.env.NODE_ENV = 'production';
98
- const config = get_config();
99
-
100
- const { build } = await Promise.resolve().then(function () { return require('./index2.js'); });
881
+ .option('--verbose', 'Log more stuff', false)
882
+ .action(async ({ verbose }) => {
883
+ process.env.NODE_ENV = process.env.NODE_ENV || 'production';
884
+ const config = await get_config();
101
885
 
102
886
  try {
103
- await build(config);
887
+ const { build } = await import('./chunks/index3.js');
888
+ const build_data = await build(config);
889
+
890
+ console.log(
891
+ `\nRun ${$.bold().cyan('npm run preview')} to preview your production build locally.`
892
+ );
893
+
894
+ if (config.kit.adapter) {
895
+ const { adapt } = await import('./chunks/index4.js');
896
+ await adapt(config, build_data, { verbose });
897
+
898
+ // this is necessary to close any open db connections, etc
899
+ process.exit(0);
900
+ }
901
+
902
+ console.log($.bold().yellow('\nNo adapter specified'));
903
+
904
+ // prettier-ignore
905
+ console.log(
906
+ `See ${$.bold().cyan('https://kit.svelte.dev/docs#adapters')} to learn how to configure your app to run on the platform of your choosing`
907
+ );
104
908
  } catch (error) {
105
909
  handle_error(error);
106
910
  }
107
911
  });
108
912
 
109
913
  prog
110
- .command('start')
914
+ .command('preview')
111
915
  .describe('Serve an already-built app')
112
916
  .option('-p, --port', 'Port', 3000)
917
+ .option('-h, --host', 'Host (only use this on trusted networks)', 'localhost')
918
+ .option('-H, --https', 'Use self-signed HTTPS certificate', false)
113
919
  .option('-o, --open', 'Open a browser tab', false)
114
- .action(async ({ port, open }) => {
115
- process.env.NODE_ENV = 'production';
116
- const config = get_config();
920
+ .action(async ({ port, host, https, open }) => {
921
+ await check_port(port);
922
+
923
+ process.env.NODE_ENV = process.env.NODE_ENV || 'production';
924
+ const config = await get_config();
117
925
 
118
- const { start } = await Promise.resolve().then(function () { return require('./index3.js'); });
926
+ const { preview } = await import('./chunks/index5.js');
119
927
 
120
928
  try {
121
- await start({ port, config });
929
+ await preview({ port, host, config, https });
122
930
 
123
- console.log(_package.$.bold().cyan(`> Listening on http://localhost:${port}`));
124
- if (open) if (open) launch(port);
931
+ welcome({ port, host, https, open });
125
932
  } catch (error) {
126
933
  handle_error(error);
127
934
  }
128
935
  });
129
936
 
130
937
  prog
131
- .command('adapt')
132
- .describe('Customise your production build for different platforms')
938
+ .command('package')
939
+ .describe('Create a package')
940
+ .option('-d, --dir', 'Destination directory', 'package')
133
941
  .action(async () => {
134
- process.env.NODE_ENV = 'production';
135
- const config = get_config();
942
+ const config = await get_config();
136
943
 
137
- const { adapt } = await Promise.resolve().then(function () { return require('./index5.js'); });
944
+ const { make_package } = await import('./chunks/index6.js');
138
945
 
139
946
  try {
140
- await adapt(config);
947
+ await make_package(config);
141
948
  } catch (error) {
142
949
  handle_error(error);
143
950
  }
144
951
  });
145
952
 
146
953
  prog.parse(process.argv, { unknown: (arg) => `Unknown option: ${arg}` });
147
- //# sourceMappingURL=cli.js.map
954
+
955
+ /** @param {number} port */
956
+ async function check_port(port) {
957
+ if (await check(port)) {
958
+ return;
959
+ }
960
+ console.log($.bold().red(`Port ${port} is occupied`));
961
+ const n = await blame(port);
962
+ if (n) {
963
+ // prettier-ignore
964
+ console.log(
965
+ `Terminate process ${$.bold(n)} or specify a different port with ${$.bold('--port')}\n`
966
+ );
967
+ } else {
968
+ // prettier-ignore
969
+ console.log(
970
+ `Terminate the process occupying the port or specify a different port with ${$.bold('--port')}\n`
971
+ );
972
+ }
973
+ process.exit(1);
974
+ }
975
+
976
+ /**
977
+ * @param {{
978
+ * open: boolean;
979
+ * host: string;
980
+ * https: boolean;
981
+ * port: number;
982
+ * loose?: boolean;
983
+ * allow?: string[];
984
+ * cwd?: string;
985
+ * }} param0
986
+ */
987
+ function welcome({ port, host, https, open, loose, allow, cwd }) {
988
+ if (open) launch(port, https);
989
+
990
+ console.log($.bold().cyan(`\n SvelteKit v${'1.0.0-next.200'}\n`));
991
+
992
+ const protocol = https ? 'https:' : 'http:';
993
+ const exposed = typeof host !== 'undefined' && host !== 'localhost' && host !== '127.0.0.1';
994
+
995
+ Object.values(networkInterfaces()).forEach((interfaces) => {
996
+ if (!interfaces) return;
997
+ interfaces.forEach((details) => {
998
+ if (details.family !== 'IPv4') return;
999
+
1000
+ // prettier-ignore
1001
+ if (details.internal) {
1002
+ console.log(` ${$.gray('local: ')} ${protocol}//${$.bold(`localhost:${port}`)}`);
1003
+ } else {
1004
+ if (details.mac === '00:00:00:00:00:00') return;
1005
+
1006
+ if (exposed) {
1007
+ console.log(` ${$.gray('network:')} ${protocol}//${$.bold(`${details.address}:${port}`)}`);
1008
+ if (loose) {
1009
+ console.log(`\n ${$.yellow('Serving with vite.server.fs.strict: false. Note that all files on your machine will be accessible to anyone on your network.')}`);
1010
+ } else if (allow?.length && cwd) {
1011
+ console.log(`\n ${$.yellow('Note that all files in the following directories will be accessible to anyone on your network: ' + allow.map(a => relative(cwd, a)).join(', '))}`);
1012
+ }
1013
+ } else {
1014
+ console.log(` ${$.gray('network: not exposed')}`);
1015
+ }
1016
+ }
1017
+ });
1018
+ });
1019
+
1020
+ if (!exposed) {
1021
+ console.log('\n Use --host to expose server to other devices on this network');
1022
+ }
1023
+
1024
+ console.log('\n');
1025
+ }
1026
+
1027
+ export { $, resolve_entry as a, posixify as b, copy_assets as c, copy as d, logger as l, mkdirp as m, print_config_conflicts as p, rimraf as r, walk as w };