Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

dev/preview paths #2189

Merged
merged 20 commits into from
Aug 13, 2021
Merged
Show file tree
Hide file tree
Changes from 18 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/clean-chicken-walk.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@sveltejs/kit': patch
---

Use /\_svelte_kit_assets when serving apps with specified paths.assets locally
benmccann marked this conversation as resolved.
Show resolved Hide resolved
5 changes: 5 additions & 0 deletions .changeset/honest-jars-report.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@sveltejs/kit': patch
benmccann marked this conversation as resolved.
Show resolved Hide resolved
---

Serve from basepath in svelte-kit dev/preview
5 changes: 5 additions & 0 deletions .changeset/metal-bottles-wash.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@sveltejs/kit': patch
---

Disallow non-absolute paths.assets option
14 changes: 8 additions & 6 deletions documentation/docs/05-modules.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,10 +23,10 @@ import { goto, invalidate, prefetch, prefetchRoutes } from '$app/navigation';
```

- `goto(href, { replaceState, noscroll, keepfocus, state })` returns a `Promise` that resolves when SvelteKit navigates (or fails to navigate, in which case the promise rejects) to the specified `href`. The second argument is optional:
- `replaceState` (boolean, default `false`) If `true`, will replace the current `history` entry rather than creating a new one with `pushState`
- `noscroll` (boolean, default `false`) If `true`, the browser will maintain its scroll position rather than scrolling to the top of the page after navigation
- `keepfocus` (boolean, default `false`) If `true`, the currently focused element will retain focus after navigation. Otherwise, focus will be reset to the body
- `state` (object, default `{}`) The state of the new/updated history entry
- `replaceState` (boolean, default `false`) If `true`, will replace the current `history` entry rather than creating a new one with `pushState`
- `noscroll` (boolean, default `false`) If `true`, the browser will maintain its scroll position rather than scrolling to the top of the page after navigation
- `keepfocus` (boolean, default `false`) If `true`, the currently focused element will retain focus after navigation. Otherwise, focus will be reset to the body
- `state` (object, default `{}`) The state of the new/updated history entry
- `invalidate(href)` causes any `load` functions belonging to the currently active page to re-run if they `fetch` the resource in question. It returns a `Promise` that resolves when the page is subsequently updated.
- `prefetch(href)` programmatically prefetches the given page, which means a) ensuring that the code for the page is loaded, and b) calling the page's `load` function with the appropriate options. This is the same behaviour that SvelteKit triggers when the user taps or mouses over an `<a>` element with [sveltekit:prefetch](#anchor-options-sveltekit-prefetch). If the next navigation is to `href`, the values returned from `load` will be used, making navigation instantaneous. Returns a `Promise` that resolves when the prefetch is complete.
- `prefetchRoutes(routes)` — programmatically prefetches the code for routes that haven't yet been fetched. Typically, you might call this to speed up subsequent navigation. If no argument is given, all routes will be fetched; otherwise, you can specify routes by any matching pathname such as `/about` (to match `src/routes/about.svelte`) or `/blog/*` (to match `src/routes/blog/[slug].svelte`). Unlike `prefetch`, this won't call `load` for individual pages. Returns a `Promise` that resolves when the routes have been prefetched.
Expand All @@ -37,8 +37,10 @@ import { goto, invalidate, prefetch, prefetchRoutes } from '$app/navigation';
import { base, assets } from '$app/paths';
```

- `base` — a root-relative (i.e. begins with a `/`) string that matches `config.kit.paths.base` in your [project configuration](#configuration)
- `assets` — a root-relative or absolute path that matches `config.kit.paths.assets` (after it has been resolved against `base`)
- `base` — a root-relative (i.e. begins with a `/`) string that matches [`config.kit.paths.base`](#configuration-paths), or the empty string if unspecified
- `assets` — an absolute URL that matches [`config.kit.paths.assets`](#configuration-paths), if specified, otherwise equal to `base`

> If a value for `config.kit.paths.assets` is specified, it will be replaced with `'/_svelte_kit_assets'` during [`svelte-kit dev`](#command-line-interface-svelte-kit-dev) or [`svelte-kit preview`](#command-line-interface-svelte-kit-preview), since the assets don't yet live at their eventual URL.

### $app/stores

Expand Down
2 changes: 1 addition & 1 deletion documentation/docs/14-configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -139,7 +139,7 @@ Options related to [creating a package](#packaging).

An object containing zero or more of the following `string` values:

- `assets` — an absolute path, or a path relative to `base`, where your app's files are served from. This is useful if your files are served from a storage bucket of some kind
- `assets` — an absolute path that your app's files are served from. This is useful if your files are served from a storage bucket of some kind
- `base` — a root-relative path that must start, but not end with `/` (e.g. `/base-path`). This specifies where your app is served from and allows the app to live on a non-root path

### prerender
Expand Down
55 changes: 29 additions & 26 deletions packages/kit/src/core/build/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -39,10 +39,11 @@ export async function build(config, { cwd = process.cwd(), runtime = '@sveltejs/
cwd,
config,
build_dir,
base:
config.kit.paths.assets === '/.'
? `/${config.kit.appDir}/`
: `${config.kit.paths.assets}/${config.kit.appDir}/`,
// TODO this is so that Vite's preloading works. Unfortunately, it fails
// during `svelte-kit preview`, because we use a local asset path. If Vite
// used relative paths, I _think_ this could get fixed. Issue here:
// https://github.com/vitejs/vite/issues/2009
assets_base: `${config.kit.paths.assets || config.kit.paths.base}/${config.kit.appDir}/`,
manifest: create_manifest_data({
config,
output: build_dir,
Expand All @@ -58,9 +59,7 @@ export async function build(config, { cwd = process.cwd(), runtime = '@sveltejs/
await build_server(options, client_manifest, runtime);

if (options.service_worker_entry_file) {
const { base, assets } = config.kit.paths;

if (assets !== base && assets !== '/.') {
if (config.kit.paths.assets) {
throw new Error('Cannot use service worker alongside config.kit.paths.assets');
}

Expand All @@ -83,7 +82,7 @@ export async function build(config, { cwd = process.cwd(), runtime = '@sveltejs/
/**
* @param {{
* cwd: string;
* base: string;
* assets_base: string;
* config: import('types/config').ValidatedConfig
* manifest: import('types/internal').ManifestData
* build_dir: string;
Expand All @@ -94,7 +93,7 @@ export async function build(config, { cwd = process.cwd(), runtime = '@sveltejs/
*/
async function build_client({
cwd,
base,
assets_base,
config,
manifest,
build_dir,
Expand Down Expand Up @@ -151,7 +150,7 @@ async function build_client({
const [merged_config, conflicts] = deep_merge(modified_vite_config, {
configFile: false,
root: cwd,
base,
base: assets_base,
build: {
cssCodeSplit: true,
manifest: true,
Expand Down Expand Up @@ -198,7 +197,7 @@ async function build_client({
/**
* @param {{
* cwd: string;
* base: string;
* assets_base: string;
* config: import('types/config').ValidatedConfig
* manifest: import('types/internal').ManifestData
* build_dir: string;
Expand All @@ -213,7 +212,7 @@ async function build_client({
async function build_server(
{
cwd,
base,
assets_base,
config,
manifest,
build_dir,
Expand All @@ -239,7 +238,7 @@ async function build_server(
return relative_file[0] === '.' ? relative_file : `./${relative_file}`;
};

const prefix = `${config.kit.paths.assets}/${config.kit.appDir}/`;
const prefix = `/${config.kit.appDir}/`;

/**
* @param {string} file
Expand Down Expand Up @@ -270,8 +269,8 @@ async function build_server(

find_deps(file, js_deps, css_deps);

const js = Array.from(js_deps).map((url) => prefix + url);
const css = Array.from(css_deps).map((url) => prefix + url);
const js = Array.from(js_deps);
const css = Array.from(css_deps);

const styles = config.kit.amp
? Array.from(css_deps).map((url) => {
Expand All @@ -281,7 +280,7 @@ async function build_server(
: [];

metadata_lookup[file] = {
entry: prefix + client_manifest[file].file,
entry: client_manifest[file].file,
css,
js,
styles
Expand All @@ -301,7 +300,7 @@ async function build_server(
`
import { respond } from '${runtime}';
import root from './generated/root.svelte';
import { set_paths } from './runtime/paths.js';
import { set_paths, assets } from './runtime/paths.js';
import { set_prerendering } from './runtime/env.js';
import * as user_hooks from ${s(app_relative(hooks_file))};

Expand All @@ -323,13 +322,13 @@ async function build_server(
amp: ${config.kit.amp},
dev: false,
entry: {
file: ${s(prefix + client_manifest[client_entry_file].file)},
css: ${s(Array.from(entry_css).map(dep => prefix + dep))},
js: ${s(Array.from(entry_js).map(dep => prefix + dep))}
file: assets + ${s(prefix + client_manifest[client_entry_file].file)},
benmccann marked this conversation as resolved.
Show resolved Hide resolved
css: [${Array.from(entry_css).map(dep => 'assets + ' + s(prefix + dep))}],
js: [${Array.from(entry_js).map(dep => 'assets + ' + s(prefix + dep))}]
},
fetched: undefined,
floc: ${config.kit.floc},
get_component_path: id => ${s(`${config.kit.paths.assets}/${config.kit.appDir}/`)} + entry_lookup[id],
get_component_path: id => assets + ${s(prefix)} + entry_lookup[id],
get_stack: error => String(error), // for security
handle_error: /** @param {Error & {frame?: string}} error */ (error) => {
if (error.frame) {
Expand Down Expand Up @@ -407,9 +406,13 @@ async function build_server(
const metadata_lookup = ${s(metadata_lookup)};

async function load_component(file) {
const { entry, css, js, styles } = metadata_lookup[file];
return {
module: await module_lookup[file](),
...metadata_lookup[file]
entry: assets + ${s(prefix)} + entry,
css: css.map(dep => assets + ${s(prefix)} + dep),
js: js.map(dep => assets + ${s(prefix)} + dep),
styles
};
}

Expand Down Expand Up @@ -442,7 +445,7 @@ async function build_server(
const [merged_config, conflicts] = deep_merge(modified_vite_config, {
configFile: false,
root: cwd,
base,
base: assets_base,
build: {
target: 'es2018',
ssr: true,
Expand Down Expand Up @@ -500,7 +503,7 @@ async function build_server(
/**
* @param {{
* cwd: string;
* base: string;
* assets_base: string;
* config: import('types/config').ValidatedConfig
* manifest: import('types/internal').ManifestData
* build_dir: string;
Expand All @@ -514,7 +517,7 @@ async function build_server(
async function build_service_worker(
{
cwd,
base,
assets_base,
config,
manifest,
build_dir,
Expand Down Expand Up @@ -575,7 +578,7 @@ async function build_service_worker(
const [merged_config, conflicts] = deep_merge(modified_vite_config, {
configFile: false,
root: cwd,
base,
base: assets_base,
build: {
lib: {
entry: service_worker_entry_file,
Expand Down
40 changes: 14 additions & 26 deletions packages/kit/src/core/config/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -68,30 +68,6 @@ function validate(definition, option, keypath) {
return merged;
}

/**
* @param {string} from
* @param {string} to
*/
function resolve(from, to) {
// the `/.` is weird, but allows `${assets}/images/blah.jpg` to work
// when `assets` is empty
return remove_trailing_slash(url.resolve(add_trailing_slash(from), to)) || '/.';
}

/**
* @param {string} str
*/
function add_trailing_slash(str) {
return str.endsWith('/') ? str : `${str}/`;
}

/**
* @param {string} str
*/
function remove_trailing_slash(str) {
return str.endsWith('/') ? str.slice(0, -1) : str;
}

/**
* @param {string} cwd
* @param {import('types/config').ValidatedConfig} validated
Expand Down Expand Up @@ -153,14 +129,26 @@ export function validate_config(config) {
);
}

if (paths.assets) {
if (!/^[a-z]+:\/\//.test(paths.assets)) {
throw new Error(
'kit.paths.assets option must be an absolute path, if specified. See https://kit.svelte.dev/docs#configuration-paths'
);
}

if (paths.assets.endsWith('/')) {
throw new Error(
"kit.paths.assets option must not end with '/'. See https://kit.svelte.dev/docs#configuration-paths"
);
}
}

if (appDir.startsWith('/') || appDir.endsWith('/')) {
throw new Error(
"kit.appDir cannot start or end with '/'. See https://kit.svelte.dev/docs#configuration"
);
}

paths.assets = resolve(paths.base, paths.assets);

return validated;
}

Expand Down
Loading