@sveltejs/kit 1.0.0-next.37 → 1.0.0-next.372
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.
- package/README.md +12 -9
- package/assets/app/env.js +28 -0
- package/assets/app/navigation.js +24 -0
- package/assets/app/paths.js +1 -0
- package/assets/app/stores.js +97 -0
- package/assets/client/singletons.js +13 -0
- package/assets/client/start.js +1796 -0
- package/assets/components/error.svelte +18 -2
- package/assets/env.js +8 -0
- package/assets/paths.js +13 -0
- package/assets/server/index.js +3526 -0
- package/dist/chunks/_commonjsHelpers.js +3 -0
- package/dist/chunks/error.js +664 -0
- package/dist/chunks/index.js +15744 -0
- package/dist/chunks/index2.js +210 -0
- package/dist/chunks/multipart-parser.js +445 -0
- package/dist/chunks/sync.js +992 -0
- package/dist/chunks/write_tsconfig.js +274 -0
- package/dist/cli.js +66 -127
- package/dist/hooks.js +28 -0
- package/dist/node/polyfills.js +12237 -0
- package/dist/node.js +5869 -0
- package/dist/vite.js +3167 -0
- package/package.json +99 -55
- package/types/ambient.d.ts +345 -0
- package/types/index.d.ts +295 -0
- package/types/internal.d.ts +318 -0
- package/types/private.d.ts +235 -0
- package/CHANGELOG.md +0 -385
- package/assets/runtime/app/navigation.js +0 -23
- package/assets/runtime/app/navigation.js.map +0 -1
- package/assets/runtime/app/paths.js +0 -2
- package/assets/runtime/app/paths.js.map +0 -1
- package/assets/runtime/app/stores.js +0 -78
- package/assets/runtime/app/stores.js.map +0 -1
- package/assets/runtime/internal/singletons.js +0 -15
- package/assets/runtime/internal/singletons.js.map +0 -1
- package/assets/runtime/internal/start.js +0 -614
- package/assets/runtime/internal/start.js.map +0 -1
- package/assets/runtime/utils-85ebcc60.js +0 -18
- package/assets/runtime/utils-85ebcc60.js.map +0 -1
- package/dist/api.js +0 -28
- package/dist/api.js.map +0 -1
- package/dist/cli.js.map +0 -1
- package/dist/create_app.js +0 -502
- package/dist/create_app.js.map +0 -1
- package/dist/index.js +0 -327
- package/dist/index.js.map +0 -1
- package/dist/index2.js +0 -3497
- package/dist/index2.js.map +0 -1
- package/dist/index3.js +0 -295
- package/dist/index3.js.map +0 -1
- package/dist/index4.js +0 -311
- package/dist/index4.js.map +0 -1
- package/dist/index5.js +0 -221
- package/dist/index5.js.map +0 -1
- package/dist/index6.js +0 -732
- package/dist/index6.js.map +0 -1
- package/dist/renderer.js +0 -2429
- package/dist/renderer.js.map +0 -1
- package/dist/standard.js +0 -100
- package/dist/standard.js.map +0 -1
- package/dist/utils.js +0 -61
- package/dist/utils.js.map +0 -1
package/dist/vite.js
ADDED
|
@@ -0,0 +1,3167 @@
|
|
|
1
|
+
import * as fs from 'fs';
|
|
2
|
+
import fs__default, { readFileSync, writeFileSync, readdirSync, statSync } from 'fs';
|
|
3
|
+
import path__default, { join, dirname, resolve as resolve$1, normalize } from 'path';
|
|
4
|
+
import { a as load_template, $, c as coalesce_to_error, l as load_config } from './chunks/error.js';
|
|
5
|
+
import { svelte } from '@sveltejs/vite-plugin-svelte';
|
|
6
|
+
import * as vite from 'vite';
|
|
7
|
+
import { loadConfigFromFile, searchForWorkspaceRoot } from 'vite';
|
|
8
|
+
import { p as posixify, m as mkdirp, r as rimraf } from './chunks/write_tsconfig.js';
|
|
9
|
+
import { g as get_runtime_path, s, i as init, u as update, a as get_mime_lookup, p as parse_route_id, b as all, l as logger } from './chunks/sync.js';
|
|
10
|
+
import { pathToFileURL, URL as URL$1 } from 'url';
|
|
11
|
+
import { installPolyfills } from './node/polyfills.js';
|
|
12
|
+
import * as qs from 'querystring';
|
|
13
|
+
import { getRequest, setResponse } from './node.js';
|
|
14
|
+
import 'assert';
|
|
15
|
+
import 'net';
|
|
16
|
+
import 'http';
|
|
17
|
+
import 'stream';
|
|
18
|
+
import 'buffer';
|
|
19
|
+
import 'util';
|
|
20
|
+
import 'stream/web';
|
|
21
|
+
import 'perf_hooks';
|
|
22
|
+
import 'util/types';
|
|
23
|
+
import 'events';
|
|
24
|
+
import 'tls';
|
|
25
|
+
import './chunks/_commonjsHelpers.js';
|
|
26
|
+
import 'async_hooks';
|
|
27
|
+
import 'console';
|
|
28
|
+
import 'zlib';
|
|
29
|
+
import 'crypto';
|
|
30
|
+
import 'node:http';
|
|
31
|
+
import 'node:https';
|
|
32
|
+
import 'node:zlib';
|
|
33
|
+
import 'node:stream';
|
|
34
|
+
import 'node:buffer';
|
|
35
|
+
import 'node:util';
|
|
36
|
+
import 'node:url';
|
|
37
|
+
import 'node:net';
|
|
38
|
+
import 'node:fs';
|
|
39
|
+
import 'node:path';
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* @param {import('vite').ConfigEnv} config_env
|
|
43
|
+
* @return {Promise<import('vite').UserConfig>}
|
|
44
|
+
*/
|
|
45
|
+
async function get_vite_config(config_env) {
|
|
46
|
+
const config = (await loadConfigFromFile(config_env))?.config;
|
|
47
|
+
if (!config) {
|
|
48
|
+
throw new Error('Could not load Vite config');
|
|
49
|
+
}
|
|
50
|
+
return config;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* @param {...import('vite').UserConfig} configs
|
|
55
|
+
* @returns {import('vite').UserConfig}
|
|
56
|
+
*/
|
|
57
|
+
function merge_vite_configs(...configs) {
|
|
58
|
+
return deep_merge(
|
|
59
|
+
...configs.map((config) => ({
|
|
60
|
+
...config,
|
|
61
|
+
resolve: {
|
|
62
|
+
...config.resolve,
|
|
63
|
+
alias: normalize_alias(config.resolve?.alias || {})
|
|
64
|
+
}
|
|
65
|
+
}))
|
|
66
|
+
);
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* Takes zero or more objects and returns a new object that has all the values
|
|
71
|
+
* deeply merged together. None of the original objects will be mutated at any
|
|
72
|
+
* level, and the returned object will have no references to the original
|
|
73
|
+
* objects at any depth. If there's a conflict the last one wins, except for
|
|
74
|
+
* arrays which will be combined.
|
|
75
|
+
* @param {...Object} objects
|
|
76
|
+
* @returns {Record<string, any>} the merged object
|
|
77
|
+
*/
|
|
78
|
+
function deep_merge(...objects) {
|
|
79
|
+
const result = {};
|
|
80
|
+
/** @type {string[]} */
|
|
81
|
+
objects.forEach((o) => merge_into(result, o));
|
|
82
|
+
return result;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* normalize kit.vite.resolve.alias as an array
|
|
87
|
+
* @param {import('vite').AliasOptions} o
|
|
88
|
+
* @returns {import('vite').Alias[]}
|
|
89
|
+
*/
|
|
90
|
+
function normalize_alias(o) {
|
|
91
|
+
if (Array.isArray(o)) return o;
|
|
92
|
+
return Object.entries(o).map(([find, replacement]) => ({ find, replacement }));
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/**
|
|
96
|
+
* Merges b into a, recursively, mutating a.
|
|
97
|
+
* @param {Record<string, any>} a
|
|
98
|
+
* @param {Record<string, any>} b
|
|
99
|
+
*/
|
|
100
|
+
function merge_into(a, b) {
|
|
101
|
+
/**
|
|
102
|
+
* Checks for "plain old Javascript object", typically made as an object
|
|
103
|
+
* literal. Excludes Arrays and built-in types like Buffer.
|
|
104
|
+
* @param {any} x
|
|
105
|
+
*/
|
|
106
|
+
const is_plain_object = (x) => typeof x === 'object' && x.constructor === Object;
|
|
107
|
+
|
|
108
|
+
for (const prop in b) {
|
|
109
|
+
if (is_plain_object(b[prop])) {
|
|
110
|
+
if (!is_plain_object(a[prop])) {
|
|
111
|
+
a[prop] = {};
|
|
112
|
+
}
|
|
113
|
+
merge_into(a[prop], b[prop]);
|
|
114
|
+
} else if (Array.isArray(b[prop])) {
|
|
115
|
+
if (!Array.isArray(a[prop])) {
|
|
116
|
+
a[prop] = [];
|
|
117
|
+
}
|
|
118
|
+
a[prop].push(...b[prop]);
|
|
119
|
+
} else {
|
|
120
|
+
a[prop] = b[prop];
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/** @param {import('types').ValidatedKitConfig} config */
|
|
126
|
+
function get_aliases(config) {
|
|
127
|
+
/** @type {Record<string, string>} */
|
|
128
|
+
const alias = {
|
|
129
|
+
__GENERATED__: path__default.posix.join(config.outDir, 'generated'),
|
|
130
|
+
$app: `${get_runtime_path(config)}/app`,
|
|
131
|
+
|
|
132
|
+
// For now, we handle `$lib` specially here rather than make it a default value for
|
|
133
|
+
// `config.kit.alias` since it has special meaning for packaging, etc.
|
|
134
|
+
$lib: config.files.lib
|
|
135
|
+
};
|
|
136
|
+
|
|
137
|
+
for (const [key, value] of Object.entries(config.alias)) {
|
|
138
|
+
alias[key] = path__default.resolve(value);
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
return alias;
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/**
|
|
145
|
+
* Given an entry point like [cwd]/src/hooks, returns a filename like [cwd]/src/hooks.js or [cwd]/src/hooks/index.js
|
|
146
|
+
* @param {string} entry
|
|
147
|
+
* @returns {string|null}
|
|
148
|
+
*/
|
|
149
|
+
function resolve_entry(entry) {
|
|
150
|
+
if (fs__default.existsSync(entry)) {
|
|
151
|
+
const stats = fs__default.statSync(entry);
|
|
152
|
+
if (stats.isDirectory()) {
|
|
153
|
+
return resolve_entry(path__default.join(entry, 'index'));
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
return entry;
|
|
157
|
+
} else {
|
|
158
|
+
const dir = path__default.dirname(entry);
|
|
159
|
+
|
|
160
|
+
if (fs__default.existsSync(dir)) {
|
|
161
|
+
const base = path__default.basename(entry);
|
|
162
|
+
const files = fs__default.readdirSync(dir);
|
|
163
|
+
|
|
164
|
+
const found = files.find((file) => file.replace(/\.[^.]+$/, '') === base);
|
|
165
|
+
|
|
166
|
+
if (found) return path__default.join(dir, found);
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
return null;
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
/**
|
|
174
|
+
* @typedef {import('rollup').RollupOutput} RollupOutput
|
|
175
|
+
* @typedef {import('rollup').OutputChunk} OutputChunk
|
|
176
|
+
* @typedef {import('rollup').OutputAsset} OutputAsset
|
|
177
|
+
*/
|
|
178
|
+
|
|
179
|
+
/**
|
|
180
|
+
* Invokes Vite.
|
|
181
|
+
* @param {import('vite').UserConfig} config
|
|
182
|
+
*/
|
|
183
|
+
async function create_build(config) {
|
|
184
|
+
const { output } = /** @type {RollupOutput} */ (
|
|
185
|
+
await vite.build({ ...config, configFile: false })
|
|
186
|
+
);
|
|
187
|
+
|
|
188
|
+
const chunks = output.filter(
|
|
189
|
+
/** @returns {output is OutputChunk} */ (output) => output.type === 'chunk'
|
|
190
|
+
);
|
|
191
|
+
|
|
192
|
+
const assets = output.filter(
|
|
193
|
+
/** @returns {output is OutputAsset} */ (output) => output.type === 'asset'
|
|
194
|
+
);
|
|
195
|
+
|
|
196
|
+
return { chunks, assets };
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
/**
|
|
200
|
+
* Adds transitive JS and CSS dependencies to the js and css inputs.
|
|
201
|
+
* @param {import('vite').Manifest} manifest
|
|
202
|
+
* @param {string} entry
|
|
203
|
+
* @param {boolean} add_dynamic_css
|
|
204
|
+
*/
|
|
205
|
+
function find_deps$1(manifest, entry, add_dynamic_css) {
|
|
206
|
+
/** @type {Set<string>} */
|
|
207
|
+
const imports = new Set();
|
|
208
|
+
|
|
209
|
+
/** @type {Set<string>} */
|
|
210
|
+
const stylesheets = new Set();
|
|
211
|
+
|
|
212
|
+
/**
|
|
213
|
+
* @param {string} file
|
|
214
|
+
* @param {boolean} add_js
|
|
215
|
+
*/
|
|
216
|
+
function traverse(file, add_js) {
|
|
217
|
+
const chunk = manifest[file];
|
|
218
|
+
|
|
219
|
+
if (imports.has(chunk.file)) return;
|
|
220
|
+
if (add_js) imports.add(chunk.file);
|
|
221
|
+
|
|
222
|
+
if (chunk.css) {
|
|
223
|
+
chunk.css.forEach((file) => stylesheets.add(file));
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
if (chunk.imports) {
|
|
227
|
+
chunk.imports.forEach((file) => traverse(file, add_js));
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
if (add_dynamic_css && chunk.dynamicImports) {
|
|
231
|
+
chunk.dynamicImports.forEach((file) => traverse(file, false));
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
traverse(entry, true);
|
|
236
|
+
|
|
237
|
+
return {
|
|
238
|
+
file: manifest[entry].file,
|
|
239
|
+
imports: Array.from(imports),
|
|
240
|
+
stylesheets: Array.from(stylesheets)
|
|
241
|
+
};
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
/**
|
|
245
|
+
* The Vite configuration that we use by default.
|
|
246
|
+
* @param {{
|
|
247
|
+
* config: import('types').ValidatedConfig;
|
|
248
|
+
* input: Record<string, string>;
|
|
249
|
+
* ssr: boolean;
|
|
250
|
+
* outDir: string;
|
|
251
|
+
* }} options
|
|
252
|
+
* @return {import('vite').UserConfig}
|
|
253
|
+
*/
|
|
254
|
+
const get_default_config = function ({ config, input, ssr, outDir }) {
|
|
255
|
+
return {
|
|
256
|
+
base: assets_base(config.kit),
|
|
257
|
+
build: {
|
|
258
|
+
cssCodeSplit: true,
|
|
259
|
+
manifest: true,
|
|
260
|
+
outDir,
|
|
261
|
+
polyfillDynamicImport: false,
|
|
262
|
+
rollupOptions: {
|
|
263
|
+
input,
|
|
264
|
+
output: {
|
|
265
|
+
format: 'esm',
|
|
266
|
+
entryFileNames: ssr ? '[name].js' : 'immutable/[name]-[hash].js',
|
|
267
|
+
chunkFileNames: 'immutable/chunks/[name]-[hash].js',
|
|
268
|
+
assetFileNames: 'immutable/assets/[name]-[hash][extname]'
|
|
269
|
+
},
|
|
270
|
+
preserveEntrySignatures: 'strict'
|
|
271
|
+
},
|
|
272
|
+
ssr,
|
|
273
|
+
target: ssr ? 'node14.8' : undefined
|
|
274
|
+
},
|
|
275
|
+
// prevent Vite copying the contents of `config.kit.files.assets`,
|
|
276
|
+
// if it happens to be 'public' instead of 'static'
|
|
277
|
+
publicDir: false,
|
|
278
|
+
resolve: {
|
|
279
|
+
alias: get_aliases(config.kit)
|
|
280
|
+
},
|
|
281
|
+
// @ts-expect-error
|
|
282
|
+
ssr: {
|
|
283
|
+
// when developing against the Kit src code, we want to ensure that
|
|
284
|
+
// our dependencies are bundled so that apps don't need to install
|
|
285
|
+
// them as peerDependencies
|
|
286
|
+
noExternal: []
|
|
287
|
+
|
|
288
|
+
}
|
|
289
|
+
};
|
|
290
|
+
};
|
|
291
|
+
|
|
292
|
+
/**
|
|
293
|
+
* @param {import('types').ValidatedKitConfig} config
|
|
294
|
+
* @returns {string}
|
|
295
|
+
*/
|
|
296
|
+
function assets_base(config) {
|
|
297
|
+
// TODO this is so that Vite's preloading works. Unfortunately, it fails
|
|
298
|
+
// during `svelte-kit preview`, because we use a local asset path. This
|
|
299
|
+
// may be fixed in Vite 3: https://github.com/vitejs/vite/issues/2009
|
|
300
|
+
const { base, assets } = config.paths;
|
|
301
|
+
return `${assets || base}/${config.appDir}/`;
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
/**
|
|
305
|
+
* @param {import('vite').UserConfig} config
|
|
306
|
+
*/
|
|
307
|
+
function remove_svelte_kit(config) {
|
|
308
|
+
// TODO i feel like there's a more elegant way to do this
|
|
309
|
+
// @ts-expect-error - it can't handle infinite type expansion
|
|
310
|
+
config.plugins = (config.plugins || [])
|
|
311
|
+
.flat(Infinity)
|
|
312
|
+
.filter((plugin) => plugin.name !== 'vite-plugin-svelte-kit');
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
/**
|
|
316
|
+
* @param {{
|
|
317
|
+
* hooks: string;
|
|
318
|
+
* config: import('types').ValidatedConfig;
|
|
319
|
+
* has_service_worker: boolean;
|
|
320
|
+
* runtime: string;
|
|
321
|
+
* template: string;
|
|
322
|
+
* }} opts
|
|
323
|
+
*/
|
|
324
|
+
const server_template = ({ config, hooks, has_service_worker, runtime, template }) => `
|
|
325
|
+
import root from '__GENERATED__/root.svelte';
|
|
326
|
+
import { respond } from '${runtime}/server/index.js';
|
|
327
|
+
import { set_paths, assets, base } from '${runtime}/paths.js';
|
|
328
|
+
import { set_prerendering } from '${runtime}/env.js';
|
|
329
|
+
|
|
330
|
+
const template = ({ head, body, assets, nonce }) => ${s(template)
|
|
331
|
+
.replace('%sveltekit.head%', '" + head + "')
|
|
332
|
+
.replace('%sveltekit.body%', '" + body + "')
|
|
333
|
+
.replace(/%sveltekit\.assets%/g, '" + assets + "')
|
|
334
|
+
.replace(/%sveltekit\.nonce%/g, '" + nonce + "')};
|
|
335
|
+
|
|
336
|
+
let read = null;
|
|
337
|
+
|
|
338
|
+
set_paths(${s(config.kit.paths)});
|
|
339
|
+
|
|
340
|
+
let default_protocol = 'https';
|
|
341
|
+
|
|
342
|
+
// allow paths to be globally overridden
|
|
343
|
+
// in svelte-kit preview and in prerendering
|
|
344
|
+
export function override(settings) {
|
|
345
|
+
default_protocol = settings.protocol || default_protocol;
|
|
346
|
+
set_paths(settings.paths);
|
|
347
|
+
set_prerendering(settings.prerendering);
|
|
348
|
+
read = settings.read;
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
export class Server {
|
|
352
|
+
constructor(manifest) {
|
|
353
|
+
this.options = {
|
|
354
|
+
csp: ${s(config.kit.csp)},
|
|
355
|
+
dev: false,
|
|
356
|
+
get_stack: error => String(error), // for security
|
|
357
|
+
handle_error: (error, event) => {
|
|
358
|
+
this.options.hooks.handleError({
|
|
359
|
+
error,
|
|
360
|
+
event,
|
|
361
|
+
|
|
362
|
+
// TODO remove for 1.0
|
|
363
|
+
// @ts-expect-error
|
|
364
|
+
get request() {
|
|
365
|
+
throw new Error('request in handleError has been replaced with event. See https://github.com/sveltejs/kit/pull/3384 for details');
|
|
366
|
+
}
|
|
367
|
+
});
|
|
368
|
+
error.stack = this.options.get_stack(error);
|
|
369
|
+
},
|
|
370
|
+
hooks: null,
|
|
371
|
+
hydrate: ${s(config.kit.browser.hydrate)},
|
|
372
|
+
manifest,
|
|
373
|
+
method_override: ${s(config.kit.methodOverride)},
|
|
374
|
+
paths: { base, assets },
|
|
375
|
+
prefix: assets + '/${config.kit.appDir}/',
|
|
376
|
+
prerender: {
|
|
377
|
+
default: ${config.kit.prerender.default},
|
|
378
|
+
enabled: ${config.kit.prerender.enabled}
|
|
379
|
+
},
|
|
380
|
+
read,
|
|
381
|
+
root,
|
|
382
|
+
service_worker: ${has_service_worker ? "base + '/service-worker.js'" : 'null'},
|
|
383
|
+
router: ${s(config.kit.browser.router)},
|
|
384
|
+
template,
|
|
385
|
+
template_contains_nonce: ${template.includes('%sveltekit.nonce%')},
|
|
386
|
+
trailing_slash: ${s(config.kit.trailingSlash)}
|
|
387
|
+
};
|
|
388
|
+
}
|
|
389
|
+
|
|
390
|
+
async respond(request, options = {}) {
|
|
391
|
+
if (!(request instanceof Request)) {
|
|
392
|
+
throw new Error('The first argument to server.respond must be a Request object. See https://github.com/sveltejs/kit/pull/3384 for details');
|
|
393
|
+
}
|
|
394
|
+
|
|
395
|
+
if (!this.options.hooks) {
|
|
396
|
+
const module = await import(${s(hooks)});
|
|
397
|
+
this.options.hooks = {
|
|
398
|
+
getSession: module.getSession || (() => ({})),
|
|
399
|
+
handle: module.handle || (({ event, resolve }) => resolve(event)),
|
|
400
|
+
handleError: module.handleError || (({ error }) => console.error(error.stack)),
|
|
401
|
+
externalFetch: module.externalFetch || fetch
|
|
402
|
+
};
|
|
403
|
+
}
|
|
404
|
+
|
|
405
|
+
return respond(request, this.options, options);
|
|
406
|
+
}
|
|
407
|
+
}
|
|
408
|
+
`;
|
|
409
|
+
|
|
410
|
+
/**
|
|
411
|
+
* @param {{
|
|
412
|
+
* cwd: string;
|
|
413
|
+
* config: import('types').ValidatedConfig
|
|
414
|
+
* vite_config_env: import('vite').ConfigEnv
|
|
415
|
+
* manifest_data: import('types').ManifestData
|
|
416
|
+
* build_dir: string;
|
|
417
|
+
* output_dir: string;
|
|
418
|
+
* service_worker_entry_file: string | null;
|
|
419
|
+
* }} options
|
|
420
|
+
* @param {{ vite_manifest: import('vite').Manifest, assets: import('rollup').OutputAsset[] }} client
|
|
421
|
+
*/
|
|
422
|
+
async function build_server(options, client) {
|
|
423
|
+
const {
|
|
424
|
+
cwd,
|
|
425
|
+
config,
|
|
426
|
+
vite_config_env,
|
|
427
|
+
manifest_data,
|
|
428
|
+
build_dir,
|
|
429
|
+
output_dir,
|
|
430
|
+
service_worker_entry_file
|
|
431
|
+
} = options;
|
|
432
|
+
|
|
433
|
+
let hooks_file = resolve_entry(config.kit.files.hooks);
|
|
434
|
+
if (!hooks_file || !fs__default.existsSync(hooks_file)) {
|
|
435
|
+
hooks_file = path__default.join(config.kit.outDir, 'build/hooks.js');
|
|
436
|
+
fs__default.writeFileSync(hooks_file, '');
|
|
437
|
+
}
|
|
438
|
+
|
|
439
|
+
/** @type {Record<string, string>} */
|
|
440
|
+
const input = {
|
|
441
|
+
index: `${build_dir}/index.js`
|
|
442
|
+
};
|
|
443
|
+
|
|
444
|
+
// add entry points for every endpoint...
|
|
445
|
+
manifest_data.routes.forEach((route) => {
|
|
446
|
+
const file = route.type === 'endpoint' ? route.file : route.shadow;
|
|
447
|
+
|
|
448
|
+
if (file) {
|
|
449
|
+
const resolved = path__default.resolve(cwd, file);
|
|
450
|
+
const relative = decodeURIComponent(path__default.relative(config.kit.files.routes, resolved));
|
|
451
|
+
const name = posixify(path__default.join('entries/endpoints', relative.replace(/\.js$/, '')));
|
|
452
|
+
input[name] = resolved;
|
|
453
|
+
}
|
|
454
|
+
});
|
|
455
|
+
|
|
456
|
+
// ...and every component used by pages...
|
|
457
|
+
manifest_data.components.forEach((file) => {
|
|
458
|
+
const resolved = path__default.resolve(cwd, file);
|
|
459
|
+
const relative = decodeURIComponent(path__default.relative(config.kit.files.routes, resolved));
|
|
460
|
+
|
|
461
|
+
const name = relative.startsWith('..')
|
|
462
|
+
? posixify(path__default.join('entries/fallbacks', path__default.basename(file)))
|
|
463
|
+
: posixify(path__default.join('entries/pages', relative));
|
|
464
|
+
input[name] = resolved;
|
|
465
|
+
});
|
|
466
|
+
|
|
467
|
+
// ...and every matcher
|
|
468
|
+
Object.entries(manifest_data.matchers).forEach(([key, file]) => {
|
|
469
|
+
const name = posixify(path__default.join('entries/matchers', key));
|
|
470
|
+
input[name] = path__default.resolve(cwd, file);
|
|
471
|
+
});
|
|
472
|
+
|
|
473
|
+
/** @type {(file: string) => string} */
|
|
474
|
+
const app_relative = (file) => {
|
|
475
|
+
const relative_file = path__default.relative(build_dir, path__default.resolve(cwd, file));
|
|
476
|
+
return relative_file[0] === '.' ? relative_file : `./${relative_file}`;
|
|
477
|
+
};
|
|
478
|
+
|
|
479
|
+
fs__default.writeFileSync(
|
|
480
|
+
input.index,
|
|
481
|
+
server_template({
|
|
482
|
+
config,
|
|
483
|
+
hooks: app_relative(hooks_file),
|
|
484
|
+
has_service_worker: config.kit.serviceWorker.register && !!service_worker_entry_file,
|
|
485
|
+
runtime: get_runtime_path(config.kit),
|
|
486
|
+
template: load_template(cwd, config)
|
|
487
|
+
})
|
|
488
|
+
);
|
|
489
|
+
|
|
490
|
+
const vite_config = await get_vite_config(vite_config_env);
|
|
491
|
+
|
|
492
|
+
const merged_config = merge_vite_configs(
|
|
493
|
+
get_default_config({ config, input, ssr: true, outDir: `${output_dir}/server` }),
|
|
494
|
+
vite_config
|
|
495
|
+
);
|
|
496
|
+
|
|
497
|
+
remove_svelte_kit(merged_config);
|
|
498
|
+
|
|
499
|
+
process.env.VITE_SVELTEKIT_ADAPTER_NAME = config.kit.adapter?.name;
|
|
500
|
+
|
|
501
|
+
const { chunks } = await create_build(merged_config);
|
|
502
|
+
|
|
503
|
+
/** @type {import('vite').Manifest} */
|
|
504
|
+
const vite_manifest = JSON.parse(fs__default.readFileSync(`${output_dir}/server/manifest.json`, 'utf-8'));
|
|
505
|
+
|
|
506
|
+
mkdirp(`${output_dir}/server/nodes`);
|
|
507
|
+
mkdirp(`${output_dir}/server/stylesheets`);
|
|
508
|
+
|
|
509
|
+
const stylesheet_lookup = new Map();
|
|
510
|
+
|
|
511
|
+
client.assets.forEach((asset) => {
|
|
512
|
+
if (asset.fileName.endsWith('.css')) {
|
|
513
|
+
if (asset.source.length < config.kit.inlineStyleThreshold) {
|
|
514
|
+
const index = stylesheet_lookup.size;
|
|
515
|
+
const file = `${output_dir}/server/stylesheets/${index}.js`;
|
|
516
|
+
|
|
517
|
+
fs__default.writeFileSync(file, `// ${asset.fileName}\nexport default ${s(asset.source)};`);
|
|
518
|
+
stylesheet_lookup.set(asset.fileName, index);
|
|
519
|
+
}
|
|
520
|
+
}
|
|
521
|
+
});
|
|
522
|
+
|
|
523
|
+
manifest_data.components.forEach((component, i) => {
|
|
524
|
+
const entry = find_deps$1(client.vite_manifest, component, true);
|
|
525
|
+
|
|
526
|
+
const imports = [`import * as module from '../${vite_manifest[component].file}';`];
|
|
527
|
+
|
|
528
|
+
const exports = [
|
|
529
|
+
'export { module };',
|
|
530
|
+
`export const index = ${i};`,
|
|
531
|
+
`export const file = '${entry.file}';`,
|
|
532
|
+
`export const imports = ${s(entry.imports)};`,
|
|
533
|
+
`export const stylesheets = ${s(entry.stylesheets)};`
|
|
534
|
+
];
|
|
535
|
+
|
|
536
|
+
/** @type {string[]} */
|
|
537
|
+
const styles = [];
|
|
538
|
+
|
|
539
|
+
entry.stylesheets.forEach((file) => {
|
|
540
|
+
if (stylesheet_lookup.has(file)) {
|
|
541
|
+
const index = stylesheet_lookup.get(file);
|
|
542
|
+
const name = `stylesheet_${index}`;
|
|
543
|
+
imports.push(`import ${name} from '../stylesheets/${index}.js';`);
|
|
544
|
+
styles.push(`\t${s(file)}: ${name}`);
|
|
545
|
+
}
|
|
546
|
+
});
|
|
547
|
+
|
|
548
|
+
if (styles.length > 0) {
|
|
549
|
+
exports.push(`export const inline_styles = () => ({\n${styles.join(',\n')}\n});`);
|
|
550
|
+
}
|
|
551
|
+
|
|
552
|
+
const out = `${output_dir}/server/nodes/${i}.js`;
|
|
553
|
+
fs__default.writeFileSync(out, `${imports.join('\n')}\n\n${exports.join('\n')}\n`);
|
|
554
|
+
});
|
|
555
|
+
|
|
556
|
+
return {
|
|
557
|
+
chunks,
|
|
558
|
+
vite_manifest,
|
|
559
|
+
methods: get_methods(cwd, chunks, manifest_data)
|
|
560
|
+
};
|
|
561
|
+
}
|
|
562
|
+
|
|
563
|
+
/** @type {Record<string, string>} */
|
|
564
|
+
const method_names = {
|
|
565
|
+
get: 'get',
|
|
566
|
+
head: 'head',
|
|
567
|
+
post: 'post',
|
|
568
|
+
put: 'put',
|
|
569
|
+
del: 'delete',
|
|
570
|
+
patch: 'patch'
|
|
571
|
+
};
|
|
572
|
+
|
|
573
|
+
/**
|
|
574
|
+
* @param {string} cwd
|
|
575
|
+
* @param {import('rollup').OutputChunk[]} output
|
|
576
|
+
* @param {import('types').ManifestData} manifest_data
|
|
577
|
+
*/
|
|
578
|
+
function get_methods(cwd, output, manifest_data) {
|
|
579
|
+
/** @type {Record<string, string[]>} */
|
|
580
|
+
const lookup = {};
|
|
581
|
+
output.forEach((chunk) => {
|
|
582
|
+
if (!chunk.facadeModuleId) return;
|
|
583
|
+
const id = chunk.facadeModuleId.slice(cwd.length + 1);
|
|
584
|
+
lookup[id] = chunk.exports;
|
|
585
|
+
});
|
|
586
|
+
|
|
587
|
+
/** @type {Record<string, import('types').HttpMethod[]>} */
|
|
588
|
+
const methods = {};
|
|
589
|
+
manifest_data.routes.forEach((route) => {
|
|
590
|
+
const file = route.type === 'endpoint' ? route.file : route.shadow;
|
|
591
|
+
|
|
592
|
+
if (file && lookup[file]) {
|
|
593
|
+
methods[file] = lookup[file]
|
|
594
|
+
.map((x) => /** @type {import('types').HttpMethod} */ (method_names[x]))
|
|
595
|
+
.filter(Boolean);
|
|
596
|
+
}
|
|
597
|
+
});
|
|
598
|
+
|
|
599
|
+
return methods;
|
|
600
|
+
}
|
|
601
|
+
|
|
602
|
+
const absolute = /^([a-z]+:)?\/?\//;
|
|
603
|
+
const scheme = /^[a-z]+:/;
|
|
604
|
+
|
|
605
|
+
/**
|
|
606
|
+
* @param {string} base
|
|
607
|
+
* @param {string} path
|
|
608
|
+
*/
|
|
609
|
+
function resolve(base, path) {
|
|
610
|
+
if (scheme.test(path)) return path;
|
|
611
|
+
|
|
612
|
+
const base_match = absolute.exec(base);
|
|
613
|
+
const path_match = absolute.exec(path);
|
|
614
|
+
|
|
615
|
+
if (!base_match) {
|
|
616
|
+
throw new Error(`bad base path: "${base}"`);
|
|
617
|
+
}
|
|
618
|
+
|
|
619
|
+
const baseparts = path_match ? [] : base.slice(base_match[0].length).split('/');
|
|
620
|
+
const pathparts = path_match ? path.slice(path_match[0].length).split('/') : path.split('/');
|
|
621
|
+
|
|
622
|
+
baseparts.pop();
|
|
623
|
+
|
|
624
|
+
for (let i = 0; i < pathparts.length; i += 1) {
|
|
625
|
+
const part = pathparts[i];
|
|
626
|
+
if (part === '.') continue;
|
|
627
|
+
else if (part === '..') baseparts.pop();
|
|
628
|
+
else baseparts.push(part);
|
|
629
|
+
}
|
|
630
|
+
|
|
631
|
+
const prefix = (path_match && path_match[0]) || (base_match && base_match[0]) || '';
|
|
632
|
+
|
|
633
|
+
return `${prefix}${baseparts.join('/')}`;
|
|
634
|
+
}
|
|
635
|
+
|
|
636
|
+
/** @param {string} path */
|
|
637
|
+
function is_root_relative(path) {
|
|
638
|
+
return path[0] === '/' && path[1] !== '/';
|
|
639
|
+
}
|
|
640
|
+
|
|
641
|
+
/**
|
|
642
|
+
* @param {string} path
|
|
643
|
+
* @param {import('types').TrailingSlash} trailing_slash
|
|
644
|
+
*/
|
|
645
|
+
function normalize_path(path, trailing_slash) {
|
|
646
|
+
if (path === '/' || trailing_slash === 'ignore') return path;
|
|
647
|
+
|
|
648
|
+
if (trailing_slash === 'never') {
|
|
649
|
+
return path.endsWith('/') ? path.slice(0, -1) : path;
|
|
650
|
+
} else if (trailing_slash === 'always' && !path.endsWith('/')) {
|
|
651
|
+
return path + '/';
|
|
652
|
+
}
|
|
653
|
+
|
|
654
|
+
return path;
|
|
655
|
+
}
|
|
656
|
+
|
|
657
|
+
/**
|
|
658
|
+
* @param {{
|
|
659
|
+
* config: import('types').ValidatedConfig;
|
|
660
|
+
* vite_config_env: import('vite').ConfigEnv;
|
|
661
|
+
* manifest_data: import('types').ManifestData;
|
|
662
|
+
* output_dir: string;
|
|
663
|
+
* service_worker_entry_file: string | null;
|
|
664
|
+
* }} options
|
|
665
|
+
* @param {import('types').Prerendered} prerendered
|
|
666
|
+
* @param {import('vite').Manifest} client_manifest
|
|
667
|
+
*/
|
|
668
|
+
async function build_service_worker(
|
|
669
|
+
{ config, vite_config_env, manifest_data, output_dir, service_worker_entry_file },
|
|
670
|
+
prerendered,
|
|
671
|
+
client_manifest
|
|
672
|
+
) {
|
|
673
|
+
const build = new Set();
|
|
674
|
+
for (const key in client_manifest) {
|
|
675
|
+
const { file, css = [], assets = [] } = client_manifest[key];
|
|
676
|
+
build.add(file);
|
|
677
|
+
css.forEach((file) => build.add(file));
|
|
678
|
+
assets.forEach((file) => build.add(file));
|
|
679
|
+
}
|
|
680
|
+
|
|
681
|
+
const service_worker = `${config.kit.outDir}/generated/service-worker.js`;
|
|
682
|
+
|
|
683
|
+
fs__default.writeFileSync(
|
|
684
|
+
service_worker,
|
|
685
|
+
`
|
|
686
|
+
// TODO remove for 1.0
|
|
687
|
+
export const timestamp = {
|
|
688
|
+
toString: () => {
|
|
689
|
+
throw new Error('\`timestamp\` has been removed from $service-worker. Use \`version\` instead');
|
|
690
|
+
}
|
|
691
|
+
};
|
|
692
|
+
|
|
693
|
+
export const build = [
|
|
694
|
+
${Array.from(build)
|
|
695
|
+
.map((file) => `${s(`${config.kit.paths.base}/${config.kit.appDir}/${file}`)}`)
|
|
696
|
+
.join(',\n\t\t\t\t')}
|
|
697
|
+
];
|
|
698
|
+
|
|
699
|
+
export const files = [
|
|
700
|
+
${manifest_data.assets
|
|
701
|
+
.filter((asset) => config.kit.serviceWorker.files(asset.file))
|
|
702
|
+
.map((asset) => `${s(`${config.kit.paths.base}/${asset.file}`)}`)
|
|
703
|
+
.join(',\n\t\t\t\t')}
|
|
704
|
+
];
|
|
705
|
+
|
|
706
|
+
export const prerendered = [
|
|
707
|
+
${prerendered.paths
|
|
708
|
+
.map((path) => s(normalize_path(path, config.kit.trailingSlash)))
|
|
709
|
+
.join(',\n\t\t\t\t')}
|
|
710
|
+
];
|
|
711
|
+
|
|
712
|
+
export const version = ${s(config.kit.version.name)};
|
|
713
|
+
`
|
|
714
|
+
.replace(/^\t{3}/gm, '')
|
|
715
|
+
.trim()
|
|
716
|
+
);
|
|
717
|
+
|
|
718
|
+
const vite_config = await get_vite_config(vite_config_env);
|
|
719
|
+
const merged_config = merge_vite_configs(vite_config, {
|
|
720
|
+
base: assets_base(config.kit),
|
|
721
|
+
build: {
|
|
722
|
+
lib: {
|
|
723
|
+
entry: /** @type {string} */ (service_worker_entry_file),
|
|
724
|
+
name: 'app',
|
|
725
|
+
formats: ['es']
|
|
726
|
+
},
|
|
727
|
+
rollupOptions: {
|
|
728
|
+
output: {
|
|
729
|
+
entryFileNames: 'service-worker.js'
|
|
730
|
+
}
|
|
731
|
+
},
|
|
732
|
+
outDir: `${output_dir}/client`,
|
|
733
|
+
emptyOutDir: false
|
|
734
|
+
},
|
|
735
|
+
// @ts-expect-error
|
|
736
|
+
configFile: false,
|
|
737
|
+
resolve: {
|
|
738
|
+
alias: {
|
|
739
|
+
'$service-worker': service_worker,
|
|
740
|
+
$lib: config.kit.files.lib
|
|
741
|
+
}
|
|
742
|
+
}
|
|
743
|
+
});
|
|
744
|
+
|
|
745
|
+
remove_svelte_kit(merged_config);
|
|
746
|
+
|
|
747
|
+
await vite.build(merged_config);
|
|
748
|
+
}
|
|
749
|
+
|
|
750
|
+
/**
|
|
751
|
+
* @typedef {{
|
|
752
|
+
* fn: () => Promise<any>,
|
|
753
|
+
* fulfil: (value: any) => void,
|
|
754
|
+
* reject: (error: Error) => void
|
|
755
|
+
* }} Task
|
|
756
|
+
*/
|
|
757
|
+
|
|
758
|
+
/** @param {number} concurrency */
|
|
759
|
+
function queue(concurrency) {
|
|
760
|
+
/** @type {Task[]} */
|
|
761
|
+
const tasks = [];
|
|
762
|
+
|
|
763
|
+
let current = 0;
|
|
764
|
+
|
|
765
|
+
/** @type {(value?: any) => void} */
|
|
766
|
+
let fulfil;
|
|
767
|
+
|
|
768
|
+
/** @type {(error: Error) => void} */
|
|
769
|
+
let reject;
|
|
770
|
+
|
|
771
|
+
let closed = false;
|
|
772
|
+
|
|
773
|
+
const done = new Promise((f, r) => {
|
|
774
|
+
fulfil = f;
|
|
775
|
+
reject = r;
|
|
776
|
+
});
|
|
777
|
+
|
|
778
|
+
done.catch(() => {
|
|
779
|
+
// this is necessary in case a catch handler is never added
|
|
780
|
+
// to the done promise by the user
|
|
781
|
+
});
|
|
782
|
+
|
|
783
|
+
function dequeue() {
|
|
784
|
+
if (current < concurrency) {
|
|
785
|
+
const task = tasks.shift();
|
|
786
|
+
|
|
787
|
+
if (task) {
|
|
788
|
+
current += 1;
|
|
789
|
+
const promise = Promise.resolve(task.fn());
|
|
790
|
+
|
|
791
|
+
promise
|
|
792
|
+
.then(task.fulfil, (err) => {
|
|
793
|
+
task.reject(err);
|
|
794
|
+
reject(err);
|
|
795
|
+
})
|
|
796
|
+
.then(() => {
|
|
797
|
+
current -= 1;
|
|
798
|
+
dequeue();
|
|
799
|
+
});
|
|
800
|
+
} else if (current === 0) {
|
|
801
|
+
closed = true;
|
|
802
|
+
fulfil();
|
|
803
|
+
}
|
|
804
|
+
}
|
|
805
|
+
}
|
|
806
|
+
|
|
807
|
+
return {
|
|
808
|
+
/** @param {() => any} fn */
|
|
809
|
+
add: (fn) => {
|
|
810
|
+
if (closed) throw new Error('Cannot add tasks to a queue that has ended');
|
|
811
|
+
|
|
812
|
+
const promise = new Promise((fulfil, reject) => {
|
|
813
|
+
tasks.push({ fn, fulfil, reject });
|
|
814
|
+
});
|
|
815
|
+
|
|
816
|
+
dequeue();
|
|
817
|
+
return promise;
|
|
818
|
+
},
|
|
819
|
+
|
|
820
|
+
done: () => {
|
|
821
|
+
if (current === 0) {
|
|
822
|
+
closed = true;
|
|
823
|
+
fulfil();
|
|
824
|
+
}
|
|
825
|
+
|
|
826
|
+
return done;
|
|
827
|
+
}
|
|
828
|
+
};
|
|
829
|
+
}
|
|
830
|
+
|
|
831
|
+
const DOCTYPE = 'DOCTYPE';
|
|
832
|
+
const CDATA_OPEN = '[CDATA[';
|
|
833
|
+
const CDATA_CLOSE = ']]>';
|
|
834
|
+
const COMMENT_OPEN = '--';
|
|
835
|
+
const COMMENT_CLOSE = '-->';
|
|
836
|
+
|
|
837
|
+
const TAG_OPEN = /[a-zA-Z]/;
|
|
838
|
+
const TAG_CHAR = /[a-zA-Z0-9]/;
|
|
839
|
+
const ATTRIBUTE_NAME = /[^\t\n\f />"'=]/;
|
|
840
|
+
|
|
841
|
+
const WHITESPACE = /[\s\n\r]/;
|
|
842
|
+
|
|
843
|
+
/** @param {string} html */
|
|
844
|
+
function crawl(html) {
|
|
845
|
+
/** @type {string[]} */
|
|
846
|
+
const hrefs = [];
|
|
847
|
+
|
|
848
|
+
let i = 0;
|
|
849
|
+
main: while (i < html.length) {
|
|
850
|
+
const char = html[i];
|
|
851
|
+
|
|
852
|
+
if (char === '<') {
|
|
853
|
+
if (html[i + 1] === '!') {
|
|
854
|
+
i += 2;
|
|
855
|
+
|
|
856
|
+
if (html.slice(i, i + DOCTYPE.length).toUpperCase() === DOCTYPE) {
|
|
857
|
+
i += DOCTYPE.length;
|
|
858
|
+
while (i < html.length) {
|
|
859
|
+
if (html[i++] === '>') {
|
|
860
|
+
continue main;
|
|
861
|
+
}
|
|
862
|
+
}
|
|
863
|
+
}
|
|
864
|
+
|
|
865
|
+
// skip cdata
|
|
866
|
+
if (html.slice(i, i + CDATA_OPEN.length) === CDATA_OPEN) {
|
|
867
|
+
i += CDATA_OPEN.length;
|
|
868
|
+
while (i < html.length) {
|
|
869
|
+
if (html.slice(i, i + CDATA_CLOSE.length) === CDATA_CLOSE) {
|
|
870
|
+
i += CDATA_CLOSE.length;
|
|
871
|
+
continue main;
|
|
872
|
+
}
|
|
873
|
+
|
|
874
|
+
i += 1;
|
|
875
|
+
}
|
|
876
|
+
}
|
|
877
|
+
|
|
878
|
+
// skip comments
|
|
879
|
+
if (html.slice(i, i + COMMENT_OPEN.length) === COMMENT_OPEN) {
|
|
880
|
+
i += COMMENT_OPEN.length;
|
|
881
|
+
while (i < html.length) {
|
|
882
|
+
if (html.slice(i, i + COMMENT_CLOSE.length) === COMMENT_CLOSE) {
|
|
883
|
+
i += COMMENT_CLOSE.length;
|
|
884
|
+
continue main;
|
|
885
|
+
}
|
|
886
|
+
|
|
887
|
+
i += 1;
|
|
888
|
+
}
|
|
889
|
+
}
|
|
890
|
+
}
|
|
891
|
+
|
|
892
|
+
// parse opening tags
|
|
893
|
+
const start = ++i;
|
|
894
|
+
if (TAG_OPEN.test(html[start])) {
|
|
895
|
+
while (i < html.length) {
|
|
896
|
+
if (!TAG_CHAR.test(html[i])) {
|
|
897
|
+
break;
|
|
898
|
+
}
|
|
899
|
+
|
|
900
|
+
i += 1;
|
|
901
|
+
}
|
|
902
|
+
|
|
903
|
+
const tag = html.slice(start, i).toUpperCase();
|
|
904
|
+
|
|
905
|
+
if (tag === 'SCRIPT' || tag === 'STYLE') {
|
|
906
|
+
while (i < html.length) {
|
|
907
|
+
if (
|
|
908
|
+
html[i] === '<' &&
|
|
909
|
+
html[i + 1] === '/' &&
|
|
910
|
+
html.slice(i + 2, i + 2 + tag.length).toUpperCase() === tag
|
|
911
|
+
) {
|
|
912
|
+
continue main;
|
|
913
|
+
}
|
|
914
|
+
|
|
915
|
+
i += 1;
|
|
916
|
+
}
|
|
917
|
+
}
|
|
918
|
+
|
|
919
|
+
let href = '';
|
|
920
|
+
let rel = '';
|
|
921
|
+
|
|
922
|
+
while (i < html.length) {
|
|
923
|
+
const start = i;
|
|
924
|
+
|
|
925
|
+
const char = html[start];
|
|
926
|
+
if (char === '>') break;
|
|
927
|
+
|
|
928
|
+
if (ATTRIBUTE_NAME.test(char)) {
|
|
929
|
+
i += 1;
|
|
930
|
+
|
|
931
|
+
while (i < html.length) {
|
|
932
|
+
if (!ATTRIBUTE_NAME.test(html[i])) {
|
|
933
|
+
break;
|
|
934
|
+
}
|
|
935
|
+
|
|
936
|
+
i += 1;
|
|
937
|
+
}
|
|
938
|
+
|
|
939
|
+
const name = html.slice(start, i).toLowerCase();
|
|
940
|
+
|
|
941
|
+
while (WHITESPACE.test(html[i])) i += 1;
|
|
942
|
+
|
|
943
|
+
if (html[i] === '=') {
|
|
944
|
+
i += 1;
|
|
945
|
+
while (WHITESPACE.test(html[i])) i += 1;
|
|
946
|
+
|
|
947
|
+
let value;
|
|
948
|
+
|
|
949
|
+
if (html[i] === "'" || html[i] === '"') {
|
|
950
|
+
const quote = html[i++];
|
|
951
|
+
|
|
952
|
+
const start = i;
|
|
953
|
+
let escaped = false;
|
|
954
|
+
|
|
955
|
+
while (i < html.length) {
|
|
956
|
+
if (!escaped) {
|
|
957
|
+
const char = html[i];
|
|
958
|
+
|
|
959
|
+
if (html[i] === quote) {
|
|
960
|
+
break;
|
|
961
|
+
}
|
|
962
|
+
|
|
963
|
+
if (char === '\\') {
|
|
964
|
+
escaped = true;
|
|
965
|
+
}
|
|
966
|
+
}
|
|
967
|
+
|
|
968
|
+
i += 1;
|
|
969
|
+
}
|
|
970
|
+
|
|
971
|
+
value = html.slice(start, i);
|
|
972
|
+
} else {
|
|
973
|
+
const start = i;
|
|
974
|
+
while (html[i] !== '>' && !WHITESPACE.test(html[i])) i += 1;
|
|
975
|
+
value = html.slice(start, i);
|
|
976
|
+
|
|
977
|
+
i -= 1;
|
|
978
|
+
}
|
|
979
|
+
|
|
980
|
+
if (name === 'href') {
|
|
981
|
+
href = value;
|
|
982
|
+
} else if (name === 'rel') {
|
|
983
|
+
rel = value;
|
|
984
|
+
} else if (name === 'src') {
|
|
985
|
+
hrefs.push(value);
|
|
986
|
+
} else if (name === 'srcset') {
|
|
987
|
+
const candidates = [];
|
|
988
|
+
let insideURL = true;
|
|
989
|
+
value = value.trim();
|
|
990
|
+
for (let i = 0; i < value.length; i++) {
|
|
991
|
+
if (value[i] === ',' && (!insideURL || (insideURL && value[i + 1] === ' '))) {
|
|
992
|
+
candidates.push(value.slice(0, i));
|
|
993
|
+
value = value.substring(i + 1).trim();
|
|
994
|
+
i = 0;
|
|
995
|
+
insideURL = true;
|
|
996
|
+
} else if (value[i] === ' ') {
|
|
997
|
+
insideURL = false;
|
|
998
|
+
}
|
|
999
|
+
}
|
|
1000
|
+
candidates.push(value);
|
|
1001
|
+
for (const candidate of candidates) {
|
|
1002
|
+
const src = candidate.split(WHITESPACE)[0];
|
|
1003
|
+
hrefs.push(src);
|
|
1004
|
+
}
|
|
1005
|
+
}
|
|
1006
|
+
} else {
|
|
1007
|
+
i -= 1;
|
|
1008
|
+
}
|
|
1009
|
+
}
|
|
1010
|
+
|
|
1011
|
+
i += 1;
|
|
1012
|
+
}
|
|
1013
|
+
|
|
1014
|
+
if (href && !/\bexternal\b/i.test(rel)) {
|
|
1015
|
+
hrefs.push(href);
|
|
1016
|
+
}
|
|
1017
|
+
}
|
|
1018
|
+
}
|
|
1019
|
+
|
|
1020
|
+
i += 1;
|
|
1021
|
+
}
|
|
1022
|
+
|
|
1023
|
+
return hrefs;
|
|
1024
|
+
}
|
|
1025
|
+
|
|
1026
|
+
/**
|
|
1027
|
+
* Inside a script element, only `</script` and `<!--` hold special meaning to the HTML parser.
|
|
1028
|
+
*
|
|
1029
|
+
* The first closes the script element, so everything after is treated as raw HTML.
|
|
1030
|
+
* The second disables further parsing until `-->`, so the script element might be unexpectedly
|
|
1031
|
+
* kept open until until an unrelated HTML comment in the page.
|
|
1032
|
+
*
|
|
1033
|
+
* U+2028 LINE SEPARATOR and U+2029 PARAGRAPH SEPARATOR are escaped for the sake of pre-2018
|
|
1034
|
+
* browsers.
|
|
1035
|
+
*
|
|
1036
|
+
* @see tests for unsafe parsing examples.
|
|
1037
|
+
* @see https://html.spec.whatwg.org/multipage/scripting.html#restrictions-for-contents-of-script-elements
|
|
1038
|
+
* @see https://html.spec.whatwg.org/multipage/syntax.html#cdata-rcdata-restrictions
|
|
1039
|
+
* @see https://html.spec.whatwg.org/multipage/parsing.html#script-data-state
|
|
1040
|
+
* @see https://html.spec.whatwg.org/multipage/parsing.html#script-data-double-escaped-state
|
|
1041
|
+
* @see https://github.com/tc39/proposal-json-superset
|
|
1042
|
+
* @type {Record<string, string>}
|
|
1043
|
+
*/
|
|
1044
|
+
const render_json_payload_script_dict = {
|
|
1045
|
+
'<': '\\u003C',
|
|
1046
|
+
'\u2028': '\\u2028',
|
|
1047
|
+
'\u2029': '\\u2029'
|
|
1048
|
+
};
|
|
1049
|
+
|
|
1050
|
+
new RegExp(
|
|
1051
|
+
`[${Object.keys(render_json_payload_script_dict).join('')}]`,
|
|
1052
|
+
'g'
|
|
1053
|
+
);
|
|
1054
|
+
|
|
1055
|
+
/**
|
|
1056
|
+
* When inside a double-quoted attribute value, only `&` and `"` hold special meaning.
|
|
1057
|
+
* @see https://html.spec.whatwg.org/multipage/parsing.html#attribute-value-(double-quoted)-state
|
|
1058
|
+
* @type {Record<string, string>}
|
|
1059
|
+
*/
|
|
1060
|
+
const escape_html_attr_dict = {
|
|
1061
|
+
'&': '&',
|
|
1062
|
+
'"': '"'
|
|
1063
|
+
};
|
|
1064
|
+
|
|
1065
|
+
const escape_html_attr_regex = new RegExp(
|
|
1066
|
+
// special characters
|
|
1067
|
+
`[${Object.keys(escape_html_attr_dict).join('')}]|` +
|
|
1068
|
+
// high surrogate without paired low surrogate
|
|
1069
|
+
'[\\ud800-\\udbff](?![\\udc00-\\udfff])|' +
|
|
1070
|
+
// a valid surrogate pair, the only match with 2 code units
|
|
1071
|
+
// we match it so that we can match unpaired low surrogates in the same pass
|
|
1072
|
+
// TODO: use lookbehind assertions once they are widely supported: (?<![\ud800-udbff])[\udc00-\udfff]
|
|
1073
|
+
'[\\ud800-\\udbff][\\udc00-\\udfff]|' +
|
|
1074
|
+
// unpaired low surrogate (see previous match)
|
|
1075
|
+
'[\\udc00-\\udfff]',
|
|
1076
|
+
'g'
|
|
1077
|
+
);
|
|
1078
|
+
|
|
1079
|
+
/**
|
|
1080
|
+
* Formats a string to be used as an attribute's value in raw HTML.
|
|
1081
|
+
*
|
|
1082
|
+
* It escapes unpaired surrogates (which are allowed in js strings but invalid in HTML), escapes
|
|
1083
|
+
* characters that are special in attributes, and surrounds the whole string in double-quotes.
|
|
1084
|
+
*
|
|
1085
|
+
* @param {string} str
|
|
1086
|
+
* @returns {string} Escaped string surrounded by double-quotes.
|
|
1087
|
+
* @example const html = `<tag data-value=${escape_html_attr('value')}>...</tag>`;
|
|
1088
|
+
*/
|
|
1089
|
+
function escape_html_attr(str) {
|
|
1090
|
+
const escaped_str = str.replace(escape_html_attr_regex, (match) => {
|
|
1091
|
+
if (match.length === 2) {
|
|
1092
|
+
// valid surrogate pair
|
|
1093
|
+
return match;
|
|
1094
|
+
}
|
|
1095
|
+
|
|
1096
|
+
return escape_html_attr_dict[match] ?? `&#${match.charCodeAt(0)};`;
|
|
1097
|
+
});
|
|
1098
|
+
|
|
1099
|
+
return `"${escaped_str}"`;
|
|
1100
|
+
}
|
|
1101
|
+
|
|
1102
|
+
/**
|
|
1103
|
+
* @typedef {import('types').PrerenderErrorHandler} PrerenderErrorHandler
|
|
1104
|
+
* @typedef {import('types').PrerenderOnErrorValue} OnError
|
|
1105
|
+
* @typedef {import('types').Logger} Logger
|
|
1106
|
+
*/
|
|
1107
|
+
|
|
1108
|
+
/** @type {(details: Parameters<PrerenderErrorHandler>[0] ) => string} */
|
|
1109
|
+
function format_error({ status, path, referrer, referenceType }) {
|
|
1110
|
+
return `${status} ${path}${referrer ? ` (${referenceType} from ${referrer})` : ''}`;
|
|
1111
|
+
}
|
|
1112
|
+
|
|
1113
|
+
/** @type {(log: Logger, onError: OnError) => PrerenderErrorHandler} */
|
|
1114
|
+
function normalise_error_handler(log, onError) {
|
|
1115
|
+
switch (onError) {
|
|
1116
|
+
case 'continue':
|
|
1117
|
+
return (details) => {
|
|
1118
|
+
log.error(format_error(details));
|
|
1119
|
+
};
|
|
1120
|
+
case 'fail':
|
|
1121
|
+
return (details) => {
|
|
1122
|
+
throw new Error(format_error(details));
|
|
1123
|
+
};
|
|
1124
|
+
default:
|
|
1125
|
+
return onError;
|
|
1126
|
+
}
|
|
1127
|
+
}
|
|
1128
|
+
|
|
1129
|
+
const OK = 2;
|
|
1130
|
+
const REDIRECT = 3;
|
|
1131
|
+
|
|
1132
|
+
/**
|
|
1133
|
+
* @param {{
|
|
1134
|
+
* config: import('types').ValidatedKitConfig;
|
|
1135
|
+
* entries: string[];
|
|
1136
|
+
* files: Set<string>;
|
|
1137
|
+
* log: Logger;
|
|
1138
|
+
* }} opts
|
|
1139
|
+
*/
|
|
1140
|
+
async function prerender({ config, entries, files, log }) {
|
|
1141
|
+
/** @type {import('types').Prerendered} */
|
|
1142
|
+
const prerendered = {
|
|
1143
|
+
pages: new Map(),
|
|
1144
|
+
assets: new Map(),
|
|
1145
|
+
redirects: new Map(),
|
|
1146
|
+
paths: []
|
|
1147
|
+
};
|
|
1148
|
+
|
|
1149
|
+
if (!config.prerender.enabled) {
|
|
1150
|
+
return prerendered;
|
|
1151
|
+
}
|
|
1152
|
+
|
|
1153
|
+
installPolyfills();
|
|
1154
|
+
|
|
1155
|
+
const server_root = join(config.outDir, 'output');
|
|
1156
|
+
|
|
1157
|
+
/** @type {import('types').ServerModule} */
|
|
1158
|
+
const { Server, override } = await import(pathToFileURL(`${server_root}/server/index.js`).href);
|
|
1159
|
+
const { manifest } = await import(pathToFileURL(`${server_root}/server/manifest.js`).href);
|
|
1160
|
+
|
|
1161
|
+
override({
|
|
1162
|
+
paths: config.paths,
|
|
1163
|
+
prerendering: true,
|
|
1164
|
+
read: (file) => readFileSync(join(config.files.assets, file))
|
|
1165
|
+
});
|
|
1166
|
+
|
|
1167
|
+
const server = new Server(manifest);
|
|
1168
|
+
|
|
1169
|
+
const error = normalise_error_handler(log, config.prerender.onError);
|
|
1170
|
+
|
|
1171
|
+
const q = queue(config.prerender.concurrency);
|
|
1172
|
+
|
|
1173
|
+
/**
|
|
1174
|
+
* @param {string} path
|
|
1175
|
+
* @param {boolean} is_html
|
|
1176
|
+
*/
|
|
1177
|
+
function output_filename(path, is_html) {
|
|
1178
|
+
const file = path.slice(config.paths.base.length + 1);
|
|
1179
|
+
|
|
1180
|
+
if (file === '') {
|
|
1181
|
+
return 'index.html';
|
|
1182
|
+
}
|
|
1183
|
+
|
|
1184
|
+
if (is_html && !file.endsWith('.html')) {
|
|
1185
|
+
return file + (file.endsWith('/') ? 'index.html' : '.html');
|
|
1186
|
+
}
|
|
1187
|
+
|
|
1188
|
+
return file;
|
|
1189
|
+
}
|
|
1190
|
+
|
|
1191
|
+
const seen = new Set();
|
|
1192
|
+
const written = new Set();
|
|
1193
|
+
|
|
1194
|
+
/**
|
|
1195
|
+
* @param {string | null} referrer
|
|
1196
|
+
* @param {string} decoded
|
|
1197
|
+
* @param {string} [encoded]
|
|
1198
|
+
*/
|
|
1199
|
+
function enqueue(referrer, decoded, encoded) {
|
|
1200
|
+
if (seen.has(decoded)) return;
|
|
1201
|
+
seen.add(decoded);
|
|
1202
|
+
|
|
1203
|
+
const file = decoded.slice(config.paths.base.length + 1);
|
|
1204
|
+
if (files.has(file)) return;
|
|
1205
|
+
|
|
1206
|
+
return q.add(() => visit(decoded, encoded || encodeURI(decoded), referrer));
|
|
1207
|
+
}
|
|
1208
|
+
|
|
1209
|
+
/**
|
|
1210
|
+
* @param {string} decoded
|
|
1211
|
+
* @param {string} encoded
|
|
1212
|
+
* @param {string?} referrer
|
|
1213
|
+
*/
|
|
1214
|
+
async function visit(decoded, encoded, referrer) {
|
|
1215
|
+
if (!decoded.startsWith(config.paths.base)) {
|
|
1216
|
+
error({ status: 404, path: decoded, referrer, referenceType: 'linked' });
|
|
1217
|
+
return;
|
|
1218
|
+
}
|
|
1219
|
+
|
|
1220
|
+
/** @type {Map<string, import('types').PrerenderDependency>} */
|
|
1221
|
+
const dependencies = new Map();
|
|
1222
|
+
|
|
1223
|
+
const response = await server.respond(new Request(`http://sveltekit-prerender${encoded}`), {
|
|
1224
|
+
getClientAddress,
|
|
1225
|
+
prerendering: {
|
|
1226
|
+
dependencies
|
|
1227
|
+
}
|
|
1228
|
+
});
|
|
1229
|
+
|
|
1230
|
+
const text = await response.text();
|
|
1231
|
+
|
|
1232
|
+
save('pages', response, text, decoded, encoded, referrer, 'linked');
|
|
1233
|
+
|
|
1234
|
+
for (const [dependency_path, result] of dependencies) {
|
|
1235
|
+
// this seems circuitous, but using new URL allows us to not care
|
|
1236
|
+
// whether dependency_path is encoded or not
|
|
1237
|
+
const encoded_dependency_path = new URL$1(dependency_path, 'http://localhost').pathname;
|
|
1238
|
+
const decoded_dependency_path = decodeURI(encoded_dependency_path);
|
|
1239
|
+
|
|
1240
|
+
const body = result.body ?? new Uint8Array(await result.response.arrayBuffer());
|
|
1241
|
+
save(
|
|
1242
|
+
'dependencies',
|
|
1243
|
+
result.response,
|
|
1244
|
+
body,
|
|
1245
|
+
decoded_dependency_path,
|
|
1246
|
+
encoded_dependency_path,
|
|
1247
|
+
decoded,
|
|
1248
|
+
'fetched'
|
|
1249
|
+
);
|
|
1250
|
+
}
|
|
1251
|
+
|
|
1252
|
+
if (config.prerender.crawl && response.headers.get('content-type') === 'text/html') {
|
|
1253
|
+
for (const href of crawl(text)) {
|
|
1254
|
+
if (href.startsWith('data:') || href.startsWith('#')) continue;
|
|
1255
|
+
|
|
1256
|
+
const resolved = resolve(encoded, href);
|
|
1257
|
+
if (!is_root_relative(resolved)) continue;
|
|
1258
|
+
|
|
1259
|
+
const { pathname, search } = new URL$1(resolved, 'http://localhost');
|
|
1260
|
+
|
|
1261
|
+
enqueue(decoded, decodeURI(pathname), pathname);
|
|
1262
|
+
}
|
|
1263
|
+
}
|
|
1264
|
+
}
|
|
1265
|
+
|
|
1266
|
+
/**
|
|
1267
|
+
* @param {'pages' | 'dependencies'} category
|
|
1268
|
+
* @param {Response} response
|
|
1269
|
+
* @param {string | Uint8Array} body
|
|
1270
|
+
* @param {string} decoded
|
|
1271
|
+
* @param {string} encoded
|
|
1272
|
+
* @param {string | null} referrer
|
|
1273
|
+
* @param {'linked' | 'fetched'} referenceType
|
|
1274
|
+
*/
|
|
1275
|
+
function save(category, response, body, decoded, encoded, referrer, referenceType) {
|
|
1276
|
+
const response_type = Math.floor(response.status / 100);
|
|
1277
|
+
const type = /** @type {string} */ (response.headers.get('content-type'));
|
|
1278
|
+
const is_html = response_type === REDIRECT || type === 'text/html';
|
|
1279
|
+
|
|
1280
|
+
const file = output_filename(decoded, is_html);
|
|
1281
|
+
const dest = `${config.outDir}/output/prerendered/${category}/${file}`;
|
|
1282
|
+
|
|
1283
|
+
if (written.has(file)) return;
|
|
1284
|
+
|
|
1285
|
+
if (response_type === REDIRECT) {
|
|
1286
|
+
const location = response.headers.get('location');
|
|
1287
|
+
|
|
1288
|
+
if (location) {
|
|
1289
|
+
const resolved = resolve(encoded, location);
|
|
1290
|
+
if (is_root_relative(resolved)) {
|
|
1291
|
+
enqueue(decoded, decodeURI(resolved), resolved);
|
|
1292
|
+
}
|
|
1293
|
+
|
|
1294
|
+
if (!response.headers.get('x-sveltekit-normalize')) {
|
|
1295
|
+
mkdirp(dirname(dest));
|
|
1296
|
+
|
|
1297
|
+
log.warn(`${response.status} ${decoded} -> ${location}`);
|
|
1298
|
+
|
|
1299
|
+
writeFileSync(
|
|
1300
|
+
dest,
|
|
1301
|
+
`<meta http-equiv="refresh" content=${escape_html_attr(`0;url=${location}`)}>`
|
|
1302
|
+
);
|
|
1303
|
+
|
|
1304
|
+
written.add(file);
|
|
1305
|
+
|
|
1306
|
+
if (!prerendered.redirects.has(decoded)) {
|
|
1307
|
+
prerendered.redirects.set(decoded, {
|
|
1308
|
+
status: response.status,
|
|
1309
|
+
location: resolved
|
|
1310
|
+
});
|
|
1311
|
+
|
|
1312
|
+
prerendered.paths.push(normalize_path(decoded, 'never'));
|
|
1313
|
+
}
|
|
1314
|
+
}
|
|
1315
|
+
} else {
|
|
1316
|
+
log.warn(`location header missing on redirect received from ${decoded}`);
|
|
1317
|
+
}
|
|
1318
|
+
|
|
1319
|
+
return;
|
|
1320
|
+
}
|
|
1321
|
+
|
|
1322
|
+
if (response.status === 200) {
|
|
1323
|
+
mkdirp(dirname(dest));
|
|
1324
|
+
|
|
1325
|
+
log.info(`${response.status} ${decoded}`);
|
|
1326
|
+
writeFileSync(dest, body);
|
|
1327
|
+
written.add(file);
|
|
1328
|
+
|
|
1329
|
+
if (is_html) {
|
|
1330
|
+
prerendered.pages.set(decoded, {
|
|
1331
|
+
file
|
|
1332
|
+
});
|
|
1333
|
+
} else {
|
|
1334
|
+
prerendered.assets.set(decoded, {
|
|
1335
|
+
type
|
|
1336
|
+
});
|
|
1337
|
+
}
|
|
1338
|
+
|
|
1339
|
+
prerendered.paths.push(normalize_path(decoded, 'never'));
|
|
1340
|
+
} else if (response_type !== OK) {
|
|
1341
|
+
error({ status: response.status, path: decoded, referrer, referenceType });
|
|
1342
|
+
}
|
|
1343
|
+
}
|
|
1344
|
+
|
|
1345
|
+
if (config.prerender.enabled) {
|
|
1346
|
+
for (const entry of config.prerender.entries) {
|
|
1347
|
+
if (entry === '*') {
|
|
1348
|
+
for (const entry of entries) {
|
|
1349
|
+
enqueue(null, config.paths.base + entry); // TODO can we pre-normalize these?
|
|
1350
|
+
}
|
|
1351
|
+
} else {
|
|
1352
|
+
enqueue(null, config.paths.base + entry);
|
|
1353
|
+
}
|
|
1354
|
+
}
|
|
1355
|
+
|
|
1356
|
+
await q.done();
|
|
1357
|
+
}
|
|
1358
|
+
|
|
1359
|
+
const rendered = await server.respond(new Request('http://sveltekit-prerender/[fallback]'), {
|
|
1360
|
+
getClientAddress,
|
|
1361
|
+
prerendering: {
|
|
1362
|
+
fallback: true,
|
|
1363
|
+
dependencies: new Map()
|
|
1364
|
+
}
|
|
1365
|
+
});
|
|
1366
|
+
|
|
1367
|
+
const file = `${config.outDir}/output/prerendered/fallback.html`;
|
|
1368
|
+
mkdirp(dirname(file));
|
|
1369
|
+
writeFileSync(file, await rendered.text());
|
|
1370
|
+
|
|
1371
|
+
return prerendered;
|
|
1372
|
+
}
|
|
1373
|
+
|
|
1374
|
+
/** @return {string} */
|
|
1375
|
+
function getClientAddress() {
|
|
1376
|
+
throw new Error('Cannot read clientAddress during prerendering');
|
|
1377
|
+
}
|
|
1378
|
+
|
|
1379
|
+
function totalist(dir, callback, pre='') {
|
|
1380
|
+
dir = resolve$1('.', dir);
|
|
1381
|
+
let arr = readdirSync(dir);
|
|
1382
|
+
let i=0, abs, stats;
|
|
1383
|
+
for (; i < arr.length; i++) {
|
|
1384
|
+
abs = join(dir, arr[i]);
|
|
1385
|
+
stats = statSync(abs);
|
|
1386
|
+
stats.isDirectory()
|
|
1387
|
+
? totalist(abs, callback, join(pre, arr[i]))
|
|
1388
|
+
: callback(join(pre, arr[i]), abs, stats);
|
|
1389
|
+
}
|
|
1390
|
+
}
|
|
1391
|
+
|
|
1392
|
+
/**
|
|
1393
|
+
* @typedef ParsedURL
|
|
1394
|
+
* @type {import('.').ParsedURL}
|
|
1395
|
+
*/
|
|
1396
|
+
|
|
1397
|
+
/**
|
|
1398
|
+
* @typedef Request
|
|
1399
|
+
* @property {string} url
|
|
1400
|
+
* @property {ParsedURL} _parsedUrl
|
|
1401
|
+
*/
|
|
1402
|
+
|
|
1403
|
+
/**
|
|
1404
|
+
* @param {Request} req
|
|
1405
|
+
* @returns {ParsedURL|void}
|
|
1406
|
+
*/
|
|
1407
|
+
function parse(req) {
|
|
1408
|
+
let raw = req.url;
|
|
1409
|
+
if (raw == null) return;
|
|
1410
|
+
|
|
1411
|
+
let prev = req._parsedUrl;
|
|
1412
|
+
if (prev && prev.raw === raw) return prev;
|
|
1413
|
+
|
|
1414
|
+
let pathname=raw, search='', query;
|
|
1415
|
+
|
|
1416
|
+
if (raw.length > 1) {
|
|
1417
|
+
let idx = raw.indexOf('?', 1);
|
|
1418
|
+
|
|
1419
|
+
if (idx !== -1) {
|
|
1420
|
+
search = raw.substring(idx);
|
|
1421
|
+
pathname = raw.substring(0, idx);
|
|
1422
|
+
if (search.length > 1) {
|
|
1423
|
+
query = qs.parse(search.substring(1));
|
|
1424
|
+
}
|
|
1425
|
+
}
|
|
1426
|
+
}
|
|
1427
|
+
|
|
1428
|
+
return req._parsedUrl = { pathname, search, query, raw };
|
|
1429
|
+
}
|
|
1430
|
+
|
|
1431
|
+
const mimes = {
|
|
1432
|
+
"ez": "application/andrew-inset",
|
|
1433
|
+
"aw": "application/applixware",
|
|
1434
|
+
"atom": "application/atom+xml",
|
|
1435
|
+
"atomcat": "application/atomcat+xml",
|
|
1436
|
+
"atomdeleted": "application/atomdeleted+xml",
|
|
1437
|
+
"atomsvc": "application/atomsvc+xml",
|
|
1438
|
+
"dwd": "application/atsc-dwd+xml",
|
|
1439
|
+
"held": "application/atsc-held+xml",
|
|
1440
|
+
"rsat": "application/atsc-rsat+xml",
|
|
1441
|
+
"bdoc": "application/bdoc",
|
|
1442
|
+
"xcs": "application/calendar+xml",
|
|
1443
|
+
"ccxml": "application/ccxml+xml",
|
|
1444
|
+
"cdfx": "application/cdfx+xml",
|
|
1445
|
+
"cdmia": "application/cdmi-capability",
|
|
1446
|
+
"cdmic": "application/cdmi-container",
|
|
1447
|
+
"cdmid": "application/cdmi-domain",
|
|
1448
|
+
"cdmio": "application/cdmi-object",
|
|
1449
|
+
"cdmiq": "application/cdmi-queue",
|
|
1450
|
+
"cu": "application/cu-seeme",
|
|
1451
|
+
"mpd": "application/dash+xml",
|
|
1452
|
+
"davmount": "application/davmount+xml",
|
|
1453
|
+
"dbk": "application/docbook+xml",
|
|
1454
|
+
"dssc": "application/dssc+der",
|
|
1455
|
+
"xdssc": "application/dssc+xml",
|
|
1456
|
+
"es": "application/ecmascript",
|
|
1457
|
+
"ecma": "application/ecmascript",
|
|
1458
|
+
"emma": "application/emma+xml",
|
|
1459
|
+
"emotionml": "application/emotionml+xml",
|
|
1460
|
+
"epub": "application/epub+zip",
|
|
1461
|
+
"exi": "application/exi",
|
|
1462
|
+
"fdt": "application/fdt+xml",
|
|
1463
|
+
"pfr": "application/font-tdpfr",
|
|
1464
|
+
"geojson": "application/geo+json",
|
|
1465
|
+
"gml": "application/gml+xml",
|
|
1466
|
+
"gpx": "application/gpx+xml",
|
|
1467
|
+
"gxf": "application/gxf",
|
|
1468
|
+
"gz": "application/gzip",
|
|
1469
|
+
"hjson": "application/hjson",
|
|
1470
|
+
"stk": "application/hyperstudio",
|
|
1471
|
+
"ink": "application/inkml+xml",
|
|
1472
|
+
"inkml": "application/inkml+xml",
|
|
1473
|
+
"ipfix": "application/ipfix",
|
|
1474
|
+
"its": "application/its+xml",
|
|
1475
|
+
"jar": "application/java-archive",
|
|
1476
|
+
"war": "application/java-archive",
|
|
1477
|
+
"ear": "application/java-archive",
|
|
1478
|
+
"ser": "application/java-serialized-object",
|
|
1479
|
+
"class": "application/java-vm",
|
|
1480
|
+
"js": "application/javascript",
|
|
1481
|
+
"mjs": "application/javascript",
|
|
1482
|
+
"json": "application/json",
|
|
1483
|
+
"map": "application/json",
|
|
1484
|
+
"json5": "application/json5",
|
|
1485
|
+
"jsonml": "application/jsonml+json",
|
|
1486
|
+
"jsonld": "application/ld+json",
|
|
1487
|
+
"lgr": "application/lgr+xml",
|
|
1488
|
+
"lostxml": "application/lost+xml",
|
|
1489
|
+
"hqx": "application/mac-binhex40",
|
|
1490
|
+
"cpt": "application/mac-compactpro",
|
|
1491
|
+
"mads": "application/mads+xml",
|
|
1492
|
+
"webmanifest": "application/manifest+json",
|
|
1493
|
+
"mrc": "application/marc",
|
|
1494
|
+
"mrcx": "application/marcxml+xml",
|
|
1495
|
+
"ma": "application/mathematica",
|
|
1496
|
+
"nb": "application/mathematica",
|
|
1497
|
+
"mb": "application/mathematica",
|
|
1498
|
+
"mathml": "application/mathml+xml",
|
|
1499
|
+
"mbox": "application/mbox",
|
|
1500
|
+
"mscml": "application/mediaservercontrol+xml",
|
|
1501
|
+
"metalink": "application/metalink+xml",
|
|
1502
|
+
"meta4": "application/metalink4+xml",
|
|
1503
|
+
"mets": "application/mets+xml",
|
|
1504
|
+
"maei": "application/mmt-aei+xml",
|
|
1505
|
+
"musd": "application/mmt-usd+xml",
|
|
1506
|
+
"mods": "application/mods+xml",
|
|
1507
|
+
"m21": "application/mp21",
|
|
1508
|
+
"mp21": "application/mp21",
|
|
1509
|
+
"mp4s": "application/mp4",
|
|
1510
|
+
"m4p": "application/mp4",
|
|
1511
|
+
"doc": "application/msword",
|
|
1512
|
+
"dot": "application/msword",
|
|
1513
|
+
"mxf": "application/mxf",
|
|
1514
|
+
"nq": "application/n-quads",
|
|
1515
|
+
"nt": "application/n-triples",
|
|
1516
|
+
"cjs": "application/node",
|
|
1517
|
+
"bin": "application/octet-stream",
|
|
1518
|
+
"dms": "application/octet-stream",
|
|
1519
|
+
"lrf": "application/octet-stream",
|
|
1520
|
+
"mar": "application/octet-stream",
|
|
1521
|
+
"so": "application/octet-stream",
|
|
1522
|
+
"dist": "application/octet-stream",
|
|
1523
|
+
"distz": "application/octet-stream",
|
|
1524
|
+
"pkg": "application/octet-stream",
|
|
1525
|
+
"bpk": "application/octet-stream",
|
|
1526
|
+
"dump": "application/octet-stream",
|
|
1527
|
+
"elc": "application/octet-stream",
|
|
1528
|
+
"deploy": "application/octet-stream",
|
|
1529
|
+
"exe": "application/octet-stream",
|
|
1530
|
+
"dll": "application/octet-stream",
|
|
1531
|
+
"deb": "application/octet-stream",
|
|
1532
|
+
"dmg": "application/octet-stream",
|
|
1533
|
+
"iso": "application/octet-stream",
|
|
1534
|
+
"img": "application/octet-stream",
|
|
1535
|
+
"msi": "application/octet-stream",
|
|
1536
|
+
"msp": "application/octet-stream",
|
|
1537
|
+
"msm": "application/octet-stream",
|
|
1538
|
+
"buffer": "application/octet-stream",
|
|
1539
|
+
"oda": "application/oda",
|
|
1540
|
+
"opf": "application/oebps-package+xml",
|
|
1541
|
+
"ogx": "application/ogg",
|
|
1542
|
+
"omdoc": "application/omdoc+xml",
|
|
1543
|
+
"onetoc": "application/onenote",
|
|
1544
|
+
"onetoc2": "application/onenote",
|
|
1545
|
+
"onetmp": "application/onenote",
|
|
1546
|
+
"onepkg": "application/onenote",
|
|
1547
|
+
"oxps": "application/oxps",
|
|
1548
|
+
"relo": "application/p2p-overlay+xml",
|
|
1549
|
+
"xer": "application/patch-ops-error+xml",
|
|
1550
|
+
"pdf": "application/pdf",
|
|
1551
|
+
"pgp": "application/pgp-encrypted",
|
|
1552
|
+
"asc": "application/pgp-signature",
|
|
1553
|
+
"sig": "application/pgp-signature",
|
|
1554
|
+
"prf": "application/pics-rules",
|
|
1555
|
+
"p10": "application/pkcs10",
|
|
1556
|
+
"p7m": "application/pkcs7-mime",
|
|
1557
|
+
"p7c": "application/pkcs7-mime",
|
|
1558
|
+
"p7s": "application/pkcs7-signature",
|
|
1559
|
+
"p8": "application/pkcs8",
|
|
1560
|
+
"ac": "application/pkix-attr-cert",
|
|
1561
|
+
"cer": "application/pkix-cert",
|
|
1562
|
+
"crl": "application/pkix-crl",
|
|
1563
|
+
"pkipath": "application/pkix-pkipath",
|
|
1564
|
+
"pki": "application/pkixcmp",
|
|
1565
|
+
"pls": "application/pls+xml",
|
|
1566
|
+
"ai": "application/postscript",
|
|
1567
|
+
"eps": "application/postscript",
|
|
1568
|
+
"ps": "application/postscript",
|
|
1569
|
+
"provx": "application/provenance+xml",
|
|
1570
|
+
"cww": "application/prs.cww",
|
|
1571
|
+
"pskcxml": "application/pskc+xml",
|
|
1572
|
+
"raml": "application/raml+yaml",
|
|
1573
|
+
"rdf": "application/rdf+xml",
|
|
1574
|
+
"owl": "application/rdf+xml",
|
|
1575
|
+
"rif": "application/reginfo+xml",
|
|
1576
|
+
"rnc": "application/relax-ng-compact-syntax",
|
|
1577
|
+
"rl": "application/resource-lists+xml",
|
|
1578
|
+
"rld": "application/resource-lists-diff+xml",
|
|
1579
|
+
"rs": "application/rls-services+xml",
|
|
1580
|
+
"rapd": "application/route-apd+xml",
|
|
1581
|
+
"sls": "application/route-s-tsid+xml",
|
|
1582
|
+
"rusd": "application/route-usd+xml",
|
|
1583
|
+
"gbr": "application/rpki-ghostbusters",
|
|
1584
|
+
"mft": "application/rpki-manifest",
|
|
1585
|
+
"roa": "application/rpki-roa",
|
|
1586
|
+
"rsd": "application/rsd+xml",
|
|
1587
|
+
"rss": "application/rss+xml",
|
|
1588
|
+
"rtf": "application/rtf",
|
|
1589
|
+
"sbml": "application/sbml+xml",
|
|
1590
|
+
"scq": "application/scvp-cv-request",
|
|
1591
|
+
"scs": "application/scvp-cv-response",
|
|
1592
|
+
"spq": "application/scvp-vp-request",
|
|
1593
|
+
"spp": "application/scvp-vp-response",
|
|
1594
|
+
"sdp": "application/sdp",
|
|
1595
|
+
"senmlx": "application/senml+xml",
|
|
1596
|
+
"sensmlx": "application/sensml+xml",
|
|
1597
|
+
"setpay": "application/set-payment-initiation",
|
|
1598
|
+
"setreg": "application/set-registration-initiation",
|
|
1599
|
+
"shf": "application/shf+xml",
|
|
1600
|
+
"siv": "application/sieve",
|
|
1601
|
+
"sieve": "application/sieve",
|
|
1602
|
+
"smi": "application/smil+xml",
|
|
1603
|
+
"smil": "application/smil+xml",
|
|
1604
|
+
"rq": "application/sparql-query",
|
|
1605
|
+
"srx": "application/sparql-results+xml",
|
|
1606
|
+
"gram": "application/srgs",
|
|
1607
|
+
"grxml": "application/srgs+xml",
|
|
1608
|
+
"sru": "application/sru+xml",
|
|
1609
|
+
"ssdl": "application/ssdl+xml",
|
|
1610
|
+
"ssml": "application/ssml+xml",
|
|
1611
|
+
"swidtag": "application/swid+xml",
|
|
1612
|
+
"tei": "application/tei+xml",
|
|
1613
|
+
"teicorpus": "application/tei+xml",
|
|
1614
|
+
"tfi": "application/thraud+xml",
|
|
1615
|
+
"tsd": "application/timestamped-data",
|
|
1616
|
+
"toml": "application/toml",
|
|
1617
|
+
"trig": "application/trig",
|
|
1618
|
+
"ttml": "application/ttml+xml",
|
|
1619
|
+
"ubj": "application/ubjson",
|
|
1620
|
+
"rsheet": "application/urc-ressheet+xml",
|
|
1621
|
+
"td": "application/urc-targetdesc+xml",
|
|
1622
|
+
"vxml": "application/voicexml+xml",
|
|
1623
|
+
"wasm": "application/wasm",
|
|
1624
|
+
"wgt": "application/widget",
|
|
1625
|
+
"hlp": "application/winhlp",
|
|
1626
|
+
"wsdl": "application/wsdl+xml",
|
|
1627
|
+
"wspolicy": "application/wspolicy+xml",
|
|
1628
|
+
"xaml": "application/xaml+xml",
|
|
1629
|
+
"xav": "application/xcap-att+xml",
|
|
1630
|
+
"xca": "application/xcap-caps+xml",
|
|
1631
|
+
"xdf": "application/xcap-diff+xml",
|
|
1632
|
+
"xel": "application/xcap-el+xml",
|
|
1633
|
+
"xns": "application/xcap-ns+xml",
|
|
1634
|
+
"xenc": "application/xenc+xml",
|
|
1635
|
+
"xhtml": "application/xhtml+xml",
|
|
1636
|
+
"xht": "application/xhtml+xml",
|
|
1637
|
+
"xlf": "application/xliff+xml",
|
|
1638
|
+
"xml": "application/xml",
|
|
1639
|
+
"xsl": "application/xml",
|
|
1640
|
+
"xsd": "application/xml",
|
|
1641
|
+
"rng": "application/xml",
|
|
1642
|
+
"dtd": "application/xml-dtd",
|
|
1643
|
+
"xop": "application/xop+xml",
|
|
1644
|
+
"xpl": "application/xproc+xml",
|
|
1645
|
+
"xslt": "application/xml",
|
|
1646
|
+
"xspf": "application/xspf+xml",
|
|
1647
|
+
"mxml": "application/xv+xml",
|
|
1648
|
+
"xhvml": "application/xv+xml",
|
|
1649
|
+
"xvml": "application/xv+xml",
|
|
1650
|
+
"xvm": "application/xv+xml",
|
|
1651
|
+
"yang": "application/yang",
|
|
1652
|
+
"yin": "application/yin+xml",
|
|
1653
|
+
"zip": "application/zip",
|
|
1654
|
+
"3gpp": "video/3gpp",
|
|
1655
|
+
"adp": "audio/adpcm",
|
|
1656
|
+
"amr": "audio/amr",
|
|
1657
|
+
"au": "audio/basic",
|
|
1658
|
+
"snd": "audio/basic",
|
|
1659
|
+
"mid": "audio/midi",
|
|
1660
|
+
"midi": "audio/midi",
|
|
1661
|
+
"kar": "audio/midi",
|
|
1662
|
+
"rmi": "audio/midi",
|
|
1663
|
+
"mxmf": "audio/mobile-xmf",
|
|
1664
|
+
"mp3": "audio/mpeg",
|
|
1665
|
+
"m4a": "audio/mp4",
|
|
1666
|
+
"mp4a": "audio/mp4",
|
|
1667
|
+
"mpga": "audio/mpeg",
|
|
1668
|
+
"mp2": "audio/mpeg",
|
|
1669
|
+
"mp2a": "audio/mpeg",
|
|
1670
|
+
"m2a": "audio/mpeg",
|
|
1671
|
+
"m3a": "audio/mpeg",
|
|
1672
|
+
"oga": "audio/ogg",
|
|
1673
|
+
"ogg": "audio/ogg",
|
|
1674
|
+
"spx": "audio/ogg",
|
|
1675
|
+
"opus": "audio/ogg",
|
|
1676
|
+
"s3m": "audio/s3m",
|
|
1677
|
+
"sil": "audio/silk",
|
|
1678
|
+
"wav": "audio/wav",
|
|
1679
|
+
"weba": "audio/webm",
|
|
1680
|
+
"xm": "audio/xm",
|
|
1681
|
+
"ttc": "font/collection",
|
|
1682
|
+
"otf": "font/otf",
|
|
1683
|
+
"ttf": "font/ttf",
|
|
1684
|
+
"woff": "font/woff",
|
|
1685
|
+
"woff2": "font/woff2",
|
|
1686
|
+
"exr": "image/aces",
|
|
1687
|
+
"apng": "image/apng",
|
|
1688
|
+
"avif": "image/avif",
|
|
1689
|
+
"bmp": "image/bmp",
|
|
1690
|
+
"cgm": "image/cgm",
|
|
1691
|
+
"drle": "image/dicom-rle",
|
|
1692
|
+
"emf": "image/emf",
|
|
1693
|
+
"fits": "image/fits",
|
|
1694
|
+
"g3": "image/g3fax",
|
|
1695
|
+
"gif": "image/gif",
|
|
1696
|
+
"heic": "image/heic",
|
|
1697
|
+
"heics": "image/heic-sequence",
|
|
1698
|
+
"heif": "image/heif",
|
|
1699
|
+
"heifs": "image/heif-sequence",
|
|
1700
|
+
"hej2": "image/hej2k",
|
|
1701
|
+
"hsj2": "image/hsj2",
|
|
1702
|
+
"ief": "image/ief",
|
|
1703
|
+
"jls": "image/jls",
|
|
1704
|
+
"jp2": "image/jp2",
|
|
1705
|
+
"jpg2": "image/jp2",
|
|
1706
|
+
"jpeg": "image/jpeg",
|
|
1707
|
+
"jpg": "image/jpeg",
|
|
1708
|
+
"jpe": "image/jpeg",
|
|
1709
|
+
"jph": "image/jph",
|
|
1710
|
+
"jhc": "image/jphc",
|
|
1711
|
+
"jpm": "image/jpm",
|
|
1712
|
+
"jpx": "image/jpx",
|
|
1713
|
+
"jpf": "image/jpx",
|
|
1714
|
+
"jxr": "image/jxr",
|
|
1715
|
+
"jxra": "image/jxra",
|
|
1716
|
+
"jxrs": "image/jxrs",
|
|
1717
|
+
"jxs": "image/jxs",
|
|
1718
|
+
"jxsc": "image/jxsc",
|
|
1719
|
+
"jxsi": "image/jxsi",
|
|
1720
|
+
"jxss": "image/jxss",
|
|
1721
|
+
"ktx": "image/ktx",
|
|
1722
|
+
"ktx2": "image/ktx2",
|
|
1723
|
+
"png": "image/png",
|
|
1724
|
+
"btif": "image/prs.btif",
|
|
1725
|
+
"pti": "image/prs.pti",
|
|
1726
|
+
"sgi": "image/sgi",
|
|
1727
|
+
"svg": "image/svg+xml",
|
|
1728
|
+
"svgz": "image/svg+xml",
|
|
1729
|
+
"t38": "image/t38",
|
|
1730
|
+
"tif": "image/tiff",
|
|
1731
|
+
"tiff": "image/tiff",
|
|
1732
|
+
"tfx": "image/tiff-fx",
|
|
1733
|
+
"webp": "image/webp",
|
|
1734
|
+
"wmf": "image/wmf",
|
|
1735
|
+
"disposition-notification": "message/disposition-notification",
|
|
1736
|
+
"u8msg": "message/global",
|
|
1737
|
+
"u8dsn": "message/global-delivery-status",
|
|
1738
|
+
"u8mdn": "message/global-disposition-notification",
|
|
1739
|
+
"u8hdr": "message/global-headers",
|
|
1740
|
+
"eml": "message/rfc822",
|
|
1741
|
+
"mime": "message/rfc822",
|
|
1742
|
+
"3mf": "model/3mf",
|
|
1743
|
+
"gltf": "model/gltf+json",
|
|
1744
|
+
"glb": "model/gltf-binary",
|
|
1745
|
+
"igs": "model/iges",
|
|
1746
|
+
"iges": "model/iges",
|
|
1747
|
+
"msh": "model/mesh",
|
|
1748
|
+
"mesh": "model/mesh",
|
|
1749
|
+
"silo": "model/mesh",
|
|
1750
|
+
"mtl": "model/mtl",
|
|
1751
|
+
"obj": "model/obj",
|
|
1752
|
+
"stpz": "model/step+zip",
|
|
1753
|
+
"stpxz": "model/step-xml+zip",
|
|
1754
|
+
"stl": "model/stl",
|
|
1755
|
+
"wrl": "model/vrml",
|
|
1756
|
+
"vrml": "model/vrml",
|
|
1757
|
+
"x3db": "model/x3d+fastinfoset",
|
|
1758
|
+
"x3dbz": "model/x3d+binary",
|
|
1759
|
+
"x3dv": "model/x3d-vrml",
|
|
1760
|
+
"x3dvz": "model/x3d+vrml",
|
|
1761
|
+
"x3d": "model/x3d+xml",
|
|
1762
|
+
"x3dz": "model/x3d+xml",
|
|
1763
|
+
"appcache": "text/cache-manifest",
|
|
1764
|
+
"manifest": "text/cache-manifest",
|
|
1765
|
+
"ics": "text/calendar",
|
|
1766
|
+
"ifb": "text/calendar",
|
|
1767
|
+
"coffee": "text/coffeescript",
|
|
1768
|
+
"litcoffee": "text/coffeescript",
|
|
1769
|
+
"css": "text/css",
|
|
1770
|
+
"csv": "text/csv",
|
|
1771
|
+
"html": "text/html",
|
|
1772
|
+
"htm": "text/html",
|
|
1773
|
+
"shtml": "text/html",
|
|
1774
|
+
"jade": "text/jade",
|
|
1775
|
+
"jsx": "text/jsx",
|
|
1776
|
+
"less": "text/less",
|
|
1777
|
+
"markdown": "text/markdown",
|
|
1778
|
+
"md": "text/markdown",
|
|
1779
|
+
"mml": "text/mathml",
|
|
1780
|
+
"mdx": "text/mdx",
|
|
1781
|
+
"n3": "text/n3",
|
|
1782
|
+
"txt": "text/plain",
|
|
1783
|
+
"text": "text/plain",
|
|
1784
|
+
"conf": "text/plain",
|
|
1785
|
+
"def": "text/plain",
|
|
1786
|
+
"list": "text/plain",
|
|
1787
|
+
"log": "text/plain",
|
|
1788
|
+
"in": "text/plain",
|
|
1789
|
+
"ini": "text/plain",
|
|
1790
|
+
"dsc": "text/prs.lines.tag",
|
|
1791
|
+
"rtx": "text/richtext",
|
|
1792
|
+
"sgml": "text/sgml",
|
|
1793
|
+
"sgm": "text/sgml",
|
|
1794
|
+
"shex": "text/shex",
|
|
1795
|
+
"slim": "text/slim",
|
|
1796
|
+
"slm": "text/slim",
|
|
1797
|
+
"spdx": "text/spdx",
|
|
1798
|
+
"stylus": "text/stylus",
|
|
1799
|
+
"styl": "text/stylus",
|
|
1800
|
+
"tsv": "text/tab-separated-values",
|
|
1801
|
+
"t": "text/troff",
|
|
1802
|
+
"tr": "text/troff",
|
|
1803
|
+
"roff": "text/troff",
|
|
1804
|
+
"man": "text/troff",
|
|
1805
|
+
"me": "text/troff",
|
|
1806
|
+
"ms": "text/troff",
|
|
1807
|
+
"ttl": "text/turtle",
|
|
1808
|
+
"uri": "text/uri-list",
|
|
1809
|
+
"uris": "text/uri-list",
|
|
1810
|
+
"urls": "text/uri-list",
|
|
1811
|
+
"vcard": "text/vcard",
|
|
1812
|
+
"vtt": "text/vtt",
|
|
1813
|
+
"yaml": "text/yaml",
|
|
1814
|
+
"yml": "text/yaml",
|
|
1815
|
+
"3gp": "video/3gpp",
|
|
1816
|
+
"3g2": "video/3gpp2",
|
|
1817
|
+
"h261": "video/h261",
|
|
1818
|
+
"h263": "video/h263",
|
|
1819
|
+
"h264": "video/h264",
|
|
1820
|
+
"m4s": "video/iso.segment",
|
|
1821
|
+
"jpgv": "video/jpeg",
|
|
1822
|
+
"jpgm": "image/jpm",
|
|
1823
|
+
"mj2": "video/mj2",
|
|
1824
|
+
"mjp2": "video/mj2",
|
|
1825
|
+
"ts": "video/mp2t",
|
|
1826
|
+
"mp4": "video/mp4",
|
|
1827
|
+
"mp4v": "video/mp4",
|
|
1828
|
+
"mpg4": "video/mp4",
|
|
1829
|
+
"mpeg": "video/mpeg",
|
|
1830
|
+
"mpg": "video/mpeg",
|
|
1831
|
+
"mpe": "video/mpeg",
|
|
1832
|
+
"m1v": "video/mpeg",
|
|
1833
|
+
"m2v": "video/mpeg",
|
|
1834
|
+
"ogv": "video/ogg",
|
|
1835
|
+
"qt": "video/quicktime",
|
|
1836
|
+
"mov": "video/quicktime",
|
|
1837
|
+
"webm": "video/webm"
|
|
1838
|
+
};
|
|
1839
|
+
|
|
1840
|
+
function lookup(extn) {
|
|
1841
|
+
let tmp = ('' + extn).trim().toLowerCase();
|
|
1842
|
+
let idx = tmp.lastIndexOf('.');
|
|
1843
|
+
return mimes[!~idx ? tmp : tmp.substring(++idx)];
|
|
1844
|
+
}
|
|
1845
|
+
|
|
1846
|
+
const noop = () => {};
|
|
1847
|
+
|
|
1848
|
+
function isMatch(uri, arr) {
|
|
1849
|
+
for (let i=0; i < arr.length; i++) {
|
|
1850
|
+
if (arr[i].test(uri)) return true;
|
|
1851
|
+
}
|
|
1852
|
+
}
|
|
1853
|
+
|
|
1854
|
+
function toAssume(uri, extns) {
|
|
1855
|
+
let i=0, x, len=uri.length - 1;
|
|
1856
|
+
if (uri.charCodeAt(len) === 47) {
|
|
1857
|
+
uri = uri.substring(0, len);
|
|
1858
|
+
}
|
|
1859
|
+
|
|
1860
|
+
let arr=[], tmp=`${uri}/index`;
|
|
1861
|
+
for (; i < extns.length; i++) {
|
|
1862
|
+
x = extns[i] ? `.${extns[i]}` : '';
|
|
1863
|
+
if (uri) arr.push(uri + x);
|
|
1864
|
+
arr.push(tmp + x);
|
|
1865
|
+
}
|
|
1866
|
+
|
|
1867
|
+
return arr;
|
|
1868
|
+
}
|
|
1869
|
+
|
|
1870
|
+
function viaCache(cache, uri, extns) {
|
|
1871
|
+
let i=0, data, arr=toAssume(uri, extns);
|
|
1872
|
+
for (; i < arr.length; i++) {
|
|
1873
|
+
if (data = cache[arr[i]]) return data;
|
|
1874
|
+
}
|
|
1875
|
+
}
|
|
1876
|
+
|
|
1877
|
+
function viaLocal(dir, isEtag, uri, extns) {
|
|
1878
|
+
let i=0, arr=toAssume(uri, extns);
|
|
1879
|
+
let abs, stats, name, headers;
|
|
1880
|
+
for (; i < arr.length; i++) {
|
|
1881
|
+
abs = normalize(join(dir, name=arr[i]));
|
|
1882
|
+
if (abs.startsWith(dir) && fs.existsSync(abs)) {
|
|
1883
|
+
stats = fs.statSync(abs);
|
|
1884
|
+
if (stats.isDirectory()) continue;
|
|
1885
|
+
headers = toHeaders(name, stats, isEtag);
|
|
1886
|
+
headers['Cache-Control'] = isEtag ? 'no-cache' : 'no-store';
|
|
1887
|
+
return { abs, stats, headers };
|
|
1888
|
+
}
|
|
1889
|
+
}
|
|
1890
|
+
}
|
|
1891
|
+
|
|
1892
|
+
function is404(req, res) {
|
|
1893
|
+
return (res.statusCode=404,res.end());
|
|
1894
|
+
}
|
|
1895
|
+
|
|
1896
|
+
function send(req, res, file, stats, headers) {
|
|
1897
|
+
let code=200, tmp, opts={};
|
|
1898
|
+
headers = { ...headers };
|
|
1899
|
+
|
|
1900
|
+
for (let key in headers) {
|
|
1901
|
+
tmp = res.getHeader(key);
|
|
1902
|
+
if (tmp) headers[key] = tmp;
|
|
1903
|
+
}
|
|
1904
|
+
|
|
1905
|
+
if (tmp = res.getHeader('content-type')) {
|
|
1906
|
+
headers['Content-Type'] = tmp;
|
|
1907
|
+
}
|
|
1908
|
+
|
|
1909
|
+
if (req.headers.range) {
|
|
1910
|
+
code = 206;
|
|
1911
|
+
let [x, y] = req.headers.range.replace('bytes=', '').split('-');
|
|
1912
|
+
let end = opts.end = parseInt(y, 10) || stats.size - 1;
|
|
1913
|
+
let start = opts.start = parseInt(x, 10) || 0;
|
|
1914
|
+
|
|
1915
|
+
if (start >= stats.size || end >= stats.size) {
|
|
1916
|
+
res.setHeader('Content-Range', `bytes */${stats.size}`);
|
|
1917
|
+
res.statusCode = 416;
|
|
1918
|
+
return res.end();
|
|
1919
|
+
}
|
|
1920
|
+
|
|
1921
|
+
headers['Content-Range'] = `bytes ${start}-${end}/${stats.size}`;
|
|
1922
|
+
headers['Content-Length'] = (end - start + 1);
|
|
1923
|
+
headers['Accept-Ranges'] = 'bytes';
|
|
1924
|
+
}
|
|
1925
|
+
|
|
1926
|
+
res.writeHead(code, headers);
|
|
1927
|
+
fs.createReadStream(file, opts).pipe(res);
|
|
1928
|
+
}
|
|
1929
|
+
|
|
1930
|
+
const ENCODING = {
|
|
1931
|
+
'.br': 'br',
|
|
1932
|
+
'.gz': 'gzip',
|
|
1933
|
+
};
|
|
1934
|
+
|
|
1935
|
+
function toHeaders(name, stats, isEtag) {
|
|
1936
|
+
let enc = ENCODING[name.slice(-3)];
|
|
1937
|
+
|
|
1938
|
+
let ctype = lookup(name.slice(0, enc && -3)) || '';
|
|
1939
|
+
if (ctype === 'text/html') ctype += ';charset=utf-8';
|
|
1940
|
+
|
|
1941
|
+
let headers = {
|
|
1942
|
+
'Content-Length': stats.size,
|
|
1943
|
+
'Content-Type': ctype,
|
|
1944
|
+
'Last-Modified': stats.mtime.toUTCString(),
|
|
1945
|
+
};
|
|
1946
|
+
|
|
1947
|
+
if (enc) headers['Content-Encoding'] = enc;
|
|
1948
|
+
if (isEtag) headers['ETag'] = `W/"${stats.size}-${stats.mtime.getTime()}"`;
|
|
1949
|
+
|
|
1950
|
+
return headers;
|
|
1951
|
+
}
|
|
1952
|
+
|
|
1953
|
+
function sirv (dir, opts) {
|
|
1954
|
+
dir = resolve$1(dir || '.');
|
|
1955
|
+
|
|
1956
|
+
let isNotFound = opts.onNoMatch || is404;
|
|
1957
|
+
let setHeaders = opts.setHeaders || noop;
|
|
1958
|
+
|
|
1959
|
+
let extensions = opts.extensions || ['html', 'htm'];
|
|
1960
|
+
let gzips = opts.gzip && extensions.map(x => `${x}.gz`).concat('gz');
|
|
1961
|
+
let brots = opts.brotli && extensions.map(x => `${x}.br`).concat('br');
|
|
1962
|
+
|
|
1963
|
+
const FILES = {};
|
|
1964
|
+
|
|
1965
|
+
let fallback = '/';
|
|
1966
|
+
let isEtag = !!opts.etag;
|
|
1967
|
+
let isSPA = !!opts.single;
|
|
1968
|
+
if (typeof opts.single === 'string') {
|
|
1969
|
+
let idx = opts.single.lastIndexOf('.');
|
|
1970
|
+
fallback += !!~idx ? opts.single.substring(0, idx) : opts.single;
|
|
1971
|
+
}
|
|
1972
|
+
|
|
1973
|
+
let ignores = [];
|
|
1974
|
+
if (opts.ignores !== false) {
|
|
1975
|
+
ignores.push(/[/]([A-Za-z\s\d~$._-]+\.\w+){1,}$/); // any extn
|
|
1976
|
+
if (opts.dotfiles) ignores.push(/\/\.\w/);
|
|
1977
|
+
else ignores.push(/\/\.well-known/);
|
|
1978
|
+
[].concat(opts.ignores || []).forEach(x => {
|
|
1979
|
+
ignores.push(new RegExp(x, 'i'));
|
|
1980
|
+
});
|
|
1981
|
+
}
|
|
1982
|
+
|
|
1983
|
+
let cc = opts.maxAge != null && `public,max-age=${opts.maxAge}`;
|
|
1984
|
+
if (cc && opts.immutable) cc += ',immutable';
|
|
1985
|
+
else if (cc && opts.maxAge === 0) cc += ',must-revalidate';
|
|
1986
|
+
|
|
1987
|
+
if (!opts.dev) {
|
|
1988
|
+
totalist(dir, (name, abs, stats) => {
|
|
1989
|
+
if (/\.well-known[\\+\/]/.test(name)) ; // keep
|
|
1990
|
+
else if (!opts.dotfiles && /(^\.|[\\+|\/+]\.)/.test(name)) return;
|
|
1991
|
+
|
|
1992
|
+
let headers = toHeaders(name, stats, isEtag);
|
|
1993
|
+
if (cc) headers['Cache-Control'] = cc;
|
|
1994
|
+
|
|
1995
|
+
FILES['/' + name.normalize().replace(/\\+/g, '/')] = { abs, stats, headers };
|
|
1996
|
+
});
|
|
1997
|
+
}
|
|
1998
|
+
|
|
1999
|
+
let lookup = opts.dev ? viaLocal.bind(0, dir, isEtag) : viaCache.bind(0, FILES);
|
|
2000
|
+
|
|
2001
|
+
return function (req, res, next) {
|
|
2002
|
+
let extns = [''];
|
|
2003
|
+
let pathname = parse(req).pathname;
|
|
2004
|
+
let val = req.headers['accept-encoding'] || '';
|
|
2005
|
+
if (gzips && val.includes('gzip')) extns.unshift(...gzips);
|
|
2006
|
+
if (brots && /(br|brotli)/i.test(val)) extns.unshift(...brots);
|
|
2007
|
+
extns.push(...extensions); // [...br, ...gz, orig, ...exts]
|
|
2008
|
+
|
|
2009
|
+
if (pathname.indexOf('%') !== -1) {
|
|
2010
|
+
try { pathname = decodeURIComponent(pathname); }
|
|
2011
|
+
catch (err) { /* malform uri */ }
|
|
2012
|
+
}
|
|
2013
|
+
|
|
2014
|
+
let data = lookup(pathname, extns) || isSPA && !isMatch(pathname, ignores) && lookup(fallback, extns);
|
|
2015
|
+
if (!data) return next ? next() : isNotFound(req, res);
|
|
2016
|
+
|
|
2017
|
+
if (isEtag && req.headers['if-none-match'] === data.headers['ETag']) {
|
|
2018
|
+
res.writeHead(304);
|
|
2019
|
+
return res.end();
|
|
2020
|
+
}
|
|
2021
|
+
|
|
2022
|
+
if (gzips || brots) {
|
|
2023
|
+
res.setHeader('Vary', 'Accept-Encoding');
|
|
2024
|
+
}
|
|
2025
|
+
|
|
2026
|
+
setHeaders(res, pathname, data.stats);
|
|
2027
|
+
send(req, res, data.abs, data.stats, data.headers);
|
|
2028
|
+
};
|
|
2029
|
+
}
|
|
2030
|
+
|
|
2031
|
+
// in `vite dev` and `vite preview`, we use a fake asset path so that we can
|
|
2032
|
+
// serve local assets while verifying that requests are correctly prefixed
|
|
2033
|
+
const SVELTE_KIT_ASSETS = '/_svelte_kit_assets';
|
|
2034
|
+
|
|
2035
|
+
// Vite doesn't expose this so we just copy the list for now
|
|
2036
|
+
// https://github.com/vitejs/vite/blob/3edd1af56e980aef56641a5a51cf2932bb580d41/packages/vite/src/node/plugins/css.ts#L96
|
|
2037
|
+
const style_pattern = /\.(css|less|sass|scss|styl|stylus|pcss|postcss)$/;
|
|
2038
|
+
|
|
2039
|
+
const cwd$1 = process.cwd();
|
|
2040
|
+
|
|
2041
|
+
/**
|
|
2042
|
+
* @param {import('vite').ViteDevServer} vite
|
|
2043
|
+
* @param {import('vite').ResolvedConfig} vite_config
|
|
2044
|
+
* @param {import('types').ValidatedConfig} svelte_config
|
|
2045
|
+
* @return {Promise<Promise<() => void>>}
|
|
2046
|
+
*/
|
|
2047
|
+
async function dev(vite, vite_config, svelte_config) {
|
|
2048
|
+
installPolyfills();
|
|
2049
|
+
|
|
2050
|
+
init(svelte_config);
|
|
2051
|
+
|
|
2052
|
+
const runtime = get_runtime_path(svelte_config.kit);
|
|
2053
|
+
|
|
2054
|
+
process.env.VITE_SVELTEKIT_APP_VERSION_POLL_INTERVAL = '0';
|
|
2055
|
+
|
|
2056
|
+
/** @type {import('types').Respond} */
|
|
2057
|
+
const respond = (await import(`${runtime}/server/index.js`)).respond;
|
|
2058
|
+
|
|
2059
|
+
/** @type {import('types').SSRManifest} */
|
|
2060
|
+
let manifest;
|
|
2061
|
+
|
|
2062
|
+
function update_manifest() {
|
|
2063
|
+
const { manifest_data } = update(svelte_config);
|
|
2064
|
+
|
|
2065
|
+
manifest = {
|
|
2066
|
+
appDir: svelte_config.kit.appDir,
|
|
2067
|
+
assets: new Set(manifest_data.assets.map((asset) => asset.file)),
|
|
2068
|
+
mimeTypes: get_mime_lookup(manifest_data),
|
|
2069
|
+
_: {
|
|
2070
|
+
entry: {
|
|
2071
|
+
file: `/@fs${runtime}/client/start.js`,
|
|
2072
|
+
imports: [],
|
|
2073
|
+
stylesheets: []
|
|
2074
|
+
},
|
|
2075
|
+
nodes: manifest_data.components.map((id, index) => {
|
|
2076
|
+
return async () => {
|
|
2077
|
+
const url = id.startsWith('..') ? `/@fs${path__default.posix.resolve(id)}` : `/${id}`;
|
|
2078
|
+
|
|
2079
|
+
const module = /** @type {import('types').SSRComponent} */ (
|
|
2080
|
+
await vite.ssrLoadModule(url, { fixStacktrace: false })
|
|
2081
|
+
);
|
|
2082
|
+
|
|
2083
|
+
return {
|
|
2084
|
+
module,
|
|
2085
|
+
index,
|
|
2086
|
+
file: url.endsWith('.svelte') ? url : url + '?import',
|
|
2087
|
+
imports: [],
|
|
2088
|
+
stylesheets: [],
|
|
2089
|
+
// in dev we inline all styles to avoid FOUC
|
|
2090
|
+
inline_styles: async () => {
|
|
2091
|
+
const node = await vite.moduleGraph.getModuleByUrl(url);
|
|
2092
|
+
|
|
2093
|
+
if (!node) throw new Error(`Could not find node for ${url}`);
|
|
2094
|
+
|
|
2095
|
+
const deps = new Set();
|
|
2096
|
+
await find_deps(vite, node, deps);
|
|
2097
|
+
|
|
2098
|
+
/** @type {Record<string, string>} */
|
|
2099
|
+
const styles = {};
|
|
2100
|
+
|
|
2101
|
+
for (const dep of deps) {
|
|
2102
|
+
const parsed = new URL$1(dep.url, 'http://localhost/');
|
|
2103
|
+
const query = parsed.searchParams;
|
|
2104
|
+
|
|
2105
|
+
if (
|
|
2106
|
+
style_pattern.test(dep.file) ||
|
|
2107
|
+
(query.has('svelte') && query.get('type') === 'style')
|
|
2108
|
+
) {
|
|
2109
|
+
try {
|
|
2110
|
+
const mod = await vite.ssrLoadModule(dep.url, { fixStacktrace: false });
|
|
2111
|
+
styles[dep.url] = mod.default;
|
|
2112
|
+
} catch {
|
|
2113
|
+
// this can happen with dynamically imported modules, I think
|
|
2114
|
+
// because the Vite module graph doesn't distinguish between
|
|
2115
|
+
// static and dynamic imports? TODO investigate, submit fix
|
|
2116
|
+
}
|
|
2117
|
+
}
|
|
2118
|
+
}
|
|
2119
|
+
|
|
2120
|
+
return styles;
|
|
2121
|
+
}
|
|
2122
|
+
};
|
|
2123
|
+
};
|
|
2124
|
+
}),
|
|
2125
|
+
routes: manifest_data.routes.map((route) => {
|
|
2126
|
+
const { pattern, names, types } = parse_route_id(route.id);
|
|
2127
|
+
|
|
2128
|
+
if (route.type === 'page') {
|
|
2129
|
+
return {
|
|
2130
|
+
type: 'page',
|
|
2131
|
+
id: route.id,
|
|
2132
|
+
pattern,
|
|
2133
|
+
names,
|
|
2134
|
+
types,
|
|
2135
|
+
shadow: route.shadow
|
|
2136
|
+
? async () => {
|
|
2137
|
+
const url = path__default.resolve(cwd$1, /** @type {string} */ (route.shadow));
|
|
2138
|
+
return await vite.ssrLoadModule(url, { fixStacktrace: false });
|
|
2139
|
+
}
|
|
2140
|
+
: null,
|
|
2141
|
+
a: route.a.map((id) => (id ? manifest_data.components.indexOf(id) : undefined)),
|
|
2142
|
+
b: route.b.map((id) => (id ? manifest_data.components.indexOf(id) : undefined))
|
|
2143
|
+
};
|
|
2144
|
+
}
|
|
2145
|
+
|
|
2146
|
+
return {
|
|
2147
|
+
type: 'endpoint',
|
|
2148
|
+
id: route.id,
|
|
2149
|
+
pattern,
|
|
2150
|
+
names,
|
|
2151
|
+
types,
|
|
2152
|
+
load: async () => {
|
|
2153
|
+
const url = path__default.resolve(cwd$1, route.file);
|
|
2154
|
+
return await vite.ssrLoadModule(url, { fixStacktrace: false });
|
|
2155
|
+
}
|
|
2156
|
+
};
|
|
2157
|
+
}),
|
|
2158
|
+
matchers: async () => {
|
|
2159
|
+
/** @type {Record<string, import('types').ParamMatcher>} */
|
|
2160
|
+
const matchers = {};
|
|
2161
|
+
|
|
2162
|
+
for (const key in manifest_data.matchers) {
|
|
2163
|
+
const file = manifest_data.matchers[key];
|
|
2164
|
+
const url = path__default.resolve(cwd$1, file);
|
|
2165
|
+
const module = await vite.ssrLoadModule(url, { fixStacktrace: false });
|
|
2166
|
+
|
|
2167
|
+
if (module.match) {
|
|
2168
|
+
matchers[key] = module.match;
|
|
2169
|
+
} else {
|
|
2170
|
+
throw new Error(`${file} does not export a \`match\` function`);
|
|
2171
|
+
}
|
|
2172
|
+
}
|
|
2173
|
+
|
|
2174
|
+
return matchers;
|
|
2175
|
+
}
|
|
2176
|
+
}
|
|
2177
|
+
};
|
|
2178
|
+
}
|
|
2179
|
+
|
|
2180
|
+
/** @param {Error} error */
|
|
2181
|
+
function fix_stack_trace(error) {
|
|
2182
|
+
return error.stack ? vite.ssrRewriteStacktrace(error.stack) : error.stack;
|
|
2183
|
+
}
|
|
2184
|
+
|
|
2185
|
+
update_manifest();
|
|
2186
|
+
|
|
2187
|
+
for (const event of ['add', 'unlink']) {
|
|
2188
|
+
vite.watcher.on(event, (file) => {
|
|
2189
|
+
if (file.startsWith(svelte_config.kit.files.routes + path__default.sep)) {
|
|
2190
|
+
update_manifest();
|
|
2191
|
+
}
|
|
2192
|
+
});
|
|
2193
|
+
}
|
|
2194
|
+
|
|
2195
|
+
const assets = svelte_config.kit.paths.assets ? SVELTE_KIT_ASSETS : svelte_config.kit.paths.base;
|
|
2196
|
+
const asset_server = sirv(svelte_config.kit.files.assets, {
|
|
2197
|
+
dev: true,
|
|
2198
|
+
etag: true,
|
|
2199
|
+
maxAge: 0,
|
|
2200
|
+
extensions: []
|
|
2201
|
+
});
|
|
2202
|
+
|
|
2203
|
+
return () => {
|
|
2204
|
+
const serve_static_middleware = vite.middlewares.stack.find(
|
|
2205
|
+
(middleware) =>
|
|
2206
|
+
/** @type {function} */ (middleware.handle).name === 'viteServeStaticMiddleware'
|
|
2207
|
+
);
|
|
2208
|
+
|
|
2209
|
+
remove_html_middlewares(vite.middlewares);
|
|
2210
|
+
|
|
2211
|
+
vite.middlewares.use(async (req, res) => {
|
|
2212
|
+
try {
|
|
2213
|
+
if (!req.url || !req.method) throw new Error('Incomplete request');
|
|
2214
|
+
|
|
2215
|
+
const base = `${vite.config.server.https ? 'https' : 'http'}://${
|
|
2216
|
+
req.headers[':authority'] || req.headers.host
|
|
2217
|
+
}`;
|
|
2218
|
+
|
|
2219
|
+
const decoded = decodeURI(new URL$1(base + req.url).pathname);
|
|
2220
|
+
|
|
2221
|
+
if (decoded.startsWith(assets)) {
|
|
2222
|
+
const pathname = decoded.slice(assets.length);
|
|
2223
|
+
const file = svelte_config.kit.files.assets + pathname;
|
|
2224
|
+
|
|
2225
|
+
if (fs__default.existsSync(file) && !fs__default.statSync(file).isDirectory()) {
|
|
2226
|
+
if (has_correct_case(file, svelte_config.kit.files.assets)) {
|
|
2227
|
+
req.url = encodeURI(pathname); // don't need query/hash
|
|
2228
|
+
asset_server(req, res);
|
|
2229
|
+
return;
|
|
2230
|
+
}
|
|
2231
|
+
}
|
|
2232
|
+
}
|
|
2233
|
+
|
|
2234
|
+
const file = posixify(path__default.resolve(decoded.slice(1)));
|
|
2235
|
+
const is_file = fs__default.existsSync(file) && !fs__default.statSync(file).isDirectory();
|
|
2236
|
+
const allowed =
|
|
2237
|
+
!vite_config.server.fs.strict ||
|
|
2238
|
+
vite_config.server.fs.allow.some((dir) => file.startsWith(dir));
|
|
2239
|
+
|
|
2240
|
+
if (is_file && allowed) {
|
|
2241
|
+
// @ts-expect-error
|
|
2242
|
+
serve_static_middleware.handle(req, res);
|
|
2243
|
+
return;
|
|
2244
|
+
}
|
|
2245
|
+
|
|
2246
|
+
if (!decoded.startsWith(svelte_config.kit.paths.base)) {
|
|
2247
|
+
return not_found(
|
|
2248
|
+
res,
|
|
2249
|
+
`Not found (did you mean ${svelte_config.kit.paths.base + req.url}?)`
|
|
2250
|
+
);
|
|
2251
|
+
}
|
|
2252
|
+
|
|
2253
|
+
/** @type {Partial<import('types').Hooks>} */
|
|
2254
|
+
const user_hooks = resolve_entry(svelte_config.kit.files.hooks)
|
|
2255
|
+
? await vite.ssrLoadModule(`/${svelte_config.kit.files.hooks}`, {
|
|
2256
|
+
fixStacktrace: false
|
|
2257
|
+
})
|
|
2258
|
+
: {};
|
|
2259
|
+
|
|
2260
|
+
const handle = user_hooks.handle || (({ event, resolve }) => resolve(event));
|
|
2261
|
+
|
|
2262
|
+
/** @type {import('types').Hooks} */
|
|
2263
|
+
const hooks = {
|
|
2264
|
+
getSession: user_hooks.getSession || (() => ({})),
|
|
2265
|
+
handle,
|
|
2266
|
+
handleError:
|
|
2267
|
+
user_hooks.handleError ||
|
|
2268
|
+
(({ /** @type {Error & { frame?: string }} */ error }) => {
|
|
2269
|
+
console.error($.bold().red(error.message));
|
|
2270
|
+
if (error.frame) {
|
|
2271
|
+
console.error($.gray(error.frame));
|
|
2272
|
+
}
|
|
2273
|
+
if (error.stack) {
|
|
2274
|
+
console.error($.gray(error.stack));
|
|
2275
|
+
}
|
|
2276
|
+
}),
|
|
2277
|
+
externalFetch: user_hooks.externalFetch || fetch
|
|
2278
|
+
};
|
|
2279
|
+
|
|
2280
|
+
if (/** @type {any} */ (hooks).getContext) {
|
|
2281
|
+
// TODO remove this for 1.0
|
|
2282
|
+
throw new Error(
|
|
2283
|
+
'The getContext hook has been removed. See https://kit.svelte.dev/docs/hooks'
|
|
2284
|
+
);
|
|
2285
|
+
}
|
|
2286
|
+
|
|
2287
|
+
if (/** @type {any} */ (hooks).serverFetch) {
|
|
2288
|
+
// TODO remove this for 1.0
|
|
2289
|
+
throw new Error('The serverFetch hook has been renamed to externalFetch.');
|
|
2290
|
+
}
|
|
2291
|
+
|
|
2292
|
+
// TODO the / prefix will probably fail if outDir is outside the cwd (which
|
|
2293
|
+
// could be the case in a monorepo setup), but without it these modules
|
|
2294
|
+
// can get loaded twice via different URLs, which causes failures. Might
|
|
2295
|
+
// require changes to Vite to fix
|
|
2296
|
+
const { default: root } = await vite.ssrLoadModule(
|
|
2297
|
+
`/${posixify(path__default.relative(cwd$1, `${svelte_config.kit.outDir}/generated/root.svelte`))}`,
|
|
2298
|
+
{ fixStacktrace: false }
|
|
2299
|
+
);
|
|
2300
|
+
|
|
2301
|
+
const paths = await vite.ssrLoadModule(
|
|
2302
|
+
true
|
|
2303
|
+
? `/${posixify(path__default.relative(cwd$1, `${svelte_config.kit.outDir}/runtime/paths.js`))}`
|
|
2304
|
+
: `/@fs${runtime}/paths.js`,
|
|
2305
|
+
{ fixStacktrace: false }
|
|
2306
|
+
);
|
|
2307
|
+
|
|
2308
|
+
paths.set_paths({
|
|
2309
|
+
base: svelte_config.kit.paths.base,
|
|
2310
|
+
assets
|
|
2311
|
+
});
|
|
2312
|
+
|
|
2313
|
+
let request;
|
|
2314
|
+
|
|
2315
|
+
try {
|
|
2316
|
+
request = await getRequest(base, req);
|
|
2317
|
+
} catch (/** @type {any} */ err) {
|
|
2318
|
+
res.statusCode = err.status || 400;
|
|
2319
|
+
return res.end(err.reason || 'Invalid request body');
|
|
2320
|
+
}
|
|
2321
|
+
|
|
2322
|
+
const template = load_template(cwd$1, svelte_config);
|
|
2323
|
+
|
|
2324
|
+
const rendered = await respond(
|
|
2325
|
+
request,
|
|
2326
|
+
{
|
|
2327
|
+
csp: svelte_config.kit.csp,
|
|
2328
|
+
dev: true,
|
|
2329
|
+
get_stack: (error) => {
|
|
2330
|
+
return fix_stack_trace(error);
|
|
2331
|
+
},
|
|
2332
|
+
handle_error: (error, event) => {
|
|
2333
|
+
hooks.handleError({
|
|
2334
|
+
error: new Proxy(error, {
|
|
2335
|
+
get: (target, property) => {
|
|
2336
|
+
if (property === 'stack') {
|
|
2337
|
+
return fix_stack_trace(error);
|
|
2338
|
+
}
|
|
2339
|
+
|
|
2340
|
+
return Reflect.get(target, property, target);
|
|
2341
|
+
}
|
|
2342
|
+
}),
|
|
2343
|
+
event,
|
|
2344
|
+
|
|
2345
|
+
// TODO remove for 1.0
|
|
2346
|
+
// @ts-expect-error
|
|
2347
|
+
get request() {
|
|
2348
|
+
throw new Error(
|
|
2349
|
+
'request in handleError has been replaced with event. See https://github.com/sveltejs/kit/pull/3384 for details'
|
|
2350
|
+
);
|
|
2351
|
+
}
|
|
2352
|
+
});
|
|
2353
|
+
},
|
|
2354
|
+
hooks,
|
|
2355
|
+
hydrate: svelte_config.kit.browser.hydrate,
|
|
2356
|
+
manifest,
|
|
2357
|
+
method_override: svelte_config.kit.methodOverride,
|
|
2358
|
+
paths: {
|
|
2359
|
+
base: svelte_config.kit.paths.base,
|
|
2360
|
+
assets
|
|
2361
|
+
},
|
|
2362
|
+
prefix: '',
|
|
2363
|
+
prerender: {
|
|
2364
|
+
default: svelte_config.kit.prerender.default,
|
|
2365
|
+
enabled: svelte_config.kit.prerender.enabled
|
|
2366
|
+
},
|
|
2367
|
+
read: (file) => fs__default.readFileSync(path__default.join(svelte_config.kit.files.assets, file)),
|
|
2368
|
+
root,
|
|
2369
|
+
router: svelte_config.kit.browser.router,
|
|
2370
|
+
template: ({ head, body, assets, nonce }) => {
|
|
2371
|
+
return (
|
|
2372
|
+
template
|
|
2373
|
+
.replace(/%sveltekit\.assets%/g, assets)
|
|
2374
|
+
.replace(/%sveltekit\.nonce%/g, nonce)
|
|
2375
|
+
// head and body must be replaced last, in case someone tries to sneak in %sveltekit.assets% etc
|
|
2376
|
+
.replace('%sveltekit.head%', () => head)
|
|
2377
|
+
.replace('%sveltekit.body%', () => body)
|
|
2378
|
+
);
|
|
2379
|
+
},
|
|
2380
|
+
template_contains_nonce: template.includes('%sveltekit.nonce%'),
|
|
2381
|
+
trailing_slash: svelte_config.kit.trailingSlash
|
|
2382
|
+
},
|
|
2383
|
+
{
|
|
2384
|
+
getClientAddress: () => {
|
|
2385
|
+
const { remoteAddress } = req.socket;
|
|
2386
|
+
if (remoteAddress) return remoteAddress;
|
|
2387
|
+
throw new Error('Could not determine clientAddress');
|
|
2388
|
+
}
|
|
2389
|
+
}
|
|
2390
|
+
);
|
|
2391
|
+
|
|
2392
|
+
if (rendered.status === 404) {
|
|
2393
|
+
// @ts-expect-error
|
|
2394
|
+
serve_static_middleware.handle(req, res, () => {
|
|
2395
|
+
setResponse(res, rendered);
|
|
2396
|
+
});
|
|
2397
|
+
} else {
|
|
2398
|
+
setResponse(res, rendered);
|
|
2399
|
+
}
|
|
2400
|
+
} catch (e) {
|
|
2401
|
+
const error = coalesce_to_error(e);
|
|
2402
|
+
vite.ssrFixStacktrace(error);
|
|
2403
|
+
res.statusCode = 500;
|
|
2404
|
+
res.end(error.stack);
|
|
2405
|
+
}
|
|
2406
|
+
});
|
|
2407
|
+
};
|
|
2408
|
+
}
|
|
2409
|
+
|
|
2410
|
+
/** @param {import('http').ServerResponse} res */
|
|
2411
|
+
function not_found(res, message) {
|
|
2412
|
+
res.statusCode = 404;
|
|
2413
|
+
res.end(message);
|
|
2414
|
+
}
|
|
2415
|
+
|
|
2416
|
+
/**
|
|
2417
|
+
* @param {import('connect').Server} server
|
|
2418
|
+
*/
|
|
2419
|
+
function remove_html_middlewares(server) {
|
|
2420
|
+
const html_middlewares = [
|
|
2421
|
+
'viteIndexHtmlMiddleware',
|
|
2422
|
+
'vite404Middleware',
|
|
2423
|
+
'viteSpaFallbackMiddleware',
|
|
2424
|
+
'viteServeStaticMiddleware'
|
|
2425
|
+
];
|
|
2426
|
+
for (let i = server.stack.length - 1; i > 0; i--) {
|
|
2427
|
+
// @ts-expect-error using internals until https://github.com/vitejs/vite/pull/4640 is merged
|
|
2428
|
+
if (html_middlewares.includes(server.stack[i].handle.name)) {
|
|
2429
|
+
server.stack.splice(i, 1);
|
|
2430
|
+
}
|
|
2431
|
+
}
|
|
2432
|
+
}
|
|
2433
|
+
|
|
2434
|
+
/**
|
|
2435
|
+
* @param {import('vite').ViteDevServer} vite
|
|
2436
|
+
* @param {import('vite').ModuleNode} node
|
|
2437
|
+
* @param {Set<import('vite').ModuleNode>} deps
|
|
2438
|
+
*/
|
|
2439
|
+
async function find_deps(vite, node, deps) {
|
|
2440
|
+
// since `ssrTransformResult.deps` contains URLs instead of `ModuleNode`s, this process is asynchronous.
|
|
2441
|
+
// instead of using `await`, we resolve all branches in parallel.
|
|
2442
|
+
/** @type {Promise<void>[]} */
|
|
2443
|
+
const branches = [];
|
|
2444
|
+
|
|
2445
|
+
/** @param {import('vite').ModuleNode} node */
|
|
2446
|
+
async function add(node) {
|
|
2447
|
+
if (!deps.has(node)) {
|
|
2448
|
+
deps.add(node);
|
|
2449
|
+
await find_deps(vite, node, deps);
|
|
2450
|
+
}
|
|
2451
|
+
}
|
|
2452
|
+
|
|
2453
|
+
/** @param {string} url */
|
|
2454
|
+
async function add_by_url(url) {
|
|
2455
|
+
const node = await vite.moduleGraph.getModuleByUrl(url);
|
|
2456
|
+
|
|
2457
|
+
if (node) {
|
|
2458
|
+
await add(node);
|
|
2459
|
+
}
|
|
2460
|
+
}
|
|
2461
|
+
|
|
2462
|
+
if (node.ssrTransformResult) {
|
|
2463
|
+
if (node.ssrTransformResult.deps) {
|
|
2464
|
+
node.ssrTransformResult.deps.forEach((url) => branches.push(add_by_url(url)));
|
|
2465
|
+
}
|
|
2466
|
+
|
|
2467
|
+
if (node.ssrTransformResult.dynamicDeps) {
|
|
2468
|
+
node.ssrTransformResult.dynamicDeps.forEach((url) => branches.push(add_by_url(url)));
|
|
2469
|
+
}
|
|
2470
|
+
} else {
|
|
2471
|
+
node.importedModules.forEach((node) => branches.push(add(node)));
|
|
2472
|
+
}
|
|
2473
|
+
|
|
2474
|
+
await Promise.all(branches);
|
|
2475
|
+
}
|
|
2476
|
+
|
|
2477
|
+
/**
|
|
2478
|
+
* Determine if a file is being requested with the correct case,
|
|
2479
|
+
* to ensure consistent behaviour between dev and prod and across
|
|
2480
|
+
* operating systems. Note that we can't use realpath here,
|
|
2481
|
+
* because we don't want to follow symlinks
|
|
2482
|
+
* @param {string} file
|
|
2483
|
+
* @param {string} assets
|
|
2484
|
+
* @returns {boolean}
|
|
2485
|
+
*/
|
|
2486
|
+
function has_correct_case(file, assets) {
|
|
2487
|
+
if (file === assets) return true;
|
|
2488
|
+
|
|
2489
|
+
const parent = path__default.dirname(file);
|
|
2490
|
+
|
|
2491
|
+
if (fs__default.readdirSync(parent).includes(path__default.basename(file))) {
|
|
2492
|
+
return has_correct_case(parent, assets);
|
|
2493
|
+
}
|
|
2494
|
+
|
|
2495
|
+
return false;
|
|
2496
|
+
}
|
|
2497
|
+
|
|
2498
|
+
/**
|
|
2499
|
+
* Generates the data used to write the server-side manifest.js file. This data is used in the Vite
|
|
2500
|
+
* build process, to power routing, etc.
|
|
2501
|
+
* @param {{
|
|
2502
|
+
* build_data: import('types').BuildData;
|
|
2503
|
+
* relative_path: string;
|
|
2504
|
+
* routes: import('types').RouteData[];
|
|
2505
|
+
* format?: 'esm' | 'cjs'
|
|
2506
|
+
* }} opts
|
|
2507
|
+
*/
|
|
2508
|
+
function generate_manifest({ build_data, relative_path, routes, format = 'esm' }) {
|
|
2509
|
+
/** @typedef {{ index: number, path: string }} LookupEntry */
|
|
2510
|
+
/** @type {Map<string, LookupEntry>} */
|
|
2511
|
+
const bundled_nodes = new Map();
|
|
2512
|
+
|
|
2513
|
+
// 0 and 1 are special, they correspond to the root layout and root error nodes
|
|
2514
|
+
bundled_nodes.set(build_data.manifest_data.components[0], {
|
|
2515
|
+
path: `${relative_path}/nodes/0.js`,
|
|
2516
|
+
index: 0
|
|
2517
|
+
});
|
|
2518
|
+
|
|
2519
|
+
bundled_nodes.set(build_data.manifest_data.components[1], {
|
|
2520
|
+
path: `${relative_path}/nodes/1.js`,
|
|
2521
|
+
index: 1
|
|
2522
|
+
});
|
|
2523
|
+
|
|
2524
|
+
routes.forEach((route) => {
|
|
2525
|
+
if (route.type === 'page') {
|
|
2526
|
+
[...route.a, ...route.b].forEach((component) => {
|
|
2527
|
+
if (component && !bundled_nodes.has(component)) {
|
|
2528
|
+
const i = build_data.manifest_data.components.indexOf(component);
|
|
2529
|
+
|
|
2530
|
+
bundled_nodes.set(component, {
|
|
2531
|
+
path: `${relative_path}/nodes/${i}.js`,
|
|
2532
|
+
index: bundled_nodes.size
|
|
2533
|
+
});
|
|
2534
|
+
}
|
|
2535
|
+
});
|
|
2536
|
+
}
|
|
2537
|
+
});
|
|
2538
|
+
|
|
2539
|
+
/** @type {(path: string) => string} */
|
|
2540
|
+
const load =
|
|
2541
|
+
format === 'esm'
|
|
2542
|
+
? (path) => `import('${path}')`
|
|
2543
|
+
: (path) => `Promise.resolve().then(() => require('${path}'))`;
|
|
2544
|
+
|
|
2545
|
+
/** @type {(path: string) => string} */
|
|
2546
|
+
const loader = (path) => `() => ${load(path)}`;
|
|
2547
|
+
|
|
2548
|
+
const assets = build_data.manifest_data.assets.map((asset) => asset.file);
|
|
2549
|
+
if (build_data.service_worker) {
|
|
2550
|
+
assets.push(build_data.service_worker);
|
|
2551
|
+
}
|
|
2552
|
+
|
|
2553
|
+
/** @param {string | undefined} id */
|
|
2554
|
+
const get_index = (id) => id && /** @type {LookupEntry} */ (bundled_nodes.get(id)).index;
|
|
2555
|
+
|
|
2556
|
+
const matchers = new Set();
|
|
2557
|
+
|
|
2558
|
+
// prettier-ignore
|
|
2559
|
+
return `{
|
|
2560
|
+
appDir: ${s(build_data.app_dir)},
|
|
2561
|
+
assets: new Set(${s(assets)}),
|
|
2562
|
+
mimeTypes: ${s(get_mime_lookup(build_data.manifest_data))},
|
|
2563
|
+
_: {
|
|
2564
|
+
entry: ${s(build_data.client.entry)},
|
|
2565
|
+
nodes: [
|
|
2566
|
+
${Array.from(bundled_nodes.values()).map(node => loader(node.path)).join(',\n\t\t\t\t')}
|
|
2567
|
+
],
|
|
2568
|
+
routes: [
|
|
2569
|
+
${routes.map(route => {
|
|
2570
|
+
const { pattern, names, types } = parse_route_id(route.id);
|
|
2571
|
+
|
|
2572
|
+
types.forEach(type => {
|
|
2573
|
+
if (type) matchers.add(type);
|
|
2574
|
+
});
|
|
2575
|
+
|
|
2576
|
+
if (route.type === 'page') {
|
|
2577
|
+
return `{
|
|
2578
|
+
type: 'page',
|
|
2579
|
+
id: ${s(route.id)},
|
|
2580
|
+
pattern: ${pattern},
|
|
2581
|
+
names: ${s(names)},
|
|
2582
|
+
types: ${s(types)},
|
|
2583
|
+
path: ${route.path ? s(route.path) : null},
|
|
2584
|
+
shadow: ${route.shadow ? loader(`${relative_path}/${build_data.server.vite_manifest[route.shadow].file}`) : null},
|
|
2585
|
+
a: ${s(route.a.map(get_index))},
|
|
2586
|
+
b: ${s(route.b.map(get_index))}
|
|
2587
|
+
}`.replace(/^\t\t/gm, '');
|
|
2588
|
+
} else {
|
|
2589
|
+
if (!build_data.server.vite_manifest[route.file]) {
|
|
2590
|
+
// this is necessary in cases where a .css file snuck in —
|
|
2591
|
+
// perhaps it would be better to disallow these (and others?)
|
|
2592
|
+
return null;
|
|
2593
|
+
}
|
|
2594
|
+
|
|
2595
|
+
return `{
|
|
2596
|
+
type: 'endpoint',
|
|
2597
|
+
id: ${s(route.id)},
|
|
2598
|
+
pattern: ${pattern},
|
|
2599
|
+
names: ${s(names)},
|
|
2600
|
+
types: ${s(types)},
|
|
2601
|
+
load: ${loader(`${relative_path}/${build_data.server.vite_manifest[route.file].file}`)}
|
|
2602
|
+
}`.replace(/^\t\t/gm, '');
|
|
2603
|
+
}
|
|
2604
|
+
}).filter(Boolean).join(',\n\t\t\t\t')}
|
|
2605
|
+
],
|
|
2606
|
+
matchers: async () => {
|
|
2607
|
+
${Array.from(matchers).map(type => `const { match: ${type} } = await ${load(`${relative_path}/entries/matchers/${type}.js`)}`).join('\n\t\t\t\t')}
|
|
2608
|
+
return { ${Array.from(matchers).join(', ')} };
|
|
2609
|
+
}
|
|
2610
|
+
}
|
|
2611
|
+
}`.replace(/^\t/gm, '');
|
|
2612
|
+
}
|
|
2613
|
+
|
|
2614
|
+
/** @typedef {import('http').IncomingMessage} Req */
|
|
2615
|
+
/** @typedef {import('http').ServerResponse} Res */
|
|
2616
|
+
/** @typedef {(req: Req, res: Res, next: () => void) => void} Handler */
|
|
2617
|
+
|
|
2618
|
+
/**
|
|
2619
|
+
* @param {{
|
|
2620
|
+
* middlewares: import('connect').Server;
|
|
2621
|
+
* httpServer: import('http').Server;
|
|
2622
|
+
* }} vite
|
|
2623
|
+
* @param {import('types').ValidatedConfig} config
|
|
2624
|
+
* @param {'http' | 'https'} protocol
|
|
2625
|
+
*/
|
|
2626
|
+
async function preview(vite, config, protocol) {
|
|
2627
|
+
installPolyfills();
|
|
2628
|
+
|
|
2629
|
+
const { paths } = config.kit;
|
|
2630
|
+
const base = paths.base;
|
|
2631
|
+
const assets = paths.assets ? SVELTE_KIT_ASSETS : paths.base;
|
|
2632
|
+
|
|
2633
|
+
const etag = `"${Date.now()}"`;
|
|
2634
|
+
|
|
2635
|
+
const index_file = join(config.kit.outDir, 'output/server/index.js');
|
|
2636
|
+
const manifest_file = join(config.kit.outDir, 'output/server/manifest.js');
|
|
2637
|
+
|
|
2638
|
+
/** @type {import('types').ServerModule} */
|
|
2639
|
+
const { Server, override } = await import(pathToFileURL(index_file).href);
|
|
2640
|
+
const { manifest } = await import(pathToFileURL(manifest_file).href);
|
|
2641
|
+
|
|
2642
|
+
override({
|
|
2643
|
+
paths: { base, assets },
|
|
2644
|
+
prerendering: false,
|
|
2645
|
+
protocol,
|
|
2646
|
+
read: (file) => fs__default.readFileSync(join(config.kit.files.assets, file))
|
|
2647
|
+
});
|
|
2648
|
+
|
|
2649
|
+
const server = new Server(manifest);
|
|
2650
|
+
|
|
2651
|
+
return () => {
|
|
2652
|
+
// files in `static`
|
|
2653
|
+
vite.middlewares.use(scoped(assets, mutable(config.kit.files.assets)));
|
|
2654
|
+
|
|
2655
|
+
// immutable generated client assets
|
|
2656
|
+
vite.middlewares.use(
|
|
2657
|
+
scoped(
|
|
2658
|
+
assets,
|
|
2659
|
+
sirv(join(config.kit.outDir, 'output/client'), {
|
|
2660
|
+
setHeaders: (res, pathname) => {
|
|
2661
|
+
// only apply to build directory, not e.g. version.json
|
|
2662
|
+
if (pathname.startsWith(`/${config.kit.appDir}/immutable`)) {
|
|
2663
|
+
res.setHeader('cache-control', 'public,max-age=31536000,immutable');
|
|
2664
|
+
}
|
|
2665
|
+
}
|
|
2666
|
+
})
|
|
2667
|
+
)
|
|
2668
|
+
);
|
|
2669
|
+
|
|
2670
|
+
vite.middlewares.use((req, res, next) => {
|
|
2671
|
+
const original_url = /** @type {string} */ (req.url);
|
|
2672
|
+
const { pathname } = new URL(original_url, 'http://dummy');
|
|
2673
|
+
|
|
2674
|
+
if (pathname.startsWith(base)) {
|
|
2675
|
+
next();
|
|
2676
|
+
} else {
|
|
2677
|
+
res.statusCode = 404;
|
|
2678
|
+
res.end(`Not found (did you mean ${base + pathname}?)`);
|
|
2679
|
+
}
|
|
2680
|
+
});
|
|
2681
|
+
|
|
2682
|
+
// prerendered dependencies
|
|
2683
|
+
vite.middlewares.use(
|
|
2684
|
+
scoped(base, mutable(join(config.kit.outDir, 'output/prerendered/dependencies')))
|
|
2685
|
+
);
|
|
2686
|
+
|
|
2687
|
+
// prerendered pages (we can't just use sirv because we need to
|
|
2688
|
+
// preserve the correct trailingSlash behaviour)
|
|
2689
|
+
vite.middlewares.use(
|
|
2690
|
+
scoped(base, (req, res, next) => {
|
|
2691
|
+
let if_none_match_value = req.headers['if-none-match'];
|
|
2692
|
+
|
|
2693
|
+
if (if_none_match_value?.startsWith('W/"')) {
|
|
2694
|
+
if_none_match_value = if_none_match_value.substring(2);
|
|
2695
|
+
}
|
|
2696
|
+
|
|
2697
|
+
if (if_none_match_value === etag) {
|
|
2698
|
+
res.statusCode = 304;
|
|
2699
|
+
res.end();
|
|
2700
|
+
return;
|
|
2701
|
+
}
|
|
2702
|
+
|
|
2703
|
+
const { pathname } = new URL(/** @type {string} */ (req.url), 'http://dummy');
|
|
2704
|
+
|
|
2705
|
+
// only treat this as a page if it doesn't include an extension
|
|
2706
|
+
if (pathname === '/' || /\/[^./]+\/?$/.test(pathname)) {
|
|
2707
|
+
const file = join(
|
|
2708
|
+
config.kit.outDir,
|
|
2709
|
+
'output/prerendered/pages' +
|
|
2710
|
+
pathname +
|
|
2711
|
+
(pathname.endsWith('/') ? 'index.html' : '.html')
|
|
2712
|
+
);
|
|
2713
|
+
|
|
2714
|
+
if (fs__default.existsSync(file)) {
|
|
2715
|
+
res.writeHead(200, {
|
|
2716
|
+
'content-type': 'text/html',
|
|
2717
|
+
etag
|
|
2718
|
+
});
|
|
2719
|
+
|
|
2720
|
+
fs__default.createReadStream(file).pipe(res);
|
|
2721
|
+
return;
|
|
2722
|
+
}
|
|
2723
|
+
}
|
|
2724
|
+
|
|
2725
|
+
next();
|
|
2726
|
+
})
|
|
2727
|
+
);
|
|
2728
|
+
|
|
2729
|
+
// SSR
|
|
2730
|
+
vite.middlewares.use(async (req, res) => {
|
|
2731
|
+
const host = req.headers['host'];
|
|
2732
|
+
|
|
2733
|
+
let request;
|
|
2734
|
+
|
|
2735
|
+
try {
|
|
2736
|
+
request = await getRequest(`${protocol}://${host}`, req);
|
|
2737
|
+
} catch (/** @type {any} */ err) {
|
|
2738
|
+
res.statusCode = err.status || 400;
|
|
2739
|
+
return res.end(err.reason || 'Invalid request body');
|
|
2740
|
+
}
|
|
2741
|
+
|
|
2742
|
+
setResponse(
|
|
2743
|
+
res,
|
|
2744
|
+
await server.respond(request, {
|
|
2745
|
+
getClientAddress: () => {
|
|
2746
|
+
const { remoteAddress } = req.socket;
|
|
2747
|
+
if (remoteAddress) return remoteAddress;
|
|
2748
|
+
throw new Error('Could not determine clientAddress');
|
|
2749
|
+
}
|
|
2750
|
+
})
|
|
2751
|
+
);
|
|
2752
|
+
});
|
|
2753
|
+
};
|
|
2754
|
+
}
|
|
2755
|
+
|
|
2756
|
+
/**
|
|
2757
|
+
* @param {string} dir
|
|
2758
|
+
* @returns {Handler}
|
|
2759
|
+
*/
|
|
2760
|
+
const mutable = (dir) =>
|
|
2761
|
+
fs__default.existsSync(dir)
|
|
2762
|
+
? sirv(dir, {
|
|
2763
|
+
etag: true,
|
|
2764
|
+
maxAge: 0
|
|
2765
|
+
})
|
|
2766
|
+
: (req, res, next) => next();
|
|
2767
|
+
|
|
2768
|
+
/**
|
|
2769
|
+
* @param {string} scope
|
|
2770
|
+
* @param {Handler} handler
|
|
2771
|
+
* @returns {Handler}
|
|
2772
|
+
*/
|
|
2773
|
+
function scoped(scope, handler) {
|
|
2774
|
+
if (scope === '') return handler;
|
|
2775
|
+
|
|
2776
|
+
return (req, res, next) => {
|
|
2777
|
+
if (req.url?.startsWith(scope)) {
|
|
2778
|
+
const original_url = req.url;
|
|
2779
|
+
req.url = req.url.slice(scope.length);
|
|
2780
|
+
handler(req, res, () => {
|
|
2781
|
+
req.url = original_url;
|
|
2782
|
+
next();
|
|
2783
|
+
});
|
|
2784
|
+
} else {
|
|
2785
|
+
next();
|
|
2786
|
+
}
|
|
2787
|
+
};
|
|
2788
|
+
}
|
|
2789
|
+
|
|
2790
|
+
const cwd = process.cwd();
|
|
2791
|
+
|
|
2792
|
+
/** @type {Record<string, any>} */
|
|
2793
|
+
const enforced_config = {
|
|
2794
|
+
base: true,
|
|
2795
|
+
build: {
|
|
2796
|
+
cssCodeSplit: true,
|
|
2797
|
+
emptyOutDir: true,
|
|
2798
|
+
lib: {
|
|
2799
|
+
entry: true,
|
|
2800
|
+
name: true,
|
|
2801
|
+
formats: true
|
|
2802
|
+
},
|
|
2803
|
+
manifest: true,
|
|
2804
|
+
outDir: true,
|
|
2805
|
+
polyfillDynamicImport: true,
|
|
2806
|
+
rollupOptions: {
|
|
2807
|
+
input: true,
|
|
2808
|
+
output: {
|
|
2809
|
+
format: true,
|
|
2810
|
+
entryFileNames: true,
|
|
2811
|
+
chunkFileNames: true,
|
|
2812
|
+
assetFileNames: true
|
|
2813
|
+
},
|
|
2814
|
+
preserveEntrySignatures: true
|
|
2815
|
+
},
|
|
2816
|
+
ssr: true
|
|
2817
|
+
},
|
|
2818
|
+
publicDir: true,
|
|
2819
|
+
resolve: {
|
|
2820
|
+
alias: {
|
|
2821
|
+
$app: true,
|
|
2822
|
+
$lib: true,
|
|
2823
|
+
'$service-worker': true
|
|
2824
|
+
}
|
|
2825
|
+
},
|
|
2826
|
+
root: true
|
|
2827
|
+
};
|
|
2828
|
+
|
|
2829
|
+
/**
|
|
2830
|
+
* @return {import('vite').Plugin[]}
|
|
2831
|
+
*/
|
|
2832
|
+
function sveltekit() {
|
|
2833
|
+
return [...svelte(), kit()];
|
|
2834
|
+
}
|
|
2835
|
+
|
|
2836
|
+
/**
|
|
2837
|
+
* @return {import('vite').Plugin}
|
|
2838
|
+
*/
|
|
2839
|
+
function kit() {
|
|
2840
|
+
/** @type {import('types').ValidatedConfig} */
|
|
2841
|
+
let svelte_config;
|
|
2842
|
+
|
|
2843
|
+
/** @type {import('vite').ResolvedConfig} */
|
|
2844
|
+
let vite_config;
|
|
2845
|
+
|
|
2846
|
+
/** @type {import('vite').ConfigEnv} */
|
|
2847
|
+
let vite_config_env;
|
|
2848
|
+
|
|
2849
|
+
/** @type {import('types').ManifestData} */
|
|
2850
|
+
let manifest_data;
|
|
2851
|
+
|
|
2852
|
+
/** @type {boolean} */
|
|
2853
|
+
let is_build;
|
|
2854
|
+
|
|
2855
|
+
/** @type {import('types').Logger} */
|
|
2856
|
+
let log;
|
|
2857
|
+
|
|
2858
|
+
/** @type {import('types').Prerendered} */
|
|
2859
|
+
let prerendered;
|
|
2860
|
+
|
|
2861
|
+
/** @type {import('types').BuildData} */
|
|
2862
|
+
let build_data;
|
|
2863
|
+
|
|
2864
|
+
/**
|
|
2865
|
+
* @type {{
|
|
2866
|
+
* build_dir: string;
|
|
2867
|
+
* output_dir: string;
|
|
2868
|
+
* client_out_dir: string;
|
|
2869
|
+
* }}
|
|
2870
|
+
*/
|
|
2871
|
+
let paths;
|
|
2872
|
+
|
|
2873
|
+
function create_client_config() {
|
|
2874
|
+
/** @type {Record<string, string>} */
|
|
2875
|
+
const input = {
|
|
2876
|
+
// Put unchanging assets in immutable directory. We don't set that in the
|
|
2877
|
+
// outDir so that other plugins can add mutable assets to the bundle
|
|
2878
|
+
start: `${get_runtime_path(svelte_config.kit)}/client/start.js`
|
|
2879
|
+
};
|
|
2880
|
+
|
|
2881
|
+
// This step is optional — Vite/Rollup will create the necessary chunks
|
|
2882
|
+
// for everything regardless — but it means that entry chunks reflect
|
|
2883
|
+
// their location in the source code, which is helpful for debugging
|
|
2884
|
+
manifest_data.components.forEach((file) => {
|
|
2885
|
+
const resolved = path__default.resolve(cwd, file);
|
|
2886
|
+
const relative = decodeURIComponent(path__default.relative(svelte_config.kit.files.routes, resolved));
|
|
2887
|
+
|
|
2888
|
+
const name = relative.startsWith('..')
|
|
2889
|
+
? path__default.basename(file)
|
|
2890
|
+
: posixify(path__default.join('pages', relative));
|
|
2891
|
+
input[name] = resolved;
|
|
2892
|
+
});
|
|
2893
|
+
|
|
2894
|
+
return get_default_config({
|
|
2895
|
+
config: svelte_config,
|
|
2896
|
+
input,
|
|
2897
|
+
ssr: false,
|
|
2898
|
+
outDir: `${paths.client_out_dir}`
|
|
2899
|
+
});
|
|
2900
|
+
}
|
|
2901
|
+
|
|
2902
|
+
return {
|
|
2903
|
+
name: 'vite-plugin-svelte-kit',
|
|
2904
|
+
|
|
2905
|
+
async config(config, config_env) {
|
|
2906
|
+
vite_config_env = config_env;
|
|
2907
|
+
svelte_config = await load_config();
|
|
2908
|
+
is_build = config_env.command === 'build';
|
|
2909
|
+
|
|
2910
|
+
paths = {
|
|
2911
|
+
build_dir: `${svelte_config.kit.outDir}/build`,
|
|
2912
|
+
output_dir: `${svelte_config.kit.outDir}/output`,
|
|
2913
|
+
client_out_dir: `${svelte_config.kit.outDir}/output/client/${svelte_config.kit.appDir}`
|
|
2914
|
+
};
|
|
2915
|
+
|
|
2916
|
+
if (is_build) {
|
|
2917
|
+
process.env.VITE_SVELTEKIT_APP_VERSION = svelte_config.kit.version.name;
|
|
2918
|
+
process.env.VITE_SVELTEKIT_APP_VERSION_FILE = `${svelte_config.kit.appDir}/version.json`;
|
|
2919
|
+
process.env.VITE_SVELTEKIT_APP_VERSION_POLL_INTERVAL = `${svelte_config.kit.version.pollInterval}`;
|
|
2920
|
+
|
|
2921
|
+
manifest_data = all(svelte_config).manifest_data;
|
|
2922
|
+
|
|
2923
|
+
const new_config = create_client_config();
|
|
2924
|
+
|
|
2925
|
+
warn_overridden_config(config, new_config);
|
|
2926
|
+
|
|
2927
|
+
return new_config;
|
|
2928
|
+
}
|
|
2929
|
+
|
|
2930
|
+
// dev and preview config can be shared
|
|
2931
|
+
const result = {
|
|
2932
|
+
base: '/',
|
|
2933
|
+
build: {
|
|
2934
|
+
rollupOptions: {
|
|
2935
|
+
// Vite dependency crawler needs an explicit JS entry point
|
|
2936
|
+
// eventhough server otherwise works without it
|
|
2937
|
+
input: `${get_runtime_path(svelte_config.kit)}/client/start.js`
|
|
2938
|
+
}
|
|
2939
|
+
},
|
|
2940
|
+
resolve: {
|
|
2941
|
+
alias: get_aliases(svelte_config.kit)
|
|
2942
|
+
},
|
|
2943
|
+
root: cwd,
|
|
2944
|
+
server: {
|
|
2945
|
+
fs: {
|
|
2946
|
+
allow: [
|
|
2947
|
+
...new Set([
|
|
2948
|
+
svelte_config.kit.files.lib,
|
|
2949
|
+
svelte_config.kit.files.routes,
|
|
2950
|
+
svelte_config.kit.outDir,
|
|
2951
|
+
path__default.resolve(cwd, 'src'),
|
|
2952
|
+
path__default.resolve(cwd, 'node_modules'),
|
|
2953
|
+
path__default.resolve(searchForWorkspaceRoot(cwd), 'node_modules')
|
|
2954
|
+
])
|
|
2955
|
+
]
|
|
2956
|
+
},
|
|
2957
|
+
watch: {
|
|
2958
|
+
ignored: [
|
|
2959
|
+
// Ignore all siblings of config.kit.outDir/generated
|
|
2960
|
+
`${posixify(svelte_config.kit.outDir)}/!(generated)`
|
|
2961
|
+
]
|
|
2962
|
+
}
|
|
2963
|
+
}
|
|
2964
|
+
};
|
|
2965
|
+
warn_overridden_config(config, result);
|
|
2966
|
+
return result;
|
|
2967
|
+
},
|
|
2968
|
+
|
|
2969
|
+
configResolved(config) {
|
|
2970
|
+
vite_config = config;
|
|
2971
|
+
},
|
|
2972
|
+
|
|
2973
|
+
buildStart() {
|
|
2974
|
+
if (is_build) {
|
|
2975
|
+
rimraf(paths.build_dir);
|
|
2976
|
+
mkdirp(paths.build_dir);
|
|
2977
|
+
|
|
2978
|
+
rimraf(paths.output_dir);
|
|
2979
|
+
mkdirp(paths.output_dir);
|
|
2980
|
+
}
|
|
2981
|
+
},
|
|
2982
|
+
|
|
2983
|
+
async writeBundle(_options, bundle) {
|
|
2984
|
+
log = logger({
|
|
2985
|
+
verbose: vite_config.logLevel === 'info'
|
|
2986
|
+
});
|
|
2987
|
+
|
|
2988
|
+
fs__default.writeFileSync(
|
|
2989
|
+
`${paths.client_out_dir}/version.json`,
|
|
2990
|
+
JSON.stringify({ version: process.env.VITE_SVELTEKIT_APP_VERSION })
|
|
2991
|
+
);
|
|
2992
|
+
|
|
2993
|
+
/** @type {import('rollup').OutputChunk[]} */
|
|
2994
|
+
const chunks = [];
|
|
2995
|
+
/** @type {import('rollup').OutputAsset[]} */
|
|
2996
|
+
const assets = [];
|
|
2997
|
+
for (const key of Object.keys(bundle)) {
|
|
2998
|
+
// collect asset and output chunks
|
|
2999
|
+
if (bundle[key].type === 'asset') {
|
|
3000
|
+
assets.push(/** @type {import('rollup').OutputAsset} */ (bundle[key]));
|
|
3001
|
+
} else {
|
|
3002
|
+
chunks.push(/** @type {import('rollup').OutputChunk} */ (bundle[key]));
|
|
3003
|
+
}
|
|
3004
|
+
}
|
|
3005
|
+
|
|
3006
|
+
/** @type {import('vite').Manifest} */
|
|
3007
|
+
const vite_manifest = JSON.parse(
|
|
3008
|
+
fs__default.readFileSync(`${paths.client_out_dir}/manifest.json`, 'utf-8')
|
|
3009
|
+
);
|
|
3010
|
+
|
|
3011
|
+
const entry_id = posixify(
|
|
3012
|
+
path__default.relative(cwd, `${get_runtime_path(svelte_config.kit)}/client/start.js`)
|
|
3013
|
+
);
|
|
3014
|
+
|
|
3015
|
+
const client = {
|
|
3016
|
+
assets,
|
|
3017
|
+
chunks,
|
|
3018
|
+
entry: find_deps$1(vite_manifest, entry_id, false),
|
|
3019
|
+
vite_manifest
|
|
3020
|
+
};
|
|
3021
|
+
log.info(`Client build completed. Wrote ${chunks.length} chunks and ${assets.length} assets`);
|
|
3022
|
+
|
|
3023
|
+
const options = {
|
|
3024
|
+
cwd,
|
|
3025
|
+
config: svelte_config,
|
|
3026
|
+
vite_config_env,
|
|
3027
|
+
build_dir: paths.build_dir, // TODO just pass `paths`
|
|
3028
|
+
manifest_data,
|
|
3029
|
+
output_dir: paths.output_dir,
|
|
3030
|
+
service_worker_entry_file: resolve_entry(svelte_config.kit.files.serviceWorker)
|
|
3031
|
+
};
|
|
3032
|
+
|
|
3033
|
+
log.info('Building server');
|
|
3034
|
+
|
|
3035
|
+
const server = await build_server(options, client);
|
|
3036
|
+
|
|
3037
|
+
process.env.SVELTEKIT_SERVER_BUILD_COMPLETED = 'true';
|
|
3038
|
+
|
|
3039
|
+
/** @type {import('types').BuildData} */
|
|
3040
|
+
build_data = {
|
|
3041
|
+
app_dir: svelte_config.kit.appDir,
|
|
3042
|
+
manifest_data,
|
|
3043
|
+
service_worker: options.service_worker_entry_file ? 'service-worker.js' : null, // TODO make file configurable?
|
|
3044
|
+
client,
|
|
3045
|
+
server
|
|
3046
|
+
};
|
|
3047
|
+
|
|
3048
|
+
fs__default.writeFileSync(
|
|
3049
|
+
`${paths.output_dir}/server/manifest.js`,
|
|
3050
|
+
`export const manifest = ${generate_manifest({
|
|
3051
|
+
build_data,
|
|
3052
|
+
relative_path: '.',
|
|
3053
|
+
routes: manifest_data.routes
|
|
3054
|
+
})};\n`
|
|
3055
|
+
);
|
|
3056
|
+
|
|
3057
|
+
const static_files = manifest_data.assets.map((asset) => posixify(asset.file));
|
|
3058
|
+
|
|
3059
|
+
const files = new Set([
|
|
3060
|
+
...static_files,
|
|
3061
|
+
...chunks.map((chunk) => `${svelte_config.kit.appDir}/${chunk.fileName}`),
|
|
3062
|
+
...assets.map((chunk) => `${svelte_config.kit.appDir}/${chunk.fileName}`)
|
|
3063
|
+
]);
|
|
3064
|
+
|
|
3065
|
+
// TODO is this right?
|
|
3066
|
+
static_files.forEach((file) => {
|
|
3067
|
+
if (file.endsWith('/index.html')) {
|
|
3068
|
+
files.add(file.slice(0, -11));
|
|
3069
|
+
}
|
|
3070
|
+
});
|
|
3071
|
+
|
|
3072
|
+
log.info('Prerendering');
|
|
3073
|
+
|
|
3074
|
+
prerendered = await prerender({
|
|
3075
|
+
config: svelte_config.kit,
|
|
3076
|
+
entries: manifest_data.routes
|
|
3077
|
+
.map((route) => (route.type === 'page' ? route.path : ''))
|
|
3078
|
+
.filter(Boolean),
|
|
3079
|
+
files,
|
|
3080
|
+
log
|
|
3081
|
+
});
|
|
3082
|
+
|
|
3083
|
+
if (options.service_worker_entry_file) {
|
|
3084
|
+
if (svelte_config.kit.paths.assets) {
|
|
3085
|
+
throw new Error('Cannot use service worker alongside config.kit.paths.assets');
|
|
3086
|
+
}
|
|
3087
|
+
|
|
3088
|
+
log.info('Building service worker');
|
|
3089
|
+
|
|
3090
|
+
await build_service_worker(options, prerendered, client.vite_manifest);
|
|
3091
|
+
}
|
|
3092
|
+
|
|
3093
|
+
console.log(
|
|
3094
|
+
`\nRun ${$.bold().cyan('npm run preview')} to preview your production build locally.`
|
|
3095
|
+
);
|
|
3096
|
+
},
|
|
3097
|
+
|
|
3098
|
+
async closeBundle() {
|
|
3099
|
+
if (!is_build) {
|
|
3100
|
+
return; // vite calls closeBundle when dev-server restarts, ignore that
|
|
3101
|
+
}
|
|
3102
|
+
if (svelte_config.kit.adapter) {
|
|
3103
|
+
const { adapt } = await import('./chunks/index2.js');
|
|
3104
|
+
await adapt(svelte_config, build_data, prerendered, { log });
|
|
3105
|
+
} else {
|
|
3106
|
+
console.log($.bold().yellow('\nNo adapter specified'));
|
|
3107
|
+
// prettier-ignore
|
|
3108
|
+
console.log(
|
|
3109
|
+
`See ${$.bold().cyan('https://kit.svelte.dev/docs/adapters')} to learn how to configure your app to run on the platform of your choosing`
|
|
3110
|
+
);
|
|
3111
|
+
}
|
|
3112
|
+
|
|
3113
|
+
if (svelte_config.kit.prerender.enabled) {
|
|
3114
|
+
// this is necessary to close any open db connections, etc.
|
|
3115
|
+
// TODO: prerender in a subprocess so we can exit in isolation
|
|
3116
|
+
// https://github.com/sveltejs/kit/issues/5306
|
|
3117
|
+
process.exit(0);
|
|
3118
|
+
}
|
|
3119
|
+
},
|
|
3120
|
+
|
|
3121
|
+
async configureServer(vite) {
|
|
3122
|
+
return await dev(vite, vite_config, svelte_config);
|
|
3123
|
+
},
|
|
3124
|
+
|
|
3125
|
+
configurePreviewServer(vite) {
|
|
3126
|
+
return preview(vite, svelte_config, vite_config.preview.https ? 'https' : 'http');
|
|
3127
|
+
}
|
|
3128
|
+
};
|
|
3129
|
+
}
|
|
3130
|
+
|
|
3131
|
+
/**
|
|
3132
|
+
* @param {Record<string, any>} config
|
|
3133
|
+
* @param {Record<string, any>} resolved_config
|
|
3134
|
+
* @param {string} [path]
|
|
3135
|
+
* @param {string[]} [out] used locally to compute the return value
|
|
3136
|
+
*/
|
|
3137
|
+
function warn_overridden_config(config, resolved_config, path = '', out = []) {
|
|
3138
|
+
const overridden = find_overridden_config(config, resolved_config, path, out);
|
|
3139
|
+
if (overridden.length > 0) {
|
|
3140
|
+
console.log(
|
|
3141
|
+
$.bold().red('The following Vite config options will be overridden by SvelteKit:')
|
|
3142
|
+
);
|
|
3143
|
+
console.log(overridden.map((key) => ` - ${key}`).join('\n'));
|
|
3144
|
+
}
|
|
3145
|
+
}
|
|
3146
|
+
|
|
3147
|
+
/**
|
|
3148
|
+
* @param {Record<string, any>} config
|
|
3149
|
+
* @param {Record<string, any>} resolved_config
|
|
3150
|
+
* @param {string} path
|
|
3151
|
+
* @param {string[]} out used locally to compute the return value
|
|
3152
|
+
*/
|
|
3153
|
+
function find_overridden_config(config, resolved_config, path, out) {
|
|
3154
|
+
for (const key in enforced_config) {
|
|
3155
|
+
if (typeof config === 'object' && config !== null && key in config) {
|
|
3156
|
+
if (enforced_config[key] === true && config[key] !== resolved_config[key]) {
|
|
3157
|
+
out.push(path + key);
|
|
3158
|
+
} else {
|
|
3159
|
+
find_overridden_config(config[key], resolved_config[key], path + key + '.', out);
|
|
3160
|
+
}
|
|
3161
|
+
}
|
|
3162
|
+
}
|
|
3163
|
+
|
|
3164
|
+
return out;
|
|
3165
|
+
}
|
|
3166
|
+
|
|
3167
|
+
export { generate_manifest as g, sveltekit };
|