various minor fixes

This commit is contained in:
Rich Harris
2018-02-17 18:40:20 -05:00
parent ab1ca60363
commit f2eb95d546
3 changed files with 85 additions and 60 deletions

View File

@@ -23,11 +23,16 @@ function generate_client(routes: Route[], src: string, dev: boolean) {
${routes ${routes
.filter(route => route.type === 'page') .filter(route => route.type === 'page')
.map(route => { .map(route => {
const file = posixify(`../../routes/${route.file}`);
if (route.id === '_4xx' || route.id === '_5xx') {
return `{ error: '${route.id.slice(1)}', load: () => import(/* webpackChunkName: "${route.id}" */ '${file}') }`;
}
const params = route.dynamic.length === 0 const params = route.dynamic.length === 0
? '{}' ? '{}'
: `{ ${route.dynamic.map((part, i) => `${part}: match[${i + 1}]`).join(', ')} }`; : `{ ${route.dynamic.map((part, i) => `${part}: match[${i + 1}]`).join(', ')} }`;
const file = posixify(`../../routes/${route.file}`);
return `{ pattern: ${route.pattern}, params: ${route.dynamic.length > 0 ? `match` : `()`} => (${params}), load: () => import(/* webpackChunkName: "${route.id}" */ '${file}') }`; return `{ pattern: ${route.pattern}, params: ${route.dynamic.length > 0 ? `match` : `()`} => (${params}), load: () => import(/* webpackChunkName: "${route.id}" */ '${file}') }`;
}) })
.join(',\n\t')} .join(',\n\t')}
@@ -67,11 +72,16 @@ function generate_server(routes: Route[], src: string) {
export const routes = [ export const routes = [
${routes ${routes
.map(route => { .map(route => {
const file = posixify(`${src}/${route.file}`);
if (route.id === '_4xx' || route.id === '_5xx') {
return `{ error: '${route.id.slice(1)}', module: ${route.id} }`;
}
const params = route.dynamic.length === 0 const params = route.dynamic.length === 0
? '{}' ? '{}'
: `{ ${route.dynamic.map((part, i) => `${part}: match[${i + 1}]`).join(', ')} }`; : `{ ${route.dynamic.map((part, i) => `${part}: match[${i + 1}]`).join(', ')} }`;
const file = posixify(`${src}/${route.file}`);
return `{ id: '${route.id}', type: '${route.type}', pattern: ${route.pattern}, params: ${route.dynamic.length > 0 ? `match` : `()`} => (${params}), module: ${route.id} }`; return `{ id: '${route.id}', type: '${route.type}', pattern: ${route.pattern}, params: ${route.dynamic.length > 0 ? `match` : `()`} => (${params}), module: ${route.id} }`;
}) })
.join(',\n\t') .join(',\n\t')

View File

@@ -20,7 +20,7 @@ export default function create_serviceworker({ routes, client_files, src }: {
export const shell = [\n\t${client_files.map((x: string) => `"${x}"`).join(',\n\t')}\n]; export const shell = [\n\t${client_files.map((x: string) => `"${x}"`).join(',\n\t')}\n];
export const routes = [\n\t${routes.filter((r: Route) => r.type === 'page').map((r: Route) => `{ pattern: ${r.pattern} }`).join(',\n\t')}\n]; export const routes = [\n\t${routes.filter((r: Route) => r.type === 'page' && !/^_[45]xx$/.test(r.id)).map((r: Route) => `{ pattern: ${r.pattern} }`).join(',\n\t')}\n];
`.replace(/^\t\t/gm, '').trim(); `.replace(/^\t\t/gm, '').trim();
write('app/manifest/service-worker.js', code); write('app/manifest/service-worker.js', code);

View File

@@ -1,5 +1,6 @@
import * as fs from 'fs'; import * as fs from 'fs';
import * as path from 'path'; import * as path from 'path';
import { ClientRequest, ServerResponse } from 'http';
// import * as mime from 'mime'; // import * as mime from 'mime';
import mkdirp from 'mkdirp'; import mkdirp from 'mkdirp';
import rimraf from 'rimraf'; import rimraf from 'rimraf';
@@ -17,40 +18,61 @@ type Assets = {
client: Record<string, string>; client: Record<string, string>;
} }
type RouteObject = {
type: 'page' | 'route';
pattern: RegExp;
params: (match: RegExpMatchArray) => Record<string, string>;
module: {
render: (data: any) => {
head: string;
css: { code: string, map: any };
html: string
},
preload: (data: any) => any | Promise<any>
};
error?: string;
}
type Handler = (req: Req, res: ServerResponse, next: () => void) => void;
interface Req extends ClientRequest {
url: string;
method: string;
pathname: string;
params: Record<string, string>;
}
export default function middleware({ routes }: { export default function middleware({ routes }: {
routes: Route[] routes: RouteObject[]
}) { }) {
const client_info = JSON.parse(fs.readFileSync(path.join(dest, 'client_info.json'), 'utf-8')); const client_info = JSON.parse(fs.readFileSync(path.join(dest, 'client_info.json'), 'utf-8'));
const assets: Assets = {
index: try_read(path.join(dest, 'index.html')),
service_worker: try_read(path.join(dest, 'service-worker.js')),
client: fs.readdirSync(path.join(dest, 'client')).reduce((lookup: Record<string, string>, file: string) => {
lookup[file] = try_read(path.join(dest, 'client', file));
return lookup;
}, {})
};
const template = create_template(); const template = create_template();
const middleware = compose_handlers([ const shell = try_read(path.join(dest, 'index.html'));
set_req_pathname, const serviceworker = try_read(path.join(dest, 'service-worker.js'));
get_asset_handler({ const middleware = compose_handlers([
filter: (pathname: string) => pathname === '/index.html', (req: Req, res: ServerResponse, next: () => void) => {
req.pathname = req.url.replace(/\?.*/, '');
next();
},
shell && get_asset_handler({
pathname: '/index.html',
type: 'text/html', type: 'text/html',
cache: 'max-age=600', cache: 'max-age=600',
fn: () => assets.index body: shell
}), }),
get_asset_handler({ serviceworker && get_asset_handler({
filter: (pathname: string) => pathname === '/service-worker.js', pathname: '/service-worker.js',
type: 'application/javascript', type: 'application/javascript',
cache: 'max-age=600', cache: 'max-age=600',
fn: () => assets.service_worker body: serviceworker
}), }),
(req, res, next) => { (req: Req, res: ServerResponse, next: () => void) => {
if (req.pathname.startsWith('/client/')) { if (req.pathname.startsWith('/client/')) {
// const type = mime.getType(req.pathname); // const type = mime.getType(req.pathname);
const type = 'application/javascript'; // TODO might not be, if using e.g. CSS plugin const type = 'application/javascript'; // TODO might not be, if using e.g. CSS plugin
@@ -71,38 +93,33 @@ export default function middleware({ routes }: {
} }
}, },
get_route_handler(client_info.assetsByChunkName, () => assets, () => routes, () => template), get_route_handler(client_info.assetsByChunkName, routes, template),
get_not_found_handler(client_info.assetsByChunkName, () => routes, () => template) get_not_found_handler(client_info.assetsByChunkName, routes, template)
]); ].filter(Boolean));
// here for API consistency between dev, and prod, but
// doesn't actually need to do anything
middleware.close = () => {};
return middleware; return middleware;
} }
function set_req_pathname(req, res, next) { function get_asset_handler({ pathname, type, cache, body }: {
req.pathname = req.url.replace(/\?.*/, ''); pathname: string;
next(); type: string;
} cache: string;
body: string;
}) {
return (req: Req, res: ServerResponse, next: () => void) => {
if (req.pathname !== pathname) return next();
function get_asset_handler(opts) { res.setHeader('Content-Type', type);
return (req, res, next) => { res.setHeader('Cache-Control', cache);
if (!opts.filter(req.pathname)) return next(); res.end(body);
res.setHeader('Content-Type', opts.type);
res.setHeader('Cache-Control', opts.cache);
res.end(opts.fn(req.pathname));
}; };
} }
const resolved = Promise.resolve(); const resolved = Promise.resolve();
function get_route_handler(chunks: Record<string, string>, get_assets: () => Assets, get_routes: () => Route[], get_template: () => Template) { function get_route_handler(chunks: Record<string, string>, routes: RouteObject[], template: Template) {
function handle_route(route, req, res, next, { client }) { function handle_route(route: RouteObject, req: Req, res: ServerResponse, next: () => void) {
req.params = route.params(route.pattern.exec(req.pathname)); req.params = route.params(route.pattern.exec(req.pathname));
const mod = route.module; const mod = route.module;
@@ -117,8 +134,6 @@ function get_route_handler(chunks: Record<string, string>, get_assets: () => Ass
const data = { params: req.params, query: req.query }; const data = { params: req.params, query: req.query };
const template = get_template();
if (mod.preload) { if (mod.preload) {
const promise = Promise.resolve(mod.preload(req)).then(preloaded => { const promise = Promise.resolve(mod.preload(req)).then(preloaded => {
const serialized = try_serialize(preloaded); const serialized = try_serialize(preloaded);
@@ -212,14 +227,14 @@ function get_route_handler(chunks: Record<string, string>, get_assets: () => Ass
} }
} }
return function find_route(req, res, next) { const error_route = routes.find((route: RouteObject) => route.error === '5xx')
const url = req.pathname;
const routes = get_routes(); return function find_route(req: Req, res: ServerResponse, next: () => void) {
const url = req.pathname;
try { try {
for (const route of routes) { for (const route of routes) {
if (route.pattern.test(url)) return handle_route(route, req, res, next, get_assets()); if (!route.error && route.pattern.test(url)) return handle_route(route, req, res, next);
} }
// no matching route — 404 // no matching route — 404
@@ -230,15 +245,14 @@ function get_route_handler(chunks: Record<string, string>, get_assets: () => Ass
res.statusCode = 500; res.statusCode = 500;
res.setHeader('Content-Type', 'text/html'); res.setHeader('Content-Type', 'text/html');
const route = get_routes().find((route: Route) => route.pattern.test('/5xx')); const rendered = error_route ? error_route.module.render({
const rendered = route ? route.module.render({
status: 500, status: 500,
error error
}) : { head: '', css: '', html: 'Not found' }; }) : { head: '', css: null, html: 'Not found' };
const { head, css, html } = rendered; const { head, css, html } = rendered;
res.end(get_template().render({ res.end(template.render({
scripts: `<script src='/client/${chunks.main}'></script>`, scripts: `<script src='/client/${chunks.main}'></script>`,
html, html,
head: `<noscript id='sapper-head-start'></noscript>${head}<noscript id='sapper-head-end'></noscript>`, head: `<noscript id='sapper-head-start'></noscript>${head}<noscript id='sapper-head-end'></noscript>`,
@@ -248,20 +262,21 @@ function get_route_handler(chunks: Record<string, string>, get_assets: () => Ass
}; };
} }
function get_not_found_handler(chunks: Record<string, string>, get_routes: () => Route[], get_template: () => Template) { function get_not_found_handler(chunks: Record<string, string>, routes: RouteObject[], template: Template) {
return function handle_not_found(req, res) { const route = routes.find((route: RouteObject) => route.error === '4xx');
return function handle_not_found(req: Req, res: ServerResponse) {
res.statusCode = 404; res.statusCode = 404;
res.setHeader('Content-Type', 'text/html'); res.setHeader('Content-Type', 'text/html');
const route = get_routes().find((route: Route) => route.pattern.test('/4xx')); // TODO separate 4xx and 5xx out
const rendered = route ? route.module.render({ const rendered = route ? route.module.render({
status: 404, status: 404,
message: 'Not found' message: 'Not found'
}) : { head: '', css: '', html: 'Not found' }; }) : { head: '', css: null, html: 'Not found' };
const { head, css, html } = rendered; const { head, css, html } = rendered;
res.end(get_template().render({ res.end(template.render({
scripts: `<script src='/client/${chunks.main}'></script>`, scripts: `<script src='/client/${chunks.main}'></script>`,
html, html,
head: `<noscript id='sapper-head-start'></noscript>${head}<noscript id='sapper-head-end'></noscript>`, head: `<noscript id='sapper-head-start'></noscript>${head}<noscript id='sapper-head-end'></noscript>`,
@@ -270,8 +285,8 @@ function get_not_found_handler(chunks: Record<string, string>, get_routes: () =>
}; };
} }
function compose_handlers(handlers) { function compose_handlers(handlers: Handler[]) {
return (req, res, next) => { return (req: Req, res: ServerResponse, next: () => void) => {
let i = 0; let i = 0;
function go() { function go() {
const handler = handlers[i]; const handler = handlers[i];