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

fix: separate framework code from app code #8957

Merged
merged 21 commits into from
Feb 19, 2023
Merged
Show file tree
Hide file tree
Changes from 10 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/brave-eggs-sparkle.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@sveltejs/kit': patch
---

fix: set public env before starting app
2 changes: 1 addition & 1 deletion packages/kit/src/core/generate_manifest/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ export function generate_manifest({ build_data, relative_path, routes }) {
assets: new Set(${s(assets)}),
mimeTypes: ${s(get_mime_lookup(build_data.manifest_data))},
_: {
entry: ${s(build_data.client_entry)},
client: ${s(build_data.client)},
nodes: [
${(node_paths).map(loader).join(',\n\t\t\t\t')}
],
Expand Down
5 changes: 3 additions & 2 deletions packages/kit/src/core/sync/write_client_manifest.js
Original file line number Diff line number Diff line change
Expand Up @@ -106,9 +106,8 @@ export function write_client_manifest(kit, manifest_data, output, metadata) {

const hooks_file = resolve_entry(kit.files.hooks.client);

// String representation of __CLIENT__/manifest.js
write_if_changed(
`${output}/manifest.js`,
`${output}/app.js`,
trim(`
${hooks_file ? `import * as client_hooks from '${relative_path(output, hooks_file)}';` : ''}

Expand All @@ -125,6 +124,8 @@ export function write_client_manifest(kit, manifest_data, output, metadata) {
hooks_file ? 'client_hooks.handleError || ' : ''
}(({ error }) => { console.error(error) }),
};

export { default as root } from '../root.svelte';
`)
);

Expand Down
1 change: 1 addition & 0 deletions packages/kit/src/exports/vite/build/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import path from 'node:path';
* @param {import('vite').Manifest} manifest
* @param {string} entry
* @param {boolean} add_dynamic_css
* @returns {import('types').AssetDependencies}
*/
export function find_deps(manifest, entry, add_dynamic_css) {
/** @type {Set<string>} */
Expand Down
18 changes: 13 additions & 5 deletions packages/kit/src/exports/vite/dev/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -105,11 +105,19 @@ export async function dev(vite, vite_config, svelte_config) {
assets: new Set(manifest_data.assets.map((asset) => asset.file)),
mimeTypes: get_mime_lookup(manifest_data),
_: {
entry: {
file: `${runtime_base}/client/start.js`,
imports: [],
stylesheets: [],
fonts: []
client: {
start: {
file: `${runtime_base}/client/start.js`,
imports: [],
stylesheets: [],
fonts: []
},
app: {
file: `${svelte_config.kit.outDir}/generated/client/app.js`,
imports: [],
stylesheets: [],
fonts: []
}
},
nodes: manifest_data.nodes.map((node, index) => {
return async () => {
Expand Down
25 changes: 14 additions & 11 deletions packages/kit/src/exports/vite/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -216,12 +216,7 @@ function kit({ svelte_config }) {
const new_config = {
resolve: {
alias: [
{
find: '__CLIENT__',
replacement: `${generated}/${is_build ? 'client-optimized' : 'client'}`
},
{ find: '__SERVER__', replacement: `${generated}/server` },
{ find: '__GENERATED__', replacement: generated },
{ find: '$app', replacement: `${runtime_directory}/app` },
...get_config_aliases(kit)
]
Expand Down Expand Up @@ -452,6 +447,7 @@ export function set_assets(path) {
} else {
/** @type {Record<string, string>} */
input.start = `${runtime_directory}/client/start.js`;
input.app = `${kit.outDir}/generated/client-optimized/app.js`;

manifest_data.nodes.forEach((node) => {
if (node.component) {
Expand Down Expand Up @@ -590,7 +586,7 @@ export function set_assets(path) {
app_path: `${kit.paths.base.slice(1)}${kit.paths.base ? '/' : ''}${kit.appDir}`,
manifest_data,
service_worker: !!service_worker_entry_file ? 'service-worker.js' : null, // TODO make file configurable?
client_entry: null,
client: null,
server_manifest
};

Expand Down Expand Up @@ -639,11 +635,18 @@ export function set_assets(path) {
/** @type {import('vite').Manifest} */
const client_manifest = JSON.parse(read(`${out}/client/${vite_config.build.manifest}`));

build_data.client_entry = find_deps(
client_manifest,
posixify(path.relative('.', `${runtime_directory}/client/start.js`)),
false
);
build_data.client = {
start: find_deps(
client_manifest,
posixify(path.relative('.', `${runtime_directory}/client/start.js`)),
false
),
app: find_deps(
client_manifest,
posixify(path.relative('.', `${kit.outDir}/generated/client-optimized/app.js`)),
false
)
};

const css = output.filter(
/** @type {(value: any) => value is import('rollup').OutputAsset} */
Expand Down
30 changes: 0 additions & 30 deletions packages/kit/src/runtime/client/ambient.d.ts

This file was deleted.

61 changes: 30 additions & 31 deletions packages/kit/src/runtime/client/client.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,6 @@ import {
} from './fetcher.js';
import { parse } from './parse.js';

import Root from '__GENERATED__/root.svelte';
import { nodes, server_loads, dictionary, matchers, hooks } from '__CLIENT__/manifest.js';
import { base } from '$internal/paths';
import { HttpError, Redirect } from '../control.js';
import { stores } from './singletons.js';
Expand All @@ -36,16 +34,6 @@ import { INDEX_KEY, PRELOAD_PRIORITIES, SCROLL_KEY, SNAPSHOT_KEY } from './const
import { validate_common_exports } from '../../utils/exports.js';
import { compact } from '../../utils/array.js';

const routes = parse(nodes, server_loads, dictionary, matchers);

const default_layout_loader = nodes[0];
const default_error_loader = nodes[1];

// we import the root layout/error nodes eagerly, so that
// connectivity errors after initialisation don't nuke the app
default_layout_loader();
default_error_loader();

// We track the scroll position associated with each history entry in sessionStorage,
// rather than on history.state itself, because when navigation is driven by
// popstate it's too late to update the scroll position associated with the
Expand All @@ -65,11 +53,22 @@ function update_scroll_positions(index) {

/**
* @param {{
* app: import('./types').SvelteKitApp;
* target: HTMLElement;
* }} opts
* @returns {import('./types').Client}
*/
export function create_client({ target }) {
export function create_client({ app, target }) {
const routes = parse(app);

const default_layout_loader = app.nodes[0];
const default_error_loader = app.nodes[1];

// we import the root layout/error nodes eagerly, so that
// connectivity errors after initialisation don't nuke the app
default_layout_loader();
default_error_loader();

const container = __SVELTEKIT_EMBEDDED__ ? target : document.documentElement;
/** @type {Array<((url: URL) => boolean)>} */
const invalidated = [];
Expand Down Expand Up @@ -429,7 +428,7 @@ export function create_client({ target }) {

page = /** @type {import('types').Page} */ (result.props.page);

root = new Root({
root = new app.root({
target,
props: { ...result.props, stores, components },
hydrate: true
Expand Down Expand Up @@ -978,7 +977,7 @@ export function create_client({ target }) {
/** @type {import('types').ServerDataNode | null} */
let server_data_node = null;

const default_layout_has_server_load = server_loads[0] === 0;
const default_layout_has_server_load = app.server_loads[0] === 0;

if (default_layout_has_server_load) {
// TODO post-https://github.com/sveltejs/kit/discussions/6124 we can use
Expand Down Expand Up @@ -1292,6 +1291,21 @@ export function create_client({ target }) {
after_navigate();
}

/**
* @param {unknown} error
* @param {import('types').NavigationEvent} event
* @returns {import('../../../types/private.js').MaybePromise<App.Error>}
Rich-Harris marked this conversation as resolved.
Show resolved Hide resolved
*/
function handle_error(error, event) {
if (error instanceof HttpError) {
return error.body;
}
return (
app.hooks.handleError({ error, event }) ??
/** @type {any} */ ({ message: event.route.id != null ? 'Internal Error' : 'Not Found' })
);
}

return {
after_navigate: (fn) => {
onMount(() => {
Expand Down Expand Up @@ -1687,7 +1701,7 @@ export function create_client({ target }) {
const server_data_node = server_data_nodes[i];

return load_node({
loader: nodes[n],
loader: app.nodes[n],
url,
params,
route,
Expand Down Expand Up @@ -1774,21 +1788,6 @@ async function load_data(url, invalid) {
return data;
}

/**
* @param {unknown} error
* @param {import('types').NavigationEvent} event
* @returns {import('../../../types/private.js').MaybePromise<App.Error>}
*/
function handle_error(error, event) {
if (error instanceof HttpError) {
return error.body;
}
return (
hooks.handleError({ error, event }) ??
/** @type {any} */ ({ message: event.route.id != null ? 'Internal Error' : 'Not Found' })
);
}

function reset_focus() {
const autofocus = document.querySelector('[autofocus]');
if (autofocus) {
Expand Down
7 changes: 2 additions & 5 deletions packages/kit/src/runtime/client/parse.js
Original file line number Diff line number Diff line change
@@ -1,13 +1,10 @@
import { exec, parse_route_id } from '../../utils/routing.js';

/**
* @param {import('types').CSRPageNodeLoader[]} nodes
* @param {number[]} server_loads
* @param {typeof import('__CLIENT__/manifest.js').dictionary} dictionary
* @param {Record<string, (param: string) => boolean>} matchers
* @param {import('./types').SvelteKitApp} app
* @returns {import('types').CSRRoute[]}
*/
export function parse(nodes, server_loads, dictionary, matchers) {
export function parse({ nodes, server_loads, dictionary, matchers }) {
const layouts_with_server_load = new Set(server_loads);

return Object.entries(dictionary).map(([id, [leaf, layouts, errors]]) => {
Expand Down
11 changes: 5 additions & 6 deletions packages/kit/src/runtime/client/start.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,15 +5,14 @@ import { set_assets, set_version, set_public_env } from '../shared.js';

/**
* @param {{
* app: Promise<import('./types').SvelteKitApp>;
* assets: string;
* env: Record<string, string>;
* hydrate: Parameters<import('./types').Client['_hydrate']>[0];
* target: HTMLElement;
* version: string;
* }} opts
*/
export async function start({ assets, env, hydrate, target, version }) {
set_public_env(env);
export async function start({ app, assets, hydrate, target, version }) {
set_assets(assets);
set_version(version);

Expand All @@ -23,9 +22,7 @@ export async function start({ assets, env, hydrate, target, version }) {
);
}

const client = create_client({
target
});
const client = create_client({ app: await app, target });

init({ client });

Expand All @@ -37,3 +34,5 @@ export async function start({ assets, env, hydrate, target, version }) {

client._start_router();
}

export { set_public_env as env };
38 changes: 37 additions & 1 deletion packages/kit/src/runtime/client/types.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,43 @@ import {
preloadData
} from '$app/navigation';
import { SvelteComponent } from 'svelte';
import { CSRPageNode, CSRPageNodeLoader, CSRRoute, Page, TrailingSlash, Uses } from 'types';
import {
ClientHooks,
CSRPageNode,
CSRPageNodeLoader,
CSRRoute,
Page,
ParamMatcher,
TrailingSlash,
Uses
} from 'types';

export interface SvelteKitApp {
/**
* A list of all the error/layout/page nodes used in the app
*/
nodes: CSRPageNodeLoader[];

/**
* A list of all layout node ids that have a server load function.
* Pages are not present because it's shorter to encode it on the leaf itself.
*/
server_loads: number[];

/**
* A map of `[routeId: string]: [leaf, layouts, errors]` tuples, which
* is parsed into an array of routes on startup. The numbers refer to the indices in `nodes`.
* If the leaf number is negative, it means it does use a server load function and the complement is the node index.
* The route layout and error nodes are not referenced, they are always number 0 and 1 and always apply.
*/
dictionary: Record<string, [leaf: number, layouts: number[], errors?: number[]]>;

matchers: Record<string, ParamMatcher>;

hooks: ClientHooks;

root: typeof SvelteComponent;
}

export interface Client {
// public API, exposed via $app/navigation
Expand Down
Loading