mirror of
https://github.com/kevin-DL/sapper.git
synced 2026-01-13 11:35:28 +00:00
Compare commits
49 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
969169ae20 | ||
|
|
79fa15da3d | ||
|
|
ddc08d94cc | ||
|
|
e2193a6080 | ||
|
|
f66c7dcb0d | ||
|
|
06f1a0e6c0 | ||
|
|
7726325b4b | ||
|
|
f97400caaa | ||
|
|
03af9b1a16 | ||
|
|
02cef046aa | ||
|
|
c2aeac34b6 | ||
|
|
abd2f7fd39 | ||
|
|
e7cf9bf1b6 | ||
|
|
1fdd0e3ad2 | ||
|
|
af0a7e04f9 | ||
|
|
ed19a19fed | ||
|
|
8ebfcc9a54 | ||
|
|
af2a792508 | ||
|
|
14e809af6e | ||
|
|
03c5f5b446 | ||
|
|
6655b1b49d | ||
|
|
eebf076f23 | ||
|
|
198be28f4b | ||
|
|
4f720446b2 | ||
|
|
e69cb3639a | ||
|
|
1b1a86764f | ||
|
|
f50f83c4a4 | ||
|
|
eadefd996b | ||
|
|
ab52aabd1d | ||
|
|
c5a80543b3 | ||
|
|
cfd95ac024 | ||
|
|
73ff95c677 | ||
|
|
382fe6b7b9 | ||
|
|
3b714c0de3 | ||
|
|
28186227a9 | ||
|
|
2ac0f2bf3d | ||
|
|
4991f3b359 | ||
|
|
65128118c7 | ||
|
|
3eced6fa4d | ||
|
|
c4aee66c32 | ||
|
|
410c52df41 | ||
|
|
ffd56e2a20 | ||
|
|
1e5a87cf71 | ||
|
|
281e183c61 | ||
|
|
3fe7b55955 | ||
|
|
464924ed67 | ||
|
|
e5d7d8ab2b | ||
|
|
d3e560325d | ||
|
|
64e5065aa5 |
37
CHANGELOG.md
37
CHANGELOG.md
@@ -1,5 +1,42 @@
|
||||
# sapper changelog
|
||||
|
||||
## 0.24.3
|
||||
|
||||
* Add service-worker-index.html shell file for offline support ([#422](https://github.com/sveltejs/sapper/issues/422))
|
||||
* Don't cache .map files ([#534](https://github.com/sveltejs/sapper/issues/534))
|
||||
|
||||
## 0.24.2
|
||||
|
||||
* Support Rollup 1.0 ([#541](https://github.com/sveltejs/sapper/pull/541))
|
||||
|
||||
## 0.24.1
|
||||
|
||||
* Include CSS chunks in webpack build info to avoid duplication ([#529](https://github.com/sveltejs/sapper/pull/529))
|
||||
* Fix preload `as` for styles ([#530](https://github.com/sveltejs/sapper/pull/530))
|
||||
|
||||
## 0.24.0
|
||||
|
||||
* Handle external URLs in `this.redirect` ([#490](https://github.com/sveltejs/sapper/issues/490))
|
||||
* Strip leading `/` from basepath ([#495](https://github.com/sveltejs/sapper/issues/495))
|
||||
* Treat duplicate query string parameters as arrays ([#497](https://github.com/sveltejs/sapper/issues/497))
|
||||
* Don't buffer `stdout` and `stderr` ([#305](https://github.com/sveltejs/sapper/issues/305))
|
||||
* Posixify `build_dir` ([#498](https://github.com/sveltejs/sapper/pull/498))
|
||||
* Use `page[XY]Offset` instead of `scroll[XY]` ([#480](https://github.com/sveltejs/sapper/issues/480))
|
||||
|
||||
## 0.23.5
|
||||
|
||||
* Include lazily-imported CSS in main CSS chunk ([#492](https://github.com/sveltejs/sapper/pull/492))
|
||||
* Make search param decoding spec-compliant ([#493](https://github.com/sveltejs/sapper/pull/493))
|
||||
* Handle async route errors ([#488](https://github.com/sveltejs/sapper/pull/488))
|
||||
|
||||
## 0.23.4
|
||||
|
||||
* Ignore empty anchors when exporting ([#491](https://github.com/sveltejs/sapper/pull/491))
|
||||
|
||||
## 0.23.3
|
||||
|
||||
* Clear `error` and `status` on successful render ([#477](https://github.com/sveltejs/sapper/pull/477))
|
||||
|
||||
## 0.23.2
|
||||
|
||||
* Fix entry point CSS ([#471](https://github.com/sveltejs/sapper/pull/471))
|
||||
|
||||
99
package-lock.json
generated
99
package-lock.json
generated
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "sapper",
|
||||
"version": "0.23.1",
|
||||
"version": "0.24.2",
|
||||
"lockfileVersion": 1,
|
||||
"requires": true,
|
||||
"dependencies": {
|
||||
@@ -1702,12 +1702,6 @@
|
||||
"integrity": "sha512-jnjyiM6eRyZl2H+W8Q/zLMA481hzi0eszAaBUzIVnmYVDBbnLxVNnfu1HgEBvCbL+71FrxMl3E6lpKH7Ge3OXA==",
|
||||
"dev": true
|
||||
},
|
||||
"duplexer": {
|
||||
"version": "0.1.1",
|
||||
"resolved": "http://registry.npmjs.org/duplexer/-/duplexer-0.1.1.tgz",
|
||||
"integrity": "sha1-rOb/gIwc5mtX0ev5eXessCM0z8E=",
|
||||
"dev": true
|
||||
},
|
||||
"duplexify": {
|
||||
"version": "3.6.1",
|
||||
"resolved": "https://registry.npmjs.org/duplexify/-/duplexify-3.6.1.tgz",
|
||||
@@ -2043,22 +2037,6 @@
|
||||
"integrity": "sha1-Cr9PHKpbyx96nYrMbepPqqBLrJs=",
|
||||
"dev": true
|
||||
},
|
||||
"event-stream": {
|
||||
"version": "3.3.6",
|
||||
"resolved": "https://registry.npmjs.org/event-stream/-/event-stream-3.3.6.tgz",
|
||||
"integrity": "sha512-dGXNg4F/FgVzlApjzItL+7naHutA3fDqbV/zAZqDDlXTjiMnQmZKu+prImWKszeBM5UQeGvAl3u1wBiKeDh61g==",
|
||||
"dev": true,
|
||||
"requires": {
|
||||
"duplexer": "^0.1.1",
|
||||
"flatmap-stream": "^0.1.0",
|
||||
"from": "^0.1.7",
|
||||
"map-stream": "0.0.7",
|
||||
"pause-stream": "^0.0.11",
|
||||
"split": "^1.0.1",
|
||||
"stream-combiner": "^0.2.2",
|
||||
"through": "^2.3.8"
|
||||
}
|
||||
},
|
||||
"events": {
|
||||
"version": "1.1.1",
|
||||
"resolved": "http://registry.npmjs.org/events/-/events-1.1.1.tgz",
|
||||
@@ -2281,12 +2259,6 @@
|
||||
"write": "^0.2.1"
|
||||
}
|
||||
},
|
||||
"flatmap-stream": {
|
||||
"version": "0.1.1",
|
||||
"resolved": "https://registry.npmjs.org/flatmap-stream/-/flatmap-stream-0.1.1.tgz",
|
||||
"integrity": "sha512-lAq4tLbm3sidmdCN8G3ExaxH7cUCtP5mgDvrYowsx84dcYkJJ4I28N7gkxA6+YlSXzaGLJYIDEi9WGfXzMiXdw==",
|
||||
"dev": true
|
||||
},
|
||||
"flush-write-stream": {
|
||||
"version": "1.0.3",
|
||||
"resolved": "https://registry.npmjs.org/flush-write-stream/-/flush-write-stream-1.0.3.tgz",
|
||||
@@ -2321,12 +2293,6 @@
|
||||
"map-cache": "^0.2.2"
|
||||
}
|
||||
},
|
||||
"from": {
|
||||
"version": "0.1.7",
|
||||
"resolved": "https://registry.npmjs.org/from/-/from-0.1.7.tgz",
|
||||
"integrity": "sha1-g8YK/Fi5xWmXAH7Rp2izqzA6RP4=",
|
||||
"dev": true
|
||||
},
|
||||
"from2": {
|
||||
"version": "2.3.0",
|
||||
"resolved": "https://registry.npmjs.org/from2/-/from2-2.3.0.tgz",
|
||||
@@ -3648,12 +3614,6 @@
|
||||
"integrity": "sha1-wyq9C9ZSXZsFFkW7TyasXcmKDb8=",
|
||||
"dev": true
|
||||
},
|
||||
"map-stream": {
|
||||
"version": "0.0.7",
|
||||
"resolved": "https://registry.npmjs.org/map-stream/-/map-stream-0.0.7.tgz",
|
||||
"integrity": "sha1-ih8HiW2CsQkmvTdEokIACfiJdKg=",
|
||||
"dev": true
|
||||
},
|
||||
"map-visit": {
|
||||
"version": "1.0.0",
|
||||
"resolved": "https://registry.npmjs.org/map-visit/-/map-visit-1.0.0.tgz",
|
||||
@@ -4059,17 +4019,17 @@
|
||||
}
|
||||
},
|
||||
"npm-run-all": {
|
||||
"version": "4.1.3",
|
||||
"resolved": "https://registry.npmjs.org/npm-run-all/-/npm-run-all-4.1.3.tgz",
|
||||
"integrity": "sha512-aOG0N3Eo/WW+q6sUIdzcV2COS8VnTZCmdji0VQIAZF3b+a3YWb0AD0vFIyjKec18A7beLGbaQ5jFTNI2bPt9Cg==",
|
||||
"version": "4.1.5",
|
||||
"resolved": "https://registry.npmjs.org/npm-run-all/-/npm-run-all-4.1.5.tgz",
|
||||
"integrity": "sha512-Oo82gJDAVcaMdi3nuoKFavkIHBRVqQ1qvMb+9LHk/cF4P6B2m8aP04hGf7oL6wZ9BuGwX1onlLhpuoofSyoQDQ==",
|
||||
"dev": true,
|
||||
"requires": {
|
||||
"ansi-styles": "^3.2.0",
|
||||
"chalk": "^2.1.0",
|
||||
"cross-spawn": "^6.0.4",
|
||||
"ansi-styles": "^3.2.1",
|
||||
"chalk": "^2.4.1",
|
||||
"cross-spawn": "^6.0.5",
|
||||
"memorystream": "^0.3.1",
|
||||
"minimatch": "^3.0.4",
|
||||
"ps-tree": "^1.1.0",
|
||||
"pidtree": "^0.3.0",
|
||||
"read-pkg": "^3.0.0",
|
||||
"shell-quote": "^1.6.1",
|
||||
"string.prototype.padend": "^3.0.0"
|
||||
@@ -4399,15 +4359,6 @@
|
||||
"pify": "^2.0.0"
|
||||
}
|
||||
},
|
||||
"pause-stream": {
|
||||
"version": "0.0.11",
|
||||
"resolved": "http://registry.npmjs.org/pause-stream/-/pause-stream-0.0.11.tgz",
|
||||
"integrity": "sha1-/lo0sMvOErWqaitAPuLnO2AvFEU=",
|
||||
"dev": true,
|
||||
"requires": {
|
||||
"through": "~2.3"
|
||||
}
|
||||
},
|
||||
"pbkdf2": {
|
||||
"version": "3.0.17",
|
||||
"resolved": "https://registry.npmjs.org/pbkdf2/-/pbkdf2-3.0.17.tgz",
|
||||
@@ -4427,6 +4378,12 @@
|
||||
"integrity": "sha1-elfrVQpng/kRUzH89GY9XI4AelA=",
|
||||
"dev": true
|
||||
},
|
||||
"pidtree": {
|
||||
"version": "0.3.0",
|
||||
"resolved": "https://registry.npmjs.org/pidtree/-/pidtree-0.3.0.tgz",
|
||||
"integrity": "sha512-9CT4NFlDcosssyg8KVFltgokyKZIFjoBxw8CTGy+5F38Y1eQWrt8tRayiUOXE+zVKQnYu5BR8JjCtvK3BcnBhg==",
|
||||
"dev": true
|
||||
},
|
||||
"pify": {
|
||||
"version": "2.3.0",
|
||||
"resolved": "https://registry.npmjs.org/pify/-/pify-2.3.0.tgz",
|
||||
@@ -4539,15 +4496,6 @@
|
||||
"integrity": "sha1-0/wRS6BplaRexok/SEzrHXj19HY=",
|
||||
"dev": true
|
||||
},
|
||||
"ps-tree": {
|
||||
"version": "1.1.0",
|
||||
"resolved": "https://registry.npmjs.org/ps-tree/-/ps-tree-1.1.0.tgz",
|
||||
"integrity": "sha1-tCGyQUDWID8e08dplrRCewjowBQ=",
|
||||
"dev": true,
|
||||
"requires": {
|
||||
"event-stream": "~3.3.0"
|
||||
}
|
||||
},
|
||||
"pseudomap": {
|
||||
"version": "1.0.2",
|
||||
"resolved": "https://registry.npmjs.org/pseudomap/-/pseudomap-1.0.2.tgz",
|
||||
@@ -5665,15 +5613,6 @@
|
||||
"integrity": "sha512-TfOfPcYGBB5sDuPn3deByxPhmfegAhpDYKSOXZQN81Oyrrif8ZCodOLzK3AesELnCx03kikhyDwh0pfvvQvF8w==",
|
||||
"dev": true
|
||||
},
|
||||
"split": {
|
||||
"version": "1.0.1",
|
||||
"resolved": "https://registry.npmjs.org/split/-/split-1.0.1.tgz",
|
||||
"integrity": "sha512-mTyOoPbrivtXnwnIxZRFYRrPNtEFKlpB2fvjSnCQUiAA6qAZzqwna5envK4uk6OIeP17CsdF3rSBGYVBsU0Tkg==",
|
||||
"dev": true,
|
||||
"requires": {
|
||||
"through": "2"
|
||||
}
|
||||
},
|
||||
"split-string": {
|
||||
"version": "3.1.0",
|
||||
"resolved": "https://registry.npmjs.org/split-string/-/split-string-3.1.0.tgz",
|
||||
@@ -5729,16 +5668,6 @@
|
||||
"readable-stream": "^2.0.2"
|
||||
}
|
||||
},
|
||||
"stream-combiner": {
|
||||
"version": "0.2.2",
|
||||
"resolved": "http://registry.npmjs.org/stream-combiner/-/stream-combiner-0.2.2.tgz",
|
||||
"integrity": "sha1-rsjLrBd7Vrb0+kec7YwZEs7lKFg=",
|
||||
"dev": true,
|
||||
"requires": {
|
||||
"duplexer": "~0.1.1",
|
||||
"through": "~2.3.4"
|
||||
}
|
||||
},
|
||||
"stream-each": {
|
||||
"version": "1.2.3",
|
||||
"resolved": "https://registry.npmjs.org/stream-each/-/stream-each-1.2.3.tgz",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "sapper",
|
||||
"version": "0.23.2",
|
||||
"version": "0.24.3",
|
||||
"description": "Military-grade apps, engineered by Svelte",
|
||||
"bin": {
|
||||
"sapper": "./sapper"
|
||||
@@ -40,7 +40,7 @@
|
||||
"mkdirp": "^0.5.1",
|
||||
"mocha": "^5.2.0",
|
||||
"node-fetch": "^2.2.0",
|
||||
"npm-run-all": "^4.1.3",
|
||||
"npm-run-all": "^4.1.5",
|
||||
"polka": "^0.5.1",
|
||||
"port-authority": "^1.0.5",
|
||||
"pretty-bytes": "^5.1.0",
|
||||
|
||||
@@ -116,10 +116,15 @@ export async function build({
|
||||
let serviceworker_stats;
|
||||
|
||||
if (serviceworker) {
|
||||
|
||||
const client_files = client_result.chunks
|
||||
.filter(chunk => !chunk.file.endsWith('.map')) // SW does not need to cache sourcemap files
|
||||
.map(chunk => `client/${chunk.file}`);
|
||||
|
||||
create_serviceworker_manifest({
|
||||
manifest_data,
|
||||
output,
|
||||
client_files: client_result.chunks.map(chunk => `client/${chunk.file}`),
|
||||
client_files,
|
||||
static_files
|
||||
});
|
||||
|
||||
|
||||
@@ -214,12 +214,9 @@ class Watcher extends EventEmitter {
|
||||
// TODO watch the configs themselves?
|
||||
const compilers: Compilers = await create_compilers(this.bundler, cwd, src, dest, false);
|
||||
|
||||
let log = '';
|
||||
|
||||
const emitFatal = () => {
|
||||
this.emit('fatal', <FatalEvent>{
|
||||
message: `Server crashed`,
|
||||
log
|
||||
message: `Server crashed`
|
||||
});
|
||||
|
||||
this.crashed = true;
|
||||
@@ -236,7 +233,6 @@ class Watcher extends EventEmitter {
|
||||
handle_result: (result: CompileResult) => {
|
||||
deferred.promise.then(() => {
|
||||
const restart = () => {
|
||||
log = '';
|
||||
this.crashed = false;
|
||||
|
||||
ports.wait(this.port)
|
||||
@@ -260,8 +256,7 @@ class Watcher extends EventEmitter {
|
||||
if (this.crashed) return;
|
||||
|
||||
this.emit('fatal', <FatalEvent>{
|
||||
message: `Server is not listening on port ${this.port}`,
|
||||
log
|
||||
message: `Server is not listening on port ${this.port}`
|
||||
});
|
||||
});
|
||||
};
|
||||
@@ -292,12 +287,10 @@ class Watcher extends EventEmitter {
|
||||
});
|
||||
|
||||
this.proc.stdout.on('data', chunk => {
|
||||
log += chunk;
|
||||
this.emit('stdout', chunk);
|
||||
});
|
||||
|
||||
this.proc.stderr.on('data', chunk => {
|
||||
log += chunk;
|
||||
this.emit('stderr', chunk);
|
||||
});
|
||||
|
||||
|
||||
@@ -38,6 +38,8 @@ async function _export({
|
||||
oninfo = noop,
|
||||
onfile = noop
|
||||
}: Opts = {}) {
|
||||
basepath = basepath.replace(/^\//, '')
|
||||
|
||||
cwd = path.resolve(cwd);
|
||||
static_files = path.resolve(cwd, static_files);
|
||||
build_dir = path.resolve(cwd, build_dir);
|
||||
@@ -92,7 +94,9 @@ async function _export({
|
||||
const is_html = type === 'text/html';
|
||||
|
||||
if (is_html) {
|
||||
file = file === '' ? 'index.html' : `${file}/index.html`;
|
||||
if (pathname !== '/service-worker-index.html') {
|
||||
file = file === '' ? 'index.html' : `${file}/index.html`;
|
||||
}
|
||||
body = minify_html(body);
|
||||
}
|
||||
|
||||
@@ -111,7 +115,10 @@ async function _export({
|
||||
});
|
||||
|
||||
async function handle(url: URL) {
|
||||
const pathname = (url.pathname.replace(root.pathname, '') || '/');
|
||||
let pathname = url.pathname;
|
||||
if (pathname !== '/service-worker-index.html') {
|
||||
pathname = pathname.replace(root.pathname, '') || '/'
|
||||
}
|
||||
|
||||
if (seen.has(pathname)) return;
|
||||
seen.add(pathname);
|
||||
@@ -136,7 +143,7 @@ async function _export({
|
||||
const range = ~~(r.status / 100);
|
||||
|
||||
if (range === 2) {
|
||||
if (type === 'text/html') {
|
||||
if (type === 'text/html' && pathname !== '/service-worker-index.html') {
|
||||
const urls: URL[] = [];
|
||||
|
||||
const cleaned = clean_html(body);
|
||||
@@ -179,6 +186,7 @@ async function _export({
|
||||
|
||||
return ports.wait(port)
|
||||
.then(() => handle(root))
|
||||
.then(() => handle(resolve(root.href, 'service-worker-index.html')))
|
||||
.then(() => proc.kill())
|
||||
.catch(err => {
|
||||
proc.kill();
|
||||
@@ -187,6 +195,6 @@ async function _export({
|
||||
}
|
||||
|
||||
function get_href(attrs: string) {
|
||||
const match = /href\s*=\s*(?:"(.+?)"|'(.+?)'|([^\s>]+))/.exec(attrs);
|
||||
const match = /href\s*=\s*(?:"(.*?)"|'(.+?)'|([^\s>]+))/.exec(attrs);
|
||||
return match[1] || match[2] || match[3];
|
||||
}
|
||||
18
src/cli.ts
18
src/cli.ts
@@ -64,6 +64,14 @@ prog.command('dev')
|
||||
|
||||
let first = true;
|
||||
|
||||
watcher.on('stdout', data => {
|
||||
process.stdout.write(data);
|
||||
});
|
||||
|
||||
watcher.on('stderr', data => {
|
||||
process.stderr.write(data);
|
||||
});
|
||||
|
||||
watcher.on('ready', async (event: ReadyEvent) => {
|
||||
if (first) {
|
||||
console.log(colors.bold.cyan(`> Listening on http://localhost:${event.port}`));
|
||||
@@ -73,16 +81,6 @@ prog.command('dev')
|
||||
}
|
||||
first = false;
|
||||
}
|
||||
|
||||
// TODO clear screen?
|
||||
|
||||
event.process.stdout.on('data', data => {
|
||||
process.stdout.write(data);
|
||||
});
|
||||
|
||||
event.process.stderr.on('data', data => {
|
||||
process.stderr.write(data);
|
||||
});
|
||||
});
|
||||
|
||||
watcher.on('invalid', (event: InvalidEvent) => {
|
||||
|
||||
@@ -142,12 +142,14 @@ export default class RollupCompiler {
|
||||
|
||||
const bundle = await rollup.rollup({
|
||||
input,
|
||||
inlineDynamicImports: true,
|
||||
external: (id: string) => {
|
||||
return (id[0] !== '.' && !path.isAbsolute(id)) || id.slice(-5, id.length) === '.json';
|
||||
}
|
||||
});
|
||||
|
||||
const { code } = await bundle.generate({ format: 'cjs' });
|
||||
const resp = await bundle.generate({ format: 'cjs' });
|
||||
const { code } = resp.output ? resp.output[0] : resp;
|
||||
|
||||
// temporarily override require
|
||||
const defaultLoader = require.extensions['.js'];
|
||||
|
||||
@@ -55,14 +55,25 @@ export default class WebpackResult implements CompileResult {
|
||||
}
|
||||
|
||||
to_json(manifest_data: ManifestData, dirs: Dirs): BuildInfo {
|
||||
const extract_css = (assets: string[] | string) => {
|
||||
assets = Array.isArray(assets) ? assets : [assets];
|
||||
return assets.find(asset => /\.css$/.test(asset));
|
||||
};
|
||||
|
||||
return {
|
||||
bundler: 'webpack',
|
||||
shimport: null, // webpack has its own loader
|
||||
assets: this.assets,
|
||||
css: {
|
||||
// TODO
|
||||
main: null,
|
||||
chunks: {}
|
||||
main: extract_css(this.assets.main),
|
||||
chunks: Object
|
||||
.keys(this.assets)
|
||||
.filter(chunkName => chunkName !== 'main')
|
||||
.reduce((chunks: { [key: string]: string }, chukName) => {
|
||||
const assets = this.assets[chukName];
|
||||
chunks[chukName] = extract_css(assets);
|
||||
return chunks;
|
||||
}, {})
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
@@ -219,7 +219,7 @@ export default function extract_css(client_result: CompileResult, components: Pa
|
||||
});
|
||||
|
||||
unclaimed.forEach(file => {
|
||||
entry_css_modules.push(css_map.get(file));
|
||||
entry_css_modules.push(file);
|
||||
});
|
||||
|
||||
const leftover = get_css_from_modules(entry_css_modules, css_map, dirs);
|
||||
|
||||
@@ -45,17 +45,15 @@ export function create_serviceworker_manifest({ manifest_data, output, client_fi
|
||||
client_files: string[];
|
||||
static_files: string;
|
||||
}) {
|
||||
let files: string[];
|
||||
let files: string[] = ['/service-worker-index.html'];
|
||||
|
||||
if (fs.existsSync(static_files)) {
|
||||
files = walk(static_files);
|
||||
files = files.concat(walk(static_files));
|
||||
} else {
|
||||
// TODO remove in a future version
|
||||
if (fs.existsSync('assets')) {
|
||||
throw new Error(`As of Sapper 0.21, the assets/ directory should become static/`);
|
||||
}
|
||||
|
||||
files = [];
|
||||
}
|
||||
|
||||
let code = `
|
||||
@@ -226,8 +224,8 @@ function generate_server(
|
||||
error
|
||||
};`.replace(/^\t\t/gm, '').trim();
|
||||
|
||||
const build_dir = path.relative(cwd, dest);
|
||||
const src_dir = path.relative(cwd, src);
|
||||
const build_dir = posixify(path.relative(cwd, dest));
|
||||
const src_dir = posixify(path.relative(cwd, src));
|
||||
|
||||
return `// This file is generated by Sapper — do not edit it!\n` + template
|
||||
.replace('__BUILD__DIR__', JSON.stringify(build_dir))
|
||||
@@ -242,4 +240,4 @@ function get_file(path_to_routes: string, component: PageComponent) {
|
||||
}
|
||||
|
||||
return posixify(`${path_to_routes}/${component.file}`);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -69,7 +69,6 @@ export type ErrorEvent = {
|
||||
|
||||
export type FatalEvent = {
|
||||
message: string;
|
||||
log?: string;
|
||||
};
|
||||
|
||||
export type InvalidEvent = {
|
||||
|
||||
@@ -87,11 +87,14 @@ export function select_route(url: URL): Target {
|
||||
|
||||
const match = page.pattern.exec(path);
|
||||
if (match) {
|
||||
const query: Record<string, string | true> = {};
|
||||
const query: Record<string, string | string[]> = Object.create(null);
|
||||
if (url.search.length > 0) {
|
||||
url.search.slice(1).split('&').forEach(searchParam => {
|
||||
const [, key, value] = /([^=]+)(?:=(.*))?/.exec(searchParam);
|
||||
query[key] = decodeURIComponent((value || '').replace(/\+/g, ' '));
|
||||
let [, key, value] = /([^=]*)(?:=(.*))?/.exec(decodeURIComponent(searchParam));
|
||||
value = (value || '').replace(/\+/g, ' ');
|
||||
if (typeof query[key] === 'string') query[key] = [<string>query[key]];
|
||||
if (typeof query[key] === 'object') query[key].push(value);
|
||||
else query[key] = value;
|
||||
});
|
||||
}
|
||||
return { url, path, page, match, query };
|
||||
@@ -101,8 +104,8 @@ export function select_route(url: URL): Target {
|
||||
|
||||
export function scroll_state() {
|
||||
return {
|
||||
x: scrollX,
|
||||
y: scrollY
|
||||
x: pageXOffset,
|
||||
y: pageYOffset
|
||||
};
|
||||
}
|
||||
|
||||
@@ -310,7 +313,7 @@ export function prepare_page(target: Target): Promise<{
|
||||
};
|
||||
}
|
||||
|
||||
const props = { path, query };
|
||||
const props = { path, query, error: null, status: null };
|
||||
const data = {
|
||||
path,
|
||||
preloading: false,
|
||||
|
||||
@@ -55,7 +55,7 @@ export type Target = {
|
||||
path: string;
|
||||
page: Page;
|
||||
match: RegExpExecArray;
|
||||
query: Record<string, string | true>;
|
||||
query: Record<string, string | string[]>;
|
||||
};
|
||||
|
||||
export type Redirect = {
|
||||
|
||||
@@ -3,7 +3,7 @@ import * as path from 'path';
|
||||
import cookie from 'cookie';
|
||||
import devalue from 'devalue';
|
||||
import fetch from 'node-fetch';
|
||||
import { URL } from 'url';
|
||||
import { URL, resolve } from 'url';
|
||||
import { build_dir, dev, src_dir, IGNORE } from '../placeholders';
|
||||
import { Manifest, Page, Props, Req, Res, Store } from './types';
|
||||
|
||||
@@ -34,6 +34,7 @@ export function get_page_handler(
|
||||
}
|
||||
|
||||
async function handle_page(page: Page, req: Req, res: Res, status = 200, error: Error | string = null) {
|
||||
const isSWIndexHtml = req.path === '/service-worker-index.html';
|
||||
const build_info: {
|
||||
bundler: 'rollup' | 'webpack',
|
||||
shimport: string | null,
|
||||
@@ -47,7 +48,7 @@ export function get_page_handler(
|
||||
// preload main.js and current route
|
||||
// TODO detect other stuff we can preload? images, CSS, fonts?
|
||||
let preloaded_chunks = Array.isArray(build_info.assets.main) ? build_info.assets.main : [build_info.assets.main];
|
||||
if (!error) {
|
||||
if (!error && !isSWIndexHtml) {
|
||||
page.parts.forEach(part => {
|
||||
if (!part) return;
|
||||
|
||||
@@ -67,7 +68,10 @@ export function get_page_handler(
|
||||
} else {
|
||||
const link = preloaded_chunks
|
||||
.filter(file => file && !file.match(/\.map$/))
|
||||
.map(file => `<${req.baseUrl}/client/${file}>;rel="preload";as="script"`)
|
||||
.map((file) => {
|
||||
const as = /\.css$/.test(file) ? 'style' : 'script';
|
||||
return `<${req.baseUrl}/client/${file}>;rel="preload";as="${as}"`;
|
||||
})
|
||||
.join(', ');
|
||||
|
||||
res.setHeader('Link', link);
|
||||
@@ -142,17 +146,22 @@ export function get_page_handler(
|
||||
|
||||
match = error ? null : page.pattern.exec(req.path);
|
||||
|
||||
preloaded = await Promise.all([root_preloaded].concat(page.parts.map(part => {
|
||||
if (!part) return null;
|
||||
let toPreload = [root_preloaded];
|
||||
if (!isSWIndexHtml) {
|
||||
toPreload = toPreload.concat(page.parts.map(part => {
|
||||
if (!part) return null;
|
||||
|
||||
return part.component.preload
|
||||
? part.component.preload.call(preload_context, {
|
||||
path: req.path,
|
||||
query: req.query,
|
||||
params: part.params ? part.params(match) : {}
|
||||
})
|
||||
: {};
|
||||
})));
|
||||
return part.component.preload
|
||||
? part.component.preload.call(preload_context, {
|
||||
path: req.path,
|
||||
query: req.query,
|
||||
params: part.params ? part.params(match) : {}
|
||||
})
|
||||
: {};
|
||||
}))
|
||||
}
|
||||
|
||||
preloaded = await Promise.all(toPreload);
|
||||
} catch (err) {
|
||||
preload_error = { statusCode: 500, message: err };
|
||||
preloaded = []; // appease TypeScript
|
||||
@@ -160,7 +169,7 @@ export function get_page_handler(
|
||||
|
||||
try {
|
||||
if (redirect) {
|
||||
const location = `${req.baseUrl}/${redirect.location}`;
|
||||
const location = resolve(req.baseUrl || '/', redirect.location);
|
||||
|
||||
res.statusCode = redirect.statusCode;
|
||||
res.setHeader('Location', location);
|
||||
@@ -201,23 +210,29 @@ export function get_page_handler(
|
||||
});
|
||||
|
||||
let level = data.child;
|
||||
for (let i = 0; i < page.parts.length; i += 1) {
|
||||
const part = page.parts[i];
|
||||
if (!part) continue;
|
||||
if (isSWIndexHtml) {
|
||||
level.props = Object.assign({}, props, {
|
||||
params: {}
|
||||
})
|
||||
} else {
|
||||
for (let i = 0; i < page.parts.length; i += 1) {
|
||||
const part = page.parts[i];
|
||||
if (!part) continue;
|
||||
|
||||
const get_params = part.params || (() => ({}));
|
||||
const get_params = part.params || (() => ({}));
|
||||
|
||||
Object.assign(level, {
|
||||
component: part.component,
|
||||
props: Object.assign({}, props, {
|
||||
params: get_params(match)
|
||||
}, preloaded[i + 1])
|
||||
});
|
||||
Object.assign(level, {
|
||||
component: part.component,
|
||||
props: Object.assign({}, props, {
|
||||
params: get_params(match)
|
||||
}, preloaded[i + 1])
|
||||
});
|
||||
|
||||
level.props.child = <Props["child"]>{
|
||||
segment: segments[i + 1]
|
||||
};
|
||||
level = level.props.child;
|
||||
level.props.child = <Props["child"]>{
|
||||
segment: segments[i + 1]
|
||||
};
|
||||
level = level.props.child;
|
||||
}
|
||||
}
|
||||
|
||||
const { html, head, css } = manifest.root.render(data, {
|
||||
@@ -300,6 +315,12 @@ export function get_page_handler(
|
||||
return function find_route(req: Req, res: Res, next: () => void) {
|
||||
if (req[IGNORE]) return next();
|
||||
|
||||
if (req.path === '/service-worker-index.html') {
|
||||
const homePage = pages.find(page => page.pattern.test('/'));
|
||||
handle_page(homePage, req, res);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!server_routes.some(route => route.pattern.test(req.path))) {
|
||||
for (const page of pages) {
|
||||
if (page.pattern.test(req.path)) {
|
||||
@@ -335,4 +356,4 @@ function escape_html(html: string) {
|
||||
};
|
||||
|
||||
return html.replace(/["'&<>]/g, c => `&${chars[c]};`);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,7 +2,7 @@ import { IGNORE } from '../placeholders';
|
||||
import { Req, Res, ServerRoute } from './types';
|
||||
|
||||
export function get_server_route_handler(routes: ServerRoute[]) {
|
||||
function handle_route(route: ServerRoute, req: Req, res: Res, next: () => void) {
|
||||
async function handle_route(route: ServerRoute, req: Req, res: Res, next: () => void) {
|
||||
req.params = route.params(route.pattern.exec(req.path));
|
||||
|
||||
const method = req.method.toLowerCase();
|
||||
@@ -53,7 +53,7 @@ export function get_server_route_handler(routes: ServerRoute[]) {
|
||||
};
|
||||
|
||||
try {
|
||||
handle_method(req, res, handle_next);
|
||||
await handle_method(req, res, handle_next);
|
||||
} catch (err) {
|
||||
handle_next(err);
|
||||
}
|
||||
|
||||
@@ -8,6 +8,10 @@ declare const prefetchRoutes: () => Promise<void>;
|
||||
declare const prefetch: (href: string) => Promise<void>;
|
||||
declare const goto: (href: string) => Promise<void>;
|
||||
|
||||
type StartOpts = {
|
||||
requestInterceptor?: (interceptedRequst: puppeteer.Request) => any
|
||||
};
|
||||
|
||||
export class AppRunner {
|
||||
cwd: string;
|
||||
entry: string;
|
||||
@@ -24,7 +28,7 @@ export class AppRunner {
|
||||
this.messages = [];
|
||||
}
|
||||
|
||||
async start() {
|
||||
async start({ requestInterceptor }: StartOpts = {}) {
|
||||
this.port = await ports.find(3000);
|
||||
|
||||
this.proc = fork(this.entry, [], {
|
||||
@@ -50,6 +54,11 @@ export class AppRunner {
|
||||
}
|
||||
});
|
||||
|
||||
if (requestInterceptor) {
|
||||
await this.page.setRequestInterception(true);
|
||||
this.page.on('request', requestInterceptor);
|
||||
}
|
||||
|
||||
return {
|
||||
page: this.page,
|
||||
base: `http://localhost:${this.port}`,
|
||||
@@ -58,7 +67,8 @@ export class AppRunner {
|
||||
start: () => this.page.evaluate(() => start()),
|
||||
prefetchRoutes: () => this.page.evaluate(() => prefetchRoutes()),
|
||||
prefetch: (href: string) => this.page.evaluate((href: string) => prefetch(href), href),
|
||||
goto: (href: string) => this.page.evaluate((href: string) => goto(href), href)
|
||||
goto: (href: string) => this.page.evaluate((href: string) => goto(href), href),
|
||||
title: () => this.page.$eval('h1', node => node.textContent)
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -1,9 +1 @@
|
||||
<h1>message: "{message}"</h1>
|
||||
|
||||
<script>
|
||||
export default {
|
||||
preload({ query }) {
|
||||
return query;
|
||||
}
|
||||
};
|
||||
</script>
|
||||
<h1>{JSON.stringify(query)}</h1>
|
||||
@@ -3,5 +3,6 @@
|
||||
<a href="a">a</a>
|
||||
<a href="ambiguous/ok.json">ok</a>
|
||||
<a href="echo-query?message">ok</a>
|
||||
<a href="echo-query?p=one&p=two">ok</a>
|
||||
|
||||
<div class='hydrate-test'></div>
|
||||
@@ -204,7 +204,7 @@ describe('basics', function() {
|
||||
|
||||
assert.equal(
|
||||
await title(),
|
||||
'message: ""'
|
||||
'{"message":""}'
|
||||
);
|
||||
});
|
||||
|
||||
@@ -217,7 +217,29 @@ describe('basics', function() {
|
||||
|
||||
assert.equal(
|
||||
await title(),
|
||||
'message: ""'
|
||||
'{"message":""}'
|
||||
);
|
||||
});
|
||||
|
||||
it('accepts duplicated query string parameter on server', async () => {
|
||||
await page.goto(`${base}/echo-query?p=one&p=two`);
|
||||
|
||||
assert.equal(
|
||||
await title(),
|
||||
'{"p":["one","two"]}'
|
||||
);
|
||||
});
|
||||
|
||||
it('accepts duplicated query string parameter on client', async () => {
|
||||
await page.goto(base);
|
||||
await start();
|
||||
await prefetchRoutes();
|
||||
|
||||
await page.click('a[href="echo-query?p=one&p=two"]')
|
||||
|
||||
assert.equal(
|
||||
await title(),
|
||||
'{"p":["one","two"]}'
|
||||
);
|
||||
});
|
||||
|
||||
|
||||
64
test/apps/css/rollup.config.js
Normal file
64
test/apps/css/rollup.config.js
Normal file
@@ -0,0 +1,64 @@
|
||||
import resolve from 'rollup-plugin-node-resolve';
|
||||
import replace from 'rollup-plugin-replace';
|
||||
import svelte from 'rollup-plugin-svelte';
|
||||
|
||||
const mode = process.env.NODE_ENV;
|
||||
const dev = mode === 'development';
|
||||
|
||||
const config = require('../../../config/rollup.js');
|
||||
|
||||
export default {
|
||||
client: {
|
||||
input: config.client.input(),
|
||||
output: config.client.output(),
|
||||
plugins: [
|
||||
replace({
|
||||
'process.browser': true,
|
||||
'process.env.NODE_ENV': JSON.stringify(mode)
|
||||
}),
|
||||
svelte({
|
||||
dev,
|
||||
hydratable: true,
|
||||
emitCss: true
|
||||
}),
|
||||
resolve()
|
||||
],
|
||||
|
||||
// temporary, pending Rollup 1.0
|
||||
experimentalCodeSplitting: true
|
||||
},
|
||||
|
||||
server: {
|
||||
input: config.server.input(),
|
||||
output: config.server.output(),
|
||||
plugins: [
|
||||
replace({
|
||||
'process.browser': false,
|
||||
'process.env.NODE_ENV': JSON.stringify(mode)
|
||||
}),
|
||||
svelte({
|
||||
generate: 'ssr',
|
||||
dev
|
||||
}),
|
||||
resolve({
|
||||
preferBuiltins: true
|
||||
})
|
||||
],
|
||||
external: ['sirv', 'polka'],
|
||||
|
||||
// temporary, pending Rollup 1.0
|
||||
experimentalCodeSplitting: true
|
||||
},
|
||||
|
||||
serviceworker: {
|
||||
input: config.serviceworker.input(),
|
||||
output: config.serviceworker.output(),
|
||||
plugins: [
|
||||
resolve(),
|
||||
replace({
|
||||
'process.browser': true,
|
||||
'process.env.NODE_ENV': JSON.stringify(mode)
|
||||
})
|
||||
]
|
||||
}
|
||||
};
|
||||
9
test/apps/css/src/client.js
Normal file
9
test/apps/css/src/client.js
Normal file
@@ -0,0 +1,9 @@
|
||||
import * as sapper from '../__sapper__/client.js';
|
||||
|
||||
window.start = () => sapper.start({
|
||||
target: document.querySelector('#sapper')
|
||||
});
|
||||
|
||||
window.prefetchRoutes = () => sapper.prefetchRoutes();
|
||||
window.prefetch = href => sapper.prefetch(href);
|
||||
window.goto = href => sapper.goto(href);
|
||||
7
test/apps/css/src/routes/_components/Title.html
Normal file
7
test/apps/css/src/routes/_components/Title.html
Normal file
@@ -0,0 +1,7 @@
|
||||
<h1>Title</h1>
|
||||
|
||||
<style>
|
||||
h1 {
|
||||
color: green;
|
||||
}
|
||||
</style>
|
||||
3
test/apps/css/src/routes/_error.html
Normal file
3
test/apps/css/src/routes/_error.html
Normal file
@@ -0,0 +1,3 @@
|
||||
<h1>{status}</h1>
|
||||
|
||||
<p>{error.message}</p>
|
||||
11
test/apps/css/src/routes/bar.html
Normal file
11
test/apps/css/src/routes/bar.html
Normal file
@@ -0,0 +1,11 @@
|
||||
<svelte:component this={Title}/>
|
||||
|
||||
<script>
|
||||
export default {
|
||||
oncreate() {
|
||||
import('./_components/Title.html').then(({ default: Title }) => {
|
||||
this.set({ Title });
|
||||
});
|
||||
}
|
||||
};
|
||||
</script>
|
||||
7
test/apps/css/src/routes/foo.html
Normal file
7
test/apps/css/src/routes/foo.html
Normal file
@@ -0,0 +1,7 @@
|
||||
<h1>Foo</h1>
|
||||
|
||||
<style>
|
||||
h1 {
|
||||
color: blue;
|
||||
}
|
||||
</style>
|
||||
10
test/apps/css/src/routes/index.html
Normal file
10
test/apps/css/src/routes/index.html
Normal file
@@ -0,0 +1,10 @@
|
||||
<h1>Great success!</h1>
|
||||
|
||||
<a href="foo">foo</a>
|
||||
<a href="bar">bar</a>
|
||||
|
||||
<style>
|
||||
h1 {
|
||||
color: red;
|
||||
}
|
||||
</style>
|
||||
8
test/apps/css/src/server.js
Normal file
8
test/apps/css/src/server.js
Normal file
@@ -0,0 +1,8 @@
|
||||
import polka from 'polka';
|
||||
import * as sapper from '../__sapper__/server.js';
|
||||
|
||||
const { PORT } = process.env;
|
||||
|
||||
polka()
|
||||
.use(sapper.middleware())
|
||||
.listen(PORT);
|
||||
82
test/apps/css/src/service-worker.js
Normal file
82
test/apps/css/src/service-worker.js
Normal file
@@ -0,0 +1,82 @@
|
||||
import { timestamp, files, shell, routes } from '../__sapper__/service-worker.js';
|
||||
|
||||
const ASSETS = `cache${timestamp}`;
|
||||
|
||||
// `shell` is an array of all the files generated by webpack,
|
||||
// `files` is an array of everything in the `static` directory
|
||||
const to_cache = shell.concat(ASSETS);
|
||||
const cached = new Set(to_cache);
|
||||
|
||||
self.addEventListener('install', event => {
|
||||
event.waitUntil(
|
||||
caches
|
||||
.open(ASSETS)
|
||||
.then(cache => cache.addAll(to_cache))
|
||||
.then(() => {
|
||||
self.skipWaiting();
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
self.addEventListener('activate', event => {
|
||||
event.waitUntil(
|
||||
caches.keys().then(async keys => {
|
||||
// delete old caches
|
||||
for (const key of keys) {
|
||||
if (key !== ASSETS) await caches.delete(key);
|
||||
}
|
||||
|
||||
self.clients.claim();
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
self.addEventListener('fetch', event => {
|
||||
if (event.request.method !== 'GET') return;
|
||||
|
||||
const url = new URL(event.request.url);
|
||||
|
||||
// don't try to handle e.g. data: URIs
|
||||
if (!url.protocol.startsWith('http')) return;
|
||||
|
||||
// ignore dev server requests
|
||||
if (url.hostname === self.location.hostname && url.port !== self.location.port) return;
|
||||
|
||||
// always serve assets and webpack-generated files from cache
|
||||
if (url.host === self.location.host && cached.has(url.pathname)) {
|
||||
event.respondWith(caches.match(event.request));
|
||||
return;
|
||||
}
|
||||
|
||||
// for pages, you might want to serve a shell `index.html` file,
|
||||
// which Sapper has generated for you. It's not right for every
|
||||
// app, but if it's right for yours then uncomment this section
|
||||
/*
|
||||
if (url.origin === self.origin && routes.find(route => route.pattern.test(url.pathname))) {
|
||||
event.respondWith(caches.match('/index.html'));
|
||||
return;
|
||||
}
|
||||
*/
|
||||
|
||||
if (event.request.cache === 'only-if-cached') return;
|
||||
|
||||
// for everything else, try the network first, falling back to
|
||||
// cache if the user is offline. (If the pages never change, you
|
||||
// might prefer a cache-first approach to a network-first one.)
|
||||
event.respondWith(
|
||||
caches
|
||||
.open(`offline${timestamp}`)
|
||||
.then(async cache => {
|
||||
try {
|
||||
const response = await fetch(event.request);
|
||||
cache.put(event.request, response.clone());
|
||||
return response;
|
||||
} catch(err) {
|
||||
const response = await cache.match(event.request);
|
||||
if (response) return response;
|
||||
|
||||
throw err;
|
||||
}
|
||||
})
|
||||
);
|
||||
});
|
||||
14
test/apps/css/src/template.html
Normal file
14
test/apps/css/src/template.html
Normal file
@@ -0,0 +1,14 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset='utf-8'>
|
||||
|
||||
%sapper.base%
|
||||
%sapper.styles%
|
||||
%sapper.head%
|
||||
</head>
|
||||
<body>
|
||||
<div id='sapper'>%sapper.html%</div>
|
||||
%sapper.scripts%
|
||||
</body>
|
||||
</html>
|
||||
78
test/apps/css/test.ts
Normal file
78
test/apps/css/test.ts
Normal file
@@ -0,0 +1,78 @@
|
||||
import * as assert from 'assert';
|
||||
import * as puppeteer from 'puppeteer';
|
||||
import { build } from '../../../api';
|
||||
import { AppRunner } from '../AppRunner';
|
||||
import { wait } from '../../utils';
|
||||
|
||||
describe('css', function() {
|
||||
this.timeout(10000);
|
||||
|
||||
let runner: AppRunner;
|
||||
let page: puppeteer.Page;
|
||||
let base: string;
|
||||
|
||||
// helpers
|
||||
let start: () => Promise<void>;
|
||||
let prefetchRoutes: () => Promise<void>;
|
||||
let prefetch: (href: string) => Promise<void>;
|
||||
let goto: (href: string) => Promise<void>;
|
||||
let title: () => Promise<string>;
|
||||
|
||||
// hooks
|
||||
before(async () => {
|
||||
await build({ cwd: __dirname });
|
||||
|
||||
runner = new AppRunner(__dirname, '__sapper__/build/server/server.js');
|
||||
({ base, page, start, prefetchRoutes, prefetch, goto, title } = await runner.start());
|
||||
});
|
||||
|
||||
after(() => runner.end());
|
||||
|
||||
it('includes critical CSS with server render', async () => {
|
||||
await page.goto(base);
|
||||
|
||||
assert.equal(
|
||||
await page.evaluate(() => {
|
||||
const h1 = document.querySelector('h1');
|
||||
return getComputedStyle(h1).color;
|
||||
}),
|
||||
'rgb(255, 0, 0)'
|
||||
);
|
||||
});
|
||||
|
||||
it('loads CSS when navigating client-side', async () => {
|
||||
await page.goto(base);
|
||||
|
||||
await start();
|
||||
await prefetchRoutes();
|
||||
|
||||
await page.click(`[href="foo"]`);
|
||||
await wait(50);
|
||||
|
||||
assert.equal(
|
||||
await page.evaluate(() => {
|
||||
const h1 = document.querySelector('h1');
|
||||
return getComputedStyle(h1).color;
|
||||
}),
|
||||
'rgb(0, 0, 255)'
|
||||
);
|
||||
});
|
||||
|
||||
it('loads CSS for a lazily-rendered component', async () => {
|
||||
await page.goto(base);
|
||||
|
||||
await start();
|
||||
await prefetchRoutes();
|
||||
|
||||
await page.click(`[href="bar"]`);
|
||||
await wait(50);
|
||||
|
||||
assert.equal(
|
||||
await page.evaluate(() => {
|
||||
const h1 = document.querySelector('h1');
|
||||
return getComputedStyle(h1).color;
|
||||
}),
|
||||
'rgb(0, 128, 0)'
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -1,11 +1,10 @@
|
||||
<h1>{slug} ({message})</h1>
|
||||
<h1>{slug} {JSON.stringify(query)}</h1>
|
||||
|
||||
<script>
|
||||
export default {
|
||||
preload({ params, query }) {
|
||||
preload({ params }) {
|
||||
return {
|
||||
slug: params.slug,
|
||||
message: query.message
|
||||
slug: params.slug
|
||||
};
|
||||
}
|
||||
};
|
||||
|
||||
@@ -1,3 +1,3 @@
|
||||
<h1>Great success!</h1>
|
||||
|
||||
<a href="echo/page/encöded?message=hëllö+wörld">link</a>
|
||||
<a href="echo/page/encöded?message=hëllö+wörld&föo=bar&=baz">link</a>
|
||||
@@ -35,11 +35,11 @@ describe('encoding', function() {
|
||||
});
|
||||
|
||||
it('encodes req.params and req.query for server-rendered pages', async () => {
|
||||
await page.goto(`${base}/echo/page/encöded?message=hëllö+wörld`);
|
||||
await page.goto(`${base}/echo/page/encöded?message=hëllö+wörld&föo=bar&=baz`);
|
||||
|
||||
assert.equal(
|
||||
await page.$eval('h1', node => node.textContent),
|
||||
'encöded (hëllö wörld)'
|
||||
'encöded {"message":"hëllö wörld","föo":"bar","":"baz"}'
|
||||
);
|
||||
});
|
||||
|
||||
@@ -48,12 +48,12 @@ describe('encoding', function() {
|
||||
await start();
|
||||
await prefetchRoutes();
|
||||
|
||||
await page.click('a[href="echo/page/encöded?message=hëllö+wörld"]');
|
||||
await page.click('a[href="echo/page/encöded?message=hëllö+wörld&föo=bar&=baz"]');
|
||||
await wait(50);
|
||||
|
||||
assert.equal(
|
||||
await page.$eval('h1', node => node.textContent),
|
||||
'encöded (hëllö wörld)'
|
||||
'encöded {"message":"hëllö wörld","föo":"bar","":"baz"}'
|
||||
);
|
||||
});
|
||||
|
||||
|
||||
3
test/apps/errors/src/routes/async-throw.json.js
Normal file
3
test/apps/errors/src/routes/async-throw.json.js
Normal file
@@ -0,0 +1,3 @@
|
||||
export function get(req, res) {
|
||||
return Promise.reject(new Error('oops'));
|
||||
}
|
||||
7
test/apps/errors/src/routes/enhance-your-calm.html
Normal file
7
test/apps/errors/src/routes/enhance-your-calm.html
Normal file
@@ -0,0 +1,7 @@
|
||||
<script>
|
||||
export default {
|
||||
preload() {
|
||||
this.error(420, 'Enhance your calm');
|
||||
}
|
||||
};
|
||||
</script>
|
||||
3
test/apps/errors/src/routes/no-error.html
Normal file
3
test/apps/errors/src/routes/no-error.html
Normal file
@@ -0,0 +1,3 @@
|
||||
<h1>{error ? error.message : 'No error here'}</h1>
|
||||
|
||||
<a href="enhance-your-calm">Enhance your calm</a>
|
||||
@@ -14,13 +14,14 @@ describe('errors', function() {
|
||||
// helpers
|
||||
let start: () => Promise<void>;
|
||||
let prefetchRoutes: () => Promise<void>;
|
||||
let title: () => Promise<string>;
|
||||
|
||||
// hooks
|
||||
before(async () => {
|
||||
await build({ cwd: __dirname });
|
||||
|
||||
runner = new AppRunner(__dirname, '__sapper__/build/server/server.js');
|
||||
({ base, page, start, prefetchRoutes } = await runner.start());
|
||||
({ base, page, start, prefetchRoutes, title } = await runner.start());
|
||||
});
|
||||
|
||||
after(() => runner.end());
|
||||
@@ -110,4 +111,27 @@ describe('errors', function() {
|
||||
'oops'
|
||||
);
|
||||
});
|
||||
|
||||
it('does not serve error page for async non-page error', async () => {
|
||||
await page.goto(`${base}/async-throw.json`);
|
||||
|
||||
assert.equal(
|
||||
await page.evaluate(() => document.body.textContent),
|
||||
'oops'
|
||||
);
|
||||
});
|
||||
|
||||
it('clears props.error on successful render', async () => {
|
||||
await page.goto(`${base}/no-error`);
|
||||
await start();
|
||||
await prefetchRoutes();
|
||||
|
||||
await page.click('[href="enhance-your-calm"]');
|
||||
await wait(50);
|
||||
assert.equal(await title(), '420');
|
||||
|
||||
await page.goBack();
|
||||
await wait(50);
|
||||
assert.equal(await title(), 'No error here');
|
||||
});
|
||||
});
|
||||
@@ -1,3 +1,4 @@
|
||||
<h1>Great success!</h1>
|
||||
|
||||
<a href="blog">blog</a>
|
||||
<a href="blog">blog</a>
|
||||
<a href="">empty anchor</a>
|
||||
@@ -30,6 +30,7 @@ describe('export', function() {
|
||||
'blog/index.html',
|
||||
'global.css',
|
||||
'index.html',
|
||||
'service-worker-index.html',
|
||||
'service-worker.js'
|
||||
]);
|
||||
});
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
<h1>root</h1>
|
||||
|
||||
<a href="redirect-from">redirect from</a>
|
||||
<a href="redirect-to-root">redirect to root</a>
|
||||
<a href="redirect-to-root">redirect to root</a>
|
||||
<a href="redirect-to-external">redirect to external</a>
|
||||
9
test/apps/redirects/src/routes/redirect-to-external.html
Normal file
9
test/apps/redirects/src/routes/redirect-to-external.html
Normal file
@@ -0,0 +1,9 @@
|
||||
<h1>unredirected</h1>
|
||||
|
||||
<script>
|
||||
export default {
|
||||
preload() {
|
||||
this.redirect(301, 'https://example.com');
|
||||
}
|
||||
};
|
||||
</script>
|
||||
@@ -14,13 +14,26 @@ describe('redirects', function() {
|
||||
// helpers
|
||||
let start: () => Promise<void>;
|
||||
let prefetchRoutes: () => Promise<void>;
|
||||
let title: () => Promise<string>;
|
||||
|
||||
// hooks
|
||||
before(async () => {
|
||||
await build({ cwd: __dirname });
|
||||
|
||||
runner = new AppRunner(__dirname, '__sapper__/build/server/server.js');
|
||||
({ base, page, start, prefetchRoutes } = await runner.start());
|
||||
({ base, page, start, prefetchRoutes, title } = await runner.start({
|
||||
requestInterceptor: (interceptedRequest) => {
|
||||
if (/example\.com/.test(interceptedRequest.url())) {
|
||||
interceptedRequest.respond({
|
||||
status: 200,
|
||||
contentType: 'text/html',
|
||||
body: `<h1>external</h1>`
|
||||
});
|
||||
} else {
|
||||
interceptedRequest.continue();
|
||||
}
|
||||
}
|
||||
}));
|
||||
});
|
||||
|
||||
after(() => runner.end());
|
||||
@@ -34,7 +47,7 @@ describe('redirects', function() {
|
||||
);
|
||||
|
||||
assert.equal(
|
||||
await page.$eval('h1', node => node.textContent),
|
||||
await title(),
|
||||
'redirected'
|
||||
);
|
||||
});
|
||||
@@ -53,7 +66,7 @@ describe('redirects', function() {
|
||||
);
|
||||
|
||||
assert.equal(
|
||||
await page.$eval('h1', node => node.textContent),
|
||||
await title(),
|
||||
'redirected'
|
||||
);
|
||||
});
|
||||
@@ -67,7 +80,7 @@ describe('redirects', function() {
|
||||
);
|
||||
|
||||
assert.equal(
|
||||
await page.$eval('h1', node => node.textContent),
|
||||
await title(),
|
||||
'root'
|
||||
);
|
||||
});
|
||||
@@ -86,8 +99,41 @@ describe('redirects', function() {
|
||||
);
|
||||
|
||||
assert.equal(
|
||||
await page.$eval('h1', node => node.textContent),
|
||||
await title(),
|
||||
'root'
|
||||
);
|
||||
});
|
||||
|
||||
it('redirects to external URL on server', async () => {
|
||||
await page.goto(`${base}/redirect-to-external`);
|
||||
|
||||
assert.equal(
|
||||
page.url(),
|
||||
`https://example.com/`
|
||||
);
|
||||
|
||||
assert.equal(
|
||||
await title(),
|
||||
'external'
|
||||
);
|
||||
});
|
||||
|
||||
it('redirects to external URL in client', async () => {
|
||||
await page.goto(base);
|
||||
await start();
|
||||
await prefetchRoutes();
|
||||
|
||||
await page.click('[href="redirect-to-external"]');
|
||||
await wait(50);
|
||||
|
||||
assert.equal(
|
||||
page.url(),
|
||||
`https://example.com/`
|
||||
);
|
||||
|
||||
assert.equal(
|
||||
await title(),
|
||||
'external'
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -17,7 +17,7 @@ describe('with-basepath', function() {
|
||||
|
||||
await api.export({
|
||||
cwd: __dirname,
|
||||
basepath: 'custom-basepath'
|
||||
basepath: '/custom-basepath'
|
||||
});
|
||||
|
||||
runner = new AppRunner(__dirname, '__sapper__/build/server/server.js');
|
||||
@@ -56,6 +56,7 @@ describe('with-basepath', function() {
|
||||
assert.deepEqual(non_client_assets, [
|
||||
'custom-basepath/global.css',
|
||||
'custom-basepath/index.html',
|
||||
'custom-basepath/service-worker-index.html',
|
||||
'custom-basepath/service-worker.js'
|
||||
]);
|
||||
});
|
||||
|
||||
9
test/apps/with-sourcemaps-webpack/src/client.js
Normal file
9
test/apps/with-sourcemaps-webpack/src/client.js
Normal file
@@ -0,0 +1,9 @@
|
||||
import * as sapper from '../__sapper__/client.js';
|
||||
|
||||
window.start = () => sapper.start({
|
||||
target: document.querySelector('#sapper')
|
||||
});
|
||||
|
||||
window.prefetchRoutes = () => sapper.prefetchRoutes();
|
||||
window.prefetch = href => sapper.prefetch(href);
|
||||
window.goto = href => sapper.goto(href);
|
||||
3
test/apps/with-sourcemaps-webpack/src/routes/_error.html
Normal file
3
test/apps/with-sourcemaps-webpack/src/routes/_error.html
Normal file
@@ -0,0 +1,3 @@
|
||||
<h1>{status}</h1>
|
||||
|
||||
<p>{error.message}</p>
|
||||
3
test/apps/with-sourcemaps-webpack/src/routes/index.html
Normal file
3
test/apps/with-sourcemaps-webpack/src/routes/index.html
Normal file
@@ -0,0 +1,3 @@
|
||||
<h1>Great success!</h1>
|
||||
|
||||
<p>Woot!</p>
|
||||
8
test/apps/with-sourcemaps-webpack/src/server.js
Normal file
8
test/apps/with-sourcemaps-webpack/src/server.js
Normal file
@@ -0,0 +1,8 @@
|
||||
import polka from 'polka';
|
||||
import * as sapper from '../__sapper__/server.js';
|
||||
|
||||
const { PORT } = process.env;
|
||||
|
||||
polka()
|
||||
.use(sapper.middleware())
|
||||
.listen(PORT);
|
||||
82
test/apps/with-sourcemaps-webpack/src/service-worker.js
Normal file
82
test/apps/with-sourcemaps-webpack/src/service-worker.js
Normal file
@@ -0,0 +1,82 @@
|
||||
import { timestamp, files, shell, routes } from '../__sapper__/service-worker.js';
|
||||
|
||||
const ASSETS = `cache${timestamp}`;
|
||||
|
||||
// `shell` is an array of all the files generated by webpack,
|
||||
// `files` is an array of everything in the `static` directory
|
||||
const to_cache = shell.concat(ASSETS);
|
||||
const cached = new Set(to_cache);
|
||||
|
||||
self.addEventListener('install', event => {
|
||||
event.waitUntil(
|
||||
caches
|
||||
.open(ASSETS)
|
||||
.then(cache => cache.addAll(to_cache))
|
||||
.then(() => {
|
||||
self.skipWaiting();
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
self.addEventListener('activate', event => {
|
||||
event.waitUntil(
|
||||
caches.keys().then(async keys => {
|
||||
// delete old caches
|
||||
for (const key of keys) {
|
||||
if (key !== ASSETS) await caches.delete(key);
|
||||
}
|
||||
|
||||
self.clients.claim();
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
self.addEventListener('fetch', event => {
|
||||
if (event.request.method !== 'GET') return;
|
||||
|
||||
const url = new URL(event.request.url);
|
||||
|
||||
// don't try to handle e.g. data: URIs
|
||||
if (!url.protocol.startsWith('http')) return;
|
||||
|
||||
// ignore dev server requests
|
||||
if (url.hostname === self.location.hostname && url.port !== self.location.port) return;
|
||||
|
||||
// always serve assets and webpack-generated files from cache
|
||||
if (url.host === self.location.host && cached.has(url.pathname)) {
|
||||
event.respondWith(caches.match(event.request));
|
||||
return;
|
||||
}
|
||||
|
||||
// for pages, you might want to serve a shell `index.html` file,
|
||||
// which Sapper has generated for you. It's not right for every
|
||||
// app, but if it's right for yours then uncomment this section
|
||||
/*
|
||||
if (url.origin === self.origin && routes.find(route => route.pattern.test(url.pathname))) {
|
||||
event.respondWith(caches.match('/index.html'));
|
||||
return;
|
||||
}
|
||||
*/
|
||||
|
||||
if (event.request.cache === 'only-if-cached') return;
|
||||
|
||||
// for everything else, try the network first, falling back to
|
||||
// cache if the user is offline. (If the pages never change, you
|
||||
// might prefer a cache-first approach to a network-first one.)
|
||||
event.respondWith(
|
||||
caches
|
||||
.open(`offline${timestamp}`)
|
||||
.then(async cache => {
|
||||
try {
|
||||
const response = await fetch(event.request);
|
||||
cache.put(event.request, response.clone());
|
||||
return response;
|
||||
} catch(err) {
|
||||
const response = await cache.match(event.request);
|
||||
if (response) return response;
|
||||
|
||||
throw err;
|
||||
}
|
||||
})
|
||||
);
|
||||
});
|
||||
14
test/apps/with-sourcemaps-webpack/src/template.html
Normal file
14
test/apps/with-sourcemaps-webpack/src/template.html
Normal file
@@ -0,0 +1,14 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset='utf-8'>
|
||||
|
||||
%sapper.base%
|
||||
%sapper.styles%
|
||||
%sapper.head%
|
||||
</head>
|
||||
<body>
|
||||
<div id='sapper'>%sapper.html%</div>
|
||||
%sapper.scripts%
|
||||
</body>
|
||||
</html>
|
||||
43
test/apps/with-sourcemaps-webpack/test.ts
Normal file
43
test/apps/with-sourcemaps-webpack/test.ts
Normal file
@@ -0,0 +1,43 @@
|
||||
import * as puppeteer from 'puppeteer';
|
||||
import { build } from '../../../api';
|
||||
import * as assert from "assert";
|
||||
import { AppRunner } from '../AppRunner';
|
||||
import * as fs from "fs";
|
||||
import * as path from "path";
|
||||
|
||||
describe('with-sourcemaps-webpack', function() {
|
||||
this.timeout(10000);
|
||||
|
||||
let runner: AppRunner;
|
||||
let page: puppeteer.Page;
|
||||
let base: string;
|
||||
|
||||
// helpers
|
||||
let start: () => Promise<void>;
|
||||
let prefetchRoutes: () => Promise<void>;
|
||||
let prefetch: (href: string) => Promise<void>;
|
||||
let goto: (href: string) => Promise<void>;
|
||||
|
||||
// hooks
|
||||
before(async () => {
|
||||
await build({ cwd: __dirname, bundler: 'webpack' });
|
||||
|
||||
runner = new AppRunner(__dirname, '__sapper__/build/server/server.js');
|
||||
({ base, page, start, prefetchRoutes, prefetch, goto } = await runner.start());
|
||||
});
|
||||
|
||||
it('does not put sourcemap files in service worker shell', async () => {
|
||||
const serviceWorker = await import(`${__dirname}/__sapper__/service-worker.js`);
|
||||
const shell: string[] = serviceWorker.shell;
|
||||
|
||||
assert.equal(shell.filter(_ => _.endsWith('.map')).length, 0,
|
||||
'sourcemap files are not cached in SW');
|
||||
|
||||
const clientShellDir = path.resolve(`${__dirname}/__sapper__/build`, path.dirname(shell[0]));
|
||||
const sourcemapFiles = fs.readdirSync(clientShellDir).filter(_ => _.endsWith('.map'));
|
||||
assert.ok(sourcemapFiles.length > 0, 'sourcemap files exist');
|
||||
});
|
||||
|
||||
after(() => runner.end());
|
||||
|
||||
});
|
||||
73
test/apps/with-sourcemaps-webpack/webpack.config.js
Normal file
73
test/apps/with-sourcemaps-webpack/webpack.config.js
Normal file
@@ -0,0 +1,73 @@
|
||||
const webpack = require('webpack');
|
||||
const config = require('../../../config/webpack.js');
|
||||
|
||||
const mode = process.env.NODE_ENV;
|
||||
const dev = mode === 'development';
|
||||
|
||||
module.exports = {
|
||||
client: {
|
||||
entry: config.client.entry(),
|
||||
output: config.client.output(),
|
||||
resolve: {
|
||||
extensions: ['.js', '.json', '.html'],
|
||||
mainFields: ['svelte', 'module', 'browser', 'main']
|
||||
},
|
||||
module: {
|
||||
rules: [
|
||||
{
|
||||
test: /\.html$/,
|
||||
use: {
|
||||
loader: 'svelte-loader',
|
||||
options: {
|
||||
dev,
|
||||
hydratable: true,
|
||||
hotReload: true
|
||||
}
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
mode,
|
||||
plugins: [
|
||||
dev && new webpack.HotModuleReplacementPlugin(),
|
||||
new webpack.DefinePlugin({
|
||||
'process.browser': true,
|
||||
'process.env.NODE_ENV': JSON.stringify(mode)
|
||||
}),
|
||||
].filter(Boolean),
|
||||
devtool: dev ? 'inline-source-map' : 'source-map'
|
||||
},
|
||||
|
||||
server: {
|
||||
entry: config.server.entry(),
|
||||
output: config.server.output(),
|
||||
target: 'node',
|
||||
resolve: {
|
||||
extensions: ['.js', '.json', '.html'],
|
||||
mainFields: ['svelte', 'module', 'browser', 'main']
|
||||
},
|
||||
module: {
|
||||
rules: [
|
||||
{
|
||||
test: /\.html$/,
|
||||
use: {
|
||||
loader: 'svelte-loader',
|
||||
options: {
|
||||
css: false,
|
||||
generate: 'ssr',
|
||||
dev
|
||||
}
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
mode: process.env.NODE_ENV
|
||||
},
|
||||
|
||||
serviceworker: {
|
||||
entry: config.serviceworker.entry(),
|
||||
output: config.serviceworker.output(),
|
||||
mode: process.env.NODE_ENV,
|
||||
devtool: 'sourcemap'
|
||||
}
|
||||
};
|
||||
64
test/apps/with-sourcemaps/rollup.config.js
Normal file
64
test/apps/with-sourcemaps/rollup.config.js
Normal file
@@ -0,0 +1,64 @@
|
||||
import resolve from 'rollup-plugin-node-resolve';
|
||||
import replace from 'rollup-plugin-replace';
|
||||
import svelte from 'rollup-plugin-svelte';
|
||||
|
||||
const mode = process.env.NODE_ENV;
|
||||
const dev = mode === 'development';
|
||||
|
||||
const config = require('../../../config/rollup.js');
|
||||
|
||||
export default {
|
||||
client: {
|
||||
input: config.client.input(),
|
||||
output: Object.assign({}, config.client.output(), { sourcemap: true }),
|
||||
plugins: [
|
||||
replace({
|
||||
'process.browser': true,
|
||||
'process.env.NODE_ENV': JSON.stringify(mode)
|
||||
}),
|
||||
svelte({
|
||||
dev,
|
||||
hydratable: true,
|
||||
emitCss: true
|
||||
}),
|
||||
resolve()
|
||||
],
|
||||
|
||||
// temporary, pending Rollup 1.0
|
||||
experimentalCodeSplitting: true
|
||||
},
|
||||
|
||||
server: {
|
||||
input: config.server.input(),
|
||||
output: config.server.output(),
|
||||
plugins: [
|
||||
replace({
|
||||
'process.browser': false,
|
||||
'process.env.NODE_ENV': JSON.stringify(mode)
|
||||
}),
|
||||
svelte({
|
||||
generate: 'ssr',
|
||||
dev
|
||||
}),
|
||||
resolve({
|
||||
preferBuiltins: true
|
||||
})
|
||||
],
|
||||
external: ['sirv', 'polka'],
|
||||
|
||||
// temporary, pending Rollup 1.0
|
||||
experimentalCodeSplitting: true
|
||||
},
|
||||
|
||||
serviceworker: {
|
||||
input: config.serviceworker.input(),
|
||||
output: config.serviceworker.output(),
|
||||
plugins: [
|
||||
resolve(),
|
||||
replace({
|
||||
'process.browser': true,
|
||||
'process.env.NODE_ENV': JSON.stringify(mode)
|
||||
})
|
||||
]
|
||||
}
|
||||
};
|
||||
9
test/apps/with-sourcemaps/src/client.js
Normal file
9
test/apps/with-sourcemaps/src/client.js
Normal file
@@ -0,0 +1,9 @@
|
||||
import * as sapper from '../__sapper__/client.js';
|
||||
|
||||
window.start = () => sapper.start({
|
||||
target: document.querySelector('#sapper')
|
||||
});
|
||||
|
||||
window.prefetchRoutes = () => sapper.prefetchRoutes();
|
||||
window.prefetch = href => sapper.prefetch(href);
|
||||
window.goto = href => sapper.goto(href);
|
||||
3
test/apps/with-sourcemaps/src/routes/_error.html
Normal file
3
test/apps/with-sourcemaps/src/routes/_error.html
Normal file
@@ -0,0 +1,3 @@
|
||||
<h1>{status}</h1>
|
||||
|
||||
<p>{error.message}</p>
|
||||
3
test/apps/with-sourcemaps/src/routes/index.html
Normal file
3
test/apps/with-sourcemaps/src/routes/index.html
Normal file
@@ -0,0 +1,3 @@
|
||||
<h1>Great success!</h1>
|
||||
|
||||
<p>Woot!</p>
|
||||
8
test/apps/with-sourcemaps/src/server.js
Normal file
8
test/apps/with-sourcemaps/src/server.js
Normal file
@@ -0,0 +1,8 @@
|
||||
import polka from 'polka';
|
||||
import * as sapper from '../__sapper__/server.js';
|
||||
|
||||
const { PORT } = process.env;
|
||||
|
||||
polka()
|
||||
.use(sapper.middleware())
|
||||
.listen(PORT);
|
||||
82
test/apps/with-sourcemaps/src/service-worker.js
Normal file
82
test/apps/with-sourcemaps/src/service-worker.js
Normal file
@@ -0,0 +1,82 @@
|
||||
import { timestamp, files, shell, routes } from '../__sapper__/service-worker.js';
|
||||
|
||||
const ASSETS = `cache${timestamp}`;
|
||||
|
||||
// `shell` is an array of all the files generated by webpack,
|
||||
// `files` is an array of everything in the `static` directory
|
||||
const to_cache = shell.concat(ASSETS);
|
||||
const cached = new Set(to_cache);
|
||||
|
||||
self.addEventListener('install', event => {
|
||||
event.waitUntil(
|
||||
caches
|
||||
.open(ASSETS)
|
||||
.then(cache => cache.addAll(to_cache))
|
||||
.then(() => {
|
||||
self.skipWaiting();
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
self.addEventListener('activate', event => {
|
||||
event.waitUntil(
|
||||
caches.keys().then(async keys => {
|
||||
// delete old caches
|
||||
for (const key of keys) {
|
||||
if (key !== ASSETS) await caches.delete(key);
|
||||
}
|
||||
|
||||
self.clients.claim();
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
self.addEventListener('fetch', event => {
|
||||
if (event.request.method !== 'GET') return;
|
||||
|
||||
const url = new URL(event.request.url);
|
||||
|
||||
// don't try to handle e.g. data: URIs
|
||||
if (!url.protocol.startsWith('http')) return;
|
||||
|
||||
// ignore dev server requests
|
||||
if (url.hostname === self.location.hostname && url.port !== self.location.port) return;
|
||||
|
||||
// always serve assets and webpack-generated files from cache
|
||||
if (url.host === self.location.host && cached.has(url.pathname)) {
|
||||
event.respondWith(caches.match(event.request));
|
||||
return;
|
||||
}
|
||||
|
||||
// for pages, you might want to serve a shell `index.html` file,
|
||||
// which Sapper has generated for you. It's not right for every
|
||||
// app, but if it's right for yours then uncomment this section
|
||||
/*
|
||||
if (url.origin === self.origin && routes.find(route => route.pattern.test(url.pathname))) {
|
||||
event.respondWith(caches.match('/index.html'));
|
||||
return;
|
||||
}
|
||||
*/
|
||||
|
||||
if (event.request.cache === 'only-if-cached') return;
|
||||
|
||||
// for everything else, try the network first, falling back to
|
||||
// cache if the user is offline. (If the pages never change, you
|
||||
// might prefer a cache-first approach to a network-first one.)
|
||||
event.respondWith(
|
||||
caches
|
||||
.open(`offline${timestamp}`)
|
||||
.then(async cache => {
|
||||
try {
|
||||
const response = await fetch(event.request);
|
||||
cache.put(event.request, response.clone());
|
||||
return response;
|
||||
} catch(err) {
|
||||
const response = await cache.match(event.request);
|
||||
if (response) return response;
|
||||
|
||||
throw err;
|
||||
}
|
||||
})
|
||||
);
|
||||
});
|
||||
14
test/apps/with-sourcemaps/src/template.html
Normal file
14
test/apps/with-sourcemaps/src/template.html
Normal file
@@ -0,0 +1,14 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset='utf-8'>
|
||||
|
||||
%sapper.base%
|
||||
%sapper.styles%
|
||||
%sapper.head%
|
||||
</head>
|
||||
<body>
|
||||
<div id='sapper'>%sapper.html%</div>
|
||||
%sapper.scripts%
|
||||
</body>
|
||||
</html>
|
||||
43
test/apps/with-sourcemaps/test.ts
Normal file
43
test/apps/with-sourcemaps/test.ts
Normal file
@@ -0,0 +1,43 @@
|
||||
import * as puppeteer from 'puppeteer';
|
||||
import { build } from '../../../api';
|
||||
import * as assert from "assert";
|
||||
import { AppRunner } from '../AppRunner';
|
||||
import * as fs from 'fs';
|
||||
import * as path from "path";
|
||||
|
||||
describe('with-sourcemaps', function() {
|
||||
this.timeout(10000);
|
||||
|
||||
let runner: AppRunner;
|
||||
let page: puppeteer.Page;
|
||||
let base: string;
|
||||
|
||||
// helpers
|
||||
let start: () => Promise<void>;
|
||||
let prefetchRoutes: () => Promise<void>;
|
||||
let prefetch: (href: string) => Promise<void>;
|
||||
let goto: (href: string) => Promise<void>;
|
||||
|
||||
// hooks
|
||||
before(async () => {
|
||||
await build({ cwd: __dirname });
|
||||
|
||||
runner = new AppRunner(__dirname, '__sapper__/build/server/server.js');
|
||||
({ base, page, start, prefetchRoutes, prefetch, goto } = await runner.start());
|
||||
});
|
||||
|
||||
it('does not put sourcemap files in service worker shell', async () => {
|
||||
const serviceWorker = await import(`${__dirname}/__sapper__/service-worker.js`);
|
||||
const shell: string[] = serviceWorker.shell;
|
||||
|
||||
assert.equal(shell.filter(_ => _.endsWith('.map')).length, 0,
|
||||
'sourcemap files are not cached in SW');
|
||||
|
||||
const clientShellDir = path.resolve(`${__dirname}/__sapper__/build`, path.dirname(shell[0]));
|
||||
const sourcemapFiles = fs.readdirSync(clientShellDir).filter(_ => _.endsWith('.map'));
|
||||
assert.ok(sourcemapFiles.length > 0, 'sourcemap files exist');
|
||||
});
|
||||
|
||||
after(() => runner.end());
|
||||
|
||||
});
|
||||
Reference in New Issue
Block a user