Compare commits

..

34 Commits

Author SHA1 Message Date
Rich Harris
2319ed9ed3 dont create fallback components 2018-07-21 10:38:53 -04:00
Rich Harris
5d7a715122 emit error event if manifest creation fails 2018-07-21 10:38:25 -04:00
Rich Harris
448e91a970 update find_page API 2018-07-20 11:41:37 -04:00
Rich Harris
d927597c1e doh 2018-07-20 11:41:24 -04:00
Rich Harris
aa92342e71 oops 2018-07-17 18:17:14 -04:00
Rich Harris
99b4cd43b9 minor tweak 2018-07-17 18:00:30 -04:00
Rich Harris
20015d6613 oops 2018-07-17 17:27:48 -04:00
Rich Harris
3d39ef96c2 add segment, params and query to server-rendered pages 2018-07-17 17:21:37 -04:00
Rich Harris
c867f051c2 fix fallback index file 2018-07-17 16:59:13 -04:00
Rich Harris
9e1207cdd7 fix error pages 2018-07-17 16:04:22 -04:00
Rich Harris
f126c6ac6c only replace components for changed segments 2018-07-17 15:42:35 -04:00
Rich Harris
84aaf3be4a please let this work 2018-07-16 20:02:42 -04:00
Rich Harris
e751cbebd5 once more, with feeling 2018-07-16 19:53:32 -04:00
Rich Harris
d2ee6ff3d5 argh 2018-07-16 18:05:13 -04:00
Rich Harris
6c68b3151c maybe fix some windows errors 2018-07-16 17:54:59 -04:00
Rich Harris
5428a7ec95 try locking node version to get tests running on windows 2018-07-16 17:42:54 -04:00
Rich Harris
dd190af904 ugh windows 2018-07-16 16:29:12 -04:00
Rich Harris
1f66e4c530 all tests passing 2018-07-16 16:23:43 -04:00
Rich Harris
b0b8b78c5d set preloading true when appropriate 2018-07-16 15:25:17 -04:00
Rich Harris
7d3e191e46 identify leaf index.html components 2018-07-16 15:10:46 -04:00
Rich Harris
61e3b6c6a0 handle errors in client 2018-07-16 14:57:49 -04:00
Rich Harris
af0bd1580d handle errors 2018-07-16 14:49:47 -04:00
Rich Harris
34cf953fde use serialized preloaded data 2018-07-16 14:27:13 -04:00
Rich Harris
8299c68678 inject fallback index.html where necessary 2018-07-16 14:18:21 -04:00
Rich Harris
f221281f8a client-side rendering 2018-07-16 14:07:06 -04:00
Rich Harris
9dc5ba569f server-side rendering 2018-07-16 12:06:10 -04:00
Rich Harris
969430716f update manifest generation 2018-07-16 11:21:24 -04:00
Rich Harris
624f17364c tidy up 2018-07-15 23:12:14 -04:00
Rich Harris
c90d8ee3cd more tests 2018-07-15 23:11:08 -04:00
Rich Harris
6c5630f281 add more tests 2018-07-15 22:50:53 -04:00
Rich Harris
bf8e56748a change how routes are created 2018-07-15 22:13:30 -04:00
Rich Harris
5b024f2c8d small tidy up 2018-07-15 22:12:47 -04:00
Rich Harris
1af0f13799 Merge branch 'master' into gh-262 2018-07-14 21:59:39 -04:00
Rich Harris
80ece8b148 delete App.html 2018-07-05 09:04:38 -04:00
28 changed files with 288 additions and 382 deletions

View File

@@ -1,9 +1,5 @@
# sapper changelog
## 0.15.0
* Nested routes (consult [migration guide](https://sapper.svelte.technology/guide#0-14-to-0-15) and docs on [layouts](https://sapper.svelte.technology/guide#layouts)) ([#262](https://github.com/sveltejs/sapper/issues/262))
## 0.14.2
* Prevent unsafe replacements ([#307](https://github.com/sveltejs/sapper/pull/307))

View File

@@ -1,6 +1,6 @@
{
"name": "sapper",
"version": "0.15.0",
"version": "0.14.2",
"description": "Military-grade apps, engineered by Svelte",
"main": "dist/middleware.ts.js",
"bin": {
@@ -12,7 +12,6 @@
"runtime",
"webpack",
"sapper",
"components",
"dist"
],
"directories": {
@@ -68,7 +67,7 @@
"cy:open": "cypress open",
"test": "mocha --opts mocha.opts",
"pretest": "npm run build",
"build": "rm -rf dist && rollup -c",
"build": "rollup -c",
"dev": "rollup -cw",
"prepublishOnly": "npm test",
"update_mime_types": "curl http://svn.apache.org/repos/asf/httpd/httpd/trunk/docs/conf/mime.types | grep -e \"^[^#]\" > src/middleware/mime-types.md"

View File

@@ -19,8 +19,7 @@ export default [
},
plugins: [
typescript({
typescript: require('typescript'),
target: "ES2017"
typescript: require('typescript')
})
]
},

View File

@@ -14,10 +14,6 @@ export function create_main_manifests({ routes, dev_port }: {
const client_manifest = generate_client(routes, path_to_routes, dev_port);
const server_manifest = generate_server(routes, path_to_routes);
write_if_changed(
`${locations.app()}/manifest/default-layout.html`,
`<svelte:component this={child.component} {...child.props}/>`
);
write_if_changed(`${locations.app()}/manifest/client.js`, client_manifest);
write_if_changed(`${locations.app()}/manifest/server.js`, server_manifest);
}
@@ -48,7 +44,7 @@ function right_pad(str: string, len: number) {
}
function generate_client(
routes: { root: PageComponent, components: PageComponent[], pages: Page[], server_routes: ServerRoute[] },
routes: { components: PageComponent[], pages: Page[], server_routes: ServerRoute[] },
path_to_routes: string,
dev_port?: number
) {
@@ -62,15 +58,15 @@ function generate_client(
let code = `
// This file is generated by Sapper — do not edit it!
import root from '${posixify(`${path_to_routes}/${routes.root.file}`)}';
import root from '${posixify(`${path_to_routes}/index.html`)}';
import error from '${posixify(`${path_to_routes}/_error.html`)}';
${routes.components.map(component =>
`const ${component.name} = () =>
import(/* webpackChunkName: "${component.name}" */ '${get_file(path_to_routes, component)}');`)
import(/* webpackChunkName: "${component.name}" */ '${posixify(`${path_to_routes}/${component.file}`)}');`)
.join('\n')}
export const manifest = {
export const routes = {
ignore: [${server_routes_to_ignore.map(route => route.pattern).join(', ')}],
pages: [
@@ -93,10 +89,7 @@ function generate_client(
root,
error
};
// this is included for legacy reasons
export const routes = {};`.replace(/^\t\t/gm, '').trim();
};`.replace(/^\t\t/gm, '').trim();
if (dev()) {
const sapper_dev_client = posixify(
@@ -116,15 +109,15 @@ function generate_client(
}
function generate_server(
routes: { root: PageComponent, components: PageComponent[], pages: Page[], server_routes: ServerRoute[] },
routes: { components: PageComponent[], pages: Page[], server_routes: ServerRoute[] },
path_to_routes: string
) {
const imports = [].concat(
routes.server_routes.map(route =>
`import * as ${route.name} from '${posixify(`${path_to_routes}/${route.file}`)}';`),
routes.components.map(component =>
`import ${component.name} from '${get_file(path_to_routes, component)}';`),
`import root from '${posixify(`${path_to_routes}/${routes.root.file}`)}';`,
`import ${component.name} from '${posixify(`${path_to_routes}/${component.file}`)}';`),
`import root from '${posixify(`${path_to_routes}/index.html`)}';`,
`import error from '${posixify(`${path_to_routes}/_error.html`)}';`
);
@@ -132,7 +125,7 @@ function generate_server(
// This file is generated by Sapper — do not edit it!
${imports.join('\n')}
export const manifest = {
export const routes = {
server_routes: [
${routes.server_routes.map(route => `{
// ${route.file}
@@ -169,18 +162,7 @@ function generate_server(
root,
error
};
// this is included for legacy reasons
export const routes = {};`.replace(/^\t\t/gm, '').trim();
};`.replace(/^\t\t/gm, '').trim();
return code;
}
function get_file(path_to_routes: string, component: PageComponent) {
if (component.default) {
return `./default-layout.html`;
}
return posixify(`${path_to_routes}/${component.file}`);
}

View File

@@ -4,22 +4,11 @@ import { locations } from '../config';
import { Page, PageComponent, ServerRoute } from '../interfaces';
import { posixify } from './utils';
const default_layout_file = posixify(path.resolve(
__dirname,
'../components/default-layout.html'
));
export default function create_routes(cwd = locations.routes()) {
const components: PageComponent[] = [];
const pages: Page[] = [];
const server_routes: ServerRoute[] = [];
const default_layout: PageComponent = {
default: true,
name: '_default_layout',
file: null
};
function walk(
dir: string,
parent_segments: Part[][],
@@ -65,7 +54,9 @@ export default function create_routes(cwd = locations.routes()) {
.sort(comparator);
items.forEach(item => {
if (item.basename[0] === '_') return;
if (item.basename[0] === '_') {
if (item.basename !== (item.is_dir ? '_default' : '_default.html')) return;
}
if (item.basename[0] === '.') {
if (item.file !== '.well-known') return;
@@ -100,18 +91,16 @@ export default function create_routes(cwd = locations.routes()) {
params.push(...item.parts.filter(p => p.dynamic).map(p => p.content));
if (item.is_dir) {
const index = path.join(dir, item.basename, '_layout.html');
const layout = fs.existsSync(index)
const index = path.join(dir, item.basename, 'index.html');
const component = fs.existsSync(index)
? {
name: `${get_slug(item.file)}__layout`,
file: `${item.file}/_layout.html`
name: `page_${get_slug(item.file)}`,
file: `${item.file}/index.html`
}
: null;
if (layout) {
components.push(layout);
} else if (components.indexOf(default_layout) === -1) {
components.push(default_layout);
if (component) {
components.push(component);
}
walk(
@@ -119,15 +108,41 @@ export default function create_routes(cwd = locations.routes()) {
segments,
params,
stack.concat({
component: layout || default_layout,
component: component || {
missing: true,
name: null,
file: path.join(item.file, 'index.html')
},
params
})
);
}
else if (item.basename === 'index.html') {
const is_branch = items.some(other_item => {
if (other_item === item) return false;
if (other_item.basename[0] === '_') {
return other_item.basename === (other_item.is_dir ? '_default' : '_default.html');
}
if (other_item.is_dir) {
return fs.existsSync(path.join(dir, other_item.basename, 'index.html'));
}
return other_item.is_page;
});
if (!is_branch) {
pages.push({
pattern: get_pattern(parent_segments),
parts: stack
});
}
}
else if (item.is_page) {
const component = {
name: get_slug(item.file),
name: `page_${get_slug(item.file)}`,
file: item.file
};
@@ -137,7 +152,7 @@ export default function create_routes(cwd = locations.routes()) {
});
components.push(component);
if (item.basename === 'index.html') {
if (item.basename === '_default.html') {
pages.push({
pattern: get_pattern(parent_segments),
parts
@@ -161,19 +176,21 @@ export default function create_routes(cwd = locations.routes()) {
});
}
const root_file = path.join(cwd, '_layout.html');
const root = fs.existsSync(root_file)
? {
name: 'main',
file: '_layout.html'
}
: default_layout;
walk(cwd, [], [], []);
// check for clashes
const seen_pages: Map<string, Page> = new Map();
pages.forEach(page => {
// check for missing intermediate index.html files
let i = page.parts.length;
const last_part = page.parts[i - 1];
while (i--) {
const part = page.parts[i];
if (part.component.missing) {
throw new Error(`Missing ${part.component.file}, which is required for ${last_part.component.file} to be valid`);
}
}
// check for clashes
const pattern = page.pattern.toString();
if (seen_pages.has(pattern)) {
const file = page.parts.pop().component.file;
@@ -198,7 +215,6 @@ export default function create_routes(cwd = locations.routes()) {
});
return {
root,
components,
pages,
server_routes
@@ -212,11 +228,9 @@ type Part = {
};
function comparator(
a: { basename: string, parts: Part[], file: string, is_index: boolean },
b: { basename: string, parts: Part[], file: string, is_index: boolean }
a: { basename: string, parts: Part[], file: string, is_dir: boolean },
b: { basename: string, parts: Part[], file: string, is_dir: boolean }
) {
if (a.is_index !== b.is_index) return a.is_index ? -1 : 1;
const max = Math.max(a.parts.length, b.parts.length);
for (let i = 0; i < max; i += 1) {

View File

@@ -21,7 +21,7 @@ export type Store = {
};
export type PageComponent = {
default?: boolean;
missing?: boolean;
name: string;
file: string;
};

View File

@@ -26,7 +26,7 @@ type Page = {
}>
};
type Manifest = {
type RouteObject = {
server_routes: ServerRoute[];
pages: Page[];
root: Component;
@@ -39,20 +39,6 @@ type Store = {
get: () => any
};
type Props = {
path: string;
query: Record<string, string>;
params: Record<string, string>;
error?: { message: string };
status?: number;
child: {
segment: string;
component: Component;
props: Props;
};
[key: string]: any;
};
interface Req extends ClientRequest {
url: string;
baseUrl: string;
@@ -73,19 +59,12 @@ interface Component {
preload: (data: any) => any | Promise<any>
}
export default function middleware(opts: {
manifest: Manifest,
store: (req: Req) => Store,
routes?: any // legacy
export default function middleware({ routes, store }: {
routes: RouteObject,
store: (req: Req) => Store
}) {
if (opts.routes) {
throw new Error(`As of Sapper 0.15, opts.routes should be opts.manifest`);
}
const output = locations.dest();
const { manifest, store } = opts;
let emitted_basepath = false;
const middleware = compose_handlers([
@@ -138,8 +117,8 @@ export default function middleware(opts: {
cache_control: 'max-age=31536000'
}),
get_server_route_handler(manifest.server_routes),
get_page_handler(manifest, store)
get_server_route_handler(routes.server_routes),
get_page_handler(routes, store)
].filter(Boolean));
return middleware;
@@ -256,7 +235,7 @@ function get_server_route_handler(routes: ServerRoute[]) {
};
}
function get_page_handler(manifest: Manifest, store_getter: (req: Req) => Store) {
function get_page_handler(routes: RouteObject, store_getter: (req: Req) => Store) {
const output = locations.dest();
const get_chunks = dev()
@@ -267,22 +246,17 @@ function get_page_handler(manifest: Manifest, store_getter: (req: Req) => Store)
? () => fs.readFileSync(`${locations.app()}/template.html`, 'utf-8')
: (str => () => str)(fs.readFileSync(`${locations.dest()}/template.html`, 'utf-8'));
const { server_routes, pages } = manifest;
const error_route = manifest.error;
function handle_error(req: Req, res: ServerResponse, statusCode: number, error: Error | string) {
handle_page({
pattern: null,
parts: [
{ name: null, component: error_route }
]
}, req, res, statusCode, error);
}
const { server_routes, pages } = routes;
const error_route = routes.error;
function handle_page(page: Page, req: Req, res: ServerResponse, status = 200, error: Error | string = null) {
const get_params = page.parts[page.parts.length - 1].params || (() => ({}));
const match = error ? null : page.pattern.exec(req.path);
req.params = error
? {}
: get_params(match);
const chunks: Record<string, string | string[]> = get_chunks();
res.setHeader('Content-Type', 'text/html');
@@ -305,75 +279,67 @@ function get_page_handler(manifest: Manifest, store_getter: (req: Req) => Store)
res.setHeader('Link', link);
const store = store_getter ? store_getter(req) : null;
const props = { query: req.query, path: req.path };
if (error) {
props.error = error instanceof Error ? error : { message: error };
props.status = status;
}
let redirect: { statusCode: number, location: string };
let preload_error: { statusCode: number, message: Error | string };
const preload_context = {
redirect: (statusCode: number, location: string) => {
if (redirect && (redirect.statusCode !== statusCode || redirect.location !== location)) {
throw new Error(`Conflicting redirects`);
}
redirect = { statusCode, location };
},
error: (statusCode: number, message: Error | string) => {
preload_error = { statusCode, message };
},
fetch: (url: string, opts?: any) => {
const parsed = new URL(url, `http://127.0.0.1:${process.env.PORT}${req.baseUrl ? req.baseUrl + '/' :''}`);
if (opts) {
opts = Object.assign({}, opts);
const include_cookies = (
opts.credentials === 'include' ||
opts.credentials === 'same-origin' && parsed.origin === `http://127.0.0.1:${process.env.PORT}`
);
if (include_cookies) {
const cookies: Record<string, string> = {};
if (!opts.headers) opts.headers = {};
const str = []
.concat(
cookie.parse(req.headers.cookie || ''),
cookie.parse(opts.headers.cookie || ''),
cookie.parse(res.getHeader('Set-Cookie') || '')
)
.map(cookie => {
return Object.keys(cookie)
.map(name => `${name}=${encodeURIComponent(cookie[name])}`)
.join('; ');
})
.filter(Boolean)
.join(', ');
opts.headers.cookie = str;
}
}
return fetch(parsed.href, opts);
},
store
};
const root_preloaded = manifest.root.preload
? manifest.root.preload.call(preload_context, {
path: req.path,
query: req.query,
params: {}
})
: {};
Promise.all([root_preloaded].concat(page.parts.map(part => {
Promise.all(page.parts.map(part => {
return part.component.preload
? part.component.preload.call(preload_context, {
path: req.path,
query: req.query,
params: part.params ? part.params(match) : {}
})
? part.component.preload.call({
redirect: (statusCode: number, location: string) => {
if (redirect && (redirect.statusCode !== statusCode || redirect.location !== location)) {
throw new Error(`Conflicting redirects`);
}
redirect = { statusCode, location };
},
error: (statusCode: number, message: Error | string) => {
preload_error = { statusCode, message };
},
fetch: (url: string, opts?: any) => {
const parsed = new URL(url, `http://127.0.0.1:${process.env.PORT}${req.baseUrl ? req.baseUrl + '/' :''}`);
if (opts) {
opts = Object.assign({}, opts);
const include_cookies = (
opts.credentials === 'include' ||
opts.credentials === 'same-origin' && parsed.origin === `http://127.0.0.1:${process.env.PORT}`
);
if (include_cookies) {
const cookies: Record<string, string> = {};
if (!opts.headers) opts.headers = {};
const str = []
.concat(
cookie.parse(req.headers.cookie || ''),
cookie.parse(opts.headers.cookie || ''),
cookie.parse(res.getHeader('Set-Cookie') || '')
)
.map(cookie => {
return Object.keys(cookie)
.map(name => `${name}=${encodeURIComponent(cookie[name])}`)
.join('; ');
})
.filter(Boolean)
.join(', ');
opts.headers.cookie = str;
}
}
return fetch(parsed.href, opts);
},
store
}, req)
: {};
}))).catch(err => {
})).catch(err => {
preload_error = { statusCode: 500, message: err };
return []; // appease TypeScript
}).then(preloaded => {
@@ -386,34 +352,28 @@ function get_page_handler(manifest: Manifest, store_getter: (req: Req) => Store)
}
if (preload_error) {
handle_error(req, res, preload_error.statusCode, preload_error.message);
handle_page({
pattern: null,
parts: [
{ name: null, component: error_route }
]
}, req, res, preload_error.statusCode, preload_error.message);
return;
}
const serialized = {
preloaded: `[${preloaded.map(data => try_serialize(data)).join(',')}]`,
preloaded: page.parts.map((part, i) => {
return part.component.preload ? try_serialize(preloaded[i]) : null;
}),
store: store && try_serialize(store.get())
};
const segments = req.path.split('/').filter(Boolean);
const props: Props = {
path: req.path,
query: req.query,
params: {},
child: null
};
if (error) {
props.error = error instanceof Error ? error : { message: error };
props.status = status;
}
const data = Object.assign({}, props, preloaded[0], {
params: {},
const data = Object.assign({}, props, { params: req.params }, {
child: {}
});
let level = data.child;
for (let i = 0; i < page.parts.length; i += 1) {
const part = page.parts[i];
@@ -423,15 +383,16 @@ function get_page_handler(manifest: Manifest, store_getter: (req: Req) => Store)
segment: segments[i],
component: part.component,
props: Object.assign({}, props, {
params: get_params(match)
}, preloaded[i + 1])
params: get_params(match),
query: req.query
}, preloaded[i])
});
level.props.child = <Props["child"]>{};
level.props.child = {};
level = level.props.child;
}
const { html, head, css } = manifest.root.render(data, {
const { html, head, css } = routes.root.render(data, {
store
});
@@ -442,9 +403,8 @@ function get_page_handler(manifest: Manifest, store_getter: (req: Req) => Store)
.join('');
let inline_script = `__SAPPER__={${[
error && `error:1`,
`baseUrl: "${req.baseUrl}"`,
serialized.preloaded && `preloaded: ${serialized.preloaded}`,
serialized.preloaded && `preloaded: [${serialized.preloaded}]`,
serialized.store && `store: ${serialized.store}`
].filter(Boolean).join(',')}};`;
@@ -475,13 +435,8 @@ function get_page_handler(manifest: Manifest, store_getter: (req: Req) => Store)
});
}
}).catch(err => {
if (error) {
// we encountered an error while rendering the error page — oops
res.statusCode = 500;
res.end(`<pre>${escape_html(err.message)}</pre>`);
} else {
handle_error(req, res, 500, err);
}
res.statusCode = 500;
res.end(err.message);
});
}
@@ -495,7 +450,12 @@ function get_page_handler(manifest: Manifest, store_getter: (req: Req) => Store)
}
}
handle_error(req, res, 404, 'Not found');
handle_page({
pattern: null,
parts: [
{ name: null, component: error_route }
]
}, req, res, 404, 'Not found');
};
}
@@ -526,15 +486,3 @@ function try_serialize(data: any) {
return null;
}
}
function escape_html(html: string) {
const chars: Record<string, string> = {
'"' : 'quot',
"'": '#39',
'&': 'amp',
'<' : 'lt',
'>' : 'gt'
};
return html.replace(/["'&<>]/g, c => `&${chars[c]};`);
}

View File

@@ -1,12 +1,12 @@
import { detach, findAnchor, scroll_state, which } from './utils';
import { Component, ComponentConstructor, Params, Query, Redirect, Manifest, RouteData, ScrollPosition, Store, Target } from './interfaces';
import { Component, ComponentConstructor, Params, Query, Redirect, Routes, RouteData, ScrollPosition, Store, Target } from './interfaces';
const initial_data = typeof window !== 'undefined' && window.__SAPPER__;
export let root: Component;
let target: Node;
let store: Store;
let manifest: Manifest;
let routes: Routes;
let segments: string[] = [];
type RootProps = {
@@ -56,10 +56,10 @@ function select_route(url: URL): Target {
const path = url.pathname.slice(initial_data.baseUrl.length);
// avoid accidental clashes between server routes and pages
if (manifest.ignore.some(pattern => pattern.test(path))) return;
if (routes.ignore.some(pattern => pattern.test(path))) return;
for (let i = 0; i < manifest.pages.length; i += 1) {
const page = manifest.pages[i];
for (let i = 0; i < routes.pages.length; i += 1) {
const page = routes.pages[i];
const match = page.pattern.exec(path);
if (match) {
@@ -106,9 +106,7 @@ function render(data: any, changed_from: number, scroll: ScrollPosition, token:
detach(end);
}
Object.assign(data, root_data);
root = new manifest.root({
root = new routes.root({
target,
data,
store,
@@ -128,9 +126,6 @@ function changed(a: Record<string, string | true>, b: Record<string, string | tr
return JSON.stringify(a) !== JSON.stringify(b);
}
let root_preload: Promise<any>;
let root_data: any;
function prepare_page(target: Target): Promise<{
redirect?: Redirect;
data?: any;
@@ -167,16 +162,6 @@ function prepare_page(target: Target): Promise<{
}
};
if (!root_preload) {
root_preload = manifest.root.preload
? initial_data.preloaded[0] || manifest.root.preload.call(preload_context, {
path,
query,
params: {}
})
: {};
}
return Promise.all(page.parts.map(async (part, i) => {
if (i < changed_from) return null;
@@ -187,17 +172,15 @@ function prepare_page(target: Target): Promise<{
params: part.params ? part.params(target.match) : {}
};
const preloaded = ready || !initial_data.preloaded[i + 1]
const preloaded = ready || !initial_data.preloaded[i]
? Component.preload ? await Component.preload.call(preload_context, req) : {}
: initial_data.preloaded[i + 1];
: initial_data.preloaded[i];
return { Component, preloaded };
})).catch(err => {
error = { statusCode: 500, message: err };
return [];
}).then(async results => {
if (!root_data) root_data = await root_preload;
}).then(results => {
if (redirect) {
return { redirect };
}
@@ -220,7 +203,7 @@ function prepare_page(target: Target): Promise<{
data: Object.assign({}, props, {
preloading: false,
child: {
component: manifest.error,
component: routes.error,
props
}
})
@@ -386,23 +369,13 @@ function trigger_prefetch(event: MouseEvent | TouchEvent) {
let inited: boolean;
let ready = false;
export function init(opts: {
App: ComponentConstructor,
target: Node,
manifest: Manifest,
store?: (data: any) => Store,
routes?: any // legacy
}) {
export function init(opts: { App: ComponentConstructor, target: Node, routes: Routes, store?: (data: any) => Store }) {
if (opts instanceof HTMLElement) {
throw new Error(`The signature of init(...) has changed — see https://sapper.svelte.technology/guide#0-11-to-0-12 for more information`);
}
if (opts.routes) {
throw new Error(`As of Sapper 0.15, opts.routes should be opts.manifest`);
}
target = opts.target;
manifest = opts.manifest;
routes = opts.routes;
if (opts && opts.store) {
store = opts.store(initial_data.store);
@@ -429,10 +402,8 @@ export function init(opts: {
history.replaceState({ id: uid }, '', href);
if (!initial_data.error) {
const target = select_route(new URL(window.location.href));
if (target) return navigate(target, uid);
}
const target = select_route(new URL(window.location.href));
if (target) return navigate(target, uid);
});
}
@@ -452,9 +423,9 @@ export function goto(href: string, opts = { replaceState: false }) {
}
export function prefetchRoutes(pathnames: string[]) {
if (!manifest) throw new Error(`You must call init() first`);
if (!routes) throw new Error(`You must call init() first`);
return manifest.pages
return routes.pages
.filter(route => {
if (!pathnames) return true;
return pathnames.some(pathname => route.pattern.test(pathname));

View File

@@ -23,7 +23,7 @@ export type Page = {
}>;
};
export type Manifest = {
export type Routes = {
ignore: RegExp[];
root: ComponentConstructor;
error: () => Promise<{ default: ComponentConstructor }>;

View File

@@ -1,11 +1,11 @@
import { init, prefetchRoutes } from '../../../runtime.js';
import { Store } from 'svelte/store.js';
import { manifest } from './manifest/client.js';
import { routes } from './manifest/client.js';
window.init = () => {
return init({
target: document.querySelector('#sapper'),
manifest,
routes,
store: data => new Store(data)
});
};

View File

@@ -4,7 +4,7 @@ import express from 'express';
import serve from 'serve-static';
import sapper from '../../../dist/middleware.ts.js';
import { Store } from 'svelte/store.js';
import { manifest } from './manifest/server.js';
import { routes } from './manifest/server.js';
let pending;
let ended;
@@ -86,7 +86,7 @@ const middlewares = [
},
sapper({
manifest,
routes,
store: () => {
return new Store({
title: 'Stored title'

View File

@@ -0,0 +1,26 @@
<svelte:head>
<title>Sapper project template</title>
</svelte:head>
<h1>Great success!</h1>
<a href='.'>home</a>
<a href='about'>about</a>
<a href='slow-preload'>slow preload</a>
<a href='redirect-from'>redirect</a>
<a href='blog/nope'>broken link</a>
<a href='blog/throw-an-error'>error link</a>
<a href='credentials?creds=include'>credentials</a>
<a rel=prefetch class='{page === "blog" ? "selected" : ""}' href='blog'>blog</a>
<div class='hydrate-test'></div>
<style>
h1 {
text-align: center;
font-size: 2.8em;
text-transform: uppercase;
font-weight: 700;
margin: 0 0 0.5em 0;
}
</style>

View File

@@ -1,15 +0,0 @@
{#if preloading}
<progress class='preloading-progress' value=0.5/>
{/if}
<svelte:component this={child.component} {rootPreloadFunctionRan} {...child.props}/>
<script>
export default {
preload() {
return {
rootPreloadFunctionRan: true
};
}
};
</script>

View File

@@ -0,0 +1,25 @@
<svelte:head>
<title>Blog</title>
</svelte:head>
<h1>Recent posts</h1>
<ul>
{#each posts as post}
<!-- we're using the non-standard `rel=prefetch` attribute to
tell Sapper to load the data for the page as soon as
the user hovers over the link or taps it, instead of
waiting for the 'click' event -->
<li><a rel='prefetch' href='blog/{post.slug}'>{post.title}</a></li>
{/each}
</ul>
<script>
export default {
preload({ params, query }) {
return fetch(`blog.json`).then(r => r.json()).then(posts => {
return { posts };
});
}
};
</script>

View File

@@ -1,25 +1 @@
<svelte:head>
<title>Blog</title>
</svelte:head>
<h1>Recent posts</h1>
<ul>
{#each posts as post}
<!-- we're using the non-standard `rel=prefetch` attribute to
tell Sapper to load the data for the page as soon as
the user hovers over the link or taps it, instead of
waiting for the 'click' event -->
<li><a rel='prefetch' href='blog/{post.slug}'>{post.title}</a></li>
{/each}
</ul>
<script>
export default {
preload({ params, query }) {
return fetch(`blog.json`).then(r => r.json()).then(posts => {
return { posts };
});
}
};
</script>
<svelte:component this={child.component} {...child.props}/>

View File

@@ -1,26 +1,6 @@
<svelte:head>
<title>Sapper project template</title>
</svelte:head>
{#if preloading}
<progress class='preloading-progress' value=0.5/>
{/if}
<h1>Great success!</h1>
<svelte:component this={child.component} {...child.props}/>
<a href='.'>home</a>
<a href='about'>about</a>
<a href='slow-preload'>slow preload</a>
<a href='redirect-from'>redirect</a>
<a href='blog/nope'>broken link</a>
<a href='blog/throw-an-error'>error link</a>
<a href='credentials?creds=include'>credentials</a>
<a rel=prefetch class='{page === "blog" ? "selected" : ""}' href='blog'>blog</a>
<div class='hydrate-test'></div>
<style>
h1 {
text-align: center;
font-size: 2.8em;
text-transform: uppercase;
font-weight: 700;
margin: 0 0 0.5em 0;
}
</style>

View File

@@ -1 +0,0 @@
<h1>root preload function ran: {rootPreloadFunctionRan}</h1>

View File

@@ -0,0 +1,9 @@
<p>URL is {url}</p>
<script>
export default {
preload({ url }) {
if (url) return { url };
}
};
</script>

View File

@@ -100,11 +100,12 @@ describe('sapper', function() {
// Client scripts that should show up in the extraction directory.
const expectedClientRegexes = [
/client\/[^/]+\/main(\.\d+)?\.js/,
/client\/[^/]+\/index(\.\d+)?\.js/,
/client\/[^/]+\/about(\.\d+)?\.js/,
/client\/[^/]+\/blog_\$slug(\.\d+)?\.js/,
/client\/[^/]+\/blog(\.\d+)?\.js/,
/client\/[^/]+\/slow\$45preload(\.\d+)?\.js/,
/client\/[^/]+\/page_index(\.\d+)?\.js/,
/client\/[^/]+\/page_about(\.\d+)?\.js/,
/client\/[^/]+\/page_blog_\$slug(\.\d+)?\.js/,
/client\/[^/]+\/page_blog(\.\d+)?\.js/,
/client\/[^/]+\/page_show\$45url(\.\d+)?\.js/,
/client\/[^/]+\/page_slow\$45preload(\.\d+)?\.js/,
];
const allPages = walkSync(dest);
@@ -369,6 +370,16 @@ function run({ mode, basepath = '' }) {
});
});
it('passes entire request object to preload', () => {
return nightmare
.goto(`${base}/show-url`)
.init()
.evaluate(() => document.querySelector('p').innerHTML)
.then(html => {
assert.equal(html, `URL is /show-url`);
});
});
it('calls a delete handler', () => {
return nightmare
.goto(`${base}/delete-test`)
@@ -656,14 +667,6 @@ function run({ mode, basepath = '' }) {
assert.equal(title, 'it works');
});
});
it('runs preload in root component', () => {
return nightmare.goto(`${base}/preload-root`)
.page.title()
.then(title => {
assert.equal(title, 'root preload function ran: true');
});
});
});
describe('headers', () => {

View File

@@ -2,58 +2,52 @@ const path = require('path');
const assert = require('assert');
const { create_routes } = require('../../../dist/core.ts.js');
const _default_layout = {
default: true,
name: '_default_layout',
file: null
};
describe('create_routes', () => {
it('creates routes', () => {
const { components, pages, server_routes } = create_routes(path.join(__dirname, 'samples/basic'));
const index = { name: 'index', file: 'index.html' };
const about = { name: 'about', file: 'about.html' };
const blog = { name: 'blog', file: 'blog/index.html' };
const blog_$slug = { name: 'blog_$slug', file: 'blog/[slug].html' };
const page_index = { name: 'page_index', file: '_default.html' };
const page_about = { name: 'page_about', file: 'about.html' };
const page_blog = { name: 'page_blog', file: 'blog/index.html' };
const page_blog_index = { name: 'page_blog_index', file: 'blog/_default.html' };
const page_blog_$slug = { name: 'page_blog_$slug', file: 'blog/[slug].html' };
assert.deepEqual(components, [
index,
about,
_default_layout,
blog,
blog_$slug
page_index,
page_about,
page_blog,
page_blog_index,
page_blog_$slug
]);
assert.deepEqual(pages, [
{
pattern: /^\/?$/,
parts: [
{ component: index, params: [] }
{ component: page_index, params: [] }
]
},
{
pattern: /^\/about\/?$/,
parts: [
{ component: about, params: [] }
{ component: page_about, params: [] }
]
},
{
pattern: /^\/blog\/?$/,
parts: [
{ component: _default_layout, params: [] },
{ component: blog, params: [] }
{ component: page_blog, params: [] },
{ component: page_blog_index, params: [] }
]
},
{
pattern: /^\/blog\/([^\/]+?)\/?$/,
parts: [
{ component: _default_layout, params: [] },
{ component: blog_$slug, params: ['slug'] }
{ component: page_blog, params: [] },
{ component: page_blog_$slug, params: ['slug'] }
]
}
]);
@@ -80,9 +74,9 @@ describe('create_routes', () => {
// had to remove ? and " because windows
// const quote = { name: '$34', file: '".html' };
const hash = { name: '$35', file: '#.html' };
// const question_mark = { name: '$63', file: '?.html' };
// const quote = { name: 'page_$34', file: '".html' };
const hash = { name: 'page_$35', file: '#.html' };
// const question_mark = { name: 'page_$63', file: '?.html' };
assert.deepEqual(components, [
// quote,
@@ -111,14 +105,14 @@ describe('create_routes', () => {
const { pages } = create_routes(path.join(__dirname, 'samples/sorting'));
assert.deepEqual(pages.map(p => p.parts.map(part => part.component.file)), [
['index.html'],
['_default.html'],
['about.html'],
[_default_layout.file, 'post/index.html'],
[_default_layout.file, 'post/bar.html'],
[_default_layout.file, 'post/foo.html'],
[_default_layout.file, 'post/f[xx].html'],
[_default_layout.file, 'post/[id([0-9-a-z]{3,})].html'],
[_default_layout.file, 'post/[id].html'],
['post/index.html', 'post/_default.html'],
['post/index.html', 'post/bar.html'],
['post/index.html', 'post/foo.html'],
['post/index.html', 'post/f[xx].html'],
['post/index.html', 'post/[id([0-9-a-z]{3,})].html'],
['post/index.html', 'post/[id].html'],
['[wildcard].html']
]);
});

View File

@@ -6,9 +6,9 @@
"noEmitOnError": true,
"allowJs": true,
"lib": ["es5", "es6", "dom"],
"importHelpers": true,
"target": "ES5"
"importHelpers": true
},
"target": "ES5",
"include": [
"src"
],