Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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
33 changes: 28 additions & 5 deletions packages/kit/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -93,20 +93,43 @@
"generate:types": "node scripts/generate-dts.js"
},
"imports": {
"#app/env": {
"types": "./src/runtime/app/env/client.js",
"workerd": "./src/runtime/app/env/server.js",
"browser": "./src/runtime/app/env/client.js",
"default": "./src/runtime/app/env/server.js"
},
"#app/env/public": {
"workerd": "./src/runtime/app/env/public/server.js",
"browser": "./src/runtime/app/env/public/client.js",
"default": "./src/runtime/app/env/public/server.js"
},
"#app/env/server": {
"workerd": "./src/runtime/app/env/server.js",
"browser": "./src/runtime/invalid-import.js",
"default": "./src/runtime/app/env/server.js"
},
"#app/forms": {
"types": "./src/runtime/app/forms/client.js",
"workerd": "./src/runtime/app/forms/server.js",
"browser": "./src/runtime/app/forms/client.js",
"default": "./src/runtime/app/forms/server.js"
},
"#app/internal/transport": {
"default": "./src/runtime/app/internal/transport.js"
},
"#app/navigation": {
"types": "./src/runtime/app/navigation/client.js",
"workerd": "./src/runtime/app/navigation/server.js",
"browser": "./src/runtime/app/navigation/client.js",
"default": "./src/runtime/app/navigation/server.js"
},
"#app/paths": {
"types": "./src/runtime/app/paths/internal.d.ts",
"workerd": "./src/runtime/app/paths/server.js",
"browser": "./src/runtime/app/paths/client.js",
"default": "./src/runtime/app/paths/server.js"
},
"#app/env/public": {
"workerd": "./src/runtime/app/env/public/server.js",
"browser": "./src/runtime/app/env/public/client.js",
"default": "./src/runtime/app/env/public/server.js"
},
"#internal": {
"workerd": "./src/exports/internal/server/index.js",
"browser": "./src/exports/internal/client.js",
Expand Down
2 changes: 1 addition & 1 deletion packages/kit/scripts/generate-dts.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ await createBundle({
'@sveltejs/kit/node': 'src/exports/node/index.js',
'@sveltejs/kit/params': 'src/exports/params/public.d.ts',
'@sveltejs/kit/vite': 'src/exports/vite/public.d.ts',
'$app/env': 'src/runtime/app/env/types.d.ts',
'$app/env': 'src/runtime/app/env/client.js',
'$app/forms': 'src/runtime/app/forms/public.d.ts',
'$app/navigation': 'src/runtime/app/navigation/public.d.ts',
'$app/paths': 'src/runtime/app/paths/public.d.ts',
Expand Down
10 changes: 6 additions & 4 deletions packages/kit/src/core/env.js
Original file line number Diff line number Diff line change
Expand Up @@ -39,8 +39,10 @@ export async function load_explicit_env(vite, kit, file, root, mode) {
logLevel: 'silent',
mode,
define: {
__SVELTEKIT_PAYLOAD__: 'undefined', // coming in through static import in env/internal.js but will end up unused
__SVELTEKIT_APP_VERSION__: JSON.stringify(kit.version.name) // needed by $app/env
// these are needed by $app/env
__SVELTEKIT_APP_VERSION__: JSON.stringify(kit.version.name),
__SVELTEKIT_DEV__: mode === 'development',
__SVELTEKIT_PAYLOAD__: 'undefined' // coming in through static import in env/internal.js but will end up unused
},
resolve: {
alias: [
Expand All @@ -55,8 +57,8 @@ export async function load_explicit_env(vite, kit, file, root, mode) {

const runner = get_runner(vite, server);

/** @type {typeof import('../runtime/app/env/internal.js')} */ (
await runner.import(`${runtime_directory}/app/env/internal.js`)
/** @type {typeof import('../runtime/app/env/server.js')} */ (
await runner.import(`${runtime_directory}/app/env/server.js`)
).set_building();

try {
Expand Down
2 changes: 1 addition & 1 deletion packages/kit/src/core/sync/write_server.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ const server_template = ({
has_service_worker,
template
}) => `
import { set_building, set_prerendering } from '$app/env/internal';
import { set_building, set_prerendering } from '$app/env/server';

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

did you mean

Suggested change
import { set_building, set_prerendering } from '$app/env/server';
import { set_building, set_prerendering } from '#app/env/server';

?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No. This file is written inside the .svelte-kit directory, where SvelteKit's subpath imports don't apply. We could either use an absolute path here (which would arguably be neater) or continue using the alias — for now I chose the alias

import { set_assets } from '$app/paths/internal/server';
import { set_fix_stack_trace, set_manifest, set_read_implementation, log_response } from '__sveltekit/server';
import error from '../shared/error-template.js';
Expand Down
2 changes: 1 addition & 1 deletion packages/kit/src/exports/vite/module_ids.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,5 +16,5 @@ export const app_server = posixify(
);

export const app_env_private = posixify(
fileURLToPath(new URL('../../runtime/app/env/private.js', import.meta.url))
fileURLToPath(new URL('../../runtime/app/env/private/index.js', import.meta.url))
);
Original file line number Diff line number Diff line change
@@ -1,19 +1,24 @@
import { payload } from '../../client/payload.js';

/**
* `true` if the app is running in the browser.
* @type {boolean}
*/
export const browser: boolean;
export const browser = true;

/**
* Whether the dev server is running. This is not guaranteed to correspond to `NODE_ENV` or `MODE`.
* @type {boolean}
*/
export const dev: boolean;
export const dev = __SVELTEKIT_DEV__;

/**
* SvelteKit analyses your app during the `build` step by running it. During this process, `building` is `true`. This also applies during prerendering.
* @type {boolean}
*/
export const building: boolean;
export const building = false;

/**
* The value of `config.version.name`.
*/
export const version: string;
export const version = payload.version;
3 changes: 1 addition & 2 deletions packages/kit/src/runtime/app/env/index.js
Original file line number Diff line number Diff line change
@@ -1,2 +1 @@
export { BROWSER as browser, DEV as dev } from 'esm-env';
export { building, version } from './internal.js';
export { browser, dev, building, version } from '#app/env';
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import { BROWSER } from 'esm-env';
import { payload } from '../../client/payload.js';

export const version = BROWSER ? payload.version : __SVELTEKIT_APP_VERSION__;
export const browser = false;
export const dev = __SVELTEKIT_DEV__;
export const version = __SVELTEKIT_APP_VERSION__;
export let building = false;

export let prerendering = false;

export function set_building() {
Expand Down
Empty file.
231 changes: 231 additions & 0 deletions packages/kit/src/runtime/app/forms/client.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,231 @@
/** @import { ActionResult, SubmitFunction } from './types.js' */
import { DEV } from 'esm-env';
import { noop } from '../../../utils/functions.js';
import { refreshAll } from '../navigation/index.js';
import {
applyAction,
apply_action_navigation,
handle_error,
is_current_location
} from '../../client/client.js';
import { notify_version } from '../../client/state.svelte.js';
import { deserialize } from './shared.js';

export { applyAction, deserialize };

/**
* Shallow clone an element, so that we can access e.g. `form.action` without worrying
* that someone has added an `<input name="action">` (https://github.com/sveltejs/kit/issues/7593)
* @template {HTMLElement} T
* @param {T} element
* @returns {T}
*/
function clone(element) {
return /** @type {T} */ (HTMLElement.prototype.cloneNode.call(element));
}

/**
* This action enhances a `<form>` element that otherwise would work without JavaScript.
*
* The `submit` function is called upon submission with the given FormData and the `action` that should be triggered.
* If `cancel` is called, the form will not be submitted.
* You can use the abort `controller` to cancel the submission in case another one starts.
* If a function is returned, that function is called with the response from the server.
* If nothing is returned, the fallback will be used.
*
* If this function or its return value isn't set, it emulates the browser-native behaviour, just without the full-page reload. It
* - resets the `<form>` element and refreshes all data in case of a successful submission with no redirect response
* - updates the `form` prop, `page.form` and `page.status` if the action is on the same page as the form
* - navigates to the page the submission lands on — populating that page's `form` prop and `page.status` — on success and failure if that isn't the current page, just as a native form submission would, but with the `?/actionName` param stripped from the destination URL
* - redirects in case of a redirect response
* - renders the nearest error page in case of an unexpected error — the one nearest the action's route, if the action is on a different page
*
* If you provide a custom function with a callback and want to use the default behavior, invoke `update` in your callback.
* It accepts an options object
* - `reset: false` if you don't want the `<form>` values to be reset after a successful submission
* - `refreshAll` to control whether all data is refreshed after submission; it defaults to `true` for successes and `false` for failures
* - `navigate: false` to apply non-redirect results to the current page rather than navigating to `result.location`; redirects are always followed
* @template {Record<string, unknown> | undefined} Success
* @template {Record<string, unknown> | undefined} Failure
* @param {HTMLFormElement} form_element The form element
* @param {SubmitFunction<Success, Failure>} submit Submit callback
*/
export function enhance(form_element, submit = noop) {
if (DEV && clone(form_element).method !== 'post') {
throw new Error('use:enhance can only be used on <form> fields with method="POST"');
}

/**
* @param {{
* result: ActionResult;
* reset?: boolean;
* refreshAll?: boolean;
* invalidateAll?: boolean;
* navigate?: boolean;
* }} opts
*/
const fallback_callback = async ({
result,
reset = true,
refreshAll: should_refresh_all,
invalidateAll: deprecated_invalidate_all,
navigate = true
}) => {
if (DEV && deprecated_invalidate_all !== undefined) {
console.warn(
'The `update({ invalidateAll })` option has been deprecated in favour of `update({ refreshAll })`'
);
}

should_refresh_all ??= deprecated_invalidate_all ?? result.type === 'success';

if (result.type === 'success' && reset) {
// We call reset from the prototype to avoid DOM clobbering
HTMLFormElement.prototype.reset.call(form_element);
}

const destination =
navigate && result.type !== 'redirect' && !is_current_location(result.location)
? result.location
: undefined;

if (destination === undefined) {
if (should_refresh_all && result.type !== 'redirect') {
await refreshAll();
}

await applyAction(result);
return;
}

// emulate the browser: navigate to where the submission lands, rendering that
// page with this result
await apply_action_navigation(destination, result, should_refresh_all);
};

/** @param {SubmitEvent} event */
async function handle_submit(event) {
const method = event.submitter?.hasAttribute('formmethod')
? /** @type {HTMLButtonElement | HTMLInputElement} */ (event.submitter).formMethod
: clone(form_element).method;
if (method !== 'post') return;

event.preventDefault();

const action = new URL(
// We can't do submitter.formAction directly because that property is always set
event.submitter?.hasAttribute('formaction')
? /** @type {HTMLButtonElement | HTMLInputElement} */ (event.submitter).formAction
: clone(form_element).action
);

const enctype = event.submitter?.hasAttribute('formenctype')
? /** @type {HTMLButtonElement | HTMLInputElement} */ (event.submitter).formEnctype
: clone(form_element).enctype;

const form_data = new FormData(form_element, event.submitter);

if (DEV && enctype !== 'multipart/form-data') {
for (const value of form_data.values()) {
if (value instanceof File) {
throw new Error(
'Your form contains <input type="file"> fields, but is missing the necessary `enctype="multipart/form-data"` attribute. This will lead to inconsistent behavior between enhanced and native forms. For more details, see https://github.com/sveltejs/kit/issues/9819.'
);
}
}
}

const controller = new AbortController();

let cancelled = false;
const cancel = () => (cancelled = true);

const callback =
(await submit({
action,
cancel,
controller,
formData: form_data,
formElement: form_element,
submitter: event.submitter
})) ?? fallback_callback;
if (cancelled) return;

/** @type {ActionResult} */
let result;

try {
const headers = new Headers({
accept: 'application/json',
'x-sveltekit-action': 'true'
});

// do not explicitly set the `Content-Type` header when sending `FormData`
// or else it will interfere with the browser's header setting
// see https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest_API/Using_FormData_Objects#sect4
if (enctype !== 'multipart/form-data') {
headers.set(
'Content-Type',
/^(:?application\/x-www-form-urlencoded|text\/plain)$/.test(enctype)
? enctype
: 'application/x-www-form-urlencoded'
);
}

// @ts-expect-error `URLSearchParams(form_data)` is kosher, but typescript doesn't know that
const body = enctype === 'multipart/form-data' ? form_data : new URLSearchParams(form_data);

const response = await fetch(action, {
method: 'POST',
headers,
cache: 'no-store',
body,
signal: controller.signal
});

// detect new deployments from the response header
notify_version(response.headers.get('x-sveltekit-version'));

result = deserialize(await response.text());
if (result.type === 'error' || result.type === 'failure') {
result.status = response.status;
}
} catch (error) {
if (/** @type {any} */ (error)?.name === 'AbortError') return;
result = {
type: 'error',
error: await handle_error(error, {
params: {},
route: { id: null },
url: new URL(location.href)
})
};
}

await callback({
action,
formData: form_data,
formElement: form_element,
update: (opts) =>
fallback_callback({
result,
reset: opts?.reset,
refreshAll: opts?.refreshAll,
invalidateAll: opts?.invalidateAll,
navigate: opts?.navigate
}),
// @ts-expect-error generic constraints stuff we don't care about
result
});
}

// @ts-expect-error
HTMLFormElement.prototype.addEventListener.call(form_element, 'submit', handle_submit);

return {
destroy() {
// @ts-expect-error
HTMLFormElement.prototype.removeEventListener.call(form_element, 'submit', handle_submit);
}
};
}
Loading
Loading