@sveltejs/kit 1.0.0-next.206 → 1.0.0-next.208

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,490 +1,109 @@
1
- import { m as mkdirp, r as rimraf, d as copy, $, l as logger } from '../cli.js';
2
- import { S as SVELTE_KIT } from './constants.js';
3
- import { readFileSync, writeFileSync } from 'fs';
4
- import { resolve, join, dirname } from 'path';
5
- import { pathToFileURL, URL } from 'url';
6
- import { __fetch_polyfill } from '../install-fetch.js';
7
- import { g as get_single_valued_header, r as resolve$1, i as is_root_relative } from './url.js';
8
- import 'sade';
9
- import 'child_process';
10
- import 'net';
11
- import 'os';
12
- import './error.js';
13
- import 'node:http';
14
- import 'node:https';
15
- import 'node:zlib';
16
- import 'node:stream';
17
- import 'node:util';
18
- import 'node:url';
19
-
20
- /** @typedef {{
21
- * fn: () => Promise<any>,
22
- * fulfil: (value: any) => void,
23
- * reject: (error: Error) => void
24
- * }} Task */
25
-
26
- /** @param {number} concurrency */
27
- function queue(concurrency) {
28
- /** @type {Task[]} */
29
- const tasks = [];
30
-
31
- let current = 0;
32
-
33
- /** @type {(value?: any) => void} */
34
- let fulfil;
35
-
36
- /** @type {(error: Error) => void} */
37
- let reject;
38
-
39
- let closed = false;
40
-
41
- const done = new Promise((f, r) => {
42
- fulfil = f;
43
- reject = r;
44
- });
45
-
46
- done.catch(() => {
47
- // this is necessary in case a catch handler is never added
48
- // to the done promise by the user
49
- });
50
-
51
- function dequeue() {
52
- if (current < concurrency) {
53
- const task = tasks.shift();
54
-
55
- if (task) {
56
- current += 1;
57
- const promise = Promise.resolve(task.fn());
58
-
59
- promise
60
- .then(task.fulfil, (err) => {
61
- task.reject(err);
62
- reject(err);
63
- })
64
- .then(() => {
65
- current -= 1;
66
- dequeue();
67
- });
68
- } else if (current === 0) {
69
- closed = true;
70
- fulfil();
71
- }
72
- }
73
- }
74
-
75
- return {
76
- /** @param {() => any} fn */
77
- add: (fn) => {
78
- if (closed) throw new Error('Cannot add tasks to a queue that has ended');
79
-
80
- const promise = new Promise((fulfil, reject) => {
81
- tasks.push({ fn, fulfil, reject });
82
- });
83
-
84
- dequeue();
85
- return promise;
86
- },
87
-
88
- done: () => {
89
- if (current === 0) {
90
- closed = true;
91
- fulfil();
92
- }
93
-
94
- return done;
95
- }
96
- };
97
- }
1
+ import { s } from './misc.js';
2
+ import { g as get_mime_lookup } from '../cli.js';
98
3
 
99
4
  /**
100
- * @typedef {import('types/config').PrerenderErrorHandler} PrerenderErrorHandler
101
- * @typedef {import('types/config').PrerenderOnErrorValue} OnError
102
- * @typedef {import('types/internal').Logger} Logger
5
+ * @param {import('../../../types/internal').BuildData} build_data;
6
+ * @param {string} relative_path;
7
+ * @param {import('../../../types/internal').RouteData[]} routes;
8
+ * @param {'esm' | 'cjs'} format
103
9
  */
104
-
105
- /** @param {string} html */
106
- function clean_html(html) {
107
- return html
108
- .replace(/<!\[CDATA\[[\s\S]*?\]\]>/gm, '')
109
- .replace(/(<script[\s\S]*?>)[\s\S]*?<\/script>/gm, '$1</' + 'script>')
110
- .replace(/(<style[\s\S]*?>)[\s\S]*?<\/style>/gm, '$1</' + 'style>')
111
- .replace(/<!--[\s\S]*?-->/gm, '');
112
- }
113
-
114
- /** @param {string} attrs */
115
- function get_href(attrs) {
116
- const match = /(?:[\s'"]|^)href\s*=\s*(?:"(.*?)"|'(.*?)'|([^\s>]*))/.exec(attrs);
117
- return match && (match[1] || match[2] || match[3]);
118
- }
119
-
120
- /** @param {string} attrs */
121
- function get_src(attrs) {
122
- const match = /(?:[\s'"]|^)src\s*=\s*(?:"(.*?)"|'(.*?)'|([^\s>]*))/.exec(attrs);
123
- return match && (match[1] || match[2] || match[3]);
124
- }
125
-
126
- /** @param {string} attrs */
127
- function is_rel_external(attrs) {
128
- const match = /rel\s*=\s*(?:["'][^>]*(external)[^>]*["']|(external))/.exec(attrs);
129
- return !!match;
130
- }
131
-
132
- /** @param {string} attrs */
133
- function get_srcset_urls(attrs) {
134
- const results = [];
135
- // Note that the srcset allows any ASCII whitespace, including newlines.
136
- const match = /([\s'"]|^)srcset\s*=\s*(?:"(.*?)"|'(.*?)'|([^\s>]*))/s.exec(attrs);
137
- if (match) {
138
- const attr_content = match[1] || match[2] || match[3];
139
- // Parse the content of the srcset attribute.
140
- // The regexp is modelled after the srcset specs (https://html.spec.whatwg.org/multipage/images.html#srcset-attribute)
141
- // and should cover most reasonable cases.
142
- const regex = /\s*([^\s,]\S+[^\s,])\s*((?:\d+w)|(?:-?\d+(?:\.\d+)?(?:[eE]-?\d+)?x))?/gm;
143
- let sub_matches;
144
- while ((sub_matches = regex.exec(attr_content))) {
145
- results.push(sub_matches[1]);
146
- }
147
- }
148
- return results;
149
- }
150
-
151
- /** @type {(errorDetails: Parameters<PrerenderErrorHandler>[0] ) => string} */
152
- function errorDetailsToString({ status, path, referrer, referenceType }) {
153
- return `${status} ${path}${referrer ? ` (${referenceType} from ${referrer})` : ''}`;
154
- }
155
-
156
- /** @type {(log: Logger, onError: OnError) => PrerenderErrorHandler} */
157
- function chooseErrorHandler(log, onError) {
158
- switch (onError) {
159
- case 'continue':
160
- return (errorDetails) => {
161
- log.error(errorDetailsToString(errorDetails));
162
- };
163
- case 'fail':
164
- return (errorDetails) => {
165
- throw new Error(errorDetailsToString(errorDetails));
166
- };
167
- default:
168
- return onError;
169
- }
170
- }
171
-
172
- const OK = 2;
173
- const REDIRECT = 3;
174
-
175
- /**
176
- * @param {{
177
- * cwd: string;
178
- * out: string;
179
- * log: Logger;
180
- * config: import('types/config').ValidatedConfig;
181
- * build_data: import('types/internal').BuildData;
182
- * fallback?: string;
183
- * all: boolean; // disregard `export const prerender = true`
184
- * }} opts
185
- * @returns {Promise<Array<string>>} returns a promise that resolves to an array of paths corresponding to the files that have been prerendered.
186
- */
187
- async function prerender({ cwd, out, log, config, build_data, fallback, all }) {
188
- if (!config.kit.prerender.enabled && !fallback) {
189
- return [];
190
- }
191
-
192
- __fetch_polyfill();
193
-
194
- const dir = resolve(cwd, `${SVELTE_KIT}/output`);
195
-
196
- const seen = new Set();
197
-
198
- const server_root = resolve(dir);
199
-
200
- /** @type {import('types/internal').App} */
201
- const app = await import(pathToFileURL(`${server_root}/server/app.js`).href);
202
-
203
- app.init({
204
- paths: config.kit.paths,
205
- prerendering: true,
206
- read: (file) => readFileSync(join(config.kit.files.assets, file))
10
+ function generate_manifest(
11
+ build_data,
12
+ relative_path,
13
+ routes = build_data.manifest_data.routes,
14
+ format = 'esm'
15
+ ) {
16
+ const bundled_nodes = new Map();
17
+
18
+ // 0 and 1 are special, they correspond to the root layout and root error nodes
19
+ bundled_nodes.set(build_data.manifest_data.components[0], {
20
+ path: `${relative_path}/nodes/0.js`,
21
+ index: 0
207
22
  });
208
23
 
209
- const error = chooseErrorHandler(log, config.kit.prerender.onError);
210
-
211
- const files = new Set([...build_data.static, ...build_data.client]);
212
- const written_files = [];
213
-
214
- build_data.static.forEach((file) => {
215
- if (file.endsWith('/index.html')) {
216
- files.add(file.slice(0, -11));
217
- }
24
+ bundled_nodes.set(build_data.manifest_data.components[1], {
25
+ path: `${relative_path}/nodes/1.js`,
26
+ index: 1
218
27
  });
219
28
 
220
- /**
221
- * @param {string} path
222
- */
223
- function normalize(path) {
224
- if (config.kit.trailingSlash === 'always') {
225
- return path.endsWith('/') ? path : `${path}/`;
226
- } else if (config.kit.trailingSlash === 'never') {
227
- return !path.endsWith('/') || path === '/' ? path : path.slice(0, -1);
228
- }
229
-
230
- return path;
231
- }
232
-
233
- const q = queue(config.kit.prerender.concurrency);
234
-
235
- /**
236
- * @param {string} decoded_path
237
- * @param {string?} referrer
238
- */
239
- function enqueue(decoded_path, referrer) {
240
- const path = encodeURI(normalize(decoded_path));
241
-
242
- if (seen.has(path)) return;
243
- seen.add(path);
244
-
245
- return q.add(() => visit(path, decoded_path, referrer));
246
- }
247
-
248
- /**
249
- * @param {string} path
250
- * @param {string} decoded_path
251
- * @param {string?} referrer
252
- */
253
- async function visit(path, decoded_path, referrer) {
254
- /** @type {Map<string, import('types/hooks').ServerResponse>} */
255
- const dependencies = new Map();
29
+ routes.forEach((route) => {
30
+ if (route.type === 'page') {
31
+ [...route.a, ...route.b].forEach((component) => {
32
+ if (component && !bundled_nodes.has(component)) {
33
+ const i = build_data.manifest_data.components.indexOf(component);
256
34
 
257
- const rendered = await app.render(
258
- {
259
- host: config.kit.host,
260
- method: 'GET',
261
- headers: {},
262
- path,
263
- rawBody: null,
264
- query: new URLSearchParams()
265
- },
266
- {
267
- prerender: {
268
- all,
269
- dependencies
270
- }
271
- }
272
- );
273
-
274
- if (rendered) {
275
- const response_type = Math.floor(rendered.status / 100);
276
- const headers = rendered.headers;
277
- const type = headers && headers['content-type'];
278
- const is_html = response_type === REDIRECT || type === 'text/html';
279
-
280
- const parts = decoded_path.split('/');
281
- if (is_html && parts[parts.length - 1] !== 'index.html') {
282
- parts.push('index.html');
283
- }
284
-
285
- const file = `${out}${parts.join('/')}`;
286
- mkdirp(dirname(file));
287
-
288
- if (response_type === REDIRECT) {
289
- const location = get_single_valued_header(headers, 'location');
290
-
291
- if (location) {
292
- log.warn(`${rendered.status} ${decoded_path} -> ${location}`);
293
- writeFileSync(file, `<meta http-equiv="refresh" content="0;url=${encodeURI(location)}">`);
294
- written_files.push(file);
295
-
296
- const resolved = resolve$1(path, location);
297
- if (is_root_relative(resolved)) {
298
- enqueue(resolved, path);
299
- }
300
- } else {
301
- log.warn(`location header missing on redirect received from ${decoded_path}`);
302
- }
303
-
304
- return;
305
- }
306
-
307
- if (rendered.status === 200) {
308
- log.info(`${rendered.status} ${decoded_path}`);
309
- writeFileSync(file, rendered.body || '');
310
- written_files.push(file);
311
- } else if (response_type !== OK) {
312
- error({ status: rendered.status, path, referrer, referenceType: 'linked' });
313
- }
314
-
315
- dependencies.forEach((result, dependency_path) => {
316
- const response_type = Math.floor(result.status / 100);
317
-
318
- const is_html = result.headers['content-type'] === 'text/html';
319
-
320
- const parts = dependency_path.split('/');
321
- if (is_html && parts[parts.length - 1] !== 'index.html') {
322
- parts.push('index.html');
323
- }
324
-
325
- const file = `${out}${parts.join('/')}`;
326
- mkdirp(dirname(file));
327
-
328
- if (result.body) {
329
- writeFileSync(file, result.body);
330
- written_files.push(file);
331
- }
332
-
333
- if (response_type === OK) {
334
- log.info(`${result.status} ${dependency_path}`);
335
- } else {
336
- error({
337
- status: result.status,
338
- path: dependency_path,
339
- referrer: path,
340
- referenceType: 'fetched'
35
+ bundled_nodes.set(component, {
36
+ path: `${relative_path}/nodes/${i}.js`,
37
+ index: bundled_nodes.size
341
38
  });
342
39
  }
343
40
  });
41
+ }
42
+ });
344
43
 
345
- if (is_html && config.kit.prerender.crawl) {
346
- const cleaned = clean_html(/** @type {string} */ (rendered.body));
347
-
348
- let match;
349
- const pattern = /<(a|img|link|source)\s+([\s\S]+?)>/gm;
350
-
351
- const hrefs = [];
352
-
353
- while ((match = pattern.exec(cleaned))) {
354
- const element = match[1];
355
- const attrs = match[2];
356
-
357
- if (element === 'a' || element === 'link') {
358
- if (is_rel_external(attrs)) continue;
359
-
360
- hrefs.push(get_href(attrs));
44
+ /** @type {(path: string) => string} */
45
+ const importer =
46
+ format === 'esm'
47
+ ? (path) => `() => import('${path}')`
48
+ : (path) => `() => Promise.resolve().then(() => require('${path}'))`;
49
+
50
+ // prettier-ignore
51
+ return `{
52
+ appDir: ${s(build_data.app_dir)},
53
+ assets: new Set(${s(build_data.manifest_data.assets.map(asset => asset.file))}),
54
+ _: {
55
+ mime: ${s(get_mime_lookup(build_data.manifest_data))},
56
+ entry: ${s(build_data.client.entry)},
57
+ nodes: [
58
+ ${Array.from(bundled_nodes.values()).map(node => importer(node.path)).join(',\n\t\t\t\t')}
59
+ ],
60
+ routes: [
61
+ ${routes.map(route => {
62
+ if (route.type === 'page') {
63
+ return `{
64
+ type: 'page',
65
+ pattern: ${route.pattern},
66
+ params: ${get_params(route.params)},
67
+ path: ${route.path ? s(route.path) : null},
68
+ a: ${s(route.a.map(component => component && bundled_nodes.get(component).index))},
69
+ b: ${s(route.b.map(component => component && bundled_nodes.get(component).index))}
70
+ }`.replace(/^\t\t/gm, '');
361
71
  } else {
362
- if (element === 'img') {
363
- hrefs.push(get_src(attrs));
72
+ if (!build_data.server.vite_manifest[route.file]) {
73
+ // this is necessary in cases where a .css file snuck in —
74
+ // perhaps it would be better to disallow these (and others?)
75
+ return null;
364
76
  }
365
- hrefs.push(...get_srcset_urls(attrs));
366
- }
367
- }
368
-
369
- for (const href of hrefs) {
370
- if (!href) continue;
371
-
372
- const resolved = resolve$1(path, href);
373
- if (!is_root_relative(resolved)) continue;
374
77
 
375
- const parsed = new URL(resolved, 'http://localhost');
376
- const pathname = decodeURI(parsed.pathname).replace(config.kit.paths.base, '');
377
-
378
- const file = pathname.slice(1);
379
- if (files.has(file)) continue;
380
-
381
- if (parsed.search) ;
382
-
383
- enqueue(pathname, path);
384
- }
385
- }
386
- }
387
- }
388
-
389
- if (config.kit.prerender.enabled) {
390
- for (const entry of config.kit.prerender.entries) {
391
- if (entry === '*') {
392
- for (const entry of build_data.entries) {
393
- enqueue(entry, null);
394
- }
395
- } else {
396
- enqueue(entry, null);
397
- }
398
- }
399
-
400
- await q.done();
401
- }
402
-
403
- if (fallback) {
404
- const rendered = await app.render(
405
- {
406
- host: config.kit.host,
407
- method: 'GET',
408
- headers: {},
409
- path: '[fallback]', // this doesn't matter, but it's easiest if it's a string
410
- rawBody: null,
411
- query: new URLSearchParams()
412
- },
413
- {
414
- prerender: {
415
- fallback,
416
- all: false,
417
- dependencies: new Map()
418
- }
419
- }
420
- );
421
-
422
- const file = join(out, fallback);
423
- mkdirp(dirname(file));
424
- writeFileSync(file, rendered.body || '');
425
- written_files.push(file);
426
- }
427
-
428
- return written_files;
429
- }
430
-
431
- /**
432
- * @param {{
433
- * cwd: string;
434
- * config: import('types/config').ValidatedConfig;
435
- * build_data: import('types/internal').BuildData;
436
- * log: import('types/internal').Logger;
437
- * }} opts
438
- * @returns {import('types/config').AdapterUtils}
439
- */
440
- function get_utils({ cwd, config, build_data, log }) {
441
- return {
442
- log,
443
- rimraf,
444
- mkdirp,
445
- copy,
446
-
447
- copy_client_files(dest) {
448
- return copy(`${cwd}/${SVELTE_KIT}/output/client`, dest, (file) => file[0] !== '.');
449
- },
450
-
451
- copy_server_files(dest) {
452
- return copy(`${cwd}/${SVELTE_KIT}/output/server`, dest, (file) => file[0] !== '.');
453
- },
454
-
455
- copy_static_files(dest) {
456
- return copy(config.kit.files.assets, dest);
457
- },
458
-
459
- async prerender({ all = false, dest, fallback }) {
460
- await prerender({
461
- out: dest,
462
- all,
463
- cwd,
464
- config,
465
- build_data,
466
- fallback,
467
- log
468
- });
78
+ return `{
79
+ type: 'endpoint',
80
+ pattern: ${route.pattern},
81
+ params: ${get_params(route.params)},
82
+ load: ${importer(`${relative_path}/${build_data.server.vite_manifest[route.file].file}`)}
83
+ }`.replace(/^\t\t/gm, '');
84
+ }
85
+ }).filter(Boolean).join(',\n\t\t\t\t')}
86
+ ]
469
87
  }
470
- };
88
+ }`.replace(/^\t/gm, '');
471
89
  }
472
90
 
473
- /**
474
- * @param {import('types/config').ValidatedConfig} config
475
- * @param {import('types/internal').BuildData} build_data
476
- * @param {{ cwd?: string, verbose: boolean }} opts
477
- */
478
- async function adapt(config, build_data, { cwd = process.cwd(), verbose }) {
479
- const { name, adapt } = config.kit.adapter;
480
-
481
- console.log($.bold().cyan(`\n> Using ${name}`));
482
-
483
- const log = logger({ verbose });
484
- const utils = get_utils({ cwd, config, build_data, log });
485
- await adapt({ utils, config });
486
-
487
- log.success('done');
91
+ /** @param {string[]} array */
92
+ function get_params(array) {
93
+ // given an array of params like `['x', 'y', 'z']` for
94
+ // src/routes/[x]/[y]/[z]/svelte, create a function
95
+ // that turns a RexExpMatchArray into ({ x, y, z })
96
+ return array.length
97
+ ? '(m) => ({ ' +
98
+ array
99
+ .map((param, i) => {
100
+ return param.startsWith('...')
101
+ ? `${param.slice(3)}: m[${i + 1}] || ''`
102
+ : `${param}: m[${i + 1}]`;
103
+ })
104
+ .join(', ') +
105
+ '})'
106
+ : 'null';
488
107
  }
489
108
 
490
- export { adapt };
109
+ export { generate_manifest as g };